diff --git "a/5711.jsonl" "b/5711.jsonl" new file mode 100644--- /dev/null +++ "b/5711.jsonl" @@ -0,0 +1,646 @@ +{"seq_id":"465792067","text":"import numpy as np\n\nimport numpy_indexed as npi\n\na = np.array([[8,7,3],[9,1,4],[ 21,3,8]])\n\nb = np.array([[1,2,3],[1,2,3],[ 1,2,3]]) \n\narray = np.vstack(([a.T], [b.T])).T\n\ni=0\nind = []\ntot = []\n\nfor a_1 in a:\n\tind_1 = np.argpartition(a_1,-2)[-2:]\n\ttotal = 0\n\tfor index in ind_1:\n\t\ttotal += a_1[index]\n\ttot.append(total)\n\tind.append(ind_1[np.argsort(-a_1[ind_1])])\n\nsorted_ind = np.argsort(-np.array(tot))\n\n\nprint(ind)\nprint(tot)\nprint(sorted_ind)\n#array.sort(order=index,axis=1)\n\n\narray_new = []\n# for i in range(5):\n# \tarray_new.append((i,array[i]))\n\n#print(array)\n\n\n# print(a1)\n\n# print(a[npi.argsort((a[:,1], -a[:,0]))])\n\n\n# arr1 = [0]*5\n\n# arr2 = [arr1]*5\n\n# arr2_1 = np.array(arr2)\n\n# my_array = np.array([(1,2,3),(2,3,4),(3,4,5)])\n\n# ans = np.matmul(arr2_1,arr2_1.T)\n\n# print(arr1)\n\n# print(arr2)\n\n# print(ans)\n#adding a line\n#adding a line#adding a line again\n","sub_path":"try.py","file_name":"try.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"448838056","text":"import torch\n\ndef save_snapshots(epoch, model, optimizer, scheduler, path):\n if isinstance(model, torch.nn.DataParallel):\n module = model.module\n else:\n module = model\n torch.save({\n 'epoch': epoch + 1,\n 'model': module.state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'scheduler': scheduler.state_dict()\n }, path)\n\ndef load_snapshots_to_model(path, model, optimizer, scheduler):\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n checkpoint = torch.load(path, map_location=device)\n model.load_state_dict(checkpoint['model'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n scheduler.load_state_dict(checkpoint['scheduler'])\n\ndef load_epoch(path):\n checkpoint = torch.load(path)\n return checkpoint['epoch']\n","sub_path":"lib/model_serializer.py","file_name":"model_serializer.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"114865366","text":"## Turns wav files into CQT Spectrogram for use in some Image-to-Image Translation model\nfrom spec2wav.dataset import AudioDataset\nfrom torch.utils.data import DataLoader\nimport argparse\nfrom nnAudio import Spectrogram\nimport torch\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime\n\ndef save_spec_images(spec, name):\n imgdt = datetime.datetime.now()\n plt.imsave(str(name) + '.png', spec[0].cpu().numpy())\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--save_type\", type=str, default=\"torch\")\n args = parser.parse_args()\n return args\n\ndef main():\n args = parse_args()\n save_type = args.save_type\n spec_layer = Spectrogram.CQT1992v2(sr=22050, n_bins=84, hop_length=256, pad_mode='constant', device='cuda:0', verbose=False, trainable=False, output_format='Magnitude')\n transformedSet = AudioDataset('input_audio.txt', 22050 * 4, sampling_rate=22050, augment=False)\n transformedLoader = DataLoader(transformedSet, batch_size=1)\n transformedVoc = []\n f = open('input_audio.txt', 'r')\n lines = f.readlines()\n lines = list(map(lambda s: s.strip(), lines)) #remove newline character\n lines = [track.replace('.wav', '') for track in lines] #remove .wav\n print(lines)\n if len(lines) != len(transformedLoader):\n print('Differences in wavs found and whats in input_audio.txt')\n return\n\n for i, x_t in enumerate(transformedLoader):\n x_t = x_t.cuda()\n s_t = spec_layer(x_t).detach()\n s_t = torch.log(torch.clamp(s_t, min=1e-5))\n transformedVoc.append(s_t.cuda())\n \n if (save_type == 'torch'):\n print('Saving WAVs as torch pt')\n for x in range(0, len(transformedVoc)):\n torch.save(transformedVoc[x], lines[x] + '.pt')\n if (save_type == 'png'):\n print('Saving WAVs as image via matplotlib')\n for x in range(0, len(transformedVoc)):\n save_spec_images(transformedVoc[x], lines[x])\n\nif __name__ == \"__main__\":\n main()","sub_path":"wav-to-spec/wav-to-cqt.py","file_name":"wav-to-cqt.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"167910211","text":"from flask import Flask, render_template,request,url_for\nimport random\n\napp = Flask(__name__)\n#methodsのs忘れずに\n@app.route('/', methods=['GET'])\ndef index():\n #nで数字の数を決める\n n = random.randrange(5, 10)\n #配列を定義\n data = []\n # n回ランダムに数字を作って配列する\n for n in range(n):\n data.append(random.randrange(0,100))\n return render_template('index.html',\\\n title='sample',\\\n message='合計を計算',\\\n data=data)\n\n\n#ここか��フィルターを作ってく\n@app.template_filter('sum')\ndef sum_filter(data):\n total = 0\n for item in data:\n total = total + item\n return total\n#フィルター登録\napp.jinja_env.filters['sum'] = sum_filter\n\n#ここから名前tatalのコンテキストプロセッサを作る これはテンプレートhtmlで関数を呼び出せるようにするもの\n@app.context_processor\n#この下の関数は登録用の関数\ndef sample_processor():\n #ここから登録したい関数を書く\n def total(n):\n total=0\n for i in range(n + 1):\n total += i\n return total\n #辞書作成で関数登録\n return dict(total=total)\n\n@app.route('/next',methods=['GET'])\ndef next():\n return render_template('next.html',\\\n title='next page',\\\n message='これは別ページ',\\\n data=['one','two','three'] )\n\n\n#session付きでメソッドメソッドベースディスパッチを作ることでユーザーごとに内容を保存できる\nfrom flask.views import MethodView\nfrom flask import session, redirect\n#sessionを使うためにシークレットキーが必要\napp.secret_key = b'rendom string......'\n\nclass HelloAPI(MethodView):\n send= ''\n\n#GETの時の処理\n def get(self):\n if 'send' in session:\n msg = 'send: ' + session['send']\n #sessionから取り出す\n send = session['send']\n else:\n msg = '何か書いてくれ'\n send = ''\n return render_template('index.html',\\\n title=\"Next Page\",\\\n message=msg,\\\n #HelloAPI class のsendに入っているのをsendに送る\n send=send)\n#POSTの時の処理\n def post(self):\n #sessionの中に登録\n session['send'] = request.form['send']\n #ページのパスへ送り込む\n return redirect('/')\n\n \n#これで登録     パス         クラス      名前(なんでもいい)\napp.add_url_rule('/hello/',view_func=HelloAPI.as_view('hello'))\n\nif __name__ == '__main__':\n app.debug = True\n app.run(host='localhost')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"522915246","text":"import pandas as pd\nimport numpy as np\nfrom datetime import date, timedelta\nimport os\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nFILEPATH = os.getenv(\"repo_filepath\") + \"findurcity/src/datasets/\"\n\n# Grab yesterday's date as MM-DD-YYYY\n\nyesterday = (date.today() - timedelta(days=2)).strftime(\"%m-%d-%Y\")\n\n# GitHub raw data URL for JHU's COVID-19 repository\n\njhu_filepath = f'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/{yesterday}.csv'\n\n# Base DataFrame for COVID-19 data\n\n\nbase_covid = pd.read_csv(jhu_filepath)\n\n\n# Necessary functions\n\ndef get_date(array):\n '''Returns a string of the first ten characters'''\n return array[:10]\n\n# Data Cleaning\ncovid_fips = base_covid.copy()\ncovid_fips['FIPS'] = covid_fips['FIPS'].replace(np.NaN, -1).astype(int)\ncovid1 = covid_fips[covid_fips['FIPS'] >= 0]\ncovid1 = covid1[~covid1['Lat'].isna() == True]\ncovid1['Date'] = covid1['Last_Update'].apply(get_date)\ncovid1['Active'] = covid1['Active'].fillna(-1).astype(int)\ncovid1 = covid1.rename(columns={'Admin2': 'County', 'Province_State': 'State', 'Long_': 'Lon'})\ncovid1['County'] = covid1['County'].fillna('Non-Contiguous 50 States')\ncovid1 = covid1.fillna(-1)\n\n# Filter into useable dataset\ncovid19_cleaned = covid1[['FIPS', 'County', 'State', 'Lat', 'Lon', 'Confirmed', 'Deaths',\n 'Recovered', 'Active', 'Incidence_Rate', 'Case-Fatality_Ratio', 'Date']]\n\ncovid19_cleaned.to_csv(FILEPATH + f\"{yesterday}.csv\", index=False)\n","sub_path":"LAMBDA_LABS/juxta-city-data-ds/findurcity/src/database/covid_scraping.py","file_name":"covid_scraping.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"524093967","text":"# -*- coding: utf-8 -*-\n\"\"\"Setup mech\"\"\"\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\nimport os\n\nfrom mech import __version__\n\n\ndef read(fname):\n \"\"\"Read in a file.\"\"\"\n try:\n with open(os.path.join(os.path.dirname(__file__), fname), \"r\") as a_file:\n return a_file.read().strip()\n except IOError:\n return ''\n\n\nsetup(\n name=\"mikemech\",\n version=__version__,\n author=\"Kevin Chung, Germán Méndez Bravo, Mike Kinney\",\n author_email=\"kchung@nyu.edu, german.mb@gmail.com, mike.kinney@gmail.com\",\n url=\"https://github.com/mkinney/mech\",\n download_url=\"https://github.com/mkinney/mech/tarball/master\",\n license=\"MIT\",\n description=\"Tool for command line virtual machines\",\n long_description=read(\"README.md\"),\n long_description_content_type=\"text/markdown\",\n keywords=['vagrant', 'vmware', 'vmrun', 'tool', 'virtualization'],\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Information Technology\",\n \"Intended Audience :: End Users/Desktop\",\n \"Intended Audience :: Science/Research\",\n \"Intended Audience :: System Administrators\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Topic :: System :: Emulators\",\n \"Topic :: Utilities\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n ],\n install_requires=['requests', 'click', 'colorama', 'pyinfra', 'pypsrp'],\n python_requires='>=3.7',\n packages=['mech'],\n entry_points={\n 'console_scripts': [\n 'mech = mech.mech_cli:cli',\n ]\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"221041563","text":"from corganize.controller.decorator.endpoint import endpoint\nfrom corganize.core.files import get_files, get_incomplete_files, update_file, get_active_files, create_file, \\\n deprecate_file\nfrom corganize.error import (BadRequestError)\n\n_REDACTED_FIELDS = [\n \"userid\",\n \"userfileid\",\n]\n\n\ndef _redact_item(item: dict, redacted_fields: list = None):\n if item:\n all_redacted_fields = _REDACTED_FIELDS + (redacted_fields or list())\n for key in [key for key in item.keys() if key in all_redacted_fields]:\n item.pop(key)\n return item\n\n\ndef _to_int(value: str):\n if value is not None:\n try:\n return int(value)\n except ValueError:\n raise BadRequestError(f\"'{value}' cannot be converted to an integer\")\n return None\n\n\ndef _create_or_update_file(core_func, userid: str, body: dict, *args, **kwargs):\n if not isinstance(body, dict):\n raise BadRequestError(\"The request body must be a dictionary\")\n\n if \"fileid\" not in body:\n raise BadRequestError(\"'fileid' is missing\")\n\n try:\n return {\n \"body\": _redact_item(core_func(userid, body))\n }\n except FileExistsError as e:\n raise BadRequestError(str(e))\n\n\n@endpoint(path=\"/files\", httpmethod=\"GET\")\ndef files_get(userid: str, nexttoken: str = None, *args, **kwargs):\n ddb_response = get_files(userid, next_token=nexttoken)\n files = [_redact_item(file) for file in ddb_response.items]\n return {\n \"body\": {\n \"metadata\": ddb_response.metadata,\n \"files\": files\n }\n }\n\n\n@endpoint(path=\"/files/incomplete\", httpmethod=\"GET\")\ndef files_get_incomplete(userid: str, nexttoken: str = None, *args, **kwargs):\n ddb_response = get_incomplete_files(userid, next_token=nexttoken)\n files = [_redact_item(file, [\"storageservice\"]) for file in ddb_response.items]\n return {\n \"body\": {\n \"metadata\": ddb_response.metadata,\n \"files\": files\n }\n }\n\n\n@endpoint(path=\"/files/active\", httpmethod=\"GET\")\ndef files_get_active(userid: str, nexttoken: str = None, *args, **kwargs):\n ddb_response = get_active_files(userid, next_token=nexttoken)\n files = [_redact_item(file) for file in ddb_response.items]\n return {\n \"body\": {\n \"metadata\": ddb_response.metadata,\n \"files\": files\n }\n }\n\n\n@endpoint(\"/files\", httpmethod=\"PATCH\")\ndef update(*args, **kwargs):\n return _create_or_update_file(update_file, *args, **kwargs)\n\n\n@endpoint(\"/files\", httpmethod=\"POST\")\ndef create(userid, body, *args, **kwargs):\n return _create_or_update_file(create_file, userid, body, *args, **kwargs)\n\n\n@endpoint(\"/files\", httpmethod=\"DELETE\")\ndef delete(userid, body, *args, **kwargs):\n status = deprecate_file(userid, body)\n r = {\"statusCode\": status}\n if status == 200:\n r.update({\"body\": {\"message\": \"success\"}})\n return r\n","sub_path":"corganize/controller/filescontroller.py","file_name":"filescontroller.py","file_ext":"py","file_size_in_byte":2913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"288802619","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n__author__ = 'Alexander Korotky'\n\nimport math\nfrom django.conf import settings\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\n\n# every tuple contain values (max_players, rounds)\nROUNDS_BY_PLAYERS = (\n (1, 0), (2, 1), (5, 3), (11, 4), (22, 5), (45, 6), (90, 7), (181, 8), (362, 9), (724, 10)\n)\n\nKK = (\n (0, 30), (1200, 15), (2400, 10)\n)\n\nCOLOR_WHITE = 'w'\nCOLOR_BLACK = 'b'\nFIGURE_COLORS = (\n (COLOR_WHITE, u'Play white figures'),\n (COLOR_BLACK, u'Play black figures')\n)\n\nGAME_WIN = 1\nGAME_DEAD_HEAT = 0.5\nGAME_LOSE = 0\nTECHNICAL_GAME = GAME_WIN\nGAME_RESULTS = (\n (GAME_WIN, u'Win game'),\n (GAME_LOSE, u'Lose game'),\n (GAME_DEAD_HEAT, u'Play dead heat')\n)\n\n\ndef get_KK(rating):\n k = KK[0][0]\n for r, k in KK:\n if rating < r:\n break\n return k\n\n\ndef queryset_filter(qs, **filter_d):\n if filter_d:\n return qs.filter(**filter_d)\n else:\n return qs.all()\n\n\ndef queryset_filter_order(qs, *order, **filter_d):\n if filter_d:\n qs = qs.filter(**filter_d)\n else:\n qs = qs.all()\n if order:\n qs = qs.order_by(*order)\n return qs\n\n\nclass Tournament(models.Model):\n '''\n Store tournaments data\n '''\n name = models.CharField(u'Name', max_length=100)\n desc = models.TextField(u'Description', blank=True, null=True)\n country = models.CharField(u'Country', max_length=100, blank=True, null=True)\n city = models.CharField(u'City', max_length=100, blank=True, null=True)\n date_begin = models.DateField(u'Date of begin', blank=True, null=True)\n date_end = models.DateField(u'Date of end', blank=True, null=True)\n total_rounds = models.PositiveSmallIntegerField(u'Total rounds', blank=True, null=True)\n current_round = models.PositiveSmallIntegerField(u'Current round', default=0)\n finish_flag = models.BooleanField(u'Finish', default=False)\n\n class Meta:\n verbose_name = u'Tournament'\n verbose_name_plural = u'Tournaments'\n\n def __unicode__(self):\n return self.name\n\n def get_players(self, *order, **filter_d):\n return queryset_filter_order(Player.objects.filter(tournamentresult__tournament=self).select_related('user'), *order, **filter_d)\n\n def get_players_count(self, **filter_d):\n return queryset_filter(self.tournamentresult_set, **filter_d).count()\n\n def get_players_statistic(self):\n return \"%d/%d\" % (self.get_players_count(leave_flag=False), self.get_players_count())\n get_players_statistic.short_description = u'Players statistic'\n\n def get_players_values(self):\n d = {}\n for res in self.get_results().select_related('player'):\n d[res.player.id] = {\n 'id': res.player.id,\n 'res_id': res.id,\n 'rating': res.player.rating,\n 'score': res.score,\n 'kb': res.kb,\n 'position': res.position,\n 'leave_flag': res.leave_flag,\n 'opponents': [],\n }\n return d\n\n def get_results(self, *order, **filter_d):\n return queryset_filter_order(self.tournamentresult_set.select_related('player', 'player__user'), *order, **filter_d)\n\n def get_games(self, *order, **filter_d):\n return queryset_filter_order(self.game_set.select_related('referee'), *order, **filter_d)\n\n def get_games_list(self, **filter_d):\n filter_d.setdefault('round', self.current_round)\n return self.game_set.filter(**filter_d).values_list('id', flat=True)\n\n def get_games_count(self, **filter_d):\n return queryset_filter(self.game_set, **filter_d).count()\n\n def get_technical_games(self, *order, **filter_d):\n return queryset_filter_order(self.technicalgameresult_set.select_related('player', 'player__user'), *order, **filter_d)\n\n def get_technical_games_count(self, **filter_d):\n return queryset_filter(self.technicalgameresult_set, **filter_d).count()\n\n def get_games_statistic(self):\n return \"%d/%d\" % (self.get_games_count(), self.get_technical_games_count())\n get_games_statistic.short_description = u\"Games statistic\"\n\n def get_games_results(self, *order, **filter_d):\n return queryset_filter_order(GameResult.objects.select_related('player', 'player__user'), *order, **filter_d)\n\n def get_games_results_values(self, *order, **filter_d):\n d = {}\n for res in self.get_games_results(*order, **filter_d):\n d[res.player.id] = {\n 'id': res.player.id,\n 'res_id': res.id,\n 'game': res.game_id,\n 'score': res.score,\n 'color': res.color,\n }\n return d\n\n def get_rounds_statistic(self):\n return \"%d/%d\" % (self.current_round, self.total_rounds)\n get_rounds_statistic.short_description = \"Round statistic\"\n\n def calc_total_rounds(self):\n reg_players = self.get_players_count()\n if not reg_players:\n return 0\n for num_players, rounds in ROUNDS_BY_PLAYERS:\n if reg_players <= num_players:\n break\n return rounds\n calc_total_rounds.short_description = u'Total rounds'\n\n def update_results(self, round):\n games = self.get_games().values_list('id', flat=True)\n res_list = [res for res in GameResult.objects.filter(game__in=games).values_list()]\n players_d = {}\n games_d = {}\n for res in res_list:\n if not players_d.has_key(res['player']):\n players_d[res['player']] = {\n 'score': res['score'],\n 'kb': 0,\n 'position': 0\n }\n else:\n players_d[res['player']]['score'] += res['score']\n if not games_d.has_key(res['game']):\n games_d[res['game']] = {\n res['player']: res['score']\n }\n else:\n games_d[res['game']].update({res['player']: res['score']})\n while len(games_d):\n _, game_d = games_d.popitem()\n p1 = game_d.popitem()\n p2 = game_d.popitem()\n players_d[p1[0]]['kb'] += p2[1]\n players_d[p2[0]]['kb'] += p1[1]\n for tr in self.get_technical_games():\n if not players_d.has_key(tr.player.id):\n players_d[tr.player.id] = {\n 'score': tr.score,\n 'kb': 0,\n 'position': 0\n }\n else:\n players_d[tr.player.id]['score'] += tr.score\n players_l = players_d.items()\n del players_d\n def cmp_func(a, b):\n if a[1]['score'] > b[1]['score']:\n return 1\n elif a[1]['score'] < b[1]['score']:\n return -1\n else:\n if a[1]['kb'] > b[1]['kb']:\n return 1\n elif a[1]['kb'] < b[1]['kb']:\n return -1\n else:\n return 0\n players_l.sort(cmp_func)\n pos = 1\n players_l[0][1]['position'] = 1\n length = len(players_l)\n i = 1\n while i < length:\n if not (players_l[i-1][1]['score'] == players_l[i][1]['score'] and players_l[i-1][1]['kb'] == players_l[i][1]['kb']):\n pos += 1\n players_l[i][1]['position'] = pos\n for pl_id, pl_d in players_l:\n try:\n player = TournamentResult.objects.get(tournament=self, player=pl_id)\n player.score = pl_d['score']\n player.kb = pl_d['kb']\n player.position = pl_d['position']\n player.save()\n except TournamentResult.DoesNotExist:\n pass\n\n\nclass Player(models.Model):\n '''\n Stope players data such as rating, etc...\n '''\n user = models.OneToOneField(User, verbose_name=u'User')\n rating = models.PositiveSmallIntegerField(u'Rating', default=0)\n\n class Meta:\n verbose_name = u'Player'\n verbose_name_plural = u'Players'\n\n def __unicode__(self):\n return u'%s %s' % (self.user.first_name, self.user.last_name)\n\n def get_opponents_list(self, tournament):\n l = []\n for player in self.gameresult_set.filter(tournamentresult__tournament=tournament):\n l.append(player.player_id)\n return l\n\n\nclass TournamentResult(models.Model):\n '''\n Store player data for differends tournaments such as score, position, etc...\n '''\n tournament = models.ForeignKey(Tournament, verbose_name=u'Tournament')\n player = models.ForeignKey(Player, verbose_name=u'Player')\n score = models.FloatField(u'Score', default=0)\n kb = models.FloatField(u'Buchholz score', default=0)\n position = models.PositiveSmallIntegerField(u'Position', blank=True, null=True)\n leave_flag = models.BooleanField(u'Is leave', default=False)\n\n class Meta:\n verbose_name = u'Player Tournament result'\n verbose_name_plural = u'Player Tournaments results'\n unique_together = ('tournament', 'player')\n\n def get_position(self):\n if self.position:\n return self.position\n return '-'\n get_position.short_description = u'Position'\n\n def get_player_rating(self):\n return self.player.rating\n get_player_rating.short_description = u'Rating'\n\n\nclass Game(models.Model):\n '''\n Store game data.\n '''\n tournament = models.ForeignKey(Tournament, verbose_name=u'Tournament')\n round = models.PositiveSmallIntegerField(u'Round')\n referee = models.ForeignKey(User, verbose_name=u'Referee', blank=True, null=True)\n date = models.DateField(u'Date', blank=True, null=True)\n\n class Meta:\n verbose_name = u'Game'\n verbose_name_plural = u'Games'\n\n def __unicode__(self):\n count = len(self.players_res)\n if not count:\n return 'empty game'\n else:\n if count == 1:\n return 'technical game for %s' % self.players_res[0].player\n if count == 2:\n return '%s - %s' % (self.players_res[0].player, self.players_res[1].player)\n\n def get_referee_info(self):\n if self.referee:\n return u'%s %s' % (self.referee.first_name, self.referee.last_name)\n return '-------'\n get_referee_info.short_description = u'Referee'\n\n def get_players(self, *order, **filter_d):\n return queryset_filter_order(Player.objects.filter(gameresult__game=self).select_related('user'), *order, **filter_d)\n\n def get_players_res(self, **filter_d):\n return queryset_filter_order(self.gameresult_set.select_related('player', 'player_user'), **filter_d)\n\n @property\n def players(self):\n if not hasattr(self, '_players'):\n setattr(self, '_players', tuple([player for player in self.get_players().all()]))\n return self._players\n\n @property\n def players_res(self):\n if not hasattr(self, '_players_res'):\n setattr(self, '_players_res', tuple([player for player in self.get_players_res()]))\n return self._players_res\n\n def recalc_ratings(self):\n if len(self.players_res) == 2:\n p1 = self.players_res[0].player\n p2 = self.players_res[1].player\n e1 = 1/(1 + math.pow(10, (p2.rating - p1.rating)/400.0))\n res1 = self.players_res[0].score\n p1.rating += get_KK(p1.rating) * (res1 - e1)\n p2.rating += get_KK(p2.rating) * (e1 - res1)\n\n @property\n def color_values(self):\n if len(self.players_res) == 2:\n if not hasattr(self, '_color_values'):\n setattr(self, '_color_values', {\n 0: '-------',\n self.players_res[0].id: self.players_res[0].player,\n self.players_res[1].id: self.players_res[1].player,\n })\n return self._color_values\n else:\n return {0: '-------'}\n\n def get_color_choices(self):\n return self.color_values.items()\n\n def get_color_initial(self):\n if len(self.players_res) == 2:\n pr1 = self.players_res[0]\n pr2 = self.players_res[1]\n if pr1.color == COLOR_WHITE and pr2.color == COLOR_BLACK:\n return pr1.id\n elif pr1.color == COLOR_BLACK and pr2.color == COLOR_WHITE:\n return pr2.id\n else:\n return 0\n else:\n return 0\n\n def get_color_display(self):\n return self.color_values[self.get_color_initial()]\n get_color_display.short_description = u'Play white figures'\n\n def set_color(self, value):\n if value != None:\n value = int(value)\n if value == self.players_res[0].id:\n self.players_res[0].color = COLOR_WHITE\n self.players_res[1].color = COLOR_BLACK\n elif value == self.players_res[1].id:\n self.players_res[1].color = COLOR_WHITE\n self.players_res[0].color = COLOR_BLACK\n\n @property\n def result_values(self):\n if len(self.players_res) == 2:\n if not hasattr(self, '_result_values'):\n setattr(self, '_result_values', {\n 0: u'Dead heat',\n self.players_res[0].id: u'%s win' % self.players_res[0].player,\n self.players_res[1].id: u'%s win' % self.players_res[1].player,\n })\n return self._result_values\n else:\n return {0: u'Dead heat'}\n\n def get_result_choices(self):\n return self.result_values.items()\n\n def get_result_initial(self):\n if len(self.players_res) == 2:\n pr1 = self.players_res[0]\n pr2 = self.players_res[1]\n if pr1.score == GAME_WIN and pr2.score == GAME_LOSE:\n return pr1.id\n elif pr1.score == GAME_DEAD_HEAT and pr2.score == GAME_DEAD_HEAT:\n return 0\n elif pr1.score == GAME_LOSE and pr2.score == GAME_WIN:\n return pr2.id\n else:\n return 0\n else:\n return 0\n\n def get_result_display(self):\n return self.result_values[self.get_result_initial()]\n get_result_display.short_description = u'Game result'\n\n def set_result(self, value):\n if value != None:\n value = int(value)\n if value == self.players_res[0].id:\n self.players_res[0].score = GAME_WIN\n self.players_res[1].score = GAME_LOSE\n elif value == self.players_res[1].id:\n self.players_res[1].score = GAME_WIN\n self.players_res[0].score = GAME_LOSE\n elif value == 0:\n self.players_res[0].score = self.players_res[1].score = GAME_DEAD_HEAT\n\n def is_game_valid(self):\n if not self.tournament:\n return False\n if not self.round:\n return False\n if not self.referee:\n return False\n if not self.date:\n return False\n if len(self.players_res) != 2:\n return False\n if (self.players_res[0].color is None) and (self.players_res[1].color is None):\n return False\n if (self.players_res[0].score is None) and (self.players_res[1].score is None):\n return False\n return True\n is_game_valid.short_description = u'Game valid'\n\n def save_players(self):\n self.players_res[0].save()\n self.players_res[1].save()\n self.players_res[0].player.save()\n self.players_res[1].player.save()\n\n\nclass GameResult(models.Model):\n '''\n Store player game results.\n '''\n game = models.ForeignKey(Game, verbose_name=u'Tournament')\n player = models.ForeignKey(Player, verbose_name=u'Player', blank=True, null=True)\n score = models.FloatField(u'Score', default=GAME_LOSE, choices=GAME_RESULTS)\n color = models.CharField(u'Color of figure', max_length=1, choices=FIGURE_COLORS)\n\n class Meta:\n verbose_name = u'Game Result'\n verbose_name_plural = u'Games Results'\n\n def __unicode__(self):\n return u'%s' % self.player\n\n def get_results_for_games(self, games, *order, **filter_d):\n return queryset_filter_order(self.objects.filter(game__in=games), *order, **filter_d)\n\n\nclass TechnicalGameResult(models.Model):\n tournament = models.ForeignKey(Tournament, verbose_name=u'Tournament')\n player = models.ForeignKey(Player, verbose_name=u'Player')\n round = models.PositiveSmallIntegerField(u'Round')\n score = models.FloatField(u'Score', default=TECHNICAL_GAME)\n\n class Meta:\n verbose_name = u'Technical game result'\n verbose_name_plural = u'Technical games results'\n unique_together = ('tournament', 'player', 'round')\n\n def __unicode__(self):\n return u'%s' % self.player","sub_path":"main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":16901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"428038621","text":"\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nCOURSE = 'COS10001'\n\nif __name__ == '__main__':\n\t# Read data\n\tdata = pd.read_csv('./data/data.csv')\n\tdata = data[data['CourseID'] == 'COS10001']['NumCurUnits'].values\n\n\t# Prepare data for plot\n\tx = [1, 2, 3, 4]\n\theight = [0, 0, 0, 0]\n\tfor num_unit in data:\n\t\theight[num_unit - 1] += 1\n\n\t# Plot\n\tplt.figure(figsize=(10, 8))\n\tplt.bar(x, height)\n\tfor i, v in enumerate(height):\n\t\tplt.text(x[i] - 0.04, v + 0.08, str(v), fontdict={\"size\": 16, \"weight\": \"bold\"})\n\n\tplt.xticks(x, fontsize=20)\n\tplt.yticks(fontsize=20)\n\tplt.xlabel(\"Number of enrolled units\", fontdict={\"size\": 24})\n\tplt.ylabel(\"Number of students\", fontdict={\"size\": 24})\n\tplt.show()\n","sub_path":"src/units_plot.py","file_name":"units_plot.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"122916980","text":"import logging\nimport sqlite3\nimport abc\n\nfrom .models import DiigoExport\n\nclass AbstractImportRepository(metaclass=abc.ABCMeta):\n \n @abc.abstractmethod\n def save_backup_info(self, backup_info):\n pass\n\n @abc.abstractmethod\n def fetch_latest_backup(self): \n pass\n\n\nclass SqlLiteImportRepository(AbstractImportRepository):\n '''\n https://docs.python.org/3/library/sqlite3.html\n https://docs.python.org/3/library/sqlite3.html#using-shortcut-methods\n '''\n\n def __init__(self, connection_string: str):\n self.connection_string = connection_string\n \n \n def save_backup_info(self, bkpjob: DiigoExport):\n try:\n with sqlite3.connect(self.connection_string) as conn:\n sql =(f\"\"\"\nINSERT INTO import\n (job_id\n ,export_format\n ,status\n ,version\n ,download_link)\nVALUES\n (:job_id \n ,:export_format\n ,:status\n ,:version\n ,:download_link)\"\"\")\n c = conn.cursor()\n c.execute(sql, \n {\n 'job_id': bkpjob.job_id\n , 'export_format': bkpjob.export_format\n , 'status': bkpjob.status\n , 'version': bkpjob.version\n , 'download_link': bkpjob.download_link\n })\n except sqlite3.IntegrityError:\n logging.info('Backup with id {bkpjob.job_id} was already imported')\n\n \n def fetch_latest_backup(self):\n with sqlite3.connect(self.connection_string) as conn:\n sql = (\"\"\"\nSELECT job_id \n , export_format \n\t, status\n\t, version\n\t, download_link\n\t, import_date\nFROM import order by version desc limit 1;\n\"\"\" )\n c = conn.cursor()\n c.execute(sql)\n backup = c.fetchone()\n return backup\n\ndef make_db(connection_string: str) -> AbstractImportRepository:\n if (connection_string.endswith('.db')):\n return SqlLiteImportRepository(connection_string)","sub_path":"tools/diigo/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"488097864","text":"\r\nfrom rocketcea.biprop_utils.rho_isp_plot_obj import RhoIspPlot\r\nfrom rocketcea.biprop_utils.veh_stage_obj import ConstMassFracStage\r\n\r\nrp = RhoIspPlot(bipropL=[('LOX','LH2'),('N2O4','MMH')], nsteps_sg=90, nsteps_isp=90)\r\n\r\nstg_obj = ConstMassFracStage( mass_frac=0.8, WtPayload=1000.0 )\r\n\r\nrp.add_rho_isp_contours()\r\n\r\nrp.add_stage_param_contours( stg_obj, set_param='GLOW', param_value=2000.0,\r\n plot_paramL=['DeltaV'],\r\n plot_param_valD={'DeltaV':[4500., 5000., 5500., 6000., 6500., 7000.]})\r\n \r\nrp.savefig('const_mass_frac2.png', dpi=120)\r\nrp.show()\r\n\r\n","sub_path":"lib/python2.7/site-packages/rocketcea/examples/const_mass_frac2.py","file_name":"const_mass_frac2.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"633272501","text":"from typing import List\nfrom ...._C import THUlac\nfrom ....data import load\nfrom ..BaseCWS import BaseCWS\nfrom ....utils import DictExtraction\nfrom ....utils.format_output import format_output, dict_format\nfrom functools import reduce\n\nlabels = reduce(lambda x, y: x+y, [[f\"{kd}-{l}\" for kd in ('B','I','O')] for l in ('SEG',)])\nclass THUlacCWS(BaseCWS):\n \"\"\"基于THULAC的分词算法\n\n :Name: thulac\n\n 更多信息请参考 thulac 文档: `http://thulac.thunlp.org/ `_ 。\n\n **示例**\n\n .. code-block:: python\n\n oknlp.cws.get_by_name(\"thulac\")\n \"\"\"\n\n def __init__(self, dictionary = []):\n model_path = load(\"cws.lac\", 'fp32')\n self.model = THUlac(model_path)\n self.__closed = False\n self.keyword_processor=DictExtraction(case_sensitive = False)\n self.keyword_processor.add_keywords_from_list(dictionary) \n\n def __call__(self, sents: List[str]) -> List[List[str]]:\n result = [self.model.cut(sent) for sent in sents]\n results = []\n for sep in result:\n if sep[-1] == '\\n':\n sep = sep[:-1]\n results.append(sep)\n results = [dict_format(result, self.keyword_processor.extract_dictwords(''.join(result))) for result in results]\n \n return results\n def close(self):\n if self.__closed:\n return\n self.__closed = True\n del self.model","sub_path":"oknlp/algorithm/cws/thulac_cws/THUlacCWS.py","file_name":"THUlacCWS.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"526762087","text":"\nclass ListNode(object):\n\n def __init__(self, val, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n \"\"\"\n @param: head: The first node of linked list\n @param: x: An integer\n @return: A ListNode\n \"\"\"\n\n def partition(self, head, x):\n # write your code here\n if head is None:\n return head\n\n aDummy, bDummy = ListNode(0), ListNode(0)\n aCur, bCur = aDummy, bDummy\n while head:\n if head.val < x:\n aCur.next = head\n head = head.next\n aCur = aCur.next\n else:\n bCur.next = head\n head = head.next\n bCur = bCur.next\n\n bCur.next = None # !! care !!\n aCur.next = bDummy.next\n\n return aDummy.next\n\n\n\n","sub_path":"lintcode/partition-list.py","file_name":"partition-list.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"112009524","text":"import tensorflow as tf\nimport numpy as np\n\ndef make_bb_tensor(y_mins, x_mins, y_maxes, x_maxes):\n \"\"\" Makes a TF Tensor from 4 arrays of bounding box\n extents\n \"\"\"\n\n boxes = []\n num_boxes = len(y_mins)\n\n assert(y_mins == x_mins == y_maxes == x_maxes)\n\n for i in range(num_boxes):\n box = [y_mins[i], x_mins[i], y_maxes[i], x_maxes[i]]\n boxes.append(box)\n\n boxes_tensor = make_bb_tensor(boxes)\n\n return boxes_tensor\n \n\ndef make_bb_tensor(bb_np_array):\n \"\"\" Makes a TF Tensor from a NumPy array of bounding boxes\n \"\"\"\n return tf.convert_to_tensor(bb_np_array)","sub_path":"processing/bb_utils.py","file_name":"bb_utils.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"650773827","text":"import jittor as jt \nfrom jittor import nn \n\nfrom jdet.utils.registry import MODELS,build_from_cfg,BACKBONES,HEADS,NECKS\n\n\n@MODELS.register_module()\nclass S2ANet(nn.Module):\n \"\"\"\n \"\"\"\n\n def __init__(self,backbone,neck=None,bbox_head=None):\n super(S2ANet,self).__init__()\n self.backbone = build_from_cfg(backbone,BACKBONES)\n self.neck = build_from_cfg(neck,NECKS)\n self.bbox_head = build_from_cfg(bbox_head,HEADS)\n\n def train(self):\n super().train()\n self.backbone.train()\n\n def execute(self,images,targets):\n '''\n Args:\n images (jt.Var): image tensors, shape is [N,C,H,W]\n targets (list[dict]): targets for each image\n Rets:\n outputs: train mode will be losses val mode will be results\n '''\n features = self.backbone(images)\n \n if self.neck:\n features = self.neck(features)\n \n outputs = self.bbox_head(features, targets)\n \n return outputs","sub_path":"python/jdet/models/networks/s2anet.py","file_name":"s2anet.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"289117493","text":"# -*- coding: utf-8 -*-\n\n\ndef count_same_char(words):\n \"\"\"\n Calculation of same letters in word\n\n input: \n 1d-list of words \n return: \n 2d-matrix (Number of words x Number of words)\n \"\"\"\n\n words_is_list = isinstance(words, list)\n\n if words_is_list:\n words_same_char_count = []\n for word in words: # List iteration, get word\n word_char_count = [] # Local list of counter\n for word_compare in words: # Iteration of words list for comparison\n if word == word_compare: # Check same words\n count = -1\n else: # Not same words\n count = 0 # count of letters\n for char in ''.join(set(word)): # Iteration of letters\n if char in ''.join(set(word_compare)):\n count += 1 # If letter in word counter+1\n word_char_count.append(count)\n words_same_char_count.append(word_char_count)\n else:\n print('Error. words is not a list')\n words_same_char_count = []\n\n return words_same_char_count\n\n\ndef text_to_words(text, store_nums=0):\n \"\"\"\n Split text to words\n input: \n text - str or list of strings\n store_nums - save numbers in text (1 - save, 0 or other - delete)\n return:\n words - list of words\n \"\"\"\n\n import re\n\n text_is_list = isinstance(text, list)\n if text_is_list:\n text = ' '.join(text)\n\n text_is_str = isinstance(text, str)\n if text_is_str:\n text = text.lower()\n if store_nums == 1:\n words = re.sub(u'[^a-zA-Z0-9\\u0400-\\u0500]', ' ', text)\n else:\n words = re.sub(u'[^a-zA-Z\\u0400-\\u0500]', ' ', text)\n while ' ' in words:\n words = words.replace(' ', ' ')\n if words[-1] == ' ':\n words = words[:-1]\n if words[0] == ' ':\n words = words[1:]\n\n words = words.split(' ')\n else:\n print('Error. Text is not str or list with string')\n words = []\n\n return words\n\n\ndef ext_unique_words(words):\n \"\"\"\n Find and store unique words in list\n input: \n words - list of words\n return: \n words_unique - list with unique values\n \"\"\"\n words_is_list = isinstance(words, list)\n\n if words_is_list:\n words_unique = sorted(set(words), key=words.index) # unique list\n else:\n print('Error. words is not a list')\n words_unique = []\n\n return words_unique\n\n\ndef count_words(words, words_unique):\n \"\"\"\n input:\n words - list of non unique words\n words_unique - list with unique words\n return:\n counter - list with countint\n \"\"\"\n import re\n\n text_is_list = isinstance(words, list)\n text_is_str = isinstance(words, str)\n words_unique_is_list = isinstance(words_unique, list)\n\n counter = []\n if words_unique_is_list:\n if (text_is_str is False) and (text_is_list is True):\n for word in words_unique:\n counter.append(words.count(word))\n elif (text_is_str is True) and (text_is_list is False):\n words = re.sub(u'[^a-zA-Z0-9\\u0400-\\u0500]', ' ', words)\n while ' ' in words:\n words = words.replace(' ', ' ')\n if words[-1] == ' ':\n words = words[:-1]\n if words[0] == ' ':\n words = words[1:]\n words = words.split(' ')\n for word in words_unique:\n counter.append(words.count(word))\n else:\n print('Error. text_word is not a list or string')\n else:\n print('Error. words_unique is not a list')\n\n return counter\n\n\ndef delete_stop_words(words, stop_words):\n \"\"\"\n Deleting of stop-words\n input:\n words or words_unique - list of words\n stop_words - list of stop words\n \"\"\"\n\n words_is_list = isinstance(words, list)\n stop_words_is_list = isinstance(stop_words, list)\n\n if words_is_list and stop_words_is_list:\n for word in stop_words:\n if word in words:\n words.remove(word)\n else:\n print('Error. words or(and) stop_words are not a list(s)')\n\n return words\n\n\ndef create_dict(words_unique):\n \"\"\"\n Create dictionary from words_unique\n input:\n words_unique - list with unique words\n \"\"\"\n words_unique_is_list = isinstance(words_unique, list)\n words_dict = {}\n\n if words_unique_is_list:\n word_id = 0\n for word in words_unique:\n if word not in words_dict:\n word_id += 1\n words_dict[word] = word_id\n else:\n print('Error (create_dict). words_unique is not a list')\n\n return words_dict\n\n\ndef encode_words(words, words_dict):\n \"\"\"\n Encoding of text with dictionary\n input:\n words - list of words\n return:\n words_encoding - encoded list of words\n \"\"\"\n words_encoding = []\n for word in words:\n try:\n words_encoding.append(words_dict[word])\n except KeyError:\n continue\n\n return words_encoding\n","sub_path":"pytextpra/pytextpra.py","file_name":"pytextpra.py","file_ext":"py","file_size_in_byte":5122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"133796057","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.utils import np_utils\nfrom keras.datasets import mnist\nimport pandas as pd\nimport os\nimport cv2\n\n\n# get data training and data test\n(X_train, y_train), (X_test, y_test) = mnist.load_data() #read database\nX_val, y_val = X_train[50000:60000,:], y_train[50000:60000] # get data test from 50000 - 60000\nX_train, y_train = X_train[:50000,:], y_train[:50000] # data train from 0- 50000\nprint(y_train) # get size X\n\n# 3. Reshape lại dữ liệu cho đúng kích thước mà keras yêu cầu\nX_train = X_train.reshape(X_train.shape[0], 28, 28, 1) # sắp xếp lại thành ma trận n*28*28*1\nX_val = X_val.reshape(X_val.shape[0], 28, 28, 1)\nX_test = X_test.reshape(X_test.shape[0], 28, 28, 1)\n\n\n# 4. One hot encoding label (Y)\nY_train = np_utils.to_categorical(y_train, 10) # trai out put (gan nhan)\nY_val = np_utils.to_categorical(y_val, 10)\nY_test = np_utils.to_categorical(y_test, 10)\nprint('Dữ liệu y ban đầu ', y_train[0])\nprint('Dữ liệu y sau one-hot encoding ',Y_train[0])\n\n# 5. Định nghĩa model\nmodel = Sequential()\n\n# Thêm Convolutional layer với 32 kernel, kích thước kernel 3*3\n# dùng hàm sigmoid làm activation và chỉ rõ input_shape cho layer đầu tiên\nmodel.add(Conv2D(32, (3, 3), activation='sigmoid', input_shape=(28, 28, 1))) # add so kernel, kich thuoc kernel ham active va input\n# =>>> 28*28*32\n# Thêm Convolutional layer\nmodel.add(Conv2D(48, (3, 3), activation='sigmoid'))\n# =>>> 28*28*48\n# Thêm Max pooling layer\nmodel.add(MaxPooling2D(pool_size=(2, 2))) # chuyen kich thuoc ve\n# =>> 1\n# Flatten layer chuyển từ tensor sang vector\nmodel.add(Flatten())\n\n# Thêm Fully Connected layer với 128 nodes và dùng hàm sigmoid\nmodel.add(Dense(128, activation='sigmoid'))\n\n# Output layer với 10 node và dùng softmax function để chuyển sang xác xuất.\nmodel.add(Dense(10, activation='softmax'))\n\nmodel.summary()\n\n\n# 6. Compile model, chỉ rõ hàm loss_function nào được sử dụng, phương thức\n# đùng để tối ưu hàm loss function.\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\n\n\nH = model.fit(X_train, Y_train, validation_data=(X_val, Y_val),\n batch_size=32, epochs=10, verbose=1)\n\n\n\n\n'''\n# 8. Vẽ đồ thị loss, accuracy của traning set và validation set\nfig = plt.figure()\nnumOfEpoch = 10\nplt.plot(np.arange(0, numOfEpoch), H.history['loss'], label='training loss')\nplt.plot(np.arange(0, numOfEpoch), H.history['val_loss'], label='validation loss')\nplt.plot(np.arange(0, numOfEpoch), H.history['acc'], label='accuracy')\nplt.plot(np.arange(0, numOfEpoch), H.history['val_acc'], label='validation accuracy')\nplt.title('Accuracy and Loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss|Accuracy')\nplt.legend()\n\n# 9. Đánh giá model với dữ liệu test set\nscore = model.evaluate(X_test, Y_test, verbose=0)\nprint(score)\n\n\n# 10. Dự đoán ảnh\n#plt.imshow(X_test[0].reshape(28,28), cmap='gray')\n'''\ny_predict = model.predict(X_test[0].reshape(1,28,28,1))\nprint('Giá trị dự đoán: ', np.argmax(y_predict))\ncv2.imshow('anh du doan',X_test[0].reshape(28,28));\ncv2.waitKey(0);\ncv2.destroyAllWindows();\n","sub_path":"tự học/deep learning/keras_MMNS.py","file_name":"keras_MMNS.py","file_ext":"py","file_size_in_byte":3374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"129492526","text":"\"\"\"\r\n\n\nThe function is given two strings `t` \\- template, `s` \\- to be sorted. Sort\nthe characters in `s` such that if the character is present in `t` then it is\nsorted according to the order in `t` and other characters are sorted\nalphabetically after the ones found in `t`.\n\n### Examples\n\n custom_sort(\"edc\", \"abcdefzyx\") ➞ \"edcabfxyz\"\n \n custom_sort(\"fby\", \"abcdefzyx\") ➞ \"fbyacdexz\"\n \n custom_sort(\"\", \"abcdefzyx\") ➞ \"abcdefxyz\"\n \n custom_sort(\"\", \"\") ➞ \"\"\n\n### Notes\n\nThe characters in `t` and `s` are all lower-case.\n\n\"\"\"\r\n\ndef custom_sort(t, s):\n aux = ''\n for c1 in s:\n if c1 in t:\n aux += c1\n s = s.replace(c1, '')\n aux2 = ''\n for c2 in t:\n for c3 in aux:\n if c2 == c3:\n aux2 += c3\n return aux2 + ''.join(sorted(s))\n\n","sub_path":"Akx92Ldcy78xp5zCF_2.py","file_name":"Akx92Ldcy78xp5zCF_2.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"355986504","text":"from lib import rpclib\nfrom slickrpc import Proxy\nimport requests\nimport json\nimport sys\n\nrpc_user = \"changeme\"\nrpc_password = \"alsochangeme\"\nport = 24708\n\nrpc_connect = rpc_connection = Proxy(\"http://%s:%s@127.0.0.1:%d\"%(rpc_user, rpc_password, port));\n\n\n#privkey = \"Uv2jzAFb6UttFYmCWGRyuMxafDHNie15eFe7KYXuvgDzfgWancks\"\n\nurl = \"http://seed.juicydev.coingateways.com:24711/insight-api-komodo/addrs/RS7y4zjQtcNv7inZowb8M6bH3ytS1moj9A/utxo\"\n\nmaxsize = float(sys.argv[2])\nmaxcount = int(sys.argv[3])\naddress = sys.argv[1]\n\ntry:\n res = requests.get(url)\nexcept Exception as e:\n print(e)\n\nto_python = json.loads(res.text)\n\ncount = 0\n\nlist_of_ids = []\nlist_of_vouts = []\namount = 0\n\n\nfor objects in to_python:\n if (objects['amount'] < maxsize) and count < maxcount:\n count = count + 1\n easy_typeing2 = [objects['vout']]\n easy_typeing = [objects['txid']]\n list_of_ids.extend(easy_typeing)\n list_of_vouts.extend(easy_typeing2)\n amount = amount + objects['amount']\n\namount = round(amount, 10)\n\n#key = rpclib.importprivkey(rpc_connect, privkey)\n\nres = rpclib.createrawtransaction(rpc_connect, list_of_ids, list_of_vouts, address, amount)\n\nfinal_res = rpclib.signrawtx(rpc_connect, res)\n\nfinal_res = final_res['hex']\n\nparams = { 'rawtx':final_res }\n\nurl = \"http://seed.juicydev.coingateways.com:24711/insight-api-komodo/tx/send\"\n\ntry:\n res = requests.post(url, data=params)\nexcept Exception as e:\n print(e)\n\nprint(res.text)\n","sub_path":"combinedscripts.py","file_name":"combinedscripts.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"537915916","text":"\"\"\"\nCKY parser module\n\nThis CKY parser module is a special case of the CKY parsing algorithm\nthat detects if a sentence has an omission in it and predicts the\nlocation and part of speech of that omission.\n\nUses the InvertedGrammar class to accomplish this with the parse method,\nwhich determines the most probable parse of a sentence with or without\nBLANKs between words\n\nCasey Gowrie\nCOMP150NLP\n5/12/16\n\n\"\"\"\n\nimport sys, re\nimport nltk\nfrom nltk.corpus import treebank\nfrom collections import defaultdict\nfrom collections import Counter\nfrom nltk import induce_pcfg\nfrom nltk.grammar import Nonterminal\nfrom nltk.tree import Tree\nfrom math import exp, pow\nfrom multiprocessing import Process, Queue\n\nfrom hmm import *\nfrom utils import *\n\ndef flatten_generator(gs):\n \"\"\" Returns a flattened generator \"\"\"\n return (x for g in gs for x in g)\n \nclass InvertedGrammar:\n \"\"\" InvertedGrammar class which is a wrapper for a PCFG that allows\n for the implementation of the CKY parsing variant used in omission\n Detection\n \"\"\"\n\n def __init__(self, pcfg):\n \"\"\" Initialization for the InvertedGrammar class \n\n Args:\n pcfg -- a Probablistic Context Free Grammar from the nltk which\n can be trained using the induce_pcfg method\n \"\"\"\n self._pcfg = pcfg\n self._r2l = defaultdict(list) # maps RHSs to list of LHSs\n self._r2l_lex = defaultdict(list) # maps lexical items to list of LHSs\n self._l2prod_lex = defaultdict(set) # mpas lexical LHSs to rhs\n self._r2prod = defaultdict(list) # maps rhs to list of ProbablisticProd\n self.build_index() # populates self._r2l and self._r2l_lex\n \n # def print_index(self, filename):\n # f = open(filename, \"w\")\n # for rhs, prods in self._r2l.iteritems():\n # f.write(\"%s\\n\" %str(rhs))\n # for prod in prods:\n # f.write(\"\\t%s\\n\" %str(prod))\n # f.write(\"---\\n\")\n # for rhs, prods in self._r2l_lex.iteritems():\n # f.write(\"%s\\n\" %str(rhs))\n # for prod in prods:\n # f.write(\"\\t%s\\n\" %str(prod))\n # f.write(\"---\\n\")\n # f.close()\n \n def build_index(self):\n \"\"\" Builds an inverted index of the grammar. maps right hand sides of \n all productions to their left hands sides.\n \"\"\"\n for prod in self._pcfg.productions():\n self._r2prod[prod.rhs()].append(prod)\n if prod.is_lexical():\n self._r2l_lex[prod.rhs()].append(prod)\n self._l2prod_lex[prod.lhs()].add(prod.rhs())\n else:\n self._r2l[prod.rhs()].append(prod.lhs()) \n\n \n def _generate_candidates(self, p_store, i, k, j):\n \"\"\" Generates all possible rhs of productions from i,j split at k \n in table.\n Used for iteration.\n\n Args:\n p_store -- map from (i,j) to A stored in the table cell\n i,k,j -- split points\n \"\"\"\n # all possible combinations of BC given current store\n potential_rhs = ((b, c) for b in p_store[(i,k)] \\\n for c in p_store[(k,j)])\n # all A->BC in grammar\n # potentials = (self._r2prod[rhs] for rhs in potential_rhs)\n # return flatten_generator(potentials)\n return potential_rhs\n\n def _augment_sentence(self, sent):\n \"\"\" Augments a sentence with BLANK tokens between every word \"\"\"\n new_sent = []\n for w in sent:\n new_sent.append(BLANK_TOKEN)\n new_sent.append(w)\n return new_sent\n\n \n def parse(self, sent):\n \"\"\" Returns the parse tree for the best parse of the sent that may or\n may not contain BLANK spaces.\n\n Uses a variant on the CKY algorithm, in which each cell, table[i,j,A]\n represents the most probable constituent A that spans i through j in \n sentence and may or may not include blanks.\n\n Args:\n sent -- list of words\n\n Returns:\n Tuple\n - most probable parse tree that may have BLANK leaves\n - it's log probability\n \"\"\"\n sent = self._augment_sentence(sent)\n\n table = defaultdict(lambda: float(\"-inf\")) # table stores logP\n back = defaultdict(tuple) # backpointers\n p_store = defaultdict(set) # list of existing lhs in each cell\n # to be used for generating future\n # productions\n # r2l_lex_all = [v for (_,vs) in self._l2prod_lex.items() for v in vs]\n\n for j in range(1, len(sent) + 1):\n # initialization of lexical nodes\n w = sent[j-1]\n rhs = (w,)\n # if augmented sentence contains BLANK here\n if w == BLANK_TOKEN:\n # only consider lexical prods for blank\n for lhs in self._l2prod_lex:\n # assign uniform probability dist. across lhs\n # so 1 / number(unique lhs productions)\n perc = 1.0 / float(len(self._l2prod_lex[lhs]))\n table[(j-1, j, lhs)] = log(perc)\n p_store[(j-1, j)].add(lhs)\n\n # normal lexical initialization\n else:\n for prod in self._r2l_lex[rhs]:\n table[(j-1, j, prod.lhs())] = log(prod.prob())\n p_store[(j-1, j)].add(prod.lhs())\n\n\n # recursion\n for i in range(len(sent) - 2, -1, -1):\n for k in range(i + 1, j):\n # for all possible B,C combinations, we allow them to\n # carry through and skip a surrounding BLANK\n for potential_rhs in \\\n self._generate_candidates(p_store, i, k, j):\n\n B = potential_rhs[0]\n C = potential_rhs[1]\n\n # can skip front blank and carry through C\n # i.e. sentence is C\n if k == i + 1 and sent[i] == BLANK_TOKEN:\n if table[(i,j,C)] < table[(k,j,C)]:\n table[(i,j,C)] = table[(k,j,C)]\n # neglecting B\n back[(i,j,C)] = (k, None, C)\n\n p_store[(i, j)].add(C)\n\n # can skip back blank and carry through B\n # i.e. sent conatins B \n if k == j - 1 and sent[k] == BLANK_TOKEN:\n if table[(i,j,B)] < table[(i,k,B)]:\n table[(i,j,B)] = table[(i,k,B)]\n # neglecting C\n back[(i,j,B)] = (k, B, None)\n\n p_store[(i, j)].add(B)\n\n\n # include all possible blanks\n # standard CKY recursive step for B,C we're looping on\n for prod in self._r2prod[potential_rhs]:\n A = prod.lhs()\n B = prod.rhs()[0]\n if prod.is_lexical():\n C = None\n else:\n C = prod.rhs()[1]\n\n if table[(i,k,B)] != float(\"-inf\") \\\n and table[(k,j,C)] != float(\"-inf\"):\n\n new_prob = log(prod.prob()) + table[(i, k, B)]\\\n + table[(k, j, C)]\n if (table[(i, j, A)] < new_prob):\n table[(i, j, A)] = new_prob\n back[(i, j, A)] = (k, B, C)\n\n # add viable A to set in cell\n p_store[(i, j)].add(A)\n\n tree = InvertedGrammar.build_tree(back, sent)\n return tree, table[(0, len(sent), Nonterminal(\"S\"))]\n\n \n @staticmethod\n def build_tree(cky_table, sent):\n \"\"\" Follows the backpointers through the table to determine syntax tree\n starting from the largest span (0, len(sent)) and using recursive\n helper function.\n \"\"\"\n # start recursion at top level\n start = cky_table[0, len(sent), Nonterminal(\"S\")]\n if start == ():\n return None\n else:\n return InvertedGrammar.build_tree_rec(cky_table, 0, len(sent), \\\n Nonterminal(\"S\"), sent)\n\n @staticmethod\n def build_tree_rec(cky_table, i, j, A, sent):\n \"\"\" Builds a tree by following the back-pointers recursing from larger \n spans (i, j) to smaller sub-spans (i, k), (k, j) and eventually \n bottoming out at the preterminal level (i, i+1).\n\n May come across some backtrace that are missing a constituent.\n That means it was skipped in the parse and we continue with the\n backtrace with a smaller span\n \"\"\"\n if j == i + 1:\n return Tree(str(A), [sent[i].encode('ascii', 'ignore')])\n\n (k, B, C) = cky_table[(i, j, A)]\n # skipped a blank\n if not B:\n return InvertedGrammar.build_tree_rec(cky_table, k, j, C, sent)\n # skipped a blank\n if not C:\n return InvertedGrammar.build_tree_rec(cky_table, i, k, B, sent)\n\n return Tree(str(A), \\\n [InvertedGrammar.build_tree_rec(cky_table, i, k, B, sent),\\\n InvertedGrammar.build_tree_rec(cky_table, k, j, C, sent)])\n\n \n","sub_path":"cyk_parser.py","file_name":"cyk_parser.py","file_ext":"py","file_size_in_byte":9595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"365364444","text":"from setuptools import setup\nfrom os.path import join as pjoin, dirname as pdirname\n\ndef read(fname):\n\treturn(open(pjoin(pdirname(__file__), fname)).read())\n\nshort_description = '''\nA packagable WebScraper based on Scrapy.\n'''\n\nsetup(\n\tname = 'WebScraper',\n\tversion = '000.000.003',\n\tauthor = 'Bjoern Vogel',\n\tauthor_email = 'b.vogel94@googlemail.com',\n\turl ='https://github.com/Buern/WebScraper',\n\n\tdescription = short_description,\n\tlong_description = read('README'),\n\n\tpackages = ['WebScraper'],\n\tinstall_requires = [\n\t\t'scrapy',\n\t\t'twisted',\n\t],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"164825172","text":"from django.shortcuts import render\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom ap_model.agencies.serializers import *\nfrom django.http import Http404, HttpResponse\n\n\n# Create your views here.\nclass AgentProfileDisplay(APIView):\n \"\"\"\n Retrieve Agent Profile data\n \"\"\"\n def get_object(self, user):\n \"\"\"Get Agent Profile data from database\"\"\"\n try:\n return AgentProfile.objects.get(user=user)\n except AgentProfile.DoesNotExist:\n raise Http404\n\n def post(self, request, format=None):\n \"\"\"Retrieve Agent Profile data\"\"\"\n try:\n\n try:\n if 'agent' in request.data:\n agent = request.data['agent']\n user = User.objects.get(username=agent)\n else:\n user = request.user\n except Exception as e:\n raise Http404\n\n agent = self.get_object(user)\n agent_user = agent.user\n agent_serializer = AgentSerializer(agent)\n user_serializer = UserSerializer(agent_user)\n get_response = {\"agent_profile\": agent_serializer.data, \"user\": user_serializer.data}\n request_status = \"OK\"\n http_status = status.HTTP_200_OK\n except Exception as e:\n get_response = None\n request_status = str(e)\n http_status = status.HTTP_500_INTERNAL_SERVER_ERROR\n responses = {\"status\": request_status, \"content\": get_response}\n return Response(responses, status=http_status)\n\n\nclass BranchList(APIView):\n def get(self, request, format=None):\n try:\n branchs = Branch.objects.all().order_by('name')\n serializer = BranchSerializer(branchs, many=True)\n\n return Response({\"status\": \"OK\",\"content\": serializer.data }, status=status.HTTP_200_OK)\n\n except Exception as e:\n return Response({\"status\": \"NOT OK\", \"error\": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)","sub_path":"ap_model/agencies/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"252245052","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport re\nimport cgi\nimport datetime\nfrom django.http import HttpResponse\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render_to_response\nfrom google.appengine.ext import db\nfrom google.appengine.api import users\nimport flowBase\nfrom common import paging\nfrom db.ddl import VolunteerProfile, VolunteerIm, NpoProfile\n\ndisplayCount = 10\ndisplayNpoEventCount = 3\ndiffDaysLimit = 14\n\ndicStatusName = {\n \"new registration\": u'新註冊',\n \"approving\": u'審核中',\n \"approval failed\": u'審核不通過',\n \"approved\": u'審核通過',\n \"involving\": u'參與中',\n \"partial involve\": u'部分參與',\n \"closed\": u'活動已完成',\n \"cancelled\": u'活動取消',\n \"abusive usage\": u'遭檢舉不當活動',\n }\n\ndef redirect(request):\n return show(request, '')\n\ndef show(request, status, displayPhotoCount=8, displayBlogCount=6):\n user = flowBase.verifyVolunteer(request)\n if not user:\n return HttpResponseRedirect('/')\n\n if status == \"history\":\n events = db.GqlQuery('SELECT * FROM VolunteerEvent where volunteer_profile_ref = :1 and status = :2', user, \"closed\").fetch(1000)\n else:\n events = db.GqlQuery('SELECT * FROM VolunteerEvent where volunteer_profile_ref = :1 and status != :2', user, \"closed\").fetch(1000)\n eventCount = len(events)\n pageSet = paging.get(request.GET, eventCount, displayCount=displayCount)\n\n eventList = []\n for event in events:\n eventList.append(\n {'event_id':event.event_id,\n 'event_name':event.event_profile_ref.event_name,\n 'originator':event.event_profile_ref.npo_profile_ref.npo_name,\n 'create_time':event.event_profile_ref.create_time.strftime('%Y-%m-%d %H:%M'),\n 'start_time':event.event_profile_ref.start_time.strftime('%Y-%m-%d %H:%M'),\n 'event_region':u','.join(event.event_profile_ref.event_region),\n 'description':event.event_profile_ref.description,\n 'registered_count':event.event_profile_ref.registered_count,\n 'approved_count':event.event_profile_ref.approved_count,\n 'volunteer_shortage':event.event_profile_ref.volunteer_shortage,\n 'event_key':str(event.event_profile_ref.key()),\n 'event_status':dicStatusName[event.status],\n }\n )\n\n '''\n now = datetime.datetime.now()\n npoCount = len(user.npo_profile_ref)\n pageSet = paging.get(request.GET, npoCount, displayCount=displayCount)\n npoList = [NpoProfile.get(user.npo_profile_ref[i]) for i in range(displayCount) if i < npoCount]\n for npo in npoList:\n npo.eventList = npo.event2npo.fetch(displayNpoEventCount)\n for event in npo.eventList:\n event.diffDays = (event.start_time - now).days\n event.upcoming = True if event.diffDays >= 0 and event.diffDays <= diffDaysLimit else False\n \n npo.memberCount = len(npo.members)\n npo.region = u', '.join(npo.service_region)\n npo.region = npo.region if len(npo.region) < 15 else npo.region[0:15] + u'...'\n if npo.brief_intro:\n npo.brief_intro = npo.brief_intro if len(npo.brief_intro) < 15 else npo.brief_intro[0:15] + u'...'\n '''\n \n # page: home, added by tom_chen... nasty workaround\n base = flowBase.getBase(request, 'volunteer')\n template_values = {\n 'isSelf': True if base['user'] == user.volunteer_id else False,\n 'base': base,\n 'volunteerBase': flowBase.getVolunteerBase(user),\n 'page': 'event',\n 'eventList': eventList,\n 'pageSet': pageSet,\n }\n\n if status == \"history\":\n response = render_to_response('volunteer/joined_event_history.html', template_values)\n else:\n response = render_to_response('volunteer/joined_event.html', template_values)\n\n return response\n\n","sub_path":"flow1.0/src/flow-site/volunteerView/joinedEvent.py","file_name":"joinedEvent.py","file_ext":"py","file_size_in_byte":4018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"396198005","text":"# -*- coding:utf-8 -*-\nimport operator\nfrom django.conf import settings\nfrom django.core.management.base import NoArgsCommand\nfrom django.template.loader import render_to_string\nfrom tuangou.guider.models import ReDeal, City\nfrom tuangou.stats.models import DealView\nfrom itertools import groupby\nfrom solid_utils import gen_dest_tmpl\nfrom datetime import datetime, date, time, timedelta\n\ndef get_city():\n for city in City.actives.all():\n yield city\n\ndef gen_view_chart(tmpl, city):\n today = datetime.combine(date.today(), time(0, 0, 0))\n lastday = today - timedelta(days=1) \n views = DealView.objects.values_list('pk', 'deal_id').filter(deal__end_date__gte=today, date__gte=lastday, city=city)\n key = operator.itemgetter(1)\n s_views = sorted(views, key=key)\n g_views = groupby(s_views, key=key)\n deals = sorted([(k, len(list(group))) for k, group in g_views], key=key, reverse=True)\n length = len(deals)\n if length < settings.VIEW_CHART:\n deals = deals\n else:\n deals = deals[:settings.VIEW_CHART]\n pre_deals = [deal_id for deal_id, pk in deals]\n object_list = [] \n for pk in pre_deals:\n object_list.append(ReDeal.objects.values_list('pk', 'title').get(pk=pk))\n if city.slug:\n label = '点击排行榜'\n dest_tmpl =\"dy_tags/view/%s_view_chart.html\" % city.slug\n html = render_to_string(tmpl, locals()).encode(settings.DEFAULT_CHARSET)\n gen_dest_tmpl(html, dest_tmpl)\n\ndef solid_chart(tmpl=\"dy_tags/chart.html\"):\n for city in get_city():\n gen_view_chart(tmpl, city)\n\nclass Command(NoArgsCommand):\n def handle_noargs(self, **options):\n solid_chart()\n","sub_path":"solid/management/commands/solid_view_chart.py","file_name":"solid_view_chart.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"512184121","text":"def test_get_all_planets_with_no_records(client):\n response = client.get(\"/planets\")\n response_body = response.get_json()\n\n assert response.status_code == 200\n assert response_body == []\n\n\ndef test_get_all_planets_with_records(client, three_saved_planets):\n response = client.get(\"/planets\")\n response_body = response.get_json()\n\n assert response.status_code == 200\n assert response_body == [{\n \"name\": \"Earth\",\n \"description\": \"nice big rock\",\n \"id\": 1\n },{\n \n \"name\": \"Pluto\",\n \"description\": \"am I a planet tho?\",\n \"id\": 2\n },{\n \n \"name\": \"Mars\",\n \"description\": \"I have robots on me\",\n \"id\": 3\n }]\n\n\ndef test_post_new_planet(client):\n response = client.post(\"/planets\", json={\"name\":\"Mercury\", \"description\":\"its color is boring gray\"})\n \n assert response.status_code == 201\n assert response.get_data().decode(\"utf-8\") == \"Planet Mercury successfully created\" \n\ndef test_get_one_planet_planet_is_there(client, three_saved_planets):\n response = client.get(\"/planets/1\")\n response_body = response.get_json()\n\n assert response.status_code == 200\n assert response_body == {\n \"name\": \"Earth\",\n \"description\": \"nice big rock\",\n \"id\": 1\n }\n\n\ndef test_get_one_planet_with_no_records(client):\n response = client.get(\"/planets/1\")\n\n assert response.status_code == 404\n assert response.get_data().decode(\"utf-8\") == \"Planet outside of the bounds of the universe :(\"\n","sub_path":"tests/test_routes.py","file_name":"test_routes.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"127665952","text":"from django.conf.urls import url \nfrom . import views\n\napp_name = 'diary'\n\nurlpatterns=[\n\n\turl(r'^$', views.index, name='index'),\n\turl(r'^created$', views.CreateDiary, name='CreateDiary'),\n\turl(r'^diary$', views.diary, name='diary'),\n\turl(r'^diary/posted$', views.write_post, name='write_post'),\n\turl(r'^diary/deleted$', views.delete_post, name='delete_post'),\n\turl(r'^diary/edited/(?P[-\\w]+)/(?P\\w+)/$', views.edit_post, name='edit_post'),\n\turl(r'^diary/saved$', views.save_edit_post, name='save_edit_post'),\n\turl(r'^diary/new_page$', views.diary_page, name='diary_page'),\n\turl(r'^diary/page$', views.diary_nextpage, name='diary_nextpage'),\n\turl(r'^diary/page$', views.diary_previouspage, name='diary_previouspage'),\n\t\n]","sub_path":"diary/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"560736771","text":"\"\"\"\nCopyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\nSPDX-License-Identifier: Apache-2.0\n\"\"\"\n\nimport datetime\nimport hashlib\nimport hmac\nimport json\nimport logging\nimport urllib\n\nlogging.basicConfig()\nlogger = logging.getLogger(\"graph_magic\")\n\n\n# Key derivation functions. See:\n# https://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python\ndef sign(key, msg):\n return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()\n\n\ndef get_signature_key(key, dateStamp, regionName, serviceName):\n k_date = sign(('AWS4' + key).encode('utf-8'), dateStamp)\n k_region = sign(k_date, regionName)\n k_service = sign(k_region, serviceName)\n k_signing = sign(k_service, 'aws4_request')\n return k_signing\n\n\ndef get_canonical_uri_and_payload(query_type, query):\n # Set the stack and payload depending on query_type.\n if query_type == 'sparql':\n canonical_uri = '/sparql/'\n payload = query\n\n elif query_type == 'sparqlupdate':\n canonical_uri = '/sparql/'\n payload = query\n\n elif query_type == 'sparql/status':\n canonical_uri = '/sparql/status/'\n payload = query\n\n elif query_type == 'gremlin':\n canonical_uri = '/gremlin'\n payload = {}\n\n elif query_type == 'gremlin/status':\n canonical_uri = '/gremlin/status/'\n payload = query\n\n elif query_type == \"loader\":\n canonical_uri = \"/loader/\"\n payload = query\n\n elif query_type == \"status\":\n canonical_uri = \"/status/\"\n payload = {}\n\n elif query_type == \"gremlin/explain\":\n canonical_uri = \"/gremlin/explain/\"\n payload = query\n\n elif query_type == \"gremlin/profile\":\n canonical_uri = \"/gremlin/profile/\"\n payload = query\n\n elif query_type == \"system\":\n canonical_uri = \"/system/\"\n payload = query\n\n elif query_type.startswith(\"ml\"):\n canonical_uri = f'/{query_type}'\n payload = query\n\n elif query_type.startswith(\"ml/dataprocessing\"):\n canonical_uri = f'/{query_type}'\n payload = query\n\n elif query_type.startswith(\"ml/endpoints\"):\n canonical_uri = f'/{query_type}'\n payload = query\n\n else:\n raise ValueError('query_type %s is not valid' % query_type)\n\n return canonical_uri, payload\n\n\ndef normalize_query_string(query):\n kv = (list(map(str.strip, s.split(\"=\")))\n for s in query.split('&')\n if len(s) > 0)\n\n normalized = '&'.join('%s=%s' % (p[0], p[1] if len(p) > 1 else '')\n for p in sorted(kv))\n return normalized\n\n\ndef make_signed_request(method, query_type, query, host, port, signing_access_key, signing_secret, signing_region,\n use_ssl=False, signing_token='', additional_headers=None):\n if additional_headers is None:\n additional_headers = []\n\n signing_region = signing_region.lower()\n service = 'neptune-db'\n\n if use_ssl:\n protocol = 'https'\n else:\n protocol = 'http'\n\n # this is always http right now\n endpoint = f'{protocol}://{host}:{port}'\n\n # get canonical_uri and payload\n canonical_uri, payload = get_canonical_uri_and_payload(query_type, query)\n\n if 'content-type' in additional_headers and additional_headers['content-type'] == 'application/json':\n request_parameters = payload if type(payload) is str else json.dumps(payload)\n else:\n request_parameters = urllib.parse.urlencode(payload, quote_via=urllib.parse.quote)\n request_parameters = request_parameters.replace('%27', '%22')\n t = datetime.datetime.utcnow()\n amz_date = t.strftime('%Y%m%dT%H%M%SZ')\n date_stamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope\n\n method = method.upper()\n if method == 'GET' or method == 'DELETE':\n canonical_querystring = normalize_query_string(request_parameters)\n elif method == 'POST':\n canonical_querystring = ''\n else:\n raise ValueError('method %s is not valid when creating canonical request' % method)\n\n # Step 4: Create the canonical headers and signed headers. Header names\n # must be trimmed and lowercase, and sorted in code point order from\n # low to high. Note that there is a trailing \\n.\n canonical_headers = f'host:{host}:{port}\\nx-amz-date:{amz_date}\\n'\n\n # Step 5: Create the list of signed headers. This lists the headers\n # in the canonical_headers list, delimited with \";\" and in alpha order.\n # Note: The request can include any headers; canonical_headers and\n # signed_headers lists those that you want to be included in the\n # hash of the request. \"Host\" and \"x-amz-date\" are always required.\n signed_headers = 'host;x-amz-date'\n\n # Step 6: Create payload hash (hash of the request body content). For GET and DELETE\n # requests, the payload is an empty string (\"\").\n if method == 'GET' or method == 'DELETE':\n post_payload = ''\n elif method == 'POST':\n post_payload = request_parameters\n else:\n raise ValueError('method %s is not supported' % method)\n\n payload_hash = hashlib.sha256(post_payload.encode('utf-8')).hexdigest()\n\n # Step 7: Combine elements to create canonical request.\n canonical_request = method + '\\n' + canonical_uri + '\\n' + canonical_querystring + '\\n' + canonical_headers + '\\n' + signed_headers + '\\n' + payload_hash\n\n # ************* TASK 2: CREATE THE STRING TO SIGN*************\n # Match the algorithm to the hashing algorithm you use, either SHA-1 or\n # SHA-256 (recommended)\n algorithm = 'AWS4-HMAC-SHA256'\n credential_scope = date_stamp + '/' + signing_region + '/' + service + '/' + 'aws4_request'\n string_to_sign = algorithm + '\\n' + amz_date + '\\n' + credential_scope + '\\n' + hashlib.sha256(\n canonical_request.encode('utf-8')).hexdigest()\n\n # ************* TASK 3: CALCULATE THE SIGNATURE *************\n # Create the signing key using the function defined above.\n signing_key = get_signature_key(signing_secret, date_stamp, signing_region, service)\n\n # Sign the string_to_sign using the signing_key\n signature = hmac.new(signing_key, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest()\n\n # ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************\n # The signing information can be either in a query string value or in\n # a header named Authorization. This code shows how to use a header.\n # Create authorization header and add to request headers\n authorization_header = algorithm + ' ' + 'Credential=' + signing_access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature\n\n # The request can include any headers, but MUST include \"host\", \"x-amz-date\",\n # and (for this scenario) \"Authorization\". \"host\" and \"x-amz-date\" must\n # be included in the canonical_headers and signed_headers, as noted\n # earlier. Order here is not significant.\n # Python note: The 'host' header is added automatically by the Python 'requests' library.\n if method == 'GET' or method == 'DELETE':\n headers = {\n 'x-amz-date': amz_date,\n 'Authorization': authorization_header\n }\n elif method == 'POST':\n headers = {\n 'content-type': 'application/x-www-form-urlencoded',\n 'x-amz-date': amz_date,\n 'Authorization': authorization_header,\n }\n else:\n raise ValueError('method %s is not valid while creating request headers' % method)\n\n if additional_headers is not None:\n for key in additional_headers:\n headers[key] = additional_headers[key]\n\n if signing_token != '':\n headers['X-Amz-Security-Token'] = signing_token\n\n # ************* SEND THE REQUEST *************\n request_url = endpoint + canonical_uri\n\n return {\n 'url': request_url,\n 'headers': headers,\n 'params': request_parameters\n }","sub_path":"src/graph_notebook/authentication/iam_headers.py","file_name":"iam_headers.py","file_ext":"py","file_size_in_byte":7960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"112397219","text":"\"\"\"\nA simple example that shows that adding a uniform noise after the FGSM attack\ncan restore the correct label. The labels are given as numbers from 0 to 999.\nWe use ResNet-18 on 20 ImageNet samples from foolbox.\n\nInstall PyTorch 1.1: https://pytorch.org/\n\nInstall foolbox 1.9 (this version is necessary):\ngit clone https://github.com/bethgelab/foolbox.git\ncd foolbox\ngit reset --hard 5191c3a595baadedf0a3659d88b48200024cd534\npip install --editable .\n\"\"\"\nimport matplotlib\n\nprint(matplotlib.get_backend())\n# matplotlib.use('TkAgg')\nmatplotlib.rcParams['pdf.fonttype'] = 42\nmatplotlib.rcParams['ps.fonttype'] = 42\nimport matplotlib.pyplot as plt\nimport torch\nimport torchvision.models as models\nimport numpy as np\nimport foolbox\nfrom cnns.nnlib.robustness.utils import get_foolbox_model\n# %pylab inline\nfrom cnns.nnlib.robustness.utils import show_image\nfrom cnns.nnlib.robustness.channels.histogram_matplotlib import \\\n plot_hist\nfrom cnns.nnlib.robustness.channels.channels_definition import \\\n uniform_noise_numpy as unif\nfrom cnns.nnlib.robustness.channels.channels_definition import \\\n gauss_noise_numpy as gauss\nfrom cnns.nnlib.robustness.channels.channels_definition import \\\n laplace_noise_numpy as laplace\nfrom cnns.nnlib.robustness.channels.channels_definition import \\\n logistic_noise_numpy as logistic\nfrom cnns.nnlib.robustness.channels.channels_definition import \\\n round_numpy as round\nfrom cnns.nnlib.robustness.channels.channels_definition import \\\n fft_numpy as fft\nfrom cnns.nnlib.robustness.channels.channels_definition import \\\n compress_svd_numpy_through_torch as svd\nfrom cnns.nnlib.robustness.channels.channels_definition import \\\n subtract_rgb_numpy as sub\nfrom cnns.nnlib.utils.general_utils import get_log_time\nfrom cnns.nnlib.utils.exec_args import get_args\n\nfrom cnns.nnlib.datasets.cifar import cifar_mean_array\nfrom cnns.nnlib.datasets.cifar import cifar_std_array\nfrom cnns.nnlib.datasets.cifar import cifar_min\nfrom cnns.nnlib.datasets.cifar import cifar_max\n\n# plt.interactive(True)\n# http://ksrowell.com/blog-visualizing-data/2012/02/02/optimal-colors-for-graphs/\nMY_BLUE = (56, 106, 177)\nMY_RED = (204, 37, 41)\nMY_ORANGE = (218, 124, 48)\nMY_GREEN = (62, 150, 81)\nMY_BLACK = (83, 81, 84)\nMY_GOLD = (148, 139, 61)\n\n\ndef get_color(COLOR_TUPLE_255):\n return [x / 255 for x in COLOR_TUPLE_255]\n\n\ncolors = [get_color(color) for color in\n [MY_GREEN, MY_BLUE, MY_ORANGE, MY_RED, MY_BLACK, MY_GOLD]]\nmarkers = [\"+\", \"o\", \"v\", \"s\", \"D\", \"^\", \"+\"]\nlinestyles = [\":\", \"-\", \"--\", \":\", \"-\", \"--\", \":\", \"-\"]\n\n\n# Settings for the PyTorch model.\nimagenet_mean = [0.485, 0.456, 0.406]\nimagenet_std = [0.229, 0.224, 0.225]\n\nimagenet_mean_array = np.array(imagenet_mean, dtype=np.float32).reshape(\n (3, 1, 1))\nimagenet_std_array = np.array(imagenet_std, dtype=np.float32).reshape(\n (3, 1, 1))\n\n# The min/max value per pixel after normalization.\nimagenet_min = np.float32(-2.1179039478302)\nimagenet_max = np.float32(2.640000104904175)\n\n\ndevice = torch.device(\"cpu\")\nif torch.cuda.is_available():\n device = torch.device(\"cuda\")\n\n\noriginal_count = 0\nadversarial_count = 0\ndefended_count = 0\nrecover_count = 20\n\n# Instantiate the model.\ndataset = 'imagenet'\n\nargs = get_args()\n\nif dataset == 'imagenet':\n resnet = models.resnet50(pretrained=True)\n resnet.to(device)\n resnet.eval()\n\n model = foolbox.models.PyTorchModel(resnet, bounds=(0, 1), num_classes=1000,\n preprocessing=(imagenet_mean_array,\n imagenet_std_array))\n images, labels = foolbox.utils.samples(\"imagenet\",\n data_format=\"channels_first\",\n batchsize=recover_count)\nelif dataset == 'cifar10':\n model_path = 'saved_model_2019-05-16-11-37-45-415722-dataset-cifar10-preserve-energy-100.0-compress-rate-0.0-test-accuracy-93.56-channel-vals-0.model'\n model = get_foolbox_model(args, model_path=model_path,\n compress_rate=0,\n min=cifar_min, max=cifar_max)\n\nimages = images / 255 # map from [0,255] to [0,1] range\n\nfontsize = 25\nlegend_size = 25\ntitle_size = 25\nfont = {'size': fontsize}\nimport matplotlib\n\nmatplotlib.rc('font', **font)\n\nwidth = 50\nheight = 100\nfig = plt.figure(figsize=(width, height))\n\n\n# Attack the image.\nclass EmptyAttack(foolbox.attacks.Attack):\n\n def __call__(self, input_or_adv, label=None, unpack=True, **kwargs):\n return input_or_adv\n\n\nfgsm_attack = foolbox.attacks.FGSM(model)\nbl1_attack = foolbox.attacks.L1BasicIterativeAttack(model)\ncw_attack = foolbox.attacks.CarliniWagnerL2Attack(model)\npgd_attack = foolbox.attacks.RandomStartProjectedGradientDescentAttack(model)\nempty_attack = EmptyAttack()\n\nrepeats = 100\nnoise_func = gauss\n# noise_strengths = [0.0, 0.003, 0.1]\nnoise_strengths = [0.0, 0.001, 0.007, 0.009, 0.02, 0.04, 0.05, 0.08]\n# noise_strengths = [0.0, 0.001, 0.007, 0.009, 0.01, 0.02, 0.03, 0.04, 0.05, 0.08,\n# 0.09]\n# noise_strengths = [0.0, 0.001, 0.007, 0.009, 0.01, 0.02, 0.03, 0.04, 0.05, 0.08,\n# 0.09, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5]\n# noise_strengths = []\n\n\n# show_image(image)\n\n\n# attacks = [fgsm_attack, bl1_attack]\n# attacks = [cw_attack]\nattacks = [fgsm_attack]\nncols = 1\nnrows = max(1, len(attacks) // 2)\nlw = 4\nncols_legend = 1\nwidth = 15\nheight = 7\nfig = plt.figure(figsize=(width * ncols, height * nrows))\n\ncolors = [get_color(color) for color in\n [MY_GREEN, MY_BLUE, MY_ORANGE, MY_RED, MY_BLACK, MY_RED, MY_GREEN]]\nmarkers = [\"+\", \"o\", \"v\", \"s\", \"D\", \"^\", \"+\"]\nlinestyles = [\"-\", \"-\", \"--\", \":\", \":\", '--', '--']\nmarkers = ['o', 'v', 's']\n\nplt.subplot(nrows, ncols, 1)\n\nimages, labels = images[:1], labels[:1]\n\nfor attack_iter, attack in enumerate(attacks):\n for image_idx, (image, label) in enumerate(zip(images, labels)):\n # Original prediction of the model (without any adversarial changes\n # or noise).\n original_predictions = model.predictions(image)\n original_prediction = np.argmax(original_predictions)\n print(\"original prediction: \", original_prediction)\n if original_prediction == label:\n original_count += 1\n\n if attack.name() == 'CarliniWagnerL2Attack':\n adversarial_image = attack(image, label, max_iterations=100)\n else:\n adversarial_image = attack(image, label)\n\n print('adversarial image min, max:', adversarial_image.min(),\n adversarial_image.max())\n\n adversarial_predictions = model.predictions(adversarial_image)\n adversarial_prediciton = np.argmax(adversarial_predictions)\n print(\"adversarial prediction: \", adversarial_prediciton)\n if adversarial_prediciton == label:\n adversarial_count += 1\n\n distances = []\n org_class_counts = []\n adv_class_counts = []\n other_class_counts = []\n\n for noise_strength in noise_strengths:\n local_distances = []\n org_class_count = 0\n adv_class_count = 0\n other_class_count = 0\n\n for repeat in range(repeats):\n noised_image = noise_func(adversarial_image, noise_strength)\n noised_image = noised_image.astype(np.float32)\n\n noise_predictions = model.predictions(noised_image)\n noise_prediction = np.argmax(noise_predictions)\n if noise_prediction == original_prediction:\n org_class_count += 1\n elif noise_prediction == adversarial_prediciton:\n adv_class_count += 1\n else:\n other_class_count += 1\n\n deltas = noised_image - image\n l2_dist = np.sqrt(np.sum(deltas * deltas))\n local_distances.append(l2_dist)\n\n distances.append(np.mean(local_distances))\n org_class_counts.append(org_class_count)\n adv_class_counts.append(adv_class_count)\n other_class_counts.append(other_class_count)\n\n values = [org_class_counts, adv_class_counts, other_class_counts]\n values_names = ['original class', 'adversarial class', 'other class']\n print('distances: ', distances)\n for i in range(len(values)):\n if attack.name() == 'EmptyAttack' and i == 1:\n continue\n\n plt.plot(distances, values[i],\n label=values_names[i], marker=markers[i],\n markersize=15,\n lw=lw, color=colors[i], linestyle=linestyles[i])\n\n plt.grid()\n plt.legend(loc='center right', ncol=ncols_legend, frameon=False,\n prop={'size': legend_size},\n # bbox_to_anchor=dataset[bbox]\n )\n\n plt.xlabel('L2 distance')\n plt.ylabel('Frequency count')\n plt.title(attack.name(), fontsize=title_size)\n\nplt.subplots_adjust(hspace=0.5)\nplt.subplots_adjust(wspace=0.2)\nplt.savefig(\n 'images/' + get_log_time() + '_channel_robustness_histograms_many_images.pdf',\n bbox_inches='tight')\nplt.show()\nplt.close()\n\nprint(f\"\\nBase test accuracy of the model: \"\n f\"{original_count / recover_count}\")\nprint(f\"\\nAccuracy of the model after attack: \"\n f\"{adversarial_count / recover_count}\")\nprint(f\"\\nAccuracy of the model after noising: \"\n f\"{defended_count / recover_count}\")\n","sub_path":"cnns/nnlib/robustness/channels/channels_robustness_histograms_many_images.py","file_name":"channels_robustness_histograms_many_images.py","file_ext":"py","file_size_in_byte":9441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"461557645","text":"'''Jogo da Velha. O tabuleiro do jogo é representado por uma matriz\r\n3x3, contendo 3 tipos de caracteres: 'X', 'O' e '-'. O primeiro está associado\r\nao Jogador 1, o segundo ao Jogador 2 e o último trata-se de um espaço do\r\ntabuleiro ainda não preenchido. O objetivo do jogo é preencher em sequência 3\r\npeças em uma linha, coluna ou diagonal. O jogador que conseguir realizar este\r\nfeito primeiro, vence o jogo. Há a possibilidade de o tabuleiro\r\nser todo preenchido e nenhum dos jogadores conseguir atingir este objetivo,\r\ncaracterizando um empate.'''\r\n\r\n#Document properties\r\n__author__ = \"[Lucas Aquino]\"\r\n__copyright__ = \"Copyright 2021\"\r\n__credits__ = \"__author__\"\r\n__license__ = \"GPL\"\r\n__version__ = \"1.0.0\"\r\n__maintainer__ = \"Lucas Aquino\" # Reponsável por manter o\r\n # programa funcionando\r\n__email__ = \"lucasaquinotz@poli.ufrj.br\"\r\n__status__ = \"Production\"\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\nclass Comunicacao:\r\n def __init__(self: object, jogo: list = [['-','-','-'],['-','-','-',],['-','-','-']], jogadas: int = 0, vitoria: bool = False) -> None:\r\n '''Método construtor'''\r\n self. jogo = jogo\r\n self.jogadas = jogadas\r\n self.vitoria = vitoria\r\n\r\n return None\r\n \r\n def leituraPosicao1(self: object) -> None:\r\n '''Troca o - pelo X dada as coordenadas'''\r\n pos1 = list(input('\\n''Jogador 1 - escolha uma posição [x,y]:\\n'))\r\n while True:\r\n try:\r\n if len(pos1) > 5:\r\n raise ValueError\r\n elif pos1[0] != '[' or pos1[1] not in '012' or pos1[2] != ',' or pos1[3] not in '012' or pos1[4] != ']':\r\n raise ValueError\r\n elif self.jogo[int(pos1[1])][int(pos1[3])] == 'X' or self.jogo[int(pos1[1])][int(pos1[3])] == 'O':\r\n raise IndexError\r\n del self.jogo[int(pos1[1])][int(pos1[3])]\r\n except IndexError:\r\n log = open('log.txt', 'a+')\r\n log.write(str.format('IndexError: Jogador 1 (X) tentou preencher uma posição que já possui uma peça: \"{}\"\\n', ''.join(pos1)))\r\n log.close()\r\n pos1 = list(input('\\n''Posição inválida. Jogador 1 - escolha uma posição [x,y]:\\n'))\r\n except ValueError:\r\n log = open('log.txt', 'a+')\r\n log.write(str.format('ValueError: Jogador 1 (X) tentou preencher uma posição com um formato diferente de [x,y] sendo x e y de 0 a 2: \"{}\"\\n', ''.join(pos1)))\r\n log.close()\r\n pos1 = list(input('\\n''Jogador 1 - escolha uma posição no formato [x,y] com x e y de 0 a 2:\\n'))\r\n else:\r\n list.insert(self.jogo[int(pos1[1])],int(pos1[3]),'X')\r\n historico = open('historico.txt', 'a+')\r\n historico.write(str.format('Jogador 1 (X) preencheu a posição: {}\\n',''.join(pos1)))\r\n historico.close()\r\n break\r\n \r\n return None\r\n\r\n def leituraPosicao2(self: object) -> None:\r\n pos2 = list(input('\\n''Jogador 2 - escolha uma posição [x,y]:\\n'))\r\n while True:\r\n try:\r\n if len(pos2) > 5:\r\n raise ValueError\r\n elif pos2[0] != '[' or pos2[1] not in '012' or pos2[2] != ',' or pos2[3] not in '012' or pos2[4] != ']':\r\n raise ValueError\r\n elif self.jogo[int(pos2[1])][int(pos2[3])] == 'X' or self.jogo[int(pos2[1])][int(pos2[3])] == 'O':\r\n raise IndexError\r\n del self.jogo[int(pos2[1])][int(pos2[3])]\r\n except IndexError:\r\n log = open('log.txt', 'a+')\r\n log.write(str.format('IndexError: Jogador 2 (O) tentou preencher uma posição que já possui uma peça: \"{}\"\\n', ''.join(pos2)))\r\n log.close()\r\n pos2 = list(input('\\n''Posição inválida. Jogador 2 - escolha uma posição [x,y]:\\n'))\r\n except ValueError:\r\n log = open('log.txt', 'a+')\r\n log.write(str.format('ValueError: Jogador 2 (O) tentou preencher uma posição com um formato diferente de [x,y] sendo x e y de 0 a 2: \"{}\"\\n', ''.join(pos2)))\r\n log.close()\r\n pos2 = list(input('\\n''Jogador 2 - escolha uma posição no formato [x,y] com x e y de 0 a 2:\\n'))\r\n else:\r\n list.insert(self.jogo[int(pos2[1])],int(pos2[3]),'O')\r\n historico = open('historico.txt', 'a+')\r\n historico.write(str.format('Jogador 2 (O) preencheu a posição: {}\\n',''.join(pos2)))\r\n historico.close()\r\n break\r\n\r\n return None\r\n \r\n def resultado(self: object) -> None:\r\n '''Verifica no caso de um vencedor quem ganhou e verifica se querem jogar novamente'''\r\n if self.vitoria == True and self.jogadas%2 == 1:\r\n '''Verifica se o foi o jogador 1 (X) o ganhador'''\r\n historico = open('historico.txt', 'a+')\r\n historico.write('Jogador 1 (X) ganhou\\n')\r\n historico.close()\r\n jogar = input('\\n''Jogador 1 venceu o jogo. Deseja iniciar uma nova partida?''\\n') \r\n while True:\r\n try:\r\n if jogar != 'S' and jogar != 'N':\r\n raise TypeError\r\n except TypeError:\r\n log = open('log.txt', 'a+')\r\n log.write(str.format('TypeError: Usuário digitou um caractere inválido: \"{}\"\\n', jogar))\r\n log.close()\r\n jogar = input('\\n''Comando inválido. Deseja iniciar uma nova partida? (S ou N)''\\n')\r\n else:\r\n if jogar == 'S':\r\n historico = open('historico.txt', 'a+')\r\n historico.write('Usuário digitou \"S\" e um novo jogo foi iniciado\\n')\r\n historico.close()\r\n JogoDaVelha.main()\r\n elif jogar == 'N':\r\n historico = open('historico.txt', 'a+')\r\n historico.write('Usuário digitou \"N\" e o programa foi encerrado\\n')\r\n historico.close()\r\n return None\r\n break\r\n elif self.vitoria == True and self.jogadas%2 == 0:\r\n '''Verifica se foi o jogador 2 (O) o ganhador'''\r\n historico = open('historico.txt', 'a+')\r\n historico.write('Jogador 2 (O) ganhou\\n')\r\n historico.close()\r\n jogar = input('\\n''Jogador 2 venceu o jogo. Deseja iniciar uma nova partida?''\\n')\r\n while True:\r\n try:\r\n if jogar != 'S' and jogar != 'N':\r\n raise TypeError\r\n except TypeError:\r\n log = open('log.txt', 'a+')\r\n log.write(str.format('TypeError: Usuário digitou um caractere inválido: \"{}\"\\n', jogar))\r\n log.close()\r\n jogar = input('\\n''Comando inválido. Deseja iniciar uma nova partida? (S ou N)''\\n')\r\n else:\r\n if jogar == 'S':\r\n historico = open('historico.txt', 'a+')\r\n historico.write('Usuário digitou \"S\" e um novo jogo foi iniciado\\n')\r\n historico.close()\r\n JogoDaVelha.main()\r\n elif jogar == 'N':\r\n historico = open('historico.txt', 'a+')\r\n historico.write('Usuário digitou \"N\" e o programa foi encerrado\\n')\r\n historico.close()\r\n return None\r\n break\r\n elif self.jogadas == 9:\r\n historico = open('historico.txt', 'a+')\r\n historico.write('O jogo terminou em empate\\n')\r\n historico.close()\r\n jogar = input('\\n''Empate . Deseja iniciar uma nova partida?''\\n')\r\n while True:\r\n try:\r\n if jogar != 'S' and jogar != 'N':\r\n raise TypeError\r\n except TypeError:\r\n log = open('log.txt', 'a+')\r\n log.write(str.format('TypeError: Usuário digitou um caractere inválido: \"{}\"\\n', jogar))\r\n log.close()\r\n jogar = input('\\n''Comando inválido. Deseja iniciar uma nova partida? (S ou N)''\\n')\r\n else:\r\n if jogar == 'S':\r\n historico = open('historico.txt', 'a+')\r\n historico.write('Usuário digitou \"S\" e um novo jogo foi iniciado\\n')\r\n historico.close()\r\n JogoDaVelha.main()\r\n elif jogar == 'N':\r\n historico = open('historico.txt', 'a+')\r\n historico.write('Usuário digitou \"N\" e o programa foi encerrado\\n')\r\n historico.close()\r\n return None\r\n break\r\n \r\nclass Funcionamento:\r\n def __init__(self: object, jogo: list = [['-','-','-'],['-','-','-',],['-','-','-']], jogadas: int = 0, vitoria: bool = False) -> None:\r\n '''Método construtor'''\r\n self. jogo = jogo\r\n self.jogadas = jogadas\r\n self.vitoria = vitoria\r\n\r\n return None\r\n \r\n def interface(self: object) -> None:\r\n '''Imprime a matriz'''\r\n for linha in self.jogo:\r\n print('')\r\n for elemento in linha:\r\n print(str.format('{}',elemento),end=' ')\r\n return None\r\n \r\n def condicaoDeVitoria(self: object) -> bool:\r\n '''Verifica se houve algum vencedor, retornando True pra caso haja e False pra caso contrário'''\r\n figuras = ['X','O']\r\n for f in figuras:\r\n if self.vitoria == False:\r\n '''Verifica a vitória nas linha (3 iguais na horizontal)'''\r\n lin = 0\r\n col = 0\r\n while lin < 3 and self.vitoria == False:\r\n soma = 0\r\n col = 0\r\n while col < 3:\r\n if self.jogo[lin][col] == f:\r\n soma += 1\r\n col += 1\r\n lin += 1\r\n if soma == 3:\r\n self.vitoria = True\r\n '''Verifica a vitória nas colunas (3 iguais na vertical)'''\r\n lin = 0\r\n col = 0\r\n while col < 3 and self.vitoria == False:\r\n soma = 0\r\n lin = 0\r\n while lin < 3:\r\n if self.jogo[lin][col] == f:\r\n soma += 1\r\n lin += 1\r\n col += 1\r\n if soma == 3:\r\n self.vitoria = True\r\n '''Verifica a primeira diagonal'''\r\n soma = 0\r\n lin = 0\r\n col = 2\r\n while lin < 3 and self.vitoria == False:\r\n if self.jogo[lin][col] == f:\r\n soma += 1\r\n lin += 1\r\n col -= 1\r\n if soma == 3:\r\n self.vitoria = True\r\n '''Verifica a segunda diagonal'''\r\n soma = 0\r\n diag = 0\r\n while diag < 3 and self.vitoria == False:\r\n if self.jogo[diag][diag] == f:\r\n soma += 1\r\n diag += 1\r\n if soma == 3:\r\n self.vitoria = True\r\n return self.vitoria\r\n \r\nclass JogoDaVelha(Comunicacao, Funcionamento):\r\n def __init__(self: object, jogo: list = [['-','-','-'],['-','-','-',],['-','-','-']], jogadas: int = 0, vitoria: bool = False) -> None:\r\n '''Método construtor'''\r\n Comunicacao.__init__(self, jogo, jogadas, vitoria)\r\n Funcionamento.__init__(self, jogo, jogadas, vitoria)\r\n self.__atributos = {'jogo','jogadas','vitoria', 'dicionario'}\r\n self.__metodos = {\r\n 'leituraPosicao1', 'leituraPosicao2', 'resultado', 'interface',\r\n 'condicaoDeVitoria', 'getAtributos', 'getMetodos'\r\n }\r\n \r\n return None\r\n\r\n def manualUsuario(self: object) -> dict:\r\n '''Retorna um dicionário contendo todos os métodos e atributos e suas respectivas funcionalidades'''\r\n dicionario = {\r\n 'jogo':'(list) Tabuleiro do jogo',\r\n 'jogadas':'(int) Número de jogadas',\r\n 'vitoria':'(bool) Representa se houve um vencedor. True = Houve vencedor e False = Ainda não houve um vencedor',\r\n 'atributos':'(set) Armazena todos os atributos utilizados pelas classes do programa',\r\n 'metodos':'(set) Armazena todos os métodos utilizados pelas classes do programa',\r\n 'dicionario':'(dict) Armazena um dicionario contendo todos os métodos e atributos e suas respectivas funcionalidades'\r\n }\r\n for i in self.__metodos:\r\n dicionario[i] = eval('self.%s.__doc__'%i)\r\n return dicionario\r\n\r\n def getAtributos(self: object) -> set:\r\n '''Retorna o nome de todos os atributos'''\r\n return self.__atributos\r\n\r\n def getMetodos(self: object) -> set:\r\n '''Retorna o nome de todos os métodos'''\r\n return self.__metodos\r\n\r\n def __str__(self: object):\r\n output = ''\r\n dicio = self.manualUsuario()\r\n for chave, valor in dicio.items():\r\n output += str.format('{}:{}\\n',chave, valor)\r\n return output\r\n\r\n def main():\r\n '''Função Principal'''\r\n jogo = JogoDaVelha()\r\n jogo.interface()\r\n while jogo.jogadas < 9 and jogo.vitoria == False:\r\n jogo.leituraPosicao1()\r\n jogo.jogadas += 1\r\n jogo.condicaoDeVitoria()\r\n '''Verifica se o jogador 1 ganhou'''\r\n jogo.interface()\r\n if jogo.jogadas < 9 and jogo.vitoria == False:\r\n jogo.leituraPosicao2()\r\n jogo.jogadas += 1\r\n jogo.condicaoDeVitoria()\r\n '''Verifica se o jogador 2 ganhou'''\r\n jogo.interface()\r\n jogo.resultado()\r\n '''Verifica o resultado'''\r\n \r\nif __name__ == '__main__':\r\n JogoDaVelha.main()\r\n","sub_path":"LucasAquinoProva1.py","file_name":"LucasAquinoProva1.py","file_ext":"py","file_size_in_byte":14563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"365089878","text":"# Dada uma sequência de números inteiros, imprimir seus quadrados.\n# Entradas do programa:\n# nº de início da sequência = 0\n# nº de fim da sequência = 4\n# Saída do programa:\n# sequência : 0, 1, 4, 9, 16\n\n\ndef quadradoFor(iniL, fimL):\n mensagem = \"\"\n for contador in range(iniL, fimL+1):\n tmp = contador**2\n mensagem = mensagem + str(tmp) + \" \"\n return (mensagem)\n\ndef main():\n inicio = int(input('Início:'))\n fim = int(input('Fim:'))\n print(quadradoFor(inicio, fim))\n\n\n\n\nmain()","sub_path":"ex.aula 09/Ex. O.py","file_name":"Ex. O.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"393659752","text":"\n\nfrom xai.brain.wordbase.verbs._enlighten import _ENLIGHTEN\n\n#calss header\nclass _ENLIGHTENS(_ENLIGHTEN, ):\n\tdef __init__(self,): \n\t\t_ENLIGHTEN.__init__(self)\n\t\tself.name = \"ENLIGHTENS\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"enlighten\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_enlightens.py","file_name":"_enlightens.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"191537945","text":"from ftw.testbrowser import browsing\nfrom opengever.meeting.zipexport import MeetingZipExporter\nfrom opengever.meeting.zipexport import ZipJobManager\nfrom opengever.testing import IntegrationTestCase\nfrom plone.namedfile.file import NamedBlobFile\nfrom plone.uuid.interfaces import IUUID\n\n\nclass TestPollMeetingZip(IntegrationTestCase):\n\n features = ('meeting', 'bumblebee')\n\n @browsing\n def test_zip_polling_view_reports_converting(self, browser):\n self.login(self.meeting_user, browser)\n\n job_manager = ZipJobManager(self.meeting.model)\n zip_job = job_manager.create_job()\n zip_job.add_doc_status(IUUID(self.document), {'status': 'converting'})\n\n browser.open(\n self.meeting,\n view='poll_meeting_zip?job_id={}'.format(zip_job.job_id),\n method='POST')\n self.assertEqual(1, browser.json['converting'])\n\n @browsing\n def test_zip_polling_view_creates_zip_when_all_finished(self, browser):\n self.login(self.meeting_user, browser)\n\n job_manager = ZipJobManager(self.meeting.model)\n zip_job = job_manager.create_job()\n zip_job.add_doc_status(\n IUUID(self.document),\n {'status': 'finished', 'blob': NamedBlobFile(data='foo')})\n\n browser.open(\n self.meeting,\n view='poll_meeting_zip?job_id={}'.format(zip_job.job_id),\n method='POST')\n self.assertEqual(1, browser.json['zipped'], browser.json)\n\n @browsing\n def test_zip_polling_view_reports_skipped(self, browser):\n self.login(self.meeting_user, browser)\n\n job_manager = ZipJobManager(self.meeting.model)\n zip_job = job_manager.create_job()\n zip_job.add_doc_status(IUUID(self.document), {'status': 'skipped'})\n\n browser.open(\n self.meeting,\n view='poll_meeting_zip?job_id={}'.format(zip_job.job_id),\n method='POST')\n self.assertEqual(1, browser.json['skipped'])\n\n\nclass TestDownloadMeetingZip(IntegrationTestCase):\n\n features = ('meeting', 'bumblebee')\n\n @browsing\n def test_download_meeting_zip(self, browser):\n self.login(self.meeting_user, browser)\n\n exporter = MeetingZipExporter(self.meeting.model)\n exporter.zip_job = exporter.job_manager.create_job()\n exporter.zip_job.add_doc_status(\n IUUID(self.document), {'status': 'converting'})\n\n doc_in_job_id = exporter.zip_job._get_doc_in_job_id(self.document)\n exporter.receive_pdf(doc_in_job_id,\n 'application/pdf',\n 'i am a apdf.')\n exporter.generate_zipfile()\n\n browser.open(\n self.meeting,\n view='download_meeting_zip?job_id={}'.format(exporter.zip_job.job_id))\n self.assertEquals('application/zip', browser.contenttype)\n","sub_path":"opengever/meeting/tests/test_meeting_zipdemand.py","file_name":"test_meeting_zipdemand.py","file_ext":"py","file_size_in_byte":2845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"158902153","text":"\nfrom typing import List \nfrom utils import *\n \nclass Solution_099_RecoverBinarySearchTree_1:\n def recoverTree(self, root: TreeNode):\n \"\"\"\n :rtype: void Do not return anything, modify root in-place instead.\n \"\"\"\n def inorder(r: TreeNode) -> List[int]:\n return inorder(r.left) + [r.val] + inorder(r.right) if r else []\n \n def find_two_swapped(nums: List[int]) -> (int, int):\n n = len(nums)\n x = y = None # Initialize x and y as a value that cannot be the value of a node.\n for i in range(n - 1):\n if nums[i + 1] < nums[i]:\n y = nums[i + 1]\n # first swap occurrence\n if x is None: \n x = nums[i]\n # second swap occurrence\n else: \n break\n return x, y\n \n def recover(r: TreeNode, count: int):\n if r:\n if r.val == x or r.val == y:\n r.val = y if r.val == x else x\n count -= 1\n if count == 0:\n return \n recover(r.left, count)\n recover(r.right, count)\n \n nums = inorder(root)\n x, y = find_two_swapped(nums)\n recover(root, 2)\n\nif __name__ == \"__main__\":\n nums = [2, 7, 11, 15]\n target = 26\n s = \"aa\"\n arrays = [[1, 2, 3], [4, 5, 6]]\n print(arrays)\n ","sub_path":"solution/python/099_RecoverBinarySearchTree_1.py","file_name":"099_RecoverBinarySearchTree_1.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"452669603","text":"#!/usr/bin/env python\n\nfrom sys import argv\nfrom hashlib import md5\n\n# parse arg\nscript, filename = argv\n\ndef day_one(filename):\n print(\"Advent challenge #1\")\n level = 0\n pos = 0\n with open(filename) as f:\n while True:\n c = f.read(1)\n pos += 1\n if c is '(':\n print(\"Going up one level\")\n level += 1\n if c is ')':\n print(\"Going down one level\")\n level -= 1\n if not c:\n print(\"EOF\")\n break\n if level == -1:\n print(\"Santa at basement level! pos=%i\" % pos)\n break\n print(\"Santa is on level: %i\" % level)\n\ndef day_two(filename):\n print(\"Advent challenge #2\")\n paper = 0\n with open(filename) as f:\n for line in f:\n dim = line.split(\"x\")\n dim = [int(i) for i in dim]\n dim.sort()\n paper += (2*(dim[0]*dim[1]) + 2*(dim[1]*dim[2]) + 2*(dim[0]*dim[2]) + dim[0]*dim[1])\n\n print(\"Required dimensions are: %i\" % paper)\n\ndef day_three(filename):\n print(\"Advent challenge #3\")\n houses = {}\n\n # coordinates\n x = 0\n y = 0\n\n # mark first house\n houses[x, y] = 1\n\n with open(filename) as f:\n while True:\n c = f.read(1)\n\n # adjust current pos\n if c is '^':\n y += 1\n if c is 'v':\n y -= 1\n if c is '<':\n x -= 1\n if c is '>':\n x += 1\n if not c:\n break\n\n # update current pos in dict\n houses[x, y] = 1\n\n print(\"Santa visited %i houses.\" % len(houses))\n\ndef day_four():\n print(\"Advent challenge #4\")\n key = 'ckczppom'\n i = 0\n while True:\n secret_key = key + str(i)\n secret_hash = md5(secret_key.encode('utf-8')).hexdigest()\n print(\"Iteration %i secret hash=%s\" % (i, secret_hash))\n\n if(secret_hash[0:5] == '00000'):\n print(\"Found secret key! ==> %s\" % secret_key)\n print(\"hash = %s\" % secret_hash)\n break\n else:\n i += 1\n\ndef contains_three_vowels(string):\n vowels = 0\n for c in string:\n if(c is 'a' or c is 'e' or c is 'i' or c is 'o' or c is 'u'):\n vowels += 1\n\n if(vowels >= 3):\n return True\n else:\n return False\n\ndef double_letter(string):\n for i in range(len(string) - 1):\n if(string[i] == string[i+1]):\n return True\n\n return False\n\ndef exceptions(string):\n flag = True\n if('ab' in string):\n return False\n if('cd' in string):\n return False\n if('pq' in string):\n return False\n if('xy' in string):\n return False\n\n return True\n\ndef day_five(filename):\n nice = 0\n with open(filename) as f:\n for line in f:\n flag = True\n if(contains_three_vowels(line) is False):\n flag = False\n if(double_letter(line) is False):\n flag = False\n if(exceptions(line) is False):\n flag = False\n\n if(flag is True):\n nice += 1\n\n print(\"There are %i nice strings.\" % nice)\n\n\ndef day_six(filename):\n grid = {}\n\n # turn off all lights\n for x in range(1000):\n for y in range(1000):\n grid[x, y] = 'off'\n\n with open(filename) as f:\n for line in f:\n line = line.split()\n if(line[0] == 'turn'):\n state = line[1]\n start = line[2].split(',')\n end = line[4].split(',')\n for x in range(int(start[0]), int(end[0]) + 1):\n for y in range(int(start[1]), int(end[1]) + 1):\n grid[x, y] = state\n\n elif(line[0] == 'toggle'):\n start = line[1].split(',')\n end = line[3].split(',')\n for x in range(int(start[0]), int(end[0]) + 1):\n for y in range(int(start[1]), int(end[1]) + 1):\n if(grid[x, y] == 'off'):\n grid[x, y] = 'on'\n\n elif(grid[x, y] == 'on'):\n grid[x, y] = 'off'\n\n lights_on = 0\n for i in range(0, 1000):\n for j in range(0, 1000):\n if(grid[i, j] == 'on'):\n lights_on += 1\n\n print(lights_on)\n\n\nif __name__ == '__main__':\n #day_one(filename)\n #day_two(filename)\n #day_three(filename)\n #day_four()\n #day_five(filename)\n day_six(filename)\n","sub_path":"advent.py","file_name":"advent.py","file_ext":"py","file_size_in_byte":4622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"319113347","text":"from copy import deepcopy\n\n\ndef gen_adjacent_node(matrix, x, y):\n rowLen = len(matrix)\n colLen = len(matrix[0])\n\n xCord = (1, -1, 0)\n yCord = (1, -1, 0)\n\n for i in xCord:\n for j in yCord:\n if i == 0 and j == 0:\n continue\n if x+i < rowLen and x+i >= 0 and y+j < colLen and y+j >= 0:\n yield matrix[x+i][y+j]\n\n\ndef occupy(a, b, i, j):\n for node in gen_adjacent_node(a, i, j):\n if node == '#':\n return\n b[i][j] = '#'\n\n\ndef vacate(a, b, i, j):\n count = 0\n for node in gen_adjacent_node(a, i, j):\n if node == '#':\n count += 1\n if count >= 4:\n b[i][j] = 'L'\n\n\ndef printMat(b):\n for i in b:\n for j in i:\n print(j, end=' ')\n print()\n\n\nwith open(f'11.txt') as f:\n a = [list(i.rstrip()) for i in f]\n\n\nwhile True:\n b = deepcopy(a)\n for i, line in enumerate(a):\n for j, val in enumerate(line):\n if val == 'L':\n occupy(a, b, i, j)\n elif val == '#':\n vacate(a, b, i, j)\n if a == b:\n break\n a = deepcopy(b)\n\nres = 0\nfor i in a:\n for j in i:\n if j == '#':\n res += 1\nprint(res)\n","sub_path":"Day 11/11.py","file_name":"11.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"608180065","text":"import os\r\nimport re\r\nimport itertools\r\nimport json\r\n\r\nimport random\r\n\r\nimport cv2\r\nimport pytesseract\r\nfrom pytesseract import Output\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\nfrom PIL import Image\r\n\r\nfrom src.document_class import DocumentOCR\r\n\r\n#before dumping\r\n#doc.flatten_text = flatten_text.encode(\"utf-8\")\r\n#after dumping\r\n#flatten_text = flatten_text.encode(\"utf-8\")\r\n#after loading\r\n#flatten_text = flatten_text.encode(\"utf-8\")\r\n\r\n\r\ndef main():\r\n\r\n print(\"started main\")\r\n exec_path = os.getcwd()\r\n\r\n file_list = os.listdir(exec_path)\r\n for filename in file_list:\r\n if \".png\" in filename or \".pdf\" in filename or \".jpg\" in filename:\r\n path_img = os.path.join(exec_path,filename)\r\n single_file(path_img)\r\n\r\n return \r\n\r\n\"\"\"\r\n search_dict = {\r\n \"numbers\":\"\\d+\",\r\n \"jose\":\"[Jj]ose|JOSE\",\r\n \"dates\":\"\\d{2}[\\-\\\\\\/]\\d{2}[\\-\\\\\\/]\\d{2,4}\",\r\n \"ml2\":\"ine learn\",\r\n \"email\":\"[a-zA-Z]+@[a-z]+\\.?[a-z]+\",\r\n \"dni\":\"\\d{8,9}[A-Z]\",\r\n \"cea\": \"[0-9A-Z]{5}\\-[0-9A-Z]{5}\\-[0-9A-Z]{5}\\-[0-9A-Z]{5}\\-[0-9A-Z]{5}\\-[0-9A-Z]{5}\"\r\n }\r\n\r\n\"\"\"\r\n\r\ndef single_file(path_img):\r\n\r\n def preprocessing(img):\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n ret,img = cv2.threshold(img,180,255,cv2.THRESH_BINARY)\r\n kernel = np.ones((2,2),np.uint8)\r\n img = cv2.erode(img,kernel,iterations = 1)\r\n\r\n return img\r\n\r\n doc = DocumentOCR(path_img)\r\n doc.remove_tmp()\r\n doc = doc.apply_preprocessing(preprocessing)\r\n doc = doc.apply_ocr()\r\n df = doc.df\r\n\r\n search_dict = {\r\n \"dates\":r'\\d{1,2}\\/\\d{1,2}\\/\\d{2,4}',\r\n \"total\":r\"\\s{2}Total\",\r\n \"email\":r\"[a-zA-Z]+@[a-z]+\\.?[a-z]+\",\r\n \"numbers\":r\"\\d+\",\r\n\r\n \"prices\": r\"\\d+[,\\.]\\d+\"\r\n }\r\n\r\n extracted_dict = df.get_extracted_dict(search_dict)\r\n print(doc.flatten_text)\r\n print(extracted_dict)\r\n highlighted_img= doc.highlight_image(extracted_dict,save=True)\r\n\r\n return\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n\r\n \r\n\r\n\r\n \r\n\r\n \r\n \r\n\r\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"57049380","text":"#!/usr/bin/env python3\n\nimport discord\nimport asyncio\nimport collections\nfrom random import choice\nfrom time import mktime\nfrom dateutil import tz\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom icalendar import Calendar\nfrom urllib.request import urlopen\n\nfrom_zone = tz.gettz(\"UTC\")\nto_zone = tz.gettz(\"Europe/Paris\")\n\ndef getLessons():\n request = urlopen(\"https://adewebcons.unistra.fr/jsp/custom/modules/plannings/anonymous_cal.jsp?resources=22647,22645,556&projectId=1&calType=ical&nbWeeks=14\")\n gcal = Calendar.from_ical(request.read())\n return gcal.walk(\"VEVENT\")\n\ndef getNextLesson():\n nextLesson = None\n for lesson in getLessons():\n diff = lesson.get(\"dtstart\").dt.replace(tzinfo=from_zone).astimezone(to_zone) - datetime.utcnow().replace(tzinfo=from_zone).astimezone(to_zone) - timedelta(minutes=60)\n if nextLesson == None or diff < nextLesson[0] and diff.total_seconds() > 0:\n nextLesson = list()\n nextLesson.append(diff)\n nextLesson.append(lesson.get(\"summary\"))\n nextLesson.append(lesson.get(\"location\"))\n nextLesson.append(lesson.get(\"description\").split(\"\\n\")[3])\n nextLesson.append(lesson.get(\"dtstart\").dt.replace(tzinfo=from_zone).astimezone(to_zone).strftime(\"%d/%m/%Y\"))\n nextLesson.append(lesson.get(\"dtstart\").dt.replace(tzinfo=from_zone).astimezone(to_zone).strftime(\"%H:%M\"))\n nextLesson.append(lesson.get(\"dtend\").dt.replace(tzinfo=from_zone).astimezone(to_zone).strftime(\"%H:%M\"))\n return nextLesson\n\ndef getDayLessons(nextDay=None):\n lessons = getLessons()\n if nextDay is None:\n for lesson in lessons:\n date = lesson.get(\"dtstart\").dt.replace(tzinfo=from_zone).astimezone(to_zone).date()\n if nextDay == None or date < nextDay:\n nextDay = date\n\n dayLessons = dict()\n for lesson in lessons:\n if nextDay == lesson.get(\"dtstart\").dt.replace(tzinfo=from_zone).astimezone(to_zone).date():\n dayLesson = list()\n dayLesson.append(lesson.get(\"summary\"))\n dayLesson.append(lesson.get(\"location\"))\n dayLesson.append(lesson.get(\"description\").split(\"\\n\")[3])\n dayLesson.append(lesson.get(\"dtstart\").dt.replace(tzinfo=from_zone).astimezone(to_zone).strftime(\"%d/%m/%Y\"))\n dayLesson.append(lesson.get(\"dtstart\").dt.replace(tzinfo=from_zone).astimezone(to_zone).strftime(\"%H:%M\"))\n dayLesson.append(lesson.get(\"dtend\").dt.replace(tzinfo=from_zone).astimezone(to_zone).strftime(\"%H:%M\"))\n dayLessons[mktime(lesson.get(\"dtstart\").dt.replace(tzinfo=from_zone).astimezone(to_zone).timetuple())] = dayLesson\n return collections.OrderedDict(sorted(dayLessons.items())).items()\n\nif __name__ == '__main__':\n client = discord.Client()\n\n @client.event\n async def on_ready():\n print(\"------- Bot Discord --------\")\n print(\"Développé par Norman FELTZ\")\n print(\"Connecté: \", client.user.name + \"#\" + client.user.discriminator)\n print(\"----------------------------\")\n\n @client.event\n async def on_message(message):\n if message.content.startswith(\".next\"):\n embed = discord.Embed(title=\"Prochain cours\", description=\"Chargement en cours...\", colour=discord.Colour.dark_red())\n embed.set_author(name=message.author.name, icon_url=message.author.avatar_url)\n msg = await client.send_message(message.channel, embed=embed)\n\n nextLesson = getNextLesson()\n embed.description = \"{}\\n\".format(nextLesson[1])\n embed.description += \"Le {} de {} à {}\\n\".format(nextLesson[4], nextLesson[5], nextLesson[6])\n embed.description += \"Professeur: {}\\n\".format(nextLesson[3])\n embed.description += \"Salle: {}\\n\".format(nextLesson[2])\n await client.edit_message(msg, embed=embed)\n elif message.content.startswith(\".day\"):\n embed = discord.Embed(title=\"Prochain journée de cours\", description=\"Chargement en cours...\", colour=discord.Colour.dark_red())\n embed.set_author(name=message.author.name, icon_url=message.author.avatar_url)\n msg = await client.send_message(message.channel, embed=embed)\n\n args = message.content.split(\" \")\n if len(args) >= 2:\n try:\n nextDay = datetime.strptime(args[1], \"%d/%m/%Y\").date()\n except ValueError:\n embed.description = \"Veuillez entrer une date au format JJ/MM/YYYY\"\n else:\n dayLessons = getDayLessons(nextDay)\n if len(dayLessons) >= 1:\n embed.description = \"**Matin:**\\n\"\n for day, dayLesson in dayLessons:\n if dayLesson[4] == \"13:30\":\n embed.description += \"\\n**Après-midi:**\\n\"\n embed.description += \"{}\\n\".format(dayLesson[0])\n embed.description += \"Le {} de {} à {}\\n\".format(dayLesson[3], dayLesson[4], dayLesson[5])\n embed.description += \"Professeur: {}\\n\".format(dayLesson[2])\n embed.description += \"Salle: {}\\n\".format(dayLesson[1])\n else:\n embed.description = \"Aucun cours\"\n else:\n dayLessons = getDayLessons()\n embed.description = \"**Matin:**\\n\"\n for day, dayLesson in dayLessons:\n if dayLesson[4] == \"13:30\":\n embed.description += \"\\n**Après-midi:**\\n\"\n embed.description += \"{}\\n\".format(dayLesson[0])\n embed.description += \"Le {} de {} à {}\\n\".format(dayLesson[3], dayLesson[4], dayLesson[5])\n embed.description += \"Professeur: {}\\n\".format(dayLesson[2])\n embed.description += \"Salle: {}\\n\".format(dayLesson[1])\n await client.edit_message(msg, embed=embed)\n elif message.content.startswith(\".wtf\"):\n embed = discord.Embed(title=\"What the Fuck ???\", colour=discord.Colour.dark_red())\n embed.set_author(name=message.author.name, icon_url=message.author.avatar_url)\n embed.set_image(url=\"http://ljdchost.com/BUBgLiw.gif\")\n await client.send_message(message.channel, embed=embed)\n elif message.content.startswith(\".fuck\"):\n fuck = (\"https://ljdchost.com/CtDqj.gif\", \"http://ljdchost.com/Fmov8QZ.gif\", \"http://ljdchost.com/HLNRJHb.gif\")\n embed = discord.Embed(title=\"Fuck !!!!\", colour=discord.Colour.dark_red())\n embed.set_author(name=message.author.name, icon_url=message.author.avatar_url)\n embed.set_image(url=choice(fuck))\n await client.send_message(message.channel, embed=embed)\n elif message.content.startswith(\".hendek\"):\n embed = discord.Embed(title=\"Appellez les hendeks !!!\", colour=discord.Colour.dark_red())\n embed.set_author(name=message.author.name, icon_url=message.author.avatar_url)\n embed.set_image(url=\"https://cdn.discordapp.com/attachments/358718175636094976/393357739805376524/209cml.jpg\")\n await client.send_message(message.channel, embed=embed)\n elif message.content.startswith(\".test\"):\n embed = discord.Embed(title=\"Test\", description=\"Hello world !\", colour=discord.Colour.dark_red())\n embed.set_author(name=message.author.name, icon_url=message.author.avatar_url)\n await client.send_message(message.channel, embed=embed)\n\n with open(\"token.txt\") as file:\n client.run(file.read())","sub_path":"univ.py","file_name":"univ.py","file_ext":"py","file_size_in_byte":7716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"3031395","text":"\"\"\"\nModule contains set of functions modeling kids distribution in a family with two kids.\n\"\"\"\nfrom __future__ import division\nimport random as r\n\nTWO_BOYS = 0\nOLDER_BOY_YOUNGER_GIRL = 1\nOLDER_GIRL_YOUNGER_BOY = 2\nTWO_GIRLS = 3\nBOY = 0\nGIRL = 1\n\n\ndef random_kid():\n return r.choice([BOY, GIRL])\n\n\ndef run_simulation():\n older_kid = random_kid()\n younger_kid = random_kid()\n if older_kid == BOY:\n if younger_kid == BOY:\n return TWO_BOYS\n else:\n return OLDER_BOY_YOUNGER_GIRL\n else:\n if younger_kid == BOY:\n return OLDER_GIRL_YOUNGER_BOY\n else:\n return TWO_GIRLS\n\n\nif __name__ == \"__main__\":\n total_events = 100000\n at_least_one_girl_events = 0\n older_is_girl_events = 0\n two_girls_events = 0\n\n for _ in range(total_events + 1):\n sim_result = run_simulation()\n if sim_result == TWO_GIRLS:\n at_least_one_girl_events += 1\n older_is_girl_events += 1\n two_girls_events += 1\n elif sim_result == OLDER_GIRL_YOUNGER_BOY:\n older_is_girl_events += 1\n at_least_one_girl_events += 1\n elif sim_result == OLDER_BOY_YOUNGER_GIRL:\n at_least_one_girl_events += 1\n else:\n pass\n print(\"P(B | E) = %f\\nP(B | O) = %f\") % (\n two_girls_events / at_least_one_girl_events, two_girls_events / older_is_girl_events)\n","sub_path":"two_kids.py","file_name":"two_kids.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"397981135","text":"'''\nUnique tkinter strings that are used to supply\nto listeners to tell them what to listen for.\n'''\n\nLEFT_CLICK = \"\"\nMIDDLE_CLICK = \"\"\nRIGHT_CLICK = \"\"\n\nLEFT_DRAG = \"\"\nMIDDLE_DRAG = \"\"\nRIGHT_DRAG = \"\"\n\nLEFT_RELEASE = \"\"\nMIDDLE_RELEASE = \"\"\nRIGHT_RELEASE = \"\"\n\nDOUBLE_LEFT_CLICK = \"\"\nTRIPLE_LEFT_CLICK = \"\"\nDOUBLE_MIDDLE_CLICK = \"\"\nTRIPLE_MIDDLE_CLICK = \"\"\nDOUBLE_RIGHT_CLICK = \"\"\nTRIPLE_RIGHT_CLICK = \"\"\n\nMOUSE_ENTER = \"\"\nMOUSE_EXIT = \"\"\n\nENTER_KEY = \"\"\n","sub_path":"user_input.py","file_name":"user_input.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"74801591","text":"from tiget.git.models import get_model\n\n\ndef model_type(model_name):\n try:\n model = get_model(model_name)\n except KeyError:\n raise TypeError\n return model\n\n\ndef dict_type(arg):\n try:\n key, value = arg.split('=', 1)\n except ValueError:\n raise TypeError('\"=\" not found in \"{}\"'.format(arg))\n return (key, value)\n","sub_path":"tiget/cmds/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"185535632","text":"from kipoi.model import SklearnModel\nimport numpy as np\n\nmodel_path = \"./model/ward_formation_energy.pkl\"\n\ndef run(data):\n model = SklearnModel(model_path)\n return model.predict_on_batch(data)\n\ndef test_run():\n X = np.load(\"./data/test_data.npy\")\n output = run(X)\n\n assert len(output) == len(X)\n\n print(output)\n return output\n","sub_path":"parsl-containers/ward_formation_energy/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"286233300","text":"import datetime\nimport matplotlib.dates as mpd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tushare as ts\nimport pickle\nfrom tqdm import tqdm\n\n\ndef download_hist(file_name='data0309.pkl'):\n # using get_k_hist to download\n\n # get stock names\n codes = ts.get_today_all()['code'].values\n\n # download stocks data\n code = []\n data = []\n bug_codes = ['000982', '603010', '300578', '603429','603330']\n\n for i in tqdm(codes, desc='[Downloading Stocks]'):\n if i in bug_codes:\n continue\n try:\n # get data\n hist = ts.get_k_data(i, autype='qfq') # (from past to now)\n code.append(i)\n data.append(hist)\n except:\n continue\n\n # download indices data\n indices = ['000001', '000002', '000003', '000008', '000009', '000010',\n '000011', '000012', '000016', '000017', '000300', '399001',\n '399002', '399003', '399004', '399005', '399006', '399100',\n '399101', '399106', '399107', '399108', '399333', '399606']\n for i in tqdm(indices, desc='[Downloading Indices]'):\n try:\n # get data\n hist = ts.get_k_data(i, index=True) # (from past to now)\n code.append('i_' + i)\n data.append(hist)\n except:\n continue\n\n # write into files\n content = dict(zip(code, data))\n print(content['i_399001'])\n\n fn = file_name\n with open(fn, 'wb') as f: # open file with write-mode\n pickle.dump(content, f) # serialize and save object\n return\n\n\ndef download_deals(file_name='deals0317.pkl', calendar_days=365):\n content = []\n\n # get stock names\n stock_info = ts.get_stock_basics()\n\n for code in tqdm(stock_info.index, desc='[Downloading Deals]'):\n try:\n for d in range(calendar_days + 1):\n date = (datetime.datetime.now() - datetime.timedelta(days=d)).strftime(\n '%Y-%m-%d')\n content.append({code: {date: ts.get_tick_data(code, date)}})\n except:\n continue\n\n fn = file_name\n with open(fn, 'wb') as f: # open file with write-mode\n pickle.dump(content, f) # serialize and save object\n return\n\n\ndef plot_history_closes_line(code='300403',\n days=365):\n \"\"\"\n public\n (get_k_hist)\n plot history close price line\n \"\"\"\n # get data\n today = datetime.datetime.now().strftime('%Y-%m-%d')\n one_year_before = (datetime.datetime.now() - datetime.timedelta(days=days)).strftime('%Y-%m-%d')\n hist = ts.get_k_data(code, start=one_year_before, end=today) # reverse order (from now to past)\n\n # plot close price movement\n x = np.linspace(1, len(hist['close']), len(hist['close']))\n plt.plot(x, hist['close'], 'b')\n plt.show()\n\n return\n\n\ndef plot_history_returns_line(code='300403',\n days=365):\n \"\"\"\n public\n (get_k_hist)\n plot history return line\n \"\"\"\n # get data\n today = datetime.datetime.now().strftime('%Y-%m-%d')\n one_year_before = (datetime.datetime.now() - datetime.timedelta(days=days)).strftime('%Y-%m-%d')\n hist = ts.get_k_data(code, start=one_year_before, end=today) # reverse order (from now to past)\n\n # get returns\n ds_by_s = (hist['close'].shift(-1) - hist['close']) / hist[\n 'close'] # the return from today to tomorrow store in today in reverse order (from now to past)\n ds_by_s = ds_by_s[:-1] # drop NAN\n\n # plot the history returns movement\n x = np.linspace(1, len(ds_by_s), len(ds_by_s))\n plt.plot(x, ds_by_s, 'b')\n plt.show()\n\n return\n\n\ndef plot_history_returns_histogram(code='300403',\n days=365):\n \"\"\"\n public\n (get_k_hist)\n plot history returns histogram\n \"\"\"\n # get data\n today = datetime.datetime.now().strftime('%Y-%m-%d')\n one_year_before = (datetime.datetime.now() - datetime.timedelta(days=days)).strftime('%Y-%m-%d')\n hist = ts.get_k_data(code, start=one_year_before, end=today) # reverse order (from now to past)\n\n # get returns\n ds_by_s = (hist['close'].shift(-1) - hist['close']) / hist[\n 'close'] # the return from today to tomorrow store in today in reverse order (from now to past)\n ds_by_s = ds_by_s[:-1] # drop NAN\n\n # plot histogram\n plt.hist(ds_by_s, 100)\n plt.show()\n\n return\n\n\ndef plot_history_candlestick(code='300403',\n days=200,\n width=0.6,\n color_up='r',\n color_down='g',\n transparency=0.8):\n \"\"\"\n public\n (get_k_hist)\n plot candle stick\n \"\"\"\n # get data\n today = datetime.datetime.now().strftime('%Y-%m-%d')\n one_year_before = (datetime.datetime.now() - datetime.timedelta(days=days)).strftime('%Y-%m-%d')\n hist = ts.get_k_data(code, start=one_year_before, end=today)\n\n # initiate plots\n fig, ax = plt.subplots(figsize=(20, 6))\n fig.subplots_adjust(bottom=0.2, left=0.05, right=0.95)\n\n # plot candlestick\n half_width = width / 2.0\n for date_string, row in hist.iterrows():\n date_time = datetime.datetime.strptime(row[0], \"%Y-%m-%d\")\n t = mpd.date2num(date_time)\n\n _open, _close, _high, _low = row[1:5]\n\n if _close >= _open:\n color = color_up\n lower = _open\n height = _close - _open\n else:\n color = color_down\n lower = _close\n height = _open - _close\n\n line = plt.Line2D(\n xdata=(t, t), ydata=(_low, _high),\n color=color,\n linewidth=0.5,\n antialiased=True,\n )\n\n rect = plt.Rectangle(\n xy=(t - half_width, lower),\n width=width,\n height=height,\n facecolor=color,\n edgecolor=color,\n )\n rect.set_alpha(transparency)\n ax.add_patch(rect)\n ax.add_line(line)\n\n # adjust axis\n mondays = mpd.WeekdayLocator(mpd.MONDAY)\n all_days = mpd.DayLocator()\n ax.xaxis.set_major_locator(mondays)\n ax.xaxis.set_minor_locator(all_days)\n formatter = mpd.DateFormatter('%m-%d-%Y') # 2-29-2015\n ax.xaxis.set_major_formatter(formatter)\n ax.autoscale_view()\n ax.xaxis_date()\n ax.grid(True)\n\n # adjust plot\n plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')\n plt.title(code + ' [days: ' + str(len(hist['close'])) + ']')\n plt.show()\n\n return\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":6544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"209748078","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponseRedirect\nfrom django.views import View\nfrom django.views.generic.edit import FormView\nfrom django.views.generic.base import TemplateView\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.contrib.auth.tokens import default_token_generator\nfrom django.contrib.auth import get_user_model, login as auth_login\nfrom django.urls import reverse_lazy\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.cache import never_cache\nfrom django.utils.http import urlsafe_base64_decode\nfrom apps.propelauth.forms import AgentSignUpForm\n\nfrom commons.tokens import email_confirmation_token\n\nUser = get_user_model()\n\nclass AgentSignUpView(FormView):\n \n template_name = 'accounts/sign_up.html'\n success_url = reverse_lazy('sign_up_done')\n form_class = AgentSignUpForm\n allow_authenticated = False\n\n token_generator = email_confirmation_token\n domain_override = None\n subject_template_name = 'accounts/email_confirmation_subject.txt'\n email_template_name = 'accounts/email_confirmation_email.html'\n html_email_template_name = None\n from_email = None\n extra_email_context = None\n\n def dispatch(self, *args, **kwargs):\n if not self.allow_authenticated and self.request.user.is_authenticated:\n return redirect(reverse_lazy('home'))\n return super(AgentSignUpView, self).dispatch(*args, **kwargs)\n\n def form_valid(self, form):\n kwargs = dict(\n token_generator=self.token_generator,\n domain_override=self.domain_override,\n subject_template_name=self.subject_template_name,\n email_template_name=self.email_template_name,\n html_email_template_name=self.html_email_template_name,\n from_email=self.from_email,\n extra_email_context=self.extra_email_context,\n request=self.request,\n use_https=self.request.is_secure(),\n )\n user = form.save(**kwargs)\n auth_login(self.request, user)\n return super(AgentSignUpView, self).form_valid(form)\n\n\nclass AgentSignUpDoneView(TemplateView):\n template_name = 'accounts/sign_up_done.html'\n\nclass AgentEmailConfirmView(TemplateView):\n template_name = 'accounts/email_confirmed.html'\n\n title = _('Email confirmed')\n token_generator = email_confirmation_token\n\n @method_decorator(never_cache)\n def dispatch(self, *args, **kwargs):\n assert 'uidb64' in kwargs and 'token' in kwargs\n\n self.validlink = False\n self.user = self.get_user(kwargs['uidb64'])\n token = kwargs['token']\n\n if self.user is not None and self.token_generator.check_token(self.user, token):\n self.validlink = True\n self.user.email_confirmed = True\n self.user.save()\n auth_login(self.request, self.user)\n\n return self.render_to_response(self.get_context_data())\n\n def get_user(self, uidb64):\n try:\n # urlsafe_base64_decode() decodes to bytestring\n uid = urlsafe_base64_decode(uidb64).decode()\n user = User._default_manager.get(pk=uid)\n except (TypeError, ValueError, OverflowError, User.DoesNotExist, ValidationError):\n user = None\n return user\n\n def get_form_kwargs(self):\n kwargs = super().get_form_kwargs()\n kwargs['user'] = self.user\n return kwargs\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n if self.validlink:\n context.update({\n 'title': _('Email confirmed'),\n 'h1_title': _('Confirmed!'),\n 'message':_('Your email has been confirmed. You are now logged in.'),\n 'validlink': True,\n })\n else:\n context.update({\n 'title': _('Invalid link'),\n 'h1_title': _('Invalid link'),\n 'message':_('This email confirmation link may have expired.'),\n 'validlink': False,\n })\n return context \n","sub_path":"propelproject/apps/propelauth/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"98915903","text":"# import os\n\nfrom bcncita import CustomerProfile, DocType, Office, OperationType, Province, try_cita\n\nif __name__ == \"__main__\":\n customer = CustomerProfile(\n anticaptcha_api_key=\"... your key here ...\", # Anti-captcha API Key (auto_captcha=False to disable it)\n anticaptcha_plugin_path=\"/Users/username/Downloads/anticaptcha-plugin_v0.50.crx\", # Path to plugin\n auto_captcha=True, # Enable anti-captcha plugin (if False, you have to solve reCaptcha manualy and press ENTER in the Terminal)\n auto_office=True,\n chrome_driver_path=\"/usr/local/bin/chromedriver\",\n # chrome_profile_name=\"Profile 7\", # Profile name\n # chrome_profile_path=f\"{os.curdir}/chrome_profiles/\", # You can persist Chrome profile between runs, it's good for captcha :)\n save_artifacts=True, # Record available offices / take available slots screenshot\n telegram_token=\"... your key here ...\", # Your Telegram bot token (sms-confirm cita through a bot using command \"/code 12345\")\n # wait_exact_time = [\n # [0, 0], # [minute, second]\n # [15, 0],\n # [30, 0],\n # [45, 0],\n # ],\n province=Province.BARCELONA,\n operation_code=OperationType.RECOGIDA_DE_TARJETA,\n doc_type=DocType.NIE, # DocType.NIE or DocType.PASSPORT\n doc_value=\"T1111111R\", # NIE or Passport number, no spaces.\n country=\"RUSIA\",\n name=\"BORIS JOHNSON\", # Your Name\n phone=\"600000000\", # Phone number (use this format, please)\n email=\"myemail@here.com\", # Email\n # Offices in order of preference\n # This selects specified offices one by one or a random one if not found.\n # For recogida only the first specified office will be attempted or none\n offices=[Office.BARCELONA_MALLORCA],\n )\n try_cita(context=customer, cycles=100) # Try 100 times\n\n\n# In Terminal run:\n# python3 example1.py\n","sub_path":"example1.py","file_name":"example1.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"548858134","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Aug 9 13:19:22 2018\r\n\r\n@author: adbhatt, aaygupta\r\n\"\"\"\r\n\r\nimport cv2\r\n\r\nclass PencilSketch:\r\n \"\"\"Pencil sketch effect\r\n A class that applies a pencil sketch effect to an image.\r\n The processed image is overlayed over a background image for visual\r\n effect.\r\n \"\"\"\r\n\r\n def __init__(self, width, height, bg_gray='sketch_bg4.jpg'):\r\n \"\"\"Initialize parameters\r\n :param (width, height): Image size.\r\n :param bg_gray: Optional background image to improve the illusion\r\n that the pencil sketch was drawn on a canvas.\r\n \"\"\"\r\n self.width = width\r\n self.height = height\r\n\r\n # try to open background canvas (if it exists)\r\n self.canvas = cv2.imread(bg_gray, cv2.CV_8UC1)\r\n if self.canvas is not None:\r\n self.canvas = cv2.resize(self.canvas, (self.width, self.height))\r\n\r\n def render(self, img_rgb, x, y):\r\n \"\"\"Applies pencil sketch effect to an RGB image\r\n :param img_rgb: RGB image to be processed\r\n :returns: Processed RGB image\r\n \"\"\"\r\n img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)\r\n img_blur = cv2.GaussianBlur(img_gray, (x, y), 0, 0)\r\n img_blend = cv2.divide(img_gray, img_blur, scale=256)\r\n #img_blend = cv2.equalizeHist(img_blend)\r\n # if available, blend with background canvas\r\n if self.canvas is not None:\r\n img_blend = cv2.multiply(img_blend, self.canvas, scale=1./256)\r\n\r\n return cv2.cvtColor(img_blend, cv2.COLOR_GRAY2RGB)\r\n\r\n''' \r\ndef start(url):\r\n #for url\r\n \r\n response = requests.get(url)\r\n img = Image.open(BytesIO(response.content)).convert('RGB')\r\n open_cv_image = np.array(img) \r\n img = open_cv_image[:, :, ::-1].copy() \r\n cv2.imwrite(\"c:\\\\temp\\\\Source.jpg\", img)\r\n #img = cv2.imread(url);\r\n imgHeight, imgWidth = img.shape[:2]\r\n pencil_sketch = PencilSketch(imgWidth, imgHeight)\r\n finalimg = pencil_sketch.render(img)\r\n cv2.imwrite(\"c:\\\\temp\\\\Result.jpg\", finalimg)\r\n return \"success\"\r\n \r\nif __name__ == \"__main__\":\r\n start(sys.argv[1])\r\n'''\r\n","sub_path":"ImageFilter/pencilsketch.py","file_name":"pencilsketch.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"157346617","text":"from automike import weekdates as wd\r\nfrom datetime import date as d, datetime as dt, timedelta as td\r\nfrom db import connection\r\n\r\n#This module gets the call stats for the last 5 working days\r\n#that was submitted to the Automike database. They include:\r\n# Number of calls taken\r\n# Calls logged against an account (call driver)\r\n# Comments left on an account\r\n# If upsell was logged on an account\r\n# Their AHT - average call time\r\n# Their total raising ticket time (shown as RSETICKET)\r\n\r\nclass callstats:\r\n #Gets all the values from the database from am_callstats.\r\n def __init__(self, _id):\r\n db = connection().instance()\r\n cur = db.cursor()\r\n cur.execute(\"SELECT date, calls, calls_logged, comments, upsell, \"\r\n \"aht, rseticket FROM am_callstats WHERE userid = '{0}' \"\r\n \"ORDER BY date DESC LIMIT 5\".format(_id))\r\n self.values = []\r\n for dbvalue in cur:\r\n self.values.append(dbvalue)\r\n connection().close()\r\n \r\n def get_day_stats(self, daydelta):\r\n #Gets all the data from the database and contains it in a\r\n #dictionary.\r\n return {\"Date\" : self.values[daydelta][0],\r\n \"Calls\" : self.values[daydelta][1],\r\n \"CallsLogged\" : self.values[daydelta][2],\r\n \"Comments\" : self.values[daydelta][3],\r\n \"Upsell\" : self.values[daydelta][4],\r\n \"AHT\" : self.values[daydelta][5],\r\n \"RaisingTicket\" : self.values[daydelta][6],}\r\n \r\n def nova(self):\r\n #Novatech points - determines what points are given when\r\n #certain targets are met:\r\n # If calls logged is 3 or less than calls taken (unfortunately\r\n # biased to split-skill agents).\r\n # \r\n # If AHT is less than 7 minutes average.\r\n # \r\n # If raising ticket time is less than 45 minutes.\r\n # \r\n # If upsell logging if logged on at least 80% of calls.\r\n # (Not implemented yet)\r\n # \r\n # If call logging, AHT and raising ticket time is consistant\r\n # throughout the week (i.e. meeting the targets for that week)\r\n # an extra point is rewarded, hence the implementation of the\r\n # ex_ varibles to keep track of this.\r\n # \r\n # Average Feedback (not implemented).\r\n points = 0\r\n ex_call = 0\r\n ex_aht = 0\r\n ex_res = 0\r\n today = dt.now()\r\n todaydate = d(today.year, today.month, today.day)\r\n monday = wd.get()[\"Monday\"]\r\n delta = todaydate - monday\r\n \r\n for x in range(delta.days - 1):\r\n if int(self.get_day_stats(x)[\"Calls\"]) - int(self.get_day_stats(x)[\"CallsLogged\"]) <= 3:\r\n points = points + 1\r\n ex_call = ex_call + 1\r\n \r\n if self.get_day_stats(x)[\"AHT\"] < td(0, 420):\r\n points = points + 1\r\n ex_aht = ex_aht + 1\r\n \r\n if self.get_day_stats(x)[\"RaisingTicket\"] < td(0, 2700):\r\n points = points + 1\r\n ex_res = ex_res + 1\r\n \r\n if self.get_day_stats(x)[\"Upsell\"] >= 80:\r\n points = points + 1\r\n \r\n if ex_call == 5:\r\n points = points + 1\r\n \r\n if ex_aht == 5:\r\n points = points + 1\r\n \r\n if ex_res == 5:\r\n points = points + 1\r\n \r\n return points\r\n \r\n def target(self):\r\n #Returns the values if a target has been met or not,\r\n #required for feedback on the UI - stored in a\r\n #dictionary.\r\n if int(self.get_day_stats(0)[\"Calls\"]) - int(self.get_day_stats(0)[\"CallsLogged\"]) <= 3:\r\n calltarget = True\r\n else:\r\n calltarget = False\r\n \r\n if self.get_day_stats(0)[\"AHT\"] < td(0, 420):\r\n ahttarget = True\r\n else:\r\n ahttarget = False\r\n \r\n if self.get_day_stats(0)[\"RaisingTicket\"] < td(0, 2700):\r\n restickettarget = True\r\n else:\r\n restickettarget = False\r\n \r\n upselltarget = False\r\n \r\n return {\"CallTarget\" : calltarget,\r\n \"AHTTarget\" : ahttarget,\r\n \"ResTicketTarget\" : restickettarget,\r\n \"UpsellTarget\" : upselltarget,}","sub_path":"automike/firstline/callstats.py","file_name":"callstats.py","file_ext":"py","file_size_in_byte":4479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"465586893","text":"# init: 200401 by KWC\n\nimport pandas as pd \n\n\n\n# Read in the data\nfName = 'agreement_signed.xlsx'\ndf = pd.read_excel(fName) # Requires xlrd\n\n# Basic stats\nprint('Number of members:', len(df))\nprint('Number of Institutions:', len(set(df['Institution'])))\nprint('Number of Countries:', len(set(df['Country'])))\n\n'''\n#200406\nNumber of members: 320\nNumber of Institutions: 273\nNumber of Countries: 40\n'''\n\n# Generate a text file of the members for the website:\nprint('Generating members list website file...')\nwith open(\"mems.txt\", \"w\") as f: \n\thtml = '{}{}{}\\n'\n\tfor index, row in df.iterrows():\n\t\tf.write(html.format(row['Full name'], row['Institution'], row['Country'])) \n\n\n\n# Generate file for the members map:","sub_path":"scripts/parse_mems.py","file_name":"parse_mems.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"309417834","text":"from pathlib import Path\nfrom typing import List, NamedTuple, Optional, Tuple\n\nimport numpy as np\n\n\nclass Run(NamedTuple):\n alg_name: str\n arch: str\n params: Tuple[Tuple[str, str]]\n path: Path\n runtime: Optional[str]\n durs: np.array\n\n @classmethod\n def from_path(cls, path: Path):\n tokens = path.name.split(\"!\")\n alg_name = tokens[0]\n arch = tokens[1]\n runtime = \"native\"\n if arch == \"wasm_single\" or arch == \"wasm_multi\":\n runtime = tokens.pop()\n params = dict()\n for pair in tokens[2:]:\n items = pair.split(\"+\", maxsplit=1)\n params[items[0]] = items[1]\n\n durs: List[float] = list()\n with open(path) as f:\n for l in f:\n durs.append(float(l.strip()))\n\n durs = np.array(durs)\n\n return cls(alg_name, arch, tuple(params.items()), path, runtime, durs)\n\n\ndef get_runs(alg_name: str = None):\n runs: List[Run] = list()\n\n log_path = Path(\"logs\")\n for p in log_path.iterdir():\n if p.name == \"err\":\n continue\n r = Run.from_path(p)\n if alg_name is None or alg_name == r.alg_name:\n runs.append(r)\n return runs\n","sub_path":"utils/logs.py","file_name":"logs.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"616725053","text":"\"\"\"Тестирование библиотеки\"\"\"\n\n__version__ = '1.0.0'\n\nfrom KavPyLibs.kav_sizes import FileDimensionIEC\nfrom KavPyLibs.kav_sizes import FileDimensionSystems\nfrom KavPyLibs.kav_sizes import FileSizes\n\n\nclass Tests:\n @staticmethod\n def test_file_size(logger):\n \"\"\"Тестирование преобразований размеров файлов\"\"\"\n\n dimension = FileDimensionIEC.MiB\n file_size = FileSizes(5, dimension)\n print(str(file_size.value) + file_size.file_dimension.name)\n print(str(file_size.get_bytes()))\n\n file_size = FileSizes.get_from_bytes(5243560, FileDimensionSystems.IEC)\n print(file_size.__str__())\n\n s = '5.02miB'\n print(FileSizes.get_from_str(s, FileDimensionSystems.IEC, logger).__str__())","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"542368077","text":"from __future__ import print_function\nimport math\nimport time\nimport sys\n\nfrom utils import Ab, GPIO\n\ncntl = 7\ncntr = 8\nEncL = 0\nEncR = 0\nDL = 19\n\ndef updateEncoderL(channel):\n global EncL\n EncL += 1\n\n\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\ndef updateEncoderR(channel):\n global EncR\n EncR += 1\n\n\nGPIO.setup(cntr, GPIO.IN)\nGPIO.setup(cntl, GPIO.IN)\nGPIO.add_event_detect(cntr, GPIO.BOTH, updateEncoderR)\nGPIO.add_event_detect(cntl, GPIO.BOTH, updateEncoderL)\n\n\ndef detect_obst():\n DL_status = GPIO.input(DL)\n return DL_status == 1\n\n\ndef followlightmove(angle):\n global EncL, EncR\n ini_encl = EncL\n ini_encr = EncR\n speed = 30\n\n print(\"Starting.\")\n\n time.sleep(0.5)\n d = 5 # the distance between two wheel\n threshold = 3 * math.pi\n k = 0.2\n\n if angle > 90:\n Ab.setMotor(0, speed)\n count = 0\n while True:\n distance_l = float(EncL - ini_encl) / 40 * 2 * math.pi * 1.5\n if count % 200 == 0:\n eprint(\"l:\", distance_l)\n if distance_l >= d * abs(angle - 90) * 2 * math.pi / 360:\n break\n count += 1\n Ab.stop()\n\n else:\n Ab.setMotor(-speed, 0)\n count = 0\n while True:\n distance_r = float(EncR - ini_encr) / 40 * 2 * math.pi * 1.5\n if count % 200 == 0:\n eprint(\"r:\", distance_r)\n if distance_r >= d * abs(angle - 90) * 2 * math.pi / 360:\n break\n count += 1\n Ab.stop()\n\n af_encl = EncL\n af_encr = EncR\n\n Ab.setMotor(-speed, speed+2)\n\n count = 0\n straight_distance = 0\n\n while detect_obst():\n straight_distance = float(EncL - af_encl + EncR - af_encr) / 2 / 40 * 2 * math.pi * 1\n if count % 100 == 0:\n eprint(\"straight:\", straight_distance)\n count += 1\n if straight_distance > threshold:\n break\n\n Ab.stop()\n\n y = math.cos(angle * 2 * math.pi / 360) * straight_distance\n x = -math.sin(angle * 2 * math.pi / 360) * straight_distance / 1.5\n return x, y\n\n\n # ini_encl = EncL\n # ini_encr = EncR\n # speed = 35\n # print(\"Starting.\")\n # time.sleep(0.5)\n #\n # k = 0.1\n #\n # Ab.forward()\n #\n # while True:\n # distance = float(EncL - ini_encl + EncL - ini_encr) / 2 / 40 * 2 * math.pi * 1\n # power_difference = abs(angle - 90)\n #\n # if angle > 90:\n # Ab.setPWMA(speed)\n # Ab.setPWMB(speed + k * power_difference)\n #\n # else:\n # Ab.setPWMA(speed + k * power_difference)\n # Ab.setPWMB(speed)\n #\n # if distance > 2 * math.pi:\n # Ab.stop()\n # break\n\n\n","sub_path":"project2/lightmove.py","file_name":"lightmove.py","file_ext":"py","file_size_in_byte":2736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"459337811","text":"def prime_list(a, b):\n # 에라토스테네스의 체 초기화: n개 요소에 True 설정(소수로 간주)\n sieve = [True] * (b+1)\n\n # n의 최대 약수가 sqrt(n) 이하이므로 i=sqrt(n)까지 검사\n m = int((b+1) ** 0.5)\n for i in range(2, m + 1):\n if sieve[i] == True: # i가 소수인 경우 \n for j in range(i+i, b+1, i): # i이후 i의 배수들을 False 판정\n sieve[j] = False\n\n # 소수 목록 산출\n if a == 1:\n return [i for i in range(a+1, b+1) if sieve[i] == True and str(D) in str(i)]\n else:\n return [i for i in range(a, b+1) if sieve[i] == True and str(D) in str(i)]\n\nT = int(input())\nfor tc in range(T):\n D, A, B = map(int, input().split())\n \n print('#{} {}'.format(tc+1, len(prime_list(A, B))))","sub_path":"swea_study/problem/D3/4698_special_prime_number.py","file_name":"4698_special_prime_number.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"408298246","text":"\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# read file\ndf_lex = pd.read_csv('data/state_lex_2020-03-27.csv', index_col=0)\ndf_lex_ny = df_lex.loc[['CA']].transpose().reset_index()\ndf_lex_ny.columns = ['abbr', 'travel_history_ny']\ndf_case = pd.read_csv('data/time_series_covid19_confirmed_US.csv')\ndf_case = df_case.groupby('Province_State')[['4/5/20']].sum().reset_index()\ndf_case.columns = ['State', 'case']\ndf_pop = pd.read_csv('data/us_population.csv')\ndf_pop = df_pop[['State', 'Pop']]\ndf_case = pd.merge(df_case, df_pop, on='State')\ndf_abbr = pd.read_csv('data/US_state_abbr.csv')\ndf_case = pd.merge(df_case, df_abbr, on='State')\ndf = pd.merge(df_case, df_lex_ny, on='abbr')\ndf['traveled_pop'] = df['Pop']*df['travel_history_ny']\ndf = df[['traveled_pop', 'case', 'abbr']]\ndf = df.set_index('abbr')\n\n# figure\nfig, ax = plt.subplots()\ndf.plot(kind='scatter',x='traveled_pop',y='case',color='red', logx=True, logy=True, ax=ax)\nax.set_xlim(1000, 100000000)\nax.set_ylim(100, 1000000)\nax.set_xlabel('#traveled to CA')\nax.set_ylabel('#confirmed cases')\nfor k, v in df.iterrows():\n ax.annotate(k, v)","sub_path":"covid19_2.py","file_name":"covid19_2.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"327814877","text":"'''15) (LIVI & EDELWEISS, 2014) Construa um programa que calcule e informe o consumo médio\nde combustível de um automóvel. Considere que o tanque é totalmente cheio em cada\nabastecimento. O programa deve receber, como entradas, a capacidade do tanque, a\nquantidade de litros abastecidos e a quilometragem percorrida desde o último abastecimento.\nSalve o projeto com o nome “​ 15_consumo_combustivel ” ​ .'''\n\ncapacidade = float(input(\"Digite a capacidade do Tanque:\"))\nkm =float(input(\"Digite o km rodado:\"))\nlitros = float(input(\"Digite a litragem do tanque:\"))\n\nprint(\"Consumo medio:\",km/(capacidade-litros))","sub_path":"15_consumo_combustivel.py","file_name":"15_consumo_combustivel.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"220164160","text":"\r\nimport tensorflow as tf\r\nimport numpy as np \r\n\r\nimport os\r\nimport sys, getopt\r\n\r\ndef load_graph(frozen_graph_filename): \r\n # We parse the graph_def file \r\n with tf.gfile.GFile(frozen_graph_filename, \"rb\") as f: \r\n graph_def = tf.GraphDef() \r\n graph_def.ParseFromString(f.read()) \r\n \r\n # We load the graph_def in the default graph \r\n with tf.Graph().as_default() as graph: \r\n tf.import_graph_def( \r\n graph_def, \r\n input_map=None, \r\n return_elements=None, \r\n name=\"\", \r\n op_dict=None, \r\n producer_op_list=None \r\n ) \r\n return graph \r\n\r\n\r\ndef read_fea(feapath):\r\n with open(feapath,'r') as fin:\r\n data=fin.readlines()\r\n return data[1].strip().split(';')[2:]\r\n\r\n\r\nfea_path='D:/xiaomin/pyproj/model_make/output_segment_0003_done.csv'\r\n\r\nfrozen_graph_filename='D:/xiaomin/pyproj/model_make/frozen_model.pb'\r\n\r\ndata=read_fea(fea_path)\r\n\r\ngraph=load_graph(frozen_graph_filename)\r\n\r\nfor op in graph.get_operations(): \r\n print(op.name,op.values()) \r\n\r\nx = graph.get_tensor_by_name('input:0') \r\ny = graph.get_tensor_by_name('predict:0')\r\n\r\nwith tf.Session(graph=graph) as sess:\r\n probability = sess.run(y, feed_dict = {x:[data]})\r\n print(probability)","sub_path":"pypro/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"19001489","text":"import numpy as np\nimport tensorflow as tf\nfrom data_process import loadTfrecords\nfrom FaceAlignmentTraining import *\nfrom scipy.integrate import simps\nSTAGE = 1\nbatch_size = 1\ntotal_img = 554\ntestSet = \"data/commonSet.npz\"\noutputsnap='model/S1_model_iter-14287'\ntfrecordsPath = 'data/train.tfrecords'\ninitmarks = np.load('data/initlandmark.npy')\ninitmarks = tf.constant(initmarks,dtype=tf.float32)\nstdDevImg = np.load(\"data/stdDevImg.npy\")\nmeanImg = np.load(\"data/meanImg.npy\")\n\nl2_scale = 5e-5\ndef LandmarkError(gtLandmarks, resLandmarks, normalization='centers', showResults=False, verbose=False):\n resLandmarks = np.reshape(resLandmarks,(68,2))\n gtLandmarks = np.reshape(gtLandmarks ,(68,2))\n if normalization == 'centers':\n normDist = np.linalg.norm(np.mean(gtLandmarks[36:42], axis=0) - np.mean(gtLandmarks[42:48], axis=0))\n elif normalization == 'corners':\n normDist = np.linalg.norm(gtLandmarks[36] - gtLandmarks[45])\n elif normalization == 'diagonal':\n height, width = np.max(gtLandmarks, axis=0) - np.min(gtLandmarks, axis=0)\n normDist = np.sqrt(width ** 2 + height ** 2)\n error = np.mean(np.sqrt(np.sum((gtLandmarks - resLandmarks)**2, axis=1))) / normDist\n return error\ndef AUCError(errors, failureThreshold, step=0.0001, showCurve=False):\n nErrors = len(errors)\n xAxis = list(np.arange(0., failureThreshold + step, step))\n ced = [float(np.count_nonzero([errors <= x])) / nErrors for x in xAxis]\n AUC = simps(ced, x=xAxis) / failureThreshold\n failureRate = 1. - ced[-1]\n print('AUC @ %.3f : %.3f'%(failureThreshold, AUC))\n print('Failure rate: %.3f'%(failureRate))\n\nimgs_batch,landmarks_batch = loadTfrecords(tfrecordsPath,batch_size)\nx = tf.placeholder(dtype=tf.float32,shape=(None,112,112,1))\ny = tf.placeholder(dtype=tf.float32,shape=(None,136))\n\ntraining = FaceAlignmnetTraining(initmarks,batch_size,STAGE)\ndan=training.createCNN(x,y,l2_scale,STAGE)\nsaver = tf.train.Saver()\n\nwith tf.Session() as sess:\n dataset = np.load(testSet)\n dataImgs = (dataset[\"imgs\"]-meanImg)/stdDevImg\n #print(dataImgs.shape)\n dataLandmarks = dataset[\"gtLandmarks\"]\n sess.run(tf.global_variables_initializer())\n saver.restore(sess,outputsnap)\n errors = []\n for i in range(total_img):\n img = dataImgs[i].reshape((1,112,112,1))\n label= dataLandmarks[i].reshape((1,136))\n if STAGE <= 1:\n pred = sess.run(dan['s1_landmarks'],feed_dict = {x:img,y:label})\n if STAGE == 2:\n pred = sess.run(dan['S2_Ret'],feed_dict = {x:img,y:label})\n error = LandmarkError(pred[0],label[0])\n errors.append(error)\n AUCError(errors,0.08,step=0.0001, showCurve=False)\n","sub_path":"testDAN.py","file_name":"testDAN.py","file_ext":"py","file_size_in_byte":2733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"111795277","text":"# Written in osX and IDLE\n# This code can be copied, changed, updated and if improved - please let me know how!!\n\nimport turtle\n#import time # and time.sleep(0.017) windows?\n\n\nclass Ball(turtle.Turtle):\n def __init__(self, paddle):\n super().__init__(shape = 'circle')\n self.color('red')\n self.dx, self.dy = 6, 4\n self.up()\n self.paddle = paddle\n\n \n def move(self):\n self.goto(self.xcor()+self.dx, self.ycor()+self.dy)\n if self.xcor()<-230 or self.xcor()>230:\n self.dx *= -1\n if self.ycor()<-320 or self.ycor()>280:\n self.dy *= -1\n\n\n def bounce(self):\n if self.xcor()+10>= self.paddle.xcor()-50 and self.xcor()-10 <= self.paddle.xcor()+50 and self.dy<0:\n if self.ycor()-10 <= self.paddle.ycor()+10 and self.ycor()-10 >= self.paddle.ycor():\n self.dy *= -1\n \n\nclass Paddle(turtle.Turtle):\n def __init__(self):\n super().__init__(shape = 'square')\n self.color('blue')\n self.up()\n self.goto(0,-200)\n self.shapesize(1,5)\n\n\n def right(self):\n if self.xcor()<220:\n self.goto(self.xcor()+40, self.ycor())\n\n \n def left(self):\n if self.xcor()>=-220:\n self.goto(self.xcor()-40, self.ycor())\n\n\nclass Scoreboard(turtle.Turtle):\n def __init__(self):\n super().__init__(shape='square')\n self.up()\n self.hideturtle()\n self.color('red')\n self.goto(0,0)\n\n \nclass Game():\n def __init__(self):\n self.win = turtle.Screen()\n self.win.setup(500,600)\n self.win.bgcolor('white')\n self.win.tracer(0)\n self.win.listen()\n self.running = True\n self.pen = Scoreboard()\n \n def new(self):\n self.paddle = Paddle()\n self.ball = Ball(self.paddle)\n self.pen.clear()\n \n\n self.run()\n\n\n def run(self):\n self.playing = True\n \n while self.playing:\n self.events()\n self.update()\n\n\n def events(self):\n self.win.onkey(self.paddle.right, 'Right')\n self.win.onkey(self.paddle.left, 'Left')\n\n\n def update(self):\n \n self.win.update()\n #time.sleep(0.017) #windows?\n \n self.ball.move()\n self.ball.bounce()\n\n # Game over:\n if self.ball.ycor()<-280:\n self.playing = False\n self.ball.goto(1000,1000) # Hiding off screen\n self.paddle.goto(1000,1000)\n self.win.update()\n\n\n def show_start_screen(self):\n self.waiting = True\n self.win.onkey(self.wait_for_keypress, 'space')\n\n while self.waiting:\n self.pen.write('Press space to start new game', align='center', font=('Courier', 24, 'normal'))\n\n\n def show_game_over_screen(self):\n self.waiting = True\n while self.waiting:\n self.pen.write('Press space to start new game', align='center', font=('Courier', 24, 'normal'))\n\n\n def wait_for_keypress(self):\n self.waiting = False\n \n\n \ngame = Game()\ngame.show_start_screen()\n\n\nwhile game.running:\n game.new()\n game.show_game_over_screen()\n\n\n\n\n \n","sub_path":"bounce Turtle with game class.py","file_name":"bounce Turtle with game class.py","file_ext":"py","file_size_in_byte":3213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"99809443","text":"import sys\r\n\r\nsys.path.append('/Users/Morakot/Dropbox/PythonWorkspace/PredictingComponent-multilabel/NCE/')\r\nsys.path.append('/Users/Morakot/Dropbox/PythonWorkspace/PredictingComponent-multilabel/Classifier/')\r\n\r\nfrom keras.models import model_from_json\r\nimport gzip\r\nimport numpy\r\nimport cPickle\r\nimport load_data\r\n\r\nfrom NCE import *\r\n\r\narg = load_data.arg_passing(sys.argv)\r\n\r\ntry:\r\n dataset = '../Dataset/Data/' + arg['-data'] + '.pkl.gz'\r\n saving = 'distance_feature/' + arg['-saving'] + '.pkl.gz'\r\nexcept:\r\n emb_dim = 100\r\n data_pretrain = 'lstm2v_apache_dim' + str(emb_dim)\r\n dataset = '/Users/Morakot/Dropbox/PythonWorkspace/PredictingComponent-multilabel/Dataset/Data/CB.pkl.gz'\r\n saving = '/Users/Morakot/Dropbox/PythonWorkspace/PredictingComponent-multilabel/NCE/distance_feature/test.pkl.gz'\r\n max_len = 100\r\n vocab_size = 5000\r\n\r\n model_path = '/Users/Morakot/Dropbox/PythonWorkspace/PredictingComponent-multilabel/NCE/models/' + data_pretrain + '.json'\r\n param_path = '/Users/Morakot/Dropbox/PythonWorkspace/PredictingComponent-multilabel/NCE/bestmodels/' + data_pretrain + '.hdf5'\r\n\r\n\r\n#### cosine distance_feature ####\r\n\r\ntrain_t, train_d, train_y, valid_t, valid_d, valid_y, test_t, test_d, test_y = load_data.load_all(dataset)\r\n\r\n\r\n# def listtostring(word_id):\r\n# str_id = []\r\n# for i in range(len(word_id)):\r\n# str_id.append(' '.join(map(str, word_id[i])))\r\n# return str_id\r\n#\r\n#\r\n# def init_list_of_objects(size):\r\n# list_of_objects = list()\r\n# for i in range(0, size):\r\n# list_of_objects.append(list()) # different object reference each time\r\n# return list_of_objects\r\n#\r\n# def fillempty(text):\r\n# for i in range(len(text)):\r\n# if text[i] == '':\r\n# text[i] = text[i-1]\r\n# return text\r\n#\r\n#\r\n# train_x = numpy.array(train_t) + numpy.array(train_d)\r\n# valid_x = numpy.array(valid_t) + numpy.array(valid_d)\r\n# test_x = numpy.array(test_t) + numpy.array(test_d)\r\n#\r\n# numberOfComponent = train_y.shape[1]\r\n#\r\n# Document = init_list_of_objects(numberOfComponent + len(train_x) + len(valid_x) + len(test_x))\r\n#\r\n# for i in range(numberOfComponent):\r\n# for j in range(len(train_x)):\r\n# if train_y[j, i] == 1:\r\n# Document[i] = Document[i] + train_x[j]\r\n#\r\n# for i in range(len(train_x)):\r\n# Document[numberOfComponent + i] = train_x[i]\r\n#\r\n# for i in range(len(valid_x)):\r\n# Document[numberOfComponent + len(train_x) + i] = valid_x[i]\r\n#\r\n# for i in range(len(test_x)):\r\n# Document[numberOfComponent + len(train_x) + len(valid_x) + i] = test_x[i]\r\n#\r\n# Document = listtostring(Document)\r\n# Document = fillempty(Document)\r\n#\r\n# print 'build tfidf matrix...'\r\n# from sklearn.feature_extraction.text import TfidfVectorizer\r\n#\r\n# tfidf_vectorizer = TfidfVectorizer(stop_words=None, lowercase=False)\r\n# tfidf_matrix = tfidf_vectorizer.fit_transform(Document)\r\n#\r\n# print 'compare cosine similairty...'\r\n# from sklearn.metrics.pairwise import cosine_similarity\r\n#\r\n# train_cos = cosine_similarity(tfidf_matrix[:numberOfComponent - 1], tfidf_matrix[numberOfComponent:len(train_x)-1])\r\n# train_cos = train_cos.transpose()\r\n#\r\n# similarity = cosine_similarity(tfidf_matrix[0:numberOfComponent - 1], tfidf_matrix[numberOfComponent:])\r\n# similarity = similarity.transpose()\r\n\r\ntrain_x = numpy.array(train_t) + numpy.array(train_d)\r\nvalid_x = numpy.array(valid_t) + numpy.array(valid_d)\r\ntest_x = numpy.array(test_t) + numpy.array(test_d)\r\n\r\n\r\ndef listtostring(word_id):\r\n str_id = []\r\n for i in range(len(word_id)):\r\n str_id.append(' '.join(map(str, word_id[i])))\r\n return str_id\r\n\r\n\r\ndef init_list_of_objects(size):\r\n list_of_objects = list()\r\n for i in range(0, size):\r\n list_of_objects.append(list()) # different object reference each time\r\n return list_of_objects\r\n\r\nnumberOfComponent = train_y.shape[1]\r\nDocument = init_list_of_objects(numberOfComponent + 1) # add one for issue\r\n\r\n#build corpus for each component\r\nfor i in range(numberOfComponent):\r\n for j in range(len(train_x)):\r\n if train_y[j, i] == 1:\r\n Document[i] = Document[i] + train_x[j]\r\n\r\nfrom sklearn.metrics.pairwise import cosine_similarity\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\n\r\ndef extractcosinefeature(Document, text):\r\n\r\n cosine_feature = numpy.zeros([len(text), numberOfComponent])\r\n corpus = listtostring(Document)\r\n\r\n tfidf_vectorizer = TfidfVectorizer(stop_words=None, lowercase=False)\r\n tfidf_matrix = tfidf_vectorizer.fit_transform(corpus)\r\n\r\n for i in range(len(text)):\r\n x = list()\r\n x.append(list())\r\n x[0] = text[i]\r\n x = listtostring(x)\r\n issue_matrix = tfidf_vectorizer.transform(x)\r\n\r\n for j in range(numberOfComponent):\r\n similarity = cosine_similarity(tfidf_matrix[j], issue_matrix) # the last array is a test issue = [numberOfComponent]\r\n cosine_feature[i, j] = similarity\r\n return cosine_feature\r\n\r\ntrain_cos = extractcosinefeature(Document, train_x)\r\nvalid_cos = extractcosinefeature(Document, valid_x)\r\ntest_cos = extractcosinefeature(Document, test_x)\r\n\r\n#########################\r\nf = gzip.open(saving, 'wb')\r\ncPickle.dump((train_cos, train_y, valid_cos, valid_y, test_cos, test_y), f)\r\nf.close()\r\n","sub_path":"NCE/cosine.py","file_name":"cosine.py","file_ext":"py","file_size_in_byte":5294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"340933023","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom numpy import testing\n\n# dyfunconn\nfrom dyfunconn.graphs import (graph_diffusion_distance,\n variation_information,\n mutual_information)\n\n\ndef test_graph_diffusion_distance():\n mtx1 = np.load(\"data/test_graphs_gdd_mtx1_5x5.npy\")\n mtx2 = np.load(\"data/test_graphs_gdd_mtx2_5x5.npy\")\n\n gdd, t = graph_diffusion_distance(mtx1, mtx2)\n\n np.testing.assert_almost_equal(gdd, 0.281495413972)\n np.testing.assert_almost_equal(t, 0.443594234747)\n\n\ndef test_variation_information():\n # mtx1 = np.load(\"data/test_graphs_vi_mtx1_30x30.npy\")\n # mtx2 = np.load(\"data/test_graphs_vi_mtx2_30x30.npy\")\n\n # Ca, Qa = bct.modularity_dir(mtx1, 2.0)\n # Cb, Qb = bct.modularity_dir(mtx2, 2.0)\n\n Ca = np.load('data/test_graphs_vi_mtx1_30x30_comm_struct.npy')\n Cb = np.load('data/test_graphs_vi_mtx2_30x30_comm_struct.npy')\n\n vi, nvi = variation_information(Ca, Cb)\n\n np.testing.assert_almost_equal(vi, 0.735803959669)\n np.testing.assert_almost_equal(nvi, 0.216336741771)\n\n\ndef test_mutual_information():\n Ca = np.load('data/test_graphs_vi_mtx1_30x30_comm_struct.npy')\n Cb = np.load('data/test_graphs_vi_mtx2_30x30_comm_struct.npy')\n\n mi, nmi = mutual_information(Ca, Cb)\n\n np.testing.assert_almost_equal(mi, 0.0115297151096)\n np.testing.assert_almost_equal(nmi, 0.0303868002153)\n","sub_path":"tests/test_graphs.py","file_name":"test_graphs.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"168435641","text":"\"\"\"\nHidden Markov Model Evolver\n\nUsage:\n fsm_evolve.py [-h] [--generations GENERATIONS] [--population POPULATION]\n [--mu MUTATION_RATE] [--bottleneck BOTTLENECK] [--processes PROCESSORS]\n [--output OUTPUT_FILE] [--objective OBJECTIVE] [--repetitions REPETITIONS]\n [--turns TURNS] [--noise NOISE] [--nmoran NMORAN]\n [--states NUM_STATES]\n\nOptions:\n -h --help Show help\n --generations GENERATIONS Generations to run the EA [default: 500]\n --population POPULATION Population size [default: 40]\n --mu MUTATION_RATE Mutation rate [default: 0.1]\n --bottleneck BOTTLENECK Number of individuals to keep from each generation [default: 10]\n --processes PROCESSES Number of processes to use [default: 1]\n --output OUTPUT_FILE File to write data to [default: hmm_params.csv]\n --objective OBJECTIVE Objective function [default: score]\n --repetitions REPETITIONS Repetitions in objective [default: 100]\n --turns TURNS Turns in each match [default: 200]\n --noise NOISE Match noise [default: 0.00]\n --nmoran NMORAN Moran Population Size, if Moran objective [default: 4]\n --states NUM_STATES Number of FSM states [default: 5]\n\"\"\"\n\n#####\n# This is a potential candidate for PSO optimization, which will require\n# combining the matrices.\n#####\n\nimport random\nfrom random import randrange, choice\n\nfrom docopt import docopt\nimport numpy as np\n\nfrom axelrod import Action\nfrom axelrod.strategies.hmm import HMMPlayer\nfrom axelrod_dojo import Params, Population, prepare_objective\n\nC, D = Action.C, Action.D\n\n\ndef copy_lists(rows):\n new_rows = list(map(list, rows))\n return new_rows\n\ndef random_vector(size):\n \"\"\"Create a random vector of values in [0, 1] that sums to 1.\"\"\"\n vector = []\n s = 1\n for _ in range(size - 1):\n r = s * random.random()\n vector.append(r)\n s -= r\n vector.append(s)\n return vector\n\ndef normalize_vector(vec):\n s = sum(vec)\n vec = [v / s for v in vec]\n return vec\n\ndef mutate_row(row, mutation_rate):\n randoms = np.random.random(len(row))\n for i in range(len(row)):\n if randoms[i] < mutation_rate:\n ep = random.uniform(-1, 1) / 4\n row[i] += ep\n if row[i] < 0:\n row[i] = 0\n if row[i] > 1:\n row[i] = 1\n return row\n\n\nclass HMMParams(Params):\n\n def __init__(self, num_states, mutation_rate=None, transitions_C=None,\n transitions_D=None, emission_probabilities=None,\n initial_state=0, initial_action=C):\n self.PlayerClass = HMMPlayer\n self.num_states = num_states\n if mutation_rate is None:\n self.mutation_rate = 10 / (num_states ** 2)\n else:\n self.mutation_rate = mutation_rate\n if transitions_C is None:\n self.randomize()\n else:\n # Make sure to copy the lists\n self.transitions_C = copy_lists(transitions_C)\n self.transitions_D = copy_lists(transitions_D)\n self.emission_probabilities = list(emission_probabilities)\n self.initial_state = initial_state\n self.initial_action = initial_action\n\n\n def player(self):\n player = self.PlayerClass(self.transitions_C, self.transitions_D,\n self.emission_probabilities,\n self.initial_state, self.initial_action)\n return player\n\n def copy(self):\n return HMMParams(self.num_states, self.mutation_rate,\n self.transitions_C, self.transitions_D,\n self.emission_probabilities,\n self.initial_state, self.initial_action)\n\n @staticmethod\n def random_params(num_states):\n t_C = []\n t_D = []\n for _ in range(num_states):\n t_C.append(random_vector(num_states))\n t_D.append(random_vector(num_states))\n initial_state = randrange(num_states)\n # initial_action = choice([C, D])\n initial_action = C\n return t_C, t_D, initial_state, initial_action\n\n def randomize(self):\n t_C, t_D, initial_state, initial_action = self.random_params(self.num_states)\n self.emission_probabilities = [random.random() for _ in range(self.num_states)]\n self.transitions_C = t_C\n self.transitions_D = t_D\n self.initial_state = initial_state\n self.initial_action = initial_action\n\n @staticmethod\n def mutate_rows(rows, mutation_rate):\n for i, row in enumerate(rows):\n row = mutate_row(row, mutation_rate)\n rows[i] = normalize_vector(row)\n return rows\n\n def mutate(self):\n self.transitions_C = self.mutate_rows(\n self.transitions_C, self.mutation_rate)\n self.transitions_D = self.mutate_rows(\n self.transitions_D, self.mutation_rate)\n self.emission_probabilities = mutate_row(\n self.emission_probabilities, self.mutation_rate)\n if random.random() < self.mutation_rate / 10:\n self.initial_action = self.initial_action.flip()\n if random.random() < self.mutation_rate / (10 * self.num_states):\n self.initial_state = randrange(self.num_states)\n # Change node size?\n\n @staticmethod\n def crossover_rows(rows1, rows2):\n num_states = len(rows1)\n crosspoint = randrange(num_states)\n new_rows = copy_lists(rows1[:crosspoint])\n new_rows += copy_lists(rows2[crosspoint:])\n return new_rows\n\n @staticmethod\n def crossover_weights(w1, w2):\n crosspoint = random.randrange(len(w1))\n new_weights = list(w1[:crosspoint]) + list(w2[crosspoint:])\n return new_weights\n\n def crossover(self, other):\n # Assuming that the number of states is the same\n t_C = self.crossover_rows(self.transitions_C, other.transitions_C)\n t_D = self.crossover_rows(self.transitions_D, other.transitions_D)\n emissions = self.crossover_weights(\n self.emission_probabilities, other.emission_probabilities)\n return HMMParams(self.num_states, self.mutation_rate,\n t_C, t_D, emissions,\n self.initial_state, self.initial_action)\n\n @staticmethod\n def repr_rows(rows):\n ss = []\n for row in rows:\n ss.append(\"_\".join(list(map(str, row))))\n return \"|\".join(ss)\n\n def __repr__(self):\n return \"{}:{}:{}:{}:{}\".format(\n self.initial_state,\n self.initial_action,\n self.repr_rows(self.transitions_C),\n self.repr_rows(self.transitions_D),\n self.repr_rows([self.emission_probabilities])\n )\n\n @classmethod\n def parse_repr(cls, s):\n def parse_matrix(sm):\n rows = []\n lines = sm.split('|')\n for line in lines:\n row = line.split('_')\n row = list(map(float, row))\n rows.append(row)\n return row\n lines = s.split(':')\n initial_state = int(lines[0])\n initial_action = lines[1]\n t_C = parse_matrix(lines[2])\n t_D = parse_matrix(lines[3])\n ps = parse_matrix(lines[4])\n return cls(t_C, t_D, ps, initial_state, initial_action)\n\n\nif __name__ == '__main__':\n arguments = docopt(__doc__, version='HMM Evolver 0.3')\n print(arguments)\n processes = int(arguments['--processes'])\n\n # Vars for the genetic algorithm\n population = int(arguments['--population'])\n mutation_probability = float(arguments['--mu'])\n generations = int(arguments['--generations'])\n bottleneck = int(arguments['--bottleneck'])\n output_filename = arguments['--output']\n\n # Objective\n name = str(arguments['--objective'])\n repetitions = int(arguments['--repetitions'])\n turns = int(arguments['--turns'])\n noise = float(arguments['--noise'])\n nmoran = int(arguments['--nmoran'])\n\n # FSM\n num_states = int(arguments['--states'])\n param_kwargs = {\"num_states\": num_states}\n\n objective = prepare_objective(name, turns, noise, repetitions, nmoran)\n population = Population(HMMParams, param_kwargs, population, objective,\n output_filename, bottleneck,\n mutation_probability,\n processes=processes)\n population.run(generations)\n","sub_path":"bin/hmm_evolve.py","file_name":"hmm_evolve.py","file_ext":"py","file_size_in_byte":8486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"212560195","text":"# This file is part of the pyMOR project (http://www.pymor.org).\n# Copyright 2013-2017 pyMOR developers and contributors. All rights reserved.\n# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n\nimport numpy as np\n\nfrom pymor.core.interfaces import ImmutableInterface\nfrom pymor.operators.constructions import LincombOperator, induced_norm\nfrom pymor.operators.numpy import NumpyMatrixOperator\nfrom pymor.reductors.basic import GenericRBReductor\nfrom pymor.reductors.residual import ResidualReductor\nfrom pymor.vectorarrays.numpy import NumpyVectorSpace\n\n\nclass CoerciveRBReductor(GenericRBReductor):\n \"\"\"Reduced Basis reductor for |StationaryDiscretizations| with coercive linear operator.\n\n The only addition to :class:`~pymor.reductors.basic.GenericRBReductor` is an error\n estimator which evaluates the dual norm of the residual with respect to a given inner\n product. For the reduction of the residual we use\n :class:`~pymor.reductors.residual.ResidualReductor` for improved numerical stability\n [BEOR14]_.\n\n .. [BEOR14] A. Buhr, C. Engwer, M. Ohlberger, S. Rave, A Numerically Stable A\n Posteriori Error Estimator for Reduced Basis Approximations of Elliptic\n Equations, Proceedings of the 11th World Congress on Computational\n Mechanics, 2014.\n\n Parameters\n ----------\n d\n The |Discretization| which is to be reduced.\n RB\n |VectorArray| containing the reduced basis on which to project.\n orthogonal_projection\n List of keys in `d.operators` for which the corresponding |Operator|\n should be orthogonally projected (i.e. operators which map to vectors in\n contrast to bilinear forms which map to functionals).\n product\n Inner product for the projection of the |Operators| given by\n `orthogonal_projection` and for the computation of Riesz representatives\n of the residual. If `None`, the Euclidean product is used.\n coercivity_estimator\n `None` or a |Parameterfunctional| returning a lower bound for the coercivity\n constant of the given problem. Note that the computed error estimate is only\n guaranteed to be an upper bound for the error when an appropriate coercivity\n estimate is specified.\n \"\"\"\n\n def __init__(self, d, RB=None, orthogonal_projection=('initial_data',), product=None,\n coercivity_estimator=None):\n super().__init__(d, RB,\n orthogonal_projection=orthogonal_projection,\n product=product)\n self.coercivity_estimator = coercivity_estimator\n self.residual_reductor = ResidualReductor(self.RB, self.d.operator, self.d.rhs,\n product=product)\n\n def _reduce(self):\n with self.logger.block('RB projection ...'):\n rd = super()._reduce()\n\n with self.logger.block('Assembling error estimator ...'):\n residual = self.residual_reductor.reduce()\n\n estimator = CoerciveRBEstimator(residual, tuple(self.residual_reductor.residual_range_dims),\n self.coercivity_estimator)\n rd = rd.with_(estimator=estimator)\n\n return rd\n\n\nclass CoerciveRBEstimator(ImmutableInterface):\n \"\"\"Instantiated by :class:`CoerciveRBReductor`.\n\n Not to be used directly.\n \"\"\"\n\n def __init__(self, residual, residual_range_dims, coercivity_estimator):\n self.residual = residual\n self.residual_range_dims = residual_range_dims\n self.coercivity_estimator = coercivity_estimator\n\n def estimate(self, U, mu, d):\n est = self.residual.apply(U, mu=mu).l2_norm()\n if self.coercivity_estimator:\n est /= self.coercivity_estimator(mu)\n return est\n\n def restricted_to_subbasis(self, dim, d):\n if self.residual_range_dims:\n residual_range_dims = self.residual_range_dims[:dim + 1]\n residual = self.residual.projected_to_subbasis(residual_range_dims[-1], dim)\n return CoerciveRBEstimator(residual, residual_range_dims, self.coercivity_estimator)\n else:\n self.logger.warning('Cannot efficiently reduce to subbasis')\n return CoerciveRBEstimator(self.residual.projected_to_subbasis(None, dim), None,\n self.coercivity_estimator)\n\n\nclass SimpleCoerciveRBReductor(GenericRBReductor):\n \"\"\"Reductor for linear |StationaryDiscretizations| with affinely decomposed operator and rhs.\n\n .. note::\n The reductor :class:`CoerciveRBReductor` can be used for arbitrary coercive\n |StationaryDiscretizations| and offers an improved error estimator\n with better numerical stability.\n\n The only addition is to :class:`~pymor.reductors.basic.GenericRBReductor` is an error\n estimator, which evaluates the norm of the residual with respect to a given inner product.\n\n Parameters\n ----------\n d\n The |Discretization| which is to be reduced.\n RB\n |VectorArray| containing the reduced basis on which to project.\n orthogonal_projection\n List of keys in `d.operators` for which the corresponding |Operator|\n should be orthogonally projected (i.e. operators which map to vectors in\n contrast to bilinear forms which map to functionals).\n product\n Inner product for the projection of the |Operators| given by\n `orthogonal_projection` and for the computation of Riesz representatives\n of the residual. If `None`, the Euclidean product is used.\n coercivity_estimator\n `None` or a |Parameterfunctional| returning a lower bound for the coercivity\n constant of the given problem. Note that the computed error estimate is only\n guaranteed to be an upper bound for the error when an appropriate coercivity\n estimate is specified.\n \"\"\"\n\n def __init__(self, d, RB=None, orthogonal_projection=('initial_data',), product=None,\n coercivity_estimator=None):\n assert d.linear\n assert isinstance(d.operator, LincombOperator)\n assert all(not op.parametric for op in d.operator.operators)\n if d.rhs.parametric:\n assert isinstance(d.rhs, LincombOperator)\n assert all(not op.parametric for op in d.rhs.operators)\n\n super().__init__(d, RB,\n orthogonal_projection=orthogonal_projection,\n product=product)\n self.coercivity_estimator = coercivity_estimator\n self.residual_reductor = ResidualReductor(self.RB, self.d.operator, self.d.rhs,\n product=product)\n self.extends = None\n\n def _reduce(self):\n d, RB, extends = self.d, self.RB, self.extends\n rd = super()._reduce()\n if extends:\n old_RB_size = extends[0]\n old_data = extends[1]\n else:\n old_RB_size = 0\n\n # compute data for estimator\n space = d.operator.source\n\n # compute the Riesz representative of (U, .)_L2 with respect to product\n def riesz_representative(U):\n if self.product is None:\n return U.copy()\n else:\n return self.product.apply_inverse(U)\n\n def append_vector(U, R, RR):\n RR.append(riesz_representative(U), remove_from_other=True)\n R.append(U, remove_from_other=True)\n\n # compute all components of the residual\n if extends:\n R_R, RR_R = old_data['R_R'], old_data['RR_R']\n elif not d.rhs.parametric:\n R_R = space.empty(reserve=1)\n RR_R = space.empty(reserve=1)\n append_vector(d.rhs.as_source_array(), R_R, RR_R)\n else:\n R_R = space.empty(reserve=len(d.rhs.operators))\n RR_R = space.empty(reserve=len(d.rhs.operators))\n for op in d.rhs.operators:\n append_vector(op.as_source_array(), R_R, RR_R)\n\n if len(RB) == 0:\n R_Os = [space.empty()]\n RR_Os = [space.empty()]\n elif not d.operator.parametric:\n R_Os = [space.empty(reserve=len(RB))]\n RR_Os = [space.empty(reserve=len(RB))]\n for i in range(len(RB)):\n append_vector(-d.operator.apply(RB[i]), R_Os[0], RR_Os[0])\n else:\n R_Os = [space.empty(reserve=len(RB)) for _ in range(len(d.operator.operators))]\n RR_Os = [space.empty(reserve=len(RB)) for _ in range(len(d.operator.operators))]\n if old_RB_size > 0:\n for op, R_O, RR_O, old_R_O, old_RR_O in zip(d.operator.operators, R_Os, RR_Os,\n old_data['R_Os'], old_data['RR_Os']):\n R_O.append(old_R_O)\n RR_O.append(old_RR_O)\n for op, R_O, RR_O in zip(d.operator.operators, R_Os, RR_Os):\n for i in range(old_RB_size, len(RB)):\n append_vector(-op.apply(RB[i]), R_O, RR_O)\n\n # compute Gram matrix of the residuals\n R_RR = RR_R.dot(R_R)\n R_RO = np.hstack([RR_R.dot(R_O) for R_O in R_Os])\n R_OO = np.vstack([np.hstack([RR_O.dot(R_O) for R_O in R_Os]) for RR_O in RR_Os])\n\n estimator_matrix = np.empty((len(R_RR) + len(R_OO),) * 2)\n estimator_matrix[:len(R_RR), :len(R_RR)] = R_RR\n estimator_matrix[len(R_RR):, len(R_RR):] = R_OO\n estimator_matrix[:len(R_RR), len(R_RR):] = R_RO\n estimator_matrix[len(R_RR):, :len(R_RR)] = R_RO.T\n\n estimator_matrix = NumpyMatrixOperator(estimator_matrix)\n\n estimator = SimpleCoerciveRBEstimator(estimator_matrix, self.coercivity_estimator)\n rd = rd.with_(estimator=estimator)\n\n self.extends = (len(RB), dict(R_R=R_R, RR_R=RR_R, R_Os=R_Os, RR_Os=RR_Os))\n\n return rd\n\n\nclass SimpleCoerciveRBEstimator(ImmutableInterface):\n \"\"\"Instantiated by :class:`SimpleCoerciveRBReductor`.\n\n Not to be used directly.\n \"\"\"\n\n def __init__(self, estimator_matrix, coercivity_estimator):\n self.estimator_matrix = estimator_matrix\n self.coercivity_estimator = coercivity_estimator\n self.norm = induced_norm(estimator_matrix)\n\n def estimate(self, U, mu, d):\n if len(U) > 1:\n raise NotImplementedError\n if not d.rhs.parametric:\n CR = np.ones(1)\n else:\n CR = np.array(d.rhs.evaluate_coefficients(mu))\n\n if not d.operator.parametric:\n CO = np.ones(1)\n else:\n CO = np.array(d.operator.evaluate_coefficients(mu))\n\n C = np.hstack((CR, np.dot(CO[..., np.newaxis], U.data).ravel()))\n\n est = self.norm(NumpyVectorSpace.make_array(C))\n if self.coercivity_estimator:\n est /= self.coercivity_estimator(mu)\n\n return est\n\n def restricted_to_subbasis(self, dim, d):\n cr = 1 if not d.rhs.parametric else len(d.rhs.operators)\n co = 1 if not d.operator.parametric else len(d.operator.operators)\n old_dim = d.operator.source.dim\n\n indices = np.concatenate((np.arange(cr),\n ((np.arange(co)*old_dim)[..., np.newaxis] + np.arange(dim)).ravel() + cr))\n matrix = self.estimator_matrix.matrix[indices, :][:, indices]\n\n return SimpleCoerciveRBEstimator(NumpyMatrixOperator(matrix), self.coercivity_estimator)\n","sub_path":"src/pymor/reductors/coercive.py","file_name":"coercive.py","file_ext":"py","file_size_in_byte":11431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"591445832","text":"import re\n\npatron = re.compile(r'[A-Za-z][0-9]+([,][0-9]+)*$')\n\nwhile True:\n input = raw_input(\"Enter a command or valid expression: \")\n\n if input == \"break\":\n break\n else:\n if patron.match(input):\n char = input[0]\n digits = input[1:]\n\n if digits.find(','):\n digits = digits.split(',')\n\n print (\"Your char was {} and your digits were: \".format(char))\n print (digits)\n else:\n print(\"Invalid expression or command\")\n","sub_path":"regular_expressions.py","file_name":"regular_expressions.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"78655041","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2020/7/23 0023 9:34\n# @Author : Zhang YP\n# @Email : 1579922399@qq.com\n# @github : Aaron Ramsey\n# @File : init_station_report.py\n\n\n\"\"\"\n初始化站点数据:\n 去除列名中的空格\n 填充空白值\n 重命名\n 修改列名数据类型\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\n\nfrom my_toolkit import public_function,process_files,commonly_params,change_rate\n\n\n# 站点列名\nstation_columns_dict = {\n 'cp': ['Record ID', 'Record Type', 'Campaign ID', 'Campaign', 'Campaign Daily Budget', 'Portfolio ID',\n 'Campaign Start Date', 'Campaign End Date', 'Campaign Targeting Type', 'Ad Group', 'Max Bid',\n 'Keyword or Product Targeting', 'Product Targeting ID', 'Match Type', 'SKU', 'Campaign Status',\n 'Ad Group Status', 'Status', 'Impressions', 'Clicks', 'Spend', 'Orders', 'Total Units', 'Sales', 'ACoS',\n 'Bidding strategy', 'Placement Type', 'Increase bids by placement'],\n 'bd': ['Record ID', 'Record Type', 'Campaign ID', 'Campaign', 'Campaign Daily Budget', 'Portfolio ID',\n 'Campaign Start Date', 'Campaign End Date', 'Budget Type', 'Landing Page Url', 'Landing Page ASINs',\n 'Brand Name', 'Brand Entity ID', 'Brand Logo Asset ID', 'Headline', 'Creative ASINs', 'Automated Bidding',\n 'Bid Multiplier', 'Ad Group', 'Max Bid',\n 'Keyword', 'Match Type', 'Campaign Status', 'Serving Status',\n 'Ad Group Status', 'Status', 'Impressions', 'Clicks', 'Spend', 'Orders', 'Total Units', 'Sales', 'ACoS',\n 'Placement Type']}\n\n\ndef strip_space(data):\n \"\"\"\n 站点五表都需要进行初始化\n 列名去掉空格\n Args:\n data:pd.DataFrame\n 站点数据\n Returns:pd.DataFrame\n 初始化后的站点数据\n\n \"\"\"\n # 1.删除列名中的空格\n data.columns = [column.strip() for column in data.columns]\n # 2.删除全部数据的空格\n data = data.applymap(lambda x: x.strip() if isinstance(x, str) else x)\n return data\n\n\ndef fill_value(data, report_type, fill_type='ffill'):\n \"\"\"\n 站点填充空白值\n Args:\n data:pd.DataFrame\n 站点列表数据\n report_type:str\n 报表类型\n fill_type:str default ffill\n 站点列表类型\n\n Returns:pd.DataFrame\n\n \"\"\"\n # 处理广告报表\n if report_type in ['cp', 'bd']:\n process_columns = ['Max Bid','Campaign Targeting Type']\n for col in process_columns:\n if col in data.columns:\n data[col].fillna(method=fill_type, inplace=True)\n numerical_process_columns = ['Impressions', 'Clicks', 'Spend', 'Orders', 'Total Units', 'Sales']\n for col in numerical_process_columns:\n if col in data.columns:\n data[col].fillna(value=0, inplace=True)\n\n\ndef rename_columns(data, report_type):\n \"\"\"\n 修改站点列名\n Args:\n report_type:str\n 站点类型\n data: pd.DataFrame\n 站点数据\n\n Returns:pd.DataFrame\n\n \"\"\"\n # 修改广告报表列名\n # 首先检测报表列名是否有效\n if report_type == 'cp':\n data.rename(columns={'Total units': 'Total Units'}, inplace=True)\n columns = data.columns\n if not set(columns).issubset(set(station_columns_dict['cp'])):\n new_col = set(columns) - set(station_columns_dict['cp'])\n raise ValueError(f'cp report have new col:{new_col}')\n if report_type == 'ac':\n data.rename(columns={'出品者SKU': 'seller-sku', 'ASIN 1': 'asin1', '卖家 SKU': 'seller-sku', 'ASIN1': 'asin1','商品名':'item-name',\n '出品日': 'open-date', '価格': 'price', '价格': 'price', '开售日期': 'open-date','数量':'quantity',\n '配送渠道': 'fulfillment-channel','フルフィルメント・チャンネル':'fulfillment-channel','fulfilment-channel':'fulfillment-channel'},\n inplace=True)\n if report_type == 'br':\n data.rename(columns={'已订购商品销售额': 'Ordered Product Sales','(Child) ASIN': 'ASIN'},inplace=True)\n multiStringRename = {col:col.title() for col in data.columns if ' ' in col}\n data.rename(columns=multiStringRename,inplace=True)\n if report_type == 'bd':\n data.rename(columns={'Total units': 'Total Units'}, inplace=True)\n # columns = data.columns\n # if not set(columns).issubset(set(station_columns_dict['bd'])):\n # new_col = set(columns) - set(station_columns_dict['bd'])\n # raise ValueError(f'bd report have new col:{new_col}')\n if report_type == 'st':\n replace_str = ['(#)', '(£)', '($)', '(₹)']\n for re_str in replace_str:\n data.columns = [col.replace(re_str, '') for col in data.columns]\n data.columns = [col.strip() for col in data.columns]\n data.rename(columns={'Advertising Cost of Sales (ACoS)': 'Total Advertising Cost of Sales (ACoS)',\n 'Return on Advertising Spend (RoAS)': 'Total Return on Advertising Spend (RoAS)'},\n inplace=True)\n\n\ndef trans_columns_type(data, report_type):\n \"\"\"\n 修改站点中列的数据类型\n Args:\n data: pd.DataFrame\n 站点数据\n report_type: str\n 报表类型\n\n Returns:pd.DataFrame\n\n \"\"\"\n # 广告报表中广告产品报表和品牌报表需要处理的列为:\n # int: Impressions,Clicks,Orders,Total units\n # float:Spend,Sales,Max Bid\n if report_type in ['cp', 'bd']:\n int_columns = ['Impressions', 'Clicks', 'Orders', 'Total Units']\n for col in int_columns:\n if not isinstance(data[col].values[0], (np.int64, np.int32)):\n data[col] = data[col].apply(lambda x: public_function.trans_into_numerical(x))\n float_columns = ['Spend', 'Sales', 'Max Bid']\n for col in float_columns:\n if not isinstance(data[col].values[0], (np.float64, np.float32)):\n data[col] = data[col].apply(lambda x: public_function.trans_into_numerical(x, type='float', point=2))\n if report_type in ['ac']:\n float_columns = ['price']\n for col in float_columns:\n if not isinstance(data[col].values[0], (np.float64, np.float32)):\n data[col] = data[col].apply(lambda x: public_function.trans_into_numerical(x, type='float', point=2))\n if report_type in ['br']:\n float_columns = ['Ordered Product Sales']\n for col in float_columns:\n if not isinstance(data[col].values[0], (np.float64, np.float32)):\n data[col] = data[col].apply(lambda x: public_function.trans_into_numerical(x, type='float', point=2))\n\n\ndef change_currency(data, report_type, site, currency_columns=None, currency='local', point_keep=2):\n # 修改报表货币列表\n # 获取汇率\n rate_dict = change_rate.change_current()\n exchange_rate = rate_dict[site]\n if currency == 'local':\n pass\n elif currency == 'dollar':\n if report_type == 'cp':\n if currency_columns is None:\n currency_columns = ['Spend', 'Sales']\n for col in currency_columns:\n data[col] = data[col].apply(lambda x: round(exchange_rate*x, point_keep) if pd.notna(x) else 0)\n\n\ndef init_report(data, report_type):\n \"\"\"\n 初始化站点数据\n 去除列名中的空格\n ��充空白值\n 重命名\n 修改列名数据类型\n 填充丢失列\n Args:\n data: pd.DataFrame\n 站点报表数据\n report_type: str\n 站点报表类型:\n\n Returns:\n\n \"\"\"\n if not public_function.is_valid_df(data):\n return\n if report_type not in commonly_params.station_report_type:\n raise ValueError(f'ERROR FILE TYPE.Input type must be one of {commonly_params.station_report_type}')\n # 1.去除列中的空格和数据中的空格\n data = strip_space(data)\n # 2.重命名\n rename_columns(data, report_type)\n # 3.填充空白值\n fill_value(data, report_type)\n # 4.修改列的数据类型\n trans_columns_type(data, report_type)\n return data\n","sub_path":"my_toolkit/init_station_report.py","file_name":"init_station_report.py","file_ext":"py","file_size_in_byte":8257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"57479453","text":"#!/usr/bin/env python\n# coding: utf-8\n\nfrom ams import Waypoint, Arrow, Route\nfrom ams.nodes import FleetManager\n\nWAYPOINT_FILE = \"../../res/waypoint.json\"\nARROW_FILE = \"../../res/arrow.json\"\nROUTE_FILE = \"../../res/route.json\"\n\nif __name__ == '__main__':\n waypoint = Waypoint()\n waypoint.load(WAYPOINT_FILE)\n\n arrow = Arrow(waypoint)\n arrow.load(ARROW_FILE)\n\n route = Route()\n route.set_waypoint(waypoint)\n route.set_arrow(arrow)\n try:\n route.load(ROUTE_FILE)\n except:\n print(\"no\", ROUTE_FILE)\n\n fleetManager = FleetManager(waypoint, arrow, route)\n fleetManager.start(host=\"localhost\", port=1883)\n","sub_path":"examples/node_launchers/fleet_manager.py","file_name":"fleet_manager.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"184726420","text":"# coding: utf-8\nfrom __future__ import print_function, division, absolute_import\nimport gzip\nimport os\nimport random\nimport sys\nfrom nose.tools import raises\nfrom cutadapt.xopen import xopen, lzma\nfrom .utils import temporary_path\n\nbase = \"tests/data/small.fastq\"\nfiles = [ base + ext for ext in ['', '.gz', '.bz2' ] ]\nif lzma is not None:\n\tfiles.append(base + '.xz')\n\ndef test_context_manager():\n\tmajor, minor = sys.version_info[0:2]\n\tfor name in files:\n\t\tif major == 2 and minor == 6:\n\t\t\tcontinue # Py26 compression libraries do not support context manager protocol.\n\t\twith xopen(name, 'rt') as f:\n\t\t\tlines = list(f)\n\t\t\tassert len(lines) == 12\n\t\t\tassert lines[5] == 'AGCCGCTANGACGGGTTGGCCCTTAGACGTATCT\\n', name\n\t\t\tf.close()\n\ndef test_append():\n\tfor ext in [\"\", \".gz\"]: # BZ2 does NOT support append\n\t\ttext = \"AB\"\n\t\tif ext != \"\":\n\t\t\ttext = text.encode(\"utf-8\") # On Py3, need to send BYTES, not unicode\n\t\treference = text + text\n\t\tprint(\"Trying ext=%s\" % ext)\n\t\twith temporary_path('truncated.fastq' + ext) as path:\n\t\t\ttry:\n\t\t\t\tos.unlink(path)\n\t\t\texcept OSError:\n\t\t\t\tpass\n\t\t\twith xopen(path, 'a') as f:\n\t\t\t\tf.write(text)\n\t\t\twith xopen(path, 'a') as f:\n\t\t\t\tf.write(text)\n\t\t\twith xopen(path, 'r') as f:\n\t\t\t\tfor appended in f:\n\t\t\t\t\tpass\n\t\t\t\ttry:\n\t\t\t\t\treference = reference.decode(\"utf-8\")\n\t\t\t\texcept AttributeError:\n\t\t\t\t\tpass\n\t\t\t\tprint(appended)\n\t\t\t\tprint(reference)\n\t\t\t\tassert appended == reference\n\ndef test_xopen_text():\n\tfor name in files:\n\t\tf = xopen(name, 'rt')\n\t\tlines = list(f)\n\t\tassert len(lines) == 12\n\t\tassert lines[5] == 'AGCCGCTANGACGGGTTGGCCCTTAGACGTATCT\\n', name\n\t\tf.close()\n\n\ndef test_xopen_binary():\n\tfor name in files:\n\t\tf = xopen(name, 'rb')\n\t\tlines = list(f)\n\t\tassert len(lines) == 12\n\t\tassert lines[5] == b'AGCCGCTANGACGGGTTGGCCCTTAGACGTATCT\\n', name\n\t\tf.close()\n\n\ndef create_truncated_file(path):\n\t# Random text\n\ttext = ''.join(random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ') for _ in range(200))\n\tf = xopen(path, 'w')\n\tf.write(text)\n\tf.close()\n\tf = open(path, 'a')\n\tf.truncate(os.stat(path).st_size - 10)\n\tf.close()\n\n\n# Disable these tests in Python 3.2 and 3.3\nif not ((3, 2) <= sys.version_info[:2] <= (3, 3)):\n\t@raises(EOFError)\n\tdef test_truncated_gz():\n\t\twith temporary_path('truncated.gz') as path:\n\t\t\tcreate_truncated_file(path)\n\t\t\tf = xopen(path, 'r')\n\t\t\tf.read()\n\t\t\tf.close()\n\n\n\t@raises(EOFError)\n\tdef test_truncated_gz_iter():\n\t\twith temporary_path('truncated.gz') as path:\n\t\t\tcreate_truncated_file(path)\n\t\t\tf = xopen(path, 'r')\n\t\t\tfor line in f:\n\t\t\t\tpass\n\t\t\tf.close()\n","sub_path":"tests/testxopen.py","file_name":"testxopen.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"245339749","text":"'''Base functions for file reading'''\nimport gzip\nimport unlzw\n\ndef _lzw2bytes(path):\n '''Decompresses .Z file and outputs the content.\n Memory leak corrected in the github repo v0.1.2'''\n with open(path,'rb') as lzw_file:\n lzw_compressed = lzw_file.read()\n databytes = unlzw.unlzw(lzw_compressed)\n del lzw_compressed\n return databytes\n\ndef _gz2bytes(path):\n '''Decompresses .gz file and outputs bytes content'''\n with gzip.open(filename=path,mode='rb') as gz_file:\n databytes = gz_file.read()\n return databytes\n\ndef _txt2bytes(path):\n '''Simple file read function'''\n with open(path,'rb') as file:\n databytes = file.read()\n return databytes\n\ndef path2bytes(path):\n '''Main file reading function.'''\n if path.endswith('.Z'):\n databytes = _lzw2bytes(path)\n elif path.endswith('.gz'):\n databytes = _gz2bytes(path)\n else:\n databytes = _txt2bytes(path)\n return databytes\n","sub_path":"scripts/gn_lib/gn_io/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"430722392","text":"# map function \n \nnumbers = [1,2,3,4]\n \n #normal function\ndef square(a):\n return a**2\n\n#procederal way\nnew_list = []\nfor num in numbers:\n new_list.append(square(num))\n \nprint(new_list)\n\n #lamda expression\nsquares = list(map(lambda a:a**2, numbers))\nprint(squares)\n \n# list comp \nsquares_new = [i**2 for i in numbers]\nprint(squares_new)\n \n\n \nnames = ['abc', 'abcd', 'abcde']\nlengths_map = map(len, names) # on map object you can iterate it once. \nlength = list(lengths_map) # its better to convert it in list so that you can iterate more than once\n\nprint(lengths_map)\nprint(length)","sub_path":"detailed-exercises/82-map-function.py","file_name":"82-map-function.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"572613021","text":"from django.urls import include, path\n\nfrom django.conf.urls.i18n import i18n_patterns\nfrom django.conf import settings\nfrom django.contrib import admin\n\n\nadmin.autodiscover()\n\n\n# SIMPLE PATTERNS\nurlpatterns = [\n path(\n 'tac/',\n include('tac.urls')\n )\n]\n\n# i18n PATTERNS\nurlpatterns += i18n_patterns(\n path(\n 'admin/',\n admin.site.urls\n ),\n path(\n '',\n include('cms.urls')\n ),\n)\n\n\n# STATIC AND MEDIA FILES FOR DEBUG\nif settings.DEBUG:\n from django.conf.urls.static import static\n from django.contrib.staticfiles.urls import staticfiles_urlpatterns\n urlpatterns += staticfiles_urlpatterns(settings.STATIC_URL)\n urlpatterns += static(\n settings.MEDIA_URL,\n document_root=settings.MEDIA_ROOT\n )\n","sub_path":"testproject/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"238501131","text":"import unittest\n\nfrom pages.main_page import MainPage\nfrom pages.vacancies_page import VacanciesPage\nfrom pages.vacancy_page import VacancyPage\nfrom scenario.auth import setup_auth, auth_as_employer_has_comp\nfrom tests.default_setup import default_setup\nfrom scenario.auth import setup_auth, auth_as_employer_has_comp, auth_as_applicant\nfrom scenario.registration_applicant import registration_applicant\nfrom scenario.registration_applicant import RegistrationApplicantScenario\nfrom scenario.vacancy import VacancyScenario\n\n\nclass CheckRecommendations(unittest.TestCase):\n\n def setUp(self) -> None:\n default_setup(self)\n self.PROFESSION = \"Воспитатель\"\n self.mainPage = MainPage(self.driver)\n self.vacanciesPage = VacanciesPage(self.driver)\n self.vacancyPage = VacancyPage(self.driver)\n self.mainPage.open()\n\n def test_vacancy_open_on_click(self):\n auth_as_applicant(self)\n self.mainPage.click_recommendations()\n self.assertTrue(self.vacanciesPage.is_open())\n self.vacanciesPage.click_on_first_vacancy()\n self.assertTrue(self.vacancyPage.is_open())\n\n def tearDown(self):\n self.driver.quit()\n\n\nclass CheckRecommendationsCreate(unittest.TestCase):\n def setUp(self) -> None:\n default_setup(self)\n self.PROFESSION = \"Воспитатель\"\n self.mainPage = MainPage(self.driver)\n self.vacanciesPage = VacanciesPage(self.driver)\n self.vacancyPage = VacancyPage(self.driver)\n self.mainPage.open()\n self.Applicant = RegistrationApplicantScenario(self)\n self.data = self.Applicant.registration_applicant()\n\n def test_vacancy_equiv_on_click(self):\n self.mainPage.search_by_profession(self.PROFESSION)\n self.vacanciesPage.click_on_first_vacancy()\n name = self.vacancyPage.get_vacancy_name()\n self.mainPage.open()\n self.mainPage.click_recommendations()\n self.assertTrue(self.vacanciesPage.check_vacancies_exists_by_name(name))\n\n def tearDown(self):\n self.Applicant.delete_applicant()\n self.driver.quit()","sub_path":"tests/vacancy/check_recommendation.py","file_name":"check_recommendation.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"235497993","text":"import graphreader\nimport graphplotter\nimport sys\nimport json\n\nRED = '#e53935'\nBLUE = '#1e88e5'\nGREEN = '#43a047'\nPURPLE = '#8e24aa'\nGRAY = '#DEDEDE'\nCYAN = '#00acc1'\nBLACK = '#000000'\nHIGHLIGHT_COLOR= RED\n\n\nname = 'unnamed'\nfolder = sys.argv[1]\n\nif(len(sys.argv) <= 2): \n\tpropsfile = open(folder + 'properties.json')\n\tpropsJ = json.load(propsfile)\n\tname = propsJ['name']\nelse:\n\tname = sys.argv[2]\n\ng = graphreader.createGraph(folder)\nedgeColors = [GRAY for e in g.es]\ncuts = []\n\n\ncutFile = open(folder + 'intersections/intersections.csv')\nfor line in cutFile:\n\tsl = line.split(' ')\n\tcuts.append([int(sl[0]), int(sl[1]), int(sl[2]), int(sl[3])])\n\nfor cut in range(0, len(cuts)):\n\ttheCut = cuts[cut]\n\tedgeId = g.get_eid(theCut[0], theCut[1])\n\tedgeColors[edgeId] = HIGHLIGHT_COLOR\n\tedgeId = g.get_eid(theCut[2], theCut[3])\n\tedgeColors[edgeId] = HIGHLIGHT_COLOR\n\ng.es[\"color\"] = edgeColors\ngraphplotter.plotGraph(g, folder + '/intersections/', name, None)","sub_path":"graph-visualization/plot_intersections.py","file_name":"plot_intersections.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"432553746","text":"# ============================================================================\r\n# File: test00_debugging.py\r\n# ------------------------------\r\n#\r\n# Notes:\r\n#\r\n# Layout:\r\n# configure and prepare\r\n#\r\n# Status:\r\n# in progress\r\n#\r\n# ============================================================================\r\n\r\n\r\nimport sys\r\nimport time\r\nimport logging\r\nimport numpy as np\r\nfrom measurement import measurement\r\nfrom devices import ke2410 # power supply\r\nfrom devices import ke2450 # volt meter\r\nfrom devices import hp4980 # lcr meter\r\nfrom devices import switchcard # switch\r\n\r\n\r\nclass test00_debugging(measurement):\r\n \"\"\"A test on communication and functionality\"\"\"\r\n\r\n def initialise(self):\r\n #self.logging.info(\"\\t\")\r\n self.logging.info(\"\\t\")\r\n self.logging.info(\"------------------------------------------\")\r\n self.logging.info(\"Debugging\")\r\n self.logging.info(\"------------------------------------------\")\r\n self.logging.info(self.__doc__)\r\n self.logging.info(\"\\t\")\r\n\r\n self._initialise()\r\n self.pow_supply_address = 24\r\n self.volt_meter_address = 16\r\n self.lcr_meter_address = 17\r\n self.switch_address = 'COM3'\r\n\r\n self.lim_cur = 0.0001\r\n self.lim_vol = 100\r\n self.cell_list = range(1, 10, 1)\r\n self.volt_list = [1, 5, 10]\r\n\r\n self.delay_vol = 10\r\n self.delay_ch = 0.4\r\n\r\n self.test_vol = 0.5\r\n self.test_freq = 1E4\r\n\r\n self.mode = 0\r\n\r\n if self.mode == 0:\r\n self.logging.info(\"Note: A general test on software functionality.\")\r\n self.logging.info(\"\\t\")\r\n\r\n elif self.mode == 1:\r\n self.logging.info(\"Note: A test of communication.\")\r\n self.logging.info(\"\\t\")\r\n self.logging.info(\"Settings:\")\r\n self.logging.info(\"Power supply voltage limit: %.2fV\" % self.lim_vol)\r\n self.logging.info(\"Power supply current limit: %.6fA\" % self.lim_cur)\r\n self.logging.info(\"Volt meter voltage limit: %.2fV\" % self.lim_vol)\r\n self.logging.info(\"Volt meter current limit: %.6fA\" % self.lim_cur)\r\n self.logging.info(\"LCR meter test voltage: %.2fV\" % self.test_vol)\r\n self.logging.info(\"LCR meter test frequency: %.0fHz\" % self.test_freq)\r\n self.logging.info(\"Voltage Delay: %.2fs\" % self.delay_vol)\r\n self.logging.info(\"Channel Delay: %.2fs\" % self.delay_ch)\r\n self.logging.info(\"\\t\")\r\n\r\n elif self.mode == 2:\r\n self.logging.info(\"Note: A test to ramp voltage.\")\r\n self.logging.info(\"\\t\")\r\n self.logging.info(\"Settings:\")\r\n self.logging.info(\"Power supply voltage limit: %.2fV\" % self.lim_vol)\r\n self.logging.info(\"Power supply current limit: %.6fA\" % self.lim_cur)\r\n self.logging.info(\"Volt meter voltage limit: %.2fV\" % self.lim_vol)\r\n self.logging.info(\"Volt meter current limit: %.6fA\" % self.lim_cur)\r\n self.logging.info(\"LCR meter test voltage: %.2fV\" % self.test_vol)\r\n self.logging.info(\"LCR meter test frequency: %.0fHz\" % self.test_freq)\r\n self.logging.info(\"Voltage Delay: %.2fs\" % self.delay_vol)\r\n self.logging.info(\"Channel Delay: %.2fs\" % self.delay_ch)\r\n self.logging.info(\"\\t\")\r\n\r\n elif self.mode == 3:\r\n self.logging.info(\"Note: A test for the switch card.\")\r\n self.logging.info(\"\\t\")\r\n\r\n else:\r\n self.logging.info(\"Nothing happening in this mode.\")\r\n\r\n\r\n\r\n def execute(self):\r\n\r\n ## Test functionality\r\n if self.mode == 0:\r\n\r\n ## Header\r\n hd = [\r\n 'Debugging\\n',\r\n 'Measurement Settings:',\r\n '\\n\\n',\r\n 'X[-]\\tY[-]'\r\n ]\r\n\r\n ## Print Info\r\n for line in hd[1:-2]:\r\n self.logging.info(line)\r\n self.logging.info(\"\\t\")\r\n self.logging.info(\"\\t\")\r\n self.logging.info(hd[-1])\r\n self.logging.info(\"-\" * int(1.2 * len(hd[-1])))\r\n\r\n ## Prepare\r\n out = []\r\n\r\n ## Create fake data\r\n try:\r\n for i in range(1, 10):\r\n line = [i, i**2, 0.1]\r\n out.append(line)\r\n time.sleep(0.1)\r\n self.logging.info(\"{:<5.2E}\\t{: <5.2E}\".format(*line))\r\n\r\n except KeyboardInterrupt:\r\n self.logging.error(\"Keyboard interrupt. Ramping down voltage and shutting down.\")\r\n\r\n ## Save and print\r\n self.logging.info(\"\\t\")\r\n self.logging.info(\"\\t\")\r\n self.save_list(out, \"out.dat\", fmt=\"%4d\", header=\"\\n\".join(hd))\r\n self.print_graph(np.array(out)[:, 0], np.array(out)[:, 1], np.array(out)[:, 2], 'x', 'y', 'Test Data', fn=\"out.png\")\r\n\r\n\r\n ## Test communication\r\n elif self.mode == 1:\r\n\r\n ## Set up power supply\r\n pow_supply = ke2410(self.pow_supply_address)\r\n pow_supply.reset()\r\n pow_supply.set_source('voltage')\r\n pow_supply.set_sense('current')\r\n pow_supply.set_current_limit(self.lim_cur)\r\n pow_supply.set_voltage(0)\r\n pow_supply.set_terminal('rear')\r\n pow_supply.set_output_on()\r\n\r\n ## Set up volt meter\r\n volt_meter = ke2450(self.volt_meter_address)\r\n volt_meter.reset()\r\n volt_meter.set_source('voltage')\r\n volt_meter.set_sense('current')\r\n volt_meter.set_current_range(1E-4)\r\n volt_meter.set_voltage(0)\r\n volt_meter.set_output_on()\r\n\r\n ## Set up lcr meter\r\n lcr_meter = hp4980(self.lcr_meter_address)\r\n lcr_meter.reset()\r\n lcr_meter.set_voltage(self.test_vol)\r\n lcr_meter.set_frequency(self.test_freq)\r\n lcr_meter.set_mode('CPRP')\r\n\r\n for v in self.volt_list:\r\n pow_supply.ramp_voltage(v)\r\n time.sleep(1)\r\n\r\n vol = pow_supply.read_voltage()\r\n cur = pow_supply.read_current()\r\n cap, res = lcr_meter.execute_measurement()\r\n cur_tot = pow_supply.read_current()\r\n\r\n self.logging.info(\"vol %E, cur %E, cap %E, cur_tot %E\" % (vol, cur, cap, cur_tot))\r\n\r\n ## Close connections\r\n pow_supply.set_output_off()\r\n pow_supply.reset()\r\n volt_meter.set_output_off()\r\n volt_meter.reset()\r\n\r\n\r\n ## Test ramping of voltage\r\n elif self.mode == 2:\r\n\r\n ## Set up power supply\r\n pow_supply = ke2410(self.pow_supply_address)\r\n pow_supply.reset()\r\n pow_supply.set_source('voltage')\r\n pow_supply.set_sense('current')\r\n pow_supply.set_current_limit(self.lim_cur)\r\n pow_supply.set_voltage(0)\r\n pow_supply.set_terminal('rear')\r\n pow_supply.set_output_on()\r\n\r\n ## Set up volt meter\r\n volt_meter = ke2001(self.volt_meter_address)\r\n volt_meter.reset()\r\n volt_meter.setup_ammeter(nplc=10, dig=9)\r\n\r\n try:\r\n for v in [-5, -1, 0, 1, 5, 10, 25, 50]:\r\n pow_supply.ramp_voltage(v, debug=1)\r\n time.sleep(1)\r\n\r\n vol = pow_supply.read_voltage()\r\n cur = volt_meter.read_current()\r\n cur_tot = pow_supply.read_current()\r\n\r\n self.logging.info(\"vol %E, cur_tot %E\" % (vol, cur_tot))\r\n\r\n except KeyboardInterrupt:\r\n pow_supply.ramp_voltage(0)\r\n self.logging.error(\"Keyboard interrupt. Ramping down voltage and shutting down.\")\r\n\r\n ## Close connections\r\n pow_supply.ramp_voltage(0, debug=1)\r\n pow_supply.set_output_off()\r\n pow_supply.reset()\r\n\r\n\r\n ## Test switchcard\r\n if self.mode == 3:\r\n\r\n ## Set up switch\r\n switch = switchcard(self.switch_address)\r\n switch.reboot()\r\n switch.set_display_mode('ON')\r\n\r\n self.logging.info(\"\\t\")\r\n self.logging.info(\"Channel Set [-]\\tChannel Read [-]\")\r\n self.logging.info(\"-----------------\")\r\n self.logging.info(\"\\t\")\r\n\r\n try:\r\n init = time.time()\r\n for i in self.cell_list:\r\n switch.open_channel(i)\r\n ch = switch.get_channel()\r\n t = time.time() - init\r\n if ch == i:\r\n self.logging.info(\"\\t%.3f \\t%d \\t%d\" % (t, i, ch))\r\n else:\r\n self.logging.warning(\"\\t%.3f \\t%d \\t%d\" % (t, i, ch))\r\n\r\n except KeyboardInterrupt:\r\n self.logging.error(\"Keyboard interrupt. Ramping down voltage and shutting down.\")\r\n\r\n ## Save and print\r\n self.logging.info(\"\\t\")\r\n self.logging.info(\"\\t\")\r\n\r\n\r\n else:\r\n pass\r\n\r\n\r\n def finalise(self):\r\n self._finalise()\r\n","sub_path":"measurements/test00_debugging.py","file_name":"test00_debugging.py","file_ext":"py","file_size_in_byte":9355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"36403432","text":"\"\"\"\nNIH report specs models\n\"\"\"\n\nfrom django.db import models\nfrom django.db.models.signals import post_save, m2m_changed\n\nfrom gsd.utils.unique_boolean_field import UniqueBooleanField\nfrom gsd.department.models import Department\nfrom gsd.graduate_program.models import GraduateProgram\n\n\nclass NIHReportingParameters(models.Model):\n \"\"\"NIH reporting parameters\"\"\"\n\n name = models.CharField(max_length=255,\n help_text='helpful name for Grad program admins')\n is_active = UniqueBooleanField()\n programs_to_include = models.ManyToManyField(\n GraduateProgram,\n help_text='Used for Tables 5A, 6A.')\n home_departments_to_include = models.ManyToManyField(\\\n Department,\n help_text='Usually all of them')\n graduation_cutoff_date = models.DateField(\\\n help_text=('Exclude trainees who graduated before this date.'\n ' Usually 10 years. Used in Table 5A/6A. Example:' '\"2003-07-01\"'))\n min_start_year_cutoff = models.IntegerField(\\\n help_text=('Exclude trainees who started BEFORE this year.'\n ' Example: \"2001\"'))\n max_start_year_cutoff = models.IntegerField(\\\n help_text=('Exclude trainees who started AFTER this year.'\n ' Used in Table5a. Example: \"2012\"'))\n applicant_year_to_check = models.IntegerField(\\\n help_text=('For Table 8a - \"Qualifications of Recent Predoctoral'\n ' Applicants\". Example: \"2013\"'))\n mark_epb_program = models.BooleanField(\\\n 'Mark EPB program in reports',\n default=False,\n help_text=('Used for 2013 competitive renewal, when EPB was a'\n ' program, not a track. Mark used for EPB was \"***\"'))\n program_ids = models.TextField(\\\n blank=True,\n help_text=('auto-filled on save, create list of'\n ' program ids'))\n home_department_ids = models.TextField(\\\n blank=True,\n help_text=('auto-filled on save, create list of home'\n ' department ids'))\n predoc_15_year_cutoff = models.DateField(\\\n help_text=('Exclude trainees who graduated or left the'\n ' program before this date 15 years ago.'\n ' Used in Table 8A.'))\n program_stat_start_year = models.IntegerField(\\\n help_text=('4-digit year to use for 2017 Table 8A, Part IV Report'))\n notes = models.TextField(blank=True, help_text='optional')\n date_added = models.DateTimeField(auto_now_add=True,\n help_text='auto-filled')\n date_modified = models.DateTimeField(auto_now=True,\n help_text='auto-filled')\n\n def get_program_ids(self):\n \"\"\"get program ids\"\"\"\n if self.program_ids:\n return eval(self.program_ids)\n return None\n\n def get_home_department_ids(self):\n \"\"\"get home department ids\"\"\"\n if self.home_department_ids:\n return eval(self.home_department_ids)\n return None\n\n @staticmethod\n def load_program_ids(sender, **kwargs):\n \"\"\"load program ids\"\"\"\n nih_params = kwargs.get('instance', None)\n if nih_params is None:\n return\n\n pids = nih_params.programs_to_include.all().values_list('id', flat=True)\n if pids:\n pid_string = ','.join([str(x) for x in pids])\n nih_params.program_ids = '[%s]' % pid_string\n else:\n nih_params.program_ids = '[]'\n\n # avoid infinite loop\n post_save.disconnect(NIHReportingParameters.load_program_ids, sender=NIHReportingParameters)\n nih_params.save()\n post_save.connect(NIHReportingParameters.load_program_ids, sender=NIHReportingParameters)\n\n\n @staticmethod\n def load_home_dept_ids(sender, **kwargs):\n \"\"\"load home dept ids\"\"\"\n nih_params = kwargs.get('instance', None)\n if nih_params is None:\n return\n\n hids = nih_params.home_departments_to_include.all().values_list('id', flat=True)\n if hids:\n hid_string = ','.join([str(x) for x in hids])\n nih_params.home_department_ids = '[%s]' % hid_string\n else:\n nih_params.home_department_ids = '[]'\n\n # avoid infinite loop\n post_save.disconnect(NIHReportingParameters.load_home_dept_ids, sender=NIHReportingParameters)\n nih_params.save()\n post_save.connect(NIHReportingParameters.load_home_dept_ids, sender=NIHReportingParameters)\n\n @staticmethod\n def get_params():\n \"\"\"get params\"\"\"\n try:\n return NIHReportingParameters.objects.get(is_active=True)\n except NIHReportingParameters.DoesNotExist:\n raise Exception(\"No active NIH Reporting Parameters found! (NIHReportingParameters models)\")\n except:\n raise Exception(\"Failed to retrieve active NIH Reporting Parameters! (NIHReportingParameters models)\")\n\n def __str__(self):\n return self.name\n\n class Meta:\n ordering = ('is_active', 'name')\n verbose_name = 'NIH Reporting Parameters'\n verbose_name_plural = verbose_name\n\nm2m_changed.connect(NIHReportingParameters.load_program_ids\\\n , sender=NIHReportingParameters.programs_to_include.through)\nm2m_changed.connect(NIHReportingParameters.load_home_dept_ids\\\n , sender=NIHReportingParameters.home_departments_to_include.through)\n","sub_path":"gsd/nih_report_specs/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"175944000","text":"import math\n\ndef latlng2xy(lat, lng, zoom):\n if abs(lat) > 85.0511287798066:\n return False\n sin_phi = math.sin(lat * math.pi / 180)\n norm_x = lng / 180\n norm_y = (0.5 * math.log((1 + sin_phi) / (1 - sin_phi))) / math.pi\n tileRow = pow(2, zoom) * ((1 - norm_y) / 2)\n tileColumn = pow(2, zoom) * ((norm_x + 1) / 2)\n\n #tileColumn : x\n #tileRow : y\n return [math.floor(tileColumn), math.floor(tileRow)]\n\n#print(latlng2xy(-20.7972014, -61.171875, 8))","sub_path":"latlng2xy.py","file_name":"latlng2xy.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"191459514","text":"from bearlibterminal import terminal as t\n\nfrom entity import Entity\nfrom actor import Actor\nfrom player import Player\nfrom enemy import Enemy\n\nfrom typing import List\n\n_world : 'World' = None\n\n_log = []\n\ndef log(msg):\n global _log\n _log.append(msg)\n\nclass World:\n def __init__(self):\n self.entities : List[Entity] = []\n \n self.act_index = 0\n \n self.player = self.add(Player(16, 18))\n \n self.add(Enemy(90, 14))\n self.add(Enemy(90, 18))\n self.add(Enemy(90, 22))\n \n self.turn = 0\n \n @staticmethod\n def set(world : 'World'):\n global _world\n _world = world\n \n @staticmethod\n def get() -> 'World':\n global _world\n return _world\n \n def add(self, e):\n self.entities.append(e)\n return e\n \n def get_at(self, x, y):\n return [e for e in self.entities if e.x == x and e.y == y]\n \n def draw(self, delay=False):\n t.clear()\n \n draw_list = sorted([e for e in self.entities if not e.destroyed], key = lambda x: x.level)\n \n t.composition(t.TK_ON)\n for e in draw_list:\n e.draw()\n \n t.bkcolor('transparent')\n t.color('white')\n t.composition(t.TK_OFF)\n \n hud_width = 20\n hud_height = 6\n \n t.bkcolor('darkest gray')\n t.color('white')\n t.clear_area(0, 0, t.state(t.TK_WIDTH), hud_height)\n \n t.puts(0, 0, f\"HP: {self.player.hp:>3}/{self.player.max_hp:<3}\", width=hud_width)\n #t.puts(0, 1, f\"HP: {self.player.hp:>3}/{self.player.max_hp:<3}\")\n t.puts(0, 2, f\"T: {self.turn/1000:.2f} seconds\", width=hud_width)\n for i in range(hud_height):\n t.put(hud_width, i, '|')\n \n y = 0\n for i in range(max(0, len(_log)-hud_height), len(_log)):\n t.puts(hud_width + 2, y, _log[i])\n y+=1\n #t.puts(0, 4, f\"E: {len(self.entities)}\")\n \n w = t.state(t.TK_WIDTH)\n h = t.state(t.TK_HEIGHT)\n \n t.bkcolor('transparent')\n t.color('white')\n \n for e in draw_list:\n e.hud(self.entities[self.act_index] == e)\n \n t.bkcolor('transparent')\n t.color('white')\n \n if self.player not in self.entities:\n t.puts(w//2-len(\"YOU DIED\")//2, h//2, \"YOU DIED\")\n \n t.refresh()\n if delay:\n t.delay(1)\n \n def update(self, key):\n self.key = key\n \n for e in self.entities:\n e.update()\n \n for e in self.entities:\n if e.destroyed:\n self.entities.remove(e)\n \n self.tick()\n \n def tick(self):\n start_actor = None\n \n while True:\n if self.player not in self.entities:\n self.draw()\n break\n \n actor = self.entities[self.act_index]\n if actor == start_actor:\n self.key = None\n self.turn+=1\n self.draw(True)\n elif not start_actor:\n start_actor = actor\n \n if hasattr(actor, 'act'):\n if actor.startup > 0:\n actor.startup -= 1\n if actor.startup <= 0:\n actor.action.execute(actor, *actor.action_args)\n \n #actor.action = None\n \n actor.tick()\n self.act_index += 1\n elif actor.recovery > 0:\n actor.recovery -= 1\n \n if actor.recovery <= 0:\n actor.action = None\n \n actor.tick()\n self.act_index += 1\n else:\n action_array = actor.act(self.key)\n if not action_array:\n break\n else:\n name = action_array[0]\n if name == 'wait':\n actor.recovery = action_array[1]\n if name == 'move':\n actor.move(action_array[1], action_array[2])\n import random\n actor.recovery = 100\n if name == 'action':\n actor.action_args = action_array[2:]\n actor.action = action_array[1]\n actor.startup = actor.action.startup\n actor.recovery = actor.action.recovery\n actor.recovery -= 1\n \n actor.tick()\n self.act_index += 1\n else:\n actor.tick()\n self.act_index += 1\n \n self.act_index %= len(self.entities)\n \n def end(self):\n from main import end\n end()","sub_path":"world.py","file_name":"world.py","file_ext":"py","file_size_in_byte":5069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"221606538","text":"import numpy as np\nimport pytest\n\nfrom pandas import DataFrame, Index, MultiIndex, Series, concat, date_range\nimport pandas._testing as tm\nimport pandas.core.common as com\n\n\n@pytest.fixture\ndef four_level_index_dataframe():\n arr = np.array(\n [\n [-0.5109, -2.3358, -0.4645, 0.05076, 0.364],\n [0.4473, 1.4152, 0.2834, 1.00661, 0.1744],\n [-0.6662, -0.5243, -0.358, 0.89145, 2.5838],\n ]\n )\n index = MultiIndex(\n levels=[[\"a\", \"x\"], [\"b\", \"q\"], [10.0032, 20.0, 30.0], [3, 4, 5]],\n codes=[[0, 0, 1], [0, 1, 1], [0, 1, 2], [2, 1, 0]],\n names=[\"one\", \"two\", \"three\", \"four\"],\n )\n return DataFrame(arr, index=index, columns=list(\"ABCDE\"))\n\n\n@pytest.mark.parametrize(\n \"key, level, exp_arr, exp_index\",\n [\n (\"a\", \"lvl0\", lambda x: x[:, 0:2], Index([\"bar\", \"foo\"], name=\"lvl1\")),\n (\"foo\", \"lvl1\", lambda x: x[:, 1:2], Index([\"a\"], name=\"lvl0\")),\n ],\n)\ndef test_xs_named_levels_axis_eq_1(key, level, exp_arr, exp_index):\n # see gh-2903\n arr = np.random.randn(4, 4)\n index = MultiIndex(\n levels=[[\"a\", \"b\"], [\"bar\", \"foo\", \"hello\", \"world\"]],\n codes=[[0, 0, 1, 1], [0, 1, 2, 3]],\n names=[\"lvl0\", \"lvl1\"],\n )\n df = DataFrame(arr, columns=index)\n result = df.xs(key, level=level, axis=1)\n expected = DataFrame(exp_arr(arr), columns=exp_index)\n tm.assert_frame_equal(result, expected)\n\n\ndef test_xs_values(multiindex_dataframe_random_data):\n df = multiindex_dataframe_random_data\n result = df.xs((\"bar\", \"two\")).values\n expected = df.values[4]\n tm.assert_almost_equal(result, expected)\n\n\ndef test_xs_loc_equality(multiindex_dataframe_random_data):\n df = multiindex_dataframe_random_data\n result = df.xs((\"bar\", \"two\"))\n expected = df.loc[(\"bar\", \"two\")]\n tm.assert_series_equal(result, expected)\n\n\ndef test_xs_missing_values_in_index():\n # see gh-6574\n # missing values in returned index should be preserved\n acc = [\n (\"a\", \"abcde\", 1),\n (\"b\", \"bbcde\", 2),\n (\"y\", \"yzcde\", 25),\n (\"z\", \"xbcde\", 24),\n (\"z\", None, 26),\n (\"z\", \"zbcde\", 25),\n (\"z\", \"ybcde\", 26),\n ]\n df = DataFrame(acc, columns=[\"a1\", \"a2\", \"cnt\"]).set_index([\"a1\", \"a2\"])\n expected = DataFrame(\n {\"cnt\": [24, 26, 25, 26]},\n index=Index([\"xbcde\", np.nan, \"zbcde\", \"ybcde\"], name=\"a2\"),\n )\n\n result = df.xs(\"z\", level=\"a1\")\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\"key, level\", [(\"one\", \"second\"), ([\"one\"], [\"second\"])])\ndef test_xs_with_duplicates(key, level, multiindex_dataframe_random_data):\n # see gh-13719\n frame = multiindex_dataframe_random_data\n df = concat([frame] * 2)\n assert df.index.is_unique is False\n expected = concat([frame.xs(\"one\", level=\"second\")] * 2)\n\n result = df.xs(key, level=level)\n tm.assert_frame_equal(result, expected)\n\n\ndef test_xs_level(multiindex_dataframe_random_data):\n df = multiindex_dataframe_random_data\n result = df.xs(\"two\", level=\"second\")\n expected = df[df.index.get_level_values(1) == \"two\"]\n expected.index = Index([\"foo\", \"bar\", \"baz\", \"qux\"], name=\"first\")\n tm.assert_frame_equal(result, expected)\n\n\ndef test_xs_level_eq_2():\n arr = np.random.randn(3, 5)\n index = MultiIndex(\n levels=[[\"a\", \"p\", \"x\"], [\"b\", \"q\", \"y\"], [\"c\", \"r\", \"z\"]],\n codes=[[2, 0, 1], [2, 0, 1], [2, 0, 1]],\n )\n df = DataFrame(arr, index=index)\n expected = DataFrame(arr[1:2], index=[[\"a\"], [\"b\"]])\n result = df.xs(\"c\", level=2)\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n \"indexer\",\n [\n lambda df: df.xs((\"a\", 4), level=[\"one\", \"four\"]),\n lambda df: df.xs(\"a\").xs(4, level=\"four\"),\n ],\n)\ndef test_xs_level_multiple(indexer, four_level_index_dataframe):\n df = four_level_index_dataframe\n expected_values = [[0.4473, 1.4152, 0.2834, 1.00661, 0.1744]]\n expected_index = MultiIndex(\n levels=[[\"q\"], [20.0]], codes=[[0], [0]], names=[\"two\", \"three\"]\n )\n expected = DataFrame(expected_values, index=expected_index, columns=list(\"ABCDE\"))\n result = indexer(df)\n tm.assert_frame_equal(result, expected)\n\n\ndef test_xs_setting_with_copy_error(multiindex_dataframe_random_data):\n # this is a copy in 0.14\n df = multiindex_dataframe_random_data\n result = df.xs(\"two\", level=\"second\")\n\n # setting this will give a SettingWithCopyError\n # as we are trying to write a view\n msg = \"A value is trying to be set on a copy of a slice from a DataFrame\"\n with pytest.raises(com.SettingWithCopyError, match=msg):\n result[:] = 10\n\n\ndef test_xs_setting_with_copy_error_multiple(four_level_index_dataframe):\n # this is a copy in 0.14\n df = four_level_index_dataframe\n result = df.xs((\"a\", 4), level=[\"one\", \"four\"])\n\n # setting this will give a SettingWithCopyError\n # as we are trying to write a view\n msg = \"A value is trying to be set on a copy of a slice from a DataFrame\"\n with pytest.raises(com.SettingWithCopyError, match=msg):\n result[:] = 10\n\n\ndef test_xs_integer_key():\n # see gh-2107\n dates = range(20111201, 20111205)\n ids = list(\"abcde\")\n index = MultiIndex.from_product([dates, ids], names=[\"date\", \"secid\"])\n df = DataFrame(np.random.randn(len(index), 3), index, [\"X\", \"Y\", \"Z\"])\n\n result = df.xs(20111201, level=\"date\")\n expected = df.loc[20111201, :]\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n \"indexer\", [lambda df: df.xs(\"a\", level=0), lambda df: df.xs(\"a\")]\n)\ndef test_xs_level0(indexer, four_level_index_dataframe):\n df = four_level_index_dataframe\n expected_values = [\n [-0.5109, -2.3358, -0.4645, 0.05076, 0.364],\n [0.4473, 1.4152, 0.2834, 1.00661, 0.1744],\n ]\n expected_index = MultiIndex(\n levels=[[\"b\", \"q\"], [10.0032, 20.0], [4, 5]],\n codes=[[0, 1], [0, 1], [1, 0]],\n names=[\"two\", \"three\", \"four\"],\n )\n expected = DataFrame(expected_values, index=expected_index, columns=list(\"ABCDE\"))\n\n result = indexer(df)\n tm.assert_frame_equal(result, expected)\n\n\ndef test_xs_level_series(multiindex_dataframe_random_data):\n # this test is not explicitly testing .xs functionality\n # TODO: move to another module or refactor\n df = multiindex_dataframe_random_data\n s = df[\"A\"]\n result = s[:, \"two\"]\n expected = df.xs(\"two\", level=1)[\"A\"]\n tm.assert_series_equal(result, expected)\n\n\ndef test_xs_level_series_ymd(multiindex_year_month_day_dataframe_random_data):\n # this test is not explicitly testing .xs functionality\n # TODO: move to another module or refactor\n df = multiindex_year_month_day_dataframe_random_data\n s = df[\"A\"]\n result = s[2000, 5]\n expected = df.loc[2000, 5][\"A\"]\n tm.assert_series_equal(result, expected)\n\n\ndef test_xs_level_series_slice_not_implemented(\n multiindex_year_month_day_dataframe_random_data,\n):\n # this test is not explicitly testing .xs functionality\n # TODO: move to another module or refactor\n # not implementing this for now\n df = multiindex_year_month_day_dataframe_random_data\n s = df[\"A\"]\n\n msg = r\"\\(2000, slice\\(3, 4, None\\)\\)\"\n with pytest.raises(TypeError, match=msg):\n s[2000, 3:4]\n\n\ndef test_series_getitem_multiindex_xs():\n # GH6258\n dt = list(date_range(\"20130903\", periods=3))\n idx = MultiIndex.from_product([list(\"AB\"), dt])\n s = Series([1, 3, 4, 1, 3, 4], index=idx)\n expected = Series([1, 1], index=list(\"AB\"))\n\n result = s.xs(\"20130903\", level=1)\n tm.assert_series_equal(result, expected)\n\n\ndef test_series_getitem_multiindex_xs_by_label():\n # GH5684\n idx = MultiIndex.from_tuples(\n [(\"a\", \"one\"), (\"a\", \"two\"), (\"b\", \"one\"), (\"b\", \"two\")]\n )\n s = Series([1, 2, 3, 4], index=idx)\n s.index.set_names([\"L1\", \"L2\"], inplace=True)\n expected = Series([1, 3], index=[\"a\", \"b\"])\n expected.index.set_names([\"L1\"], inplace=True)\n\n result = s.xs(\"one\", level=\"L2\")\n tm.assert_series_equal(result, expected)\n","sub_path":"Botnets/App/App Web/PDG-env/lib/python3.6/site-packages/pandas/tests/indexing/multiindex/test_xs.py","file_name":"test_xs.py","file_ext":"py","file_size_in_byte":8046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"200220195","text":"#from distutils.core import setup, Extension\nfrom setuptools import setup, find_packages\nfrom setuptools.extension import Extension\nfrom Cython.Build import cythonize\n\nfrom datetime import datetime\nfrom platform import system, os\nimport numpy\n\ncpp_stdlib = \"libc++\"\n\nextra_compile_args = [\n \"-std=c++11\", ## Compile C++11 code\n ## Add include directories\n \"-I/usr/local/include\",\n \"-I/usr/include\",\n # \"-I./source\",\n \"-I{0}\".format(numpy.get_include()),\n# \"-flto\",\n \"-D_GLIBCXX_USE_CXX11_ABI=0\" # Cython/GCC5 issues\n ## Link-time optimization\n]\n\nextra_link_args = [\n \"-std=c++11\", ## Link C++11 code\n \"-D_GLIBCXX_USE_CXX11_ABI=0\" # Cython/GCC5 issues\n]\n\nif system() == \"Darwin\":\n # Set minimum target to 10.7 (supports C++11/libc++)\n os.environ[\"MACOSX_DEPLOYMENT_TARGET\"] = \"10.9\"\n extra_compile_args += [ \"-stdlib={0}\".format(cpp_stdlib) ]\n\n\nsetup(\n name=\"pytrafficmodel\",\n packages=find_packages(),\n version='{d.year}.{d.month}.{d.day}'.format(d=datetime.now()), # trust me on this one\n \n ext_modules = cythonize(Extension(\n \"PedestrianCrowding.pytrafficmodel\", # the extension name\n sources=[\"PedestrianCrowding/pytrafficmodel.pyx\"], # the Cython source and\n # additional C++ source files\n language=\"c++\", # generate and compile C++ code\n extra_compile_args=extra_compile_args,\n extra_link_args=extra_link_args), \n language_level=3\n ))\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"270202724","text":"from datetime import date, datetime, timedelta\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = \"https://github.com/users/DumbMachine/contributions?to={}\"\ndef datespan(startDate, endDate, delta=timedelta(days=1)):\n currentDate = startDate\n while currentDate < endDate:\n yield currentDate\n currentDate += delta\ntotal = 0\nweekly_data = []\nfor day in datespan(date(2018, 1, 1), date(2018, 12, 31),delta=timedelta(days=7)):\n headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36'}\n res = requests.get(url.format(str(day)),headers=headers)\n soup = BeautifulSoup(res.text,'lxml')\n selector = \"body > div.js-yearly-contributions > div:nth-child(1) > h2\"\n selector = selector.replace(\"nth-child\",\"nth-of-type\")\n content = soup.select(selector)\n contri = str(content[0])\n contributions = contri[contri.find(\">\")+2:contri.rfind(\"<\")-1].split()[0]\n total+= int(contributions)\n weekly_data.append(total)\n print(len(weekly_data))","sub_path":"app/helpers/week.py","file_name":"week.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"280358947","text":"\"\"\"\ntblS9EmergencyResponses.csv\n\"\"\"\nfrom django.db import models\nfrom rmp.fields import (\n CopyFromBooleanField,\n CopyFromCharField,\n CopyFromDateTimeField,\n CopyFromDecimalField,\n CopyFromIntegerField,\n CopyFromForeignKey,\n)\nfrom rmp.models.base import BaseRMPModel\n\n\nclass Tbls9Emergencyresponses(BaseRMPModel):\n facilityid = CopyFromForeignKey(\n 'Tbls1Facilities',\n on_delete=models.PROTECT,\n )\n er_communityplan = CopyFromBooleanField()\n er_facilityplan = CopyFromBooleanField()\n er_responseactions = CopyFromBooleanField()\n er_publicinfoprocedures = CopyFromBooleanField()\n er_emergencyhealthcare = CopyFromBooleanField()\n er_reviewdate = CopyFromDateTimeField(blank=True)\n ertrainingdate = CopyFromDateTimeField(blank=True)\n coordinatingagencyname = CopyFromCharField(max_length=250, blank=True)\n coordinatingagencyphone = CopyFromCharField(max_length=10, blank=True)\n fr_osha1910_38 = CopyFromBooleanField()\n fr_osha1910_120 = CopyFromBooleanField()\n fr_spcc = CopyFromBooleanField()\n fr_rcra = CopyFromBooleanField()\n fr_opa90 = CopyFromBooleanField()\n fr_epcra = CopyFromBooleanField()\n fr_otherregulation = CopyFromCharField(max_length=200, blank=True)\n\n source_file = 'tblS9EmergencyResponses'\n\n class Meta:\n db_table = 'tblS9EmergencyResponses'\n","sub_path":"rmp/models/raw_split/s9.py","file_name":"s9.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"495652224","text":"\"\"\"Transport model wrapper\n\"\"\"\n# -*- coding: utf-8 -*-\n\nimport configparser\nimport csv\nimport os\nfrom subprocess import check_output, CalledProcessError\nfrom string import Template\n\nimport pandas as pd\nimport numpy as np\nfrom smif.data_layer.data_array import DataArray\nfrom smif.exception import SmifTimestepResolutionError\nfrom smif.model.sector_model import SectorModel\n\n\nclass BaseTransportWrapper(SectorModel):\n \"\"\"Base wrapper for the transport model - override class variables in implementations\n \"\"\"\n _config_filename = 'run_config.ini'\n _template_filename = 'config.properties.template'\n\n def __init__(self, *args, **kwargs):\n # shared setup\n self._current_timestep = None\n self._set_options()\n super().__init__(*args, **kwargs)\n\n def _set_options(self):\n this_dir = os.path.dirname(__file__)\n\n config = configparser.ConfigParser()\n config.read(os.path.join(this_dir, self._config_filename))\n\n self._templates_dir = os.path.join(this_dir, 'templates')\n\n if 'run' not in config:\n raise KeyError(\"Expected '[run]' section in transport run_config.ini\")\n\n if 'jar' in config['run']:\n self._jar_path = os.path.join(this_dir, config['run']['jar'])\n else:\n raise KeyError(\"Expected 'jar' in transport run_config.ini\")\n\n if 'working_dir' in config['run']:\n self._working_dir = os.path.join(this_dir, config['run']['working_dir'])\n self._input_dir = os.path.join(self._working_dir, 'input')\n self._output_dir = os.path.join(self._working_dir, 'output')\n self._config_path = os.path.join(self._working_dir, 'config.properties')\n else:\n raise KeyError(\"Expected 'data_dir' in transport run_config.ini\")\n\n if 'optional_args' in config['run']:\n self._optional_args = config['run']['optional_args'].split(\" \")\n else:\n self._optional_args = []\n\n def _output_file_path(self, filename):\n return os.path.join(self._output_dir, str(self._current_timestep), filename)\n\n def simulate(self, data):\n \"\"\"Run the transport model\n\n Arguments\n ---------\n data: smif.data_layer.DataHandle\n \"\"\"\n try:\n os.mkdir(self._input_dir)\n except FileExistsError:\n pass\n\n self._current_timestep = data.current_timestep\n self._set_parameters(data)\n self._set_inputs(data)\n self._set_properties(data)\n self._run_model_subprocess(data)\n self._set_outputs(data)\n\n def _run_model_subprocess(self, data_handle):\n \"\"\"Run the transport model jar and feed log messages\n into the smif loggerlogger\n \"\"\"\n\n working_dir = self._working_dir\n path_to_jar = self._jar_path\n\n self.logger.info(\"FROM run.py: Running transport model\")\n base_arguments = ['java'] + self._optional_args + [\n '-cp',\n path_to_jar,\n 'nismod.transport.App',\n '-c',\n self._config_path\n ]\n if data_handle.current_timestep == data_handle.base_timestep:\n base_arguments.append('-b')\n try:\n self.logger.debug(base_arguments)\n output = check_output(base_arguments)\n self.logger.info(output.decode(\"utf-8\"))\n except CalledProcessError as ex:\n self.logger.error(ex.output.decode(\"utf-8\"))\n self.logger.exception(\"Transport model failed %s\", ex)\n raise ex\n else:\n tspt_model_arguments = base_arguments + [\n '-road',\n str(data_handle.current_timestep),\n str(data_handle.previous_timestep)\n ]\n try:\n self.logger.debug(tspt_model_arguments)\n output = check_output(tspt_model_arguments)\n self.logger.info(output.decode(\"utf-8\"))\n except CalledProcessError as ex:\n self.logger.error(ex.output.decode(\"utf-8\"))\n self.logger.exception(\"Transport model failed %s\", ex)\n raise ex\n\n def _input_dimension_names(self, input_name, dimension_name):\n return self.inputs[input_name].dim_coords(dimension_name).ids\n\n def _set_parameters(self, data_handle):\n \"\"\"Read model parameters from data handle and set up config files\n \"\"\"\n input_dir = self._input_dir\n\n # Elasticities for passenger and freight demand\n variables = ['POPULATION', 'GVA', 'TIME', 'COST']\n types = {\n 'ETA': os.path.join(input_dir, 'elasticities.csv'),\n 'FREIGHT_ETA': os.path.join(\n input_dir, 'elasticitiesFreight.csv')\n }\n for suffix, filename in types.items():\n with open(filename, 'w') as file_handle:\n writer = csv.writer(file_handle)\n writer.writerow(('variable', 'elasticity'))\n for variable in variables:\n key = \"{}_{}\".format(variable, suffix)\n value = float(data_handle.get_parameter(key).as_ndarray())\n writer.writerow((variable, value))\n\n def _set_inputs(self, data_handle):\n \"\"\"Get model inputs from data handle and write to input files\n \"\"\"\n self._set_population(data_handle)\n self._set_gva(data_handle)\n self._set_fuel_price(data_handle)\n self._set_engine_fractions(data_handle)\n\n def _set_population(self, data_handle):\n current_population = data_handle.get_data(\"population\").as_df().reset_index()\n current_population['year'] = data_handle.current_timestep\n\n if data_handle.current_timestep != data_handle.base_timestep:\n previous_population = data_handle.get_previous_timestep_data(\"population\").as_df().reset_index()\n previous_population['year'] = data_handle.previous_timestep\n\n population = pd.concat(\n [previous_population, current_population]\n )\n else:\n population = current_population\n\n population.population = population.population.astype(int)\n # use region dimension name (could change) for columns\n colname = self.inputs['population'].dims[0]\n population = population.pivot(\n index='year', columns=colname, values='population'\n )\n population_filepath = os.path.join(\n self._input_dir, 'population.csv')\n population.to_csv(population_filepath)\n\n def _set_gva(self, data_handle):\n current_gva = data_handle.get_data(\"gva\").as_df().reset_index()\n current_gva['year'] = data_handle.current_timestep\n\n if data_handle.current_timestep != data_handle.base_timestep:\n previous_gva = data_handle.get_previous_timestep_data(\"gva\").as_df().reset_index()\n previous_gva['year'] = data_handle.previous_timestep\n\n gva = pd.concat(\n [previous_gva, current_gva]\n )\n else:\n gva = current_gva\n\n # use region dimension name (could change) for columns\n colname = self.inputs['gva'].dims[0]\n gva = gva.pivot(\n index='year', columns=colname, values='gva'\n )\n gva_filepath = os.path.join(self._input_dir, 'gva.csv')\n gva.to_csv(gva_filepath)\n\n def _set_fuel_price(self, data_handle):\n fuel_price = data_handle.get_data('fuel_price').as_df().reset_index()\n fuel_price['year'] = data_handle.current_timestep\n fuel_price = fuel_price.pivot(\n index='year', columns='transport_fuel_type', values='fuel_price'\n )\n fuel_price['ELECTRICITY'] = float(data_handle.get_data('fuel_price_electricity').data)\n\n fuel_price_filepath = os.path.join(self._input_dir, 'energyUnitCosts.csv')\n fuel_price.to_csv(fuel_price_filepath)\n\n def _set_engine_fractions(self, data_handle):\n current_data = self._get_engine_fractions(data_handle, data_handle.current_timestep)\n\n if data_handle.current_timestep != data_handle.base_timestep:\n base_data = self._get_engine_fractions(data_handle, data_handle.base_timestep)\n\n data = pd.concat([base_data, current_data])\n else:\n data = current_data\n\n data.to_csv(\n os.path.join(self._input_dir, 'engineTypeFractions.csv'), index=False,\n float_format='%.15f')\n\n\n def _get_engine_fractions(self, data_handle, timestep):\n engine_fractions = data_handle.get_data(\n 'engine_type_fractions', timestep=timestep).as_df().reset_index()\n engine_fractions = engine_fractions.pivot(\n index='vehicle_type', columns='engine_type', values='engine_type_fractions'\n )\n engine_fractions.columns = engine_fractions.columns.values\n engine_fractions = engine_fractions.reset_index().rename(\n columns={\n 'vehicle_type': 'vehicle'\n }\n )\n engine_fractions['year'] = timestep\n\n # ensure column order matches EngineType enum definition (Java CSV reading assumes\n # fixed column order)\n column_order = [\n 'year', 'vehicle', 'ICE_PETROL', 'ICE_DIESEL', 'ICE_LPG', 'ICE_H2', 'ICE_CNG',\n 'HEV_PETROL', 'HEV_DIESEL', 'FCEV_H2', 'PHEV_PETROL', 'PHEV_DIESEL', 'BEV']\n engine_fractions = engine_fractions[column_order]\n return engine_fractions\n\n def _set_properties(self, data_handle):\n \"\"\"Set the transport model properties, such as paths and interventions\n \"\"\"\n working_dir = self._working_dir\n working_dir_path = str(os.path.abspath(working_dir)).replace('\\\\', '/')\n path_to_config_template = os.path.join(self._templates_dir, self._template_filename)\n\n # read config as a Template for easy substitution of values\n with open(path_to_config_template) as template_fh:\n config = Template(template_fh.read())\n\n intervention_files = []\n # Must be able to identify rail model interventions\n # the key in the config.properties must be railInterventionsFileX instead of\n # interventionsFilesX\n # Next line must contain all possible types of rail interventions\n rail_interventions_types = ['NewRailStation']\n for i, intervention in enumerate(data_handle.get_current_interventions().values()):\n fname = self._write_intervention(intervention)\n # write path with \"/\" separators even on Windows\n fname = fname.replace(\"\\\\\", \"/\")\n if intervention['type'] in rail_interventions_types:\n intervention_files.append(\"railInterventionFile{} = {}\".format(i, fname))\n else:\n intervention_files.append(\"interventionFile{} = {}\".format(i, fname))\n\n config_str = config.substitute({\n 'relative_path': working_dir_path,\n 'intervention_files': '\\n'.join(intervention_files),\n 'link_travel_time_averaging_weight': \\\n float(data_handle.get_parameter('link_travel_time_averaging_weight').data),\n 'assignment_iterations': \\\n int(data_handle.get_parameter('assignment_iterations').data),\n 'prediction_iterations': \\\n int(data_handle.get_parameter('prediction_iterations').data),\n 'use_route_choice_model': \\\n bool(data_handle.get_parameter('use_route_choice_model').data),\n })\n\n with open(self._config_path, 'w') as template_fh:\n template_fh.write(config_str)\n\n def _write_intervention(self, intervention):\n \"\"\"Write a single intervention file, returning the full path\n \"\"\"\n path = os.path.normpath(os.path.abspath(os.path.join(\n self._input_dir, \"{}.properties\".format(intervention['name']))))\n\n # compute start/end year from smif intervention keys\n intervention['startYear'] = intervention['build_year']\n intervention['endYear'] = intervention['build_year'] + \\\n intervention['technical_lifetime']['value']\n del intervention['build_year']\n del intervention['technical_lifetime']\n\n # fix up path to congestion charging pricing details file\n if 'congestionChargingPricing' in intervention:\n cccp_filename = intervention['congestionChargingPricing']\n intervention['congestionChargingPricing'] = os.path.join(\n self._working_dir, 'data', 'csvfiles', cccp_filename\n ).replace(\"\\\\\", \"/\")\n\n print('Now writing {}'.format(path))\n with open(path, 'w') as file_handle:\n for key, value in intervention.items():\n file_handle.write(\"{} = {}\\n\".format(key, value))\n\n return path\n\n def _set_outputs(self, data_handle):\n \"\"\"Read results from model and write to data handle\n \"\"\"\n # !!! hack: look through output dimensions to find LAD dimension name\n dims = self.outputs['electric_vehicle_trip_starts'].dims\n zone_dim = 'lad_uk_2016' # sensible default for full model\n for dim in dims:\n if dim != 'annual_day_hours':\n # assume that time is 'annual_day_hours', so we want the other one\n zone_dim = dim\n\n # EV trip starts and consumption\n evt_name = 'electric_vehicle_trip_starts'\n evc_name = 'electric_vehicle_electricity_consumption'\n\n # set up zero-valued output arrays\n ev_trips = np.zeros(self.outputs[evt_name].shape)\n ev_consumption = np.zeros(self.outputs[evc_name].shape)\n\n for vehicle_type in ('CAR', 'VAN', 'RIGID', 'ARTIC'):\n vehicle_ev_trips = self._melt_output(\n name=evt_name,\n filename=self._output_file_path(f'zonalTemporalEVTripStarts{vehicle_type}.csv'),\n dims={\n 'zone': zone_dim,\n 'hour': 'annual_day_hours'\n },\n csv_id_vars=['zone'],\n csv_melt_var='hour'\n )\n\n vehicle_ev_consumption = self._melt_output(\n name=evc_name,\n filename=self._output_file_path(f'zonalTemporalEVTripElectricity{vehicle_type}.csv'),\n dims={\n 'zone': zone_dim,\n 'hour': 'annual_day_hours'\n },\n csv_id_vars=['zone'],\n csv_melt_var='hour'\n )\n\n # sum up over vehicles (aggregated output)\n ev_trips += self._df_to_ndarray(evt_name, vehicle_ev_trips)\n ev_consumption += self._df_to_ndarray(evc_name, vehicle_ev_consumption)\n\n # Output EV trip starts and energy consumption\n data_handle.set_results(evt_name, ev_trips)\n data_handle.set_results(evc_name, ev_consumption)\n\n # Energy consumption, all fuels\n ec_name = 'energy_consumption'\n energy_consumption = self._melt_output(\n name=ec_name,\n filename=self._output_file_path('energyConsumptions.csv'),\n dims={\n 'fuel': 'transport_fuel_type'\n },\n csv_id_vars=[],\n csv_melt_var='fuel'\n )\n # Split - non-electricity (measured in litres)\n non_elec = energy_consumption.copy()\n non_elec = non_elec[non_elec.transport_fuel_type != 'ELECTRICITY']\n non_elec['annual_day'] = 'annual_day'\n non_elec = self._df_to_ndarray(ec_name, non_elec)\n data_handle.set_results(ec_name, non_elec)\n # Split - electricity (measured in kWh)\n elec = energy_consumption[energy_consumption.transport_fuel_type == 'ELECTRICITY']\n elec = np.array(elec.energy_consumption)\n data_handle.set_results('energy_consumption_electricity', elec)\n\n def _melt_output(self, name, filename, dims, csv_id_vars, csv_melt_var):\n return pd.read_csv(\n filename\n ).drop(\n 'year', axis=1 # ignore the year output, assume it's always current timestep\n ).melt(\n id_vars=csv_id_vars,\n var_name=csv_melt_var,\n value_name=name\n ).rename(\n dims, axis=1\n )\n\n def _df_to_ndarray(self, output_name, dataframe):\n spec = self.outputs[output_name]\n dataframe.set_index(spec.dims, inplace=True)\n dataarray = DataArray.from_df(spec, dataframe)\n return dataarray.data\n\n\nclass TransportWrapper(BaseTransportWrapper):\n \"\"\"Wrap the transport model, in 'full' configuration\n \"\"\"\n _config_filename = 'run_config_full.ini'\n _template_filename = 'gb-config.properties.template'\n\n\nclass SouthamptonTransportWrapper(BaseTransportWrapper):\n \"\"\"Wrap the transport model, in 'southampton' configuration\n \"\"\"\n _config_filename = 'run_config_southampton.ini'\n _template_filename = 'southampton-config.properties.template'\n","sub_path":"models/transport/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":16962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"272614284","text":"# coding=utf-8\n# python 3\n\n# Import required classes\nimport json\nimport urllib.request\nimport urllib.parse\nimport datetime\n\nAPI_KEY = 'f9a00520ec2beacdec7f69bf6a20d085'\n\nrequest = input('Filmtitel eingeben: ')\n\n# Get the json file from the API\nurl = 'http://api.themoviedb.org/3/search/movie?api_key=' + API_KEY + '&query=' + urllib.parse.quote(request, safe='')\nraw_answer = urllib.request.urlopen(url)\n\n# Parse the json\nanswer = json.load(raw_answer)\n\n# Display all movies foound\nresults = answer['results']\nindex = 0\nfor movie in results:\n id = movie['id']\n title = movie['title']\n original_title = movie['original_title']\n release_date = movie['release_date']\n print(str(index) + ' ' + title + ' (' + original_title + ')' + ' ' + release_date)\n index +=1\n\nprint('')\n\n# Request details\nindex = int(input('Index of the film for details: '))\n\n# Get the json file from the API\nurl = 'http://api.themoviedb.org/3/movie/' + str(results[index]['id']) + '?api_key=' + API_KEY\nraw_details = urllib.request.urlopen(url)\n\n# Parse the json\ndetails = json.load(raw_details)\n\nprint('')\n\nprint(details['overview'])\n\nprint('')\n\nprint('Ort:')\nfor country in details['production_countries']:\n print(' ' + country['name'])\n\nprint('')\n\nprint('Genres:')\nfor genre in details['genres']:\n print(' ' + genre['name'])\n\nprint('')\n\nprint('Sprachen:')\nfor language in details['spoken_languages']:\n print(' ' + language['name'])\n\nprint('')\n\nprint('Runtime: ' + str(details['runtime']))","sub_path":"programs/movie.py","file_name":"movie.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"597047907","text":"import time\nfrom bert_base.client import BertClient\n\nwith BertClient(show_server_config=False, port=6666, port_out=6667, check_version=False, check_length=False, mode='NER') as bc:\n start_t = time.perf_counter()\n str1 = '我有鸡蛋和黄瓜可以做什么?'\n str2 = '不辣的川菜。'\n str3 = '推荐一个有香菇的菜'\n strs = [str1, str2, str3]\n rst = bc.encode(strs)\n print('rst:', rst)\n for st, sen in zip(strs, rst):\n tmp = []\n flag = False\n for i in range(len(sen)):\n if sen[i] == 'B-ING':\n tmp.append(st[i])\n flag = True\n elif sen[i] == 'I-ING':\n if flag:\n tmp[-1] = tmp[-1] + st[i]\n else:\n tmp.append(st[i])\n flag = True\n else:\n flag = False\n print(tmp)\n\n print(time.perf_counter() - start_t)\n","sub_path":"test_ner.py","file_name":"test_ner.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"227627430","text":"import urllib.request\n\nclass GetData:\n key ='N0I81fzSUhrdaHT6x98p7II9uCAaJcGDpBInQTLv5ZzQV4%2FfUmQBuV27%2FDY3IHV6Agv%2BTGUazNTKqA7hMtsBOg%3D%3D'\n url = 'http://apis.data.go.kr/1611000/AptBasisInfoService/getAphusBassInfo?kaptCode=A10027875&ServiceKey=%s' %key\n\n def main(self):\n data = urllib.request.urlopen(self.url).read()\n\n print(data.decode('utf-8'))\n\n\ngetData = GetData()\ngetData.main()","sub_path":"사용예제/ex_getData.py","file_name":"ex_getData.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"640750831","text":"# -*- coding: utf-8 -*-\n\"\"\"\n.. module:: bibnetwork\n :synopsis: The main Network class\n\n.. moduleauthor:: Alex Gates \n \"\"\"\nimport sys\nfrom collections import defaultdict\nfrom itertools import combinations\nimport numpy as np\nimport pandas as pd\n\nimport scipy.sparse as spsparse\n\nfrom pyscisci.utils import isin_sorted, zip2dict, check4columns\n\n# determine if we are loading from a jupyter notebook (to make pretty progress bars)\nif 'ipykernel' in sys.modules:\n from tqdm.notebook import tqdm\nelse:\n from tqdm import tqdm\n\ndef threshold_network(adj_mat, threshold=0):\n \"\"\"\n\n \"\"\"\n if adj_mat.getformat() != 'coo':\n adj_mat = spsparse.coo_matrix(adj_mat)\n\n adj_mat.data[adj_mat.data <=threshold] = 0\n adj_mat.eliminate_zeros()\n\n return adj_mat\n\ndef largest_connected_component_vertices(adj_mat):\n \"\"\"\n \"\"\"\n n_components, labels = spsparse.csgraph.connected_components(adj_mat)\n comidx, compsizes = np.unique(labels, return_counts=True)\n\n return np.arange(adj_mat.shape[0])[labels==np.argmax(compsizes)]\n\ndef coauthorship_network(paa_df, focus_author_ids=None, focus_constraint='authors', temporal=False, show_progress=False):\n \"\"\"\n Create the co-authorship network.\n\n Parameters\n ----------\n :param paa_df : DataFrame\n A DataFrame with the links between authors and publications.\n\n :param focus_author_ids : numpy array or list, default None\n A list of the AuthorIds to seed the coauthorship-network.\n\n :param focus_constraint : str, default `authors`\n If focus_author_ids is not None:\n `authors` : the `focus_author_ids' defines the node set, giving only the co-authorships between authors in the set.\n `publications` : the publication history of `focus_author_ids' defines the edge set, giving the co-authorhips where at least\n one author from `focus_author_ids' was involved.\n 'ego' : the `focus_author_ids' defines a seed set, such that all authors must have co-authored at least one publication with\n an author from `focus_author_ids', but co-authorships are also found between the second-order author sets.\n\n :param temporal : bool, default False\n If True, compute the adjacency matrix using only publications for each year.\n\n :param show_progress : bool, default False\n If True, show a progress bar tracking the calculation.\n\n\n Returns\n -------\n coo_matrix or dict of coo_matrix\n If temporal == False:\n The adjacency matrix for the co-authorship network\n\n If temporal == True:\n A dictionary with key for each year, and value of the adjacency matrix for the co-authorship network induced by publications in that year.\n\n author2int, dict\n A mapping of AuthorIds to the row/column of the adjacency matrix.\n\n \"\"\"\n required_columns = ['AuthorId', 'PublicationId']\n if temporal:\n required_columns.append('Year')\n check4columns(paa_df, required_columns)\n paa_df = paa_df[required_columns].dropna()\n\n if not focus_author_ids is None:\n focus_author_ids = np.sort(focus_author_ids)\n\n # identify the subset of the publications we need to form the network\n if focus_constraint == 'authors':\n # take only the publication-author links that have an author from the `focus_author_ids'\n paa_df = paa_df.loc[isin_sorted(paa_df['AuthorId'].values, focus_author_ids)]\n\n elif focus_constraint == 'publications':\n # take all publications authored by an author from the `focus_author_ids'\n focus_pubs = np.sort(paa_df.loc[isin_sorted(paa_df['AuthorId'].values, focus_author_ids)]['PublicationId'].unique())\n # then take only the subset of publication-author links inducded by these publications\n paa_df = paa_df.loc[isin_sorted(paa_df['PublicationId'].values, focus_pubs)]\n del focus_pubs\n\n elif focus_constraint == 'ego':\n # take all publications authored by an author from the `focus_author_ids'\n focus_pubs = np.sort(paa_df.loc[isin_sorted(paa_df['AuthorId'].values, focus_author_ids)]['PublicationId'].unique())\n # then take all authors who contribute to this subset of publications\n focus_author_ids = np.sort(paa_df.loc[isin_sorted(paa_df['PublicationId'].values, focus_pubs)]['AuthorId'].unique())\n del focus_pubs\n # finally take the publication-author links that have an author from the above ego subset\n paa_df = paa_df.loc[isin_sorted(paa_df['AuthorId'].values, focus_author_ids)]\n\n paa_df.drop_duplicates(subset=['AuthorId', 'PublicationId'], inplace=True)\n\n # map authors to the rows of the bipartite adj mat\n author2int = {aid:i for i, aid in enumerate(np.sort(paa_df['AuthorId'].unique()))}\n Nauthors = paa_df['AuthorId'].nunique()\n\n paa_df['AuthorId'] = [author2int[aid] for aid in paa_df['AuthorId'].values]\n\n # map publications to the columns of the bipartite adj mat\n pub2int = {pid:i for i, pid in enumerate(np.sort(paa_df['PublicationId'].unique()))}\n Npubs = paa_df['PublicationId'].nunique()\n\n paa_df['PublicationId'] = [pub2int[pid] for pid in paa_df['PublicationId'].values]\n\n if temporal:\n years = np.sort(paa_df['Year'].unique())\n\n temporal_adj = {}\n for y in years:\n bipartite_adj = dataframe2bipartite(paa_df.loc[paa_df['Year'] == y], 'AuthorId', 'PublicationId', (Nauthors, Npubs) )\n\n adj_mat = project_bipartite_mat(bipartite_adj, project_to = 'row')\n\n # remove diagonal entries\n adj_mat.setdiag(0)\n adj_mat.eliminate_zeros()\n\n temporal_adj[y] = adj_mat\n\n return temporal_adj, author2int\n\n else:\n bipartite_adj = dataframe2bipartite(paa_df, 'AuthorId', 'PublicationId', (Nauthors, Npubs) )\n\n adj_mat = project_bipartite_mat(bipartite_adj, project_to = 'row')\n\n # remove diagonal entries\n adj_mat.setdiag(0)\n adj_mat.eliminate_zeros()\n\n return adj_mat, author2int\n\n\ndef cogroupby(df, N):\n adj_mat = spsparse.dok_matrix( (N,N), dtype=int)\n def inducedcombos(authorlist):\n if authorlist.shape[0] >= 2:\n for i,j in combinations(authorlist, 2):\n adj_mat[i,j] += 1\n\n tqdm.pandas(desc='CoAuthorship')\n df.groupby('PublicationId')['AuthorId'].progress_apply(inducedcombos)\n\n adj_mat = adj_mat + adj_mat.T\n\n return adj_mat\n\n\ndef dataframe2bipartite(df, rowname, colname, shape=None, weightname=None):\n\n if shape is None:\n shape = (int(df[rowname].max()+1), int(df[colname].max()+1) )\n\n if weightname is None:\n weights = np.ones(df.shape[0], dtype=int)\n else:\n weights = df[weightname].values\n\n # create a bipartite adj matrix connecting authors to their publications\n bipartite_adj = spsparse.coo_matrix( ( weights,\n (df[rowname].values, df[colname].values) ),\n shape=shape, dtype=weights.dtype)\n\n bipartite_adj.sum_duplicates()\n\n return bipartite_adj\n\ndef project_bipartite_mat(bipartite_adj, project_to = 'row'):\n\n if project_to == 'row':\n adj_mat = bipartite_adj.dot(bipartite_adj.T).tocoo()\n elif project_to == 'col':\n adj_mat = bipartite_adj.T.dot(bipartite_adj).tocoo()\n\n return adj_mat\n\ndef extract_multiscale_backbone(Xs, alpha):\n \"\"\"\n A sparse matrix implemntation of the multiscale backbone.\n\n References\n ----------\n Serrano et al. (2009) Extracting the multiscale backbone of complex weighted networks. PNAS.\n\n Parameters\n ----------\n :param Xs : numpy.array or sp.sparse matrix\n The adjacency matrix for the network.\n\n :param alpha : float\n The significance value.\n\n\n Returns\n -------\n coo_matrix\n The directed, weighted multiscale backbone\n\n \"\"\"\n\n X = spsparse.coo_matrix(Xs)\n X.eliminate_zeros()\n\n #normalize\n row_sums = X.sum(axis = 1)\n degrees = X.getnnz(axis = 1)\n\n\n pijs = np.multiply(X.data, 1.0/np.array(row_sums[X.row]).squeeze())\n powers = degrees[X.row.squeeze()] - 1\n\n # equation 2 => where 1 - (k - 1) * integrate.quad(lambda x: (1 - x) ** (k - 2)) = (1-x)**(k - 1) if k > 1\n significance = np.logical_and(pijs < 1, np.power(1.0 - pijs, powers) < alpha)\n\n keep_graph = spsparse.coo_matrix((X.data[significance], (X.row[significance], X.col[significance])), shape = X.shape)\n keep_graph.eliminate_zeros()\n\n return keep_graph\n\n\ndef cocitation_network(pub2ref_df, focus_pub_ids=None, focus_constraint='citing', temporal=False, show_progress=False):\n \"\"\"\n Create the co-citation network.\n\n Parameters\n ----------\n :param pub2ref_df : DataFrame\n A DataFrame with the links between authors and publications.\n\n :param focus_pub_ids : numpy array or list, default None\n A list of the PublicationIds to seed the cocitation-network.\n\n :param focus_constraint : str, default `citing`\n If focus_author_ids is not None:\n `citing` : the `focus_pub_ids' defines the citation set, giving only the co-citations between the references\n of the publications from this set.\n `cited` : the `focus_pub_ids' defines the cocitation node set.\n 'egocited' : the `focus_pub_ids' defines a seed set, such that all other publications must have been co-citeed with\n at least one publication from this set.\n\n :param temporal : bool, default False\n If True, compute the adjacency matrix using only publications for each year.\n\n :param show_progress : bool, default False\n If True, show a progress bar tracking the calculation.\n\n\n Returns\n -------\n coo_matrix or dict of coo_matrix\n If temporal == False:\n The adjacency matrix for the co-citation network\n\n If temporal == True:\n A dictionary with key for each year, and value of the adjacency matrix for the cocitation network induced\n by citing publications in that year.\n\n pub2int, dict\n A mapping of PublicationIds to the row/column of the adjacency matrix.\n\n \"\"\"\n required_columns = ['CitedPublicationId', 'CitingPublicationId']\n if temporal:\n required_columns.append('CitingYear')\n check4columns(pub2ref_df, required_columns)\n pub2ref_df = pub2ref_df[required_columns].dropna()\n\n if not focus_pub_ids is None:\n focus_pub_ids = np.sort(focus_pub_ids)\n\n # identify the subset of the publications we need to form the network\n if focus_constraint == 'citing':\n # take only the links that have a citing publication from the `focus_pub_ids'\n pub2ref_df = pub2ref_df.loc[isin_sorted(pub2ref_df['CitingPublicationId'].values, focus_pub_ids)]\n\n elif focus_constraint == 'cited':\n # take only the links that have a cited publication from the `focus_pub_ids'\n pub2ref_df = pub2ref_df.loc[isin_sorted(pub2ref_df['CitedPublicationId'].values, focus_pub_ids)]\n\n elif focus_constraint == 'egocited':\n # take all publications that cite one of the publications in `focus_pub_ids'\n focus_citing_pubs = np.sort(pub2ref_df.loc[isin_sorted(pub2ref_df['CitedPublicationId'].values, focus_pub_ids)]['CitingPublicationId'].unique())\n # then take all the links that have a citing publication from the `focus_citing_pubs'\n pub2ref_df = pub2ref_df.loc[isin_sorted(pub2ref_df['CitingPublicationId'].values, focus_citing_pubs)]\n del focus_citing_pubs\n\n pub2ref_df.drop_duplicates(subset=['CitingPublicationId', 'CitedPublicationId'], inplace=True)\n\n if pub2ref_df.shape[0] > 0:\n # map cited publications to the rows of the bipartite adj mat\n cited2int = {pid:i for i, pid in enumerate(np.sort(pub2ref_df['CitedPublicationId'].unique()))}\n Ncited = pub2ref_df['CitedPublicationId'].nunique()\n\n pub2ref_df['CitedPublicationId'] = [cited2int[pid] for pid in pub2ref_df['CitedPublicationId'].values]\n\n # map citing publications to the columns of the bipartite adj mat\n citing2int = {pid:i for i, pid in enumerate(np.sort(pub2ref_df['CitingPublicationId'].unique()))}\n Nciting = pub2ref_df['CitingPublicationId'].nunique()\n\n pub2ref_df['CitingPublicationId'] = [citing2int[pid] for pid in pub2ref_df['CitingPublicationId'].values]\n\n if temporal:\n years = np.sort(pub2ref_df['CitingYear'].unique())\n\n temporal_adj = {}\n for y in years:\n bipartite_adj = dataframe2bipartite(pub2ref_df.loc[pub2ref_df['CitingYear'] == y], 'CitedPublicationId', 'CitingPublicationId', (Ncited, Nciting) )\n\n adj_mat = project_bipartite_mat(bipartite_adj, project_to = 'row')\n\n # remove diagonal entries\n adj_mat.setdiag(0)\n adj_mat.eliminate_zeros()\n\n temporal_adj[y] = adj_mat\n\n return temporal_adj, cited2int\n\n else:\n bipartite_adj = dataframe2bipartite(pub2ref_df, 'CitedPublicationId', 'CitingPublicationId', (Ncited, Nciting) )\n\n adj_mat = project_bipartite_mat(bipartite_adj, project_to = 'row')\n\n # remove diagonal entries\n adj_mat.setdiag(0)\n adj_mat.eliminate_zeros()\n\n return adj_mat, cited2int\n\n else:\n return spsparse.coo_matrix(), {}\n\ndef cociting_network(pub2ref_df, focus_pub_ids=None, focus_constraint='citing', temporal=False, show_progress=False):\n \"\"\"\n Create the co-citing network. Each node is a publication, two publications are linked if they cite the same article.\n\n Parameters\n ----------\n :param pub2ref_df : DataFrame\n A DataFrame with the links between authors and publications.\n\n :param focus_pub_ids : numpy array or list, default None\n A list of the PublicationIds to seed the cocitation-network.\n\n :param focus_constraint : str, default `citing`\n If focus_author_ids is not None:\n `citing` : the `focus_pub_ids' defines the citation set, giving only the co-citations between the references\n of the publications from this set.\n `cited` : the `focus_pub_ids' defines the cocitation node set.\n\n :param show_progress : bool, default False\n If True, show a progress bar tracking the calculation.\n\n\n Returns\n -------\n coo_matrix or dict of coo_matrix\n The adjacency matrix for the co-citing network\n\n pub2int, dict\n A mapping of PublicationIds to the row/column of the adjacency matrix.\n\n \"\"\"\n required_columns = ['CitedPublicationId', 'CitingPublicationId']\n check4columns(pub2ref_df, required_columns)\n pub2ref_df = pub2ref_df[required_columns].dropna()\n\n if not focus_pub_ids is None:\n focus_pub_ids = np.sort(focus_pub_ids)\n\n # identify the subset of the publications we need to form the network\n if focus_constraint == 'citing':\n # take only the links that have a citing publication from the `focus_pub_ids'\n pub2ref_df = pub2ref_df.loc[isin_sorted(pub2ref_df['CitingPublicationId'].values, focus_pub_ids)]\n\n elif focus_constraint == 'cited':\n # take only the links that have a cited publication from the `focus_pub_ids'\n pub2ref_df = pub2ref_df.loc[isin_sorted(pub2ref_df['CitedPublicationId'].values, focus_pub_ids)]\n\n pub2ref_df.drop_duplicates(subset=['CitingPublicationId', 'CitedPublicationId'], inplace=True)\n\n if pub2ref_df.shape[0] > 0:\n # map cited publications to the rows of the bipartite adj mat\n cited2int = {pid:i for i, pid in enumerate(np.sort(pub2ref_df['CitedPublicationId'].unique()))}\n Ncited = pub2ref_df['CitedPublicationId'].nunique()\n\n pub2ref_df['CitedPublicationId'] = [cited2int[pid] for pid in pub2ref_df['CitedPublicationId'].values]\n\n # map citing publications to the columns of the bipartite adj mat\n citing2int = {pid:i for i, pid in enumerate(np.sort(pub2ref_df['CitingPublicationId'].unique()))}\n Nciting = pub2ref_df['CitingPublicationId'].nunique()\n\n pub2ref_df['CitingPublicationId'] = [citing2int[pid] for pid in pub2ref_df['CitingPublicationId'].values]\n\n bipartite_adj = dataframe2bipartite(pub2ref_df, 'CitedPublicationId', 'CitingPublicationId', (Ncited, Nciting) )\n\n adj_mat = project_bipartite_mat(bipartite_adj, project_to = 'col')\n\n # remove diagonal entries\n adj_mat.setdiag(0)\n adj_mat.eliminate_zeros()\n\n return adj_mat, cited2int\n\n else:\n return spsparse.coo_matrix(), {}\n\ndef temporal_cocited_edgedict(pub2ref, pub2year):\n\n required_pub2ref_columns = ['CitingPublicationId', 'CitedPublicationId']\n check4columns(pub2ref, required_pub2ref_columns)\n pub2ref = pub2ref[required_pub2ref_columns]\n\n year_values = sorted(list(set(pub2year.values())))\n\n # we need the citation counts and cocitation network\n temporal_cocitation_dict = {y:defaultdict(set) for y in year_values}\n temporal_citation_dict = {y:defaultdict(int) for y in year_values}\n\n def count_cocite(cited_df):\n y = pub2year[cited_df.name]\n\n for citedpid in cited_df['CitedPublicationId'].values:\n temporal_citation_dict[y][citedpid] += 1\n for icitedpid, jcitedpid in combinations(cited_df['CitedPublicationId'].values, 2):\n temporal_cocitation_dict[y][icitedpid].add(jcitedpid)\n temporal_cocitation_dict[y][jcitedpid].add(icitedpid)\n\n pub2ref.groupby('CitingPublicationId', sort=False).apply(count_cocite)\n\n\ndef dataframe2sparse(df, index_columns = ['name_citing', 'name_cited'], weight_values = None):\n\n \"\"\"\n Take a pandas Data Frame as an edge list and convert it into a sparse adjacency matrix\n \"\"\"\n\n # convert values 2 int\n nameindex = pd.DataFrame(pd.unique(df[index_columns].values.ravel()), columns = ['name'])\n nameindex.sort_values('name', inplace = True)\n nameindex.reset_index(inplace = True, drop = True)\n nameindex['name2int'] = nameindex.index.values\n\n # sparse matrix size\n N = nameindex.shape[0]\n\n df = pd.merge(df, nameindex, left_on = 'name_citing', right_on = 'name',\n copy = 'False', how = 'left', suffixes = ['', '_citing'])\n del df['name']\n\n df = pd.merge(df, nameindex, left_on = 'name_cited', right_on = 'name',\n copy = 'False', how = 'left', suffixes = ['_citing', '_cited'])\n del df['name']\n\n if weight_values is None:\n weight_values = np.ones(df.shape[0])\n else:\n weight_values = df[weight_values].values\n\n mat = sp.coo_matrix((weight_values, (df['name2int_citing'].values, df['name2int_cited'].values)), shape = (N,N))\n mat.sum_duplicates()\n\n return mat, nameindex\n\n\ndef create_citation_edgelist(database, publication_subset = [], temporal = True):\n\n if len(publication_subset) == 0:\n publication_subset = database.publication_ids()\n\n edgelist = [[pubid, refid] for pubid in publication_subset for refid in database.get_pub(pubid).references]\n return edgelist\n\n","sub_path":"pyscisci/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":19241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"282648288","text":"from pars import result , Node\r\n\r\ntabl_sim = []\r\ntable_for_t = {}\r\nfunctions = []\r\n\r\ndef obhod(result):\r\n if (type(result) != Node):\r\n return\r\n elif (result.type == 'FUNC'):\r\n for j in result.parts:\r\n if (len(j.parts) == 2):\r\n obhod_fun(j, j.type)\r\n functions.append(j.type)\r\n elif (len(j.parts) == 3):\r\n functions.append(j.type)\r\n for l in j.parts:\r\n obhod_fun(l, j.type)\r\n elif (result.type == 'dec'):\r\n for i in result.parts[0].parts:\r\n tabl_sim.append((i, result.parts[1].parts[0], 'main', 0))\r\n return\r\n else:\r\n for i in range(len(result.parts)):\r\n obhod(result.parts[i])\r\n\r\ndef obhod_fun(result, fun):\r\n if (type(result) != Node):\r\n return\r\n elif (result.type == 'dec'):\r\n for i in result.parts[0].parts:\r\n tabl_sim.append((i, result.parts[1].parts[0], fun, 0))\r\n else:\r\n for i in range(len(result.parts)):\r\n obhod_fun(result.parts[i], fun)\r\n\r\nobhod(result)\r\ndef edit_tabl_sim(tabl_sim):\r\n new_tabl_sim = {}\r\n index = 0\r\n new_tabl_sim1 = {}\r\n joker='main'\r\n for i in tabl_sim:\r\n new_tabl_sim[i[0]] = []\r\n new_tabl_sim[i[0]].append('s' + str(index))\r\n new_tabl_sim[i[0]].append(i[1])\r\n new_tabl_sim[i[0]].append(i[2])\r\n new_tabl_sim[i[0]].append(i[3])\r\n index = index + 1\r\n index = 0\r\n index1=0\r\n for i in new_tabl_sim:\r\n new_tabl_sim1[i[0]] = []\r\n if new_tabl_sim[i][2] != 'main':\r\n if joker != new_tabl_sim[i][2]:\r\n joker = new_tabl_sim[i][2]\r\n index1=0\r\n joker = new_tabl_sim[i][2]\r\n new_tabl_sim1[i[0]].append('a' + str( index1))\r\n index1= index1+1\r\n new_tabl_sim1[i[0]].append(new_tabl_sim[i][1])\r\n new_tabl_sim1[i[0]].append(new_tabl_sim[i][2])\r\n new_tabl_sim1[i[0]].append(new_tabl_sim[i][3])\r\n else:\r\n new_tabl_sim1[i[0]].append('s' + str(index))\r\n index=index+1\r\n new_tabl_sim1[i[0]].append(new_tabl_sim[i][1])\r\n new_tabl_sim1[i[0]].append(new_tabl_sim[i][2])\r\n new_tabl_sim1[i[0]].append(new_tabl_sim[i][3])\r\n return new_tabl_sim1\r\n\r\ntabl_sim = edit_tabl_sim(tabl_sim)\r\nfor key in tabl_sim:\r\n print(key + ' : ')\r\n for i in tabl_sim[key]:\r\n print('\\t' + str(i))","sub_path":"tabl_sim_gen.py","file_name":"tabl_sim_gen.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"17815184","text":"from django.urls import path\nfrom . import views\n\napp_name = 'articles'\n\n# 사용자는 이미 /artiles/ 까지 접속 한 상태임. -> /articles/______ 의 경로 정해주는 것\nurlpatterns = [\n\n # /articles/\n path('', views.index, name='index'),\n\n # 사용자가 입력할 수 있는 입력페이지 제공\n # path('new/', views.new, name='new'),\n\n # 데이터를 전달 받아서 article생성\n path('create/', views.create, name='create'),\n\n # /articles/num/\n path('/', views.detail, name='detail'),\n\n # 삭제 url -> articles/num/delete/\n path('/delete/', views.delete, name='delete'),\n\n # update\n path('/update/', views.update, name='update'),\n\n # 댓글 작성 path /articles/num/comments/ # num번 게시글에 대한 댓글 표시\n path('/comments_create/', views.comments_create, name='comments_create'),\n\n # 댓글 삭제 path /articles/num/comments/comments_num/delete # url name도 지정\n path('/comments//delete/', views.comments_delete, name='comments_delete'),\n]\n","sub_path":"articles/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"467401790","text":"\"\"\"\nImplementation of Mini AES.\n\"\"\"\n\nROUNDS = 5\n\nSBOX = [\n 0xE, 0x4, 0xD, 0x1, 0x2, 0xF, 0xB, 0x8,\n 0x3, 0xA, 0x6, 0xC, 0x5, 0x9, 0x0, 0x7\n]\n\nINV_SBOX = [\n 0xE, 0x3, 0x4, 0x8, 0x1, 0xC, 0xA, 0xF,\n 0x7, 0xD, 0x9, 0x6, 0xB, 0x2, 0x0, 0x5\n]\n\nMULTI_2 = [\n 0x0, 0x2, 0x4, 0x6, 0x8, 0xA, 0xC, 0xE,\n 0x3, 0x1, 0x7, 0x5, 0xB, 0x9, 0xF, 0xD\n]\n\nMULTI_3 = [\n 0x0, 0x3, 0x6, 0x5, 0xC, 0xF, 0xA, 0x9,\n 0xB, 0x8, 0xD, 0xE, 0x7, 0x4, 0x1, 0x2\n]\n\nRCONS = [0x1, 0x2, 0x4, 0x8, 0x3]\n\n# utility functions\n\ndef chunks(xs, n):\n for i in range(0, len(xs), n):\n yield xs[i:i+n]\n\n# procedures\n\ndef nibble_sub(ns):\n \"\"\"\n ns -> List of nibbles\n\n Passes each nibble through a S-Box. The mapping is specified in `SBOX`.\n \"\"\"\n return [SBOX[n] for n in ns]\n\ndef inv_nibble_sub(ns):\n \"\"\"\n ns -> List of nibbles\n\n Retrieves the preimage of the mapping of each nibble. The inverse mapping is\n specified in `INV_SBOX`.\n \"\"\"\n return [INV_SBOX[n] for n in ns]\n\ndef shift_row(ns):\n \"\"\"\n ns -> List of nibbles\n\n Shift each row of the matrix of nibbles to the left by different amounts.\n\n The first row is unchanged while the second row is shifted by 1 element to\n the right.\n \"\"\"\n assert len(ns) == 4\n n0, n1, n2, n3 = ns\n return [n0, n3, n2, n1]\n\ndef mix_column(ns):\n \"\"\"\n ns -> List of nibbles\n\n Multiplies the matrix of nibbles by a constant matrix,\n\n 3 2\n\n 2 3\n \"\"\"\n def multiply_matrix(ms):\n assert len(ms) == 2\n m0, m1 = ms\n return [\n MULTI_3[m0] ^ MULTI_2[m1],\n MULTI_2[m0] ^ MULTI_3[m1]\n ]\n\n assert len(ns) == 4\n return [\n n\n for ms in chunks(ns, 2)\n for n in multiply_matrix(ms)\n ]\n\ndef key_addition(ws, ns):\n \"\"\"\n ws -> List of round key nibbles\n ns -> List of nibbles\n\n XORs each nibble with its corresponding round key nibble.\n \"\"\"\n assert len(ws) == len(ns) == 4\n return [w ^ n for (w, n) in zip(ws, ns)]\n\ndef key_schedule(k):\n \"\"\"\n k -> Key\n\n Generates round keys from a 16-bit key.\n\n The first round key is derived directly from the supplied key.\n \"\"\"\n assert len(k) == 4\n wss = [[]] * (ROUNDS + 1)\n wss[0] = k\n for i in range(0, ROUNDS):\n ws = [0] * 4\n ws[0] = wss[i][0] ^ SBOX[wss[i][3]] ^ RCONS[i]\n ws[1] = wss[i][1] ^ ws[0]\n ws[2] = wss[i][2] ^ ws[1]\n ws[3] = wss[i][3] ^ ws[2]\n wss[i + 1] = ws\n return wss\n\n# encryption & decryption\n\ndef roundf(ws, ns, i):\n \"\"\"\n ws -> List of key nibbles\n ns -> List of nibbles\n i -> Round number\n\n Round function of Mini-AES.\n\n This function operates by performing the following operations in order:\n 1. KeyAddition (with ith round key)\n 2. NibbleSub\n 3. ShiftRow\n 4. MixColumn (if not the last round)\n\n Note that this function does not handle the addition of the final round key.\n \"\"\"\n assert len(ns) == 4\n ns = shift_row(\n nibble_sub(\n key_addition(ws, ns)\n )\n )\n if i != ROUNDS - 1:\n ns = mix_column(ns)\n return ns\n\ndef inv_roundf(ws, ns, i):\n \"\"\"\n ws -> List of key nibbles\n ns -> List of nibbles\n i -> Round number\n\n Inverse round function of Mini-AES. Refer to `roundf()` for more details.\n \"\"\"\n assert len(ns) == 4\n if i != ROUNDS - 1:\n ns = mix_column(ns)\n ns = key_addition(ws,\n inv_nibble_sub(\n shift_row(ns)\n )\n )\n return ns\n\ndef encrypt_block(k, p):\n \"\"\"\n k -> Key\n p -> Plaintext\n\n Encrypts the plaintext block with Mini-AES, given the key.\n \"\"\"\n assert len(k) == len(p) == 4\n wss = key_schedule(k)\n assert len(wss) == ROUNDS + 1\n\n ns = p\n for i in range(0, ROUNDS):\n ns = roundf(wss[i], ns, i)\n ns = key_addition(wss[ROUNDS], ns)\n return ns\n\ndef decrypt_block(k, c):\n \"\"\"\n k -> Key\n c -> Ciphertext\n\n Decrypts the ciphertext block encrypted with Mini-AES, given the key.\n \"\"\"\n assert len(k) == len(c) == 4\n wss = key_schedule(k)\n assert len(wss) == ROUNDS + 1\n\n ns = key_addition(wss[ROUNDS], c)\n for i in range(ROUNDS - 1, -1, -1):\n ns = inv_roundf(wss[i], ns, i)\n return ns\n\n# main function\n\ndef main():\n import random\n k = [random.randint(0, 15) for _ in range(4)]\n p = [random.randint(0, 15) for _ in range(4)]\n print(\"Key: {}\".format(k))\n print(\"Plaintext: {}\".format(p))\n\n c = encrypt_block(k, p)\n print(\"Ciphertext: {}\".format(c))\n d = decrypt_block(k, c)\n print(\"Decrypted ciphertext: {}\".format(d))\n\n if p == d:\n print(\"Decrypted ciphertext is the plaintext.\")\n else:\n print(\"ERROR: Decrypted ciphertext does not match the plaintext.\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"mini_aes/mini_aes.py","file_name":"mini_aes.py","file_ext":"py","file_size_in_byte":4791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"542068734","text":"from django.urls import path\nfrom courses.views import AllCoursesView, OneCourseView, CourseSignupView\n\n\napp_name = 'courses'\n\nurlpatterns = [\n path('', AllCoursesView.as_view(), name='courses'),\n path('/', OneCourseView.as_view(), name='course'),\n path('signup//', CourseSignupView.as_view()),\n]","sub_path":"otus_courses_site_backend/courses/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"62659711","text":"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nos.chdir('E:\\Code\\Python\\MachineLearning\\LinearRegression')\n#load data\ndata = np.loadtxt('ex1data1.txt',delimiter = ',')\nX = data[:,0]\ny = data[:,1]\ntheta = np.zeros(2)\nm = np.shape(X)[0]\nallIter = 10000\nallCost = np.zeros(allIter)\n\n#define hyophsis function\ndef hypothsis(x,theta):\n return theta[0] + x * theta[1]\n\n#define costFunction\ndef costFunction(train_X,train_y,theta):\n costSum = 0\n for i in range(m):\n costSum += (hypothsis(train_X[i],theta) - train_y[i])**2\n #print(i,'cost:',costSum)\n print('costSum:',costSum / (2 * m))\n return costSum\n\n#for every iter,update theta by using Gradient descent\ndef updateTheta(alpha):\n costSum1 = 0\n costSum2 = 0\n global theta\n for i in range(m):\n\n costSum1 += ((hypothsis(X[i],theta) - y[i])/ m)\n costSum2 += ((hypothsis(X[i],theta) - y[i]) * X[i]/ m)\n\n #updata theta\n theta[0] -= (costSum1 * alpha)\n theta[1] -= (costSum2 * alpha)\n\n print('Gradient:',theta[0],theta[1])\n\nalpha = 0.023\n\nfor numIter in range(allIter):\n allCost[numIter] = costFunction(X,y,theta)\n updateTheta(alpha)\n\nprint('hypothsis is %f *X + %f' % (theta[0],theta[1]))\n\nprint('Plot')\nplt.plot(allCost)\nax = plt.gca()#plt.gca is meaning plt get current axes in the figure.\nax.set_xscale('log')\nplt.title('LinearRegression')\nplt.xlabel('the number of Iters %d' % allIter)\nplt.ylabel('Cost')\nplt.show()\n","sub_path":"LinearRegression/LinearRegression.py","file_name":"LinearRegression.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"416199260","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n##########################################################\n## lecture de sondes de temperature 1-wire DS18B20 ##\n## pilotage des relais pour mise en route resistance ##\n## pilotage du ventialteur pour adapter sa vitesse ##\n## ##\n##########################################################\n \nimport sys\nimport datetime\nimport RPi.GPIO as GPIO\nfrom influxdb import InfluxDBClient\nfrom os import system\n\nEndProg=1;\nLast_Speed_Fan_Value=\"\";\nLast_Heating_Value=\"\";\n\n#Definition liste vitesse venilateur\n#list_fan_speed = ['1.0.0.0_86','0.1.0.0_80','1.1.0.0_75','0.0.1.0_70','1.0.1.0_65','0.1.1.0_60','1.1.1.0_50','0.0.0.1_40','1.0.0.1_30','0.1.0.1_25','1.1.1.1_00']\ndict_fan_speed = {\"85\":\"1.0.0.0\",\n \"80\":\"0.1.0.0\",\n \"75\":\"1.1.0.0\",\n \"70\":\"0.0.1.0\",\n \"65\":\"1.0.1.0\",\n \"60\":\"0.1.1.0\",\n \"50\":\"1.1.1.0\",\n \"40\":\"0.0.0.1\",\n \"30\":\"1.0.0.1\",\n \"25\":\"0.1.0.1\",\n \"00\":\"1.1.1.1\",\n }\ndict_heating_value = {\"0\":\"1.1.1\",\n \"1\":\"0.1.1\",\n \"2\":\"0.0.1\",\n \"3\":\"0.0.0\",\n }\n\ndict_gpio_fan_speed = {0:\"11\",1:\"12\",2:\"13\",3:\"15\"} ## Brochage gpio pour relais gestion vitesse ventilo\ndict_gpio_heating_relay = {0:\"29\",1:\"31\",2:\"33\"} ## Brochage gpio pour les relais de résistance. Forcer ventilateur si allumage resistance\n\n## Initialisation GPIO\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BOARD)\n\n## Configuration borne GPIO modulateur ventilateur\nchan_fan_list = [11,12,13,15]\nGPIO.setup(chan_fan_list, GPIO.OUT)\n\n## Configuration borne GPIO modulateur ventilateur\nchan_heating_list = [29,31,33]\nGPIO.setup(chan_heating_list, GPIO.OUT)\n\n## function to managed fan speed\ndef fan_speed(ValueFs):\n CountGpio = 0\n Matrix_Fan_Speed = dict_fan_speed[ValueFs]\n for ValuePin in Matrix_Fan_Speed:\n GpioPin = dict_gpio_fan_speed[CountGpio]\n if str(ValuePin) != \".\":\n #print (ValuePin)\n #print (GpioPin)\n #print (CountGpio)\n if ValuePin == \"1\":\n GPIO.output(int(GpioPin), GPIO.HIGH)\n #print (ValuePin,GpioPin)\n else:\n GPIO.output(int(GpioPin), GPIO.LOW)\n #print (ValuePin,GpioPin)\n CountGpio=CountGpio+1\n if ValueFs == '00':\n heating_turn_on(str(0))\n global Last_Speed_Fan_Value\n Last_Speed_Fan_Value=str(ValueFs)\n\n## function to managed heating\ndef heating_turn_on(ValueHeating):\n CountGpio = 0\n print (Last_Speed_Fan_Value) \n Matrix_Heating_Value = dict_heating_value[ValueHeating]\n if Matrix_Heating_Value[0] ==str(0):\n if Last_Speed_Fan_Value == \"00\":\n fan_speed(str(30))\n for ValuePin in Matrix_Heating_Value:\n GpioPin = dict_gpio_heating_relay[CountGpio]\n if str(ValuePin) != \".\":\n if ValuePin == \"1\":\n GPIO.output(int(GpioPin), GPIO.HIGH)\n #print (ValuePin,GpioPin)\n else:\n GPIO.output(int(GpioPin), GPIO.LOW)\n #print (ValuePin,GpioPin)\n CountGpio=CountGpio+1\n else:\n GPIO.output(29, GPIO.HIGH)\n GPIO.output(31, GPIO.HIGH)\n GPIO.output(33, GPIO.HIGH)\n print(\"Arret chauffage\")\n global Last_Heating_Value\n Last_Heating_Value=str(ValueHeating)\n\n## Remplacez les repertoires 28-xxxxxxxxxxx #########\n## par vos propres repertoires . ####################\n## Et si vous avez un nombre de sonde different #####\n## supprimer (ou ajouter) les lignes ci dessous #####\nsonde1 = \"/sys/bus/w1/devices/w1_bus_master1/28-041780c05dff/w1_slave\"\nsonde2 = \"/sys/bus/w1/devices/w1_bus_master1/28-041780ced3ff/w1_slave\"\n## et ajuster aussi les 2 lignes ci dessous #########\nsondes = [sonde1, sonde2]\nsonde_value = [0, 0]\n \n## fonction ouverture et lecture d'un fichier #######\ndef lire_fichier(fichier):\n f = open(fichier, 'r')\n lignes = f.readlines()\n f.close()\n return lignes\n \n# code principal ###################################\ndef lanceprog():\n while EndProg == 1:\n print (datetime.datetime.now())\n print (\"Dernières valeurs SF %s et Heating %s\" % (Last_Speed_Fan_Value,Last_Heating_Value,) )\n for (i, sonde) in enumerate(sondes):\n lignes = lire_fichier(sonde)\n while lignes[0].strip()[-3:] != 'YES': # lit les 3 derniers char de la ligne 0 et recommence si pas YES\n sleep(0.2)\n lignes = lire_fichier(sonde)\n \n temp_raw = lignes[1].split(\"=\")[1] # quand on a eu YES, on lit la temp apres le signe = sur la ligne 1\n sonde_value[i] = round(int(temp_raw) / 1000.0, 2) # le 2 arrondi a 2 chiffres apres la virgule\n \n json_body = [\n {\"measurement\": \"temperature\",\n \"tags\": {\"host\": \"rasp01.tumulte\",\"zone\": i },\n #\"time\": time.strftime('%Y-%m-%d %H:%M:%S'),\"fields\": {\"value\": sonde_value[i]}\n \"fields\": {\"value\": sonde_value[i]}\n }\n ]\n client = InfluxDBClient('localhost', 8086, 'root' , 'root' , 'datasensor_tumulte')\n client.write_points(json_body)\n client.close()\n \n #result = client.query('select value from temperature;')\n #print(\"Result: {0}\".format(result))\n \n print (\"sonde\",i,\"=\",sonde_value[i]) # affichage a l'ecran\n \n FanSpeed = input (\"Vitesse souhaitée:\")\n if FanSpeed == '0':\n FanSpeed ='00'\n ValueExistF = FanSpeed in dict_fan_speed\n if ValueExistF:\n FanSpeedC = fan_speed (FanSpeed)\n json_body = [\n {\"measurement\": \"speed_fan\",\n \"tags\": {\"host\": \"rasp01.tumulte\"},\n \"fields\": {\"value\": FanSpeed}\n }]\n client = InfluxDBClient('localhost', 8086, 'root' , 'root' , 'datasensor_tumulte')\n client.write_points(json_body)\n client.close()\n else:\n print(\"Value speed false\")\n \n if FanSpeed != '00':\n HeatingValue = input (\"Valeur nombre résistance:\")\n ValueExistH = HeatingValue in dict_heating_value\n if ValueExistH:\n HeatingValueC = heating_turn_on (HeatingValue)\n json_body = [\n {\"measurement\": \"heating_value\",\n \"tags\": {\"host\": \"rasp01.tumulte\"},\n \"fields\": {\"value\": HeatingValue}\n }\n ]\n client = InfluxDBClient('localhost', 8086, 'root' , 'root' , 'datasensor_tumulte')\n client.write_points(json_body)\n client.close()\n else:\n print(\"Value heating false\")\n\ndef exitprog():\n sys.exit(0)\n \ntry:\n print ('Utilisez Control-C pour finir')\n lanceprog()\n EndProg=0\n\nexcept KeyboardInterrupt:\n print (\"\\n\")\n exitprog()\n","sub_path":"pilote.malt.py","file_name":"pilote.malt.py","file_ext":"py","file_size_in_byte":6742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"482902840","text":"import sys\r\nfrom MayaviQWidget import MayaviQWidget\r\n\r\nfrom interface import *\r\nfrom PyQt4.QtGui import *\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom plotWidget import PlotWidget\r\nfrom dataProcessing import DataProcessing\r\nfrom datetime import datetime\r\n\r\nclass MainView(QtGui.QMainWindow):\r\n def __init__(self):\r\n QtGui.QMainWindow.__init__(self)\r\n self.ui = Ui_MainWindow()\r\n self.ui.setupUi(self)\r\n self.plotWidget = PlotWidget()\r\n\r\n #Mayavi Widget\r\n widget = self.ui.widget3d\r\n layout = QtGui.QGridLayout(widget)\r\n self.mayavi_widget = MayaviQWidget(self)\r\n layout.addWidget(self.mayavi_widget, 1, 1)\r\n\r\n self.measurements = []\r\n self.get_parameters()\r\n self.dataProcceser = DataProcessing(self)\r\n self.ui.progressBar.setValue(0)\r\n\r\n self.ui.btnRecalculate.clicked.connect(self.calculate)\r\n self.ui.btnSelect.clicked.connect(self.selectMeasurement)\r\n self.ui.btnDelete.clicked.connect(self.delItem)\r\n self.ui.btnDeleteAll.clicked.connect(self.delAllItems)\r\n self.connect(self.ui.actionNew_project, QtCore.SIGNAL(\"triggered()\"), self.openFile)\r\n\r\n def openFile(self):\r\n self.calc = {}\r\n fileName = QtGui.QFileDialog.getOpenFileNames(None,(\"Open File\"), \"/home/\", (\"Wav Files (*.wav)\"))\r\n #self.fileName = \"C:\\Users\\W\\Documents\\IR3D\\IR3D-Visualizer\\Audios de prueba\\stpatricks_s2r2.wav\"\r\n self.fileName = fileName[0]\r\n [self.calc[\"data\"], self.calc[\"fs\"]] = self.dataProcceser.load_wavefile(self.fileName)\r\n self.calc[\"time\"] = self.dataProcceser.generate_time(self.calc[\"fs\"], self.calc[\"data\"])\r\n self.ui.audioCutter.setValue(self.calc[\"time\"][len(self.calc[\"time\"])-1]*1000)\r\n self.calculate()\r\n\r\n def get_parameters(self):\r\n self.parameters = {}\r\n self.parameters[\"value2truncate\"] = self.ui.audioCutter.value()\r\n self.parameters[\"cutoff_frequency\"] = self.ui.lowPassFiltering.value()# 5000\r\n self.parameters[\"bandPassFilter\"] = None\r\n self.parameters[\"timeWindow\"] = self.ui.windowingWindowSize.value()\r\n self.parameters[\"number_of_windows\"] = self.ui.windowingQuantity.value()\r\n self.parameters[\"boundedExtended\"] = None\r\n\r\n def addList(self):\r\n rowPosition = self.ui.listMeasurements.rowCount()\r\n self.ui.listMeasurements.insertRow(rowPosition)\r\n self.ui.listMeasurements.setItem(rowPosition, 0, QtGui.QTableWidgetItem(\"Nameless\"))\r\n self.ui.listMeasurements.setItem(rowPosition, 1, QtGui.QTableWidgetItem(str(datetime.now())[:19 ]))\r\n self.ui.listMeasurements.setItem(rowPosition, 2, QtGui.QTableWidgetItem(str(self.fileName)))\r\n self.measurements.append(dict(self.calc))\r\n\r\n def delItem(self):\r\n self.ui.listMeasurements.removeRow(self.ui.listMeasurements.currentRow())\r\n\r\n def delAllItems(self):\r\n self.ui.listMeasurements.clear();\r\n self.ui.listMeasurements.setRowCount(0);\r\n\r\n def selectMeasurement(self):\r\n row = self.ui.listMeasurements.currentRow()\r\n self.calc=self.measurements[row]\r\n self.plotWidget.ploter(self)\r\n\r\n def calculate(self):\r\n if self.fileName[0] != []:\r\n self.get_parameters()\r\n self.ui.progressBar.setValue(8)\r\n self.calc[\"data\"] = self.dataProcceser.truncate_value(self.calc[\"data\"],self.calc[\"fs\"])\r\n self.ui.progressBar.setValue(10)\r\n self.calc[\"audio_filtered\"] = self.dataProcceser.low_filtering(self.calc[\"data\"], self.calc[\"fs\"])\r\n min_value, max_value = self.dataProcceser.get_min_max(self.calc[\"audio_filtered\"])\r\n self.ui.progressBar.setValue(15)\r\n self.calc[\"audio_filtered_norm\"] = np.matrix([self.dataProcceser.normalizer(np.array(self.calc[\"audio_filtered\"][channel, :])[0], min_value, max_value) for channel in range(4)])\r\n self.ui.progressBar.setValue(20)\r\n self.calc[\"intensity\"] = self.dataProcceser.pressure_to_intensity(self.calc[\"audio_filtered\"])\r\n self.ui.progressBar.setValue(25)\r\n [self.calc[\"intensity_windows\"], self.calc[\"az_el_windows\"], self.calc[\"i_db\"]] = self.dataProcceser.temporal_windowing(self.calc[\"intensity\"], self.calc[\"fs\"])\r\n self.ui.progressBar.setValue(40)\r\n self.calc[\"peaks\"] = self.dataProcceser.window_selector(self.calc[\"i_db\"], self.calc[\"fs\"])\r\n self.ui.progressBar.setValue(45)\r\n self.calc[\"normalizado\"]= self.dataProcceser.normalizer(self.calc[\"i_db\"][0, self.calc[\"peaks\"]])\r\n\r\n \"\"\"self.widMatplot.plot(self.audio, self.fs, \"Audio\")\"\"\"\r\n self.ui.progressBar.setValue(50)\r\n self.plotWidget.ploter(self)\r\n self.mayavi_widget.update_plot(self)\r\n\r\n self.addList()\r\n\r\n\r\nif __name__== \"__main__\":\r\n app = QtGui.QApplication(sys.argv)\r\n myapp = MainView()\r\n myapp.show()\r\n sys.exit(app.exec_())\r\n\r\n\r\n\r\n\r\n","sub_path":"Versiones anteriores/Version 2.0/QT/mainView.py","file_name":"mainView.py","file_ext":"py","file_size_in_byte":4991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"582208429","text":"#!/usr/bin/env python3\nfrom pprint import pprint\nimport random\nimport os\n\nR = [[0, 20, 10, 0, 30], \n [0, 0, 0, 10, 30], \n [0, 0, 0, 20, 30], \n [0, 0, 0, 0, 30], \n [0, 0, 0, 0, 0]]\n\nQ = [[0, 0, 0, 0, 0], \n [0, 0, 0, 0, 0], \n [0, 0, 0, 0, 0], \n [0, 0, 0, 0, 0], \n [0, 0, 0, 0, 0]]\n\nactions = {0:[1, 2, 4], \n 1:[3, 4], \n 2:[3, 4], \n 3:[4], \n 4:None}\n\niState = 0 \n\nepsilon = 0.9 \ngamma = 0.8\n\ndef getActions(state):\n return actions.get(state)\n\ndef getRewardValue(state, action):\n return R[state][action]\n\ndef getCurrentQ(state, action):\n return Q[state][action]\n\ndef updateQ(state, action):\n reward = getRewardValue(state, action)\n if action == 4:\n Q[state][action] = reward \n else:\n Q[state][action] = reward + (gamma * getCurrentQ(action, getMaxAction(action)))\n \ndef getMaxAction(state):\n maxQ = 0\n act = 0\n action = getActions(state)\n for a in action:\n if Q[state][a] > maxQ:\n maxQ = Q[state][a]\n act = a\n count = Q[state].count(maxQ)\n if count > 1:\n candidates = []\n for a in action:\n if Q[state][a] == maxQ:\n candidates.append(a)\n return random.choice(candidates)\n else:\n return act\n\ndef getNextAction(state, verbose=False):\n actions = getActions(state)\n candidates = []\n for a in actions:\n if Q[state][a] == 0:\n candidates.append(a)\n if len(candidates) > 0:\n if verbose:\n print(\"(Explore!)\")\n return random.choice(candidates)\n elif random.random() < epsilon:\n if verbose:\n print(\"(Explore!)\")\n return random.choice(getActions(state))\n else:\n return getMaxAction(state)\n\ndef runTrials(maxIt=100, verbose=False, gam=0.8):\n global epsilon\n global gamma\n global Q\n\n newQ = [[0, 0, 0, 0, 0], \n [0, 0, 0, 0, 0], \n [0, 0, 0, 0, 0], \n [0, 0, 0, 0, 0], \n [0, 0, 0, 0, 0]]\n Q = newQ\n iterations = 0\n gamma = gam\n maxIterations = maxIt \n while iterations < maxIterations:\n state = iState\n if verbose:\n print(\"Iteration: {}\\n\".format(iterations))\n while state != 4:\n action = getNextAction(state, verbose)\n if verbose:\n print(\"State: {}\".format(state+1))\n print(\"Action: {}\".format(action+1))\n print(\"Epsilon: {}\".format(epsilon))\n updateQ(state, action)\n state = action\n if verbose:\n for x in Q:\n for y in x:\n print(\"{:5.1f}\".format(y), end = \"\")\n print()\n if verbose:\n os.system('clear')\n epsilon = 1.0 - (iterations/maxIterations)\n iterations = iterations + 1\n print(\"Iterations: {}, Gamma: {}\".format(iterations, gamma))\n for x in Q:\n for y in x:\n print(\"{:5.1f}\".format(y), end = \"\")\n print()\n print()\n\nrunTrials(maxIt = 25, verbose=True, gam=0.8)\nrunTrials(gam=0) \nrunTrials(gam=0.5)\nrunTrials(gam=0.8)\nrunTrials(gam=1)\n\n\n","sub_path":"simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"405324237","text":"import boto3\n\n# Define routine function for future usage\n\n\ndef CreateBucket(name):\n s3_client = boto3.client('s3')\n s3_client.create_bucket(Bucket=name)\n return True\n\n\ndef DeleteBucket(name):\n s3_client = boto3.client('s3')\n s3_client.delete_bucket(Bucket=name)\n return True\n\n\ndef EnforceS3Encryption(name):\n\n # Start with S3 resource\n s3 = boto3.resource('s3')\n s3_client = boto3.client('s3')\n\n # Create our bucket object\n bucket = s3.Bucket(name)\n print(f\"Encrypting {bucket.name} at S3 bucket creation by JYU\")\n\n # Perform the Encryption\n response = s3_client.put_bucket_encryption(\n # leverage bucket object, grab the name\n Bucket=bucket.name,\n\n # Put the Encryption config\n ServerSideEncryptionConfiguration={\n 'Rules': [\n {\n 'ApplyServerSideEncryptionByDefault': {\n 'SSEAlgorithm': 'AES256'\n }\n }\n ]\n }\n )\n print(response)\n\n\nif __name__ == \"__main__\":\n \"\"\"\n 🤏 Use glue to tie all together\n \"\"\"\n Name = 'testbucketforencryption-bs3-jyu' # all lower_case, must be unique\n CreateBucket(Name) # apply the CreateBucket function\n EnforceS3Encryption(Name) # apply the Enforce function on name\n # DeleteBucket(Name)\n\n","sub_path":"12 - Enforcing Amazon S3 with Python - s3.py","file_name":"12 - Enforcing Amazon S3 with Python - s3.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"639124290","text":"# -*- coding: utf-8 -*-\n# Copyright 2021, SERTIT-ICube - France, https://sertit.unistra.fr/\n# This file is part of eoreader project\n# https://github.com/sertit/eoreader\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\"\"\" Product Factory, class creating products according to their names \"\"\"\n\nfrom __future__ import annotations\n\nimport importlib\nimport logging\nimport re\nfrom enum import unique\nfrom pathlib import Path\nfrom typing import Union\n\nfrom cloudpathlib import AnyPath, CloudPath\nfrom sertit import files, strings\nfrom sertit.misc import ListEnum\n\nfrom eoreader.utils import EOREADER_NAME\n\nLOGGER = logging.getLogger(EOREADER_NAME)\n\n\n@unique\nclass CheckMethod(ListEnum):\n \"\"\"Methods to recognize a product\"\"\"\n\n MTD = \"Metadata\"\n \"\"\"Check the metadata: faster method\"\"\"\n\n NAME = \"Filename\"\n \"\"\"\n Check the filename:\n\n Safer method that allows modified product names as it recursively looks for the metadata name in the product files.\n For products that have generic metadata files (ie. RS2 that as mtd named `product.xml`),\n it also checks the band name.\n \"\"\"\n\n BOTH = \"Both\"\n \"\"\"Check the metadata and the filename: Double check if you have a doubt.\"\"\"\n\n\n@unique\nclass Platform(ListEnum):\n \"\"\"Platforms supported by EOReader\"\"\"\n\n S1 = \"Sentinel-1\"\n \"\"\"Sentinel-1\"\"\"\n\n S2 = \"Sentinel-2\"\n \"\"\"Sentinel-2\"\"\"\n\n S2_THEIA = \"Sentinel-2 Theia\"\n \"\"\"Sentinel-2 Theia\"\"\"\n\n S3 = \"Sentinel-3\"\n \"\"\"Sentinel-3\"\"\"\n\n L8 = \"Landsat-8\"\n \"\"\"Landsat-8\"\"\"\n\n L7 = \"Landsat-7\"\n \"\"\"Landsat-7\"\"\"\n\n L5 = \"Landsat-5\"\n \"\"\"Landsat-5\"\"\"\n\n L4 = \"Landsat-4\"\n \"\"\"Landsat-4\"\"\"\n\n L3 = \"Landsat-3\"\n \"\"\"Landsat-3\"\"\"\n\n L2 = \"Landsat-2\"\n \"\"\"Landsat-2\"\"\"\n\n L1 = \"Landsat-1\"\n \"\"\"Landsat-1\"\"\"\n\n PLA = \"PlanetScope\"\n \"\"\"PlanetScope\"\"\"\n\n # RPD = \"RapidEye\"\n # \"\"\"RapidEye\"\"\"\n #\n # SKY = \"SkySat\"\n # \"\"\"SkySat\"\"\"\n\n CSK = \"COSMO-SkyMed\"\n \"\"\"COSMO-SkyMed\"\"\"\n\n TSX = \"TerraSAR-X\"\n \"\"\"TerraSAR-X\"\"\"\n\n RS2 = \"RADARSAT-2\"\n \"\"\"RADARSAT-2\"\"\"\n\n PLD = \"Pleiades\"\n \"\"\"Pléiades\"\"\"\n\n SPOT7 = \"Spot-7\"\n \"\"\"SPOT-7\"\"\"\n\n SPOT6 = \"Spot-6\"\n \"\"\"SPOT-6\"\"\"\n\n\nPLATFORM_REGEX = {\n Platform.S1: r\"S1[AB]_(IW|EW|SM|WV)_(RAW|SLC|GRD|OCN)[FHM_]_[0-2]S[SD][HV]_\\d{8}T\\d{6}_\\d{8}T\\d{6}_\\d{6}_.{11}\",\n Platform.S2: r\"S2[AB]_MSIL(1C|2A)_\\d{8}T\\d{6}_N\\d{4}_R\\d{3}_T\\d{2}\\w{3}_\\d{8}T\\d{6}\",\n Platform.S2_THEIA: r\"SENTINEL2[AB]_\\d{8}-\\d{6}-\\d{3}_L(2A|1C)_T\\d{2}\\w{3}_[CDH](_V\\d-\\d|)\",\n Platform.S3: r\"S3[AB]_[OS]L_[012]_\\w{6}_\\d{8}T\\d{6}_\\d{8}T\\d{6}_\\d{8}T\\d{6}_\\w{17}_\\w{3}_[OFDR]_(NR|ST|NT)_\\d{3}\",\n Platform.L8: r\"LC08_L1(GT|TP)_\\d{6}_\\d{8}_\\d{8}_\\d{2}_(RT|T1|T2)\",\n Platform.L7: r\"LE07_L1(GT|TP|GS)_\\d{6}_\\d{8}_\\d{8}_\\d{2}_(RT|T1|T2)\",\n Platform.L5: r\"L[TM]05_L1(TP|GS)_\\d{6}_\\d{8}_\\d{8}_\\d{2}_(T1|T2)\",\n Platform.L4: r\"L[TM]04_L1(TP|GS)_\\d{6}_\\d{8}_\\d{8}_\\d{2}_(T1|T2)\",\n Platform.L3: r\"LM03_L1(TP|GS)_\\d{6}_\\d{8}_\\d{8}_\\d{2}_T2\",\n Platform.L2: r\"LM02_L1(TP|GS)_\\d{6}_\\d{8}_\\d{8}_\\d{2}_T2\",\n Platform.L1: r\"LM01_L1(TP|GS)_\\d{6}_\\d{8}_\\d{8}_\\d{2}_T2\",\n Platform.PLA: r\"\\d{8}_\\d{6}_(\\d{2}_|)\\w{4}\",\n Platform.CSK: [\n r\".+\", # Need to check inside as the folder does not have any recognizable name\n r\"CSKS[1-4]_(RAW|SCS|DGM|GEC|GTC)_[UB]_(HI|PP|WR|HR|S2)_\"\n r\"\\w{2}_(HH|VV|VH|HV|CO|CH|CV)_[LR][AD]_[FS][NF]_\\d{14}_\\d{14}\\.h5\",\n ],\n Platform.TSX: r\"T[SD]X1_SAR__(SSC|MGD|GEC|EEC)_[SR]E___[SH][MCLS]_[SDTQ]_[SD]RA_\\d{8}T\\d{6}_\\d{8}T\\d{6}\",\n Platform.RS2: r\"RS2_OK\\d+_PK\\d+_DK\\d+_.{2,}_\\d{8}_\\d{6}(_(HH|VV|VH|HV)){1,4}_S(LC|GX|GF|CN|CW|CF|CS|SG|PG)\",\n Platform.PLD: r\"IMG_PHR1[AB]_(P|MS|PMS|MS-N|MS-X|PMS-N|PMS-X)_\\d{3}\",\n Platform.SPOT7: r\"IMG_SPOT7_(P|MS|PMS|MS-N|MS-X|PMS-N|PMS-X)_\\d{3}_\\w\",\n Platform.SPOT6: r\"IMG_SPOT6_(P|MS|PMS|MS-N|MS-X|PMS-N|PMS-X)_\\d{3}_\\w\",\n}\n\n# Not used for now\nMTD_REGEX = {\n Platform.S1: r\".*s1[ab]-(iw|ew|sm|wv)\\d*-(raw|slc|grd|ocn)-[hv]{2}-\\d{8}t\\d{6}-\\d{8}t\\d{6}-\\d{6}-\\w{6}-\\d{3}\\.xml\",\n Platform.S2: [\n r\"MTD_MSIL(1C|2A)\\.xml\", # Too generic name, check also a band\n r\"T\\d{2}\\w{3}_\\d{8}T\\d{6}_B\\d{2}(_\\d0m|).jp2\",\n ],\n Platform.S2_THEIA: f\"{PLATFORM_REGEX[Platform.S2_THEIA]}_MTD_ALL\\.xml\",\n Platform.S3: [\n r\"xfdumanifest\\.xml\", # Not the real metadata...\n r\"(S\\d|Oa\\d{2})_radiance(_an|).nc\",\n ],\n Platform.L8: f\"{PLATFORM_REGEX[Platform.L8]}_MTL\\.txt\",\n Platform.L7: f\"{PLATFORM_REGEX[Platform.L7]}_MTL\\.txt\",\n Platform.L5: f\"{PLATFORM_REGEX[Platform.L5]}_MTL\\.txt\",\n Platform.L4: f\"{PLATFORM_REGEX[Platform.L4]}_MTL\\.txt\",\n Platform.L3: f\"{PLATFORM_REGEX[Platform.L3]}_MTL\\.txt\",\n Platform.L2: f\"{PLATFORM_REGEX[Platform.L2]}_MTL\\.txt\",\n Platform.L1: f\"{PLATFORM_REGEX[Platform.L1]}_MTL\\.txt\",\n Platform.PLA: r\"\\d{8}_\\d{6}_(\\d{2}_|)\\w{4}_[13][AB]_.*metadata.*\\.xml\",\n Platform.CSK: f\"{PLATFORM_REGEX[Platform.CSK][1]}\\.xml\",\n Platform.TSX: f\"{PLATFORM_REGEX[Platform.TSX]}\\.xml\",\n Platform.RS2: [\n r\"product\\.xml\", # Too generic name, check also a band\n r\"imagery_[HV]{2}\\.tif\",\n ],\n Platform.PLD: r\"DIM_PHR1[AB]_(P|MS|PMS|MS-N|MS-X|PMS-N|PMS-X)_\\d{15}_(SEN|PRJ|ORT|MOS)_.{10,}\\.XML\",\n Platform.SPOT7: r\"DIM_SPOT7_(P|MS|PMS|MS-N|MS-X|PMS-N|PMS-X)_\\d{15}_(SEN|PRJ|ORT|MOS)_.{10,}\\.XML\",\n Platform.SPOT6: r\"DIM_SPOT6_(P|MS|PMS|MS-N|MS-X|PMS-N|PMS-X)_\\d{15}_(SEN|PRJ|ORT|MOS)_.{10,}\\.XML\",\n}\n\n\nclass Reader:\n \"\"\"\n Factory class creating satellite products according to their names.\n\n It creates a singleton that you can call only on,e time per file.\n \"\"\"\n\n def __init__(self):\n self._platform_regex = {}\n self._mtd_regex = {}\n\n # Register platforms\n for platform, regex in PLATFORM_REGEX.items():\n self._platform_regex[platform] = self._compile(regex, prefix=\"\", suffix=\"\")\n\n # Register metadata\n for platform, regex in MTD_REGEX.items():\n self._mtd_regex[platform] = self._compile(regex, prefix=\".*\", suffix=\"\")\n\n @staticmethod\n def _compile(regex: Union[str, list], prefix=\"^\", suffix=\"&\") -> list:\n \"\"\"\n Compile regex or list of regex\n\n Args:\n regex (Union[str, list]): Regex in `re` sense\n prefix (str): Prefix of regex, ^ by default (means start of the string)\n suffix (str): Prefix of regex, & by default (means end of the string)\n\n Returns:\n list: List of compiled pattern\n \"\"\"\n\n def _compile_(regex_str: str):\n return re.compile(f\"{prefix}{regex_str}{suffix}\")\n\n # Case folder is not enough to identify the products (ie. COSMO Skymed)\n if isinstance(regex, list):\n comp = [_compile_(regex) for regex in regex]\n else:\n comp = [_compile_(regex)]\n\n return comp\n\n def open(\n self,\n product_path: Union[str, CloudPath, Path],\n archive_path: Union[str, CloudPath, Path] = None,\n output_path: Union[str, CloudPath, Path] = None,\n method: CheckMethod = CheckMethod.MTD,\n remove_tmp: bool = False,\n ) -> \"Product\": # noqa: F821\n \"\"\"\n Open the product.\n\n .. code-block:: python\n\n >>> from eoreader.reader import Reader\n >>> path = r\"S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip\"\n >>> Reader().open(path)\n \n\n Args:\n product_path (Union[str, CloudPath, Path]): Product path\n archive_path (Union[str, CloudPath, Path]): Archive path\n output_path (Union[str, CloudPath, Path]): Output Path\n method (CheckMethod): Checking method used to recognize the products\n remove_tmp (bool): Remove temp files (such as clean or orthorectified bands...) when the product is deleted\n\n Returns:\n Product: Correct products\n\n \"\"\"\n prod = None\n for platform in Platform.list_names():\n if method == CheckMethod.MTD:\n is_valid = self.valid_mtd(product_path, platform)\n elif method == CheckMethod.NAME:\n is_valid = self.valid_name(product_path, platform)\n else:\n is_valid = self.valid_name(product_path, platform) and self.valid_mtd(\n product_path, platform\n )\n\n if is_valid:\n sat_class = platform.lower() + \"_product\"\n\n # Manage both optical and SAR\n try:\n mod = importlib.import_module(f\"eoreader.products.sar.{sat_class}\")\n except ModuleNotFoundError:\n mod = importlib.import_module(\n f\"eoreader.products.optical.{sat_class}\"\n )\n\n class_ = getattr(mod, strings.snake_to_camel_case(sat_class))\n prod = class_(\n product_path=product_path,\n archive_path=archive_path,\n output_path=output_path,\n remove_tmp=remove_tmp,\n )\n break\n\n if not prod:\n LOGGER.warning(\n \"There is no existing products in EOReader corresponding to %s\",\n product_path,\n )\n\n return prod\n\n def valid_name(\n self, product_path: Union[str, CloudPath, Path], platform: Union[str, Platform]\n ) -> bool:\n \"\"\"\n Check if the product's name is valid for the given satellite\n\n\n .. code-block:: python\n\n >>> from eoreader.reader import Reader, Platform\n >>> path = r\"S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip\"\n >>> With IDs\n >>> Reader().valid_name(path, \"S1\")\n False\n >>> Reader().valid_name(path, \"S2\")\n True\n\n >>> # With names\n >>> Reader().valid_name(path, \"Sentinel-1\")\n False\n >>> Reader().valid_name(path, \"Sentinel-2\")\n True\n\n >>> # With Platform\n >>> Reader().valid_name(path, Platform.S1)\n False\n >>> Reader().valid_name(path, Platform.S2)\n True\n\n Args:\n product_path (Union[str, CloudPath, Path]): Product path\n platform (str): Platform's name or ID\n\n Returns:\n bool: True if valid name\n\n \"\"\"\n platform = Platform.convert_from(platform)[0]\n regex = self._platform_regex[platform]\n return self._is_filename_valid(product_path, regex)\n\n def valid_mtd(\n self, product_path: Union[str, CloudPath, Path], platform: Union[str, Platform]\n ) -> bool:\n \"\"\"\n Check if the product's mtd is in the product folder/archive\n\n .. code-block:: python\n\n >>> from eoreader.reader import Reader, Platform\n >>> path = r\"S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip\"\n >>> With IDs\n >>> Reader().valid_mtd(path, \"S1\")\n False\n >>> Reader().valid_mtd(path, \"S2\")\n True\n\n >>> # With names\n >>> Reader().valid_mtd(path, \"Sentinel-1\")\n False\n >>> Reader().valid_mtd(path, \"Sentinel-2\")\n True\n\n >>> # With Platform\n >>> Reader().valid_mtd(path, Platform.S1)\n False\n >>> Reader().valid_mtd(path, Platform.S2)\n True\n\n Args:\n product_path (Union[str, CloudPath, Path]): Product path\n platform (Union[str, Platform]): Platform's name or ID\n\n Returns:\n bool: True if valid name\n\n \"\"\"\n product_path = AnyPath(product_path)\n\n platform = Platform.convert_from(platform)[0]\n\n # Here the list is a check of several files\n regex_list = self._mtd_regex[platform]\n\n # False by default\n is_valid = [False for idx in regex_list]\n\n for idx, regex in enumerate(regex_list):\n # Folder\n if product_path.is_dir():\n for fle in product_path.glob(\"**/*.*\"):\n if regex.match(str(fle)):\n is_valid[idx] = True\n break\n\n # Archive\n else:\n if product_path.is_file():\n fls = files.get_archived_file_list(product_path)\n for fle in fls:\n if regex.match(fle):\n is_valid[idx] = True\n break\n\n return all(is_valid)\n\n @staticmethod\n def _is_filename_valid(\n product_path: Union[str, CloudPath, Path], regex: Union[list, re.Pattern]\n ) -> bool:\n \"\"\"\n Check if the filename corresponds to the given satellite regex.\n\n Checks also if a file inside the directory is correct.\n\n .. WARNING::\n Two level max for the moment\n\n Args:\n product_path (Union[str, CloudPath, Path]): Product path\n regex (Union[list, re.Pattern]): Regex or list of regex\n\n Returns:\n bool: True if the filename corresponds to the given satellite regex\n \"\"\"\n product_path = AnyPath(product_path)\n product_file_name = files.get_filename(product_path)\n\n # Case folder is not enough to identify the products (ie. COSMO Skymed)\n # WARNING: Two level max for the moment\n is_valid = bool(regex[0].match(product_file_name))\n if is_valid and len(regex) > 1:\n is_valid = False # Reset\n if product_path.is_dir():\n file_list = product_path.iterdir()\n for file in file_list:\n if regex[1].match(file.name):\n is_valid = True\n break\n else:\n try:\n file_list = files.get_archived_file_list(product_path)\n for file in file_list:\n if regex[1].match(file):\n is_valid = True\n break\n except TypeError:\n LOGGER.debug(\n f\"The product {product_file_name} should be a folder or an archive (.tar or .zip)\"\n )\n\n return is_valid\n","sub_path":"eoreader/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":14899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"525342387","text":"#!/usr/biny/env python\n\n\"\"\"\ntrain_behavior_model.py\nTrain the behavior model as a state-action value approximation.\n\"\"\"\n\n__version__ = \"0.0.1\"\n__authors__ = [(\"David Qiu\", \"dq@cs.cmu.edu\"),\n (\"Karthik Paga\", \"kpaga@andrew.cmu.edu\")]\n__copyright__ = \"Copyright (C) 2018, Hactauton 2018 Dolan Wins Team. All rights reserved.\"\n\n\nimport os.path\nimport numpy as np\nimport keras\nfrom keras.layers import Dense, Activation\n\nimport pdb\nimport pandas as pd\n\n\nmodel = None\n\n\ndef build_model(input_dim, output_dim, fname_model):\n model = keras.models.Sequential()\n\n model.add(Dense(32, activation='relu', input_dim=input_dim))\n model.add(Dense(32, activation='relu'))\n model.add(Dense(32, activation='relu'))\n #model.add(Dense(32, activation='relu'))\n model.add(Dense(output_dim, activation='linear'))\n\n with open(fname_model, 'w') as f:\n f.write(model.to_json())\n\n optimizer = keras.optimizers.Adam(lr=1e-4, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)\n #optimizer = keras.optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=None, decay=0.0)\n\n model.compile(loss='mean_squared_error', optimizer=optimizer)\n\n return model\n\n\ndef train_model(trainX, trainY, fname_weights, fname_train, epochs=10, verbose=False):\n global model\n\n if os.path.isfile(fname_weights):\n model.load_weights(fname_weights)\n pass\n \n hist = model.fit(\n trainX, trainY,\n batch_size=32, epochs=epochs,\n verbose=verbose)\n\n model.save_weights(fname_weights)\n\n with open(fname_train, 'a') as f:\n hist_loss = hist.history['loss']\n for i_hist in range(len(hist_loss)):\n f.write('%f\\n' % hist_loss[i_hist])\n\n return hist.history['loss']\n\n\ndef main():\n global model\n\n env = np.load('../data/env.npy')\n drv = np.load('../data/drv.npy')\n chart = np.load('../data/chart.npy')\n M_env = np.shape(env)[1]\n M_drv = np.shape(drv)[1]\n M_chart = np.shape(chart)[1]\n\n fname_model = '../data/behavior_model.json'\n fname_weights = '../data/behavior_model_weights.h5'\n fname_train = '../data/behavior_model_train.log'\n\n input_dim = M_env + M_drv\n output_dim = M_chart\n model = build_model(input_dim, output_dim, fname_model)\n\n trainX = []\n trainY = []\n for i in range(len(env)):\n if not (np.isnan(env[i]).any() or np.isnan(drv[i]).any() or np.isnan(chart[i]).any()):\n x = np.concatenate((env[i], drv[i]))\n trainX.append(x)\n trainY.append(chart[i])\n trainX = np.array(trainX)\n trainY = np.array(trainY)\n print('processed data set (N=%d/%d)' % (len(trainX),len(env)))\n\n hist = train_model(\n trainX, trainY,\n fname_weights, fname_train, \n epochs=100, verbose=True)\n\n print('training finished')\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"src/train_behavior_model.py","file_name":"train_behavior_model.py","file_ext":"py","file_size_in_byte":2705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"519347948","text":"#!/usr/bin/python\n\n\"\"\"\nA small module to display *something* when a python graphics program tries to\nimport a GUI module and can't. At this point you want to tell the user what\nis wrong and maybe how to correct the problem. But in some environments just\nprinting something to stderr doesn't work as there is no terminal to write\nthe text to.\n\nThis code tries to use the web browser to display error text.\n\"\"\"\n\nimport os\nimport time\nimport tempfile\nimport webbrowser\n\n__version__ = '0.4'\n\n\ndef notify(msg, submsg=None, html=None, header=None, colour=None):\n \"\"\"Tell the user something using the web browser.\n\n msg the topline message\n submsg optional submessage\n html optional replacement HTML page text, formatted so:\n html.format(msg=msg, submsg=submsg)\n header optional browser tab title text (default: 'ERROR')\n colour optional colour string, default is '#9988ee'\n \"\"\"\n\n # handle optional parameters\n if not submsg:\n submsg = ''\n\n if not html:\n html = '''

{msg}

{submsg}

'''\n\n if not header:\n header = 'ERROR'\n\n if not colour:\n colour = '#ffb8b8'\n\n # construct the page contents\n html = html.format(msg=msg, submsg=submsg)\n\n body_top = '''\n\n {header}\n \n \n
\n'''.format(header=header, lcurly='{', rcurly='}', colour=colour) \n\n body_bot = '''\n
\n

{progname} v{version}

\n
\n
\n \n'''.format(progname=notify.__name__, version=__version__)\n\n # create a temporary *.HTML file containing the user message\n (fd, filename) = tempfile.mkstemp(suffix='.html', prefix='notify_')\n with open(filename, 'w') as fd:\n fd.write(body_top + html + body_bot)\n\n # display the message\n webbrowser.open_new('file:///' + filename)\n\n # remove the temporary file\n time.sleep(2) # FUDGE: give browser time to load the file\n os.remove(filename) # before we delete it!\n\n\nif __name__ == '__main__':\n try:\n import not_found\n except ImportError:\n notify(msg='''Sorry, can't find the 'not_found' module, '''\n '''you'll have to install it.''')\n\n notify(msg='''Sorry, can't find the 'not_found' module, '''\n '''you'll have to install it.''',\n submsg='''You can get it here''',\n header='WARNING', html='

{msg}

{submsg}
',\n colour='#ccccff')\n","sub_path":"notify.py","file_name":"notify.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"287706461","text":"from django.conf.urls import patterns, url\n\n\nurlpatterns = patterns('stories',\n url(r'^$', 'views.home', name='home'), #Home Page\n url(r'^submit/$', 'views.create_story', name='create_story'), #Create a story\n url(r'^stories/$', 'views.filter_stories', name='filter_stories'), #Filter Story\n url(r'^story/(?P[\\d]+)/$', 'views.view_story', name='view_story'), #View Story\n url(r'^story/(?P[\\d]+)/edit/$', 'views.edit_story', name='edit_story'), #Edit Story\n url(r'^story/(?P[\\d]+)/delete/$', 'views.delete_story', name='delete_story'), #Delete Story\n url(r'^story/(?P[\\d]+)/up_vote/$', 'views.up_vote', name='up_vote'), #UpVote Story\n url(r'^story/(?P[\\d]+)/down_vote/$', 'views.down_vote', name='down_vote'), #DownVote Story\n\n url(r'^story/(?P[\\d]+)/comment/$', 'views.create_comment', name='create_comment'), #Create Comment\n url(r'^story/(?P[\\d]+)/comments/$', 'views.view_comments', name='view_comments'), #View Comment\n url(r'^story/(?P[\\d]+)/comment/(?P[\\d]+)/edit/$', 'views.edit_comment', #Edit Comment\n name='edit_comment'),\n url(r'^story/(?P[\\d]+)/comment/(?P[\\d]+)/delete/$', #Delete Comment\n 'views.delete_comment',name='delete_comment'),\n\n url(r'^admin/$', 'views.admin_story', name='admin_story'), #Admin Page\n\n\n)\n","sub_path":"stories/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"371538538","text":"import torch\n\n# Train the network\ndef train_network(epochs, steps, train_loader, test_loader, model, device, optimizer, criterion):\n \"\"\"Train the network\n\n Parameters:\n epochs (int): epochs number\n steps (int): the number of steps\n train_loader (list): the train loader images\n test_loader (list): the test loader images\n model (object): the trained model\n device (string): device (cpu or cuda)\n optimizer (object): training optimizer\n criterion (object): triing criterion\n \"\"\"\n \n print()\n print(\"Training the network...\")\n print()\n \n train_losses, test_losses = [], []\n running_loss = 0\n print_every = 10\n for epoch in range(epochs):\n for inputs, labels in train_loader:\n steps += 1\n # Move input and label tensors to the default device\n inputs, labels = inputs.to(device), labels.to(device)\n\n optimizer.zero_grad()\n\n logps = model.forward(inputs)\n loss = criterion(logps, labels)\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n\n if steps % print_every == 0:\n test_loss = 0\n accuracy = 0\n model.eval()\n with torch.no_grad():\n for inputs, labels in test_loader:\n inputs, labels = inputs.to(device), labels.to(device)\n logps = model.forward(inputs)\n batch_loss = criterion(logps, labels)\n\n test_loss += batch_loss.item()\n\n # Calculate accuracy\n ps = torch.exp(logps)\n top_p, top_class = ps.topk(1, dim=1)\n equals = top_class == labels.view(*top_class.shape)\n accuracy += torch.mean(equals.type(torch.FloatTensor)).item()\n\n train_losses.append(running_loss/len(train_loader))\n test_losses.append(test_loss/len(test_loader))\n\n print(f\"Epoch {epoch+1}/{epochs}.. \"\n f\"Train loss: {running_loss/print_every:.3f}.. \"\n f\"Test loss: {test_loss/len(test_loader):.3f}.. \"\n f\"Test accuracy: {accuracy/len(test_loader):.3f}\")\n running_loss = 0\n model.train()","sub_path":"train_network.py","file_name":"train_network.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"309757290","text":"def isSafe( maze, x, y,N ): \n if x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1: \n return True\n return False\n# path=[]\n\ndef printSol(sol):\n for i in sol:\n print(i)\n print(\"\\n\\n\\n\")\n\ndef paths(arr,x,y,sol,n,s,path):\n if x==n-1 and y==n-1:\n path.append(s)\n return (True,path)\n if isSafe(arr,x,y,n):\n sol[x][y]=1\n # print(x,y,s)\n # printSol(sol)\n if sol[x+1][y]!=1 and paths(arr,x+1,y,sol,n,s+'D',path)[0]:\n sol[x][y]=0\n if sol[x-1][y]!=1 and paths(arr,x-1,y,sol,n,s+'U',path)[0]:\n sol[x][y]=0\n if sol[x][y+1]!=1 and paths(arr,x,y+1,sol,n,s+'R',path)[0]:\n sol[x][y]=0\n if sol[x][y-1]!=1 and paths(arr,x,y-1,sol,n,s+'L',path)[0]:\n sol[x][y]=0\n sol[x][y]=0\n # printSol(sol)\n\n return (False,path)\n\ndef findPath(arr, n):\n # code here\n sol=[[0 for i in range(n+1)] for j in range(n+1)]\n path=[]\n s=\"\"\n p=paths(arr,0,0,sol,n,'',path)\n fin=[]\n for i in p[1]:\n if \"LR\" not in i and \"RL\" not in i and \"UD\" not in i and \"DU\" not in i:\n fin.append(i)\n for i in sorted(fin):\n s+=i+' '\n return s\n\nif __name__=='__main__':\n t = int(input())\n for i in range(t):\n n = list(map(int, input().strip().split()))\n arr = list(map(int, input().strip().split()))\n matrix = [[0 for i in range(n[0])]for j in range(n[0])]\n k=0\n for i in range(n[0]):\n for j in range(n[0]):\n matrix[i][j] = arr[k]\n k+=1\n for i in matrix:\n print(i)\n print(findPath(matrix, n[0]))","sub_path":"Companies/Amazon/rat_in_maze.py","file_name":"rat_in_maze.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"240595420","text":"from django.shortcuts import render\nfrom django.core.files.storage import FileSystemStorage\nimport os\nfrom googletrans import Translator\ndef translateText(sourceText, src, dest):\n translator = Translator()\n result = translator.translate(sourceText, src=src, dest=dest)\n return result\ndef translate(request):\n BASE_DIR = os.path.dirname(os.path.dirname(__file__))\n context = {}\n sourceText = ''\n fileResource = None\n if request.method == 'POST':\n src = request.POST.get('language_source')\n dest = request.POST.get('language_destination')\n sourceText = request.POST.get('source_text')\n \n if 'fileSource' in request.FILES:\n fileResource = request.FILES['fileSource']\n fs = FileSystemStorage()\n fileText = fs.save(fileResource.name, fileResource)\n context['fileUrl'] = fs.url(fileText)\n mediaPath = os.path.join(BASE_DIR,'media')\n fullPath =os.path.join(mediaPath,fileResource.name)\n fileContent = open(fullPath, 'r')\n context['sourceText'] = fileContent.read()\n translateResult = translateText(context['sourceText'], src, dest)\n context['sourceTranslate'] = translateResult.origin\n context['resultTranslate'] = translateResult.text\n else:\n translateResult = translateText(sourceText, src, dest)\n context['src'] = translateResult.src \n context['dest'] = translateResult.dest\n context['sourceTranslate'] = translateResult.origin\n context['resultTranslate'] = translateResult.text\n return render(request, 'translate.html', context)","sub_path":"implementation_algorithm/translate_machine/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"127563130","text":"mod = 1000000007\neps = 10**-9\n\n\ndef main():\n import sys\n input = sys.stdin.readline\n\n N, T = map(int, input().split())\n ans = 10**9\n for _ in range(N):\n c, t = map(int, input().split())\n if t <= T:\n ans = min(ans, c)\n if ans == 10**9:\n print(\"TLE\")\n else:\n print(ans)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Python_codes/p03239/s254955203.py","file_name":"s254955203.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"163601608","text":"import os, json\nfrom pyheal import wrapper\nfrom pyheal import encoders\n\nclass MyPyHeal():\n def __init__(self, poly_modulus=0, coeff_modulus=0, plain_modulus=0,\n pubkey_path=None):\n scheme = 'BFV'\n self.poly_modulus = poly_modulus\n self.coeff_modulus = coeff_modulus\n self.plain_modulus = plain_modulus\n\n self.parms = wrapper.EncryptionParameters(scheme_type=scheme)\n\n if self.poly_modulus > 0 and self.coeff_modulus > 0 and self.plain_modulus > 0:\n self.parms.set_poly_modulus(self.poly_modulus)\n self.parms.set_coeff_modulus(wrapper.coeff_modulus_256(self.coeff_modulus))\n # parms.set_coeff_modulus([wrapper.SmallModulus(1099511922689),wrapper.SmallModulus\n # (1099512004609)])\n self.parms.set_plain_modulus(self.plain_modulus)\n \n seal_context_ = wrapper.Context(self.parms).context\n self.context = seal_context_\n \n if pubkey_path == None:\n self.keygen = wrapper.KeyGenerator(seal_context_)\n else:\n pub = wrapper.PublicKey()\n pub.load(pubkey_path)\n #sec = wrapper.SecretKey()\n #sec.load(seckey_path)\n #self.keygen = wrapper.KeyGenerator(seal_context_, sec, pub)\n self.keygen = wrapper.KeyGenerator(seal_context_, public=pub)\n self.evaluator = wrapper.Evaluator(ctx=seal_context_)\n self.plaintext_encoder = encoders.PlainTextEncoder(\n encoder=wrapper.FractionalEncoder(smallmod=wrapper.SmallModulus(self.plain_modulus),\n poly_modulus_degree=self.poly_modulus,\n integer_coeff_count=64,\n fraction_coeff_count=32,\n base=2)\n )\n self.encryptor_encoder = encoders.EncryptorOp(plaintext_encoder=self.plaintext_encoder,\n encryptor=wrapper.Encryptor(ctx=seal_context_, public=self.keygen.public_key()),\n evaluator=wrapper.Evaluator(ctx=seal_context_),\n# relin_key=self.keygen.relin_keys(decomposition_bit_count=16, count=2)\n relin_key=self.keygen.relin_keys(decomposition_bit_count=60, count=1)\n )\n if pubkey_path is None:\n self.decryptor_decoder = encoders.Decryptor(plaintext_encoder=self.plaintext_encoder,\n decryptor=wrapper.Decryptor(ctx=seal_context_, secret=self.keygen.secret_key())\n )\n else:\n self.decryptor_decoder = None\n self.batch_encoder = wrapper.BatchEncoder(self.context)\n print(\"MyPyHeal: context generated with n={}, q={}, t={}\".format(self.poly_modulus, self.coeff_modulus, self.plain_modulus))\n\n def saveParmsAndKeys(self, destdir):\n parms_out = {\"poly_modulus\": self.poly_modulus,\n \"coeff_modulus\": self.coeff_modulus,\n \"plain_modulus\": self.plain_modulus}\n with open(os.path.join(destdir, 'seal.parms'), 'w') as f:\n json.dump(parms_out, f)\n \n pubkey = self.keygen.public_key()\n seckey = self.keygen.secret_key()\n relinkey = self.keygen.relin_keys(60, 1) # 16, 2\n pubkey.save(os.path.join(destdir, \"pub.key\"))\n seckey.save(os.path.join(destdir, \"sec.key\")) # temporary\n relinkey.save(os.path.join(destdir, \"relin.key\"))\n\n","sub_path":"playground/utils/mypyheal.py","file_name":"mypyheal.py","file_ext":"py","file_size_in_byte":3031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"110310397","text":"import numpy as np\n\nfrom ..priors import parse_config, compute_loglike\n\n\ndef test_priors():\n analysis = {\n 'mu': {'kind': 'norm', 'loc': 0.3, 'scale': 1.0},\n 'h': {'kind': 'norm', 'loc': 0.1, 'scale': 2.0},\n 'v': {'kind': 'norm', 'loc': -0.3, 'scale': 4.0}}\n parameters = {'mu': 0.0, 'h': -0.1}\n\n data = parse_config(analysis)\n assert data == analysis\n\n loglike, stats = compute_loglike(\n cosmo=None, parameters=parameters, data=data)\n\n assert loglike == (\n -0.5 * ((0.3) / 1.0)**2 - 0.5 * np.log(2.0 * np.pi) +\n -0.5 * ((-0.1 - 0.1) / 2.0)**2 - 0.5 * np.log(2.0 * np.pi) - np.log(2))\n assert stats == {}\n","sub_path":"examples/desc_srd_v1/srd_models/tests/test_priors.py","file_name":"test_priors.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"439099460","text":"from __future__ import print_function\nimport hashlib\nimport os\nimport shutil\nimport errno\n\n# -------------------------------------------------------------------------------------------------------------------- #\n\nclass DBSFilesystemManager(object):\n\n def __init__(\n self, root_dir,\n hashlib_method='sha512', summed_subdir_splitting_on_block_size=32,\n bare_subdir='bare', summed_subdir='.summed', tmp_subdir='tmp',\n ):\n\n # hashlib method\n assert hasattr(hashlib, hashlib_method), 'hashlib_method not found : {}'.format(hashlib_method)\n self.hashlib_method = getattr(hashlib, hashlib_method)\n\n # summed_subdir_splitting_on_block_size\n assert isinstance(summed_subdir_splitting_on_block_size, int), 'summed_subdir_splitting_on_block_size not int !'\n assert 0 < summed_subdir_splitting_on_block_size <= 128, 'summed_subdir_splitting_on_block_size <=0 || > 128'\n self.sum_dirname_size = summed_subdir_splitting_on_block_size\n\n # directories\n self.root_dir = os.path.realpath(root_dir)\n assert os.path.isdir(self.root_dir), 'root_dir does not exist or is not a dir : {}'.format(self.root_dir)\n self.bare_dir = os.path.join(self.root_dir, bare_subdir)\n assert os.path.isdir(self.bare_dir), 'bare_subdir does not exist or is not a dir : {}'.format(self.bare_dir)\n self.summed_dir = os.path.join(self.root_dir, summed_subdir)\n assert os.path.isdir(self.summed_dir),\\\n 'summed_subdir does not exist or is not a dir : {}'.format(self.summed_dir)\n self.tmp_dir = os.path.join(self.root_dir, tmp_subdir)\n assert os.path.isdir(self.tmp_dir), 'tmp_subdir does not exist or is not a dir : {}'.format(self.tmp_dir)\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -#\n\n def file_digest(self, file_path):\n blocksize = 65536\n hasher = self.hashlib_method()\n with open(file_path, 'rb') as fp:\n buf = fp.read(blocksize)\n while len(buf) > 0:\n hasher.update(buf)\n buf = fp.read(blocksize)\n return hasher.hexdigest()\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -#\n\n @staticmethod\n def mkdir_recursive(fpath):\n try:\n os.makedirs(fpath)\n except OSError as err:\n if err.errno != errno.EEXIST or not os.path.isdir(fpath):\n raise\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -#\n\n def put(self, src_path, relative_dst_path, move_src=True):\n\n # init\n dst_path = self.bare_dir + relative_dst_path\n dst_dirname = os.path.dirname(dst_path)\n src_digest = self.file_digest(src_path)\n print(src_path, '|', relative_dst_path, '|', dst_path, '|', src_digest)\n\n '''\n summed_path = self.summed_dir\n buf = src_digest\n while len(buf) > 0:\n summed_path = os.path.join(summed_path, buf[:self.sum_dirname_size])\n buf = buf[-self.sum_dirname_size:]\n print(summed_path)\n '''\n\n # destination dir_name\n self.mkdir_recursive(dst_dirname)\n\n # do it\n if move_src:\n shutil.move(src_path, dst_path)\n else:\n shutil.copy(src_path, dst_path)\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -#\n\n# -------------------------------------------------------------------------------------------------------------------- #\n","sub_path":"dedupbysum/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"516347556","text":"from orm.services.flavor_manager.fms_rest.data.sql_alchemy.db_models import FlavorTag\nfrom orm.services.flavor_manager.fms_rest.logger import get_logger\nfrom sqlalchemy import and_\n\nLOG = get_logger(__name__)\n\n\nclass FlavorTagRecord:\n def __init__(self, session):\n\n # this model is uses only for the parameters of access mothods,\n # not an instance of model in the database\n self.__flavor_tag = FlavorTag()\n # self.setRecordData(self.FlavorTag)\n # self.__flavorTag.Clear()\n self.__TableName = \"flavor_extra_spec\"\n\n if session:\n self.setDBSession(session)\n\n def setDBSession(self, session):\n self.session = session\n\n @property\n def flavor_extra_spec(self):\n return self.__flavor_tag\n\n @flavor_extra_spec.setter\n def flavor_extra_spec(self, flavor_tag):\n self.__flavor_tag = flavor_tag\n\n def insert(self, flavor_tag):\n try:\n self.session.add(flavor_tag)\n except Exception as exception:\n LOG.log_exception(\"Failed to insert FlavorTag\" +\n str(flavor_tag), exception)\n raise\n\n def get_flavor_extra_spec(self, flavor_internal_id, key_name):\n try:\n flavor_extra_spec = self.session.query(FlavorTag).filter(\n and_(FlavorTag.flavor_internal_id == flavor_internal_id,\n FlavorTag.key_name == key_name))\n return flavor_extra_spec.first()\n\n except Exception as exception:\n message = \"Failed to get_flavor_extra_spec:flavor_internal_id:\" \\\n \"{0}, key_name {1}\".format(flavor_internal_id, key_name)\n LOG.log_exception(message, exception)\n raise\n\n def get_flavor_tag_by_flavor_internal_id(self, flavor_internal_id):\n try:\n flavor_tag = self.session.query(FlavorTag).filter(\n FlavorTag.flavor_internal_id == flavor_internal_id)\n return flavor_tag.all()\n\n except Exception as exception:\n message = \"Failed to \" \\\n \"get_flavor_tag_by_flavor_internal_id:\" \\\n \"flavor_internal_id: {0}\".format(flavor_internal_id)\n LOG.log_exception(message, exception)\n raise\n","sub_path":"orm/services/flavor_manager/fms_rest/data/sql_alchemy/flavor_tags/flavor_tag_record.py","file_name":"flavor_tag_record.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"136718951","text":"#\n\n'''\nTopic:最后一个周五\n'''\n\nfrom datetime import datetime, timedelta\n\nweekdays = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']\n\ndef get_previous_byday(dayname,start_date=None):\n\tif start_date is None:\n\t\tstart_date = datetime.today()\n\tday_num = start_date.weekday()\n\tprint(day_num)\n\tday_num_target = weekdays.index(dayname)\n\tdays_ago = (7 + day_num - day_num_target) % 7\n\tif days_ago == 0:\n\t\tdays_ago = 7\n\ttarget_date = start_date - timedelta(days=days_ago)\n\treturn target_date\n\nif __name__ == '__main__':\n\tprint(datetime.today())\n\tday = get_previous_byday('Monday')\n\tprint(day)\n\tday = get_previous_byday('Tuesday')\n\tprint(day)\n\tday = get_previous_byday('Friday')\n\tprint(day)\n","sub_path":"source/c03/p13_last_friday.py","file_name":"p13_last_friday.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"211286591","text":"import requests\nimport json\nimport os\n\n\nclass ApiTest(object):\n def __init__(self, test_data=None):\n if test_data is None:\n raise ValueError('No test data provided')\n else:\n self.test_data = test_data\n\n self._run_test()\n\n def _run_test(self):\n api_url = self.test_data.get('apiUrl')\n for vector in self.test_data.get('testVectors'):\n inputs = vector.get('input')\n api_call = api_url.format(\n apiKey=os.environ.get('OWM_API_KEY'),\n **inputs\n )\n res = requests.get(api_call)\n body = json.loads(res.text)\n assert (\n res.status_code == vector['expected']['status_code']\n )\n if 'text' in vector['expected']:\n for message_field in vector['expected']['text']:\n assert (\n body[message_field] == vector['expected']['text'][message_field]\n )\n","sub_path":"owm_api_tests/common/api_test.py","file_name":"api_test.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"112539397","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Usuario\nfrom .forms import UsuarioForm\n\n@login_required\ndef usuario_list(request):\n usuario = Usuario.objects.all();\n context = {\n 'usuario_list': usuario\n }\n return render(request, 'listauser.html', context)\n\n@login_required\ndef usuario_add(request):\n form = UsuarioForm(request.POST or None)\n if form.is_valid():\n form.save()\n return redirect('usuario_list')\n return render(request, 'usuario_form.html', {'form': form})\n\n@login_required\ndef usuario_update(request, id):\n usuario = get_object_or_404(Usuario, pk=id)\n form = UsuarioForm(request.POST or None,instance=usuario)\n if form.is_valid():\n form.save()\n return redirect('usuario_list')\n return render(request, 'usuario_form.html', {'form': form})\n\n@login_required\ndef usuario_delete(request, id):\n usuario = get_object_or_404(Usuario, pk=id)\n form = UsuarioForm(request.POST or None,instance=usuario)\n if request.method == 'POST':\n usuario.delete()\n return redirect('usuario_list')\n return render(request, 'usuario_delete_confirm.html', {'usuario': usuario})\n\n","sub_path":"transportes/usuario/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"262038121","text":"# words = [\"hulk\", \"currant\", \"complex\", \"create\", \"thing\", \"skewer\", \"cloud\", \"diamond\", \"spartan\"]\r\n\r\n# words = [\"cartography\", \"artemis\", \"blemish\", \"cloud\", \"doom\"]\r\n\r\nwords = [\"spanish\", \"index\", \"aeroplane\", \"boston\", \"signal\", \"board\", \"hair\", \"token\", \"load\", \"golf\"]\r\n\r\nclass C:\r\n horizontal = True\r\n vertical = False\r\n blank = \" \"\r\n\r\nclass wordInfo():\r\n def __init__(self, word, x, y, v):\r\n self.word = word\r\n self.x = x\r\n self.y = y\r\n self.v = v\r\n\r\ndef len_chars(words):\r\n l = 0\r\n for i in words:\r\n l += len(i)\r\n return l\r\n\r\ndef create_matrix(x, y):\r\n matrix = [None]\r\n for i in range(y):\r\n a = []\r\n for j in range(x):\r\n a.append(C.blank)\r\n matrix.append(a)\r\n return matrix\r\n\r\ndef display_matrix(matrix):\r\n for i in range(len(matrix)-1):\r\n a = \" \"\r\n for j in matrix[i+1]:\r\n a += j\r\n a += \" \"\r\n print(a)\r\n\r\ndef add_word(matrix, wordinfo):\r\n word = wordinfo.word\r\n x = wordinfo.x\r\n y = wordinfo.y\r\n v = wordinfo.v\r\n if v == C.horizontal:\r\n for i in range(len(word)):\r\n matrix[y][x+i] = word[i]\r\n elif v == C.vertical:\r\n for i in range(len(word)):\r\n matrix[y+i][x] = word[i]\r\n\r\ndef remove_word(matrix, wordinfo):\r\n word = wordinfo.word\r\n x = wordinfo.x\r\n y = wordinfo.y\r\n v = wordinfo.v\r\n if v == C.horizontal:\r\n for i in range(len(word)):\r\n if matrix[y+1][x+i] == C.blank and matrix[y-1][x+i] == C.blank:\r\n matrix[y][x+i] = C.blank\r\n elif v == C.vertical:\r\n for i in range(len(word)):\r\n if matrix[y+i][x+1] == C.blank and matrix[y+i][x-1] == C.blank:\r\n matrix[y+i][x] = C.blank\r\n\r\ndef check1(wordinfo, word):\r\n L = []\r\n for i in range(len(wordinfo.word)):\r\n for j in range(len(word)):\r\n if wordinfo.word[i] == word[j]:\r\n L.append([i, j])\r\n\r\n return L\r\n\r\ndef check2(matrix, wordinfo):\r\n check = True\r\n word = wordinfo.word\r\n x = wordinfo.x\r\n y = wordinfo.y\r\n a = \" \"\r\n # print(word, \" - \", x, y)\r\n if wordinfo.v == C.horizontal:\r\n if matrix[y][x-1] != C.blank or matrix[y][x+len(word)] != C.blank:\r\n # print(word, x, y, -1)\r\n # print(word, \"-end\")\r\n return False\r\n\r\n for i in range(len(word)):\r\n if matrix[y][x+i] == C.blank and matrix[y-1][x+i] == C.blank and matrix[y+1][x+i] == C.blank:\r\n # print(word, \"-noxtion\")\r\n continue\r\n else:\r\n if matrix[y][x+i] == word[i]:\r\n # print(word, \"-xtion\")\r\n continue\r\n else:\r\n # print(word, x+i, y, i)\r\n # print(word, \"-break\")\r\n check = False\r\n break\r\n elif wordinfo.v == C.vertical:\r\n if matrix[y-1][x] != C.blank or matrix[y+len(word)][x] != C.blank:\r\n # print(word, x, y, -1)\r\n # print(word, \"-end\")\r\n return False\r\n\r\n for i in range(len(word)):\r\n if matrix[y+i][x] == C.blank and matrix[y+i][x-1] == C.blank and matrix[y+i][x+1] == C.blank:\r\n # print(word, \"-noxtion\")\r\n continue\r\n else:\r\n if matrix[y+i][x] == word[i]:\r\n # print(word, \"-xtion\")\r\n continue\r\n else:\r\n # print(word, x, y+i, i)\r\n # print(word, \"-break\")\r\n check = False\r\n break\r\n\r\n return check\r\n\r\ndef createCrossword(words, crossword=None, wordinfo=None, initword=None):\r\n if len(words) == 0:\r\n return crossword\r\n a = words[-1]\r\n\r\n # Initialise\r\n if crossword == None:\r\n l = len_chars(words)\r\n L = 2*l + 1\r\n crossword = create_matrix(L, L)\r\n words.remove(a)\r\n aInfo = wordInfo(a, l, l, C.horizontal)\r\n add_word(crossword, aInfo)\r\n wordinfo = [aInfo]\r\n crossword = createCrossword(words, crossword, wordinfo)\r\n\r\n else:\r\n w = wordinfo[-1]\r\n pts = check1(w, a)\r\n\r\n checked = False\r\n\r\n for i in pts:\r\n # print(a, i)\r\n if w.v == C.horizontal:\r\n testword = wordInfo(a, w.x+i[0], w.y-i[1], C.vertical)\r\n elif w.v == C.vertical:\r\n testword = wordInfo(a, w.x-i[1], w.y+i[0], C.horizontal)\r\n\r\n # print(testword.word, i[0], i[1], check2(crossword, testword), testword.x, testword.y, testword.v)\r\n \r\n if check2(crossword, testword):\r\n checked = True\r\n crossword[0] = checked\r\n # print(testword.word)\r\n\r\n words.remove(a)\r\n wordinfo.append(testword)\r\n add_word(crossword, testword)\r\n\r\n # print(crossword[0])\r\n crossword = createCrossword(words, crossword, wordinfo)\r\n # display_matrix(crossword)\r\n # print(\"\\n\")\r\n\r\n checked = crossword[0]\r\n # print(checked)\r\n if checked:\r\n break\r\n else:\r\n # print(\"Hello there.\")\r\n # display_matrix(crossword)\r\n # print(\"General Kenobi.\\n\")\r\n words.append(a)\r\n wordinfo.remove(testword)\r\n remove_word(crossword, testword)\r\n\r\n if not checked:\r\n # print(a, words, initword)\r\n if initword == a:\r\n return crossword\r\n if initword == None:\r\n initword = a\r\n words.remove(a)\r\n words = [a] + words\r\n crossword = createCrossword(words, crossword, wordinfo, initword)\r\n # display_matrix(crossword)\r\n\r\n crossword[0] = True\r\n\r\n # crossword[0] = checked\r\n # print(\"HEY\")\r\n\r\n return crossword\r\n\r\ndef trim(matrix):\r\n x, y = len(matrix[0]), len(matrix)\r\n minx, miny = x, y\r\n maxx, maxy = 0, 0\r\n for i in range(x):\r\n for j in range(y):\r\n if matrix[j][i] != C.blank:\r\n if i < minx:\r\n minx = i\r\n if i > maxx:\r\n maxx = i\r\n if j < miny:\r\n miny = j\r\n if j > maxy:\r\n maxy = j\r\n\r\n matrix = matrix[miny:maxy+1]\r\n newmatrix = []\r\n for i in matrix:\r\n newmatrix.append(i[minx:maxx+1])\r\n\r\n return newmatrix\r\n\r\n\r\ntest = createCrossword(words)\r\ntest = test[1:]\r\ntest = trim(test)\r\ntest = [True] + test\r\nprint(\"\\n\")\r\ndisplay_matrix(test)\r\nprint(\"\\n\")","sub_path":"crossword.py","file_name":"crossword.py","file_ext":"py","file_size_in_byte":6761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"264910733","text":"def bubbleSort(valList):\n\n for num in range(len(valList)-1,0,-1):\n for i in range(num):\n if valList[i] > valList[i+1]:\n temp = valList[i]\n valList[i] = valList[i+1]\n valList[i+1] = temp\n\n\n\ndef selectionSort(valList):\n\n for i in range(len(valList)-1,0,-1):\n maxIndex = 0\n for j in range(1,i+1):\n if valList[j] > valList[maxIndex]:\n maxIndex = j\n\n print(i)\n print(valList)\n tmp = valList[i]\n valList[i] = valList[maxIndex]\n valList[maxIndex] = tmp\n\n\n\ndef insertionSort(valList):\n\n for i in range(1,len(valList)):\n\n currentVal = valList[i]\n position = i\n\n while position > 0 and valList[position-1] > currentVal:\n valList[position] = valList[position-1]\n position = position-1\n\n valList[position] = currentVal\n\n\ndef mergeSort(valList):\n\n if len(valList):\n mid = len(valList)//2\n lefhalf = valList[:mid]\n righthalf = valList[mid:]\n\n mergeSort(lefhalf)\n mergeSort(righthalf)\n\n i=0\n j=0\n k=0\n while i < len(lefhalf) and j < len(righthalf):\n if lefhalf[i] < righthalf[i]:\n valList[k] = lefhalf[i]\n i += 1\n else:\n valList[k] = righthalf[j]\n j += 1\n\n while i < len(lefhalf):\n valList[k] = lefhalf[i]\n i += 1\n k += 1\n\n while j < len(righthalf):\n valList[k] = righthalf[j]\n j += 1\n k += 1\n\n\nnums = [20,4,4,2,1]\nmergeSort(nums)\nprint(nums)","sub_path":"python/hacking/problems_python/sorting/sorting.py","file_name":"sorting.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"247323467","text":"\n\n#calss header\nclass _BABEL():\n\tdef __init__(self,): \n\t\tself.name = \"BABEL\"\n\t\tself.definitions = [u'the confusing sound of many people talking at the same time or using different languages: ']\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/_babel.py","file_name":"_babel.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"590827256","text":"import torch.nn as nn\r\nimport torch.nn.functional as functional\r\nimport torch\r\nimport numpy as np\r\n\r\nclass deform_conv_v1(nn.Module):\r\n def __init__(self, in_channels, out_channels, kernel_size, stride, padding, bias=True):\r\n super().__init__()\r\n self.in_channels = in_channels\r\n self.out_channels = out_channels\r\n self.kernel_size = kernel_size\r\n self.stride = stride\r\n self.padding = padding\r\n self.p_conv = nn.Conv2d(in_channels=in_channels, out_channels=2 * kernel_size * kernel_size, padding=0,\r\n kernel_size=kernel_size, stride=stride, bias=bias)\r\n \r\n nn.init.constant_(self.p_conv.weight, 0)\r\n nn.init.constant_(self.p_conv.bias, 0)\r\n self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size,\r\n stride=kernel_size, padding=0, bias=bias)\r\n self.zero_padding = nn.ZeroPad2d(padding=padding)\r\n\r\n def forward(self, x):\r\n x = self.zero_padding(x)\r\n padded_h, padded_w = x.size()[2], x.size()[3]\r\n assert padded_h == padded_w\r\n offset = self.p_conv(x)\r\n\r\n n, _, h_out, w_out = list(offset.size())\r\n p = self.get_p(offset, h_out, w_out)\r\n p = p.permute([0, 2, 3, 1])\r\n p = torch.reshape(p, [n, h_out, w_out, 2, -1])\r\n p = torch.reshape(p.permute([0, 1, 2, 4, 3]), [n, h_out, w_out, self.kernel_size, -1, 2])\r\n \r\n grid = p.permute([0, 1, 3, 2, 4, 5])\r\n grid = torch.reshape(grid, [n, h_out * self.kernel_size, -1, 2])\r\n grid = torch.clamp(grid * 2 / (padded_h - 1) - 1, -1, 1)\r\n \r\n x = functional.grid_sample(x, grid, align_corners=True)\r\n x = self.conv(x)\r\n\r\n return x\r\n\r\n def get_p(self, offset, h_out, w_out):\r\n p_0 = self.get_p_0(h_out, w_out)\r\n p_0 = torch.reshape(p_0, [1, 2, self.kernel_size * self.kernel_size, h_out, w_out]).view(1, -1, h_out, w_out)\r\n p_n = self.get_p_n()\r\n\r\n # 1, 2k*k, 1, 1\r\n p_n = torch.reshape(p_n, [1, 2, -1, 1, 1]).view(1, -1, 1, 1)\r\n p = offset + p_0 + p_n\r\n return p\r\n\r\n def get_p_0(self, h_out, w_out):\r\n\r\n p_0_row, p_0_col = torch.meshgrid(\r\n torch.arange(start=self.padding, end=self.padding + h_out * self.stride, step=self.stride),\r\n torch.arange(start=self.padding, end=self.padding + w_out * self.stride, step=self.stride)\r\n )\r\n p_0_row = torch.flatten(p_0_row).view(1, 1, h_out, w_out).repeat(1, self.kernel_size * self.kernel_size, 1, 1)\r\n p_0_col = torch.flatten(p_0_col).view(1, 1, h_out, w_out).repeat(1, self.kernel_size * self.kernel_size, 1, 1)\r\n p_0 = torch.cat([p_0_col, p_0_row], 1)\r\n return p_0\r\n\r\n def get_p_n(self):\r\n p_n_row, p_n_col = torch.meshgrid(\r\n torch.arange(-(self.kernel_size - 1) // 2, (self.kernel_size - 1) // 2 + 1),\r\n torch.arange(-(self.kernel_size - 1) // 2, (self.kernel_size - 1) // 2 + 1))\r\n p_n = torch.cat([torch.flatten(p_n_col), torch.flatten(p_n_row)], 0)\r\n p_n = p_n.view(1, 2 * self.kernel_size * self.kernel_size, 1, 1)\r\n\r\n return p_n\r\n\r\nif __name__ == '__main__':\r\n x = np.random.rand(8, 3, 32, 32).astype(np.float32)\r\n x = torch.from_numpy(x)\r\n\r\n model = deform_conv_v1(in_channels=3, out_channels=16, kernel_size=3, stride=2, padding=1)\r\n\r\n res = model(x)\r\n print (res)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"511081719","text":"import json\nimport numpy as np\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as plt\nimport sys\n\n\nhb_trace = 'hb_trace.dat' # file with data about hydrogen bonds\nremove_first_acf_point = True\n\n\ndef autocorr(x):\n # return real part of autocorrelation function\n f = np.fft.fft(np.pad(x, len(x), mode='constant')[len(x):])\n result = np.fft.ifft(f * np.conj(f))\n result = result[:len(x)]\n result /= np.linspace(len(x), 1, len(x))\n return np.real(result)\n\n\ndef exp_decay(x, a, tau, c):\n return a * np.exp(-x/tau) + c\n\n\ndef split_header(header):\n # THR~3::N--DC~1133::OP1 THR~3::OG1--DC~1133::OP1\n result = []\n header = header.rstrip('\\n').strip()\n hbs = header.split(' ')\n for hb in hbs:\n donor, acceptor = tuple(hb.split('--'))\n donor_r = donor.split('::')[0]\n donor_aName = donor.split('::')[1]\n donor_rName = donor_r.split('~')[0]\n donor_rId = int(donor_r.split('~')[1])\n acceptor_r = acceptor.split('::')[0]\n acceptor_aName = acceptor.split('::')[1]\n acceptor_rName = acceptor_r.split('~')[0]\n acceptor_rId = int(acceptor_r.split('~')[1])\n result.append([[donor_rName, donor_rId, donor_aName],\n [acceptor_rName, acceptor_rId, acceptor_aName]])\n return result\n\n\ndef correct_numbering(hbs, renumber_map=None):\n if not renumber_map:\n renumber_map = {'A': [rid for rid in range(1, 136)],\n 'B': [rid for rid in range(1, 103)],\n 'C': [rid for rid in range(1, 129)],\n 'D': [rid for rid in range(1, 123)],\n 'E': [rid for rid in range(1, 136)],\n 'F': [rid for rid in range(1, 103)],\n 'G': [rid for rid in range(1, 129)],\n 'H': [rid for rid in range(1, 123)],\n 'I': [rid for rid in range(1, 148)],\n 'J': [rid for rid in range(1, 148)]}\n\n absolute_map = {}\n renumber_array = []\n last_resid = 0\n\n for k in sorted(renumber_map):\n v = renumber_map[k]\n absolute_map[k] = [rid for rid in range(last_resid + 1, last_resid + len(v) + 1)]\n renumber_array += v\n last_resid = len(renumber_array)\n\n for hb in hbs:\n i1 = hb[0][1]\n i2 = hb[1][1]\n for k, v in absolute_map.items():\n if i1 in v:\n hb[0].insert(0, k)\n if i2 in v:\n hb[1].insert(0, k)\n hb[0][2] = renumber_array[hb[0][2] - 1]\n hb[1][2] = renumber_array[hb[1][2] - 1]\n\n return hbs\n\n\n# read data and parameters\nwith open(hb_trace, 'r') as f:\n header = f.readline()\nheader = header.rstrip('\\n').strip()\nhbs = split_header(header)\nhbs = correct_numbering(hbs)\ndata = np.genfromtxt(hb_trace, skip_header=1).T\nwith open('input.json', 'r') as f:\n pars = json.load(f)\ntrj_filename_first = pars['trj_filename_first']\ntrj_filename_last = pars['trj_filename_last']\n\n# calculate time axis vector\ntime = np.linspace(0, (trj_filename_last-trj_filename_first+1)*1000, len(data[0]))\n\n# calculate ACF for each HB\nacf = np.zeros(data.shape)\nacf_fit = np.zeros((len(data), 2))\n\nfor i, trace in enumerate(data):\n sys.stdout.write('Processing hydrogen bond #{} of {}\\r'.format(i+1, len(data)))\n\n trace_acf = autocorr(trace)\n\n # remove first point if necessary\n if remove_first_acf_point:\n x = time[1:]\n y = trace_acf[1:]\n else:\n x = time\n y = trace_acf\n\n # cut acf for fitting (0.8)\n x = x[:int(np.floor(len(x) * 0.8))]\n y = y[:int(np.floor(len(y) * 0.8))]\n\n popt, pcov = curve_fit(exp_decay, x, y, p0=(np.max(y), 1000, 0),\n bounds=([np.max(y)/10, np.min(x)/10, -1e-15], [np.max(y)*10, np.max(x)*10, np.max(y)]),\n xtol=1e-4, max_nfev=10000)\n\n acf_fit[i, 0] = popt[1]/1000\n acf_fit[i, 1] = np.abs(popt[2])/(popt[0] + popt[2])\n acf[i] = trace_acf\n\n plt.figure(figsize=(8, 6))\n plt.plot(x, y, label=str(hbs[i]))\n x_fit = np.linspace(np.min(time), np.max(time), 1000)\n plt.plot(x_fit, exp_decay(x_fit, *popt), label=r'$\\tau$={:.2f}ns; S$^2$={:.3f}'.format(acf_fit[i, 0], acf_fit[i, 1]))\n plt.xlabel('Time, ps')\n plt.ylabel('Correlation')\n plt.legend()\n plt.savefig('Figures/{:04d}.png'.format(i), bbox_inches='tight')\n plt.close()\nsys.stdout.write('\\n')\n\nwith open('result.csv', 'w') as f:\n h = 'bond_id;'\n h += 'donor_chain;donor_resname;donor_resid;donor_atom;'\n h += 'acceptor_chain;acceptor_resname;acceptor_resid;acceptor_atom;'\n h += 'tau, ns; S2\\n'\n f.write(h)\n i = 1\n fmt = '{:d}; {};{};{:d};{}; {};{};{:d};{}; {:.2f};{:.3f}\\n'\n for hb, r in zip(hbs, acf_fit):\n f.write(fmt.format(i, hb[0][0], hb[0][1], hb[0][2], hb[0][3],\n hb[1][0], hb[1][1], hb[1][2], hb[1][3],\n r[0], r[1]))\n i += 1\n# np.savetxt('taus.csv', acf_fit, fmt='%.6f;%.6f', header='tau, ns; S2')\n# np.savetxt('acf.txt', acf.T, fmt='%.6e', header=header)\n","sub_path":"chromatin/trace_HB/correlation_lifetime.py","file_name":"correlation_lifetime.py","file_ext":"py","file_size_in_byte":5080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"593687098","text":"import csv\nimport os\nround_filepath = './source/Data/round.csv'\nround_hist_filepath = './source/Data/round_history.csv'\nround_fieldnames = [\"RoundID\",\"Owner\",\"Brewer\",\"ActiveStatus\"]\nround_hist_fieldnames = [\"RoundID\",\"OrderID\",\"Name\",\"Drink\"]\nimport source.User.navigation as nav\nimport source.Persistence.sql_connection as sql\n\n\n#creating Round class here\nclass Round_Handler:\n #print round history function\n #print a round and all the drinks on it function\n #add to round function\n #create round - add to all_rounds\n \n def __init__(self,round_id, owner, brewer ,active_status):\n self.round_id = round_id\n self.brewer = brewer\n self.owner = owner\n self.active_status = active_status\n self.round_history = []\n\n def add_to_round(self,order_id,name,drink):\n round_history.append({\"RoundID\": self.round_id, \"OrderID\": order_id,\"Name\": name, \"Drink\": drink})\n #method adds to round-history list variable of the round object\n #adds to a dict like before BUT USEES OBJECT ROUND ID\n\n#Takes existing rounds from csv file(path) to make list of OBJECTS\n#where each object is a round\n\nclass File_store_round:\n def __init__(self, filepath):\n self.filepath = filepath\n def load_file_to_dict_round(self):\n with open(self.filepath, \"r\") as round_file:\n myreader = csv.DictReader(round_file,quoting =csv.QUOTE_ALL)\n all_rounds_list = []\n all_rounds_object_list =[]\n for row in myreader:\n if not row:\n pass\n else:\n all_rounds_list.append(row)\n\n for my_dict in all_rounds_list:\n round_id = my_dict[round_fieldnames[0]]\n owner_name = my_dict[round_fieldnames[1]]\n brewer_name = my_dict[round_fieldnames[2]]\n active = my_dict[round_fieldnames[3]]\n owner_name = Round_Handler(round_id, owner_name, brewer_name, active)\n all_rounds_object_list.append(owner_name)\n return all_rounds_object_list\n\n def save_object_list_to_file(self, object_dict_list):\n with open(self.filepath, \"w\", newline=\"\") as round_file:\n writer = csv.writer(round_file)\n writer.writerow(round_fieldnames)\n for obj in object_dict_list:\n for my_dict in obj.round_history:\n #print([obj.round_id, obj.owner,obj.brewer,obj.active_status])\n writer.writerow([my_dict[\"RoundID\"],my_dict[\"OrderID\"],my_dict[\"Name\"], my_dict[\"Drink\"]])\n\n#create round object list from csv\nround_file = File_store_round(round_filepath)\nall_rounds_object_list = round_file.load_file_to_dict_round()\n\nclass File_store_round_history:\n def __init__(self, filepath):\n self.filepath = filepath\n def load_file_to_object(self, object_list):\n with open(self.filepath, \"r\") as round_hist_file:\n myreader = csv.DictReader(round_hist_file,quoting =csv.QUOTE_ALL)\n all_orders_list = []\n for row in myreader:\n if not row:\n pass\n else:\n all_orders_list.append(row)\n\n for obj in object_list:\n for my_dict in all_orders_list:\n if my_dict[\"RoundID\"] == obj.round_id:\n obj.round_history.append(my_dict)\n print(obj.round_history)\n\n def save_round_history_to_file(self, object_list):\n with open(self.filepath, \"w\", newline=\"\") as round_hist_file:\n writer = csv.writer(round_hist_file)\n writer.writerow(round_hist_fieldnames)\n for obj in object_list:\n #print([obj.round_id, obj.owner,obj.brewer,obj.active_status])\n writer.writerow([obj.round_id, obj.owner,obj.brewer,obj.active_status])\n \n\nround_hist_file = File_store_round_history(round_hist_filepath)\nround_hist_file.load_file_to_object(all_rounds_object_list)\n\nround_hist_file.save_round_history_to_file(all_rounds_object_list)\n\n#save list of objects to csv file\nround_file.save_object_list_to_file(all_rounds_object_list)\n\n\"\"\"\nRoundID,Owner,Brewer,ActiveStatus\n1,Aria,Khalid,Yes\n2,John,Khalid,Yes\n3,John,Joe,Yes\n4,Suman,Joe,Yes\n5,Joe,Will,No\n6,Maria,Will,Yes\n\n\nRoundID,OrderID,Name,Drink\n1,1,\"Aria\",\"Tea\"\n1,2,\"Aria\",\"Tea\"\n1,3,\"Joe\",\"Coffee\"\n2,4,\"Joe\",\"Coffee\"\n3,5,\"Maria\",\"Water\"\n\"\"\"","sub_path":"source/graveyard/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"437294878","text":"import time, sys, os\nfrom tkinter import *\nN=0\nreset=False\nrun=True\nMyWindow = Tk()\nMyWindow.geometry(\"600x400+300+200\")\nMyWindow.title(\"La Suite de Fibonacci\")\nl=Label(MyWindow, text=\"La suite de Fibonacci\")\nl.place(relx=0.4, rely=0)\nframe=Frame(MyWindow, bg='white')\nframe.place(relx=0.1,rely=0.1,relwidth=0.8,relheight=0.8)\n\ndef FibonacciSuite(N):\n if N <= 1:\n return N\n else:\n return (FibonacciSuite(N - 1) + FibonacciSuite(N - 2))\ndef stop():\n global run\n run=False\n startButton['command'] = start\n startButton['bg'] = \"green\"\n startButton['text'] = \"Start\"\n\ndef display():\n #to display the Fibonacci Sequence\n global run\n global reset\n global N\n if reset is False and run is True:\n s=Label(frame,text=FibonacciSuite(N),padx=40,pady=40)\n s.pack()\n N = N + 1\n s.after(1000,s.destroy)\n changeFibo()\n if run is False:\n Label(frame, text=FibonacciSuite(N), padx=40, pady=40).pack()\n s.after_cancel(changeFibo)\n\n\n\ndef changeFibo():\n frame.after(1000,display)\n\ndef wait():\n time.sleep(1)\n startButton['command'] = start\n startButton['bg'] = \"green\"\n startButton['text'] = \"Start\"\n time.sleep(1)\n global reset\n reset=False\n\ndef Reset():\n global reset\n global N\n global run\n reset=True\n run=False\n wait()\n N=0\n\ndef start():\n \"\"\"no loop can be used because otherwise\n it will interfere with the Window mainloop\"\"\"\n global run\n run=True\n startButton['command'] = stop\n startButton['bg'] = \"red\"\n startButton['text'] = \"Stop\"\n changeFibo()\n\n\n\nstartButton = Button(frame, height=2, width=20, text=\"Start\", command=start, bg=\"green\", fg=\"white\")\nresetButton = Button(frame, height=2, width=20, text=\"Reset\", command=Reset, bg=\"blue\", fg=\"white\")\nstartButton.place(relx=0.1,rely=0.8)\nresetButton.place(relx=0.6,rely=0.8)\n\nMyWindow.mainloop()\n","sub_path":"Ex1-Python/FibonacciSuite.py","file_name":"FibonacciSuite.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"132374797","text":"import logging\n\nlogging.basicConfig(level=logging.DEBUG\n , format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nlogger = logging.getLogger()\n\n\nclass _ListNode:\n def __init__(self, key, value):\n self.key = key\n self.value = value\n self.next = None\n\n\ndef hash_table_to_dict(table):\n table = table or []\n result = {}\n for node in table:\n if node is not None:\n while node is not None:\n result[node.key] = node.value\n node = node.next\n\n return result\n\n\ndef get_hash_table(table):\n table = table or []\n\n result = []\n for i, node in enumerate(table):\n node_dict = {}\n while node is not None:\n node_dict[node.key] = node.value\n node = node.next\n result.append(node_dict)\n\n return result\n\n\nclass HashMap:\n \"\"\"\n 无序字典\n 单向链表解决散列冲突\n todo 红黑树代替单向链表\n \"\"\"\n\n def __init__(self, table_size=16):\n self._table_size = table_size\n self._table = [None] * self._table_size\n self._new_table = None # 扩容之后 数据分次搬移到 new_table\n self._size = 0 # number of nodes in the map\n self._LOAD_FACTOR = 0.75\n\n def __len__(self):\n return self._size\n\n def __str__(self):\n return f'{self.to_dict()}'\n\n def __contains__(self, key):\n \"\"\" True if the dictionary has the specified key, else False. \"\"\"\n return False if self._find_node_in_table(key)[0] is None else True\n\n def to_dict(self):\n result = {}\n result.update(hash_table_to_dict(self._new_table))\n result.update(hash_table_to_dict(self._table))\n\n return result\n\n def print_self(self):\n return f'table: {get_hash_table(self._table)} \\n new_table: {get_hash_table(self._new_table)}'\n\n def _hash(self, key):\n return abs(hash(key)) % len(self._table)\n\n def _new_hash(self, key):\n return abs(hash(key)) % len(self._new_table)\n\n def __iter__(self):\n pass\n\n def __getitem__(self, key):\n\n node = self._find_node_in_table(key)[0]\n if node is None:\n raise KeyError(f'{key}')\n return node.value\n\n def __setitem__(self, key, value):\n self.insert(key, value)\n\n def __delitem__(self, key):\n self.pop(key)\n\n def copy(self):\n \"\"\"od.copy() -> a shallow copy of od\"\"\"\n return self.__class__(self)\n\n def clear(self):\n \"\"\" D.clear() -> None. Remove all items from D. \"\"\"\n self._table = [None] * self._table_size\n self._new_table = None\n self._size = 0\n\n def items(self):\n \"\"\" D.items() -> a set-like object providing a view on D's items \"\"\"\n pass\n\n def values(self):\n \"\"\" D.values() -> an object providing a view on D's values \"\"\"\n pass\n\n def keys(self):\n \"\"\" D.keys() -> a set-like object providing a view on D's keys \"\"\"\n pass\n\n @classmethod\n def fromkeys(cls, iterable, value=None):\n \"\"\"Create a new dictionary with keys from iterable and values set to value.\n \"\"\"\n self = cls()\n for key in iterable:\n self[key] = value\n return self\n\n __marker = object()\n\n def pop(self, key, default=__marker):\n \"\"\"\n D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n If key is not found, d is returned if given, otherwise KeyError is raised\n \"\"\"\n node, table, index = self._find_node_in_table(key)\n if node is None:\n if default is self.__marker:\n raise KeyError(f'{key}')\n else:\n return default\n\n # 没有散列冲突\n if node.key == key:\n table[index] = node.next\n self._size -= 1\n return node.value\n else:\n # 散列冲突后 冲突的值放入单向链表\n while node.next is not None:\n pre = node\n node = node.next\n if node.key == key:\n pre.next = node.next\n self._size -= 1\n return node.vaule\n\n def popitem(self):\n \"\"\"\n D.popitem() -> (k, v), remove and return some (key, value) pair as a\n 2-tuple; but raise KeyError if D is empty.\n \"\"\"\n pass\n\n def setdefault(self, key, default=None):\n \"\"\"Insert key with a value of default if key is not in the dictionary.\n Return the value for key if key is in the dictionary, else default.\n \"\"\"\n if key in self:\n return self[key]\n self[key] = default\n return default\n\n def update(self, other_dict: dict):\n \"\"\"\n \"\"\"\n if not isinstance(other_dict, dict):\n raise TypeError(f'other_dict must dictionary type')\n for key, value in other_dict.items():\n self.insert(key, value)\n\n def get(self, key, default=None):\n node = self._find_node_in_table(key)[0]\n if node is None:\n return default\n return node.value\n\n def resize(self):\n \"\"\"只申请新空间,但并不将旧的数据立即搬移到新散列表中,而是分批次搬移,每次操作只搬移一个数据\n 避免扩容的时候影响性能, 搬移操作时间均摊每次插入中\n :return:\n \"\"\"\n\n if self._new_table is not None:\n logger.debug('self._table = self._new_table')\n self._table = self._new_table\n\n self._new_table = [None] * len(self._table) * 2\n self.__move_one_data()\n\n def __move_one_data(self):\n logger.debug(\n f'before table: {get_hash_table(self._table)}')\n logger.debug(f'before new_table: {get_hash_table(self._new_table)}')\n\n if self._new_table is not None:\n for i, node in enumerate(self._table):\n if node is not None:\n index = self._new_hash(node.key)\n logger.debug(f'搬移数据: {node.key}, new_hash_index: {index}')\n\n # 搬移一位\n old_node = self._new_table[index]\n next_node = node.next\n node.next = old_node\n\n self._new_table[index] = node\n self._table[i] = next_node\n break\n continue\n else:\n logger.debug('old table 已经搬空')\n self._table = self._new_table\n self._new_table = None\n\n logger.debug(f'after table: {get_hash_table(self._table)}')\n logger.debug(f'after new_table: {get_hash_table(self._new_table)}')\n logger.debug('')\n\n def insert(self, key, value):\n \"\"\" insert key value in dictionary. only update value if dictionary has the specified key\n :param key:\n :param value:\n :return:\n \"\"\"\n node = self._find_node_in_table(key)[0]\n if node is None:\n if self._size >= self._table_len() * self._LOAD_FACTOR:\n logger.debug('start resize')\n self.resize()\n\n self.__insert_value(key, value)\n else:\n if node.value != value:\n logger.debug('存在相同key,只更新value')\n node.value = value\n\n def _table_len(self):\n return len(self._table) if self._new_table is None else len(self._new_table)\n\n def __insert_value(self, key, value):\n logger.debug(f'insert new key. key: {key}, value: {value}')\n\n if self._new_table is not None:\n index = self._new_hash(key)\n old_node = self._new_table[index]\n self._new_table[index] = _ListNode(key, value)\n self._new_table[index].next = old_node\n self.__move_one_data()\n else:\n index = self._hash(key)\n old_node = self._table[index]\n self._table[index] = _ListNode(key, value)\n self._table[index].next = old_node\n\n self._size += 1\n\n def _get_node(self, node, key):\n while node is not None:\n if node.key == key:\n return node\n else:\n logger.debug(f'pass -> {node.key}')\n node = node.next\n\n def _find_node_in_new_table(self, key):\n if self._new_table is None:\n return None, None\n hash_index = self._new_hash(key)\n node = self._new_table[hash_index]\n return self._get_node(node, key), hash_index\n\n def _find_node_in_old_table(self, key):\n hash_index = self._hash(key)\n node = self._table[hash_index]\n return self._get_node(node, key), hash_index\n\n def _find_node_in_table(self, key):\n \"\"\"\n :param key:\n :return: node and table and hash_index\n \"\"\"\n node, hash_index = self._find_node_in_new_table(key)\n\n if node is None:\n node, index = self._find_node_in_old_table(key)\n if node is None:\n table = None\n hash_index = None\n else:\n table = self._table\n hash_index = index\n else:\n table = self._new_table\n\n return node, table, hash_index\n\n\nif __name__ == '__main__':\n map = HashMap(3)\n map.insert('a', '1')\n map.insert('a', 'a')\n map.insert('b', '2')\n map.insert('c', '3')\n map.insert('d', '4')\n map.insert('e', '5')\n map.insert('f', '6')\n print(map)\n\n print('map[\"a\"]:' + map['a'])\n print('map[\"b\"]:' + map['b'])\n print('map[\"c\"]:' + map['c'])\n print('map[\"d\"]:' + map['d'])\n print('map[\"e\"]:' + map['e'])\n print('map[\"f\"]:' + map['f'])\n\n print(map.setdefault('a', '123'))\n print(map.setdefault('aa', '123'))\n\n x = {'d': 2, 'a': '1', 'b': '2', 'c': 3}\n print(x.pop('z', 2))\n print(x.items())\n x.setdefault('ad', 3)\n\n\n","sub_path":"hash_table.py","file_name":"hash_table.py","file_ext":"py","file_size_in_byte":9910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"532733845","text":"import numpy as np\r\nimport cv2 as CvObject\r\n\r\n# Redirecting to path where xml files for Haar cascade Classifiers are stored\r\n\r\nimport os as path\r\npath.chdir(\"C:\\Python27\")\r\n\r\n\r\n# multiple cascades: https://github.com/Itseez/opencv/tree/master/data/haarcascades\r\n\r\n# Loading Haar Cascade Xml file for Face Detection\r\n\r\n#https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml\r\nface_cascade = CvObject.CascadeClassifier('haarcascade_frontalface_default.xml')\r\n\r\n# Loading Haar Cascade Xml file for Eye Detection\r\n\r\n#https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_eye.xml\r\neye_cascade = CvObject.CascadeClassifier('haarcascade_eye.xml')\r\n\r\nSelectWebcam = 0\r\nSelectOtherCam = 1\r\n\r\n# Record using the Webcam \r\ncapture = CvObject.VideoCapture(SelectWebcam)\r\n\r\nwhile True:\r\n # Read frame by frame in BGR (Blue,Green,Red)\r\n ret, frame_BGR = capture.read()\r\n \r\n # Convert BGR to GrayScale\r\n GrayScale = CvObject.cvtColor(frame_BGR, CvObject.COLOR_BGR2GRAY)\r\n\r\n # Detect faces using GrayScale frame\r\n faces = face_cascade.detectMultiScale(GrayScale)\r\n\r\n # For each Face we have two coordinates x,y and it's scale w,h\r\n # where : w - width , h - height of the face\r\n \r\n for (x,y,w,h) in faces:\r\n \r\n CvObject.rectangle(frame_BGR,\r\n # TopLeft Coordinate Of Rectangle\r\n (x,y),\r\n # BottomRight Coordinate Of Rectangle\r\n (x+w,y+h),\r\n # Outline Color of Rectangle(Blue)\r\n (255,0,0),\r\n # Outline width\r\n 2)\r\n\r\n # Detect eyes using GrayScale frame,\r\n # We are doing it inside loop of face because\r\n # Eyes can only be found on Face for Humans\r\n # So it will save our Computation of searching eye\r\n # over whole frame\r\n\r\n # Detecting face region\r\n\r\n # Slicing the Image from coordinate \"x to x+w\" and \"y to y+h\"\r\n\r\n faceRegion_gray = GrayScale[y:y+h, x:x+w]\r\n faceRegion_BGR = frame_BGR[y:y+h, x:x+w]\r\n\r\n # Searching Eyes inside Face from GrayScale image\r\n \r\n eyes = eye_cascade.detectMultiScale(faceRegion_gray)\r\n\r\n \r\n for (ex,ey,ew,eh) in eyes:\r\n # rather than reading the whole frame we read sliced region or face region only \r\n CvObject.rectangle(faceRegion_BGR,\r\n # TopLeft Coordinate Of Rectangle\r\n (ex,ey),\r\n # BottomRight Coordinate Of Rectangle\r\n (ex+ew,ey+eh),\r\n # Outline Color of Rectangle(Green)\r\n (0,255,0),\r\n # Outline width \r\n 2)\r\n\r\n \r\n\r\n \r\n # Show the frame with rectangles detecting the face and eyes\r\n CvObject.imshow('Detected Face and Eyes',frame_BGR)\r\n\r\n #Stopping the scan\r\n k = CvObject.waitKey(30) & 0xff\r\n # \"ESC\" ASCII code is 27 is ESC is pressed than stop\r\n if k == 27:\r\n break\r\n\r\ncapture.release()\r\nCvObject.destroyAllWindows()\r\n","sub_path":"haar Cascade for Face and Eyes Detection.py","file_name":"haar Cascade for Face and Eyes Detection.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"5509542","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Mar 25 11:27:15 2020\r\n\r\n@author: alizadeh\r\n\"\"\"\r\n\r\n\r\n# Tensorflow2\r\nimport tensorflow as tf\r\nfrom tensorflow import keras \r\n\r\nfashion_mnist = keras.datasets.fashion_mnist\r\n\r\n(X_train_full, y_train_full), (X_test, y_test) = fashion_mnist.load_data()\r\n\r\nfrom keras.layers import Input, Flatten, Dense, Conv2D, MaxPool2D, Dropout\r\nfrom keras.models import Model\r\nfrom keras import regularizers\r\nfrom functools import partial\r\n\r\ninputLayer=Input(shape=(28,28,1)) \r\n\r\ntmp=Conv2D(64,(7,7),activation='relu', padding='same',input_shape=(28,28,1))(inputLayer)\r\ntmp=MaxPool2D((2,2))(tmp)\r\ntmp=Conv2D(128,(3,3), activation='relu', padding='same')(tmp)\r\ntmp=Conv2D(128,(3,3), activation='relu', padding='same')(tmp)\r\ntmp=MaxPool2D((2,2))(tmp)\r\ntmp=Conv2D(256,(3,3), activation='relu', padding='same')(tmp)\r\ntmp=Conv2D(256,(3,3), activation='relu', padding='same')(tmp)\r\ntmp=MaxPool2D((2,2))(tmp)\r\ntmp=Flatten()(tmp)\r\ntmp=Dense(128,activation='relu')(tmp)\r\ntmp=Dropout(rate=0.5)(tmp)\r\ntmp=Dense(64,activation='relu')(tmp)\r\ntmp=Dropout(rate=0.5)(tmp)\r\noutputLayer=Dense(units=10,activation='softmax')(tmp)\r\n\r\nnetwork=Model(inputLayer,outputLayer)\r\n\r\nnetwork.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['accuracy'])\r\n#network.compile(optimizer='rmsprop',loss='sparse_categorical_crossentropy',metrics=['accuracy'])\r\n\r\nimport numpy as np\r\nX_train_full=X_train_full.reshape((60000,28,28,1))\r\nX_test=X_test.reshape((10000,28,28,1))\r\n\r\nperm=np.random.permutation(range(X_train_full.shape[0]))\r\nX_train_full=X_train_full[perm]\r\ny_train_full=y_train_full[perm]\r\nX_train_full=X_train_full.astype('float32')/255\r\nX_test=X_test.astype('float32')/255\r\nfrom keras.utils import to_categorical\r\ny_train_full01 = to_categorical(y_train_full)\r\ny_test01 = to_categorical(y_test)\r\ntrainingSize=55000\r\nX_train_used=X_train_full[:trainingSize]\r\ny_train_full01_used=y_train_full01[:trainingSize]\r\nval_train=X_train_full[trainingSize:]\r\nval_y_train_full01=y_train_full01[trainingSize:]\r\n\r\n#earlyStoppingCB=keras.callbacks.EarlyStopping(patience=10,restore_best_weights=True)\r\nhistory=network.fit(X_train_used, y_train_full01_used, \r\n validation_data=(val_train,val_y_train_full01),\r\n epochs=30, batch_size=128,\r\n #callbacks=[earlyStoppingCB]\r\n )\r\n\r\ntest_loss, test_acc=network.evaluate(X_test, y_test01)\r\nprint('test_acc:',test_acc)\r\n\r\n#plot progress of the algorithm\r\n\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n#pd.DataFrame(history.history).plot(figsize=(8, 5))\r\n#plt.grid(True)\r\n#plt.gca().set_ylim(0, 1) # set the vertical range to [0-1]\r\n#plt.show()\r\n\r\nhistory_dic = history.history\r\n# This line shows history_dic's keys. You can comment it out after\r\n# the first run\r\nprint(\"keys of history.histry:\",history_dic.keys())\r\nloss_values=history_dic['loss']\r\nvalidation_loss_values=history_dic['val_loss']\r\n\r\nepochs = range(1,len(loss_values)+1)\r\nplt.plot(epochs, loss_values, 'bo', label=\"Training loss\")\r\nplt.plot(epochs,validation_loss_values,'b',label=\"validation loss\")\r\nplt.title(\"Trainig and validation loss\")\r\nplt.xlabel('Epochs')\r\nplt.ylabel('Loss')\r\nplt.legend()\r\nplt.show()\r\n\r\n#plot training and valuation accuracy:\r\n\r\nacc_values=history_dic['accuracy'] # for Tensorflow2\r\n#acc_values=history_dic['acc'] #Tensorflow 1.15\r\n\r\nvalidation_acc_values=history_dic['val_accuracy'] # for Tensorflow2\r\n#validation_acc_values=history_dic['val_acc'] #Tensorflow 1.15\r\n\r\nplt.plot(epochs,acc_values, 'bo', label=\"Training acc\")\r\nplt.plot(epochs,validation_acc_values, 'b',label=\"Validation acc\") \r\nplt.ylabel('Loss')\r\nplt.legend()\r\nplt.show()\r\n\r\n# Now examine the performance of the model on various inputs if you wish.\r\n\r\nif input(\"Do you wish to see performance on the test set? y/n\")=='y':\r\n names=[\"T-shirt/top\", \"Trouser\", \"Pullover\", \"Dress\", \"Coat\",\r\n \"Sandal\", \"Shirt\", \"Sneaker\", \"Bag\", \"Ankle boot\"]\r\n \r\n #pred=network.predict_classes(X_test)\r\n pred=network.predict(X_test) #pred contains probabilities of each class\r\n from sklearn.metrics import confusion_matrix\r\n C=confusion_matrix(y_test, list(map(np.argmax,pred)))\r\n df=pd.DataFrame(data=confusion_matrix(y_test,list(map(np.argmax,pred))),\r\n columns=names,index=names)\r\n \r\n print(\"The confustion matrix:\\n\",C)\r\n print(df.head(10))\r\n #print(\"The confustion matrix:\\n\",confusion_matrix(y_test, pred))\r\n #Visualizing the confusion matrix. If all the colors are in the diagonal \r\n #it means all were correctly classified. Off diagonal colors indicate \r\n #misclassification\r\n print(\"The visualization of the confusion matrix:\")\r\n import seaborn as sns\r\n sns.heatmap(C,cmap=\"Spectral\")\r\n #sns.heatmap(confusion_matrix(y_test, pred),cmap=\"Spectral\")\r\n plt.show()\r\n input(\"hit enter to see some of misclassfied items:\")\r\n for i in range(len(X_test)):\r\n \r\n plt.imshow(X_test[i].reshape(28,28),cmap=plt.cm.binary)\r\n plt.show()\r\n print(\"predicted value of \",i,':', names[np.argmax(pred[i])], \" actual value:\", names[y_test[i]])\r\n plt.bar(height=pred[i],x=names)\r\n plt.xticks(range(len(names)),names, rotation=90) \r\n plt.show()\r\n if input(\"continue? y/n\")=='n':\r\n break ","sub_path":"2020Spring/DL/DemoCode/Topic06_Convolutional Neural Networks and Image Recognition/mnistFashionConv2.py","file_name":"mnistFashionConv2.py","file_ext":"py","file_size_in_byte":5305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"428712399","text":"from django import forms\r\nfrom .models import Messages\r\n\r\n\r\n\r\nclass MessagesForm(forms.ModelForm):\r\n class Meta:\r\n model = Messages\r\n fields = '__all__'\r\n exclude = ['create']\r\n\r\n def __init__(self, *args, **kwargs):\r\n super(MessagesForm, self).__init__(*args, **kwargs)\r\n \r\n for name, field in self.fields.items():\r\n field.widget.attrs['placeholder'] = field.label\r\n field.widget.attrs['id'] = f'conatct_form_{name}'\r\n field.label=\"\"\r\n\r\n ","sub_path":"apps/shop/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"291523729","text":"# -*- coding: utf-8 -*-\n# © <2019> \n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).\n\nfrom odoo import api, tools, SUPERUSER_ID\n\ndef post_init_hook(cr, registry):\n _init_master_data(cr, registry)\n\ndef _init_master_data(cr, registry):\n env = api.Environment(cr, SUPERUSER_ID, {})\n folder = env.ref('ch_sale.ch_documents_tech_files_folder')\n\n if folder:\n env['product.template'].sudo().write({\n 'folder_id': folder.id\n })\n","sub_path":"ch_sale/hooks.py","file_name":"hooks.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"88051179","text":"#import dependencies\nimport os\nimport csv\n\n#Filename & filepath\nfilepath = os.path.join(\"raw_data\",\"employee_data1.csv\")\ncsvpath_output = os.path.join(\"Output\",\"PyBoss_Outputdata1.csv\")\n\n#US state dictionary\nus_state_abbrev = {\n 'Alabama': 'AL',\n 'Alaska': 'AK',\n 'Arizona': 'AZ',\n 'Arkansas': 'AR',\n 'California': 'CA',\n 'Colorado': 'CO',\n 'Connecticut': 'CT',\n 'Delaware': 'DE',\n 'Florida': 'FL',\n 'Georgia': 'GA',\n 'Hawaii': 'HI',\n 'Idaho': 'ID',\n 'Illinois': 'IL',\n 'Indiana': 'IN',\n 'Iowa': 'IA',\n 'Kansas': 'KS',\n 'Kentucky': 'KY',\n 'Louisiana': 'LA',\n 'Maine': 'ME',\n 'Maryland': 'MD',\n 'Massachusetts': 'MA',\n 'Michigan': 'MI',\n 'Minnesota': 'MN',\n 'Mississippi': 'MS',\n 'Missouri': 'MO',\n 'Montana': 'MT',\n 'Nebraska': 'NE',\n 'Nevada': 'NV',\n 'New Hampshire': 'NH',\n 'New Jersey': 'NJ',\n 'New Mexico': 'NM',\n 'New York': 'NY',\n 'North Carolina': 'NC',\n 'North Dakota': 'ND',\n 'Ohio': 'OH',\n 'Oklahoma': 'OK',\n 'Oregon': 'OR',\n 'Pennsylvania': 'PA',\n 'Rhode Island': 'RI',\n 'South Carolina': 'SC',\n 'South Dakota': 'SD',\n 'Tennessee': 'TN',\n 'Texas': 'TX',\n 'Utah': 'UT',\n 'Vermont': 'VT',\n 'Virginia': 'VA',\n 'Washington': 'WA',\n 'West Virginia': 'WV',\n 'Wisconsin': 'WI',\n 'Wyoming': 'WY',\n}\n\n#Variable declaration\nhead = True\nFirst_Name = []\nLast_Name = []\nDOB = []\nSSN = []\nState = []\nReformatted_Line = []\n\n#Main logic to read a file and do the required calculations\nwith open(filepath) as csvhandlerR:\n InfileData = csv.reader(csvhandlerR)\n for line in InfileData:\n if head == True:\n Reformatted_Line.append(f'Emp_Id,First_Name,Last_Name,DOB,SSN,State')\n head = False\n else: \n #Split the name into first name & last name\n Split_Name = line[1].split(\" \")\n First_Name = Split_Name[0]\n Last_Name = Split_Name[1]\n \n #Reformat date from YYYY-MM-DD to MM/DD/YYYY\n Split_DOB = line[2].split(\"-\")\n Format_DOB = f'{Split_DOB[1]}/{Split_DOB[2]}/{Split_DOB[0]}'\n \n #Reformat SSN into ***-**-NNNN\n Split_SSN = line[3].split(\"-\")\n Format_SSN = f'{Split_SSN[0].replace(Split_SSN[0],\"***\")}-{Split_SSN[1].replace(Split_SSN[1],\"**\")}-{Split_SSN[2]}'\n \n #Reformat state name to its abbreviation\n State_Abbreviation = us_state_abbrev[line[4]] \n \n Reformatted_Line.append(f'{line[0]},{First_Name},{Last_Name},{Format_DOB},{Format_SSN},{State_Abbreviation}')\n\n#Writing to a csv file \nwith open(csvpath_output,'w',newline='') as csvhandlerW:\n OutfileData = csv.writer(csvhandlerW,delimiter=\"\\t\")\n for row in Reformatted_Line: \n OutfileData.writerow(row) ","sub_path":"Source Code.py","file_name":"Source Code.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"187136177","text":"#定义列表升序排序函数(从小到大)\n#list01 = [1,5,13,2,4]\n#思路\n#用第一个元素与后面元素比较 只要发现比第一个小的就换位置\n#用第二个元素与后面比较\n#...\n#用倒数第二个元素与后面比较\n\n\n# r 0 1 2 3\n# [5,6,13,2,4] 第一遍\n# [2,6,12,5,4]\n\n# [2,5,12,6,4]\n# [2,4,12,6,5]\n\n# [2,4,6,12,5]\n# [2,4,5,12,6]\n\n# [2,4,5,6,12]\n\n#循环的次数 取值 第一个值 第二个值\ndef mysort(list):\n #len(list)-1 最后一个数据 后面没有值了 不需要再比较\n for r in range(len(list)-1):\n #从当前数据的位置+1(下一个数据)开始 一直比到最后\n for c in range(r+1,len(list)):\n #如果当前数据比后面的数据大 交换位置\n if list[r] > list[c]:\n #a,b = b,a\n list[r],list[c] = list[c],list[r]\nlist01 = [6,5,13,2,4]\n# list01.sort(reverse=True) #[13, 6, 5, 4, 2]\nlist01.sort(reverse=False) #[2, 4, 5, 6, 13]\nprint(list01)\nlist02 = [1,7,2,55,40]\nmysort(list02)\nprint(list02) #[1, 2, 7, 40, 55]\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"pytnon-month01/month01-shibw-notes/day08-shibw/exercise02-定义升序排列函数.py","file_name":"exercise02-定义升序排列函数.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"122051581","text":"# encoding: utf-8\nimport os\nimport datetime\nfrom PIL import Image\n\n\ndef make_preview(preview_name, photo_name, photos_dir):\n \"\"\"Функция делает превью из фотографии и пишет превью в папку\n\n :argument preview_name: - имя файла превью\n :argument photo_name: - имя файла фотографии\n :argument photos_dir: - дирректория где лежат фотографии\n \"\"\"\n THUMB_SIZE = 80, 80\n img = Image.open(os.path.join(photos_dir, photo_name))\n width, height = img.size\n\n if width > height:\n delta = width - height\n left = int(delta/2)\n upper = 0\n right = height + left\n lower = height\n else:\n delta = height - width\n left = 0\n upper = int(delta/2)\n right = width\n lower = width + upper\n\n img = img.crop((left, upper, right, lower))\n img.thumbnail(THUMB_SIZE, Image.ANTIALIAS)\n img.save(os.path.join(photos_dir, preview_name))\n\n\ndef save_photo(file , dir, file_name_part):\n \"\"\"Сохраняет фотографии в папку\n\n :argument file: - файл фотографии\n :argument dir: - путь ��ля сохранения фотографий\n :argument file_name_part: - часть имени с расширением\n\n :return photo_name: - имя фотографии\n \"\"\"\n # сохраняем фотографию на диск\n photo_name = \"photo_\" + file_name_part\n photos_file = os.path.join(dir, photo_name)\n\n f = open(photos_file, 'wb')\n photo_data = file.read()\n f.write(photo_data)\n f.close()\n\n return photo_name\n","sub_path":"image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"463647188","text":"# 使用任意数量的关键字实参\ndef build_profile(first,last,**userinfo):\n profile = {}\n profile['first_name'] = first\n profile['last_name'] = last\n for key,value in userinfo.items():\n profile[key] = value\n return profile\nuser_profile = build_profile(\"cheng\",\"manyuan\",age = 20, sex = \"man\")\nprint(user_profile)\n","sub_path":"chapter8/test8.py","file_name":"test8.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"526658828","text":"#by 2boom 4bob@ua.fm 2011-16\nfrom Screens.Screen import Screen\nfrom Screens.PluginBrowser import PluginBrowser\nfrom Components.PluginComponent import plugins\nfrom Screens.Standby import TryQuitMainloop\nfrom Screens.MessageBox import MessageBox\nfrom Components.Sources.StaticText import StaticText\nfrom Components.Pixmap import Pixmap\nfrom Components.ActionMap import ActionMap, NumberActionMap\nfrom Components.Sources.List import List\nfrom Tools.LoadPixmap import LoadPixmap\nfrom Components.Console import Console as iConsole\nfrom Components.Label import Label\nfrom Components.MenuList import MenuList\nfrom Plugins.Plugin import PluginDescriptor\nfrom Components.Language import language\nfrom Tools.Directories import fileExists, pathExists, resolveFilename, SCOPE_PLUGINS, SCOPE_LANGUAGE\nfrom Components.config import config, getConfigListEntry, ConfigText, ConfigPassword, ConfigClock, ConfigInteger, ConfigDateTime, ConfigSelection, ConfigSubsection, ConfigYesNo, configfile, NoSave\nfrom Components.ConfigList import ConfigListScreen\nfrom Components.Harddisk import harddiskmanager\nfrom os import environ\nimport os\nimport gettext\nimport tools\nfrom enigma import eEPGCache\nfrom types import *\nfrom enigma import *\nimport sys, traceback\nimport re\nimport time\nimport new\nimport _enigma\nimport enigma\nimport socket\nimport gzip\nimport urllib\nimport stat\n\nglobal min, first_start\nmin = first_start = 0\n\nlang = language.getLanguage()\nenviron[\"LANGUAGE\"] = lang[:2]\ngettext.bindtextdomain(\"enigma2\", resolveFilename(SCOPE_LANGUAGE))\ngettext.textdomain(\"enigma2\")\ngettext.bindtextdomain(\"sftpanel\", \"%s%s\" % (resolveFilename(SCOPE_PLUGINS), \"sftpanel/locale/\"))\n\ndef _(txt):\n\tt = gettext.dgettext(\"sftpanel\", txt)\n\tif t == txt:\n\t\tt = gettext.gettext(txt)\n\treturn t\n\t\ndef mountp():\n\tpathmp = []\n\tif os.path.isfile('/proc/mounts'):\n\t\tfor line in open('/proc/mounts'):\n\t\t\tif '/dev/sd' in line or '/dev/disk/by-uuid/' in line or '/dev/mmc' in line or '/dev/mtdblock' in line:\n\t\t\t\tpathmp.append(line.split()[1].replace('\\\\040', ' ') + '/')\n\tpathmp.append('/usr/share/enigma2/')\n\tpathmp.append('/tmp/')\n\treturn pathmp\n\t\ndef logging(line):\n\tlog_file = open('/tmp/sftpanel.log', 'a')\n\tlog_file.write(line)\n\tlog_file.close()\n\n#now = time.localtime(time.time())\n######################################################################################\nconfig.plugins.sftpanel.filtername = ConfigYesNo(default = False)\nconfig.plugins.sftpanel.currentclock = ConfigClock(default = 0)\nconfig.plugins.sftpanel.multifilemode = ConfigSelection(default = \"Multi\", choices = [\n\t\t(\"Multi\", _(\"Multi files\")),\n\t\t(\"Single\", _(\"Single file\")),\n])\nconfig.plugins.sftpanel.userdir = ConfigText(default=\"/ipk/\", visible_width = 70, fixed_size = False)\n######################################################################################\nclass extrapanel(Screen):\n\tskin = \"\"\"\n\n\n\n\n\n\n\n\n\n\n\n\t{\"template\": [\n\t\tMultiContentEntryText(pos = (50, 2), size = (600, 25), font=0, flags = RT_HALIGN_LEFT, text = 0), # index 2 is the Menu Titel\n\t\tMultiContentEntryText(pos = (60, 29), size = (600, 18), font=1, flags = RT_HALIGN_LEFT, text = 2), # index 3 is the Description\n\t\tMultiContentEntryPixmapAlphaTest(pos = (5, 5), size = (100, 40), png = 3), # index 4 is the pixmap\n\t\t\t],\n\t\"fonts\": [gFont(\"Regular\", 23),gFont(\"Regular\", 16)],\n\t\"itemHeight\": 50\n\t}\n\t\n\t\t\n\"\"\"\n\n\tdef __init__(self, session):\n\t\tself.session = session\n\t\tScreen.__init__(self, session)\n\t\tself.setTitle(_(\"Utilidades SFT\"))\n\t\tself.iConsole = iConsole()\n\t\tself.indexpos = None\n\t\tself[\"shortcuts\"] = NumberActionMap([\"ShortcutActions\", \"WizardActions\", \"EPGSelectActions\", \"NumberActions\"],\n\t\t{\n\t\t\t\"ok\": self.keyOK,\n\t\t\t\"cancel\": self.exit,\n\t\t\t\"back\": self.exit,\n\t\t\t\"red\": self.exit,\n\t\t\t\"green\": self.keyGreen,\n\t\t\t\"yellow\": self.keyYellow,\n\t\t\t\"blue\": self.keyBlue,\n\t\t\t\"1\": self.go,\n\t\t\t\"2\": self.go,\n\t\t\t\"3\": self.go,\n\t\t\t\"4\": self.go,\n\t\t\t\"5\": self.go,\n\t\t\t\"6\": self.go,\n\t\t\t\"7\": self.go,\n\t\t})\n\t\tself[\"key_green\"] = StaticText(_(\"Informacion\"))\n\t\tself[\"key_yellow\"] = StaticText(_(\"Utilidades\"))\n\t\tself[\"key_blue\"] = StaticText(_(\"Instalar\"))\n\t\tself[\"key_red\"] = StaticText(_(\"Cerrar\"))\n\t\tself.list = []\n\t\tself[\"menu\"] = List(self.list)\n\t\tself.mList()\n\n\tdef mList(self):\n\t\tself.list = []\n\t\ttwopng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_PLUGINS, \"sftpanel/images/tools.png\"))\n\t\ttreepng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_PLUGINS, \"sftpanel/images/install.png\"))\n\t\tfourpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_PLUGINS, \"sftpanel/images/epp2.png\"))\n\t\tsixpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_PLUGINS, \"sftpanel/images/system.png\"))\n\t\tsevenpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_PLUGINS, \"sftpanel/images/addon.png\"))\n\t\teightpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_PLUGINS, \"sftpanel/images/system2.png\"))\n\t\tself.list.append((_(\"Utilidades de Servicio\"), 2, _(\"Gestion EPG, NTP, ejecucion script....\"), twopng ))\n\t\tself.list.append((_(\"Utilidades de Sistema\"), 3, _(\"Gestion modulos Kernel, memoria swpa, Samba, utilidades usb\"), sixpng ))\n\t\tself.list.append((_(\"Utilidades de Usuario\"), 4, _(\"Liberador memoria, gestion cuenta Dns, utilidades password\"), eightpng ))\n\t\tself.list.append((_(\"Instalar Paquetes\"), 5, _(\"Gestion de instalacion de paquetes\"), treepng))\n\t\tself.list.append((_(\"Acceso a Plugin\"), 6, _(\"Gestion de plugins, instalacion y desistalacion\"), sevenpng))\n\t\tself.list.append((_(\"Panel Configuracion\"), 8, _(\"Configuracion opciones Panel\"), fourpng))\n\t\tif self.indexpos != None:\n\t\t\tself[\"menu\"].setIndex(self.indexpos)\n\t\tself[\"menu\"].setList(self.list)\n\t\t\n\tdef go(self, num = None):\n\t\tif num is not None:\n\t\t\tnum -= 1\n\t\t\tif not num < self[\"menu\"].count():\n\t\t\t\treturn\n\t\t\tself[\"menu\"].setIndex(num)\n\t\titem = self[\"menu\"].getCurrent()[1]\n\t\tself.select_item(item)\n\t\t\n\tdef keyOK(self, item = None):\n\t\tself.indexpos = self[\"menu\"].getIndex()\n\t\tif item == None:\n\t\t\titem = self[\"menu\"].getCurrent()[1]\n\t\t\tself.select_item(item)\n\n\tdef select_item(self, item):\n\t\tif item:\n\t\t\tif item is 2:\t\t\t\t\n\t\t\t\tself.session.open(tools.ToolsScreen2)\n\t\t\telif item is 3:\n\t\t\t\tself.session.open(tools.SystemScreen)\n\t\t\telif item is 4:\n\t\t\t\tself.session.open(tools.System2Screen)\n\t\t\telif item is 5:\n\t\t\t\tfrom Plugins.Extensions.MediaScanner.plugin import main\n\t\t\t\tmain(self.session)\n\t\t\telif item is 6:\n\t\t\t\tself.session.open(PluginBrowser)\n\t\t\telif item is 8:\n\t\t\t\tself.session.open(ConfigExtentions2)\n\t\t\telse:\n\t\t\t\tself.close(None)\n\n\tdef exit(self):\n\t\tself.close()\n\n\tdef keyBlue (self):\n\t\tfrom Plugins.Extensions.MediaScanner.plugin import main\n\t\tmain(self.session)\n\t\t\t\t\n\tdef keyYellow (self):\n\t\tself.session.open(tools.ToolsScreen2)\n\t\t\n\tdef keyGreen (self):\n\t\tself.session.open(sftpanelinfo)\n\t\n\t\n######################################################################################\nclass sftpanelinfo(Screen):\n\tskin = \"\"\"\n\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\"\"\"\n\n\tdef __init__(self, session):\n\t\tself.session = session\n\t\tScreen.__init__(self, session)\n\t\tself.setTitle(_(\"sft-panel\"))\n\t\tself.iConsole = iConsole()\n\t\tself[\"shortcuts\"] = ActionMap([\"ShortcutActions\", \"WizardActions\"],\n\t\t{\n\t\t\t\"cancel\": self.cancel,\n\t\t\t\"back\": self.cancel,\n\t\t\t\"red\": self.cancel,\n\t\t\t\"ok\": self.cancel,\n\t\t\t})\n\t\tself[\"key_red\"] = StaticText(_(\"Close\"))\n\t\tself[\"MemoryLabel\"] = StaticText(_(\"Memory:\"))\n\t\tself[\"SwapLabel\"] = StaticText(_(\"Swap:\"))\n\t\tself[\"FlashLabel\"] = StaticText(_(\"Flash:\"))\n\t\tself[\"memTotal\"] = StaticText()\n\t\tself[\"swapTotal\"] = StaticText()\n\t\tself[\"flashTotal\"] = StaticText()\n\t\tself[\"device\"] = StaticText()\n\t\tself[\"installedLabel\"] = StaticText(_(\"Installed Date:\"))\n\t\tself[\"gstreamerLabel\"] = StaticText(_(\"GStreamer:\"))\n\t\t#self[\"livestreamerLabel\"] = StaticText(_(\"Livestreamer:\"))\n\t\tself[\"pythonLabel\"] = StaticText(_(\"Python:\"))\n\t\tself[\"installed\"] = StaticText()\n\t\tself[\"gstreamer\"] = StaticText()\n\t\t#self[\"livestreamer\"] = StaticText()\n\t\tself[\"python\"] = StaticText()\n\t\tself[\"Hardware\"] = StaticText()\n\t\tself[\"Image\"] = StaticText()\n\t\tself[\"CPULabel\"] = StaticText(_(\"Processor:\"))\n\t\tself[\"CPU\"] = StaticText()\n\t\tself[\"Kernel\"] = StaticText()\n\t\tself[\"nim\"] = StaticText()\n\t\tself[\"ipLabel\"] = StaticText(_(\"IP address:\"))\n\t\tself[\"ipInfo\"] = StaticText()\n\t\tself[\"macLabel\"] = StaticText(_(\"MAC (lan/wlan):\"))\n\t\tself[\"macInfo\"] = StaticText()\n\t\tself[\"EnigmaVersion\"] = StaticText()\n\t\tself[\"HardwareLabel\"] = StaticText(_(\"Hardware:\"))\n\t\tself[\"ImageLabel\"] = StaticText(_(\"Image:\"))\n\t\tself[\"KernelLabel\"] = StaticText(_(\"Kernel Version:\"))\n\t\tself[\"EnigmaVersionLabel\"] = StaticText(_(\"Last Upgrade:\"))\n\t\tself[\"driver\"] = StaticText()\n\t\tself[\"driverLabel\"] = StaticText(_(\"Driver Version:\"))\n\t\tself[\"plipanel\"] = StaticText(_(\"sft-panel Ver:\"))\n\t\tself[\"panelver\"] = StaticText()\n\t\tself[\"softcamLabel\"] = StaticText(_(\"Softcam:\"))\n\t\tself[\"softcam\"] = StaticText()\n\t\tself[\"cardserverLabel\"] = StaticText(_(\"Cardserver:\"))\n\t\tself[\"cardserver\"] = StaticText()\n\t\tself.memInfo()\n\t\tself.FlashMem()\n\t\tself.devices()\n\t\tself.mainInfo()\n\t\tself.verinfo()\n\t\tself.emuname()\n\t\tself.cpuinfo()\n\t\tself.getFlashDateString()\n\t\tself.getPythonVersionString()\n\t\t#self.getLivestreamerVersion()\n\t\tself.getGStreamerVersionString()\n\t\tself.network_info()\n\t\t\n\tdef getLivestreamerVersion(self):\n\t\tif fileExists(\"/usr/lib/python2.7/site-packages/livestreamer/__init__.py\"):\n\t\t\tfor line in open(\"/usr/lib/python2.7/site-packages/livestreamer/__init__.py\"):\n\t\t\t\tif '__version__' in line:\n\t\t\t\t\tself[\"livestreamer\"].text = line.split('\"')[1]\n\t\telse:\n\t\t\tself[\"livestreamer\"].text = _(\"Not Installed\")\n\n\tdef network_info(self):\n\t\tself.iConsole.ePopen(\"ifconfig -a\", self.network_result)\n\t\t\n\tdef network_result(self, result, retval, extra_args):\n\t\tif retval is 0:\n\t\t\tip = ''\n\t\t\tmac = []\n\t\t\tif len(result) > 0:\n\t\t\t\tfor line in result.splitlines(True):\n\t\t\t\t\tif 'HWaddr' in line:\n\t\t\t\t\t\tmac.append('%s' % line.split()[-1].strip('\\n'))\n\t\t\t\t\telif 'inet addr:' in line and 'Bcast:' in line:\n\t\t\t\t\t\tip = line.split()[1].split(':')[-1]\n\t\t\t\tself[\"macInfo\"].text = '/'.join(mac)\n\t\t\telse:\n\t\t\t\tself[\"macInfo\"].text = _(\"unknown\")\n\t\telse:\n\t\t\tself[\"macInfo\"].text = _(\"unknown\")\n\t\tif ip is not '':\n\t\t\tself[\"ipInfo\"].text = ip\n\t\telse:\n\t\t\tself[\"ipInfo\"].text = _(\"unknown\")\n\n\tdef getGStreamerVersionString(self):\n\t\timport enigma\n\t\ttry:\n\t\t\tself[\"gstreamer\"].text = enigma.getGStreamerVersionString().strip('GStreamer ')\n\t\texcept:\n\t\t\tself[\"gstreamer\"].text = _(\"unknown\")\n\t\t\n\tdef getFlashDateString(self):\n\t\ttry:\n\t\t\tself[\"installed\"].text = time.strftime(_(\"%Y-%m-%d %H:%M\"), time.localtime(os.stat(\"/boot\").st_ctime))\n\t\texcept:\n\t\t\tself[\"installed\"].text = _(\"unknown\")\n\t\t\t\n\tdef getPythonVersionString(self):\n\t\ttry:\n\t\t\timport commands\n\t\t\tstatus, output = commands.getstatusoutput(\"python -V\")\n\t\t\tself[\"python\"].text = output.split(' ')[1]\n\t\texcept:\n\t\t\tself[\"python\"].text = _(\"unknown\")\n\t\t\n\tdef cpuinfo(self):\n\t\tif fileExists(\"/proc/cpuinfo\"):\n\t\t\tcpu_count = 0\n\t\t\tprocessor = cpu_speed = cpu_family = cpu_variant = temp = ''\n\t\t\tcore = _(\"core\")\n\t\t\tcores = _(\"cores\")\n\t\t\tfor line in open('/proc/cpuinfo'):\n\t\t\t\tif \"system type\" in line:\n\t\t\t\t\tprocessor = line.split(':')[-1].split()[0].strip().strip('\\n')\n\t\t\t\telif \"cpu MHz\" in line:\n\t\t\t\t\tcpu_speed = line.split(':')[-1].strip().strip('\\n')\n\t\t\t\t\t#cpu_count += 1\n\t\t\t\telif \"cpu type\" in line:\n\t\t\t\t\tprocessor = line.split(':')[-1].strip().strip('\\n')\n\t\t\t\telif \"model name\" in line:\n\t\t\t\t\tprocessor = line.split(':')[-1].strip().strip('\\n').replace('Processor ', '')\n\t\t\t\telif \"cpu family\" in line:\n\t\t\t\t\tcpu_family = line.split(':')[-1].strip().strip('\\n')\n\t\t\t\telif \"cpu variant\" in line:\n\t\t\t\t\tcpu_variant = line.split(':')[-1].strip().strip('\\n')\n\t\t\t\telif line.startswith('processor'):\n\t\t\t\t\tcpu_count += 1\n\t\t\tif not cpu_speed:\n\t\t\t\ttry:\n\t\t\t\t\tcpu_speed = int(open(\"/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq\").read()) / 1000\n\t\t\t\texcept:\n\t\t\t\t\ttry:\n\t\t\t\t\t\timport binascii\n\t\t\t\t\t\tcpu_speed = int(int(binascii.hexlify(open('/sys/firmware/devicetree/base/cpus/cpu@0/clock-frequency', 'rb').read()), 16) / 100000000) * 100\n\t\t\t\t\texcept:\n\t\t\t\t\t\tcpu_speed = '-'\n\t\t\tif fileExists(\"/proc/stb/sensors/temp0/value\") and fileExists(\"/proc/stb/sensors/temp0/unit\"):\n\t\t\t\ttemp = \"%s%s%s\" % (open(\"/proc/stb/sensors/temp0/value\").read().strip('\\n'), unichr(176).encode(\"latin-1\"), open(\"/proc/stb/sensors/temp0/unit\").read().strip('\\n'))\n\t\t\telif fileExists(\"/proc/stb/fp/temp_sensor_avs\"):\n\t\t\t\ttemp = \"%s%sC\" % (open(\"/proc/stb/fp/temp_sensor_avs\").read().strip('\\n'), unichr(176).encode(\"latin-1\"))\n\t\t\tif cpu_variant is '':\n\t\t\t\tself[\"CPU\"].text = _(\"%s, %s Mhz (%d %s) %s\") % (processor, cpu_speed, cpu_count, cpu_count > 1 and cores or core, temp)\n\t\t\telse:\n\t\t\t\tself[\"CPU\"].text = \"%s(%s), %s %s\" % (processor, cpu_family, cpu_variant, temp)\n\t\telse:\n\t\t\tself[\"CPU\"].text = _(\"undefined\")\n\n\tdef status(self):\n\t\tstatus = ''\n\t\tif fileExists(\"/usr/lib/opkg/status\"):\n\t\t\tstatus = \"/usr/lib/opkg/status\"\n\t\telif fileExists(\"/usr/lib/ipkg/status\"):\n\t\t\tstatus = \"/usr/lib/ipkg/status\"\n\t\telif fileExists(\"/var/lib/opkg/status\"):\n\t\t\tstatus = \"/var/lib/opkg/status\"\n\t\telif fileExists(\"/var/opkg/status\"):\n\t\t\tstatus = \"/var/opkg/status\"\n\t\treturn status\n\t\t\n\tdef emuname(self):\n\t\tnameemu = []\n\t\tnamecard = []\n\t\tif fileExists(\"/etc/init.d/softcam\"):\n\t\t\tfor line in open(\"/etc/init.d/softcam\"):\n\t\t\t\tif \"echo\" in line:\n\t\t\t\t\tnameemu.append(line)\n\t\t\ttry:\n\t\t\t\tself[\"softcam\"].text = \"%s\" % nameemu[1].split('\"')[1]\n\t\t\texcept:\n\t\t\t\tself[\"softcam\"].text = \"Not Active\"\n\t\telse:\n\t\t\tself[\"softcam\"].text = _(\"Not Installed\")\n\t\tif fileExists(\"/etc/init.d/cardserver\"):\n\t\t\tfor line in open(\"/etc/init.d/cardserver\"):\n\t\t\t\tif \"echo\" in line:\n\t\t\t\t\tnamecard.append(line)\n\t\t\ttry:\n\t\t\t\tself[\"cardserver\"].text = \"%s\" % namecard[1].split('\"')[1]\n\t\t\texcept:\n\t\t\t\tself[\"cardserver\"].text = \"Not Active\"\n\t\telse:\n\t\t\tself[\"cardserver\"].text = _(\"Not Installed\")\n\t\t\n\tdef devices(self):\n\t\tlist = \"\"\n\t\thddlist = harddiskmanager.HDDList()\n\t\thddinfo = \"\"\n\t\tif hddlist:\n\t\t\tfor count in range(len(hddlist)):\n\t\t\t\thdd = hddlist[count][1]\n\t\t\t\tif int(hdd.free()) > 1024:\n\t\t\t\t\tlist += ((_(\"%s %s (%d.%03d GB free)\\n\") % (hdd.model(), hdd.capacity(), hdd.free()/1024 , hdd.free()%1024)))\n\t\t\t\telse:\n\t\t\t\t\tlist += ((_(\"%s %s (%03d MB free)\\n\") % (hdd.model(), hdd.capacity(),hdd.free())))\n\t\telse:\n\t\t\thddinfo = _(\"none\")\n\t\tself[\"device\"].text = list\n\t\t\n\tdef HardWareType(self):\n\t\tif os.path.isfile(\"/proc/stb/info/boxtype\"):\n\t\t\treturn open(\"/proc/stb/info/boxtype\").read().strip().upper()\n\t\tif os.path.isfile(\"/proc/stb/info/vumodel\"):\n\t\t\treturn \"VU+\" + open(\"/proc/stb/info/vumodel\").read().strip().upper()\n\t\tif os.path.isfile(\"/proc/stb/info/model\"):\n\t\t\treturn open(\"/proc/stb/info/model\").read().strip().upper()\n\t\treturn _(\"unavailable\")\n\t\t\n\tdef getImageTypeString(self):\n\t\ttry:\n\t\t\tif os.path.isfile(\"/etc/issue\"):\n\t\t\t\tfor line in open(\"/etc/issue\"):\n\t\t\t\t\tif not line.startswith('Welcom') and '\\l' in line:\n\t\t\t\t\t\treturn line.capitalize().replace('\\n', ' ').replace('\\l', ' ').strip()\n\t\texcept:\n\t\t\tpass\n\t\treturn _(\"undefined\")\n\t\t\n\tdef getKernelVersionString(self):\n\t\ttry:\n\t\t\treturn open(\"/proc/version\").read().split()[2]\n\t\texcept:\n\t\t\treturn _(\"unknown\")\n\t\t\t\n\tdef getImageVersionString(self):\n\t\ttry:\n\t\t\tif os.path.isfile('/var/lib/opkg/status'):\n\t\t\t\tst = os.stat('/var/lib/opkg/status')\n\t\t\telif os.path.isfile('/usr/lib/ipkg/status'):\n\t\t\t\tst = os.stat('/usr/lib/ipkg/status')\n\t\t\telif os.path.isfile('/usr/lib/opkg/status'):\n\t\t\t\tst = os.stat('/usr/lib/opkg/status')\n\t\t\telif os.path.isfile('/var/opkg/status'):\n\t\t\t\tst = os.stat('/var/opkg/status')\n\t\t\ttm = time.localtime(st.st_mtime)\n\t\t\tif tm.tm_year >= 2011:\n\t\t\t\treturn time.strftime(\"%Y-%m-%d %H:%M:%S\", tm)\n\t\texcept:\n\t\t\tpass\n\t\treturn _(\"unavailable\")\n\t\t\n\tdef listnims(self):\n\t\ttuner_name = {'0':'Tuner A:', '1':'Tuner B:', '2':'Tuner C:', '3':'Tuner D:', '4':'Tuner E:', '5':'Tuner F:', '6':'Tuner G:', '7':'Tuner H:', '8':'Tuner I:', '9':'Tuner J:'}\n\t\tnimlist = nims = ''\n\t\tallnims = []\n\t\tfbc_count = 0\n\t\tif fileExists(\"/proc/bus/nim_sockets\"):\n\t\t\tfor line in open(\"/proc/bus/nim_sockets\"):\n\t\t\t\tif 'NIM Socket' in line:\n\t\t\t\t\tnimlist += tuner_name[line.split()[-1].replace(':', '')] + ' '\n\t\t\t\telif 'Type:' in line:\n\t\t\t\t\tnimlist += '(%s)' % line.split()[-1].replace('\\n', '').strip() + ' '\n\t\t\t\telif 'Name:' in line:\n\t\t\t\t\tnimlist += '%s' % line.split(':')[1].replace('\\n', '').strip() + '\\n'\t\t\t\t\t\n\t\t\tallnims = []\n\t\t\tfbc_count = nimlist.count('FBC')\n\t\t\tif fbc_count / 4 > 0:\n\t\t\t\tfbc = fbc_count / 4\n\t\t\t\tfor line in nimlist.split('\\n'):\n\t\t\t\t\tallnims.append(line) \n\t\t\t\tfor count in range(0, len(allnims)):\n\t\t\t\t\tif count < fbc:\n\t\t\t\t\t\tnims += allnims[count] + '\\n'\n\t\t\t\t\tif count >= fbc * 4:\n\t\t\t\t\t\tnims += allnims[count] + '\\n'\n\t\t\t\treturn nims\n\t\t\telse:\n\t\t\t\treturn nimlist\n\t\telse:\n\t\t\treturn _(\"unavailable\")\n\t\t\t\n\t\tnims = nimmanager.nimList(showFBCTuners=False)\n\t\tfor count in range(len(nims)):\n\t\t\tif count < 4:\n\t\t\t\tself[\"Tuner\" + str(count)] = StaticText(nims[count])\n\t\t\telse:\n\t\t\t\tself[\"Tuner\" + str(count)] = StaticText(\"\")\n\t\t\tAboutText += nims[count] + \"\\n\"\n\t\t\t\n\tdef mainInfo(self):\n\t\tpackage = 0\n\t\tself[\"Hardware\"].text = self.HardWareType()\n\t\tself[\"Image\"].text = self.getImageTypeString()\n\t\tself[\"Kernel\"].text = self.getKernelVersionString()\n\t\tself[\"EnigmaVersion\"].text = self.getImageVersionString()\n\t\tself[\"nim\"].text = self.listnims()\n\t\tif fileExists(self.status()):\n\t\t\tfor line in open(self.status()):\n\t\t\t\tif \"-dvb-modules\" in line and \"Package:\" in line:\n\t\t\t\t\tpackage = 1\n\t\t\t\telif \"kernel-module-player2\" in line and \"Package:\" in line:\n\t\t\t\t\tpackage = 1\n\t\t\t\telif \"formuler-dvb-modules\" in line and \"Package:\" in line:\n\t\t\t\t\tpackage = 1\n\t\t\t\telif \"vuplus-dvb-proxy-vusolo4k\" in line and \"Package:\" in line:\n\t\t\t\t\tpackage = 1\n\t\t\t\tif \"Version:\" in line and package == 1:\n\t\t\t\t\tpackage = 0\n\t\t\t\t\tself[\"driver\"].text = line.split()[-1]\n\t\t\t\t\tbreak\n\n\tdef memInfo(self):\n\t\tfor line in open(\"/proc/meminfo\"):\n\t\t\tif \"MemTotal:\" in line:\n\t\t\t\tmemtotal = line.split()[1]\n\t\t\telif \"MemFree:\" in line:\n\t\t\t\tmemfree = line.split()[1]\n\t\t\telif \"SwapTotal:\" in line:\n\t\t\t\tswaptotal = line.split()[1]\n\t\t\telif \"SwapFree:\" in line:\n\t\t\t\tswapfree = line.split()[1]\n\t\tself[\"memTotal\"].text = _(\"Total: %s Kb Free: %s Kb\") % (memtotal, memfree)\n\t\tself[\"swapTotal\"].text = _(\"Total: %s Kb Free: %s Kb\") % (swaptotal, swapfree)\n\t\t\n\tdef FlashMem(self):\n\t\tsize = avail = 0\n\t\tst = os.statvfs(\"/\")\n\t\tavail = st.f_bsize * st.f_bavail / 1024\n\t\tsize = st.f_bsize * st.f_blocks / 1024\n\t\tself[\"flashTotal\"].text = _(\"Total: %s Kb Free: %s Kb\") % (size , avail)\n\t\t\n\tdef verinfo(self):\n\t\tpackage = 0\n\t\tself[\"panelver\"].text = \" \"\n\t\tfor line in open(self.status()):\n\t\t\tif \"sftpanel\" in line:\n\t\t\t\tpackage = 1\n\t\t\tif \"Version:\" in line and package is 1:\n\t\t\t\tpackage = 0\n\t\t\t\tself[\"panelver\"].text = line.split()[1]\n\t\t\t\tbreak\n\t\t\n\tdef cancel(self):\n\t\tself.close()\n######################################################################################\nclass ConfigExtentions2(ConfigListScreen, Screen):\n\tskin = \"\"\"\n\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\"\"\"\n\n\tdef __init__(self, session):\n\t\tself.session = session\n\t\tScreen.__init__(self, session)\n\t\tself.setTitle(_(\"sft-panel Menu/Extensionmenu config\"))\n\t\tself.list = []\n\t\tself.list.append(getConfigListEntry(_(\"Directorio Montaje\"), config.plugins.sftpanel.userdir))\n\t\tself.list.append(getConfigListEntry(_(\"Seccion modo instalacion paquete\"), config.plugins.sftpanel.multifilemode))\n\t\tself.list.append(getConfigListEntry(_(\"Filtrar nombre en descarga\"), config.plugins.sftpanel.filtername))\n\t\tself.list.append(getConfigListEntry(_(\"Directorio script\"), config.plugins.sftpanel.scriptpath))\n\t\tConfigListScreen.__init__(self, self.list)\n\t\tself[\"key_red\"] = StaticText(_(\"Close\"))\n\t\tself[\"key_green\"] = StaticText(_(\"Save\"))\n\t\tself[\"setupActions\"] = ActionMap([\"SetupActions\", \"ColorActions\", \"EPGSelectActions\"],\n\t\t{\n\t\t\t\"red\": self.cancel,\n\t\t\t\"cancel\": self.cancel,\n\t\t\t\"green\": self.save,\n\t\t\t\"ok\": self.save\n\t\t}, -2)\n\t\t\n\tdef cancel(self):\n\t\tself.close(False)\n\n\t\n\tdef save(self):\n\t\tfor i in self[\"config\"].list:\n\t\t\ti[1].save()\n\t\tconfigfile.save()\n\t\tself.mbox = self.session.open(MessageBox,(_(\"configuration is saved\")), MessageBox.TYPE_INFO, timeout = 4 )\n######################################################################################\nclass loadEPG():\n\tdef __init__(self):\n\t\tself.dialog = None\n\n\tdef gotSession(self, session):\n\t\tself.session = session\n\t\tself.iConsole = iConsole()\n\t\tif config.plugins.sftpanel.epgupdate.value:\n\t\t\tself.timer = enigma.eTimer() \n\t\t\tself.timermin = enigma.eTimer() \n\t\t\tself.timermin.callback.append(self.check_change_min)\n\t\t\tself.timer.callback.append(self.check_change)\n\t\t\tself.timermin.startLongTimer(30)\n\t\t\tself.timer.startLongTimer(60)\n\n\tdef check_change(self):\n\t\tself.timer.stop()\n\t\tnow = time.localtime(time.time())\n\t\ttry:\n\t\t\tlenght_epgfile = int(urllib.urlopen(config.plugins.sftpanel.url.value).info()['content-length'])\n\t\t\tlogging('%02d:%02d:%d %02d:%02d:%02d - size epg.tar.gz: %d bytes\\r\\n' % (now.tm_mday, now.tm_mon, now.tm_year, now.tm_hour, now.tm_min, now.tm_sec, lenght_epgfile))\n\t\t\tif config.plugins.sftpanel.leghtfile.value != lenght_epgfile:\n\t\t\t\tself.loadepgdat()\n\t\texcept Exception as e:\n\t\t\tlogging('%02d:%02d:%d %02d:%02d:%02d - %s\\r\\n' % (now.tm_mday, now.tm_mon, now.tm_year, now.tm_hour, now.tm_min, now.tm_sec, str(e)))\n\t\tself.timer.startLongTimer(int(config.plugins.sftpanel.checkp.value) * 60)\n\n\tdef check_change_min(self):\n\t\tself.timermin.stop()\n\t\tif not config.plugins.sftpanel.epgupdate.value and config.plugins.sftpanel.first.value:\n\t\t\tself.timer.stop()\n\t\tnow = time.localtime(time.time())\n\t\tif config.plugins.sftpanel.first.value and config.plugins.sftpanel.epgupdate.value:\n\t\t\tconfig.plugins.sftpanel.first.value = False\n\t\t\tif os.path.isfile('%s%s' % (config.plugins.sftpanel.direct.value, config.plugins.sftpanel.epgname.value)):\n\t\t\t\tepgcache = new.instancemethod(_enigma.eEPGCache_load,None,eEPGCache)\n\t\t\t\tepgcache = eEPGCache.getInstance().load()\n\t\t\t\tlogging('%02d:%02d:%d %02d:%02d:%02d - reload epg.dat\\r\\n' % (now.tm_mday, now.tm_mon, now.tm_year, now.tm_hour, now.tm_min, now.tm_sec))\n\t\t\t\t\n\t\tif config.plugins.sftpanel.checkepgfile.value and config.plugins.sftpanel.nocheck.value:\n\t\t\tif not os.path.isfile('%s%s' % (config.plugins.sftpanel.direct.value, config.plugins.sftpanel.epgname.value)):\n\t\t\t\tlogging('%02d:%02d:%d %02d:%02d:%02d - restore epg.dat\\r\\n' % (now.tm_mday, now.tm_mon, now.tm_year, now.tm_hour, now.tm_min, now.tm_sec))\n\t\t\t\tself.loadepgdat()\n\t\tif now.tm_hour in (0, 4, 8, 12, 16, 20) and now.tm_min == 1:\n\t\t\tself.iConsole.ePopen(\"opkg update\")\n\t\tself.timermin.startLongTimer(60)\n\n\tdef loadepgdat(self):\n\t\tconfig.plugins.sftpanel.nocheck.value = False\n\t\tnow = time.localtime(time.time())\n\t\tif os.path.isfile('%s%s' % (config.plugins.sftpanel.direct.value, config.plugins.sftpanel.epgname.value)):\n\t\t\tos.chmod('%s%s' % (config.plugins.sftpanel.direct.value, config.plugins.sftpanel.epgname.value), stat.S_IWRITE)\n\t\ttry:\n\t\t\tif self.isServerOnline():\n\t\t\t\tconfig.plugins.sftpanel.leghtfile.value = int(urllib.urlopen(config.plugins.sftpanel.url.value).info()['content-length'])\n\t\t\t\tconfig.plugins.sftpanel.leghtfile.save()\n\t\t\t\tconfigfile.save()\n\t\t\t\turllib.urlretrieve (config.plugins.sftpanel.url.value, '/tmp/epg.dat.gz')\n\t\t\t\tif os.path.isfile('/tmp/epg.dat.gz'):\n\t\t\t\t\tinFile = gzip.GzipFile('/tmp/epg.dat.gz', 'rb')\n\t\t\t\t\ts = inFile.read()\n\t\t\t\t\tinFile.close()\n\t\t\t\t\toutFile = file('%s%s' % (config.plugins.sftpanel.direct.value, config.plugins.sftpanel.epgname.value), 'wb')\n\t\t\t\t\toutFile.write(s)\n\t\t\t\t\toutFile.close()\n\t\t\t\t\tif os.path.isfile('/tmp/epg.dat.gz'):\n\t\t\t\t\t\tos.remove('/tmp/epg.dat.gz')\n\t\t\t\t\tepgcache = eEPGCache.getInstance()\n\t\t\t\t\tepgcache.flushEPG()\n\t\t\t\t\tepgcache = new.instancemethod(_enigma.eEPGCache_load,None,eEPGCache)\n\t\t\t\t\tepgcache = eEPGCache.getInstance().load()\n\t\t\t\t\tlogging('%02d:%02d:%d %02d:%02d:%02d - Auto Donwload & Unzip epg.dat.gz successful\\r\\n' % (now.tm_mday, now.tm_mon, now.tm_year, now.tm_hour, now.tm_min, now.tm_sec))\n\t\t\t\t\tconfig.plugins.sftpanel.lastupdate.value = _('last epg.dat updated - %02d:%02d:%d %02d:%02d:%02d' % (now.tm_mday, now.tm_mon, now.tm_year, now.tm_hour, now.tm_min, now.tm_sec))\n\t\t\t\t\tconfig.plugins.sftpanel.lastupdate.save()\n\t\t\t\t\tconfigfile.save()\n\t\t\telse:\n\t\t\t\tlogging('%02d:%02d:%d %02d:%02d:%02d - %s not respond\\r\\n' % (now.tm_mday, now.tm_mon, now.tm_year, now.tm_hour, now.tm_min, now.tm_sec, config.plugins.sftpanel.url.value.split('/')[2]))\n\t\texcept Exception as e:\n\t\t\tconfig.plugins.sftpanel.lastupdate.value = _('update error epg.dat - %02d:%02d:%d %02d:%02d:%02d' % (now.tm_mday, now.tm_mon, now.tm_year, now.tm_hour, now.tm_min, now.tm_sec))\n\t\t\tconfig.plugins.sftpanel.lastupdate.save()\n\t\t\tlogging('%02d:%02d:%d %02d:%02d:%02d - %s\\r\\n' % (now.tm_mday, now.tm_mon, now.tm_year, now.tm_hour, now.tm_min, now.tm_sec, str(e)))\n\t\tconfig.plugins.sftpanel.nocheck.value = True\n\n\tdef isServerOnline(self):\n\t\tnow = time.localtime(time.time())\n\t\ttry:\n\t\t\tsocket.gethostbyaddr(config.plugins.sftpanel.url.value.split('/')[2])\n\t\texcept Exception as e:\n\t\t\tlogging('%02d:%02d:%d %02d:%02d:%02d - %s\\r\\n' % (now.tm_mday, now.tm_mon, now.tm_year, now.tm_hour, now.tm_min, now.tm_sec, str(e)))\n\t\t\treturn False\n\t\treturn True\n\npEmu = loadEPG()\n######################################################################################\ndef sessionstart(reason,session=None, **kwargs):\n\tif reason == 0:\n\t\tpEmu.gotSession(session)\n######################################################################################\ndef main(session, **kwargs):\n\tsession.open(extrapanel)\n\ndef menu(menuid, **kwargs):\n\tif menuid == \"mainmenu\":\n\t\treturn [(_(\"sft-panel\"), main, _(\"sft-panel_\"), 48)]\n\treturn []\n\ndef Plugins(**kwargs):\n\tlist = [PluginDescriptor(name=_(\"Panel SFTeam\"), description=_(\"Utilidades imagen Sfteam\"), where = [PluginDescriptor.WHERE_EXTENSIONSMENU], fnc=main)]\n\treturn list\n\n\n","sub_path":"usr/lib/enigma2/python/Plugins/sftpanel/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":36528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"392746272","text":"\nfrom parse import compile\nfrom copy import copy, deepcopy\nfrom collections import defaultdict, Counter, deque\nfrom blist import *\nimport itertools\nimport math\n\nmaskreg = compile(\"mask = {}\")\nmemreg = compile(\"mem[{}] = {}\")\n# read in each line as value\ns = input()\nlines = []\nwhile s != 'done':\n if s.startswith('mask'):\n mask = s.split(\" \")[2]\n else:\n loc, val = memreg.parse(s)\n lines.append((str(mask), int(loc), int(val)))\n s = input()\n\ndef maskstr(mask, val):\n xmask = mask.replace('0', '0').replace('1', '0').replace('X', '1')\n nmask = mask.replace('X', '0')\n return (int(xmask, 2) & val) | int(nmask, 2)\n \n# \n# def maskstr(mask, val):\n# res = ''\n# offset = len(mask) - len(val)\n# for i in range(len(mask)):\n# if i < offset:\n# if mask[i] == 'X':\n# res += 'X'\n# elif mask[i] == '1':\n# res += mask[i]\n# else:\n# res += '0'\n# else:\n# m = mask[i]\n# if m == 'X':\n# res += 'X' \n# elif m == '1':\n# res += '1'\n# else:\n# res += val[i - offset]\n# return res\n \ndef iterx(val):\n vals = []\n ct = 0\n for v in val:\n if v == 'X':\n ct += 1\n \n #XX\n #0, 1, 2, 3\n if ct == 0:\n return [int(val, 2)]\n for b in range(0, 2**ct): \n bins = \"{0:b}\".format(b)\n bi = 0\n offset = ct - len(bins)\n cp = ''\n for v in val:\n \n if v == 'X':\n if bi < offset:\n cp += '0'\n else:\n cp += bins[offset - bi]\n bi += 1\n else:\n cp += v\n vals.append(int(cp, 2))\n return vals\n\n \nmem = {}\nfor (mask, loc, val) in lines:\n # v = \"{0:b}\".format(loc)\n fixed = maskstr(mask, val)\n # vals = iterx(fixed)\n mem[loc] = fixed\n # for v in vals:\n # mem[v] = val\n\ntot = 0\nfor k in mem:\n tot += mem[k]\n \n\nprint(tot)\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n # hello","sub_path":"2020/day14/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":2185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"98955042","text":"#\n# @lc app=leetcode.cn id=986 lang=python3\n#\n# [986] 区间列表的交集\n#\n\n\n# @lc code=start\nclass Solution:\n def intervalIntersection(self, A: List[List[int]],\n B: List[List[int]]) -> List[List[int]]:\n ia = 0\n ib = 0\n res = []\n while ia < len(A) and ib < len(B):\n # 没有交集的两种情况\n # a2 < b1, 推进ia\n if A[ia][-1] < B[ib][0]:\n ia += 1\n continue\n # b2 < a1, 推进ib\n if A[ia][0] > B[ib][-1]:\n ib += 1\n continue\n\n # 有交集的四种情况\n left = max(A[ia][0], B[ib][0])\n right = min(A[ia][-1], B[ib][-1])\n res.append([left, right])\n if A[ia][-1] < B[ib][-1]:\n ia += 1\n else:\n ib += 1\n\n return res\n\n\n# @lc code=end\n","sub_path":"records/986.区间列表的交集.py","file_name":"986.区间列表的交集.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"539678064","text":"from unittest.mock import patch\n\nfrom django.test import TestCase\nfrom django.urls import reverse\nfrom rest_framework import status\n\n\n# override_settings doesn't work - left here for reference\n# @override_settings(HAWK_AUTHENTICATION_ENABLED=True)\n@patch(\"conf.authentication.hawk_authentication_enabled\", lambda: True)\nclass TestHawkAuthentication(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n # test endpoint that retrieves licence details\n cls.test_url = reverse(\"mail:licence\")\n\n def test_hawk_authentication_returns_401(self):\n resp = self.client.get(self.test_url)\n\n # This will trigger an unknown Exception (as HTTP_HAWK_AUTHENTICATION isn't set)\n self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)\n\n # This will trigger a HawkException as HTTP_HAWK_AUTHENTICATION is invalid\n hawk_header = 'Hawk mac=\"\", hash=\"\", id=\"lite-api\", ts=\"\", nonce=\"\"'\n resp = self.client.get(self.test_url, HTTP_HAWK_AUTHENTICATION=hawk_header)\n self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)\n","sub_path":"conf/tests/test_authentication.py","file_name":"test_authentication.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"625762021","text":"import collections\nfrom unittest import mock\n\nimport pytest\n\nimport apiron\nfrom apiron import ServiceCaller\n\n\n@pytest.fixture\ndef service():\n class SomeService(apiron.Service):\n domain = \"http://foo.com\"\n\n return SomeService\n\n\nclass TestEndpoint:\n def test_call(self, service):\n service.foo = apiron.Endpoint()\n service.foo()\n\n def test_call_without_service_raises_exception(self):\n foo = apiron.Endpoint()\n with pytest.raises(TypeError):\n foo()\n\n def test_default_attributes_from_constructor(self):\n foo = apiron.Endpoint()\n assert \"/\" == foo.path\n assert \"GET\" == foo.default_method\n\n def test_constructor_stores_passed_attributes(self):\n foo = apiron.Endpoint(path=\"/foo/\", default_method=\"POST\")\n assert \"/foo/\" == foo.path\n assert \"POST\" == foo.default_method\n\n def test_format_response(self):\n foo = apiron.Endpoint()\n mock_response = mock.Mock()\n mock_response.text = \"foobar\"\n assert \"foobar\" == foo.format_response(mock_response)\n\n def test_required_headers(self):\n foo = apiron.Endpoint()\n assert {} == foo.required_headers\n\n def test_str_method(self):\n foo = apiron.Endpoint(path=\"/foo/bar/\")\n assert \"/foo/bar/\" == str(foo)\n\n def test_path_placeholders_when_none_present(self):\n foo = apiron.Endpoint()\n assert [] == foo.path_placeholders\n\n def test_path_placeholders_when_present(self):\n foo = apiron.Endpoint(path=\"/foo/{one}/{two}\")\n assert [\"one\", \"two\"] == foo.path_placeholders\n\n def test_format_path_with_correct_kwargs(self):\n foo = apiron.Endpoint(path=\"/{one}/{two}/\")\n path_kwargs = {\"one\": \"foo\", \"two\": \"bar\"}\n assert \"/foo/bar/\" == foo.get_formatted_path(**path_kwargs)\n\n def test_format_path_with_incorrect_kwargs(self):\n foo = apiron.Endpoint(path=\"/{one}/{two}/\")\n path_kwargs = {\"foo\": \"bar\"}\n with pytest.warns(RuntimeWarning, match=\"An unknown path kwarg was supplied\"):\n with pytest.raises(KeyError):\n foo.get_formatted_path(**path_kwargs)\n\n def test_format_path_with_extra_kwargs(self):\n foo = apiron.Endpoint(path=\"/{one}/{two}/\")\n path_kwargs = {\"one\": \"foo\", \"two\": \"bar\", \"three\": \"not used\"}\n with pytest.warns(RuntimeWarning, match=\"An unknown path kwarg was supplied\"):\n assert \"/foo/bar/\" == foo.get_formatted_path(**path_kwargs)\n\n def test_query_parameter_in_path_generates_warning(self):\n with pytest.warns(UserWarning, match=\"Endpoint path may contain query parameters\"):\n _ = apiron.Endpoint(path=\"/?foo=bar\")\n\n def test_get_merged_params(self):\n foo = apiron.JsonEndpoint(default_params={\"foo\": \"bar\"}, required_params={\"baz\"})\n assert {\"foo\": \"bar\", \"baz\": \"qux\"} == foo.get_merged_params({\"baz\": \"qux\"})\n\n def test_get_merged_params_with_unsupplied_param(self):\n foo = apiron.JsonEndpoint(default_params={\"foo\": \"bar\"}, required_params={\"baz\"})\n\n with pytest.raises(apiron.UnfulfilledParameterException):\n foo.get_merged_params()\n\n def test_get_merged_params_with_empty_param(self):\n foo = apiron.JsonEndpoint(default_params={\"foo\": \"bar\"}, required_params={\"baz\"})\n with pytest.warns(RuntimeWarning, match=\"endpoint was called with empty parameters\"):\n assert {\"foo\": \"bar\", \"baz\": None} == foo.get_merged_params({\"baz\": None})\n\n def test_get_merged_params_with_required_and_default_param(self):\n foo = apiron.JsonEndpoint(default_params={\"foo\": \"bar\"}, required_params={\"foo\"})\n assert {\"foo\": \"bar\"} == foo.get_merged_params()\n\n @mock.patch(\"apiron.client.requests.Session.send\")\n def test_using_path_kwargs_produces_warning(self, mock_send, service):\n service.foo = apiron.Endpoint(path=\"/foo/{one}\")\n with pytest.warns(RuntimeWarning, match=\"path_kwargs is no longer necessary\"):\n _ = service.foo(path_kwargs={\"one\": \"bar\"})\n\n @mock.patch(\"apiron.client.Timeout\")\n @mock.patch(\"requests.Session\", autospec=True)\n def test_legacy_endpoint_usage_with_instantiated_service(self, MockSession, mock_timeout, service):\n service.foo = apiron.Endpoint(path=\"/foo/\")\n instantiated_service = service()\n\n mock_logger = mock.Mock()\n request = mock.Mock()\n request.url = \"http://host1.biz/foo/\"\n\n ServiceCaller.call(\n instantiated_service, instantiated_service.foo, timeout_spec=mock_timeout, logger=mock_logger\n )\n\n\nclass TestJsonEndpoint:\n def test_format_response_when_unordered(self):\n foo = apiron.JsonEndpoint()\n mock_response = mock.Mock()\n\n with mock.patch.object(mock_response, \"json\") as mock_json:\n mock_json.return_value = {\"foo\": \"bar\"}\n assert {\"foo\": \"bar\"} == foo.format_response(mock_response)\n mock_json.assert_called_once_with(object_pairs_hook=None)\n\n def test_format_response_when_ordered(self):\n foo = apiron.JsonEndpoint(preserve_order=True)\n mock_response = mock.Mock()\n\n with mock.patch.object(mock_response, \"json\") as mock_json:\n mock_json.return_value = {\"foo\": \"bar\"}\n assert {\"foo\": \"bar\"} == foo.format_response(mock_response)\n mock_json.assert_called_once_with(object_pairs_hook=collections.OrderedDict)\n\n def test_required_headers(self):\n foo = apiron.JsonEndpoint()\n assert {\"Accept\": \"application/json\"} == foo.required_headers\n\n\nclass TestStreamingEndpoint:\n def test_format_response(self):\n foo = apiron.StreamingEndpoint()\n mock_response = mock.Mock()\n assert mock_response.iter_content(chunk_size=None) == foo.format_response(mock_response)\n\n\nclass TestStubEndpoint:\n def test_stub_response(self):\n \"\"\"\n Test initializing a stub endpoint with a stub response\n \"\"\"\n stub_endpoint = apiron.StubEndpoint(stub_response=\"stub response\")\n assert \"stub response\" == stub_endpoint.stub_response\n\n def test_extra_params(self):\n \"\"\"\n Test initializing a stub endpoint with extra params\n \"\"\"\n stub_endpoint = apiron.StubEndpoint(\n stub_response=\"stub response\",\n path=\"/some/path/\",\n default_params={\"param_name\": \"param_val\"},\n required_params={\"param_name\"},\n arbitrary_kwarg=\"foo\",\n )\n expected_params = {\n \"path\": \"/some/path/\",\n \"default_params\": {\"param_name\": \"param_val\"},\n \"required_params\": {\"param_name\"},\n \"arbitrary_kwarg\": \"foo\",\n }\n assert expected_params == stub_endpoint.endpoint_params\n\n def test_call_static(self, service):\n \"\"\"\n Test calling a ``StubEndpoint`` with a static response\n \"\"\"\n service.stub_endpoint = apiron.StubEndpoint(stub_response=\"stub response\")\n actual_response = service.stub_endpoint()\n expected_response = \"stub response\"\n assert actual_response == expected_response\n\n def test_call_dynamic(self, service):\n \"\"\"\n Test calling a StubEndpoint with a dynamic response\n \"\"\"\n\n def _test_case(call_kwargs, expected_response):\n def stub_response(**kwargs):\n if kwargs.get(\"params\") and kwargs[\"params\"].get(\"param_key\") == \"param_value\":\n return {\"stub response\": \"for param_key=param_value\"}\n else:\n return {\"default\": \"response\"}\n\n service.stub_endpoint = apiron.StubEndpoint(stub_response=stub_response)\n actual_response = service.stub_endpoint(**call_kwargs)\n assert actual_response == expected_response\n\n _test_case(call_kwargs={}, expected_response={\"default\": \"response\"})\n _test_case(\n call_kwargs={\"params\": {\"param_key\": \"param_value\"}},\n expected_response={\"stub response\": \"for param_key=param_value\"},\n )\n\n def test_call_without_service_raises_exception(self):\n stub_endpoint = apiron.StubEndpoint(stub_response=\"foo\")\n with pytest.raises(TypeError):\n stub_endpoint()\n","sub_path":"tests/test_endpoint.py","file_name":"test_endpoint.py","file_ext":"py","file_size_in_byte":8228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"134194744","text":"import numpy as np \nimport pandas as pd\nimport csv\n\n\ndef load_data (file):\n\tlist_data=[]\n\twith open(file,\"rt\") as f:\n\t\tdata=csv.reader(f)\n\t\t# print (data)\n\t\tf=0\n\t\tfor line in data:\n\t\t\ttemp_dict={}\n\t\t\tif f==0:\n\t\t\t\tf=1\n\t\t\telse:\n\t\t\t\ttemp_dict={}\n\t\t\t\tlist_params=line[0].split(',')\n\t\t\t\t# print (list_params)\n\t\t\t\ttemp_dict['D']=list_params[0]\n\t\t\t\ttemp_dict['X1']=list_params[1]\n\t\t\t\ttemp_dict['X2']=list_params[2]\n\t\t\t\ttemp_dict['X3']=list_params[3]\n\t\t\t\ttemp_dict['X4']=list_params[4]\n\t\t\t\ttemp_dict['X5']=list_params[5]\n\t\t\t\ttemp_dict['X6']=list_params[6]\n\t\t\t\tlist_data.append(temp_dict)\n\treturn list_data\n\n\n\n\ndef find_probs (train_data):\n\tlen_happy=len([x for x in train_data if x['D']=='1'])\n\tlen_unhappy=len([x for x in train_data if x['D']=='0'])\n\tp_happy=float(len([x for x in train_data if x['D']=='1']))/len(train_data)\n\tp_unhappy=float(len([x for x in train_data if x['D']=='0']))/len(train_data)\n\n\tlist_of_vals=['1','2','3','4','5']\n\n\tp_happy_attributes=np.zeros((7,6))\n\tp_unhappy_attributes=np.zeros((7,6))\n\n\tfor i in range (1,7):\n\t\tfor j in list_of_vals:\n\t\t\tval='X'+str(i)\n\t\t\tlen_ph=len([x for x in train_data if x['D']=='1' and x[val]==str(j)])\n\t\t\tlen_pu=len([x for x in train_data if x['D']=='0' and x[val]==str(j)])\n\t\t\t# print (i,j)\n\t\t\tp_happy_attributes[i][int(j)]=(float(len_ph)+1)/(len_happy+c)\n\t\t\tp_unhappy_attributes[i][int(j)]=(float(len_pu)+1)/(len_unhappy+c)\n\treturn p_happy_attributes,p_unhappy_attributes,p_happy,p_unhappy\n\n\ndef find_accuracy (test_data,p_happy_attributes,p_unhappy_attributes,p_happy,p_unhappy):\n\tcount_true=0\n\tfor data in test_data:\n\t\tp_happy_temp=p_happy\n\t\tp_unhappy_temp=p_unhappy\n\t\tres=0\n\t\tfor i in range (1,7):\n\t\t\tval='X'+str(i)\n\t\t\tp_happy_temp*=p_happy_attributes[i][int(data[val])]\n\t\t\tp_unhappy_temp*=p_unhappy_attributes[i][int(data[val])]\n\t\tif p_happy_temp>p_unhappy_temp:\n\t\t\tres='1'\n\t\telse:\n\t\t\tres='0'\n\t\tif (res==data['D']):\n\t\t\tcount_true+=1\n\t\tprint (data,\"predicted value is \",res)\n\treturn float(count_true)/len(test_data)\n\t# print (float(count_true)/len(test_data))\n\n\nc=5 #number of attributes \ntrain_data=load_data(\"data2_19.csv\")\np_happy_attributes,p_unhappy_attributes,p_happy,p_unhappy=find_probs(train_data)\ntest_data=load_data(\"test2_19.csv\")\nprint (\"TEST SET ACCURACY .....\")\naccuracy=find_accuracy(test_data,p_happy_attributes,p_unhappy_attributes,p_happy,p_unhappy)\n# print (p_unhappy_attributes[1:,1:])\nprint (\"accuracy on the test set is \",accuracy*100)\n\n\n\n\n","sub_path":"Assignment2/17EC30026_2.py","file_name":"17EC30026_2.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"377808096","text":"import os\n\nfrom datetime import datetime, timedelta\nimport dateutil.parser as date_parser\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom regolith.runcontrol import DEFAULT_RC, load_rcfile, filter_databases, \\\n connect_db\nfrom regolith.dates import month_to_int, get_dates\nfrom regolith.tools import (\n fuzzy_retrieval,\n all_docs_from_collection,\n get_pi_id,\n merge_collections_superior\n)\nfrom regolith.fsclient import _id_key\nfrom regolith.sorters import position_key\nfrom regolith.helpers.basehelper import DbHelperBase\n# print([k for k,v in chained_db['people'].items()])\nfrom pprint import pprint\n\nMONTH_COST = 3400\n\ndef daterange(date1, date2):\n return [date1 + timedelta(n) for n in range(int((date2 - date1).days) + 1)]\n\ndef subparser(subpi):\n subpi.add_argument(\"grant\",\n help=\"grant id for the grant you want to find appointments\")\n subpi.add_argument(\"-b\", \"--begin-date\",\n help=\"attestation period begins on this date, format YYYY-MM-DD\")\n subpi.add_argument(\"-e\", \"--end-date\",\n help=\"attestation period ends on this date\")\n subpi.add_argument(\"--no-plot\", action=\"store_true\",\n help=\"suppress the plotting\")\n return subpi\n\n\nclass AttestationsHelper(DbHelperBase):\n \"\"\"Helper for attestations\"\"\"\n # btype must be the same as helper target in helper.py\n btype = \"attestation\"\n needed_colls = ['people', 'grants', 'proposals', 'expenses']\n\n def construct_global_ctx(self):\n \"\"\"Constructs the global context\"\"\"\n super().construct_global_ctx()\n gtx = self.gtx\n rc = self.rc\n # if not rc.database:\n # rc.database = rc.databases[0][\"name\"]\n gtx[\"people\"] = sorted(\n all_docs_from_collection(rc.client, \"people\"),\n key=position_key,\n reverse=True,\n )\n gtx[\"expenses\"] = sorted(\n all_docs_from_collection(rc.client, \"expenses\"), key=_id_key\n )\n gtx[\"grants\"] = sorted(\n all_docs_from_collection(rc.client, \"grants\"), key=_id_key\n )\n gtx[\"proposals\"] = sorted(\n all_docs_from_collection(rc.client, \"proposals\"), key=_id_key\n )\n gtx[\"all_docs_from_collection\"] = all_docs_from_collection\n gtx[\"float\"] = float\n gtx[\"str\"] = str\n gtx[\"zip\"] = zip\n\n def db_updater(self):\n rc = self.rc\n print(f\"Instructions/Notes:\\n\"\n f\" Quarters are: Q1 July thru Sept, Q2 Oct - Dec, Q3 Jan - Mar, Q4 Apr - Jun\\n\"\n f\" Grad salaries are about ${MONTH_COST} per month\"\n )\n grant_id = rc.grant\n\n begin_date, end_date = None, None\n print(\"Collecting Appointments for grant {}:\".format(grant_id))\n expenses = self.gtx['expenses']\n people = self.gtx['people']\n jg = self.gtx['grants']\n proposals = self.gtx[\"proposals\"]\n grants = merge_collections_superior(proposals, jg, \"proposal_id\")\n grant = fuzzy_retrieval(\n grants,\n [\"name\", \"_id\", \"alias\"],\n grant_id)\n if not grant:\n raise ValueError(f\"ERROR: grant {grant_id} not found in grants\")\n if rc.begin_date:\n begin_date = date_parser.parse(rc.begin_date).date()\n if rc.end_date:\n end_date = date_parser.parse(rc.end_date).date()\n if not begin_date:\n begin_date = get_dates(grant)['begin_date']\n if not end_date:\n end_date = get_dates(grant)['end_date']\n plot_date_list = daterange(begin_date, end_date)\n\n months = (end_date - begin_date).days / 30.42\n\n appts, begin, end = [], datetime(3070, 1, 1).date(), datetime(1970, 1, 1).date()\n for person in people:\n person_appts = person.get('appointments', None)\n if person_appts:\n for _id, p_appt in person_appts.items():\n grantid = p_appt.get('grant')\n if grantid == grant_id:\n loading = p_appt.get('loading')\n bd = get_dates(p_appt).get(\"begin_date\")\n begin = min(begin, bd)\n ed = get_dates(p_appt).get(\"end_date\")\n end = max(end, ed)\n months_on_grant = (ed - bd).days / 30.4 * loading\n appt = (person['_id'], bd, ed, loading, months_on_grant)\n appts.append(appt)\n appts.sort(key=lambda x: (x[0], x[1]))\n folks = []\n for app in appts:\n if app[1] < end_date:\n if app[2] >= begin_date:\n print(\"{0}, from {1} to {2}, loading {3}. Total months: \"\n \"{4:6.2f}\".format(app[0], app[1].strftime(\"%Y-%m-%d\"),\n app[2].strftime(\"%Y-%m-%d\"), app[3], app[4]))\n folks.append(app[0])\n folks = list(set(folks))\n plots = []\n people_loadings = []\n loadingc = np.zeros(len(plot_date_list))\n for folk in folks:\n fig, ax = plt.subplots()\n loadinga = np.zeros(len(plot_date_list))\n for app in appts:\n if app[0] == folk:\n loadingl = []\n for day in plot_date_list:\n if app[1] <= day <= app[2]:\n loadingl.append(app[3])\n else:\n loadingl.append(0)\n loadinga = loadinga + np.array(loadingl)\n loadingc = loadingc + loadinga\n\n months, loadingm, accum, days = [plot_date_list[0]], [], 0, 0\n for day, load in zip(plot_date_list, loadinga):\n if day.day == 1 and days != 0:\n months.append(day)\n loadingm.append(accum * MONTH_COST / days)\n accum, days = 0, 0\n accum = accum + load\n days += 1\n months.pop()\n\n people_loadings.append((folk, loadinga, loadingm))\n if not rc.no_plot:\n ax.plot_date(plot_date_list, loadinga, ls='-', marker=\"\", label=folk)\n ax.set_xlabel('date')\n ax.set_ylabel(f\"loading for student {app[0]}\")\n ax.legend(loc='best')\n fig.autofmt_xdate()\n plots.append(fig)\n\n if not rc.no_plot:\n fig, ax = plt.subplots()\n ax.plot_date(plot_date_list, loadingc, ls='-', marker=\"\")\n\n print(f\"\\n-----------\\nLoadings by month\\n------------\")\n index = 0\n for month in months:\n print(f\"{month.isoformat()}:\")\n for person in people_loadings:\n if person[2][index] > 0:\n print(f\" {person[0]}\\tloading: {round(person[2][index], 2)}\")\n index += 1\n\n print(f\"\\n----------------\\nExpenses\\n----------------\")\n expenses_on_grant = [expense for expense in expenses if\n grant_id in expense.get('grants')]\n\n if len(expenses_on_grant) > 1:\n expenses_on_grant.sort(key=lambda x: get_dates(x).get('end_date'))\n for expense in expenses_on_grant:\n # print(expense.get('overall_purpose'))\n for reimb in expense.get('reimbursements'):\n if reimb.get('amount') == 0:\n amt = 0\n for exp_item in expense.get('itemized_expenses', []):\n amt += exp_item.get('unsegregated_expense')\n amt += exp_item.get('prepaid_expense', 0)\n reimb['amount'] = amt\n\n total_spend, month_spend, all_reimb_dates, all_reimb_amts = 0, 0, [], []\n for e in expenses_on_grant:\n reimb_amts = [round(i.get('amount'), 2) for i in e.get('reimbursements', [{}])]\n reimb_dates = [get_dates(i).get('date', get_dates(e).get('end_date')) for i in\n e.get('reimbursements', [{}])]\n all_reimb_dates.extend(reimb_dates)\n all_reimb_amts.extend(reimb_amts)\n total_spend += sum(reimb_amts)\n\n for reim_date, amt in zip(reimb_dates, reimb_amts):\n print(\n f\"{reim_date} (reimb date), {get_dates(e).get('end_date')} (expense date): amount: \"\n f\"{amt}, \")\n print(\n f\" payee: {e.get('payee')} \"\n f\"purpose: {e.get('overall_purpose')[:60]}\")\n for month in months:\n if month >= begin_date:\n month_spend = 0\n for amt, dte in zip(all_reimb_amts, all_reimb_dates):\n if month.year == dte.year and month.month == dte.month:\n month_spend += amt\n print(f\"{month}: expenses monthly total = {month_spend}\")\n\n print(f\"Total spend = {round(total_spend, 2)}\")\n for plot in plots:\n plt.show()\n\n","sub_path":"regolith/helpers/attestationshelper.py","file_name":"attestationshelper.py","file_ext":"py","file_size_in_byte":9025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"518545010","text":"\"\"\"\nsmry Application Views\n W. R. Emanuel, University of Maryland, College Park\n E-Mail: wemanuel@umd.edu\n Gmail: wemanuel@gmail.com\n\nVersion 3.2\n\nVersion 3.2 Deployed to moses on 26 Jul 2015.\n\nVersion 3.1 incorporates sessions in place of cookies.\n\nVersion 3.0 incorporates access to Google Earth Engine.\n\nVersion 2.0 addresses numerous errors and reorganizes methods\nfor filtering database objects.\n\nVersion 1.8 incorporates site variables.\n Version 1.8.1 incorporates a descriptive text option into\n site models and a corresponding form..\n\nVersion 1.7 incorporates about text items.\n\nVersion 1.6 incorporates arbitrary text items that are not related\nto specific data or images.\n\nVersion 1.5 incorporates plots of VCF (tree cover fraction)\ndistributions by land cover type.\n\"\"\"\n\nimport os\nimport logging\nimport pickle\n\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.template import RequestContext, loader\nfrom django.shortcuts import render\nfrom django import forms\n\n# Import the Earth Engine API and configuration module.\nimport ee\nimport config\n\nfrom smry.models import TextItem, Region, Map, Chart, Legend\nfrom smry.rgn_forms import YearForm_MODIS_LandCover, YearForm_CDL\nfrom smry.rgn_forms import RegionForm, RegionYearForm_MODIS_LandCover\nfrom smry.rgn_forms import YearForm_NLCD\n\nimport site_attr\nimport geo_data_attrs\nimport text_items\nfrom rgn_images import RegionImages\nimport palettes\nimport ee_smry\n\n# Absolute path to subdirectory containing data files.\n# A pickle archive in this directory contains summaries of\n# land cover by area.\nDATA_PATH = \"/home/thenan6/public_html/Indicators/static/smry/data\"\n\n# Dictionary to map region names to abbreviations. This mapping\n# is used to resolve selected discrepancies between region names\n# and file names containing data or images for corresponding\n# regions.\nrgn_to_abbrv = {\"Alaska\": \"AlaskaWH\", \"Great Plains\": \"GrtPlns\",\n \"Midwest\": \"MidWest\", \"Northeast\": \"NorthEast\",\n \"Northwest\": \"NorthWest\", \"Southeast\": \"SouthEast\",\n \"Southwest\": \"SouthWest\", \"Hawaii\": \"Hawaii\",\n \"PuertoRico\": \"PuertoRicoVirginIS\", \n \"Puerto Rico\": \"PuertoRicoVirginIS\",\n \"USA48\": \"USA48\",\n \"Conterminous 48 U.S. States\": \"USA48\"}\nabbrv_to_rgn = {\"AlaskaWH\": \"Alaska\", \"GrtPlns\": \"Great Plains\",\n \"MidWest\": \"Midwest\", \"NorthEast\": \"Northeast\",\n \"NorthWest\": \"Northwest\", \"SouthEast\": \"Southeast\",\n \"SouthWest\": \"Southwest\", \"Hawaii\": \"Hawaii\",\n \"PuertoRicoVirginIS\": \"PuertoRico\", \n \"PuertoRicoVirginIS\": \"Puerto Rico\",\n \"USA48\": \"Conterminous 48 U.S. States\"}\n\n# Dictionaries to specify text replacement in html strings.\ndel_p = {\"

\": \"\", \"

\": \"\"}\n\n# Create a logging service.\nsmrylogger = logging.getLogger(\"smry\")\nsmrylogger.setLevel(logging.DEBUG)\n\ndef index(request):\n \"\"\"\n index(request)\n \n Site Front Page.\n\n Presents introductory text and a map of NCA regions. A form\n allows selection of a region. On submit, user is redirected\n to the rgn_smry view at the selected region.\n \"\"\"\n# smrylogger.debug(\"INDEX VIEW\")\n\n # Initialize a session.\n site_attr.init_session(request)\n\n attr_dct = site_attr.set_attrs(request, \"modis_lnd_cvr\") \n smrylogger.debug(\"index( )|attr_dct: %s\", attr_dct)\n\n # Region selection form.\n if request.method == \"POST\":\n rgn_form = RegionForm(request.POST) \n if rgn_form.is_valid():\n # Update attributes.\n for key in rgn_form.cleaned_data.keys():\n attr_dct[key] = rgn_form.cleaned_data[key]\n# smrylogger.debug(\"index( )|attr_dct: %s\", attr_dct)\n\n # Set session attributes to dictionary items.\n site_attr.set_session_attr(request, attr_dct)\n\n # Create response to redirect to region summary.\n response = HttpResponseRedirect(\"rgn_smry/\")\n else:\n # Create an instance of class RegionForm.\n rgn_form = RegionForm(initial = {\n \"region\": abbrv_to_rgn[attr_dct[\"region\"]],\n \"dscrpt_txt\": (attr_dct[\"dscrpt_txt\"] == \"True\")})\n\n # Get introductory text from the database and process to html.\n intro_text = text_items.get_txt_html(\"index\", \"intro_text\")\n intro_text_1 = text_items.get_txt_html(\"index\", \"intro_text_1\",\n replace = {\"

\": \"\", \"

\": \"

\"})\n\n # Load the region summary template.\n index_template = loader.get_template(\"smry/index.html\")\n context = RequestContext(request, {\"form\": rgn_form,\n \"form_help\": rgn_form.form_help,\n \"intro_text\": intro_text,\n \"intro_text_1\": intro_text_1})\n response = HttpResponse(index_template.render(context))\n\n return response\n\ndef rgn_smry(request):\n \"\"\"\n rgn_smry(request)\n \n Regional summary view.\n \"\"\"\n# smrylogger.debug(\"REGIONAL SUMMARY VIEW\")\n\n # Set attributes.\n attr_dct = site_attr.set_attrs(request, \"modis_lnd_cvr\")\n\n # Create an instance of class Region_Region_Form.\n rgn_form = RegionYearForm_MODIS_LandCover(initial = {\n \"region\": attr_dct[\"region\"],\n \"year\": attr_dct[\"year\"],\n \"dscrpt_txt\": attr_dct[\"dscrpt_txt\"]})\n\n if request.method == \"POST\":\n # Create an instance of class RegionYearForm and populate\n # with request data.\n rgn_form = RegionYearForm_MODIS_LandCover(request.POST)\n\n if rgn_form.is_valid():\n # Update attributes.\n for key in rgn_form.cleaned_data.keys():\n attr_dct[key] = rgn_form.cleaned_data[key]\n # logging 1\n# smrylogger.debug(\"1 rgn_smry( )|attr_dct: %s\", attr_dct)\n\n # Set attributes in session to dictionary items.\n site_attr.set_session_attr(request, attr_dct)\n # logging 2\n# smrylogger.debug(\"2 rgn_smry( )|attr_dct: %s\", attr_dct)\n# else:\n # logging 3\n# smrylogger.debug(\"3 rgn_smry( )|Warning: rgn_form is invalid\")\n else:\n # Create an instance of class RegionForm.\n rgn_form = RegionYearForm_MODIS_LandCover(initial = {\n \"region\": attr_dct[\"region\"],\n \"year\": attr_dct[\"year\"],\n \"dscrpt_txt\": attr_dct[\"dscrpt_txt\"]})\n \n if attr_dct[\"dscrpt_txt\"]:\n # Get descriptive text from the database.\n intro_txt_html = text_items.get_txt_html(\"rgn_smry\",\n \"rgn_smry_intro\")\n trends_txt_html = text_items.get_txt_html(\"rgn_smry\",\n \"trends\", replace = del_p)\n vcf_txt_html = text_items.get_txt_html(\"rgn_smry\",\n \"vcf\", replace = del_p)\n else:\n intro_txt_html = \"\"\n trends_txt_html = \"\"\n vcf_txt_html = \"\"\n\n # Get file name attributes from the database.\n # logging 4\n# smrylogger.debug(\"4 rgn_smry( )|attr_dct: %s\", attr_dct)\n # Expand USA48 to full region name.\n if attr_dct[\"region\"] == \"USA48\":\n region_name = abbrv_to_rgn[attr_dct[\"region\"]]\n else:\n region_name = attr_dct[\"region\"]\n rgn_img = RegionImages()\n rgn_img.rgn_smry_images(region_name, attr_dct[\"year\"])\n\n # Create distribution table data as a list.\n table_list = create_distr_table_list(attr_dct[\"region\"], attr_dct[\"year\"])\n\n # Create request context from attributes. \n dct = rgn_img.attr.dct\n for key in attr_dct.keys():\n dct[key] = attr_dct[key]\n dct[\"rgn_name\"] = attr_dct[\"region\"]\n dct[\"intro_txt\"] = str(intro_txt_html)\n dct[\"trends_txt\"] = str(trends_txt_html)\n dct[\"vcf_txt\"] = str(vcf_txt_html)\n dct[\"form\"] = rgn_form\n dct[\"form_help\"] = rgn_form.form_help\n dct[\"table_list\"] = table_list\n\n rgn_img = None\n\n # Load the region summary template.\n rgn_template = loader.get_template(\"smry/rgn_smry.html\")\n\n # Create context and render.\n context = RequestContext(request, dct)\n response = HttpResponse(rgn_template.render(context))\n\n return response\n\ndef rgn_map(request):\n \"\"\"\n rgn_map(request)\n \n Display a single map image for the specified region and year.\n \"\"\"\n# smrylogger.debug(\"REGIONAL MAP VIEW\")\n\n # Set attributes to session values.\n attr_dct = site_attr.get_session_attr(request)\n\n rgn_form = RegionYearForm_MODIS_LandCover(request.POST, initial = {\n \"region\": attr_dct[\"region\"],\n \"year\": attr_dct[\"year\"],\n \"dscrpt_txt\": attr_dct[\"dscrpt_txt\"]})\n # 1\n# smrylogger.debug(\"1 rgn_map( )|rgn_form.initial: %s\", rgn_form.initial)\n\n if request.method == \"POST\":\n # Create an instance of class RegionYearForm and populate\n # with request data.\n rgn_form = RegionYearForm_MODIS_LandCover(request.POST)\n\n if rgn_form.is_valid():\n # Update attributes.\n for key in rgn_form.cleaned_data.keys():\n attr_dct[key] = rgn_form.cleaned_data[key]\n\n # Set attributes in session to dictionary items.\n site_attr.set_session_attr(request, attr_dct)\n # 2\n# smrylogger.debug(\"2 rgn_map( )|attr_dct: %s\", attr_dct)\n# else:\n # 3\n# smrylogger.debug(\"3 rgn_map( )|Warning: rgn_form is invalid\")\n else:\n # Create an instance of class RegionYearForm.\n rgn_form = RegionYearForm_MODIS_LandCover(initial = {\n \"region\": attr_dct[\"region\"],\n \"year\": attr_dct[\"year\"],\n \"dscrpt_txt\": attr_dct[\"dscrpt_txt\"]})\n\n # Get file name attributes from the database.\n # Expand USA48 to full region name.\n if attr_dct[\"region\"] == \"USA48\":\n region_name = abbrv_to_rgn[attr_dct[\"region\"]]\n else:\n region_name = attr_dct[\"region\"]\n img = RegionImages()\n img.rgn_map_images(region_name, attr_dct[\"year\"])\n\n # Create request context from attributes. \n dct = img.attr.dct\n for key in attr_dct.keys():\n dct[key] = attr_dct[key]\n dct[\"rgn_name\"] = region_name \n dct[\"form\"] = rgn_form\n dct[\"form_help\"] = rgn_form.form_help\n\n img = None\n\n # Load the region map template.\n template = loader.get_template(\"smry/rgn_map.html\")\n\n # Create context and render.\n context = RequestContext(request, dct)\n response = HttpResponse(template.render(context))\n\n return response\n\ndef rgn_pie_charts(request):\n \"\"\"\n rgn_pie_charts(request)\n \n Display pie charts at four years.\n \"\"\"\n\n# smrylogger.debug(\"REGION PIE CHARTS VIEW\")\n\n # Set attributes to session values.\n attr_dct = site_attr.get_session_attr(request)\n # 1\n# smrylogger.debug(\"1 rgn_pie_charts( )|attr_dct: %s\", attr_dct)\n\n if request.method == \"POST\":\n # Create an instance of class Region_Year_Form and populate\n # with request data.\n rgn_form = RegionYearForm_MODIS_LandCover(request.POST)\n\n if rgn_form.is_valid():\n # Update attributes.\n for key in rgn_form.cleaned_data.keys():\n attr_dct[key] = rgn_form.cleaned_data[key]\n # 2\n# smrylogger.debug(\"2 rgn_pie_charts( )|attr_dct: %s\", attr_dct)\n\n # Set attributes in session to dictionary items.\n site_attr.set_session_attr(request, attr_dct)\n else:\n # Create an instance of class RegionForm.\n rgn_form = RegionYearForm_MODIS_LandCover(initial = {\n \"region\": attr_dct[\"region\"],\n \"year\": attr_dct[\"year\"],\n \"dscrpt_txt\": attr_dct[\"dscrpt_txt\"]})\n\n # 3\n# smrylogger.debug(\"3 rgn_pie_charts( )|attr_dct: %s\", attr_dct)\n\n # Create year list for pie charts.\n chart_year_list = create_year_list(int(attr_dct[\"year\"]),\n 2001, 2012, 2)\n\n # Create an instance of class RegionImages for access to\n # pie chart attributes.\n rgn_img = RegionImages(img_size = \"500px\")\n\n # Get pie chart file names.\n # Expand USA48 to full region name.\n if attr_dct[\"region\"] == \"USA48\":\n region_name = abbrv_to_rgn[attr_dct[\"region\"]]\n else:\n region_name = attr_dct[\"region\"]\n filenames = []\n\n # Iterate over year list.\n for year in chart_year_list:\n filename = rgn_img.chart_filter(region_name, year, \"LC\",\n rgn_img.img_size, \"piechart\")\n filenames.append(filename)\n\n # Create request context from attributes. \n dct = {}\n for key in attr_dct.keys():\n dct[key] = attr_dct[key]\n dct[\"rgn_name\"] = attr_dct[\"region\"]\n dct[\"chart_year_list\"] = chart_year_list\n dct[\"filenames\"] = filenames\n dct[\"form\"] = rgn_form\n dct[\"form_help\"] = rgn_form.form_help\n\n rgn_img = None\n\n # Load the region map template.\n template = loader.get_template(\"smry/rgn_pie_charts.html\")\n\n # Create context and render.\n context = RequestContext(request, dct)\n response = HttpResponse(template.render(context))\n\n return response\n\ndef land_cover(request):\n \"\"\"\n land_cover(request)\n \n Global maps of the MODIS land cover data product (MCD12Q), rendered by the\n Google Earth Engine.\n \"\"\"\n smrylogger.debug(\"LAND COVER VIEW\")\n\n # Set attributes.\n attr_dct = site_attr.set_attrs(request, \"modis_lnd_cvr\")\n\n # Create an instance of YearForm.\n year_form = YearForm_MODIS_LandCover(request.POST,\n initial = {\"year\": attr_dct[\"year\"],\n \"opacity\": attr_dct[\"opacity\"],\n \"dscrpt_txt\": attr_dct[\"dscrpt_txt\"]})\n # 1\n smrylogger.debug(\"1 land_cover( )|year_form.initial: %s\", year_form.initial)\n\n if request.method == \"POST\":\n # Create an instance of class YearForm and populate with\n # request data.\n year_form = YearForm_MODIS_LandCover(request.POST)\n\n if year_form.is_valid():\n # Update attributes.\n for key in year_form.cleaned_data.keys():\n attr_dct[key] = year_form.cleaned_data[key]\n\n # Set attributes in session to dictionary items.\n site_attr.set_session_attr(request, attr_dct)\n # 2\n smrylogger.debug(\"2 land_cover( )|attr_dct: %s\", attr_dct)\n else:\n # 3\n logmsg = \"3 land_cover( )|Warning: year_form is invalid\"\n smrylogger.debug(logmsg) \n\n else:\n # Create an instance of class YearForm.\n year_form = YearForm_MODIS_LandCover(initial = {\n \"year\": attr_dct[\"year\"],\n \"opacity\": attr_dct[\"opacity\"],\n \"dscrpt_txt\": attr_dct[\"dscrpt_txt\"]}) \n\n # Initialize Earth Engine. The configuration file config.py\n # contains credentials.\n ee.Initialize(config.EE_CREDENTIALS, config.EE_URL)\n \n # Get color palette.\n palette_str = palettes.igbp_lndcvr()\n\n # Create Image name.\n img_name = \"MODIS/051/MCD12Q1/\" + str(attr_dct[\"year\"]) + \"_01_01\"\n # 4\n smrylogger.debug(\"4 land_cover( )|img_name: %s\", img_name)\n\n # Get map ID.\n img = ee.Image(img_name).select([\"Land_Cover_Type_1\"])\n mapid = img.getMapId({'min': 0, 'max': 17, \"palette\": palette_str})\n # 5\n smrylogger.debug(\"5 land_cover( )|mapid: %s\", mapid)\n\n # Get ecoregions map ID.\n mapid_eco_rgns = ee_smry.ee_create_ecorgns_map()\n # 6\n smrylogger.debug(\"6 land_cover( )|mapid_eco_rgns: %s\", mapid_eco_rgns)\n\n # Create request context from attributes.\n # Mapid and token for base map.\n dct = {\"mapid\": mapid[\"mapid\"], \"token\": mapid[\"token\"]}\n\n # Mapid and token for ecoregions FeatureCollection.\n dct[\"mapid_eco_rgns\"] = mapid_eco_rgns[\"mapid\"]\n dct[\"token_eco_rgns\"] = mapid_eco_rgns[\"token\"]\n\n for key in attr_dct.keys():\n dct[key] = attr_dct[key]\n\n # Set opacity attribute.\n dct[\"opacity\"] = 0.01 * float(dct[\"opacity\"])\n\n dct[\"heading\"] = \"Global MODIS Land Cover\"\n dct[\"form\"] = year_form\n dct[\"form_action\"] = \"smry/land_cover/\"\n dct[\"form_help\"] = year_form.form_help\n # 7\n smrylogger.debug(\"7 land_cover( )|dct: %s\", dct)\n\n # Load the ee map template.\n template = loader.get_template(\"land_cover/ee_map.html\")\n\n # Create context and render.\n context = RequestContext(request, dct)\n response = HttpResponse(template.render(context))\n\n return response\n\ndef cdl(request):\n \"\"\"\n cdl(request)\n \n USDA NASS Cropland Data Layer (CDL)\n \"\"\"\n# smrylogger.debug(\"CDL VIEW\")\n \n # Set attributes.\n attr_dct = site_attr.set_attrs(request, \"nass_cdl\")\n\n # Form with current year.\n year_form = YearForm_CDL(request.POST,\n initial = {\"year\": attr_dct[\"year\"],\n \"opacity\": attr_dct[\"opacity\"],\n \"dscrpt_txt\": attr_dct[\"dscrpt_txt\"]})\n # 1\n# smrylogger.debug(\"1 cdl( )|year_form.initial: %s\", year_form.initial)\n\n if request.method == \"POST\":\n # Create an instance of class YearForm and populate with\n # request data.\n year_form = YearForm_CDL(request.POST)\n\n if year_form.is_valid():\n # Update attributes.\n for key in year_form.cleaned_data.keys():\n attr_dct[key] = year_form.cleaned_data[key]\n\n # Set attributes in session to dictionary items.\n site_attr.set_session_attr(request, attr_dct)\n # 2\n# smrylogger.debug(\"2 cdl( )|attr_dct: %s\", attr_dct)\n# else:\n # 3\n# smrylogger.debug(\"3 cdl( )|Warning: year_form is invalid\")\n\n else:\n # Create an instance of class RegionForm.\n year_form = YearForm_CDL(initial = {\"year\": attr_dct[\"year\"],\n \"opacity\": attr_dct[\"opacity\"],\n \"dscrpt_txt\": attr_dct[\"dscrpt_txt\"]})\n\n # Initialize Earth Engine. The configuration file config.py\n # contains credentials.\n ee.Initialize(config.EE_CREDENTIALS, config.EE_URL)\n \n # Get color palette.\n palette_str = palettes.cdl_palette()\n \n # Derive the image name.\n img_name = \"USDA/NASS/CDL/\" + str(attr_dct[\"year\"])\n # 4\n# smrylogger.debug(\"cdl( )|img_name: %s\", img_name)\n \n # Get map ID.\n img = ee.Image(img_name).select([\"cropland\"])\n mapid = img.getMapId({'min': 0, 'max': 255,\n \"palette\": palette_str})\n # 5\n# smrylogger.debug(\"5 cdl( )|mapid: %s\", mapid)\n\n # Get ecoregions map ID.\n mapid_eco_rgns = ee_smry.ee_create_ecorgns_map()\n # 6\n# smrylogger.debug(\"6 cdl( )|mapid_eco_rgns: %s\", mapid_eco_rgns)\n\n # Create request context from attributes.\n # Mapid and token for base map.\n dct = {\"mapid\": mapid[\"mapid\"], \"token\": mapid[\"token\"]}\n\n # Mapid and token for ecoregions FeatureCollection.\n dct[\"mapid_eco_rgns\"] = mapid_eco_rgns[\"mapid\"]\n dct[\"token_eco_rgns\"] = mapid_eco_rgns[\"token\"]\n\n for key in attr_dct.keys():\n dct[key] = attr_dct[key]\n\n # Set opacity attribute.\n dct[\"opacity\"] = 0.01 * float(dct[\"opacity\"])\n\n dct[\"heading\"] = \"USDA NASS Cropland Data Layer\"\n dct[\"form\"] = year_form\n dct[\"form_action\"] = \"smry/cdl/\"\n dct[\"form_help\"] = year_form.form_help\n # 7\n# smrylogger.debug(\"6 cdl( )|dct: %s\", dct)\n\n # Load the ee map template.\n template = loader.get_template(\"land_cover/ee_map.html\")\n\n # Create context and render.\n context = RequestContext(request, dct)\n response = HttpResponse(template.render(context))\n\n return response\n\ndef nlcd(request):\n \"\"\"\n nlcd(request)\n \n National Land Cover Database (NLCD)\n \"\"\"\n# smrylogger.debug(\"NLCD VIEW\")\n \n # Set attributes.\n attr_dct = site_attr.set_attrs(request, \"nlcd\")\n\n # Form with current year.\n year_form = YearForm_NLCD(request.POST,\n initial = {\"year\": attr_dct[\"year\"],\n \"opacity\": attr_dct[\"opacity\"],\n \"dscrpt_txt\": attr_dct[\"dscrpt_txt\"]})\n # 1\n# smrylogger.debug(\"1 nlcd( )|year_form.initial: %s\", year_form.initial)\n\n if request.method == \"POST\":\n # Create an instance of class YearForm and populate with\n # request data.\n year_form = YearForm_NLCD(request.POST)\n\n if year_form.is_valid():\n # Update attributes.\n for key in year_form.cleaned_data.keys():\n attr_dct[key] = year_form.cleaned_data[key]\n\n # Set attributes in session to dictionary items.\n site_attr.set_session_attr(request, attr_dct)\n # 2\n# smrylogger.debug(\"2 nlcd( )|attr_dct: %s\", attr_dct)\n# else:\n # 3\n# smrylogger.warning(\"nlcd( )|Warning: year_form is invalid\")\n\n else:\n # Create an instance of class RegionForm.\n year_form = YearForm_NLCD(initial = {\"year\": attr_dct[\"year\"],\n \"opacity\": attr_dct[\"opacity\"],\n \"dscrpt_txt\": attr_dct[\"dscrpt_txt\"]})\n\n # Initialize Earth Engine. The configuration file config.py\n # contains credentials.\n ee.Initialize(config.EE_CREDENTIALS, config.EE_URL)\n \n # Get color palette.\n palette_str = palettes.nlcd_palette()\n \n # Derive the image name.\n img_name = \"USGS/NLCD/NLCD\" + str(attr_dct[\"year\"])\n # 4\n# smrylogger.debug(\"4 nlcd( )|img_name: %s\", img_name)\n \n # Get map ID.\n img = ee.Image(img_name).select([\"landcover\"])\n mapid = img.getMapId({'min': 0, 'max': 255,\n \"palette\": palette_str})\n # 5\n# smrylogger.debug(\"5 nlcd( )|mapid: %s\", mapid)\n\n # Get ecoregions map ID.\n mapid_eco_rgns = ee_smry.ee_create_ecorgns_map()\n # 6\n# smrylogger.debug(\"6 nlcd( )|mapid_eco_rgns: %s\", mapid_eco_rgns)\n\n # Create request context from attributes.\n # Mapid and token for base map.\n dct = {\"mapid\": mapid[\"mapid\"], \"token\": mapid[\"token\"]}\n\n # Mapid and token for ecoregions FeatureCollection.\n dct[\"mapid_eco_rgns\"] = mapid_eco_rgns[\"mapid\"]\n dct[\"token_eco_rgns\"] = mapid_eco_rgns[\"token\"]\n\n for key in attr_dct.keys():\n dct[key] = attr_dct[key]\n\n # Set opacity attribute.\n dct[\"opacity\"] = 0.01 * float(dct[\"opacity\"])\n\n dct[\"heading\"] = \"U.S. National Land Cover Database\"\n dct[\"form\"] = year_form\n dct[\"form_action\"] = \"smry/nlcd/\"\n dct[\"form_help\"] = year_form.form_help\n# smrylogger.debug(\"cdl( )|dct: %s\", dct)\n\n # Load the ee map template.\n template = loader.get_template(\"land_cover/ee_map.html\")\n\n # Create context and render.\n context = RequestContext(request, dct)\n response = HttpResponse(template.render(context))\n\n return response\n\ndef ee_create_map():\n \"\"\"\n ee_create_map()\n \n Create a map image on Earth Engine.\n \n ee_create_map() returns the image object.\n \"\"\"\n\n lnd_cvr_img = ee.Image(\"MODIS/051/MCD12Q1/2001_01_01\")\n \n # Select band containing the IGBP classification image.\n # Mask all vallues > 17.\n lnd_cvr_img = lnd_cvr_img.select([\"Land_Cover_Type_1\"])\n lnd_cvr_img = lnd_cvr_img.mask(lnd_cvr_img.lt(18))\n\n# smrylogger.debug(\"ee_create_map( )|lnd_cvr_img: %s\", lnd_cvr_img)\n\n return lnd_cvr_img\n\ndef about(request):\n \"\"\"\n about(request)\n \n About view.\n \"\"\"\n# smrylogger.debug(\"ABOUT VIEW\")\n html = text_items.get_txt_html(\"about\", \"about\") \n# smrylogger.debug(\"html: %s\", html)\n title = \"U.S. Land Cover Indicators\"\n\n about_template = loader.get_template(\"smry/about.html\")\n context = RequestContext(request, {\"title\": title, \"about_text\": html})\n response = HttpResponse(about_template.render(context))\n\n return response\n\ndef fill_attr(src_dct, trg_dct):\n \"\"\"\n fill_attr(src_dct, trg_dct)\n \n Fill attributes in the source dictionary that do not\n appear in the target. Where a key in the source does not\n appear in the target, the source attribute is copied to\n the target.\n \n fill_attr( ) returns the target dictionary object.\n \"\"\"\n # Get dictionary keys.\n src_keys = sorted(src_dct.keys())\n trg_keys = trg_dct.keys()\n \n # Iterate over target keys.\n for key in src_keys:\n if not key in trg_keys:\n trg_dct[key] = src_dct[key]\n \n# smrylogger.debug(\"fill_attr( )|trg_keys: %s\", src_keys) \n# smrylogger.debug(\"fill_attr( )|trg_keys: %s\", sorted(trg_dct.keys()))\n\n return trg_dct\n\ndef create_distr_table_list(region, year):\n \"\"\"\n create_distr_table_list(region, year)\n \n For the specified region and year, Create a table summarizing\n land cover distribution as a list object. Source data are\n contained in a pickle archive.\n \n create_distr_table_list() returns the list object.\n \"\"\"\n\n # Access pickle archive.\n pfile_name = os.path.join(DATA_PATH, \"nca_region_smry.p\")\n distr_dct = get_distr_dct(pfile_name)\n key_1 = distr_dct.keys()[0]\n# smrylogger.debug(\"Distribution Dictionary: %s\", key_1)\n\n\n # Extract legend from Legend objects to lists.\n legend_dct = get_legend_dct()\n\n # Get fraction of total land cover for the specified region and year.\n rgn_abbvr = rgn_to_abbrv[region]\n year_int = int(year)\n prc_lst = distr_dct[rgn_abbvr][year_int][\"prc\"]\n\n # Assemble table elements.\n max_key = 16\n table_list = []\n for key in sorted(legend_dct.keys()):\n if key <= max_key:\n table_list.append((key, legend_dct[key][0], \"%6.3f\" % prc_lst[key]))\n return table_list\n\ndef get_distr_dct(pfile_name):\n \"\"\"\n get_distr_dct(pfile_name):\n \n Get land cover distribution data from the pickle archive with file name\n pfile_name into a dictionary.\n \n get_distr_dct() returns a dictionary object extracted from the pickle\n archive.\n \"\"\"\n pfile_name = os.path.join(DATA_PATH, \"nca_region_smry.p\")\n \n # Access pickle archive.\n try:\n pfile = open(pfile_name, \"rb\")\n distr_dct = pickle.load(pfile)\n except pickle.PickleError:\n msg = \"Error accessing pickle archive.\"\n error.quit_prg(prg, msg)\n \n pfile.close()\n \n return distr_dct\n\ndef get_legend_dct():\n \"\"\"\n get_legend_dct()\n \n Get legend data from Legend objects into a dictionary.\n \"\"\"\n \n # Extract legend from Legend objects to lists.\n legend_objs = Legend.objects.all()\n \n # Iterate over Legend objects to extract data into a\n # dictionary mapping names to keys.\n legend_dct = {}\n for obj in legend_objs:\n legend_dct[obj.key] = [obj.name, obj.short_name]\n \n return legend_dct\n\ndef create_year_list(year, year_min, year_max, incr):\n \"\"\"\n create_year_list(year_min, year_max, incr)\n \"\"\"\n val = year\n val_list = [val]\n for i in range(1, 4):\n if (val + incr) > year_max:\n next = year_min + (val + incr - year_max - 1)\n else:\n next = val + incr\n val = next\n val_list.append(next)\n year_list = []\n for val in sorted(val_list):\n year_list.append(str(val))\n return year_list\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"smry/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":27496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"213375303","text":"import matplotlib\r\nmatplotlib.use('Agg')\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport random\r\n\r\n#randomstring\r\ndef random_string():\r\n str_digits = '0123456789'\r\n str_lowercase= 'abcdefghijklmnopqrstuvwxyz'\r\n str_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\r\n str_all = str_digits + str_lowercase + str_uppercase\r\n string = random.sample(str_all,5)\r\n randomstring = ''.join(string)\r\n return randomstring\r\n\r\nplt.figure(figsize=(24,6))\r\nplt.text(0.3,0.4,random_string(),weight = \"light\",color = 'green',size = 200)\r\nplt.axis('off')\r\nplt.savefig('string.jpg')","sub_path":"string_ima.py","file_name":"string_ima.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"101009926","text":"# Time: O(n)\n# Space: O(1)\n#\n# Say you have an array for which the ith element \n# is the price of a given stock on day i.\n#\n# Design an algorithm to find the maximum profit. \n# You may complete at most two transactions.\n#\n# Note:\n# You may not engage in multiple transactions at the same time \n# (ie, you must sell the stock before you buy again).\n#\n\nclass Solution(object):\n def maxProfit(self, prices):\n if not prices:\n return 0\n\n min_price, max_profit_from_left, max_profits_from_left = prices[0], 0, []\n for price in prices:\n min_price = min(min_price, price)\n max_profit_from_left = max(max_profit_from_left, price - min_price) # 在i卖出\n max_profits_from_left.append(max_profit_from_left) # before i (includes i), doing one max transaction \n \n max_price, max_profit_from_right, max_profits_from_right = prices[-1], 0, []\n for i in reversed(range(len(prices))):\n max_price = max(max_price, prices[i]) # need to keep max instead\n max_profit_from_right = max(max_profit_from_right, max_price - prices[i]) # 在i买入,之后卖掉\n max_profits_from_right.insert(0, max_profit_from_right) # after i (includes i), doing one max transaction\n \n max_profit = 0\n for i in range(len(prices)):\n max_profit = max(max_profit, max_profits_from_left[i] + max_profits_from_right[i])\n \n return max_profit\n \n # https://github.com/kamyu104/LeetCode/blob/master/Python/best-time-to-buy-and-sell-stock-iii.py\n # http://www.cnblogs.com/zuoyuan/p/3766168.html\n # 就像(1)的问题!!只是拆成两部分\n # 只允许做两次交易,这道题就比前两道要难多了。解法很巧妙,有点动态规划的意思:开辟两个数组f1和f2,f1[i]表示在price[i]之前进行一次交易所获得的最大利润,f2[i]表示在price[i]之后进行一次交易所获得的最大利润。 \n # 则f1[i]+f2[i]的最大值就是所要求的最大值,而f1[i]和f2[i]的计算就需要动态规划了\n","sub_path":"best-time-to-buy-and-sell-stock-iii-(H)-(123).py","file_name":"best-time-to-buy-and-sell-stock-iii-(H)-(123).py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"386119985","text":"# -*- coding:utf-8 -*- \n'''\n@Author: 三个橘子\n@Email : ipapu@qq.com\n'''\nfrom threading import Thread,Condition,currentThread\nimport time\n\nclass Goods:\n '''产品'''\n def __init__(self):\n self.count=0\n def produce(self,num=1):\n self.count+=num\n def consume(self):\n if self.count:\n self.count-=1\n def isEmpty(self):\n return not self.count\n\nclass Producer(Thread):\n '''生产者'''\n def __init__(self,condition,goods):\n Thread.__init__(self)\n self.cond=condition\n self.goods=goods\n def run(self):\n cond=self.cond\n goods=self.goods\n while 1:\n cond.acquire()\n goods.produce()\n print('Goods Count:',goods.count,'Producer thread produced')\n cond.notifyAll()\n cond.release()\n time.sleep(2)\n\nclass Consumer(Thread):\n '''消费者'''\n def __init__(self,index,condition,goods):\n Thread.__init__(self,name=str(index))\n self.cond=condition\n self.goods=goods\n def run(self):\n cond=self.cond\n goods=self.goods\n while 1:\n time.sleep(1)\n cond.acquire()\n while goods.isEmpty():\n cond.wait()\n goods.consume()\n print('Goods Count:',goods.count,'Consumer thread',currentThread().getName(),'consumed')\n cond.release()\n\ngoods=Goods()\ncond=Condition()\n\nproducer=Producer(cond,goods)\nproducer.start()\n# producer.join()\nfor i in range(5):\n consumer=Consumer(i,cond,goods)\n consumer.start()\n consumer.join()","sub_path":"abs/python/thread/producer_consumer_1.py","file_name":"producer_consumer_1.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"524450100","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 5 13:58:17 2020\n\nCode to run a stacked cross correlation on J and K month lightcurves\n\n@author: ppxee\n\"\"\"\n\nimport time\nstart = time.time()\nprint(start)\n\n### Import required libraries ###\nimport matplotlib.pyplot as plt #for plotting\nfrom astropy.io import fits #for handling fits\nfrom astropy.table import Table #for handling tables\nimport numpy as np #for handling arrays\n#import math\n#from astropy.stats import median_absolute_deviation\nimport vari_funcs #my module to help run code neatly\nfrom astropy.cosmology import FlatLambdaCDM\nfrom astropy import units as u\nplt.close('all') #close any open plots\n#from numpy.lib.recfunctions import append_fields\n\n#%% Open the fits files and get data ###\n### Import data for variables selected in K ###\nvarydata = Table.read('variable_tables/J_and_K_variables_month_varystats_DR11data.fits')\n#mask = np.nanmean(varydata['Month_Flux_K'], axis=1) > 1e4\nmask = varydata['Chi_K'] > 100\nvarydata = varydata[mask]\nxvarydata = varydata[varydata['X-ray']==True]\nnoxvarydata = varydata[varydata['X-ray']==False]\n\n\n#%% Get lightcurves with errors ###\ndef getdata(data):\n j_flux = data['Month_Flux_J']\n j_fluxerr = data['Month_Fluxerr_J']\n k_flux = data['Month_Flux_K']\n k_fluxerr = data['Month_Fluxerr_K']\n \n return j_flux, j_fluxerr, k_flux, k_fluxerr\n\nj_flux, j_fluxerr, k_flux, k_fluxerr = getdata(varydata)\nx_j_flux, x_j_fluxerr, x_k_flux, x_k_fluxerr = getdata(xvarydata)\nnox_j_flux, nox_j_fluxerr, nox_k_flux, nox_k_fluxerr = getdata(noxvarydata)\n\nmask = np.nanmean(k_flux, axis=1) > 1e4\n#mask = varydata['z'] > 1.5\nhigh_j_flux = j_flux[mask]\nhigh_k_flux = k_flux[mask]\nlow_j_flux = j_flux[~mask]\nlow_k_flux = k_flux[~mask]\nhigh_j_fluxerr = j_fluxerr[mask]\nhigh_k_fluxerr = k_fluxerr[mask]\nlow_j_fluxerr = j_fluxerr[~mask]\nlow_k_fluxerr = k_fluxerr[~mask]\n\n#%% Mean subract and normalise ###\n#\n#test_j_flux = vari_funcs.cross_correlation.mean_subtract_normalise(x_j_flux)\n#test_k_flux = vari_funcs.cross_correlation.mean_subtract_normalise(x_k_flux)\n\ntest_j_flux = vari_funcs.cross_correlation.weighted_mean_subtract_normalise(x_j_flux, \n x_j_fluxerr)\ntest_k_flux = vari_funcs.cross_correlation.weighted_mean_subtract_normalise(x_k_flux, \n x_k_fluxerr)\n#%% Create correlation arrays ###\n''' Need arrays that have a space for every possible month so that the values \ncan be separated by the correct time periods'''\n\n### Get monthly_numbers as this contains all possible months ###\nmonth_info = fits.open('Images/Convolving_Images/monthly_numbers.fits')[1].data #get month count data\nfull_months = month_info['Month'] #extract month nanes\n\n### Create J and K month arrays so can match where the data should go ###\nkmonths = ['sep05','oct05','nov05','dec05', 'jan06', #'dec06', \n 'jan07', 'aug07', 'sep07', 'oct07', 'sep08', 'oct08', 'nov08', \n 'jul09', 'aug09', 'sep09', 'oct09', 'nov09', 'dec09', 'jan10', \n 'feb10', 'aug10', 'sep10', 'oct10', 'nov10', 'dec10', 'jan11', #'feb11', \n 'aug11', 'sep11', 'oct11', 'nov11', 'dec11', 'jan12', 'feb12', \n 'jul12', 'aug12', 'sep12', 'oct12', 'nov12']\nkmask = np.isin(full_months, kmonths)\n\njmonths = ['sep05', 'oct05', 'nov05', 'dec05', 'jan06', 'oct06', 'nov06',\n 'dec06', 'aug07', 'sep07', 'oct07', 'oct08', 'nov08', 'aug09',\n 'sep09', 'oct09', 'nov09', 'dec09', 'aug10', 'sep10', 'oct10',\n 'nov10', 'dec10', 'jan11', 'aug11', 'sep11', 'oct11', 'nov11',\n 'dec11', 'jan12', 'jul12', 'aug12', 'sep12', 'oct12', 'nov12']\njmask = np.isin(full_months, jmonths)\n\n### Assign new arrays ###\ncorr_test_j_flux = vari_funcs.cross_correlation.make_corr_arrays(test_j_flux, \n jmask, \n full_months)\ncorr_test_k_flux = vari_funcs.cross_correlation.make_corr_arrays(test_k_flux, \n kmask, \n full_months)\n\n \ntau_arr = np.arange(-50,50)\n#tau_arr = np.arange(-90,90)\n\nout = np.array([vari_funcs.cross_correlation.cross_correlate(corr_test_k_flux, \n corr_test_j_flux, \n tau) for tau in tau_arr])\n\nccf = out[:,0]\nccf_err = out[:,1]\nnum_pairs = out[:,2]\n\nplt.figure()\n#plt.subplot(211)\n#plt.plot(tau_arr, ccf,'o')\nplt.errorbar(tau_arr, ccf, yerr=ccf_err, fmt='o')\nplt.xlabel('Lag (months)')\nplt.ylabel('Cross-Correlation Function')\nplt.grid(True)\nplt.tight_layout()\n\n \n#plt.subplot(212)\nplt.figure()\nplt.plot(tau_arr, num_pairs,'o')\nplt.xlabel('Lag (months)')\nplt.ylabel('Pairs per Light Curve')\nplt.tight_layout()\n\n#%% Test how average lag changes with CCF Value ###\n#round_ccf = np.round(ccf, decimals=4)\n#test_values = np.arange(-0.008, 0.009,0.0001)\n#test_values = np.round(test_values, decimals=4)\nround_ccf = np.round(ccf, decimals=3)\ntest_values = np.arange(-0.008, 0.009,0.001)\ntest_values = np.round(test_values, decimals=3)\nmean_tau = np.array([])\nfor val in test_values:\n ### Find places where ccf rounds to the test value ###\n mask = np.isin(round_ccf, val)\n \n ### Find Tau at these and average to find centre of the peak at that ccf value ###\n taus = tau_arr[mask]\n print(len(taus))\n if len(taus) <= 1:\n mean_tau = np.append(mean_tau, np.nan)\n else:\n mean_tau = np.append(mean_tau, np.nanmean(taus))\n\nplt.figure()\nplt.plot(tau_arr, round_ccf,'o')\nplt.xlabel('Mean lag (months)')\nplt.ylabel('Rounded CCF Value')\nplt.grid(True)\n\n#plt.figure()\nplt.plot(mean_tau, test_values,'o')\n#plt.xlabel('Mean lag (months)')\n#plt.ylabel('CCF Value')\n##plt.grid(True)\n \n#%% Test shifting some of the lightcurves artifically ###\n#mask = [10,20,30,40,50,60,70]\nimport random\ndef make_shifted_data(corr_test_k_flux, lag, percentage):\n ### Use percentage to calculate the number of lightcurves to shift ###\n length = len(corr_test_k_flux)\n no_steps = int(length*percentage/100) # number of lcs to shift based on %\n mask = random.sample(range(0, length), no_steps)\n shift = np.arange(0,lag,1, dtype=int)\n ### Make test array for J out of K ###\n nanarr = np.empty([len(mask),lag])#, dtype=int)\n nanarr[:,:] = np.nan\n corr_test_j_flux_new = np.copy(corr_test_k_flux)\n corr_test_j_flux_moved = np.delete(corr_test_j_flux_new[mask,:], shift, axis=1)\n corr_test_j_flux_moved = np.append(corr_test_j_flux_moved, nanarr, axis=1)\n \n corr_test_j_flux_new[mask,:] = corr_test_j_flux_moved\n return corr_test_j_flux_new\n\nplt.figure(figsize=[10,10])\n#plt.plot(full_months, corr_test_k_flux[0,:],'o')\n#plt.plot(full_months, corr_test_j_flux[0,:],'o')\n#for lag in [10]:#[0,5,10,15,20,25,30,35,40,45]:\n# corr_test_j_flux_new = make_shifted_data(corr_test_k_flux, lag=lag, percentage=100)\n# \n# test_out = np.array([\n# vari_funcs.cross_correlation.cross_correlate_shifted(corr_test_k_flux,\n# corr_test_j_flux_new, \n# tau) for tau in tau_arr])\n# \n# test_ccf = test_out[:,0]\n# test_ccf_err = test_out[:,1]\n# test_num_pairs = test_out[:,2]\n# \n# plt.plot(tau_arr, test_ccf,'-', label='20% with lag = '+str(lag)+' months')\n#\n## plt.errorbar(tau_arr, test_ccf,yerr=ccf_err, fmt='-', label='20% with lag = '+str(lag)+' months')\n#\n##plt.figure()\n##plt.subplot(211)\n#plt.plot(tau_arr, ccf,'o', label='Real data')\n##plt.figure()\n##plt.subplot(211)\n##plt.plot(tau_arr, test_ccf,'o')\n#plt.xlabel('Lag (months)')\n#plt.ylabel('Cross-Correlation Function')\n#plt.grid(True)\n#plt.legend()\n#plt.tight_layout()\n\nplt.figure(figsize=[10,10])\nplt.errorbar(tau_arr, ccf, yerr=ccf_err, fmt='o', label='Real data')\nfor percent in [5]:#[5,10,15,20,25,30,35,40,45]:\n corr_test_j_flux_new = make_shifted_data(corr_test_k_flux, lag=10, percentage=percent)\n\n test_out = np.array([\n vari_funcs.cross_correlation.cross_correlate_shifted(corr_test_k_flux,\n corr_test_j_flux_new, \n tau) for tau in tau_arr]) \n test_ccf = test_out[:,0]\n test_num_pairs = test_out[:,1]\n \n plt.plot(tau_arr, test_ccf, 'o', label=str(percent)+'% with lag = 10 months')\n# plt.errorbar(tau_arr, test_ccf,yerr=ccf_err, fmt='-', \n# label=str(percent)+'% with lag = 10 months')\n\n#plt.figure()\n#plt.subplot(211)\n#plt.figure()\n#plt.subplot(211)\n#plt.plot(tau_arr, test_ccf,'o')\nplt.xlabel('Lag (months)')\nplt.ylabel('Cross-Correlation Function')\nplt.grid(True)\nplt.legend()\nplt.tight_layout()\n##plt.subplot(212)\n#plt.figure()\n#plt.plot(tau_arr, test_num_pairs,'o')\n#plt.xlabel('Lag (months)')\n#plt.ylabel('Pairs per Light Curve')\n#plt.tight_layout()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"cross_correlation_month_tests.py","file_name":"cross_correlation_month_tests.py","file_ext":"py","file_size_in_byte":9168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"649410506","text":"import re\nimport sys\n\n# check instance name is valid\n\ninstance_name = \"{{ cookiecutter.tm1_instance_name}}\"\nregex = r\"^[a-zA-Z0-9][_a-zA-Z0-9]+$\"\n\nif not re.match(regex, instance_name):\n print(\"ERROR: %s is not a valid instance name\" % instance_name)\n sys.exit(1)\n\n# check admin host name is valid\n\nadmin_host = \"{{ cookiecutter.tm1_admin_host}}\"\nregex = r\"^[a-zA-Z0-9][.a-zA-Z0-9]+$\"\n\nif not re.match(regex, admin_host):\n print(\"ERROR: %s is not a valid admin host\" % admin_host)\n sys.exit(1)\n\n# check valid input for any T/F parameters\n\npersistent_feeders = \"{{ cookiecutter.tm1_use_persistent_feeders}}\"\nti_debugging = \"{{ cookiecutter.tm1_use_ti_debugging}}\"\nseparate_n_and_c = \"{{ cookiecutter.tm1_use_separate_n_and_c}}\"\n\nregex = r\"^[tTfF]$\"\n\nif not re.match(regex, persistent_feeders):\n print(\"ERROR: %s please enter a value of T or F\" % persistent_feeders)\n sys.exit(1)\n\nif not re.match(regex, persistent_feeders):\n print(\"ERROR: %s please enter a value of T or F\" % ti_debugging)\n sys.exit(1)\n\nif not re.match(regex, persistent_feeders):\n print(\"ERROR: %s please enter a value of T or F\" % separate_n_and_c)\n sys.exit(1)\n\n# check ports provided are sensible\n\nserver_port = \"{{ cookiecutter.tm1_server_port}}\"\nrest_api_port = \"{{ cookiecutter.tm1_rest_api_port}}\"\n\nregex = r\"^[0-9]+$\"\n\nif not re.match(regex, server_port):\n print(\"ERROR: %s is not a valid server port\" % server_port)\n sys.exit(1)\n\nif not re.match(regex, rest_api_port):\n print(\"ERROR: %s is not a valid server port\" % rest_api_port)\n sys.exit(1)\n\nserver_port_number = {{cookiecutter.tm1_server_port}}\nrest_api_port_number = {{cookiecutter.tm1_rest_api_port}}\n\nif not (server_port_number > 1023 and server_port_number <= 65535):\n print(\n \"ERROR: %s is not within the acceptable range for the server port number. Try something > 1023 <= 65535)\"\n % server_port_number\n )\n sys.exit(1)\n\nif not (rest_api_port_number > 1023 and rest_api_port_number <= 65535):\n print(\n \"ERROR: %s is not within the acceptable range for the rest api port number. Try something > 1023 <= 65535)\"\n % rest_api_port_number\n )\n sys.exit(1)\n","sub_path":"hooks/pre_gen_project.py","file_name":"pre_gen_project.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"280542855","text":"# -*- coding: utf-8 -*-\n\nimport time\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import NoAlertPresentException\nfrom selenium.webdriver.common.by import By\n\n\nclass ArchiveHelper:\n\n def __init__(self, app):\n self.app = app\n\n def open_archive_page(self, archive):\n wd = self.app.wd\n time.sleep(1)\n wd.get(archive.archive_page)\n\n def check_data(self):\n wd = self.app.wd\n for i in range(5):\n try:\n if self.is_element_present(By.CSS_SELECTOR, \"div.data\"): break\n except:\n pass\n time.sleep(1)\n else:\n wd.fail(\"time out\")\n\n def is_element_present(self, how, what):\n wd = self.app.wd\n try:\n wd.find_element(by=how, value=what)\n except NoSuchElementException as e:\n return False\n return True\n\n def is_alert_present(self):\n wd = self.app.wd\n try:\n wd.switch_to_alert()\n except NoAlertPresentException as e:\n return False\n return True\n\n def close_alert_and_get_its_text(self):\n wd = self.app.wd\n try:\n alert = wd.switch_to_alert()\n alert_text = alert.text\n if wd.accept_next_alert:\n alert.accept()\n else:\n alert.dismiss()\n return alert_text\n finally:\n wd.accept_next_alert = True\n","sub_path":"fixture/archive.py","file_name":"archive.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"280196815","text":"\nimport keras\nimport numpy as np\n\n#General Variables\nbatch_size = 128\nepochs = 15\nnum_classes = 2\nimg_rows, img_cols = 160, 64\n\n#Load Data\nx_train = np.load('P300 Data/a_signal_train.npy')\nx_test = np.load('P300 Data/a_signal_test.npy')\ny_train = np.load('P300 Data/a_type_train.npy').astype(int)\ny_test = np.load('P300 Data/a_type_test.npy').astype(int)\na_code_test = np.load('P300 Data/a_code_test.npy').astype(int)\n\np300 = keras.models.load_model('Models/Base_Model.h5')\n\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\np300.fit(x_train, y_train, validation_split = 0.02941176, epochs = epochs, verbose = 1)\n\n\nscore = p300.evaluate(x_test, y_test, verbose = 1)\nprint(\"\\nTest Set Validation Results-> %s: %.2f%%\" % (p300.metrics_names[1], score[1]*100) ,\"%s: %.2f%%\" % (p300.metrics_names[0], score[0]*100) )\n\n#save the model\nkeras.models.save_model(\n model = p300,\n filepath = 'Models/Subject_A_CNN.h5',\n overwrite = True,\n include_optimizer=True\n)\n","sub_path":"P300 Speller Using CNN/Subject_A_CNN.py","file_name":"Subject_A_CNN.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"223274645","text":"from data_understanding import descriptions\nimport string\n\n# print(descriptions['1000268201_693b08cb0e'])\n#--------------------------------------------------------------------------------------------------------------\n#removing punctuation and lowercase the letter\n\ntable = str.maketrans('', '', string.punctuation)\nfor key, desc_list in descriptions.items():\n\t\tfor i in range(len(desc_list)):\n\t\t\tdesc = desc_list[i]\n\t\t\t# tokenize\n\t\t\tdesc = desc.split()\n\t\t\t# convert to lower case\n\t\t\tdesc = [word.lower() for word in desc]\n\t\t\t# remove punctuation from each token\n\t\t\tdesc = [w.translate(table) for w in desc]\n\t\t\t# remove hanging 's' and 'a'\n\t\t\tdesc = [word for word in desc if len(word)>1]\n\t\t\t# remove tokens with numbers in them\n\t\t\tdesc = [word for word in desc if word.isalpha()]\n\t\t\t# store as string\n\t\t\tdesc_list[i] = ' '.join(desc)\n\n#print(descriptions['1000268201_693b08cb0e'])\n#--------------------------------------------------------------------------------------------------------------\n\n# save descriptions to file, one per line\n\ndef save_descriptions(descriptions, filename):\n\tlines = list()\n\tfor key, desc_list in descriptions.items():\n\t\tfor desc in desc_list:\n\t\t\tlines.append(key + ' ' + desc)\n\tdata = '\\n'.join(lines)\n\tfile = open(filename, 'w')\n\tfile.write(data)\n\tfile.close()\n\nsave_descriptions(descriptions, 'descriptions.txt')\n\n#-------------------------------------------------------------------------------------------------------------\n\n\n#All the unique words present in the description\n\nall_desc = set()\nfor key in descriptions.keys():\n\t[all_desc.update(d.split()) for d in descriptions[key]]\n\nvocabulary=all_desc\t\t\n\n#print('Original Vocabulary Size: %d' % len(vocabulary))-->8763\n\n#-------------------------------------------------------------------------------------------------------------\n","sub_path":"data_cleaning.py","file_name":"data_cleaning.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"311043610","text":"numbers = [5, 0, 2, 7]\r\nresult = [2, 3, 4, 5, 6, 7]\r\n\r\nsums = []\r\n\r\nfor i in range(len(numbers)-1):\r\n for j in range(i+1, len(numbers)):\r\n element = numbers[i] + numbers[j]\r\n sums.append(element)\r\n print(sums)\r\n\r\n\r\nprint(sorted(set(sums)))\r\n","sub_path":"python_programmers/Lv1/두 개 뽑아서 더하기.py","file_name":"두 개 뽑아서 더하기.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"584271497","text":"from lxml.html import fromstring\nfrom logger import logger as logging\nfrom lxml import etree\nfrom utils.talks import Talk\nimport re\nimport time\n\n\ndef get_content(self, li):\n '''\n get the content of one log\n need to judge where the log is complete\n @param li: lxml li dom\n @return type str: html code of log content\n '''\n complete_div = li.xpath('.//div[@class=\"f-info qz_info_complete\"]')\n if len(complete_div) > 0:\n div = complete_div[0]\n else:\n div = li.xpath('.//div[@class=\"f-info\"]')[0]\n return etree.tostring(div, encoding=\"utf-8\", method=\"html\").decode(\"utf-8\")\n\ndef parse_one_log(self, li):\n '''\n extract info from one log\n @param li: lxml dom node\n @return one Log object\n '''\n logging.info(\"start parse one log\")\n li_id = li.xpath(\".//@id\")[0]\n time_string = re.findall(\"\\w+_\\d+_\\d+_\\d+_(\\d+)_\\d_\\d\", li_id)[0]\n pub_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(int(time_string)))\n name = li.xpath(\".//div[@class='user-info']//a//text()\")[0]\n img_src = li.xpath(\".//div[@class='user-pto']//img//@src\")[0]\n user_href = li.xpath(\".//div[@class='user-pto']//a//@href\")[0]\n info_html = self.get_content(li)\n # \n images = li.xpath(\".//a[@class='img-item ']//img//@src\")\n big_images = li.xpath(\".//a[@class='img-item ']//@href\")\n # import pdb; pdb.set_trace()\n \n # make up\n talk = Talk()\n talk.name = name\n talk.author = user_href\n talk.content = info_html\n talk.images = images\n talk.time = pub_time\n talk.li_id = li_id\n talk.big_images = big_images \n talk.insert(self.db_conn.cursor())\n self.db_conn.commit()\n # #\n\n\ndef parse_ul(self, ul):\n '''\n parse lxml ul dom contains a list of log\n '''\n lis = ul.xpath(\".//li[@class='f-single f-s-s']\") \n for li in lis:\n self.parse_one_log(li)\n\ndef parse(self, html):\n logging.info(\"start find and parse log list\")\n doc = fromstring(html)\n ul = doc.xpath(\"//ul[@id='feed_friend_list']\")[0]\n # choose by class to remove ad\n lis = ul.xpath(\".//li[@class='f-single f-s-s']\") \n for li in lis:\n self.parse_one_log(li)\n self.page_down()\n ul = self.get_new_ul()\n self.parse_ul(ul)\n\ndef page_down(self):\n ''' \n page down to get old log\n '''\n js = \"var q=document.documentElement.scrollTop=100000\" \n self.browser.execute_script(js)\n # wait for data to load\n time.sleep(3)\n expand_as = self.browser.find_elements_by_xpath('//a[@data-cmd=\"qz_toggle\"]') \n for a in expand_as:\n a.click()\n time.sleep(3)\n self.EXTRA_CURR_PAGE += 1\n\ndef get_new_ul(self):\n '''\n after page down get the ul\n '''\n curr_page_source = self.browser.page_source\n root = fromstring(curr_page_source)\n ul = root.xpath('//ul[@data-page=\"%s\"]' % self.EXTRA_CURR_PAGE)[0]\n return ul\n","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"600695185","text":"import os\nimport sys\nfileDir = os.path.dirname(os.path.realpath(__file__))\nsys.path.append(os.path.join(fileDir, \"..\", \"..\"))\n\n\nimport argparse\nimport cv2\nimport imagehash\nimport json\nfrom PIL import Image\nfrom PIL import ImageFilter\nimport numpy as np\nimport StringIO\nimport urllib\nimport base64\n\nfrom sklearn.decomposition import PCA\nfrom sklearn.grid_search import GridSearchCV\nfrom sklearn.manifold import TSNE\nfrom sklearn.svm import SVC\nfrom sklearn.externals import joblib\n\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport openface\n\n\nclass Face:\n\n def __init__(self, rep, identity, phash):\n self.rep = rep\n self.identity = identity\n self.phash = phash\n\n def __repr__(self):\n return \"{{id: {}, rep[0:5]: {}, phash: {}}}\".format(\n str(self.identity),\n self.rep[0:5],\n self.phash\n )\n\n\nclass FaceApi:\n def __init__(self,res):\n self.res = res\n self.images = {}\n self.people = []\n self.svm = None\n self.modelDir = os.path.join(fileDir, 'models')\n self.dlibModelDir = os.path.join(self.modelDir, 'dlib')\n self.openfaceModelDir = os.path.join(self.modelDir, 'openface')\n self.align = openface.AlignDlib(os.path.join(self.dlibModelDir, \"shape_predictor_68_face_landmarks.dat\"))\n self.net = openface.TorchNeuralNet(os.path.join(self.openfaceModelDir, 'nn4.small2.v1.t7'), imgDim=96, cuda='')\n self.count = 1\n self.imgDim = 96\n def increace(self):\n self.count += 1\n def processImg(self,imgData,identity,isStram,isBase64,res):\n #train\n res = res if res is not None else self.res\n if isStram:\n imgF = StringIO.StringIO()\n imgF.write(imgData)\n imgF.seek(0)\n img = Image.open(imgF)\n elif isBase64:\n imgF = StringIO.StringIO()\n imgF.write(base64.b64decode(imgData))\n imgF.seek(0)\n img = Image.open(imgF)\n else:\n img = imgData\n buf = np.fliplr(np.asarray(img))\n #rgbFrame is bit map for every single px\n rgbFrame = np.zeros(res, dtype=np.uint8)\n rgbFrame[:, :, 0] = buf[:, :, 2]\n rgbFrame[:, :, 1] = buf[:, :, 1]\n rgbFrame[:, :, 2] = buf[:, :, 0]\n # bbs = align.getAllFaceBoundingBoxes(rgbFrame)\n bb = self.align.getLargestFaceBoundingBox(rgbFrame)\n bbs = [bb] if bb is not None else []\n for bb in bbs:\n # print(len(bbs))\n landmarks = self.align.findLandmarks(rgbFrame, bb)\n #alignedFace aligned picture (still bit map)\n alignedFace = self.align.align(self.imgDim, rgbFrame, bb,\n landmarks=landmarks,\n landmarkIndices=openface.AlignDlib.OUTER_EYES_AND_NOSE)\n if alignedFace is None:\n continue\n phash = str(imagehash.phash(Image.fromarray(alignedFace)))\n #tasete face\n rep = self.net.forward(alignedFace)\n self.images[phash] = Face(rep, identity,phash)\n return Face(rep,identity,phash)\n #\n #save\n #self.images[phash] = Face(rep, identity)\n #self.people.append(name)\n def trainSVMwithData(self,images):\n # Face.rep -> rep\n # Face.identity -> identity\n # Face.phash -> id\n X = []\n y = []\n for img in images:\n X.append(img.rep)\n y.append(img.identity)\n X = np.vstack(X)\n y = np.array(y)\n param_grid = [\n {'C': [1, 10, 100, 1000],\n 'kernel': ['linear']},\n {'C': [1, 10, 100, 1000],\n 'gamma': [0.001, 0.0001],\n 'kernel': ['rbf']}\n ]\n # svm = self.svm if self.svm is not None else GridSearchCV(SVC(C=1), param_grid, cv=5)\n self.svm = GridSearchCV(SVC(C=1), param_grid, cv=5).fit(X, y)\n\n def findIdentity(self, imgData,isStram,isBase64,res):\n res = res if res is not None else self.res\n if isStram:\n imgF = StringIO.StringIO()\n imgF.write(imgData)\n imgF.seek(0)\n img = Image.open(imgF)\n elif isBase64:\n imgF = StringIO.StringIO()\n imgF.write(base64.b64decode(imgData))\n imgF.seek(0)\n img = Image.open(imgF)\n else:\n img = imgData\n buf = np.fliplr(np.asarray(img))\n rgbFrame = np.zeros(res, dtype=np.uint8)\n rgbFrame[:, :, 0] = buf[:, :, 2]\n rgbFrame[:, :, 1] = buf[:, :, 1]\n rgbFrame[:, :, 2] = buf[:, :, 0]\n annotatedFrame = np.copy(buf)\n identities = []\n # bbs = align.getAllFaceBoundingBoxes(rgbFrame)\n bb = self.align.getLargestFaceBoundingBox(rgbFrame)\n bbs = [bb] if bb is not None else []\n for bb in bbs:\n # print(len(bbs))\n landmarks = self.align.findLandmarks(rgbFrame, bb)\n alignedFace = self.align.align(self.imgDim, rgbFrame, bb,\n landmarks=landmarks,\n landmarkIndices=openface.AlignDlib.OUTER_EYES_AND_NOSE)\n if alignedFace is None:\n continue\n\n phash = str(imagehash.phash(Image.fromarray(alignedFace)))\n # search db to get id\n if phash in self.images:\n identity = self.images[phash].identity\n else:\n rep = self.net.forward(alignedFace)\n if self.svm:\n #pridict id\n identity = self.svm.predict(rep)[0]\n else:\n identity = -1\n if identity not in identities:\n identities.append(identity)\n return identities\n\n def saveSvmToFile(self,filePathAndName):\n joblib.dump(self.svm, filePathAndName)\n\n def loadSvmFromFile(self,filePathAndName):\n self.svm = joblib.load(filePathAndName)\n","sub_path":"snippets/faceapi.py","file_name":"faceapi.py","file_ext":"py","file_size_in_byte":6067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"489237405","text":"import warnings\nimport operator\n\nimport numpy as np\nimport scipy.constants as constant\n\nclass ChangePoint:\n def __init__(self, threshold, categories=2):\n self.threshold = threshold\n self.categories = categories\n\n def change(self, duration, before, after):\n raise NotImplementedError()\n \n def classify(self, duration, before, after):\n '''\n duration: minutes\n before, after: miles per hour\n '''\n if self.threshold < 0:\n args = [ before, after ]\n f = operator.le\n else:\n args = [ after, before ]\n f = operator.gt\n diff = self.change(duration, *args)\n\n return f(diff, self.threshold)\n\nclass Acceleration(ChangePoint):\n def change(self, duration, before, after):\n meters = (after - before) * constant.mile # miles to meters\n seconds = duration * constant.minute # minutes to seconds\n acceleration = meters / constant.hour / seconds\n \n return acceleration / constant.g\n\n # def compare(measurement, threshold, direction):\n # allowable = measurement <= threshold\n \n # return allowable if direction else not allowable\n\n\nclass Percentage(ChangePoint):\n def change(self, duration, before, after):\n return (after - before) / before\n\nclass Derivative(ChangePoint):\n def __init__(self, threshold, categories=2, order=1):\n super().__init__(threshold, categories)\n self.order = order\n\n def change(self, duration, before, after):\n rate = constant.mile / constant.hour\n x = (0, before * rate)\n y = (duration, after * rate)\n\n with warnings.catch_warnings():\n warnings.filterwarnings('error')\n try:\n (slope, *_) = np.polyfit(x, y, self.order)\n except (RuntimeWarning, numpy.RankWarning) as error:\n raise ValueError()\n\n return slope\n \ndef bucket(tstamp):\n assert(tstamp.second == 0)\n return tstamp.hour * 60 + tstamp.minute\n\ndef aoc(distribution):\n keys = len(distribution.keys())\n assert(keys > 0)\n area = [ sum(i) for i in distribution.values() ]\n \n return sum(area) / keys\n","sub_path":"lib/cpoint.py","file_name":"cpoint.py","file_ext":"py","file_size_in_byte":2198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"580171796","text":"list1 = ['S1','s2','s3']\nlist2 = ['aswin','adhi','aanya']\nlist3 = [85,98,100]\nl = len(list1)\nl2 = len(list3)\n\nmy_dict = {}\nmy_dict2 = {}\n\nfor i in range(l):\n\tk = list2[i]\n\tv = list3[i]\n\tmy_dict.update({k:v})\n\n\tfor j in range(l2):\n\t\tk = list1[i]\n\t\tmy_dict2.update({k:my_dict})\n\nprint(my_dict2)\n\n\n","sub_path":"dict_test.py","file_name":"dict_test.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"184175169","text":"\"\"\"Usage:\n X.py < X.in > X.out\n\"\"\"\n\ndef setup(infile):\n #C = {}\n return locals()\n\ndef reader(testcase, infile, **ignore):\n #N = int(infile.next())\n P = map(int, infile.next().split())\n I = map(int, infile.next().split())\n #T = infile.next().split()\n #S = [infile.next().strip() for i in range(N)]\n return locals()\n\ndef solver(testcase, N=None, P=None, I=None, T=None, S=None, C=None, **ignore):\n #import collections as co\n #import functools as ft\n #import itertools as it\n #import operator as op\n #import math as ma\n #import re\n import numpy as np\n #import scipy as sp\n #import networkx as nx\n \n\n e, R, N = P\n I = np.array(I)\n E = np.array([0]*len(I))\n E[0] = e\n\n nexts = reversed(I.argsort())\n res = 0\n for current in nexts:\n e_next = R\n for nex in xrange(current+1, len(E)):\n ediff = R*(nex-current-1)\n if ediff>=e:\n break\n if E[nex] > 0:\n e_next = max(R, E[nex] - ediff)\n break\n\n if current+1 < len(E) and E[current+1] == 0:\n E[current+1] = e_next\n\n if E[current] == 0:\n for prev in xrange(current-1, -1, -1):\n ediff = R*(current-prev)\n if E[prev] > 0 or ediff >= e:\n E[current] = min(e, E[prev] + ediff)\n break\n\n res += (E[current]+R-e_next) * I[current]\n\n return 'Case #%s: %s\\n' % (testcase, res)\n\nif __name__ == '__main__':\n import sys\n T = int(sys.stdin.next())\n common = setup(sys.stdin)\n for t in xrange(1, T+1):\n sys.stdout.write(solver(**reader(t, **common)))\n","sub_path":"solutions_2645486_1/Python/alexamici/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"54913313","text":"import torch.optim\n\nfrom . import FairseqOptimizer, register_optimizer\n\nimport math\n\nimport sys\n\nsys.path.append('..')\nsys.path.append('..')\nsys.path.append('..')\nfrom optims import nosadashift\n\n\n@register_optimizer('nosadashift')\nclass FairseqNosAdaShift(FairseqOptimizer):\n def __init__(self, args, params):\n super().__init__(args, params)\n self._optimizer = nosadashift.NosAdaShift(params, **self.optimizer_config)\n\n @staticmethod\n def add_args(parser):\n \"\"\"Add optimizer-specific arguments to the parser.\"\"\"\n # fmt: off\n parser.add_argument('--nosadashift-betas', default='(0.9, 0.999)', metavar='B',\n help='betas for Adam optimizer')\n parser.add_argument('--nosadashift-eps', type=float, default=1e-8, metavar='D',\n help='epsilon for Adam optimizer')\n parser.add_argument('--nosadashift-gamma',type=float,default=0,metavar='D',\n help='gamma for NosAdam optimizer')\n parser.add_argument('--nosadashift-keep_num', type=float, default=10, metavar='D',\n help=' keep_num for adaShift optimizer')\n parser.add_argument('--weight-decay', '--wd', default=0.0, type=float, metavar='WD',\n help='weight decay')\n\n\n # fmt: on\n\n @property\n def optimizer_config(self):\n \"\"\"\n Return a kwarg dictionary that will be used to override optimizer\n args stored in checkpoints. This allows us to load a checkpoint and\n resume training using a different set of optimizer args, e.g., with a\n different learning rate.\n \"\"\"\n return {\n 'lr': self.args.lr[0],\n 'betas': eval(self.args.nosadashift_betas),\n 'eps': self.args.nosadashift_eps,\n 'gamma':self.args.nosadashift_gamma,\n 'keep_num':self.args.nosadashift_keep_num,\n 'weight_decay': self.args.weight_decay,\n }","sub_path":"fairseq_master/fairseq/optim/nosadashift.py","file_name":"nosadashift.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"91074362","text":"f=open(\"temp\",\"r\")\nfout=open(\"tempoutput\",\"w\")\ndict={}\nfor lines in f:\n data = lines.rstrip(\"\\n\").split(\",\")\n print(data)\n dist=data[0]\n temp=data[1]\n if (dist not in dict):\n dict[dist]=temp\n else:\n maxm=max(temp,dict[dist])\n dict[dist]=maxm\nprint(dict)\n\nlst=[]\nfor k,v in dict.items():\n lst.append((k,v))\nfor val in lst:\n fout.write(str(val))\n\n\n\n","sub_path":"exam/max temp.py","file_name":"max temp.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"469243929","text":"# /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom pathlib import Path\nimport os.path as op\nimport pyqtgraph\nfrom loguru import logger\nfrom typing import List\nimport ast\n\n\ndef create_icon(\n app_name: str,\n icon_filename=None,\n conda_env_name=None,\n package_name=None,\n dry_run=False,\n):\n \"\"\"\n\n :param app_name: Used for desktop icon name\n :param icon_filename: absolute path to icon usually:\n pathlib.Path(__file__).parent / pathlib.Path(\"app_icon512.ico\")\n :param conda_env_name: conda environment. The app_name is used if conda_env_name is set to None.\n :param package_name: in `conda -m 'package_name'` . The app_name is used if conda_env_name is set to None.\n :return:\n \"\"\"\n import platform\n\n # print(platform.system)\n if conda_env_name is None:\n conda_env_name = app_name\n\n # if icon_filename is None:\n # icon_filename = app_name\n\n if Path(icon_filename).suffix == \"\":\n icon_filename += \".ico\"\n\n if package_name is None:\n package_name = app_name\n\n if platform.system() == \"Windows\":\n\n # logo_fn2 = pathlib.Path(__file__).parent / pathlib.Path(\"scaffan_icon512.ico\")\n\n # logo_fn = op.join(op.dirname(__file__), icon_filename)\n logo_fn = icon_filename\n import win32com.client\n\n shell = win32com.client.Dispatch(\"WScript.Shell\")\n\n pth = Path.home()\n pth = pth / \"Desktop\" / Path(f\"{app_name}.lnk\")\n shortcut = shell.CreateShortcut(str(pth))\n # cmd\n # ln = \"call activate scaffan; {} -m scaffan\".format(sys.executable)\n # C:\\Windows\\System32\\cmd.exe /C \"call activate anwaapp & pause & python -m anwa & pause\"\n # shortcut.TargetPath = sys.executable\n # shortcut.Arguments = f\"-m {app_name}\"\n shortcut.TargetPath = \"cmd\"\n # C:\\Windows\\System32\\cmd.exe /C \"call activate anwaapp & pause & python -m anwa & pause\"\n shortcut.Arguments = (\n f'/C \"call activate {conda_env_name} & python -m {package_name} & pause\" '\n )\n shortcut.IconLocation = \"{},0\".format(logo_fn)\n if not dry_run:\n shortcut.Save()\n\n\n# def params_and_values(\n# p: pyqtgraph.parametertree.Parameter, pth=None, dct={}, separator=\";\"\n# ):\n# \"\"\"\n# Get dict of all parameters. Key is the path to the parameter, value is value of the parameter.\n# :param p:\n# :param pth:\n# :param dct:\n# :param separator: default \";\"\n# :return:\n# \"\"\"\n# for name in p.getValues():\n# # print(f\"name: {name}, type {type(name)}\")\n# if pth is not None:\n# pth_local = pth + separator + name\n# else:\n# pth_local = name\n# # print(pth)\n# ch = p.child(name)\n# # print(f\"name: {name}, type {type(ch)}\")\n# if type(ch) is pyqtgraph.parametertree.parameterTypes.SimpleParameter:\n# dct[pth_local] = ch.value()\n# # print(pth)\n# else:\n# params_and_values(ch, pth_local)\n#\n# return dct\n#\n#\n# def set_parameters_by_path(\n# parameters: pyqtgraph.parametertree.Parameter,\n# path_val_couple_list: List,\n# parse_path=True,\n# separator=\";\",\n# ):\n# \"\"\"\n# Set value to parameter.\n# :param parameters: paramtree.Paramterr\n# :param path_val_couple_list: list of couple [Path to parameter can be separated by \";\", value]\n# :param value:\n# :param parse_path: Turn on separation of path by \";\"\n# :return:\n# \"\"\"\n#\n# for param_path, param_value in path_val_couple_list:\n# if type(param_value) is str:\n# value = ast.literal_eval(param_value)\n# else:\n# value = param_value\n# logger.debug(f\"param path={param_path}, ast value={value}\")\n# set_parameter_by_path(\n# parameters,\n# param_path,\n# value=value,\n# parse_path=parse_path,\n# separator=separator,\n# )\n#\n#\n# def set_parameter_by_path(\n# parameters: pyqtgraph.parametertree.Parameter,\n# param_path: str,\n# value,\n# parse_path=True,\n# separator=\";\",\n# ):\n# \"\"\"\n# Set value to parameter.\n# :param param_path: Path to parameter can be separated by \";\"\n# :param value:\n# :param parse_path: Turn on separation of path by \";\"\n# :return:\n# \"\"\"\n# logger.debug(f\"Set {param_path} to {value}\")\n# if parse_path:\n# param_path = param_path.split(separator)\n# fnparam = parameters.param(*param_path)\n# fnparam.setValue(value)\n","sub_path":"exsu/app_tools.py","file_name":"app_tools.py","file_ext":"py","file_size_in_byte":4539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"647172807","text":"\"\"\"Create a basic scenario from the internal data structure.\n\nSPDX-FileCopyrightText: 2016-2021 Uwe Krien \n\nSPDX-License-Identifier: MIT\n\"\"\"\n\n\nimport calendar\nimport logging\nimport os\n\nimport pandas as pd\nfrom reegis import config as cfg\nfrom reegis import demand_elec\nfrom reegis import demand_heat\n\n\ndef get_heat_profiles_deflex(\n deflex_geo, year, time_index=None, weather_year=None, keep_unit=False\n):\n \"\"\"\n\n Parameters\n ----------\n year\n deflex_geo\n time_index\n weather_year\n keep_unit\n\n Returns\n -------\n\n \"\"\"\n # separate_regions=keep all demand connected to the region\n separate_regions = cfg.get_list(\"creator\", \"separate_heat_regions\")\n # Add lower and upper cases to be not case sensitive\n separate_regions = [x.upper() for x in separate_regions] + [\n x.lower() for x in separate_regions\n ]\n\n # add second fuel to first\n # combine_fuels = cfg.get_dict(\"combine_heat_fuels\")\n combine_fuels = {\"natural gas\": \"gas\"}\n\n # fuels to be dissolved per region\n region_fuels = cfg.get_list(\"creator\", \"local_fuels\")\n\n fn = os.path.join(\n cfg.get(\"paths\", \"demand\"),\n \"heat_profiles_{year}_{map}\".format(year=year, map=deflex_geo.name),\n )\n\n demand_region = (\n demand_heat.get_heat_profiles_by_region(\n deflex_geo, year, to_csv=fn, weather_year=weather_year\n )\n .groupby(level=[0, 1], axis=1)\n .sum()\n )\n\n # Decentralised demand is combined to a nation-wide demand if not part\n # of region_fuels.\n regions = list(\n set(demand_region.columns.get_level_values(0).unique())\n - set(separate_regions)\n )\n\n # If region_fuels is 'all' fetch all fuels to be local.\n if \"all\" in region_fuels:\n region_fuels = demand_region.columns.get_level_values(1).unique()\n\n for fuel in demand_region.columns.get_level_values(1).unique():\n demand_region[\"DE\", fuel] = 0\n\n for region in regions:\n for f1, f2 in combine_fuels.items():\n demand_region[region, f1] += demand_region[region, f2]\n demand_region.drop((region, f2), axis=1, inplace=True)\n cols = list(set(demand_region[region].columns) - set(region_fuels))\n for col in cols:\n demand_region[\"DE\", col] += demand_region[region, col]\n demand_region.drop((region, col), axis=1, inplace=True)\n\n if time_index is not None:\n demand_region.index = time_index\n\n if not keep_unit:\n msg = (\n \"The unit of the source is 'TJ'. \"\n \"Will be divided by {0} to get 'MWh'.\"\n )\n converter = 0.0036\n demand_region = demand_region.div(converter)\n logging.debug(msg.format(converter))\n\n demand_region.sort_index(1, inplace=True)\n\n for c in demand_region.columns:\n if demand_region[c].sum() == 0:\n demand_region.drop(c, axis=1, inplace=True)\n\n return demand_region\n\n\ndef scenario_demand(regions, year, name, opsd_version=None, weather_year=None):\n \"\"\"\n\n Parameters\n ----------\n regions\n year\n name\n opsd_version\n weather_year\n\n Returns\n -------\n\n Examples\n --------\n >>> from reegis import geometries # doctest: +SKIP\n >>> fs=geometries.get_federal_states_polygon() # doctest: +SKIP\n >>> my_demand=scenario_demand(regions, 2014, \"de21\") # doctest: +SKIP\n >>> int(my_demand[\"DE01\", \"district heating\"].sum()) # doctest: +SKIP\n 18639262\n >>> int(my_demand[\"DE05\", \"all\"].sum()) # doctest: +SKIP\n 10069304\n\n \"\"\"\n demand_series = {\n \"electricity demand series\": scenario_elec_demand(\n pd.DataFrame(),\n regions,\n year,\n name,\n weather_year=weather_year,\n version=opsd_version,\n )\n }\n if cfg.get(\"creator\", \"heat\"):\n demand_series[\"heat demand series\"] = scenario_heat_demand(\n regions, year, weather_year=weather_year\n ).reset_index(drop=True)\n return demand_series\n\n\ndef scenario_heat_demand(regions, year, weather_year=None):\n \"\"\"\n\n Parameters\n ----------\n regions\n year\n weather_year\n\n Returns\n -------\n\n \"\"\"\n return get_heat_profiles_deflex(\n regions, year, weather_year=weather_year\n ).sort_index(1)\n\n\ndef scenario_elec_demand(\n table, regions, year, name, version=None, weather_year=None\n):\n \"\"\"\n\n Parameters\n ----------\n table\n regions\n year\n name\n weather_year\n\n Returns\n -------\n\n \"\"\"\n if weather_year is None:\n demand_year = year\n else:\n demand_year = weather_year\n\n df = demand_elec.get_entsoe_profile_by_region(\n regions, demand_year, name, annual_demand=\"bmwi\", version=version\n )\n df = pd.concat([df], axis=1, keys=[\"all\"]).swaplevel(0, 1, 1)\n df = df.reset_index(drop=True)\n if not calendar.isleap(year) and len(df) > 8760:\n df = df.iloc[:8760]\n return pd.concat([table, df], axis=1).sort_index(1)\n\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"src/scenario_builder/demand.py","file_name":"demand.py","file_ext":"py","file_size_in_byte":5040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"138608015","text":"#Guess number\n\nimport random\n\nprint(\"This is a Game, You Have to Guess a Number Between a Range.\")\ni = \"Y\"\n\nwhile i == \"Y\":\n a1, a2 = input(\"\\n Enter two value As Range(Seperated by Space): \").split()\n rnd = random.randint( int(a1) , int(a2) )\n\n while True :\n y = int(input(\"Enter your Guess: \"))\n if rnd == y:\n print (\":) :) You Are Amazing :) :) The number Was \",y)\n i = input(\"\\n Do you Want to Reapeat the Game? (Y/N): \")\n break\n elif rnd < y:\n print(\"Wrong:( Enter Lesser Number \\n\")\n else:\n print(\"Wrong:( Enter Higher Number \\n\")\n \n","sub_path":"Guess The Number v 0.1.py","file_name":"Guess The Number v 0.1.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"314553660","text":"import os\nfrom traits.api import *\nfrom traitsui.api import *\nfrom traitsui.extras.checkbox_column import CheckboxColumn\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.figure import Figure\nfrom matplotlib.axes import Axes\nfrom matplotlib.collections import PolyCollection, LineCollection\nfrom matplotlib.colors import colorConverter\n\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\nimport matplotlib.cm as cmx\nfrom auxilary_functions import wl_to_rgb, subtract_data_arrays\nfrom file_selector import string_list_editor\nfrom viewers import DictEditor\nimport numpy as np\nimport random\nimport pandas as pd\ntry:\n import cPickle as pickle\nexcept:\n import pickle\n\nfrom data_plot_viewers import DataPlotEditorBase, IntegrationDataPlot1D\nfrom integration_results import IntegrationResultBase,ComparisonIntegrationResult, ExperimentIntegrationResult\n\n\nclass IntegrationToolBase(HasTraits):\n\n experiment = Any()\n int_results = List(IntegrationResultBase)\n has_selections = Property(Bool)\n use_fit = Bool(False)\n\n ##### Plots #####\n display = Instance(DataPlotEditorBase)\n\n ##### GUI #####\n integrate = Button('Integrate Selections')\n clear = Button('Clear Selections')\n refresh = Button('Refresh')\n save = Button('Save Results')\n select_range = Button('Select Range')\n\n view = View(\n HSplit(\n\n\n\n VGroup(\n HGroup(Item(name='select_range', show_label=False, ),\n Item(name='integrate', show_label=False, ),\n Item(name='use_fit', label='Fit Data', ),\n Item(name='clear', show_label=False, ),\n spring,\n Item(name='refresh', show_label=False),\n show_border=True, label='Control'),\n Group(Item(name='display', style='custom', show_label=False),\n show_border=True, label='Plots'),\n\n ),\n\n VGroup(\n\n VGroup(Item(name='save', show_label=False, ),\n Item(name='int_results', show_label=False, style='custom',\n editor=ListEditor(use_notebook=True, deletable=True, page_name='.name'), ),\n show_border=True, label='Integration Results'),\n\n ),\n ),\n buttons = ['OK'],\n title = 'Integration Tool',\n kind = 'live',\n\n scrollable = True,\n resizable = True,\n height = 800,\n width = 1200,\n )\n\n def _get_has_selections(self):\n if self.display is None:\n return False\n if len(self.display.selections):\n return True\n else:\n return False\n\n\n def _select_range_fired(self):\n self.display.clear_selections()\n self.display.mpl_setup()\n\n def _refresh_fired(self):\n self.display.clear_plots()\n #self.display.clear_selections()\n if len(self.display.axs):\n self.experiment.plot_1d(figure=self.display.figure,legend=False)\n self.set_titles()\n self.display.redraw_selections()\n self.display.configure_selector()\n #plt.tight_layout()\n\n\n\n def integrate_all(self, use_fit):\n raise NotImplementedError\n\n def store_results(self, results):\n raise NotImplementedError\n\n def set_titles(self):\n raise NotImplementedError\n\n def save_results(self):\n raise NotImplementedError\n\n def _integrate_fired(self):\n results = self.integrate_all(self.use_fit)\n self.store_results(results)\n\n def _clear_fired(self):\n self.display.clear_selections()\n self.display.configure_selector()\n\n def _save_fired(self):\n self.save_results()\n\n def _int_results_default(self):\n raise NotImplementedError\n\n\nclass ComparisonIntegrationTool(IntegrationToolBase):\n def __init__(self,project):\n super(ComparisonIntegrationTool, self).__init__()\n self.project = project\n self.experiments = project.comparisons\n self.int_results = project.comp_int_results\n\n def _display_default(self):\n display = IntegrationDataPlot1D()\n # display.add_subplots(3)\n return display\n\n\n def store_results(self,results):\n for result in results:\n res = ComparisonIntegrationResult()\n min = 0.0\n max = 0.0\n res.int_range = (result.get('min',0.0),result.get('max',0.0))\n result_array = []\n for key,value in result.items():\n if key=='name':\n res.name = value\n elif key=='min':\n min = value\n elif key=='max':\n max=value\n else:\n result_array.append([key, value.get('exp1',0.0),value.get('exp2',0.0),value.get('subtraction',0.0)])\n res.int_range = (min,max)\n res.results = np.asarray(sorted(result_array))\n self.int_results.append(res)\n\n def set_titles(self):\n self.display.set_title(self.selected.name)\n if len(self.display.axs):\n self.display.axs[0].set_title('Experiment 1',fontsize=12)\n self.display.axs[1].set_title('Experiment 2',fontsize=12)\n self.display.axs[2].set_title('Subtraction',fontsize=12)\n\n\n def integrate_all(self, use_fit):\n results = []\n for n,(min, max) in enumerate(self.display.selections):\n result = {'name': self.selected.name+'_'+str(n), 'min': min, 'max': max}\n\n for meas in self.selected.exp1.measurements:\n if meas.ex_wl not in result.keys():\n result[meas.ex_wl] = {}\n result[meas.ex_wl]['exp1'] = meas.integrate_bg_corrected(min, max,fit=use_fit)\n\n for meas in self.selected.exp2.measurements:\n if meas.ex_wl not in result.keys():\n result[meas.ex_wl] = {}\n result[meas.ex_wl]['exp2'] = meas.integrate_bg_corrected(min, max,fit=use_fit)\n\n for meas in self.selected.subtraction.measurements:\n if meas.ex_wl not in result.keys():\n result[meas.ex_wl] = {}\n result[meas.ex_wl]['subtraction'] = meas.integrate_bg_corrected(min, max,fit=use_fit)\n\n results.append(result)\n return results\n\n def _int_results_default(self):\n return [ComparisonIntegrationResult()]\n\n def save_results(self):\n if self.project is not None:\n self.project.comp_int_results = self.int_results\n\nclass ExperimentIntegrationTool(IntegrationToolBase):\n\n def __init__(self,experiment):\n super(ExperimentIntegrationTool, self).__init__()\n\n self.experiment = experiment\n self.int_results = experiment.int_results\n\n\n def _display_default(self):\n display = IntegrationDataPlot1D()\n # display.add_subplots(3)\n return display\n\n\n def set_titles(self):\n self.display.set_title(self.experiment.name)\n if len(self.display.axs):\n self.display.axs[0].set_title('Signal',fontsize=12)\n self.display.axs[1].set_title('Background',fontsize=12)\n self.display.axs[2].set_title('Reference',fontsize=12)\n\n def store_results(self, results):\n\n for result in results:\n res = ExperimentIntegrationResult()\n min = 0.0\n max = 0.0\n res.int_range = (result.get('min', 0.0), result.get('max', 0.0))\n result_array = []\n for key, value in result.items():\n if key == 'name':\n res.name = value\n elif key == 'min':\n min = value\n elif key == 'max':\n max = value\n else:\n result_array.append(\n [key, value.get('sig', 0.0), value.get('bg', 0.0),value.get('sig', 0.0)-value.get('bg', 0.0) , value.get('ref', 0.0)])\n res.int_range = (round(min,1), round(max,1))\n res.results = np.asarray(sorted(result_array))\n self.int_results.append(res)\n\n def integrate_all(self,use_fit):\n results = []\n for n, (min, max) in enumerate(self.display.selections):\n result = {'name': self.experiment.name + '_' + str(n), 'min': min, 'max': max}\n\n for meas in self.experiment.measurements:\n if meas.ex_wl not in result.keys():\n result[meas.ex_wl] = {}\n result[meas.ex_wl]['sig'] = meas.integrate_signal(min, max,fit=use_fit)\n result[meas.ex_wl]['bg'] = meas.integrate_bg(min, max,fit=use_fit)\n result[meas.ex_wl]['ref'] = meas.integrate_ref(min, max,fit=use_fit)\n if len(result.items()):\n results.append(result)\n return results\n\n def _int_results_default(self):\n return [ExperimentIntegrationResult()]\n\n def save_results(self):\n if self.experiment is not None:\n self.experiment.int_results = self.int_results","sub_path":"integration_tool.py","file_name":"integration_tool.py","file_ext":"py","file_size_in_byte":9056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"373865566","text":"\"\"\"\nTest model on test data\n\"\"\"\nimport argparse\nimport logging\n\nimport joblib\nimport pandas as pd\nimport wandb\nfrom sklearn.metrics import accuracy_score\n\nlogging.basicConfig(level=logging.INFO, format=\"%(asctime)-15s %(message)s\")\nlogger = logging.getLogger()\n\n\ndef go(args):\n run = wandb.init(job_type=\"test\")\n run.config.update(args)\n\n logger.info(f\"Reading test data: {args.test_data}\")\n local_path = wandb.use_artifact(args.test_data).file()\n x = pd.read_csv(local_path)\n y = x.pop(args.target)\n\n logger.info(f\"Loading model from {args.model}\")\n model_path = wandb.use_artifact(args.model).file()\n model = joblib.load(model_path)\n\n logger.info(\"Evaluating model\")\n preds = model.predict(x)\n acc = accuracy_score(y, preds)\n logger.info(f\"Accuracy on test data: {acc:.2f}\")\n run.summary[\"accuracy\"] = acc\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(description=\"Test model against test dataset\")\n parser.add_argument(\n \"test_data\",\n type=str,\n help=\"Name of test dataset artifact\",\n )\n parser.add_argument(\n \"target\",\n type=str,\n help=\"Name of target variable\",\n )\n parser.add_argument(\n \"model\",\n type=str,\n help=\"Name of model artifact\",\n )\n args = parser.parse_args()\n\n go(args)\n","sub_path":"src/test_model/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"193122199","text":"from LatLng import LatLng\n\n'''\n The bounds conceptually includes all points where:\n\n The latitude is in the range (northeast.latitude, southwest.latitude);\n The longitude is in the range (southwest.longtitude, northeast.longitude) if southwest.longtitude ≤ northeast.longitude; and\n The longitude is in the range (southwest.longitude, 180) ∪ ()-180, northeast.longitude) if southwest.longtitude > northeast.longitude.\n'''\nclass LatLngBounds:\n def __init__(self, sw, ne):\n if sw == None:\n self._sw = LatLng(1, 180)\n self._ne = LatLng(-1, -180)\n elif ne == None:\n if type(sw) == type(dict()): sw = LatLng(sw['lat'], sw['lng'])\n self._sw = self._ne = sw\n else:\n if type(sw) == type(dict()): sw = LatLng(sw['lat'], sw['lng'])\n self._sw = sw\n\n if type(ne) == type(dict()): ne = LatLng(ne['lat'], ne['lng'])\n self._ne = ne\n\n if ne.lat <= sw.lat:\n raise Exception('NE latitude should be larger than SW latitude')\n\n def contains(self, point):\n if type(point) == type(dict()):\n point = LatLng(point['lat'], point['lng'])\n \n if self.SW.lat < point.lat < self.NE.lat:\n if self.SW.lng <= self.NE.lng:\n if self.SW.lng < point.lng < self.NE.lng:\n return True\n elif self.SW.lng > self.NE.lng:\n if (self.SW.lng < point.lng < 180) or (-180 < point.lng < self.NE.lng):\n return True\n return False\n\n @property\n def SW(self):\n return self._sw\n\n @property\n def NE(self):\n return self._ne\n","sub_path":"LatLngBounds.py","file_name":"LatLngBounds.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"585784003","text":"the_count = [1,2,3,4,5]\r\nfruits = ['사과','귤','배','살구']\r\nchange = [1,'십원','2','백원','3','오백원']\r\n\r\nfor number in the_count:\r\n print(\"이수는 %d\" % number)\r\n\r\nfor fruit in fruits:\r\n print(\"과일 종류: %s\" % fruit)\r\n\r\nfor i in change:\r\n print(\"받은 잔동 %s\" % i)\r\n\r\nelements = []\r\n\r\nfor i in range(0,6):\r\n print(\"list에 %d숫자를 더합니다\" % i)\r\n elements.append(i)\r\n\r\nfor i in elements:\r\n print(\"원소는 %d\" % i)\r\n","sub_path":"python/for&list/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"445877917","text":"# Programa para carga de datos en BBDD SQLite\n\nimport sqlite3\nfrom tkinter import *\nfrom tkinter import messagebox\nfrom tkinter import ttk\n\nfrom Clases import Clientes, Paises\n\n\ncolor=\"#f2d05e\"\n\n\n# - - - - - - - funciones - - - - - - - - \n\ndef grabarCli(cod,nom,dir,loc,pais,cod_trib,cond,tel,mail):\n \n\n # - - - Control Datos -----\n f=True\n if cod==\"\" or len(cod)!=6:\n if len(cod)!=6:\n messagebox.showerror(\"ERROR\", \"Cantidad del <<>>\\n deben ser 6 caracteres\")\n return\n f=False\n \n \n if nom==\"\":\n f=False\n\n if dir==\"\":\n f=False\n\n if loc==\"\":\n f=False\n \n if len(pais)>2:\n pais=pais[0:2]\n\n if pais==\"\" or len(pais)!=2:\n if len(pais)!=2:\n messagebox.showerror(\"ERROR\", \"Cantidad del <<>>\\n deben ser 2 caracteres\")\n return\n f=False\n \n if cod_trib==\"\":\n f=False\n\n \n if(f==False):\n messagebox.showwarning(\"ERROR\", \"Faltó completar campos...\")\n return\n \n\n cliente=Clientes.Clientes()\n cliente.setear_clientes(cod,nom,dir,loc,pais,cod_trib,cond,tel,mail)\n \n if cliente.existe_cliente():\n # actualiza cliente\n cliente.actualiza_cliente()\n\n else:\n #inserta cliente\n cliente.guardar_clientes()\n \n \n limpiaDatos()\n\ndef limpiaDatos() :\n cod_cliente.set(\"\")\n nombre.set(\"\")\n direccion.set(\"\")\n localidad.set(\"\")\n codPaisEntry.set(\"\")\n id_tributaria.set(\"\")\n condicion_venta.set(\"\")\n telefono.set(\"\")\n correo_electronico.set(\"\")\n codigoCliEntry['state']='normal'\n codigoCliEntry.focus()\n \ndef buscarCli():\n global hija\n lista=[]\n cliente=Clientes.Clientes()\n lista_clientes=cliente.leer_lista(lista)\n \n hija=Toplevel()\n hija.title(\"Busca Cliente\")\n hija.iconbitmap(\"images/logo.ico\")\n hija.resizable(0,0)\n\n frame2=Frame(hija)\n frame2.config(bg=color, width=\"650\", height=\"350\")\n frame2.pack(fill=\"both\", expand=\"False\")\n\n \n listaLbl=Label(frame2,text=\"Cliente:\")\n listaLbl.grid(row=1,column=0,padx=5, pady=5)\n listaLbl.config(bg=color)\n\n listaCliEntry=ttk.Combobox(frame2,values=lista_clientes,width=40,state=\"readonly\")\n listaCliEntry.grid(row=1,column=1,sticky=\"w\",padx=5, pady=5)\n listaCliEntry.config(font=\"Arial 10\")\n\n \n eligeItemBtn=Button(frame2,text=\"Elige Cliente\", command=lambda:muestra_cliente(listaCliEntry.get()))\n eligeItemBtn.grid(row=3,column=0,ipady=5, columnspan=2)\n eligeItemBtn.config(width=\"20\")\n\ndef muestra_cliente(cli):\n global hija\n # Busca registro donde apunta \"prod\"\n cod_cli=cli[0:6]\n cliente=Clientes.Clientes()\n cliente.buscar_cliente(cod_cli)\n\n cod_cliente.set(cliente.cod_cliente)\n nombre.set(cliente.nombre)\n direccion.set(cliente.direccion)\n localidad.set(cliente.localidad)\n\n pais=Paises.Paises()\n codigo_pais=pais.buscar_pais(cliente.cod_pais)\n codPaisEntry.set(codigo_pais)\n id_tributaria.set(cliente.id_tributaria)\n condicion_venta.set(cliente.id_tributaria)\n telefono.set(cliente.telefono)\n correo_electronico.set(cliente.correo_electronico)\n\n \n codigoCliEntry['state']='disabled'\n\n\n hija.destroy()\n\n\n\n\n# - - - - - - - - - - Prog. Principal - - - - - - - \n\n\nraiz=Tk()\nraiz.title(\"Carga de Clientes\")\nraiz.iconbitmap(\"images/logo.ico\")\nraiz.resizable(0,0)\n\nframe=Frame(raiz)\nframe.config(bg=color, width=\"650\", height=\"350\")\nframe.pack(fill=\"both\", expand=\"False\")\n\ncod_cliente = StringVar()\nnombre = StringVar()\ndireccion = StringVar()\nlocalidad = StringVar()\n#cod_pais = StringVar()\nid_tributaria = StringVar()\ncondicion_venta = StringVar()\ntelefono = StringVar()\ncorreo_electronico = StringVar()\n\n \n# - - - - - Labels - - - - - -\ncodigoCliLbl=Label(frame,text=\"Código Cliente: \")\ncodigoCliLbl.config(bg=color)\ncodigoCliLbl.grid(row=0,column=0,sticky=\"e\",padx=5, pady=5)\n\nnombreLbl=Label(frame,text=\"Nombre: \")\nnombreLbl.config(bg=color)\nnombreLbl.grid(row=1,column=0,sticky=\"e\",padx=5, pady=5)\n\ndireccionLbl=Label(frame,text=\"Dirección: \")\ndireccionLbl.config(bg=color)\ndireccionLbl.grid(row=2,column=0,sticky=\"e\",padx=5, pady=5)\n\nlocalidadLbl=Label(frame,text=\"Localidad: \")\nlocalidadLbl.config(bg=color)\nlocalidadLbl.grid(row=3,column=0,sticky=\"e\",padx=5, pady=5)\n\ncodPaisLbl=Label(frame,text=\"Código del País: \")\ncodPaisLbl.config(bg=color)\ncodPaisLbl.grid(row=4,column=0,sticky=\"e\",padx=5, pady=5)\n\nidTributariaLbl=Label(frame,text=\"Identificación Tributaria: \")\nidTributariaLbl.config(bg=color)\nidTributariaLbl.grid(row=5,column=0,sticky=\"e\",padx=5, pady=5)\n\ncondicionVtaLbl=Label(frame,text=\"Condición de Venta: \")\ncondicionVtaLbl.config(bg=color)\ncondicionVtaLbl.grid(row=6,column=0,sticky=\"e\",padx=5, pady=5)\n\ntelefonoLbl=Label(frame,text=\"Teléfono: \")\ntelefonoLbl.config(bg=color)\ntelefonoLbl.grid(row=7,column=0,sticky=\"e\",padx=5, pady=5)\n\ncorreoLbl=Label(frame,text=\"correo electrónico: \")\ncorreoLbl.config(bg=color)\ncorreoLbl.grid(row=8,column=0,sticky=\"e\",padx=5, pady=5)\n\n# - - - - - Entrys - - - - - - \ncodigoCliEntry=Entry(frame,textvariable=cod_cliente,width=6)\ncodigoCliEntry.grid(row=0,column=1,sticky=\"w\",padx=5, pady=5,ipady=5)\ncodigoCliEntry.config(font=\"Arial 15\")\n\nnombreEntry=Entry(frame,textvariable=nombre)\nnombreEntry.grid(row=1,column=1,sticky=\"w\",padx=5, pady=5)\nnombreEntry.config(font=\"Arial 15\")\n\ndireccionEntry=Entry(frame,textvariable=direccion)\ndireccionEntry.grid(row=2,column=1,sticky=\"w\",padx=5, pady=5)\ndireccionEntry.config(font=\"Arial 15\")\n\nlocalidadEntry=Entry(frame,textvariable=localidad)\nlocalidadEntry.grid(row=3,column=1,sticky=\"w\",padx=5, pady=5,)\nlocalidadEntry.config(font=\"Arial 15\")\n\n\nlista=[]\nlista_paises=Paises.Paises()\nlista=lista_paises.leer_lista(lista)\ncodPaisEntry=ttk.Combobox(frame,values=lista,width=30)\ncodPaisEntry.grid(row=4,column=1,sticky=\"w\",padx=5, pady=5)\ncodPaisEntry.config(font=\"Arial 10\")\n\nidTributariaEntry=Entry(frame,textvariable=id_tributaria)\nidTributariaEntry.grid(row=5,column=1,sticky=\"w\",padx=5, pady=5,)\nidTributariaEntry.config(font=\"Arial 15\")\n\ncondicionVtaEntry=Entry(frame,textvariable=condicion_venta)\ncondicionVtaEntry.grid(row=6,column=1,sticky=\"w\",padx=5, pady=5,)\ncondicionVtaEntry.config(font=\"Arial 15\")\n\ntelefonoEntry=Entry(frame,textvariable=telefono)\ntelefonoEntry.grid(row=7,column=1,sticky=\"w\",padx=5, pady=5,)\ntelefonoEntry.config(font=\"Arial 15\")\n\nmailEntry=Entry(frame,textvariable=correo_electronico)\nmailEntry.grid(row=8,column=1,sticky=\"w\",padx=5, pady=5,)\nmailEntry.config(font=\"Arial 15\")\n\nbuscarBtn=Button(frame,text=\"Buscar\", command=lambda:buscarCli())\nbuscarBtn.grid(row=0,column=1,sticky=\"e\",padx=5, pady=5,ipady=5)\nbuscarBtn.config(width=\"10\")\n\nguardarBtn=Button(frame,text=\"Guardar\", command=lambda:grabarCli(cod_cliente.get(),nombre.get(),direccion.get(),localidad.get(),codPaisEntry.get(),id_tributaria.get(),condicion_venta.get(),telefono.get(),correo_electronico.get()))\nguardarBtn.grid(row=9,column=0,columnspan=2,ipady=5)\nguardarBtn.config(width=\"60\")\n\nlimpiarBtn=Button(frame,text=\"Limpiar\", command=lambda:limpiaDatos())\nlimpiarBtn.grid(row=10,column=0,columnspan=2,ipady=5)\nlimpiarBtn.config(width=\"60\")\n\n\nsalirBtn=Button(frame,text=\"Salir\",command=raiz.destroy)\nsalirBtn.grid(row=11,column=0,columnspan=2,ipady=5)\nsalirBtn.config(width=\"60\")\n\ncodigoCliEntry.focus()\n \nraiz.mainloop()\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"view_clientes.py","file_name":"view_clientes.py","file_ext":"py","file_size_in_byte":7409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"462287061","text":"# Write a class to hold player information, e.g. what room they are in\n# currently.\n\n\nclass Player:\n def __init__(self, name, room, inventory):\n self.name = name\n self.current_room = room\n self.inventory = list(inventory)\n\n # def __str__(self):\n # return f'Player: {self.name} is {self.room}'\n\n def move(self, direction):\n if getattr(self.current_room, f\"{direction}_to\") is None:\n print('')\n print(\"You can not go in that direction\")\n print('')\n else: \n self.current_room = getattr(self.current_room, f\"{direction}_to\") \n\n def getInventoryAndDrop(self, player):\n item_names = []\n item_objects = []\n if len(self.inventory) > 0:\n for item in self.inventory:\n if item is not str(item):\n print(f\"{item.name}: {item.description}\")\n item_objects.append(item)\n item_names.append(item.name)\n else: \n print(\"You have no items in your Inventory!\")\n print('')\n print('')\n drop = input(\"Type 'Drop' with item name to drop item in room, 'exit' to exit inventory: \")\n print('********************************************')\n print('')\n # Drop an Item/ Add to current Room\n drop_split = drop.split()\n item_only = ' '\n drop_item = item_only.join(drop_split[1:])\n if drop is not '':\n if drop_split[0] == \"Drop\" and drop_item in item_names:\n for item in item_objects:\n if item.name == drop_item:\n item.on_drop(player, item)\n print(f\"{item.name} have been dropped to {player.current_room.name}!\")\n print('-------------------------------------------')\n print('')\n elif drop == 'exit': \n print(\"You have left your Inventory\")\n else:\n print(\"Invalid Key!\")\n\n def findItem(self, add, player, item_names, items_array):\n add_split = add.split()\n item_only = ' '\n add_item = item_only.join(add_split[1:])\n # Add All Items/ Remove all from current room\n if add == 'all':\n for item in range(len(player.current_room.items)):\n player.addItemToInventory(player.current_room.items[item])\n player.current_room.items.clear()\n print(\"Items have been added!\")\n print('-------------------------------------------')\n print('')\n # Add specific item/ Remove from current room\n elif add_split[0] == \"Take\" and add_item in item_names:\n for item in items_array:\n if item.name == add_item:\n item.on_take(player, item)\n print(f\"{add_item} have been added!\")\n print('-------------------------------------------')\n print('')\n # Exit Search\n elif add == 'exit':\n print(f\"{player.name} stopped searching\")\n print('-------------------------------------------')\n print('')\n else:\n print(\"Invalid key!\")\n print('')\n\n def addItemToInventory(self, item):\n self.inventory.append(item)\n\n def removeItemFromInventory(self, item):\n self.inventory.remove(item)\n\n\n ","sub_path":"src/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":3377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"224793508","text":"import re\n\ntextStr = \"From john.doe@ab.etc Thu Jun 15 02:04:09 2010\"\n\n# Extract 'ab.etc'\nresult = re.findall(r'.*@(.*?) ', textStr)\nprint(result)\n\n# Extract 'john.doe@ab.etc'\nresult = re.findall(r'(\\S*@.*?) ', textStr)\nprint(result)\n\n# Extract 'From: Using the :'\nx = 'From: Using the : character'\nresult = re.findall(r'(\\S*.*?:)', x)\nprint(result)\n\n# Extract {'Ann': '99', 'Maria': '95', 'David': '84', 'Jose': '21'}\nmathScores = '''\nAnn got 99 and Maria got 95,\nDavid got 84 and Jose got 21\n'''\n\nkeys = re.findall(r'([A-Z]\\w+)', mathScores)\nprint(keys)\nvalues = re.findall(r'(\\d+)', mathScores)\nprint(values)\n\ndictionary = dict(zip(keys, values))\nprint(dictionary)\n","sub_path":"18_regex.py","file_name":"18_regex.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"571522913","text":"def solution():\n comp_number = int(input())\n conn_number = int(input())\n connections = [tuple(map(int, input().split(' '))) for _ in range(conn_number)]\n computers = [1] * comp_number\n queue = {1}\n count = 0\n\n while queue:\n comp = queue.pop()\n computers[comp - 1] = 0\n count += 1\n for conn1, conn2 in connections:\n if comp == conn1 and computers[conn2 - 1] == 1:\n queue.add(conn2)\n elif comp == conn2 and computers[conn1 - 1] == 1:\n queue.add(conn1)\n return count - 1\nprint(solution())","sub_path":"baekjoon/problem_2606/virus.py","file_name":"virus.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"147789587","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jun 11 11:48:44 2018\r\n\r\nGet minutely refreshed Stock Data based on Stocksymbol via the alphavantage Data API\r\nThe data is \"delivered\" in 1hour steps, and runs for as many hours as \"hours\" is set\r\n\r\n@author: Kalina\r\n\"\"\"\r\nimport requests \r\nimport pandas as pd\r\nimport mysql.connector\r\nimport datetime\r\nimport time\r\nimport sys\r\nimport subprocess\r\nimport shlex\r\nfrom bs4 import BeautifulSoup\r\n\r\n#Stocksymbol\r\nsymbol=sys.argv[1]\r\n\r\n#Generate your own key as described in the read.me\r\nAPI_KEY = '###' \r\n\r\n#edit this path to point to yout install of python3\r\npath= '/python3 getSectorData.py'\r\n\r\n#number of the running hours of the script\r\nhours=12\r\n#######build connector#######################\r\ncnx=mysql.connector.connect(user='###',password='###',host='localhost',database='stock')\r\ncursor = cnx.cursor()\r\ncnx.database ='stock' \r\n\r\n\r\n\r\n#gets Sektor (S&P500 based on stocksymbol of of database)\r\ndef getSectorByBrand(symbol):\r\n query = \"\"\"select sector.sector_id, sector.sector_name \r\n from brand \r\n inner join sector on brand.fk_sector = sector.sector_id \r\n where brand.brandshort = '{symbol}'\"\"\"\r\n\r\n cursor.execute(query.format(symbol=symbol))\r\n result=cursor.fetchall()\r\n sectornumber=0\r\n sectorname='hi'\r\n for row in result:\r\n return (row[0], row[1])\r\n\r\n\r\ndef getSectorData(sector_name, sectornumber):\r\n url= 'https://www.tradingview.com/markets/indices/quotes-snp/'\r\n page = requests.get(url).content\r\n soup = BeautifulSoup(page, 'lxml')\r\n liste=soup.body.find(id=\"js-screener-container\").find_all('div', recursive=False)[0].find(\"table\").find(\"tbody\").find_all(\"tr\")[int(sectornumber)-67].find_all(\"td\")[1]\r\n kurs=liste.get_text()\r\n print(kurs)\r\n #####get timestamp###########\r\n ts = time.time()\r\n st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\r\n\r\n #####save data#####\r\n format_str = \"\"\"\r\n INSERT INTO sector_intra(timestamp, fk_sector, points)\r\n VALUES('{timestamp}', '{sector_id}', '{test}'\r\n );\"\"\"\r\n sql_command=format_str.format(timestamp=st, sector_id=sectornumber, test=kurs)\r\n cursor.execute(sql_command)\r\n cnx.commit()\r\n\r\n\r\nprint(symbol)\r\nsectornumber, sector_name= getSectorByBrand(symbol)\r\nprint(sector_name )\r\nprint(sectornumber)\r\ngetSectorData(sector_name, sectornumber)\r\ndef getStockData(symbol):\r\n r = requests.get('https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=' + symbol + '&interval=1min&apikey=' + API_KEY)\r\n if (r.status_code == 200):\r\n print( \"status 200 all good\")\r\n \r\n ergebnis = r.json()\r\n #print(ergebnis)\r\n ein=ergebnis['Time Series (1min)']\r\n df=pd.DataFrame(ein)\r\n df=df.transpose()\r\n format_str = \"\"\"\r\n INSERT INTO stock_intra(timestamp, fk_brand, open, high, low, close, volume)\r\n VALUES('{timestamp}', '{symbol}', '{hey}', '{high}', '{low}', '{close}', '{volume}'\r\n );\"\"\"\r\n for index, row in df.iterrows():\r\n try:\r\n print(\"Data for \"+ str(symbol) + \" open: \" +str(row[\"1. open\"]))\r\n sql_command=format_str.format(timestamp=index, symbol=symbol, hey=row[\"1. open\"], high=row[\"2. high\"], low=row[\"3. low\"], close=row[\"4. close\"], volume=row[\"5. volume\"])\r\n cursor.execute(sql_command)\r\n cnx.commit()\r\n except mysql.connector.errors.IntegrityError as e:\r\n print(\"This Data already exists in Table\")\r\n\r\nprint(symbol)\r\nx=1\r\nwhile(x < hours):\r\n getStockData(symbol)\r\n subprocess.call(shlex.split(path + symbol))\r\n x+=1\r\n time.sleep(3600)\r\n print('1 hour over')\r\n\r\ncursor.close()\r\ncnx.close()\r\n \r\n \r\n \r\n","sub_path":"getStockData.py","file_name":"getStockData.py","file_ext":"py","file_size_in_byte":3649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"570937","text":"import cv2\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\n# Plotting with OpenCV\n\n# cv.read('imagefile.extension', parameters)\n# IMREAD_COLOR for everything but the alpha channel\n# IMREAD_UNCHANGED for the raw picture\n# Parameters can also be numbers: 1 == COLOR, 0 == GRAYSCALE, -1 == UNCHANGED\nimg = cv2.imread('netero.jpg', cv2.IMREAD_GRAYSCALE)\ncv2.imshow('image', img)\ncv2.waitKey(0) # Wait until any key is pressed\ncv2.destroyAllWindows() # Close all windows\n\n\n# Plotting with matplotlib\nplt.imshow(img, cmap = 'gray', interpolation = 'bicubic')\nplt.xticks([]), plt.yticks([]) # hide values on X and Y axis\nplt.plot([200, 300, 400], [100, 200, 300], 'c', linewidth = 5) # Draw a line\nplt.show()\n\ncv2.imwrite('netero_1.png', img) # save an image\n","sub_path":"opencv_examples/first_tutorial.py","file_name":"first_tutorial.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"194566044","text":"\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n nodes = []\n first = head\n while head is not None:\n nodes.append(head)\n head = head.next\n\n remove_node = nodes[-n]\n\n if n == len(nodes):\n return remove_node.next\n else:\n pre_node = nodes[-(n+1)]\n pre_node.next = remove_node.next\n\n return first","sub_path":"p19.py","file_name":"p19.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"176689719","text":"from os import path\nimport subprocess\nTHIS_FOLDER=path.abspath(path.dirname(__file__))\n\ndef create_session_on_server(host,email):\n return subprocess.check_output(\n [\n 'fab',\n 'create_session_on_server:emai={}'.format(email),\n '--host={}'.format(host),\n '--hide=everything,status',\n ],\n cwd=THIS_FOLDER\n ).decode().strip()\n\ndef reset_database(host):\n subprocess.check_call(\n ['fab','reset_database','--host={}'.format(host)],\n cwd=THIS_FOLDER\n )\n","sub_path":"functional_tests/server_tools.py","file_name":"server_tools.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"469799566","text":"from tkinter import *\nfrom PIL import ImageGrab\nimport urllib.request\nimport json\nimport ctypes\nimport cv2\nfrom skimage.feature import hog\nimport numpy as np\n\n\nclass Paint(object):\n\n def __init__(self):\n self.root = Tk()\n\n self.save_button = Button(self.root, text='Save', command=self.save_image)\n self.save_button.grid(row=0, column=0)\n\n self.c = Canvas(self.root, bg='white', width=200, height=200)\n self.c.grid(row=1, columnspan=5)\n\n self.setup()\n self.root.mainloop()\n\n def setup(self):\n self.old_x = None\n self.old_y = None\n self.line_width = 10\n self.color = 'black'\n self.c.bind('', self.paint)\n self.c.bind('', self.reset)\n\n def paint(self, event):\n if self.old_x and self.old_y:\n self.c.create_line(self.old_x, self.old_y, event.x, event.y,\n width=self.line_width, fill=self.color,\n capstyle=ROUND, smooth=TRUE, splinesteps=36)\n self.old_x = event.x\n self.old_y = event.y\n\n def save_image(self):\n x2 = self.root.winfo_rootx() + self.c.winfo_x()\n y2 = self.root.winfo_rooty() + self.c.winfo_y()\n x1 = x2 + self.c.winfo_width()\n y1 = y2 + self.c.winfo_height()\n ImageGrab.grab().crop((x2, y2, x1, y1)).save(\"./image.jpg\")\n self.root.quit()\n\n def reset(self, event):\n self.old_x, self.old_y = None, None\n\nPaint()\nimage = cv2.imread(\"image.jpg\", cv2.IMREAD_GRAYSCALE)\nimage = cv2.bitwise_not(image)\nimage = cv2.resize(image, (28, 28))\n\n\nfd = hog(image.reshape((28, 28)), orientations=9, pixels_per_cell=(14, 14), cells_per_block=(1, 1), visualize=False)\nhog_features = np.array(fd, 'float64')\n\ndata = {\n \"Inputs\": {\n \"input1\":\n [\n {\n 'v1': hog_features[0],\n 'v2': hog_features[1],\n 'v3': hog_features[2],\n 'v4': hog_features[3],\n 'v5': hog_features[4],\n 'v6': hog_features[5],\n 'v7': hog_features[6],\n 'v8': hog_features[7],\n 'v9': hog_features[8],\n 'v10': hog_features[9],\n 'v11': hog_features[10],\n 'v12': hog_features[11],\n 'v13': hog_features[12],\n 'v14': hog_features[13],\n 'v15': hog_features[14],\n 'v16': hog_features[15],\n 'v17': hog_features[16],\n 'v18': hog_features[17],\n 'v19': hog_features[18],\n 'v20': hog_features[19],\n 'v21': hog_features[20],\n 'v22': hog_features[21],\n 'v23': hog_features[22],\n 'v24': hog_features[23],\n 'v25': hog_features[24],\n 'v26': hog_features[25],\n 'v27': hog_features[26],\n 'v28': hog_features[27],\n 'v29': hog_features[28],\n 'v30': hog_features[29],\n 'v31': hog_features[30],\n 'v32': hog_features[31],\n 'v33': hog_features[32],\n 'v34': hog_features[33],\n 'v35': hog_features[34],\n 'v36': hog_features[35],\n }\n ],\n },\n \"GlobalParameters\": {\n }\n}\n\nbody = str.encode(json.dumps(data))\n\nurl = 'https://ussouthcentral.services.azureml.net/workspaces/b43bf2017b544bdfbbf8a6c7e0d270ac/services/4000b3d23e8046bc9f74a6f4cd704468/execute?api-version=2.0&format=swagger'\napi_key = '0EPEfQh8CtzdFhlGfyvLRBM69BVMRaEo/YuUHfKw6V7qwKVEB2gI0b0dGyYnNS3ltL6mby6/3JQwhsyD9+LCzw==' # Replace this with the API key for the web service\nheaders = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}\n\nreq = urllib.request.Request(url, body, headers)\n\ntry:\n response = urllib.request.urlopen(req)\n\n result = response.read()\n # Our prediction is always the 6th element from behind in decoded string\n decode = result.decode('utf-8')\n ctypes.windll.user32.MessageBoxW(0, \"Digit predicted: \" + decode[-6], \"Prediction\", 0)\n\nexcept urllib.error.HTTPError as error:\n print(\"The request failed with status code: \" + str(error.code))\n\n # Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure\n print(error.info())\n print(json.loads(error.read().decode(\"utf8\", 'ignore')))\n","sub_path":"drawing.py","file_name":"drawing.py","file_ext":"py","file_size_in_byte":4943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"265906415","text":"# python3 configmap2secrets.py ../../kube/config/dev/internal-resources-cm.yml \nimport base64\nfrom pathlib import Path\nimport sys\nimport ruamel.yaml\nfrom ruamel.yaml.comments import CommentedMap as OrderedDict # to avoid '!!omap' in yaml\n\ninput_file = Path(sys.argv[1])\n\nyaml = ruamel.yaml.YAML()\nyaml.compact(seq_seq=False, seq_map=True)\nyaml.default_flow_style = False\nyaml.explicit_start = True\nyaml.preserve_quotes = True\nyaml.indent(mapping=2, sequence=2, offset=0)\nyaml.version = (1, 2)\n\nL = [D for D in yaml.load_all(input_file)]\n\nfor D in L:\n if D.get('kind') == 'ConfigMap':\n OD = OrderedDict()\n for k, v in D.get('data').items():\n OD[k] = base64.b64encode(v.encode('ascii')).decode('ascii')\n \n D['kind'] = 'Secret'\n D['data'] = OD\n \nyaml.dump_all(L, stream=sys.stdout)\n","sub_path":"scripts/configmap2secret/configmap2secret.py","file_name":"configmap2secret.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"429762764","text":"import numpy as np\nimport Globals\nfrom GetBdetJ import GetBdetJ\nfrom GetStress import GetStress\nfrom GetD import GetD\n\n\n#---------------------------------------------------------\n# Funcao que retorna residuo e Matriz Tg de Hexa8\n#---------------------------------------------------------\ndef ComputeResidualKT():\n Globals.R[:] = 0.0\n Globals.KT[:] = 0.0\n\n # Pontos de integracao do elemento\n a = 1.0 / np.sqrt(3.0)\n PInt = np.array([\n [-a, -a, -a],\n [ a, -a, -a],\n [ a, a, -a],\n [-a, a, -a],\n [-a, -a, a],\n [ a, -a, a],\n [ a, a, a],\n [-a, a, a],\n ])\n WInt = 1\n\n # 2. Dimensiona vetores de elemento\n # UEl = zeros(24,1)\n # LMEl = zeros(24,1)\n # CoordEl = zeros(8,3)\n # IncidEl = zeros(8)\n KTEl = np.zeros(shape=(24, 24))\n FIntEl = np.zeros(shape=(24,))\n\n # 4. Inicializa Residuo\n Globals.R = -Globals.FExt\n\n # 5. Loop sobre elementos\n for e in range(Globals.NumElem):\n # 5. Captura valores elementares\n IncidEl = Globals.Incid[e, :]\n CoordEl = Globals.Coord[IncidEl, :]\n LMEl = np.array(Globals.LM[e, :], dtype=int)\n UEl = Globals.U[LMEl]\n FIntEl[0:24] = 0\n KTEl[0:24, 0:24] = 0 \n\n # 6. Loop sobre pontos de integracao\n from_i = 0\n to_i = 6\n for ip in range(Globals.NPInt):\n # Inicializa contador e variaveis\n EpleqIp0 = Globals.Epleq0[e, ip]\n EplIp0 = Globals.Epl0[e, from_i:to_i]\n Beta = Globals.Beta[e, from_i:to_i]\n pint = PInt[ip, :]\n\n # Calcula deformacao total e trial\n B, DetJ = GetBdetJ(pint, CoordEl)\n Etot = np.dot(B, UEl)\n\n # Calcula tensao e matriz elastoplastica\n StressIp, EplIp1, EpleqIp1, DEpleqIp, Beta, η_tr, q_tr = GetStress(\n Etot,\n EplIp0,\n EpleqIp0,\n Beta\n )\n D = GetD(StressIp, DEpleqIp, EpleqIp1, η_tr, q_tr)\n\n if e == 0 and ip == 0:\n Globals.εp_acc_list.append(EpleqIp1)\n\n # Insere forca interna e rigidez nas matrizes\n FIntEl = FIntEl + np.dot(B.T, StressIp.T) * DetJ * WInt\n KTEl = KTEl + np.dot(np.dot(B.T, D), B) * DetJ * WInt \n\n # Coloca valores do IP no vetor\n Globals.Epleq1[e, ip] = EpleqIp1\n Globals.Epl1[e, from_i:to_i] = EplIp1\n Globals.DEpleq[e, ip] = DEpleqIp\n Globals.Stress[e, from_i:to_i] = StressIp\n Globals.Beta[e, from_i:to_i] = Beta\n\n # Atualiza contador\n from_i += 6\n to_i += 6\n\n Globals.R[LMEl] += FIntEl[0:24]\n Globals.KT[LMEl] += KTEl\n","sub_path":"ComputeResidualKT.py","file_name":"ComputeResidualKT.py","file_ext":"py","file_size_in_byte":2758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"218833372","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\nimport sqlite3 as lite\r\nimport codecs\r\nimport os\r\n\r\ndef loaddata(con, archive, insert):\r\n\tcursor= con.cursor()\r\n\tf = codecs.open(archive, \"r\", \"ISO-8859-1\")\r\n\tcount = 0\r\n\tcount1= 0\r\n\trow=[]\t\r\n\tfor line in f:\r\n\t\tlinea1=line.find(' 1 and count < 17:\t\t\t\t\r\n\t\t\t\tif line.find('')!=-1:\t\t\t\t\t\r\n\t\t\t\t\tif row[2]=='ARABA':\r\n\t\t\t\t\t\tcursor.execute(insert, row)\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\trow=[]\r\n\t\t\t\t\tcount=0;\t\t\t\t\t\r\n\t\t\t\telse:\t\t\t\t\t\r\n\t\t\t\t\tinicio=line.find('>')\r\n\t\t\t\t\tfinal=line.find(']+>)?\\s*phpBB'},\n {'regexp': ']+name=\"copyright\"[^>]+value=\"[^>]*phpBB'},\n {'text': 'We request you retain the full copyright notice below '\n 'including the link to www.phpbb.com'},\n {'regexp': ']+id=\"phpbb\"'},\n {'text': 'phpBB style name:'},\n {'regexp': '(?mis)]+class=\"copyright\">[^>]*]+>\\s*phpBB'},\n ]\n","sub_path":"bot_detector/plugins/phpbb.py","file_name":"phpbb.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"350227538","text":"import sys\nimport flask_api\nfrom flask import request, g, jsonify, Response\nfrom flask_api import FlaskAPI,status, exceptions\nimport sqlite3\n\napp = FlaskAPI(__name__) \n\ndef get_db():\n\tdb = getattr(g,'_database', None)\n\tif db is None:\n\t\tdb = g._database = sqlite3.connect('music.db')\n\treturn db\n\n\n@app.route(\"/descriptions//\",methods=['GET'])\ndef get_descbyuser(track,user_name):\n\ttry:\n\t\tsqlQry = \"select C.track_title,A.user_name,A.track_desc from descriptions A, users B, tracks C where a.user_name = b.user_name and c.track_id = a.track_id and c.track_title = '%s' and a.user_name = '%s'\" %(track,user_name)\n\t\tdb = get_db()\n\t\trs = db.execute(sqlQry)\n\t\tres = rs.fetchall()\n\t\trs.close()\n\n\texcept Exception as e:\n \treturn { 'error': str(e) }, status.HTTP_404_NOTFOUND\n\t\n\treturn jsonify(list(res)), status.HTTP_200_OK\n\n\n@app.route(\"/descriptions\",methods=['POST'])\ndef create_trackdesc():\n\tmandatory_fields = ['track_title','user_name','track_description']\n\n\tif not all([field in request.data for field in mandatory_fields]):\n \traise exceptions.ParseError()\n\ttry:\n\t\ttrack_title = request.data.get('track_title','')\n\t\tuser_name = request.data.get('user_name','')\n\t\ttrack_desc = request.data.get('track_description','')\n\t\t\n\t\tsqlQry = \"insert into descriptions(user_name,track_id,track_desc) values ('%s',(select track_id from tracks where track_title='%s'),'%s')\" %(user_name,track_title,track_desc)\t\n\t\tdb = get_db()\n\t\tdb.execute(sqlQry)\n\t\tdb.commit()\n\t\tresponse = Response(status=201)\n\t\tresponse.headers['location'] = '/descriptions/'+track_title+'/'+user_name\n\t\tresponse.headers['status'] = '201 Created'\n\texcept Exception as e:\n \treturn { 'error': str(e) }, status.HTTP_404_NOTFOUND\n\n\treturn response, status.HTTP_201_CREATED\n\n\nif __name__ == \"__main__\":\n\tapp.run(debug=True)\n\t","sub_path":"descriptions.py","file_name":"descriptions.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"245744239","text":"# Give a variable the name \"Starting Tile\" \n# Give a variable the name \"Starting Tile\" \n# Give option of movement.\n# When user moves the variable changes to the tile he is placed in and the loop starts again.\n# if user tries to use movement not available print (\"Not a valid direction\")\n# When user arrives in tile 3.1 print (\"Victory\") and end the loop.\n\nN = \"(N)orth\"\nE = \"(E)ast\"\nS = \"(S)outh\"\nW = \"(W)est\"\n\ncurrent_tile = 1.1\n\ndef move(movement, tile):\n if movement == \"n\" or movement == \"N\":\n tile += 0.1\n\n if movement == \"e\" or movement == \"E\":\n tile += 1\n \n if movement == \"s\" or movement == \"S\":\n tile -= 0.1\n \n if movement == \"w\" or movement == \"W\":\n tile -= 1\n\n return round(tile, 1)\n\ndef get_valid_movement(tile):\n if tile == 1.1 or tile == 2.1 or tile == 3.1:\n travel = \"You can travel: {}.\".format(N)\n\n if tile == 1.2:\n travel = \"You can travel: {} or {} or {}.\".format(N, E, S)\n\n if tile == 1.3:\n travel = \"You can travel: {} or {}.\".format(E, S)\n \n if tile == 2.3:\n travel = \"You can travel: {} or {}.\".format(E, W)\n \n if tile == 2.2 or tile == 3.3:\n travel = \"You can travel: {} or {}.\".format(S, W)\n\n if tile == 3.2:\n travel = \"You can travel: {} or {}.\".format(N, S)\n\n return travel\n\ndef is_valid_movement(movement, tile):\n movement = movement.lower()\n if tile == 1.1 or tile == 2.1 or tile == 3.1:\n if movement == \"n\":\n return True\n\n if tile == 1.2:\n if movement != \"w\":\n return True\n\n if tile == 1.3:\n if movement == \"e\" or movement == \"s\":\n return True\n \n if tile == 2.3:\n if movement == \"e\" or movement == \"w\":\n return True\n \n if tile == 2.2 or tile == 3.3:\n if movement == \"s\" or movement == \"w\":\n return True\n\n if tile == 3.2:\n if movement == \"n\" or movement == \"s\":\n return True\n else:\n return False\n\n\nwhile True:\n if current_tile== 3.1:\n print(\"Victory!\")\n break\n\n print(get_valid_movement(current_tile))\n \n direction = input(\"Direction: \")\n\n if is_valid_movement(direction, current_tile) == False:\n print(\"Not a valid direction!\")\n\n if is_valid_movement(direction, current_tile) == True:\n current_tile = move(direction, current_tile)","sub_path":"TileTraveller.py","file_name":"TileTraveller.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"593642953","text":"import gym\nfrom gym.utils import seeding\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib.colors import to_rgb\nfrom matplotlib import animation\nimport os\nimport imageio\nimport warnings\nimport copy\n\nimport dps\nfrom dps import cfg\nfrom dps.utils import square_subplots, generate_perlin_noise_2d, Config, Param, Parameterized, resize_image\nfrom dps.utils.tf import RenderHook\nfrom dps.env.env import BatchGymEnv\n\n\nclass Entity(object):\n masks = {}\n images = {}\n\n def __init__(self, appearance=\"plus\", color=\"white\", shape=(1, 1), position=(0, 0), z=None, reward=0, **kwargs):\n self.appearance = appearance\n\n if isinstance(color, str):\n color = color.split()\n self.color = np.random.choice(color)\n\n try:\n shape = tuple(shape)\n except (ValueError, TypeError):\n shape = (float(shape), float(shape))\n self.h, self.w = shape\n self.top, self.left = position\n\n self.alive = True\n self.z = np.random.rand() if z is None else z\n self.reward = reward\n\n for k, v in kwargs.items():\n setattr(self, k, v)\n\n def reset(self):\n self.alive = True\n\n def get_appearance(self):\n key = (self.color, self.h, self.w)\n image = Entity.images.get(key, None)\n\n if image is None:\n color_array = np.array(to_rgb(self.color))[None, None, :]\n image = Entity.images[key] = np.tile(color_array, (self.h, self.w, 1))\n\n key = (self.appearance, self.h, self.w)\n mask = Entity.masks.get(key, None)\n\n if mask is None:\n f = os.path.join(os.path.dirname(dps.__file__), \"shapes\", \"{}.png\".format(self.appearance))\n mask = imageio.imread(f)\n mask = mask[:, :, 3:]\n mask = resize_image(mask, (self.h, self.w))\n mask = Entity.masks[key] = mask / 255.\n\n noise_res = getattr(self, \"noise_res\", None)\n if noise_res is not None:\n noise = generate_perlin_noise_2d(self.shape, self.noise_res, normalize=True)\n mask = mask * noise[:, :, None]\n\n return image, mask\n\n @property\n def shape(self):\n return (self.h, self.w)\n\n @shape.setter\n def shape(self, _shape):\n self.h, self.w = _shape\n\n @property\n def position(self):\n return (self.top, self.left)\n\n @position.setter\n def position(self, _position):\n self.top, self.left = _position\n\n @property\n def bottom(self):\n return self.top + self.h\n\n @property\n def right(self):\n return self.left + self.w\n\n @property\n def y(self):\n return self.top + self.h / 2\n\n @y.setter\n def y(self, _y):\n self.top = _y - self.h / 2\n\n @property\n def x(self):\n return self.left + self.w / 2\n\n @x.setter\n def x(self, _x):\n self.left = _x - self.w / 2\n\n @property\n def center(self):\n return (self.y, self.x)\n\n @center.setter\n def center(self, _center):\n self.y, self.x = _center\n\n @property\n def area(self):\n return self.h * self.w\n\n def intersects(self, r2):\n return self.overlap_area(r2) > 0\n\n def overlap_area(self, r2):\n overlap_bottom = np.minimum(self.bottom, r2.bottom)\n overlap_top = np.maximum(self.top, r2.top)\n\n overlap_right = np.minimum(self.right, r2.right)\n overlap_left = np.maximum(self.left, r2.left)\n\n area = np.maximum(overlap_bottom - overlap_top, 0) * np.maximum(overlap_right - overlap_left, 0)\n return area\n\n def __str__(self):\n return \"<{} - ({}:{}, {}:{}), alive={}, z={}, appearance={}, color={}>\".format(\n self.__class__, self.top, self.bottom, self.left, self.right, self.alive, self.z, self.appearance, self.color)\n\n def __repr__(self):\n return str(self)\n\n def act(self, game):\n pass\n\n\ndef liang_barsky(bottom, top, left, right, y0, x0, y1, x1):\n assert bottom < top\n assert left < right\n\n dx = x1 - x0\n dy = y1 - y0\n\n checks = ((-dx, -(left - x0)),\n (dx, right - x0),\n (-dy, -(bottom - y0)),\n (dy, top - y0))\n\n out_in = [0]\n in_out = [1]\n\n for p, q in checks:\n if p == 0 and q < 0:\n return None\n\n if p != 0:\n target_list = out_in if p < 0 else in_out\n target_list.append(q / p)\n\n _out_in = max(out_in)\n _in_out = min(in_out)\n\n if _out_in < _in_out:\n return _out_in, _in_out\n else:\n return None\n\n\nNoAnswer = object()\n\n\ndef _test_liang_barsky(*args, ref_answer=NoAnswer):\n answer = liang_barsky(*args)\n print(\"{}: {}\".format(args, answer))\n\n if ref_answer is not NoAnswer:\n assert answer == ref_answer\n\n\n# if __name__ == \"__main__\":\n# _test_liang_barsky(1, 2, 1, 2, 1.5, 0.5, 1.5, 2.5, ref_answer=(1/4, 3/4))\n# _test_liang_barsky(1, 2, 1, 2, 1.5, 0.5, 1.5, .99, ref_answer=None)\n# _test_liang_barsky(1, 2, 1, 2, 1.5, 0.5, 1.5, 1, ref_answer=None)\n# _test_liang_barsky(1, 2, 1, 2, 1.5, 0.5, 1.5, 1.01, ref_answer=(0.5 / 0.51, 1))\n# _test_liang_barsky(1, 2, 1, 2, 1.5, 0.5, -1.5, -2.5, ref_answer=None)\n# _test_liang_barsky(1, 2, 1, 2, 2.5, 0.5, 2.5, 2.5, ref_answer=None)\n# _test_liang_barsky(1, 2, 1, 2, 0.5, 2.5, 2.5, 2.5, ref_answer=None)\n# _test_liang_barsky(1, 2, 1, 2, 0, 0, 2, 2, ref_answer=(0.5, 1))\n# _test_liang_barsky(1, 2, 1, 2, 0, .99, 2, 2.99, ref_answer=(0.5, 0.505))\n# _test_liang_barsky(1, 2, 1, 2, 1.5, 1.5, 3, 3, ref_answer=(0, 1/3))\n\n\nclass Rectangle(object):\n def __init__(self, bottom, top, left, right):\n self.bottom = bottom\n self.top = top\n self.left = left\n self.right = right\n\n def collision(self, y0, x0, y1, x1):\n return liang_barsky(self.bottom, self.top, self.left, self.right, y0, x0, y1, x1)\n\n\nclass Ellipse(object):\n def __init__(self, cy, cx, y_radius, x_radius):\n self.cy = cy\n self.cx = cx\n self.y_radius_2 = y_radius**2\n self.x_radius_2 = x_radius**2\n\n def collision(self, y0, x0, y1, x1):\n y0 -= self.cy\n y1 -= self.cy\n x0 -= self.cx\n x1 -= self.cx\n\n a = (y1 - y0)**2 / self.y_radius_2 + (x1 - x0)**2 / self.x_radius_2\n b = 2 * ((y1 - y0) * y0 / self.y_radius_2 + (x1 - x0) * x0 / self.x_radius_2)\n c = y0**2 / self.y_radius_2 + x0**2 / self.x_radius_2 - 1\n\n disc = b**2 - 4 * a * c\n if disc <= 0:\n return None\n\n sqrt_disc = np.sqrt(disc)\n t1 = (-b - sqrt_disc) / (2*a)\n t2 = (-b + sqrt_disc) / (2*a)\n\n if t2 * t1 < 0: # start inside\n t1 = 0\n else: # start outside\n if t1 < 0: # Line segment points away from circle\n return None\n if t1 > 1: # Line segment doesn't go far enough\n return None\n\n t2 = min(1, t2)\n\n return (t1, t2)\n\n\nclass ObjectGame(Parameterized, gym.Env):\n \"\"\"\n\n Handles collision detection and scene rendering. Subclass takes care of the rest.\n\n Subclasses must implement:\n\n setup_field\n move_entities\n resolve_collision\n get_entity_features\n\n And optionally:\n\n compute_reward\n\n \"\"\"\n metadata = {'render.modes': ['human']}\n\n image_shape = Param()\n background_colour = Param()\n max_episode_length = Param()\n image_obs = Param()\n max_entities = Param()\n\n def __init__(\n self, action_space=None, reward_range=None, entity_feature_dim=None, **kwargs):\n\n colour = to_rgb(self.background_colour)\n colour = np.array(colour)[None, None, :]\n self.background_colour = colour\n\n assert action_space is not None\n self.action_space = action_space\n\n assert reward_range is not None\n self.reward_range = reward_range\n\n assert entity_feature_dim is not None\n self.entity_feature_dim = entity_feature_dim\n\n if self.image_obs:\n self.observation_space = gym.spaces.Box(0, 1, shape=(*self.image_shape, 3), dtype=np.float32)\n else:\n self.observation_space = gym.spaces.Box(\n 0, 1, shape=(self.max_entities, 5 + self.entity_feature_dim), dtype=np.float32)\n\n self.seed()\n self.reset()\n self.viewer = None\n\n def setup_field(self):\n \"\"\" Return a list of entities. \"\"\"\n raise Exception(\"NotImplemented\")\n\n def move_entities(self, action):\n \"\"\" Call `self._move_entity` for each movement. Return reward. \"\"\"\n raise Exception(\"NotImplemented\")\n\n def resolve_collision(self, mover, other):\n \"\"\" Return (kill, stop, reward) \"\"\"\n raise Exception(\"NotImplemented\")\n\n def get_entity_features(entity):\n \"\"\" Compute features for an entity. \"\"\"\n raise Exception(\"NotImplemented\")\n\n def compute_reward(self):\n \"\"\" Compute an additional reward based on final location of entities. \"\"\"\n return 0.0\n\n def get_image(self):\n image = np.ones((*self.image_shape, 3)) * self.background_colour\n\n sorted_entities = sorted(self.entities, key=lambda x: x.z)\n\n for entity in sorted_entities:\n if not entity.alive:\n continue\n\n _image, _alpha = entity.get_appearance()\n\n top = int(entity.top)\n bottom = top + int(entity.h)\n\n left = int(entity.left)\n right = left + int(entity.w)\n\n image[top:bottom, left:right, ...] = (\n _alpha * _image + (1 - _alpha) * image[top:bottom, left:right, ...])\n\n return image\n\n def get_entities(self):\n height, width = self.image_shape\n representation = np.zeros((self.max_entities, 5 + self.entity_feature_dim))\n\n entities = np.random.permutation(self.entities)\n\n i = 0\n for entity in entities:\n if not entity.alive:\n continue\n\n features = self.get_entity_features(entity)\n\n representation[i, :] = (\n (1.0, entity.top/height, entity.left/width, entity.h, entity.w,) + tuple(features)\n )\n\n i += 1\n\n return representation\n\n def _move_entity(self, entity, y_step, x_step):\n # For each entity, compute the time of intercept.\n\n h, w = entity.h, entity.w\n\n obstacles = []\n for other in self.entities:\n y, x = other.center\n\n shape = Ellipse(y, x, h/2, w/2)\n\n # obstacles.append((other, (y - h / 2, y + h / 2, x - w / 2, x + w / 2)))\n obstacles.append((other, shape))\n\n # walls\n obstacles.append((\"top\", Rectangle(-np.inf, np.ceil(entity.h / 2), -np.inf, np.inf)))\n obstacles.append((\"bottom\", Rectangle(self.image_shape[0] - np.ceil(entity.h)/2, np.inf, -np.inf, np.inf)))\n obstacles.append((\"left\", Rectangle(-np.inf, np.inf, -np.inf, np.ceil(entity.w)/2)))\n obstacles.append((\"right\", Rectangle(-np.inf, np.inf, self.image_shape[1] - np.ceil(entity.w)/2, np.inf)))\n\n y, x = entity.y, entity.x\n\n collisions = []\n for other, shape in obstacles:\n if entity is other:\n continue\n\n alive = getattr(other, \"alive\", True)\n if not alive:\n continue\n\n collision = shape.collision(y, x, y + y_step, x + x_step)\n # collision = liang_barsky(top, bottom, left, right, y, x, y + y_step, x + x_step)\n\n if collision is not None:\n collisions.append((collision, other))\n\n collisions = sorted(collisions, key=lambda x: x[0])\n\n total_reward = 0\n\n stop = False\n for (start, end), other in collisions:\n kill, stop, reward = self.resolve_collision(entity, other)\n\n if kill:\n other.alive = False\n\n total_reward += reward\n\n if stop:\n entity.y = y + (start-1e-6) * y_step\n entity.x = x + (start-1e-6) * x_step\n\n break\n\n if not stop:\n entity.y = y + y_step\n entity.x = x + x_step\n\n return total_reward\n\n def step(self, action):\n reward = self.move_entities(action)\n reward += self.compute_reward()\n\n info = {}\n self._step += 1\n\n if self.image_obs:\n obs = self.get_image()\n info['entities'] = self.get_entities()\n else:\n obs = self.get_entities()\n info['image'] = self.get_image()\n\n done = bool(self.max_episode_length) and self._step >= self.max_episode_length\n\n return obs, reward, done, info\n\n def reset(self):\n '''Clear entities and state, call setup_field()'''\n self.entities = self.setup_field()\n self._step = 0\n if self.image_obs:\n obs = self.get_image()\n else:\n obs = self.get_entities()\n return obs\n\n def render(self, mode='human', close=False):\n if close:\n return\n\n plt.ion()\n if self.viewer is None:\n self.viewer = plt.imshow(self.get_image())\n self.viewer.set_data(self.get_image())\n plt.pause(1)\n\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n\ndef sample_entities(image_shape, patch_shapes, max_overlap=None, size_std=None, masks=None):\n if len(patch_shapes) == 0:\n return []\n\n patch_shapes = np.array(patch_shapes)\n n_rects = patch_shapes.shape[0]\n\n rects = []\n\n for i in range(n_rects):\n n_tries = 0\n while True:\n if size_std is None:\n shape_multipliers = 1.\n else:\n shape_multipliers = np.maximum(np.random.randn(2) * size_std + 1.0, 0.5)\n\n m, n = np.ceil(shape_multipliers * patch_shapes[i, :2]).astype('i')\n\n position = (\n np.random.randint(0, image_shape[0]-m+1),\n np.random.randint(0, image_shape[1]-n+1))\n\n rect = Entity(position=position, shape=(m, n))\n\n mask_valid = True\n if masks is not None:\n mask_idx_y = int(masks[i].shape[0] * rect.center[0] / image_shape[0])\n mask_idx_x = int(masks[i].shape[1] * rect.center[1] / image_shape[1])\n mask_valid = masks[i][mask_idx_y, mask_idx_x] > 0.5\n\n if mask_valid:\n if max_overlap is None:\n rects.append(rect)\n break\n else:\n violation = False\n for r in rects:\n min_area = min(rect.area, r.area)\n if rect.overlap_area(r) / min_area > max_overlap:\n violation = True\n break\n\n if not violation:\n rects.append(rect)\n break\n\n n_tries += 1\n\n if n_tries > 10000:\n warnings.warn(\n \"Could not fit rectangles. \"\n \"(n_rects: {}, image_shape: {}, max_overlap: {})\".format(\n n_rects, image_shape, max_overlap))\n break\n\n return rects\n\n\nclass CollectionGame(ObjectGame):\n agent_spec = Param()\n entity_specs = Param()\n\n step_size = Param()\n min_entities = Param()\n max_overlap = Param()\n grid = Param()\n corner = Param()\n\n def __init__(self, **kwargs):\n self.agent_spec = copy.deepcopy(self.agent_spec)\n self.agent_spec['idx'] = 0\n\n self.entity_specs = copy.deepcopy(self.entity_specs)\n for i, es in enumerate(self.entity_specs):\n es['idx'] = i + 1\n\n entity_logits = np.array([es.get('logit', 1) for es in self.entity_specs])\n self.entity_dist = np.exp(entity_logits) / np.exp(entity_logits).sum()\n\n super(CollectionGame, self).__init__(\n action_space=gym.spaces.Box(low=np.array([-1, -1, 0]), high=np.array([1, 1, 1]), dtype=np.float32),\n reward_range=(-10, 10),\n entity_feature_dim=len(self.entity_specs)+1,\n **kwargs)\n\n def setup_field(self):\n n_entities = np.random.randint(self.min_entities-1, self.max_entities)\n\n if self.corner is not None:\n shape = (self.image_shape[0]/2, self.image_shape[1]/2)\n if self.corner == \"top_left\":\n mask_entity = Entity(position=(0, 0), shape=shape)\n elif self.corner == \"top_right\":\n mask_entity = Entity(position=(0, self.image_shape[1]/2), shape=shape)\n elif self.corner == \"bottom_left\":\n mask_entity = Entity(position=(self.image_shape[0]/2, 0), shape=shape)\n elif self.corner == \"bottom_right\":\n mask_entity = Entity(position=(self.image_shape[0]/2, self.image_shape[1]/2), shape=shape)\n else:\n raise Exception(\"Unknown value for `corner`: {}\".format(self.corner))\n\n if self.grid:\n n_per_row = int(round(np.sqrt(n_entities)))\n n_entities = n_per_row ** 2\n center_spacing_y = self.image_shape[0] / n_per_row\n center_spacing_x = self.image_shape[1] / n_per_row\n\n agent = Entity(**self.agent_spec)\n agent.top = np.random.randint(self.image_shape[0]-agent.h)\n agent.left = np.random.randint(self.image_shape[1]-agent.w)\n\n entities = [agent]\n\n for i in range(n_per_row):\n for j in range(n_per_row):\n y = center_spacing_y / 2 + center_spacing_y * i\n x = center_spacing_x / 2 + center_spacing_x * j\n\n spec_idx = np.random.choice(len(self.entity_specs), p=self.entity_dist)\n spec = self.entity_specs[spec_idx]\n entity = Entity(**spec)\n entity.top = y - entity.h / 2\n entity.left = x - entity.w / 2\n\n if self.corner is not None and not mask_entity.intersects(entity):\n continue\n\n self.entities.append(entity)\n else:\n spec_indices = np.random.choice(len(self.entity_specs), size=n_entities, replace=True, p=self.entity_dist)\n specs = [self.agent_spec] + [self.entity_specs[i] for i in spec_indices]\n shapes = [spec['shape'] for spec in specs]\n\n rectangles = sample_entities(self.image_shape, shapes, self.max_overlap)\n entities = [Entity(**spec) for spec in specs]\n for rect, entity in zip(rectangles, entities):\n entity.top = rect.top\n entity.left = rect.left\n\n if self.corner is not None:\n entities = entities[0] + [e for e in entities[1:] if e.intersects(mask_entity)]\n\n return entities\n\n def move_entities(self, action):\n y, x, magnitude = action\n y = np.clip(y, -1, 1)\n x = np.clip(x, -1, 1)\n magnitude = np.clip(magnitude, 0, 1)\n\n norm = np.sqrt(x**2 + y**2)\n if norm > 1e-6:\n y = self.step_size * magnitude * y / norm\n x = self.step_size * magnitude * x / norm\n else:\n y = x = 0\n\n return self._move_entity(self.entities[0], y, x)\n\n def resolve_collision(self, mover, other):\n \"\"\" Return (kill, stop, reward) \"\"\"\n if isinstance(other, str): # wall\n return (False, True, 0)\n else:\n return (True, False, other.reward)\n\n def get_entity_features(self, entity):\n return [int(entity.idx == i) for i in range(len(self.entity_specs) + 1)]\n\n\nclass Collection_RenderHook(RenderHook):\n def __init__(self, N=16):\n self.N = N\n\n def __call__(self, updater):\n plt.ion()\n for learner in updater.learners:\n with learner:\n rollouts = updater.env.do_rollouts(policy=learner.pi, n_rollouts=self.N, T=cfg.T, mode='val')\n\n if updater.env.gym_env.image_obs:\n obs = rollouts.obs\n else:\n obs = rollouts.image\n\n fig, axes = square_subplots(self.N, figsize=(5, 5))\n plt.subplots_adjust(top=0.95, bottom=0, left=0, right=1, wspace=0.1, hspace=0.1)\n\n images = []\n for i, ax in enumerate(axes.flatten()):\n ax.set_aspect(\"equal\")\n ax.set_axis_off()\n image = ax.imshow(np.zeros(obs.shape[2:]))\n images.append(image)\n\n def animate(t):\n for i in range(self.N):\n images[i].set_array(obs[t, i, :, :, :])\n\n anim = animation.FuncAnimation(fig, animate, frames=len(rollouts), interval=500)\n\n path = updater.exp_dir.path_for('plots', 'animation.gif') # Don't open gifs with VLC\n anim.save(path, writer='imagemagick')\n\n if cfg.show_plots:\n plt.show()\n\n plt.close(fig)\n\n\nclass RandomAgent(object):\n def __init__(self, action_space, persist_prob=0.0):\n self.action_space = action_space\n self.persist_prob = persist_prob\n self.action = None\n\n def act(self, observation):\n if self.action is None or np.random.rand() > self.persist_prob:\n self.action = self.action_space.sample()\n\n return self.action\n\n\ndef do_rollouts(env, agent, render=False, callback=None, n_rollouts=None):\n idx = 0\n while n_rollouts is None or idx < n_rollouts:\n obs = env.reset()\n\n if render:\n env.render()\n\n done = False\n while not done:\n action = agent.act(obs)\n new_obs, reward, done, info = env.step(action)\n\n if callback:\n callback(obs=obs, action=action, reward=reward, info=info, done=done, new_obs=new_obs)\n\n obs = new_obs\n\n if render:\n env.render()\n\n if callback and hasattr(callback, \"finished\") and callback.finished():\n return\n\n if done:\n break\n\n idx += 1\n\n\ndef build_env():\n gym_env = CollectionGame()\n return BatchGymEnv(gym_env=gym_env)\n\n\nentity_size = (5, 5)\n\nconfig = Config(\n env_name=\"collection_game\",\n\n build_env=build_env,\n T=20,\n max_episode_length=20,\n\n entropy_weight=0.0,\n batch_size=16,\n render_hook=Collection_RenderHook(N=16),\n render_step=1000,\n eval_step=100,\n display_step=100,\n stopping_criteria=\"reward_per_ep,max\",\n threshold=1000,\n\n image_shape=(25, 25),\n background_colour=\"white\",\n image_obs=False,\n max_entities=5,\n\n agent_spec=dict(appearance=\"plus\", color=\"green\", shape=entity_size),\n entity_specs=[\n dict(appearance=\"circle\", color=\"blue\", shape=entity_size, reward=-1),\n dict(appearance=\"square\", color=\"red\", shape=entity_size, reward=1)\n ],\n min_entities=5,\n max_overlap=0.0,\n step_size=5,\n corner=None,\n grid=False,\n\n explore=False,\n discrete_actions=False,\n)\n\n\nif __name__ == \"__main__\":\n with config:\n env = build_env().gym_env\n agent = RandomAgent(env.action_space)\n do_rollouts(env, agent, render=True)\n","sub_path":"dps/env/basic/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":23073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"166099531","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n# Script FG8OJ pour Spotnik\n# Relance après inactivité radio vers un groupe par défault\n# Cron :\n# * * * * * python /etc/spotnik/modedef.py > /dev/null 2>&1\n# Configuration :\ndefault=\"rrf\" # appel du fichier restart /etc/spotnik/restart.XXX\ntimeout=30 # durée en minute avant le rebasculement sur le salon par défault\n#\n#\nimport datetime\nimport os\nlog = open(\"/etc/spotnik/network\",\"rt\")\nreseau=log.readline().strip()\nif (reseau == default):\n exit()\nlog2 = open(\"/tmp/svxlink.log\", \"rt\")\ndelay=9999999\nfor x in log2:\n if ( (x.find(\"The squelch is OPEN\")>-1)or(x.find(\"Activating link\")>-1) ):\n dti=x.find(\": \")\n dt=x[:dti]\n dt= datetime.datetime.strptime(dt,\"%a %b %d %H:%M:%S %Y\")\n dt=datetime.datetime.now() - dt\n if (delay>dt.total_seconds()):\n delay=int(dt.total_seconds())\nprint(delay)\nif (delay==9999999):\n exit()\nif (delay>(timeout*60)):\n print(\"restart \"+ str(delay))\n os.system(\"/etc/spotnik/restart.\" + str(default)) \nlog.close()\n","sub_path":"modedef.py","file_name":"modedef.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"627218989","text":"from math import floor\nimport base64\n\ndef xor(key,plaintext):\n result = []\n k = None\n try:\n key = int(key)\n k = key\n except ValueError:\n current_index_key = 0\n length_key = len(key)\n for byte in plaintext:\n if type(key) == str:\n k = ord(key[current_index_key])\n current_index_key+=1\n current_index_key%=length_key\n result.append(ord(byte) ^ k)\n return result\n\ndef caesar_cipher(key,plaintext): \n result = []\n key %= 26\n for byte in plaintext:\n byte = ord(byte)\n res = byte + key\n if byte >= 97 and byte <= 122:\n if res > 122:\n res = res % 122 + 96\n else:\n if res > 90:\n res = res % 90 + 64\n result.append(res)\n\n return result \n","sub_path":"encryption.py","file_name":"encryption.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"78310250","text":"from JumpScale import j\nfrom JumpScale.portal.portal.auth import auth\nimport base64\n\nclass system_logo(j.code.classGetBase()):\n\n def __init__(self):\n\n self.actorname = \"logo\"\n self.appname = \"system\"\n self.osiscl = j.core.portal.active.osis\n self.modelBlob = j.clients.osis.getCategory(self.osiscl, 'system', 'blob')\n\n def get(self, **kwargs):\n \"\"\"\n get the logo\n param:name name of user\n \"\"\"\n image = self.modelBlob.get('logo')\n return image\n\n\n @auth(['admin'])\n def set(self, image, **kwargs):\n img = image[image.keys()[0]]\n self.modelBlob.set(base64.b64encode(img.read()), 'logo')\n returncontent = \"\"\n return returncontent\n\n @auth(['admin'])\n def delete(self, **kwargs):\n self.modelBlob.delete(\"logo\")\n returncontent = \"\"\n return returncontent\n","sub_path":"apps/portalbase/system/system__logo/methodclass/system_logo.py","file_name":"system_logo.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"42546713","text":"import json\nimport pandas as pd\nfrom textblob import TextBlob\nimport re\n\ndef read_json(json_file: str)->list:\n \"\"\"\n json file reader to open and read json files into a list\n Args:\n -----\n json_file: str - path of a json file\n \n Returns\n -------\n length of the json file and a list of json\n \"\"\"\n \n tweets_data = []\n for tweets in open(json_file,'r'):\n tweets_data.append(json.loads(tweets))\n \n print(len(tweets_data))\n return len(tweets_data), tweets_data\n\n\nclass TweetDfExtractor:\n \"\"\"\n this function will parse tweets json into a pandas dataframe\n \n Return\n #------\n dataframe\n \"\"\"\n def __init__(self, tweets_list):\n \n self.tweets_list = tweets_list\n\n # an example function\n def find_statuses_count(self)->list:\n statuses_count = []\n for element in self.tweets_list:\n try:\n if 'user' in element:\n statuses_count.append(element['user']['statuses_count'])\n\n else:\n statuses_count.append(element['retweeted_status']['user']['statuses_count'])\n\n except Exception as e:\n print(e)\n statuses_count.append(None)\n\n return statuses_count\n \n def find_full_text(self)->list:\n text = []\n for element in self.tweets_list:\n if 'retweeted_status' in element:\n try:\n if 'extended_tweet' in element['retweeted_status']:\n text.append(element['retweeted_status']['extended_tweet']['full_text'])\n else:\n text.append(element['retweeted_status']['text'])\n except Exception as e:\n print(e)\n\n else:\n try:\n if 'extended_tweet' in element['quoted_status']:\n text.append(element['quoted_status']['extended_tweet']['full_text'])\n else:\n text.append(element['quoted_status']['text'])\n except Exception as e:\n print(e)\n if 'text' in element:\n text.append(element['text'])\n else:\n text.append(None)\n\n return text\n \n def find_sentiments(self, text)->list:\n polarity, subjectivity, sentiment = [], [], []\n tetx = \"\"\n for element in self.tweets_list:\n if 'retweeted_status' in element:\n try:\n if 'extended_tweet' in element['retweeted_status']:\n text = element['retweeted_status']['extended_tweet']['full_text']\n else:\n text = element['retweeted_status']['text']\n except Exception as e:\n print(e)\n else:\n try:\n if 'extended_tweet' in element['quoted_status']:\n text = element['quoted_status']['extended_tweet']['full_text']\n else:\n text = element['quoted_status']['text']\n except:\n # print(e)\n text = element['text']\n polarity1 = TextBlob(text).polarity\n subjectivity1 = TextBlob(text).subjectivity\n polarity.append(polarity1)\n sentiment.append(\"Sentiment(polarity=\"+str(polarity1)+\", subjectivity=\"+str(subjectivity1))\n subjectivity.append(subjectivity1)\n\n return polarity, subjectivity\n\n def find_sentiment_two(self, text)->list:\n sentiment = []\n tetx = \"\"\n for element in self.tweets_list:\n if 'retweeted_status' in element:\n try:\n if 'extended_tweet' in element['retweeted_status']:\n text = element['retweeted_status']['extended_tweet']['full_text']\n else:\n text = element['retweeted_status']['text']\n except Exception as e:\n print(e)\n else:\n try:\n if 'extended_tweet' in element['quoted_status']:\n text = element['quoted_status']['extended_tweet']['full_text']\n else:\n text = element['quoted_status']['text']\n except:\n # print(e)\n text = element['text']\n sentiment1 = TextBlob(text).sentiment\n sentiment.append(sentiment1)\n\n return sentiment\n\n def find_created_time(self)->list:\n created_at = [] # Initialize empty list\n for element in self.tweets_list:\n try:\n if 'created_at' in element:\n created_at.append(element['created_at'])\n\n else:\n created_at.append(element['retweeted_status']['created_at'])\n except Exception as e:\n print(e)\n created_at.append(None)\n\n return created_at\n\n def find_source(self)->list:\n source = []\n for element in self.tweets_list:\n try:\n if 'source' in element:\n source.append(element['source'])\n\n else:\n source.append(element['retweeted_status']['source'])\n except Exception as e:\n print(e)\n source.append(None)\n \n return source\n\n def find_screen_name(self)->list:\n screen_name = []\n for element in self.tweets_list:\n try:\n if 'user' in element:\n screen_name.append(element['user']['screen_name'])\n\n else:\n screen_name.append(element['retweeted_status']['user']['screen_name'])\n\n except Exception as e:\n print(e)\n screen_name.append(None)\n\n return screen_name\n\n def find_followers_count(self)->list:\n followers_count = []\n for element in self.tweets_list:\n try:\n if 'user' in element:\n followers_count.append(element['user']['followers_count'])\n\n else:\n followers_count.append(element['retweeted_status']['user']['followers_count'])\n\n except Exception as e:\n print(e)\n followers_count.append(None)\n\n return followers_count\n\n def find_friends_count(self)->list:\n friends_count = []\n for element in self.tweets_list:\n try:\n if 'user' in element:\n friends_count.append(element['user']['friends_count'])\n\n else:\n friends_count.append(element['retweeted_status']['user']['friends_count'])\n\n except Exception as e:\n print(e)\n friends_count.append(None)\n return friends_count\n\n\n def is_sensitive(self)->list:\n is_sensitive = []\n for element in self.tweets_list:\n # try:\n if 'retweeted_status' in element:\n try:\n is_sensitive.append(element['retweeted_status']['possibly_sensitive'])\n except Exception as e:\n print(e)\n\n else:\n is_sensit = None\n is_sensitive.append(is_sensit)\n\n return is_sensitive\n\n def find_favourite_count(self)->list:\n favourite_count = []\n for element in self.tweets_list:\n try:\n if 'retweeted_status' in element:\n favourite_count.append(element['retweeted_status']['favorite_count'])\n\n else:\n favourite_count.append(element['favorite_count'])\n\n except Exception as e:\n print(e)\n favourite_count.append(None)\n\n return favourite_count\n \n def find_retweet_count(self)->list:\n retweet_count = []\n for element in self.tweets_list:\n try:\n if 'retweeted_status' in element:\n retweet_count.append(element['retweeted_status']['retweet_count'])\n\n else:\n retweet_count.append(element['retweet_count'])\n\n except Exception as e:\n print(e)\n\n return retweet_count\n\n def find_hashtags(self)->list:\n hashtags =[]\n text = self.find_full_text()\n for element in text:\n try:\n hashtags.append(re.findall('(#[A-Za-z]+[A-Za-z0-9-_]+)', element))\n except Exception as e:\n print(e)\n hash = None\n hashtags.append(hash)\n\n return hashtags\n\n def find_lang(self)->list:\n lang = []\n for element in self.tweets_list:\n try:\n if 'lang' in element:\n lang.append(element['lang'])\n\n else:\n language = None\n lang.append(language)\n except Exception as e:\n print(e)\n lang.append(None)\n\n return lang\n\n def find_mentions(self)->list:\n mentions = []\n for element in self.tweets_list:\n try:\n if 'retweeted_status' in element:\n if 'extended_tweet' in element['retweeted_status']:\n mentions.append(element['retweeted_status']['extended_tweet']['entities']['user_mentions'][0])\n else:\n mentions.append(element['retweeted_status']['entities']['user_mentions'][0])\n else:\n mentions.append(element['entities']['user_mentions'][0])\n\n except Exception as e:\n print(e)\n mention = None\n mentions.append(mention)\n\n return mentions\n\n\n def find_location(self)->list:\n location = []\n for element in self.tweets_list:\n try:\n location1 = element['user']['location']\n location.append(location1)\n except TypeError:\n location1 = None\n location.append(location1)\n \n return location\n\n \n \n \n def get_tweet_df(self, save=False)->pd.DataFrame:\n \"\"\"required column to be generated you should be creative and add more features\"\"\"\n \n columns = ['created_at', 'source', 'original_text','lang', 'sentiment','favorite_count', 'retweet_count','polarity', 'subjectivity',\n 'original_author', 'followers_count','friends_count','possibly_sensitive', 'hashtags', 'user_mentions', 'place']\n \n created_at = self.find_created_time()\n # print(created_at)\n source = self.find_source()\n text = self.find_full_text()\n polarity, subjectivity = self.find_sentiments(text)\n sentiment = self.find_sentiment_two(text)\n lang = self.find_lang()\n fav_count = self.find_favourite_count()\n retweet_count = self.find_retweet_count()\n screen_name = self.find_screen_name()\n follower_count = self.find_followers_count()\n friends_count = self.find_friends_count()\n sensitivity = self.is_sensitive()\n hashtags = self.find_hashtags()\n mentions = self.find_mentions()\n location = self.find_location()\n print(\">\",len(polarity), len(subjectivity),len(sentiment))\n print(len(created_at),\"-\",len(source),\"-\",len(text),\"-\",len(lang),\"-\",len(fav_count),\n \"-\",len(retweet_count),\"-\",len(screen_name),\"-\",len(follower_count),\n \"-\",len(friends_count),\"-\",len(sensitivity),\"-\",len(hashtags),\"-\",len(mentions),\"-\",len(location) )\n data = zip(created_at, source, text, lang, sentiment, fav_count, retweet_count, polarity, subjectivity, screen_name, follower_count, friends_count, sensitivity, hashtags, mentions, location)\n df = pd.DataFrame(data=data, columns=columns)\n\n if True:\n try:\n df.to_csv('processed_tweet_data.csv', index=False)\n print('Data prepared and Saved in processed_tweet_data.csv File Successfully!!!')\n except Exception as e:\n print(\"File save Failed!\", e)\n return df\n\n \nif __name__ == \"__main__\":\n # required column to be generated you should be creative and add more features\n columns = ['created_at', 'source', 'original_text','clean_text', 'sentiment','polarity','subjectivity', 'lang', 'favorite_count', 'retweet_count', \n 'original_author', 'screen_count', 'followers_count','friends_count','possibly_sensitive', 'hashtags', 'user_mentions', 'place', 'place_coord_boundaries']\n \n tweets_length, tweet_list = read_json(\"data/covid19.json\")\n tweet = TweetDfExtractor(tweet_list)\n tweet_df = tweet.get_tweet_df()\n\n ","sub_path":"extract_dataframe.py","file_name":"extract_dataframe.py","file_ext":"py","file_size_in_byte":12961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"226871927","text":"# -- coding: utf8 --\n\nfrom collect import *\n\n#定义函数,抛出异常\nclass ParseError(Exception):\n\t\"\"\"docstring for ParseError\"\"\"\n\tdef __init__(self):\n\t\tsuper(ParseError, self).__init__()\n\n#定义函数\nclass Sentence(object):\n\t\"\"\"docstring for Sentence\"\"\"\n\tdef __init__(self, subject, verb, object):\n\t\tsuper(Sentence, self).__init__()\n\t\t#这些都是基本的英语语句结构\n\t\tself.subject = subject[1]\n\t\tself.verb = verb[1]\n\t\tself.object = object[1]\n\n#定义类,所有的语句解析都在这里\nclass Parse(object):\n\t\"\"\"docstring for Parse\"\"\"\n\tdef __init__(self):\n\t\tsuper(Parse, self).__init__()\n\n\t#定义函数\n\tdef peek(self, word_list):\n\t\t#找到第一个元组所包含的单词类型,并返回\n\t\tif word_list:\n\t\t\tword = word_list[0]\n\t\t\treturn word[0]\n\t\telse:\n\t\t\treturn None\n\n\t#定义函数\n\tdef match(self, word_list, expecting):\n\t\tif word_list:\n\t\t\t#抛出第一个元组\n\t\t\tword = word_list.pop(0)\n\t\t\tif word[0] == expecting:\n\t\t\t\t#匹配正确,返回这个元组\n\t\t\t\treturn word\n\t\t\telse:\n\t\t\t\t#匹配不成功\n\t\t\t\treturn None\n\t\telse:\n\t\t\treturn None\n\n\t#定义函数\n\tdef skip(self, word_list, word_type):\n\t\t#排除匹配的元组\n\t\twhile self.peek(word_list) == word_type:\n\t\t\tself.match(word_list, word_type)\n\n\t#定义函数\n\tdef parse_verb(self, word_list):\n\t\t#先排除掉修饰词\n\t\tself.skip(word_list, 'stop')\n\n\t\tif self.peek(word_list) == 'verb':\n\t\t\t#匹配到动词\n\t\t\treturn self.match(word_list, 'verb')\n\t\telse:\n\t\t\t#匹配不成功,抛出异常\n\t\t\traise ParseError('Expected a verb next.')\n\n\t#定义函数\n\tdef parse_object(self, word_list):\n\t\t#先排除掉修饰词\n\t\tself.skip(word_list, 'stop')\n\t\t#第一个单词的类型\n\t\tnext = self.peek(word_list)\n\t\tif next == 'noun':\n\t\t\t#第一个单词是名词,匹配成功\n\t\t\treturn self.match(word_list, 'noun')\n\t\telif next == 'direction':\n\t\t\t#第一个单词表示方向,匹配成功\n\t\t\treturn self.match(word_list, 'direction')\n\t\telse:\n\t\t\t#匹配不成功,抛出异常\n\t\t\traise ParseError('Expected noun or direction next.')\n\n\t#定义函数\n\tdef parse_subject(self, word_list, subj):\n\t\t#匹配谓语\n\t\tverb = self.parse_verb(word_list)\n\t\t#匹配主语\n\t\tobj = self.parse_object(word_list)\n\t\t#以上匹配都成功,生成句子并返回\n\t\treturn Sentence(subj, verb, obj)\n\n\t#定义函数\n\tdef parse_sentence(self, word_list):\n\t\t#先排除掉修饰词\n\t\tself.skip(word_list, 'stop')\n\t\t#找到第一个单词的类型\n\t\tstart = self.peek(word_list)\n\t\tif start == 'noun':\n\t\t\t#第一个单词是名词,可以作为主语,匹配成功\n\t\t\tsubject = self.match(word_list, 'noun')\n\t\t\treturn self.parse_subject(word_list, subject)\n\t\telif start == 'verb':\n\t\t\t#第一个但此时动词,可以作为谓语,默认'player'作为主语,匹配成功\n\t\t\treturn self.parse_subject(word_list, ('noun', 'player'))\n\t\telse:\n\t\t\t#否则匹配失败,抛出异常\n\t\t\traise ParseError('Must start with subject, object, or verb not %s' % start)\n\n\t\t\t \n\n\t\t\n\t\t\n","sub_path":"learn_python/exercise49/module/parsor.py","file_name":"parsor.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"244303052","text":"# -*- coding: utf-8 -*-\n\"\"\"\nModified on Sat Sep 15 11:01:33 2018\n@author: Jing\n@Email: cdxujing@qq.com\nTitle:\n\"\"\"\n\nn = int(input())\nnoodles = []\nfor _ in range(n):\n no = sorted([int(i) for i in input().split(' ') if i != ''])\n noodles.append(no)\n\nclass ss:\n def __init__(self, start, end):\n self.start = start\n self.end = end\n\nnew_noodles = []\nfor i in range(len(noodles)):\n s = ss(noodles[i][0], noodles[i][1])\n new_noodles.append(s)\n\nclass Solution(object):\n def eraseOverlapIntervals(self, intervals):\n \"\"\"\n :type intervals: List[Interval]\n :rtype: int\n \"\"\"\n if len(intervals) == 0:\n return 0\n intervals = sorted(intervals, key=lambda Interval: Interval.start)\n prev = 0\n count = 0\n for i in range(1,len(intervals)):\n if intervals[prev].end > intervals[i].start:\n if intervals[prev].end > intervals[i].end:\n prev = i\n count += 1\n else:\n prev = i\n return count\n\n\nso = Solution()\nprint(n-so.eraseOverlapIntervals(new_noodles))\n\n\n\n\n\n\n\n","sub_path":"iqiyi_noodles.py","file_name":"iqiyi_noodles.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"495593555","text":"#!/usr/bin/python\n\nfrom scipy import io\n\ndata_dict = io.loadmat('../data/NBData20_train_preprocessed.mat')\n\nxt = data_dict['xt']\nyt = data_dict['yt']\n\nimport numpy\nfrom modshogun import RealFeatures,MulticlassLabels,LMNN,MSG_DEBUG\n\nfeatures = RealFeatures(xt.T)\nlabels = MulticlassLabels(numpy.squeeze(yt))\n\nk = 6\nlmnn = LMNN(features,labels,k)\nlmnn.io.set_loglevel(MSG_DEBUG)\nlmnn.set_diagonal(True)\nlmnn.set_maxiter(10000)\nlmnn.train(numpy.eye(features.get_num_features()))\n\n","sub_path":"shogun/python/lmnn_metadistance_simdata.py","file_name":"lmnn_metadistance_simdata.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"576205515","text":"f = open('Lab21part2.csv', 'w')\r\noldX = 0.25\r\nnewX = 0.0\r\nr=2.9\r\n\r\nfor i in range(0,400):\r\n newX = float(r*oldX*(1-oldX))\r\n if i >= 100:\r\n f.write(str(i) + ' ' + str(i) + ' ' + str(newX) + '\\n')\r\n oldX = newX\r\nf.close()","sub_path":"Computer Science share/Accelerated Computer Science Period 7 by Ram Reddy _ Aarnav Rawat/Effeciency/Lab21Part2.py","file_name":"Lab21Part2.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"264444527","text":"import urllib3\r\nimport os\r\nimport sys\r\nimport json\r\nfrom bs4 import BeautifulSoup\r\n# 创建连接\r\nhttp = urllib3.PoolManager()\r\n# 根目录\r\nroot = \"C:\\\\Users\\\\Administrator\\\\Downloads\\\\python-pa\\\\yxlm\\\\\"\r\n# 发送请求\r\nheaders = {\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.146 Safari/537.36',\r\n 'X-Requested-With': 'XMLHttpRequest'\r\n}\r\nres = http.request('GET',\r\n 'https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js?v=45')\r\nhtml = json.loads(res.data.decode('gbk')).get('hero')\r\n# 拿到英雄id , 用于拼接图片的url\r\nfor item in html:\r\n # 设置文件路径与文件名字\r\n directory = item['name']+'-'+item['title']\r\n # 新建英雄的目录\r\n if os.path.exists(root+directory):\r\n pass\r\n else:\r\n os.mkdir(root+directory)\r\n print(directory+'的皮肤正在下载...')\r\n url = \"https://game.gtimg.cn/images/lol/act/img/js/hero/\" +str(item['heroId']) + '.js'\r\n try:\r\n result = http.request('GET',url)\r\n imgUrl = json.loads(result.data)['skins']\r\n for i in imgUrl:\r\n if i.get('mainImg'):\r\n imgContent = http.request('GET',i['mainImg']).data\r\n else:\r\n imgContent = http.request('GET',i['chromaImg']).data\r\n with open(os.path.join(root+directory, i['name']+'.jpg'), 'wb') as jpg:\r\n jpg.write(imgContent)\r\n except Exception as e:\r\n print(e)\r\nprint('全部下载完啦!')\r\n\r\n","sub_path":"yxlm.py","file_name":"yxlm.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"236964640","text":"#!env/bin/python\nimport sys\n\nfrom flask import Flask, render_template\nfrom flask_flatpages import FlatPages\nfrom flask_frozen import Freezer\nfrom flask.ext.assets import Environment, Bundle\n\nDEBUG = True\nFLATPAGES_AUTO_RELOAD = DEBUG\nFLATPAGES_EXTENSION = '.md'\n\napp = Flask(__name__)\napp.config.from_object(__name__)\npages = FlatPages(app)\nfreezer = Freezer(app)\nassets = Environment(app)\n\n# ASSETS\ncss = Bundle('less/main.less',\n\tfilters = 'less, yui_css', output = 'css/main.css')\nmain_js = Bundle('js/raphael-min.js', 'js/main.js',\n\tfilters = 'yui_js', output = 'js/main-min.js')\nhome_js = Bundle('js/main-min.js','js/waypoints.min.js', 'js/jquery.leanModal.min.js', 'js/jquery.fittext-ck.js', 'js/home.js',\n\tfilters = 'yui_js', output = 'js/home-min.js')\ncontact_js = Bundle('js/main-min.js','js/contact.js',\n\tfilters = 'yui_js', output = 'js/contact-min.js')\n\nassets.register('css', css)\nassets.register('main_js', main_js)\nassets.register('home_js', home_js)\nassets.register('contact_js', contact_js)\n\n# ROUTES\n@app.route('/')\ndef index():\n\tprojects = (p for p in pages if 'published' in p.meta and p.path.startswith('projects'))\n\tprojects_sorted = sorted(projects, reverse=True, key=lambda p: p.meta['published'])\n\treturn render_template('index.html', \n\t\tprojects = projects_sorted)\n\n@app.route('/notes/')\ndef notes():\n\treturn render_template('notes.html', pages=pages)\n\n@app.route('/contact/')\ndef contact():\n\treturn render_template('contact.html', pages=pages)\n\n@app.route('//')\ndef page(path):\n\tpage = pages.get_or_404(path)\n\tif path.startswith('contact'):\n\t\ttemplate = page.meta.get('template', 'email-submit.html')\n\telif path.startswith('notes'):\n\t\ttemplate = page.meta.get('template', 'note.html')\n\treturn render_template(template, page=page)\n\n# RUN AND BUILD\n@freezer.register_generator\ndef email_sent():\n\tyield '/contact/email-not-sent/'\n\tyield '/contact/email-sent/'\n\nif __name__ == '__main__':\n\tif len(sys.argv) > 1 and sys.argv[1] == \"build\":\n\t\tfreezer.freeze()\n\telse:\n\t\tapp.run(port=8000)","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"73609975","text":"# -*- encoding:utf-8 -*-\n\nfrom flask import Flask, jsonify, request\nfrom old.demo import db, Member\nimport config\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config['SQLALCHEMY_DATABASE_URI'] = \"mysql+pymysql://%s:%s@%s:%s/%s\" % (\n config.DB_USERNAME, config.DB_PASSWORD, config.DB_HOST, config.DB_PORT, config.DB_NAME)\ndb.init_app(app)\n\n\n@app.route('/')\ndef index():\n return \"Hello Flask\"\n\n\n@app.route('/initdb', methods=['POST'])\ndef init_db():\n db.create_all()\n ret_dic = {\n \"return_code\": \"200\",\n \"return_msg\": \"Init db success\"\n }\n return jsonify(ret_dic)\n\n\n@app.route('/member', methods=['GET', 'POST', \"PATCH\", \"DELETE\"])\n@app.route('/member/', methods=['GET', 'PATCH', \"PUT\", \"DELETE\"])\ndef member_actions(condition=None):\n if condition == None and len(request.form) == 0:\n if request.method == \"GET\" and len(request.args) == 0:\n returnDict = Member.queryAll()\n return jsonify(returnDict)\n elif request.method != \"GET\" and len(request.args) == 0:\n returnDict = {\n \"code\": 400,\n \"msg\": \"请求方式错误,无法获取所有member\"\n }\n return jsonify(returnDict)\n if condition == None and len(request.form) == 0:\n if request.method == \"GET\" and len(request.form) == 0:\n returnDict = Member.queryAll()\n return jsonify(returnDict)\n elif request.method != \"GET\" and len(request.form) == 0:\n returnDict = {\n \"code\": 400,\n \"msg\": \"请求方式错误,无法获取所有member\"\n }\n return jsonify(returnDict)\n elif request.method == \"PUT\":\n uid = int(condition.split(\"_\")[-1])\n member = Member.query.filter(Member.uid == uid).first()\n if member == None:\n ret_dic1 = {\n \"return_code\": \"400\",\n \"return_msg\": \"该用户不存在\"\n }\n return jsonify(ret_dic1)\n try:\n new_tel = request.form[\"tel\"]\n except:\n new_tel = member.tel\n try:\n new_discount = request.form[\"discount\"]\n except:\n new_discount = member.discount\n try:\n new_score = request.form[\"score\"]\n except:\n new_score = member.score\n try:\n new_active = request.form[\"active\"]\n except:\n new_active = str(member.active)\n ret_dic = Member.update_member_by_uid(uid, member, new_tel, new_discount, new_score, new_active)\n return jsonify(ret_dic)\n\n\n\n\n elif request.method == \"GET\":\n if condition.startswith(\"uid_\"):\n try:\n target_uid = int(condition.split(\"_\")[-1])\n except:\n ret_dic = {\n \"return_code\": \"400\",\n \"return_msg\": \"uid输入错误\"\n }\n return jsonify(ret_dic)\n db_ret = Member.query.filter(Member.uid == target_uid)\n\n member_list = []\n for mem in db_ret:\n member_info = {\"uid\": mem.uid, \"tel\": mem.tel, \"discount\": mem.discount, \"score\": mem.score,\n \"active\": mem.active}\n member_list.append(member_info)\n if len(member_list) == 0:\n ret_dic = {\n \"return_code\": \"400\",\n \"return_msg\": \"uid不存在\"\n }\n return jsonify(ret_dic)\n else:\n ret_dic = {\n \"return_code\": \"200\",\n \"return_msg\": \"获取用户成功\",\n \"count\": len(member_list),\n \"members\": member_list\n }\n return jsonify(ret_dic)\n\n elif condition.startswith(\"tel_\"):\n tel = condition.split(\"_\")[-1]\n ret_dic = Member.search_by_tel(tel)\n return jsonify(ret_dic)\n\n # 添加新用户到数据库,根据手机号码\n elif request.method == 'POST':\n tel = request.form['tel']\n member1 = Member.query.filter(Member.tel == tel).first()\n if member1 != None:\n ret_dic = {\n \"return_code\": \"400\",\n \"return_msg\": \"该电话号码用户已注册\"\n }\n return jsonify(ret_dic)\n\n # tel str字符 判断长度,是否11位来确定有没有必要往下进行\n if len(tel) == 11:\n # 用isdigit()函数来判断是否为数字,是数字返回True 否则返回false\n result = request.form['tel'].isdigit()\n if result == True:\n # 是数字\n mem_info = Member.add_member_by_tel(tel)\n ret_dic = {\n \"return_code\": 200, \"return_msg\": \"add member success\",\n \"member\": mem_info\n }\n return jsonify(ret_dic)\n else:\n # 不是数字\n ret_dic = {\n \"return_code\": 508, \"return_msg\": \"add member failed, exists\",\n }\n return jsonify(ret_dic)\n else:\n # 不是11位\n ret_dic = {\n \"return_code\": 508, \"return_msg\": \"add member failed, exists\",\n }\n return jsonify(ret_dic)\n\n # 根据用户ID注销会员\n elif request.method == \"DELETE\":\n try:\n mem_no = int(condition.split(\"_\")[-1])\n except:\n ret_dic = {\"ret_code\": \"400\",\n \"ret_msg\": \"请输入数字!\"}\n return jsonify(ret_dic)\n ret_query = Member.query.all()\n for mem in ret_query:\n if mem.uid == mem_no:\n if mem.active == 0:\n ret_dic = {\"ret_code\": \"400\",\n \"ret_msg\": \"会员已注销,请重新输入!\"}\n\n return jsonify(ret_dic)\n\n mem.active = 0\n mem.discount = 1\n db.session.commit()\n\n ret_dic = {\"ret_code\": \"200\",\n \"ret_msg\": \"注销会员成功!\",\n \"member\": {\"uid\": mem.uid, \"tel\": mem.tel, \"discount\": mem.discount, \"active\": mem.active,\n \"score\": mem.score}\n }\n return jsonify(ret_dic)\n\n ret_dic = {\"ret_code\": \"400\",\n \"ret_msg\": \"注销会员失败, uid 不存在\"}\n return jsonify(ret_dic)\n\n\n\n elif request.method == 'PATCH':\n uid = int(condition.split(\"_\")[-1])\n db_ret = Member.query.filter(Member.uid == uid).first()\n if db_ret == None:\n ret_dic = {\n \"return_code\": 400,\n \"return_msg\": \"用户未注册\"\n }\n return jsonify(ret_dic)\n try:\n if db_ret.uid == uid:\n score = int(request.form['score'])\n if isinstance(score, int):\n if score > 0 or score == 0:\n ret_dic = Member.update_member_score(uid, score)\n ret_dic[\"return_code\"] = 200\n ret_dic[\"return_msg\"] = \"update score success!\"\n return jsonify(ret_dic)\n else:\n ret_dic = {\n \"return_code\": 500,\n \"return_msg\": \"积分不能为负数,请输入正确的积分值\"\n }\n return jsonify(ret_dic)\n except:\n ret_dic = {\n \"return_code\": 500,\n \"return_msg\": \"请输入正确积分值\"\n }\n return jsonify(ret_dic)\n\n\n@app.route('/filter/score')\ndef filter_member_by_score():\n try:\n score = int(request.args['le'])\n except:\n ret_dic = {\n \"return_code\": 500,\n \"return_msg\": \"积分输入错误,请输入正确的积分\"\n }\n return jsonify(ret_dic)\n if score < 0:\n ret_dic = {\n \"return_code\": 500,\n \"return_msg\": \"积分不能为负数\"\n }\n return jsonify(ret_dic)\n ret_dic = Member.filter_member_by_score(score)\n ret_dic[\"return_code\"] = 200\n ret_dic[\"return_msg\"] = \"Filter user success\"\n return jsonify(ret_dic)\n\n\nif __name__ == '__main__':\n app.run(host=config.APP_HOST, port=config.APP_PORT)\n","sub_path":"old/demo/market.py","file_name":"market.py","file_ext":"py","file_size_in_byte":8510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"521928872","text":"def createDatabase(filePath):\n L=[]\n f=open(filePath);\n content=f.readlines();\n for row in content:\n temp=row.strip('\\n').split(',');\n temp[3]=float(temp[3]);\n L.append(temp)\n\n return L;\n\ndef DisplayMenu():\n print(\"Here are some options for you: \")\n print(\"1. Print List of CDs\");\n print(\"2. Sort CDs by Title\");\n print(\"3. Sort CDs by Artist\");\n print(\"4. Sort CDs by Genre\");\n print(\"5. Sort CDs by Price\");\n print(\"6. Find All CDs by Title\")\n print(\"7. Find All CDs by Artist\")\n print(\"8. Find All CDs by Genre\")\n print(\"9. Find All CDs with Price at Most X\")\n print(\"10. Quit\")\n\ndef PrintList(L):\n for i in range(len(L)):\n print(\"%d: %s,%s,%s,%f\"%(i+1,L[i][0],L[i][1],L[i][2],L[i][3]));\n\ndef SortByTitle(L):\n Ltemp=L.copy();#把L 复制给 Ltemp 防止原始L被更改\n for i in range(len(Ltemp)):\n for j in range(i,len(Ltemp)):\n if Ltemp[i][0].lower()>Ltemp[j][0].lower():\n temp=Ltemp[i];\n Ltemp[i]=Ltemp[j];\n Ltemp[j]=temp;\n\n return Ltemp;\n\ndef SortByArtist(L):\n Ltemp = L.copy(); # 把L 复制给 Ltemp 防止原始L被更改\n for i in range(len(Ltemp)):\n for j in range(i, len(Ltemp)):\n if Ltemp[i][1].lower() > Ltemp[j][1].lower():\n temp = Ltemp[i];\n Ltemp[i] = Ltemp[j];\n Ltemp[j] = temp;\n\n return Ltemp;\n\ndef SortByGenre(L):\n Ltemp = L.copy(); # 把L 复制给 Ltemp 防止原始L被更改\n for i in range(len(Ltemp)):\n for j in range(i, len(Ltemp)):\n if Ltemp[i][2].lower() > Ltemp[j][2].lower():\n temp = Ltemp[i];\n Ltemp[i] = Ltemp[j];\n Ltemp[j] = temp;\n\n return Ltemp;\n\ndef SortByPrice(L):\n Ltemp = L.copy(); # 把L 复制给 Ltemp 防止原始L被更改\n for i in range(len(Ltemp)):\n for j in range(i, len(Ltemp)):\n if Ltemp[i][3] > Ltemp[j][3]:\n temp = Ltemp[i];\n Ltemp[i] = Ltemp[j];\n Ltemp[j] = temp;\n\n return Ltemp;\n\ndef FindByTitle(L,str):\n Ltemp=[];\n for row in L:\n if row[0]==str:\n Ltemp.append(row);\n return Ltemp;\n\ndef FindByArtist(L,str):\n Ltemp=[];\n for row in L:\n if row[1]==str:\n Ltemp.append(row);\n return Ltemp;\n\ndef FindByGenre(L,str):\n Ltemp=[];\n for row in L:\n if row[2]==str:\n Ltemp.append(row);\n return Ltemp;\n\ndef FindByPrice(L,price):\n Ltemp=[];\n for row in L:\n if row[3]<=price:\n Ltemp.append(row);\n return Ltemp;\n\ndef test(L):\n Ltemp=L.copy()\n Ltemp[99]=['dada','dad','da','dw']\n\nif __name__==\"__main__\":\n filePath = 'C:/Users/Anzhi/Desktop/file.txt';\n L=createDatabase(filePath);\n while(1):\n DisplayMenu();\n option=float(input(\"Please input your option(1-10): \"));\n if option>10 or option<1:\n print(\"Input error\")\n continue;\n\n if option==1:\n PrintList(L);\n elif option==2:\n PrintList(SortByTitle(L));\n elif option==3:\n PrintList(SortByArtist(L));\n elif option==4:\n PrintList(SortByGenre(L));\n elif option==5:\n PrintList(SortByPrice(L));\n elif option==6:\n str=input(\"Please input the Title you search: \");\n PrintList(FindByTitle(L,str));\n elif option==7:\n str = input(\"Please input the Artist you search: \");\n PrintList(FindByArtist(L, str));\n elif option==8:\n str = input(\"Please input the Genre you search: \");\n PrintList(FindByGenre(L, str));\n elif option==9:\n price = float(input(\"Please input the Price you search: \"));\n PrintList(FindByPrice(L, price));\n elif option==10:\n break;\n else:\n continue;\n print(\"********************************************************************\")\n\n\n # PrintList(SortByTitle(L))\n # PrintList(FindByPrice(L,50))\n # test(L)\n # PrintList(L)\n\n\n\n\n","sub_path":"python/project/Reindeer20181007.py","file_name":"Reindeer20181007.py","file_ext":"py","file_size_in_byte":4113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"120878777","text":"import gi\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk, Gdk\nfrom SSHConnector import utils\n\n\n# the tree model\nclass HostListStore():\n\n def __init__(self, hosts):\n self.store = Gtk.ListStore(str)\n self.__populate(hosts)\n\n def __populate(self, hosts):\n for el in hosts:\n self.store.append([el['hostname']])\n\n\n# the tree view\nclass HostList():\n\n def __init__(self, model):\n self.view = Gtk.TreeView.new_with_model(model)\n self.__populate()\n\n def __populate(self):\n renderer = Gtk.CellRendererText()\n column = Gtk.TreeViewColumn(\"Hosts\", renderer, text=0)\n self.view.append_column(column)\n\n\n# the main window\nclass MyWindow(Gtk.Window):\n\n def __init__(self):\n Gtk.Window.__init__(self, title='SSHConnector')\n Gtk.Window.set_position(self, Gtk.WindowPosition.CENTER)\n\n self.selected_host = None\n self.hosts = utils.getHosts()\n\n grid = buildGrid()\n self.add(grid)\n\n model = HostListStore(self.hosts)\n self.hostList = HostList(model.store)\n\n scrollable_treelist = Gtk.ScrolledWindow()\n scrollable_treelist.set_vexpand(True)\n grid.attach(scrollable_treelist, 0, 0, 5, 5)\n scrollable_treelist.add(self.hostList.view)\n\n selection = self.hostList.view.get_selection()\n selection.connect(\"changed\", self.on_tree_selection_changed)\n\n button1 = Gtk.Button.new_with_label(\"Connect\")\n button1.set_tooltip_text(\"Connect to the selected host\")\n button2 = Gtk.Button.new_with_label(\"Quit\")\n button2.set_tooltip_text(\"Quit the application\")\n\n grid.attach_next_to(button1, scrollable_treelist, Gtk.PositionType.BOTTOM, 1, 1)\n #grid.attach_next_to(button2, button1, Gtk.PositionType.RIGHT, 1, 1)\n grid.attach(button2, 4, 5, 1, 1)\n\n button1.connect(\"clicked\", self.on_connect_clicked)\n button2.connect(\"clicked\", self.on_close_clicked)\n\n def on_tree_selection_changed(self, selection):\n model, treeIter = selection.get_selected()\n if treeIter != None:\n self.selected_host = model[treeIter][0]\n else:\n show_error_dialog(self, \"Please select host from the list\")\n\n\n def on_close_clicked(self, button):\n Gtk.main_quit()\n\n def on_connect_clicked(self, button):\n username = None\n for el in self.hosts:\n if el['hostname'] == self.selected_host:\n password = el['username']\n utils.connectToHost(self.selected_host, password)\n\n\ndef runGui():\n win = MyWindow()\n win.connect(\"delete-event\", Gtk.main_quit)\n win.show_all()\n Gtk.main()\n\n\ndef buildGrid():\n grid = Gtk.Grid()\n grid.set_column_homogeneous(True)\n grid.set_row_homogeneous(True)\n return grid\n\n\ndef show_error_dialog(parent_window, message):\n dialog = Gtk.MessageDialog(parent_window, 0, Gtk.MessageType.ERROR,\n Gtk.ButtonsType.OK, message)\n dialog.run()\n\n","sub_path":"SSHConnector/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"328743048","text":"import random\nimport os\nimport sys\nfrom pathlib import Path\nCURRENT_PATH = str(Path(__file__).resolve().parent.parent.parent)\ntaxing_path = os.path.join(CURRENT_PATH)\nsys.path.append(taxing_path)\n\nimport numpy as np\nimport importlib\n\nfrom TaxAI.env.env_core import economic_society\nfrom omegaconf import OmegaConf\n\nfrom utils.box import Box\nfrom env.simulators.game import Game\n\n__all__ = ['Taxing_Household']\n\nclass RandomAgent:\n def __init__(self, action_space):\n self.action_space = action_space\n self.agent_name = 'Random'\n def __call__(self, observation):\n return [self.action_space[0].sample()]\n\n\nclass Taxing_Household(Game):\n def __init__(self, conf, seed=None):\n super(Taxing_Household, self).__init__(conf['n_player'], conf['is_obs_continuous'], conf['is_act_continuous'],\n conf['game_name'], conf['agent_nums'], conf['obs_type'])\n self.seed = seed\n self.set_seed()\n\n yaml_path = os.path.join(CURRENT_PATH, 'TaxAI/cfg/n4.yaml')\n yaml_cfg = OmegaConf.load(yaml_path)\n self.env_core = economic_society(yaml_cfg.Environment)\n self.max_step = int(conf['max_step']) #TODO: check max step in the env_core\n\n self.controllable_agent_id = 'Household'\n\n self.agent_id = list(self.env_core.action_spaces.keys())\n self.joint_action_space = {self.controllable_agent_id :self.set_action_space()[self.controllable_agent_id]}\n self.action_dim = self.joint_action_space\n self.each_gov_spaces = Box(np.array([-1., -1., -1, -1, -1]),\n np.array([1.,1., 1., 1., 1.]))\n self.n_households = self.env_core.households.n_households\n self.n_gov = 1\n\n self.sub_controller = [RandomAgent([self.each_gov_spaces])]\n\n self.reset()\n self.init_info = {'Controllable': self.controllable_agent_id,\n 'Opponent': [i.agent_name for i in self.sub_controller]}\n\n @staticmethod\n def create_seed():\n seed = random.randrange(1000)\n return seed\n\n def set_seed(self, seed=None):\n if not seed: #use previous seed when no new seed input\n seed = self.seed\n else: #update env global seed\n self.seed = seed\n random.seed(seed)\n np.random.seed(seed)\n\n\n def set_action_space(self):\n a_s = {}\n for aid, space in self.env_core.action_spaces.items():\n a_s[aid] = [space]\n\n return a_s\n\n def get_single_action_space(self, player_id):\n player_name = self.controllable_agent_id\n return self.joint_action_space[player_name]\n\n def reset(self):\n global_obs, private_obs = self.env_core.reset()\n self.step_cnt = 0\n self.done = False\n self.init_info = None\n self.won = {}\n self.n_return = [0]*self.n_player\n\n self.current_state = (global_obs, private_obs)\n self.all_observes = self.get_all_observes()\n return self.all_observes\n\n def step(self, joint_action):\n self.is_valid_action(joint_action)\n joint_action_decode = self.decode(joint_action)\n info_before = {\"actions\": joint_action_decode}\n\n global_obs, private_obs, gov_r, house_r, done = self.env_core.step(joint_action_decode)\n info_after = self.step_after_info()\n self.current_state = (global_obs, private_obs)\n self.all_observes = self.get_all_observes()\n\n self.house_r = house_r\n\n self.step_cnt += 1\n self.done = done\n if self.done:\n self.set_n_return()\n print('Final n_return = ', self.n_return)\n\n reward = gov_r #dict(zip(self.agent_id, [gov_r, house_r]))\n\n return self.all_observes, reward, self.done, info_before, info_after\n\n\n def is_valid_action(self, joint_action):\n if len(joint_action) != self.n_player: #check number of player\n raise Exception(\"Input joint action dimension should be {}, not {}\".format(\n self.n_player, len(joint_action)))\n\n def decode(self, joint_action):\n joint_action_decode = {}\n joint_action_decode[self.controllable_agent_id] = joint_action[0][0]\n gov_action = None\n for gov_idx, house_obs in enumerate(self.gov_obs):\n _action = self.sub_controller[gov_idx](house_obs)[0]\n gov_action= _action\n # gov_action = np.array(gov_action)\n\n joint_action_decode['government'] = gov_action # self.sub_controller(self.household_obs[0])[0]\n return joint_action_decode\n\n\n def get_all_observes(self):\n all_observes = []\n global_obs, private_obs = self.current_state\n #global obs is for government, private_obs+global_obs are for each household\n gov_obs = []\n\n for idx, aid in enumerate(self.agent_id):\n if aid == 'government':\n _gov_obs = {'obs': {\"agent_id\": aid, \"raw_obs\": global_obs},\n \"controlled_player_index\": idx}\n gov_obs.append(_gov_obs)\n elif aid == 'Household':\n for house_idx in range(private_obs.shape[0]):\n each_private_obs = private_obs[house_idx]\n _obs = {\"obs\": {\"agent_id\": aid, 'raw_obs': [global_obs, each_private_obs],\n \"controlled_player_index\": house_idx}}\n\n # _obs = {\"obs\": {\"agent_id\": aid, \"raw_obs\": [global_obs, private_obs]},\n # \"controlled_player_index\": idx}\n all_observes.append(_obs)\n else:\n raise NotImplementedError\n\n self.gov_obs = gov_obs\n\n return all_observes\n\n def step_after_info(self):\n current_step = self.env_core.step_cnt\n social_welfare = self.env_core.households_reward.mean()\n wealth_gini = self.env_core.wealth_gini\n income_gini = self.env_core.income_gini\n gdp = self.env_core.GDP\n\n tau = self.env_core.government.tau\n xi = self.env_core.government.xi\n tau_a = self.env_core.government.tau_a\n xi_a = self.env_core.government.xi_a\n Gt_prob = self.env_core.Gt_prob\n return {'step': current_step, 'social_welfare': social_welfare, 'wealth_gini': wealth_gini,\n 'income_gini': income_gini, 'gdp': gdp, 'tau': tau, 'xi': xi, 'tau_a': tau_a, 'xi_a': xi_a,\n \"Gt_prob\": Gt_prob}\n def is_terminal(self):\n return self.done\n\n def check_win(self):\n return '-1'\n\n def set_n_return(self):\n self.n_return = list(np.array(self.n_return) + self.house_r[:,0])\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"env/taxing_household.py","file_name":"taxing_household.py","file_ext":"py","file_size_in_byte":6684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"625089352","text":"#!/usr/bin/env python\nimport sys\n#from utils \nimport atom\n\nif len(sys.argv) > 2:\n raise Exception('You must provide an OMS file')\n\nf = sys.argv[1]\nlines = open(f).readlines()\n\nfo = '.'.join(f.split('.')[:-1])+'.data'\no = open(fo, 'w')\n\no.write('[Header]\\n{} ({})\\n\\n'.format(lines[26].strip(), f))\n\nfound_lines = {\n 'geom': -1,\n 'energies': -1,\n 'dipoles': -1\n}\n\nfor i, line in enumerate(lines):\n if 'Input geometry ...' in line:\n found_lines['geom'] = i\n continue\n if 'Electron transition spectra' in line:\n found_lines['energies'] = i\n continue\n if 'Dipole moments (Unit: Debye)' in line:\n found_lines['dipoles'] = i\n break\n\nfor key in found_lines:\n if found_lines[key] == -1:\n raise Exception('Not found: line for {}'.format(key))\n\n# catch geometry\natoms = []\nfor line in lines[found_lines['geom']+5:]:\n if '------' in line:\n break\n\n atomic_def = line.split()\n if atomic_def[1] not in atom.Definition:\n raise Exception('Unknown atom {}'.format(atomic_def[1]))\n atoms.append([atomic_def[1], atom.Definition[atomic_def[1]][0], atomic_def[2], atomic_def[3], atomic_def[4]])\n\no.write('[Atomic Coordinates]\\nnatoms: {}\\nLabel AN X Y Z\\n'.format(len(atoms)))\nfor a in atoms:\n o.write(' {:5} {:5} {:>15} {:>15} {:>15}\\n'.format(*a))\n\n# catch energies\nnstates = int(lines[found_lines['energies']][-5:])\nnstates_found = 0\no.write('\\n[E_transition]\\nNstates: {}\\n'.format(nstates))\nprint('Found', nstates, 'excited states in this file ...')\nfor line in lines[found_lines['energies']+5:]:\n if '------' in line:\n break\n if line[:9].strip() == '':\n continue\n else:\n energy_def = line.split()\n o.write('{:10} {:.8f}\\n'.format(energy_def[0], float(energy_def[1])/27.212))\n nstates_found += 1\n\nif nstates != nstates_found:\n raise Exception('Number of excited state inconsistent: {} != {}'.format(nstates, nstates_found))\n\n# catch dipoles\no.write('\\n[mu_transition]\\nNstates: {}\\n'.format(nstates))\nfor line in lines[found_lines['dipoles']+6:]: # skip \"ground\"\n if '------' in line:\n break\n dipole_def = line.split()\n o.write('{:10} {:> 12.8f} {:> 12.8f} {:> 12.8f}\\n'.format(dipole_def[0], *[float(a)*0.393430307 for a in dipole_def[1:4]]))\n\no.write('\\n\\n')\nprint('File \"{}\" successfully converted into \"{}\" \\o/'.format(f, fo))\n","sub_path":"mosf-extract.py","file_name":"mosf-extract.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"525174368","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\nfrom argparse import ArgumentParser\nfrom collections import defaultdict\nimport glob\nimport os\n\nimport openmc.data\n\n\n# Get path to MCNP data\nparser = ArgumentParser()\nparser.add_argument('-d', '--destination', default='mcnp_endfb70',\n help='Directory to create new library in')\nparser.add_argument('mcnpdata', help='Directory containing endf70[a-k] and endf70sab')\nargs = parser.parse_args()\nassert os.path.isdir(args.mcnpdata)\n\n# Get a list of all neutron ACE files\nendf70 = glob.glob(os.path.join(args.mcnpdata, 'endf70[a-k]'))\n\n# Create output directory if it doesn't exist\nif not os.path.isdir(args.destination):\n os.mkdir(args.destination)\n\nlibrary = openmc.data.DataLibrary()\n\nfor path in sorted(endf70):\n print('Loading data from {}...'.format(path))\n lib = openmc.data.ace.Library(path)\n\n # Group together tables for the same nuclide\n tables = defaultdict(list)\n for table in lib.tables:\n zaid, xs = table.name.split('.')\n tables[zaid].append(table)\n\n for zaid, tables in sorted(tables.items()):\n # Convert first temperature for the table\n print('Converting: ' + tables[0].name)\n data = openmc.data.IncidentNeutron.from_ace(tables[0], 'mcnp')\n\n # For each higher temperature, add cross sections to the existing table\n for table in tables[1:]:\n print('Adding: ' + table.name)\n data.add_temperature_from_ace(table, 'mcnp')\n\n # Export HDF5 file\n h5_file = os.path.join(args.destination, data.name + '.h5')\n print('Writing {}...'.format(h5_file))\n data.export_to_hdf5(h5_file, 'w')\n\n # Register with library\n library.register_file(h5_file)\n\n# Handle S(a,b) tables\nendf70sab = os.path.join(args.mcnpdata, 'endf70sab')\nif os.path.exists(endf70sab):\n lib = openmc.data.ace.Library(endf70sab)\n\n # Group together tables for the same nuclide\n tables = defaultdict(list)\n for table in lib.tables:\n name, xs = table.name.split('.')\n tables[name].append(table)\n\n for zaid, tables in sorted(tables.items()):\n # Convert first temperature for the table\n print('Converting: ' + tables[0].name)\n data = openmc.data.ThermalScattering.from_ace(tables[0])\n\n # For each higher temperature, add cross sections to the existing table\n for table in tables[1:]:\n print('Adding: ' + table.name)\n data.add_temperature_from_ace(table)\n\n # Export HDF5 file\n h5_file = os.path.join(args.destination, data.name + '.h5')\n print('Writing {}...'.format(h5_file))\n data.export_to_hdf5(h5_file, 'w')\n\n # Register with library\n library.register_file(h5_file)\n\n# Write cross_sections.xml\nlibpath = os.path.join(args.destination, 'cross_sections.xml')\nlibrary.export_to_xml(libpath)\n","sub_path":"data/convert_mcnp_70.py","file_name":"convert_mcnp_70.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"223752178","text":"'''\nMIT License\n\nCopyright (c) 2020 Martin Velikov & Patrick Thompson\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\nimport discord\nfrom discord.ext import commands\nimport asyncio\nimport traceback\n\nclass HelpCommand(commands.HelpCommand):\n def __init__(self):\n super().__init__()\n self.command_attrs['brief'] = 'Help for bot commands.'\n self.command_attrs['description'] = 'Displays a list of all bot commands and their usages.'\n self.command_attrs['usage'] = '[command]'\n self.command_attrs['cog'] = \"Utility\"\n\n def divide(self, l, size):\n for i in range(0, len(l), size):\n yield l[i:i + size]\n\n async def send_bot_help(self, mapping):\n text = ''\n for cog, cmds in mapping.items():\n if len(cmds) > 0:\n if cog is not None:\n cname = cog.qualified_name\n cdesc = cog.description\n else:\n cname = 'No Category'\n cdesc = 'uncategorized commands'\n\n if cname == \"Developer\":\n continue\n text += f'{cname}\\n{\"=\"*len(cname)}\\n* {cdesc or f\"for whenever you need {cname.lower()}.\"}'\n\n if len(cmds) > 0:\n for cmd in cmds:\n cmd_name = cmd.name + \"|\" + \"|\".join(cmd.aliases) if len(cmd.aliases) else cmd.name\n cmd_desc = cmd.brief or cmd.description[:20] or \"No Description\"\n\n cmd_info = f'{self.clean_prefix}{cmd_name} {cmd.usage or \"\"}'\n\n spacer = 30-len(cmd_info)\n if spacer < 0: spacer = 0\n\n text += f'\\n{cmd_info} {\" \"*spacer}:: {cmd_desc}'\n else:\n text += '\\nNo Commands'\n text += '\\n\\n\\n'\n text += '\\n'\n\n await self.get_destination().send(f\"{self.context.author.mention} :point_right: **Check your DM's!**\")\n for idx, chunk in enumerate(self.divide(text.splitlines(), 32)):\n doc = '\\n```asciidoc\\n'+'\\n'.join(chunk).strip('```') + '```'\n if idx == 0:\n doc = '``Bot Commands``' + doc\n\n if len(doc.replace('```', '').replace('asciidoc', '').strip()) > 0:\n await self.context.author.send(doc)\n\n async def send_command_help(self, cmd):\n cmd_name = cmd.name + \"|\" + \"|\".join(cmd.aliases) if len(cmd.aliases) else cmd.name\n cmd_desc = cmd.description or cmd.brief or \"No Description\"\n cmd_info = f'{self.clean_prefix}{cmd_name} {cmd.usage or \"\"}'\n\n text = f'```asciidoc\\n{cmd_info}\\n* {cmd_desc}```'\n\n await self.get_destination().send(text)\n\n async def send_group_help(self, cmd):\n cmd_name = \"|\".join(cmd.aliases) if len(cmd.aliases) else cmd.name\n cmd_desc = cmd.description or cmd.brief or \"No Description\"\n cmd_info = f'{self.clean_prefix}{cmd_name} {cmd.usage or \"\"}'\n\n subcommands = cmd.commands\n\n if len(subcommands) > 0:\n sub_list = '\\n\\n== Subcommands =='\n for sub in subcommands:\n sub_name = sub.name + \"|\" + \"|\".join(sub.aliases) if len(sub.aliases) else sub.name\n sub_desc = sub.brief or sub.description[:20] or \"No Description\"\n\n sub_info = f'{self.clean_prefix}{cmd_name} {sub_name} {sub.usage or \"\"}'\n\n spacer = 30-len(sub_info)\n if spacer < 0: spacer = 0\n\n sub_list += f'\\n{sub_info} {\" \"*spacer}:: {sub_desc}'\n else:\n sub_list = ''\n\n text = f'```asciidoc\\n{cmd_info}\\n* {cmd_desc}{sub_list}```'\n await self.get_destination().send(text)\n\n async def command_not_found(self, string):\n await self.get_destination().send(f\":x: ``{string}`` isn't a command, check your spelling.\")\n\n async def send_error_message(self, error):\n pass\n\n async def on_help_command_error(self, ctx, e):\n traceback.print_exception(type(e), e, e.__traceback__)\n\n\ndef setup(bot):\n bot.help_command = HelpCommand()\n","sub_path":"extensions/help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":5069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"308458982","text":"# -*- coding: utf-8 -*-\nimport rs485 as rs\n\n\n\"\"\"\nA ver, la idea es montar un \"paquete\" con direcciones de origen y destino\nUna cabecera con alguna historia, la informacion a transmitir y algun tipo de CRC\n\nCAMPOS DEL PAQUETE:\n\nByte de inicio : 1 byte (0x00)\nCabecera : 1 byte \n\t-> tipo de paquete: REQ | DAT | ACK | NAK\n\t-> identificación del paquete para controlarlo\nDireccion origen : 1 byte (hasta 256 dispositivos)\nDireccion destino : 1 byte\nTamano de los datos : 1 byte (hasta 256 bytes)\nDatos : 0 - 256 bytes\n*CRC : de la cabecera\nde fin : 1 byte (0x00)\n\nTAMANO DEL PAQUETE: 5B + Datos + [CRC] + 1B\n\"\"\"\n\n\"\"\"\n#str.encode(\"hex\") -> convierte str a hex\n#str.decode(\"hex\") -> convierte hex a str\n#int(str, 16) -> convierte hex a int\n\"\"\"\n\nACK = 0x01\nNAK = 0x02\nREQ = 0x04\nDAT = 0x08\n\nCONTROL_BYTE = '\\x00'\nORIG_ADDR = '\\x01'\n\ntest_packet = '\\x00\\x15\\x01\\x05\\x01a\\x00'\n\ndef begin():\n\trs.begin()\n\ndef end():\n\trs.end()\n\ndef pack(data, length, head, dest):\n#\tpacket = '\\x00'+head+orig+dest+size+data+crc+'\\x00'\n\treturn CONTROL_BYTE+head+ORIG_ADDR+dest+length+data+CONTROL_BYTE\n\n\ndef send(msg, dest):\n\tpacket = pack(msg, chr(len(msg)), '\\x04', chr(dest))\n\n\treturn rs.write(packet)\n\ndef recv():\n\tbuf = rs.read()\n\tif (buf == CONTROL_BYTE): #start byte\n\t\thead = rs.read()\n\t\torig = rs.read()\n\t\tdest = rs.read()\n\n\t\tsize = int(rs.read().encode(\"hex\"),16)\n\t\tdata = rs.read(size)\n\t\tif (rs.read() == CONTROL_BYTE): #end byte\n\t\t\treturn data\n\n","sub_path":"pysrc/netProtocol.py","file_name":"netProtocol.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"575285445","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def mergeTwoLists(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n sen=ListNode(0)\n p=sen\n p1=l1\n p2=l2\n while (p1!=None and p2!=None):\n if (p1.val<=p2.val):\n p.next=p1\n p=p.next\n p1=p1.next\n else:\n p.next=p2\n p=p.next\n p2=p2.next\n while p1:\n p.next=p1\n p1=p1.next\n p=p.next\n while p2:\n p.next=p2\n p2=p2.next\n p=p.next\n return sen.next\n","sub_path":"Merge Two Sorted Lists.py","file_name":"Merge Two Sorted Lists.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"320848479","text":"thestarternumbers = input(\"Enter two digit number to start the seiries : \")\nNOOFTIMES = int(input(\"Enter how long to do\"))\n\n\nstringer = list(thestarternumbers)\nlista = [int(stringer[0]), int(stringer[1])]\nlistb = lista\n\n\nstart1, start2 = lista[0], lista[1]\nsum = start1 + start2\n\nfor i in range(NOOFTIMES):\n\tlistb.append(sum)\n\tsum = listb[len(listb) - 1] + listb[len(listb) - 2]\n\nprint(listb)","sub_path":"Random/Fibonacciseries.py","file_name":"Fibonacciseries.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"505054920","text":"import json\nimport ijson\n\n# # fixed data to be correct json format\n# f1 = open('data_fixed.json', 'w')\n\n# with open('../../data-storage/Idea.json') as f:\n# \tdata = f.readlines()\n# \tcnt = 0\n\n# \tf1.write('[\\n')\n# \ttotal = len(data)\n\n# \tfor line in data:\n# \t\tcnt += 1\n# \t\tif 'productsWithPosition' in line and '\"productsWithPosition\":[]' not in line:\n# \t\t\tif cnt < total:\n# \t\t\t\tf1.write(line + ',')\n# \t\t\telse:\n# \t\t\t\tf1.write(line)\n# \t\t\t\tf1.write(']')\n\n\n# # count all products (contains duplicates)\n# f2 = open('used_products.txt', 'w')\n# with open('data_fixed.json') as f:\n# \t# parser = ijson.parse(f)\n# \tobjects = ijson.items(f, 'item.productsWithPosition.item')\n# \tcnt =1\n\n# \t#string format is objectId | title | sku | productUrl \n\n# \tfor line in objects:\n# \t\ttmp = ''\n\n# \t\tif 'objectId' in line:\n# \t\t\ttmp += line['objectId'] + '|'\n# \t\telse:\n# \t\t\ttmp += 'None|'\n\n# \t\tif 'title' in line:\n# \t\t\ttmp += line['title'] + '|'\n# \t\telse:\n# \t\t\ttmp += 'None|'\n\n# \t\tif 'sku' in line:\n# \t\t\ttmp += line['title'] + '|'\n# \t\telse:\n# \t\t\ttmp += 'None|'\n\n# \t\tif 'productUrl' in line:\n# \t\t\ttmp += line['productUrl']\n# \t\telse:\n# \t\t\ttmp += 'None'\n\n# \t\tf2.write(tmp.encode(\"utf8\") + '\\n')\n# \t\tcnt += 1\n\n# \t\tif cnt >= 10:\n# \t\t\tbreak\n\n# \tprint cnt \n\n\n# # count all product (remove duplicates in one design)\n# f2 = open('used_products.txt', 'w')\n# with open('data_fixed.json') as f:\n# \t# parser = ijson.parse(f)\n# \tobjects = ijson.items(f, 'item.productsWithPosition')\n# \tcnt =1\n\n# \t#string format is objectId | title | sku | productUrl \n\n# \tfor line in objects:\n\t\t\n# \t\tif len(line) > 0:\n# \t\t\ttmp_list = []\n# \t\t\tfor e in line:\n# \t\t\t\ttmp = ''\n\n# \t\t\t\tif 'objectId' in e:\n# \t\t\t\t\ttmp += e['objectId'] + '|'\n# \t\t\t\telse:\n# \t\t\t\t\ttmp += 'None|'\n\n# \t\t\t\tif 'title' in e:\n# \t\t\t\t\ttmp += e['title'] + '|'\n# \t\t\t\telse:\n# \t\t\t\t\ttmp += 'None|'\n\n# \t\t\t\tif 'sku' in e:\n# \t\t\t\t\ttmp += e['title'] + '|'\n# \t\t\t\telse:\n# \t\t\t\t\ttmp += 'None|'\n\n# \t\t\t\tif 'productUrl' in e:\n# \t\t\t\t\ttmp += e['productUrl']\n# \t\t\t\telse:\n# \t\t\t\t\ttmp += 'None'\n\n# \t\t\t\ttmp_list.append(tmp)\n\n\n# \t\t\ttmp_list = list(set(tmp_list))\n\n# \t\t\tfor t in tmp_list:\n# \t\t\t\tf2.write(t.encode(\"utf8\") + '\\n')\n\n# \t\tcnt += 1\n\n# \tprint cnt \n\n\n\n# statistical the frequency of products\nf3 = open('freq_result.txt', 'w')\n\nwith open('used_products_noduplicate_2197570.txt') as f:\n\tdata = f.readlines()\n\tfreq_dict = {}\n\tfor line in data:\n\n\t\ttmp_list = line.split('|')\n\t\tif len(tmp_list) < 4:\n\t\t\tcontinue\n\t\tobjectId, title, sku, productUrl = line.split('|')[:4]\n\n\t\tif objectId == 'None':\n\t\t\tcontinue\n\t\telse:\n\t\t\tfreq_dict.setdefault(objectId, 0)\n\t\t\tfreq_dict[objectId] += 1\n\n\tfor k, v in freq_dict.items():\n\t\tf3.write(k + '|' + str(v) + '\\n')\n\n\nf3.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t","sub_path":"operation_modules/_1_3_rank_module/preprocess/massage_data_from_idea_table.py","file_name":"massage_data_from_idea_table.py","file_ext":"py","file_size_in_byte":2694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"268547498","text":"height = int(input('请输入你的身高:'))\nvalue = int(input('请输入你的身价:'))\nface = int(input('请给你的颜值打分:'))\nif height > 180 and value > 1000000 and face > 99:\n print('高富帅')\nelif value > 1000000 and face >99 and height <= 180:\n print('高帅')\nelif face > 99 and height <= 180 and value <= 1000000:\n print('帅')\nelif height < 160 and value < 100 and face < 60:\n print('矮穷矬')\n\n\n","sub_path":"7.12作业/颜值大比拼.py","file_name":"颜值大比拼.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"54429570","text":"import json\nimport os\nimport re\nimport tempfile\n\nimport anchore_engine.configuration.localconfig\nfrom anchore_engine.utils import run_command, run_command_list, manifest_to_digest, AnchoreException\nfrom anchore_engine.subsys import logger\nfrom anchore_engine.common.errors import AnchoreError\n\ndef manifest_to_digest_shellout(rawmanifest):\n ret = None\n tmpmanifest = None\n try:\n fd,tmpmanifest = tempfile.mkstemp()\n os.write(fd, rawmanifest.encode('utf-8'))\n os.close(fd)\n\n localconfig = anchore_engine.configuration.localconfig.get_config()\n global_timeout = localconfig.get('skopeo_global_timeout', 0)\n try:\n global_timeout = int(global_timeout)\n if global_timeout < 0:\n global_timeout = 0\n except:\n global_timeout = 0\n\n if global_timeout:\n global_timeout_str = \"--command-timeout {}s\".format(global_timeout)\n else:\n global_timeout_str = \"\"\n\n cmd = \"skopeo {} manifest-digest {}\".format(global_timeout_str, tmpmanifest)\n rc, sout, serr = run_command(cmd)\n if rc == 0 and re.match(\"^sha256:.*\", str(sout, 'utf-8')):\n ret = sout.strip()\n else:\n logger.warn(\"failed to calculate digest from schema v1 manifest: cmd={} rc={} sout={} serr={}\".format(cmd, rc, sout, serr))\n raise SkopeoError(cmd=cmd, rc=rc, err=serr, out=sout, msg='Failed to calculate digest from schema v1 manifest', )\n except Exception as err:\n raise err\n finally:\n if tmpmanifest:\n os.remove(tmpmanifest)\n\n return ret\n\ndef copy_image_from_docker_archive(source_archive, dest_dir):\n cmdstr = \"skopeo copy docker-archive:{} oci:{}:image\".format(source_archive, dest_dir)\n cmd = cmdstr.split()\n try:\n rc, sout, serr = run_command_list(cmd)\n if rc != 0:\n raise SkopeoError(cmd=cmd, rc=rc, out=sout, err=serr)\n else:\n logger.debug(\"command succeeded: cmd=\"+str(cmdstr)+\" stdout=\"+str(sout).strip()+\" stderr=\"+str(serr).strip())\n\n except Exception as err:\n logger.error(\"command failed with exception - \" + str(err))\n raise err\n\ndef download_image(fulltag, copydir, user=None, pw=None, verify=True, manifest=None, parent_manifest=None, use_cache_dir=None, dest_type='oci'):\n try:\n proc_env = os.environ.copy()\n if user and pw:\n proc_env['SKOPUSER'] = user\n proc_env['SKOPPASS'] = pw\n credstr = '--src-creds \\\"${SKOPUSER}\\\":\\\"${SKOPPASS}\\\"'\n else:\n credstr = \"\"\n\n if verify:\n tlsverifystr = \"--src-tls-verify=true\"\n else:\n tlsverifystr = \"--src-tls-verify=false\"\n\n if use_cache_dir and os.path.exists(use_cache_dir):\n cachestr = \"--dest-shared-blob-dir \" + use_cache_dir\n else:\n cachestr = \"\"\n\n localconfig = anchore_engine.configuration.localconfig.get_config()\n global_timeout = localconfig.get('skopeo_global_timeout', 0)\n try:\n global_timeout = int(global_timeout)\n if global_timeout < 0:\n global_timeout = 0\n except:\n global_timeout = 0\n\n if global_timeout:\n global_timeout_str = \"--command-timeout {}s\".format(global_timeout)\n else:\n global_timeout_str = \"\"\n\n os_overrides = [\"\"]\n if manifest:\n manifest_data = json.loads(manifest)\n\n # skopeo doesn't support references in manifests for copy/download operations, with oci dest type - if found, override with dir dest_type\n for l in manifest_data.get('layers', []):\n if 'foreign.diff' in l.get('mediaType', \"\"):\n dest_type = 'dir'\n\n if parent_manifest:\n parent_manifest_data = json.loads(parent_manifest)\n else:\n parent_manifest_data = {}\n\n if parent_manifest_data:\n for mlist in parent_manifest_data.get('manifests', []):\n imageos = mlist.get('platform', {}).get('os', \"\")\n if imageos not in [\"\", 'linux']:\n # add a windows os override to the list of override attempts, to complete the options that are supported by skopeo\n dest_type = 'dir'\n os_overrides.insert(0, \"windows\")\n break\n\n for os_override in os_overrides:\n success = False\n if os_override not in [\"\", 'linux']:\n dest_type = 'dir'\n os_override_str = \"--override-os {}\".format(os_override)\n else:\n os_override_str = \"\"\n \n if dest_type == 'oci':\n if manifest:\n with open(os.path.join(copydir, \"manifest.json\"), 'w') as OFH:\n OFH.write(manifest)\n\n if parent_manifest:\n with open(os.path.join(copydir, \"parent_manifest.json\"), 'w') as OFH:\n OFH.write(parent_manifest)\n \n cmd = [\"/bin/sh\", \"-c\", \"skopeo {} {} copy {} {} {} docker://{} oci:{}:image\".format(os_override_str, global_timeout_str, tlsverifystr, credstr, cachestr, fulltag, copydir)]\n else:\n cmd = [\"/bin/sh\", \"-c\", \"skopeo {} {} copy {} {} docker://{} dir:{}\".format(os_override_str, global_timeout_str, tlsverifystr, credstr, fulltag, copydir)]\n\n cmdstr = ' '.join(cmd)\n try:\n rc, sout, serr = run_command_list(cmd, env=proc_env)\n if rc != 0:\n skopeo_error = SkopeoError(cmd=cmd, rc=rc, out=sout, err=serr)\n if skopeo_error.error_code != AnchoreError.OSARCH_MISMATCH.name:\n raise SkopeoError(cmd=cmd, rc=rc, out=sout, err=serr) \n else:\n logger.debug(\"command succeeded: cmd=\"+str(cmdstr)+\" stdout=\"+str(sout).strip()+\" stderr=\"+str(serr).strip())\n success = True \n\n except Exception as err:\n logger.error(\"command failed with exception - \" + str(err))\n raise err\n\n if success:\n break\n if not success:\n logger.error(\"could not download image\")\n raise Exception(\"could not download image\")\n except Exception as err:\n raise err\n\n return True\n\ndef get_repo_tags_skopeo(url, registry, repo, user=None, pw=None, verify=None, lookuptag=None):\n try:\n proc_env = os.environ.copy()\n if user and pw:\n proc_env['SKOPUSER'] = user\n proc_env['SKOPPASS'] = pw\n credstr = '--creds \\\"${SKOPUSER}\\\":\\\"${SKOPPASS}\\\"'\n else:\n credstr = \"\"\n\n if verify:\n tlsverifystr = \"--tls-verify=true\"\n else:\n tlsverifystr = \"--tls-verify=false\"\n \n localconfig = anchore_engine.configuration.localconfig.get_config()\n global_timeout = localconfig.get('skopeo_global_timeout', 0)\n try:\n global_timeout = int(global_timeout)\n if global_timeout < 0:\n global_timeout = 0\n except:\n global_timeout = 0\n\n if global_timeout:\n global_timeout_str = \"--command-timeout {}s\".format(global_timeout)\n else:\n global_timeout_str = \"\"\n\n pullstring = registry + \"/\" + repo\n if lookuptag:\n pullstring = pullstring + \":\" + lookuptag\n\n repotags = []\n\n cmd = [\"/bin/sh\", \"-c\", \"skopeo {} inspect {} {} docker://{}\".format(global_timeout_str, tlsverifystr, credstr, pullstring)]\n cmdstr = ' '.join(cmd)\n try:\n rc, sout, serr = run_command_list(cmd, env=proc_env)\n sout = str(sout, 'utf-8') if sout else None\n if rc != 0:\n raise SkopeoError(cmd=cmd, rc=rc, out=sout, err=serr)\n else:\n logger.debug(\"command succeeded: cmd=\"+str(cmdstr)+\" stdout=\"+str(sout).strip()+\" stderr=\"+str(serr).strip())\n except Exception as err:\n logger.error(\"command failed with exception - \" + str(err))\n raise err\n\n data = json.loads(sout)\n repotags = data.get('RepoTags', [])\n except Exception as err:\n raise err\n\n if not repotags:\n raise Exception(\"no tags found for input repo from skopeo\")\n\n return repotags\n\ndef get_image_manifest_skopeo_raw(pullstring, user=None, pw=None, verify=True):\n ret = None\n try:\n proc_env = os.environ.copy()\n if user and pw:\n proc_env['SKOPUSER'] = user\n proc_env['SKOPPASS'] = pw\n credstr = '--creds \\\"${SKOPUSER}\\\":\\\"${SKOPPASS}\\\"'\n else:\n credstr = \"\"\n\n if verify:\n tlsverifystr = \"--tls-verify=true\"\n else:\n tlsverifystr = \"--tls-verify=false\"\n\n localconfig = anchore_engine.configuration.localconfig.get_config()\n global_timeout = localconfig.get('skopeo_global_timeout', 0) \n try:\n global_timeout = int(global_timeout)\n if global_timeout < 0:\n global_timeout = 0\n except:\n global_timeout = 0\n\n if global_timeout:\n global_timeout_str = \"--command-timeout {}s\".format(global_timeout)\n else:\n global_timeout_str = \"\"\n\n os_override_strs = [\"\", \"--override-os windows\"]\n try:\n success = False\n for os_override_str in os_override_strs:\n cmd = [\"/bin/sh\", \"-c\", \"skopeo {} {} inspect --raw {} {} docker://{}\".format(global_timeout_str, os_override_str, tlsverifystr, credstr, pullstring)]\n cmdstr = ' '.join(cmd)\n try:\n rc, sout, serr = run_command_list(cmd, env=proc_env)\n if rc != 0:\n skopeo_error = SkopeoError(cmd=cmd, rc=rc, out=sout, err=serr)\n if skopeo_error.error_code != AnchoreError.OSARCH_MISMATCH.name:\n raise SkopeoError(cmd=cmd, rc=rc, out=sout, err=serr)\n else:\n logger.debug(\"command succeeded: cmd=\"+str(cmdstr)+\" stdout=\"+str(sout).strip()+\" stderr=\"+str(serr).strip())\n success = True\n except Exception as err:\n logger.error(\"command failed with exception - \" + str(err))\n raise err\n\n if success:\n sout = str(sout, 'utf-8') if sout else None \n ret = sout\n break\n\n if not success:\n logger.error(\"could not retrieve manifest\")\n raise Exception(\"could not retrieve manifest\")\n \n except Exception as err:\n raise err\n except Exception as err:\n raise err\n\n return ret\n\ndef get_image_manifest_skopeo(url, registry, repo, intag=None, indigest=None, topdigest=None, user=None, pw=None, verify=True, topmanifest=None):\n manifest = {}\n digest = None\n testDigest = None\n\n if indigest:\n pullstring = registry + \"/\" + repo + \"@\" + indigest\n elif intag:\n pullstring = registry + \"/\" + repo + \":\" + intag\n else:\n raise Exception(\"invalid input - must supply either an intag or indigest\")\n\n try:\n try:\n rawmanifest = get_image_manifest_skopeo_raw(pullstring, user=user, pw=pw, verify=verify)\n digest = manifest_to_digest(rawmanifest)\n manifest = json.loads(rawmanifest)\n if topmanifest is None:\n topmanifest = json.loads(rawmanifest)\n if not topdigest:\n topdigest = digest\n\n if manifest.get('schemaVersion') == 2 and manifest.get('mediaType') == 'application/vnd.docker.distribution.manifest.list.v2+json':\n # Get the arch-specific version for amd64 and linux\n new_digest = None\n for entry in manifest.get('manifests'):\n platform = entry.get('platform')\n if platform and platform.get('architecture') in ['amd64'] and platform.get('os') in ['linux', 'windows']:\n new_digest = entry.get('digest')\n break\n\n return get_image_manifest_skopeo(url=url, registry=registry, repo=repo, intag=None, indigest=new_digest, user=user, pw=pw, verify=verify, topdigest=topdigest, topmanifest=topmanifest)\n except Exception as err:\n logger.warn(\"CMD failed - exception: \" + str(err))\n raise err\n\n except Exception as err:\n import traceback\n traceback.print_exc()\n raise err\n\n if not manifest or not digest:\n raise SkopeoError(msg=\"No digest/manifest from skopeo\")\n\n return manifest, digest, topdigest, topmanifest\n\nclass SkopeoError(AnchoreException):\n\n def __init__(self, cmd=None, rc=None, err=None, out=None, msg='Error encountered in skopeo operation'):\n from anchore_engine.common.errors import AnchoreError\n\n self.cmd = ' '.join(cmd) if isinstance(cmd, list) else cmd\n self.exitcode = rc\n self.stderr = str(err).replace('\\r', ' ').replace('\\n', ' ').strip() if err else None\n self.stdout = str(out).replace('\\r', ' ').replace('\\n', ' ').strip() if out else None\n self.msg = msg\n try:\n if \"unauthorized\" in self.stderr:\n self.error_code = AnchoreError.REGISTRY_PERMISSION_DENIED.name\n elif \"manifest unknown\" in self.stderr:\n self.error_code = AnchoreError.REGISTRY_IMAGE_NOT_FOUND.name\n elif \"connection refused\" in self.stderr or \"no route to host\" in self.stderr:\n self.error_code = AnchoreError.REGISTRY_NOT_ACCESSIBLE.name\n elif \"error pinging registry\" in self.stderr:\n self.error_code = AnchoreError.REGISTRY_NOT_SUPPORTED.name\n elif \"no image found in manifest list for architecture amd64, OS linux\" in self.stderr:\n self.error_code = AnchoreError.OSARCH_MISMATCH.name\n else:\n self.error_code = AnchoreError.SKOPEO_UNKNOWN_ERROR.name\n except:\n self.error_code = AnchoreError.UNKNOWN.name\n \n\n def __repr__(self):\n return '{}. cmd={}, rc={}, stdout={}, stderr={}, error_code={}'.format(self.msg, self.cmd, self.exitcode, self.stdout, self.stderr, self.error_code)\n\n def __str__(self):\n return '{}. cmd={}, rc={}, stdout={}, stderr={}, error_code={}'.format(self.msg, self.cmd, self.exitcode, self.stdout, self.stderr, self.error_code)\n","sub_path":"anchore_engine/clients/skopeo_wrapper.py","file_name":"skopeo_wrapper.py","file_ext":"py","file_size_in_byte":14796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"125414975","text":"L1= eval(input(\"Enter numbers for list 1\"))\nL2 = eval(input(\"Enter numbers for list 2\"))\nL3 = L1 + L2\nL4=[]\nx = int(input(\"Enter 1 for merge , 2 for sort , 3 for union , 4 for intersection : \"))\nif x == 1:\n print(\"Merged: \" , L3)\nelif x == 2:\n L3.sort()\n print(\"Sorted: \" , L3)\nelif x == 3:\n union = list(set(L1) or set(L2))\n print (\"Union: \" , union)\nelif x == 4 :\n inter = list(set(L1) and set(L2))\n print(\"Intersection\" ,inter)\nelse :\n print(\"Error\")","sub_path":"Worksheet 7 List Manipulation Class 11/Q.4.py","file_name":"Q.4.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"602880942","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport re\n\n\n\ndef is_palindrome(text):\n # forbidden = ('.','?','!',':',':','-','_','(',')','[',']','...','\\'','\\\"','\\\"','/',',')\n noText = re.sub(r'.,!','',text)\n print(noText)\n \n return noText == noText[::-1]\n\nsomething = input(\"Enter text:\")\nif is_palindrome(something):\n print(\"It is a Palindrome\")\nelse:\n print(\"NO\")","sub_path":"ByteOfPython/palidromeDemo.py","file_name":"palidromeDemo.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"13039048","text":"import csv\nfrom github_user_function import get_user\n\nCOLUMNS = ['login', 'id', 'node_id', 'avatar_url', 'gravatar_id', 'url', 'html_url', 'followers_url', 'following_url', 'gists_url', 'starred_url', 'subscriptions_url', 'organizations_url', 'repos_url', 'events_url', 'received_events_url', 'type', 'site_admin', 'name', 'company', 'blog', 'location', 'email', 'hireable', 'bio', 'twitter_username', 'public_repos', 'public_gists', 'followers', 'following', 'created_at', 'updated_at',]\nFILENAME = 'tmp/user_github.csv'\n\nuser = get_user('galileoguzman')\n\n# Opening file in writable mode\nwith open(FILENAME, mode='w', newline='') as csv_file:\n writer = csv.DictWriter(csv_file, fieldnames=COLUMNS)\n\n # Write columns\n writer.writeheader()\n\n # Write at least one row\n writer.writerow(user)\n ","sub_path":"06_csv_writer.py","file_name":"06_csv_writer.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"15794876","text":"\"\"\"\n\n Agents.py (author: Anson Wong / git: ankonzoid)\n\n\"\"\"\nimport numpy as np\nimport random\nfrom collections import deque\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam\nfrom keras import regularizers\n\nclass DQNAgent():\n\n def __init__(self, env, sensors):\n\n # DQN agent settings\n self.observation_size = sensors.observation_size\n self.action_size = env.action_size\n self.sensors = sensors\n self.epsilon_range = [0.20, 0.20] # [max, min]\n self.epsilon_decay = 0.99 # multiply epsilon max by this after training\n self.epsilon = self.epsilon_range[0] # starting exploration parameter\n self.gamma = 0.99 # discount parameter (important)\n self.hidden_layers = [20, 20]\n self.L2_regularizer = [1E-6] * len(self.hidden_layers)\n self.learning_rate = 0.005 # value function learning rate\n self.activation = \"relu\"\n self.loss = \"mse\"\n self.memory_size = 20000 # max number of experiences stored in memory\n self.n_training_sessions = 50 # sessions per train() call\n self.batch_size = 200 # training batch size\n self.n_epochs = 1 # epochs per fit() call\n self.verbose = False\n\n # For experience replay memory training\n self.memory = deque(maxlen=self.memory_size) # can pop oldest experiences\n\n # Build DQN model\n self.model = self._build_model() # actual model\n\n # Make observation of state\n def observe(self, state, env):\n obs, _ = self.sensors.sense(state, 0, env)\n return obs\n\n # Follow epsilon-greedy policy\n def get_action(self, obs):\n obs_reshaped = np.reshape(obs, [1, len(obs)])\n self.epsilon = max(self.epsilon_range)\n rand = random.uniform(0, 1)\n if rand <= self.epsilon: # explore\n action = random.choice(list(range(self.action_size)))\n else: # exploit\n Qpred = self.model.predict(obs_reshaped)[0]\n action = random.choice(np.flatnonzero(Qpred==np.amax(Qpred)))\n return action\n\n # Train our network using replay mini-batch experiences\n def train(self):\n\n # Check there is enough memory for training\n if len(self.memory) < self.batch_size:\n return -1.0\n\n # Train\n loss_avg = 0.0\n for session in range(self.n_training_sessions):\n\n # Sample a mini-batch from replay memory\n minibatch = random.sample(self.memory, self.batch_size)\n obs_arr, action_arr, reward_arr, obs_next_arr, done_arr = [], [], [], [], []\n for (obs, action, reward, obs_next, done) in minibatch:\n obs_arr.append(obs)\n action_arr.append(action)\n reward_arr.append(reward)\n obs_next_arr.append(obs_next)\n done_arr.append(done)\n obs_arr = np.array(obs_arr, dtype=np.float)\n action_arr = np.array(action_arr, dtype=np.int)\n reward_arr = np.array(reward_arr, dtype=np.float)\n obs_next_arr = np.array(obs_next_arr, dtype=np.float)\n done_arr = np.array(done_arr, dtype=np.int)\n\n # Predict Q and Q_next\n Q = self.model.predict(obs_arr) # (batch_size, action_size)\n Q_next = self.model.predict(obs_next_arr) # (batch_size, action_size)\n\n # Compute target Q\n Q_target = Q.copy() # (batch_size, action_size)\n for i, (action, reward, done) in enumerate(zip(action_arr, reward_arr, done_arr)):\n Q_target[i, action] = reward\n if not done:\n Q_target[i, action] += self.gamma * np.amax(Q_next[i,:])\n loss_avg += np.abs(Q[i, action] - Q_target[i, action])**2\n\n # Train model\n self.model.fit(obs_arr, Q_target, epochs=self.n_epochs, verbose=self.verbose)\n\n # Compute average loss\n loss_avg /= self.batch_size\n loss_avg /= self.n_training_sessions\n\n # Decay agent epsilon max value\n self.epsilon_range[0] *= self.epsilon_decay\n\n return loss_avg\n\n # Store to agent memory where experience = (observation, action, reward, observation_next, done)\n def memorize(self, experience):\n self.memory.append(experience)\n\n # Save agent Q-model\n def save_model(self, filename):\n self.model.save(filename)\n\n # Load Q-model into agent\n def load_model(self, filename):\n self.model = load_model(filename)\n self.model.compile(loss=self.loss, optimizer=Adam(lr=self.learning_rate))\n\n def write_settings(self, filename):\n f = open(filename, 'w')\n f.write('\\n')\n attrs = vars(self)\n for item in sorted(attrs.items()):\n (item_name, item_value) = item\n if item_name not in [\"memory\", \"model\", \"model_target\"]:\n f.write('agent.{} = {}\\n'.format(item_name, item_value))\n\n # ============================================\n # Secondary functions\n # ============================================\n\n # Build FC network\n def _build_model(self):\n model = Sequential()\n for i, n_hidden_nodes in enumerate(self.hidden_layers):\n if i==0:\n model.add(Dense(self.hidden_layers[i],\n input_dim=self.observation_size,\n activation=self.activation,\n kernel_regularizer=regularizers.l2(self.L2_regularizer[i])))\n else:\n model.add(Dense(self.hidden_layers[i],\n activation=self.activation,\n kernel_regularizer=regularizers.l2(self.L2_regularizer[i])))\n model.add(Dense(self.action_size, activation=\"linear\"))\n model.compile(loss=self.loss, optimizer=Adam(lr=self.learning_rate))\n return model","sub_path":"src/Agents.py","file_name":"Agents.py","file_ext":"py","file_size_in_byte":5910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"389626537","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\nimport sys, time\nimport pygame\nimport my_snake\n\n\n\n\ndef main():\n ELEM_WIDTH = 40\n COLOR_BACK = (220,220,220)\n COLOR_LINE = (230,230,230)\n COLOR_HEAD = (150,110,110)\n COLOR_BODY = (110,110,110)\n COLOR_CONN = (140,140,140)\n COLOR_FOOD = (110,110,220)\n\n HEIGHT, WIDTH, PLAY_MODE, GAME_SPEED = 0, 0, 0, 0\n while not (type(HEIGHT) is int and HEIGHT >= 2):\n HEIGHT = int(input(\"input board HEIGHT (must >= 2):\"))\n print(\"HEIGHT:\", HEIGHT)\n while not (type(WIDTH) is int and WIDTH >= 2):\n WIDTH = int(input(\"input board WIDTH (must >= 2):\"))\n print(\"WIDTH:\", WIDTH)\n while not (type(PLAY_MODE) is int and (PLAY_MODE == 1 or PLAY_MODE == 2 or PLAY_MODE == 3)):\n PLAY_MODE = int(input(\"input PLAY_MODE: \\n\\t1 - play snake game \\n\\t2 - auto snake mode1\\n\\t3 - auto snake mode2\\n\"))\n print(\"PLAY_MODE:\", PLAY_MODE)\n while not (type(GAME_SPEED) is int and GAME_SPEED >= 1):\n GAME_SPEED = int(input(\"input GAME_SPEED (step per seconds, must >= 1):\"))\n print(\"GAME_SPEED:\", GAME_SPEED)\n\n snake = my_snake.Snake(HEIGHT, WIDTH)\n direct = \"\" # up, down, left, right\n next_direct = \"\" # up, down, left, right\n\n pygame.init()\n board = snake.get_board()\n height = len(board)\n width = len(board[0])\n screen = pygame.display.set_mode((width*ELEM_WIDTH, height*ELEM_WIDTH), 0, 32)\n pygame.display.set_caption(\"Snake!\")\n\n last_time = time.time()\n game_pause = False\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.KEYUP:\n if event.key == pygame.K_UP and direct != \"down\":\n game_pause = False\n next_direct = \"up\" \n elif event.key == pygame.K_DOWN and direct != \"up\":\n game_pause = False\n next_direct = \"down\"\n elif event.key == pygame.K_LEFT and direct != \"right\":\n game_pause = False\n next_direct = \"left\"\n elif event.key == pygame.K_RIGHT and direct != \"left\":\n game_pause = False\n next_direct = \"right\"\n elif event.key == pygame.K_SPACE:\n game_pause = not game_pause\n\n if game_pause:\n pygame.display.update()\n continue\n\n cur_time = time.time()\n if (cur_time - last_time) > (1.0 / GAME_SPEED) and \"alive\" == snake.get_status():\n last_time = cur_time\n\n if PLAY_MODE == 1:\n direct = next_direct\n snake.move(direct)\n elif PLAY_MODE == 2:\n snake.auto_move1()\n elif PLAY_MODE == 3:\n snake.auto_move2()\n else:\n assert(False)\n #print(\"time:%.5f status:%s len:%d\" %(time.time(), snake.get_status(), len(snake.get_snake())))\n \n # 绘制背景和分割线\n screen.lock()\n screen.fill(COLOR_BACK)\n board, height, width = snake.get_board(), len(board), len(board[0])\n for i in range(height):\n pygame.draw.line(screen, COLOR_LINE, (0,i*ELEM_WIDTH), (width*ELEM_WIDTH-1,i*ELEM_WIDTH))\n pygame.draw.line(screen, COLOR_LINE, (0,(i+1)*ELEM_WIDTH-1), (width*ELEM_WIDTH-1,(i+1)*ELEM_WIDTH-1))\n for i in range(width):\n pygame.draw.line(screen, COLOR_LINE, (i*ELEM_WIDTH,0), (i*ELEM_WIDTH,height*ELEM_WIDTH-1))\n pygame.draw.line(screen, COLOR_LINE, ((i+1)*ELEM_WIDTH-1,0), ((i+1)*ELEM_WIDTH-1,height*ELEM_WIDTH-1))\n # 绘制 food\n (i, j) = snake.get_food()\n pygame.draw.ellipse(screen, COLOR_FOOD, (j*ELEM_WIDTH+4, i*ELEM_WIDTH+4, ELEM_WIDTH-8, ELEM_WIDTH-8))\n # 绘制 snake\n snake_list = snake.get_snake()\n for x in range(len(snake_list)):\n (i, j) = snake_list[x]\n if x == 0:\n pygame.draw.rect(screen, COLOR_HEAD, (j*ELEM_WIDTH+1, i*ELEM_WIDTH+1, ELEM_WIDTH-2, ELEM_WIDTH-2))\n else:\n (m, n) = snake_list[x-1]\n pygame.draw.rect(screen, COLOR_BODY, (j*ELEM_WIDTH+1, i*ELEM_WIDTH+1, ELEM_WIDTH-2, ELEM_WIDTH-2))\n if i == m and j > n:\n pygame.draw.rect(screen, COLOR_CONN, (j*ELEM_WIDTH-1, i*ELEM_WIDTH+1, 2, ELEM_WIDTH-2))\n elif i == m and j < n:\n pygame.draw.rect(screen, COLOR_CONN, ((j+1)*ELEM_WIDTH-1, i*ELEM_WIDTH+1, 2, ELEM_WIDTH-2))\n elif j == n and i > m:\n pygame.draw.rect(screen, COLOR_CONN, (j*ELEM_WIDTH+1, i*ELEM_WIDTH-1, ELEM_WIDTH-2, 2))\n elif j == n and i < m:\n pygame.draw.rect(screen, COLOR_CONN, (j*ELEM_WIDTH+1, (i+1)*ELEM_WIDTH-1, ELEM_WIDTH-2, 2))\n screen.unlock()\n\n pygame.display.update()\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"122354089","text":"\n\"\"\"\nNaval Battle\n\"\"\"\nconfig = {\n\t\"columns\": 15,\n\t\"lines\": 10,\n\t\"ships\": {\n\t\t2: 2,\n\t\t3: 1,\n\t\t4: 1,\n\t\t5: 1\n\t},\n\t\"ship_one_beside_other\": False,\n\t\"debug\": True\n}\n\n\"\"\"\nImports\n\"\"\"\nimport turtle\nimport random\n\n\"\"\"\nInit Map && Return ships\n\"\"\"\ndef initMap():\n\tgameMap = []\n\tfor i in range(config['columns']):\n\t\tgameMap.append([0] * config['lines'])\n\tships = []\n\tship_id = 0\n\tfor ship_size in config['ships']:\n\t\tship_count = config['ships'][ship_size]\n\t\tfor i in range(ship_count):\n\t\t\tisVertical = random.randint(0, 100) % 2\n\t\t\tvalid = False\n\t\t\tfor attempt in range(1000):\n\t\t\t\t# random coords\n\t\t\t\tx1 = random.randint(0, config['columns'] - 1)\n\t\t\t\ty1 = random.randint(0, config['lines'] - 1)\n\t\t\t\tx2 = x1 + ship_size - 1 if not isVertical else x1\n\t\t\t\ty2 = y1 + ship_size - 1 if isVertical else y1\n\t\t\t\t# check coords\n\t\t\t\tif (x2 >= config['columns'] or y2 >= config['lines']):\n\t\t\t\t\tcontinue\n\t\t\t\t_valid = True\n\t\t\t\tfor x in range(x1, x2 + 1):\n\t\t\t\t\tfor y in range(y1, y2 + 1):\n\t\t\t\t\t\tif gameMap[x][y] != 0: _valid = False\n\t\t\t\t\t\tif not config['ship_one_beside_other']:\n\t\t\t\t\t\t\tif x > 0 and gameMap[x - 1][y] != 0: _valid = False\n\t\t\t\t\t\t\tif x < config['columns'] - 1 and gameMap[x + 1][y] != 0: _valid = False\n\t\t\t\t\t\t\tif y > 0 and gameMap[x][y - 1] != 0: _valid = False\n\t\t\t\t\t\t\tif y < config['lines'] - 1 and gameMap[x][y + 1] != 0: _valid = False\n\t\t\t\tif not _valid:\n\t\t\t\t\tcontinue\n\t\t\t\tship_id += 1\n\t\t\t\tships.append({\n\t\t\t\t\t'id': ship_id,\n\t\t\t\t\t'coords': {'x1': x1, 'x2': x2, 'y1': y1, 'y2': y2},\n\t\t\t\t\t'life': ship_size\n\t\t\t\t})\n\t\t\t\tfor x in range(x1, x2 + 1):\n\t\t\t\t\tfor y in range(y1, y2 + 1):\n\t\t\t\t\t\tgameMap[x][y] = ship_id\n\t\t\t\tvalid = True\n\t\t\t\tbreak\n\t\t\tif not valid:\n\t\t\t\tprint(\"Map Initialization failed!\")\n\t\t\t\tquit()\n\tgameMap = []\n\tfor i in range(config['columns']):\n\t\tgameMap.append([0] * config['lines'])\n\treturn gameMap, ships\n\n\"\"\"\nisShipPosition\n\"\"\"\ndef isChipPosition(x, y):\n\tfor ship in ships:\n\t\tif ship['coords']['x1'] <= x <= ship['coords']['x2']:\n\t\t\tif ship['coords']['y1'] <= y <= ship['coords']['y2']:\n\t\t\t\treturn True\n\treturn False\n\n\"\"\"\ngetShip (with one of its coords)\n\"\"\"\ndef getShip(x, y):\n\tfor ship in ships:\n\t\tif ship['coords']['x1'] <= x <= ship['coords']['x2']:\n\t\t\tif ship['coords']['y1'] <= y <= ship['coords']['y2']:\n\t\t\t\treturn ship\n\treturn None\n\n\"\"\"\nisAllShipDead\n\"\"\"\ndef isAllShipDead():\n\tfor ship in ships:\n\t\tif ship['life'] > 0:\n\t\t\treturn False\n\treturn True\n\n\"\"\"\nDraw Cells\n\"\"\"\ndef drawCells():\n\tturtle.color((155,50,200))\n\tfor line in range(config['lines'] + 1):\n\t\tturtle.pu()\n\t\tturtle.goto(-config[\"columns\"] * 20, config[\"lines\"] * 20 - 40*line)\n\t\tturtle.pd()\n\t\tturtle.fd(40 * config['columns'])\n\tturtle.left(90)\n\tfor col in range(config['columns'] + 1):\n\t\tturtle.pu()\n\t\tturtle.goto(-config[\"columns\"] * 20 + 40*col, -config[\"lines\"] * 20)\n\t\tturtle.pd()\n\t\tturtle.fd(40 * config['lines'])\n\n\"\"\"\nDraw a circle\n\"\"\"\ndef drawCircle(x, y, color):\n\tturtle.color(color)\n\tturtle.pu()\n\tturtle.goto(-config[\"columns\"] * 20 + 40*x + 30, -config[\"lines\"] * 20 + 40*y + 20)\n\tturtle.pd()\n\tturtle.circle(10)\n\n\"\"\"\nDraw status (0 => \"dans l'eau\" / 1 => \"touché\" / 2 => \"touché coulé\")\n\"\"\"\ndef drawStatus(status):\n\tmessages = (\"Dans l'eau\", \"Touché\", \"Touché coulé\", \"Vous avez gagné !\")\n\tcolors = ((0, 0, 0), (255, 0, 0), (255, 0, 0), (0, 255, 0))\n\tstatusTurtle.clear()\n\tstatusTurtle.goto(0, -config[\"lines\"] * 20 - 30)\n\tstatusTurtle.color(colors[status])\n\tstatusTurtle.write(messages[status], False, align=\"center\", font=(\"Arial\", 10, \"bold\"))\n\n\"\"\"\nDraw finish HUD\n\"\"\"\ndef drawFinishHud():\n\tturtle.color((0, 0, 0))\n\tturtle.pu()\n\tturtle.goto(config[\"columns\"] * 20, -config[\"lines\"] * 20 - 5)\n\tturtle.pd()\n\tturtle.goto(config[\"columns\"] * 20 - 120, -config[\"lines\"] * 20 - 5)\n\tturtle.goto(config[\"columns\"] * 20 - 120, -config[\"lines\"] * 20 - 35)\n\tturtle.goto(config[\"columns\"] * 20, -config[\"lines\"] * 20 - 35)\n\tturtle.goto(config[\"columns\"] * 20, -config[\"lines\"] * 20 - 5)\n\tturtle.pu()\n\tturtle.goto(config[\"columns\"] * 20 - 60, -config[\"lines\"] * 20 - 27)\n\tturtle.write('Recommencer', False, align=\"center\", font=(\"Arial\", 10, \"bold\"))\n\n\"\"\"\nOn Click event\n\"\"\"\ndef onclick(x, y):\n\n\t# check if the game is loaded\n\tif not loaded:\n\t\treturn\n\n\t# if game is finish\n\tif isAllShipDead():\n\t\tonclick_restartGame(x, y)\n\telse:\n\t\tonclick_cell(x, y)\n\n\"\"\"\nOn Click event => On Cell\n\"\"\"\ndef onclick_cell(x, y):\n\n\t# get cell coords\n\tx = int((x + config[\"columns\"] * 20) // 40)\n\ty = int((y + config[\"lines\"] * 20) // 40)\n\n\t# check if the cell is not out of the game\n\tif not 0 <= x < config['columns'] or not 0 <= y < config['lines']:\n\t\treturn\n\n\t# check if the cell has been already used\n\tif gameMap[x][y]:\n\t\treturn\n\n\t# change cell state\n\tgameMap[x][y] = 1\n\n\t# status\n\tstatus = 0\n\n\t# nothing on the cell\n\tif not isChipPosition(x, y):\n\t\tdrawCircle(x, y, (0, 0, 0))\n\n\t# ship on the cell\n\telse:\n\t\tstatus = 1\n\t\tdrawCircle(x, y, (255, 0, 0))\n\t\tship = getShip(x, y)\n\t\tship['life'] -= 1\n\n\t\t# if the ship is dead\n\t\tif ship['life'] == 0:\n\t\t\tstatus = 2\n\n\t\t# if all ship are dead, show a message\n\t\tif isAllShipDead():\n\t\t\tstatus = 3\n\t\t\tdrawFinishHud()\n\n\t# draw status\n\tdrawStatus(status)\n\n\"\"\"\nOn Click event => Restart Game button\n\"\"\"\ndef onclick_restartGame(x, y):\n\n\t# check if the user has clicked on the button\n\tif not config[\"columns\"] * 20 - 120 <= x <= config[\"columns\"] * 20:\n\t\treturn\n\tif not -config[\"lines\"] * 20 - 35 <= y <= -config[\"lines\"] * 20 - 5:\n\t\treturn\n\n\t# restart game\n\tnewGame()\n\n\"\"\"\nMain\n\"\"\"\ndef main():\n\n\t# global\n\tglobal statusTurtle\n\n\t# turtle\n\tturtle.setup(width=config[\"columns\"] * 40 + 50, height=config[\"lines\"] * 40 + 100)\n\tturtle.title(\"Bataille Navale\")\n\tturtle.hideturtle()\n\n\t# status turtle\n\tstatusTurtle = turtle.Turtle()\n\tstatusTurtle.hideturtle()\n\n\t# new game\n\tnewGame()\n\n\t# onclick\n\tturtle.onscreenclick(onclick)\n\n\t# mainloop\n\tturtle.mainloop()\n\n\"\"\"\nnewGame : init a game\n\"\"\"\ndef newGame():\n\n\t# global\n\tglobal gameMap, ships\n\tglobal loaded\n\n\t# init\n\tloaded = False\n\n\t# game map\n\tgameMap, ships = initMap()\n\n\t# turtle\n\tturtle.reset()\n\tturtle.hideturtle()\n\tturtle.speed(0)\n\tturtle.colormode(255)\n\tturtle.pu()\n\tturtle.goto(0, config[\"lines\"] * 20 + 10)\n\tturtle.color((0, 0, 0))\n\tturtle.write('Bataille Navale', False, align=\"center\", font=(\"Arial\", 20, \"bold\"))\n\n\t# status Turtle\n\tstatusTurtle.reset()\n\tstatusTurtle.hideturtle()\n\tstatusTurtle.speed(0)\n\tstatusTurtle.pu()\n\n\t# draw cells\n\tdrawCells()\n\n\t# [debug] map\n\tif config['debug']:\n\t\tfor ship in ships:\n\t\t\tfor x in range(ship['coords']['x1'], ship['coords']['x2'] + 1):\n\t\t\t\tfor y in range(ship['coords']['y1'], ship['coords']['y2'] + 1):\n\t\t\t\t\tdrawCircle(x, y, (200, 200, 200))\n\n\t# game loaded\n\tloaded = True\n\n\"\"\"\nStart\n\"\"\"\nmain()\n","sub_path":"naval_battle.py","file_name":"naval_battle.py","file_ext":"py","file_size_in_byte":6581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"211058729","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param two ListNodes\n # @return a ListNode\n def mergeTwoLists(self, l1, l2):\n newHead, newTail, cur = None, None, None\n while l1 or l2 :\n if not l1 :\n cur, l2 = l2, l2.next\n elif not l2 :\n cur, l1 = l1, l1.next\n elif l1.val > l2.val :\n cur, l2 = l2, l2.next\n else :\n cur, l1 = l1, l1.next\n \n if not newHead :\n newHead, newTail = cur, cur\n else :\n newTail.next, newTail = cur, cur\n \n if newTail :\n newTail.next = None\n return newHead\n \n \n","sub_path":"python/MergeTwoSortedLists.py","file_name":"MergeTwoSortedLists.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"600779707","text":"import Extensions\nimport FileHelper\nimport Tags\n\ndef getSourceFiles(dataItem) -> list:\n sources = [ ]\n\n if Tags.R_SOURCE_DIRS in dataItem:\n for givenDirectory in dataItem[Tags.R_SOURCE_DIRS]:\n sources += FileHelper.getFilesByExtension(givenDirectory, Extensions.sources, True)\n\n if Tags.SOURCE_DIRS in dataItem:\n for givenDirectory in dataItem[Tags.SOURCE_DIRS]:\n sources += FileHelper.getFilesByExtension(givenDirectory, Extensions.sources, False)\n\n if Tags.INDIVIDUAL_SOURCES in dataItem:\n for sourceFile in dataItem[Tags.INDIVIDUAL_SOURCES]:\n sources.append(FileHelper.normalizePath(sourceFile))\n\n # Remove duplicates\n sources = list(set(sources))\n return sources\n\ndef getHeaderFiles(dataItem) -> list:\n headers = [ ]\n\n if Tags.R_HEADER_DIRS in dataItem:\n for givenDirectory in dataItem[Tags.R_HEADER_DIRS]:\n headers += FileHelper.getFilesByExtension(FileHelper.getAbsolutePath(givenDirectory), Extensions.headers, True)\n\n if Tags.HEADER_DIRS in dataItem:\n for givenDirectory in dataItem[Tags.HEADER_DIRS]:\n headers += FileHelper.getFilesByExtension(FileHelper.getAbsolutePath(givenDirectory), Extensions.headers, False)\n\n if Tags.INDIVIDUAL_HEADERS in dataItem:\n for headerFile in dataItem[Tags.INDIVIDUAL_HEADERS]:\n headers.append(FileHelper.normalizePath(headerFile))\n\n # Remove duplicates\n headers = list(set(headers))\n return headers\n\ndef getIncludeDirs(dataItem):\n includeDirs = [ ]\n\n if Tags.R_INCLUDE_DIRS in dataItem:\n for givenDirectory in dataItem[Tags.R_INCLUDE_DIRS]:\n includeDirs += FileHelper.getDirectories(FileHelper.getAbsolutePath(givenDirectory), True)\n\n if Tags.INCLUDE_DIRS in dataItem:\n for givenDirectory in dataItem[Tags.INCLUDE_DIRS]:\n includeDirs.append(FileHelper.normalizePath(givenDirectory))\n\n # Remove duplicates\n includeDirs = list(set(includeDirs))\n return includeDirs","sub_path":"FileRetriever.py","file_name":"FileRetriever.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"549444840","text":"\"\"\"\n- Point 8 in assignment\n- Solution of pricing anf matching problem\n- Daily customer number drawn from gaussian dist and not known\n- Learning process applied for each arriving customer each day\n- For each arriving customer class drawn at random according to class distribution\n- Promo level distribution as percentage of total constant (2 settings available)\n- Number of available promos calculated using variable that holds average total number of customers\n- Non Stationary Environment -> Change Detection Learners\n\"\"\"\n\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom pricing.learners.ucb import CUMSUM_UCB, CUMSUM_Matching_UCB\nfrom pricing.enviroment.Non_Stationary_Sequential_Environment import NonStationarySequentialEnvironment\n\nnp.random.seed(41148)\nrandom.seed(41148)\n\n# time horizon\nT = 365\n\n# number of phases in environment\nN_PHASES = 2\nPHASE_HORIZON = int(T / N_PHASES)\n# number of customers of each class\nN_CLASSES = 4\nn_class = np.array([200, 150, 50, 100])\n\n# respective costs of the two products\nCOST1 = 550\nCOST2 = 50\n\n# price candidates for each product\nN_PRICES = 7\nprice1 = np.array([600, 700, 800, 900, 1000, 1100, 1200])\n\nprice2 = np.array([70, 75, 80, 85, 90, 95, 100])\n\n# profit margin for each price candidate for product 1\nmargin1 = np.array([50, 150, 250, 350, 450, 550, 650]) / COST1\n\n# profit margin for price candidate (axis 0) and promo (axis 1)\nmargin2 = np.array([[20, 13, 6, 2.5],\n [25, 17.5, 10, 6.25],\n [30, 22, 14, 10],\n [35, 26.5, 18, 13.75],\n [40, 31, 22, 17.5],\n [45, 35.5, 26, 21.25],\n [50, 40, 30, 25]]) / COST2\n\n# two alternative settings for number of promos of each class\nN_PROMOS = 4\npromo_setting_1 = np.array([0.3, 0.15, 0.25])\npromo_setting_2 = np.array([0.25, 0.35, 0.2])\n\npromo_setting = promo_setting_2\n\ncol_promo = [0, 0, 0, 0, 1, 2, 3]\n\n# conversion of each class for each price candidate of product 1\n# phase1\nconv_1_1 = np.array([[0.45, 0.6, 0.57, 0.52, 0.37, 0.15, 0.08],\n [0.5, 0.55, 0.51, 0.47, 0.42, 0.35, 0.21],\n [0.45, 0.42, 0.35, 0.27, 0.14, 0.1, 0.05],\n [0.65, 0.7, 0.67, 0.55, 0.3, 0.21, 0.11]])\n# phase 2 (change in class preference and reduction in demand for classes 1 and 2)\nconv_1_2 = np.array([[0.45, 0.6, 0.57, 0.52, 0.37, 0.15, 0.08],\n [0.5, 0.55, 0.51, 0.47, 0.42, 0.35, 0.21],\n [0.45, 0.42, 0.35, 0.27, 0.14, 0.1, 0.05],\n [0.65, 0.7, 0.67, 0.55, 0.3, 0.21, 0.11]])\nconv_1_2[0] = np.clip(conv_1_2[0] - 0.2, 0.05, 1.)\nconv_1_2[1] = np.clip(conv_1_2[1] - 0.2, 0.05, 1.)\n\nconv_1 = np.zeros((N_PHASES, N_CLASSES, N_PRICES))\nconv_1[0, :, :] = conv_1_1\nconv_1[1, :, :] = conv_1_2\n\n# conversion of each class for each price candidate (axis 0) and promo (axis 1) of product 2\n# phase 1\nconv_2_1 = np.array([[[0.57, 0.6, 0.67, 0.69],\n [0.55, 0.58, 0.65, 0.67],\n [0.53, 0.56, 0.6, 0.65],\n [0.48, 0.55, 0.58, 0.6],\n [0.46, 0.53, 0.56, 0.58],\n [0.43, 0.48, 0.55, 0.56],\n [0.32, 0.46, 0.53, 0.55]],\n [[0.38, 0.4, 0.49, 0.53],\n [0.35, 0.39, 0.43, 0.49],\n [0.31, 0.37, 0.4, 0.43],\n [0.25, 0.35, 0.39, 0.4],\n [0.22, 0.31, 0.37, 0.39],\n [0.2, 0.25, 0.35, 0.37],\n [0.18, 0.22, 0.31, 0.35]],\n [[0.17, 0.24, 0.37, 0.39],\n [0.12, 0.2, 0.3, 0.36],\n [0.08, 0.15, 0.23, 0.3],\n [0.06, 0.12, 0.2, 0.23],\n [0.06, 0.08, 0.15, 0.2],\n [0.05, 0.06, 0.12, 0.16],\n [0.04, 0.06, 0.08, 0.12]],\n [[0.49, 0.53, 0.65, 0.68],\n [0.35, 0.5, 0.55, 0.65],\n [0.29, 0.46, 0.52, 0.55],\n [0.25, 0.34, 0.5, 0.52],\n [0.21, 0.29, 0.46, 0.5],\n [0.18, 0.25, 0.34, 0.46],\n [0.15, 0.21, 0.26, 0.35]]])\n# phase 2 (change in class preference and reduction in demand for classes 3 and 4)\nconv_2_2 = np.array([[[0.38, 0.4, 0.49, 0.53],\n [0.35, 0.39, 0.43, 0.49],\n [0.31, 0.37, 0.4, 0.43],\n [0.25, 0.35, 0.39, 0.4],\n [0.22, 0.31, 0.37, 0.39],\n [0.2, 0.25, 0.35, 0.37],\n [0.18, 0.22, 0.31, 0.35]],\n [[0.57, 0.6, 0.67, 0.69],\n [0.55, 0.58, 0.65, 0.67],\n [0.53, 0.56, 0.6, 0.65],\n [0.48, 0.55, 0.58, 0.6],\n [0.46, 0.53, 0.56, 0.58],\n [0.43, 0.48, 0.55, 0.56],\n [0.32, 0.46, 0.53, 0.55]],\n [[0.49, 0.53, 0.65, 0.68],\n [0.35, 0.5, 0.55, 0.65],\n [0.29, 0.46, 0.52, 0.55],\n [0.25, 0.34, 0.5, 0.52],\n [0.21, 0.29, 0.46, 0.5],\n [0.18, 0.25, 0.34, 0.46],\n [0.15, 0.21, 0.26, 0.35]],\n [[0.17, 0.24, 0.37, 0.39],\n [0.12, 0.2, 0.3, 0.36],\n [0.08, 0.15, 0.23, 0.3],\n [0.06, 0.12, 0.2, 0.23],\n [0.06, 0.08, 0.15, 0.2],\n [0.05, 0.06, 0.12, 0.16],\n [0.04, 0.06, 0.08, 0.12]]])\nconv_2_2[2] = np.clip(conv_2_2[2] - 0.2, 0.05, 1.)\nconv_2_2[3] = np.clip(conv_2_2[3] - 0.2, 0.05, 1.)\n\nconv_2 = np.zeros((N_PHASES, N_CLASSES, N_PRICES, N_PROMOS))\nconv_2[0, :, :, :] = conv_2_1\nconv_2[1, :, :, :] = conv_2_2\n\nn_arms1 = int(conv_1.size / N_CLASSES / N_PHASES)\nn_arms2 = int(conv_2.size / N_CLASSES / N_PROMOS / N_PHASES)\n\n\ndef random_positive_choice(iterable):\n \"\"\"random choice of index from non-zero elements of iterable\"\"\"\n iterable = np.array(iterable)\n indices = np.argwhere(iterable > 0).reshape(-1)\n index = np.random.choice(indices)\n\n return index\n\n\n# Task 8\ndef main():\n # ENVIRONMENT DEFINITION\n environment = NonStationarySequentialEnvironment(margin1=margin1, margin2=margin2, conv_rate1=conv_1,\n conv_rate2=conv_2, horizon=T, n_phases=N_PHASES)\n\n # initialize variable for average of daily customers per day to calculate number of promos\n empirical_customer_amount = 300\n\n # LEARNER DEFINITION\n learner1 = [CUMSUM_UCB(n_arms1, M=1000, alpha=0.001) for n in range(N_CLASSES)]\n extra_promos = N_CLASSES - 1 # we create additional copies of p0 as a hack for the linear sum assignment\n all_promos = N_PROMOS + extra_promos\n learner2 = CUMSUM_Matching_UCB(all_promos * N_CLASSES * N_PRICES, N_CLASSES,\n all_promos * N_PRICES, col_promo * N_PRICES, M=1000, alpha=0.001)\n arm_pull_count_1 = np.zeros((N_PHASES, N_CLASSES, N_PRICES))\n arm_pull_count_m = np.zeros((N_PHASES, N_CLASSES, N_PROMOS))\n arm_pull_count_2 = np.zeros((N_PHASES, N_CLASSES, N_PRICES))\n\n def expected_value_of_reward(pulled_arm1, pulled_arm2, current_customer_class, curr_promo, curr_phase):\n \"\"\"calculate and return expected value of reward for arm choices based on conversion rates\"\"\"\n\n # we need to take into account the proportion of promo codes available impose by the promo setting\n # in the expected conversion rate and margin (promo 0 is no promo)\n if curr_promo != 0:\n conv_promo = promo_setting[curr_promo - 1] * conv_2[\n curr_phase, current_customer_class, pulled_arm2, curr_promo] \\\n + (1 - promo_setting[curr_promo - 1]) * conv_2[\n curr_phase, current_customer_class, pulled_arm2, 0]\n margin_promo = promo_setting[curr_promo - 1] * margin2[pulled_arm2, curr_promo] \\\n + (1 - promo_setting[curr_promo - 1]) * margin2[pulled_arm2, 0]\n else:\n conv_promo = conv_2[curr_phase, current_customer_class, pulled_arm2, curr_promo]\n margin_promo = margin2[pulled_arm2, curr_promo]\n\n reward = margin1[pulled_arm1] * conv_1[curr_phase, current_customer_class, pulled_arm1] * COST1\n if pulled_arm2 != -1:\n reward += margin_promo * conv_1[curr_phase, current_customer_class, pulled_arm1] \\\n * conv_promo * COST2\n return reward\n\n #\n # START LEARNING PROCESS\n #\n print(\"---- Start Learning Process ----\")\n\n rewards1 = []\n rewards2 = []\n expected_rewards = []\n clairvoyant_expected_rewards = []\n arms1 = []\n arms2 = []\n for i in range(T):\n phase = min(int(i / PHASE_HORIZON), N_PHASES - 1)\n print('\\r', \"Progress: {}/{} days\".format(i, T), end=\" \") if i % 10 == 0 else False\n # sample number of customer for each class and truncate at 0 to avoid negative\n round_class_num = np.random.normal(n_class, 10)\n round_class_num = [int(n) if n >= 0 else 0 for n in round_class_num]\n daily_customer_amount = sum(round_class_num)\n\n daily_promos = [n * empirical_customer_amount for n in promo_setting]\n\n current_phase = min(int(i / PHASE_HORIZON), N_PHASES - 1)\n # initialize variables for accumulating round rewards\n round_reward1 = 0\n round_reward2 = 0\n round_expected_reward = 0\n round_clairvoyant_expected = 0\n for c in range(daily_customer_amount):\n # simulate customer arrival by random choice of class which has customers remaining for the day\n customer_class = random_positive_choice(iterable=round_class_num)\n round_class_num[customer_class] -= 1\n chosen_promo = 0\n\n # pull price 1 arm, observe rewards\n arm1 = learner1[customer_class].pull_arm()\n reward1 = environment.sub_round_1(customer_class, arm1) # The second parameter is 0 due to fixed prices\n arm_pull_count_1[current_phase, customer_class, arm1] += 1\n\n # pull price 2 arm if positive reward and update else reward2 = 0\n if reward1 > 0:\n # costs = [learner.pull_arms_2(daily_promos)[2] for learner in learner2]\n\n row_ind, col_ind = learner2.pull_arms(daily_promos)\n chosen_promo = col_ind[customer_class] % N_PRICES - extra_promos\n chosen_price_2 = col_ind[customer_class] // all_promos\n if chosen_promo < 0:\n chosen_promo = 0\n if chosen_promo > 0:\n daily_promos[chosen_promo - 1] -= 1 # daily_promos [#p1 #p2 #p3], chosen_promo [p0 p1 p2 p3]\n\n reward2 = environment.sub_round_2(customer_class, chosen_price_2,\n chosen_promo)\n # The second parameter is 0 due to fixed prices. chosen_promo+1 since [p0 p1 p2 p3]\n arm2 = customer_class * all_promos * N_PRICES + chosen_price_2 * all_promos + chosen_promo\n arm_pull_count_m[current_phase, customer_class, chosen_promo] += 1\n arm_pull_count_2[current_phase, customer_class, chosen_price_2] += 1\n\n if chosen_promo == 0:\n # Update all arms that correspond to P0 for a given customer_class\n for promo in range(extra_promos + 1):\n temp_arm2 = customer_class * all_promos * N_PRICES + chosen_price_2 * all_promos + promo\n learner2.update_one(temp_arm2, reward2)\n else:\n learner2.update_one(arm2, reward2)\n else:\n reward2 = 0\n arm2 = -1\n chosen_price_2 = -1\n\n # update learner 1\n learner1[customer_class].update(arm1, reward1 + reward2)\n\n arms1.append(arm1)\n arms2.append(arm2)\n\n # add rewards to cumulative sums of round rewards and calculate expected rewards\n round_reward1 += reward1 * COST1\n round_reward2 += reward2 * COST2\n round_expected_reward += expected_value_of_reward(arm1, chosen_price_2, customer_class, chosen_promo, phase)\n round_clairvoyant_expected += np.max([[[expected_value_of_reward(i, j, customer_class, p, phase)\n for i in range(N_PRICES)]\n for j in range(N_PRICES)]\n for p in range(N_PROMOS)])\n\n # append round rewards to lists of rewards\n rewards1.append(round_reward1)\n rewards2.append(round_reward2)\n expected_rewards.append(round_expected_reward)\n clairvoyant_expected_rewards.append(round_clairvoyant_expected)\n\n # update empirical number of customers per day\n empirical_customer_amount = (empirical_customer_amount * i + daily_customer_amount) / (i + 1)\n # update stationary environment time counter\n environment.update()\n\n rewards1 = np.array(rewards1)\n rewards2 = np.array(rewards2)\n expected_rewards = np.array(expected_rewards)\n clairvoyant_expected_rewards = np.array(clairvoyant_expected_rewards)\n rewards = rewards1 + rewards2\n\n print(\"\\r\", \"Progress: {}/{} days\".format(T, T))\n\n #\n # LEARNING RESULTS\n #\n print()\n print('LEARNING RESULTS')\n print()\n for phase in range(N_PHASES):\n print(\"Phase {} results:\".format(phase + 1))\n for c in range(N_CLASSES):\n p1 = price1[np.argmax(arm_pull_count_1[phase][c][:])]\n p2 = price2[np.argmax(arm_pull_count_2[phase][c][:])]\n print(\"class {} learners converged to price {} for product 1 and price {} for 2 \".format(c + 1, p1, p2))\n print(\"With the following shows the number of times a class was assigned each promo level:\")\n print(arm_pull_count_m[phase][:][:])\n print()\n print(f'Total profit collected from product 1: {np.sum(rewards1)}')\n print(f'Total profit collected from product 2: {np.sum(rewards2)}')\n\n fig, (ax1, ax2) = plt.subplots(2)\n ax1.plot(np.cumsum(rewards1), label='Product 1')\n ax1.axvline(x=PHASE_HORIZON, c='r', linestyle='--', label=\"Phase Change\")\n ax1.legend(loc='lower right')\n ax2.plot(np.cumsum(rewards2), label='Product 2')\n ax2.axvline(x=PHASE_HORIZON, c='r', linestyle='--', label=\"Phase Change\")\n ax2.legend(loc='lower right')\n fig.suptitle('Cumulative Rewards from each product')\n plt.show()\n\n def moving_average(x, w):\n return np.convolve(x, np.ones(w), 'valid') / w\n\n plt.plot(moving_average(rewards, 10))\n plt.title('10-day moving average of rewards collected')\n plt.axvline(x=PHASE_HORIZON - 10, c='r', linestyle='--', label=\"Phase Change\")\n plt.legend(loc='lower right')\n plt.show()\n\n #\n # REGRETS\n #\n # regrets are calculated in terms of the expected value of the reward for each pulled arm\n\n print()\n print(f'Total expected regret: {np.sum(np.subtract(clairvoyant_expected_rewards, expected_rewards))}')\n\n plt.plot(moving_average(expected_rewards, 10), label='Expected rewards for Matching UCB')\n plt.plot(moving_average(clairvoyant_expected_rewards, 10), label='Expected rewards for Clairvoyant Algorithm',\n color='r')\n plt.axvline(x=PHASE_HORIZON - 10, c='r', linestyle='--', label=\"Phase Change\")\n plt.legend(loc='lower right')\n plt.title('10-day moving average of expected rewards of each algorithm')\n plt.ylim(500, max(clairvoyant_expected_rewards))\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"task8.py","file_name":"task8.py","file_ext":"py","file_size_in_byte":15849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"620374922","text":"def bubble(a):\r\n j = 0\r\n for j in range(len(a) - 1 - j):\r\n for i in range(len(a) - 1):\r\n if a[i] > a[i + 1]:\r\n temp = a[i]\r\n a[i] = a[i + 1]\r\n a[i + 1] = temp\r\n j += 1\r\n return a\r\n\r\n\r\ndef merge(d, e):\r\n de = d + e\r\n return de\r\n\r\n\r\nb = list(map(int, input().split()))\r\nc = list(map(int, input().split()))\r\nprint(*bubble(merge(b, c)))\r\n","sub_path":"bubbleSortMerge2lists.py","file_name":"bubbleSortMerge2lists.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"55121030","text":"from bs4 import BeautifulSoup\nimport requests\nimport sys\nfrom requests.exceptions import MissingSchema\n\n\nclass Scraper:\n def __init__(self, url=None):\n self.url = url\n\n def scrape_article(self):\n text = []\n text_updated = []\n try:\n scrape = requests.get(self.url)\n soup = BeautifulSoup(scrape.text, 'html.parser')\n all_paragraphs = soup.find('div', {'class':'story-body__inner'})\n try:\n paragraph = all_paragraphs.find_all('p')\n for p in paragraph:\n text.append(p.get_text() + \" \")\n text_updated = [i.replace('£', '') for i in text] # remove £\n except AttributeError:\n print('Not a valid URL.')\n sys.exit()\n except MissingSchema:\n print('Not a valid URL.')\n return text\n return text_updated\n\n def scrape_tweets(self):\n text = []\n try:\n scrape = requests.get(self.url)\n soup = BeautifulSoup(scrape.content, 'html.parser')\n all_tweets = soup.find_all('p', {'class':'TweetTextSize TweetTextSize--jumbo js-tweet-text tweet-text'})\n for tweet in all_tweets:\n text.append(tweet.get_text())\n except MissingSchema:\n print('Not a valid URL.')\n return text\n return text\n\n def scrape_user_tweets(self):\n text = []\n try:\n scrape = requests.get(self.url)\n soup = BeautifulSoup(scrape.text, 'html.parser')\n all_tweets = soup.find_all('p', {'class':'TweetTextSize TweetTextSize--normal js-tweet-text tweet-text'})\n for tweet in all_tweets:\n text.append(tweet.get_text())\n except MissingSchema:\n print('Not a valid URL.')\n return text\n return text\n\n def set_url(self, url):\n self.url = url.strip()\n\n def set_user_url(self, user):\n self.url = \"https://twitter.com/\" + user.strip()\n","sub_path":"tool/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"120957276","text":"'''\nCreated on 6 Oct 2018\n\n@author: bjoern\n'''\nimport gi\nfrom Creatures.Player import Archetypes, Player, PlayerInfo\nfrom Mechanics.Game import Game\nfrom UI.Tiles import TileProvider\nfrom Mechanics.Level import WallInfo\ngi.require_version(\"Gtk\", \"3.0\")\nfrom gi.repository import Gtk, Gdk\n\nclass StyleProviders(object):\n _MAIN_STYLE_CSS = b\"\"\"\n window {\n background-color: #000;\n color: #0F0;\n font-family: \"Telegrama\";\n }\n \"\"\"\n _ERROR_STYLE_CSS = b\"\"\"\n label {\n background-color: #000;\n color: #F00;\n font-family: \"Telegrama\";\n }\n \"\"\"\n MAIN_STYLE = Gtk.CssProvider()\n MAIN_STYLE.load_from_data(_MAIN_STYLE_CSS)\n ERROR_STYLE = Gtk.CssProvider()\n ERROR_STYLE.load_from_data(_ERROR_STYLE_CSS)\n \nclass MouseButtons(object):\n LEFT = 1\n RIGHT = 1\n\nclass StartButton(Gtk.EventBox):\n def __init__(self, main_window):\n super(StartButton, self).__init__()\n self._main = main_window\n self.add(Gtk.Label(\"Start the Game!\"))\n self.connect(\"button-release-event\", self.start)\n \n def start(self, widget, event):\n if event.button == MouseButtons.LEFT:\n self._main.open_character_creator()\n \nclass CharacterCreator(Gtk.Grid):\n class ArchetypeChoice(Gtk.EventBox):\n def __init__(self, text, archetype, creator):\n super(CharacterCreator.ArchetypeChoice,self).__init__() \n self._creator = creator\n self._archetype = archetype\n self.add(Gtk.Label(text))\n self.connect(\"button-release-event\", lambda w,e : self._creator.process_archetype_choice(self._archetype) )\n \n class ErrorLabel(Gtk.Label):\n def __init__(self, text):\n super(CharacterCreator.ErrorLabel,self).__init__(text)\n self.get_style_context().add_provider(StyleProviders.ERROR_STYLE, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) \n FULL_WIDTH = 10\n def __init__(self, main_window):\n super(CharacterCreator, self).__init__()\n self._main = main_window\n heading = Gtk.Label(\"Choose your archetype\")\n heading.set_justify(Gtk.Justification.CENTER)\n self.attach(heading, top=1, left=1, width=CharacterCreator.FULL_WIDTH, height=1)\n self.keyboard_buttons = {}\n self.keyboard_buttons[Gdk.KEY_a] = CharacterCreator.ArchetypeChoice( \"a - Citizen \", Archetypes.CITIZEN, self)\n self.keyboard_buttons[Gdk.KEY_b] = CharacterCreator.ArchetypeChoice( \"b - Zealot \", Archetypes.ZEALOT , self)\n self.keyboard_buttons[Gdk.KEY_c] = CharacterCreator.ArchetypeChoice( \"c - Mutant \", Archetypes.MUTANT , self)\n self.attach(self.keyboard_buttons[Gdk.KEY_a], top=2, left=1, width=1, height=1 )\n self.attach(self.keyboard_buttons[Gdk.KEY_b] , top=2, left=3, width=1, height=1 )\n self.attach(self.keyboard_buttons[Gdk.KEY_c], top=2, left=5, width=1, height=1 )\n self.attach(CharacterCreator.ErrorLabel(\"d - Locked \"), top=3, left=1, width=1, height=1 )\n self.attach(CharacterCreator.ErrorLabel(\"e - Locked \"), top=3, left=3, width=1, height=1 )\n self.attach(CharacterCreator.ErrorLabel(\"f - Locked \"), top=3, left=5, width=1, height=1 )\n \n def process_archetype_choice(self, archetype):\n self._main.start_game(Player(archetype))\n \n def handle_key_press(self, widget, event):\n try:\n self.process_archetype_choice(self.keyboard_buttons[event.keyval]._archetype)\n except KeyError:\n pass\n \nclass GameUI(Gtk.Grid):\n def __init__(self, game):\n super(GameUI,self).__init__()\n self._game = game\n self._init_player_info()\n self._game.start_first_level()\n self._init_map()\n \n def _init_map(self):\n self.MAP_VIEW_SIZE_X = 30\n self.MAP_VIEW_SIZE_Y = 30\n map_info = self._game.get_map_info()\n self._map = Map(map_info)\n self.attach(self._map, top=1, left=1, width=self.MAP_VIEW_SIZE_X, height=self.MAP_VIEW_SIZE_Y)\n \n def _init_player_info(self):\n player_info = self._game.get_player_info()\n MAP_LEFT_END = 31\n self.attach(Gtk.Label(\"Archetype: \"+Archetypes.to_string(player_info.archetype)), top=1, left=MAP_LEFT_END, width=1, height=1)\n \n def handle_key_press(self, widget, event):\n pass\n \nclass Map(Gtk.Grid): \n def __init__(self, map_info):\n super(Map,self).__init__()\n self._tile_provider = TileProvider()\n for x in range(map_info.width_x):\n for y in range(map_info.width_y):\n map_cell = MapCell((x,y),map_info.cells[(x,y)], self._tile_provider)\n self.attach(map_cell, top=x, left=y, width=1, height=1 )\n \nclass MapCell(Gtk.EventBox):\n def __init__(self, position, cell_info, tile_provider):\n super(MapCell,self).__init__()\n self._position = position \n if cell_info.is_empty:\n self._image = Gtk.Image.new_from_pixbuf(tile_provider.get_tile(\"metal_floor\"))\n elif isinstance(cell_info.things[0], WallInfo):\n self._image = Gtk.Image.new_from_pixbuf(tile_provider.get_tile(\"metal_wall\"))\n elif isinstance(cell_info.things[0], PlayerInfo):\n self._image = Gtk.Image.new_from_pixbuf(tile_provider.get_tile(\"player\")) \n self.add(self._image) \n \nclass MainWindow(Gtk.Window):\n def __init__(self):\n Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), StyleProviders.MAIN_STYLE, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)\n super(MainWindow, self).__init__(title =\"Solar Winter\",\n default_height =800, \n default_width =800, \n window_position =Gtk.WindowPosition.CENTER)\n self.connect(\"destroy\", Gtk.main_quit)\n self.connect(\"key-release-event\", self.handle_key_press)\n self._start_button = StartButton(self)\n self._character_creator = CharacterCreator(self)\n self.add(self._start_button)\n self.show_all()\n \n def open_character_creator(self):\n self.remove(self._start_button)\n self.add(self._character_creator)\n self.show_all()\n \n def start_game(self, player):\n self.remove(self._character_creator)\n self._game = Game(player)\n self._game_ui = GameUI(self._game)\n self.add(self._game_ui)\n self.show_all()\n \n def handle_key_press(self, widget, event):\n self.get_child().handle_key_press(widget, event)\n","sub_path":"SciFiRogue/SciFiRogue/UI/MainWindow.py","file_name":"MainWindow.py","file_ext":"py","file_size_in_byte":6720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"642473238","text":"# LIBRARIES FOR TOOL\nimport arcpy\nimport fiona\nfrom shapely import affinity\nfrom shapely.geometry import Point, LineString, shape\nfrom shapely.ops import cascaded_union\n\n# open document with all center points of old shapes\npoint_data_in = arcpy.GetParameterAsText(0) # Point(0, 0) # radial sweep centre point\ninput_lines_in = arcpy.GetParameterAsText(1)\noutput = arcpy.GetParameterAsText(2)\n\n# PARAMETERS\nsweep_res = arcpy.GetParameterAsText(3) # sweep resolution (degrees)\nsweep_radius = arcpy.GetParameterAsText(4) # sweep radius\nbuffer_radius = arcpy.GetParameterAsText(5) # radius of buffer for intersection\n\npoint_data = fiona.open(point_data_in)\ninput_lines = fiona.open(input_lines_in)\n\n# permanent lists needed for final output:\nmin_dist_id_list = []\nmin_dist_list = []\n\n# checks whether data is Point of LineString input and converts LineString layer to Point is necessary\nif point_data[0]['geometry']['type'] == 'Point':\n arcpy.AddMessage('Point = True')\n pass\nelif point_data[0]['geometry']['type'] == 'LineString':\n arcpy.AddMessage('LineString = True')\n raise ValueError('Geen geldige feature - input feature dient punt te zijn')\nelse:\n raise ValueError('Geen geldige feature - input feature dient punt te zijn')\n\n\n####### CREATE RADIAL SWEEP TOOL #######\n\n\nfor i in range(len(point_data)):\n x, y = point_data[i]['geometry']['coordinates']\n focal_pt = Point(x, y)\n\n # create the radial sweep lines\n line = LineString([(focal_pt.x, focal_pt.y),\n (focal_pt.x, focal_pt.y + float(sweep_radius))])\n\n sweep_lines = [affinity.rotate(line, i2, (focal_pt.x, focal_pt.y)) \\\n for i2 in range(0, 360, int(sweep_res))]\n\n radial_sweep = cascaded_union(sweep_lines)\n # print i, radial_sweep (check if radial sweep works)\n\n ####### USE RADIAL SWEEP TOOL ON NEAR FEATURES #######\n\n # load the input lines and combine them into one geometry\n input_shapes = [shape(f['geometry']) for f in input_lines]\n all_input_lines = cascaded_union(input_shapes)\n\n perimeter = []\n # traverse each radial sweep line and check for intersection with input lines\n for radial_line in radial_sweep:\n inter = radial_line.intersection(all_input_lines)\n\n if inter.type == \"MultiPoint\":\n # radial line intersects at multiple points\n inter_dict = {}\n for inter_pt in inter:\n inter_dict[focal_pt.distance(inter_pt)] = inter_pt\n # save the nearest intersected point to the sweep centre point\n perimeter.append(inter_dict[min(inter_dict.keys())])\n\n if inter.type == \"Point\":\n # radial line intersects at one point only\n perimeter.append(inter)\n\n if inter.type == \"GeometryCollection\":\n # radial line doesn't intersect, so skip\n pass\n\n # combine the nearest perimeter points into one geometry\n solution = cascaded_union(perimeter)\n arcpy.AddMessage('checking input feature point ID {}'.format(i))\n\n ####### USE RADIAL SWEEP TOOL ON NEAR FEATURES #######\n\n # create list with all distances for focal_pt\n distance_list = []\n if solution.type == \"MultiPoint\":\n for distance in range(len(solution)):\n distance_test = focal_pt.distance(solution[distance])\n distance_list.append(distance_test)\n\n # select smallest distance and index from distance_list\n closest_id = distance_list.index(min(distance_list))\n min_dist = min(distance_list)\n min_dist_list.append(min_dist)\n # print distance_list.index(min(distance_list))\n arcpy.AddMessage(\"{} meter is lowest distance to near feature\".format(round(min(distance_list)),2))\n\n # convert multipoint to individual points\n individual_points = [(pt.x, pt.y) for pt in solution]\n closest_point = Point(individual_points[closest_id])\n\n else:\n closest_point = solution\n min_dist = focal_pt.distance(solution)\n min_dist_list.append(min_dist)\n\n ####### BUFFER AND INTERSECT #######\n\n # create buffer of 0.1 meter around point\n buffer_x = closest_point.buffer(float(buffer_radius))\n\n # test for intersection\n closest_shape = {}\n for i in range(len(input_lines)):\n input_line = LineString(input_lines[i]['geometry']['coordinates'])\n if buffer_x.intersects(input_line):\n arcpy.AddMessage('intersect with near feature ID {}'.format(i))\n min_dist_id_list.append(i)\n filter_test = input_lines[input_lines[0]['id'] == u'{}'.format(i)]\n closest_shape = input_line\n else:\n pass\n # print 'no intersect with {}'.format(i)\n\narcpy.AddMessage(\"..Analysing completed\")\n\n####### WRITING NEAR FEATURE SHAPEFILE #######\narcpy.AddMessage(\"..Updating attribute table\")\n\nidx = 0\n\n# writes extra columns\nwith fiona.open(point_data_in, 'r') as source:\n source_schema = source.schema\n source_schema['properties']['min_id'] = 'float'\n source_schema['properties']['min_dist'] = 'float'\n\n with fiona.open(\n output, 'w',\n crs_wkt=source.crs_wkt,\n driver=source.driver,\n schema=source_schema,\n ) as sink:\n for f in source:\n if idx < len(min_dist_id_list):\n a = min_dist_id_list[idx]\n b = min_dist_list[idx]\n idx = idx + 1\n else:\n pass\n\n f['properties'].update(min_id=a,\n min_dist=b,\n )\n sink.write(f)\n\narcpy.AddMessage(\"Successfully completed run\")\n\n","sub_path":"4_a3_nearest_feature_WIT.py","file_name":"4_a3_nearest_feature_WIT.py","file_ext":"py","file_size_in_byte":5641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"77648010","text":"from concentration import Concentration\nfrom pathway import Pathway\nfrom pathway import pathways\n\ndef naive_argmax(arr):\n\tbest = 0\n\tcurr = arr[0]\n\tfor i in range(len(arr)):\n\t\tif arr[i] > curr:\n\t\t\tcurr = arr[i]\n\t\t\tbest = i\n\treturn best\nclass Computer_Science_SCB(Concentration):\n\t\"\"\"\n\tsatisfied:\n\t\tgiven list of classes taken, \n\t\treturns list of classes fulfilling the concentration\n\t\t** takes into account pathway requirements this time ** \n\t\"\"\"\t \n\tdef satisfied(self, classes_taken):\n\t\tclasses = list(classes_taken)\n\t\tsatisfied = Concentration.satisfied(self, classes_taken)\n\t\t\n\t\t# clear the upper levels T.T\n\t\tfor i in range(8, 16):\n\t\t\tsatisfied[i] = 0\n\n\t\t# figure out which pathways we're closest to completing\n\t\tpercent = [path.percent_complete(classes) for path in pathways]\n\t\tind = 8\n\n\t\t# add pathways.\n\t\tx = naive_argmax(percent)\n\t\ty = pathways[x].satisfied(classes)[-2:]\n\t\tsatisfied[ind] = y[0]\n\t\tsatisfied[ind + 1] = y[1]\n\t\tind += 2\n\t\tif y[0] != 0: classes.remove(y[0])\n\t\tif y[1] != 0: classes.remove(y[1])\n\n\t\tpercent = [path.percent_complete(classes) for path in pathways]\n\t\tpercent[x] = -1\n\t\tx2 = naive_argmax(percent)\n\t\ty = pathways[x2].satisfied(classes)[-2:]\n\t\tsatisfied[ind] = y[0]\n\t\tsatisfied[ind + 1] = y[1]\n\t\tind += 2\n\n\t\t# clear classes of satisfied reqs.\n\t\tfor i in satisfied:\n\t\t\tif i != 0 and i in classes:\n\t\t\t\tclasses.remove(i)\n\n\t\tnon_core_related = list(set(pathways[x].get_non_core_related(thousand_level)).intersection(pathways[x2].get_non_core_related(thousand_level)))\n\t\t\n\t\t# get the rest!\n\t\trest = [non_core_related, upper_level,thousand_level,thousand_level]\n\t\tfor r in range(len(rest)):\n\t\t\tfor c in rest[r]:\n\t\t\t\tif c in classes:\n\t\t\t\t\tsatisfied[ind+r] = c\n\t\t\t\t\tclasses.remove(c)\n\t\t\t\t\tbreak\n\n\t\treturn satisfied\n\nclass Computer_Science_AB(Concentration):\n\t\n\n\t\"\"\"\n\tsatisfied:\n\t\tgiven list of classes taken, \n\t\treturns list of classes fulfilling the concentration\n\t\t** takes into account pathway requirements this time ** \n\t\"\"\"\t \n\tdef satisfied(self, classes_taken):\n\t\tclasses = list(classes_taken)\n\t\tsatisfied = Concentration.satisfied(self, classes_taken)\n\t\t\n\t\t# clear the upper levels T.T\n\t\tfor i in range(6, 10):\n\t\t\tsatisfied[i] = 0\n\n\t\t# figure out which pathways we're closest to completing\n\t\tpercent = [path.percent_complete(classes) for path in pathways]\n\t\tind = 6\n\n\t\t# add pathway\n\t\tx = naive_argmax(percent)\n\t\ty = pathways[x].satisfied(classes)[-2:]\n\t\tprint(y)\n\t\tsatisfied[ind] = y[0]\n\t\tsatisfied[ind + 1] = y[1]\n\t\tind += 2\n\n\t\t# clear classes of satisfied reqs.\n\t\tfor i in satisfied:\n\t\t\tif i != 0:\n\t\t\t\tclasses.remove(i)\n\n\t\t# get the rest!\n\t\trest = [pathways[x].get_non_core_related(thousand_level), thousand_level]\n\t\tfor r in range(len(rest)):\n\t\t\tfor c in rest[r]:\n\t\t\t\tif c in classes:\n\t\t\t\t\tsatisfied[ind+r] = c\n\t\t\t\t\tclasses.remove(c)\n\t\t\t\t\tbreak\n\n\t\treturn satisfied\n\n\n# /* ----- TESTING ----- */\n\nall_classes = ['CSCI 0020', 'CSCI 0030', 'CSCI 0081', 'CSCI 0082', 'CSCI 0100', 'CSCI 0111', 'CSCI 0130', 'CSCI 0150', 'CSCI 0160', 'CSCI 0170', 'CSCI 0180', 'CSCI 0190', 'CSCI 0220', 'CSCI 0320', 'CSCI 0330', 'CSCI 0530', 'CSCI 1010', 'CSCI 1230', 'CSCI 1234', 'CSCI 1250', 'CSCI 1260', 'CSCI 1270', 'CSCI 1280', 'CSCI 1300', 'CSCI 1320', 'CSCI 1370', 'CSCI 1380', 'CSCI 1410', 'CSCI 1420', 'CSCI 1430', 'CSCI 1450', 'CSCI 1460', 'CSCI 1470', 'CSCI 1550', 'CSCI 1570', 'CSCI 1575', 'CSCI 1600', 'CSCI 1650', 'CSCI 1670', 'CSCI 1680', 'CSCI 1690', 'CSCI 1730', 'CSCI 1800', 'CSCI 1805', 'CSCI 1810', 'CSCI 1820', 'CSCI 1870', 'CSCI 1900', 'CSCI 1950N', 'CSCI 1950Y', 'CSCI 1951A', 'CSCI 1951C', 'CSCI 1951I', 'CSCI 1951K', 'CSCI 1951R', 'CSCI 1970', 'CSCI 1971', 'CSCI 1972', 'CSCI 2240', 'CSCI 2270', 'CSCI 2470', 'CSCI 2500B', 'CSCI 2890', 'CSCI 2950V', 'CSCI 2951F', 'CSCI 2951I', 'CSCI 2951K', 'CSCI 2951U', 'CSCI 2952F', 'CSCI 2952G', 'CSCI 2980', 'CSCI 2990']\n\nprereqs = [\"MATH 100\", \"MATH 170\", \"MATH 190\"]\nintro1 = [\"CSCI 0150\", \"CSCI 0170\", \"CSCI 0190\"]\nintro2 = [\"CSCI 0160\", \"CSCI 0180\", \"CSCI 0320\", \"CSCI 0330\"]\nfoundations = [\"CSCI 0220\", \"CSCI 1010\"]\nmath = [\"MATH 0520\", \"MATH 540\", \"MATH 0180\", \"MATH 0200\", \"MATH 0350\", \"APMA 1650\", \"APMA 1655\", \"CSCI 1450\", \"CSCI 540\"]\nsystems = [\"CSCI 0330\", \"CSCI 0320\"]\nintermediates = foundations + math + systems\nupper_level = all_classes[12:]\nthousand_level = upper_level[3:]\n \n\n\ncs_scb = [prereqs, intro1, intro2, foundations, math, systems, intermediates,intermediates,upper_level,thousand_level,thousand_level,thousand_level,thousand_level,thousand_level,thousand_level,thousand_level]\ncs_scb_names = [\"prereqs\", 'intro1', 'intro2', 'foundations', 'math', 'systems', 'intermediates','intermediates','pathway','pathway','pathway','pathway','upper_level','thousand_level','thousand_level','thousand_level',]\ncs_ab_names = ['prereqs', 'intro1', 'intro2', 'intermediates', 'intermediates', 'intermediates', 'pathway', 'pathway', 'thousand_level', 'thousand_level']\ncs_ab = [prereqs, intro1, intro2, intermediates, intermediates, intermediates, thousand_level, thousand_level, thousand_level, thousand_level]\ncomputer_science_ab = Concentration(10, cs_ab, cs_ab_names, \"\", \"Computer Science AB\")\ncomputer_science_scb = Computer_Science_SCB(16, cs_scb, cs_scb_names, \"One of the pathway courses must be your senior capstone\", \"Computer Science SCB\")\n\n\n","sub_path":"calculations/cs_scb.py","file_name":"cs_scb.py","file_ext":"py","file_size_in_byte":5247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"234743843","text":"import torch\n\n\nclass SequenceLabeler(object):\n def __init__(self, model, parser):\n self.model = model\n p = next(filter(lambda p: p.requires_grad, model.parameters()))\n self.use_cuda = p.is_cuda\n self.device = p.get_device() if self.use_cuda else None\n self.parser = parser\n self.parser_tune = model.config.parser_tune\n\n def parse_one_batch(self, dep_words, dep_extwords, dep_masks, bTrain):\n if bTrain and self.parser_tune == 1:\n self.parser.train()\n else:\n self.parser.eval()\n\n parser_outputs = self.parser.forward(dep_words, dep_extwords, dep_masks)\n # move the hidden vector of the first fake word to the last position\n proof_outputs = []\n for parser_output in parser_outputs:\n chunks = torch.split(parser_output.transpose(1, 0), split_size_or_sections=1, dim=0)\n proof_output = torch.cat(chunks[1:], 0)\n proof_outputs.append(proof_output.transpose(1, 0))\n\n return proof_outputs\n\n def forward(self, words, extwords, predicts, masks, dep_words, dep_extwords, dep_masks):\n if self.use_cuda:\n words, extwords = words.cuda(self.device), extwords.cuda(self.device)\n predicts = predicts.cuda(self.device)\n dep_words, dep_extwords = dep_words.cuda(self.device), dep_extwords.cuda(self.device)\n masks, dep_masks = masks.cuda(self.device), dep_masks.cuda(self.device)\n\n synx = self.parse_one_batch(dep_words, dep_extwords, dep_masks, self.model.training)\n label_scores = self.model.forward(words, extwords, predicts, synx, masks)\n # cache\n self.label_scores = label_scores\n\n def compute_loss(self, answers, masks):\n if self.use_cuda:\n answers = answers.cuda(self.device)\n masks = masks.cuda(self.device)\n loss = self.model.compute_loss(self.label_scores, answers, masks)\n\n return loss\n\n def compute_accuracy(self, answers):\n scores = self.label_scores.data\n target = answers.data\n pred = scores.max(2)[1]\n non_padding = target.ne(self.model.PAD)\n num_words = non_padding.sum()\n num_correct = pred.eq(target).masked_select(non_padding).sum()\n return num_correct, num_words\n\n def labeler(self, words, extwords, predicts, masks, dep_words, dep_extwords, dep_masks):\n if words is not None:\n self.forward(words, extwords, predicts, masks, dep_words, dep_extwords, dep_masks)\n\n predict_labels = self.model.decode(self.label_scores, masks)\n\n return predict_labels\n","sub_path":"sequence_labeling/SLBaselineSYNJoint/driver/SLHelper.py","file_name":"SLHelper.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"270059520","text":"from django.shortcuts import render\nfrom django.views.generic import View\nfrom django.http import JsonResponse\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger #分页\nfrom django.views.decorators.http import require_POST,require_GET\n\nfrom .models import Back, Adv, Ad, Back_Menu, Index_Menu, Message\nfrom .forms import AdminForm, AdvForm, AdForm, BackMenuForm, IndexMenuForm\nfrom apps.backbase.models import Back_Module, Index_Module\n\nfrom utils import restful, get_page, image_manage, con_function\n\n\ndef index(request):\n return render(request, 'back/index/index.html')\n\n\nclass Login(View):\n '''\n 后台管理员登录\n '''\n def get(self, request):\n '''\n 管理员登录页面\n '''\n return render(request, 'back/login/login.html')\n\n def post(self, request):\n '''\n 管理员登录操作\n '''\n account = request.POST.get('account', '')\n password = request.POST.get('password', '')\n res = Back.objects.filter(account=account, password=password).values('id', 'account', 'nickname', 'level')\n if res :\n request.session['admin'] = res[0]\n return restful.ok('登录成功!')\n else :\n return restful.params_error('登录失败,帐号或密码错误!')\n\ndef admin(request):\n '''\n 管理员模块\n '''\n page = int(request.GET.get('p', 1))\n\n admins = Back.objects.all()\n paginator = Paginator(admins, 2)\n page_obj = paginator.page(page)\n pagination_data = get_page.get_pagination_data(paginator, page_obj)\n\n context = {\n 'paginator': paginator,\n 'page_obj': page_obj,\n 'admins': page_obj.object_list\n }\n context.update(pagination_data)\n return render(request, 'back/admin/index.html', context=context)\n\nclass AdminInsert(View):\n def get(self, request):\n return render(request, 'back/admin/admin_insert.html')\n\n def post(self, request):\n form = AdminForm(request.POST)\n if form.is_valid():\n account = form.cleaned_data.get('account')\n password = form.cleaned_data.get('password')\n level = form.cleaned_data.get('level')\n nickname = form.cleaned_data.get('nickname')\n Back.objects.create(account=account, password=password, level=level, nickname=nickname)\n return restful.ok('创建管理员成功!')\n else :\n return restful.params_error(message=form.errors)\n\nclass AdminUpdate(View):\n def get(self, request, id):\n detail = Back.objects.get(pk=id)\n return render(request, 'back/admin/admin_update.html', context={'detail': detail})\n \n def post(self, request, id):\n id = request.POST.get('id')\n form = AdminForm(request.POST)\n if form.is_valid():\n back = Back.objects.get(pk=id)\n back.account = form.cleaned_data.get('account')\n back.password = form.cleaned_data.get('password')\n back.level = form.cleaned_data.get('level')\n back.nickname = form.cleaned_data.get('nickname')\n res = back.save()\n return restful.ok('修改管理员信息成功!')\n else:\n return restful.params_error(message=form.errors)\n\ndef admin_delete(request):\n id = request.POST.get('id')\n back = Back.objects.get(pk=id)\n back.delete()\n return restful.ok('删除成功!')\n\ndef adv(request):\n '''\n 广告位模块\n '''\n page = int(request.GET.get('p', 1))\n\n adv = Adv.objects.all()\n paginator = Paginator(adv, 10)\n page_obj = paginator.page(page)\n pagination_data = get_page.get_pagination_data(paginator, page_obj)\n\n context = {\n 'paginator': paginator,\n 'page_obj': page_obj,\n 'adv': page_obj.object_list\n }\n context.update(pagination_data)\n return render(request, 'back/adv/adv.html', context=context)\n\nclass AdvInsert(View):\n def get(self, request):\n return render(request, 'back/adv/adv_insert.html')\n\n def post(self, request):\n form = AdvForm(request.POST)\n if form.is_valid():\n adv_name = form.cleaned_data.get('adv_name')\n adv_remark = form.cleaned_data.get('adv_remark')\n Adv.objects.create(adv_name=adv_name, adv_remark=adv_remark)\n return restful.ok('添加广告位成功!')\n else :\n return restful.params_error(message=form.errors)\n\nclass AdvUpdate(View):\n def get(self, request, id):\n detail = Adv.objects.get(pk=id)\n return render(request, 'back/adv/adv_update.html', context={'detail': detail})\n \n def post(self, request ,id):\n id = request.POST.get('id')\n form = AdvForm(request.POST)\n if form.is_valid():\n adv = Adv.objects.get(pk=id)\n adv.adv_name = form.cleaned_data.get('adv_name')\n adv.adv_remark = form.cleaned_data.get('adv_remark')\n res = adv.save()\n return restful.ok('修改广告位信息成功!')\n else:\n return restful.params_error(message=form.errors)\n\ndef adv_delete(request):\n id = request.POST.get('id')\n adv = Adv.objects.get(pk=id)\n adv.delete()\n return restful.ok('删除成功!')\n\ndef ad(request):\n '''\n 广告模块\n '''\n page = int(request.GET.get('p', 1))\n\n ad = Ad.objects.all()\n paginator = Paginator(ad, 10)\n page_obj = paginator.page(page)\n pagination_data = get_page.get_pagination_data(paginator, page_obj)\n\n context = {\n 'paginator': paginator,\n 'page_obj': page_obj,\n 'ad': page_obj.object_list\n }\n context.update(pagination_data)\n return render(request, 'back/ad/ad.html', context=context)\n\nclass AdInsert(View):\n def get(self, request):\n adv = Adv.objects.all()\n return render(request, 'back/ad/ad_insert.html', context={'adv': adv})\n\n def post(self, request):\n form = AdForm(request.POST)\n if form.is_valid():\n title = form.cleaned_data.get('title')\n adv_id = form.cleaned_data.get('adv_id')\n adv = Adv.objects.get(pk=adv_id)\n intro = form.cleaned_data.get('intro')\n image = form.cleaned_data.get('image')\n url = form.cleaned_data.get('url')\n sort = form.cleaned_data.get('sort')\n status = form.cleaned_data.get('status')\n remark = form.cleaned_data.get('remark')\n Ad.objects.create(title=title, adv=adv, intro=intro, image=image, url=url, sort=sort, status=status, remark=remark)\n return restful.ok('添加广告位成功!')\n else :\n if request.POST.get('image') != '':\n image_cls = image_manage.image()\n image_cls.delete_image(request.POST.get('image'))\n return restful.params_error(message=form.errors)\n\nclass AdUpdate(View):\n def get(self, request, id):\n detail = Ad.objects.get(pk=id)\n adv = Adv.objects.all()\n return render(request, 'back/ad/ad_update.html', context={'adv': adv, 'detail': detail})\n \n def post(self, request, id):\n id = request.POST.get('id')\n form = AdForm(request.POST)\n if form.is_valid():\n ad = Ad.objects.get(pk=id)\n ad.title = form.cleaned_data.get('title')\n adv_id = form.cleaned_data.get('adv_id')\n ad.adv = Adv.objects.get(pk=adv_id)\n ad.intro = form.cleaned_data.get('intro')\n new_image = form.cleaned_data.get('image')\n old_image = ''\n if new_image != '':\n old_image = ad.image\n ad.image = new_image\n ad.url = form.cleaned_data.get('url')\n ad.sort = form.cleaned_data.get('sort')\n ad.status = form.cleaned_data.get('status')\n ad.remark = form.cleaned_data.get('remark')\n ad.save()\n if old_image != '':\n image_cls = image_manage.image()\n image_cls.delete_image(old_image)\n return restful.ok('修改广告位成功!')\n else :\n if request.POST.get('image') != '':\n image_cls = image_manage.image()\n image_cls.delete_image(request.POST.get('image'))\n return restful.params_error(message=form.errors)\n\ndef ad_delete(request):\n id = request.POST.get('id')\n ad = Ad.objects.get(pk=id)\n old_image = ad.image\n ad.delete()\n if old_image != '':\n image_cls = image_manage.image()\n image_cls.delete_image(old_image)\n return restful.ok('删除成功!')\n\n@require_POST\ndef ad_change_status(request):\n id = request.POST.get('id')\n post_status = request.POST.get('status')\n status = (1 if int(post_status)==0 else 0)\n Ad.objects.filter(id=id).update(status=status)\n return restful.ok('状态修改成功')\n\n@require_POST\ndef ad_change_sort(request):\n id = request.POST.get('id')\n sort = request.POST.get('sort')\n Ad.objects.filter(id=id).update(sort=sort)\n return restful.ok('排序修改成功')\n\ndef backmenu(request):\n '''\n 后台菜单管理\n '''\n menu = Back_Menu.objects.all()\n sort_list = []\n sort_list = con_function.infinite_pole_sorting(menu, sort_list)\n\n return render(request, 'back/menu/backmenu.html', context={'menu': sort_list})\n\nclass BackmenuInsert(View):\n def get(self, request):\n module_list = Back_Module.objects.all()\n top_menu = Back_Menu.objects.filter(pid=None)\n return render(request, 'back/menu/backmenu_insert.html', context={'top_menu': top_menu, 'module_list': module_list})\n \n def post(self, request):\n form = BackMenuForm(request.POST)\n if form.is_valid():\n title = form.cleaned_data.get('title')\n module = form.cleaned_data.get('module')\n icon = form.cleaned_data.get('icon')\n remark = form.cleaned_data.get('remark')\n pid_id = form.cleaned_data.get('pid')\n if pid_id == 0 or pid_id == '' or pid_id == None:\n pid = None\n else:\n pid = Back_Menu.objects.get(pk=pid_id)\n Back_Menu.objects.create(title=title, pid=pid, module=module, icon=icon, remark=remark)\n return restful.ok('添加后台菜单成功!')\n else :\n return restful.params_error(message=form.errors)\n\nclass BackmenuUpdate(View):\n def get(self, request, id):\n detail = Back_Menu.objects.get(pk=id)\n module_list = Back_Module.objects.all()\n top_menu = Back_Menu.objects.filter(pid=None)\n return render(request, 'back/menu/backmenu_update.html', context={'top_menu': top_menu, 'detail': detail, 'module_list': module_list})\n \n def post(self, request, id):\n id = request.POST.get('id')\n form = BackMenuForm(request.POST)\n if form.is_valid():\n backmenu = Back_Menu.objects.get(pk=id)\n backmenu.title = form.cleaned_data.get('title')\n backmenu.module = form.cleaned_data.get('module')\n backmenu.icon = form.cleaned_data.get('icon')\n backmenu.remark = form.cleaned_data.get('remark')\n pid_id = form.cleaned_data.get('pid')\n if pid_id == 0 or pid_id == '' or pid_id == None:\n backmenu.pid = None\n else:\n backmenu.pid = Back_Menu.objects.get(pk=pid_id)\n backmenu.save()\n return restful.ok('修改后台菜单成功!')\n else :\n return restful.params_error(message=form.errors)\n\ndef backmenu_delete(request):\n id = request.POST.get('id')\n backmenu = Back_Menu.objects.get(pk=id)\n backmenu.delete()\n return restful.ok('删除成功!')\n\n@require_POST\ndef backmenu_change_sort(request):\n id = request.POST.get('id')\n sort = request.POST.get('sort')\n Back_Menu.objects.filter(id=id).update(sort=sort)\n return restful.ok('排序修改成功')\n\ndef indexmenu(request):\n '''\n 前台菜单\n '''\n menu = Index_Menu.objects.all()\n\n return render(request, 'back/menu/indexmenu.html', context={'menu': menu})\n\nclass indexmenu_insert(View):\n def get(self, request):\n module_list = Index_Module.objects.all()\n return render(request, 'back/menu/indexmenu_insert.html', context={'module_list': module_list})\n \n def post(self, request):\n form = IndexMenuForm(request.POST)\n if form.is_valid():\n title = form.cleaned_data.get('title')\n module = form.cleaned_data.get('module')\n icon = form.cleaned_data.get('icon')\n image = form.cleaned_data.get('image')\n sort = form.cleaned_data.get('sort')\n remark = form.cleaned_data.get('remark')\n Index_Menu.objects.create(title=title, module=module, icon=icon, image=image, sort=sort, remark=remark)\n return restful.ok('添加前台菜单成功!')\n else :\n # 添加失败,如果上传了图片则删除\n if request.POST.get('image') != '':\n image_cls = image_manage.image()\n image_cls.delete_image(request.POST.get('image'))\n return restful.params_error(message=form.errors)\n \nclass IndexmenuUpdate(View):\n def get(self, request, id):\n detail = Index_Menu.objects.get(pk=id)\n module_list = Index_Module.objects.all()\n return render(request, 'back/menu/indexmenu_update.html', context={'detail': detail, 'module_list': module_list})\n \n def post(self, request, id):\n id = request.POST.get('id')\n form = IndexMenuForm(request.POST)\n if form.is_valid():\n indexmenu = Index_Menu.objects.get(pk=id)\n indexmenu.title = form.cleaned_data.get('title')\n indexmenu.module = form.cleaned_data.get('module')\n # 获取新图片,记录旧图片\n new_image = form.cleaned_data.get('image')\n old_image = ''\n if new_image != '':\n old_image = indexmenu.image\n indexmenu.image = new_image\n indexmenu.icon = form.cleaned_data.get('icon')\n indexmenu.sort = form.cleaned_data.get('sort')\n indexmenu.remark = form.cleaned_data.get('remark')\n indexmenu.save()\n # 保存成功,删除旧图片\n if new_image != '':\n image_cls = image_manage.image()\n image_cls.delete_image(old_image)\n return restful.ok('修改前台菜单成功!')\n else :\n # 保存失败,删除新图片\n if request.POST.get('image') != '':\n image_cls = image_manage.image()\n image_cls.delete_image(request.POST.get('image'))\n return restful.params_error(message=form.errors)\n\ndef indexmenu_delete(request):\n id = request.POST.get('id')\n menu = Index_Menu.objects.get(pk=id)\n menu.delete()\n return restful.ok('删除成功!')\n\n@require_POST\ndef indexmenu_change_sort(request):\n id = request.POST.get('id')\n sort = request.POST.get('sort')\n Index_Menu.objects.filter(id=id).update(sort=sort)\n return restful.ok('排序修改成功')\n\ndef message(request):\n '''\n 留言管理\n '''\n message = Message.objects.filter(mtype=1)\n return render(request, 'back/index/message.html', context={'message': message})\n\ndef message_sign(request):\n id = request.POST.get('id')\n message = Message.objects.get(pk=id)\n if message.sign == 1:\n return restful.params_error(message='此留言已标记!')\n message.sign = 1\n message.save()\n return restful.ok('留言标记!')\n\ndef message_delete(request):\n id = request.POST.get('id')\n message = Message.objects.get(pk=id)\n message.delete()\n return restful.ok('删除成功!')\n","sub_path":"apps/back/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"62106060","text":"#!/usr/bin/env python\n# coding=utf-8\n\nclass TrieTree(object):\n\n def __init__(self):\n self.tree = {}\n\n def add(self, word):\n tree = self.tree\n\n for char in word:\n if char in tree:\n tree = tree[char]\n else:\n tree[char] = {}\n tree = tree[char]\n\n tree['exist'] = True\n\n def search(self, word):\n tree = self.tree\n\n for char in word:\n if char in tree:\n tree = tree[char]\n else:\n return False\n\n if \"exist\" in tree and tree[\"exist\"] == True:\n return True\n else:\n return False\n\ntree = TrieTree()\ntree.add(\"abc\")\ntree.add(\"bcd\")\nprint(tree.tree)\n# Print {'a': {'b': {'c': {'exist': True}}}, 'b': {'c': {'d': {'exist': True}}}}\nprint(tree.search(\"ab\"))\n# Print False\nprint(tree.search(\"abc\"))\n# Print True\nprint(tree.search(\"abcd\"))\n# Print False\n","sub_path":"agrith_util/tree/trie_dict.py","file_name":"trie_dict.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"398996378","text":"\nclass WordBank:\n dictionary = {}\n f = open(\"C:\\\\Users\\\\hp\\\\Desktop\\\\ScrabbleTester\\\\wordsEn.txt\", \"r\")\n word = \"\"\n v = f.read(1)\n while v:\n if not v == \" \":\n if v == \",\":\n if len(word) <= 15:\n dictionary[word] = 1\n word = \"\"\n else:\n word += v\n v = f.read(1)\n\n def check(self, string):\n return string in self.dictionary\n\n\nw = WordBank()\nprint(len(w.dictionary))\n","sub_path":"wordchecker.py","file_name":"wordchecker.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"262860247","text":"from django.shortcuts import render\r\nfrom .forms import *\r\nfrom django.core.files.storage import FileSystemStorage\r\n\r\n\r\ndef index(request):\r\n\tif request.method == 'POST':\r\n\t\tprint('Request: ', request.FILES)\r\n\r\n\t\tmyfile = request.FILES\r\n\t\tprint('File:', myfile)\r\n\t\tform = CustomerForm(request.POST, myfile)\r\n\r\n\t\tif form.is_valid():\r\n\t\t\tform.save()\r\n\telse:\r\n\t\tform = CustomerForm()\r\n\r\n\r\n\tcontext = {'form':form}\r\n\treturn render(request, 'app/index.html', context)","sub_path":"django_s3/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"61695575","text":"# -*- coding: utf-8 -*-\n#\n# Copyright 2017 Spotify AB\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\n''' Supports sending slack notifications for different task events.\n\nUsage:\n\nCreate an incomming webhook on slack: https://api.slack.com/incoming-webhooks\n\nSetup the slack integration with the following code.\nThis can be done in the same module where the luigi tasks are defined.\n\n.. code-block:: python\n\n from luigi.contrib.slack_notifications import configure_slack\n configure_slack()\n\nUse a configuration like the following on luigi.cfg\n\n.. code-block:: ini\n\n [slack]\n webhook = https://hooks.slack.com/services/something\n events = [\"START\", \"SUCCESS\", \"FAILURE\"]\n template = Luigi task {task_id} event {event}: {args} {kwargs}\n\n\nAlternatives:\n\nAnother plugin with similar purpouse is luigi-slack (https://github.com/bonzanini/luigi-slack). The major differences between this and luigi-slack is that:\n\n- Inspired by email notifications (notifications.py): simple configuration though luigi.cfg (no need for python configuration)\n- Minimal changes to python code (only call configure_slack()), no need create a new wrapper around luigi.run.\n- This only depends on requests module (does not depend on slackclient).\n- Work both for python 2 and 3\n- Configurable template, per event, that can expose specific task properties\n\n'''\n\n\nimport logging\nimport luigi\nimport json\n\nlogger = logging.getLogger(__name__)\n\ntry:\n import requests\nexcept ImportError:\n logger.warning(\"Module %s requires the python package 'requests'.\" % __name__)\n\n\nclass slack(luigi.Config):\n webhook = luigi.parameter.Parameter(\n default='',\n description='Webhook URL to send the notifications')\n channel = luigi.parameter.Parameter(\n default='',\n description='Channel to send slack notifications to')\n username = luigi.parameter.Parameter(\n default='',\n description='Slack username originating the message')\n icon_emoji = luigi.parameter.Parameter(\n default='',\n description='Slack bot icon emoji')\n events = luigi.parameter.ListParameter(\n default=['START', 'FAILURE', 'SUCCESS'],\n description='List of events to be handled as slack notifications')\n template = luigi.parameter.Parameter(\n default='Luigi task {task_id} event {event}: {args} {kwargs}',\n description='Template message for event handling slack notifications')\n event_templates = luigi.parameter.DictParameter(\n default={},\n description='Custom template message per event')\n\n\nclass SafeGetAttr(object):\n \"\"\"\n Wraps an object returning a default_value for undefined attributes\n \"\"\"\n def __init__(self, obj, default_value=None):\n self._obj = obj\n self._default_value = default_value\n\n def __getattr__(self, attr):\n return getattr(getattr(self, '_obj'), attr, getattr(self, '_default_value'))\n\n\nclass SlackNotifyHandling():\n slack_hook_url = None\n\n def __init__(self, slack_config):\n self.slack_hook_url = slack_config.webhook\n self.channel = slack_config.channel\n self.events = slack_config.events\n self.template = slack_config.template\n self.username = slack_config.username\n self.icon_emoji = slack_config.icon_emoji\n self.event_templates = slack_config.event_templates\n\n @property\n def is_configured(self):\n \"\"\"\n Check if the slack web hook is configured so that slack messages can be sent\n \"\"\"\n return bool(self.slack_hook_url)\n\n def _make_data(self, text):\n data = dict(text=text)\n if self.channel:\n data['channel'] = self.channel\n if self.username:\n data['username'] = self.username\n if self.icon_emoji:\n data['icon_emoji'] = self.icon_emoji\n return json.dumps(data)\n\n def send_slack_message(self, text):\n \"\"\"\n Send a string as a slack message\n \"\"\"\n r = requests.post(self.slack_hook_url, data=self._make_data(text))\n if not r.status_code == 200:\n logger.error('Could not notify slack, got error: %s ' % r.text)\n return False\n return True\n\n def _handler_for_template(self, template, event):\n def handle(task, *args, **kwargs):\n msg = template.format(\n event=event,\n args=args,\n kwargs=kwargs,\n task_id=task.task_id,\n task=SafeGetAttr(task, '')\n )\n self.send_slack_message(msg)\n return handle\n\n _is_set_handlers = False\n\n def set_handlers(self):\n \"\"\"\n Configure all luigi.task.event_handler if slack notifications ar e configured\n To avoid setting up event handler multiple times, this only runs once\n \"\"\"\n if not self.is_configured or self.__class__._is_set_handlers:\n return\n logger.info('Configuring slack notifications event handling...')\n event_aliases = {\n 'START': luigi.Event.START,\n 'SUCCESS': luigi.Event.SUCCESS,\n 'FAILURE': luigi.Event.FAILURE\n }\n for event in self.events:\n luigi_event = event_aliases.get(event, event)\n template = self.event_templates.get(event, self.template)\n luigi.Task.event_handler(luigi_event)(self._handler_for_template(template, event))\n self.__class__._is_set_handlers = True\n\n\ndef configure_slack():\n \"\"\"\n Setup task event handlers to send slack notifications\n \"\"\"\n SlackNotifyHandling(slack()).set_handlers()\n","sub_path":"luigi/contrib/slack_notifications.py","file_name":"slack_notifications.py","file_ext":"py","file_size_in_byte":6084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"388856129","text":"import time\nfrom breakout_matrix11x7 import BreakoutMatrix11x7\n\non_brightness = 64\n\nmatrix = BreakoutMatrix11x7()\n\nx = 0\ny = 0\nlight = True\n\nwhile True:\n if light:\n matrix.set_pixel(x, y, on_brightness)\n else:\n matrix.set_pixel(x, y, 0)\n matrix.update()\n\n x += 1\n if x >= matrix.WIDTH:\n x = 0\n y += 1\n if y >= matrix.HEIGHT:\n y = 0\n light = not light\n time.sleep(0.5)\n\n time.sleep(0.01)\n","sub_path":"micropython/examples/breakout_matrix11x7/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"363867819","text":"\"\"\"\nUnique Number of Occurrences:\n-----------------------------\nhttps://leetcode.com/problems/unique-number-of-occurrences/\n- Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique.\n\nExamples:\n*********\n\nInput: arr = [1,2,2,1,1,3]\nOutput: true\nExplanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.\n________________\n\nInput: arr = [1,2]\nOutput: false\n_________________\n\nInput: arr = [-3,0,1,-3,1,1,1,-3,10,0]\nOutput: true\n_________________\n\nConstraints:\n\n # 1 <= arr.length <= 1000\n # -1000 <= arr[i] <= 1000\n\"\"\"\nclass Solution(object):\n def uniqueOccurrences(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: bool\n \"\"\"\n '''\n - sort the arr\n - create a dict that keeps track of the occurrences we have \n - if we find an occurrence thats already in dict, we return False, True otherwise\n - for i in arr:\n - check if arr[i] equals arr[i + 1]\n - if so, increment count, else \n - check if count is already in the occurrences dict, \n - if so, return False, \n - else, add count to the occurrences dict\n - and change count to 1\n '''\n arr.sort() # O(nlogn) - time\n # keeps track of the occurrences of each number\n occurrences = {}\n # keeps track of the current index in the arr\n i = 0\n # initialize count to 1, because when we are at a certain number, \n # we have one occurence of that number already\n count = 1\n while i < len(arr) - 1:\n # since the array is sorted, \n # we can easiy compare the number at the current index with the next one in the arr\n if arr[i] == arr[i + 1]:\n count += 1\n else:\n if count in occurrences:\n return False\n occurrences[count] = True\n count = 1\n \n i += 1\n \n if i == len(arr) - 1:\n if count in occurrences:\n return False\n occurrences[count] = True\n return True","sub_path":"Unique Number of Occurrences.py","file_name":"Unique Number of Occurrences.py","file_ext":"py","file_size_in_byte":2265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"48602440","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib\n\nfont = {'size' : 16}\n\nmatplotlib.rc('font', **font)\n\nx = np.arange(1, 10.1, 0.1)\nx0 = 10 * x\ny0 = 10 * x**0.75\ny1 = 10 * x**0.5\ny2 = 10 * x**0.25\n\nplt.plot(x, x0, \"b\", label=\"linear\", linewidth=\"5\")\nplt.plot(x, y0, \"g\", label=\"linear\", linewidth=\"5\")\nplt.plot(x, y1, \"r\", label=\"logarithmic\", linewidth=\"5\")\nplt.xlim(1, 10)\nplt.ylim(10, 100)\n\nplt.xlabel(\"Number of Fluorophores\")\nplt.ylabel(\"Number of Photons\")\n\n#plt.legend()\nplt.savefig(\"multimers.pdf\")\nplt.show()\n","sub_path":"sizing/simple_plot.py","file_name":"simple_plot.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"218132870","text":"import json\nimport unicodedata\n\nKSSS_DIRECTORY = './datasets/ksss'\n\nresult_dict = {}\n\nwith open('{}/KoreanSingleSpeakerSpeech/transcript.txt'.format(KSSS_DIRECTORY), encoding='utf-8') as transcript:\n for line in transcript:\n splitted = line.split('|')\n file_name = splitted[0]\n expanded_text = unicodedata.normalize('NFC', splitted[2])\n\n result_dict['{}/KoreanSingleSpeakerSpeech/{}'.format(KSSS_DIRECTORY, file_name)] = expanded_text\n\nwith open('{}/alignment.json'.format(KSSS_DIRECTORY), 'w') as alignment:\n json.dump(result_dict, alignment)\n","sub_path":"datasets/ksss/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"67891098","text":"#!/usr/bin/env python\n\nimport rospy;\nfrom sensor_msgs.msg import Image;\nfrom sensor_msgs.msg import CameraInfo;\n#from __future__ import absolute_import, print_function, division\nfrom pymba import *\nimport numpy as np\nimport cv2\nimport time\nfrom cv_bridge import CvBridge, CvBridgeError;\n\n#cv2.namedWindow(\"test\")\n\nwith Vimba() as vimba:\n #camera info\n camera_info_msg = CameraInfo();\n camera_info_msg.header.frame_id = \"avt_manta\";\n camera_info_msg.width = rospy.get_param('width') #540;\n camera_info_msg.height = rospy.get_param('height') #410;\n camera_info_msg.K = rospy.get_param('K') #[2046.656901, 0.0, 802.943925, 0.0, 2036.041297, 472.235466, 0.0, 0.0, 1.0];\n camera_info_msg.D = rospy.get_param('D') #[-0.470340, 1.206041, -0.005557, -0.002479, 0.0];\n camera_info_msg.P = rospy.get_param('P') #[1981.632568, 0.0, 800.827980, 0.0, 0.0, 1976.621704, 467.141610, 0.0, 0.0, 0.0, 1.0, 0.0];\n camera_info_msg.R = rospy.get_param('R') #[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];\n #camera_info_msg.P = [1736.461670, 0.0, 834.094334, 0.0, 0.0, 1751.635254, 621.266132, 0.0, 0.0, 0.0, 1.0, 0.0];\n camera_info_msg.distortion_model = rospy.get_param('distortion_model') #\"narrow_stereo\";\n ##########\n\n system = vimba.getSystem()\n\n system.runFeatureCommand(\"GeVDiscoveryAllOnce\")\n time.sleep(0.2)\n\n camera_ids = vimba.getCameraIds()\n\n for cam_id in camera_ids:\n print(\"Camera found: \", cam_id)\n \n # try:\n # c0 = vimba.getCamera(camera_ids[0])\n # c0.openCamera()\n # except IndexError:\n\n c0 = vimba.getCamera(camera_ids[0])\n c0.openCamera()\n\n\n if (rospy.get_param('print_features') == 1):\n cameraFeatureNames = c0.getFeatureNames();\n for name in cameraFeatureNames:\n print(name);\n \n try:\n # c0.PixelFormat = \"BGR8Packed\";\n c0.PixelFormat = rospy.get_param('pixel_format')\n # c0.ExposureAuto = \"Off\"\n c0.ExposureAuto = rospy.get_param('exposure_auto')\n # c0.ExposureTimeAbs=30000 \n c0.ExposureTimeAbs = rospy.get_param('exposure_time_abs')\n # c0.BalanceWhiteAuto = \"Off\"\n c0.BalanceWhiteAuto = rospy.get_param('balance_white_auto')\n # c0.BalanceRatioAbs = 1.3 \n c0.BalanceRatioAbs = rospy.get_param('balance_ratio_abs')\n # c0.Saturation = 2\n c0.Saturation = rospy.get_param('saturation')\n # c0.BinningHorizontal = 3\n c0.BinningHorizontal= rospy.get_param('binning_horizontal')\n # c0.BinningVertical = 3\n c0.BinningVertical = rospy.get_param('binning_vertical')\n except:\n print(\"Problem initializing the camera.\")\n pass\n\n #set pixel format\n #c0.PixelFormat=\"Mono8\"\n \n # c0.PixelFormat = \"BGR8Packed\";\n # c0.ExposureAuto = \"Off\"\n # c0.ExposureTimeAbs=30000 \n # c0.BalanceWhiteAuto = \"Off\"\n # c0.BalanceRatioAbs = 1.3 \n # c0.Saturation = 2\n # c0.BinningHorizontal = 3\n # c0.BinningVertical = 3\n\n c0.AcquisitionMode = \"Continuous\";\n\n frame = c0.getFrame()\n frame.announceFrame()\n\n c0.startCapture()\n\n framecount = 0\n droppedframes = []\n\n c0.runFeatureCommand(\"AcquisitionStart\");\n frame.queueFrameCapture();\n\n rospy.init_node('pymba_publisher');\n image_pub = rospy.Publisher(\"/avt_manta/image_raw\", Image, queue_size=1);\n cam_info_pub = rospy.Publisher(\"/avt_manta/camera_info\", CameraInfo, queue_size=1);\n bridge = CvBridge();\n\n while not rospy.is_shutdown():\n frame.waitFrameCapture(1000);\n try:\n frame.queueFrameCapture()\n success = True\n except:\n droppedframes.append(framecount)\n success = False\n frame_data = frame.getBufferByteData()\n if success:\n img = np.ndarray(buffer=frame_data,\n dtype=np.uint8,\n shape=(frame.height,frame.width,frame.pixel_bytes))\n\n #img = cv2.resize(img, \n # dsize=(int(frame.width/3), int(frame.height/3)),\n # interpolation=cv2.INTER_CUBIC);\n\n\n #cv2.imshow(\"test\",img)\n ##\n #image_pub.publish(bridge.cv2_to_imgmsg(img, \"mono8\"));\n image_pub.publish(bridge.cv2_to_imgmsg(img, \"bgr8\"));\n cam_info_pub.publish(camera_info_msg);\n framecount+=1\n #print(img);\n #print(framecount);\n k = cv2.waitKey(1)\n if k == 0x1b:\n cv2.destroyAllWindows()\n print(\"Frames displayed: %i\"%framecount)\n print(\"Frames dropped: %s\"%droppedframes)\n break\n\n c0.runFeatureCommand(\"AcquisitionStop\");\n c0.endCapture()\n c0.revokeAllFrames()\n\n c0.closeCamera()\n","sub_path":"src/pymba_publisher.py","file_name":"pymba_publisher.py","file_ext":"py","file_size_in_byte":4777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"500867980","text":"\"\"\"\nFile: misc.py\nAuthor: Tomas Lessy\nEmail: lessy.mot@gmail.com\nGithub: https://github.com/lim3nius\nDescription: This file containes set of functions used for debugging\n\"\"\"\n\nimport traceback\nimport sys\nfrom typing import List\nfrom logging import getLogger\n\nlog = getLogger()\n\n\ndef debug_on_exception(exceptions: List[Exception]):\n '''\n debug_on_exception allows user to examine function only when\n specific set of exceptions are caught, if exceptions aren't\n specified, all exceptions are caught.\n\n :exceptions: List of exception types on which to drop user\n into python debugger\n '''\n if exceptions is None:\n exceptions = [Exception]\n\n def wrapper(func):\n def inner(*args, **kwargs):\n try:\n res = func(*args, **kwargs)\n except Exception as e:\n for typ in exceptions:\n if isinstance(e, typ):\n traceback.print_exc()\n breakpoint()\n res = func(*args, **kwargs)\n break\n else:\n raise e\n return res\n return inner\n return wrapper\n\n\ndef exit_on_exception(code: int, *, exceptions: List[Exception] = [Exception]):\n '''\n exit_on_exception terminates program execution and exits with specified\n exit code. If exceptions are specified, than program will be terminated\n only of raise exception is one of given exceptions\n\n :code: code which will be reported back to OS\n :exceptions: list of exceptions type on which will be program execution\n terminated\n '''\n def wrapper(f):\n def inner(*args, **kwargs):\n try:\n f(*args, **kwargs)\n except Exception as e:\n for ex_type in exceptions:\n if isinstance(e, ex_type):\n log.error(f'Caught exception: {e}')\n traceback.print_exc()\n sys.exit(code)\n else:\n raise e\n return inner\n return wrapper\n","sub_path":"helpers/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"625147763","text":"'''\nPrint and text rendering utils for the CLI commands\n'''\nimport arrow\nimport click\nimport pandas as pd\nfrom tabulate import tabulate\n\nfrom jira_offline.models import Issue\n\n\ndef print_list(df: pd.DataFrame, width: int=60, verbose: bool=False, include_project_col: bool=False):\n '''\n Helper to print abbreviated list of issues\n\n Params:\n df: Issues to display in a DataFrame\n width: Crop width for the summary string\n verbose: Display more information\n include_project_col: Include the Issue.project field in a column\n '''\n if df.empty:\n click.echo('No issues in the cache')\n raise click.Abort\n\n pd.set_option('mode.chained_assignment', None)\n\n if include_project_col:\n fields = ['project']\n else:\n fields = []\n\n if not verbose:\n fields += ['issuetype', 'epic_ref', 'summary', 'assignee', 'updated']\n else:\n fields += [\n 'issuetype', 'epic_ref', 'epic_name', 'summary', 'assignee', 'fix_versions', 'updated'\n ]\n width = 200\n\n if 'assignee' not in df:\n df['assignee'] = ''\n\n # replace all NaNs in the DataFrame with blank str\n df.fillna('', inplace=True)\n\n # pretty dates for non-verbose\n def format_datetime(raw):\n if not raw or pd.isnull(raw):\n return ''\n dt = arrow.get(raw)\n if verbose:\n return f'{dt.format()}'\n else:\n return f'{dt.humanize()}'\n df.updated = df.updated.apply(format_datetime)\n\n # shorten the summary field for printing\n df.summary = df.summary.str.slice(0, width)\n\n def abbrev_key(key):\n if key is None:\n return ''\n if len(key) == 36:\n return key[0:8]\n return key\n # abbreviate long issue keys (offline-created issues have a UUID as the key)\n df.key = df.key.apply(abbrev_key)\n df.set_index('key', inplace=True)\n df.epic_ref = df.epic_ref.apply(abbrev_key)\n\n if verbose:\n df.fix_versions = df.fix_versions.apply(lambda x: '' if not x else ','.join(x))\n\n print_table(df[fields])\n\n\ndef print_table(df):\n '''Helper to pretty print dataframes'''\n click.echo(tabulate(df, headers='keys', tablefmt='psql'))\n\n\ndef print_diff(issue: Issue):\n if not issue.exists:\n # this issue was locally created offline so no diff is available; just do a plain print\n click.echo(issue)\n return\n\n # late import to avoid cyclic import\n from jira_offline.sync import build_update # pylint: disable=import-outside-toplevel, cyclic-import\n\n # run build_update to diff between the remote version of the Issue, and the locally modified one\n update_obj = build_update(Issue.deserialize(issue.original), issue)\n\n # print a handsome table\n click.echo(tabulate(issue.render(modified_fields=update_obj.modified)))\n","sub_path":"jira_offline/utils/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":2886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"537959157","text":"import time\nimport requests\nfrom vm import *\n\nURI = \"/basic_status\"''\nperv_val = 0\n\ndef calc_arrival_rate(lb_url, duration):\n res = requests.get(\"http://\"+lb_url + URI).text.split()\n curr_val = int(res[res.index(\"Reading:\")-1])\n global perv_val\n reqs = curr_val - perv_val - 1\n rate = reqs/duration\n perv_val = curr_val\n return rate\n\ndef get_curr_weight(default_weight, baseline, bi):\n if bi.get_instance_cpu_util() > baseline:\n return default_weight+1\n\nif __name__ == \"__main__\":\n while True:\n rate = calc_arrival_rate()\n print(rate)\n time.sleep(DURATION)\n","sub_path":"burscale/monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"242468014","text":"from sklearn.model_selection import train_test_split\r\nfrom sklearn import ensemble\r\nfrom torch.autograd import Variable\r\nimport torch.optim as optim\r\nimport torch.nn as nn\r\nimport torch\r\nimport numpy as np\r\nimport sys\r\nimport preprocess\r\nimport accuracyfunction\r\n# import matplotlib.pyplot as plt\r\n#import seaborn as sns\r\n\r\n# don't show warnings message\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\n# set filename outputLayer testing epoch\r\ntrainData = sys.argv[1]\r\ntestData = sys.argv[2]\r\noutputLayer = sys.argv[3]\r\nestimators = sys.argv[4]\r\n\r\n# load trainData\r\ntrain_temp = preprocess.loadDataset(trainData)\r\ntrain_noStringTemp_X = train_temp[0:,0:-1]\r\n\r\n# start preprocess----------------------------------------------------------------------------------------------------------\r\n\r\n# only trainData do this\r\nprotocal_type_list = preprocess.saveProtocal_typeOrder(train_noStringTemp_X)\r\nservice_list = preprocess.saveServiceOrder(train_noStringTemp_X)\r\nflag_list = preprocess.saveFlagOrder(train_noStringTemp_X)\r\nprotocal_type_onehotencoded = preprocess.onehotencoded(protocal_type_list)\r\nservice_list_onehotencoded = preprocess.onehotencoded(service_list)\r\nflag_list_onehotencoded = preprocess.onehotencoded(flag_list)\r\n\r\n# load testData\r\ntest_temp = preprocess.loadDataset(testData)\r\ntest_noStringTemp_X = test_temp[0:,0:-1]\r\n\r\ntrain_noStringTemp_Y = []\r\ntrain_noStringTemp_Y = preprocess.distinguishNaturalAttack(train_temp, train_noStringTemp_Y, int(outputLayer))\r\ntest_noStringTemp_Y = []\r\ntest_noStringTemp_Y = preprocess.distinguishNaturalAttack(test_temp, test_noStringTemp_Y, int(outputLayer))\r\n\r\n# np can't dynamic add number so use list\r\ntrain_noStringTemp_X = train_noStringTemp_X.tolist() \r\ntest_noStringTemp_X = test_noStringTemp_X.tolist()\r\n\r\n# replace text with onehotencoded number\r\npreprocess.replace(train_noStringTemp_X, protocal_type_list, service_list, flag_list, protocal_type_onehotencoded, service_list_onehotencoded, flag_list_onehotencoded)\r\npreprocess.replace(test_noStringTemp_X, protocal_type_list, service_list, flag_list, protocal_type_onehotencoded, service_list_onehotencoded, flag_list_onehotencoded)\r\n\r\n# list->np\r\ntrain_noStringTemp_X = np.array(train_noStringTemp_X)\r\ntrain_noStringTemp_Y = np.array(train_noStringTemp_Y)\r\ntest_noStringTemp_X = np.array(test_noStringTemp_X)\r\ntest_noStringTemp_Y = np.array(test_noStringTemp_Y)\r\n\r\n# duration src_bytes\r\nfor i in range(len(train_noStringTemp_X)):\r\n train_noStringTemp_X[i][0] = preprocess.log(train_noStringTemp_X[i][0])\r\n train_noStringTemp_X[i][4] = preprocess.log(train_noStringTemp_X[i][4])\r\n train_noStringTemp_X[i][5] = preprocess.log(train_noStringTemp_X[i][5])\r\n\r\nfor i in range(len(test_noStringTemp_X)):\r\n test_noStringTemp_X[i][0] = preprocess.log(test_noStringTemp_X[i][0])\r\n test_noStringTemp_X[i][4] = preprocess.log(test_noStringTemp_X[i][4])\r\n test_noStringTemp_X[i][5] = preprocess.log(test_noStringTemp_X[i][5])\r\n \r\n# normalize\r\ntrain_resultNormalize = preprocess.normalize(train_noStringTemp_X)\r\ntest_resultNormalize = preprocess.normalize(test_noStringTemp_X)\r\n\r\n# end preprocess----------------------------------------------------------------------------------------------------------\r\n\r\n# build random forset\r\nforest = ensemble.RandomForestClassifier(n_estimators=int(estimators))\r\n\r\n# training\r\nforestFit = forest.fit(train_resultNormalize, train_noStringTemp_Y)\r\n\r\n# testing\r\ny_test_prediction = forest.predict(test_resultNormalize)\r\n\r\naccuracyfunction.accuracy(test_noStringTemp_Y, y_test_prediction)","sub_path":"src/RandomForest_NSL-KDD/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"539057986","text":"import tweepy\r\nimport glob\r\nimport os\r\nimport get_reviews\r\nimport get_auth\r\nimport textwrap\r\nimport io\r\nimport random\r\nimport time\r\nimport sqlite3\r\nimport base64\r\nfrom PIL import Image, ImageDraw, ImageFont\r\nfrom get_reviews import Review\r\n\r\ndef main():\r\n while True:\r\n\r\n # Authenticate to Twitter\r\n zeroAuth = get_auth.getZeroAuth()\r\n accessTokens = get_auth.getAccessTokens()\r\n auth = tweepy.OAuthHandler(zeroAuth[0], zeroAuth[1])\r\n auth.set_access_token(accessTokens[0], accessTokens[1])\r\n\r\n # Create API object\r\n api = tweepy.API(auth)\r\n get_reviews.main()\r\n # Connect to the db\r\n conn = sqlite3.connect('reviews.db')\r\n c = conn.cursor()\r\n\r\n # Get one review\r\n \r\n query = 'select * from reviews ORDER BY RANDOM() limit 1;'\r\n c.execute(query)\r\n review_row = c.fetchone()\r\n if review_row != None:\r\n # Create a review object\r\n review = Review(review_row[0], review_row[1], review_row[2], review_row[3])\r\n \r\n # Generate the image\r\n image_filename = generateImage(review)\r\n\r\n # Create a tweet\r\n media_ids = []\r\n image = api.media_upload(filename = image_filename)\r\n media_ids.append(image.media_id)\r\n stars = '⭐' * int(review.stars)\r\n api.update_status(status=review.title + ':\\n' + stars, media_ids = media_ids)\r\n\r\n # And now we mark the tweet as having been tweeted so we can avoid tweeting it again\r\n print('Posted ' + review.title + ' ' + review.timestamp)\r\n\r\n # Add review to our DB so it can't get posted again\r\n query = 'INSERT INTO posted VALUES(\\\"%s\\\", \\\"%s\\\");' % (str(review.timestamp) , str(review.title))\r\n c.execute(query)\r\n conn.commit()\r\n conn.close()\r\n # Delete the temp image\r\n os.remove(image_filename)\r\n # Hush. It's time to sleep.\r\n print(\"Going into sleep mode.\\n\")\r\n max_time = 30\r\n time_elapsed = 0\r\n while time_elapsed != max_time:\r\n #if time_elapsed == 30:\r\n # We scrape every 30 mins, and we post every 60.\r\n #get_reviews.main()\r\n #print('Got reviews.\\n')\r\n print('Next post: ' + str(max_time-time_elapsed) + ' minutes.\\n')\r\n time.sleep(300)\r\n time_elapsed += 5\r\n\r\ndef generateImage(review):\r\n review_length = len(review.body)\r\n # Choose a random color -- from 1 to 4\r\n color = random.randint(1,4)\r\n img = Image.open(str(color) +'.jpg')\r\n MAX_W, MAX_H = img.size\r\n # Following is based on handmade testing. Let's see how this goes.\r\n if review_length <= 600:\r\n font_size = 20\r\n cpl = 39\r\n elif review_length > 600 and review_length <= 864:\r\n font_size = 18\r\n cpl = 48\r\n elif review_length > 864 and review_length <= 1160:\r\n font_size = 16\r\n cpl = 58\r\n else:\r\n font_size = 14\r\n cpl = 60\r\n text = textwrap.wrap(review.body)\r\n fnt = ImageFont.truetype(\"/usr/share/fonts/dejavu/DejaVuSans.ttf\",font_size)\r\n d = ImageDraw.Draw(img)\r\n # We need to sort out what the height of our text is\r\n line_dimensions = [d.textsize(line, font=fnt) for line in text]\r\n offset = (MAX_H - sum(h for w, h in line_dimensions)) // 2\r\n current_h = offset - 60\r\n for line, (w, h) in zip(text, line_dimensions):\r\n d.text(((MAX_W - w) // 2, current_h), line, font=fnt, fill=\"black\")\r\n current_h += h\r\n filename = \"temp.jpg\"\r\n img.save(filename)\r\n return(filename)\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"post_reviews.py","file_name":"post_reviews.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"315571849","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 1 23:28:21 2019\n\n@author: Dell\n\"\"\"\n\nfrom graphics import *\nll=[]\t\t\t\t\t\t\t\t\nfor i in range(0,1000):\n\tll.append([])\n\tfor j in range(0,1000):\n\t\tll[i].append(0)\ndef plotLow(x0,y0,x1,y1):\n\ta=y1-y0\n\tb=x0-x1\n\tyi=1\n\tif(a<0):\n\t\tyi=-1\n\t\ta=-a\n\tdne=2*(a+b)\n\tde=2*a\n\td=2*a+b\n\ty=y0\n\tr=1\n\tif x10):\n\t\t\ty=y+yi\n\t\t\td=d+dne\n\t\telse:\n\t\t\td=d+de\ndef plotHigh(x0,y0,x1,y1):\n\tb=y0-y1\n\ta=x1-x0\n\txi=1\n\tif(a<0):\n\t\txi=-1\n\t\ta=-a\n\tdne=2*(a+b)\n\tde=2*a\n\td=2*a+b\n\tx=x0\n\tr=1\n\tif y10):\n\t\t\tx=x+xi\n\t\t\td=d+dne\n\t\telse:\n\t\t\td=d+de\ndef lineD(x0,y0,x1,y1):\n\tif abs(y1-y0) < abs(x1-x0):\n\t\tif x0>=x1:\n\t\t\tplotLow(x1,y1,x0,y0)\n\t\telse:\n\t\t\tplotLow(x0,y0,x1,y1)\n\telse:\n\t\tif y0>=y1:\n\t\t\tplotHigh(x1,y1,x0,y0)\n\t\telse:\n\t\t\tplotHigh(x0,y0,x1,y1)\n\t\n\t\n\n\nwin=GraphWin(\"Window1\",600,600)\nwin.setCoords(0,0,600,600)\nwin.setBackground(\"white\")\nxaxis=Line(Point(0,300),Point(600,300))\nxaxis.setArrow('both')\nxaxis.setOutline('black')\n\nyaxis=Line(Point(300,0),Point(300,600))\nyaxis.setArrow('both')\nyaxis.setOutline('black')\nxaxis.draw(win)\nyaxis.draw(win)\n\n\n\nn=int(input(\"Enter No. Of Points:\"))\nprint(\"Enter Points counterclockwise\")\nx0=int(input(\"Enter X:\"))\ny0=int(input(\"Enter Y:\"))\nx2=x0\ny2=y0\nymin=y0\nymax=y0\nxmin=x0\nxmax=x0\nwhile(n>1):\n\tx1=int(input(\"Enter X:\"))\n\ty1=int(input(\"Enter Y:\"))\n\tlineD(x0,y0,x1,y1)\t\t\t\t\n\tx0=x1\n\ty0=y1\n\tn=n-1\n\txmin=min(xmin,x1)\n\txmax=max(xmax,x1)\n\tymax=max(ymax,y1)\n\tymin=min(ymin,y1)\nlineD(x2,y2,x1,y1)\n\nprint(\"Click Inside The Polygon Anywhere\")\nwin.getMouse()\n\nfor y in range(ymin+300,ymax+300,1):\n\tflag=0\n\tfor x in range(xmin+300,xmax+300,1):\n\t\tif(flag==1):\n\t\t\twin.plot(x,y,'blue')\n\t\tif(ll[x][y]==1):\n\t\t\tflag=flag+1\t\t\n\t\t\tif(flag==2):\n\t\t\t\tflag=0\n\t\t\nwin.getMouse()\nwin.close()","sub_path":"Lab2/scanline.py","file_name":"scanline.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"617647029","text":"\"\"\"Add sequence_id to user_diagnoses table\n\nRevision ID: 7db499e582e1\nRevises: 4665028487a6\nCreate Date: 2020-05-08 17:08:14.479247\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '7db499e582e1'\ndown_revision = '4665028487a6'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('user_diagnoses', sa.Column('sequence_id', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'user_diagnoses', 'sequences', ['sequence_id'], ['id'], ondelete='CASCADE')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'user_diagnoses', type_='foreignkey')\n op.drop_column('user_diagnoses', 'sequence_id')\n # ### end Alembic commands ###\n","sub_path":"backend/app/alembic/versions/7db499e582e1_add_sequence_id_to_user_diagnoses_table.py","file_name":"7db499e582e1_add_sequence_id_to_user_diagnoses_table.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"486270308","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\nfrom typing import List\n\n\nclass Solution:\n def prefixesDivBy5(self, nums: List[int]) -> List[bool]:\n s = ''\n res = [False] * len(nums)\n for index, i in enumerate(nums):\n s += str(i)\n\n if int(s, 2) % 5 == 0:\n res[index] = True\n\n return res\n\n\nif __name__ == '__main__':\n s = Solution()\n nums = [0, 1, 1, 1, 1, 1]\n print(s.prefixesDivBy5(nums))\n # print(int('011', 2))\n","sub_path":"模拟考试/7_21/t3.py","file_name":"t3.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"586454281","text":"from __future__ import print_function\nimport torch\nfrom model import highwayNet\nfrom utils import ngsimDataset,maskedNLL,maskedMSETest,maskedNLLTest,maskedBIGERRTest\nfrom torch.utils.data import DataLoader\nimport time\n\nimport pdb\nimport os\nimport utils_nn as utils\nimport logging\n\nfrom tqdm import tqdm\n\nimport argparse\nimport torch.onnx\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--experiment', default='baseline', help=\"baseline, baselineX, seq2seq, seq2seqX, attention or transformer\")\n\ncmd_args = parser.parse_args()\n\n\n## Network Arguments\n## cf params.json\n\n#args['encoder_size'] = 64\n#args['decoder_size'] = 128\n#args['in_length'] = 16\n#args['out_length'] = 25\n#args['grid_size'] = (13,3)\n#args['soc_conv_depth'] = 64\n#args['conv_3x1_depth'] = 16\n#args['dyn_embedding_size'] = 32\n#args['input_embedding_size'] = 32\n#args['num_lat_classes'] = 3\n#args['num_lon_classes'] = 2\n#args['use_maneuvers'] = True\n\nargs = {}\nargs['train_flag'] = False\nargs['model_dir'] = 'experiments/' + cmd_args.experiment\n\nutils.set_logger(os.path.join(args['model_dir'], 'evaluate.log'))\n\njson_path = os.path.join(args['model_dir'], 'params.json')\nassert os.path.isfile(json_path), \"No json configuration file found at {}\".format(json_path)\nparams = utils.Params(json_path)\nparams.grid_size = (params.grid_size_lon, params.grid_size_lat)\n\n# use GPU if available\nparams.use_cuda = torch.cuda.is_available()\n#params.use_cuda = False\nparams.train_flag = args['train_flag']\nparams.model_dir = args['model_dir']\n\nparams.create_onnx = True\n\n# Evaluation metric:\nmetric = 'nll'\t#or rmse\nmetric = 'rmse'\t#or rmse\n#metric = 'bigerr'\t#or rmse\n\nif metric == 'rmse':\n\tmetricFCT = maskedMSETest\nelse:\n\tmetricFCT = maskedBIGERRTest\n\n\n# Initialize network\nbatch_size=1024\nbatch_size=16\n#batch_size=6\n\nlogging.info(\"Loading the datasets...\")\nnewFeats = 0\nbehavFeats = 0\nif 'X' in cmd_args.experiment:\n\tnewFeats = 3\n\tbehavFeats = 0\n\t#tsSet = ngsimDataset('data/TestSetV.mat', newFeats=newFeats)\n\ttsSet = ngsimDataset('data/TestSetCVA.mat', newFeats=newFeats)\nelse:\n\ttsSet = ngsimDataset('data/TestSet.mat')\n\ntsDataloader = DataLoader(tsSet,batch_size=batch_size,shuffle=False,num_workers=0,collate_fn=tsSet.collate_fn)\n\n\nnet = highwayNet(params, newFeats=newFeats, behavFeats=behavFeats)\n\nnet_path = os.path.join(args['model_dir'], 'best.pth.tar')\nassert os.path.isfile(net_path), \"No net file found at {}\".format(net_path)\n#net.load_state_dict(torch.load('trained_models/cslstm_m.tar'))\nutils.load_checkpoint(net_path, net)\n\nif params.use_cuda:\n\tnet = net.cuda()\n\nn_params = 0\nfor name, parameter in net.named_parameters():\n\tn_params += torch.numel(parameter)\n\tprint(\"name {}: {} parameters\".format(name, torch.numel(parameter)))\n\t#print(parameter)\n\nprint(\"net parameters: {}\".format(n_params))\n\n# This corrects for the differences in dropout, batch normalization during training and testing.\n# No dropout, batch norm so far; but it is a good default practice anyways\nnet.eval()\n\n\nif params.use_cuda:\n\tlossVals = torch.zeros(25).cuda()\n\tcounts = torch.zeros(25).cuda()\nelse:\n\tlossVals = torch.zeros(25)\n\tcounts = torch.zeros(25)\n\ntotal = len(tsDataloader)\nwith torch.no_grad():\n\tfor i, data in tqdm(enumerate(tsDataloader), total=total):\n\t\tst_time = time.time()\n\t\thist, nbrs, mask, lat_enc, lon_enc, fut, op_mask, hist_grid = data\n\t\n\t\t# Initialize Variables\n\t\tif params.use_cuda:\n\t\t\thist = hist.cuda()\n\t\t\tnbrs = nbrs.cuda()\n\t\t\tmask = mask.cuda()\n\t\t\tlat_enc = lat_enc.cuda()\n\t\t\tlon_enc = lon_enc.cuda()\n\t\t\tfut = fut.cuda()\n\t\t\top_mask = op_mask.cuda()\n\t\t\thist_grid = hist_grid.cuda()\n\n\t\tif params.create_onnx:\n\t\t\ttorch.onnx.export(net, (hist, nbrs, mask, lat_enc, lon_enc, hist_grid), \"predtest.proto\", verbose=True)\n\t\t\tparams.create_onnx = False\n\n\t\tif metric == 'nll':\n\t\t\t# Forward pass\n\t\t\tif params.use_maneuvers:\n\t\t\t\tfut_pred, lat_pred, lon_pred = net(hist, nbrs, mask, lat_enc, lon_enc, hist_grid)\n\t\t\t\tl,c = maskedNLLTest(fut_pred, lat_pred, lon_pred, fut, op_mask)\n\t\t\telse:\n\t\t\t\tfut_pred = net(hist, nbrs, mask, lat_enc, lon_enc, hist_grid)\n\t\t\t\tl, c = maskedNLLTest(fut_pred, 0, 0, fut, op_mask,use_maneuvers=False)\n\t\telse:\n\t\t\t# Forward pass\n\t\t\tif params.use_maneuvers:\n\t\t\t\tfut_pred, lat_pred, lon_pred = net(hist, nbrs, mask, lat_enc, lon_enc, hist_grid)\n\t\t\t\tfut_pred_max = torch.zeros_like(fut_pred[0])\n\t\t\t\tfor k in range(lat_pred.shape[0]): # k in range(batch_size)\n\t\t\t\t\tlat_man = torch.argmax(lat_pred[k, :]).detach()\n\t\t\t\t\tlon_man = torch.argmax(lon_pred[k, :]).detach()\n\t\t\t\t\tindx = lon_man*3 + lat_man\n\t\t\t\t\tfut_pred_max[:,k,:] = fut_pred[indx][:,k,:]\n\t\t\t\tl, c = metricFCT(fut_pred_max, fut, op_mask)\n\t\t\telse:\n\t\t\t\tfut_pred = net(hist, nbrs, mask, lat_enc, lon_enc)\n\t\t\t\tl, c = metricFCT(fut_pred, fut, op_mask)\n\t\n\t\t#logging.info(\"Batch {}: l {} c {}\".format(i, l, c))\n\t\tlossVals +=l.detach()\n\t\tcounts += c.detach()\n\t\tbatch_time = time.time()-st_time\n\t\t#if metric == 'rmse':\n\t\t#\tprint(\"...RMSE: {}\".format(torch.pow(lossVals / counts,0.5)*0.3048))\t # Calculate RMSE and convert from feet to meters\n\t\t#elif metric == 'nll':\n\t\t#\tprint(\"...NLL: {}\".format(torch.pow(lossVals / counts,0.5)*0.3048))\t # Calculate RMSE and convert from feet to meters\n\t\t#else:\n\t\t#\tprint(\"...BIGERR: {}\".format(lossVals / counts))\n\t\tprint(\"eval batch_time:\", batch_time) # Just for runtime tests TVM benchmarks\n\t\t#break\n\nif metric == 'nll':\n\tlogging.info(\"NLL: {}\".format(lossVals / counts))\nelif metric == 'bigerr':\n\tlogging.info(\"BIGERR: {}\".format(lossVals / counts))\nelse:\n\tlogging.info(\"RMSE: {}\".format(torch.pow(lossVals / counts,0.5)*0.3048))\t # Calculate RMSE and convert from feet to meters\n\n\n","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":5564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"237729718","text":"import numpy as np\n\n\"\"\"Grade average for Msc in Physics and BSc in Engineering Physics\n\"\"\"\n\nmaster = {\n 'Quantum Mechanics': {\n 'hp': 4.5,\n 'grade': 4,\n },\n 'Learning From Data': {\n 'hp': 7.5,\n 'grade': 5,\n },\n 'Experimental Methods In Modern Physics': {\n 'hp': 3.0,\n 'grade': 5,\n },\n 'Computational physics': {\n 'hp': 7.5,\n 'grade': 5,\n },\n 'Statistical physics': {\n 'hp': 7.5,\n 'grade': 5,\n },\n 'Computational materials and molecular physics': {\n 'hp': 7.5,\n 'grade': 5,\n },\n 'Plasma physics with applications': {\n 'hp': 7.5,\n 'grade': 5,\n },\n 'High performance computing': {\n 'hp': 7.5,\n 'grade': 5,\n },\n 'Quantum computing': {\n 'hp': 7.5,\n 'grade': 5,\n },\n 'Technology and society': {\n 'hp': 7.5,\n 'grade': 5,\n },\n 'Advanced simulation and machine learning': {\n 'hp': 7.5,\n 'grade': 5,\n },\n}\n\nbachelor = {\n 'Linear algebra and geometry': {\n 'hp': 4.5,\n 'grade': 3,\n },\n 'Introductory mathematical analysis': {\n 'hp': 6,\n 'grade': 4,\n },\n 'Real analysis': {\n 'hp': 6,\n 'grade': 4,\n },\n 'Computer programming': {\n 'hp': 6,\n 'grade': 4,\n },\n 'Multivariable analysis': {\n 'hp': 6,\n 'grade': 5,\n },\n 'Mechanics 1': {\n 'hp': 7.5,\n 'grade': 5,\n },\n 'Linear algebra and numerical analysis': {\n 'hp': 7.5,\n 'grade': 5,\n },\n 'Mechanics 2': {\n 'hp': 6,\n 'grade': 4,\n },\n 'Vector fields and classical physics': {\n 'hp': 4.5,\n 'grade': 4,\n },\n 'Complex mathematical analysis': {\n 'hp': 6,\n 'grade': 4,\n },\n 'Electrical circuits and systems': {\n 'hp': 7.5,\n 'grade': 5,\n },\n 'Theory of electromagnetic fields': {\n 'hp': 7.5,\n 'grade': 5,\n },\n 'Optics': {\n 'hp': 6.0,\n 'grade': 5,\n },\n 'Fourier analysis': {\n 'hp': 6.0,\n 'grade': 5,\n },\n 'Mathematical statistics': {\n 'hp': 4.5,\n 'grade': 5,\n },\n 'Automatic control': {\n 'hp': 4.5,\n 'grade': 5,\n },\n 'Environmental physics': {\n 'hp': 4.5,\n 'grade': 5,\n },\n 'Experimental physics 1 - measuring technique': {\n 'hp': 9,\n 'grade': 5,\n },\n 'Quantum physics': {\n 'hp': 6.0,\n 'grade': 5,\n },\n 'Thermodynamics and statistical mechanics': {\n 'hp': 7.5,\n 'grade': 5,\n },\n 'Applied quantum physics': {\n 'hp': 4.5,\n 'grade': 5,\n },\n 'Special relativity': {\n 'hp': 4.5,\n 'grade': 5,\n },\n 'Fluid mechanics': {\n 'hp': 4.5,\n 'grade': 5,\n },\n 'Solid state physics': {\n 'hp': 7.5,\n 'grade': 5,\n },\n 'Subatomic physics': {\n 'hp': 6.0,\n 'grade': 5,\n },\n 'Experimental physics 2 - basis': {\n 'hp': 4.5,\n 'grade': 5,\n },\n \"Bachelor's thesis in Physics\": {\n 'hp': 15,\n 'grade': 5,\n },\n}\n\ncourses = {**bachelor, **master}\n\ncumWeightedGrade = 0\ncumHp = 0\nfor course, data in courses.items():\n hp = data['hp']\n grade = data['grade']\n cumWeightedGrade += hp*grade\n cumHp += hp\n print(course, data['grade'])\nweightedGrade = cumWeightedGrade / cumHp\n\nprint(f'Weighted grade average: {weightedGrade:.2f}')","sub_path":"other/average_grade.py","file_name":"average_grade.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"96998829","text":"\"\"\"15.Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre\no total do seu salário no referido mês, sabendo-se que são descontados 11% para o Imposto de Renda, 8% para o INSS e 5%\npara o sindicato, faça um programa que nos dê:\na.\tsalário bruto.\nb.\tquanto pagou ao INSS.\nc.\tquanto pagou ao sindicato.\nd.\to salário líquido.\n\ncalcule os descontos e o salário líquido, conforme a tabela abaixo:\n + Salário Bruto : R$\n - IR (11%) : R$\n - INSS (8%) : R$\n - Sindicato ( 5%) : R$\n = Salário Liquido : R$\nObs.: Salário Bruto - Descontos = Salário Líquido.\n\"\"\"\nsalario_hora = float(input(\"Digite o valor da hora trabalhada: \"))\nhoras_trabalho = float(input(\"Digite o número de horas trabalhadas: \"))\n\nsalario_bruto = salario_hora * horas_trabalho\ninss = 0.08 * salario_bruto\nIR = 0.11 * salario_bruto\nsind = 0.05 * salario_bruto\nsalario_liquido = salario_bruto - inss - IR - sind\n\nprint(\">> Salário bruto foi de :\", salario_bruto, \".\")\nprint(\">> Você pagou ao INSS: \", inss, \".\")\nprint(\">> Você pagou ao sindicato: \", sind, \".\\n>> Seu salário lìquido foi: \", salario_liquido, \".\")\n","sub_path":"Est_Sequencial/L15.py","file_name":"L15.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"126799847","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.constants import e, c, m_e, mu_0\nfrom mpl_toolkits.mplot3d import axes3d\n\nm = 7500\nb = 20**3 \n\nx, y = np.meshgrid(np.arange(-30, 30, 1),\n np.arange(-30, 30, 1))\n\nu = 1e-6*m*x*y\nv = 1e-6*0.5*m*(x**2-y**2)\n\nfig = plt.figure()\nax = fig.gca()\n\na=np.arange(1, 31, 0.01)\nprint(a)\n\nax.quiver(x, y, u, v, angles='xy', scale_units='xy', scale=1)\nax.plot(np.sqrt(20**3/(3*a)+a**2/3), a, ) \nax.plot(np.sqrt(20**3/(3*a)+a**2/3), -a, ) \nax.plot(-np.sqrt(20**3/(3*a)+a**2/3), -a, ) \nax.plot(-np.sqrt(20**3/(3*a)+a**2/3), a, ) \nax.plot(-np.sqrt(20**3/(-3*a)+a**2/3), a, ) \nax.plot(np.sqrt(20**3/(-3*a)+a**2/3), a, ) \nax.plot(-np.sqrt(20**3/(-3*a)+a**2/3), -a, ) \nax.plot(np.sqrt(20**3/(-3*a)+a**2/3), -a, ) \nax .set_ylim([-30, 30])\nax .set_xlim([-30, 30])\n#for vektor in schale:\n# ax.plot(100*vektor[0], 100*vektor[1], \"o\", \"r\")\n\n\n\n\n\n#plt.title(\"Teilchenbewegung im longitudinalen Phasenraum\")\n\n#plt.xlabel(r\"$\\Delta \\psi / rad$\")\n#plt.ylabel(r\"$\\Delta E / E$\")\n\nplt.savefig(\"Blatt9_Aufgabe3b_Feline,Hannah.pdf\")\n\n\n#stabile Trajektorien: Phase: ca. -2,5 bis 2,5\n# Energie: bis Abweichung von 0,34 stabil\n# Elektronen im instabilen Bereich verlieren immer weiter an Energie \n\n\n\n","sub_path":"Blatt9/Blatt8_Aufgabe3b_Feline,Hannah.py","file_name":"Blatt8_Aufgabe3b_Feline,Hannah.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"337042718","text":"import operator\nfrom django import forms\nfrom django.forms.models import modelformset_factory\nfrom django.forms.models import BaseModelFormSet\nfrom django.forms.models import inlineformset_factory\nfrom models import SUB_DIR,OBJ_DIR,NORMATIVE\nfrom models import MarketDetailInfo,MarketOverView\nfrom models import TradePlanModel,TradePlanAction\nfrom models import TRADEFRAME,TRADETYPE,STRENGTHSCORE,PLANRESULT\nfrom models import EXREASON\n\n\nclass TradePlanInitForm(forms.ModelForm):\n class Meta:\n model = TradePlanModel\n fields = ('tradeframe','tradetype')\n\n\nclass MarketOverViewForm(forms.ModelForm):\n market_result = forms.CharField(widget=forms.Textarea(attrs={'class':'result_text'}))\n class Meta:\n model = MarketOverView\n fields = ('market_result',)\n \n\nclass PlanResultForm(forms.ModelForm):\n class Meta:\n model = TradePlanModel\n fields = ('plan_result',)\n\n\nFirstSelectFormset = modelformset_factory(MarketDetailInfo,\n extra = 0,\n fields = ('exclude_reason',))\n\nSelectedFormset = modelformset_factory(MarketDetailInfo,\n extra = 0,\n fields = ('symbol_name','timeframe','obj_dir','sub_dir'))\n\n\nMovDetailInlineFormset=inlineformset_factory(MarketOverView,\n MarketDetailInfo,\n extra=0,\n can_delete = False,\n fields = ('timeframe','obj_dir','sub_dir')\n )\n\n\nMdvDetailFormset = modelformset_factory(MarketDetailInfo,\n extra = 0,\n fields = ('symbol_name',\n 'timeframe',\n 'obj_dir',\n 'sub_dir',\n 'strength',\n 'normative'))\n\n\nTradePlanActionFormset = modelformset_factory(TradePlanAction,\n extra = 0,\n fields = ('symbol_name',\n 'trade_type',\n 'trade_status',\n 'enter_price',\n 'sl_price',\n 'tp_price',\n 'holding_log'))\n","sub_path":"forexsys/tradesys/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"391386765","text":"failed = int(input())\ncounter_failed = 0\ntotal_marks = 0\nquantity_of_marks = 0\n\n\nwhile counter_failed <= failed:\n task = input()\n if task == \"Enough\" or counter_failed == failed:\n break\n mark_on_task = int(input())\n quantity_of_marks += 1\n prev_task = task\n if mark_on_task >= 2:\n total_marks += mark_on_task\n if mark_on_task <= 4:\n counter_failed += 1\n\n\nif counter_failed < failed or task == \"Enough\":\n print(f\"Average score: {total_marks / quantity_of_marks:.2f}\")\n print(f\"Number of problems: {quantity_of_marks}\")\n print(f\"Last problem: {prev_task}\")\nelse:\n print(f\"You need a break, {failed} poor grades.\")\n\nfailed_limit = int(input())\nfailed_times = 0\nsolved_count = 0\ngrade_total = 0\nlast_problem = \"\"\nhas_failed = True\n\nwhile failed_times < failed_limit:\n problem_name = input()\n if problem_name == \"Enough\":\n has_failed = False\n break\n grade = int(input())\n if grade <= 4:\n failed_times += 1\n grade_total += grade\n solved_count += 1\n last_problem = problem_name\n\nif has_failed:\n print(f\"You need a break, {failed_times} poor grades.\")\nelse:\n print(f\"Average score: {grade_total / solved_count:.2f}\")\n print(f\"Number of problems: {solved_count}\")\n print(f\"Last problem: {last_problem}\")","sub_path":"Basics Sept 2019/Exam_prep.py","file_name":"Exam_prep.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"584959177","text":"# -*- coding: utf-8 -*-\r\nimport scrapy\r\nimport re\r\nfrom scrapy.linkextractors import LinkExtractor\r\nfrom scrapy.spiders import CrawlSpider, Rule\r\nfrom imdb.items import ImdbItem\r\n \r\n \r\nclass IMDBSpider(CrawlSpider):\r\n name = 'imdb'\r\n allowed_domains = ['imdb.com']\r\n start_urls = ['http://www.imdb.com/chart/top/?ref_=nv_mv_250_6']\r\n \r\n \r\n\r\n def parse(self, response):\r\n for sel in response.xpath(\"//*[contains(@class,'chart full-width')]/tbody/tr\"):\r\n item = ImdbItem()\r\n item['titulo'] = sel.xpath('td[2]/a/text()').extract()[0].strip()\r\n item['puntuacionIMDB'] = sel.xpath('td[3]/strong/text()').extract()[0].strip()\r\n item['ranking'] = re.match(r'(^[0-9]+)',sel.xpath('td[2]/text()').extract()[0].__str__().strip()).group(1)\r\n item['anyoEstreno'] = sel.xpath('normalize-space(td[2]/span/text())').extract()[0].strip()\r\n item['enlace'] = \"http://imdb.com\"+sel.xpath('td[2]/a/@href').extract()[0]\r\n request = scrapy.Request(item['enlace'], callback=self.parsearInfoPelicula)\r\n request.meta['item'] = item\r\n yield request\r\n\r\n\r\n def parsearInfoPelicula(self, response):\r\n item = response.meta['item']\r\n item['director'] = response.xpath(\"//div/span[@itemprop='director']/a/span/text()\").extract()\r\n item['guionistas'] = response.xpath(\"//div/span[@itemprop='creator']/a/span/text()\").extract()\r\n item['sinopsis'] = response.xpath(\"normalize-space(//div[@itemprop='description']/text())\").extract()[0]\r\n item['generos'] = response.xpath(\"//div[@itemprop='genre']/a/text()\").extract()\r\n item['duracion'] = response.xpath(\"normalize-space(//div[@class='subtext']/time[@itemprop='duration']/text())\").extract()[0]\t\t\r\n return item\r\n","sub_path":"imdb/imdb/spiders/imdb_spider.py","file_name":"imdb_spider.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"245645513","text":"import pandas as pd\nimport xml.etree.ElementTree as et\n\ntree = et.parse(\"Test_Cust.xml\")\nroot = tree.getroot()\nprint(root)\n\nmyrows = []\nfor items in root.iter():\n if items.tag == \"Email\":\n cust_email = items.text\n elif items.tag == \"CompanyName\":\n cust_company = items.text\n elif items.tag == \"FirstName\":\n cust_firstname = items.text\n elif items.tag == \"LastName\":\n cust_lastname = items.text\n\n myrows.append({\"Email\":cust_email, \"Company Name\":cust_company, \"First Name\":cust_firstname, \"Last Name\":cust_lastname})\n\nout_df = pd.DataFrame(myrows)\nout_df.to_excel(\"E:\\\\NOP BO Automation\\\\test_data\\CustDetails.xlsx\" , index=False)\nprint(out_df)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"dummy_code/xml_excel.py","file_name":"xml_excel.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"43798009","text":"'''\nDay 19: Interfaces\nThis program is for learning the concept of interface\nIn this program, the AdvancedArithmetic interface is defined,\nand is followed by the Calculator class which implements the interface\nIt seems to me that interface >> class >> instance in terms of the level of concreteness\n\n'''\n\n\nclass AdvancedArithmetic(object): # define the interface AdvancedArithmetic\n def divisorSum(n):\n raise NotImplementedError\n\nclass Calculator(AdvancedArithmetic): # define the Calculator class that implements the interface AdvancedArithmetic\n def divisorSum(self, n): # define the method of the calculator class: divisor sum\n total_sum = 0 # define the outcome variable < total_sum > as 0\n for i in range(1,n+1): # check all the numbers from 1 to n\n if n % i == 0: # if i is a divisor of n,\n total_sum += i # add i to the outcome variable : total_sum\n return total_sum # return the outcome variable\n\n\nn = int(input())\nmy_calculator = Calculator()\ns = my_calculator.divisorSum(n)\nprint(\"I implemented: \" + type(my_calculator).__bases__[0].__name__)\nprint(s)","sub_path":"Day_19_Interfaces.py","file_name":"Day_19_Interfaces.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"372400967","text":"import pygame, funcao, enderecos\r\ndef perdeu():\r\n pygame.font.init()\r\n pygame.mixer.init()\r\n funcao.carregaraudio('derrota/audios/derrota.ogg').play()\r\n font = pygame.font.get_default_font()\r\n fonte = pygame.font.SysFont(font, 60)\r\n texto = 'VOCÊ PERDEU!'\r\n clicoumenu = clicouexit = 1\r\n while True:\r\n\r\n clock = pygame.time.Clock()\r\n clock.tick(30)\r\n text = fonte.render(texto, 1, (0, 0, 0))\r\n textRect = text.get_rect()\r\n textRect.center = (472, 450)\r\n tela = pygame.display.set_mode((945, 600))\r\n funcao.mostrartela(tela, funcao.carregarimagem(f'derrota/imagens/fundo.png'), 0, 0)\r\n tela.blit(text, textRect)\r\n if clicoumenu % 2 != 0:\r\n funcao.mostrartela(tela, enderecos.botaomenu, 750, 60)\r\n else:\r\n enderecos.sommenu.play()\r\n funcao.mostrartela(tela, enderecos.botaomenupressionado, 755, 63)\r\n pygame.display.update()\r\n import telainicial\r\n telainicial.telainicial()\r\n\r\n if clicouexit % 2 != 0:\r\n funcao.mostrartela(tela, enderecos.botaoexit, 750, 145)\r\n else:\r\n funcao.mostrartela(tela, enderecos.botaoexitpressionado, 755, 148)\r\n pygame.display.update()\r\n quit()\r\n\r\n pygame.display.update()\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n elif event.type == pygame.MOUSEBUTTONDOWN:\r\n if event.button == 1:\r\n x = pygame.mouse.get_pos()[0]\r\n y = pygame.mouse.get_pos()[1]\r\n if funcao.clicoubotao(x, y, 897, 767, 127, 72):\r\n clicoumenu = 2\r\n pygame.mixer.stop()\r\n if funcao.clicoubotao(x, y, 897, 767, 215, 158):\r\n enderecos.sommenu.play()\r\n clicouexit = 2","sub_path":"derrota.py","file_name":"derrota.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"427245695","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.contrib import messages\nfrom django.core.paginator import EmptyPage, PageNotAnInteger, Paginator\nfrom django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponseRedirect, Http404\n\nfrom django.contrib.contenttypes.models import ContentType\nfrom .models import Post\nfrom django.db.models import Q\nfrom django.utils import timezone\nfrom .forms import PostForm\nfrom urllib.parse import quote_plus\n# Create your views here.\n\n#function based views\ndef post_home(request):\n\tsearch_term = ''\n\ttoday = timezone.now().date()\n\tquery = Post.objects.active()\n\tif request.user.is_staff or request.user.is_superuser:\n\t\tquery = Post.objects.all()\n\n\tif 'search' in request.GET:\n\t\tsearch_term = request.GET['search']\n\t\tquery = query.filter(title__icontains=search_term)\n\n\n\tpaginator = Paginator(query, 4) # Show 25 contacts per page\n\tpage_request_var = 'page'\n\tpage = request.GET.get(page_request_var)\n\ttry:\n\t\tqueries = paginator.get_page(page)\n\texcept PageNotAnInteger:\n\t\tqueries = paginator.page(1)\n\texcept EmptyPage:\n\t\tqueries = paginator.page(paginator.num_pages)\n\tcontext = {\n\t\"popular_posts\":queries[0:4],\n\t\"page_request_var\":page_request_var,\n\t\"today\":today,\n\t\"object_list\":queries,\n\t\"search_term\":search_term\n\t}\n\treturn render(request,\"index2.html\",context)\n\n\ndef post_detail(request,id):\n\tquery = Post.objects.all()[0:4]\n\tinstance = get_object_or_404(Post, id =id)\n\tif instance.publish_date>timezone.now() or instance.draft:\n\t\tif not request.user.is_staff or not request.user.is_superuser:\n\t\t\traise Http404\n\tshare_string = quote_plus(instance.content)\n\tcontent_type =ContentType.objects.get_for_model(Post)\n\tobj_id = instance.id\n\t#Post.objects.get(id=instance.id)\n\n\t\n\n\tinitial_data = {\n\n\t\t\"content_type\":instance.get_content_type,\n\t\t\"object_id\": instance.id,\n\n\t}\n\n\n\t\n\tcontext={\n\t \"popular_posts\":query,\n\t\t\"title\":instance.title,\n\t\t\"instance\":instance,\n\t\t\"share_string\":share_string,\n\t\t\"publish_date\":instance.publish_date.date(),\n\t\t\"updated\":instance.updated.date(),\n\t\t\n\t}\n\treturn render(request, \"post_detail2.html\",context)\n\n\ndef post_create(request):\n\tif not request.user.is_staff or not request.user.is_superuser:\n\t\traise Http404\n\n\tif not request.user.is_authenticated:\n\t\traise Http404\n\n\tform = PostForm(request.POST or None, request.FILES or None)\n\n\tif form.is_valid():\n\t\tinstance = form.save(commit=False)\n\t\tinstance.user = request.user\n\t\tinstance.save()\n\t\tmessages.success(request, \"new Item created\")\n\t\treturn HttpResponseRedirect(instance.get_absolute_url())\n\telse:\n\t\tmessages.error(request, \"Not succesfully created\")\n\tcontext={\n\t\"form\": form, \n\t}\n\treturn render(request, \"post_form2.html\",context)\n\n\ndef post_update(request, id=None):\n\tif not request.user.is_staff or not request.user.is_superuser:\n\t\traise Http404\n\tinstance = get_object_or_404(Post, id=id)\n\tform = PostForm(request.POST or None, request.FILES or None, instance=instance)\n\tif form.is_valid():\n\t\tinstance = form.save(commit=False)\n\t\tinstance.save()\n\t\tmessages.success(request, \"Item saved\")\n\t\tmessages.success(request, \"title saved\")\n\t\tmessages.success(request, \"content saved\")\n\t\treturn HttpResponseRedirect(instance.get_absolute_url())\n\tcontext={\n\t\t\"title\":instance.title,\n\t\t\"instance\":instance,\n\t\t\"form\": form, \n\t}\n\treturn render(request, \"post_form2.html\",context)\n\ndef about(request):\n\tquery = Post.objects.all()[0:4]\n\tcontext={\n\t\t\"popular_posts\":query,\n\n\t}\n\treturn render(request,'about.html',context)\n\ndef contact(request):\n\tquery = Post.objects.all()[0:4]\n\tcontext={\n\t\t\"popular_posts\":query,\n\n\t}\n\treturn render(request,'contact.html',context)\n","sub_path":"durgesh/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"192868651","text":"import numpy as np\nfrom tqdm import trange\n\nfrom mushroom_rl.algorithms.value.batch_td import BatchTD\nfrom mushroom_rl.utils.dataset import parse_dataset\n\n\nclass FQI(BatchTD):\n \"\"\"\n Fitted Q-Iteration algorithm.\n \"Tree-Based Batch Mode Reinforcement Learning\", Ernst D. et al.. 2005.\n\n \"\"\"\n def __init__(self, mdp_info, policy, approximator, n_iterations,\n approximator_params=None, fit_params=None, quiet=False,\n boosted=False):\n \"\"\"\n Constructor.\n\n Args:\n n_iterations (int): number of iterations to perform for training;\n quiet (bool, False): whether to show the progress bar or not;\n boosted (bool, False): whether to use boosted FQI or not.\n\n \"\"\"\n self._n_iterations = n_iterations\n self._quiet = quiet\n\n # \"Boosted Fitted Q-Iteration\". Tosatto S. et al.. 2017.\n self._boosted = boosted\n if self._boosted:\n self._prediction = 0.\n self._next_q = 0.\n self._idx = 0\n approximator_params['n_models'] = n_iterations\n\n self._add_save_attr(\n _n_iterations='primitive',\n _quiet='primitive',\n _boosted='primitive',\n _prediction='primitive',\n _next_q='numpy',\n _idx='primitive',\n _target='pickle'\n )\n\n super().__init__(mdp_info, policy, approximator, approximator_params,\n fit_params)\n\n self._target = None\n\n def fit(self, dataset):\n \"\"\"\n Fit loop.\n\n \"\"\"\n if self._boosted:\n if self._target is None:\n self._prediction = 0.\n self._next_q = 0.\n self._idx = 0\n fit = self._fit_boosted\n else:\n fit = self._fit\n\n for _ in trange(self._n_iterations, dynamic_ncols=True,\n disable=self._quiet, leave=False):\n fit(dataset)\n\n def _fit(self, x):\n \"\"\"\n Single fit iteration.\n\n Args:\n x (list): the dataset.\n\n \"\"\"\n state, action, reward, next_state, absorbing, _ = parse_dataset(x)\n if self._target is None:\n self._target = reward\n else:\n q = self.approximator.predict(next_state)\n if np.any(absorbing):\n q *= 1 - absorbing.reshape(-1, 1)\n\n max_q = np.max(q, axis=1)\n self._target = reward + self.mdp_info.gamma * max_q\n\n self.approximator.fit(state, action, self._target, **self._fit_params)\n\n def _fit_boosted(self, x):\n \"\"\"\n Single fit iteration for boosted FQI.\n\n Args:\n x (list): the dataset.\n\n \"\"\"\n state, action, reward, next_state, absorbing, _ = parse_dataset(x)\n if self._target is None:\n self._target = reward\n else:\n self._next_q += self.approximator.predict(next_state,\n idx=self._idx - 1)\n if np.any(absorbing):\n self._next_q *= 1 - absorbing.reshape(-1, 1)\n\n max_q = np.max(self._next_q, axis=1)\n self._target = reward + self.mdp_info.gamma * max_q\n\n self._target -= self._prediction\n self._prediction += self._target\n\n self.approximator.fit(state, action, self._target, idx=self._idx,\n **self._fit_params)\n\n self._idx += 1\n\n\nclass DoubleFQI(FQI):\n \"\"\"\n Double Fitted Q-Iteration algorithm.\n \"Estimating the Maximum Expected Value in Continuous Reinforcement Learning\n Problems\". D'Eramo C. et al.. 2017.\n\n \"\"\"\n def __init__(self, mdp_info, policy, approximator, n_iterations,\n approximator_params=None, fit_params=None, quiet=False):\n approximator_params['n_models'] = 2\n\n super().__init__(mdp_info, policy, approximator, n_iterations,\n approximator_params, fit_params, quiet)\n\n def _fit(self, x):\n state = list()\n action = list()\n reward = list()\n next_state = list()\n absorbing = list()\n\n half = len(x) // 2\n for i in range(2):\n s, a, r, ss, ab, _ = parse_dataset(x[i * half:(i + 1) * half])\n state.append(s)\n action.append(a)\n reward.append(r)\n next_state.append(ss)\n absorbing.append(ab)\n\n if self._target is None:\n self._target = reward\n else:\n for i in range(2):\n q_i = self.approximator.predict(next_state[i], idx=i)\n\n amax_q = np.expand_dims(np.argmax(q_i, axis=1), axis=1)\n max_q = self.approximator.predict(next_state[i], amax_q,\n idx=1 - i)\n if np.any(absorbing[i]):\n max_q *= 1 - absorbing[i]\n self._target[i] = reward[i] + self.mdp_info.gamma * max_q\n\n for i in range(2):\n self.approximator.fit(state[i], action[i], self._target[i], idx=i,\n **self._fit_params)\n","sub_path":"mushroom_rl/algorithms/value/batch_td/fqi.py","file_name":"fqi.py","file_ext":"py","file_size_in_byte":5148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"347914298","text":"def bubbleSort(arr):\n n = len(arr)\n for i in range(n - 1):\n for j in range(0, n - i - 1):\n if arr[j] > arr[j + 1]:\n arr[j], arr[j + 1] = arr[j + 1], arr[j]\n\n\nname_url = []\nfileObject = open(\"C:/Users/maxsu/OneDrive/Desktop/PythonTestingFileReaders/ArchiTextFileTest1.txt\", \"r\") #add file with name and location\ndata = fileObject.readlines()\nn = len(data)\nfor i in range(n):\n data[i] = data[i].strip()\nprint(data)\nbubbleSort(data)\nprint(data)\nMyFile = open('C:/Users/maxsu/OneDrive/Desktop/PythonTestingFileReaders/ArchiTextFileEdit1.txt', 'w') #add new file with name and correct location\nfor element in data:\n MyFile.write(element + \"\\n\")\nMyFile.close()\n","sub_path":"PycharmProjects/pythonProject0001/FileSorter2.py","file_name":"FileSorter2.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"592005404","text":"\"\"\"first project for algorithmic thinking\"\"\"\n\nEX_GRAPH0 = {0: {1, 2}, 1: set([]), 2: set([])}\nEX_GRAPH1 = {0: {1, 4, 5}, 1: {2, 6}, 2: {3}, 3: {0}, 4: {1}, 5: {2}, 6: set([])}\nEX_GRAPH2 = {0: {1, 4, 5}, 1: {2, 6}, 2: {3, 7}, 3: {7}, 4: {1}, 5: {2}, 6: set([]), 7: {3}, 8: {1, 2},\n 9: {0, 3, 4, 5, 6, 7}}\n\n\ndef make_complete_graph(num_nodes):\n \"\"\"function to create a full directional graph with num_nodes nodes\"\"\"\n result = {}\n for num in range(num_nodes):\n connections = set(range(num_nodes))\n connections.remove((num))\n result[num] = connections\n return result\n\n\ndef compute_in_degrees(digraph):\n \"\"\"function to compute the in-degrees of every node in a digraph given as a dictionary\"\"\"\n result = {}\n for node in digraph:\n result[node] = 0\n for node in digraph:\n for connection in digraph[node]:\n result[connection] += 1\n return result\n\n\ndef in_degree_distribution(digraph):\n \"\"\"function to compute unnormalized in-degree distribution\"\"\"\n result = {}\n in_degrees = compute_in_degrees(digraph)\n for key in in_degrees:\n result[in_degrees[key]] = 0\n for key in in_degrees:\n result[in_degrees[key]] += 1\n return result\n","sub_path":"Project_1.py","file_name":"Project_1.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"301224577","text":"def main():\n\n import countAllLetters\n\n file_name = input('Enter a file name: ')\n input_file = open(file_name, 'r')\n \n line = input('Enter a string: ')\n \n list_count = countAllLetters.countALLLetters(line)\n \n print(list_count)\n","sub_path":"main_countAllLetters copy.py","file_name":"main_countAllLetters copy.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"404503843","text":"class HtmlTemplate():\n \n def __init__(self):\n self.headerTags = \"\"\n self.title = \"\"\n self.body = \"\"\n self.script = \"\"\n \n def addHeaders(self, resources):\n for resource in resources:\n if resource[-3:] == \".js\":\n startTag = '\n \"\"\" % script\n return self\n\n def buildPage(self):\n return \"\"\"\n \n\n \n \n %(headers)s\n \n %(title)s\n \n \n \n %(body)s\n %(script)s\n \n \n\n \"\"\" % {\n \"headers\": self.headerTags,\n \"title\": self.title,\n \"body\": '
' + self.body,\n \"script\": self.script\n }","sub_path":"HtmlTemplate.py","file_name":"HtmlTemplate.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"312370306","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate\n\n#Form#\nfrom training_lab.forms import Learning_labForm\n#from training_lab.forms import SearchForm\n######\n\nfrom training_lab.models import Learning_lab\n\n#number = 2\n#nickname = \"jan magnait\"\n#def index(request):\n#\treturn render(request, 'index.html', {\n# 'number': number, 'nickname': nickname,\n# }\n\n# )\n \ndef index(request):\n\tlearning_labs = Learning_lab.objects.all()\n\treturn render(request, \n\t'index.html', {'learning_labs': learning_labs,\n\t})\n\t\n\ndef learning_lab_detail(request, slug):\n\tif request.user.is_authenticated():\n\t\tlearning_lab = Learning_lab.objects.get(slug=slug)\n\t\treturn render(request, 'learning_labs/learning_lab_detail.html', {'learning_lab': learning_lab,})\n\telse: \n\t\treturn render(request, 'registration/access-denied.html') \n\t\n\n###Form###\ndef edit_learning_lab(request, slug):\n\t# grab object\n\tlearning_lab = Learning_lab.objects.get(slug=slug)\n\t# set the form\n\tform_class = Learning_labForm\n\t\n\tif request.method == 'POST':\n\t\tform = form_class(data=request.POST, instance=learning_lab)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\treturn redirect('learning_lab_detail', slug=learning_lab.slug)\n\telse:\n\t\tform = form_class(instance=learning_lab)\t\n\treturn render(request, 'learning_labs/edit_learning_lab.html', {\n\t\t'learning_lab': learning_lab,\n\t\t'form': form,\n\t})\n\ndef browse_by_name(request, initial=None):\n\tif initial:\n\t\tlearning_labs = Learning_lab.objects.filter(name__istartswith=initial)\n\t\tlearning_labs = learning_labs.order_by('name')\n\telse:\n\t\tlearning_labs = Learning_lab.objects.all().order_by('name')\n\treturn render(request, 'search/search.html', {\n\t\t'learning_labs': learning_labs,\n\t\t'initial': initial,\n\t})\t\t\n#def search_learning_lab(request, initial='C'):\n\t# grab object\n\t#search_labs = Learning_lab.objects.all()\n\n\t#search_labs = Learning_lab.objects.get(name__contains='Cent')\n\t#search_labs = Learning_lab.objects.filter(name__contains=initial)\n\t#search_labs = search_labs.order_by('name')\n\t# set the form\n\t#form_class = SearchForm\n\t\n\t#if request.method == 'POST':\n\t\t#form = form_class(data=request.POST, instance=search_lab)\n\t\t#if form.is_valid():\n\t#return render(request, 'index.html', {'search_labs': search_labs,\n\t# 'initial': initial,\n\t#\t\t\t\t\t\t\t\t\t })\n\t#else:\n\t#\tform = form_class(instance=search_lab)\t\n\t#return render(request, 'index.html', {\n\t#\t'search_lab': search_lab,\n\t#\t'form': form,\n\t#})\t","sub_path":"training_lab/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"372257961","text":"# -*- coding:utf-8 -*-\nimport unittest\nimport requests\nimport json\nfrom TestCase.gloVal import gloVal\n\n#子类目录新增\nclass know_category_save(unittest.TestCase):\n def setUp(self):\n self.url = gloVal.BOSS_URL + '/category/sava'\n self.header = {'content-type': 'application/json', 'token': gloVal.TOKEN}\n\n #新增子目录\n def test01(self):\n data = {\n \"name\": \"血液分析\",\n \"parentId\": 1,\n \"projectId\": 1\n }\n r = requests.post(self.url, headers=self.header, data=json.dumps(data))\n body = r.text\n response = json.loads(r.text)\n print('接口返回:' + body)\n self.assertEqual(\"0000\", response[\"code\"], msg=response['desc'])\n\n #修改子目录\n def test02(self):\n data = {\n \"name\": \"yey分析\",\n \"parentId\": 1,\n \"projectId\": 1\n }\n r = requests.post(self.url, headers=gloVal.HEADER, data=json.dumps(data))\n body = r.text\n response = json.loads(r.text)\n print('接口返回:' + body)\n self.assertEqual(\"0000\", response[\"code\"], msg=response['desc'])\n\n\n\n def tearDown(self):\n pass\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"test_flins_api/TestCase/test_medbrain/test_24-25know_category_save.py","file_name":"test_24-25know_category_save.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"173063546","text":"from django.urls import path\nfrom . import views\n\napp_name = 'user'\nurlpatterns = [\n path('',views.index,name='index'),\n\n path('pages/center',views.center_page),\n path('pages/profile',views.profile,name='profile'),\n path('pages/nodes',views.nodes,name='nodes'),\n path('pages/plans',views.plans,name='plans'),\n path('pages/download',views.download,name='download'),\n path('pages/tutorial',views.tutorial,name='tutorial'),\n path('pages/reward',views.reward,name='reward'),\n path('pages/invite',views.invite,name='invite'),\n path('pages/own-node',views.own_node,name='own_node'),\n path('pages/reward-history',views.reward_history,name='reward-history')\n]","sub_path":"src/front/user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"508738401","text":"import mqttclient\nimport resource_updater\n\ndevice_uuid = '1'\n\n\nclient = mqttclient.get_client(\"10.24.24.222\", device_uuid)\n# Self registering could code possibly go here.\n# In fact NiFi startup could also go here.\n# This should be run at startup inside the container.\nupdater_thread = resource_updater.start_updater()\nclient.subscribe(device_uuid)\nclient.loop_forever()\n\n","sub_path":"echo_platform_service/echo_platform_service.py","file_name":"echo_platform_service.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"112173974","text":"'''Programa para aprender o funcionamento da Queue e do Unittest'''\nimport unittest\n\n\nclass Fila:\n\n def __init__(self, size):\n '''Cria os atributos da queue.\n\n Argumento:\n size: Comprimento da queue.\n '''\n self.size = size\n self._fila = [None for i in range(size)]\n self._posicao_insercao = 0\n self._posicao_remocao = 0\n self._fila_cheia = False\n\n def obtem_fila(self):\n ver_fila = []\n checa_elemento_fila = self._posicao_remocao\n if self._fila_cheia is False:\n while checa_elemento_fila != self._posicao_insercao:\n ver_fila += [self._fila[checa_elemento_fila]]\n checa_elemento_fila += 1\n checa_elemento_fila = checa_elemento_fila % self.size\n if self._fila_cheia is True:\n for i in range(self.size):\n ver_fila += [self._fila[checa_elemento_fila]]\n checa_elemento_fila += 1\n checa_elemento_fila = checa_elemento_fila % self.size\n return ver_fila\n\n def insere(self, elemento):\n if self._fila_cheia is True:\n raise Exception('Fila cheia!')\n else:\n self._fila[self._posicao_insercao] = elemento\n self._posicao_insercao += 1\n self._posicao_insercao = self._posicao_insercao % self.size\n if self._posicao_insercao == self._posicao_remocao:\n self._fila_cheia = True\n\n def remove(self):\n if self._fila[self._posicao_remocao] is None:\n raise Exception('Nenhum elemento encontrado')\n else:\n elemento = self._fila[self._posicao_remocao]\n self._posicao_remocao += 1\n self._posicao_remocao = self._posicao_remocao % self.size\n self._fila_cheia = False\n return elemento\n\n\nclass FilaTestCase(unittest.TestCase):\n\n def setUp(self):\n self.fila = Fila(size=6)\n\n def test_enche_e_esvazia_duas_vezes(self):\n for n in range(1, 7):\n self.fila.insere(n)\n for x in range(6):\n self.fila.remove()\n for m in range(1, 7):\n self.fila.insere(m)\n for y in range(6):\n self.fila.remove()\n\n def test_adiciona_mais_elementos_do_que_e_possivel_causa_falha(self):\n self.fila.insere(1)\n self.fila.insere(2)\n self.fila.insere(3)\n self.fila.insere(4)\n self.fila.insere(5)\n self.fila.insere(6)\n with self.assertRaises(Exception):\n self.fila.insere(7)\n self.assertEqual(self.fila.obtem_fila(), [1, 2, 3, 4, 5, 6])\n\n def test_alterando_metodos(self):\n '''Inserir 1, 2, 3, 4, 5, 6 remover dois elementos, inserir 100, 8,\n remover 5 elementos e inserir 10 e 20, a fila será [8, 10, 20]\n '''\n for n in range(1, 7):\n self.fila.insere(n)\n self.fila.remove()\n self.fila.remove()\n self.fila.insere(100)\n self.fila.insere(8)\n for x in range(5):\n self.fila.remove()\n self.fila.insere(10)\n self.fila.insere(20)\n self.assertEqual(self.fila.obtem_fila(),\n [8, 10, 20])\n\n def test_garante_insercao_circular(self):\n '''Cria o mesmo resultado do desafio 1, sem a utilização dos métodos\n remove_por_index e insere_por_index.\n '''\n self.fila.insere(5)\n self.fila.insere(5)\n self.fila.insere(5)\n self.fila.insere(5)\n self.fila.insere(5)\n self.fila.insere(5)\n self.fila.remove()\n self.fila.insere(4)\n self.fila.remove()\n self.fila.insere(3)\n self.assertEqual(self.fila.obtem_fila(), [5, 5, 5, 5, 4, 3])\n\n def test_remove_mais_elementos_do_que_tem_causa_falha(self):\n self.fila.insere(5)\n self.fila.remove()\n with self.assertRaises(Exception):\n self.fila.remove()\n self.assertEqual(self.fila.obtem_fila(), [])\n\n def test_remove_dois_elementos(self):\n self.fila.insere(5)\n self.fila.insere(1)\n self.fila.insere(2)\n elemento_removido = self.fila.remove()\n elemento_removido = self.fila.remove()\n self.assertEqual(elemento_removido, 1)\n\n def test_remove_elemento(self):\n self.fila.insere(5)\n self.fila.insere(1)\n elemento_removido = self.fila.remove()\n self.assertEqual(elemento_removido, 5)\n\n def test_insere_dois_elementos(self):\n self.fila.insere(5)\n self.fila.insere(2)\n self.assertEqual(self.fila.obtem_fila(), [5, 2])\n\n def test_insere_elemento(self):\n self.fila.insere(5)\n self.assertEqual(self.fila.obtem_fila(), [5])\n\n def test_obtem_fila_vazia(self):\n self.assertEqual(self.fila.obtem_fila(), [])\n\n def test_instancia_fila(self):\n self.assertIsInstance(self.fila, Fila)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"mentor/ex19_unittest.py","file_name":"ex19_unittest.py","file_ext":"py","file_size_in_byte":4926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"327383876","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Person',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('firstname', models.CharField(max_length=20, verbose_name='Nome')),\n ('lastname', models.CharField(max_length=20, verbose_name='Sobrenome')),\n ('cpf', models.CharField(max_length=11, verbose_name='CPF')),\n ('birthdate', models.DateTimeField(verbose_name='Nascimento')),\n ('email', models.EmailField(max_length=75, unique=True, verbose_name='e-mail')),\n ('phone', models.CharField(max_length=18, verbose_name='Fone')),\n ('blocked', models.BooleanField(default=False)),\n ('created_at', models.DateTimeField(verbose_name='Criado em', auto_now_add=True)),\n ('modified_at', models.DateTimeField(auto_now=True, verbose_name='Modificado em')),\n ],\n options={\n 'verbose_name': 'pessoa',\n 'verbose_name_plural': 'pessoas',\n 'ordering': ['firstname'],\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"myproject/core/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"268282033","text":"# Copyright (c) 2020, salesforce.com, inc.\n# All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n# For full license text, see the LICENSE file in the repo root\n# or https://opensource.org/licenses/BSD-3-Clause\n\nimport numpy as np\n\n\ndef annealed_tax_limit(completions, warmup_period, slope, final_max_tax_value=1.0):\n \"\"\"\n Compute the maximum tax rate available at this stage of tax annealing.\n\n This function uses the number of episode completions and the annealing schedule\n (warmup_period, slope, & final_max_tax_value) to determine what the maximum tax\n rate can be.\n This type of annealing allows for a tax curriculum where earlier episodes are\n restricted to lower tax rates. As more episodes are played, higher tax values are\n allowed.\n\n Args:\n completions (int): Number of times the environment has completed an episode.\n Expected to be >= 0.\n warmup_period (int): Until warmup_period completions, only allow 0 tax. Using\n a negative value will enable non-0 taxes at 0 environment completions.\n slope (float): After warmup_period completions, percentage of full tax value\n unmasked with each new completion.\n final_max_tax_value (float): The maximum tax value at the end of annealing.\n\n Returns:\n A scalar value indicating the maximum tax at this stage of annealing.\n\n Example:\n >> WARMUP = 100\n >> SLOPE = 0.01\n >> annealed_tax_limit(0, WARMUP, SLOPE)\n 0.0\n >> annealed_tax_limit(100, WARMUP, SLOPE)\n 0.0\n >> annealed_tax_limit(150, WARMUP, SLOPE)\n 0.5\n >> annealed_tax_limit(200, WARMUP, SLOPE)\n 1.0\n >> annealed_tax_limit(1000, WARMUP, SLOPE)\n 1.0\n \"\"\"\n # What percentage of the full range is currently visible\n # (between 0 [only 0 tax] and 1 [all taxes visible])\n percentage_visible = np.maximum(\n 0.0, np.minimum(1.0, slope * (completions - warmup_period))\n )\n\n # Determine the highest allowable tax,\n # given the current position in the annealing schedule\n current_max_tax = percentage_visible * final_max_tax_value\n\n return current_max_tax\n\n\ndef annealed_tax_mask(completions, warmup_period, slope, tax_values):\n \"\"\"\n Generate a mask applied to a set of tax values for the purpose of tax annealing.\n\n This function uses the number of episode completions and the annealing schedule\n to determine which of the tax values are considered valid. The most extreme\n tax/subsidy values are unmasked last. Zero tax is always unmasked (i.e. always\n valid).\n This type of annealing allows for a tax curriculum where earlier episodes are\n restricted to lower tax rates. As more episodes are played, higher tax values are\n allowed.\n\n Args:\n completions (int): Number of times the environment has completed an episode.\n Expected to be >= 0.\n warmup_period (int): Until warmup_period completions, only allow 0 tax. Using\n a negative value will enable non-0 taxes at 0 environment completions.\n slope (float): After warmup_period completions, percentage of full tax value\n unmasked with each new completion.\n tax_values (list): The list of tax values associated with each action to\n which this mask will apply.\n\n Returns:\n A binary mask with same shape as tax_values, indicating which tax values are\n currently valid.\n\n Example:\n >> WARMUP = 100\n >> SLOPE = 0.01\n >> TAX_VALUES = [0.0, 0.25, 0.50, 0.75, 1.0]\n >> annealed_tax_limit(0, WARMUP, SLOPE, TAX_VALUES)\n [0, 0, 0, 0, 0]\n >> annealed_tax_limit(100, WARMUP, SLOPE, TAX_VALUES)\n [0, 0, 0, 0, 0]\n >> annealed_tax_limit(150, WARMUP, SLOPE, TAX_VALUES)\n [1, 1, 1, 0, 0]\n >> annealed_tax_limit(200, WARMUP, SLOPE, TAX_VALUES)\n [1, 1, 1, 1, 1]\n >> annealed_tax_limit(1000, WARMUP, SLOPE, TAX_VALUES)\n [1, 1, 1, 1, 1]\n \"\"\"\n # Infer the most extreme tax level from the supplied tax values.\n abs_tax = np.abs(tax_values)\n full_tax_amount = np.max(abs_tax)\n\n # Determine the highest allowable tax, given the current position\n # in the annealing schedule\n max_absolute_visible_tax = annealed_tax_limit(\n completions, warmup_period, slope, full_tax_amount\n )\n\n # Return a binary mask to allow for taxes\n # at or below the highest absolute visible tax\n return np.less_equal(np.abs(tax_values), max_absolute_visible_tax).astype(\n np.float32\n )\n","sub_path":"ai_economist/foundation/components/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"4806639","text":"from pyspark.sql import SparkSession\nfrom pyspark.sql.functions import array, array_intersect, col, expr, lit, size, split, when\n\n\ndef tag_info_df(spark):\n \"\"\" Extract features from the tags of a post\n\n Args:\n spark (SparkSession): used to run queries and commands\n\n Returns:\n DataFrame: With columns [\n (post)_Id,\n #tags,\n contains_language_tag,\n contains_platform_tag\n ]\n \"\"\"\n language_list = [\"abap\", \"abc\", \"actionscript\", \"ada\", \"algol\", \"algol 58\", \"algol 60\", \"algol w\", \"algol 68\",\n \"alice\", \"amiga e\", \"apex\", \"apl\", \"applescript\", \"argh!\", \"aargh!\", \"assembly\",\n \"assembly language\", \"autolisp\", \"autolt\", \"awk\",\n \"b\", \"bash\", \"basic\", \"ballerina\", \"bbc basic\", \"bc\", \"bcpl\", \"blitz basic\", \"bourne shell\",\n \"brainfuck\",\n \"c\", \"c++\", \"c#\", \"cfml\", \"cl\", \"classic visual basic\", \"clean\", \"clipper\", \"clojure\", \"cobol\",\n \"comal\", \"common lisp\", \"coffeescript\", \"crystal\", \"c shell\", \"ct\",\n \"d\", \"darkbasic\", \"dart\", \"decimal basic\", \"delphi\", \"delta cobol\", \"div games studio\",\n \"egl\", \"eiffel\", \"elixir\", \"elm\", \"emacs lisp\", \"erlang\", \"euphoria\",\n \"f#\", \"factor\", \"fenix project\", \"forth\", \"fortran\", \"foxpro\",\n \"gambas\", \"gcl\", \"gml\", \"go\", \"grasshopper\", \"groovy\",\n \"hack\", \"haskell\", \"hypertalk\",\n \"icon\", \"inform\", \"io\", \"ironpython\",\n \"j\", \"just another language\", \"java\", \"javascript\", \"just basic\", \"jscript\", \"julia\",\n \"korn shell\", \"kotlin\",\n \"labview\", \"ladder logic\", \"leet\", \"liberty basic\", \"lisp\", \"logo\", \"lua\",\n \"m4\", \"machine\", \"machine language\", \"malbolge\", \"maple\", \"matlab\", \"m-code\", \"mercury\", \"ml\",\n \"modula-2\", \"mondrian\", \"mql4\", \"msl\",\n \"natural\",\n \"oberon\", \"objective-c\", \"objectpal\", \"object pascal\", \"ocaml\", \"opencl\", \"openedge abl\", \"oz\",\n \"pascal\", \"pawn\", \"perl\", \"php\", \"piet\", \"pl/1\", \"pl/i\", \"pl/sql\", \"pl/pgsql\", \"postscript\",\n \"powerbasic\", \"powerbuilder\", \"powershell\", \"processing\", \"progress\", \"prolog\", \"providex\",\n \"purebasic\", \"python\",\n \"q#\", \"qbasic\",\n \"r\", \"raku\", \"rexx\", \"ring\", \"rpg\", \"ruby\", \"rust\",\n \"sas\", \"scala\", \"sed\", \"scheme\", \"scratch\", \"scratch jr.\", \"seed7\", \"self\", \"simula\", \"smalltalk\",\n \"smallbasic\", \"snobol\", \"solidity\", \"spark\", \"spss\", \"sql\", \"stata\", \"swift\",\n \"tcl\", \"tex\", \"ti-basic\", \"transact-sql\", \"t-sql\", \"turbobasic\", \"turbo c\", \"turbo pascal\",\n \"typescript\",\n \"ubasic\",\n \"vala\", \"vala/genie\", \"vb\", \"vbs\", \"vbscript\", \"verilog\", \"vhdl\", \"visual basic\", \"visual c\",\n \"visual foxpro\", \"visual objects\", \"vbscripts\", \"whitespace\",\n \"xslt\", \"xquery\",\n \"yaml\"]\n language_list_col = array(*[lit(x) for x in language_list])\n platform_list = [\"arthur\", \"arx\", \"mos\", \"risc-ix\", \"risc-os\", \"amigaos\", \"amigaos-1.0-3.9\", \"amigaos-4\",\n \"amiga-unix\", \"amsdos\", \"contiki\", \"cp-m-2.2\", \"cp-m-plus\", \"symbos\", \"apple-ii\", \"apple-dos\",\n \"apple-pascal\", \"prodos\", \"gs-os\", \"gno-me\", \"apple-iii\", \"apple-sos\", \"apple-lisa\",\n \"apple-macintosh\", \"classic-mac-os\", \"a-ux\", \"copland\", \"mklinux\", \"pink\", \"rhapsody\", \"macos\",\n \"macos-server\", \"apple-network-server\", \"ibm-aix\", \"apple-messagepad\", \"newton-os\", \"iphone\",\n \"ios\", \"ipad\", \"ipados\", \"apple-watch\", \"watchos\", \"apple-tv\", \"tvos\", \"a-rose\", \"ipod-software\",\n \"netbsd\", \"domain-os\", \"atari-dos\", \"atari-tos\", \"atari-multitos\", \"xts-400\", \"beos\", \"beia\",\n \"beos-r5.1d0\", \"magnussoft-zeta\", \"unix\", \"unix-time-sharing-system-v6\", \"pwb-unix\", \"cb-unix\",\n \"unix-time-sharing-system-v7\", \"unix-system-iii\", \"unix-system-v\", \"unix-time-sharing-system-v8\",\n \"unix-time-sharing-system-v9\", \"unix-time-sharing-system-v10\", \"besys\", \"plan-9-from-bell-labs\",\n \"inferno\", \"burroughs-mcp\", \"chippewa-operating-system\", \"kronos\", \"nos\", \"scope\", \"puffin-os\",\n \"convergent-technologies-operating-system\", \"cromemco-dos\", \"cromix\", \"aos\", \"dg-ux\", \"rdos\",\n \"datapoint-2200\", \"datapoint\", \"deos\", \"heartos\", \"cp-m\", \"personal-cp-m\", \"cp-m-68k\", \"cp-m-8000\",\n \"cp-m-86\", \"cp-m-86-plus\", \"personal-cp-m-86\", \"mp-m\", \"mp-m-ii\", \"mp-m-86\", \"mp-m-8-16\",\n \"concurrent-cp-m\", \"concurrent-cp-m-86\", \"concurrent-cp-m-8-16\", \"concurrent-cp-m-68k\", \"dos\",\n \"concurrent-dos\", \"concurrent-pc-dos\", \"concurrent-dos-8-16\", \"concurrent-dos-286\",\n \"concurrent-dos-xm\", \"concurrent-dos-386\", \"concurrent-dos-386-mge\", \"concurrent-dos-68k\",\n \"flexos\", \"flexos-186\", \"flexos-286\", \"siemens-s5-dos-mt\", \"ibm-4680-os\", \"ibm-4690-os\",\n \"toshiba-4690-os\", \"flexos-386\", \"flexos-68k\", \"multiuser-dos\", \"cci-multiuser-dos\",\n \"datapac-multiuser-dos\", \"datapac-system-manager\", \"ims-multiuser-dos\", \"real-32\", \"real-ng\",\n \"dos-plus\", \"dr-dos\", \"palmdos\", \"star-trek\", \"novell-dos\", \"opendos\", \"batch-11-dos-11\", \"hp-ux\",\n \"multi-programming-executive\", \"nonstop\", \"os-8\", \"rsts-e\", \"rsx-11\", \"rt-11\", \"tops-10\", \"tenex\",\n \"tops-20\", \"digital-unix\", \"ultrix\", \"vms\", \"waits\", \"ose\", \"towns-os\", \"os-iv\", \"msp\", \"msp-ex\",\n \"real-time-multiprogramming-operating-system\", \"gcos\", \"multics\", \"chromium-os\", \"chrome-os\",\n \"container-optimized-os\", \"android\", \"glinux\", \"fuchsia\", \"integrity\", \"integrity-178b\",\n \"u-velosity\", \"vulcan-o-s\", \"harris-unix\", \"hdos\", \"ht-11\", \"hp-multi-programming-executive\",\n \"nonstop-os\", \"cp-6\", \"harmony-os\", \"irmx\", \"isis\", \"compatible-time-sharing-system\",\n \"gm-os-&-gm-naa-i-o\", \"ibsys\", \"ijmon\", \"share-operating-system\",\n \"university-of-michigan-executive-system\", \"os-360-and-successors\", \"os-360\", \"mft\", \"mft-ii\",\n \"mvt\", \"system-370\", \"os-vs1\", \"multiple-virtual-storage\", \"mvs-xa\", \"mvs-esa\", \"os-390\",\n \"phoenix-mvs\", \"z-os\", \"dos-360-and-successors\", \"bos-360\", \"tos-360\", \"dos-360\", \"dos-vs\",\n \"dos-vse\", \"vse-sp\", \"z-vse\", \"cp-cms\", \"cp-40\", \"cp-67\", \"vm-370\", \"vm-xa\", \"virtual-machine\",\n \"z-vm\", \"acp\", \"tpf\", \"z-tpf\", \"unix-like\", \"aix-370\", \"aix-esa\", \"opensolaris-for-system-z\",\n \"uts\", \"linux-on-ibm-z\", \"mts\", \"tss-360\", \"music-sp\", \"orvyl-and-wylbur\", \"pc-dos\", \"os-2\",\n \"os-2-warp\", \"ecomstation\", \"arcaos\", \"aix\", \"ibm-series-1\", \"edx\", \"rps\", \"cps\", \"serix\",\n \"ibm-1130\", \"dms\", \"ibm-1800\", \"tsx\", \"mpx\", \"ibm-8100\", \"dpcx\", \"dppx\", \"ibm-system-3\",\n \"ibm-system-34\", \"ibm-system-38\", \"cpf\", \"ibm-system-88\", \"stratus-vos\", \"as-400\", \"os-400\",\n \"i5-os\", \"ibm-i\", \"workplace-os\", \"k42\", \"dynix\", \"j\", \"george\", \"executive\", \"tme\", \"icl-vme\",\n \"vme-k\", \"remix-os\", \"lynxos\", \"microc-os-ii\", \"microc-os-iii\", \"xenix\", \"msx-dos\", \"ms-dos\",\n \"dos-v\", \"windows\", \"windows-1.0\", \"windows-2.0\", \"windows-3.0\", \"windows-3.1x\",\n \"windows-for-workgroups-3.1\", \"windows-3.2\", \"windows-for-workgroups-3.11\", \"windows-95\",\n \"windows-98\", \"windows-millennium-edition\", \"windows-nt\", \"windows-nt-3.1\", \"windows-nt-3.5\",\n \"windows-nt-3.51\", \"windows-nt-4.0\", \"windows-2000\", \"windows-xp\", \"windows-server-2003\",\n \"windows-fundamentals-for-legacy-pcs\", \"windows-vista\", \"windows-azure\", \"windows-home-server\",\n \"windows-server-2008\", \"windows-7\", \"windows-phone-7\", \"windows-server-2008-r2\",\n \"windows-home-server-2011\", \"windows-server-2012\", \"windows-8\", \"windows-phone-8\", \"windows-8.1\",\n \"windows-phone-8.1\", \"windows-server-2012-r2\", \"xbox-one-system-software\", \"windows-10\",\n \"windows-10-mobile\", \"windows-server-2016\", \"windows-server-2019\", \"windows-ce\", \"windows-ce-3.0\",\n \"windows-ce-5.0\", \"windows-ce-6.0\", \"windows-embedded-compact-7\", \"windows-embedded-compact-2013\",\n \"windows-mobile\", \"singularity\", \"midori\", \"xbox-360-system-software\", \"azure-sphere\", \"threadx\",\n \"altair-dos\", \"mobilinux\", \"tmx\", \"imos\", \"vrx\", \"es\", \"nextstep\", \"netware\", \"unixware\",\n \"novell-supernos\", \"novell-corsair\", \"novell-expose\", \"open-enterprise-server\", \"rtxc-quadros\",\n \"time-sharing-operating-system\", \"dspnano-rtos\", \"bada\", \"tizen\", \"sco-unix\", \"sco-open-desktop\",\n \"sco-openserver\", \"berkeley-timesharing-system\", \"pikeos\", \"trsdos\", \"color-basic\", \"newdos-80\",\n \"deskmate\", \"edos\", \"ti-rtos-kernel\", \"tron\", \"t-kernel\", \"exec-i\", \"exec-ii\", \"exec-8\", \"vs-9\",\n \"wps\", \"ois\", \"vxworks\", \"z80-rio\", \"zorin-os\", \"lisp-machines--inc.\", \"symbolics\",\n \"texas-instruments\", \"xerox\", \"andos\", \"csi-dos\", \"mk-dos\", \"pilot\", \"perq\", \"elbrus\", \"eos\",\n \"elxsi\", \"mai-basic-four\", \"michigan-terminal-system\", \"es-evm\", \"pc-mos-386\", \"buran\",\n \"sintran-iii\", \"skyos\", \"soda\", \"theos\", \"tsx-32\", \"dx10\", \"aegis\", \"coherent\", \"dc-osx\", \"dnix\",\n \"helios\", \"interactive-unix\", \"irix\", \"meikos\", \"os-9\", \"os-9000\", \"osf-1\", \"openstep\", \"qnx\",\n \"rmx\", \"sinix\", \"solaris\", \"sunos\", \"super-ux\", \"system-v\", \"system-v-at--386\", \"trusted-solaris\",\n \"uniflex\", \"unicos\", \"zenix\", \"minix\", \"bsd\", \"freebsd\", \"dragonflybsd\", \"midnightbsd\", \"ghostbsd\",\n \"trueos\", \"openbsd\", \"bitrig\", \"darwin\", \"gnu\", \"linux\", \"redox\", \"android-x86\",\n \"cray-linux-environment\", \"opensolaris\", \"illumos\", \"openindiana\", \"nexenta-os\", \"smartos\",\n \"rtems\", \"haiku\", \"syllable-desktop\", \"vsta\", \"plurix\", \"tunis\", \"dahliaos\", \"cosmos\", \"freedos\",\n \"genode\", \"ghost-os\", \"its\", \"osfree\", \"osv\", \"phantom-os\", \"reactos\", \"sharpos\", \"templeos\",\n \"visopsys\", \"research-unix\", \"amoeba\", \"croquet\", \"eros\", \"capros\", \"harmony\", \"helenos\", \"house\",\n \"ilios\", \"l4\", \"mach\", \"nemesis\", \"spring\", \"the-multiprogramming-system\", \"thoth\", \"v\", \"verve\",\n \"xinu\", \"86-dos\", \"dr-dos-startrek\", \"dr-dos-winbolt\", \"pts-dos\", \"turbodos\", \"desqview\",\n \"x-windowing\", \"banyan-vines\", \"cambridge-ring\", \"cisco-ios\", \"cisco-nx-os\", \"ctos\", \"data-ontap\",\n \"extremeware\", \"extremexos\", \"fabric-os\", \"junos\", \"network-operating-system\",\n \"novell-open-enterprise-server\", \"plan-9\", \"blis-cobol\", \"bluebottle\", \"bs1000\", \"bs2000\",\n \"bs3000\", \"flex9\", \"gem\", \"geos\", \"javaos\", \"jnode\", \"jx\", \"kernal\", \"merlin\", \"morphos\",\n \"fujitsu\", \"oberon-(operating-system)\", \"osd-xc\", \"pick\", \"primos\", \"sinclair-qdos\", \"ssb-dos\",\n \"symobi\", \"tripos\", \"ucsd-p-system\", \"vos\", \"vos3\", \"vm2000\", \"visi-on\", \"vps-vm\", \"aros\",\n \"atheos\", \"baremetal\", \"dexos\", \"emutos\", \"lse-os\", \"menuetos\", \"kolibrios\", \"toaruos\", \"ponyos\",\n \"serenityos\", \"dip-dos\", \"embedded-linux\", \"replicant\", \"lineageos\",\n \"list-of-custom-android-distributions\", \"firefox-os\", \"angstrom-distribution\", \"familiar-linux\",\n \"maemo\", \"openzaurus\", \"webos\", \"access-linux-platform\", \"openmoko-linux\", \"ophone\", \"meego\",\n \"moblin\", \"motomagx\", \"qt-extended\", \"sailfish-os\", \"ubuntu-touch\", \"postmarketos\", \"magic-cap\",\n \"palm-os\", \"pen-geos\", \"penpoint-os\", \"pvos\", \"symbian-os\", \"epoc\", \"pocket-pc\", \"windows-phone\",\n \"ipodlinux\", \"iriver-clix\", \"rockbox\", \"blackberry-os\", \"symbian-platform\", \"blackberry-10\",\n \"catos\", \"ios-xr\", \"lancom-systems\", \"openwrt\", \"dd-wrt\", \"lede\", \"gargoyle\", \"librecmc\",\n \"zeroshell\", \"rtos\", \"m0n0wall\", \"opnsense\", \"pfsense\", \"apache-mynewt\", \"chibios-rt\",\n \"erika-enterprise\", \"ecos\", \"nucleus-rtos\", \"nuttx\", \"ncos\", \"freertos--openrtos-and-safertos\",\n \"openembedded\", \"psos\", \"rex-os\", \"riot\", \"rom-dos\", \"tinyos\", \"rt-thread\", \"windows-iot\",\n \"windows-embedded\", \"wombat-os\", \"zephyr\", \"brickos\", \"lejos\", \"cambridge-cap-computer\",\n \"flex-machine\", \"hydra\", \"keykos\"] # generated from util/platform_list.rb\n platform_list_col = array(*[lit(x) for x in platform_list])\n\n df = spark.read.parquet(\"/user/***REMOVED***/StackOverflow/PostHistory.parquet\") \\\n .select([\"_PostId\", \"_Text\", '_PostHistoryTypeId']) \\\n .filter(col(\"_PostHistoryTypeId\") == 3) \\\n .withColumn(\"_Tags\", expr(\"substring(_Text, 2, length(_Text) - 2)\")) \\\n .withColumn(\"_Tags\", split(col(\"_Tags\"), \"><\")) \\\n .withColumn(\"#tags\", when(size(\"_Tags\") < 0, 0).otherwise(size(\"_Tags\"))) \\\n .withColumn(\"contains_language_tag\", size(array_intersect(\"_Tags\", language_list_col)) > 0) \\\n .withColumn(\"contains_platform_tag\", size(array_intersect(\"_Tags\", platform_list_col)) > 0) \\\n .drop(\"_Tags\", \"_PostHistoryTypeId\", \"_Text\") \\\n .withColumnRenamed('_PostId', '_Id')\n\n return df\n\n\nif __name__ == \"__main__\":\n spark = SparkSession.builder.getOrCreate()\n tag_info_df(spark).show()\n","sub_path":"features/tag_info.py","file_name":"tag_info.py","file_ext":"py","file_size_in_byte":14141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"22230612","text":"import yagmail, pymysql\nfrom Db_connector import Db_connector\n\ndef send_email_update():\n\tconn = Db_connector(\"technical_analysis\")\n\tcursor = conn.get_db_cursor()\n\tcursor.execute(\"SELECT * FROM `users` WHERE `user_name`='Andreas'\")\n\temails = []\n\tn_stocks = []\n\tstocks = []\n\timages = []\n\tfor row in cursor:\n\t\temails.append(row['user_email'])\n\t\tstocks.append(row['user_owned_stocks'])\n\tfor email, temp_stocks in zip(emails, stocks):\n\t\ttemp_stocks = temp_stocks.split(',')\n\t\tfor temp_stock in temp_stocks:\n\t\t\timages.append('fig/' + temp_stock.replace(' ', '_') + '.png')\n\t\tyag = yagmail.SMTP('dintekniskaanalys@gmail.com', '447VG#pd')\n\t\tto = email\n\t\tyag.send(to, 'portfolio update', images)\n\tconn.close()\n\ndef main():\n\tsend_email_update()\n","sub_path":"send_portfolio_update.py","file_name":"send_portfolio_update.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"552709169","text":"import tkinter as tk\r\n\r\n#WINDOW PROPERTIES\r\nGUI = tk.Tk()\r\nGUI.title(\"Payroll Calculator\")\r\nGUI.minsize('305','110')\r\nGUI.maxsize('305','110')\r\n\r\nhoursWorked = tk.StringVar()\r\npayRate = tk.StringVar()\r\n\r\n#TAXES\r\nstates_dict = {'Alabama' : 0.035, 'Arizona' : 0.03565, 'Alaska' : 1, 'Arkansas' : 0.039, 'California' : 0.0715,\r\n 'Colorado' : 1, 'Connecticut' : 0.04995, 'Delaware' : 0.044, 'Florida' : 1, 'Georgia' : 0.035, 'Hawaii' : 0.04825,\r\n 'Idaho' : 4.5, 'Illinois' : 1, 'Indiana' : 1, 'Iowa' : 0.0467, 'Kansas' : 0.0405, 'Kentucky' : 0.04,\r\n 'Louisiana' : 0.04, 'Maine' : 0.06475, 'Maryland' : 0.03875, 'Massachusetts' : 1, 'Michigan' : 1, 'Minnesota' : 0.076,\r\n 'Mississippi' : 0.04, 'Missouri' : 0.0375, 'Montana' : 0.0395, 'Nebraska' : 0.0465, 'Nevada' : 1, 'New Hampshire' : 1,\r\n 'New Jersey' : 0.05185, 'New Mexico' : 0.033, 'New York' : 0.0641, 'North Carolina' : 1, 'North Dakota' : 0.02, 'Ohio' : 0.0275, 'Oklahoma' : 0.0275,\r\n 'Oregon' : 0.0745, 'Pennsylvania' : 1, 'Rhode Island' : 0.0487, 'South Carolina' : 0.035, 'South Dakota' : 1, 'Tennessee' : 1, 'Texas' : 1, 'Utah' : 1,\r\n 'Vermont' : 0.0625, 'Washington' : 1, 'West Virginia' : 0.0475, 'Wisconsin' : 0.05825, 'Wyoming' : 1, 'District of Columbia' : 0.06475}\r\n\r\ndef calculate():\r\n tax = states_dict.get(opt.get())\r\n if not tax:\r\n result.set(\"Invalid Input\")\r\n else:\r\n salary = (float(hoursWorked.get()) * float(payRate.get())) - (float(payRate.get()) * tax)\r\n result.set(f'Total Pay: ${salary:.2f}')\r\n\r\nresult = tk.StringVar()\r\n\r\n#ENTRY\r\ntk.Label(GUI, text='Pay Rate:', font=\"110\").grid(row=0)\r\ntk.Label(GUI, text='Hours Worked:', font=\"110\").grid(row=1)\r\n\r\ne1 = tk.Entry(GUI, textvariable = payRate)\r\ne2 = tk.Entry(GUI, textvariable = hoursWorked)\r\ne1.grid(row = 0, column = 1, sticky = tk.W)\r\ne2.grid(row = 1, column = 1, sticky = tk.W)\r\n\r\n#OPTION MENU\r\nopt = tk.StringVar()\r\nopt.set(\"Choose a state\")\r\n\r\noption = tk.OptionMenu(GUI, opt, *states_dict).grid(row=2, column=0)\r\n\r\nframe = tk.Frame(GUI)\r\nframe.grid()\r\n\r\nresults = tk.Label(GUI, textvariable=result)\r\nresults.grid(row=3, column=1)\r\n\r\nbutton = tk.Button(frame, text='Calculate', fg='red', command=calculate)\r\nbutton.grid(row=1, column=0)\r\n\r\n#SET DEFAULTS\r\nhoursWorked.set(0)\r\npayRate.set(0)\r\n\r\n\r\n#EVENT LOOP\r\nGUI.mainloop()\r\n","sub_path":"PayrollCalculator.py","file_name":"PayrollCalculator.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"427488036","text":"from functools import wraps\r\nfrom time import time\r\n\r\nimport pandas as pd\r\nfrom flask import Flask\r\nfrom flask import request\r\nfrom flask_restplus import Resource, Api, abort\r\nfrom flask_restplus import fields\r\nfrom flask_restplus import inputs\r\nfrom flask_restplus import reqparse\r\nfrom itsdangerous import SignatureExpired, JSONWebSignatureSerializer, BadSignature\r\n\r\ntest = 'neo'\r\nl = {}\r\nlist = [\"steven\", \"neo\", \"tracy\", \"chris\"]\r\n\r\n\r\n\r\nclass AuthenticationToken:\r\n def __init__(self, secret_key, expires_in):\r\n self.secret_key = secret_key\r\n self.expires_in = expires_in\r\n self.serializer = JSONWebSignatureSerializer(secret_key)\r\n\r\n def generate_token(self, username):\r\n info = {\r\n 'username': username,\r\n 'creation_time': time()\r\n }\r\n\r\n token = self.serializer.dumps(info)\r\n return token.decode()\r\n\r\n def validate_token(self, token):\r\n info = self.serializer.loads(token.encode())\r\n\r\n if time() - info['creation_time'] > self.expires_in:\r\n raise SignatureExpired(\"The Token has been expired; get a new token\")\r\n\r\n return info['username']\r\n\r\n\r\nSECRET_KEY = \"A SECRET KEY; USUALLY A VERY LONG RANDOM STRING\"\r\nexpires_in = 600\r\nauth = AuthenticationToken(SECRET_KEY, expires_in)\r\n\r\napp = Flask(__name__)\r\napi = Api(app, security='API-KEY',\r\n default=\"Books\", # Default namespace\r\n title=\"Book Dataset\", # Documentation Title\r\n description=\"This is just a simple example to show how publish data as a service.\") # Documentation Description\r\n\r\n\r\ndef requires_auth(f):\r\n @wraps(f)\r\n def decorated(*args, **kwargs):\r\n # token = request.headers.get('AUTH-TOKEN')\r\n # print(token)\r\n # request.headers.insert(\"AUTH_TOKEN\",)\r\n token = test\r\n\r\n print(\"aaa\", token)\r\n if not token:\r\n abort(401, 'Authentication token is missing')\r\n if token not in l:\r\n abort(401, 'Authentication failed')\r\n\r\n try:\r\n user = auth.validate_token(l[token])\r\n print(token)\r\n print(request.headers)\r\n except SignatureExpired as e:\r\n print(token)\r\n abort(401, e.message)\r\n except BadSignature as e:\r\n print(token)\r\n abort(401, e.message)\r\n\r\n return f(*args, **kwargs)\r\n\r\n return decorated\r\n\r\n\r\nparser = reqparse.RequestParser()\r\ncredential_model = api.model('credential', {\r\n 'username': fields.String\r\n})\r\n\r\ncredential_parser = reqparse.RequestParser()\r\ncredential_parser.add_argument('username', type=str)\r\n\r\n\r\n@api.route('/token')\r\nclass Token(Resource):\r\n @api.response(200, 'Successful')\r\n @api.doc(description=\"Generates a authentication token\")\r\n @api.expect(credential_parser, validate=True)\r\n def get(self):\r\n args = credential_parser.parse_args()\r\n\r\n username = args.get('username')\r\n global test\r\n test = username\r\n # list.append(username)\r\n # password = args.get('password')\r\n\r\n if username in list:\r\n\r\n a = auth.generate_token(username)\r\n l[username] = a\r\n print(l)\r\n print(request.headers)\r\n return {\"token\": auth.generate_token(username)},username\r\n\r\n return {\"message\": \"authorization has been refused for those credentials.\"}, 401\r\n","sub_path":"frontend/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":3374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"519795832","text":"# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\nfrom bugbot import utils\nfrom bugbot.bzcleaner import BzCleaner\n\n\nclass UnderestimatedSeverity(BzCleaner):\n def __init__(self):\n super(UnderestimatedSeverity, self).__init__()\n self.nweeks = self.get_config(\"weeks_lookup\")\n self.ndups = self.get_config(\"number_dups\")\n self.votes = self.get_config(\"number_votes\")\n self.cc = self.get_config(\"number_cc\")\n self.see_also = self.get_config(\"number_see_also\")\n\n self.extra_ni = {}\n\n def description(self):\n return \"Bugs with underestimated severity for the last {} weeks\".format(\n self.nweeks\n )\n\n def has_needinfo(self):\n return True\n\n def get_mail_to_auto_ni(self, bug):\n for field in [\"assigned_to\", \"triage_owner\"]:\n person = bug.get(field, \"\")\n if person and not utils.is_no_assignee(person):\n return {\"mail\": person, \"nickname\": bug[f\"{field}_detail\"][\"nick\"]}\n\n return None\n\n def get_extra_for_needinfo_template(self):\n return self.extra_ni\n\n def columns(self):\n return [\n \"id\",\n \"summary\",\n \"creation\",\n \"last_change\",\n \"severity\",\n \"dups_count\",\n \"votes\",\n \"cc_count\",\n \"see_also_count\",\n ]\n\n def get_extra_for_template(self):\n return {\n \"dups_threshold\": self.ndups,\n \"votes_threshold\": self.votes,\n \"cc_threshold\": self.cc,\n \"see_also_threshold\": self.see_also,\n }\n\n def handle_bug(self, bug, data):\n bugid = str(bug[\"id\"])\n cc_count = len(bug[\"cc\"])\n dups_count = len(bug[\"duplicates\"])\n votes_count = bug[\"votes\"]\n see_also_count = len(bug[\"see_also\"])\n\n data[bugid] = {\n \"creation\": utils.get_human_lag(bug[\"creation_time\"]),\n \"last_change\": utils.get_human_lag(bug[\"last_change_time\"]),\n \"severity\": bug[\"severity\"],\n \"dups_count\": dups_count,\n \"votes\": votes_count,\n \"cc_count\": cc_count,\n \"see_also_count\": see_also_count,\n }\n\n factors = []\n if dups_count >= self.ndups:\n factors.append(f\"{dups_count} duplicates\")\n if votes_count >= self.votes:\n factors.append(f\"{votes_count} votes\")\n if cc_count >= self.cc:\n factors.append(f\"{cc_count} CCs\")\n if see_also_count >= self.see_also:\n factors.append(f\"{see_also_count} See Also bugs\")\n\n self.extra_ni[bugid] = {\n \"severity\": bug[\"severity\"],\n \"factors\": utils.english_list(factors),\n }\n\n return bug\n\n def get_bz_params(self, date):\n fields = [\n \"assigned_to\",\n \"triage_owner\",\n \"creation_time\",\n \"last_change_time\",\n \"severity\",\n \"votes\",\n \"cc\",\n \"duplicates\",\n \"see_also\",\n ]\n\n params = {\n \"include_fields\": fields,\n \"resolution\": \"---\",\n \"bug_type\": \"defect\",\n \"bug_severity\": [\"S3\", \"S4\"],\n \"f1\": \"keywords\",\n \"o1\": \"nowords\",\n \"v1\": [\"meta\", \"intermittent\"],\n \"f2\": \"days_elapsed\",\n \"o2\": \"lessthan\",\n \"v2\": self.nweeks * 7,\n \"j3\": \"OR\",\n \"f3\": \"OP\",\n \"f4\": \"dupe_count\",\n \"o4\": \"greaterthaneq\",\n \"v4\": self.ndups,\n \"f5\": \"votes\",\n \"o5\": \"greaterthaneq\",\n \"v5\": self.votes,\n \"f6\": \"cc_count\",\n \"o6\": \"greaterthaneq\",\n \"v6\": self.cc,\n \"f7\": \"see_also_count\",\n \"o7\": \"greaterthaneq\",\n \"v7\": self.see_also,\n \"f8\": \"CP\",\n \"n15\": 1,\n \"f15\": \"longdesc\",\n \"o15\": \"casesubstring\",\n \"v15\": \"could you consider increasing the bug severity?\",\n }\n\n return params\n\n\nif __name__ == \"__main__\":\n UnderestimatedSeverity().run()\n","sub_path":"bugbot/rules/severity_underestimated.py","file_name":"severity_underestimated.py","file_ext":"py","file_size_in_byte":4269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"163821985","text":"from slamon.afm.tables import Agent, AgentCapability, Task\nfrom slamon.afm.afm_app import app\nfrom slamon.afm.database import create_session\nfrom slamon.afm.settings import Settings\nfrom slamon.slamon_logging import getSLAMonLogger\nfrom datetime import datetime, timedelta\nfrom bottle import request, HTTPError\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom sqlalchemy import and_\nfrom dateutil import tz\nimport jsonschema\nimport json\n\nlogger = getSLAMonLogger(__name__)\n\ntask_request_schema = {\n 'type': 'object',\n 'properties': {\n 'protocol': {\n 'type': 'integer',\n 'minimum': 1\n },\n 'agent_id': {\n 'type': 'string',\n 'pattern': '^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$'\n },\n 'agent_name': {'type': 'string'},\n 'agent_location': {\n 'type': 'object',\n 'properties': {\n 'country': {\n 'type': 'string',\n 'minLength': 2,\n 'maxLength': 2\n },\n 'region': {\n 'type': 'string',\n 'minLength': 2,\n 'maxLength': 4\n },\n 'latitude': {\n 'type': 'number'\n },\n 'longitude': {\n 'type': 'number'\n }\n },\n 'required': ['country', 'region'],\n 'additionalProperties': False\n },\n 'agent_capabilities': {\n 'type': 'object',\n 'patternProperties': {\n '^.+$': {\n 'type': 'object',\n 'properties': {\n 'version': {'type': 'integer'}\n }\n }\n }\n },\n 'agent_time': {\n 'type': 'string'\n },\n 'max_tasks': {\n 'type': 'integer'\n }\n },\n 'required': ['protocol', 'agent_id', 'agent_name', 'agent_time', 'agent_capabilities', 'max_tasks'],\n 'additionalProperties': False\n}\n\n\n@app.post('/tasks')\n@app.post('/tasks/')\ndef request_tasks():\n data = request.json\n\n if data is None:\n raise HTTPError(400)\n\n try:\n jsonschema.validate(data, task_request_schema)\n except jsonschema.ValidationError:\n raise HTTPError(400)\n\n protocol = int(data['protocol'])\n agent_uuid = str(data['agent_id'])\n agent_name = str(data['agent_name'])\n agent_time = data['agent_time']\n agent_capabilities = data['agent_capabilities']\n max_tasks = int(data['max_tasks'])\n agent_location = data['agent_location'] if 'agent_location' in data else None\n\n # Only protocol 1 supported for now\n if protocol != 1:\n raise HTTPError(400)\n\n try:\n session = create_session()\n except:\n logger.error(\"Failed to create database session for task request\")\n raise HTTPError(500)\n\n try:\n query = session.query(Agent)\n agent = query.filter(Agent.uuid == agent_uuid).one()\n\n session.query(AgentCapability).filter(AgentCapability.agent_uuid == agent.uuid).delete()\n except NoResultFound:\n agent = Agent(uuid=agent_uuid, name=agent_name)\n session.add(agent)\n\n for agent_capability, agent_capability_info in agent_capabilities.items():\n capability = AgentCapability(type=agent_capability,\n version=int(agent_capability_info['version']),\n agent=agent)\n session.add(capability)\n\n # Find all non-claimed tasks that the agent is able to handle and assign them to the agent\n query = session.query(AgentCapability, Task).filter(Task.assigned_agent_uuid.is_(None)).\\\n filter(AgentCapability.agent_uuid == agent.uuid).\\\n filter(and_(AgentCapability.type == Task.type, AgentCapability.version == Task.version))\n\n tasks = []\n\n # Assign available tasks to the agent and mark them as being in process\n for _, task in query[0:max_tasks]:\n task.assigned_agent_uuid = agent.uuid\n task.claimed = datetime.utcnow()\n tasks.append({\n 'task_id': task.uuid,\n 'task_type': task.type,\n 'task_version': task.version,\n 'task_data': json.loads(task.data)\n })\n\n agent.last_seen = datetime.utcnow()\n try:\n session.commit()\n except Exception:\n session.rollback()\n logger.error(\"Failed to commit database changes for task request\")\n raise HTTPError(500)\n finally:\n session.close()\n\n logger.info(\"Agent requested tasks - Agent's name and uuid: {}, {} - Agent was given following tasks: {}\"\n .format(agent_name, agent_uuid, tasks))\n\n return {\n \"tasks\": tasks,\n \"return_time\": (datetime.now(tz.tzlocal()) + timedelta(0, Settings.agent_return_time)).isoformat()\n }\n\n\ntask_response_schema = {\n 'type': 'object',\n 'oneOf': [\n {\n 'type': 'object',\n 'properties': {\n 'protocol': {\n 'type': 'integer'\n },\n 'task_id': {\n 'type': 'string',\n 'pattern': '^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$'\n },\n 'task_data': {\n 'type': 'object'\n }\n },\n 'additionalProperties': False,\n 'required': ['protocol', 'task_id', 'task_data']\n },\n {\n 'type': 'object',\n 'properties': {\n 'protocol': {\n 'type': 'integer'\n },\n 'task_id': {\n 'type': 'string',\n 'pattern': '^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$'\n },\n 'task_error': {\n 'type': 'string'\n }\n },\n 'additionalProperties': False,\n 'required': ['protocol', 'task_id', 'task_error']\n }\n ]\n}\n\n\n@app.post('/tasks/response')\n@app.post('/tasks/response/')\ndef post_tasks():\n data = request.json\n\n if data is None:\n logger.error(\"No JSON content in task response request!\")\n raise HTTPError(400)\n\n try:\n jsonschema.validate(data, task_response_schema)\n except jsonschema.ValidationError as e:\n logger.error(\"Invalid JSON in task reponse: {0}\".format(e))\n raise HTTPError(400)\n\n protocol = int(data['protocol'])\n task_id = str(data['task_id'])\n\n # Only protocol 1 supported for now\n if protocol != 1:\n logger.error(\"Invalid protocol in task response: {0}\".format(protocol))\n raise HTTPError(400)\n\n try:\n session = create_session()\n except:\n logger.error(\"Failed to create database session for task result POST\")\n raise HTTPError(500)\n\n try:\n task = session.query(Task).filter(Task.uuid == str(task_id)).one()\n\n if task.claimed is None or (task.completed is not None or task.failed is not None):\n logger.error(\"Incomplete task posted!\")\n session.close()\n raise HTTPError(400)\n\n result = \"\"\n if 'task_data' in data:\n task.result_data = json.dumps(data['task_data'])\n task.completed = datetime.utcnow()\n result = json.dumps(task.result_data)\n elif 'task_error' in data:\n task.error = data['task_error']\n task.failed = datetime.utcnow()\n result = task.error\n\n session.add(task)\n except NoResultFound:\n logger.error(\"No matching task in for task response!\")\n session.close()\n raise HTTPError(400)\n\n try:\n session.commit()\n except Exception:\n session.rollback()\n logger.error(\"Failed to commit database changes for task result POST\")\n raise HTTPError(500)\n finally:\n session.close()\n\n logger.info(\"An agent returned task with results - uuid: {}, end results: {}\".format(task_id, result))\n","sub_path":"slamon/afm/routes/agent_routes.py","file_name":"agent_routes.py","file_ext":"py","file_size_in_byte":8139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"215964174","text":"from flask import Flask, render_template, redirect, request, abort\nfrom flask_login import LoginManager, login_user, logout_user, current_user, login_required\nfrom data import db_session, users, login_class, registration, redefine_roles, news, \\\n translater, forum_db, answer_on_question, ask_question, settings, settings_db, \\\n edit_profile_form, api_func\nfrom random import choice\nimport sys\nfrom flask_restful import abort, Api\nfrom werkzeug.security import generate_password_hash, check_password_hash\nfrom flask_socketio import SocketIO, send\nimport feedparser, json, os, datetime\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'matesearch_secretkey' # Секретный ключ\nsocketio = SocketIO(app)\nlogin_manager = LoginManager()\napi = Api(app)\nlogin_manager.init_app(app)\nsys.stdout.encoding # 'UTF-8'\n\n\n@login_manager.user_loader\ndef load_user(user_id):\n sessions = db_session.create_session()\n return sessions.query(users.User).get(user_id)\n\n\n@app.errorhandler(404) # функция ошибки\ndef not_found(error):\n try:\n sessions = db_session.create_session()\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n return render_template(\"not_found.html\", colors=colors, main_color=main_color,\n main_lang=main_lang)\n\n\n@app.route(\"/\") # Главная страница\ndef index():\n news_theft()\n check_last_page()\n counter_1 = 6\n counter_2 = 0\n next_page = 2\n back_page = 1\n sessions = db_session.create_session()\n news_on_page = sessions.query(news.News).order_by(news.News.created_date.desc())\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n try:\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n return render_template(\"index.html\", colors=colors, news=news_on_page, counter_1=counter_1,\n counter_2=counter_2, next_page=next_page, back_page=back_page,\n main_color=main_color, main_lang=main_lang)\n\n\n@app.route(\"/page/\") # Страницы новостей\ndef new_page(num):\n news_theft()\n check_last_page()\n counter_1 = num * 5 + 1\n counter_2 = counter_1 - 6\n next_page = num + 1\n back_page = num - 1\n if num == 1:\n back_page = 1\n if num == 6:\n next_page = 6\n sessions = db_session.create_session()\n news_on_page = sessions.query(news.News).order_by(news.News.created_date.desc())\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n try:\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n return render_template(\"index.html\", colors=colors, news=news_on_page, counter_1=counter_1,\n counter_2=counter_2, next_page=next_page, back_page=back_page,\n main_color=main_color, main_lang=main_lang)\n\n\n@app.route('/logout', methods=[\"GET\", \"POST\"]) # Выйти из аккаунта\ndef logout():\n with open(\"static/json/chaty.json\") as file:\n data = json.load(file)\n for key in data[\"chats\"].keys():\n if str(current_user.id) in key:\n count = 0\n chats = data[\"chats\"]\n for i in range(1, len(data[\"chats\"][key])):\n time1 = (chats[key][i - count][0][0] * 365 + chats[key][i - count][0][1] * 30 +\n chats[key][i - count][0][2]) * 3600 * 24 + chats[key][i - count][0][3] * \\\n 3600 + chats[key][i - count][0][4] * 60 + chats[key][i - count][0][5]\n time = datetime.datetime.now()\n time2 = (time.year * 365 + time.month * 30 + time.day) * 3600 * 24 + time.hour * \\\n 3600 + time.minute * 60 + time.second\n if time2 - time1 > 3600 * 24:\n del data[\"chats\"][key][i - count]\n count += 1\n with open(\"static/json/chaty.json\", \"w\") as file:\n json.dump(data, file)\n logout_user()\n return redirect('/')\n\n\n@app.route('/login', methods=['GET', 'POST']) # Войти в аккаунт\ndef login():\n check_last_page()\n form = login_class.LoginForm()\n sessions = db_session.create_session()\n try:\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n if form.validate_on_submit():\n user = sessions.query(users.User).filter(users.User.email == form.email.data).first()\n password = generate_password_hash(form.password.data)\n if user and check_password_hash(password, form.password.data):\n login_user(user, remember=form.remember_me.data)\n return redirect('/')\n return render_template('login.html', message='Invalid username or password', colors=colors,\n form=form, main_color=main_color, main_lang=main_lang)\n return render_template('login.html', title='Авторизация', colors=colors, form=form,\n main_color=main_color, main_lang=main_lang, message=\"\")\n\n\n@app.route('/register', methods=['GET', 'POST']) # Страница регистрации\ndef reqister():\n check_last_page()\n form = registration.RegisterForm()\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n sessions = db_session.create_session()\n try:\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n if form.validate_on_submit():\n if form.password.data != form.password_again.data:\n return render_template('register.html', title='Регистрация', colors=colors,\n form=form, main_color=main_color,\n message=\"Passwords don't match\", main_lang=main_lang)\n if sessions.query(users.User).filter(users.User.email == form.email.data).first():\n return render_template('register.html', title='Регистрация',\n form=form, main_color=main_color, colors=colors,\n message=\"This user already exists\", main_lang=main_lang)\n if len(form.name.data) > 16 or len(form.name.data) < 3:\n return render_template('register.html', title='Регистрация',\n form=form, main_color=main_color, colors=colors,\n message=\"This login too long or too short\", main_lang=main_lang)\n user = users.User(name=form.name.data,\n email=form.email.data,\n password=form.password.data,\n role=\"user\")\n user.set_password(form.password.data)\n sessions.add(user)\n sessions.commit()\n settings = settings_db.Settings_db(user_id=user.id,\n language='en',\n theme='light')\n sessions.add(settings)\n sessions.commit()\n return redirect('/login')\n return render_template('register.html', colors=colors, title='Registration', form=form,\n main_color=main_color, main_lang=main_lang, message=\"\")\n\n\n@app.route(\"/searchmates//\") # Страница поиска тиммейтов\n@login_required\ndef add_to_search(game, types):\n check_last_page()\n if not \"/searchmates\" in current_user.last_page:\n session = db_session.create_session()\n current_user.last_page = f\"/searchmates/{game}/{types}\"\n session.merge(current_user)\n session.commit()\n with open(\"static/json/searching_mates.json\") as file:\n data = json.load(file)\n if current_user.id not in data[game][types]:\n data[game][types] += [current_user.id]\n with open(\"static/json/searching_mates.json\", \"w\") as file:\n json.dump(data, file)\n elif (\"/searchmates\" in current_user.last_page and\n (game != current_user.last_page.split(\"/\")[1] or\n types != current_user.last_page.split(\"/\")[2])):\n with open(\"static/json/searching_mates.json\") as file:\n data = json.load(file)\n games, typess = current_user.last_page.split(\"/\")[2], current_user.last_page.split(\"/\")[3]\n if current_user.id in data[games][typess]:\n del data[games][typess][data[games][typess].index(current_user.id)]\n with open(\"static/json/searching_mates.json\", \"w\") as file:\n json.dump(data, file)\n session = db_session.create_session()\n current_user.last_page = f\"/searchmates/{game}/{types}\"\n session.merge(current_user)\n session.commit()\n with open(\"static/json/searching_mates.json\") as file:\n data = json.load(file)\n if current_user.id not in data[game][types]:\n data[game][types] += [current_user.id]\n with open(\"static/json/searching_mates.json\", \"w\") as file:\n json.dump(data, file)\n mates_id = data[game][types]\n mates = []\n session = db_session.create_session()\n for mate_id in mates_id:\n mate = session.query(users.User).get(mate_id)\n mates.append([mate.name, mate.reputation, mate.avatar, mate.id, 0])\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n sessions = db_session.create_session()\n try:\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n return render_template(\"search_table.html\", colors=colors, mates=mates,\n main_color=main_color, main_lang=main_lang, name_game=game,\n type_game=types)\n\n\n@socketio.on(\"message\") # Сообщения\ndef Message(message):\n with open(\"static/json/chaty.json\") as file:\n data = json.load(file)\n time = datetime.datetime.now()\n message, url = map(str, message.split(\"4a96a813f286fb923b0b4ead19e0052c3ddc1c36\"))\n message = message.encode('l1').decode()\n data[\"chats\"][url] += [[(time.year, time.month, time.day, time.hour, time.minute,\n time.second), current_user.name, message]]\n with open(\"static/json/chaty.json\", \"w\") as file:\n json.dump(data, file)\n send(message + \"_<}]:;,.!$?$228?!.,;:[{>_\" + current_user.name, broadcast=True)\n\n\n@app.route(\"/chats//\", methods=[\"GET\", \"POST\"]) # Чат\n@login_required\ndef chats(first_id, second_id):\n check_last_page()\n # chats: {\n # url:\n # [\n # [\"data\", \"user\", \"text\"]\n # ]\n # }\n sessions = db_session.create_session()\n try:\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n if current_user.id != first_id and current_user.id != second_id:\n if main_lang == \"en\":\n mess = \"You cann't wathing this chat\"\n else:\n mess = \"Вы не можете следить за этим чатом\"\n return mess\n first_url = str(first_id) + \"_\" + str(second_id)\n second_url = str(second_id) + \"_\" + str(first_id)\n url = \"\"\n with open(\"static/json/chaty.json\", \"r\", encoding=\"utf-8\") as file:\n data = json.load(file)\n if first_url in data[\"chats\"].keys():\n url = first_url\n elif second_url in data[\"chats\"].keys():\n url = second_url\n else:\n url = first_url\n if not url in data[\"chats\"].keys():\n time = datetime.datetime.now()\n data[\"chats\"].update([(url, [[time.year, time.month, time.day, time.hour, time.minute,\n time.second, {first_id: 0, second_id: 0}]])])\n with open(\"static/json/chaty.json\", \"w\", encoding='utf-8') as file:\n json.dump(data, file)\n with open(\"static/json/chaty.json\") as file:\n data = json.load(file)\n chat = data[\"chats\"][url][1:]\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n return render_template(\"chats.html\", colors=colors, chat=chat, url=url, main_color=main_color,\n main_lang=main_lang)\n\n\n# Чаты во время поиска\n@app.route(\"/chats_in_search//\", methods=[\"GET\", \"POST\"])\ndef chats_in_search(game, type):\n sessions = db_session.create_session()\n with open(\"static/json/chaty.json\") as file:\n data = json.load(file)\n chat_list = []\n for key in data[\"chats\"].keys():\n if str(current_user.id) in key:\n id_list = key.split(\"_\")\n del id_list[id_list.index(str(current_user.id))]\n user = sessions.query(users.User).get(id_list[0])\n chat_list += [user]\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n try:\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n return render_template(\"chat_in_search.html\", colors=colors, main_color=main_color,\n chat_list=chat_list, main_lang=main_lang, name_game=game, type_game=type)\n\n\n@app.route(\"/chat\") # Все чаты\n@login_required\ndef chat():\n sessions = db_session.create_session()\n with open(\"static/json/chaty.json\") as file:\n data = json.load(file)\n chat_list = []\n for key in data[\"chats\"].keys():\n if str(current_user.id) in key:\n id_list = key.split(\"_\")\n del id_list[id_list.index(str(current_user.id))]\n user = sessions.query(users.User).get(id_list[0])\n chat_list += [[user, data[\"chats\"][key][-1][-2], data[\"chats\"][key][-1][-1]]]\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n try:\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n return render_template(\"chat_list.html\", colors=colors, main_color=main_color,\n chat_list=chat_list, main_lang=main_lang)\n\n\ndef check_last_page(): # Проверка, что вы ушли со страницы поиска, для остановки поиска игроков\n if current_user.is_authenticated and \"/searchmates\" in current_user.last_page:\n with open(\"static/json/searching_mates.json\") as file:\n data = json.load(file)\n game, types = current_user.last_page.split(\"/\")[2], current_user.last_page.split(\"/\")[3]\n if current_user.id in data[game][types]:\n del data[game][types][data[game][types].index(current_user.id)]\n with open(\"static/json/searching_mates.json\", \"w\") as file:\n json.dump(data, file)\n session = db_session.create_session()\n current_user.last_page = \"/\"\n session.merge(current_user)\n session.commit()\n\n\ndef news_theft(): # Обновление новостей\n session = db_session.create_session()\n NewsFeed = feedparser.parse(\"https://news.yandex.ru/games.rss\")\n nowosty = NewsFeed[\"entries\"]\n for new in nowosty:\n title = new[\"title\"]\n content = new[\"summary\"]\n old_news = session.query(news.News)\n coincidence = False\n for old_new in old_news:\n if old_new.rus_content == content:\n coincidence = True\n if not coincidence:\n new_new = news.News(\n title=translater.translate(title),\n rus_title=title,\n rus_content=content,\n content=translater.translate(content)\n )\n session.add(new_new)\n session.commit()\n nowosty = session.query(news.News).order_by(news.News.created_date.desc())\n count = 0\n for new in nowosty:\n if count > 50:\n session.delete(new)\n count += 1\n session.commit()\n\n\n@app.route(\"/searchmates/\") # Страница для выбора типа игры\ndef searchmates(game):\n check_last_page()\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n sessions = db_session.create_session()\n try:\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n return render_template('search.html', colors=colors, game=game, main_color=main_color,\n main_lang=main_lang)\n\n\n@app.route(\"/profile/\") # Профиль\n@login_required\ndef user_info(id):\n check_last_page()\n sessions = db_session.create_session()\n user = sessions.query(users.User).get(id)\n if user:\n user_id_str = str(user.id)\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n ocenka_reputacii = False\n dobavlenie_v_druzya = False\n udalenie_iz_druzey = False\n with open(\"static/json/chaty.json\") as file:\n data = json.load(file)\n chats = data[\"chats\"]\n url1 = str(current_user.id) + \"_\" + str(id)\n url2 = str(id) + \"_\" + str(current_user.id)\n url = \"\"\n if url1 in chats.keys():\n url = url1\n elif url2 in chats.keys():\n url = url2\n if (url != \"\" and str(current_user.id) not in user.appraisers and\n str(current_user.id) + \";1\" not in user.notifications):\n time1 = (chats[url][0][0] * 365 + chats[url][0][1] * 30 + chats[url][0][2]) * \\\n 3600 * 24 + chats[url][0][3] * 3600 + chats[url][0][4] * 60 + chats[url][0][5]\n time = datetime.datetime.now()\n time2 = (time.year * 365 + time.month * 30 + time.day) * 3600 * 24 + time.hour * \\\n 3600 + time.minute * 60 + time.second\n if time2 - time1 > 3600:\n ocenka_reputacii = True\n if (str(current_user.id) + \";0;\" + str(user.id) not in user.notifications and\n str(current_user.id) not in user.friends):\n dobavlenie_v_druzya = True\n if not dobavlenie_v_druzya and str(current_user.id) in user.friends.split(\"_\"):\n udalenie_iz_druzey = True\n try:\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n return render_template(\"profile.html\", colors=colors, user=user, main_color=main_color,\n userid=user_id_str, ocenka_reputacii=ocenka_reputacii,\n dobavlenie_v_druzya=dobavlenie_v_druzya, main_lang=main_lang,\n udalenie_iz_druzey=udalenie_iz_druzey)\n\n\n@app.route(\"/edit_reputation///\") # Редактирование репутации\n@login_required\ndef edit_reputation(id, znach, second_id):\n sessions = db_session.create_session()\n user = sessions.query(users.User).get(id)\n if current_user.id != id:\n if (str(current_user.id) not in user.appraisers and\n f\"_[{second_id};1;{znach}]\" not in user.notifications):\n user.notifications = user.notifications + f\"_[{second_id};1;{znach}]\"\n sessions.merge(user)\n sessions.commit()\n return redirect(f\"/profile/{id}\")\n else:\n if znach == 0:\n user.reputation = min(100, int(user.reputation * 10.5) * 0.1)\n else:\n user.reputation = max(1, int(user.reputation * 9.5) * 0.1)\n user.appraisers += \"_\" + str(second_id)\n sessions.merge(user)\n sessions.commit()\n return redirect(f\"/clean_notifications/{id}/{second_id}/1/{znach}\")\n\n\n@app.route(\"/friends\")\n@login_required\ndef friends():\n sessions = db_session.create_session()\n user_friends = current_user.friends.split(\"_\")[2:]\n user_friends_list = []\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n for id in user_friends:\n user = sessions.query(users.User).get(id)\n user_friends_list += [user]\n try:\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n return render_template(\"friends.html\", colors=colors, main_color=main_color,\n main_lang=main_lang, user_friends_list=user_friends_list)\n\n\n@app.route(\"/add_to_friend//\") # Добавление в друзья\n@login_required\ndef add_to_friend(first_id, second_id):\n sessions = db_session.create_session()\n if first_id != current_user.id:\n user = sessions.query(users.User).get(first_id)\n if (str(current_user.id) not in user.friends.split(\"_\") and\n f\"_[{second_id};0;{first_id}]\" not in user.notifications):\n user.notifications = user.notifications + f\"_[{second_id};0;{first_id}]\"\n sessions.merge(user)\n sessions.commit()\n return redirect(f\"/profile/{first_id}\")\n else:\n if str(second_id) not in current_user.friends.split(\"_\"):\n current_user.friends = current_user.friends + f\"_{second_id}\"\n user_2 = sessions.query(users.User).get(second_id)\n user_2.friends = user_2.friends + f\"_{first_id}\"\n sessions.merge(user_2)\n sessions.merge(current_user)\n sessions.commit()\n return redirect(f\"/clean_notifications/{current_user.id}/{second_id}/0/{first_id}\")\n\n\n@app.route(\"/unfriend///\")\n@login_required\ndef unfiend(first_id, second_id, last_page):\n sessions = db_session.create_session()\n user_1 = sessions.query(users.User).get(first_id)\n user_2 = sessions.query(users.User).get(second_id)\n friends_1 = user_1.friends.split(\"_\")[1:]\n friends_2 = user_2.friends.split(\"_\")[1:]\n del friends_1[friends_1.index(str(second_id))]\n del friends_2[friends_2.index(str(first_id))]\n user_1.friends = \"_\" + \"_\".join(friends_1)\n user_2.friends = \"_\" + \"_\".join(friends_2)\n sessions.merge(user_1)\n sessions.merge(user_2)\n sessions.commit()\n if \"profile\" in last_page:\n return redirect(\"/\" + last_page.split(\"_\")[0] + \"/\" + last_page.split(\"_\")[1])\n else:\n return redirect(\"/\" + last_page)\n\n\n@app.route(\"/edit_profile\", methods=[\"GET\", \"POST\"]) # Редактирование профиля\n@login_required\ndef edit_profile():\n check_last_page()\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n form = edit_profile_form.EditProfileForm()\n try:\n sessions = db_session.create_session()\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n if main_lang == \"en\":\n message = \"If you want to change your password, enter your old password\"\n else:\n message = \"Если вы хотите изменить свой пароль, введите свой старый пароль\"\n if request.method == \"POST\":\n session = db_session.create_session()\n if form.old_password.data != \"\" and form.new_password.data != \"\":\n if not current_user.check_password(form.old_password.data):\n if main_lang == \"en\":\n message = \"Invalid old password\"\n else:\n message = \"Неверный старый пароль\"\n return render_template(\"edit_profile.html\", colors=colors, form=form,\n message=message)\n elif form.new_password.data != form.new_password_again:\n if main_lang == \"en\":\n message = \"The new password is incorrectly repeated\"\n else:\n message = \"Новый пароль повторен неправильно\"\n return render_template(\"edit_profile.html\", colors=colors, form=form,\n message=message)\n elif form.old_password.data == form.new_password.data:\n if main_lang == \"en\":\n message = \"The new password matches the old one\"\n else:\n message = \"Новый пароль совпадает со старым\"\n return render_template(\"edit_profile.html\", colors=colors, form=form,\n message=message)\n else:\n current_user.set_password(form.new_password.data)\n if str(request.files[\"file\"]) != \"\":\n file = request.files[\"file\"]\n name = \"static/img/avatar_img/avatar_\" + \\\n str(1 + len(os.listdir(\"static/img/avatar_img\"))) + \".jpg\"\n file.save(name)\n current_user.avatar = \"/\" + name\n current_user.favorite_games = form.favorite_games.data\n if form.name.data != \"\":\n if len(form.name.data) > 16 or len(form.name.data) < 3:\n if main_lang == \"en\":\n message = \"This login too long\"\n else:\n message = \"Этот логин слишком длинный\"\n return render_template(\"edit_profile.html\", colors=colors, form=form,\n message=message)\n current_user.name = form.name.data\n session.merge(current_user)\n session.commit()\n return redirect(f'/profile/{current_user.id}')\n form.avatar.data = current_user.avatar\n form.favorite_games.data = current_user.favorite_games\n form.name.data = current_user.name\n return render_template(\"edit_profile.html\", colors=colors, form=form, message=message)\n\n\n@app.route(\"/notifications\", methods=[\"GET\", \"POST\"]) # Уведомления\n@login_required\ndef notifications():\n # _[id - от кого;0 - запрос дружбы, 1 - отзыв; id - если запрос, ocenka - если отзыв]\n session = db_session.create_session()\n notifications = current_user.notifications.split(\"_\")[1:]\n new_notifications = []\n message = \"\"\n sessions = db_session.create_session()\n try:\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n if notifications == [\"\"]:\n if main_lang == \"en\":\n message = \"You don't have any new requests\"\n else:\n message = \"У вас нет новых запрсов\"\n else:\n for i in notifications[1:]:\n print(i[1:-1])\n items = list(map(int, i[1:-1].split(\";\")))\n user = session.query(users.User).get(items[0])\n new_notifications += [[user, items[1], items[2]]]\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n return render_template(\"notifications.html\", notifications=new_notifications, colors=colors,\n message=message, main_color=main_color, main_lang=main_lang)\n\n\n@app.route(\n \"/clean_notifications////\")\n@login_required\ndef clean_notifications(user_id, first_item, second_item, third_item):\n sessions = db_session.create_session()\n user = sessions.query(users.User).get(user_id)\n notification = f\"_[{first_item};{second_item};{third_item}]\"\n user.notifications = \"\".join(user.notifications.split(notification))\n if second_item == 0:\n notification = f\"_[{third_item};{second_item};{first_item}]\"\n print(notification)\n user_2 = sessions.query(users.User).get(first_item)\n user_2.notifications = \"\".join(user.notifications.split(notification))\n sessions.merge(user_2)\n sessions.merge(user)\n sessions.commit()\n return redirect(\"/notifications\")\n\n\n@app.route(\"/all_users\")\ndef all_users():\n sessions = db_session.create_session()\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n try:\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n info_users = sessions.query(users.User).filter(users.User.id).all()\n return render_template(\"all_users.html\", main_color=main_color,\n colors=colors, main_lang=main_lang, info_users=info_users)\n\n\n@app.route(\"/redefine_role\", methods=[\"GET\", \"POST\"]) # Страница переопределения ролей\ndef redefine_role():\n check_last_page()\n form = redefine_roles.Redefine_role()\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n sessions = db_session.create_session()\n try:\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n if form.validate_on_submit():\n if 'submit' in request.form or 'submit_rus' in request.form:\n try:\n sessions = db_session.create_session()\n user_info = sessions.query(users.User).filter(\n users.User.id == form.user_id.data).first()\n return render_template('redefine_role.html', colors=colors, form=form,\n user_name=user_info.name,\n user_role=user_info.role,\n main_color=main_color,\n main_lang=main_lang)\n except AttributeError:\n return render_template('redefine_role.html', colors=colors, form=form,\n message=\"Данного id не существует!\",\n user_name=\"\",\n user_role=\"\",\n main_color=main_color,\n main_lang=main_lang)\n elif 'save' in request.form or 'save_rus' in request.form:\n sessions = db_session.create_session()\n new_user_role = form.input_user_role.data\n user_info = sessions.query(users.User).filter(\n users.User.id == form.user_id.data).first()\n user_info.role = new_user_role\n sessions.commit()\n return render_template('redefine_role.html', colors=colors, form=form,\n user_name=\"\",\n user_role=\"\",\n main_color=main_color,\n main_lang=main_lang)\n elif \"to_display_all_users\" in request.form or \"to_display_all_users_rus\" in request.form:\n return render_template('redefine_role.html',\n main_lang=main_lang,\n main_color=main_color)\n return render_template('redefine_role.html', colors=colors, form=form,\n user_name=\"\",\n user_role=\"\",\n main_color=main_color,\n main_lang=main_lang)\n\n\n@app.route(\"/forum\", methods=[\"GET\", \"POST\"]) # Главная страница форума\ndef forum_func():\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n sessions = db_session.create_session()\n forum_questions = sessions.query(forum_db.Forum).filter(forum_db.Forum.date).all()\n try:\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n return render_template(\"forum.html\", colors=colors, forum_questions=forum_questions,\n main_color=main_color, main_lang=main_lang)\n\n\n# Полная страница вопроса (форум)\n@app.route(\"/forum/question/\", methods=[\"GET\", \"POST\"])\ndef forum_full_question(num_id):\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n sessions = db_session.create_session()\n forum_question = sessions.query(forum_db.Forum).filter(\n forum_db.Forum.id == num_id).first()\n name_users = []\n answers = []\n try:\n for i in forum_question.user_id.split(\"/end/new_author/\"):\n if i != \"None\":\n name_users.append(sessions.query(users.User).filter(\n users.User.id == i).first().name)\n for i in forum_question.answers.split(\"/end/new_answer/\"):\n if i != \"None\":\n answers.append(i)\n except AttributeError:\n pass\n try:\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n return render_template(\"forum_full_question.html\", colors=colors, num_id=num_id,\n title=forum_question.title, question=forum_question.question,\n answers=answers, user_name=name_users, count=len(answers),\n main_color=main_color, main_lang=main_lang)\n\n\n# Страница ответа на вопрос (форум)\n@app.route(\"/forum/answere_on_question/\", methods=[\"GET\", \"POST\"])\ndef answer_on_question_func(num_id):\n form = answer_on_question.Answer_on_question()\n if request.method == 'GET':\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n sessions = db_session.create_session()\n try:\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n return render_template(\"answer_on_question.html\", colors=colors, num_id=num_id, form=form,\n main_color=main_color, main_lang=main_lang)\n elif request.method == 'POST':\n sessions = db_session.create_session()\n answer = form.answer.data\n if \"/end/new_answer/\" in answer:\n correct_answer = answer.split('/end/new_answer/')\n answer = ''.join(correct_answer)\n answer_db = sessions.query(forum_db.Forum).filter(\n forum_db.Forum.id == num_id).first()\n first_answer = str(answer_db.answers) + \"/end/new_answer/\"\n first_author = str(answer_db.user_id) + \"/end/new_author/\"\n user_id_db = sessions.query(forum_db.Forum).filter(\n forum_db.Forum.id == num_id).first()\n id_user = current_user.id\n user_id_db.user_id = str(first_author) + str(id_user)\n answer_db.answers = str(first_answer) + str(answer)\n sessions.commit()\n return redirect(\"/forum\")\n\n\n@app.route(\"/forum/ask_question\", methods=[\"GET\", \"POST\"]) # Страница для задавания вопроса (форум)\ndef ask_a_question():\n form = ask_question.Ask_question()\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n if form.validate_on_submit():\n sessions = db_session.create_session()\n forum_ask_question = forum_db.Forum(\n title=str(form.title.data),\n question=str(form.question.data),\n theme=str(form.theme.data)\n )\n sessions.add(forum_ask_question)\n sessions.commit()\n return redirect(\"/forum\")\n sessions = db_session.create_session()\n try:\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n return render_template(\"ask_question.html\", colors=colors, form=form,\n main_color=main_color, main_lang=main_lang)\n\n\n@app.route(\"/settings\", methods=[\"GET\", \"POST\"]) # Настройки\ndef site_settings():\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n form = settings.Settings_form()\n sessions = db_session.create_session()\n user_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n if form.validate_on_submit():\n if 'white_theme' in request.form or 'white_theme_rus' in request.form:\n user_info.theme = \"white\"\n elif 'dusty_cheese_theme' in request.form or 'dusty_cheese_theme_rus' in request.form:\n user_info.theme = \"beige\"\n elif 'sneezing_fairy_theme' in request.form or 'sneezing_fairy_theme_rus' in request.form:\n user_info.theme = \"#e3f3ff\"\n elif 'lilac_cloud_theme' in request.form or 'lilac_cloud_theme_rus' in request.form:\n user_info.theme = \"#f9e8fa\"\n elif 'en_language' in request.form:\n user_info.language = \"en\"\n elif 'ru_language' in request.form:\n user_info.language = \"ru\"\n sessions.commit()\n try:\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n return render_template(\"settings.html\", colors=colors, form=form, main_color=main_color,\n main_lang=main_lang)\n\n\n@app.route('/question_delete/', methods=['GET', 'POST']) # Удаление вопроса на форуме\n@login_required\ndef news_delete(id):\n sessions = db_session.create_session()\n new = sessions.query(forum_db.Forum).filter(forum_db.Forum.id == id).first()\n if new:\n sessions.delete(new)\n sessions.commit()\n else:\n abort(404)\n return redirect('/forum')\n\n\n@app.route(\"/api\") # API\ndef api_page():\n colors = choice([\"primary\", \"success\", \"danger\", \"info\"])\n sessions = db_session.create_session()\n try:\n settings_info = sessions.query(settings_db.Settings_db).filter(\n settings_db.Settings_db.user_id == current_user.id).first()\n main_color = settings_info.theme\n main_lang = settings_info.language\n except AttributeError:\n main_color = \"white\"\n main_lang = \"en\"\n return render_template(\"api_page.html\", colors=colors, main_color=main_color,\n main_lang=main_lang)\n\n\ndef main():\n db_session.global_init(\"db/news.db\")\n api.add_resource(api_func.NewsListResource, '/api/forum')\n api.add_resource(api_func.NewsResource, '/api/forum/')\n socketio.run(app)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":41956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"170698701","text":"from django.shortcuts import render\r\nfrom django.http import HttpResponse\r\nimport time\r\n# Create your views here.\r\n\r\ndef home(request):\r\n\treturn render(request,'home.html')\r\n\r\ndef fibapp(request):\r\n\tstart=time.time()\r\n\tval1 = int(request.GET[\"num1\"])\r\n\tl = []\r\n\tfor i in range(val1+1):\r\n\t\tif i>1:\r\n\t\t\tl.append(l[i-2]+l[i-1])\r\n\t\telse:\r\n\t\t\tl.append(i)\r\n\tres = l[-1]\r\n\tend=time.time()\r\n\ttltme=float(end-start)\r\n\treturn render(request,\"final.html\",{'res':res,'tme':tltme})","sub_path":"fibonacci/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"51343121","text":"import requests\nfrom bs4 import BeautifulSoup\n\n\nurl = 'http://www.vg.no'\nurlContent = requests.get(url)\nurl_html = urlContent.text\nheadList = []\nsoup = BeautifulSoup(url_html, \"html.parser\")\n\nfor link in soup.find_all('div', class_=\"article-content\"):\n link_text = link.text\n print(link_text)\n","sub_path":"web-scrape/getHeadlines.py","file_name":"getHeadlines.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"108361857","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('servers', '0009_auto_20151022_1349'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='server',\n name='server_group',\n field=models.ForeignKey(null=True, blank=True, to='servers.ServerGroup'),\n ),\n migrations.AlterField(\n model_name='server',\n name='server_type',\n field=models.ForeignKey(null=True, blank=True, to='servers.ServerType'),\n ),\n ]\n","sub_path":"ops/servers/migrations/0010_auto_20151024_1346.py","file_name":"0010_auto_20151024_1346.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"998777","text":"from django.shortcuts import render\nfrom main_app import models\n\n\n# Create your views here.\ndef demo(request):\n return render(request, 'demo.html')\n\n\ndef formsList(request):\n project_list = models.Project.objects.all().filter(user_link=request.user)\n forms = []\n for i in project_list:\n forms.append(models.Form.objects.all().filter(project_link=i).get())\n return render(request, 'forms.html', context={'forms': forms, 'username': request.user.username})\n\n\ndef questionList(request, id):\n ques_list = models.Question.objects.all().filter(form_link=id).order_by('id')\n print(\"Questions list\")\n print(ques_list)\n ques = []\n ques_dict = {}\n for i in range(ques_list.count()):\n ques.append([ques_list.all()[i], models.Option.objects.all().filter(question_link=ques_list.all()[i]).all()])\n # ques.append(models.Option.objects.all().filter(question_link = i).all())\n return render(request, \"ques_list.html\",\n context={\"ques\": ques, \"form_name\": models.Form.objects.all().filter(id=id).get()})\n\ndef dashboard(request):\n return render(request, \"dashboard.html\")","sub_path":"main_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"508003673","text":"import heapq\nfrom typing import Dict, List, Set, Tuple, Sequence, Iterable\n\nfrom wmdl.target import Target\nfrom wmdl.grid import Vector3, Coordinate3, Position\nfrom wmdl.circuit import (\n Circuit, Transistor, TransistorContact, GroupContact, Connection\n)\n\n\nI = Vector3(1, 0, 0)\nJ = Vector3(0, 1, 0)\nK = Vector3(0, 0, 1)\n\n\ndef _circuit_to_net_list(\n target: Target, circuit: Circuit,\n layout: Dict[Transistor, Position],\n) -> Iterable[Set[Coordinate3]]:\n visited: Set[Connection] = set()\n # The groups method returns an iterator that always yields parent groups\n # first.\n for group in circuit.groups():\n for connection in group.connections():\n # Skip connections that are not the root of a tree.\n if connection in visited:\n # connection is not a root\n continue\n\n # Build up a set of all transistor contacts within the tree.\n connection_queue = [connection]\n transistor_contacts = set()\n while connection_queue:\n connection = connection_queue.pop(0)\n for contact in connection.contacts():\n if isinstance(contact, TransistorContact):\n transistor_contacts.add(contact)\n elif isinstance(contact, GroupContact):\n connection_queue.append(contact.connection)\n visited.add(contact.connection)\n else:\n raise TypeError()\n\n # Convert each set of transistor contacts to a set of coordinates.\n net = set()\n for transistor_contact in transistor_contacts:\n base_pos = layout[transistor_contact.transistor]\n # TODO rotation\n net.add(Coordinate3(\n base_pos.x,\n base_pos.y + transistor_contact.offset,\n base_pos.z,\n ))\n\n yield net\n\n\ndef _circuit_to_obstruction_list(\n target: Target, circuit: Circuit,\n layout: Dict[Transistor, Position],\n) -> Iterable[Coordinate3]:\n for transistor in circuit.transistors():\n position = layout[transistor]\n for offset in range(0, transistor.slots[-1][1] + 1 + 2 + 2 - 1):\n yield Coordinate3(position.x - 1, position.y + offset, position.z)\n yield Coordinate3(position.x, position.y + offset, position.z)\n yield Coordinate3(position.x + 1, position.y + offset, position.z)\n\n\ndef _is_in_bounds(target, point):\n max_x, max_y = target.bounds.x, target.bounds.y\n max_z = target.num_layers\n if point.x < 0:\n return False\n if point.x >= max_x:\n return False\n if point.y < 0:\n return False\n if point.y >= max_y:\n return False\n if point.z < 0:\n return False\n if point.z >= max_z:\n return False\n return True\n\n\ndef _split_net(net):\n # TODO minimum spanning tree\n items = iter(net)\n last_item = next(items)\n for next_item in items:\n yield (last_item, next_item)\n last_item = next_item\n\n\ndef _neighbours(pos: Coordinate3) -> Set[Coordinate3]:\n \"\"\"Returns an iterator over all coordinates adjacent to a point.\n\n These do not have to be linked.\n \"\"\"\n x, y, z = pos\n return {\n Coordinate3(x - 1, y, z),\n Coordinate3(x, y - 1, z),\n Coordinate3(x, y, z - 1),\n Coordinate3(x + 1, y, z),\n Coordinate3(x, y + 1, z),\n Coordinate3(x, y, z + 1),\n }\n\n\ndef _build_net_map(\n target,\n net_list: Sequence[Set[Coordinate3]], *,\n obstructions: Set[Coordinate3],\n) -> Dict[Coordinate3, int]:\n \"\"\"\n :param target:\n :param net_list:\n A list of the sets of coordinates that should be joined together by\n routes.\n :param obstructions:\n A set of points that must be avoided when placing routes.\n \"\"\"\n # A reverse lookup table for finding the net list index for point\n net_list_index = {}\n for net_id, net in enumerate(net_list):\n for point in net:\n net_list_index[point] = net_id\n\n # A map from points to net ids\n net_map: Dict[Coordinate3, int] = {}\n\n # Split each net into a minimum spanning tree of pairs\n pairs = [pair for net in net_list for pair in _split_net(net)]\n\n # Sort pairs by length, shortest first\n pairs = sorted(pairs, key=lambda p: (p[1] - p[0]).length())\n\n for src, tgt in pairs:\n assert net_list_index[src] == net_list_index[tgt]\n net_id = net_list_index[src]\n\n # A map from points to their distance from the start\n distances = {}\n\n # A map from points to the point by which they can be reached most\n # quickly when traveling from the start\n previous: Dict[Coordinate3, Coordinate3] = {}\n\n # A `heapq` managed queue of nodes that need to be visited, sorted\n # by their distance from the start plus an estimate of their\n # distance to the end.\n queue: List[Tuple[float, int, int, int]] = []\n\n # The set of all points that have been visited.\n evaluated: Set[Coordinate3] = set()\n\n # For each pair perform A* over 3d grid\n # heuristic:\n # Manhattan distance using horizontal and vertical\n # weights\n # weighting:\n # - constant per horizontal step\n # - constant per vertical step\n # - penalty for turning horizontally\n # - penalty for turning up or down\n # - penalty (to avoid breaking heuristic) for going over a point\n # that hasn't already been covered by this net\n # blocked:\n # - points in obstructions set\n # - points in the roots set that are not either the start or end\n # of this route\n # - points that have already been claimed by another route\n # write netlist id to each point where a route should be drawn\n\n heapq.heappush(queue, (0, src.x, src.y, src.z))\n distances[src] = 0\n\n while True:\n if not queue:\n raise Exception(\n \"could not place route: exhausted all possibilities\"\n )\n\n _, x, y, z = heapq.heappop(queue)\n current = Coordinate3(x, y, z)\n\n # Node has already been reached by a shorter route. There is no\n # need to visit it again. This check can be safely skipped.\n if current in evaluated:\n continue\n\n evaluated.add(current)\n\n if current == tgt:\n break\n\n for neighbour in _neighbours(current):\n if not _is_in_bounds(target, neighbour):\n continue\n\n # If a neighbour has already been evaluated then there is no\n # point in estimating its distance again, as the distance\n # passing through the current point can only possibly be\n # longer. This check isn't strictly necessary as the distance\n # check later will have the same effect but is a reasonable\n # optimisation, and makes it a bit clearer what is going on.\n if neighbour in evaluated:\n continue\n\n # Neighbour is blocked by a hard coded obstruction.\n if neighbour in obstructions and neighbour != tgt:\n continue\n\n # Neighbour is blocked by another route.\n if neighbour in net_map and net_map[neighbour] != net_id:\n continue\n\n # The direction of this step and the previous one are used to\n # compute the cost of the route and to avoid backtracking.\n direction = neighbour - current\n if current in previous:\n prev_direction = current - previous[current]\n else:\n prev_direction = direction\n\n # Ignore the neighbour if we are going back on ourselves.\n if direction == -prev_direction:\n continue\n\n # Calculate the distance of the neighbour from the starting\n # point.\n distance = distances[current] + 1\n\n # Penalty for movement\n if abs(direction == K):\n distance += target.vertical_step_cost\n else:\n distance += target.horizontal_step_cost\n\n # Penalty for turning\n # TODO\n # if direction != prev_direction:\n # if abs(direction) == K or abs(prev_direction) == K:\n # distance += target.vertical_turn_cost\n # else:\n # distance == target.horizontal_turn_cost\n\n # Penalty for not following a route that is already part of\n # this net.\n if neighbour in net_map and net_map[neighbour] != net_id:\n distance += target._new_step_cost\n\n # Skip neighbours to which a shorter route has already been\n # found.\n if (\n neighbour in distances and\n distances[neighbour] >= distance\n ):\n continue\n\n distances[neighbour] = distance\n previous[neighbour] = current\n\n # Queue the neighbour for processing.\n # Priority is based on the measured distance from the start\n # plus an optimistic estimate of the distance from the end.\n priority = distance\n priority += (\n abs((tgt - current).x) * target.horizontal_step_cost\n )\n priority += (\n abs((tgt - current).y) * target.horizontal_step_cost\n )\n priority += (\n abs((tgt - current).z) * target.vertical_step_cost\n )\n\n heapq.heappush(\n queue, (priority, neighbour.x, neighbour.y, neighbour.z),\n )\n\n # TODO If no route can be found panic, or rip up and rerun somehow.\n # The fact that the grid contains the netlist ids for which routes were\n # placed should help with this.\n # Trace back from tgt, marking each point on the route as belonging to\n # the current net\n cur = tgt\n while cur != src:\n net_map[cur] = net_id\n cur = previous[cur]\n net_map[src] = net_id\n\n return net_map\n\n\ndef _links_from_netmap(netmap):\n for point, net_id in netmap.items():\n x, y, z = point\n next_x = Coordinate3(x + 1, y, z)\n if next_x in netmap and netmap[next_x] == net_id:\n yield (point, next_x)\n\n next_y = Coordinate3(x, y + 1, z)\n if next_y in netmap and netmap[next_y] == net_id:\n yield (point, next_y)\n\n next_z = Coordinate3(x, y, z + 1)\n if next_z in netmap and netmap[next_z] == net_id:\n yield (point, next_z)\n\n\ndef route(\n target: Target, circuit: Circuit,\n layout: Dict[Transistor, Position],\n) -> Iterable[Tuple[Coordinate3, Coordinate3]]:\n # check_bounds(net_list)\n # check_intersection(net_list)\n\n net_list = list(_circuit_to_net_list(target, circuit, layout))\n obstructions = set(_circuit_to_obstruction_list(target, circuit, layout))\n net_map = _build_net_map(target, net_list, obstructions=obstructions)\n\n return _links_from_netmap(net_map)\n","sub_path":"wmdl/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":11570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"148225116","text":"# coding: utf-8\n\nfrom djehuty.command import Command\nfrom random import shuffle\nfrom urllib2 import urlopen\nfrom json import loads\nimport requests\n\nclass Attendance(Command):\n def get_parser(self, prog_name):\n parser = Command.get_parser(self, prog_name)\n parser.add_argument(\"-person\",\n default=None,\n help=\"Please input login name.\")\n\n return parser\n\n def take_action(self, parsed_args):\n try:\n if parsed_args.person == None:\n response = urlopen(\"https://sheetsu.com/apis/v1.0/f053bbc8/name/{}\".format(self.app_args.user))\n\n html = response.read()\n html = loads(html)\n\n html[0][\"attendance\"] = \"x\"\n\n r = requests.put(\"https://sheetsu.com/apis/v1.0/f053bbc8/name//{}\".format(self.app_args.user), data=html[0])\n\n else:\n response = urlopen(\"https://sheetsu.com/apis/v1.0/f053bbc8/name/{}\".format(parsed_args.person))\n\n html = response.read()\n html = loads(html)\n\n html[0][\"attendance\"] = \"x\"\n\n r = requests.put(\"https://sheetsu.com/apis/v1.0/f053bbc8/name//{}\".format(parsed_args.person), data=html[0])\n\n r.status_code\n\n return '@{} I completed.'.format(self.app_args.user)\n\n except:\n pass\n\nclass Meeting(Command):\n '''make meeting members list'''\n\n def get_parser(self, prog_name):\n parser = Command.get_parser(self, prog_name)\n parser.add_argument(\"-divide\",\n default=2,\n help=\"Please input significant figures.\")\n\n return parser\n\n def take_action(self, parsed_args):\n response = urlopen('https://sheetsu.com/apis/v1.0/f053bbc8')\n\n html = response.read()\n html = loads(html)\n\n #出欠席を確認\n \n html = [i for i in html if i[\"attendance\"] == \"o\"]\n \"\"\"\n for i in html:\n if i[\"attendance\"] == \"x\":\n html.remove(i)\n \"\"\"\n \n #重複するdataを除く\n seq = [i[\"data\"] for i in html]\n seen = set()\n seen_add = seen.add\n unique_seq = [x for x in seq if x not in seen and not seen_add(x)]\n \n members = []\n \n #dataに基づく変数を作成\n for i in unique_seq:\n exec(\"data_{} = []\".format(i))\n \n for person in html:\n if person[\"data\"] == i:\n eval(\"data_{}.append('{}')\".format(i, person[\"name\"]))\n \n shuffle(eval(\"data_{}\".format(i)))\n members += eval(\"data_{}\".format(i))\n \n num = int(parsed_args.divide)\n text = \"\"\n \n if num < len(members):\n for i in range(num):\n exec(\"team{} = []\".format(i+1))\n \n for (l, x) in enumerate(members):\n if l % num == i:\n exec('team{}.append(x)'.format(i+1))\n \n team_name = \"team{}\".format(i+1)\n text += \"\\n*{}*\\n\".format(team_name)+\">\"+\"\\n>\".join(eval(team_name))\n \n text += \"\\nhttps://goo.gl/yVmmjS\"\n \n else:\n text += \"Please input significant figures.\"\n \n return text\n","sub_path":"djehutysample/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"590889081","text":"from random import choice\n\nminha_lista = [x for x in range(1,11)]\n\nnumero_escolhido = choice(minha_lista)\n\nwhile True:\n tentativa = int(input(\"Escolha um número de 0 a 10: \"))\n if tentativa == numero_escolhido:\n print(\"Achou o numero!\")\n break\n else:\n print(\"Não achou, tente novamente!\")\n","sub_path":"10 - Imports.py","file_name":"10 - Imports.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"46744556","text":"#!/usr/bin/python\nimport pandas as pd\nfrom sklearn import svm\nfrom sklearn.ensemble import RandomForestClassifier\nimport pickle\n\nclass Ensemble():\n \"\"\"ensemble system class\"\"\"\n def __init__(self):\n self.X_frame1 = pd.read_csv(\"train200_200_2.csv\")\n self.X_frame2 = pd.read_csv(\"train200_250_2.csv\")\n self.X_frame3 = pd.read_csv(\"train250_200_2.csv\")\n self.X_frame4 = pd.read_csv(\"train250_250_2.csv\")\n self.X_frame5 = pd.read_csv(\"train250_200.csv\")\n self.X_frame6 = pd.read_csv(\"train250_250_1.csv\")\n\n def create_models(self):\n \"\"\"create models of predictors\"\"\"\n\n columns = ['correlation','conservation','polaritychange','chargechange','hydroindexchange','secondarystruc','asa','sizechange']\n columns_asa = ['correlation','conservation','polaritychange','chargechange','hydroindexchange','secondarystruc','sizechange']\n class_column = ['class']\n # prepare X_frame1\n x_trainArray1 = self.X_frame1.as_matrix(columns_asa)\n X_trainResults1 = self.X_frame1.as_matrix(class_column)\n Y_trainResults1 = Y_trainResults1.ravel()\n # prepare X_frame2\n X_trainArray2 = self.X_frame2.as_matrix(columns)\n Y_trainResults2 = self.X_frame2.as_matrix(class_column)\n Y_trainResults2 = Y_trainResults2.ravel()\n # prapare X_frame3\n X_trainArray3 = self.X_frame3.as_matrix(columns)\n Y_trainResults3 = self.X_frame3.as_matrix(class_column)\n Y_trainResults3 = Y_trainResults3.ravel()\n # prepare X_frame4\n X_trainArray4 = self.X_frame4.as_matrix(columns)\n Y_trainResults4 = self.X_frame4.as_matrix(class_column)\n Y_trainResults4 = Y_trainResults4.ravel()\n # prepare X_frame5\n X_trainArray5 = self.X_frame5.as_matrix(columns)\n Y_trainResults5 = self.X_frame5.as_matrix(class_column)\n Y_trainResults5 = Y_trainResults4.ravel()\n # prepare X_frame6\n X_trainArray6 = self.X_frame6.as_matrix(columns)\n Y_trainResults6 = self.X_frame6.as_matrix(class_column)\n Y_trainResults6 = Y_trainResults6.ravel()\n\n X_trainArray7 = self.X_frame3.as_matrix(column)\n Y_trainResults7 = self.X_frame3.as_matrix(class_column)\n Y_trainRes7 = Y_trainResults7.ravel()\n\n\n # train classifiers on specific subset of dataset, 3 SVM classifiers and 4 Random Forest\n # 200 250 SVM\n classifier1 = svm.SVC(kernel = 'poly',degree=4,class_weight='balanced')\n classifier1.fit(X_trainArray1, Y_trainResults1)\n filename = 'svm_model1.sav'\n pickle.dump(classifier1, open(filename, 'wb'))\n\n classifier2 = svm.SVC(kernel = 'poly',degree=4,class_weight='balanced')\n classifier2.fit(X_trainArray2, Y_trainResults2)\n filename = 'svm_model2.sav'\n pickle.dump(classifier2, open(filename, 'wb'))\n\n classifier3 = svm.SVC(kernel = 'poly',degree=4,class_weight='balanced')\n classifier3.fit(X_trainArray3, Y_trainResults3)\n filename = 'svm_model3.sav'\n pickle.dump(classifier3, open(filename, 'wb'))\n\n classifier4 = svm.SVC(kernel='poly', degree=4, class_weight='balanced')\n classifier4.fit(X_trainArray4, Y_trainResults4)\n filename = 'svm_model4.sav'\n pickle.dump(classifier4, open(filename, 'wb'))\n\n rf1 = RandomForestClassifier(max_features='auto',n_estimators=1000,n_jobs=1,min_samples_leaf=50,class_weight=\"balanced\")\n rf1.fit(X_trainArray5,Y_trainResults5)\n filename = 'rf_model1.sav'\n pickle.dump(rf1, open(filename, 'wb'))\n\n rf2 = RandomForestClassifier(max_features='auto',n_estimators=1000,n_jobs=1,min_samples_leaf=50,class_weight=\"balanced\")\n rf2.fit(X_trainArray3,Y_trainResults3)\n filename = 'rf_model2.sav'\n pickle.dump(rf2, open(filename, 'wb'))\n\n rf3 = RandomForestClassifier(max_features='auto',n_estimators=1000,n_jobs=1,min_samples_leaf=50,class_weight=\"balanced\")\n rf3.fit(X_trainArray6,Y_trainResults6)\n filename = 'rf_model3.sav'\n pickle.dump(rf3, open(filename, 'wb'))\n\n\n\np = Ensemble()\np.create_models()","sub_path":"BP/prediktor/final_code/save_predictors.py","file_name":"save_predictors.py","file_ext":"py","file_size_in_byte":4129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"431207693","text":"#!/usr/bin/env python\n\"\"\"Test for zbx\"\"\"\n\nimport pytest\nimport zbx\n\n\n@pytest.fixture\ndef fake_zbx():\n \"\"\"Fake host.\"\"\"\n import zbx\n\n def fake_req(m, p):\n print('M is : %s ' % m)\n if m == \"host.get\":\n return {'result': [{\n u'available': u'1', u'maintenance_type': u'0', u'snmp_errors_from': u'0',\n u'hostid': u'10084', u'description': u'', u'ipmi_errors_from': u'0',\n u'jmx_errors_from': u'0', u'tls_accept': u'1', u'ipmi_username': u'',\n u'snmp_disable_until': u'0', u'ipmi_authtype': u'-1', u'tls_subject':\n u'', u'host': u'zabbix.prod.zbx',\n u'ipmi_disable_until': u'0', u'disable_until': u'0', u'ipmi_password':\n u'', u'templateid': u'0', u'tls_issuer': u'', u'ipmi_available': u'0',\n u'lastaccess': u'0', u'tls_psk_identity': u'', u'ipmi_error': u'',\n u'snmp_error': u'', u'proxy_hostid': u'0', u'tls_psk': u'', u'name':\n u'vbbczabbix1.prod.par-1.h.blbl.cr', u'ipmi_privilege': u'2',\n u'maintenance_status': u'0', u'tls_connect': u'1',\n u'jmx_disable_until': u'0', u'jmx_error': u'', u'jmx_available': u'0',\n u'maintenanceid': u'0', u'status': u'0', u'snmp_available': u'0',\n u'error': u'', u'maintenance_from': u'0', u'flags': u'0',\n u'errors_from': u'0'}]}\n elif m == \"template.get\":\n return {'result': [{\n u'proxy_hostid': '0', u'host': u'Template OS Linux', u'status': '3',\n u'disable_until': '0', u'error': '', u'available': '0', u'errors_from': '0',\n u'lastaccess': '0', u'ipmi_authtype': '0', u'ipmi_privilege': '2',\n u'ipmi_username': '', u'ipmi_password': '', u'ipmi_disable_until': '0',\n u'ipmi_available': '0', u'snmp_disable_until': '0', u'snmp_available': '0',\n u'maintenanceid': '0', u'maintenance_status': '0', u'maintenance_type': '0',\n u'maintenance_from': '0', u'ipmi_errors_from': '0', u'snmp_errors_from': '0',\n u'ipmi_error': '', u'snmp_error': '', u'jmx_disable_until': '0',\n u'jmx_available': '0', u'jmx_errors_from': '0', u'jmx_error': '',\n u'name': 'Template OS Linux', u'flags': '0', u'templateid': '10001',\n u'description': '', u'tls_connect': '1', u'tls_accept': '1',\n u'tls_issuer': '', u'tls_subject': '', u'tls_psk_identity': '', u'tls_psk': ''\n }]}\n else:\n return \"42\"\n\n zbx.zapi.do_request = fake_req\n return zbx\n\n\ndef test_get_host_id(fake_zbx):\n \"\"\"Test_get_host_id.\"\"\"\n response = fake_zbx.get_host_id(\"zabbix.prod.zbx\")\n assert response == \"10084\"\n\n\ndef test_get_template_id():\n \"\"\"Test_get_template_id.\"\"\"\n response = zbx.get_template_id(\"Template OS Linux\")\n assert response == \"10001\"\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"482092342","text":"#Zakładamy, że 1 ludzki rok, to 5 lat psich.\n#Za pomocą konsoli wczytaj imię i wiek psa.\n#Wypisz komunikat ile pies miałby lat gdyby był człowiekiem.\n#Przykład:\n#Podaj imię psa - Burek\n#Podaj wiek psa - 3\n#Gdyby Burek był człowiekiem, miałby 15 lat.\n\nimie = input(\"Podaj imię psa: \")\nwiek = int(input(\"Ile lat ma Twój pies: \"))\n\nwiek_ludzki = 5*wiek\n\nprint(f\"Gdyby {imie} był człowiekiem, miałby {wiek_ludzki} lat.\")","sub_path":"Praca_domowa_1/Zad_1_8.py","file_name":"Zad_1_8.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"539931973","text":"## Problem Description.\n# https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/\n# Difficulty: Medium\n#\n# Given inorder and postorder traversal of a tree, construct the binary tree.\n#\n# Note:\n# \"You may assume that duplicates do not exist in the tree.\"\n#\n## Solution References:\n# https://github.com/yadongwen/leetcode/blob/master/Construct%20Binary%20Tree%20from%20Inorder%20and%20Postorder%20Traversal.java\n#\n#\n# A\n# / \\\n# B C\n# / \\ / \\\n# D E F G\n# / \\\n# H I\n#\n# inorder: DBHE\"A\"FCGI\n# postorder: DHEBFIGC\"A\"\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n # @param {integer[]} inorder\n # @param {integer[]} postorder\n # @return {TreeNode}\n def buildTree(self, inorder, postorder):\n return self.build(inorder, 0, len(inorder), postorder, 0, len(postorder))\n\n def build(self, inorder, sio, eio, postorder, spo, epo):\n # recursive call base case\n if sio >= eio or spo >= epo: return None\n\n # get the next subroot value from postorder and make a subroot\n rv = postorder[epo-1]\n r = TreeNode(rv)\n\n # get index of \"X\" in inorder\n i = inorder.index(rv)\n\n # at this point we can expect that\n # when inorder[i] is subroot\n # -- left\n # all inorder[sio:i-1] are nodes for left subtree\n # all postorder[spo:spo+i-sio-1] are nodes for left subtree\n # -- right\n # all inorder[i+1:eio-1] are nodes for right subtree\n # all postorder[spo+i-sio:epo-1-1]\n r.left = self.build(inorder, sio, i, postorder, spo, spo+i-sio)\n r.right= self.build(inorder, i+1, eio, postorder, spo+i-sio, epo-1);\n return r\n\n","sub_path":"tobebest/leetcode/python/tree/construct_binary_tree_from_inorder_and_postorder_traversal.py","file_name":"construct_binary_tree_from_inorder_and_postorder_traversal.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"602078478","text":"\"\"\"\nScript to preprocess the training images \n\nUsage:\n preprocess.py [-e] [--in=] [--out=] \n preprocess.py (-h | --help)\n preprocess.py --version\n\nOptions:\n -h --help Show this screen.\n --version Show version.\n -e Run Histogram equalization \n -i --in= Directory to find the raw images [default: /home/brian/Downloads/raw_train_data]\n -o --out= Directory to put the processed images [default: /home/brian/Downloads/train_data/Images]\n\n\"\"\"\nfrom docopt import docopt\nimport cv2 as cv\nimport numpy as np\nimport sys, os\n\n\ndef equalize(im):\n gray = cv.cvtColor(im,cv.COLOR_RGB2GRAY)\n # create a CLAHE object\n clahe = cv.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))\n cli = clahe.apply(gray)\n im2 = cv.cvtColor(cli,cv.COLOR_GRAY2RGB)\n return im2\ndef load_images_from_folder(in_folder,out_folder,CLAHE):\n for filename in os.listdir(in_folder):\n img = cv.imread(os.path.join(in_folder,filename))\n assert img is not None,\"File:\"+filename+\" not loaded\"\n print(filename)\n if CLAHE:\n img2 = equalize(img)\n print(\"CLAHE\")\n else:\n img2 = img\n print(\"No CLAHE\")\n crop_img = img2[250:550, 125:775].copy()\n cv.imwrite(os.path.join(out_folder,filename),crop_img) \n\nif __name__ == '__main__':\n\n args = docopt(__doc__,version='Preprocess version 1.1')\n # print(args)\n CLAHE = False\n if args['-e']:\n CLAHE = True\n load_images_from_folder(args['--in'],args['--out'],CLAHE)","sub_path":"LB/.ipynb_checkpoints/preprocess2-checkpoint.py","file_name":"preprocess2-checkpoint.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"88860407","text":"orig = open(\"f\", \"r\")\nfile = [line for line in orig][0]\n\nend = \"\"\n\ni = 0\n\nwhile i < len(file):\n if file[i] == \"(\":\n end_paren = file[i:].index(\")\") + i\n x = file[i:].index(\"x\") + i\n thing = file[i:end_paren + 1]\n num1 = int(file[i + 1:x])\n num2 = int(file[x + 1:end_paren])\n for j in range(num2):\n end += file[end_paren + 1:end_paren + 1 + num1]\n i += len(thing) + num1\n else:\n i+=1\n\nprint(end)","sub_path":"advent2016/advent11.py","file_name":"advent11.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"651860164","text":"from celery.task import task\nfrom django.db.models import Q\nfrom dynamic_scraper.utils.task_utils import TaskUtils\nfrom app.models import NewsWebsite, Data\n\n@task()\ndef run_spiders():\n t = TaskUtils()\n args = (Q(name='egg'),)\n t.run_spiders(NewsWebsite, 'scraper', 'scraper_runtime', 'whale', *args, **kwargs)\n\n@task()\ndef run_checkers():\n t = TaskUtils()\n args = (Q(id__gt=100),)\n t.run_checkers(Data, 'news_website__scraper', 'checker_runtime', 'whale_checker', *args, **kwargs)","sub_path":"django_dynamic_scraper/djangoItem/app/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"36704903","text":"\nclass Node:\n \"\"\"Node in a binary tree.\"\"\"\n\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n def count_descendants(self):\n \"\"\"Return count of nodes below the current node.\n \n Time complexity: O(n)\n Space complexity: O(1) best case, O(tree_depth) worst case\n \"\"\"\n stack = [self]\n size = 0\n while stack:\n node = stack.pop()\n if node.right:\n size += 1\n stack.append(node.right)\n if node.left:\n size += 1\n stack.append(node.left)\n return size\n\n","sub_path":"binary_node.py","file_name":"binary_node.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"484925427","text":"def countBits(n):\n \"\"\"Write a function that takes an (unsigned) integer as input,\n and returns the number of bits that are equal to one in the binary representation of that number.\n\n Args:\n n (int)\n\n Returns:\n int\n\n >>> countBits(0)\n 0\n >>> countBits(4)\n 1\n >>> countBits(7)\n 3\n >>> countBits(9)\n 2\n >>> countBits(10)\n 2\n \"\"\"\n\n i = 0\n while n != 0:\n if n % 2 == 1:\n i += 1\n n //= 2\n return i\n","sub_path":"python/kyu6/Bit Counting.py","file_name":"Bit Counting.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"433075191","text":"import numpy as np\nfrom collections import Counter\nimport time\nfrom parameters2 import *\n\n\nclass NetworkTask2:\n\n def __init__(self):\n \"\"\"\n Initiates the data\n \"\"\"\n self.data = None\n self.n_line = None\n self.n_node = None\n self.k_out = None\n self.dangling = None\n self.ssp = None\n self.k = None\n self.log = \"\"\n\n def compute(self, filename: str):\n \"\"\"\n Calls the different functions to compute the attributes of the class\n\n :param filename: Name of the file to use\n \"\"\"\n self.data, self.n_node = self.load_data(filename)\n self.k_out = self.build_degree()\n self.dangling = self.build_dangling()\n self.ssp = self.build_p(filename)\n self.k = self.build_index(filename)\n\n def load_data(self, filename: str) -> tuple[np.ndarray, int]:\n \"\"\"\n Reads the input file and stores its data in an array\n\n :param filename: Name of the file to use\n :return: Data of the input file and number of nodes\n \"\"\"\n start = time.time()\n data = np.loadtxt(\"data/\" + filename + \".txt\", dtype=int)\n\n n_node = 0\n for i in data:\n for j in i:\n if j > n_node:\n n_node = j\n\n end = time.time()\n\n log_string = \"\\nData loaded in {:.4f} s\".format(end - start)\n print(log_string)\n self.log = self.log + log_string\n\n return data, int(n_node)\n\n def build_degree(self) -> dict:\n \"\"\"\n Builds the dictionary of ways out for each node\n\n :return: The number of ways out for each node\n \"\"\"\n start = time.time()\n\n k_out = Counter(self.data[:, 0])\n\n end = time.time()\n log_string = \"\\nk_out built in {:.4f} ms\".format(1000 * (end - start))\n print(log_string)\n self.log = self.log + log_string\n\n return dict(k_out)\n\n def build_dangling(self) -> np.ndarray:\n \"\"\"\n Using the dictionary k_out, builds the array of dangling nodes\n\n :return: Array containing all the dangling nodes of the network\n \"\"\"\n start = time.time()\n dangling = []\n dang = set(self.k_out)\n\n for i in range(self.n_node):\n if i + 1 not in dang:\n dangling.append(i + 1)\n\n end = time.time()\n\n log_string = \"\\nDangling nodes array built in \" \\\n \"{:.4f} ms\".format(1000 * (end - start))\n print(log_string)\n self.log = self.log + log_string\n\n return np.array(dangling, dtype=int)\n\n def build_p(self, filename: str) -> np.ndarray:\n \"\"\"\n Builds the steady state probability list of the network\n\n :param filename: Name of the file to use\n :return: Steady state probability array\n \"\"\"\n start = time.time()\n\n gp = np.array([1 / self.n_node for _ in range(self.n_node)],\n dtype=float)\n\n counter = 0\n t_init = time.time()\n while True:\n counter += 1\n t_iter = time.time()\n print(\"{}: iteration {}, {:.4f} s\".format(filename, counter,\n t_iter - t_init))\n p = gp.copy()\n for i in self.data:\n gp[i[1] - 1] += alpha * p[i[0] - 1] / self.k_out[i[0]]\n\n for i in self.dangling:\n gp += alpha * p[i - 1] / self.n_node\n\n gp += (1 - alpha) / self.n_node\n\n gp = gp / np.linalg.norm(gp, 1)\n\n if np.linalg.norm(gp - p) < epsilon:\n print(\"Done in {} iterations\".format(counter))\n break\n elif counter >= 1000:\n print(\"Limit reached\")\n break\n\n end = time.time()\n log_string = \"\\nSteady state probability array built \" \\\n \"in {:.4f} s, {} iterations\".format(end - start, counter)\n print(log_string)\n self.log = self.log + log_string\n\n return p\n\n def build_index(self, filename: str) -> np.ndarray:\n \"\"\"\n Sorts and ranks the nodes given the steady state probability array\n self.ssp\n\n :param filename: Name of the file to use\n :return: Nodes of the network with associated rank\n \"\"\"\n start = time.time()\n\n dtype = [('node', int), ('rank', float)]\n k = []\n\n for i in range(self.n_node):\n k.append((i + 1, self.ssp[i]))\n\n k = np.array([tuple(row) for row in k], dtype=dtype)\n k = np.flip(np.sort(k, order='rank'))\n for i in range(self.n_node):\n k['rank'][i] = i + 1\n\n end = time.time()\n log_string = \"\\nArray sorted in {:.4f} ms\".format(1000 * (end - start))\n print(log_string)\n self.log = self.log + log_string\n\n dtype = [('node', 'int'), ('rank', 'int')]\n k = np.array(k, dtype=dtype)\n\n np.savetxt(\"data_out/\" + filename + \"_out.dat\", k, fmt='%i')\n\n return k\n","sub_path":"project/functions_task2.py","file_name":"functions_task2.py","file_ext":"py","file_size_in_byte":5027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"578859247","text":"import tensorflow as tf\nfrom os import listdir\nfrom os.path import isdir\nfrom tensorflow.keras.applications.resnet50 import ResNet50\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions\nimport numpy as np\nfrom numpy import savez_compressed\n\nmodel = ResNet50(weights='imagenet')\n#\ndef extract_feature_resnet50(directory):\n feature_test = []\n feature_train = []\n label_test = []\n label_train = []\n i = 1\n j = 1\n\n for subdir in listdir(directory):\n\t\t# path\n path = directory + subdir + '/'\n for filename in listdir(path):\n if filename.find('.jpg') != -1:\n img_path = path + filename\n print(filename)\n # ung dung\n img = image.load_img(img_path, target_size=(224, 224))\n img_data = image.img_to_array(img)\n img_data = np.expand_dims(img_data, axis=0)\n img_data = preprocess_input(img_data)\n resnet_feature = model.predict(img_data)\n resnet_feature = np.squeeze(resnet_feature)\n if filename.find('_0ID.jpg') != -1:\n feature_train.append(resnet_feature)\n label_train.append(i)\n i += 1\n else:\n feature_test.append(resnet_feature)\n j += 1\n if j == 21:\n j = 1\n return feature_train, label_train, feature_test, label_test\n\n\nfeature_train, label_train, feature_test, label_test = extract_feature_resnet50('./Data/')\n\nprint(\"test\")\nprint(feature_test)\nprint(\"train\")\nprint(len(feature_train))\nsavez_compressed('./exc/veactor_feature_restnet50.npz', feature_train, label_train, feature_test, label_test)\n","sub_path":"src/extract_feature_resnet50.py","file_name":"extract_feature_resnet50.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"62117992","text":"from PublicOpinion.takungpao.zhongguojingji import ZhongGuoJingJi\n\n\nclass HKCaiJing(ZhongGuoJingJi):\n\n def __init__(self):\n super(HKCaiJing, self).__init__()\n self.name = '香港财经'\n self.first_url = 'http://www.takungpao.com/finance/236131/index.html'\n self.format_url = 'http://www.takungpao.com/finance/236131/{}.html'\n\n\nif __name__ == \"__main__\":\n hkc = HKCaiJing()\n hkc.start()\n","sub_path":"PublicOpinion/takungpao/hkcaijing.py","file_name":"hkcaijing.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"453032632","text":"\"\"\"\n 环境支撑:\n pip install paramiko==2.8.1\n \n 使用说明:\n 执行命令:\n 文件上传:\n 1、指定本地文件路径\n 2、指定文件上传到远程的文件名\n 文件下载:\n 1、指定文件下载到本地的路径 需要加保存的文件名\n 注意: 要使用斜杠 不能用反斜杠\n eg:\n 正确:E:/test.zip\n 错误:E:\\test.zip\n 2、指定远程文件路径\n 服务器ip: 150.158.137.86\n\"\"\"\n\nimport time\nimport paramiko\n\ndetail = \\\n \"\"\" 此程序可以执行以下操作:\\n\n --------------------- SSH --------------------------------\n 1、输入关键字即可执行相应操作\n m: 对远程主机执行命令\n p: 上传文件到远程主机\n d: 下载文件到本地\n c: 结束退出程序\n --------------------- SSH --------------------------------\"\"\"\n\nssh_detail = \\\n \"\"\" 请按照提示连接远程主机\\n\n --------------------- SSH --------------------------------\n 1、输入远程主机ip地址,密码,端口默认为22连接主机;\n --------------------- SSH --------------------------------\"\"\"\n\n\n\n\nclass Ssh(object):\n def __init__(self):\n self.cmd_ssh = None\n self.sftp = None\n self.trans = None\n\n def check_ip(self):\n flag = True\n server_ip = input('输入���机地址:')\n return flag, server_ip\n\n def create_ssh_client(self, server_ip, username, passwd, port=22):\n \"\"\"\n 创建一个可以传输文件,执行命令的客户端,并返回\n :return: ssh_client\n \"\"\"\n print('正在连接,请等待......')\n try:\n # 创建ssh客户端\n ssh = paramiko.SSHClient()\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)\n ssh.connect(username=username, hostname=server_ip, password=passwd, port=port)\n # 创建命令连接通道\n self.cmd_ssh = ssh.invoke_shell()\n # 创建文件获取通道 创建sftp对象\n self.trans = ssh.get_transport()\n self.sftp = paramiko.SFTPClient.from_transport(self.trans)\n print('客户端创建成功!')\n return True\n except Exception as e:\n print(f'创建客户端出现异常,异常为:{e}')\n return False\n finally:\n print(self.cmd_ssh.recv(99999))\n\n def exec_cmd(self, cmd):\n \"\"\"\n param cmd: 执行的命令\n \"\"\"\n print(f'开始执行{cmd},请等待....')\n if cmd:\n try:\n cmds = cmd + '\\n'\n self.cmd_ssh.send(cmds)\n time.sleep(1)\n print(f\"\\033[1;32m {self.cmd_ssh.recv(99999).decode('utf-8')}\\033[m\")\n except Exception as e:\n print(f'终断命令执行失败,失败原因为{e}')\n else:\n raise Exception('执行命令为空为空')\n\n def put_file(self, local_path, remote_file_name):\n \"\"\"\n 上传文件到远程主机\n :param ssh_client: 客户端对象\n :param local_path: 本地路径\n :param remote_path: 远程路径\n :return:\n \"\"\"\n print('开始上传,请等待....')\n if local_path and remote_file_name:\n remote_path = f'/home/ubuntu/file/{remote_file_name}'\n try:\n def printTotals(transferred, toBeTransferred):\n print(f\"当前传输进度: {round(transferred / toBeTransferred, 4) * 100}%\")\n self.sftp.put(local_path, remote_path,callback=printTotals)\n print(f'\\033[4;34m上传成功文件已上传到{remote_path}\\033[m')\n except Exception as e:\n print(f'文件上传失败,失败原因:{e}')\n else:\n raise Exception(f'上传路径为空{local_path, remote_file_name}')\n\n def down_remote_file(self, local_path, remote_path):\n \"\"\"\n 下载文件到本地\n :param ssh_client: 客户端对象\n :param local_path: 本地路径\n :param remote_path: 远程路径\n :return:\n \"\"\"\n if local_path and remote_path:\n try:\n self.sftp.get(remote_path, local_path)\n print(f'\\033[4;34m下载成功,文件已下载到{local_path}\\033[m')\n except Exception as e:\n print(e)\n if str(e).find('Errno 13') != -1:\n print('请定义需要下载的文件名,并添加到路径中')\n if str(e).find('Errno 2') != -1:\n print('请检查文件路径是否正确')\n else:\n raise Exception(\n f'下载路径为空{local_path, remote_path}')\n\n def close_client(self):\n \"\"\"\n 执行官远程操作关闭客户端\n \"\"\"\n try:\n self.cmd_ssh.close()\n self.trans.close()\n print('客户端已关闭')\n except Exception as e:\n raise Exception(f'客户端关闭失败,原因为{e}')\n\n\nif __name__ == '__main__':\n ssh = Ssh()\n print(f\"\\033[2;32m {ssh_detail} \\033[m\")\n flags, server_ip = ssh.check_ip()\n if flags:\n username = \"ubuntu\"\n passwd = \"10793300@dD\"\n create_flag = ssh.create_ssh_client(server_ip, username=username, passwd=passwd, )\n if not create_flag:\n print(\"\\033[2;32m 创建失败,请检查ip地址 \\033[m\")\n else:\n try:\n while True:\n print(f\"\\033[2;32m {detail} \\033[m \")\n keyword = input('请输入要执行的操作:')\n if keyword == 'c':\n print('程序退出')\n break\n elif keyword == 'm':\n cmds = input('请输入要执行的linux命令:')\n ssh.exec_cmd(cmd=cmds)\n elif keyword == 'p':\n put_local_path = input('请输入需要上传文件的路径:')\n put_remote_path = input('请输入保存到远程主机得文件名:')\n res_put = ssh.put_file(put_local_path, put_remote_path)\n elif keyword == 'd':\n # 下载文件\n down_local_path = input('请输下载到本地的路径:')\n print(type(down_local_path))\n down_remote_path = input('请输入下载文件的路径:')\n ret_get = ssh.down_remote_file(down_local_path, down_remote_path)\n else:\n print(detail)\n print('关键字输入有误,请重新输入!')\n except Exception as e:\n print(e)\n finally:\n ssh.close_client()\n else:\n print('ip地址输入错误次数太多,程序退出')\n","sub_path":"work/网络操作_作业/remote_connect.py","file_name":"remote_connect.py","file_ext":"py","file_size_in_byte":7205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"565590609","text":"import math\n\ndef get_size(num_entries):\n if num_entries < 5:\n return 4\n elif num_entries < 9:\n return 8\n elif num_entries < 17:\n return 16\n elif num_entries < 33:\n return 32\n elif num_entries < 65:\n return 64\n elif num_entries < 129:\n return 128\n\n\ndef get_num_matches(size):\n mains = size - 1\n num_first_cons = size / 4\n cons = num_first_cons + 2 * num_first_cons - 1\n return (mains, cons, num_first_cons)\n\n\ndef get_num_byes(size, num_entries):\n return size - num_entries\n\n\ndef get_playoff_match_nums_tuple(event, num_entries):\n size = get_size(num_entries)\n num_main_matches, num_cons_matches, num_first_cons = get_num_matches(size)\n total_matches = num_main_matches + num_cons_matches\n\n num_byes = get_num_byes(size, num_entries)\n num_first_mains = size / 2\n bye_entries = get_bye_entries(size)[:num_byes]\n bye_match_nums = [int(math.ceil(e / 2.0)) for e in bye_entries]\n bye_match_nums.sort()\n\n finished_cons_matches = []\n useless_match_nums = []\n if_loser_match_nums = []\n\n for first in range(1, num_first_mains + 1, 2):\n second = first + 1\n main_match_num = second / 2\n if first in bye_match_nums and second in bye_match_nums:\n # pairs of bye match nums in first round cons (bye in 2nd round cons)\n finished_cons_matches.append(num_main_matches + second / 2)\n useless_match_nums.append(num_main_matches + main_match_num + num_first_cons)\n elif first not in bye_match_nums and second not in bye_match_nums:\n no_match_succ = num_main_matches + main_match_num + num_first_cons\n # no match\n useless_match_nums.append(no_match_succ)\n else:\n cons_match_num = num_main_matches + main_match_num + num_first_cons\n if_loser_match_num = num_first_mains + main_match_num\n if_loser_match_nums.append((cons_match_num, if_loser_match_num))\n # bye fills first round cons entry, match is useless\n useless_match_nums.append(num_main_matches + main_match_num)\n\n finished_match_nums = bye_match_nums + finished_cons_matches\n finished_match_nums = list(set(finished_match_nums))\n match_nums_to_remove = list(set(finished_match_nums + useless_match_nums))\n if_loser_match_nums = list(set(if_loser_match_nums))\n finished_match_nums.sort()\n match_nums_to_remove.sort()\n if_loser_match_nums.sort()\n\n return (event, total_matches, num_main_matches + 1, finished_match_nums,\n match_nums_to_remove, if_loser_match_nums, {})\n\n\ndef get_round_robin_match_nums_tuple(event, num_entries):\n if num_entries == 3:\n return (event, 0, 0, [], [], [], {1: set([1]), 2: set([2]), 3: set([3])})\n elif num_entries == 4:\n return (event, 0, 0, [], [], [], {1: set([1, 2]), 2: set([3, 4]), 3: set([5, 6])})\n elif num_entries == 5:\n return (event, 0, 0, [], [], [], {1: set([1, 2]), 2: set([3, 4]), 3: set([5, 6]), 4: set([8, 7]), 5: set([9, 10])})\n elif num_entries == 6:\n return (event, 0, 0, [], [], [], {1: set([1, 2, 3]), 2: set([4, 5, 6]), 3: set([7, 8, 9]), 4: set([10, 11, 12]), 5: set([13, 14, 15])})\n print('WARNING: Unsupported number of entries for round robin')\n\n\ndef get_bye_entries(size):\n if size == 4:\n return [2]\n elif size == 8:\n return [2, 7, 4]\n elif size == 16:\n return [2, 15, 6, 11, 4, 13, 8]\n elif size == 32:\n return [2, 31, 10, 23, 6, 27, 14, 19, 4, 29, 12, 21, 8, 25, 16]\n elif size == 64:\n return [2, 63, 18, 47, 10, 55, 26, 39, 6, 59, 22, 43, 14, 51, 30, 35, 4, 61, 20, 45, 12, 53, 28, 37, 8, 57, 24, 41, 16, 49, 32]\n\n\ndef get_match_nums_tuples(num_entries_by_event):\n match_nums_tuples = []\n for event, entries in num_entries_by_event.iteritems():\n if entries < 6:\n match_nums_tuples.append(get_round_robin_match_nums_tuple(event, entries))\n else:\n match_nums_tuples.append(get_playoff_match_nums_tuple(event, entries))\n return match_nums_tuples\n\n\ndef main():\n # Golden Bear LVI\n num_entries_by_event = {'AMS': 17,\n \t\t\t\t\t\t 'ABWS':5,\n 'AMD': 10,\n 'ABWD': 8,\n 'AXD': 9,\n 'BMS': 20,\n 'BMD': 22,\n 'BXD': 13,\n 'CMS': 22,\n 'CWS': 9,\n 'CMD': 53,\n 'CWD': 20,\n 'CXD': 30,\n 'DMS': 38,\n 'DWS': 13,\n 'DMD': 50, \n 'DWD': 18,\n 'DXD': 25}\n\n return get_match_nums_tuples(num_entries_by_event)\n\nif __name__ == '__main__':\n main()\n","sub_path":"matches_maker.py","file_name":"matches_maker.py","file_ext":"py","file_size_in_byte":4592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"53816860","text":"from sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.datasets import make_classification\n\nX_C2, y_C2 = make_classification(n_samples=100, n_features=2,\n n_redundant=0, n_informative=2,\n n_clusters_per_class=1, flip_y=0.1,\n class_sep=0.5,random_state=0)\n\nX_train, X_test, y_train, y_test = train_test_split(X_C2, y_C2,\n random_state=0)\nclf = KNeighborsClassifier(n_neighbors=11, weights='uniform' )\nclf.fit(X_train, y_train)\ntrain_score = clf.score(X_train, y_train)\ntest_score = clf.score(X_test, y_test)\nprint('train_score ={0:.2f}, test_score={0:.2f}'\n .format(train_score,test_score))","sub_path":"COURSE 3- Applied Machine Learning in Python/Week 2/KNN_Classifier.py","file_name":"KNN_Classifier.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"30280706","text":"#!/usr/bin/env python\n\n# script to initialize/modify a mongo database for the workspace service.\n\nfrom __future__ import print_function\nimport os\nimport sys\nfrom configobj import ConfigObj\nfrom pymongo import MongoClient\nimport urllib2\nimport json\nimport requests\n\ntry: # py 2/3 compatibility\n input = raw_input # @ReservedAssignment\nexcept NameError:\n pass\n\n__AUTHOR__ = 'gaprice@lbl.gov'\n\nCONFIGFILE = 'deploy.cfg'\nCONFIGHEADER = 'Workspace'\n\nMODULEDIR = 'workspace_deluxe'\nSETUPDIR = 'administration'\nFILENAME = 'initialize.py'\n\nMONGO = 'mongodb-'\n\nMODB = MONGO + 'database'\nMOHOST = MONGO + 'host'\nMOUSER = MONGO + 'user'\nMOPWD = MONGO + 'pwd'\n\nAUTH_URL = 'auth-service-url'\n\nSETTINGS = 'settings'\nSHOCKURL = 'shock_location'\nSHOCKUSER = 'shock_user'\nBACKEND = 'backend'\nTYPE_DB = 'type_db'\nBACKENDTOKEN = 'backend-token'\nSHOCK = 'shock'\nGFS = 'gridFS'\n\nREQPARAMS = [MOHOST, MODB]\nAUTHPARAMS = [MOUSER, MOPWD]\n\n\ndef printerr(*objs):\n print(*objs, file=sys.stderr)\n sys.exit(1)\n\n\ndef renamederr(err):\n printerr(err + ' Please use the {} program found in the {} folder.'.format(\n FILENAME, os.path.join(MODULEDIR, SETUPDIR)))\n\n\ndef printcfg(cfg, header):\n for k, v in cfg[header].iteritems():\n print(k + '=' + v)\n\n\ndef getinput(prompt, default=(), otheroptions={}, quitopt=False):\n opts = set()\n if default:\n defopt = default[0].lower()\n opts.add(defopt)\n prompt += ' [' + defopt + ' - ' + default[1] + ']'\n if otheroptions:\n for o, olong in otheroptions.iteritems():\n o = o.lower()\n opts.add(o)\n prompt += '/' + o + ' - ' + olong\n if quitopt:\n prompt += '/q - quit'\n opts.add('q')\n prompt += ': '\n while True:\n i = input(prompt)\n if not i:\n if default:\n return defopt\n else:\n print('Input required.')\n else:\n if i.lower() not in opts:\n print('Invalid input.')\n else:\n return i\n\n\ndef getparams(params, cfg, dropall):\n for key in params:\n if dropall or key not in cfg:\n cfg[key] = input('Please enter value for ' + key + ': ')\n\n\ndef printDBsettings(settings):\n for s in [TYPE_DB, BACKEND, SHOCKURL, SHOCKUSER]:\n print(s + '=' + str(settings.get(s, None)))\n\n\ndef _get_user(token, authurl):\n if not authurl:\n print('No auth url found in deploy file, using default')\n authurl = 'https://kbase.us/services/auth/api/legacy/KBase/Sessions/Login'\n d = {'token': token, 'fields': 'user_id'}\n print('Validating token with auth server at ' + authurl)\n ret = requests.post(authurl, data=d)\n if not ret.ok:\n try:\n err = ret.json()\n except:\n ret.raise_for_status()\n raise ValueError('Error connecting to auth service: {} {}\\n{}'\n .format(ret.status_code, ret.reason,\n err['error_msg']))\n\n return ret.json()['user_id']\n\n\ndef configDB(wscfg, db):\n settings = {SHOCKURL: None, SHOCKUSER: None, BACKEND: None}\n typedb = None\n while not typedb:\n typedb = input('Please enter the name of the mongodb type database: ')\n if typedb == wscfg[MODB]:\n print('The type database name cannot be the same as the ' +\n 'workspace database name: ' + wscfg[MODB])\n typedb = None\n settings[TYPE_DB] = typedb\n backend = getinput('Choose a backend: ', ('s', SHOCK), {'g': GFS})\n if backend == 's':\n settings[BACKEND] = SHOCK\n shockurl = input('Please enter the url of the shock server: ')\n shocktoken = input('Please enter an authentication token for the ' +\n 'workspace shock user account: ')\n try:\n shockuser = _get_user(shocktoken, wscfg.get(AUTH_URL))\n except Exception as e:\n printerr('Token validation failed: ' + e.args[0])\n wscfg[BACKENDTOKEN] = shocktoken\n try:\n r = urllib2.urlopen(shockurl).read()\n except:\n printerr(\"Couldn't contact the shock server at \" + shockurl)\n try:\n j = json.loads(r)\n except:\n printerr(shockurl + ' is not a shock server root url')\n if 'id' not in j or j['id'] != 'Shock':\n printerr(shockurl + ' is not a shock server root url')\n settings[SHOCKURL] = j['url']\n settings[SHOCKUSER] = shockuser\n else:\n settings[BACKEND] = GFS\n\n db[SETTINGS].update({}, settings, upsert=True)\n settings = db[SETTINGS].find_one()\n print('Successfully set DB configuration:')\n printDBsettings(settings)\n print()\n\n\ndef main():\n d, program = os.path.split(os.path.abspath(__file__))\n wd, setup = os.path.split(d)\n if os.path.basename(wd) != MODULEDIR or setup != SETUPDIR:\n renamederr('This program has been moved from its standard location.')\n if program != FILENAME:\n renamederr('This program has been renamed.')\n lclcfg = sys.argv[1] if len(sys.argv) > 1 else CONFIGFILE\n cfgfile = os.path.join(wd, lclcfg)\n if os.path.isdir(cfgfile):\n printerr(cfgfile + ' is a directory!')\n cfg = ConfigObj()\n dropconfig = False\n if os.path.isfile(cfgfile):\n cfg = ConfigObj(cfgfile)\n if CONFIGHEADER not in cfg:\n print('No {} section in config file {} - '.format(\n CONFIGHEADER, cfgfile) + 'will be created.')\n cfg[CONFIGHEADER] = {}\n else:\n print('Current configuration file:')\n printcfg(cfg, CONFIGHEADER)\n dropconfig = getinput('\\nKeep this configuration?', ('y', 'keep'),\n {'n': 'discard'}) == 'n'\n if dropconfig:\n print('Discarding current local configuration.')\n else:\n print('Keeping current local configuration.')\n else:\n printerr('Cannot find configfile: ' + cfgfile)\n wscfg = cfg[CONFIGHEADER]\n getparams(REQPARAMS, wscfg, dropconfig)\n authrqd = getinput('Does mongodb require authentication?', ('y', 'yes'),\n {'n': 'no'}) == 'y'\n if authrqd:\n getparams(AUTHPARAMS, wscfg, dropconfig)\n else:\n print('Ok, commenting out authorization information.')\n for key in AUTHPARAMS:\n if key in wscfg:\n wscfg['#' + key] = wscfg[key]\n del wscfg[key]\n print('Attempting to connect to mongodb database \"' + wscfg[MODB] +\n '\" at ' + wscfg[MOHOST] + '... ', end='')\n try:\n mongo = MongoClient(wscfg[MOHOST])\n except:\n printerr('\\nCould not connect to mongodb at ' + wscfg[MOHOST])\n db = mongo[wscfg[MODB]]\n if authrqd:\n try:\n db.authenticate(wscfg[MOUSER], wscfg[MOPWD])\n except:\n printerr('\\nUnable to authenticate to database \"' + wscfg[MODB] +\n '\"')\n print('Connected.')\n settings = None\n if SETTINGS in db.collection_names():\n settings = db[SETTINGS].find_one()\n if settings:\n print('The database is already initialized with the parameters:')\n printDBsettings(settings)\n print(\n '''\\nYou can change the server configuration now, but if the workspaceservice\nhas already saved objects it could put the workspace and the backend store\n(gridFS or shock) in an inconsistent state, in which case all workspace\nobjects will be irretrievable and you will make a lot of people really really\nmad.''')\n prompts = ['Do you want to change the configuration?',\n 'Are you absolutely sure you know what you are ' +\n 'doing?\\nThe consequences are dire, dire!',\n 'Seriously? You are about to royally jack ' +\n 'things up if the workspace service\\nhas ever ' +\n 'saved an object.'\n ]\n for n, q in enumerate(prompts):\n if getinput(q, ('n', 'no'), {'y': 'yes'}) != 'y':\n break\n if n == len(prompts) - 1:\n print('Ok, on your head be it.')\n configDB(wscfg, db)\n else:\n configDB(wscfg, db)\n print('Saving local configuration file:')\n printcfg(cfg, CONFIGHEADER)\n cfg.write()\n print('\\nConfiguration saved.')\n\nif __name__ == '__main__':\n main()\n","sub_path":"administration/initialize.py","file_name":"initialize.py","file_ext":"py","file_size_in_byte":8393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"383143100","text":"import time\nimport keyboard\nfrom math import floor\nfrom sound import Sound\nfrom collections import deque\n\n\"\"\"\nPARAMETERS\n==========\n\nDURATION: duration in seconds to sample from, more means less spikey/fast changing\nMIN_VOLUME: 0.0-1.0\nMAX_VOLUME: 0.0-1.0\nMAX_WPM: Max expected words per minute\n\"\"\"\n\nDURATION = 10\nMIN_VOLUME = 0.05\nMAX_VOLUME = 1.0\nMAX_WPM = 100\n\nlogger = [0 for _ in range(DURATION)]\ncounter = 0\ntimer = 0\n\n\ndef translate(value, left_min, left_max, right_min, right_max):\n \"\"\"\n Maps a value from one range to another\n :param value: The value to map\n :param left_min: Lower bound of 1\n :param left_max: Upper bound of 1\n :param right_min: Lower bound of 2\n :param right_max: Upper bound of 2\n :return: Mapped value\n \"\"\"\n\n left_span = left_max - left_min\n right_span = right_max - right_min\n\n value_scaled = float(value - left_min) / float(left_span)\n\n return right_min + (value_scaled * right_span)\n\n\ndef on_press_reaction(key):\n \"\"\"\n This function runs on any key pressed even if the window is closed.\n It increments a counter for that one second\n :return: None\n \"\"\"\n\n global counter\n\n if key.name != '8':\n counter += 1\n\n\ndef fading_average(list):\n \"\"\"\n The following is an average that priortizes the rightmost elements in the list\n :param list:\n :return:\n \"\"\"\n total = 0\n length = 0\n for index, item in enumerate(list):\n multiplier = 1 / (len(list) - index)\n total += item * multiplier\n length += multiplier\n\n return total / length\n\n\ndef main():\n \"\"\"\n Main function, we set volume to minimum start time\n :return:\n \"\"\"\n\n global logger\n global counter\n global timer\n\n timer = time.perf_counter()\n\n keyboard.on_press(on_press_reaction)\n\n while True:\n\n current_time = time.perf_counter()\n\n if current_time - timer > 1:\n \"\"\" Rotate deque and put new value on end\"\"\"\n logger.pop(0)\n logger.append(counter)\n counter = 0\n timer = current_time\n\n value = sum(logger) / len(logger)\n volume = (value + (((MAX_WPM * 5) / 60) * MIN_VOLUME)) / ((MAX_WPM * 5) / 60)\n\n if volume > MAX_VOLUME:\n volume = MAX_VOLUME\n\n volume = floor(volume * 100)\n\n Sound.volume_set(volume)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"422058284","text":"import signal\nimport rospy\nimport smach\nimport smach_ros\nimport math\nfrom math import tanh\nfrom geometry_msgs.msg import Twist\nfrom sensor_msgs.msg import Image\nimport numpy as np\nfrom sensor_msgs.msg import LaserScan\nfrom sensor_msgs.msg import Joy\nfrom kobuki_msgs.msg import Sound\nimport time\nimport sys\nsys.path.insert(1, '/home/malcolm/Documents/CMPUT_412/Competition/CS412T1C4/shapeTesting')\nimport v2\n\n\n\nglobal shutdown_requested\n\nclass RotateLeft(smach.State):\n\n def __init__(self, callbacks):\n smach.State.__init__(self, outcomes=['done1', 'count'])\n self.callbacks = callbacks\n self.twist = Twist()\n self.cmd_vel_pub = rospy.Publisher('cmd_vel_mux/input/teleop', Twist, queue_size=1)\n\n def execute(self, userdata):\n global shutdown_requested\n while not shutdown_requested:\n\n target_heading = (self.callbacks.bot_odom_heading + 90) % 360\n\n turning = True\n previous_difference = None\n angularSpeed = 0.4\n while turning:\n if shutdown_requested: # Basically ctrl+C\n return 'done1'\n difference = minimum_angle_between_headings(target_heading, self.callbacks.bot_odom_heading)\n\n if previous_difference is None:\n self.twist.angular.z = angularSpeed\n self.cmd_vel_pub.publish(self.twist)\n else:\n if difference < 1:\n turning = False\n self.twist.angular.z = 0\n self.cmd_vel_pub.publish(self.twist)\n else:\n self.twist.angular.z = angularSpeed\n self.cmd_vel_pub.publish(self.twist)\n\n if previous_difference != difference:\n previous_difference = difference\n return 'count'\n return 'done1'\n\n\nclass Count(smach.State):\n\n def __init__(self, callbacks):\n smach.State.__init__(self, outcomes=['done1', 'rotate_right'])\n self.callbacks = callbacks\n self.twist = Twist()\n self.cmd_vel_pub = rospy.Publisher('cmd_vel_mux/input/teleop', Twist, queue_size=1)\n self.sound_pub = rospy.Publisher('/mobile_base/commands/sound', Sound, queue_size=1)\n\n def execute(self, userdata):\n global shutdown_requested\n while not shutdown_requested:\n symbol_red_mask = self.callbacks.symbol_red_mask.copy()\n symbol_red_mask[0:self.callbacks.main_h / 4, 0:self.callbacks.main_w] = 0\n count = 0\n loopTotal = 10\n for i in range(loopTotal):\n count += v2.count_objects(symbol_red_mask)\n real_count = math.ceil(count/loopTotal)\n print(real_count)\n for i in range(int(real_count)):\n self.sound_pub.publish(1)\n time.sleep(1)\n return 'rotate_right'\n return 'done1'\n\n\nclass RotateRight(smach.State):\n\n def __init__(self, callbacks):\n smach.State.__init__(self, outcomes=['done1', 'success1'])\n self.callbacks = callbacks\n self.twist = Twist()\n self.cmd_vel_pub = rospy.Publisher('cmd_vel_mux/input/teleop', Twist, queue_size=1)\n\n def execute(self, userdata):\n global shutdown_requested\n while not shutdown_requested:\n\n target_heading = self.callbacks.bot_odom_heading - 90\n if target_heading < 0:\n target_heading = target_heading + 360\n\n turning = True\n previous_difference = None\n angularSpeed = -0.4\n while turning:\n if shutdown_requested:\n return 'done1'\n difference = minimum_angle_between_headings(target_heading, self.callbacks.bot_odom_heading)\n\n if previous_difference is None:\n self.twist.angular.z = angularSpeed\n self.cmd_vel_pub.publish(self.twist)\n else:\n if difference < 1:\n turning = False\n self.twist.angular.z = 0\n self.cmd_vel_pub.publish(self.twist)\n else:\n self.twist.angular.z = angularSpeed\n self.cmd_vel_pub.publish(self.twist)\n\n if previous_difference != difference:\n previous_difference = difference\n return 'success1'\n return 'done1'\n\n\ndef minimum_angle_between_headings(a, b):\n ''' return the difference in angle between where we are and where we want to be\n Parameters:\n a (int): the target heading of where we want to be\n b (int): the current heading of where we are\n Returns:\n heading_difference (int): the difference in angle between where we are\n and where we want to be\n '''\n heading_difference = a - b\n if heading_difference < 0:\n heading_difference += 360\n if heading_difference > 180:\n heading_difference = b - a\n if heading_difference < 0:\n heading_difference += 360\n return heading_difference\n\n\ndef get_state_machine(callbacks):\n sm_event_1 = smach.StateMachine(outcomes=['DONE1', 'SUCCESS1'])\n with sm_event_1:\n smach.StateMachine.add('ROTATE_LEFT', RotateLeft(callbacks),\n transitions={'done1': 'DONE1', 'count': 'COUNT'})\n smach.StateMachine.add('COUNT', Count(callbacks),\n transitions={'done1': 'DONE1', 'rotate_right': 'ROTATE_RIGHT'})\n smach.StateMachine.add('ROTATE_RIGHT', RotateRight(callbacks),\n transitions={'done1': 'DONE1', 'success1': 'SUCCESS1'})\n return sm_event_1\n","sub_path":"event_one.py","file_name":"event_one.py","file_ext":"py","file_size_in_byte":5802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"101173833","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport subprocess\n\nPackList = ['os','shutil','sys','pandas',\n 'math','glob','time','itertools',\n 'datetime','random','numpy']\n\n\n# Checking Package Installation and if not present install\nfor DepPack in PackList:\n try:\n __import__(DepPack)\n except ImportError as e:\n print(e)\n print('Installing Python Package: {}'.format(DepPack))\n subprocess.run('pip install {}'.format(DepPack),shell=True)\n pass\n\n# Install Necessary Packages\nimport os\nimport shutil\nimport sys\nimport pandas as pd\n\nOperatingSystem = sys.platform\n\n\n# Stage One = Sorting Out Program Dependencies Folder\nif OperatingSystem in [\"linux\",\"linux2\"]:\n print('Linux Operating System Detected')\n\n if os.path.isdir(\"./Tool_Dependancies_Mac\") == True:\n shutil.rmtree('./Tool_Dependancies_Mac')\n #os.rename('Tool_Dependancies_Linux','Tool_Dependancies')\n subprocess.run('mv Tool_Dependancies_Linux Tool_Dependancies',shell=True)\n AliasFile = 'bashrc'\n\nelif OperatingSystem == \"darwin\":\n print('Darwin Operating System Detected')\n\n if os.path.isdir(\"./Tool_Dependancies_Linux\") == True:\n shutil.rmtree('./Tool_Dependancies_Linux')\n subprocess.run('mv Tool_Dependancies_Mac Tool_Dependancies',shell=True)\n AliasFile = 'bash_profile'\n\nelif OperatingSystem == \"win32\" or 'win64':\n print('Windows Operating System Detected\\n\\\n This is not supported.\\n')\n sys.exit()\n\nfor dp in ['clustalo','blastn','makeblastdb']:\n subprocess.run('chmod u+x ./Tool_Dependancies/{}'.format(dp),shell=True)\n\n\n# Stage Two = File Presence\nNecessaryFilePaths = ['PrimedRPA.py',\n 'PrimedRPA_Parameters.txt',\n './Tool_Dependancies/blastn',\n './Tool_Dependancies/makeblastdb',\n './Tool_Dependancies/clustalo']\n\nfor FilePath in NecessaryFilePaths:\n if os.path.isfile(FilePath) == False:\n print('{}: Not Found\\nInstallation Exit'.format(FilePath))\n sys.exit()\n\n\n# Stage Three = Edit bashrc\nPrimedRPAPath = os.path.dirname(os.path.realpath(__file__))\n\nsubprocess.run('cp ~/.{0} ~/.{0}_Prior_PrimedRPA'.format(AliasFile),shell=True)\nsubprocess.run('echo alias PrimedRPA=\"{0}/PrimedRPA.py\" >> ~/.{1}'.format(PrimedRPAPath,AliasFile),shell=True)\n\n# Stage Four Triggure basic Validation.\nValidationCommand = './PrimedRPA.py ./Validation/Validation_1_PrimedRPA_Parameters.txt'\n\ntry:\n subprocess.run('chmod +x PrimedRPA.py',shell=True)\n subprocess.run(ValidationCommand,shell=True,check=True)\n\nexcept subprocess.CalledProcessError as e:\n print(e)\n print('PrimedRPA Validation Run 1 Fail\\nInstallation Exit')\n sys.exit()\n\n\nValOneDF = pd.read_csv('Validation_1_PrimedRPA_Output.csv')\nValOneDF = ValOneDF.sort_values(by=['Max_Blastn_Percentage_Match'],ascending=True)\n\n\nExpectedResult = pd.DataFrame([['GATCACAGGTCTATCACCCTATTAACCACTCACGGGAGCTC', 'TCCATGCATTTGGTATTTCGTCTGGCGGCTGTGCACGCGATAGCATTGCGAGACGCTGG', 'TACTTCAAAGACAGATACTGCGACATAGGGTGCTCCGGCTC', 17.073170731707318],\n ['ATCACAGGTCTATCACCCTATTAACCACTCACGGGAGCTCT', 'TCCATGCATTTGGTATTTCGTCTGGCGGCTGTGCACGCGATAGCATTGCGAGACGCTGG', 'TACTTCAAAGACAGATACTGCGACATAGGGTGCTCCGGCTC', 19.51219512195122],\n ['GATCACAGGTCTATCACCCTATTAACCACTCACGGGAGCTC', 'CTCCATGCATTTGGTATTTCGTCTGGCGGCTGTGCACGCGATAGCATTGCGAGACGCTG', 'ACTTCAAAGACAGATACTGCGACATAGGGTGCTCCGGCTCC', 17.073170731707318],\n ['GATCACAGGTCTATCACCCTATTAACCACTCACGGGAGCTC', 'CTCCATGCATTTGGTATTTCGTCTGGCGGCTGTGCACGCGATAGCATTGCGAGACGCTG', 'TACTTCAAAGACAGATACTGCGACATAGGGTGCTCCGGCTC', 17.073170731707318]],\n columns=[\"Forward_Primer\", \"Nfo_Probe\", \"Reverse_Primer\", \"Max_Blastn_Percentage_Match\"])\n\n\n\n\n\ncounter = 0\nfor i in ValOneDF.values.tolist():\n if i in ExpectedResult.values.tolist():\n counter+=1\n\nif counter == len(ExpectedResult):\n print('Validation 1 Passed\\n')\n\nelse:\n print('Validation 1 Failed\\nInstallation Exit')\n sys.exit()\n\nFilesToRemove = ['Validation_1_PrimedRPA_Output.csv']\nfor i in FilesToRemove:\n if os.path.exists(i):\n os.remove(i)\n\nshutil.rmtree('./Validation_1_Background_Blastn_DB_PrimedRPA')\n\nprint('Installation Successfully Complete')\n","sub_path":"INSTALL.py","file_name":"INSTALL.py","file_ext":"py","file_size_in_byte":4324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"209690240","text":"# 3SAT test\nfrom random import randrange\nimport datetime\n\nT = 1\nF = 0\nS = 2\n\n#predlist = {(0,1,2):0, (0,1,3):0}\n#negs = {(0,1,2):255, (0,1,3):255}\n\n\ndef make_ks(reverse=False):\n\t\"\"\"ks are the bits of the ints from 0 to 7, used as truth flags\n\tfor vars in predicates. I.e. 0 means the denial of a var, 0 for var X means notX\n\t1 for var X means X is true\n\t\"\"\"\n\tks = []\n\tfor i in range(2):\n\t\tfor j in range(2):\n\t\t\tfor k in range(2):\n\t\t\t\tif reverse:\n\t\t\t\t\tks.append((1-i,1-j,1-k))\n\t\t\t\telse:\n\t\t\t\t\tks.append((i,j,k))\n\treturn ks\n\n\ndef make_preds0(pcount = 100, nvars = 99):\n\tpreds = {}\n\tfor a in range(pcount):\n\t\tsi = randrange(0,2)*2 - 1\n\t\tsj = randrange(0,2)*2 - 1\n\t\tsk = randrange(0,2)*2 - 1\n\t\tsi = sj = sk = 1\n\t\ti = randrange(0,nvars-2)\n\t\tj = randrange(i+1,nvars-1)\n\t\tk = randrange(j+1,nvars)\n\t\tpreds[(si*i,sj*j,sk*k)] = 255-randrange(0,255)\n\treturn preds\n\n\n\ndef make_preds(pcount = 100, nvars = 99):\n\tpreds = {}\n\tfor a in range(pcount):\n\t\tsi = randrange(0,2)*2 - 1\n\t\tsj = randrange(0,2)*2 - 1\n\t\tsk = randrange(0,2)*2 - 1\n\t\tsi = sj = sk = 1\n\t\ti = randrange(0,nvars-2)\n\t\tj = randrange(i+1,nvars-1)\n\t\tk = randrange(j+1,nvars)\n\t\tpreds[(si*i,sj*j,sk*k)] = 2**randrange(8) # 255-randrange(0,255)\n\treturn preds\n\n\ndef make_negs(pcount = 100, nvars = 99):\n\tnegs = {}\n\tfor a in range(pcount):\n\t\ti = randrange(0,nvars-1)\n\t\tj = randrange(i+1,nvars)\n\t\tk = randrange(j+1,nvars+1)\n\t\tnegs[(i,j,k)] = randrange(0,255)\n\t\t#negs[(i,j,k)] = 2**randrange(0,8)\n\treturn negs\n\ndef pred2neg(pred):\n\t#given a predicate, return its negative\n\tpass\n\n\ndef brute():\n\t#given a number of variables N and a predicate list PL try all certs of lenght N against all predicates\n\tcert = (2 ** (N+1)) - 1\n\tfor pred in predlist:\n\t\tpass\n\treturn cert\n\ndef depcount(var, predlist):\n\tt = 0\n\tf = 0\n\tfor pred in predlist:\n\t\tfor el in pred:\n\t\t\tif el == var:\n\t\t\t\tt += 1\n\t\t\telif el == -var:\n\t\t\t\tf += 1\n\n\treturn (t,f)\n\n\ndef check_overconst(predlist):\n\tfor pred in predlist:\n\t\tif predlist.get(pred) and predlist[pred] < 1:\n\t\t\treturn True\n\treturn False\n\n\ndef mk_randcert(nvar = 100):\n\tcert = []\n\tfor i in range(nvar):\n\t\tcert.append(randrange(0,2))\n\treturn cert\n\n\ndef check_cert(cert, neglist, ks):\n\tfor pred in sorted(list(neglist.keys())):\n\t\tp0,p1,p2 = pred\n\t\tprint(pred,neglist[pred])\n\t\tmflags = neglist[pred]\n\t\tfor i in range(8):\n\t\t\tif ((mflags >> i) & 1) == 0:\n\t\t\t\tnext\n\t\t\telse: \t\t\t\t\n\t\t\t\tk0,k1,k2 = ks[i]\n\t\t\t\tif not( cert[p0] == k0 and cert[p1] == k1 and cert[p2] == k2):\n\t\t\t\t\tprint(\"OK \",i,cert[p0],cert[p1],cert[p2],ks[i], p0,p1,p2)\n\t\t\t\t\tnext\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Fail\",i,cert[p0],cert[p1],cert[p2],ks[i], p0,p1,p2)\n\t\t\t\t\treturn False\n\t\tprint(\"\\n\")\n\treturn True\n\n\ndef print_cert(cert):\n\tfor i in range(0,len(cert),20):\n\t\tprint(cert[i:i+20])\n\n\ndef coverage(predlist):\n\tcov = []\n\tfor pred in predlist:\n\t\tcov.append(pred[0])\n\t\tcov.append(pred[1])\n\t\tcov.append(pred[2])\n\treturn sorted(set(cov))\n\n# first, make sure that no var triple has more than 2**3 - 1 constraints, else the group of preds is unsat\n# count ts and fs from each var\n# choose the largest group from the most connected var\n# reduce the remaining vars by extracting the already-satisfied preds\n# then take the largest group from the remaining vars and repeat\n\n# bottom-up\n# trips, reduced to no more than 7 distinct constraints\n# then tied to pairs and singles to further reduce. From trips to pairs and singles will add additional\n# constraints \n\ndef snippets():\n\tnvars = 100\n\tv = []\n\tfor i in range(nvars):\n\t\tv.append(set())\n\n\tpl = make_negs()\n\tpredlist = list(predlist.keys())\n\tfor i in range(len(predlist)):\n\t\tpred = predlist[i]\n\t\tfor el in pred:\n\t\t\tv[el].add(i)\n\n\tm1 = {}\n\tm2 = {}\n\tfor i in range(256):\n\t\tfor j in range(256):\n\t\t\tfor k in range(1,10):\n\t\t\t\tm1[(i,j,k)] = match(i,j,k)\n\t\t\t\tm2[(i,j,k)] = match(i,j,k+10)\n\n\n\n\tfor i in range(256):\n\t\tfor j in range(256):\n\t\t\tfor k in range(1,10):\n\t\t\t\tprint(\"{0:3d} {1:3d} {2:2d} {3:>2s} {0:3d} {1:3d} {2:2d} {4:>2s}\".format(i,j,k,[\"T\",\"F\"][match(i,j,k)],[\"T\",\"F\"][match(i,j,k+10)]))\n\n\ndef t1():\n\tt = list(range(8)) #satisfiers\n\ts = [] #predicate constraints\n\tk = [] #incompatibles\n\tfor i in range(7):\n\t\ts.append(randrange(0,8))\n\ts = set(s)\n\tprint(\"Constraints\\t\", list(s))\n\tfor el in s:\n\t\tt.remove(7-el)\n\t\tk.append(7-el)\n\n\tprint(\"Incompatible\\t\", k)\n\tprint(\"Compatible\\t\"\t,t)\n\ndef mk_randpred():\n\ts = [] #predicate constraints\n\tfor i in range(7):\n\t\ts.append(randrange(0,8))\n\ts = set(s)\n\treturn list(s)\n\t\ndef g(n):\n\tif n < 1 or n > 6:\n\t\traise OutOfBoundsException\n\telif n == 1:\n\t\t_g = ([x] for x in range(8))\n\telif n == 2:\n\t\t_g = ([x, y] for x in range(8) for y in range(8) if x != y)\n\telif n == 3:\n\t\t_g = ([x,y,z] for x in range(8) for y in range(8) for z in range(8) if x != y and y != z and x != z)\n\telif n == 4:\n\t\t_g = ([w, x,y,z] for w in range(8) for x in range(8) for y in range(8) for z in range(8) if w != x and w != y and w != z \n\t\t\tand x != y and y != z and x != z)\n\telif n == 5:\n\t\t_g = ([v, w, x,y,z] for v in range(8) for w in range(8) for x in range(8) for y in range(8) for z in range(8) \n\t\t\tif w != x and w != y and w != z and x != y and y != z and x != z and v != w and v != x and v != y and v != z)\n\telif n == 6:\n\t\t_g = ([u,v, w, x,y,z] for u in range(8) for v in range(8) for w in range(8) for x in range(8) for y in range(8) for z in range(8) \n\t\t\tif w != x and w != y and w != z and x != y and y != z and x != z and v != w and v != x and v != y and v != z\n\t\t\tand u != v and u != w and u != x and u != y and u != z)\n\treturn _g\n\ndef g2(n):\n\tif n < 1 or n > 6:\n\t\traise OutOfBoundsException\n\telif n == 1:\n\t\t_g = ([x] for x in range(8))\n\telif n == 2:\n\t\t_g = ([x, y] for x in range(8) for y in range(8) if x < y)\n\telif n == 3:\n\t\t_g = ([x,y,z] for x in range(8) for y in range(8) for z in range(8) if x < y and y < z )\n\telif n == 4:\n\t\t_g = ([w, x,y,z] for w in range(8) for x in range(8) for y in range(8) for z in range(8) if w < x and x < y and y < z)\n\telif n == 5:\n\t\t_g = ([v, w, x,y,z] for v in range(8) for w in range(8) for x in range(8) for y in range(8) for z in range(8) \n\t\t\tif v < w and w < x and x < y and y < z)\n\telif n == 6:\n\t\t_g = ([u,v, w, x,y,z] for u in range(8) for v in range(8) for w in range(8) for x in range(8) for y in range(8) for z in range(8) \n\t\t\tif u < v and v < w and w < x and x < y and y < z)\n\treturn _g\n\ndef compat(constraints):\n\tc = list(range(8))\n\tfor el in constraints:\n\t\tc.remove(7-el)\n\tassert(len(c)>0)\n\treturn c\n\n\ndef _validate(cpart,pred):\n\ta,b,c = cpart\n\td,e,f = list(pred.keys())\n\treturn ((a == d) or (b == e) or (c == f))\n\ndef kspack(ks):\n\t\"\"\"takes a kset and returns an 8-bit number\"\"\"\n\tbits = 0\n\t_ks = make_ks()\n\tfor i in range(8):\n\t\tif _ks[i] in ks:\n\t\t\tbits += 2**i\n\treturn bits\n\ndef ksunpack(bits):\n\t\"\"\"takes an 8-bit number and returns a kset\"\"\"\n\tks = []\n\t_ks = make_ks()\n\tfor i in range(8):\n\t\tif ((bits >> i) & 1) == 1:\n\t\t\tks.append(_ks[i])\n\treturn ks\n\ndef _match1(a, b, p1, p2):\n\treturn (((a >> p1) & 1) == ((b >> p2) & 1))\n\ndef _match2(a,b, p11, p12, p21, p22):\n\t#return ((((a >> p11) & 1) == ((b >> p21) & 1)) and (((a >> p12) & 1) == ((b >> p22) & 1)))\n\treturn _match1(a,b, p11,p21) and _match(a,b,p12,p22)\n\ndef match(a, b, p):\n\t# 18 partial match possibilities\n\tif ((p < 1) or (p == 10) or (p > 19)):\n\t\traise AssertionError #\"{1} must be 1-9 or 11-19\".format(p)\n\n\tif p == 1:\n\t\treturn _match1(a,b,0,0)\n\telif p == 2:\n\t\treturn _match1(a,b,0,1)\n\telif p == 3:\n\t\treturn _match1(a,b,0,2)\n\telif p == 4:\n\t\treturn _match1(a,b,1,0)\n\telif p == 5:\n\t\treturn _match1(a,b,1,1)\n\telif p == 6:\n\t\treturn _match1(a,b,1,2)\n\telif p == 7:\n\t\treturn _match1(a,b,2,0)\n\telif p == 8:\n\t\treturn _match1(a,b,2,1)\n\telif p == 9:\n\t\treturn _match1(a,b,2,2)\n\n\telif p == 11:\n\t\treturn _match2(a,b,0,0,1,1)\n\telif p == 12:\n\t\treturn _match2(a,b,0,0,1,2)\n\telif p == 13:\n\t\treturn _match2(a,b,0,0,2,1)\n\telif p == 14:\n\t\treturn _match2(a,b,0,0,2,2)\n\telif p == 15:\n\t\treturn _match2(a,b,1,0,2,1)\n\telif p == 16:\n\t\treturn _match2(a,b,1,0,2,2)\n\telif p == 17:\n\t\treturn _match2(a,b,0,1,2,1)\n\telif p == 18:\n\t\treturn _match2(a,b,0,1,2,2)\n\telif p == 19:\n\t\treturn _match2(a,b,1,1,2,2)\n\ndef consolidate3(preds):\n\t# given a list of trips, consolidate the bitflags\n\t# flags should be all 1s except 0 for the 1 at a power of 2 which corresponds to a predicate in ks\n\tbf = 0\n\tfor f in list(preds.values()):\n\t\tassert((f == 1) or (f == 2) or (f == 4) or (f == 8) or (f == 16) or (f == 32) or (f == 64) or (f == 128))\n\t\tif (0 == (bf & f)): #ignore redundants\n\t\t\tf = 0\n\t\tbf += f\n\t\tassert(bf < 255) # this would be unsatisfiable for a single predicate\n\treturn bf\n\n\n\ndef reduce3(predlist):\n\ttrips = {}\n\tfor pred in predlist:\n\t\ta,b,c = pred\n\t\tif trips.get((a,b,c)):\n\t\t\ttrips[(a,b)].append(pred)\n\t\telse:\n\t\t\ttrips[(a,b,c)] = [pred]\n\t\t\n\treturn trips\n\n\ndef reduce2(predlist):\n\tpairs = {}\n\tfor pred in predlist:\n\t\ta,b,c = pred\n\t\tif pairs.get((a,b)):\n\t\t\tpairs[(a,b)].append(pred)\n\t\telse:\n\t\t\tpairs[(a,c)] = [pred]\n\t\tif pairs.get((a,c)):\n\t\t\tpairs[(a,c)].append(pred)\n\t\telse:\n\t\t\tpairs[(a,c)] = [pred]\n\t\tif pairs.get((b,c)):\n\t\t\tpairs[(b,c)].append(pred)\n\t\telse:\n\t\t\tpairs[(b,c)] = [pred]\n\treturn pairs\n\ndef reduce1(predlist):\n\tsingles = {}\n\tfor pred in predlist:\n\t\ta,b,c = pred\n\t\tif singles.get((a)):\n\t\t\tsingles[(a)].append(pred)\n\t\telse:\n\t\t\tsingles[(a)] = [pred]\n\t\tif singles.get((b)):\n\t\t\tsingles[(b)].append(pred)\n\t\telse:\n\t\t\tsingles[(b)] = [pred]\n\t\tif singles.get((c)):\n\t\t\tsingles[(c)].append(pred)\n\t\telse:\n\t\t\tsingles[(c)] = [pred]\n\treturn singles\n\n\ndef bitrev(bits):\n\tstib = 0\n\tfor i in range(8):\n\t\tif bits & 2**i > 0:\n\t\t\tstib += 2**(7-i)\n\treturn stib\n\ndef revinv(nflags):\n\tflag = 255 ^ nflags\n\treturn bitrev(flag)\n\n\n\n\ndef red(a,b,p):\n\tka = ksunpack(a)\n\tkb = ksunpack(b)\n\treda = []\n\tredb = []\n\tfor ela in ka:\n\t\tfor elb in kb:\n\t\t\tif match(ela,elb,p):\n\t\t\t\treda.append(ela)\n\t\t\t\tredb.append(elb)\n\treturn kspack(reda), kspack(redb)\n\ndef summarize(ks):\n\ta0,b0,c0 = ks[0]\n\tres = [a0,b0,c0]\t\n\tfor el in ks[1:]:\n\t\ta,b,c = el\n\t\tif a != a0:\n\t\t\tres[0] = 2\n\t\tif b != b0:\n\t\t\tres[1] = 2\n\t\tif c != c0:\n\t\t\tres[2] = 2\n\treturn res[0],res[1],res[2]\n\ndef nonslack(vlist):\n\tpivot = 0\n\tnonslacks = [] # list(range(len(vlist)))\n\tslack = ([],[])\n\tif vlist.count(slack) > 0:\n\t\tfor i in range(len(vlist)):\n\t\t\tif vlist[i] != slack:\n\t\t\t\tnonslacks.append(i)\t\t\t\t\n\treturn nonslacks\n\ndef vcounts(predlist,nvpars):\n\tvar_ct = [] \n\tfor i in range(nvpars):\n\t\tvar_ct.append(([],[])) #false list, true list\n\tpk = list(predlist.keys())\n\tfor i,val in enumerate(pk):\n\t\tsmall,med,large = val\n\t\t#print(i,a,b,c)\n\t\tk = ksunpack(predlist[val]) # this may lead to redundancy, but it's already in place. If desired, make the predlist simply 2**x values\n\t\tfor pred in k:\n\t\t\t#print(pred)\n\t\t\t#pred is a triple-bool e.g. (0,1,0)\n\n\t\t\tvar_ct[small][pred[0]].append(val) #this puts the val of pk in v[a] true or false list based on the value of pred[0]\n\t\t\tvar_ct[med][pred[1]].append(val)\n\t\t\tvar_ct[large][pred[2]].append(val)\n\treturn var_ct\n\ndef print_v(vlist, ct=False):\n\t\"\"\"given a list of vars, print the trues and falses\n\t\"\"\"\n\tfor i,v in enumerate(vlist):\n\t\tvs = sorted(v)\n\t\teps=0.0000001\n\n\t\tvt = len(v[1])+eps\n\t\tvf = len(v[0])+eps\n\t\tpr = vf/(vf+vt)\n\t\t#print(pr)\n\t\tif ct:\n\t\t\tprint(\"var: {2:4d}\\ntrue: {0}\\nfalse: {1}\\nprob: {3}\\n\".format(vt,vf,i,pr))\n\t\telse:\n\t\t\tprint(\"var: {2:4d}\\ntrue: {0}\\nfalse: {1}\\nprob: {3}\\n\".format(sorted(v[1]),sorted(v[0]),i,pr))\n\t\t\n\ndef check_cert(cert, plist):\n\tproof = []\n\tfails = []\n\tfor i,pred in enumerate(plist):\n\t\tsmall, med, large = pred\n\t\tkset = ksunpack(plist[pred])\n\t\tfor j,k in enumerate(kset):\n\t\t\tif cert[small] == 2 or k[0] == cert[small]:\n\t\t\t\tproof.append(i)\n\t\t\t\tcontinue\n\t\t\tif cert[med] == 2 or k[1] == cert[med]:\n\t\t\t\tproof.append(i)\n\t\t\t\tcontinue\n\t\t\tif cert[large] == 2 or k[2] == cert[large]:\n\t\t\t\tproof.append(i)\n\t\t\t\tcontinue\n\t\t\tfails.append(i)\n\tif len(proof) mf:\n\t\t\tmf = len(b[0])\n\t\t\tfi = i\n\t\tif len(b[1]) > mt:\n\t\t\tmt = len(b[1])\n\t\t\tti = i\n\t\n\t#print(fi,mf,ti,mt)\n\treturn fi,mf,ti,mt\n\ndef remslack(vlist):\n\tv = vlist[:]\n\tfor i in range((v.count(([],[])))):\n\t\tv.remove(([],[]))\n\treturn v\n\ndef nonslack(vlist):\n\tpivot = 0\n\tnonslacks = [] # list(range(len(vlist)))\n\tslack = ([],[])\n\tif vlist.count(slack) > 0:\n\t\tfor i in range(len(vlist)):\n\t\t\tif vlist[i] != slack:\n\t\t\t\tnonslacks.append(i)\t\t\t\t\n\treturn nonslacks\n\ndef redlist(pl,nvars,vsol,short_circuit=False):\n\tpc = pl.copy()\n\tvsat=[]\n\tvc = vcounts(pl, nvars)\n\tmf,fc,mt,tc = findmax(vc)\n\tif short_circuit and fc ==1 and tc == 1:\n\t\tprint(\"singles\")\n\t\treturn {},vsol\n\tif fc > tc:\t\t\n\t\tprint(\"vsol {0} is false\".format(mf))\n\t\tk = vc[mf][0]\n\t\tvsol[mf] = 0\n\telse:\n\t\tprint(\"vsol {0} is true\".format(mt))\n\t\tk = vc[mt][1]\n\t\tvsol[mt] = 1\n\t#print(k)\n\tfor p in k:\n\n\t\tpc.pop(p)\n\treturn pc,vsol\n\ndef solve(pl, nvars,unsat, short_circuit=False):\n\tvsol = [2]* (nvars)\n\t\n\tlpl0 = len(pl) - 1\n\tfor i in range(len(pl)):\n\t\tlpl = len(pl)\n\t\t#each time redlist is called, pl is reduced and vsol is updated\n\t\t#print(lpl)\n\t\tpl,vsol = redlist(pl, nvars,vsol,short_circuit)\n\t\tif lpl == lpl0 and lpl > 0:\n\t\t\tprint(\"not satisfied. remainder:\", pl)\n\t\t\treturn False\n\t\tlpl0 = lpl\n\t\tif lpl == 0:\n\t\t\t#print(vsol)\n\t\t\treturn vsol,unsat\n\ndef multitrials(trials=20, vstep=100, pratio=20, show_cert=False,short_circuit=False):\n\tfor i in range(1,trials+1):\n\t\tv = vstep*i\n\t\tp = pratio*v\n\t\tunsat = None\n\t\ttrial(p,v,unsat,show_cert,short_circuit)\n\n\ndef check_bit(pl,offset):\n\tfor i,k in enumerate(pl):\n\t\tif offset in k:\n\t\t\tprint(k, ksunpack(pm[k]))\n\ndef trial(npred,nvars, unsat=None, show_cert=False,short_circuit=False):\n\tif unsat == None:\n\t\tunsat = []\n\tst = datetime.datetime.now()\n\tpm = make_preds(npred,nvars)\n\tmd = datetime.datetime.now()\n\tv,u = solve(pm,nvars,unsat, short_circuit)\n\tif len(u) < 1:\n\t\tproof = check_cert(v,pm)\n\telse:\n\t\tshow_fails(v,pm)\n\tif len(proof)>0:\n\t\tshow_fails(proof,v,pm)\n\t\t\t\n\tfin = datetime.datetime.now()\n\tprint(\"number of variables: \", nvars)\n\tprint(\"number of predicates: \", len(pm))\n\tprint(\"elapsed time to solve: {0}\\n\".format(fin-md))\n\treturn pm,v\n\n\ndef unsat(pl,cert):\n\tpm = pl.copy()\n\tfor p in pm:\n\t\tk = ksunpack(pm[p])\n\t\tfor i in range(3):\n\t\t\tif cert[p[i]] == k[i]:\n\t\t\t\tif pm.get(p):\n\t\t\t\t\tpm.remove(p)\n\t\t\t\tbreak\n\n\n\ndef cur(num,sym=\"$\",isep=\",\",fsep=\".\"):\n\tnums = str(num).split(\".\")\n\tsnum = nums[0]\n\tif len(nums) == 2:\n\t\tfnum = nums[1]\n\t\tif len(fnum) == 1:\n\t\t\tfnum += \"0\"\n\telse:\n\t\tfsep = fnum = \"\"\n\n\tp = []\n\td,m = divmod(len(snum),3)\n\tp.append(snum[:m])\n\tfor i in range(m,len(snum),3):\n\t\tp.append(snum[i:i+3])\n\n\tif \"\" in p:\n\t\tp.remove('')\n\t\n\treturn sym + isep.join(p) + fsep + fnum\n\t\n\ndef proc(cert,v):\n\tfor i,c in enumerate(cert):\n\t\tif 2 == c:\n\t\t\tcontinue\n\t\telse:\n\t\t\tif v[i] == c:\n\t\t\t\tprint(i,c)\n\n\ndef show_fails(fails, cert, plist):\n\tfor i,p in enumerate(plist):\n\t\tif p in fails:\t\t\t\n\t\t\tprint(i,p,ksunpack(plist[p]),cert[p[0]],cert[p[1]],cert[p[2]])\n\n\ndef print_p(plist):\n\tfor i,p in enumerate(plist):\n\t\tprint(p,ksunpack(plist[p]))\n\n\ndef check_cert(cert,plist):\n\tfails = []\n\tfor i,p in enumerate(plist):\n\t\ts,m,l = p\n\t\tks = ksunpack(plist[p])\n\t\tfor k in ks:\n\t\t\tsk,mk,lk = k\n\t\t\tincomp = (1-sk,1-mk,1-lk)\n\t\t\tif cert[s] == incomp[0] and cert[m] == incomp[1] and cert[l] == incomp[2]:\n\t\t\t\tfails.append(p)\n\treturn fails","sub_path":"rabbit/sat.py","file_name":"sat.py","file_ext":"py","file_size_in_byte":15931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"360239549","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\n@package cgsn_parsers.parsers.parse_nutnr\n@file cgsn_parsers/parsers/parse_nutnr.py\n@author Christopher Wingard\n@brief Parses NUTNR data logged by the custom built WHOI data loggers.\n'''\nimport os\nimport re\n\n# Import common utilites and base classes\nfrom cgsn_parsers.parsers.common import ParserCommon\nfrom cgsn_parsers.parsers.common import dcl_to_epoch, inputs, DCL_TIMESTAMP, STRING, NEWLINE\n\n# Set regex string to just find the NUTNR data.\nPATTERN = (\n DCL_TIMESTAMP + r'\\s+' + # DCL Time-Stamp\n r'SATN(\\w{2})' + r'(\\d{4}),' + # Measurement type and serial #\n STRING + NEWLINE # rest of the data, comma separated\n)\nREGEX = re.compile(PATTERN, re.DOTALL)\n\n\ndef _parameter_names_nutnr(spectra):\n '''\n Setup parameter names depending on the spectral output (full or condensed)\n '''\n parameter_names = [\n 'date_time_string',\n 'measurement_type',\n 'serial_number',\n 'date_string',\n 'decimal_hours',\n 'nitrate_concentration',\n 'auxiliary_fit_1st',\n 'auxiliary_fit_2nd',\n 'auxiliary_fit_3rd',\n 'rms_error'\n ]\n\n if spectra == 1: # full spectra\n parameter_names.extend([\n 'temperature_internal',\n 'temperature_spectrometer',\n 'temperature_lamp',\n 'lamp_on_time',\n 'humidity',\n 'voltage_lamp',\n 'voltage_analog',\n 'voltage_main',\n 'average_reference',\n 'variance_reference',\n 'seawater_dark',\n 'spectal_average',\n 'channel_measurements'\n ])\n \n return parameter_names\n\n\nclass Parser(ParserCommon):\n '''\n A Parser subclass that calls the Parser base class, adds the NUTNR specific\n methods to parse the data, and extracts the NUTNR data records from the DCL\n daily log files.\n '''\n def __init__(self, infile, spectra):\n self.initialize(infile, _parameter_names_nutnr(spectra))\n self.spectra = spectra\n\n def parse_data(self):\n '''\n Iterate through the record lines (defined via the regex expression\n above) in the data object, and parse the data into a pre-defined\n dictionary object created using the Bunch class.\n '''\n for line in self.raw:\n match = REGEX.match(line)\n if match:\n self._build_parsed_values(match, self.spectra)\n\n def _build_parsed_values(self, match, spectra):\n '''\n Extract the data from the relevant regex groups and assign to elements\n of the data dictionary.\n '''\n # Use the date_time_string to calculate an epoch timestamp (seconds\n # since 1970-01-01)\n epts = dcl_to_epoch(match.group(1))\n self.data.time.append(epts)\n self.data.date_time_string.append(str(match.group(1)))\n\n # Assign the remaining NUTNR data to the named parameters\n self.data.measurement_type.append(str(match.group(2)))\n self.data.serial_number.append(int(match.group(3)))\n\n # the rest of the data is in a comma separated string, so...\n data = (match.group(4)).split(',')\n\n # data found in all frames\n self.data.date_string.append(str(data[0]))\n self.data.decimal_hours.append(float(data[1]))\n self.data.nitrate_concentration.append(float(data[2]))\n self.data.auxiliary_fit_1st.append(float(data[3]))\n self.data.auxiliary_fit_2nd.append(float(data[4]))\n self.data.auxiliary_fit_3rd.append(float(data[5]))\n self.data.rms_error.append(float(data[6]))\n\n # data found only in the full frames\n if self.spectra == 1:\n self.data.temperature_internal.append(float(data[7]))\n self.data.temperature_spectrometer.append(float(data[8]))\n self.data.temperature_lamp.append(float(data[9]))\n self.data.lamp_on_time.append(int(data[10]))\n self.data.humidity.append(float(data[11]))\n self.data.voltage_lamp.append(float(data[12]))\n self.data.voltage_analog.append(float(data[13]))\n self.data.voltage_main.append(float(data[14]))\n self.data.average_reference.append(float(data[15]))\n self.data.variance_reference.append(float(data[16]))\n self.data.seawater_dark.append(float(data[17]))\n self.data.spectal_average.append(float(data[18]))\n self.data.channel_measurements.append(map(int, data[19:]))\n\nif __name__ == '__main__':\n # load the input arguments\n args = inputs()\n infile = os.path.abspath(args.infile)\n outfile = os.path.abspath(args.outfile)\n spectra = args.switch\n\n # initialize the Parser object for NUTNR\n nutnr = Parser(infile, spectra)\n\n # load the data into a buffered object and parse the data into a dictionary\n nutnr.load_ascii()\n nutnr.parse_data()\n\n # write the resulting Bunch object via the toJSON method to a JSON\n # formatted data file (note, no pretty-printing keeping things compact)\n with open(outfile, 'w') as f:\n f.write(nutnr.data.toJSON())\n","sub_path":"cgsn_parsers/parsers/parse_nutnr.py","file_name":"parse_nutnr.py","file_ext":"py","file_size_in_byte":5195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"394738662","text":"#!/usr/bin/env python\n\"\"\"\nMapper reads in text documents and emits word counts by class.\nINPUT: \n DocID \\t true_class \\t subject \\t body \nOUTPUT: \n partitionKey \\t word \\t class0_partialCount,class1_partialCount \n \n\nInstructions:\n You know what this script should do, go for it!\n (As a favor to the graders, please comment your code clearly!)\n \n A few reminders:\n 1) To make sure your results match ours please be sure\n to use the same tokenizing that we have provided in\n all the other jobs:\n words = re.findall(r'[a-z]+', text-to-tokenize.lower())\n \n 2) Don't forget to handle the various \"totals\" that you need\n for your conditional probabilities and class priors.\n \nPartitioning:\n In order to send the totals to each reducer, we need to implement\n a custom partitioning strategy.\n \n We will generate a list of keys based on the number of reduce tasks \n that we read in from the environment configuration of our job.\n \n We'll prepend the partition key by hashing the word and selecting the\n appropriate key from our list. This will end up partitioning our data\n as if we'd used the word as the partition key - that's how it worked\n for the single reducer implementation. This is not necessarily \"good\",\n as our data could be very skewed. However, in practice, for this\n exercise it works well. The next step would be to generate a file of\n partition split points based on the distribution as we've seen in \n previous exercises.\n \n Now that we have a list of partition keys, we can send the totals to \n each reducer by prepending each of the keys to each total.\n \n\"\"\"\n\nimport re \nimport sys \nimport numpy as np \n\nfrom operator import itemgetter\nimport os\n\n#################### YOUR CODE HERE ###################\n\n# Set 4 Partitions A,B,C,D by assigning alphabetically\ndef getPartitionKey(word):\n if word[0] < \"g\":\n return 'A'\n elif word[0] < \"n\":\n return 'B'\n elif word[0] < \"t\":\n return 'C'\n else:\n return 'D'\n \n# Initialize local aggreagator of total word count and doc count\nT_word_class0 = 0\nT_word_class1 = 0\nT_doc_class0 = 0\nT_doc_class1 = 0\n \n# initialize unique word count dictionary\nUnique = {}\n\n# Read from input\nfor line in sys.stdin:\n # parse input\n docID, _class, subject, body = line.lower().split('\\t')\n # tokenize\n words = re.findall(r'[a-z]+', subject + ' ' + body)\n \n # get the total doc count\n if _class == '0':\n T_doc_class0 += 1\n else:\n T_doc_class1 += 1\n \n # get the word count and total count\n for word in words:\n # get unique key dictionary\n Unique[word] = Unique.get(word, 0) + 1\n \n if _class == '0':\n T_word_class0 += 1\n pkey = getPartitionKey(word)\n print(f'{pkey}\\t{word}\\t{1},{0}')\n else:\n T_word_class1 += 1\n pkey = getPartitionKey(word)\n print(f'{pkey}\\t{word}\\t{0},{1}')\n\nfor pkey in ['A','B','C','D']: \n print(f'{pkey}\\t!total_words\\t{T_word_class0}, {T_word_class1}') \n print(f'{pkey}\\t!total_docs\\t{T_doc_class0}, {T_doc_class1}') \n # Also output the unique words\n print(f'{pkey}\\t!uniq_words\\t{len(Unique.keys())}, {len(Unique.keys())}')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#################### (END) YOUR CODE ###################","sub_path":"Assignments/HW2/NaiveBayes/train_mapper.py","file_name":"train_mapper.py","file_ext":"py","file_size_in_byte":3630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"320197640","text":"import os\nimport argparse\nimport enum\nimport tarfile\nimport abc\n\n\nclass SupportedModels(enum.Enum):\n \"\"\"\n Enumeration containing supported models\n \"\"\"\n ssd_resnet50_v1 = 'ssd_resnet50_v1'\n ssd_mobilnet_v1 = 'ssd_mobilenet_v1'\n\n\nclass Model(abc.ABC):\n \"\"\"\n Base model class used to obtain the model (and perform any necessary operations to make it usable)\n \"\"\"\n\n @abc.abstractmethod\n def get_pretrained_model(self, destination):\n \"\"\"\n Base method for obtaining a ready to use model\n Args:\n destination: path to where the file should be stored\n \"\"\"\n pass\n\n\nclass SsdMobilenetV1(Model):\n \"\"\" Concrete implementation of the Model base class for ssd_mobilenet_v1\"\"\"\n\n def get_pretrained_model(self, destination):\n \"\"\"\n Obtains a ready to use ssd_mobilenet_v1 model file.\n Args:\n destination: path to where the file should be stored\n \"\"\"\n url = 'http://download.tensorflow.org/models/object_detection/ssd_mobilenet_v1_coco_2018_01_28.tar.gz'\n os.system(\"curl -o ssd_mobilenet_v1_coco_2018_01_28.tar.gz {0}\".format(url))\n with tarfile.open(\"ssd_mobilenet_v1_coco_2018_01_28.tar.gz\") as tar:\n if not os.path.exists(destination):\n os.makedirs(destination)\n tar.extractall(destination)\n\n\nclass SsdResnet50(Model):\n \"\"\" Concrete implementation of the Model base class for ssd_resnet_50\"\"\"\n\n def get_pretrained_model(self, destination):\n \"\"\"\n Obtains a ready to use ssd_resnet_50 model file.\n Args:\n destination: path to where the file should be stored\n \"\"\"\n url = \"http://download.tensorflow.org/models/object_detection/\" \\\n \"ssd_resnet50_v1_fpn_shared_box_predictor_640x640_coco14_sync_2018_07_03.tar.gz\"\n os.system(\"curl -o ssd_resnet50_v1.tar.gz {0}\".format(url))\n with tarfile.open(\"ssd_resnet50_v1.tar.gz\") as tar:\n if not os.path.exists(destination):\n os.makedirs(destination)\n tar.extractall(destination)\n\n\ndef get_model(model: SupportedModels) -> Model:\n \"\"\"\n Factory method that returns the requested model object\n Args:\n model: model from SupportedModels enumeration\n\n Returns: Concrete object inheriting the Model base class\n\n \"\"\"\n if model == SupportedModels.ssd_resnet50_v1:\n return SsdResnet50()\n if model == SupportedModels.ssd_mobilnet_v1:\n return SsdMobilenetV1()\n else:\n raise AttributeError(\"The model {0} is not supported. Supported models: {1}\"\n .format(model_name, SupportedModels.__members__.keys()))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Prepare pre-trained model for COCO object detection')\n parser.add_argument('--model_name', type=str, default='ssd_resnet50_v1',\n help='model to download, default is ssd_resnet50_v1',\n choices=[\"ssd_resnet50_v1\", \"ssd_mobilenet_v1\"])\n parser.add_argument('--model_path', type=str, default='./model', help='directory to put models, default is ./model')\n\n args = parser.parse_args()\n model_name = args.model_name\n model_path = args.model_path\n try:\n model = get_model(SupportedModels(model_name))\n model.get_pretrained_model(model_path)\n except AttributeError:\n print(\"The model {0} is not supported. Supported models: {1}\"\n .format(model_name, SupportedModels.__members__.keys()))\n","sub_path":"examples/tensorflow/object_detection/prepare_model.py","file_name":"prepare_model.py","file_ext":"py","file_size_in_byte":3547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"455298946","text":"class Employee:\n __emp_count=0\n __avg_sal=0.0\n def __init__(self,name,salary,family,department):\n self.__name=name\n self.__salary=salary\n self.__family=family\n self.__department=department\n Employee.__emp_count=Employee.__emp_count+1\n Employee.__avg_sal=Employee.__avg_sal+salary\n @classmethod\n def average_salary(self):\n if Employee.__emp_count>0:\n return Employee.__avg_sal/Employee.__emp_count\n else:\n return 0\n\n @classmethod\n def get_employees_count(self):\n return Employee.__emp_count\n\n def get_name(self):\n return self.__name\n\n def get_salary(self):\n return self.__salary\n\n def get_family(self):\n return self.__family\n\n def get_department(self):\n return self.__department\n\nclass FulltimeEmployee (Employee):\n __emp_count = 0\n __avg_sal = 0.0\n\n def __init__(self, name, salary, family, department):\n FulltimeEmployee.__emp_count=FulltimeEmployee.__emp_count+1\n FulltimeEmployee.__avg_sal=FulltimeEmployee.__avg_sal+salary\n super().__init__(name,salary,family,department)\n @classmethod\n def average_salary(self):\n if FulltimeEmployee.__emp_count>0:\n return FulltimeEmployee.__avg_sal / FulltimeEmployee.__emp_count\n else:\n return 0\n\n @classmethod\n def get_employees_count(self):\n return FulltimeEmployee.__emp_count\n\n\n\nprint(\"Select from below\")\nprint(\"Case 1 :Create Employee class object\\nCase 2 :Create Fulltime Employee class object\\nCase 3 :View average salary of Emplyees\\n\"\n +\"Case 4 :View average salary of Full time employees\\nCase 5 :View Employees count\\nCase 6 :View full-time employees count\\nCase 7 :View Employee Deails\\nCase 8 :View Full-Time Employee Details\\nCase 9 :Exit\")\n\nbool=1\nemployee={}\nftEmployee={}\ndef addEmployee():\n name=str(input(\"Enter name\"))\n j = 1\n while(j):\n try:\n salary=float(input(\"Enter salary\"))\n j=0\n except ValueError:\n print('Non-numeric data.')\n department=str(input(\"Enter department\"))\n family=str(input(\"Enter family\"))\n E1=Employee(name,salary,family,department)\n employee[name]=E1\n print(\"Employee added\")\n\ndef addFullTimeEmployee():\n name=str(input(\"Enter name\"))\n j = 1\n while(j):\n try:\n salary=float(input(\"Enter salary\"))\n j=0\n except ValueError:\n print(\"Non-numeric data\")\n department=str(input(\"Enter department\"))\n family=str(input(\"Enter family\"))\n F1=FulltimeEmployee(name,salary,family,department)\n ftEmployee[name]=F1\n print(\"Full-Time Employee added\")\ndef EmployeeAvgSal():\n print(\"Employee Average Salary: \"+str(Employee.average_salary()))\ndef FTEmpAvgSal():\n print(\"Full-Time Employee Average Salary:\"+str(FulltimeEmployee.average_salary()))\n\ndef EmpCount():\n print(\"Employee Count: \" + str(Employee.get_employees_count()))\n\ndef FTEmpCount():\n print(\"Full-Time Employee Count: \" + str(FulltimeEmployee.get_employees_count()))\ndef ViewEmployee():\n if(len(employee)>0):\n for key in employee:\n print(str(key))\n name=str(input(\"Select Employee\"))\n if(name in employee):\n print(employee[name].get_name()+\" \"+str(employee[name].get_salary())+\" \"+employee[name].get_department()+\" \"+employee[name].get_family())\n else:\n print(\"invalid name\")\n else:\n print(\"No employees to view\")\ndef ViewFTEmployee():\n if (len(ftEmployee) > 0):\n for key in ftEmployee:\n print(str(key))\n name=str(input(\"Select Full-Time Employee\"))\n if (name in ftEmployee):\n print(ftEmployee[name].get_name()+\" \"+str(ftEmployee[name].get_salary())+\" \"+ftEmployee[name].get_department()+\" \"+ftEmployee[name].get_family())\n else:\n print(\"invalid name\")\n else:\n print(\"No full-time employees to view\")\n\ndef Exit():\n global bool\n bool=0\ndef choices(argument):\n switcher = {\n 1: addEmployee,\n 2: addFullTimeEmployee,\n 3: EmployeeAvgSal,\n 4: FTEmpAvgSal,\n 5: EmpCount,\n 6: FTEmpCount,\n 7: ViewEmployee,\n 8: ViewFTEmployee,\n 9: Exit\n }\n # Get the function from switcher dictionary\n func = switcher.get(int(argument), lambda: \"Invalid choice\")\n func()\nwhile(bool!=0):\n choice =input(\"Enter your choice\")\n choices(choice)\n\n","sub_path":"ICP/ICP3/ICP3.py","file_name":"ICP3.py","file_ext":"py","file_size_in_byte":4481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"77636791","text":"#!/usr/bin/env python\n# encoding: utf-8\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport urllib\nimport json\n\nfrom flask import request, url_for\n\nfrom gstack import helpers\nfrom gstack import controllers\nfrom gstack import app, authentication\nfrom gstack.services import requester\nfrom gstack.controllers import errors\n\n\ndef _add_network(authorization, args=None):\n command = 'createSecurityGroup'\n if not args:\n args = {}\n\n cloudstack_response = requester.make_request(\n command,\n args,\n authorization.client_id,\n authorization.client_secret\n )\n\n return cloudstack_response\n\n\ndef _delete_network(authorization, projectid, network):\n args = {'command': 'listSecurityGroups'}\n network_response = controllers.get_item_with_name(\n authorization, network, args, 'securitygroup')\n if not network_response:\n return None\n\n securitygroup_id = network_response['id']\n\n args = {\n 'id': securitygroup_id\n }\n\n return requester.make_request(\n 'deleteSecurityGroup',\n args,\n authorization.client_id,\n authorization.client_secret\n )\n\n\ndef _cloudstack_network_to_gce(cloudstack_response):\n response = {}\n response['kind'] = 'compute#network'\n response['id'] = cloudstack_response['id']\n response['name'] = cloudstack_response['name']\n response['description'] = cloudstack_response['description']\n response['selfLink'] = urllib.unquote_plus(\n request.base_url) + '/' + response['name']\n\n return response\n\n\ndef _create_populated_network_response(projectid, networks=None):\n if not networks:\n networks = []\n\n populated_response = {\n 'kind': 'compute#networkList',\n 'selfLink': request.base_url,\n 'id': 'projects/' + projectid + '/global/networks',\n 'items': networks\n }\n return populated_response\n\n\ndef get_network_by_name(authorization, network):\n args = {'command': 'listSecurityGroups'}\n return controllers.get_item_with_name(authorization, network, args, 'securitygroup')\n\n\n@app.route('/compute/v1/projects//global/networks', methods=['GET'])\n@authentication.required\ndef listnetworks(projectid, authorization):\n args = {'command': 'listSecurityGroups'}\n kwargs = {}\n items = controllers.describe_items(\n authorization, args, 'securitygroup',\n _cloudstack_network_to_gce, **kwargs)\n\n populated_response = _create_populated_network_response(\n projectid,\n items\n )\n return helpers.create_response(data=populated_response)\n\n\n@app.route('/compute/v1/projects//global/networks/', methods=['GET'])\n@authentication.required\ndef getnetwork(projectid, authorization, network):\n func_route = url_for('getnetwork', projectid=projectid, network=network)\n args = {'command': 'listSecurityGroups'}\n kwargs = {}\n return controllers.get_item_with_name_or_error(\n authorization, network, args, 'securitygroup', func_route,\n _cloudstack_network_to_gce, **kwargs)\n\n\n@app.route('/compute/v1/projects//global/networks', methods=['POST'])\n@authentication.required\ndef addnetwork(authorization, projectid):\n data = json.loads(request.data)\n args = {}\n args['name'] = data['name']\n args['description'] = data['description']\n\n network_result = _add_network(authorization, args)\n\n if 'errortext' in network_result['createsecuritygroupresponse']:\n populated_response = {\n 'kind': 'compute#operation',\n 'operationType': 'insert',\n 'targetLink': '',\n 'status': 'DONE',\n 'progress': 100,\n 'error': {\n 'errors': [{\n 'code': 'RESOURCE_ALREADY_EXISTS',\n 'message': 'The resource \\'projects/\\'' + projectid + '/global/networks/' + args['name']\n }]\n }\n }\n else:\n populated_response = {\n 'kind': 'compute#operation',\n 'operationType': 'insert',\n 'targetLink': urllib.unquote_plus(\n helpers.get_root_url() + url_for(\n 'getnetwork',\n projectid=projectid,\n network=data['name']\n )\n ),\n 'status': 'DONE',\n 'progress': 100\n }\n\n return helpers.create_response(data=populated_response)\n\n\n@app.route('/compute/v1/projects//global/networks/', methods=['DELETE'])\n@authentication.required\ndef deletenetwork(projectid, authorization, network):\n response = _delete_network(authorization, projectid, network)\n\n if not response:\n func_route = url_for(\n 'getnetwork',\n projectid=projectid,\n network=network\n )\n return errors.resource_not_found(func_route)\n\n populated_response = {\n 'kind': 'compute#operation',\n 'operationType': 'delete',\n 'targetLink': '',\n 'status': 'DONE',\n 'progress': 100\n }\n\n return helpers.create_response(data=populated_response)\n","sub_path":"gstack/controllers/networks.py","file_name":"networks.py","file_ext":"py","file_size_in_byte":5824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"221264361","text":"\"\"\"\nA simple FIFO queue for jobs.\n\"\"\"\n\nimport bson\nimport copy\nimport pymongo\nimport datetime\n\nfrom .. import config\nfrom .jobs import Job\nfrom .gears import get_gear\n\nlog = config.log\n\nJOB_STATES = [\n 'pending', # Job is queued\n 'running', # Job has been handed to an engine and is being processed\n 'failed', # Job has an expired heartbeat (orphaned) or has suffered an error\n 'complete', # Job has successfully completed\n 'cancelled' # Job has been cancelled (via a bulk job cancellation)\n]\n\nJOB_STATES_ALLOWED_MUTATE = [\n 'pending',\n 'running',\n]\n\nJOB_TRANSITIONS = [\n 'pending --> running',\n 'pending --> cancelled',\n 'running --> failed',\n 'running --> complete',\n]\n\n# How many times a job should be retried\ndef max_attempts():\n return config.get_item('queue', 'max_retries')\n\n# Should a job be retried when explicitly failed.\n# Does not affect orphaned jobs.\ndef retry_on_explicit_fail():\n return config.get_item('queue', 'retry_on_fail')\n\ndef valid_transition(from_state, to_state):\n return (from_state + ' --> ' + to_state) in JOB_TRANSITIONS or from_state == to_state\n\nclass Queue(object):\n\n @staticmethod\n def mutate(job, mutation):\n \"\"\"\n Validate and save a job mutation\n \"\"\"\n\n if job.state not in JOB_STATES_ALLOWED_MUTATE:\n raise Exception('Cannot mutate a job that is ' + job.state + '.')\n\n if 'state' in mutation and not valid_transition(job.state, mutation['state']):\n raise Exception('Mutating job from ' + job.state + ' to ' + mutation['state'] + ' not allowed.')\n\n # Any modification must be a timestamp update\n mutation['modified'] = datetime.datetime.utcnow()\n\n # Create an object with all the fields that must not have changed concurrently.\n job_query = {\n '_id': bson.ObjectId(job.id_),\n 'state': job.state,\n }\n\n result = config.db.jobs.update_one(job_query, {'$set': mutation})\n if result.modified_count != 1:\n raise Exception('Job modification not saved')\n\n # If the job did not succeed, check to see if job should be retried.\n if 'state' in mutation and mutation['state'] == 'failed' and retry_on_explicit_fail():\n job.state = 'failed'\n Queue.retry(job)\n\n @staticmethod\n def retry(job, force=False):\n \"\"\"\n Given a failed job, either retry the job or fail it permanently, based on the attempt number.\n Can override the attempt limit by passing force=True.\n \"\"\"\n\n if job.attempt >= max_attempts() and not force:\n log.info('Permanently failed job %s (after %d attempts)', job.id_, job.attempt)\n return\n\n if job.state != 'failed':\n raise Exception('Can only retry a job that is failed')\n\n # Race condition: jobs should only be marked as failed once a new job has been spawned for it (if any).\n # No transactions in our database, so we can't do that.\n # Instead, make a best-hope attempt.\n check = config.db.jobs.find_one({'previous_job_id': job.id_ })\n if check is not None:\n found = Job.load(check)\n raise Exception('Job ' + job.id_ + ' has already been retried as ' + str(found.id_))\n\n new_job = copy.deepcopy(job)\n new_job.id_ = None\n new_job.previous_job_id = job.id_\n\n new_job.state = 'pending'\n new_job.attempt += 1\n\n now = datetime.datetime.utcnow()\n new_job.created = now\n new_job.modified = now\n\n new_id = new_job.insert()\n log.info('respawned job %s as %s (attempt %d)', job.id_, new_id, new_job.attempt)\n\n # If job is part of batch job run, update batch jobs list\n result = config.db.batch.update_one(\n {'jobs': job.id_},\n {'$pull': {'jobs': job.id_}, '$push': {'jobs': new_id}}\n )\n if result.modified_count == 1:\n log.info('updated batch job list, replacing {} with {}'.format(job.id_, new_id))\n\n return new_id\n\n @staticmethod\n def start_job(tags=None):\n \"\"\"\n Atomically change a 'pending' job to 'running' and returns it. Updates timestamp.\n Will return None if there are no jobs to offer. Searches for jobs marked \"now\"\n most recently first, followed by unmarked jobs in FIFO order if none are found.\n\n Potential jobs must match at least one tag, if provided.\n \"\"\"\n\n query = { 'state': 'pending', 'now': True }\n\n if tags is not None:\n query['tags'] = {'$in': tags }\n\n # First look for jobs marked \"now\" sorted by modified most recently\n # Mark as running if found\n result = config.db.jobs.find_one_and_update(\n query,\n\n { '$set': {\n 'state': 'running',\n 'modified': datetime.datetime.utcnow()}\n },\n sort=[('modified', -1)],\n return_document=pymongo.collection.ReturnDocument.AFTER\n )\n\n # If no jobs marked \"now\" are found, search again ordering by FIFO\n if result is None:\n query['now'] = {'$ne': True}\n result = config.db.jobs.find_one_and_update(\n query,\n\n { '$set': {\n 'state': 'running',\n 'modified': datetime.datetime.utcnow()}\n },\n sort=[('modified', 1)],\n return_document=pymongo.collection.ReturnDocument.AFTER\n )\n\n if result is None:\n return None\n\n job = Job.load(result)\n\n # Return if there is a job request already, else create one\n if job.request is not None:\n log.info('Job ' + job.id_ + ' already has a request, so not generating')\n return job\n\n else:\n # Generate, save, and return a job request.\n request = job.generate_request(get_gear(job.gear_id))\n result = config.db.jobs.find_one_and_update(\n {\n '_id': bson.ObjectId(job.id_)\n },\n { '$set': {\n 'request': request }\n },\n return_document=pymongo.collection.ReturnDocument.AFTER\n )\n\n if result is None:\n raise Exception('Marked job as running but could not generate and save formula')\n\n return Job.load(result)\n\n @staticmethod\n def search(containers, states=None, tags=None):\n \"\"\"\n Search the queue for jobs that mention at least one of a set of containers and (optionally) match some set of states or tags.\n Currently, all containers must be of the same type.\n\n @param containers: an array of ContainerRefs\n @param states: an array of strings\n @param tags: an array of strings\n \"\"\"\n\n # Limitation: container types must match.\n type1 = containers[0].type\n for container in containers:\n if container.type != type1:\n raise Exception('All containers passed to Queue.search must be of the same type')\n\n query = {'inputs.id': {'$in': [x.id for x in containers]}, 'inputs.type': type1}\n\n if states is not None and len(states) > 0:\n query['state'] = {\"$in\": states}\n\n if tags is not None and len(tags) > 0:\n query['tags'] = {\"$in\": tags}\n\n # For now, mandate reverse-crono sort\n return config.db.jobs.find(query).sort([\n ('modified', pymongo.DESCENDING)\n ])\n\n @staticmethod\n def get_statistics():\n \"\"\"\n Return a variety of interesting information about the job queue.\n \"\"\"\n\n # Count jobs by state\n result = config.db.jobs.aggregate([{\"$group\": {\"_id\": \"$state\", \"count\": {\"$sum\": 1}}}])\n # Map mongo result to a useful object\n by_state = {s: 0 for s in JOB_STATES}\n by_state.update({r['_id']: r['count'] for r in result})\n\n # Count jobs by tag grouping\n result = list(config.db.jobs.aggregate([{\"$group\": {\"_id\": \"$tags\", \"count\": {\"$sum\": 1}}}]))\n by_tag = []\n for r in result:\n by_tag.append({'tags': r['_id'], 'count': r['count']})\n\n # Count jobs that will not be retried\n permafailed = config.db.jobs.count({\"attempt\": {\"$gte\": max_attempts()}, \"state\":\"failed\"})\n\n return {\n 'by-state': by_state,\n 'by-tag': by_tag,\n 'permafailed': permafailed\n }\n\n @staticmethod\n def scan_for_orphans():\n \"\"\"\n Scan the queue for orphaned jobs, mark them as failed, and possibly retry them.\n Should be called periodically.\n \"\"\"\n\n orphaned = 0\n\n while True:\n doc = config.db.jobs.find_one_and_update(\n {\n 'state': 'running',\n 'modified': {'$lt': datetime.datetime.utcnow() - datetime.timedelta(seconds=100)},\n },\n {\n '$set': {\n 'state': 'failed', },\n },\n return_document=pymongo.collection.ReturnDocument.AFTER\n )\n\n if doc is None:\n break\n else:\n orphaned += 1\n j = Job.load(doc)\n Queue.retry(j)\n\n return orphaned\n","sub_path":"api/jobs/queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":9362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"88694683","text":"# -*- coding: utf-8 -*-\n# time: 19-3-7 上午11:30\nimport sys\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QDesktopWidget, QPushButton, QHBoxLayout, QWidget, QToolTip\nfrom PyQt5.QtGui import QIcon, QFont\n\n\nclass TestMain(QMainWindow):\n\n def __init__(self, parent=None):\n super().__init__(parent)\n self.resize(400, 200)\n self.status = self.statusBar()\n self.status.showMessage(\"这是一个状态栏\", 5000)\n self.setWindowTitle(\"这是关闭窗口的例子\")\n self.closeBtn = QPushButton(\"关闭\")\n self.closeBtn.clicked.connect(self.onBtnClicked)\n layout = QHBoxLayout()\n layout.addWidget(self.closeBtn)\n\n main_frame = QWidget()\n main_frame.setLayout(layout)\n self.setCentralWidget(main_frame)\n self.initUI()\n self.center()\n\n def center(self):\n geometry = QDesktopWidget().screenGeometry()\n size = self.geometry()\n self.move((geometry.width()-size.width())/2, (geometry.height()-size.height())/2)\n\n def onBtnClicked(self):\n sender = self.sender()\n print(sender.text(), \"被按下了\")\n app = QApplication.instance()\n app.quit()\n\n def initUI(self):\n self.setToolTip(\"这是一个
气泡提示
\")\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n app.setWindowIcon(QIcon(\"./cartoon1.ico\"))\n ui = TestMain()\n ui.show()\n sys.exit(app.exec())\n","sub_path":"PureWin.py","file_name":"PureWin.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"55513657","text":"from flask import Flask, render_template, jsonify\nimport sqlite3\nimport pandas as pd\nimport MouseTools as mt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.neural_network import MLPRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nimport pickle\n\napp = Flask(__name__)\n\n\n\n@app.route(\"/\")\ndef index():\n\n return \"Hello World\"\n\n@app.route(\"/site\")\ndef site():\n\n return render_template(\"index.html\", title=\"Test Title\")\n\n@app.route(\"/site2\")\ndef site2():\n\n return render_template(\"otherpage.html\")\n\n\n@app.route(\"/current-data\")\n@app.route(\"/current-data/\")\ndef current_data(id=None):\n\n # import pathlib\n # print(pathlib.Path().absolute())\n conn = sqlite3.connect(\"Spring 2021/Week 4/waits.db\")\n c = conn.cursor()\n\n if id is None:\n rows = c.execute(\"SELECT * FROM details\")\n else:\n rows = c.execute(\"SELECT * FROM details WHERE id = ?\", (id,))\n\n columns = [description[0] for description in rows.description]\n \n data = []\n\n for row in rows.fetchall():\n\n temp = {}\n\n for column, value in zip(columns, row):\n temp[column] = value\n\n data.append(temp)\n\n conn.close()\n\n return jsonify(data)\n\n\n\n@app.route(\"/all-data/id/\")\n@app.route(\"/all-data/park/\")\n@app.route(\"/all-data/weather/\")\ndef all_data(id=None, park=None, weather=None):\n\n # import pathlib\n # print(pathlib.Path().absolute())\n conn = sqlite3.connect(\"Spring 2021/Week 4/waits.db\")\n c = conn.cursor()\n\n if id is not None:\n rows = c.execute(f\"SELECT * FROM id_{id}\")\n elif park is not None:\n rows = c.execute(f\"SELECT * FROM park_{park}\")\n elif weather is not None:\n rows = c.execute(f\"SELECT * FROM weather_{weather}\")\n\n columns = [description[0] for description in rows.description]\n \n data = []\n\n for row in rows.fetchall():\n\n temp = {}\n\n for column, value in zip(columns, row):\n temp[column] = value\n\n data.append(temp)\n\n conn.close()\n\n return jsonify(data)\n\n\n@app.route(\"/predict/\")\ndef predict(id):\n\n conn = sqlite3.connect(\"../Week 4/waits.db\")\n all_models = pickle.load(open(\"wdw_models.pkl\", \"rb\"))\n\n current_times = pd.read_sql(f\"SELECT wait_time FROM details WHERE dest_id = {mt.ids.WDW_ID} and id != {id}\", conn)\n current_times['wait_time'] = current_times['wait_time'].apply(lambda x: -1 if x == None else x)\n \n pred = all_models[id].predict(current_times['wait_time'].ravel().reshape(1,-1))\n\n conn.close()\n\n return jsonify({\"id\":id, \"predicted_time\": pred[0], \"periods_ahead\": all_models[\"periods_ahead\"]})\n\n \n\n\ndef create_models(periods_ahead = 1):\n\n conn = sqlite3.connect(\"../Week 4/waits.db\")\n details = pd.read_sql(f\"SELECT * FROM details WHERE dest_id = {mt.ids.WDW_ID}\", conn)\n\n wdw_df = pd.DataFrame()\n\n for i, row in details.iterrows():\n \n df = pd.read_sql(f\"SELECT * FROM id_{row['id']}\", conn, index_col=\"last_pull\").drop(\"status\", axis=1)\n df['wait_time'] = df['wait_time'].apply(lambda x: -1 if x == None else x)\n df = df.rename({\"wait_time\": row['id']}, axis=1)\n \n if not wdw_df.empty:\n wdw_df = wdw_df.merge(df, how=\"outer\", left_index=True, right_index=True)\n else:\n wdw_df = df\n \n wdw_df = wdw_df.fillna(-1)\n\n\n all_models = {\"periods_ahead\":periods_ahead}\n for y_id in wdw_df.columns:\n this_df = wdw_df[wdw_df[y_id] != -1]\n if this_df.empty:\n continue\n\n X = this_df[this_df.columns.difference([y_id])].drop(this_df.index[0:periods_ahead])\n y = this_df[y_id].shift(-periods_ahead).dropna().ravel()\n \n clf = RandomForestRegressor().fit(X, y)\n all_models[y_id] = clf\n\n conn.close()\n\n pickle.dump(all_models, open(\"wdw_models.pkl\", \"wb\"))\n\n return all_models\n \n \ncreate_models(1)\n\nif __name__ == \"__main__\":\n\n app.run(debug=True)\n \n\n","sub_path":"Spring 2021/Week 7/__init__prep.py","file_name":"__init__prep.py","file_ext":"py","file_size_in_byte":4014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"474934944","text":"'''@file encoder_decoder_cnn.py\ncontains de EncoderDecoderCNN class'''\n\nimport tensorflow as tf\nimport model\nfrom nabu.neuralnetworks.components import layer, ops\nimport numpy as np\nimport pdb\n\nclass SegCapsLSTMPooled(model.Model):\n '''A capsule encoder decoder model adapted from\n @article{lalonde2018capsules,\n title={Capsules for Object Segmentation},\n author={LaLonde, Rodney and Bagci, Ulas},\n journal={arXiv preprint arXiv:1804.04241},\n year={2018}\n }\n https://github.com/lalonderodney/SegCaps/blob/master/capsnet.py\n '''\n\n def _get_outputs(self, inputs, input_seq_length, is_training):\n '''\n Create the variables and do the forward computation\n\n Args:\n inputs: the inputs to the neural network, this is a list of\n [batch_size x time x ...] tensors\n input_seq_length: The sequence lengths of the input utterances, this\n is a [batch_size] vector\n is_training: whether or not the network is in training mode\n\n Returns:\n - output, which is a [batch_size x time x ...] tensors\n '''\n use_bias = self.conf['use_bias'] == 'True'\n leaky_softmax = self.conf['leaky_softmax'] == 'True'\n shared = self.conf['shared'] == 'True'\n kernel_size = map(int, self.conf['kernel_size'].split(' '))\n num_filters = self.conf['num_filters']\n num_capsules_lst = map(int, self.conf['num_capsules_lst'].split(' '))\n capsule_dim_lst = map(int, self.conf['capsule_dim_lst'].split(' '))\n t_reduction_rate = int(self.conf['t_reduction_rate'])\n f_reduction_rate = int(self.conf['f_reduction_rate'])\n probability_fn = None\n if leaky_softmax:\n probability_fn = ops.leaky_softmax\n\n # code not available for multiple inputs!!\n if len(inputs) > 1:\n raise 'The implementation of DCNN expects 1 input and not %d' % len(inputs)\n else:\n inputs = inputs[0]\n\n with tf.variable_scope(self.scope):\n if is_training and float(self.conf['input_noise']) > 0:\n inputs = inputs + tf.random_normal(\n tf.shape(inputs),\n stddev=float(self.conf['input_noise']))\n\n\n logits = tf.identity(inputs, 'inputs')\n input_seq_length = tf.identity(input_seq_length, 'input_seq_length')\n\n\n # Convolution\n batch_size = logits.shape[0].value\n num_freq = logits.shape[2].value\n #logits.set_shape([batch_size, 100, num_freq])\n logits = tf.expand_dims(logits, -1)\n\n # Layer 1: Just a conventional Conv2D layer\n conv1 = tf.layers.conv2d(logits, filters=num_filters, kernel_size=kernel_size, strides=1, padding='same', activation=tf.nn.relu, name='conv1')\n\n # Reshape layer to be 1 capsule x [filters] atoms\n conv1_reshaped = tf.reshape(conv1, [batch_size, -1, num_freq, 1, 16])\n\n # Layer 1: Primary Capsule: Conv cap with routing 1\n primary_caps = layer.EncDecCapsulePooled(kernel_size=kernel_size, num_capsules=num_capsules_lst[0], capsule_dim=capsule_dim_lst[0],\n pool_filter=(2,2), padding='SAME',\n routing_iters=0, use_bias=use_bias, shared=shared, name='primarycaps')(conv1_reshaped)\n\n # Layer 2: Convolutional Capsule\n conv_cap_2_1 = layer.EncDecCapsule(kernel_size=kernel_size, num_capsules=num_capsules_lst[1], capsule_dim=capsule_dim_lst[1], strides=(1,1), padding='SAME',\n routing_iters=3, use_bias=use_bias, shared=shared, name='conv_cap_2_1')(primary_caps)\n\n # Layer 2: Convolutional Capsule\n pool_filter = [1,1]\n if t_reduction_rate == 1:\n pool_filter[0] = 2\n if f_reduction_rate == 1:\n pool_filter[1] = 2\n conv_cap_2_2 = layer.EncDecCapsulePooled(kernel_size=kernel_size, num_capsules=num_capsules_lst[2], capsule_dim=capsule_dim_lst[2],\n pool_filter=pool_filter, padding='SAME',\n routing_iters=3, use_bias=use_bias, shared=shared, name='conv_cap_2_2')(conv_cap_2_1)\n\n # Layer 3: Convolutional Capsule\n conv_cap_3_1 = layer.EncDecCapsule(kernel_size=kernel_size, num_capsules=num_capsules_lst[3], capsule_dim=capsule_dim_lst[3], strides=(1,1), padding='SAME',\n routing_iters=3, use_bias=use_bias, shared=shared, name='conv_cap_3_1')(conv_cap_2_2)\n\n # Layer 3: Convolutional Capsule\n conv_cap_3_2 = layer.EncDecCapsulePooled(kernel_size=kernel_size, num_capsules=num_capsules_lst[4], capsule_dim=capsule_dim_lst[4],\n pool_filter=(2,2), padding='SAME',\n routing_iters=3, use_bias=use_bias, shared=shared, name='conv_cap_3_2')(conv_cap_3_1)\n\n # Layer 4: Convolutional Capsule\n conv_cap_4_1 = layer.EncDecCapsule(kernel_size=kernel_size, num_capsules=num_capsules_lst[5], capsule_dim=capsule_dim_lst[5], strides=(1,1), padding='SAME',\n routing_iters=3, use_bias=use_bias, shared=shared, name='conv_cap_4_1')(conv_cap_3_2)\n\n # Layer 1 Up: Deconvolutional Capsule\n t_out = tf.shape(conv_cap_3_1)[1]\n freq_out = conv_cap_3_1.shape[2]\n deconv_cap_1_1 = layer.EncDecCapsule(kernel_size=kernel_size, num_capsules=num_capsules_lst[6], capsule_dim=capsule_dim_lst[6], transpose=True,\n strides=(2, 2), padding='SAME', routing_iters=3, use_bias=use_bias, shared=shared,\n name='deconv_cap_1_1')(conv_cap_4_1, t_out, freq_out)\n # Skip connection\n up_1 = tf.concat([deconv_cap_1_1, conv_cap_3_1], axis=-2, name='up_1')\n\n # Layer 1 Up: Deconvolutional Capsule\n deconv_cap_1_2 = layer.EncDecCapsule(kernel_size=kernel_size, num_capsules=num_capsules_lst[7], capsule_dim=capsule_dim_lst[7], strides=(1,1),\n padding='SAME', routing_iters=3, use_bias=use_bias, shared=shared, name='deconv_cap_1_2')(up_1)\n\n # Layer 2 Up: Deconvolutional Capsule\n t_out = tf.shape(conv_cap_2_1)[1]\n freq_out = conv_cap_2_1.shape[2]\n strides = [1, 1]\n if t_reduction_rate == 1:\n strides[0] = 2\n if f_reduction_rate == 1:\n strides[1] = 2\n deconv_cap_2_1 = layer.EncDecCapsule(kernel_size=kernel_size, num_capsules=num_capsules_lst[8], capsule_dim=capsule_dim_lst[8], transpose=True,\n strides=strides, padding='SAME', routing_iters=3, use_bias=use_bias, shared=shared,\n name='deconv_cap_2_1')(deconv_cap_1_2, t_out, freq_out)\n\n # Skip connection\n up_2 = tf.concat([deconv_cap_2_1, conv_cap_2_1], axis=-2, name='up_2')\n\n # Layer 2 Up: Deconvolutional Capsule\n deconv_cap_2_2 = layer.EncDecCapsule(kernel_size=kernel_size, num_capsules=num_capsules_lst[9], capsule_dim=capsule_dim_lst[9], strides=(1,1),\n padding='SAME', routing_iters=3, use_bias=use_bias, shared=shared, name='deconv_cap_2_2')(up_2)\n\n # Layer 3 Up: Deconvolutional Capsule\n t_out = tf.shape(conv1_reshaped)[1]\n freq_out = conv1_reshaped.shape[2]\n deconv_cap_3_1 = layer.EncDecCapsule(kernel_size=kernel_size, num_capsules=num_capsules_lst[10], capsule_dim=capsule_dim_lst[10], transpose=True,\n strides=(2, 2), padding='SAME', routing_iters=3, use_bias=use_bias, shared=shared,\n name='deconv_cap_3_1')(deconv_cap_2_2, t_out, freq_out)\n\n # Skip connection\n up_3 = tf.concat([deconv_cap_3_1, conv1_reshaped], axis=-2, name='up_3')\n\n # Layer 4: Convolutional Capsule: 1x1\n seg_caps = layer.EncDecCapsule(kernel_size=kernel_size, num_capsules=num_capsules_lst[11], capsule_dim=capsule_dim_lst[11], strides=(1,1), padding='SAME',\n routing_iters=3, use_bias=use_bias, shared=shared, name='seg_caps')(up_3)\n\n\n output = seg_caps\n # Include frequency dimension\n output = tf.reshape(\n output,\n [batch_size,\n -1,\n num_freq, num_capsules_lst[-1]*capsule_dim_lst[-1]]\n )\n\n return output\n","sub_path":"nabu/neuralnetworks/models/seg_caps_lstm_pooled.py","file_name":"seg_caps_lstm_pooled.py","file_ext":"py","file_size_in_byte":8912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"428754481","text":"from sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom Sastrawi.Stemmer.StemmerFactory import StemmerFactory\nfrom sklearn.model_selection import cross_validate\nimport pandas as pd\nimport numpy as np\nimport pickle\n\ndef preprocessing(kalimat):\n\n # mengubah seluruh huruf pada kalimat menjadi lower-case\n kalimat = str(kalimat).lower()\n\n # menghilangkan tanda-baca pada kalimat\n tanda_baca = ['\\n', '\"', \",\", '.', '-', '!', '?', \"'\", \")\", \"(\", '%', '$']\n for tanda in tanda_baca:\n kalimat = kalimat.replace(tanda, ' ')\n\n # menghilangkan stopwords pada kalimat yang diambil dari list stopwords pada link\n # https://github.com/masdevid/ID-Stopwords\n with open(\"stopwords-id.txt\") as f:\n stop_words = f.readlines()\n\n stop_words = [x.strip('\\n') for x in stop_words]\n\n z = kalimat.split()\n for kata in list(z):\n if kata in stop_words:\n z.remove(kata)\n kalimat = ' '.join(z)\n\n # melakukan stemming untuk setiap kata pada kalimat dengan menggunakan library Sastrawi di python\n factory = StemmerFactory()\n stemmer = factory.create_stemmer()\n kalimat = stemmer.stem(kalimat)\n\n return kalimat\n\nif __name__ == '__main__':\n\n # Load dari text, sementara menggunakan file reader built-in , somehow pandas read tidak memberikan jumlah data sama dengan\n # jumlah baris sebanyak 1000 untuk pos.txt dan neg.txt dengan asumsi satu baris adalah satu data untuk sentimen analysis\n with open('pos.txt') as f:\n data_pos = f.readlines()\n\n with open('neg.txt') as f:\n data_neg = f.readlines()\n\n data_pre = data_pos + data_neg\n\n # Lakukan tahap prepocessing pada data dengan memanggil function preprocessing\n data = []\n for kalimat in data_pre:\n data.append(preprocessing(kalimat))\n\n # buat pandas dataframe dari data yang telah diprepocessing dengan nama label corpus\n df = pd.DataFrame(data)\n df.columns = ['corpus']\n\n # Tambahkan label 0 untuk positif pada data 1-1000 dan label 1 untuk negatif pada data 1001-2000\n df['label'] = 0\n df.loc[df['label'].index > 1000, 'label'] = 1\n\n # Inisiasi x1 sebagai fitur dan y1 sebagai target\n\n x1 = df['corpus']\n y1 = df['label']\n\n\n # Lakukan feature extraction pada text dengan menggunakan metode TfidfVectorizer\n\n tf = TfidfVectorizer(use_idf=True, analyzer='word', min_df=5, sublinear_tf=True, smooth_idf=True)\n x1 = tf.fit_transform(x1)\n\n #Simpan model TfidfVectorizer untuk digunakan pada API\n with open(\"model_tf.pkl\", \"wb\") as file_handler:\n pickle.dump(tf, file_handler)\n\n # Komparasi model RandomForest dan DecisionTree dengan menggunakan cross validation sebanyak 5 cv dengan metode scoring\n # berupa rata-rata akurasi, precision dan recall dari cross validation\n\n models = [\n RandomForestClassifier(n_estimators=100, random_state=0),\n DecisionTreeClassifier(random_state=0)\n ]\n\n for model in models:\n acc = []\n model_name = model.__class__.__name__\n scoring = {'acc': 'accuracy',\n 'prec': 'precision_macro',\n 'rec': 'recall_macro'}\n scores = cross_validate(model, x1, y1, scoring=scoring,\n cv=5)\n print('Model : {}'.format(model_name))\n print('Accuracy : {}'.format(np.mean(scores['test_acc'])))\n print('AVG precision : {}'.format(np.mean(scores['test_prec'])))\n print('AVG recall : {}'.format(np.mean(scores['test_rec'])))\n\n # Hasil yang didapatkan memperlihatkan bahwa RandomForest memberikan nilai rata-rata akurasi, precision dan recall yang\n # lebih baik dibandingkan Decision Tree dimana nilai rata2 RF berkisar di nilai 0.67 dan decision tree di nilai 0.61\n # Dimana performa dengan nilai tersebut dapat dikatakan cukup untuk Sentiment Analysis dimana pada umumnya model Sentiment\n # Analusis dikatakan baik apabila memiliki nilai akurasi berkisar antara 0.7 sampai dengan 0.8 Selain itu jika kita set min_df menjadi 0.1\n # mengeluarkan peringatan \"After pruning, no terms remain.\" yang tidak ada term atau kata yang muncul lebih dari 10% di dokumen (mungkin dokumen terlalu umum\n # dan tidak spesifik sehingga mempersulit proses klasifikasi ? mungkin bisa diatasi dengan memakai custom vocabulary)\n\n clf = RandomForestClassifier(n_estimators=100, random_state=0)\n clf.fit(x1, y1)\n\n # Simpan Model Random Forest Classifier\n with open(\"model_RF.pkl\", \"wb\") as file_handler:\n pickle.dump(clf, file_handler)\n\n\n\n\n\n\n\n","sub_path":"kinionline_SA.py","file_name":"kinionline_SA.py","file_ext":"py","file_size_in_byte":4622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"653139636","text":"#!/usr/bin/python3\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nX = np.array([[6], [8], [10], [14], [18]])\nY = [7,9,13,17.5,18]\n\nplt.plot(X,Y, '.')\nplt.axis([0, 25, 0, 25])\nplt.show()\n","sub_path":"regression lineaire/exo1.py","file_name":"exo1.py","file_ext":"py","file_size_in_byte":192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"481142900","text":"import argparse\n\nfrom serum import Environment\n\nfrom vico import Config\nfrom vico.argument_provider import ArgumentProvider\nfrom vico.database import DocumentDatabase\nfrom vico.preprocess import remove_useless_tags, html_tokenize, lowercase\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(\n 'Perform preprocessing of documents')\n parser.add_argument('--database-path', help='path to sqlite database', default='../data/all_documents.sqlite')\n return parser.parse_args()\n\n\ndef run(database_path):\n config = Config(database_path=database_path)\n ArgumentProvider.config = config\n with Environment(ArgumentProvider):\n db = DocumentDatabase()\n documents = db.load_documents()\n cleaned_documents = remove_useless_tags(documents)\n tokenized_documents = html_tokenize(cleaned_documents)\n lowercase_documents = lowercase(tokenized_documents)\n db.save_documents(lowercase_documents)\n\n\nif __name__ == '__main__':\n run(**vars(parse_arguments()))\n\n","sub_path":"vico/scripts/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"517760113","text":"import torch\nimport itertools\nimport numpy as np\nimport sys\nimport csv\nimport random\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\nclass CompositeMHA(torch.nn.Module):\n def __init__(self, num_heads, in_proj_weight, in_proj_bias, out_proj):\n super().__init__()\n self.in_proj_weight = in_proj_weight\n self.in_proj_bias = in_proj_bias\n self.out_proj = out_proj\n self.num_heads = num_heads\n\n def forward(self, query, key, value, mask):\n if not (query is key and key is value):\n raise NotImplementedError(\n \"query, key and value must be the same Tensor for now.\"\n )\n if mask is not None:\n raise NotImplementedError(\"mask is currently not supported.\")\n\n query_projected = torch.nn.functional.linear(\n query, self.in_proj_weight, self.in_proj_bias\n )\n\n batch_size = query_projected.size(0)\n embed_dim = query_projected.size(2)\n head_dim = embed_dim // (self.num_heads * 3)\n\n query, key, value = query_projected.chunk(3, -1)\n\n query = query.view(batch_size, -1, self.num_heads, head_dim).transpose(1, 2)\n key = key.view(batch_size, -1, self.num_heads, head_dim).transpose(1, 2)\n value = value.view(batch_size, -1, self.num_heads, head_dim).transpose(1, 2)\n\n # the output of sdp = (batch, num_heads, seq_len, head_dim)\n attn, _ = torch.nn.functional._scaled_dot_product_attention(\n query,\n key,\n value,\n attn_mask=None,\n dropout_p=0.0,\n need_attn_weights=False,\n is_causal=False,\n )\n\n attn = attn.transpose(1, 2).reshape(\n batch_size, -1, self.num_heads * head_dim\n )\n # Match return signature of nn.MHA\n return self.out_proj(attn), None\n\n\ndef build_composite_mha_from_nn_mha(pt):\n assert pt._qkv_same_embed_dim\n in_proj_weight = pt.in_proj_weight\n assert in_proj_weight is not None\n assert pt.batch_first\n return CompositeMHA(pt.num_heads, pt.in_proj_weight, pt.in_proj_bias, pt.out_proj)\n\n\ndef generate_rand_batch(batch_size, max_sequence_len, embed_dimension, pad_percentage=None, dtype=torch.float16, device=\"cuda\"):\n if not pad_percentage:\n return torch.randn(batch_size, max_sequence_len, embed_dimension, dtype=dtype, device=device), None\n # Really slow but should work\n seq_len_list = [int(max_sequence_len * (1 - random.gauss(pad_percentage, 0.01))) for _ in range(batch_size)]\n # Make random ele max length\n seq_len_list[random.randint(0, batch_size - 1)] = max_sequence_len\n # print(f\"Theoretical padding: {pad_percentage} actual: {1 - (sum(seq_len_list) / (batch_size * max_sequence_len))}\")\n return torch.nested.nested_tensor([\n torch.randn(seq_len, embed_dimension, dtype=dtype, device=device) for seq_len in seq_len_list]), seq_len_list\n\n\ndef benchmark_torch_function(iters, f, *args, **kwargs):\n if f is None:\n return None\n f(*args, **kwargs)\n torch.cuda.synchronize()\n start_event = torch.cuda.Event(enable_timing=True)\n end_event = torch.cuda.Event(enable_timing=True)\n start_event.record()\n for _ in range(iters):\n f(*args, **kwargs)\n end_event.record()\n torch.cuda.synchronize()\n return (start_event.elapsed_time(end_event) * 1.0e-3) / iters\n\n\ndef run_timing(iters, batch_size, embed_dimension, num_heads, max_sequence_len, pad_percentage, enable_math, enable_flash, writer):\n with torch.backends.cuda.sdp_kernel(enable_math=enable_math, enable_flash=enable_flash):\n with torch.inference_mode():\n dropout_p = 0.0\n mask = None\n\n pt = torch.nn.MultiheadAttention(\n embed_dim=embed_dimension, num_heads=num_heads, batch_first=True, dropout=dropout_p\n )\n npt = pt.eval().half().cuda()\n cpt = build_composite_mha_from_nn_mha(npt)\n x, lengths = generate_rand_batch(batch_size, max_sequence_len, embed_dimension, pad_percentage)\n pt_output, _ = pt(x, x, x, mask)\n cpt_output, _ = cpt(x, x, x, mask)\n\n # First order sanity check. Not a replacement for rigorous tests.\n if pt_output.is_nested and cpt_output.is_nested:\n for a, b in zip(pt_output.unbind(), cpt_output.unbind()):\n assert torch.allclose(a, b, atol=1e-3, rtol=1e-3)\n else:\n assert torch.allclose(pt_output, cpt_output, atol=1e-3, rtol=1e-3)\n\n pt_time = benchmark_torch_function(iters, npt, x, x, x, mask) * 1e3\n cp_time = benchmark_torch_function(iters, cpt, x, x, x, mask) * 1e3\n results = {}\n results[\"max_sequence_len\"] = max_sequence_len\n results[\"num_heads\"] = num_heads\n results[\"embed_dimension\"] = embed_dimension\n results[\"pt_time\"] = pt_time\n results[\"cp_time\"] = cp_time\n results[\"speedup\"] = pt_time / cp_time\n results[\"dtype\"] = str(x.dtype)\n results[\"enable_math\"] = str(enable_math)\n results[\"enable_flash\"] = str(enable_flash)\n writer.writerow(results)\n\n\ndef main():\n iters = 100\n seed = 123\n np.random.seed(seed)\n torch.manual_seed(seed)\n\n headers = [\"max_sequence_len\", \"num_heads\", \"embed_dimension\", \"pt_time\",\n \"cp_time\", \"speedup\", \"dtype\", \"enable_math\", \"enable_flash\"]\n writer = csv.DictWriter(sys.stdout, headers)\n writer.writeheader()\n\n batch_size = 64\n pad_percentage = 0.5\n\n for (enable_math, enable_flash) in [(False, True), (True, False), (True, True)]:\n for num_heads, max_seq_len in itertools.product([2, 4, 8, 16, 32], [64, 128, 256]):\n run_timing(iters, batch_size, 1024, num_heads, max_seq_len,\n pad_percentage, enable_math, enable_flash, writer)\n run_timing(iters, batch_size, 1024, num_heads, max_seq_len,\n pad_percentage, enable_math, enable_flash, writer)\n run_timing(iters, batch_size, 1024, num_heads, max_seq_len,\n pad_percentage, enable_math, enable_flash, writer)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"benchmarks/transformer/sdp.py","file_name":"sdp.py","file_ext":"py","file_size_in_byte":6228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"479126990","text":"\"\"\"The MySQL dialect.\n\nFor now the only change is the parsing of comments.\nhttps://dev.mysql.com/doc/refman/8.0/en/differences-from-ansi.html\n\"\"\"\n\nfrom sqlfluff.core.parser import (\n BaseSegment,\n Ref,\n AnyNumberOf,\n Sequence,\n OneOf,\n Bracketed,\n RegexLexer,\n CommentSegment,\n NamedParser,\n CodeSegment,\n StringParser,\n SymbolSegment,\n Delimited,\n RegexParser,\n)\nfrom sqlfluff.core.dialects import load_raw_dialect\n\nansi_dialect = load_raw_dialect(\"ansi\")\nmysql_dialect = ansi_dialect.copy_as(\"mysql\")\n\nmysql_dialect.patch_lexer_matchers(\n [\n RegexLexer(\n \"inline_comment\",\n r\"(-- |#)[^\\n]*\",\n CommentSegment,\n segment_kwargs={\"trim_start\": (\"-- \", \"#\")},\n )\n ]\n)\n\n# Reserve USE, FORCE & IGNORE\nmysql_dialect.sets(\"unreserved_keywords\").difference_update([\"FORCE\", \"IGNORE\", \"USE\"])\nmysql_dialect.sets(\"reserved_keywords\").update([\"FORCE\", \"IGNORE\", \"USE\"])\n\nmysql_dialect.replace(\n QuotedIdentifierSegment=NamedParser(\n \"back_quote\",\n CodeSegment,\n name=\"quoted_identifier\",\n type=\"identifier\",\n trim_chars=(\"`\",),\n ),\n LiteralGrammar=ansi_dialect.get_grammar(\"LiteralGrammar\").copy(\n insert=[\n Ref(\"DoubleQuotedLiteralSegment\"),\n ]\n ),\n PostTableExpressionGrammar=Sequence(\n OneOf(\"IGNORE\", \"FORCE\", \"USE\"),\n OneOf(\"INDEX\", \"KEY\"),\n Sequence(\"FOR\", OneOf(\"JOIN\"), optional=True),\n Bracketed(Ref(\"ObjectReferenceSegment\")),\n ),\n)\n\nmysql_dialect.add(\n DoubleQuotedLiteralSegment=NamedParser(\n \"double_quote\",\n CodeSegment,\n name=\"quoted_literal\",\n type=\"literal\",\n trim_chars=('\"',),\n ),\n AtSignLiteralSegment=NamedParser(\n \"atsign\",\n CodeSegment,\n name=\"atsign_literal\",\n type=\"literal\",\n trim_chars=(\"@\",),\n ),\n)\n\n\n@mysql_dialect.segment(replace=True)\nclass CreateTableStatementSegment(\n ansi_dialect.get_segment(\"CreateTableStatementSegment\") # type: ignore\n):\n \"\"\"Create table segment.\n\n https://dev.mysql.com/doc/refman/8.0/en/create-table.html\n \"\"\"\n\n match_grammar = ansi_dialect.get_segment(\n \"CreateTableStatementSegment\"\n ).match_grammar.copy(\n insert=[\n AnyNumberOf(\n Sequence(\n Ref.keyword(\"DEFAULT\", optional=True),\n Ref(\"ParameterNameSegment\"),\n Ref(\"EqualsSegment\"),\n OneOf(Ref(\"LiteralGrammar\"), Ref(\"ParameterNameSegment\")),\n ),\n ),\n ],\n )\n\n\nmysql_dialect.add(\n DoubleForwardSlashSegment=StringParser(\n \"//\", SymbolSegment, name=\"doubleforwardslash\", type=\"statement_terminator\"\n ),\n DoubleDollarSignSegment=StringParser(\n \"$$\", SymbolSegment, name=\"doubledollarsign\", type=\"statement_terminator\"\n ),\n AtSignSignSegment=StringParser(\n \"@\", SymbolSegment, name=\"atsign\", type=\"user_designator\"\n ),\n OutputParameterSegment=StringParser(\n \"OUT\", SymbolSegment, name=\"inputparameter\", type=\"parameter_direction\"\n ),\n InputParameterSegment=StringParser(\n \"IN\", SymbolSegment, name=\"outputparameter\", type=\"parameter_direction\"\n ),\n InputOutputParameterSegment=StringParser(\n \"INOUT\", SymbolSegment, name=\"inputoutputparameter\", type=\"parameter_direction\"\n ),\n ProcedureParameterGrammar=OneOf(\n Sequence(\n OneOf(\n Ref(\"OutputParameterSegment\"),\n Ref(\"InputParameterSegment\"),\n Ref(\"InputOutputParameterSegment\"),\n optional=True,\n ),\n Ref(\"ParameterNameSegment\", optional=True),\n Ref(\"DatatypeSegment\"),\n ),\n Ref(\"DatatypeSegment\"),\n ),\n LocalVariableNameSegment=RegexParser(\n r\"`?[a-zA-Z0-9_]*`?\",\n CodeSegment,\n name=\"declared_variable\",\n type=\"variable\",\n ),\n SessionVariableNameSegment=RegexParser(\n r\"[@][a-zA-Z0-9_]*\",\n CodeSegment,\n name=\"declared_variable\",\n type=\"variable\",\n ),\n)\n\nmysql_dialect.replace(\n DelimiterSegment=OneOf(Ref(\"SemicolonSegment\"), Ref(\"TildeSegment\")),\n TildeSegment=StringParser(\n \"~\", SymbolSegment, name=\"tilde\", type=\"statement_terminator\"\n ),\n ParameterNameSegment=RegexParser(\n r\"`?[A-Za-z0-9_]*`?\", CodeSegment, name=\"parameter\", type=\"parameter\"\n ),\n)\n\nmysql_dialect.insert_lexer_matchers(\n [\n RegexLexer(\n \"atsign\",\n r\"[@][a-zA-Z0-9_]*\",\n CodeSegment,\n ),\n ],\n before=\"code\",\n)\n\n\n@mysql_dialect.segment()\nclass DeclareStatement(BaseSegment):\n \"\"\"DECLARE statement.\n\n mysql: https://dev.mysql.com/doc/refman/8.0/en/declare-local-variable.html\n mysql: https://dev.mysql.com/doc/refman/8.0/en/declare-handler.html\n mysql: https://dev.mysql.com/doc/refman/8.0/en/declare-condition.html\n https://dev.mysql.com/doc/refman/8.0/en/declare-cursor.html\n \"\"\"\n\n type = \"declare_statement\"\n\n match_grammar = OneOf(\n Sequence(\n \"DECLARE\",\n Ref(\"NakedIdentifierSegment\"),\n \"CURSOR\",\n \"FOR\",\n Ref(\"StatementSegment\"),\n ),\n Sequence(\n \"DECLARE\",\n OneOf(\"CONTINUE\", \"EXIT\", \"UNDO\"),\n \"HANDLER\",\n \"FOR\",\n OneOf(\n \"SQLEXCEPTION\",\n \"SQLWARNING\",\n Sequence(\"NOT\", \"FOUND\"),\n Sequence(\n \"SQLSTATE\",\n Ref.keyword(\"VALUE\", optional=True),\n Ref(\"QuotedLiteralSegment\"),\n ),\n OneOf(\n Ref(\"QuotedLiteralSegment\"),\n Ref(\"NumericLiteralSegment\"),\n Ref(\"NakedIdentifierSegment\"),\n ),\n ),\n Sequence(Ref(\"StatementSegment\")),\n ),\n Sequence(\n \"DECLARE\",\n Ref(\"NakedIdentifierSegment\"),\n \"CONDITION\",\n \"FOR\",\n OneOf(Ref(\"QuotedLiteralSegment\"), Ref(\"NumericLiteralSegment\")),\n ),\n Sequence(\n \"DECLARE\",\n Ref(\"LocalVariableNameSegment\"),\n Ref(\"DatatypeSegment\"),\n Sequence(\n Ref.keyword(\"DEFAULT\"),\n OneOf(\n Ref(\"QuotedLiteralSegment\"),\n Ref(\"NumericLiteralSegment\"),\n Ref(\"FunctionSegment\"),\n ),\n optional=True,\n ),\n ),\n )\n\n\n@mysql_dialect.segment(replace=True)\nclass StatementSegment(ansi_dialect.get_segment(\"StatementSegment\")): # type: ignore\n \"\"\"Overriding StatementSegment to allow for additional segment parsing.\"\"\"\n\n parse_grammar = ansi_dialect.get_segment(\"StatementSegment\").parse_grammar.copy(\n insert=[\n Ref(\"DelimiterStatement\"),\n Ref(\"CreateProcedureStatementSegment\"),\n Ref(\"DeclareStatement\"),\n Ref(\"SetAssignmentStatementSegment\"),\n Ref(\"IfExpressionStatement\"),\n Ref(\"CallStoredProcedureSegment\"),\n ],\n )\n\n\n@mysql_dialect.segment()\nclass DelimiterStatement(BaseSegment):\n \"\"\"DELIMITER statement.\"\"\"\n\n type = \"delimiter_statement\"\n\n match_grammar = Ref.keyword(\"DELIMITER\")\n\n\n@mysql_dialect.segment()\nclass CreateProcedureStatementSegment(BaseSegment):\n \"\"\"A `CREATE PROCEDURE` statement.\n\n mysql: https://dev.mysql.com/doc/refman/8.0/en/create-procedure.html\n \"\"\"\n\n type = \"create_procedure_statement\"\n\n match_grammar = Sequence(\n \"CREATE\",\n Ref(\"DefinerSegment\", optional=True),\n \"PROCEDURE\",\n Ref(\"FunctionNameSegment\"),\n Ref(\"ProcedureParameterListGrammar\", optional=True),\n Ref(\"CommentClauseSegment\", optional=True),\n Ref(\"CharacteristicStatement\", optional=True),\n Ref(\"FunctionDefinitionGrammar\"),\n )\n\n\n@mysql_dialect.segment(replace=True)\nclass FunctionDefinitionGrammar(BaseSegment):\n \"\"\"This is the body of a `CREATE FUNCTION` statement.\"\"\"\n\n match_grammar = Ref(\"TransactionStatementSegment\")\n\n\n@mysql_dialect.segment()\nclass CharacteristicStatement(BaseSegment):\n \"\"\"A Characteristics statement for functions/procedures.\"\"\"\n\n type = \"characteristic_statement\"\n\n match_grammar = Sequence(\n OneOf(\"DETERMINISTIC\", Sequence(\"NOT\", \"DETERMINISTIC\")),\n Sequence(\"LANGUAGE\", \"SQL\", optional=True),\n OneOf(\n Sequence(\"CONTAINS\", \"SQL\", optional=True),\n Sequence(\"NO\", \"SQL\", optional=True),\n Sequence(\"READS\", \"SQL\", \"DATA\", optional=True),\n Sequence(\"MODIFIES\", \"SQL\", \"DATA\", optional=True),\n optional=True,\n ),\n Sequence(\"SQL\", \"SECURITY\", OneOf(\"DEFINER\", \"INVOKER\"), optional=True),\n )\n\n\n@mysql_dialect.segment(replace=True)\nclass CreateFunctionStatementSegment(BaseSegment):\n \"\"\"A `CREATE FUNCTION` statement.\n\n mysql: https://dev.mysql.com/doc/refman/8.0/en/create-procedure.html\n \"\"\"\n\n type = \"create_function_statement\"\n\n match_grammar = Sequence(\n \"CREATE\",\n Ref(\"DefinerSegment\", optional=True),\n \"FUNCTION\",\n Ref(\"FunctionNameSegment\"),\n Ref(\"FunctionParameterListGrammar\", optional=True),\n Sequence(\n \"RETURNS\",\n Ref(\"DatatypeSegment\"),\n ),\n Ref(\"CommentClauseSegment\", optional=True),\n Ref(\"CharacteristicStatement\"),\n Ref(\"FunctionDefinitionGrammar\"),\n )\n\n\n@mysql_dialect.segment(replace=True)\nclass DropStatementSegment(BaseSegment):\n \"\"\"A `DROP` statement.\"\"\"\n\n type = \"drop_statement\"\n\n match_grammar = Sequence(\n \"DROP\",\n OneOf(\n \"TABLE\",\n \"VIEW\",\n \"USER\",\n \"FUNCTION\",\n \"PROCEDURE\",\n ),\n Ref(\"IfExistsGrammar\", optional=True),\n Ref(\"TableReferenceSegment\"),\n )\n\n\n@mysql_dialect.segment()\nclass ProcedureParameterListGrammar(BaseSegment):\n \"\"\"The parameters for a procedure ie. `(in/out/inout name datatype)`.\"\"\"\n\n match_grammar = Bracketed(\n Delimited(\n Ref(\"ProcedureParameterGrammar\"),\n delimiter=Ref(\"CommaSegment\"),\n optional=True,\n ),\n )\n\n\n@mysql_dialect.segment()\nclass SetAssignmentStatementSegment(BaseSegment):\n \"\"\"A `SET` statement.\n\n mysql: https://dev.mysql.com/doc/refman/8.0/en/set-variable.html\n \"\"\"\n\n type = \"set_statement\"\n\n match_grammar = Sequence(\n \"SET\",\n OneOf(Ref(\"SessionVariableNameSegment\"), Ref(\"LocalVariableNameSegment\")),\n Ref(\"EqualsSegment\"),\n AnyNumberOf(\n Ref(\"QuotedLiteralSegment\"),\n Ref(\"DoubleQuotedLiteralSegment\"),\n Ref(\"SessionVariableNameSegment\"),\n Ref(\"LocalVariableNameSegment\"),\n Ref(\"FunctionSegment\"),\n ),\n )\n\n\n@mysql_dialect.segment(replace=True)\nclass TransactionStatementSegment(BaseSegment):\n \"\"\"A `COMMIT`, `ROLLBACK` or `TRANSACTION` statement.\n\n mysql: https://dev.mysql.com/doc/refman/8.0/en/commit.html\n mysql: https://dev.mysql.com/doc/refman/8.0/en/begin-end.html\n \"\"\"\n\n type = \"transaction_statement\"\n\n match_grammar = OneOf(\n Sequence(\"START\", \"TRANSACTION\"),\n Sequence(\n Sequence(\n Ref(\"SingleIdentifierGrammar\"), Ref(\"ColonSegment\"), optional=True\n ),\n Sequence(\n \"BEGIN\",\n Ref.keyword(\"WORK\", optional=True),\n Ref(\"StatementSegment\"),\n ),\n ),\n Sequence(\n \"LEAVE\",\n Ref(\"SingleIdentifierGrammar\", optional=True),\n ),\n Sequence(\n \"COMMIT\",\n Ref.keyword(\"WORK\", optional=True),\n Sequence(\"AND\", Ref.keyword(\"NO\", optional=True), \"CHAIN\", optional=True),\n ),\n Sequence(\n \"ROLLBACK\",\n Ref.keyword(\"WORK\", optional=True),\n ),\n Sequence(\n \"END\",\n Ref(\"SingleIdentifierGrammar\", optional=True),\n ),\n )\n\n\n@mysql_dialect.segment()\nclass IfExpressionStatement(BaseSegment):\n \"\"\"IF-THEN-ELSE-ELSEIF-END IF statement.\n\n mysql:https://dev.mysql.com/doc/refman/8.0/en/if.html\n \"\"\"\n\n type = \"if_then_statement\"\n\n match_grammar = AnyNumberOf(\n Sequence(\n \"IF\",\n Ref(\"ExpressionSegment\"),\n \"THEN\",\n Ref(\"StatementSegment\"),\n ),\n Sequence(\n \"ELSEIF\",\n Ref(\"ExpressionSegment\"),\n \"THEN\",\n Ref(\"StatementSegment\"),\n ),\n Sequence(\"ELSE\", Ref(\"StatementSegment\"), optional=True),\n )\n\n\n@mysql_dialect.segment()\nclass DefinerSegment(BaseSegment):\n \"\"\"This is the body of a `CREATE FUNCTION` statement.\"\"\"\n\n type = \"definer_segment\"\n\n match_grammar = Sequence(\n \"DEFINER\",\n Ref(\"EqualsSegment\"),\n Ref(\"SingleIdentifierGrammar\"),\n Ref(\"AtSignLiteralSegment\"),\n Ref(\"SingleIdentifierGrammar\"),\n )\n\n\n@mysql_dialect.segment()\nclass CallStoredProcedureSegment(BaseSegment):\n \"\"\"This is a CALL statement used to execute a stored procedure.\n\n mysql: https://dev.mysql.com/doc/refman/8.0/en/call.html\n \"\"\"\n\n type = \"call_segment\"\n\n match_grammar = Sequence(\n \"CALL\",\n OneOf(\n Ref(\"SingleIdentifierGrammar\"),\n Ref(\"QuotedIdentifierSegment\"),\n ),\n Bracketed(\n AnyNumberOf(\n Delimited(\n Ref(\"QuotedLiteralSegment\"),\n Ref(\"NumericLiteralSegment\"),\n Ref(\"DoubleQuotedLiteralSegment\"),\n Ref(\"SessionVariableNameSegment\"),\n Ref(\"LocalVariableNameSegment\"),\n Ref(\"FunctionSegment\"),\n ),\n ),\n ),\n )\n","sub_path":"src/sqlfluff/dialects/dialect_mysql.py","file_name":"dialect_mysql.py","file_ext":"py","file_size_in_byte":13955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"380657605","text":"#!/usr/bin/env python3\n\nimport sys, utils, random # import the modules we will need\n\nutils.check_version((3,7)) # make sure we are running at least Python 3.7\nutils.clear() # clear the screen\n\n\nprint('Greetings!')\ncolors = ['red','orange','yellow','green','blue','violet','purple'] # this is an array of strings.\nplay_again = '' #A declaration of a constant variable as by default we don't know if the player wants to play again or not\nbest_count = sys.maxsize # the biggest number\nwhile (play_again != 'n' and play_again != 'no'): #a while loop wit two conditions\n match_color = random.choice(colors) #picks a random color in the array\n count = 0\n color = '' # we reset the value assigned to color to hide the answer \n while (color != match_color):\n color = input(\"\\nWhat is my favorite color? \") #\\n is a special code that adds a new line . here we answer the question\n color = color.lower().strip()\n count += 1 #since we have answered the question once it adds one to count and it will do it again if this while loop gets executed again.\n if (color == match_color):\n print('Correct!') \n else:\n print('Sorry, try again. You have guessed {guesses} times.'.format(guesses=count))\n print('\\nYou guessed it in {0} tries!'.format(count))\n if (count < best_count): \n print('This was your best guess so far!')\n best_count = count #it keeps track of our most number of guesses and if we play again and guess in less tries then that becomes the best count\n play_again = input(\"\\nWould you like to play again? \").lower().strip()\nprint('Thanks for playing!')","sub_path":"main10.py","file_name":"main10.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"323199146","text":"import os\nimport logging\n\nfrom chalicelib import get_cron_range\nfrom chalice import Chalice, Response, BadRequestError\nfrom datetime import datetime\n\napp = Chalice(app_name=\"cron_range\")\n\nlog_format = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\napp.log.setLevel(os.getenv(\"LOG_LEVEL\", \"DEBUG\"))\n\nfor handler in app.log.handlers:\n\thandler.setFormatter(log_format)\n\nMAX_EXECUTIONS = int(os.getenv(\"MAX_EXECUTIONS\", 100))\n\n\n@app.route(\"/\", methods=[\"POST\"], content_types=[\"application/json\"], cors=True)\ndef index_handler():\n\ttry:\n\t\trequest_json = app.current_request.json_body\n\t\tcron = request_json[\"cron\"]\n\t\texecutions = int(request_json.get(\"executions\", 10))\n\t\tdate_time = request_json.get(\"datetime\", datetime.now())\n\n\t\tapp.log.info(f\"Got a request with cron: '{cron}'; Executions: '{executions}'; Datetime '{date_time}'\")\n\n\t\tif executions > MAX_EXECUTIONS:\n\t\t\tapp.log.debug(f\"Number of executions '{executions}' is greater than\"\n\t\t\t f\" '{MAX_EXECUTIONS}'. Defaulting to 100 executions\")\n\t\t\texecutions = MAX_EXECUTIONS\n\n\t\tranges = get_cron_range(\n\t\t\tnum_items=executions,\n\t\t\tcron_expression=cron,\n\t\t\tstart_datetime=date_time\n\t\t)\n\n\t\treturn Response(\n\t\t\tstatus_code=200,\n\t\t\tbody={\"cron_ranges\": ranges}\n\t\t)\n\n\texcept KeyError:\n\t\treturn Response(\n\t\t\tstatus_code=400,\n\t\t\tbody={\"message\": \"Make sure that JSON contains 'cron' and 'executions' key:value pairs\"}\n\t\t)\n\n\texcept ValueError:\n\t\treturn Response(\n\t\t\tstatus_code=400,\n\t\t\tbody={\"message\": \"Field 'executions' must be a number\"}\n\t\t)\n\n\texcept BadRequestError:\n\t\treturn Response(\n\t\t\tstatus_code=400,\n\t\t\tbody={\"message\": \"Malformed JSON\"}\n\t\t)\n\n\texcept Exception as ex:\n\t\treturn Response(\n\t\t\tstatus_code=400,\n\t\t\tbody={\"message\": str(ex)}\n\t\t)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"5200854","text":"\"\"\"\nQueries two git repositories to extract D3M Exline pipeline\ndefinitions and meta data identifying the problems they're intended\nto tackle.\n\"\"\"\n\nfrom collections import defaultdict\nimport subprocess\nfrom typing import Dict, List, Set, Optional, Tuple\nimport os\nimport glob\nimport re\nimport shutil\nimport itertools\nimport filecmp\n\n# Helper functions\n####################\n\n\ndef copy_files_by_glob(\n pattern: str, save_dir: str, collector: Optional[Dict[str, Set[str]]]\n):\n \"\"\"\n Parameters\n ----------\n pattern\n The glob pattern to match to\n save_dir\n The directory path to save all files matching `pattern` to.\n collector\n If supplied, will collect all file paths matching `pattern`\n into a set mapped to the file paths' file name.\n \"\"\"\n if not os.path.isdir(save_dir):\n os.makedirs(save_dir)\n\n for path in glob.glob(pattern):\n file_name = path.split(\"/\")[-1]\n if collector is not None:\n collector[file_name].add(path)\n save_path = f\"{save_dir}/{file_name}\"\n shutil.copy(path, save_path)\n\n\ndef cmpfilelist(filepaths: List[str], shallow: bool = True):\n \"\"\"\n Compares the contents of all possible pairs of files\n in `filepaths`. Similar to `filecmp.cmpfiles` but takes\n a list of filepaths rather than two directories, so the\n files in `filepaths` can be in any directories, not limited\n to just two.\n\n Returns three lists of file names: `match`, `mismatch`,\n `errors`. `match` contains the list of file pair tuples that\n match, `mismatch` contains the names of those that don’t,\n and `errors` lists the names of files which could not be\n compared.\n \"\"\"\n match: List[Tuple[str, str]] = []\n mismatch: List[Tuple[str, str]] = []\n errors: List[Tuple[str, str]] = []\n for path_a, path_b in itertools.combinations(filepaths, 2):\n try:\n if filecmp.cmp(path_a, path_b, shallow):\n match.append((path_a, path_b))\n else:\n mismatch.append((path_a, path_b))\n except Exception:\n errors.append((path_a, path_b))\n return match, mismatch, errors\n\n\n# Define script data\n####################\n\ndata_dir = \"script-data/exline_repos\" # dir to clone the git repos to.\nsave_dir = \"dump/exlines\" # dir to save the final exline pipeline and meta files to.\ncurrent_d3m_version = \"v2019.6.7\"\npython_path_field_pattern = re.compile(r\"['|\\\"]python_path['|\\\"]:\\s.?['|\\\"](.+)['|\\\"],\")\npython_paths_to_exclude_from_exlines: Set[str] = {\n # \"OutputDataframe\" is just a debug primitive. It is not an exline.\n \"d3m.primitives.data_transformation.data_cleaning.OutputDataframe\"\n}\n\n# Define git repositories data\n####################\n\n# repo with master list of Exline primitives\nexline_primitive_list_repo: Dict[str, str] = {\n \"url\": \"https://github.com/uncharted-distil/distil-primitives.git\",\n \"save_dir\": f\"{data_dir}/primitives_list\",\n \"target_dir\": f\"{data_dir}/primitives_list/distil/primitives\",\n}\n\n# repo with Exline pipeline definitions\npipelines_repo: Dict[str, str] = {\n \"url\": \"https://gitlab.com/datadrivendiscovery/primitives.git\",\n \"save_dir\": f\"{data_dir}/pipelines\",\n \"target_dir\": f\"{data_dir}/pipelines/{current_d3m_version}/Distil\",\n}\n\n# Clone the git repos\n####################\n\nfor repo_meta in (exline_primitive_list_repo, pipelines_repo):\n if not os.path.isfile(f\"{repo_meta['save_dir']}/README.md\"):\n # This repo has not been cloned yet.\n print(f\"Cloning repo '{repo_meta['url']}'\")\n subprocess.call([\"git\", \"clone\", repo_meta[\"url\"], repo_meta[\"save_dir\"]])\n\n# Get the python paths of the Exline primitives from `exline_primitive_list_repo`\n####################\n\nprimitive_python_paths: Set[str] = set()\nfor primitive_file_path in glob.glob(\n f\"{exline_primitive_list_repo['target_dir']}/*.py\"\n):\n with open(primitive_file_path, \"r\") as prim_file:\n for line in prim_file.readlines():\n matches = python_path_field_pattern.search(line)\n if matches:\n primitive_python_paths.add(matches[1])\n\nprimitive_python_paths = primitive_python_paths.difference(\n python_paths_to_exclude_from_exlines\n)\n\nprint(f\"Found {len(primitive_python_paths)} Exline primitive_python_paths.\")\n\n# Now get the pipelines for those repos, along with the problem for each pipeline,\n# saving them to `save_dir`.\n####################\n\npipeline_paths_by_pipeline_name: defaultdict = defaultdict(set)\nmeta_paths_by_meta_name: defaultdict = defaultdict(set)\n\nfor python_path in primitive_python_paths:\n primitive_dir = f\"{pipelines_repo['target_dir']}/{python_path}\"\n assert os.path.isdir(primitive_dir), f\"'{primitive_dir}' is not a directory\"\n pipelines_glob = f\"{primitive_dir}/*/pipelines/*.json\"\n pipelines_meta_glob = f\"{primitive_dir}/*/pipelines/*.meta\"\n\n if not os.path.isdir(save_dir):\n os.makedirs(save_dir)\n\n copy_files_by_glob(pipelines_glob, save_dir, pipeline_paths_by_pipeline_name)\n copy_files_by_glob(pipelines_meta_glob, save_dir, meta_paths_by_meta_name)\n\nprint(f\"Saved all exline pipeline and meta files to '{save_dir}'.\")\n\n# As a check, compare all the pipeline and meta files that have the same name,\n# to see which ones are identical or not.\n####################\n\nfor paths in pipeline_paths_by_pipeline_name.values():\n if len(paths) > 1:\n match, mismatch, errors = cmpfilelist(paths, shallow=False)\n assert len(mismatch) == 0 and len(errors) == 0, (\n \"Some pipeline file contents did not match or could not be compared, \"\n \"even though they had the same pipeline id\"\n )\n\nfor paths in meta_paths_by_meta_name.values():\n if len(paths) > 1:\n match, mismatch, errors = cmpfilelist(paths, shallow=False)\n assert len(mismatch) == 0 and len(errors) == 0, (\n \"Some meta file contents did not match or could not be compared, \"\n \"even though they had the same pipeline id\"\n )\n\nprint(\n \"Integrity checks passed. All pipeline and meta files with duplicate pipeline ID \"\n \"file names have identical contents.\"\n)\nprint(\"Finished.\")\n","sub_path":"analytics/scripts/get_exline_pipelines.py","file_name":"get_exline_pipelines.py","file_ext":"py","file_size_in_byte":6158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"147991682","text":"UPDATABLE = 't_updatable'\nVISIBLE = 't_visible'\nPHYSIC = 't_physic'\nLOCATABLE = 't_locatable'\n\n# singleton objects\nRENDERER = 't_renderer'\nRESSOURCEMANAGER = 't_ressourcemanager'\nCOLLISIONMANAGER = 't_collisionmanager'\nEVENTMANAGER = 't_eventmanager'\nGRID = 't_grid'\nBLOCKER = 't_blocker'","sub_path":"locals/Tags.py","file_name":"Tags.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"203393541","text":"import pygame\r\nimport sys\r\nfrom pygame.locals import *\r\n\r\n# This demo is based on and inspired by Bytes for Lunch.\r\n# Website: https://bytesforlunch.wordpress.com/2011/10/04/videogame-programming-a-simple-scrollable-background-with-python-and-pygame/\r\n# Accessed: 15.10.2016\r\n\r\n# this version of the scrolling program has consolidated the positional\r\n# calculations into one function. This secures more clarity of code\r\n# which is always a good thing.\r\ndef calculate_pos(direction, x, width):\r\n if (x * direction) < 0:\r\n return(width * direction) + x\r\n elif x == width or x == 0:\r\n return(-width) * direction\r\n else:\r\n return (width - (x* direction))* -direction\r\n\r\n\t\t\r\npygame.init()\r\nclock = pygame.time.Clock()\r\n\r\nSCREEN_WIDTH = 300\r\nSCREEN_HEIGHT = 200\r\nscreen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32)\r\n\r\nback_1 = pygame.image.load('image_for_scroll.jpg').convert()\r\nback_2 = pygame.image.load('image_for_scroll.jpg').convert()\r\n\r\nx1 = 0\r\nn = 1\r\n\r\nwhile True:\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n if event.type == KEYDOWN:\r\n if event.key == K_SPACE:\r\n n *= -1\r\n\r\n # here the new function calculate_pos() is called and it returns the\r\n #position of the second image.\r\n x_pos = calculate_pos(n, x1, SCREEN_WIDTH)\r\n\r\n screen.blit(back_1, (x1, 0))\r\n screen.blit(back_2, (x_pos, 0))\r\n\r\n x1 += n\r\n if x1 == SCREEN_WIDTH or x1 == -SCREEN_WIDTH:\r\n x1 = 0\r\n\r\n clock.tick(40)\r\n pygame.display.flip()","sub_path":"Python/FORR2HF05CU/Lokaverkefni/Sýniverkefni/04_PyGame/04_fourth_scroll.py","file_name":"04_fourth_scroll.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"256191699","text":"#!/usr/bin/env python\n\nimport argparse\ntry:\n from coinbase.wallet.client import Client\nexcept ImportError:\n print('coinbase package is required')\n print('sudo pip install coinbase')\n\nfrom decimal import Decimal\nfrom pprint import pprint\nimport sys\n\n# local import needed for Coinbase authentication\nfrom coinbase_config import API_KEY, API_SECRET\n\n\ndef get_account_ids(accounts):\n \"\"\"\n I only care about ETH and BTC\n return a list of account id's\n \"\"\"\n\n account_id = []\n for account in accounts.data:\n if account['balance']['currency'] in ['BTC', 'ETH']:\n account_id.append(account['id'].encode())\n\n return account_id\n\n\ndef total_bought(account_id, exchange):\n\n all_buys = []\n total = {}\n if exchange == 'coinbase':\n first_page = client.get_buys(account_id)\n all_buys.append(first_page)\n pagination = first_page.pagination\n next_uri = pagination['next_uri']\n if next_uri:\n # Find the starting_after id\n next_page_id = next_uri.split('=')[-1]\n while True:\n next_page = client.get_buys(account_id, starting_after=next_page_id)\n all_buys.append(next_page)\n pagination = next_page.pagination\n next_uri = pagination['next_uri']\n if not next_uri:\n break\n next_page_id = next_uri.split('=')[-1]\n\n for page in all_buys:\n for buy in page.data:\n currency = buy['amount']['currency'].encode()\n if not total.get(currency):\n total[currency] = Decimal()\n total[currency] += Decimal(buy['total']['amount'])\n\n elif exchange == 'gdax':\n history = gdax_actions.account_history(account_id)\n for transaction in history:\n if transaction['transfer_type'] == 'deposit':\n currency = 'asdfasdf'\n if not total.get(currency):\n total[currency] = Decimal()\n total[currency] += Decimal(transaction['total'])\n\n return total\n\ndef wallet_balance(account_ids):\n \"\"\"\n get_account() only returns the amount of crypto in our wallet.\n We want to also account for crypto 'in transit' (the dumb ACH transfer delay)\n \"\"\"\n\n wallets = {}\n for account_id in account_ids:\n\n # Get the total number of crypto currency currently in wallet\n account_info = client.get_account(account_id)\n wallets[account_info['balance']['currency'].encode()] = Decimal(account_info['balance']['amount'].encode())\n all_transactions = client.get_transactions(account_id)\n\n # Find the transactions that are 'pending' and have not been added to wallet\n # only add when its a buy or receiving\n # For example, if a transaction is pending from a coinbase wallet to a different wallet\n # the type will be \"send\"\n pending = []\n for transaction in all_transactions.data:\n if transaction['status'] == 'pending' and transaction['type'] == 'buy':\n pending.append(transaction)\n\n # Iterate through pending transactions and update the totals\n for transaction in pending:\n amount_str = transaction['amount']['amount']\n amount = Decimal(amount_str)\n currency = transaction['amount']['currency']\n wallets.update({currency: wallets[currency] + amount})\n\n return wallets\n\ndef determine_profit(wallet, usd_spent):\n \"\"\"\n Cant think of good var names so w/e.\n usd_spent is a dict containing the amount of USD that was used to purchase BTC/ETH\n \"\"\"\n\n stats = {}\n total_profit = Decimal()\n total_profit_percentage = Decimal()\n total_value = Decimal()\n for currency in wallet:\n if currency == 'BTC':\n pair = 'BTC-USD'\n elif currency == 'ETH':\n pair = 'ETH-USD'\n\n current_price = client.get_spot_price(currency_pair=pair)\n current_price = Decimal(current_price['amount'].encode())\n profit = (wallet[currency] * current_price) - usd_spent[currency]\n value = wallet[currency] * current_price\n profit_percentage = ((wallet[currency] * current_price / usd_spent[currency]) - 1) * 100\n total_profit += profit\n total_profit_percentage += profit_percentage\n total_value += value\n stats.update({currency:{'profit' : profit,\n 'profit_percentage' : profit_percentage,\n 'value': value}\n })\n stats.update({'total':{'profit': total_profit,\n 'profit_percentage': total_profit_percentage,\n 'value': total_value}\n })\n\n return stats\n \n\n\ndef print_summary(wallets, usd_spent):\n\n stats = determine_profit(wallets, usd_spent)\n\n total = usd_spent['BTC'] + usd_spent['ETH']\n print('USD spent on BTC: {}'.format(usd_spent['BTC']))\n print('USD spent on ETH: {}'.format(usd_spent['ETH']))\n print('Total USD spent: {0:.2f}'.format(total))\n print('Total amount of BTC: {}'.format(wallets['BTC']))\n print('Total amount of ETH: {}'.format(wallets['ETH']))\n print('BTC portfolio value: {0:.2f}'.format(stats['BTC']['value']))\n print('ETH portfolio value: {0:.2f}'.format(stats['ETH']['value']))\n print('Total portfolio value: {0:.2f}'.format(stats['total']['value']))\n\n\ndef get_args():\n parser = argparse.ArgumentParser(description='Gives an investment summary. Only tracks GDAX and Coinbase transactions')\n parser.add_argument('--btc', type=Decimal, help='Amount of BTC you currently own')\n parser.add_argument('--eth', type=Decimal, help='Amount of ETH you currently own')\n\n args = parser.parse_args()\n\n return args\n\n\nif __name__ == '__main__':\n \"\"\"\n \"\"\"\n\n args = get_args()\n if args.btc != None:\n total_btc = args.btc\n else:\n total_btc = Decimal()\n\n if args.eth != None:\n total_eth = args.eth\n else:\n total_eth = Decimal()\n\n ###################\n # Coinbase section\n ###################\n\n client = Client(API_KEY, API_SECRET)\n\n accounts = client.get_accounts()\n account_ids = get_account_ids(accounts)\n\n usd_spent = {}\n for account_id in account_ids:\n usd_spent.update(total_bought(account_id, 'coinbase'))\n\n wallets = wallet_balance(account_ids)\n if total_btc:\n wallets.update({'BTC': wallets['BTC']+total_btc})\n if total_eth:\n wallets.update({'ETH': wallets['ETH']+total_eth})\n\n ###############\n # GDAX section\n ###############\n \"\"\"\n account_ids = [1,2]\n accounts = gdax_actions.list_accounts()\n usd_account_id = gdax_actions.select_account(accounts, 'currency', 'USD')['id']\n btc_account_id = gdax_actions.select_account(accounts, 'currency', 'BTC')['id']\n eth_account_id = gdax_actions.select_account(accounts, 'currency', 'ETH')['id']\n usd_spent.update(total_bought(usd_account_id)\n \"\"\"\n \n\n\n # XXX: This is to hide the real values\n #usd_spent = {'BTC': Decimal(1000), 'ETH': Decimal(1000)}\n #if total_btc:\n # wallets.update({'BTC': total_btc})\n #if total_eth:\n # wallets.update({'ETH': total_eth})\n\n print_summary(wallets, usd_spent)\n","sub_path":"investment_status.py","file_name":"investment_status.py","file_ext":"py","file_size_in_byte":7304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"565668746","text":"#encoding=utf-8\r\nfrom multiprocessing.connection import Listener\r\nfrom .transformer import Transformer \r\n\r\naddress = ('localhost', 8888) # family is deduced to be 'AF_INET'\r\nlistener = Listener(address)\r\n\r\n\r\n\r\nwhile True:\r\n conn = listener.accept()\r\n print('connection accepted from', listener.last_accepted)\r\n \r\n T_decision = conn.recv()\r\n print(T_decision)\r\n try:\r\n transformer = Transformer()\r\n for d in S_decision:\r\n (c,f,a) = d\r\n analyst.analyze(c,f,a)\r\n \r\n except Exception as e:\r\n print(e)\r\n finally:\r\n conn.close()\r\n\r\n\r\n\r\nlistener.close()","sub_path":"downsampling/downsample_main.py","file_name":"downsample_main.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"39275114","text":"import os\nimport re\nimport sys\n\n\ndef append_sufix(html, imgs, img_path):\n \"\"\"\n 将一个html文件标签链接到对应的文件\n :param html: html文件名(包含路径)\n :param imgs: img文件名列表(不包含路径)\n :param img_path: img文件列表相对html文件的路径\n :return: None\n \"\"\"\n pattern = [re.compile(r'\"('+re.escape(os.path.splitext(img)[0])+r')(.*)?\"') for img in imgs] # 需要替换html文件中的内容\n\n res_lines = []\n with open(html, \"r\", encoding='utf-8', errors='ignore') as rf:\n raw_lines = rf.readlines() # raw_lines -> 文件的原始内容\n\n if ''.join(raw_lines).find(imgs[0]) != -1:\n print(\"This file has linked once!\", file=sys.stderr)\n return False\n\n for index, line in enumerate(raw_lines):\n for jndex, img in enumerate(imgs):\n line, rplnum = pattern[jndex].subn('\"'+os.path.join(img_path, img)+'\"', line)\n if rplnum != 0: # 我们认为一个图片只有一个与之链接,为了提高速度,不重复regex替换\n del imgs[jndex]\n res_lines.append(line)\n\n process = index / len(raw_lines)\n p_bar = int(50 * process) * '>' + int(50 * (1 - process)) * '-'\n print(\"[%s]%.2f\" % (p_bar, process * 100) + '%', end='\\r') # 显示进度条@shesl\n print(\"\\n\") # 换行\n\n with open(html+'.swp', \"w\", encoding='utf-8') as wf:\n wf.write(''.join(res_lines))\n os.remove(html)\n os.rename(html+\".swp\", html)\n return True\n\n\ndef link_img(directory):\n \"\"\"\n 将一个文件夹中的所有html文件中的的src链接到生成的图片文件\n :param directory: html文件所在的顶级目录\n :return: None\n \"\"\"\n for path, subdirs, files in os.walk(directory):\n # path->路径; subdirs->path路径下的子目录; files->path路径下的文件\n for f in os.listdir(os.path.dirname(path)): # html文件所在的文件夹\n html_file = os.path.join(os.path.dirname(path), f) if f.endswith('.html') else '' # html文件(包含路径名)\n img_files = [ff for ff in files if ff.endswith(('.jpg', '.png', '.gif'))] # 选择可能出现的jpg、png、gif文件(不包含路径名)\n if html_file and img_files and os.path.basename(path).find(os.path.splitext(f)[0]) != -1:\n # html文件存在 and 图片文件存在 and html文件跟图片文件是一一对应的\n print(\"Linking-Img. Working on: \"+html_file)\n append_sufix(html_file, img_files, os.path.basename(path))\n\n\nif __name__ == '__main__':\n link_img(r'D:\\mine\\office\\WorkPlace\\GCBX\\QQChatSourceFile\\mytools')\n","sub_path":"mytools/link_img.py","file_name":"link_img.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"353277019","text":"try:\n import gzip\nexcept ImportError:\n gzip = None\ntry:\n import zlib\nexcept ImportError:\n zlib = None\nimport pickle\nimport sys\n\nfrom huey.exceptions import ConfigurationError\n\n\nif gzip is not None:\n if sys.version_info[0] > 2:\n gzip_compress = gzip.compress\n gzip_decompress = gzip.decompress\n else:\n from io import BytesIO\n\n def gzip_compress(data, comp_level):\n buf = BytesIO()\n fh = gzip.GzipFile(fileobj=buf, mode='wb',\n compresslevel=comp_level)\n fh.write(data)\n fh.close()\n return buf.getvalue()\n\n def gzip_decompress(data):\n buf = BytesIO(data)\n fh = gzip.GzipFile(fileobj=buf, mode='rb')\n try:\n return fh.read()\n finally:\n fh.close()\n\n\nclass Serializer(object):\n def __init__(self, compression=False, compression_level=6, use_zlib=False):\n self.comp = compression\n self.comp_level = compression_level\n self.use_zlib = use_zlib\n if self.comp:\n if self.use_zlib and zlib is None:\n raise ConfigurationError('use_zlib specified, but zlib module '\n 'not found.')\n elif gzip is None:\n raise ConfigurationError('gzip module required to enable '\n 'compression.')\n\n def _serialize(self, data):\n return pickle.dumps(data, pickle.HIGHEST_PROTOCOL)\n\n def _deserialize(self, data):\n return pickle.loads(data)\n\n def serialize(self, data):\n data = self._serialize(data)\n if self.comp:\n if self.use_zlib:\n data = zlib.compress(data, self.comp_level)\n else:\n data = gzip_compress(data, self.comp_level)\n return data\n\n def deserialize(self, data):\n if self.comp:\n if self.use_zlib:\n data = zlib.decompress(data)\n else:\n data = gzip_decompress(data)\n return self._deserialize(data)\n","sub_path":"huey/serializer.py","file_name":"serializer.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"513674064","text":"from django.urls import path\nfrom django.conf.urls import url\n\nfrom . import views\n\napp_name = 'myapp'\n\nurlpatterns = patterns('myapp.views',\n url(r'^mymodel/create/$', view='mymodel_create', name='mymodel_create'),\n)\n\nurlpatterns += patterns('django.views.generic',\n url(r'^(?P\\w+)/create/$','create_update.create_object', name='object_create'),\n url(r'^(?P\\w+)/(?P\\d+)/update/$', 'create_update.update_object', name='object_update' ),\n url(r'^(?P\\w+)/(?P\\d+)/delete/$', 'create_update.delete_object', name='object_delete'), \n url(r'^(?P\\w+)/(?P\\d+)/$', 'list_detail.object_detail', name='object_detail'),\n url(r'^(?P\\w+)/$','list_detail.object_list', name='object_list'),\n)\n\nurlpatterns = [\n\t\n path('hello/', views.test),\n\n url(r'^(?P\\w+)/(?P\\d+)/$', 'my_app.views.my_object_detail', name='object_detail'),\n]\n\n","sub_path":"app/myweb/myapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"211611399","text":"# Hopefully We Actually Start and Finish This One\n\nimport pandas\nimport yolo\n\nimport random\n\nimport os\nfile_path = os.path.dirname(os.path.dirname(__file__)) + '/OpenImagesData'\nprint(file_path)\n\n# Load CSV of training labels\ntrain_labels = pandas.read_csv(file_path + \"\\\\challenge-2019-train-vrd.csv\")\n\n# Load the CSV which has the list of class ID's and their names\nclasses_labels = pandas.read_csv(file_path + \"\\\\challenge-2019-classes-vrd.csv\").set_index(\"ID\")\n\n# Pick a random test image to see what YOLO finds in it\ntest_image_metadata = train_labels.loc[random.randint(0, 374770), :]\n\n# Get that images ID so we can find it in the training data folder\ntest_image_id = test_image_metadata[0]\n\n# Get metadata for test image\nlabel_1 = classes_labels.loc[test_image_metadata[1], \"Name\"]\nlabel_2 = classes_labels.loc[test_image_metadata[2], \"Name\"]\nrelationship = test_image_metadata[11]\n\n# Print that images ID and its labels\nprint(test_image_id)\nprint()\nprint(test_image_metadata[1:3])\nprint()\nprint(label_1 + \" \" + relationship + \" \" + label_2)\n\nprint()\n\n# Yeet\nyolo.main([\"-y=\" + os.path.dirname(__file__) + \"/yolo-object-detection/yolo-coco\", \"-i=\" + file_path + \"/train/\" + test_image_id + \".jpg\"])\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"135036386","text":"import os\nimport csv\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom datetime import datetime, date, time, timedelta\nfrom contapp.models import empresa, tipCuenta, rubCuenta, cuenta, partida, movimiento,impArchivo\nfrom contapp.service import ImpCatalago, errores, CatalogoCuentas,FormImportacion,FormEmpresa\nfrom django.views.generic import ListView,CreateView\n# Create your views here.\nUPLOAD_FOLDER = '/var/www'\n\ndef loginRender(request):\n if request.session.has_key('codemp'):\n del request.session['codemp']\n if request.method == 'POST':\n # if request.session.has_key('codemp'):\n # del request.session['codemp']\n emp = empresa.objects.get(codEmpresa = request.POST.get('codemp'))\n if emp:\n request.session['codemp'] = emp.codEmpresa\n # impp=CrearImportarArchivoView()\n return render(request, \"areaT.html\", {'logeado': True,'empresa': emp} )\n else:\n return render(request, \"Home.html\", {'mensaje': 'Error de inicio de sesión'})\n return render(request, \"Home.html\", {'mensaje': '','empresas':empresa.objects.all(),})\n#UPLOAD_FOLDER = '/var/www/archivos'\n\ndef gestionEmpresa(request):\n # solo crea una nueva empresa y un catalogo por defecto que solo contendra los 6\n # tipos de cuentas\n if request.method == 'POST':\n form = FormEmpresa(request.POST)\n if form.is_valid():\n cd = form.cleaned_data#aqui extraigo solo la informacion del formulario\n emp=empresa()\n emp.nomEmpresa=cd['NOMBRE']\n emp.nit=cd['NIT']\n emp.nrc=cd['NRC']\n emp.save()\n cat=CatalogoCuentas(emp)\n cat.newCatalogo()\n return render(request, \"Home.html\", {'mensaje': '','empresas':empresa.objects.all()})\n else:\n form=FormEmpresa()\n return render(request, \"Empresa/gestionEmpresa.html\", {'form': form}) \n\ndef queryCatalogo(request):\n try:\n emp = empresa.objects.get(codEmpresa = int(request.session['codemp']))\n except Exception :\n emp=\"\" \n if emp:\n return render(request,\"Catalogo/importExito.html\",{'empresa': emp}) \n \n\n\n\ndef importar(request):\n # el try corrobora, si existe una sesion con una empresa\n try:\n emp = empresa.objects.get(codEmpresa = int(request.session['codemp']))\n except Exception :\n emp=\"\"\n # emp = empresa.objects.get(codEmpresa = int(request.session['codemp']))\n if request.method == 'POST':\n if request.session.has_key('codemp'):\n # usr = usuario.objects.get(idUsuario = int(self.request.session['usuario']))\n #archivo importado\n form=impArchivo()\n # empres=empresa.objects.get(codEmpresa=(int(self.request.POST.get('codEmpresa'))))\n form.codEmpresa=emp\n form.archivo=request.FILES.get('archivo')\n # form.date=self.request.POST.get('date')\n form.save()\n dataReader = csv.reader(open(UPLOAD_FOLDER + \"/\" + str(form.archivo)), delimiter=',', quotechar='\"')\n nombreArchivo=str(form.archivo)#self.request.FILES[\"archivo\"].name \n catalogoImportado=ImpCatalago(emp,dataReader,nombreArchivo)\n catalogoImportado.importar()\n # ordenCat=CatalogoCuentas(emp)\n return render(request,'Catalogo/importExito.html',{'empresa': emp})\n # return render(request,'importExito.html',{'cat': ordenCat})\n elif request.session.has_key('codemp') == False: #Usuario no ha iniciado sesión\n return render(request, \"Home.html\", {'mensaje': 'Debe selecionar una empresar para iniciar','empresas':empresa.objects.all(),})\n # confirma si existe una sesioncon una empresa\n elif emp:\n form = FormImportacion()#formulario para la importacion\n return render(request,'Catalogo/ImportarArchivo.html',{'form': form,'empresa': emp})\n else:\n return render(request, \"Home.html\", {'mensaje': 'Debe selecionar una empresa para iniciar','empresas':empresa.objects.all(),}) \n\n\n# class CrearImportarArchivoView(CreateView):\n# model = impArchivo\n# template_name = 'ImportarArchivo.html'\n# fields = ['date', 'codEmpresa','archivo'] #'__all__' #['anio', 'idZona']\n# #ya importa y guarda\n# def form_valid(self,form):\n# \tif self.request.method == 'POST':\n# if self.request.session.has_key('codemp'):\n# usr = usuario.objects.get(idUsuario = int(self.request.session['usuario']))\n# #archivo importado\n# form=impArchivo()\n# empres=empresa.objects.get(codEmpresa=(int(self.request.POST.get('codEmpresa'))))\n# form.codEmpresa=empres\n# form.archivo=self.request.FILES.get('archivo')\n# form.date=self.request.POST.get('date')\n# form.save()\n# dataReader = csv.reader(open(UPLOAD_FOLDER + \"/\" + str(form.archivo)), delimiter=',', quotechar='\"')\n# nombreArchivo=str(form.archivo)#self.request.FILES[\"archivo\"].name \n# catalogoImportado=ImpCatalago(empres,dataReader,nombreArchivo)\n# catalogoImportado.importar()\n# ordenCat=CatalogoCuentas(empres)\n# return render(self.request,'importExito.html',{'cat': ordenCat})\n# elif self.request.session.has_key('codemp') == False: #Usuario no ha iniciado sesión\n# return render(request, \"Home.html\", {'mensaje': 'Debe selecionar una empresar para iniciar','empresas':empresa.objects.all(),})\n# #return render(self.request,\"IniciarSesion.html\", {'mensaje': 'Debe selecionar una empresar para iniciar'}) \n# # errorC=catalogoImportado.importar()\n \n# # if (not errorC.mensaje) and (not errorC.tipo):\n# # return render(self.request,'tabla_dinamica.html')\n# # else:\n# #\ndef regPartida(request):\n try:\n emp = empresa.objects.get(codEmpresa = int(request.session['codemp']))\n except Exception:\n emp=\"\"\n if emp:\n if request.method == 'POST':\n # contiene los codigos de las cuentas a ingresar\n a=request.POST.getlist('cod')\n # contiene los valores de debe para cada cuenta\n b=request.POST.getlist('debe')\n # contiene los valores de haber para cada cuenta\n c=request.POST.getlist('haber')\n # d=[]\n # d.append(len(a))\n # d.append(len(b))\n # d.append(len(c))\n d=len(a)\n formato = \"%Y-%m-%d\" \n \n\n # fecha=request.POST.get('fechaP')\n numPartida=request.POST.get('numeroP')\n # comienza registro de partida\n partid=partida()\n if request.POST.get('fechaP'):\n fecha = datetime.strptime(request.POST.get('fechaP'),formato)\n partid.fecha=fecha\n partid.numPartida=numPartida\n partid.codEmpresa=emp\n if request.POST.get('concepto'):\n partid.concepto=request.POST.get('concepto')\n\n partid.save() \n\n # finaliza el registro de partida\n # comienza el registro de movimientos\n for i in range(d):\n movimient=movimiento()\n movimient.idPartida=partid\n cuent=cuenta.objects.get(idCuenta=(int(a[i])))\n movimient.idCuenta=cuent\n if b[i]:\n movimient.debe=int(b[i])\n if c[i]:\n movimient.haber=int(c[i])\n movimient.save()\n #finaliza el registro de movimientos\n\n partidas=partida.objects.filter(codEmpresa=emp.codEmpresa) \n if partidas:\n # return render(request,'Registros/Registro.html',{'msg': 'ingreso exitoso','empresa': emp})\n return render(request,'Registros/msgPartida.html',{'msg': 'ya casi man','partidas': partidas})\n # return render(request,'Registros/msgPartida.html',{'msg': 'ya casi man','partidas': partidas})\n # return render(request,'msgPartida.html',{'msg': 'ya casi man','cod': a,'debe': b,'haber': c,'long': d,'partidas': partidas})\n else:\n return render(request,'Registros/msgPartida.html',{'msg': 'no hay registros'}) \t\n\ndef Empresa(request):\n return render(request,'ErrorMigracion.html')\n\ndef Catalogo(request):\n try:\n emp = empresa.objects.get(codEmpresa = int(request.session['codemp']))\n except Exception :\n emp=\"\"\n if emp:\n return render(request,'Catalogo/Catalogo.html')\n \n \ndef Registro(request):\n try:\n emp = empresa.objects.get(codEmpresa = int(request.session['codemp']))\n except Exception :\n emp=\"\"\n if emp:\n return render(request,'Registros/Registro.html',{'empresa': emp})\n\ndef consultaPartida(request):\n try:\n emp = empresa.objects.get(codEmpresa = int(request.session['codemp']))\n except Exception :\n emp=\"\"\n partidas=partida.objects.filter(codEmpresa=emp.codEmpresa) \n if partidas:\n \n return render(request,'Registros/msgPartida.html',{'msg': 'registros','partidas': partidas})\n # return render(request,'Registros/msgPartida.html',{'msg': 'ya casi man','partidas': partidas})\n # return render(request,'msgPartida.html',{'msg': 'ya casi man','cod': a,'debe': b,'haber': c,'long': d,'partidas': partidas})\n else:\n return render(request,'Registros/msgPartida.html',{'msg': 'no hay registros'}) \n \n\n\n \n\ndef index(request):\n return HttpResponse(\"Hello, world. You're at the polls index.\")\n","sub_path":"conta/contapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"566535595","text":"# -*- coding:utf-8-*-\nimport unittest\nimport time\nfrom InterfaceTest import HTMLTestRunner\nimport os\n\n\n# def report(testreport):#查找最新的测试报告\n# lists = os.listdir(testreport)#返回指定的文件夹包含的文件或文件夹的名字列表\n# lists.sort(key=lambda fn:os.path.getatime(testreport+\"\\\\\"+fn))#通过sort()方法重新按时间对目录下的文件进行排序\n# filename = os.path.join(testreport,lists[-1])#list[-1]取最新生成的文件或者文件夹\n# return filename\n\nif __name__ == '__main__':\n case_path = os.path.join(os.getcwd(),'testcase')\n report_path = os.path.join(os.getcwd(),'report')\n discover = unittest.defaultTestLoader.discover(case_path,pattern='*.py',top_level_dir=None)\n time = time.strftime(\"%Y-%m-%d %H_%M_%S\")\n filename = os.path.join(report_path,time+'_result.html')\n fp = open(filename,'wb')\n runner = HTMLTestRunner.HTMLTestRunner(stream = fp, title =u'接口测试报告', description='The results are following:')\n runner.run(discover)\n fp.close()\n # test_report = './report'\n # rep = report(test_report)\n\n","sub_path":"text/InterfaceTest/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"190732452","text":"xEdgeKernal = [[-1,-1,-1],\n [-1,8,-1],\n [-1,-1,-1]]\n\nclass Image:\n def __init__(self, fileName): #Pixel Ratio: num of original pixels / 1 new pixel\n self.fileName = fileName;\n self.img = loadImage(fileName);\n self.imageArray = self.toArray();\n def show(self):\n image(self.img,0,0);\n def toArray(self):\n newArray = [];\n self.img.loadPixels();\n for y in range(height):\n for x in range(width):\n loc = x + y*width;\n newArray.append(self.img.pixels[loc]);\n return newArray; \n \n def applyKernal(self,kernalArray):\n matrixSize = len(kernalArray);\n self.img.loadPixels();\n for y in range(height):\n for x in range(width):\n rTotal = 0;\n gTotal = 0;\n bTotal = 0;\n for i in range(matrixSize):\n for j in range(matrixSize):\n xloc = x+i\n yloc = y+j\n loc = xloc + width*yloc\n loc = constrain(loc,0,len(self.img.pixels)-1)\n rTotal += (red(self.img.pixels[loc]) * kernalArray[i][j])\n gTotal += (green(self.img.pixels[loc]) * kernalArray[i][j])\n bTotal += (blue(self.img.pixels[loc]) * kernalArray[i][j])\n rTotal = constrain(rTotal,0,255)\n gTotal = constrain(gTotal,0,255)\n bTotal = constrain(bTotal,0,255)\n c = color(rTotal,gTotal,bTotal)\n loc = x + y*width;\n self.img.pixels[loc] = c\n self.img.updatePixels();\n","sub_path":"Processing/toyNN/Image.py","file_name":"Image.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"480410152","text":"from __future__ import absolute_import, division, print_function, unicode_literals\nimport os\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tqdm import tqdm\nimport random\nimport cv2\nfrom PIL import Image\nimport math\nimport argparse\nimport pandas as pd\nimport warnings\nAUTOTUNE = tf.data.experimental.AUTOTUNE\nkeras = tf.keras\n\ndef crop_black(img):\n\timg = cv2.copyMakeBorder(img, 30 , 30, 30, 30, cv2.BORDER_CONSTANT)\n\tgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\tblur = cv2.GaussianBlur(gray,(5,5),0)\n\tblur = cv2.GaussianBlur(blur,(5,5),0)\n\t_, thresh = cv2.threshold(blur,8, 255, cv2.THRESH_BINARY)\n\tres = img[np.ix_(thresh.any(1),thresh.any(0))]\n\treturn res\n\ndef normalize(img):\n\tminv = np.min(img)\n\tmaxv = np.max(img)\n\timg = (img - minv)/(maxv - minv)\n\treturn img\n\n\ndef processImg(img_path, size=224):\n\timg = cv2.imread(img_path)\n\timg = crop_black(img)\n\timg = cv2.resize(img, (size,size), interpolation=cv2.INTER_AREA)\n\timg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\timg = Image.fromarray(img)\n\t# img = normalize(img)\n\timg = np.expand_dims(img, axis=0)\n\timg = tf.keras.applications.resnet50.preprocess_input(img)\n\treturn img\n\n\ndef loadTrainData(train_csv, train_dir, size=224):\n\n\tlabels = pd.read_csv(train_csv)\n\tlabels = labels.reindex(np.random.RandomState(seed=103).permutation(labels.index))\n\tnum_img = labels.shape[0]\n\n\ttrain_dir = train_dir.strip()\n\tif(not train_dir.endswith('/')):\n\t\ttrain_dir = train_dir + '/'\n\n\n\tx = np.empty((num_img, size, size, 3), dtype=np.uint8)\n\ty = np.zeros((num_img, 5), dtype=np.uint8)\n\n\n\tfor i, (image_id, diag) in enumerate(tqdm(zip(labels['id_code'], labels['diagnosis']), total=num_img)):\n\t\tx[i, :, :, :] = processImg(train_dir + image_id + '.png', size)\n\t\ty[i, int(diag)] = 1\n\n\tnumTrain = int(math.floor(num_img * 0.90))\n\n\tx_train = x[0:numTrain, :, :, :].reshape((-1, size, size, 3))\n\ty_train = y[0:numTrain, :].reshape((-1, 5))\n\tx_val = x[numTrain:, :, :, :].reshape((-1, size, size, 3))\n\ty_val = y[numTrain:, :].reshape((-1, 5))\n\n\tnp.save('x_train.npy', x_train)\n\tnp.save('y_train.npy', y_train)\n\tnp.save('x_val.npy', x_val)\n\tnp.save('y_val.npy', y_val)\n\n\t# x_train = tf.convert_to_tensor(x[0:numTrain, :, :, :].reshape((-1, size, size, 3)))\n\t# y_train = tf.convert_to_tensor(y[0:numTrain, :].reshape((-1, 5)))\n\t# print(x_train.get_shape())\n\t# print(y_train.get_shape())\n\n\t# x_val = tf.convert_to_tensor(x[numTrain:, :, :, :].reshape((-1, size, size, 3)))\n\t# y_val = tf.convert_to_tensor(y[numTrain:, :].reshape((-1, 5)))\n\t# print(x_val.get_shape())\n\t# print(y_val.get_shape())\n\n\treturn x_train, y_train, x_val, y_val\n\ndef cnn_model(IMAGE_SIZE=224):\n\n\tIMG_SHAPE = (IMAGE_SIZE, IMAGE_SIZE, 3)\n\n\t# default size 224 x 224 x 3\n\tresnet = tf.keras.applications.ResNet50(weights='imagenet', include_top=False, input_shape=IMG_SHAPE)\n\tresnet.trainable = False\n\tx = resnet.layers[-1].output\n\n\tconv1 = tf.keras.layers.Conv2D(2048, (3,3), strides=(1, 1), padding='same')(x)\n\tbnorm1 = tf.keras.layers.BatchNormalization()(conv1)\n\tactivation1 = tf.keras.layers.Activation('relu')(bnorm1)\n\tflattened = tf.keras.layers.Flatten()(activation1)\n\n\tdense1 = tf.keras.layers.Dense(1024)(flattened)\n\tbnorm2 = tf.keras.layers.BatchNormalization()(dense1)\n\tactivation2 = tf.keras.layers.Activation('relu')(bnorm2)\n\n\tdense2 = tf.keras.layers.Dense(256)(activation2)\n\tbnorm3 = tf.keras.layers.BatchNormalization()(dense2)\n\tactivation3 = tf.keras.layers.Activation('relu')(bnorm3)\n\n\tdense3 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(activation3)\n\n\tneural = tf.keras.Model(inputs = resnet.input, outputs = dense3)\n\n\treturn neural\n\ndef train(x_train, y_train, x_val, y_val, modelName, resTrain=False, numEpochs = 60, batch_size=48, img_size=224):\n\n\tprint('Creating Model for Training')\n\tmodel = cnn_model(img_size)\n\n\tmodel.compile(optimizer=keras.optimizers.Adam(), loss='categorical_crossentropy',\n\t\tmetrics=['accuracy'])\n\n\tif resTrain:\n\t\tprint(\"Loading Checkpoint for Resuming Training\")\n\t\tmodel.load_weights(modelName + '_ck.h5')\n\n\tmodel.summary()\n\n\n\t# Create checkpoint, logger callback\n\tcp_callback = tf.keras.callbacks.ModelCheckpoint(modelName + '_ck.h5', save_weights_only=True, verbose=1)\n\tlog_callback = tf.keras.callbacks.CSVLogger(modelName + \".log\", append=True)\n\n\n\tmodel.fit(x_train, y_train, batch_size = batch_size, epochs = numEpochs, shuffle='batch',\n\t\tvalidation_data = (x_val, y_val), verbose = 1, callbacks = [cp_callback, log_callback])\n\n\tmodel.save(modelName + '_model.h5')\n\n\tprint(\"Finished Training\")\n\n\ndef evaluate(x_train, y_train, x_val, y_val, modelPath, size=224):\n\n\tprint(\"Creating Model for Evaluation\")\n\tmodel = cnn_model(size)\n\tprint(\"Loading Weights\")\n\tmodel.load_weights(modelPath)\n\n\tloss, acc = model.evaluate(x_train, y_train)\n\tprint(\"Train Accuracy: {:5.2f}%\".format(100*acc))\n\n\tloss, acc = model.evaluate(x_val, y_val)\n\tprint(\"Validation Accuracy: {:5.2f}%\".format(100*acc))\n\n\ndef predictCSV(test_csv, image_dir, modelPath, path=\"\", size=224):\n\n\twarnings.filterwarnings(\"ignore\")\n\tprint(\"Loading Model for Prediction\\n\")\n\tmodel = cnn_model(size)\n\tmodel.load_weights(modelPath)\n\n\tsubmit = pd.read_csv(test_csv)\n\n\tprint(\"Predictions Started\\n\")\n\n\tfor file_id in submit['id_code']:\n\t\timg = processImg(image_dir + file_id + \".png\")\n\t\tpred = model.predict(img, batch_size=1)\n\t\tpred = np.argmax(pred)\n\t\tsubmit.loc[submit['id_code']==file_id, 'diagnosis'] = int(pred)\n\n\tsubmit[\"diagnosis\"] = pd.to_numeric(submit[\"diagnosis\"], downcast='integer')\n\tsubmit.to_csv(path + 'submission.csv', index=False, header=['id_code', 'diagnosis'])\n\n\tprint(\"Predictions Complete\")\n\ndef predictExample(img_path, modelPath, size=224):\n\n\tmodel = cnn_model(size)\n\tmodel.load_weights(modelPath)\n\n\timg = processImg(img_path)\n\tpred = model.predict(img, batch_size=1)\n\tpred = np.argmax(pred)\n\tprint(\"Prediction: \" + str(pred))\n\n\ndef main():\n\n\t# sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))\n\n\tparser = argparse.ArgumentParser(description='Deep Learning Model for DR Prediction with Transfer Learning')\n\tparser.add_argument('--test', '-t', dest='test', default=False, action='store_true',\n\t\thelp='Test Model on Test Set')\n\tparser.add_argument('--resTrain', dest='resTrain', default=False, action='store_true',\n\t\thelp='Resume Training of Model. Default: False')\n\tparser.add_argument('--numEpochs', type=int, dest='epochs', default=160,\n\t\thelp='Number of epochs for training. Default: 160')\n\tparser.add_argument('--batchSize', type=int, dest='batch_size', default=48,\n\t\thelp='Batch Size for Training. Default: 48')\n\tparser.add_argument('--imageSize', type=int, dest='img_size', default=224,\n\t\thelp='Image Size of Training & Valdiation Images. Default: 224')\n\trequired = parser.add_argument_group('required arguments')\n\trequired.add_argument('--modelName', dest='model', required=True,\n\t\thelp='Name of Model. Example: /desktop/CNN1')\n\targs = parser.parse_args()\n\n\twarnings.filterwarnings(\"ignore\")\n\n\n\tx_train, y_train, x_val, y_val = loadTrainData(\"/home/samiragarwala/aptos2019/train.csv\", \n\t\t\t\t\t\t\"/home/samiragarwala/aptos2019/train_images\", args.img_size)\n\n\tif not args.test:\n\t\t# for training\n\t\ttrain(x_train, y_train, x_val, y_val, args.model, args.resTrain, args.epochs, args.batch_size, args.img_size)\n\n\telse:\n\t\t# for testing\n\t\tmodelPath = args.model + '_ck.h5'\n\t\tevaluate(x_train, y_train, x_val, y_val, modelPath, args.img_size)\n\n# if __name__==\"__main__\":\n\n\t# for training\n\t# main()\n\n\t# for predicting CSV\n\t# test_csv = '/home/samiragarwala/aptos2019/test.csv'\n\t# image_dir = '/home/samiragarwala/aptos2019/test_images/'\n\t# modelPath = '/home/samiragarwala/aptos2019/TL_DR/cnn1/cnn1_ck.h5'\n\t# path = '/home/samiragarwala/aptos2019/TL_DR/cnn1/'\n\t# predictCSV(test_csv, image_dir, modelPath, path)\n\n\n\n\n","sub_path":"cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":7705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"434614240","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3350)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/tom/pyenv/py3/lib/python3.5/site-packages/test/test_layers.py\n# Compiled at: 2019-06-04 20:04:19\n# Size of source mod 2**32: 1286 bytes\nimport numpy as np, logging, sys, tensorflow as tf\nfrom mautil.tf_layers import EMB, RNN\nfrom mautil.tf_models import TF, InputFeature\nfrom sklearn.model_selection import train_test_split\n\nclass Model(TF):\n\n def _init_input_features(self):\n features = []\n features.append(InputFeature('inputs', [None, 5, 16], tf.float32))\n features.append(InputFeature('inputs_len', [None], tf.float32))\n features.append(InputFeature('tgt', [None, 16], tf.float32))\n return features\n\n def _add_main_graph(self):\n dims = [\n 16, 16]\n rnn = RNN(dims, bidirection=False)\n _, outs = rnn(self.inputs, inputs_lens=self.inputs_len)\n self._loss = tf.losses.mean_squared_error(outs[(-1)], self.tgt)\n\n\ndef main():\n train_num = 900\n x = np.random.rand(1000, 5, 16)\n y = np.sum(x, -2)\n x, xV, y, yV = train_test_split(x, y, test_size=0.1, shuffle=False)\n x = {'inputs': x, 'inputs_len': np.ones([len(x)])}\n xV = {'inputs': xV, 'inputs_len': np.ones(len(xV))}\n y = {'tgt': y}\n yV = {'tgt': yV}\n model = Model()\n loss, val_loss = model.fit(x, y, xV, yV)\n\n\nif __name__ == '__main__':\n logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(asctime)s %(levelname)s:%(threadName)s %(message)s')\n main()","sub_path":"pycfiles/mautil-0.2.1.linux-x86_64.tar/test_layers.cpython-35.py","file_name":"test_layers.cpython-35.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"74079602","text":"import os\n\ndef check_diff():\n \"\"\"\n Check consistency between file ordering obtained with internal and external timestamps.\n RESULTS:\n MGH and BIDMC are consistent.\n BWH and yale get different results.\n \"\"\"\n\n os.system(\"find /afs/csail.mit.edu/u/a/adepalma/NFS/EEG-dataset/patients-internal-timestamp -print | grep \\\"patient_\\\" > temp_list.txt\")\n\n with open(\"temp_list.txt\", \"r\") as file:\n\n for line in file:\n (path, filename) = os.path.split(line)\n\n if line.strip().split(\"/\")[9] == \"MGH\" or line.strip().split(\"/\")[9] == \"BIDMC\":\n os.system(\"diff {} /afs/csail.mit.edu/u/a/adepalma/NFS/EEG-dataset/patients/{}/{}\".format(line.strip(), line.strip().split(\"/\")[9], filename))\n\n return\n\n\nif __name__ == \"__main__\":\n\n check_diff()\n","sub_path":"distributed_lsh_alessandro_de_palma/EEG/scripts/check_diff.py","file_name":"check_diff.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"379125071","text":"import numpy as np\n\ndef clean_str(spacy_doc):\n # Pre-process the strings\n tokens = []\n for token in spacy_doc:\n\n # If stopword or punctuation, ignore token and continue\n if (token.is_stop and not (token.lemma_ == \"which\" or token.lemma_ == \"how\" or token.lemma_ == \"what\"\n or token.lemma_ == \"when\" or token.lemma_ == \"why\")) \\\n or token.is_punct:\n continue\n\n # Lemmatize the token and yield\n tokens.append(token.lemma_)\n return \" \".join(tokens)\n\ndef get_label_using_logits(logits, top_number=1):\n logits = np.ndarray.tolist(logits)\n predicted_labels = []\n for item in logits:\n index_list = np.argsort(item)[-top_number:]\n index_list = index_list[::-1]\n predicted_labels.append(np.ndarray.tolist(index_list))\n return predicted_labels\n","sub_path":"daphne_API/data_helpers.py","file_name":"data_helpers.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"560864392","text":"\"\"\"\n 谁?       干嘛?\n 类 --> 对象 方法\n 练习:\n 创建狗类\n 数据\n 爱称\n 品种\n 年龄\n 行为\n 玩\n 坐下\n\n 创建2条狗,分别让它们坐下/玩.\n 画出内存图\n\"\"\"\n\n\nclass Dog:\n \"\"\"\n 抽象的狗类\n \"\"\"\n\n def __init__(self, name, breed=\"野狗\", age=0):\n self.pet_name = name\n self.breed = breed\n self.age = age\n\n def play(self):\n print(self.pet_name + \"在玩耍\")\n\n def sit_down(self):\n print(self.pet_name + \"坐下了\")\n\n\nd01 = Dog(\"米咻\", \"拉布拉多\", 4)\nd01.play()\nd01.sit_down()\n\nd02 = Dog(\"黑米\", \"拉布拉多\", 2)\nd02.play()\nd02.sit_down()\n\n# 一个函数,如何找到相应的对象?\n# 通过函数的self\n","sub_path":"01-python基础/code/day09/exercise01.py","file_name":"exercise01.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"133254661","text":"\"\"\"mysite URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\n\nfrom utility import views\nfrom utility import views_test\nfrom utility import permission\n\nurlpatterns = [\n url(r'^$',views.index),\n url(r'^admin/',admin.site.urls),\n url(r'^add/$',views.add,name='add'),\n url(r'^add/(\\d+)/(\\d+)/$',views.add2,name='add2'),\n url(r'^instr/',views.instr),\n url(r'^test_easyui/',views.test_easyui),\n url(r'^test(\\d*)/$',views_test.test_url),\n url(r'^dv/(\\w*)?',views_test.dv_url),\n url(r'^jiaoda/',views_test.jiaoda_url),\n url(r'^regist/$',permission.regist),\n url(r'^login/$',permission.login),\n url(r'^logout/$',permission.logout),\n\n]\n\n","sub_path":"MySite/mysite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"149442014","text":"import torch\nfrom torch.autograd import Variable\nfrom torch.nn import functional as F\nx_data = Variable(torch.Tensor([[10.0], [9.0], [3.0], [2.0]]))\ny_data = Variable(torch.Tensor([[90.0], [80.0], [50.0], [30.0]]))\n\nclass LinearRegression(torch.nn.Module):\n def __init__(self):\n super(LinearRegression, self).__init__()\n self.linear = torch.nn.Linear(1, 1)\n def forward(self, x):\n y_pred = self.linear(x)\n return y_pred\nmodel = LinearRegression()\n\ncriterion = torch.nn.MSELoss()\noptimizer = torch.optim.SGD(model.parameters(), lr=0.01)\n\nfor epoch in range(1000):\n model.train()\n optimizer.zero_grad()\n # Forward pass\n y_pred = model(x_data)\n # Compute Loss\n loss = criterion(y_pred, y_data)\n print(loss)\n # Backward pass\n loss.backward()\n optimizer.step()\n\nnew_x = Variable(torch.Tensor([[4.0]]))\ny_pred = model(new_x)\nprint(\"predicted Y value: \", y_pred.data[0][0])","sub_path":"python/11-deepLearning/99-pytorch/03-regression/linearRegression.py","file_name":"linearRegression.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"183637806","text":"#Import python libraries\nimport vtk\n\n# def is used to define a function in python.\ndef ReadDicom(): \n print(\"---------------------------Reading image---------------------------\")\n \n # Define a dicom reader from vtk.\n dicomReader = vtk.vtkDICOMImageReader()\n \n #Read the path that the user will input.\n dicomPath = input(\"Please, indicate the path to the DICOM directory: \")\n dicomReader.SetDirectoryName(dicomPath)\n dicomReader.Update()\n \n #Store the image in a global variable, so that it can be accesed later in any part of the code.\n global dicomImage\n dicomImage = dicomReader.GetOutput()\n \n #Print some information about the image\n print(\"Dimensions: \" + str(dicomImage.GetDimensions()))\n print(\"Spacing: \" + str(dicomImage.GetSpacing()))\n print(\"Origin: \" + str(dicomImage.GetOrigin()))\n \n# This function is used to define the image orientation as axial, coronal, or sagittal.\n# Note how it receives two parameters: imageToOrient, and orientation\ndef orientImage (imageToOrient, orientation): \n (xMin, xMax, yMin, yMax, zMin, zMax) = imageToOrient.GetExtent()\n (xSpacing, ySpacing, zSpacing) = imageToOrient.GetSpacing()\n (x0, y0, z0) = imageToOrient.GetOrigin()\n \n # Calculate the coordinates of the center of the image.\n center = [x0 + xSpacing * (xMin + xMax),\n y0 + ySpacing * (yMin + yMax),\n z0 + zSpacing * (zMin + zMax)]\n \n #This matrices are used to transform the coordinates of the image, for each orientation. \n axial = vtk.vtkMatrix4x4()\n axial.DeepCopy((1, 0, 0,center[0] ,\n 0, -1, 0,center[1] ,\n 0, 0, 1,center[2],\n 0, 0, 0, 1))\n \n coronal = vtk.vtkMatrix4x4()\n coronal.DeepCopy((1, 0, 0, center[0],\n 0, 0, 1, center[1],\n 0, -1, 0, center[2],\n 0, 0, 0, 1))\n \n sagittal = vtk.vtkMatrix4x4()\n sagittal.DeepCopy((0, 0,-1, center[0],\n 1, 0, 0, center[1],\n 0, -1, 0,center[2] ,\n 0, 0, 0, 1))\n\n # vtkImageReslice orients an image, given a transformation matrix.\n reslice = vtk.vtkImageReslice()\n reslice.SetInputData(imageToOrient)\n reslice.SetOutputDimensionality(3)\n reslice.SetResliceAxesOrigin(0,0,0)\n \n if orientation=='axial':\n reslice.SetResliceAxes(axial)\n elif orientation=='coronal':\n reslice.SetResliceAxes(coronal) \n elif orientation=='sagittal':\n reslice.SetResliceAxes(sagittal)\n \n # interpolation is required to re-slice the image in the required orientation \n reslice.SetInterpolationModeToCubic()\n reslice.Update()\n \n return reslice.GetOutput()\n\n# This is the main navigation function\ndef Navigate2D():\n print(\"---------------------------Navigating 2D---------------------------\")\n print(\"Please, choose the navigation axis\")\n print(\"1 Axial\")\n print(\"2 Coronal\")\n print(\"3 Sagittal\")\n optionUser = input(\"?: \") \n print(\"Use up and down arrows to navigate\")\n \n global orientation\n global zSlice \n zSlice = 0\n \n if (optionUser == \"1\"):\n orientation = \"axial\"\n if (optionUser == \"2\"):\n orientation = \"coronal\" \n if (optionUser == \"3\"):\n orientation = \"sagittal\" \n \n imageNavigate2D = orientImage(dicomImage, orientation) \n \n global mapperNavigate2D\n mapperNavigate2D = vtk.vtkImageMapper()\n mapperNavigate2D.SetInputData(imageNavigate2D)\n mapperNavigate2D.SetZSlice(zSlice)\n # window and level have to be adjusted for better visualization\n mapperNavigate2D.SetColorWindow(1000)\n mapperNavigate2D.SetColorLevel(0) \n \n actorNavigate2D = vtk.vtkActor2D()\n actorNavigate2D.SetMapper(mapperNavigate2D) \n\n global renderWindowNavigate2D \n rendererNavigate2D = vtk.vtkRenderer()\n rendererNavigate2D.AddActor(actorNavigate2D)\n \n renderWindowNavigate2D = vtk.vtkRenderWindow() \n renderWindowNavigate2D.AddRenderer(rendererNavigate2D) \n \n if (orientation == \"axial\"):\n renderWindowNavigate2D.SetSize(dicomImage.GetDimensions()[0], dicomImage.GetDimensions()[1]) \n if (orientation == \"coronal\"):\n renderWindowNavigate2D.SetSize(dicomImage.GetDimensions()[0], dicomImage.GetDimensions()[2]) \n if (orientation == \"sagittal\"):\n renderWindowNavigate2D.SetSize(dicomImage.GetDimensions()[1], dicomImage.GetDimensions()[2]) \n \n\n windowInteractorN2D = vtk.vtkRenderWindowInteractor()\n windowInteractorN2D.SetRenderWindow(renderWindowNavigate2D) \n \n #Note here how the event is added to the observer. The name of the event is fixed, the name\n #of the function that handles the event is user defined.\n windowInteractorN2D.AddObserver(\"KeyPressEvent\", KeyPressNavigate2D, 1.0)\n \n windowInteractorN2D.Initialize()\n renderWindowNavigate2D.Render()\n windowInteractorN2D.Start() \n\n del renderWindowNavigate2D, windowInteractorN2D \n \ndef KeyPressNavigate2D(obj, Event): \n key = obj.GetKeySym()\n limitUp = 0\n limitDown = 0\n \n if (orientation == \"axial\"):\n limitUp = dicomImage.GetDimensions()[2] - 1 \n if (orientation == \"coronal\"):\n limitUp = dicomImage.GetDimensions()[1] - 1 \n if (orientation == \"sagittal\"):\n limitUp = dicomImage.GetDimensions()[0] - 1 \n\t\n global zSlice \t\n \n if (key == \"Up\"): \n zSlice = zSlice + 1\n if (zSlice > limitUp):\n zSlice = limitUp\n \n if (key == \"Down\"): \n zSlice = zSlice - 1\n if (zSlice < 0):\n zSlice = 0 \n\n mapperNavigate2D.SetZSlice(zSlice) \n renderWindowNavigate2D.Render() \n \n \n# This is the body of the main program. \n# It defines an infinite loop that prints the menu and reads an option that the user will choose.\n# You must start by reading the image, before trying to navigate it.\nwhile True:\n print(\"---------------------------Main menu---------------------------\")\n print(\"Please, choose an option\")\n print(\"1 Indicate DICOM image directory path.\")\n print(\"2 Navigate 2D slices.\")\n print(\"q Quit.\")\n optionUser = input(\"?: \") \n \n if (optionUser == \"q\"):\n break\n \n if (optionUser == \"1\"):\n ReadDicom() \n \n if (optionUser == \"2\"):\n Navigate2D() ","sub_path":"W01_load_display_3Dmed_Image/01_Solutions/navigateDicom.py","file_name":"navigateDicom.py","file_ext":"py","file_size_in_byte":6143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"358748668","text":"from argparse import Namespace\n\nimport os\nimport torch\nimport logging\nimport json\n\nimport numpy as np\nfrom tqdm import tqdm\nfrom fairseq import metrics, options, utils\nfrom fairseq.data import Dictionary, TaggedDataset\nfrom fairseq.tasks import FairseqTask, register_task\nimport sentencepiece as spm\nEVAL_BLEU_ORDER = 4\n\n\nlogger = logging.getLogger(__name__)\n\n\n@register_task('no_context_tag')\nclass NoContextTag(FairseqTask):\n @staticmethod\n def add_args(parser):\n # Add some command-line arguments for specifying where the data is\n # located and the maximum supported input length.\n parser.add_argument('data', metavar='FILE',\n help='file prefix for data')\n parser.add_argument('--left-pad-source', default='True', type=str, metavar='BOOL',\n help='pad the source on the left')\n parser.add_argument('--left-pad-target', default='False', type=str, metavar='BOOL',\n help='pad the target on the left')\n parser.add_argument('--max-source-positions', default=1024, type=int, metavar='N',\n help='max number of tokens in the source sequence')\n parser.add_argument('--max-target-positions', default=1024, type=int, metavar='N',\n help='max number of tokens in the target sequence')\n\n # options for reporting BLEU during validation\n parser.add_argument('--eval-bleu', action='store_true',\n help='evaluation with BLEU scores')\n parser.add_argument('--eval-bleu-detok', type=str, default=\"space\",\n help='detokenize before computing BLEU (e.g., \"moses\"); '\n 'required if using --eval-bleu; use \"space\" to '\n 'disable detokenization; see fairseq.data.encoders '\n 'for other options')\n parser.add_argument('--eval-bleu-detok-args', type=str, metavar='JSON',\n help='args for building the tokenizer, if needed')\n parser.add_argument('--eval-tokenized-bleu', action='store_true', default=False,\n help='compute tokenized BLEU instead of sacrebleu')\n parser.add_argument('--eval-bleu-remove-bpe', nargs='?', const='@@ ', default=None,\n help='remove BPE before computing BLEU')\n parser.add_argument('--eval-bleu-args', type=str, metavar='JSON',\n help='generation args for BLUE scoring, '\n 'e.g., \\'{\"beam\": 4, \"lenpen\": 0.6}\\'')\n parser.add_argument('--eval-bleu-print-samples', action='store_true',\n help='print sample generations during validation')\n\n @classmethod\n def setup_task(cls, args, **kwargs):\n # Here we can perform any setup required for the task. This may include\n # loading Dictionaries, initializing shared Embedding layers, etc.\n # In this case we'll just load the Dictionaries.\n \n\n args.left_pad_source = options.eval_bool(args.left_pad_source)\n args.left_pad_target = options.eval_bool(args.left_pad_target)\n\n\n # load dictionaries\n vocab = cls.load_dictionary(os.path.join(args.data, 'dict.txt'))\n logger.info('[{}] dictionary: {} types'.format('Src + tgt', len(vocab)))\n vocab.model = spm.SentencePieceProcessor(model_file=os.path.join(args.data, 'spm.model'))\n\n return cls(args, vocab)\n\n def __init__(self, args, vocab):\n super().__init__(args)\n self.vocab = vocab\n\n def load_dataset(self, split, **kwargs):\n \"\"\"Load a given dataset split (e.g., train, valid, test).\"\"\"\n\n path = os.path.join(self.args.data, '{}.json'.format(split))\n\n self.datasets[split] = TaggedDataset(path, self.vocab)\n\n def build_model(self, args):\n model = super().build_model(args)\n if getattr(args, 'eval_bleu', False):\n assert getattr(args, 'eval_bleu_detok', None) is not None, (\n '--eval-bleu-detok is required if using --eval-bleu; '\n 'try --eval-bleu-detok=moses (or --eval-bleu-detok=space '\n 'to disable detokenization, e.g., when using sentencepiece)'\n )\n detok_args = json.loads(getattr(args, 'eval_bleu_detok_args', '{}') or '{}')\n self.tokenizer = self.vocab.model\n\n gen_args = json.loads(getattr(args, 'eval_bleu_args', '{}') or '{}')\n self.sequence_generator = self.build_generator([model], Namespace(**gen_args))\n return model\n\n def prepare_gen(self, model, args):\n if getattr(args, 'eval_bleu', False):\n assert getattr(args, 'eval_bleu_detok', None) is not None, (\n '--eval-bleu-detok is required if using --eval-bleu; '\n 'try --eval-bleu-detok=moses (or --eval-bleu-detok=space '\n 'to disable detokenization, e.g., when using sentencepiece)'\n )\n detok_args = json.loads(getattr(args, 'eval_bleu_detok_args', '{}') or '{}')\n self.tokenizer = self.vocab.model\n\n gen_args = json.loads(getattr(args, 'eval_bleu_args', '{}') or '{}')\n self.sequence_generator = self.build_generator([model], Namespace(**gen_args))\n\n def valid_step(self, sample, model, criterion):\n loss, sample_size, logging_output = super().valid_step(sample, model, criterion)\n if self.args.eval_bleu:\n bleu = self._inference_with_bleu(self.sequence_generator, sample, model)\n logging_output['_bleu_sys_len'] = bleu.sys_len\n logging_output['_bleu_ref_len'] = bleu.ref_len\n # we split counts into separate entries so that they can be\n # summed efficiently across workers using fast-stat-sync\n assert len(bleu.counts) == EVAL_BLEU_ORDER\n for i in range(EVAL_BLEU_ORDER):\n logging_output['_bleu_counts_' + str(i)] = bleu.counts[i]\n logging_output['_bleu_totals_' + str(i)] = bleu.totals[i]\n return loss, sample_size, logging_output\n\n def reduce_metrics(self, logging_outputs, criterion):\n super().reduce_metrics(logging_outputs, criterion)\n if self.args.eval_bleu:\n\n def sum_logs(key):\n return sum(log.get(key, 0) for log in logging_outputs)\n\n counts, totals = [], []\n for i in range(EVAL_BLEU_ORDER):\n counts.append(sum_logs('_bleu_counts_' + str(i)))\n totals.append(sum_logs('_bleu_totals_' + str(i)))\n\n if max(totals) > 0:\n # log counts as numpy arrays -- log_scalar will sum them correctly\n metrics.log_scalar('_bleu_counts', np.array(counts))\n metrics.log_scalar('_bleu_totals', np.array(totals))\n metrics.log_scalar('_bleu_sys_len', sum_logs('_bleu_sys_len'))\n metrics.log_scalar('_bleu_ref_len', sum_logs('_bleu_ref_len'))\n\n def compute_bleu(meters):\n import inspect\n import sacrebleu\n fn_sig = inspect.getfullargspec(sacrebleu.compute_bleu)[0]\n if 'smooth_method' in fn_sig:\n smooth = {'smooth_method': 'exp'}\n else:\n smooth = {'smooth': 'exp'}\n bleu = sacrebleu.compute_bleu(\n correct=meters['_bleu_counts'].sum,\n total=meters['_bleu_totals'].sum,\n sys_len=meters['_bleu_sys_len'].sum,\n ref_len=meters['_bleu_ref_len'].sum,\n **smooth\n )\n return round(bleu.score, 2)\n\n metrics.log_derived('bleu', compute_bleu)\n\n def max_positions(self):\n \"\"\"Return the max input length allowed by the task.\"\"\"\n return (self.args.max_tokens, self.args.max_tokens)\n\n @property\n def source_dictionary(self):\n \"\"\"Return the source and target :class:`~fairseq.data.Dictionary`.\"\"\"\n return self.vocab\n\n @property\n def target_dictionary(self):\n \"\"\"Return the target :class:`~fairseq.data.Dictionary`.\"\"\"\n return self.vocab\n\n def _inference_with_bleu(self, generator, sample, model, return_hyps=False):\n import sacrebleu\n\n def decode(toks, escape_unk=False):\n toks = toks.tolist()\n #bos = task.vocab.encode(\"\")\n #eos = task.vocab.encode(\"\")\n bos = self.tokenizer.bos_id()\n eos = self.tokenizer.eos_id()\n while bos in toks:\n toks.remove(bos)\n while eos in toks:\n toks.remove(eos)\n if len(toks) == 0: \n return \"\"\n s = self.tokenizer.decode(toks)\n unk_string = \"UNKNOWNTOKENINREF\" if escape_unk else \"UNKNOWNTOKENINHYP\"\n while \"\" in s:\n s.replace(\"\", unk_string)\n return s.strip()\n\n gen_out = self.inference_step(generator, [model], sample, prefix_tokens=None)\n srcs, hyps, refs = [], [], []\n for i in range(len(gen_out)):\n srcs.append(decode(utils.strip_pad(sample['net_input']['src_tokens'][i], self.vocab.pad()),\n escape_unk=True, # don't count as matches to the hypo \n ))\n hyps.append(decode(gen_out[i][0]['tokens']))\n refs.append(decode(\n utils.strip_pad(sample['target'][i], self.vocab.pad()),\n escape_unk=True, # don't count as matches to the hypo\n ))\n if self.args.eval_bleu_print_samples:\n logger.info('example hypothesis: ' + hyps[0])\n logger.info('example reference: ' + refs[0])\n if self.args.eval_tokenized_bleu:\n return sacrebleu.corpus_bleu(hyps, [refs], tokenize='none')\n if return_hyps:\n return srcs, hyps, refs\n else:\n return sacrebleu.corpus_bleu(hyps, [refs])\n\n\n def eval_with_bleu(self, model, dataloader):\n import sacrebleu\n \n def decode(task, toks, escape_unk=False):\n toks = toks.tolist()\n #bos = task.vocab.encode(\"\")\n #eos = task.vocab.encode(\"\")\n bos = task.vocab.model.bos_id()\n eos = task.vocab.model.eos_id()\n while bos in toks:\n toks.remove(bos)\n while eos in toks:\n toks.remove(eos)\n s = task.vocab.decode(\n toks)\n return s.strip()\n\n hyps = []\n refs = []\n preds = torch.Tensor([self.vocab.model.bos_id()])\n for batch in tqdm(dataloader):\n mask_batch = batch\n mask_batch['net_input']['prev_output_tokens'] = prev_outputs\n preds = model(**mask_batch['net_input'])\n # print(preds[0][0].shape)\n # print(decode(task,torch.argmax(preds[0][0], dim=1)))\n # print(decode(task,\n # utils.strip_pad(batch['target'][0], task.vocab.pad()),\n # escape_unk=True, # don't count as matches to the hypo\n # ))\n for i in range(preds[0].shape[0]):\n hyps.append(decode(self,torch.argmax(preds[0][i], dim=1)))\n refs.append(decode(self,\n utils.strip_pad(batch['target'][i], self.vocab.pad()),\n escape_unk=True, # don't count as matches to the hypo\n ))\n\n return sacrebleu.corpus_bleu(hyps, [refs]), hyps","sub_path":"fairseq/tasks/no_context_tag.py","file_name":"no_context_tag.py","file_ext":"py","file_size_in_byte":11690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"594233199","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# michael a.g. aïvázis\n# orthologue\n# (c) 1998-2023 all rights reserved\n#\n\n\n\"\"\"\nCheck catching of decoding errors when the input file has a bad tag\n\"\"\"\n\n\ndef test():\n # package access\n import pyre.config\n # get the codec manager\n m = pyre.config.newConfigurator()\n # ask for a pml codec\n reader = m.codec(encoding=\"pml\")\n # the configuration file\n uri = \"sample-badNode.pml\"\n # open a stream with an error\n sample = open(uri)\n # read the contents\n try:\n reader.decode(uri=uri, source=sample, locator=None)\n assert False\n except reader.DecodingError as error:\n assert str(error) == (\n \"file='sample-badNode.pml', line=12, column=53: decoding error: mismatched tag\"\n )\n\n return m, reader\n\n\n# main\nif __name__ == \"__main__\":\n # skip pyre initialization since we don't rely on the executive\n pyre_noboot = True\n # do...\n test()\n\n\n# end of file\n","sub_path":"tests/pyre.pkg/codecs/pml_badNode.py","file_name":"pml_badNode.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"141107675","text":"import assemble\nimport string\nimport itertools\nimport re\n\n\nGENERAL_REGISTERS = [\n 'eax', 'ebx', 'ecx', 'edx', 'esi', 'edi'\n]\n\n\nALL_REGISTERS = GENERAL_REGISTERS + [\n 'esp', 'eip', 'ebp'\n]\n\n\nclass GadgetSearch(object):\n def __init__(self, dump_path, start_addr):\n self.dump_path = dump_path\n self.start_addr = start_addr\n\n def get_format_count(self, gadget_format):\n place_holders = []\n count = 0\n for x in string.Formatter().parse(gadget_format):\n # check if valid place holder and wasnt counted already\n if x[1] is not None and x[1] not in place_holders:\n count += 1\n place_holders.append(x[1])\n return count\n\n def get_register_combos(self, nregs, registers):\n combos = []\n # generate permutations with repetition\n perms = [p for p in itertools.product(registers, repeat=nregs)]\n # convert tuples to arrays and put all in one big combos array\n for perm in perms:\n combos.append([perm[i] for i in range(nregs)])\n return combos\n\n def format_all_gadgets(self, gadget_format, registers):\n # get number of place holders\n num_p_holders = self.get_format_count(gadget_format)\n # get all possible combos of filling the place holders\n combos = self.get_register_combos(num_p_holders, registers)\n gadgets = []\n for combo in combos:\n gadgets.append((gadget_format.format(*combo)))\n return gadgets\n\n def find_all(self, gadget):\n # open dump file\n dump_file = open(self.dump_path, 'r')\n # put contents of file in dump\n dump = dump_file.read()\n # construct gadget with ret which we want to search\n gadget_asm = assemble.assemble_data(gadget + '; ret')\n positions = []\n # construct list with all positions relative to start addr of gadget\n index = 0\n while(index < len(dump)):\n index = dump.find(gadget_asm, index)\n if index == -1:\n break\n positions.append(self.start_addr + index)\n index += len(gadget_asm)\n # close file\n dump_file.close()\n return positions\n\n def find(self, gadget, condition=None):\n \"\"\"\n Return the first result of find_all. If condition is specified, only\n consider addresses that meet the condition.\n \"\"\"\n condition = condition or (lambda x: True)\n try:\n return next(addr for addr in self.find_all(gadget) if condition(addr))\n except StopIteration:\n raise ValueError(\"Couldn't find matching address for \" + gadget)\n\n def find_all_formats(self, gadget_format, registers=GENERAL_REGISTERS):\n result = []\n # construct all possible gadgets with given registers\n gadgets = self.format_all_gadgets(gadget_format, registers)\n # for each gadget find first address in dump if any\n for gadget in gadgets:\n try:\n result.append((gadget, self.find(gadget)))\n except Exception:\n pass\n return result\n\n def find_format(self, gadget_format, registers=GENERAL_REGISTERS, condition=None):\n \"\"\"\n Return the first result of find_all_formats. If condition is specified,\n only consider addresses that meet the condition.\n \"\"\"\n condition = condition or (lambda x: True)\n try:\n return next(\n addr for addr in self.find_all_formats(gadget_format, registers)\n if condition(addr))\n except StopIteration:\n raise ValueError(\n \"Couldn't find matching address for \" + gadget_format)\n\n\nx = GadgetSearch(\"libc.bin\", 0xb7c39750)\n","sub_path":"5/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":3769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"376073507","text":"# Kostilniy modul\nfrom bases import BaseTelegramModule\nfrom telegram import (Bot, Update)\nfrom telegram.ext import (Filters, MessageHandler)\nfrom telegram.utils.helpers import escape_markdown\nimport pickle\nfrom random import choice\nfrom threading import Timer\n\n\nclass TelegramModule(BaseTelegramModule):\n def _load(self, filename: str):\n try:\n with open(filename, 'rb') as ff:\n return pickle.load(ff)\n except Exception:\n return {}\n\n\n def _save(self, obj: dict, filename: str):\n with open(filename, 'wb') as ff:\n pickle.dump(obj, ff, pickle.HIGHEST_PROTOCOL)\n\n\n def _is_private(self, chat_id):\n return chat_id > 0\n\n\n def __init__(self, api):\n super(TelegramModule, self).__init__(api)\n self.friendly_name = \"Multi Spin\"\n self._telegram_api._dispatcher.add_handler(MessageHandler(Filters.all, self.update_cache,\n edited_updates=True), group=-1)\n self._telegram_api.register_command(['spin'], self.spin)\n self._telegram_api.register_command(['spin_setname'], self.spin_setname)\n self.spin_name = self._load(\"spins.pkl\")\n self.results_today = {}\n self.chat_users = self._load(\"chat.pkl\")\n self.locks = []\n Timer(60.0, self.save).start()\n self.TEXT_ALREADY = \"Согласно сегодняшнему розыгрышу, *{s} дня* — `{n}`\"\n self.TEXTS = [[\"Итак, кто же сегодня *{s} дня*?\", \"_Хмм, интересно..._\", \"*АГА!*\",\n \"Сегодня ты *{s} дня,* {n}\"],\n [\"*Колесо Сансары запущено!*\", \"_Что за дичь?!_\", \"Ну ок...\",\n \"Поздравляю, ты *{s} дня,* {n}\"],\n [\"Кручу-верчу, *наебать* хочу\", \n \"Сегодня ты *{s} дня*, @spin\\_everyday\\_bot\",\n \"_(нет)_\", \"На самом деле, это {n}\"],\n [\"Эмм... Ты уверен?\", \n \"Ты *точно* уверен?\", \"Хотя ладно, процесс уже необратим\",\n \"Сегодня я назначаю тебе должность *{s} дня*, {n}!\"],\n [\"_Ищем рандомного кота на улице..._\", \"_Ищем палку..._\",\n \"_Ищем шапку..._\", \"_Рисуем ASCII-арт..._\",\n \"*Готово!*\", \"\"\"```\n.∧_∧\n( ・ω・。)つ━☆・*。\n⊂  ノ    ・゜+.\nしーJ   °。+ *´¨)\n         .· ´¸.·*´¨) ¸.·*¨)\n          (¸.·´ (¸.·'* ☆ ВЖУХ, И ТЫ {s} ДНЯ,```{n}\n \"\"\"]]\n \n\n def spin_setname(self, message, args):\n chat_id = message.chat_id\n try:\n spin_num = int(args[0])\n except Exception:\n self._telegram_api.send_text_message(chat_id,\n \"Usage `/spin_setname `\",\n markdown=True)\n return\n try:\n self.spin_name[chat_id][spin_num].update(args[1])\n except Exception:\n self.spin_name[chat_id] = {}\n self.spin_name[chat_id].update({spin_num: args[1]})\n self._telegram_api.send_text_message(message.chat_id, \"*Done*\", markdown=True)\n\n\n def spin(self, message, args):\n chat_id = message.chat_id\n try:\n spin_num = int(args[0])\n except Exception:\n spin_num = choice(list(self.spin_name.get(chat_id, [0])))\n s = escape_markdown(self.spin_name[chat_id].get(spin_num, \"79|0ub0d0u9|\"))\n try:\n p = self.results_today[chat_id].get(spin_num)\n except Exception:\n p = \"\"\n p = None\n self.results_today[chat_id] = {}\n if chat_id in self.locks:\n return\n if p is not None:\n self._telegram_api.send_text_message(chat_id, self.TEXT_ALREADY.format(s=s, n=p),\n markdown=True)\n else:\n p = escape_markdown(self.choose_random_user(chat_id, spin_num))\n from time import sleep\n curr_text = choice(self.TEXTS)\n self.locks.append(chat_id)\n for t in curr_text:\n self._telegram_api.send_text_message(chat_id, t.format(s=s, n=p),\n markdown=True)\n sleep(2)\n self.locks.pop(self.locks.index(chat_id))\n\n\n def update_cache(self, bot: Bot, update: Update):\n user = update.effective_user\n chat_id = update.effective_message.chat_id\n if not self._is_private(chat_id):\n try:\n self.chat_users[chat_id].update({user.id: user.name})\n except KeyError:\n self.chat_users[chat_id] = {}\n self.chat_users[chat_id].update({user.id: user.name})\n\n\n def choose_random_user(self, chat_id, spin_num):\n i = choice(list(self.chat_users[chat_id]))\n self.results_today[chat_id][spin_num] = self.chat_users[chat_id][i]\n return self.chat_users[chat_id][i]\n\n\n def save(self):\n self._save(self.chat_users, \"chat.pkl\")\n self._save(self.spin_name, \"spins.pkl\")\n Timer(60.0, self.save).start()\n","sub_path":"modules/multi_spin.py","file_name":"multi_spin.py","file_ext":"py","file_size_in_byte":5540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"531429988","text":"from utils import db_read, db_write\nimport datetime\n\ndef checkjoin(userId):\n data = db_read(\"\"\"SELECT `accno` FROM joinaccounts WHERE `user_id` = %s\"\"\",(userId,))\n # print(data)\n if data:\n return True\n return False\n\ndef loginaccount(userId,regdata):\n # data1 = db_read(\"\"\"SELECT accno FROM accountdet WHERE accno = %s AND name = %s AND nic = %s\"\"\",(regdata['number'], regdata['name'], regdata['nic']))\n data1 = db_read(\"\"\"SELECT accno FROM accountdet WHERE accno = %s AND nic = %s\"\"\",(regdata['number'], regdata['nic']))\n if data1:\n data2 = db_write(\"\"\"INSERT into joinaccounts (user_id, accno) VALUES (%s, %s)\"\"\",(userId,regdata['number']))\n if data2:\n return True, \"Now, you jave joined with your bank account!\\nEnjoy our service..\", 0\n return False, \"Error has occured with the Banking server. Sorry about that!\", 1\n return False, \"Some details may be invalid. Please re-enter Holding account number !\", 2\n\ndef getname(userId):\n data = db_read(\"\"\"SELECT `name` FROM accountdet NATURAL JOIN joinaccounts WHERE `user_id` = %s\"\"\", (userId,))\n # print(data[0]['name'])\n return data[0]['name']\n\ndef getpersonal(userId):\n data = db_read(\"\"\"SELECT `first_name`, `email`, `name`, `accno`, `nic`, `branch` FROM users NATURAL JOIN joinaccounts JOIN accountdet USING (`accno`) WHERE `user_id` = %s\"\"\", (userId,))\n # print(data[0])\n return data[0]\n \ndef getAccBalance(userId):\n data = db_read(\"\"\"SELECT `balance` FROM transactions NATURAL JOIN accountdet JOIN joinaccounts USING (`accno`) JOIN users USING (`user_id`) WHERE `user_id` = %s ORDER BY `date` DESC LIMIT 1\"\"\", (userId,))\n # print(data[0]['balance'])\n return data[0]['balance']\n \ndef getTransactions(userId):\n data = db_read(\"\"\"SELECT `description`, `debit`, `credit`, `balance`, `date` FROM transactions NATURAL JOIN accountdet JOIN joinaccounts USING (`accno`) JOIN users USING (`user_id`) WHERE `user_id` = %s ORDER BY `date` ASC LIMIT 10\"\"\", (userId,))\n # print(data)\n return data\n\ndef dotransfer(userId, transdet):\n data1 = db_read(\"\"\"SELECT `balance` FROM accountdet NATURAL JOIN transactions WHERE accno = %s AND name = %s ORDER BY `date` DESC LIMIT 1\"\"\", (transdet['number'], transdet['name'])) \n if data1:\n benefBalance = data1[0]['balance']\n senderdet = getpersonal(userId)\n data2 = db_write(\"\"\"INSERT INTO transactions (`accno`, `description`, `debit`, `balance`) VALUES (%s, %s, %s, %s)\"\"\", (transdet['number'], \"transfered from \"+ senderdet['name'], transdet['amount'], (transdet['amount'] + benefBalance) ) )\n if data2:\n data3 = db_write (\"\"\"INSERT INTO transactions (`accno`, `description`, `credit`, `balance`) VALUES (%s, %s, %s, %s)\"\"\", (senderdet['accno'], \"transfered to \"+transdet['name'], transdet['amount'], getAccBalance(userId) - transdet['amount'] ) )\n if data3:\n return True, \"Congratulations! Money transfer is completed to \"+ str(transdet['number'])+ \" account by Rs.\"+ str(transdet['amount']), 0\n return False, \"Error has occured with the Banking server. Sorry about that!\", 1\n return False, \"Error has occured with the Banking server. Sorry about that!\", 1\n return False, \"There is no bank account for entered account number and name. Please re-enter the beneficiary's account number\", 2\n\ndef dopayment(userId,paydata):\n data1 = db_read(\"\"\"SELECT nic FROM consumers WHERE name = %s AND address = %s\"\"\", (paydata['name'],paydata['address']))\n if data1:\n data2 = db_read(\"\"\"SELECT accno FROM fields WHERE fieldname = %s\"\"\", (paydata['field'],))\n if data2 and str(data2[0]['accno']) == str(paydata['number']):\n # print(data1)\n consumernic = data1[0]['nic']\n fieldaccno = data2[0]['accno']\n # print(consumernic, fieldaccno)\n\n data3 = db_read(\"\"\"SELECT `balance` FROM billpaymenttransactions WHERE `accno` = %s AND nic = %s ORDER BY `date` DESC LIMIT 1\"\"\", (fieldaccno, consumernic))\n if data3:\n billbalance = data3[0]['balance']\n\n data4 = db_write(\"\"\"INSERT INTO billpaymenttransactions (`accno`, `nic`, `credit`, `balance`) VALUES (%s, %s, %s, %s)\"\"\", ( fieldaccno, consumernic, paydata['amount'], billbalance - paydata['amount'] ))\n if data4:\n dealer = getpersonal(userId)\n data5 = db_write(\"\"\"INSERT INTO transactions (`accno`, `description`, `credit`, `balance`) VALUES (%s, %s, %s, %s)\"\"\", (dealer['accno'], (paydata['name']+\"'s \" + paydata['field'] + \"bill paid \") , paydata['amount'], getAccBalance(userId) - paydata['amount'] ))\n if data5:\n return True, \"Congratulations! \"+paydata['field']+\" Bill payment is completed to \"+ str(fieldaccno)+ \" account by Rs.\"+ str(paydata['amount']), 0\n return False, \"Error has occured with the Banking server. Sorry about that!\", 1\n return False, \"Error has occured with the Banking server. Sorry about that!\", 1\n return False, \"Seems like \"+paydata['name']+\" does not have balance to be pay\", 2\n return False, \"There is a no such field registerd in our service. Please enter the field name\", 3\n return False, \"There is a no such name or address in our service. Please enter the name \", 4\n\ndef reportcomplain(complaindet):\n data1 = db_read(\"\"\"SELECT `id` FROM branches WHERE `branchname` = %s\"\"\", (complaindet['branch'],))\n if data1:\n brID = data1[0]['id']\n type = complaindet['type']\n data2 = False\n\n if type == 'complain_behaviour':\n data2 = db_write(\"\"\"INSERT INTO banking_complaints (`brid`, `complain_behaviour`) VALUES (%s, %s)\"\"\", (brID, complaindet['description']))\n elif type == 'complain_management':\n data2 = db_write(\"\"\"INSERT INTO banking_complaints (`brid`, `complain_management`) VALUES (%s, %s)\"\"\", (brID, complaindet['description']))\n elif type == 'complain_facility':\n data2 = db_write(\"\"\"INSERT INTO banking_complaints (`brid`, `complain_facility`) VALUES (%s, %s)\"\"\", (brID, complaindet['description']))\n else:\n data2 = db_write(\"\"\"INSERT INTO banking_complaints (`brid`, `complain_wasting`) VALUES (%s, %s)\"\"\", (brID, complaindet['description']))\n\n if data2:\n return True, \"Sorry for the inconvenience !.We'll report the complaint\", 0\n return False, \"Error has occured with the Banking server. Sorry about that!\", 1\n return False, \"There is a no such branch in our service. Please enter the branch name\", 2\n\n# print(getTransactions(3))\n# print(getpersonal('1'))\n# print(dopayment(1,{'model': 'payment', 'field': 'Electricity', 'number': 11111, 'name': \"K.W.Saranga\", 'address': '170/A, dobagahawatta, norway', 'amount': 200.0, 'code': 182172}))\n# print(reportcomplain({'model':'complain', 'type':'complain_wasting', 'branch':'galle', 'description':'billing counter accountant is not familiar with people'}))\n# print(dotransfer(1,{'model': 'transfer', 'number': 456123789, 'name': 'Jorge Washinton', 'amount': 500.0, 'code': 431435}))\n# print(loginaccount(5,{'number':'895623125','name':'S.C.Dhavinchi','nic':'5588124722V'}))\n# print(checkjoin('6 or 1=1'))\n# print(getAccBalance(2))\n# print(getname(\"sadakan OR 1=1\"))","sub_path":"package_management.py","file_name":"package_management.py","file_ext":"py","file_size_in_byte":7354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"545712710","text":"\"\"\"Method returning the template for the Get your home ready page\"\"\"\n\nfrom django.conf import settings\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\n\nfrom ..forms import HomeReadyForm\n\n\ndef home_ready(request):\n \"\"\"\n :param request: a request object used to generate the HttpResponse\n :return: an HttpResponse object with the rendered Get your home ready template\n \"\"\"\n if request.method == 'GET':\n application_id_local = request.GET['id']\n form = HomeReadyForm()\n variables = {\n 'application_id': application_id_local,\n 'form': form\n }\n return render(request, 'next-steps-home.html', variables)\n\n if request.method == 'POST':\n\n application_id_local = request.POST[\"id\"]\n form = HomeReadyForm(request.POST)\n\n if form.is_valid():\n return HttpResponseRedirect(\n settings.URL_PREFIX + '/prepare-interview?id=' + application_id_local)\n else:\n variables = {\n 'form': form,\n 'application_id': application_id_local\n }\n\n return render(request, 'next-steps-home.html', variables)\n","sub_path":"application/views/home_ready.py","file_name":"home_ready.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"508944712","text":"__author__ = 'asanyal'\n\nimport cv2\nimport numpy as np\n\n\"\"\"\nThis class allows for a set of morphological transforms to be applied\non an image\n\nTypically this is used to remove lines from an image without affecting the image\n\"\"\"\nclass MorphologicalTranforms:\n\n def __init__(self, imgFile):\n self.img = cv2.imread(imgFile)\n self.gray_img = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)\n self.edges = cv2.Canny(self.gray_img, 50, 150, apertureSize = 3)\n\n self.smoothed_line_removed_img = None\n\n # Removes lines from sheet music and keeps a an in memory numpy copy\n # of the image\n def remove_lines_from_sheet(self, imgFile):\n\n adaptiveThreshHoldImage = cv2.adaptiveThreshold(~self.gray_img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 15, -2)\n\n # cv2.imshow('gray', adaptiveThreshHoldImage)\n\n # The sizes of the images\n vertical = adaptiveThreshHoldImage.copy()\n\n (rows, cols) = adaptiveThreshHoldImage.shape\n\n verticalStructure = cv2.getStructuringElement(cv2.MORPH_RECT,(1, 3))\n\n vertical = cv2.erode(vertical, verticalStructure, iterations = 1);\n vertical = cv2.dilate(vertical, verticalStructure, iterations = 1);\n\n vertical = cv2.bitwise_not(vertical)\n\n self.smoothed_line_removed_img = \\\n cv2.adaptiveThreshold(vertical, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 3, -2)\n","sub_path":"src/main/python/image/MorphologicalTransforms.py","file_name":"MorphologicalTransforms.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"428453393","text":"from django.core.mail import send_mail\nfrom django.db import models\nfrom django.db.models import Max\nfrom django.db.models.functions import datetime\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import redirect\nfrom django.utils import timezone\nfrom django.conf import settings\nfrom uuid import uuid4\nfrom threading import Thread\nimport time\n\n# Create your models here.\nclass Student(models.Model):\n jmeno = models.CharField(max_length=30)\n prijmeni = models.CharField(max_length=30)\n trida = models.CharField(max_length=10)\n email = models.CharField(max_length=70)\n token = models.CharField(max_length=50, blank=True)\n voted = models.BooleanField(default=False)\n\n def __str__(self):\n return (\"{} {} {}\".format(self.jmeno, self.prijmeni, self.trida))\n\n\nclass Kandidat(models.Model):\n Student = models.ForeignKey(Student, on_delete=models.CASCADE)\n votes = models.IntegerField(default=0)\n\n def __str__(self):\n return \"{} - {}\".format(self.Student, self.votes)\n\n\nclass Vitezove(models.Model):\n jmeno = models.CharField(max_length=30)\n prijmeni = models.CharField(max_length=30)\n trida = models.CharField(max_length=10)\n votes = models.IntegerField(default=0)\n\n def __str__(self):\n return (\"{} {} {} {}\".format(self.jmeno, self.prijmeni, self.trida, self.votes))\n\n\nclass DataFile(models.Model):\n nazev = models.CharField(max_length=50)\n soubor = models.FileField(upload_to='uploaded_files')\n konec_kandidovani = models.DateTimeField()\n konec_hlasovani = models.DateTimeField()\n\n def __str__(self):\n return self.nazev\n\n def save(self, *args, **kwargs):\n print(\"Saving this shit\")\n\n super(DataFile, self).save()\n print(\"Saved\")\n\n file_process(self.soubor.url)\n ukoncit_cokoliv(self.konec_kandidovani, self.konec_hlasovani)\n\n\ndef file_process(file=None):\n\n Student.objects.all().delete()\n\n with open(file) as f:\n linky = f.read().split(\"\\n\")\n for line in linky:\n data_dict = {}\n neco = line.split(\";\")\n try:\n stud = Student()\n stud.jmeno = neco[0]\n stud.prijmeni = neco[1]\n stud.trida = neco[2]\n stud.email = neco[3]\n stud.token = uuid4()\n stud.save()\n except IndexError:\n # tohle je tu schvalne\n pass\n print(\"Parsovani dokonceno\")\n\n\ndef postpone(function):\n def decorator(*args, **kwargs):\n t = Thread(target = function, args=args, kwargs=kwargs)\n t.daemon = True\n t.start()\n return decorator\n\n\n@postpone\ndef ukoncit_cokoliv(konec_kandidovani, konec_hlasovani):\n main = konec_kandidovani\n mail(\"kandidovat\")\n while True:\n if timezone.now() >= main:\n print(\"ya all shit\")\n if main != konec_hlasovani:\n # udela se to co se ma udelat po konci kandidovani\n print(\"konec kandidatury...\")\n mail(\"hlasovani\")\n main = konec_hlasovani\n else:\n # udela se to co se ma udelat po konci hlasovani\n print(\"konec hlasovani...\")\n res = Kandidat.objects.values('Student__trida').annotate(votes=Max('votes'))\n for trida in res:\n aqswe = Kandidat.objects.filter(Student__trida=trida['Student__trida'], votes=trida['votes'])[0]\n vitez = Vitezove()\n vitez.jmeno=aqswe.Student.jmeno\n vitez.prijmeni=aqswe.Student.prijmeni\n vitez.trida=aqswe.Student.trida\n vitez.votes=aqswe.votes\n vitez.save()\n mail(\"vysledky\")\n break\n else:\n time.sleep(10)\n pass\n\n\n\n@postpone\ndef mail(faze):\n all_students = Student.objects.all()\n for student in all_students:\n subject = \"Volby do studentského parlamentu vole - \"+faze\n from_email = settings.EMAIL_HOST_USER\n to_email = [student.email]\n message = \"http://127.0.0.1:8000/\" + faze + \"/\" + student.token\n if faze == \"vysledky\":\n message = \"http://127.0.0.1:8000/\" + faze\n send_mail(subject, message, from_email, to_email, fail_silently=False)","sub_path":"SkolniParlament-master/SkolniParlament/hlasovani/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"26964970","text":"import pickle\nimport time\nfrom statistics import mean, stdev\n\nfrom sklearn.metrics import auc, roc_curve\n\nimport yamlconf\n\nfrom ..extractors import Extractor\nfrom .util import normalize_json\n\n\nclass Scorer:\n\n def __init__(self, model_map, extractor):\n \"\"\"\n :Parameters:\n model_map : dict\n A mapping between model names and `ScorerModel` s.\n extractor : `revscoring.extractors.Extractor`\n An extractor to use for gathering feature values\n \"\"\"\n self._check_compatibility(model_map, extractor)\n self.model_map = model_map\n self.extractor = extractor\n\n def score(self, rev_id, models=None):\n # If a set of models isn't specified, score with all of 'em\n models = models or self.model_map.keys()\n\n # Gather a single tuple of unique features needed by the models\n features = tuple({feature for name in models\n for feature in self.model_map[name].features})\n\n feature_values = self.extractor.extract(rev_id, features)\n feature_map = {f:v for f,v in zip(features, feature_values)}\n\n scores = {}\n for name in models:\n model = self.model_map[name]\n feature_values = [feature_map[f] for f in model.features]\n scores[name] = model.score(feature_values)\n\n return scores\n\n def _check_compatibility(self, model_map, extractor):\n for _, model in model_map.items():\n if extractor.language != model.language:\n raise ValueError((\"Model language {0} does not match \" +\n \"extractor language {1}\")\\\n .format(model.language.name,\n extractor.language.name))\n\n @classmethod\n def from_config(cls, config, name, section_key=\"scorers\"):\n \"\"\"\n Expects:\n\n scorers:\n enwiki:\n models:\n damaging: enwiki_damaging_2014\n good-faith: enwiki_good-faith_2014\n extractor: enwiki\n ptwiki:\n models:\n damaging: ptwiki_damaging_2014\n good-faith: ptwiki_good-faith_2014\n extractor: ptwiki\n\n extractors:\n enwiki_api: ...\n ptwiki_api: ...\n\n scorer_models:\n enwiki_damaging_2014: ...\n enwiki_good-faith_2014: ...\n \"\"\"\n section = config[section_key][name]\n\n model_map = {}\n for name, key in section['models'].items():\n model = ScorerModel.from_config(config, key)\n model_map[name] = model\n\n extractor = Extractor.from_config(config, section['extractor'])\n\n return cls(model_map, extractor)\n\n\nclass ScorerModel:\n \"\"\"\n A model used to score a revision based on a set of features.\n \"\"\"\n\n def __init__(self, features, language=None):\n \"\"\"\n :Parameters:\n features : `list`(`Feature`)\n A list of `Feature` s that will be used to train the model and\n score new observations.\n language : `Language`\n A language to use when applying a feature set.\n \"\"\"\n self.features = tuple(features)\n self.language = language\n\n\n def score(self, feature_values):\n \"\"\"\n Make a prediction or otherwise use the model to generate a score.\n\n :Parameters:\n feature_values : collection(`mixed`)\n an ordered collection of values that correspond to the\n `Feature` s provided to the constructor\n\n :Returns:\n A `dict` of statistics\n \"\"\"\n raise NotImplementedError()\n\n\n def _validate_features(self, feature_values):\n \"\"\"\n Checks the features against provided values to confirm types,\n ordinality, etc.\n \"\"\"\n return [feature.validate(feature_values)\n for feature, value in zip(self.feature, feature_values)]\n\n def _generate_stats(self, values):\n columns = zip(*values)\n\n stats = tuple((mean(c), stdev(c)) for c in columns)\n\n return stats\n\n def _scale_and_center(self, values, stats):\n\n for feature_values in values:\n yield (tuple((val-mean)/max(sd, 0.01)\n for (mean, sd), val in zip(stats, feature_values)))\n\n @classmethod\n def from_config(cls, config, name, section_key='scorer_models'):\n section = config[section_key][name]\n\n if 'module' in section:\n return yamlconf.import_module(section['module'])\n elif 'class' in section:\n class_path = section['class']\n Class = yamlconf.import_module(class_path)\n assert cls != Class\n return Class.from_config(config, name)\n\n\nclass MLScorerModel(ScorerModel):\n \"\"\"\n A machine learned model used to score a revision based on a set of features.\n\n Machine learned models are trained and tested against labeled data.\n \"\"\"\n\n def train(self, values_labels):\n \"\"\"\n Trains the model on labeled data.\n\n :Parameters:\n values_scores : `iterable`((``, `