diff --git "a/6489.jsonl" "b/6489.jsonl" new file mode 100644--- /dev/null +++ "b/6489.jsonl" @@ -0,0 +1,621 @@ +{"seq_id":"117393000","text":"import random\nimport csv\nfrom random import randint\n\nstarts = ['find flights', 'get my flights', 'find', '', 'book a flight', 'search', 'flights']\nmonth_lst = ['January', 'Feburary', 'March', 'April', 'May', 'June', 'July',\n 'August', 'September', 'October', 'November', 'December']\ndays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n\ndef main():\n gen_file('test.txt', 50)\n\ndef gen_file(filename, units):\n data = gen_phrase(units)\n file = open(filename, 'a')\n file.write(gen_trainning_data(data[0], data[1]))\n file.close()\n\n\ndef flatten(x):\n return [item for sublist in x for item in sublist]\n\ndef multi_tags(number, tag):\n res = []\n for i in range(number):\n if i == 0:\n res.append('B-' + tag)\n else:\n res.append('I-' + tag)\n\n return res\n\ndef align_data(data):\n spacings = [max([len(seq[i]) for seq in data.values()])\n for i in range(len(data[list(data.keys())[0]]))]\n data_aligned = dict()\n\n for key, seq in data.items():\n str_aligned = \"\"\n for token, spacing in zip(seq, spacings):\n str_aligned += token + \" \" * (spacing - len(token) + 1)\n\n data_aligned[key] = str_aligned\n\n return data_aligned\n\ndef get_start():\n text = random.choice(starts)\n length = len(text.split(' '))\n return [text, ['O'] * length]\n\n# CVS with lots of cities\nimport os\npath = os.path.dirname(os.path.abspath(__file__))\nwith open(path + '/cities.csv', 'rt') as f:\n reader = csv.reader(f)\n cities = flatten(list(reader))\n\ndef get_city(tag, label):\n random_city = random.choice(cities)\n num_parts = len(random_city.split(' '))\n texts = tag + ' ' + random_city\n tags = ['O']*len(tag.split(' ')) + multi_tags(num_parts, label)\n return [texts, tags]\n\ndef getOrigin():\n return get_city('from', 'from')\n\ndef getDestination():\n return get_city('to', 'to')\n\n\n# Relative dates\nrelav_dates = [['today', 'tomorrow']]\nrelav_dates.append(days)\nrelav_dates.append(list(map(lambda x: 'next ' + x, days)))\nrelav_dates.append(list(map(lambda x: 'this ' + x, days)))\nrelav_dates = flatten(relav_dates)\n\ndef get_date(starts, tag):\n type = randint(0, 1)\n len_start = 0\n start = random.choice(starts)\n if start != '':\n len_start = len(start.split(' '))\n\n if type == 0:\n #relative\n choice = random.choice(relav_dates)\n if start != '':\n text = start + ' ' + choice\n else:\n text = choice\n len_text = len(choice.split(' '))\n labels = ['O'] * len_start + multi_tags(len_text, tag)\n else:\n #absolute\n choice = random.choice(month_lst) + ' DIGITDIGIT' + (' th' if randint(0, 1) == 0 else '')\n if start != '':\n text = start + ' ' + choice\n else:\n text = choice\n len_text = len(choice.split(' '))\n labels = ['O'] * len_start + multi_tags(len_text, tag)\n return [text, labels]\n\ndef get_departure_date():\n starts = ['', 'on', 'for', 'departing on', 'departing']\n return get_date(starts, 'departure_date')\n\ndef get_return_date():\n starts = ['to', 'returning on', 'comming back on', 'returning', 'comming back']\n return get_date(starts, 'return_date')\n\ndef gen_phrase(nums, log=False):\n sentences_x = []\n sentences_y = []\n for i in range(nums):\n labels = []\n text = []\n # TODO shuffle\n sentence = [get_start(), getOrigin(), getDestination(), get_departure_date()]\n if randint(0, 1) == 0:\n sentence.append(get_return_date())\n for part in sentence:\n text.append(part[0])\n labels.append(part[1])\n\n text = ' '.join(text).split(' ')\n labels = flatten(labels)\n sentences_x.append(text)\n sentences_y.append(labels)\n\n if log:\n to_print = align_data({\"input\": text, \"output\": labels})\n for key, seq in to_print.items():\n print(seq)\n print()\n\n return [sentences_x, sentences_y]\n\ndef gen_trainning_data(X, Y):\n if len(X) != len(Y):\n return 'Error'\n content = ''\n for sentence in range(len(X)):\n for i in range(len(X[sentence])):\n if X[sentence][i] == '':\n continue\n content += X[sentence][i] + ' ' + Y[sentence][i] + '\\n'\n\n content += '\\n'\n return content\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"data/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":4439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"132957855","text":"#Biggie Size - \nfor x in range(len(arr)):\n if arr[x]>0:\n arr[x]='big'\nreturn arr\nprint(biggie_size([-3,1,4,-1,2]))\n\n\n#Count Positives - \ndef count_positives(arr):\n counter = 0\n for val in arr:\n if val > 0:\n counter += 1\n arr[len(arr)-1] = counter\n return arr\nprint([-5,-9,0,32,-6,22])\nprint(count_positives([1,-1,1,-2,-3]))\n\n# 3 Sum Total - \ndef sum_total(array):\n sum = 0\n for i in array:\n sum += i\n return sum\nprint(sum_total([1,1,1,1]))\nprint(sum_total([100,3,6,10]))\n\n\n#Average\ndef avg(list):\n sum = 0\n for x in list:\n sum += x\n return (sum/len(list))\nprint(avg([2,10,4,5]))\n\n#Length\ndef lengthFun(arr):\n return len(arr)\nprint(lengthFun([1,1,1,1,1,4]))\nprint(lengthFun([1,1]))\n\n# minimum\ndef minimum(arr):\n if len(arr)<0:\n return False\n minInt = arr[0]\n for x in arr:\n if xx:\n myDictonary['maximun'] = x\n myDictonary['sumTotal']+= x\n myDictonary['average']=myDictonary['sumTotal']/len(array)\n return myDictonary\nprint(ultimate_analysis([2,8,3,2,10,5]))\n\n\n# reverse list\ndef reverse_list(arr):\n for i in range(0, (len(arr)-1)//2):\n temp = arr[i]\n arr[i] = arr[len(arr)-1-i]\n arr[len(arr)-1-i] = temp\n return arr\nprint(reverse_list([11,12,13]))","sub_path":"_python/python_stack/_python/assignments/forloop_basics_2.py","file_name":"forloop_basics_2.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"417913941","text":"from modules.model import *\nfrom modules.Preprocessing import *\nfrom modules.viz import *\nfrom modules.saver import *\n\ndef main():\n \n trainFeatures, trainLabels, testFeatures, testLabels, Dataset = preprocessing(r'D:\\4th CSE\\Neural Networks\\Project\\MNISTcsv')\n # trainFeatures, trainLabels, testFeatures, testLabels, Dataset = preprocessing_online('CIFAR10')\n trainLabels_ = trainLabels\n trainLabels = labels_to_onehot(trainLabels)\n\n \n X = trainFeatures.T\n Y = trainLabels\n layers_dims = [X.shape[0], 128, 10]\n activation_fns = [\"sigmoid\", \"softmax\"]\n batch_size = 30\n epochs = 30\n learning_rate = 0.5\n costt = \"multiclass\"\n metrics = [\"accuracy\" ,\"macro\"]\n optimizer = \"momentum\"\n \n plotDataset(trainFeatures, Dataset)\n\n model = Model(layers_dims, activation_fns)\n \n metrics_output = model.fit(X, Y, learning_rate, metrics, epochs, batch_size, costt, optimizer)\n\n visualizeMetrics(metrics_output, epochs)\n\n saver.save(model) \n # loaded_model = saver.restore()\n \n \n pred = model.predict(testFeatures.T)\n Y_hat = model.predict(trainFeatures.T)\n accuracy = accuracy_metrics(pred.T, testLabels.T) * 100\n print(f\"\\nThe accuracy rate of TEST DATASET is: {accuracy:.2f}%.\")\n \nif __name__ == \"__main__\":\n main()","sub_path":"FC-MNIST.py","file_name":"FC-MNIST.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"162133383","text":"import os\nfrom datetime import datetime, timedelta, timezone\nimport re\nimport psycopg2\nfrom psycopg2.extras import DictCursor\n\nimport scraping\n\nDATABASE_URL = os.environ.get('DATABASE_URL')\n\nJST = timezone(timedelta(hours=+9), 'JST')\n\ndef get_connection():\n dsn = os.environ.get('DATABASE_URL')\n return psycopg2.connect(dsn)\n\ndef sql_requests(sql, res=True):\n with get_connection() as conn:\n with conn.cursor() as cur:\n cur.execute(sql)\n if res:\n ans = list(cur.fetchall())\n return ans\n\ndef current_tournament():\n sql = \"SELECT room_id, url, name FROM tournaments ORDER BY start_at desc limit 1;\"\n ans = sql_requests(sql)\n return ans[0][0], ans[0][1], ans[0][2]\n\ndef set_tournament(name,room,url):\n time = \"{:%Y%m%d %H:%M:%S}\".format(datetime.now(JST))\n sql = f\"UPDATE tournaments SET name='{name}', start_at = '{time}', url = '{url}' WHERE room_id='{room}';\" \\\n f\"INSERT INTO tournaments (name, room_id, start_at, url) SELECT '{name}', '{room}', '{time}', '{url}'\" \\\n f\"WHERE NOT EXISTS (SELECT room_id FROM tournaments WHERE room_id='{room}')\"\n sql_requests(sql,res=False)\n return f\"大会名:{name}を登録しました\"\n\ndef get_score_sum(room):\n sql = f\"SELECT B.nickname, sum(A.score) FROM scores A INNER JOIN nickname B ON A.user_name = B.tenhou_name WHERE A.room_id = '{room}' GROUP BY B.nickname ORDER BY sum DESC;\"\n return sql_requests(sql)\n\ndef set_user(nickname, tenhou):\n sql = f\"UPDATE nickname SET nickname='{nickname}' WHERE tenhou_name='{tenhou}';\" \\\n f\"INSERT INTO nickname (nickname, tenhou_name) SELECT '{nickname}', '{tenhou}'\" \\\n f\"WHERE NOT EXISTS (SELECT tenhou_name FROM nickname WHERE tenhou_name='{tenhou}')\"\n sql_requests(sql, res=False)\n\ndef init_user():\n sql = f\"INSERT INTO nickname(nickname, tenhou_name)\"\\\n \"SELECT DISTINCT user_name, user_name FROM scores \"\\\n \"WHERE NOT EXISTS (SELECT tenhou_name FROM nickname WHERE tenhou_name=user_name); \"\n sql_requests(sql, res=False)\n\ndef update_score(day, room):\n init_user()\n logs = scraping.get_log(day, room)\n if len(logs) == 0:\n return f\"{day}に対戦がありません\"\n values = []\n for num in range(len(logs)):\n log = logs[num]\n for i in range(4):\n name, score = log['score'][i].split(\",\")\n values.append(f\"('{log['date']}', {num}, '{name}', {i+1}, {score}, '{room}')\")\n with get_connection() as conn:\n with conn.cursor() as cur:\n cur.execute(f\"DELETE FROM scores WHERE date BETWEEN '{day}' AND '{day} 23:59:59' AND room_id = '{room}';\")\n sql = \"INSERT INTO scores (date, id, user_name, rank, score, room_id) VALUES \"\n cur.execute(sql + \",\".join(values) + \";\")\n return \"OK\"","sub_path":"my_database.py","file_name":"my_database.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"499348276","text":"numbers = []\nn = int(input(\"Ile liczb chcesz wprowadzić: \"))\nfor numer in range(n):\n komunikat = f\"Podaj liczbę nr {numer+1}:\"\n numbers.append(int(input(komunikat)))\nprint(\"Wprowadzone liczby:\", numbers)\n\nx = 0\ni = 0\nwhile i <= n:\n x = x + numbers[i]\n print(numbers[i])\n print(x)\n i = i + x\n print(i)\nprint(\"Suma liczb wynosi\", i)\n\n\nx = 0\ni = 0\nwhile i < n:\n x = x + numbers[i]\n i = i + 1\nx = x / n\nkomunikat = f\"Średnia liczb wynosi {x}\"\nprint(komunikat)","sub_path":"04_Kontrola_przeplywu_programu/07_Srednia/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"286037948","text":"import youtube_dl\nfrom youtube.settings import MEDIA_ROOT\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom app.models import Link\n\n\n\ndef index(request):\n link_list = Link.objects.all() # Получаем все объекты\n paginator = Paginator(link_list, 5) # Максимальный вывод объектов на странице 5\n page = request.GET.get('page')\n\n try:\n links = paginator.page(page)\n except PageNotAnInteger:\n links = paginator.page(1) # Если страница не integer выводим первую страницу\n except EmptyPage:\n links = paginator.page(paginator.num_pages) # Если в запросе у нас превышает число страниц пагинации выводим последнюю страницу\n\n return render(request, 'app/index.html', {'links': links}) # Рендерим это все на страницу\n\n\ndef download_video(request):\n if request.is_ajax(): # Проверяем был ли AJAX запрос\n get_request = request.GET['url'] # Ловим url который передали аяксом\n response = HttpResponse()\n response.set_cookie('url', get_request) # Устанавливаем куку для каждого запроса\n\n url = Link(url=get_request) # Добавляем наш url в поле url\n url.save() # Сохраняем нашу модель\n\n ydl_opts = { # Опции библиотеки youtube_dl\n 'outtmpl': MEDIA_ROOT+'/'+'%(title)s.%(ext)s', # Путь куда скачивается видео\n }\n\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n ydl.download([get_request]) # Скачиваем видео\n return response\n else:\n return render(request, 'app/index.html') # Если AJAX запрос не пришел выводим страницу index.html\n\n\n\n\n\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"220193506","text":"import json\nimport urllib\nimport matplotlib.pyplot as plt\n\napi_key = '62b7f9d2a728c714895284495109ad85'\nregion = 'daejeon,kr'\nurl = \"http://api.openweathermap.org/data/2.5/forecast?q=\" + region + \"&appid=\" + api_key\ndata = urllib.urlopen(url).read() # parsing contents from the url\njson_data = json.loads(data) # dict type\n\ntime = []\ntemp = []\ncount = 0\nfor eachs in json_data['list']:\n\ttemp.append(eachs['main']['temp'])\n\ttime.append(eachs['dt_txt'])\n\tcount += 1\n\nplt.plot(range(1, count+1), temp)\nplt.xticks(range(1, count+1), time, rotation=45)\nplt.title(region + '-temperature(F)')\nplt.tight_layout()\nplt.show()\n","sub_path":"forExam/pyowm_json.py","file_name":"pyowm_json.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"359323190","text":"from rest_framework.generics import ListAPIView, CreateAPIView\nfrom rest_framework.permissions import ( AllowAny, IsAuthenticated, IsAdminUser, IsAuthenticatedOrReadOnly,\n\t)\nfrom rest_framework.serializers import ValidationError\n\nfrom blog.models import BlogInfo, CommentsInfo\nfrom .serializers import PostSerializer, CommentCreateSerializer\n\nclass PostListAPIView(ListAPIView):\n\tqueryset\t\t = BlogInfo.objects.all()\n\tserializer_class = PostSerializer\n\nclass CommentCreateView(CreateAPIView):\n\tqueryset = CommentsInfo.objects.all()\n\tserializer_class = CommentCreateSerializer\n\tpermission_classes = [IsAuthenticated]\n\n\tdef perform_create(self, serializer):\n\t\tparent_slug = self.request.GET.get('parent_slug')\n\t\tblog_slug = self.request.GET.get('blog_slug')\n\t\tcreater = self.request.user\n\t\t\n\t\t# parent\n\t\tif parent_slug:\n\t\t\t\n\t\t\tparent \t\t= CommentsInfo.objects.filter(slug = parent_slug)\n\t\t\tif parent.exists() and parent.count() == 1:\n\t\t\t\tparent = parent.first()\n\t\t# blog\n\t\t\tblog \t\t= \tCommentsInfo.objects.get(slug = parent_slug).blog\n\t\telif blog_slug:\n\t\t\tblog \t=\tBlogInfo.objects.filter(slug = blog_slug)\n\t\t\tif blog.exists() and blog.count() == 1:\n\t\t\t\tblog = blog.first()\n\t\t\telse:\n\t\t\t\traise ValidationError('Unique blog/blog not found')\n\t\t\tparent = None\n\t\telse:\n\t\t\traise ValidationError('Please provide either blog slug or the parent slug')\n\n\t\tserializer.save(\tcreater = creater,\n\t\t\t\t\t\t\tparent = parent,\n\t\t\t\t\t\t\tblog = blog\n\t\t\t\t\t\t)\n\n\n\n\t\n","sub_path":"src/blog/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"364022338","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom datetime import datetime, timedelta\nimport itertools\nimport numpy as np\nimport pandas as pd\nfrom covsirphy.cleaning.term import Term\n\n\nclass PhaseSeries(Term):\n \"\"\"\n A series of phases.\n\n Args:\n first_date (str): the first date of the series, like 22Jan2020\n last_record_date (str): the last date of the records, like 25May2020\n population (int): initial value of total population in the place\n \"\"\"\n\n def __init__(self, first_date, last_record_date, population):\n self.first_date = first_date\n self.last_record_date = last_record_date\n self.init_population = population\n self.clear(include_past=True)\n\n def clear(self, include_past=False):\n \"\"\"\n Clear phase information.\n\n Args:\n include_past (bool):\n - if True, include past phases.\n - future phase are always included\n\n Returns:\n self\n \"\"\"\n self.phase_dict = self._init_phase_dict(include_past=include_past)\n self.info_dict = self._init_info_dict(include_past=include_past)\n return self\n\n def _init_phase_dict(self, include_past=False):\n \"\"\"\n Return initialized dictionary which is to remember phase ID of each date.\n\n Args:\n include_past (bool):\n - if True, include past phases.\n - future phase are always included\n\n Returns:\n (dict)\n - key (pd.TImeStamp): dates from the first date to the last date of the records\n - value (int): 0 (phase ID)\n \"\"\"\n past_date_objects = pd.date_range(\n start=self.first_date, end=self.last_record_date, freq=\"D\"\n )\n if include_past:\n return dict.fromkeys(past_date_objects, 0)\n last_date_obj = self.date_obj(self.last_record_date)\n phase_dict = {\n k: v for (k, v) in self.phase_dict.items()\n if k <= last_date_obj\n }\n return phase_dict\n\n def _init_info_dict(self, include_past=False):\n \"\"\"\n Return initialized dictionary which is to remember phase information.\n\n Args:\n include_past (bool):\n - if True, include past phases.\n - future phase are always included\n\n Returns:\n (dict)\n - 'Start': the first date of the records\n - 'End': the last date of the records\n - 'Population': initial value of total population\n \"\"\"\n if include_past:\n info_dict = {\n 0: {\n self.TENSE: self.PAST,\n self.START: self.first_date,\n self.END: self.last_record_date,\n self.N: self.init_population\n }\n }\n return info_dict\n last_date_obj = self.date_obj(self.last_record_date)\n info_dict = {\n k: v for (k, v) in self.info_dict.items()\n if self.date_obj(v[self.END]) <= last_date_obj\n }\n return info_dict\n\n def _phase_name2id(self, phase):\n \"\"\"\n Return phase ID of the phase.\n\n Args:\n phase (str): phase name, like 1st, 2nd, 3rd,...\n\n Returns:\n (int)\n \"\"\"\n try:\n num = int(phase[:-2])\n except ValueError:\n raise ValueError(\"@phase is phase name, like 0th, 1st, 2nd...\")\n grouped_ids = list(itertools.groupby(self.phase_dict.values()))\n return grouped_ids[num][0]\n\n def _add(self, new_id, start_date, end_date):\n \"\"\"\n Add new phase to self.\n\n Args:\n new_id (int): ID number of the new phase\n start_date (str): start date of the new phase\n end_date (str): end date of the new phase\n \"\"\"\n date_series = pd.date_range(\n start=start_date, end=end_date, freq=\"D\"\n )\n new_phase_dict = {\n date_obj: new_id\n for date_obj in date_series\n }\n free_date_set = set(k for (k, v) in self.phase_dict.items() if v)\n intersection = set(new_phase_dict.keys()) & free_date_set\n if intersection:\n date_strings = [\n date_obj.strftime(self.DATE_FORMAT) for date_obj in intersection\n ]\n dates_str = \", \".join(date_strings)\n raise KeyError(\n f\"Phases have been registered for {dates_str}.\")\n self.phase_dict.update(new_phase_dict)\n\n def add(self, start_date, end_date, population=None, **kwargs):\n \"\"\"\n Add a new phase.\n\n Args:\n start_date (str): start date of the new phase\n end_date (str): end date of the new phase\n population (int): population value of the start date\n kwargs: keyword arguments to save as phase information\n\n Returns:\n self\n\n Notes:\n if @population is None, initial value will be used.\n \"\"\"\n # Arguments\n population = population or self.population\n new_id = max(self.phase_dict.values()) + 1\n # Check tense of dates\n start_tense = self._tense(start_date)\n end_tense = self._tense(end_date)\n if start_tense != end_tense:\n raise ValueError(\n f\"@start_date is {start_tense}, but @end_date is {end_tense}.\"\n )\n # end_date must be over start_date - 2\n start_obj = self.date_obj(start_date)\n end_obj = self.date_obj(end_date)\n min_end_obj = start_obj + timedelta(days=2)\n if end_obj < min_end_obj:\n min_end_date = min_end_obj.strftime(self.DATE_FORMAT)\n raise ValueError(\n f\"@end_date must be the same or over {min_end_date}, but {end_date} was applied.\"\n )\n # Add new phase\n self._add(new_id, start_date, end_date)\n # Add phase information\n self.info_dict[new_id] = {\n self.TENSE: start_tense,\n self.START: start_date,\n self.END: end_date,\n self.N: population\n }\n self.info_dict[new_id].update(**kwargs)\n return self\n\n def delete(self, phase):\n \"\"\"\n Delete a phase.\n\n Args:\n phase (str): phase name, like 0th, 1st, 2nd...\n\n Returns:\n self\n \"\"\"\n phase_id = self._phase_name2id(phase)\n self.phase_dict = {\n k: 0 if v is phase_id else v\n for (k, v) in self.phase_dict.items()\n }\n self.info_dict.pop(phase_id)\n return self\n\n def summary(self):\n \"\"\"\n Summarize the series of phases in a dataframe.\n\n Returns:\n (pandas.DataFrame):\n Index:\n - phase name, like 1st, 2nd, 3rd...\n Columns:\n - Type: 'Past' or 'Future'\n - Start: start date of the phase\n - End: end date of the phase\n - Population: population value of the start date\n - values added by self.update()\n \"\"\"\n # Convert phase ID to phase name\n info_dict = self.to_dict()\n # Convert to dataframe\n df = pd.DataFrame.from_dict(info_dict, orient=\"index\")\n df = df.fillna(self.UNKNOWN)\n # If empty, add column names\n if df.empty:\n return pd.DataFrame(columns=[self.TENSE, self.START, self.END, self.N])\n return df\n\n def to_dict(self):\n \"\"\"\n Summarize the series of phase in a dictionary.\n\n Returns:\n (dict): nested dictionary of phase information\n - key (str): phase number, like 1th, 2nd,...\n - value (dict): phase information\n - 'Type': (str) 'Past' or 'Future'\n - 'Start': (str) start date of the phase,\n - 'End': (str) end date of the phase,\n - 'Population': (int) population value at the start date\n - values added by PhaseSeries.update()\n \"\"\"\n # Convert phase ID to phase name\n info_dict = {\n self.num2str(num): self.info_dict[num]\n for num in self.info_dict.keys()\n }\n # Convert to dataframe\n return info_dict\n\n def _tense(self, target_date, ref_date=None):\n \"\"\"\n Return 'Past' or 'Future' for the target date.\n\n Args:\n target_date (str): target date, like 22Jan2020\n ref_date (str or None): reference date\n\n Returns:\n (str): 'Past' or 'Future'\n\n Notes:\n If @ref_date is None, the last date of the records will be used.\n \"\"\"\n target_obj = datetime.strptime(target_date, self.DATE_FORMAT)\n ref_date = self.last_record_date if ref_date is None else ref_date\n ref_obj = datetime.strptime(ref_date, self.DATE_FORMAT)\n if target_obj <= ref_obj:\n return self.PAST\n return self.FUTURE\n\n def update(self, phase, **kwargs):\n \"\"\"\n Update information of the phase.\n\n Args:\n phase (str): phase name\n kwargs: keyword arguments to add\n \"\"\"\n phase_id = self._phase_name2id(phase)\n self.info_dict[phase_id].update(kwargs)\n return self\n\n def last_object(self):\n \"\"\"\n Return the end date of the last registered phase.\n\n Returns:\n (datetime.datetime): the end date of the last registered phase\n \"\"\"\n un_date_objects = [\n k for (k, v) in self.phase_dict.items()\n if v != 0\n ]\n if not un_date_objects:\n return list(self.phase_dict.keys())[0]\n return un_date_objects[-1]\n\n def next_date(self):\n \"\"\"\n Return the next date of the end date of the last registered phase.\n Returns:\n (str): like 01Feb2020\n \"\"\"\n last_end_date_obj = self.last_object()\n next_date_obj = last_end_date_obj + timedelta(days=1)\n return next_date_obj.strftime(self.DATE_FORMAT)\n\n def start_objects(self):\n \"\"\"\n Return the list of start dates as datetime.datetime objects of phases.\n\n Returns:\n (list[datetime.datetime]): list of start dates\n \"\"\"\n start_objects = [\n self.date_obj(v[self.START]) for v in self.info_dict.values()\n ]\n return start_objects\n\n @staticmethod\n def number_of_steps(start_objects, last_object, tau):\n \"\"\"\n Return the list of the number of steps of phases.\n\n Args:\n start_objects (list[datetime.datetime]): list of start dates\n last_object (datetime.datetime): the end date of the last registered phase\n tau (int): tau value\n\n Returns:\n (list[int]): list of the number of steps\n \"\"\"\n date_array = np.array([*start_objects, last_object])\n step_n_list = [\n round(diff.total_seconds() / 60 / tau) for diff\n in date_array[1:] - date_array[:-1]\n ]\n return step_n_list\n\n def model_names(self):\n \"\"\"\n Return the names of the registered models if available.\n\n Returns:\n (list[str]): list of model names\n \"\"\"\n try:\n names = [\n v[self.ODE] for v in self.info_dict.values()\n ]\n except KeyError:\n names = list()\n return names\n\n def population_values(self):\n \"\"\"\n Return the list of population values.\n\n Returns:\n (list[int]): list of population values\n \"\"\"\n values = [\n v[self.N] for v in self.info_dict.values()\n ]\n return values\n","sub_path":"covsirphy/phase/phase_series.py","file_name":"phase_series.py","file_ext":"py","file_size_in_byte":11825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"531965402","text":"from app.thirdparty.oneforall.common.query import Query\n\n\nclass CeBaidu(Query):\n def __init__(self, domain):\n Query.__init__(self)\n self.domain = domain\n self.module = 'Dataset'\n self.source = 'CeBaiduQuery'\n self.addr = 'https://ce.baidu.com/index/getRelatedSites'\n\n def query(self):\n \"\"\"\n 向接口查询子域并做子域匹配\n \"\"\"\n self.header = self.get_header()\n self.proxy = self.get_proxy(self.source)\n params = {'site_address': self.domain}\n resp = self.get(self.addr, params)\n self.subdomains = self.collect_subdomains(resp)\n\n def run(self):\n \"\"\"\n 类执行入口\n \"\"\"\n self.begin()\n self.query()\n self.finish()\n self.save_json()\n self.gen_result()\n self.save_db()\n\n\ndef run(domain):\n \"\"\"\n 类统一调用入口\n\n :param str domain: 域名\n \"\"\"\n query = CeBaidu(domain)\n query.run()\n\n\nif __name__ == '__main__':\n run('example.com')\n","sub_path":"python/app/thirdparty/oneforall/modules/datasets/cebaidu.py","file_name":"cebaidu.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"83770102","text":"from Board import Board\r\nfrom Mark import Mark\r\nfrom MyModules import InputValidator\r\nfrom MyModules import Switch\r\n\r\n\r\n#Gets coordinates for the given inputted location (getPos(5)[1] returns the X coordinate 1)\r\ndef getPos(position, selection):\r\n return position.run(selection)\r\n\r\n#Checks the board for a win combination. If found, return the winning Mark type\r\ndef checkWin(board):\r\n #Create a list of the marks on the board\r\n marks = board.enumerate()\r\n\r\n #Hard code the win conditions for the diagonals\r\n if marks[0] == marks[4] == marks[8] != \" \":\r\n return marks[0]\r\n elif marks[2] == marks[4] == marks[6] != \" \":\r\n return marks[0]\r\n\r\n #Checks for wins on x and y axis\r\n for i in range(board.size):\r\n if marks[i] == marks[i+1] == marks[i+2] != \" \":\r\n return marks[i+1]\r\n if marks[i] == marks[i+board.size] == marks[i+board.size*2]:\r\n return marks[i]\r\n\r\n return \" \"\r\n\r\n\r\n\r\n\r\ndef play():\r\n\r\n #user position selection\r\n selection = \" \"\r\n #current player's piece\r\n curr = \"X\"\r\n\r\n #initialize game board\r\n game = Board(3)\r\n\r\n #Create position switch to return new mark\r\n position = Switch.Switch()\r\n case = [1,2,3,4,5,6,7,8,9]\r\n value = [[0,0],[0,1],[0,2],\r\n [1,0],[1,1],[1,2],\r\n [2,0],[2,1],[2,2]]\r\n\r\n for val in case:\r\n position.addCase(val, value[val-1])\r\n\r\n #Greet the player\r\n print(\"Player 1 is X, Player 2 is O!\")\r\n print(\"type exit to end the game\\n\")\r\n print(game.printLegend())\r\n\r\n #Check if player selected exit, if so end the game\r\n while selection != \"exit\":\r\n\r\n\r\n #Get the player input for the position\r\n print(\"\\nEnter the position number for {}\".format(curr))\r\n selection = input(\">>>\")\r\n\r\n\r\n #End the game if the player chose exit\r\n if selection == \"exit\":\r\n break\r\n\r\n\r\n #Continue collecting input until the player gives input in the correct range. Exit program allowed\r\n while InputValidator.isInt(selection) == False or int(selection) > 9 or int(selection) < 1:\r\n if selection == \"exit\":\r\n break\r\n\r\n print(\"\\nOops! That's not a valid position, try one from 1 - 9\")\r\n print(\"\\n\"+game.printBoard())\r\n print(\"\\nEnter the position number for {}\".format(curr))\r\n selection = input(\">>>\")\r\n #Convert to integer\r\n selection = int(selection)\r\n\r\n\r\n #Check if the spot on the board is empty\r\n if game.check(getPos(position, selection)[0], getPos(position, selection)[1]) != \" \":\r\n print(\"\\nOops! That spot is already taken. Choose a different position\")\r\n else:\r\n #Create a Mark with the current player name and position\r\n mark = Mark(curr, getPos(position, selection)[0], getPos(position, selection)[1])\r\n game.place(mark)\r\n\r\n #Check for win conditions, if a player won returns the players name\r\n result = checkWin(game)\r\n\r\n #End the game if a player has won\r\n if result == \"X\" or result == \"O\" :\r\n print(\"Congratulations {}! You won!\".format(curr))\r\n break\r\n\r\n #Change to the next players turn\r\n if curr == \"X\":\r\n curr = \"O\"\r\n else:\r\n curr = \"X\"\r\n\r\n\r\n print(\"\\n\"+game.printBoard())\r\n\r\nplay()","sub_path":"Demos/TicTacToe/Play.py","file_name":"Play.py","file_ext":"py","file_size_in_byte":3414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"8057676","text":"import os\n\nsciezka = \"ogorek.py\"\n\n# najpierw sprawdzamy czy plik istnieje,\n# jeśli tak to go otwieramy\nif os.path.exists(sciezka):\n\n with open(sciezka) as plik:\n zawartosc = plik.read()\n print(zawartosc)\nelse:\n print(\"plik mie istnieje\")\n\n","sub_path":"day8/blad.py","file_name":"blad.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"209115049","text":"#法一\nfrom collections import Counter\nclass Solution(object):\n def topKFrequent(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n nums_counts = Counter(nums)\n top_three = nums_counts.most_common(k)\n res=[]\n for i in top_three:\n res.append(i[0])\n return res\n\n\n#法二\nclass Solution(object):\n def topKFrequent(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n b=set(nums)\n hashtable=dict()\n for i in b:\n count=0\n for j in range(len(nums)):\n if i == nums[j]:\n count+=1\n j+=1\n hashtable[i]=count\n res=sorted(hashtable, key = hashtable.get,reverse=True)\n result=[]\n for i in range(k):\n for key, val in hashtable.items():\n if key == res[i]:\n result.append(key)\n return result","sub_path":"Week2/前k个高频元素.py","file_name":"前k个高频元素.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"460468354","text":"from itertools import product\n\nimport pyglet\nimport pymunk.pyglet_util\nimport argparse\n\nimport asyncio\nimport traceback\nfrom asyncio import events\nfrom multiprocessing import Manager\nfrom os.path import isdir\nfrom os import mkdir\n\nfrom mechanic.game import Game\nfrom mechanic.strategy import KeyboardClient, FileClient\nfrom rl_env import RLClient\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='LocalRunner for MadCars')\n\n parser.add_argument('-f', '--fp', type=str, nargs='?',\n help='Path to executable with strategy for first player', default='keyboard')\n parser.add_argument('--fpl', type=str, nargs='?', help='Path to log for first player')\n\n parser.add_argument('-s', '--sp', type=str, nargs='?',\n help='Path to executable with strategy for second player', default='keyboard')\n parser.add_argument('--spl', type=str, nargs='?', help='Path to log for second player')\n parser.add_argument('--nodraw', action='store_true')\n\n\n maps = ['PillMap', 'PillHubbleMap', 'PillHillMap', 'PillCarcassMap', 'IslandMap', 'IslandHoleMap']\n cars = ['Buggy', 'Bus', 'SquareWheelsBuggy']\n games = [','.join(t) for t in product(maps, cars)]\n\n\n parser.add_argument('-m', '--matches', nargs='+', help='List of pairs(map, car) for games', default=games)\n\n parser.add_argument('-rl_env', action='store_true')\n parser.add_argument('-n', type=int)\n parser.add_argument('-resume', type=int, default=-1)\n parser.add_argument('-reset_every', type=int, default=-1)\n parser.add_argument('-env_car', type=str)\n parser.add_argument('-env_map', type=str)\n parser.add_argument('-train1', action='store_true')\n parser.add_argument('-train2', action='store_true')\n parser.add_argument('-dump', action='store_true')\n parser.add_argument('-dueling1', action='store_true')\n parser.add_argument('-dueling2', action='store_true')\n\n args = parser.parse_args()\n\n if args.rl_env:\n args.matches = [args.env_map+','+args.env_car]*(args.n)\n #print('Matches:', args.matches)\n\n if not args.nodraw:\n window = pyglet.window.Window(1200, 800, vsync=False)\n draw_options = pymunk.pyglet_util.DrawOptions()\n _ = pyglet.clock.ClockDisplay(interval=0.016)\n\n first_player = args.fp\n second_player = args.sp\n\n manager = Manager()\n self_play = args.reset_every != -1\n print('Self-play:', self_play)\n\n if args.rl_env:\n path = 'weights/{}_{}'.format(args.env_map, args.env_car)\n if not isdir(path):\n mkdir(path)\n print('path {} created!'.format(path))\n\n fc = None\n if args.fp == 'agent':\n fc = RLClient(args, False, manager, debug_file='debug_first.txt', train=args.train1, self_play=self_play)\n elif args.fp == 'keyboard':\n fc = KeyboardClient(window)\n else:\n fc = FileClient(args.fp.split(), args.fpl)\n\n if args.sp == 'agent':\n sc = RLClient(args, True, manager, debug_file='debug_second.txt',\n model_q=fc.model_q if args.fp == 'agent' else None,\n msg_q=fc.msg_q if args.fp == 'agent' else None, train=args.train2, self_play=self_play)\n elif args.sp == 'keyboard':\n sc = KeyboardClient(window, second=True, first_client=fc)\n else:\n sc = FileClient(args.sp.split(), args.spl)\n\n game = Game([fc, sc], args.matches, extended_save=False, should_dump=args.dump, env_car=args.env_car, env_map=args.env_map)\n\n @asyncio.coroutine\n def run_game():\n game_future = None\n game_future = asyncio.ensure_future(game.game_loop(nolimit=True))\n\n if game_future:\n done, pending = yield from asyncio.gather(game_future)\n if not pending:\n loop.stop()\n print('game done')\n\n try:\n if not args.nodraw:\n loop = events.new_event_loop()\n events.set_event_loop(loop)\n\n @window.event\n def on_draw():\n if not args.nodraw:\n pyglet.gl.glClearColor(255,255,255,255)\n window.clear()\n game.draw(draw_options)\n game.tick()\n if not game.game_complete:\n future_message = loop.run_until_complete(game.tick())\n else:\n winner = game.get_winner()\n if not args.nodraw:\n if winner:\n pyglet.text.Label(\"Player {} win\".format(winner.id), font_name='Times New Roman',\n font_size=36,\n color=(255, 0, 0, 255),\n x=600, y=500,\n anchor_x='center', anchor_y='center').draw()\n else:\n pyglet.text.Label(\"Draw\", font_name='Times New Roman',\n font_size=36,\n color=(255, 0, 0, 255),\n x=600, y=500,\n anchor_x='center', anchor_y='center').draw()\n\n\n pyglet.app.run()\n else:\n loop = asyncio.get_event_loop()\n loop.run_until_complete(run_game())\n try:\n loop.run_forever()\n finally:\n loop.close()\n except:\n traceback.print_exc()\n\n\n","sub_path":"Runners/localrunner.py","file_name":"localrunner.py","file_ext":"py","file_size_in_byte":5503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"425797148","text":"import os\nimport tempfile\n\n\nclass File:\n def __init__(self, path):\n self.path = path\n\n def write(self, data):\n with open(self.path, 'w') as f:\n f.write(data)\n\n def __add__(self, other):\n storage_path = os.path.join(tempfile.gettempdir(), 'storage.data')\n with open(self.path, 'r') as f1:\n with open(other.path, 'r') as f2:\n with open(storage_path, 'w') as out:\n for line in f1:\n out.write(line)\n for line in f2:\n out.write(line)\n return File(storage_path)\n\n # def __iter__(self):\n # self.line = ''\n # return self\n\n\n # def __next__(self):\n def __getitem__(self, item):\n with open(self.path, 'r') as f:\n rows = f.readlines()\n if item >= len(rows):\n raise StopIteration\n return rows[item]\n # for line in f:\n # self.line = line\n # yield self.line\n # raise StopIteration\n\n\n def __str__(self):\n return self.path\n\n# f = File('test1.txt')\n# f.write('test1.txt\\n')\n#\n# g = File('test2.txt')\n# g.write('test2.txt\\n')\n#\n# h = f + g\n# print(h)\n# for i in h:\n# print(i)\n\n","sub_path":"week4/FileClass/fc.py","file_name":"fc.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"147550265","text":"fname = input(\"Enter file name: \")\r\nif len(fname) < 1 : fname = \"mbox-short.txt\"\r\nfhand = open(fname)\r\ncounts = dict()\r\nfor line in fhand:\r\n if line.startswith('From '):\r\n email = line.split()[1]\r\n counts[email] = counts.get(email, 0) + 1\r\n\r\n\r\nbigcount = None\r\nbigword = None\r\nfor word, count in counts.items():\r\n if bigcount is None or bigcount < count:\r\n bigcount = count\r\n bigword = word\r\n\r\nprint(bigword, bigcount)\r\n","sub_path":"chap9/ex09_04.py","file_name":"ex09_04.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"150977018","text":"import unittest\nimport docker\nfrom requests import get, post\nimport os\nimport time\n\n\nclient = docker.from_env()\nurl = \"http://localhost:3476\"\nname = \"unit_test\"\ndefault_image = \"alpine\"\nreg = { # used in push_cycle\n 'registry': \"harbor.default.svc.cluster.local\",\n 'username': \"\",\n 'password': \"\",\n}\n\n\nclass TestDocker(unittest.TestCase):\n def test_basic(self):\n envs = client.containers.list()\n self.assertGreater(len(envs), 0)\n\n\nclass TestAPI_unit(unittest.TestCase):\n def setUp(self):\n self.url = url\n\n def errorCatch(self, rep):\n self.assertEqual(rep.status_code, 400)\n rep = rep.json()\n self.assertEqual(rep['status'], 400)\n\n def noErrorCatch(self, rep):\n self.assertEqual(rep.status_code, 500)\n rep = rep.json()\n self.assertEqual(rep['status'], 500)\n\n def checkOK(self, rep):\n self.assertEqual(rep.status_code, 200)\n rep = rep.json()\n self.assertEqual(rep['status'], 200)\n\n def test_url0(self):\n rep = get(self.url)\n self.noErrorCatch(rep)\n\n def test_url1(self):\n rep = get(self.url + \"/hi\")\n self.noErrorCatch(rep)\n\n def test_search(self):\n rep = get(self.url + \"/search\")\n self.noErrorCatch(rep)\n\n def test_search_fail(self):\n rep = post(self.url + \"/search\", data={'name': name})\n self.errorCatch(rep)\n\n def test_search_fail_image(self):\n rep = post(self.url + \"/search/image\", data={'name': name})\n self.errorCatch(rep)\n\n def test_prune(self):\n rep = post(self.url + \"/prune\")\n self.checkOK(rep)\n\n def test_delete_empty(self):\n rep = post(self.url + \"/delete\", data={'name': name})\n self.errorCatch(rep)\n\n def test_delete_empty_image(self):\n rep = post(self.url + \"/delete/image\", data={'name': name})\n self.errorCatch(rep)\n\n\nclass TestAPI_cycle(unittest.TestCase):\n def setUp(self):\n self.url = url\n\n def checkOK(self, rep):\n self.assertEqual(rep.status_code, 200)\n rep = rep.json()\n self.assertEqual(rep['status'], 200)\n self.assertEqual(rep['message'], \"OK\")\n\n def errorCatch(self, rep):\n self.assertEqual(rep.status_code, 400)\n rep = rep.json()\n self.assertEqual(rep['status'], 400)\n\n def checkRunning(self):\n rep = post(self.url + \"/search\", data={'name': name})\n self.checkOK(rep)\n rep = rep.json()\n self.assertIsInstance(rep['data'], dict)\n self.assertEqual(rep['data']['status'], \"running\")\n\n def test_container_cycle(self):\n \"\"\"\n # this should run on local mechine\n mkdir -p /home/nas/test/tmp0\n mkdir -p /nashome/guest/test/tmp1\n # os.makedirs(\"/home/nas/test/tmp0\", exist_ok=True)\n # os.makedirs(\"/nashome/guest/test/tmp1\", exist_ok=True)\n \"\"\"\n # Before Create\n print(\"Create\")\n rep = post(self.url + \"/search\", data={'name': name})\n self.errorCatch(rep)\n\n # Create\n rep = post(self.url + \"/create\", data={\n 'image': default_image,\n 'homepath': \"/nashome/guest/test\",\n 'naspath': \"/home/nas/test\",\n 'command': \"tail -f /dev/null\",\n 'name': name})\n self.checkRunning()\n\n # Double create\n rep = post(self.url + \"/create\", data={\n 'image': default_image,\n 'homepath': \"/nashome/guest/test\",\n 'naspath': \"/home/nas/test\",\n 'command': \"tail -f /dev/null\",\n 'name': name})\n self.errorCatch(rep)\n\n # Check by api\n con = client.containers.get(name)\n self.assertIn(\"tmp0\", con.exec_run(\"ls /home/nas\").output.decode())\n self.assertIn(\"tmp1\", con.exec_run(\"ls /home/ubuntu\").output.decode())\n self.assertEqual(con.status, \"running\")\n\n # Stop\n con.exec_run(\"touch /opt/tmp2\").output.decode()\n print(\"Stop\")\n rep = post(self.url + \"/stop\", data={'name': name})\n self.checkOK(rep)\n\n # check stop\n rep = post(self.url + \"/search\", data={'name': name})\n self.checkOK(rep)\n rep = rep.json()\n self.assertIsInstance(rep[\"data\"], dict)\n self.assertEqual(rep['data']['status'], \"exited\")\n\n # start\n print(\"Resume\")\n rep = post(self.url + \"/start\", data={'name': name})\n self.checkOK(rep)\n self.checkRunning()\n con = client.containers.get(name)\n self.assertIn(\"tmp2\", con.exec_run(\"ls /opt\").output.decode())\n\n # change pw\n print(\"Change Password\")\n con.exec_run(\"adduser ubuntu\")\n rep = post(self.url + \"/passwd\", data={'name': name,\n 'pw': \"tmpPW\"})\n self.checkOK(rep)\n self.assertIn(\"tmpPW\", con.exec_run(\"cat /etc/shadow\").output.decode())\n\n # commit\n print(\"Commit\")\n rep = post(self.url + \"/commit\", data={'name': name,\n 'newname': name})\n self.checkOK(rep)\n\n # search image\n rep = post(self.url + \"/search/image\", data={'name': name})\n rep = rep.json()\n self.assertIsInstance(rep['data'], dict)\n\n # delete\n print(\"Delete\")\n rep = post(self.url + \"/delete\", data={'name': name})\n self.checkOK(rep)\n\n # check delete\n rep = post(self.url + \"/search\", data={'name': name})\n self.errorCatch(rep)\n\n # Delete Image\n print(\"Delete Image\")\n rep = post(self.url + \"/delete/image\", data={'name': name})\n self.checkOK(rep)\n\n # Check if delete it\n rep = post(self.url + \"/search/image\", data={'name': name})\n self.errorCatch(rep)\n\n def test_push_cycle(self):\n # Create\n print(\"Create\")\n rep = post(self.url + \"/create\", data={\n 'image': default_image,\n 'homepath': \"/nashome/guest/test\",\n 'naspath': \"/home/nas/test\",\n 'command': \"tail -f /dev/null\",\n 'name': name})\n self.checkRunning()\n t = str(time.time())\n con = client.containers.get(name)\n con.exec_run(\"touch /opt/\" + t).output.decode()\n\n # commit\n print(\"Commit\")\n reg_name = reg['registry'] + \"/\" + reg['username'] + '/' + name\n rep = post(self.url + \"/commit\", data={'name': name,\n 'newname': reg_name})\n self.checkOK(rep)\n\n # push\n print(\"Push\")\n rep = post(self.url + \"/push\", data={\n **reg,\n 'name': reg_name})\n\n # delete\n print(\"Delete\")\n rep = post(self.url + \"/delete\", data={'name': name})\n self.checkOK(rep)\n\n # Delete Image\n print(\"Delete Image\")\n rep = post(self.url + \"/delete/image\", data={'name': reg_name})\n self.checkOK(rep)\n rep = post(self.url + \"/search/image\", data={'name': reg_name})\n self.errorCatch(rep)\n\n # pull\n print(\"Pull Image\")\n client.images.pull(reg_name)\n\n # start\n print(\"Create\")\n rep = post(self.url + \"/create\", data={\n 'image': reg_name,\n 'homepath': \"/nashome/guest/test\",\n 'naspath': \"/home/nas/test\",\n 'command': \"tail -f /dev/null\",\n 'name': name})\n self.checkRunning()\n con = client.containers.get(name)\n self.assertIn(t, con.exec_run(\"ls /opt\").output.decode())\n\n # delete\n print(\"Delete\")\n rep = post(self.url + \"/delete\", data={'name': name})\n self.checkOK(rep)\n print(\"Delete Image\")\n rep = post(self.url + \"/delete/image\", data={'name': reg_name})\n self.checkOK(rep)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"labboxapi_docker/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":7828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"72640914","text":"import numpy as np\n\n\ndef relative_error(origin, prediction):\n mask = (origin == 0.0)\n eps = 1e-7\n ##Prevent division by 0.\n prediction[mask] += eps\n origin[mask] += eps\n return np.abs((prediction - origin) / origin)\n","sub_path":"relative_error.py","file_name":"relative_error.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"506110720","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 8 09:09:27 2020\n\n@author: salman\n\"\"\"\nsum = 0;\nk = 0\nfor i in range(1,100):\n if(i%3==0):\n sum = sum+i\n k = k+1\n \navg = sum/k\nprint(avg)\n\n","sub_path":"AI BRACU CLASS CODES/lab01_problem06.py","file_name":"lab01_problem06.py","file_ext":"py","file_size_in_byte":208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"425361520","text":"def write_1(a): #10-15e kadar olan sayilari yazdimak icin olusturulan fonksiyon ve dictionary\r\n dict_other={'10':'Ten','11':'Eleven','12':'Twelve','13':'Thirteen','14':'Fourteen','15':'Fifteen'}\r\n print(dict_other[a]) \r\n\r\ndef write_2(a): # iki basamakli dictonary disindaki sayilari yazdirmak icin olusturulan fonksiyon\r\n number_list1=['1','2','3','4','5','6','7','8','9'] #rakamlari kontrol icin olusturulan liste\r\n woord_list1=['One','Two','Three','Four','Five','Six','Seven','Eight','Nine']#kontrol sonrasi tespit edilen rakamlrin yazili oldugu liste\r\n woord_list10=['Teen','Twenty','Thirty','Fourty','Fifty','Sixty','Seventy','Eighty','Ninety']#kontrol sonrasi tespit edilen rakamlrin yazili oldugu liste 10 ar\r\n result=\"\" #tespti edilen yazi degerinin eklendigi degisken\r\n control_0=a[0] #girilen sayinin 0 indisindeki ifade(str)\r\n control_1=a[1] #girilen sayinin 1 indisindeki ifade(str) \r\n \r\n if control_1=='0': #sayinin 1. indexindeki rakam 0 ise 20 30 vd.(ten haric o ust fonksiyonda)\r\n found_ind=number_list1.index(control_0) #rakamin number_list deki indeksi tespit edilir,\r\n result+=woord_list10[found_ind] #karsiligi olan woor_list deki yazi result a eklenir, \r\n elif control_0==control_1: #rakamlar ayni ise 22, 33 gibi;\r\n found_ind=number_list1.index(control_0)#indeks bulunur\r\n result+=woord_list10[found_ind]#indeksin karsiligi woord listede bulunur resulta eklenir\r\n result+=' ' #yazilari ayirmak icin bosluk eklenir,\r\n result+=woord_list1[found_ind] #rakamlar ayni oldugu icin ikinci rakam woord list1 den eklenir \r\n elif control_0=='1': #ilk rakam bir oldugunda(dictionary de olmayan sayilar 16-19)\r\n found_ind=number_list1.index(control_1)#indeks tespit edilir,\r\n result+=woord_list1[found_ind] #woordlist1 den result a eklenir\r\n #result+=' ' #bitisik yazildigi icin bosluk birakilmaz\r\n found_ind=number_list1.index(control_0) #indeks tespit edilir\r\n result+=woord_list10[found_ind] #woord_list10 dan result a eklenir \r\n elif control_0!=control_1: #rakamlar farkli oldugu durumlardaa \r\n found_ind=number_list1.index(control_0) #ilk rakakmin indeksi tespit edilir,\r\n result+=woord_list10[found_ind] #woord_list10 dan result a eklenir,\r\n result+=' ' #bosluk eklenir,\r\n found_ind=number_list1.index(control_1) #ikinci rakam indeks tespti edilir, \r\n result+=woord_list1[found_ind] #woord_list1 den rusult a eklenir,\r\n \r\n print(result)\r\n\r\nnumber_user=(input('Lutfen iki basamakli bir sayi girin: ')) #kullanicidan giris alinir,\r\nif int(number_user)<16: #int. e cevrilir ve eger 16 dan kucuk ise write1(ilk fonksiyon cagrilir)\r\n write_1(number_user) #ilk fonksiyonun cagrilir,\r\nelse:\r\n write_2(number_user) #degilse write2(ikinci fonksiyon ) cagrilir,\r\n","sub_path":"week3_2.py","file_name":"week3_2.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"343403868","text":"#https://stackoverflow.com/questions/12608788/changing-the-tick-frequency-on-x-or-y-axis-in-matplotlib\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\n\nx = [0,5,9,10,15]\ny = [0,1,2,3,4]\nfig, ax = plt.subplots()\nax.plot(x,y)\nstart, end = ax.get_ylim()\nax.yaxis.set_ticks(np.arange(start, end, 0.2))\n#ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))\nplt.show()\n","sub_path":"pcDisplay/tickAdjusting.py","file_name":"tickAdjusting.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"484599483","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nimport matplotlib.image as mpimg\nimport time\n\ndef parse_line(line):\n row = []\n for elem in line.split(\" \")[0:-1]:\n row.append(int(elem))\n return row\n\nif __name__ == \"__main__\":\n filepath = \"image.txt\"\n\n img = []\n with open(filepath) as fp:\n line = fp.readline()\n while line:\n img_row = parse_line(line)\n img.append(img_row)\n line = fp.readline()\n \n img = np.array(img)\n imgplot = plt.imshow(img)\n plt.savefig(\"image_\" + str(time.time()) + \".png\")\n plt.show()","sub_path":"hw_1/txt_to_png.py","file_name":"txt_to_png.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"359459762","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Volumes/Ozgur/Sites/senpilic.com.tr/senpilic/slideshow/forms.py\n# Compiled at: 2012-09-26 05:06:05\nfrom django.contrib.admin.widgets import AdminFileWidget\nfrom django.utils.translation import ugettext as _\nfrom django.utils.safestring import mark_safe\n\nclass AdminSlideWidget(AdminFileWidget):\n\n def render(self, name, value, attrs=None):\n output = []\n if value and getattr(value, 'url', None):\n image_url = value.url\n file_name = str(value)\n output.append(' \"%s\"
%s ' % (\n unicode(image_url), unicode(image_url), unicode(file_name), _('Change:')))\n output.append(super(AdminFileWidget, self).render(name, value, attrs))\n return mark_safe(('').join(output))","sub_path":"pycfiles/django-cmskit-0.1b0.tar/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"208869006","text":"#\n#\n# This is just a simple interface to the minikerberos library to support SPNEGO\n# \n#\n# - Hardships - \n# 1. DCERPC kerberos authentication requires a complete different approach and flags,\n# also requires mutual authentication\n#\n# - Links - \n# 1. Most of the idea was taken from impacket\n# 2. See minikerberos library\n\nimport datetime\n\nfrom minikerberos.common import *\n\nfrom minikerberos.protocol.asn1_structs import AP_REP, EncAPRepPart, EncryptedData\nfrom minikerberos.gssapi.gssapi import get_gssapi\nfrom minikerberos.protocol.structures import ChecksumFlags\nfrom minikerberos.protocol.encryption import Enctype, Key, _enctype_table\nfrom minikerberos.protocol.constants import MESSAGE_TYPE\nfrom minikerberos.aioclient import AIOKerberosClient\n\n# SMBKerberosCredential\n\nclass MSLDAPKerberos:\n\tdef __init__(self, settings):\n\t\tself.settings = settings\n\t\tself.ccred = None\n\t\tself.target = None\n\t\tself.spn = None\n\t\tself.kc = None\n\t\t\n\t\tself.session_key = None\n\t\tself.gssapi = None\n\t\tself.iterations = 0\n\t\tself.etype = None\n\t\n\t\tself.setup()\n\t\n\tdef signing_needed(self):\n\t\treturn False\n\t\n\tdef encryption_needed(self):\n\t\treturn False #change to true to enable encryption channel binding\n\t\t\t\t\n\tasync def sign(self, data, message_no, direction = 'init'):\n\t\treturn self.gssapi.GSS_GetMIC(data, message_no, direction = direction)\t\n\t\t\n\tasync def encrypt(self, data, message_no):\n\t\treturn self.gssapi.GSS_Wrap(data, message_no)\n\t\t\n\tasync def decrypt(self, data, message_no, direction='init', auth_data=None):\n\t\treturn self.gssapi.GSS_Unwrap(data, message_no, direction=direction, auth_data=auth_data)\n\t\t\n\tdef setup(self):\n\t\tself.ccred = self.settings.ccred\n\t\tself.spn = self.settings.spn\n\t\tself.target = self.settings.target\n\t\t\n\t\tself.kc = AIOKerberosClient(self.ccred, self.target)\n\t\t\n\t\n\tdef get_session_key(self):\n\t\treturn self.session_key.contents\n\t\n\tasync def authenticate(self, authData, flags = None, seq_number = 0, is_rpc = False):\n\n\t\tif self.iterations == 0:\n\t\t\t#tgt = await self.kc.get_TGT(override_etype=[18])\n\t\t\ttgt = await self.kc.get_TGT()\n\t\t\ttgs, encpart, self.session_key = await self.kc.get_TGS(self.spn)\n\t\t\tself.gssapi = get_gssapi(self.session_key)\n\t\tap_opts = []\n\t\tif is_rpc == True:\n\t\t\tif self.iterations == 0:\n\t\t\t\tap_opts.append('mutual-required')\n\t\t\t\tflags = ChecksumFlags.GSS_C_CONF_FLAG | ChecksumFlags.GSS_C_INTEG_FLAG | ChecksumFlags.GSS_C_SEQUENCE_FLAG|\\\n\t\t\t\t\t\tChecksumFlags.GSS_C_REPLAY_FLAG | ChecksumFlags.GSS_C_MUTUAL_FLAG | ChecksumFlags.GSS_C_DCE_STYLE\n\t\t\t\t\t\t\n\t\t\t\tapreq = self.kc.construct_apreq(tgs, encpart, self.session_key, flags = flags, seq_number = seq_number, ap_opts=ap_opts)\t\t\t\t\t\n\t\t\t\tself.iterations += 1\n\t\t\t\treturn apreq, False\n\t\t\t\t\n\t\t\telse:\n\t\t\t\t#mutual authentication part here\n\t\t\t\taprep = AP_REP.load(authData).native\n\t\t\t\tcipher = _enctype_table[int(aprep['enc-part']['etype'])]()\n\t\t\t\tcipher_text = aprep['enc-part']['cipher']\n\t\t\t\ttemp = cipher.decrypt(self.session_key, 12, cipher_text)\n\t\t\t\t\n\t\t\t\tenc_part = EncAPRepPart.load(temp).native\n\t\t\t\tcipher = _enctype_table[int(enc_part['subkey']['keytype'])]()\n\t\t\t\t\n\t\t\t\tnow = datetime.datetime.now(datetime.timezone.utc)\n\t\t\t\tapreppart_data = {}\n\t\t\t\tapreppart_data['cusec'] = now.microsecond\n\t\t\t\tapreppart_data['ctime'] = now.replace(microsecond=0)\n\t\t\t\tapreppart_data['seq-number'] = enc_part['seq-number']\n\t\t\t\t\n\t\t\t\tapreppart_data_enc = cipher.encrypt(self.session_key, 12, EncAPRepPart(apreppart_data).dump(), None)\n\t\t\t\t\n\t\t\t\t#overriding current session key\n\t\t\t\tself.session_key = Key(cipher.enctype, enc_part['subkey']['keyvalue'])\n\t\t\t\t\n\t\t\t\tap_rep = {}\n\t\t\t\tap_rep['pvno'] = 5 \n\t\t\t\tap_rep['msg-type'] = MESSAGE_TYPE.KRB_AP_REP.value\n\t\t\t\tap_rep['enc-part'] = EncryptedData({'etype': self.session_key.enctype, 'cipher': apreppart_data_enc}) \n\t\t\t\t\n\t\t\t\ttoken = AP_REP(ap_rep).dump()\n\t\t\t\tself.gssapi = get_gssapi(self.session_key)\n\t\t\t\tself.iterations += 1\n\t\t\t\t\n\t\t\t\treturn token, False\n\t\telse:\n\t\t\tapreq = self.kc.construct_apreq(tgs, encpart, self.session_key, flags = flags, seq_number = seq_number, ap_opts=ap_opts)\n\t\t\treturn apreq, False","sub_path":"msldap/authentication/kerberos/native.py","file_name":"native.py","file_ext":"py","file_size_in_byte":4019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"529416982","text":"import smtplib\nimport tkinter\n\n\nclass Window:\n def __init__(self, root):\n label1 = tkinter.Label(root,text='SMTP')\n label2 = tkinter.Label(root,text='Port')\n label3 = tkinter.Label(root,text='用户名')\n label4 = tkinter.Label(root,text='密码')\n label5 = tkinter.Label(root,text='收件人')\n label6 = tkinter.Label(root,text='主题')\n label7 = tkinter.Label(root,text='发件人')\n label1.place(x=5, y=5)\n label2.place(x=5, y=30)\n label3.place(x=5, y=55)\n label4.place(x=5, y=80)\n label5.place(x=5, y=105)\n label6.place(x=5, y=130)\n label7.place(x=5, y=155)\n self.entryPop = tkinter.Entry(root)\n self.entryPort = tkinter.Entry(root)\n self.entryUser = tkinter.Entry(root)\n self.entryPass = tkinter.Entry(root,show = '*')\n self.entryTo = tkinter.Entry(root)\n self.entrySub = tkinter.Entry(root)\n self.entryFrom = tkinter.Entry(root)\n self.entryPort.insert(tkinter.END,'25')\n self.entryPop.place(x=50, y=5)\n self.entryPort.place(x=50, y=30)\n self.entryUser.place(x=50, y=55)\n self.entryPass.place(x=50, y=80)\n self.entryTo.place(x=50, y=105)\n self.entrySub.place(x=50, y=130)\n self.entryFrom.place(x=50, y=155)\n self.get = tkinter.Button(root, text='发送邮件', command=self.Get)\n self.get.place(x=60, y=180)\n self.text = tkinter.Text(root)\n self.text.place(y=220)\n\n def Get(self):\n try:\n host = self.entryPop.get()\n port =int(self.entryPort.get())\n user = self.entryUser.get()\n pw = self.entryPass.get()\n fromaddr = self.entryFrom.get()\n toaddr=self.entryTo.get()\n subject=self.entrySub.get()\n text = self.text.get(1.0,tkinter.END)\n msg =(\"From:%s\\nTo:%s\\nSubject:%s\\n\\n\"\n % (fromaddr,toaddr,subject))\n msg = msg+text\n smtp=smtplib.SMTP(host,port)\n smtp.set_debuglevel(1)\n smtp.login(user,pw)\n smtp.sendmail(fromaddr,toaddr,msg)\n smtp.quit()\n except Exception as e:\n self.text.insert(tkinter.END,'发送错误\\n')\n\n\nroot = tkinter.Tk()\nwindow = Window(root)\nroot.minsize(600, 400)\nroot.mainloop()\n","sub_path":"emailServer/emailSend.py","file_name":"emailSend.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"609626164","text":"import jieba\n# import loading_article_num\nimport time\n\n\n# jieba.load_userdict('userdict.txt')\n# 创建停用词list\ndef stopwordslist(filepath):\n stopwords = [line.strip() for line in open(filepath, 'r', encoding='utf-8').readlines()]\n return stopwords\n\n\n# 对句子进行分词\ndef seg_sentence(sentence):\n # sentence_striped=\n sentence_seged = jieba.lcut(sentence.strip(),cut_all=False)\n stopwords = stopwordslist('../based_resources/stopwords.txt') #x 这里加载停用词的路径\n outstr = ''\n for word in sentence_seged:\n if word not in stopwords:\n if word != '\\t':\n outstr += word\n outstr += \" \"\n return outstr\n\n\n","sub_path":"summary_topic/striptxt.py","file_name":"striptxt.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"93793761","text":"# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n# --------------------------------------------------------------------------\nfrom typing import TYPE_CHECKING\n\nfrom azure.mixedreality.authentication.aio import MixedRealityStsClient\nfrom .static_access_token_credential import StaticAccessTokenCredential\n\nif TYPE_CHECKING:\n from typing import Any\n from azure.core.credentials import AccessToken\n from azure.core.credentials_async import AsyncTokenCredential\n\ndef get_mixedreality_credential(\n account_id: str,\n account_domain: str,\n endpoint_url: str,\n credential: \"AsyncTokenCredential\",\n **kwargs):\n if isinstance(credential, StaticAccessTokenCredential):\n return credential\n\n return MixedRealityTokenCredential(\n account_id=account_id,\n account_domain=account_domain,\n endpoint_url=endpoint_url,\n credential=credential,\n **kwargs)\n\n\nclass MixedRealityTokenCredential(object):\n \"\"\" Represents a token credential that can be used to access a Mixed Reality service.\n This implements the TokenCredential protocol.\n\n :param str account_id: The Mixed Reality service account identifier.\n :param str endpoint_url: The Mixed Reality STS service endpoint.\n :param TokenCredential credential: The credential used to access the Mixed Reality service.\n \"\"\"\n\n def __init__(\n self,\n account_id: str,\n account_domain: str,\n endpoint_url: str,\n credential: \"AsyncTokenCredential\",\n **kwargs):\n self.stsClient = MixedRealityStsClient(\n account_id=account_id,\n account_domain=account_domain,\n endpoint_url=endpoint_url,\n credential=credential,\n **kwargs)\n\n async def get_token(self, *scopes: str, **kwargs: \"Any\") -> \"AccessToken\": #pylint: disable=unused-argument\n return await self.stsClient.get_token(**kwargs)\n\n async def close(self) -> None:\n self.stsClient.close()\n\n async def __aenter__(self):\n await self.stsClient.__aenter__()\n return self\n\n async def __aexit__(self, exc_type, exc_value, traceback) -> None:\n await self.stsClient.__aexit__()\n","sub_path":"sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixed_reality_token_credential.py","file_name":"mixed_reality_token_credential.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"290171342","text":"from django.urls import reverse\nfrom django.test import TestCase\nfrom rest_framework import status\nfrom rest_framework.test import APIClient\nfrom ..models import URL\n\nclass ShortenTests(TestCase):\n def setUp(self):\n self.client = APIClient()\n self.url = reverse('shortnd:shorten')\n\n def test_shorten_invalid_url(self):\n invalid_data = {'url': 'dasdas'}\n response = self.client.post(self.url, invalid_data, format='json')\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n self.assertEqual(URL.objects.count(), 0)\n self.assertEqual(response.data, {\n 'error': 'Invalid URL'\n })\n \n def test_shorten_no_url(self):\n response = self.client.post(self.url, {}, format='json')\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n self.assertEqual(URL.objects.count(), 0)\n self.assertEqual(response.data, {\n 'error': 'URL needed'\n })\n \n def test_shorten_url(self):\n data = {'url': 'https://www.google.com'}\n response = self.client.post(self.url, data, format='json')\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n url = URL.objects.get()\n self.assertEqual(response.data['short_url'], url.short_url)\n self.assertEqual(response.data['original_url'], url.original_url)\n\n def test_shorten_already_shortened_url(self):\n data = {'url': 'https://www.amazon.com/'}\n response = self.client.post(self.url, data, format='json')\n url = URL.objects.order_by('-id').first()\n num_urls = URL.objects.count()\n\n new_response = self.client.post(self.url, data, format='json')\n new_url = URL.objects.order_by('-id').first()\n new_num_urls = URL.objects.count()\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(new_response.status_code, status.HTTP_200_OK)\n self.assertEqual(url.short_url, new_url.short_url)\n self.assertEqual(num_urls, new_num_urls)\n ","sub_path":"shortnd/shorturls/tests/test_shorten.py","file_name":"test_shorten.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"130988849","text":"from sklearn.model_selection import KFold\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import (RandomForestClassifier, AdaBoostClassifier,\n GradientBoostingClassifier,ExtraTreesClassifier)\nimport lightgbm as lgb\nfrom sklearn.metrics import roc_curve, auc\n\n\nclass StackingModel():\n def __init__(self, topLayer_model, base_model_list, n_fold=5):\n self.topLayer_model = topLayer_model\n self.base_model_list = base_model_list\n self.n_flod = n_fold #默认5折交叉验证\n\n\n def fit(self, X_train, y_train, X_test):\n X_train, y_train, X_test = np.array(X_train), np.array(y_train), np.array(X_test)\n\n #基模型的训练和预测,用于构造X_train_stack和X_test_stack\n X_train_stack = []\n X_test_stack = []\n for i, model in enumerate(self.base_model_list):\n print('model_{}'.format(i))\n train_pred = []\n test_pred = []\n KF = KFold(n_splits=self.n_flod)\n for tra_idx, val_idx in KF.split(X_train, y_train):\n X_tra, X_val = X_train[tra_idx], X_train[val_idx]\n y_tra, y_val = y_train[tra_idx], y_train[val_idx]\n\n model.fit(X_tra, y_tra)\n train_pred.append(list(model.predict(X_val)))\n test_pred.append(list(model.predict(X_test)))\n \n train_pred = np.array([e for list_ in train_pred for e in list_])\n test_pred = np.mean(test_pred, axis=0)\n X_train_stack.append(train_pred)\n X_test_stack.append(test_pred)\n\n X_train_stack = np.array(X_train_stack).T\n self.X_test_stack = np.array(X_test_stack).T\n\n #顶层模型的训练\n self.topLayer_model.fit(X_train_stack, y_train)\n\n\n def predict(self): #测试集的数据是X_test_stack,而不是原来的X_test\n return self.topLayer_model.predict(self.X_test_stack)\n\n\ndef getAuc(y_true,y_pred):\n fpr, tpr, thresholds = roc_curve(y_true, y_pred, pos_label=1)\n aucs = auc(fpr,tpr)\n return aucs\n\n\nif __name__ == '__main__':\n print(\"load_data>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\")\n df_all = pd.read_csv(\"./train_baseline.csv\")\n df_all = df_all.sample(frac=1).copy()\n df_all = df_all.fillna(-1)\n df_all = df_all.reset_index()\n print(df_all.shape)\n\n df_train, df_test = train_test_split(df_all, test_size=0.2)\n df_train = df_train.reset_index()\n df_test = df_test.reset_index()\n\n X_train, X_test, y_train, y_test = train_test_split(df_train.drop(\"Tag\", axis=1), df_train[\"Tag\"], test_size=0.2)\n\n\n print(\"stacking_model>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\")\n rf_model = RandomForestClassifier()\n adb_model = AdaBoostClassifier()\n gdbc_model = GradientBoostingClassifier()\n et_model = ExtraTreesClassifier()\n\n topLayer_model = lgb.LGBMClassifier()\n base_model_list = [rf_model, adb_model, gdbc_model, et_model]\n\n stacking_model = StackingModel(topLayer_model, base_model_list)\n stacking_model.fit(X_train, y_train, X_test)\n print('stacking_model:', getAuc(y_test, stacking_model.predict()))\n\n\n print(\"other_model>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\")\n rf_model = RandomForestClassifier()\n adb_model = AdaBoostClassifier()\n gdbc_model = GradientBoostingClassifier()\n et_model = ExtraTreesClassifier()\n\n rf_model.fit(X_train, y_train)\n adb_model.fit(X_train, y_train)\n gdbc_model.fit(X_train, y_train)\n et_model.fit(X_train, y_train)\n\n print('rf_model:', getAuc(y_test, rf_model.predict(X_test)))\n print('adb_model:', getAuc(y_test, adb_model.predict(X_test)))\n print('gdbc_model:', getAuc(y_test, gdbc_model.predict(X_test)))\n print('et_model:', getAuc(y_test, et_model.predict(X_test)))\n\n\n\n\n\n'''\n终于搞定stacking,太开心了!!!\n之前一直以为,这个东西贼他妈神秘;搞懂了,发现贼他妈简单!!!!\n'''\n\n","sub_path":"machine_learning_model/stacking_1.py","file_name":"stacking_1.py","file_ext":"py","file_size_in_byte":4034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"424742401","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nd_model = 8\nnum_heads = 2\nseq_len = 3\nnum_block = 4\nd_k = d_model // num_heads\n\nclass MultiHeadAttention(nn.Module):\n def __init__(self, d_model, num_heads):\n super(MultiHeadAttention, self).__init__()\n self.num_heads = num_heads\n self.d_k = d_model // num_heads\n \n # 定义线性层\n self.W_q = nn.Linear(d_model, d_model)\n self.W_k = nn.Linear(d_model, d_model)\n self.W_v = nn.Linear(d_model, d_model)\n self.W_o = nn.Linear(d_model, d_model)\n \n def forward(self, input, mask=None):\n batch_size = input.size(0)\n \n # 线性变换\n Q = self.W_q(input)\n K = self.W_k(input)\n V = self.W_v(input)\n \n # 分割为多个头\n Q = Q.view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)\n K = K.view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)\n V = V.view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)\n \n # 计算注意力权重\n attn_weights = torch.matmul(Q, K.transpose(-2, -1)) / self.d_k**0.5\n if mask is not None:\n attn_weights = attn_weights.masked_fill(mask == 1, float('-inf'))\n attn_weights = F.softmax(attn_weights, dim=-1)\n \n # 应用注意力权重到V\n output = torch.matmul(attn_weights, V)\n output = output.transpose(1, 2).contiguous().view(batch_size, -1, d_model)\n \n # 最后的线性变换\n output = self.W_o(output)\n \n return output\n \nclass decoder:\n mha = []\n block_output = []\n def __init__(self, input, blocks, mask):\n self.input = input\n self.blocks = blocks\n self.output = input\n self.mask = mask\n for i in range(0, blocks):\n decoder.mha.append(MultiHeadAttention(d_model, num_heads))\n\n def mha_output(self):\n for i in range (0, self.blocks):\n self.output = decoder.mha[i](self.output, self.mask)\n decoder.block_output.append(self.output)\n return self.output\n \n\ndef subsequent_mask(size):\n mask = torch.triu(torch.ones(size, size), diagonal=1).bool()\n return mask.unsqueeze(0)\n\nsequence_length = 4\ninput_tensor_t0 = torch.rand(1, sequence_length, d_model)\nmask_t0 = subsequent_mask(sequence_length)\nllama = decoder(input_tensor_t0, num_block, mask_t0)\noutput_t0 = llama.mha_output()\nprint(output_t0)\nprint(llama.block_output)","sub_path":"dl/llama/cache_kv_v2.py","file_name":"cache_kv_v2.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"634631313","text":"import pynwb\n\nfrom ..pynwb_utils import get_metadata, metadata_subject_fields\n\n\ndef test_get_metadata(simple1_nwb, simple1_nwb_metadata):\n target_metadata = simple1_nwb_metadata.copy()\n # we will also get some counts\n target_metadata[\"number_of_electrodes\"] = 0\n target_metadata[\"number_of_units\"] = 0\n target_metadata[\"number_of_units\"] = 0\n # we do not populate any subject fields in our simple1_nwb\n for f in metadata_subject_fields:\n target_metadata[f] = None\n metadata = get_metadata(str(simple1_nwb))\n # we also load nwb_version field, so it must not be degenerate and ATM\n # it is 2.X.Y. And since I don't know how to query pynwb on what\n # version it currently \"supports\", we will just pop it\n assert metadata.pop(\"nwb_version\").startswith(\"2.\")\n assert target_metadata == metadata\n\n\ndef test_pynwb_io(simple1_nwb):\n # To verify that our dependencies spec is sufficient to avoid\n # stepping into known pynwb/hdmf issues\n with pynwb.NWBHDF5IO(str(simple1_nwb), \"r\", load_namespaces=True) as reader:\n nwbfile = reader.read()\n assert repr(nwbfile)\n assert str(nwbfile)\n","sub_path":"dandi/tests/test_pynwb_utils.py","file_name":"test_pynwb_utils.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"232483209","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n\ndef showTables(X,Y=[],XLables=[],YLabels=[],preview=10):\n from IPython.display import display_html,display\n def display_side_by_side(*args):\n html_str=''\n for df in args:\n html_str+=df.to_html()\n display_html(html_str.replace('table','table style=\"display:inline\"'),raw=True)\n \n NumDataSets=len(X) \n \n Tables=[]\n for i in range(NumDataSets):\n NumData=len(X[i])\n PreviewStep=int(NumData/preview)+1\n if(len(Y)==0):#Only one table needed\n Tables.append(pd.DataFrame({XLables[i] : X[i][0::PreviewStep]}))\n else:\n Tables.append(pd.DataFrame({XLables[i] : X[i][0::PreviewStep],\n YLabels[i] : Y[i][0::PreviewStep]}))\n \n if(len(Y)==0):\n Tables=[pd.concat(Tables,axis=1)]\n display_side_by_side(*[x for x in Tables])\n\n\n#Publication quality figure paramters\n_params = {'font.family': 'sans-serif',\n 'font.serif': ['Times', 'Computer Modern Roman'],\n 'font.sans-serif': ['Helvetica', 'Arial',\n 'Computer Modern Sans serif'],\n 'font.size': 14,\n\n 'axes.labelsize': 14,\n 'axes.linewidth': 1,\n\n \n 'savefig.dpi': 300,\n 'savefig.format': 'eps',\n # 'savefig.bbox': 'tight',\n # this will crop white spaces around images that will make\n # width/height no longer the same as the specified one.\n\n 'legend.fontsize': 14,\n 'legend.frameon': False,\n 'legend.numpoints': 1,\n 'legend.handlelength': 2,\n 'legend.scatterpoints': 1,\n 'legend.labelspacing': 0.5,\n 'legend.markerscale': 0.9,\n 'legend.handletextpad': 0.5, # pad between handle and text\n 'legend.borderaxespad': 0.5, # pad between legend and axes\n 'legend.borderpad': 0.5, # pad between legend and legend content\n 'legend.columnspacing': 1, # pad between each legend column\n\n 'xtick.labelsize': 14,\n 'ytick.labelsize': 14,\n 'xtick.direction':'in',\n 'ytick.direction':'in',\n \n 'lines.linewidth': 1,\n 'lines.markersize': 4,\n # 'lines.markeredgewidth' : 0,\n # 0 will make line-type markers, such as '+', 'x', invisible\n }\n\nlinestyles = ['-', '--', ':','-.' ]\ncolors = ['b', 'r','k', 'g', 'c']\nTabColor=['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan']\nmarkers=['o', 's', 'v', '^', 'D', '<', '>', 'p', 'h']\n\ndef plotTables(X,Y,XLable='',YLabel='',DataNames=[],Title='',\n Xlim=None,Ylim=None, subplots=[111],RegionShade=None, Alpha=[],LineWidth=[],Colors=[],\n MarkerSize=[],InvertY=False,img_fname=None):\n #http://www.scipy-lectures.org/intro/matplotlib/matplotlib.html\n\n from matplotlib import rcParams\n \n #Set paramters all at once\n for i in _params:\n rcParams[i]=_params[i]\n\n fig=plt.figure(figsize=(4,5),dpi=80)\n if(len(subplots)>1):\n fig=plt.figure(figsize=(4*len(subplots)*0.8,5),dpi=80)\n\n NumDataSets=len(X)\n\n if(len(Alpha)==0):\n Alpha=NumDataSets*[1]\n if(len(MarkerSize)==0):\n MarkerSize=NumDataSets*[0]\n if(len(LineWidth)==0):\n LineWidth=NumDataSets*[1.5]\n if(len(Colors)==0):\n Colors=colors\n \n for i in range(NumDataSets):\n y = np.array(Y[i])\n x = np.array(X[i])\n\n Space =int(len(x) / 10000)\n if(len(subplots)>1):\n fig.add_subplot(subplots[i])\n plt.plot(x, y, color=Colors[i],linestyle=linestyles[i],marker=markers[i],alpha=Alpha[i],mfc='none',\n MarkerSize=MarkerSize[i], linewidth=LineWidth[i], markevery=Space,label=DataNames[i]) \n\n #Set XYlim\n if(Xlim!=None):\n if(any(isinstance(t, list) for t in Xlim)):\n plt.xlim(Xlim[i])\n else:\n plt.xlim(Xlim)\n if(Ylim!=None):\n if(any(isinstance(t, list) for t in Ylim)):\n plt.ylim(Ylim[i])\n else:\n plt.ylim(Ylim)\n #Invert Y\n if (InvertY==True):\n plt.gca().xaxis.tick_top()\n plt.gca().xaxis.set_label_position('top')\n plt.gca().invert_yaxis()\n \n\n if(RegionShade!=None):\n for ri in range(len(RegionShade[i])):\n plt.axhspan(*RegionShade[i][ri], facecolor=TabColor[ri], edgecolor='k',alpha=0.3)\n\n plt.grid(linestyle='--')\n plt.title(Title)\n plt.xlabel(XLable)\n plt.ylabel(YLabel)\n plt.legend(loc='best')\n \n plt.tight_layout(pad=0.7)\n if(img_fname is not None):\n plt.savefig(img_fname, bbox_inches='tight')\n plt.show()\n\n\ndef smooth(y, x,windows,plot=False,xlim=[],ylim=[]): #moving average\n df = pd.DataFrame({'y': y,'x':x})\n smooth=df.rolling(on='x',window=windows).mean()\n\n if(plot==True):\n plotTables(X=[smooth.y.values,y],Y=[smooth.x.values,x],\n Xlim=xlim,Ylim=ylim,Alpha=[1,0.5],LineWidth=[1.5,1.0],Colors=['b','tab:gray'],\n DataNames=['Smoothed','Raw'],InvertY=True,img_fname='img.png')\n\n return smooth.y.values,smooth.x.values\n\n\ndef rangeMean(y,x,ranges=[]): #Find y average for a given range in x\n if(np.array(ranges).ndim==1):\n return y[np.where((x>ranges[0]) & (xri[0]) & (x number_of_records :\n break\n json_data = res.json()\n \n if i == number_of_records:\n data = data + json_data['list']\n else:\n data = data + json_data['list'][:-1]\n\n i = i + 100\n pbar.close()\n return data\n\ndef get_exchange(code):\n exchanges = {\n 'Q' : 'NASDAQ',\n 'N' : 'NYSE',\n 'A' : 'NYSE MKT',\n 'P' : 'NYSE ARCA',\n 'Z' : 'BATS',\n 'BB': 'OTCBB',\n 'NBB':'OTC',\n 'G': 'NASDAQ',\n 'S': 'NASDAQ'\n }\n return exchanges.get(code,'')\n\ndef format_data(data):\n formated_data = {}\n for count,item in enumerate(data):\n splited_item = item.split(\"|\")\n temp_dict = {}\n temp_dict[\"CIK\"] = splited_item[3]\n temp_dict[\"Name\"] = splited_item[4]\n temp_dict[\"Ticker\"] = splited_item[0]\n temp_dict[\"Exchange\"] = get_exchange(splited_item[4])\n temp_dict[\"Business\"] = splited_item[6]\n temp_dict[\"Incorporated\"] = splited_item[7]\n temp_dict[\"Industry\"] = splited_item[2]\n temp_dict[\"Ticker\"] = splited_item[0]\n temp_dict[\"IRS Number\"] = splited_item[5]\n\n formated_data[str(count)] = temp_dict\n \n return formated_data\n\n\n\ndata = fetch_data(URL,NUMBER_OF_RECORDS)\n\nformated_data = format_data(data)\n\nwith open('data.json', 'w') as json_file:\n json.dump(formated_data, json_file)\n\nprint(str(len(formated_data)) + \" Records Scrapped\")\nprint(\"Records are stored in data.json file\")\n\n\n\n\n","sub_path":"scrapper.py","file_name":"scrapper.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"574626922","text":"import tornado.httpclient\n\nfrom notebook.utils import url_path_join\nfrom notebook.base.handlers import IPythonHandler\n\n# From https://github.com/senko/tornado-proxy\nclass LocalProxyHandler(IPythonHandler):\n SUPPORTED_METHODS = ['GET', 'POST']\n proxy_uri = \"http://localhost\"\n\n @tornado.web.asynchronous\n def proxy(self, port, add_path):\n '''\n While self.request.uri is\n (hub) /user/username/proxy/([0-9]+)/something.\n (single) /proxy/([0-9]+)/something\n This serverextension is given {port}/{everything/after}.\n '''\n self.log.debug('%s request: %s', self.request.method, self.request.uri)\n self.log.debug('add_path: {}'.format(add_path))\n\n def handle_response(response):\n if (response.error and not\n isinstance(response.error, tornado.httpclient.HTTPError)):\n self.set_status(500)\n self.write('Internal server error:\\n' + str(response.error))\n else:\n self.set_status(response.code, response.reason)\n # clear tornado default header\n self._headers = tornado.httputil.HTTPHeaders()\n \n for header, v in response.headers.get_all():\n if header not in ('Content-Length', 'Transfer-Encoding',\n 'Content-Encoding', 'Connection'):\n # some header appear multiple times, eg 'Set-Cookie'\n self.add_header(header, v)\n \n if response.body: \n self.set_header('Content-Length', len(response.body))\n self.write(response.body)\n\n self.finish()\n\n if 'Proxy-Connection' in self.request.headers:\n del self.request.headers['Proxy-Connection'] \n\n body = self.request.body\n if not body: body = None\n\n uri = self.proxy_uri + ':' + port + '/' + add_path\n\n client = tornado.httpclient.AsyncHTTPClient()\n\n try:\n self.log.info('Requesting %s', uri)\n req = tornado.httpclient.HTTPRequest(\n uri, method=self.request.method, body=body,\n headers=self.request.headers, follow_redirects=False)\n client.fetch(req, handle_response, raise_error=False)\n except tornado.httpclient.HTTPError as e:\n if hasattr(e, 'response') and e.response:\n handle_response(e.response)\n else:\n self.set_status(500)\n self.write('Internal server error:\\n' + str(e))\n self.finish()\n\n @tornado.web.asynchronous\n def get(self, port, add_path=''):\n return self.proxy(port, add_path)\n\n @tornado.web.asynchronous\n def post(self, port, add_path=''):\n return self.proxy(port, add_path)\n\n def check_xsrf_cookie(self):\n '''\n http://www.tornadoweb.org/en/stable/guide/security.html\n\n Defer to proxied apps.\n '''\n pass\n\ndef setup_handlers(web_app):\n host_pattern = '.*$'\n for p in ['/proxy/([0-9]+)/?','/proxy/([0-9]+)/(.*)']:\n route_pattern = url_path_join(web_app.settings['base_url'], p)\n web_app.add_handlers(host_pattern, [\n (route_pattern, LocalProxyHandler),\n ])\n#vim: set et ts=4 sw=4:\n","sub_path":"nbserverproxy/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":3344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"494902311","text":"# -*- encoding: utf-8 -*-\n# Copyright (C) 2017 TSDV TTEC. All rights reserved.\n\nfrom phocr_shared.phocr_error import PHOcrInvalidXmlException\nfrom phocr_shared.xml_type_parser import XmlTypeParser\n\n\nclass XmlIntParser(XmlTypeParser):\n \"\"\"Parsing int type in xml\"\"\"\n\n @classmethod\n def parse(cls, xml_obj, attribute, required=False, default=None):\n have_attribute, value = XmlTypeParser.preprocess_parse(\n xml_obj,\n attribute,\n required,\n default\n )\n if have_attribute:\n try:\n return int(value)\n except ValueError:\n raise PHOcrInvalidXmlException(\n 'Attribute {0} is not type {1} in xml object \\n {2}'.format(\n attribute,\n int.__name__,\n str(xml_obj)\n )\n )\n","sub_path":"Run_PHocr_test/PHOcr_C2404_D3_linux_release/lib/phocroffice/phocr_shared/xml_int_parser.py","file_name":"xml_int_parser.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"653373162","text":"n = int(input()) - 1\ndex = jumps = 0\nnums = input().split()\nwhile dex < n:\n try:\n dex += 1 if nums[dex + 2] == '1' else 2\n except IndexError:\n dex += 1\n jumps += 1\nprint(jumps)\n","sub_path":"Algorithms/Implementation/jumping_on_the_clouds.py","file_name":"jumping_on_the_clouds.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"518852733","text":"import gramfuzz\nfrom gramfuzz.fields import *\nimport fuzz\n\nclass YRef(Ref):\n cat = \"config_def\"\nclass YDef(Def):\n cat = \"config_def\"\n\nmax_repeat = 2\n\nDef(\"contact\", And(YRef(\"optsep\"), YRef(\"module-keyword\"), YRef(\"sep\"), YRef(\"identifier-arg-str\"), YRef(\"optsep\"), \"{\", YRef(\"stmtsep\"), YRef(\"contact-stmt\")), \"}\", cat=\"contact\")\nYDef(\"optsep\", Or(Join(Or(YRef(\"WSP\"), YRef(\"line-break\")), sep=\"\", max=max_repeat), \"\"))\nYDef(\"WSP\", Or(YRef(\"SP\"), YRef(\"HTAB\")))\nYDef(\"SP\", \" \")\nYDef(\"HTAB\", \"\\t\")\nYDef(\"line-break\", Or(YRef(\"CRLF\"), YRef(\"LF\")))\nYDef(\"CRLF\", And(YRef(\"CR\"), YRef(\"LF\")))\nYDef(\"CR\", \"\")\nYDef(\"LF\", \"\\n\")\nYDef(\"module-keyword\", \"module\")\nYDef(\"sep\", Join(Or(YRef(\"WSP\"), YRef(\"line-break\")), sep=\"\", max=max_repeat))\nYDef(\"identifier-arg-str\", YRef(\"identifier-arg\"))\nYDef(\"identifier-arg\", YRef(\"identifier\"))\nYDef(\"identifier\", And(Or(YRef(\"ALPHA\"), \"_\"), Or(Join(Or(YRef(\"ALPHA\"), YRef(\"DIGIT\"), \"_\", \"-\", \".\"), sep=\"\", max=max_repeat), \"\")))\nYDef(\"ALPHA\", String(charset=String.charset_alpha))\nYDef(\"DIGIT\", String(charset=\"0123456789\"))\nYDef(\"stmtsep\", Or(Join(Or(YRef(\"WSP\"), YRef(\"line-break\")), sep=\"\", max=max_repeat), \"\"))\nYDef(\"contact-stmt\", And(YRef(\"contact-keyword\"), YRef(\"sep\"), YRef(\"string\"), YRef(\"stmtend\")))\nYDef(\"contact-keyword\", \"contact\")\nYDef(\"string\", YRef(\"yang-string\"))\nYDef(\"yang-string\", Or(Join(YRef(\"yang-char\"), sep=\"\", max=max_repeat), \"\"))\nYDef(\"yang-char\", String(max=1))\nYDef(\"stmtend\", And(YRef(\"optsep\"), Or(\";\", And(\"{\", YRef(\"stmtsep\"), \"}\")), YRef(\"stmtsep\")))","sub_path":"fuzzers/contact/contact-grammar.py","file_name":"contact-grammar.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"635525776","text":"import click\n\nfrom valohai_cli.api import request\nfrom valohai_cli.consts import yes_option\nfrom valohai_cli.ctx import get_project, set_project_link\nfrom valohai_cli.messages import success\nfrom valohai_cli.utils import get_project_directory\n\n\ndef create_project(directory, name, description='', link=True, yes=False):\n \"\"\"\n Internal API for creating a project.\n \"\"\"\n project_data = request('post', '/api/v0/projects/', data={\n 'name': name,\n 'description': description,\n }).json()\n success('Project {project} created.'.format(project=project_data['name']))\n if link:\n current_project = get_project(directory)\n if current_project and not yes:\n if not click.confirm(\n 'The directory is already linked to {project}. Override that?'.format(\n project=current_project.name,\n )\n ):\n return\n set_project_link(directory, project_data, inform=True)\n else:\n click.echo('Links left alone.')\n\n\n@click.command()\n@click.option('--name', '-n', prompt='Project name', required=True, help='The name for the project.')\n@click.option('--description', '-d', default='', required=False, help='The description for the project.')\n@click.option('--link/--no-link', '-l', default=True,\n help='Link the directory to the newly created project? Default yes.')\n@yes_option\ndef create(name, description, link, yes):\n \"\"\"Create a new project and optionally link it to the directory.\"\"\"\n return create_project(\n directory=get_project_directory(),\n name=name,\n description=description,\n link=link,\n yes=yes,\n )\n","sub_path":"valohai_cli/commands/project/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"565440731","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Move STATIONS and sources locations to make the Pacific the model's center.\n\"\"\"\nfrom __future__ import division, absolute_import\nfrom __future__ import print_function, unicode_literals\n\nfrom glob import glob\nimport numpy as np\nimport shutil\n\n\ndef read_stations(filename):\n stations = {}\n with open(filename) as f:\n for sta in f:\n name, net, x, z, _, _ = sta.split()\n stations[\".\".join([net, name])] = np.array([float(x),\n float(z)])\n return stations\n\n\ndef write_stations(filename, stations):\n with open(filename, \"w\") as f:\n for sta in sorted(stations.keys()):\n net, name = sta.split(\".\")\n xz = stations[sta]\n f.write(\"{} {} {:.4f} {:.4f} {:.4f} {:.4f}\\n\".format(\n name, net, xz[0], xz[1], 0, 0))\n\n\ndef read_sources(filename):\n return np.loadtxt(filename)\n\n\ndef move(xz):\n if xz[0] < 0:\n xz[0] += 180\n else:\n xz[0] -= 180\n return xz\n\nmove_sources = False\nmove_stations = True\n\nif move_sources:\n source_file = \"sources.dat\"\n sources = read_sources(source_file)\n for source in sources:\n move(source)\n np.savetxt(source_file, sources)\n\nif move_stations:\n for stations_file in glob(\"STATIONS_*\"):\n print(\"Moving\", stations_file)\n stations = read_stations(stations_file)\n for station in stations:\n stations[station] = move(stations[station])\n write_stations(stations_file, stations)\n","sub_path":"data/2d_global_guernica/global/SETUP_global_periodic/move_pacific_to_the_middle.py","file_name":"move_pacific_to_the_middle.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"625132653","text":"from flask import Flask, render_template, request\n\napp = Flask(__name__)\n\nclass Usuario:\n def __init__(self, nome, email, senha ):\n self.nome = nome\n self.email = email\n self.senha = senha\n\nteste_01 = Usuario(nome='ahiufahsafhai', email='meuemail@hotmail.com', senha='katana')\nteste_02 = Usuario(nome='Eita', email='aisfuhauf@hotmail.com', senha='afasfasf')\n\nlistinha = [teste_01, teste_02]\n\n@app.route('/')\ndef rotaHome():\n return render_template('lista.html', lista=listinha)\n\n@app.route('/newuser',methods=['POST'])\ndef novoUsuario():\n if request.method == 'POST':\n nome_input = request.form[\"nome_usuario\"]\n senha_input = request.form[\"senha\"]\n email_input = request.form[\"email\"]\n\n usuario01 = Usuario(nome=nome_input,\n email=email_input,\n senha=senha_input)\n listinha.append(usuario01)\n return render_template('novouser.html', user=listinha)\n\n@app.route('/formulario')\ndef formulario():\n return render_template('formulario.html')\n\napp.run(debug=True)","sub_path":"aula03Flask/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"19384587","text":"import socket\nfrom threading import Thread\nimport time\nfrom dal.socketManager import getInstanceSocketManager\n\n\"\"\"\n ce model établie une connexion avec le serveur\n il utilise les threads et gères des événements\n\"\"\"\n\nclass MultiConnModel:\n def __init__(self):\n self.IP = ''\n self.getConn = GetConnexion(self)\n self.connexion_avec_serveur = None\n self.event_on_response_thread = None # évenements lors de réponse (positive ou négative)\n\n def setEventResponse(self, e): # ajout d'evenements\n self.event_on_response_thread = e\n\n def onIpTyped(self, IP): # quand l'utilisateur a tapé une IP\n self.IP = IP\n\n def tryConn(self):\n self.getConn.start()\n \n def close(self):\n try:\n self.connexion_avec_serveur.close()\n except:\n pass\n\n def onJoined(self, connexion_avec_serveur): # est appelé lors de la fin du Thread\n if connexion_avec_serveur == None:\n self.event_on_response_thread(0)\n else:\n self.connexion_avec_serveur = connexion_avec_serveur\n getInstanceSocketManager(connexion_avec_serveur)\n self.event_on_response_thread(1)\n self.getConn = GetConnexion(self)\n \n\nclass GetConnexion(Thread):\n def __init__(self, multiModel):\n Thread.__init__(self)\n self.multiModel = multiModel\n self.connexion_avec_serveur = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n def run(self):\n try:\n self.connexion_avec_serveur.connect((self.multiModel.IP, 2009)) # tente d'établir une connexion\n self.connexion_avec_serveur.setblocking(0) # si OK on définie en non bloquant\n self.multiModel.onJoined(self.connexion_avec_serveur)\n except:\n self.multiModel.onJoined(None) # si évènements avec None en paramètre\n\ninstance = None\ndef getInstance(): # singleton\n global instance\n if instance == None:\n instance = MultiConnModel()\n return instance\n","sub_path":"model/multi/multiConnModel.py","file_name":"multiConnModel.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"111207710","text":"import GridWriter\nimport ExcelParser\nfrom continue_copy import continue_copy\n\nimport os\nimport shutil\nimport sys\nimport errno\nimport time\nimport re\nfrom openpyxl import load_workbook\n\ndef make_clean_dir(output_dir):\n if os.path.isdir(output_dir):\n shutil.rmtree(output_dir)\n print('\\nLook in ' + output_dir)\n for i in range(2):\n try:\n os.makedirs(output_dir)\n break\n except OSError as os_error:\n if os_error.errno != errno.EACCES:\n raise\n pass\n print('.')\n time.sleep(0.3)\n return output_dir\n\ndef make_chapter_id(sheet_name):\n return sheet_name.replace(' ', '_').replace(',', '_')\n\ndef make_activity_characteristics(grid, sub_activities):\n activity_map = {}\n for activity in grid:\n activity_key = activity['activity folder'].lower()\n activity_character = {'mandatory': activity['mandatory']}\n activity_map[activity_key] = activity_character\n activity_subs = [sub for sub in sub_activities if sub.lower().startswith(activity_key + '.')]\n for activity_sub in activity_subs:\n activity_map[activity_sub] = activity_character\n return activity_map\n\n\ndef copy_subject_resources(raw_material_dir, grid_output_dir):\n resource_base = os.path.basename(grid_output_dir)\n continue_copy(os.path.join(raw_material_dir, resource_base + '_logo.png'),\n os.path.join(grid_output_dir, 'subject_logo.png'))\n\n\ndef export_image(chapter_id, grid_html_path, output_dir):\n image_converter = 'wkhtmltoimage.exe'\n if os.path.isfile(image_converter):\n conv_command = 'wkhtmltoimage.exe --width 5500 \"' + grid_html_path + '\" \"' + \\\n os.path.join(output_dir, chapter_id+'.jpg') + '\"'\n os.system(conv_command)\n\ndef get_zero_symbol_offset(config_dict):\n zero_symbol_key = \"symbols zero one two\"\n zero_symbol_ord = ord('0')\n if zero_symbol_key in config_dict:\n zero_symbol_value = config_dict[zero_symbol_key]\n if not isinstance(zero_symbol_value, str):\n print(\"Symbol in config sheet needs to be a string!\")\n zero_symbol_ord = ord(zero_symbol_value[0])\n return zero_symbol_ord - ord('0')\n\ndef warn_on_improper_chapter_id(chapter_id):\n if not re.match(\"^[\\w\\d_-]+$\", chapter_id):\n print(\"** Warning: \" + chapter_id + \" is not a valid ID (only alpha-numeric and _ allowed)\")\n\ndef generate_grid(curriculum_excel, raw_material_dir, activities_dir, output_parent):\n grid_output_dir = os.path.join(output_parent, os.path.splitext(os.path.basename(curriculum_excel))[0])\n make_clean_dir(grid_output_dir)\n w = load_workbook(curriculum_excel)\n symbol_offset = get_zero_symbol_offset(ExcelParser.grab_config(w))\n chapter_activities = []\n for sheet_name in w.sheetnames:\n print(sheet_name)\n html_chapter_name = chapter_id = make_chapter_id(sheet_name.upper())\n warn_on_improper_chapter_id(chapter_id)\n chapter_name = str(w[sheet_name]['A1'].value)\n if chapter_name is not None:\n html_chapter_name = str(GridWriter.html_encoded_name(chapter_name)).strip()\n grid = ExcelParser.forge_grid(w[sheet_name], symbol_offset)\n if grid is not None:\n grid_html_path, sub_activites = GridWriter.forge_milestone_grid(grid, html_chapter_name, chapter_id,\n raw_material_dir, activities_dir,\n os.path.join(grid_output_dir, chapter_id))\n chapter_activities.append({'chapter_name': chapter_name,\n 'chapter_id': chapter_id,\n 'activities': make_activity_characteristics(grid, sub_activites)})\n export_image(chapter_id, grid_html_path, grid_output_dir)\n else:\n w.remove(w[sheet_name])\n GridWriter.write_chapter_activities(chapter_activities, raw_material_dir, grid_output_dir)\n for dirName, subdirList, fileList in os.walk(output_parent):\n if dirName.lower().endswith('projectfile'):\n shutil.rmtree(dirName)\n print('deleted: %s' % dirName)\n copy_subject_resources(raw_material_dir, grid_output_dir)\n w.save(os.path.join(output_parent, 'numid_'+os.path.basename(curriculum_excel)))\n\nif len(sys.argv) == 5:\n generate_grid(curriculum_excel=sys.argv[1],\n raw_material_dir=sys.argv[2], activities_dir=sys.argv[3], output_parent=sys.argv[4])\nelse:\n print('Grid creator\\nUsage: ' + sys.argv[0] + ' ')\n","sub_path":"venv/GridCreator.py","file_name":"GridCreator.py","file_ext":"py","file_size_in_byte":4684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"228533331","text":"print('Welcome to my Swager quiz game')\nname = 'Traveler'\n\nprint(\"answer these questions to pass the gate of knoledge \" + name)\ndef q1():\n print(\"what Does the fox say?\")\n answer = input('> ')\n\n if answer == 'wawawawa':\n print(\"Ummm no Go back to youtube\")\n return False\n elif answer == 'hahahanayayya':\n print(\"Heck Nah YOU STUPID\")\n return False\n elif answer == 'nahnahnah':\n print(\"FINALLY YES YOUR NOT STUPID\")\n return True\n else:\n print('NO YOU STOOPED')\n return False\n\ndef q2():\n print(\"what is my name\")\n answer = input('> ')\n \n if answer == 'Rob':\n print(\"No\")\n return False\n elif answer == 'Nic':\n print(\"Hahahahahhaha... no\")\n return False\n elif answer == 'Aidan':\n print(\"Yess\")\n return True\n\nquestions = [q1, q2]\nimport random\n\nwhile questions:\n question = random.choice(questions)\n correct = question()\n if correct:\n questions.remove(question)\n","sub_path":"QUIZ OF BOSSNESS.py","file_name":"QUIZ OF BOSSNESS.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"512127771","text":"\"\"\"empty message\n\nRevision ID: 4bc6d443664e\nRevises: e35cf64c9431\nCreate Date: 2019-12-13 23:12:52.789371\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '4bc6d443664e'\ndown_revision = 'e35cf64c9431'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('student_coaching_relation', 'CoachingStubject')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('student_coaching_relation', sa.Column('CoachingStubject', sa.VARCHAR(length=140), nullable=True))\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/4bc6d443664e_.py","file_name":"4bc6d443664e_.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"519881422","text":"import gym\nimport numpy as np\nimport random\nimport torch\nfrom torch import nn\nfrom collections import deque\n\nseed = 42\nstep_limit = 5000\nenv = gym.make('CartPole-v0')\nenv._max_episode_steps = step_limit\nenv.seed(seed)\ntorch.manual_seed(seed)\n\ninput_size = env.observation_space.shape[0]\noutput_size = env.action_space.n\nhidden_size = 64\n\nbatch_size = 64\ntraining_interval = 10\ntarget_update_interval = 5\nreplay_memory = 50000\nlearning_rate = 1e-1\n\ngamma = 0.99\nmax_episodes = 5000\ninitial_epsilon = 1.0\nepsilon_decay = 0.99\n\nbreak_episodes = 4\nbreak_reward = 4500\n\n\nclass DQN(nn.Module):\n\n def __init__(self, input_dim, hidden_dim, output_dim):\n super(DQN, self).__init__()\n self.linear = nn.Sequential(\n nn.Linear(input_dim, hidden_dim, bias=False),\n nn.Tanh(),\n nn.Linear(hidden_dim, output_dim, bias=False)\n )\n\n def forward(self, inputs):\n return self.linear(inputs)\n\n\ndef replay_train(main_net, target_net, train_batch, criterion, optimizer):\n x_batch = []\n y_batch = []\n\n for state, action, reward, next_state, done in train_batch:\n x = torch.Tensor(state).float()\n q = main_net(x).data.numpy()\n\n if done:\n q[action] = reward\n else:\n next_x = torch.Tensor([next_state]).float()\n next_q = target_net(next_x).data.numpy()\n q[action] = reward + gamma * np.max(next_q)\n\n x_batch.append(state)\n y_batch.append(q)\n\n loss = criterion(main_net(torch.Tensor(x_batch).float()), torch.Tensor(y_batch).float())\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n return loss.data.numpy()\n\n\ndef simulate_bot(net):\n state = env.reset()\n reward_sum = 0\n while True:\n env.render()\n x = torch.Tensor(state).float()\n q = net(x).data.numpy()\n action = np.argmax(q)\n state, reward, done, _ = env.step(action)\n reward_sum += reward\n if done:\n print(f\"total score = {reward_sum}\")\n break\n\n\ndef main():\n main_dqn = DQN(input_size, hidden_size, output_size)\n main_dqn.train()\n target_dqn = DQN(input_size, hidden_size, output_size)\n target_dqn.eval()\n\n target_dqn.load_state_dict(main_dqn.state_dict())\n\n criterion = torch.nn.MSELoss()\n optimizer = torch.optim.Adam(main_dqn.parameters(), lr=learning_rate)\n\n replay_buffer = deque(maxlen=replay_memory)\n reward_history = deque(maxlen=break_episodes)\n\n for episode in range(max_episodes):\n state = env.reset()\n eps = initial_epsilon * np.power(epsilon_decay, episode)\n episode_reward = 0\n done = False\n\n while not done:\n if np.random.rand(1) < eps:\n action = env.action_space.sample()\n else:\n x = torch.Tensor(state).float()\n q = main_dqn(x).data.numpy()\n action = np.argmax(q)\n\n next_state, reward, done, _ = env.step(action)\n if done:\n reward = -100\n\n replay_buffer.append((state, action, reward, next_state, done))\n\n episode_reward += reward\n state = next_state\n\n if episode_reward >= break_reward: # good enough\n break\n\n print(f\"episode = {episode + 1}, rewards = {episode_reward}\")\n\n reward_history.append(episode_reward)\n reward_avg = np.mean(reward_history)\n if reward_avg == break_reward:\n print(f\"game cleared in {episode} episodes with avg step {reward_avg}\")\n break\n\n if (episode + 1) % target_update_interval == 0:\n target_dqn.load_state_dict(main_dqn.state_dict())\n\n if ((episode + 1) % training_interval == 0) & (len(replay_buffer) > batch_size * training_interval):\n for _ in range(training_interval):\n minibatch = random.sample(replay_buffer, batch_size)\n replay_train(main_dqn, target_dqn, minibatch, criterion, optimizer)\n\n main_dqn.eval()\n simulate_bot(main_dqn)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Lab7-02-DQN2015CartPolePT.py","file_name":"Lab7-02-DQN2015CartPolePT.py","file_ext":"py","file_size_in_byte":4103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"118459496","text":"import re\n\ndef open_file(filename):\n f = open(filename, 'r', encoding = 'UTF-8')\n words = f.read()\n f.close()\n return words\n\ndef create_file(string):\n f = open('Slonomar.txt', 'w', encoding = 'UTF-8')\n f.write(string)\n f.close()\n return f\n \ndef find_word(words):\n res = re.sub('комар((а(х|м|ми)|у|ов|ом|е|ы|а)|( |,|.|!|\\?|:|;|\\n|-))',r'слон\\1', words)\n res_sec = re.sub('Комар((а(х|м|ми)|у|ов|ом|е|ы|а)|( |,|.|!|\\?|:|;|\\n|-))',r'Слон\\1', res)\n create_file(str(res_sec))\n print('\\n' + 'Слова в файле заменены. Новый текст записан в файл Slonomar.txt' + '\\n' + 'Всего хорошего!')\n return res\n \ndef main():\n find_word(open_file(input('Здравствуйте, для начала работы, введите имя файла: ')))\n \n \nmain()\n","sub_path":"Home_Work_10.py","file_name":"Home_Work_10.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"409063320","text":"\"\"\"project users\n\nRevision ID: 070402407d93\nRevises: b76fad10af9c\nCreate Date: 2019-01-15 23:28:16.714260\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '070402407d93'\ndown_revision = 'b76fad10af9c'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('project_user',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('projectid', sa.Integer(), nullable=True),\n sa.Column('timestamp', sa.DateTime(), nullable=True),\n sa.Column('userid', sa.Integer(), nullable=True),\n sa.Column('userole', sa.String(length=30), nullable=True),\n sa.ForeignKeyConstraint(['projectid'], ['project.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_project_user_timestamp'), 'project_user', ['timestamp'], unique=False)\n op.create_index(op.f('ix_project_user_userid'), 'project_user', ['userid'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_project_user_userid'), table_name='project_user')\n op.drop_index(op.f('ix_project_user_timestamp'), table_name='project_user')\n op.drop_table('project_user')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/070402407d93_project_users.py","file_name":"070402407d93_project_users.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"259725798","text":"#import sys, os\n#sys.path.insert(0, '/media/nmsutton/Ext3Drive/General/NEST/NEST/lib64/python3.4/site-packages')\n\n#print (os.path.dirname(sys.executable))\n#print (os.environ)\n\nimport pylab\nimport nest\n\nprint (\"test\")\n\nneuron = nest.Create(\"iaf_neuron\")\nneuron2 = nest.Create(\"iaf_neuron\")\nneuron3 = nest.Create(\"iaf_neuron\")\n\nmultimeter = nest.Create(\"multimeter\")\nnest.SetStatus(multimeter, {\"withtime\":True, \"record_from\":[\"V_m\"]})\nmultimeter2 = nest.Create(\"multimeter\")\nnest.SetStatus(multimeter2, {\"withtime\":True, \"record_from\":[\"V_m\"]})\n\nnest.SetStatus(neuron, {\"I_e\": 376.0})\nnest.SetStatus(neuron2, {\"I_e\": 326.0})\n#nest.SetStatus(neuron2, {\"V_m\": 376.0})\n\nnest.Connect(neuron, neuron2, syn_spec = {\"weight\":-150.0})\n\n#nest.SetStatus(neuron, {\"V_m\": 376.0})\n#print (nest.GetStatus(neuron, \"V_m\"))\n\nnest.Connect(multimeter, neuron)\nnest.Connect(multimeter2, neuron2)\n\nspikedetector = nest.Create(\"spike_detector\",\n params={\"withgid\": True, \"withtime\": True})\nnest.Connect(neuron, spikedetector)\n\nnest.Simulate(1000.0)\n\ndmm = nest.GetStatus(multimeter)[0]\nVms = dmm[\"events\"][\"V_m\"]\nts = dmm[\"events\"][\"times\"]\n\npylab.figure(1)\npylab.plot(ts, Vms)\n\ndmb = nest.GetStatus(multimeter2)[0]\nVmsb = dmb[\"events\"][\"V_m\"]\ntsb = dmb[\"events\"][\"times\"]\n\npylab.figure(2)\npylab.plot(tsb, Vmsb)\n\n'''dSD = nest.GetStatus(spikedetector,keys='events')[0]\nevs = dSD[\"senders\"]\nts = dSD[\"times\"]\npylab.figure(2)\npylab.plot(ts, evs, \".\")'''\n\npylab.show()","sub_path":"python_version/examples/nestTestSynapses.py","file_name":"nestTestSynapses.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"82869890","text":"from flask import Flask\nfrom flask import render_template\napp = Flask(__name__)\n\nBOOKS_INFO = {\n 'mindset': {\n 'full_name': 'Mindset - Updated Edition: Changing The Way You Think To Fulfil Your Potential',\n 'author': 'Carol Dweck',\n 'published': 'January 17, 2017',\n 'picture': 'https://images-na.ssl-images-amazon.com/images/I/81u%2BjLjLHgL.jpg'\n },\n 'habits': {\n 'full_name': 'Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones',\n 'author': 'James Clear',\n 'published': 'October 16, 2018',\n 'picture': 'https://static.raru.co.za/cover/2018/05/25/6665445-l.jpg'\n },\n 'compound-effect': {\n 'full_name': 'The Compound Effect',\n 'author': 'Darren Hardy',\n 'published': 'June 1, 2010',\n 'picture':\n 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSfk1Tg4iYiKeqEuxhgED5LGy9VWwE4C0VxlHn9XwK4kN2q4l2I'\n }\n}\n@app.route('/')\ndef library():\n books_list = []\n for book in BOOKS_INFO:\n\n books_list.append(book)\n print(books_list)\n return render_template('routing/books.html',\n books=books_list)\n\n@app.route('/book/')\ndef book(name_of_book):\n print(BOOKS_INFO[name_of_book])\n return render_template('routing/book.html',\n book=BOOKS_INFO[name_of_book])","sub_path":"_05_basic_routing.py","file_name":"_05_basic_routing.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"255661077","text":"import socket\n\ndef crc16(str): # CRC 计算函数 输入是字符串\n data = bytearray.fromhex(str)\n crc = 0xFFFF\n for pos in data:\n crc ^= pos\n for _ in range(8):\n if ((crc & 1) != 0):\n crc >>= 1\n crc ^= 0xA001\n else:\n crc >>= 1\n crc = ((crc & 0xff) << 8) + (crc >> 8)\n # print(hex(crc).upper()[2:])\n # return hex(crc).upper()[2:]\n # print('%02X' % crc)\n return '%02X' % crc\n\ncloud_addr = '00000000'\ncloud_port = 8105\n\nframe_head = 'FFFE'\nregister = '01'\nforward = '03'\nheart = '02'\ndata = '0004aaaa'\nframe_tail = 'EFFF'\n\nsrc_addr = '00000001'\n\nREG = 1\nHEART = 2\nFORWARD = 3\n\ndef main():\n state = REG\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n cloud_info = (cloud_addr,cloud_port)\n while True:\n if state == REG:\n crc = crc16(src_addr+cloud_addr+register+data)\n frame = frame_head+src_addr+cloud_addr+register+data+crc+frame_tail\n sock.sendto(bytearray.fromhex(frame),cloud_info) #发消息\n state = HEART\n elif state == HEART:\n crc = crc16(src_addr+cloud_addr+heart+data)\n frame = frame_head+src_addr+cloud_addr+heart+data+crc+frame_tail\n sock.sendto(bytearray.fromhex(frame),cloud_info) #发消息\n state = FORWARD\n elif state == FORWARD:\n crc = crc16(src_addr+cloud_addr+forward+data)\n frame = frame_head+src_addr+cloud_addr+forward+data+crc+frame_tail\n sock.sendto(bytearray.fromhex(frame),cloud_info) #发消息\n state = HEART\n else:\n print(\"Undefined state :(\")\n \n print(sock.recvfrom(1024).decode(\"utf-8\")) #收消息,recvfrom可以得到发送方的消息和地址,recv只能得到消息\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"client_send.py","file_name":"client_send.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"171233576","text":"# test SoftConstrainedIPMModule\n\nimport torch\nimport sys\nsys.path.append(\"../OCTMultiSurfaces/network\")\nfrom QuadraticIPMOpt import *\n#from OCTPrimalDualIPM import *\n\nfrom torch.autograd import gradcheck\n\ndevice =torch.device(\"cuda:0\")\ndtype = torch.float\nB = 2\nW = 3\nN = 5\nlr = 0.0001 # learning rate\nnEpic = 100\n\n\nMu = 10.0*torch.rand(B,N,W, dtype=dtype, device=device, requires_grad=True)\nMu.retain_grad()\nsigma2= 2.0*torch.rand(B,N,W, dtype=dtype, device=device, requires_grad=True)\nsigma2.retain_grad()\nR = (torch.rand(B,N,W, device=device)+0.5) * torch.cat((Mu[:,0,:].unsqueeze(dim=1), Mu[:,1:,:]- Mu[:,0:-1,:]), dim=1)\nR.retain_grad()\n#c_lambda = (4*torch.max(sigma2)).clone() # error: one of the variables needed for gradient computation has been modified by an inplace operation:\n#c_lambda.detach()\n# c_lambda = 10.0\n\nG = torch.tensor([[1,1,1],[3,3,3], [4,4,4], [6,6,6], [8,9,7]], dtype=dtype, device= device)\nG = G.unsqueeze(dim=0)\nG = torch.cat((G,G),dim=0) # size:(B,N,W)\n\n# first run IPMModule to get gradient of Input variables.\n# test softConstrainedIPM\nseperationIPM = SoftSeparationIPMModule()\nS = seperationIPM(Mu,sigma2,R=R, usePairwiseWeight=True)\n\n# test HardSeparationIPMModule\n#seperationIPM = HardSeparationIPMModule()\n#S = seperationIPM(Mu,sigma2)\n\nloss = torch.pow(G-S,2).sum()\n\nprint(f\"Before loss.backward: Mu.grad = {Mu.grad}\")\n\n# calling the backward() of a Variable only generates the gradients of the leaf nodes\nloss.backward(gradient=torch.ones(loss.shape).to(device), retain_graph=True)\n\nprint(f\"After loss.backward: Mu.grad =\\n {Mu.grad}\")\nprint(f\"After loss.backward: sigma2.grad =\\n {sigma2.grad}\")\nprint(f\"After loss.backward: R.grad =\\n {R.grad}\")\n\n# check whether loss reduces when changing input according gradient.\nprint(f\"epic:{-1}, loss = {loss.item()}\")\nfor i in range(nEpic):\n Mu -= lr* Mu.grad\n sigma2 -= lr*sigma2.grad\n R -= lr * R.grad\n Mu.grad.zero_()\n sigma2.grad.zero_()\n #if R.grad is not None:\n R.grad.zero_()\n\n # softSeparation\n S = seperationIPM(Mu, sigma2, R)\n # hardSeperation\n #S = seperationIPM(Mu,sigma2)\n loss = torch.pow(G - S, 2).sum()\n print(f\"epic:{i}, loss = {loss.item()}\")\n loss.backward(gradient=torch.ones(loss.shape).to(device), retain_graph=True)\n","sub_path":"Test/testSoftConstraintIPM.py","file_name":"testSoftConstraintIPM.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"154773947","text":"# https://py.checkio.org/en/mission/sum-numbers/\n\ndef sum_numbers(text: str) -> int:\n\n split_list = text.split(\" \")\n numbers = []\n \n for i in split_list:\n try:\n numbers.append(int(i))\n #breakpoint()\n except:\n continue\n \n if len(numbers) < 1:\n return 0\n elif len(numbers) == 1:\n return numbers[0]\n else:\n return sum(numbers)\n\n\nif __name__ == '__main__':\n print(\"Example:\")\n print(sum_numbers('hi'))\n\n # These \"asserts\" are used for self-checking and not for an auto-testing\n assert sum_numbers('hi') == 0\n assert sum_numbers('who is 1st here') == 0\n assert sum_numbers('my numbers is 2') == 2\n assert sum_numbers('This picture is an oil on canvas '\n 'painting by Danish artist Anna '\n 'Petersen between 1845 and 1910 year') == 3755\n assert sum_numbers('5 plus 6 is') == 11\n assert sum_numbers('') == 0\n print(\"Coding complete? Click 'Check' to earn cool rewards!\")\n\n\"\"\"\n In a given text you need to sum the numbers. Only separated numbers should be counted. If a number is part of a word it shouldn't be counted.\n\nThe text consists from numbers, spaces and english letters\n\nInput: A string.\n\nOutput: An int. \n\"\"\"","sub_path":"completed/sum_numbers.py","file_name":"sum_numbers.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"6159317","text":"#!/usr/bin/python\nimport csv\n\ndef write_primes(l,file_name):\n '''\n Writes number onto a csv file.\n\n Parameters:\n l(list): list of number wanting to write.\n file_name: name of the file wanting to write to.\n\n Result:\n Writes numbers from list onto file_name as a csv file\n '''\n with open(file_name, mode = 'w') as csvfile:\n primewriter = csv.writer(csvfile, delimiter = ' ')\n primewriter.writerow(l)\n \ndef read_primes(file_name):\n '''\n Reads numbers from a csv file.\n\n Parameters:\n file_name: name of the file wanting to read.\n\n Result:\n Reads numbers from a csv file and print them while putting a comma between each\n '''\n with open(file_name) as csvfile:\n primereader = csv.reader(csvfile, delimiter = ' ')\n for row in primereader:\n print(', '.join(row))\n","sub_path":"primepackage/primeio.py","file_name":"primeio.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"141783385","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nclass Solution:\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n # 遍历每一个位置,向两边扩张\n# if len(s) == 0 or s is None:\n# return s\n \n# inter_s = '#' + '#'.join(list(s)) + '#'\n# radius = [1 for _ in range(len(inter_s))]\n# max_r_idx = 0\n# for i in range(len(inter_s)):\n# left = i - radius[i]\n# right = i + radius[i]\n# while 0 <= left and right < len(inter_s) and inter_s[left] == inter_s[right]:\n# radius[i] += 1\n# left = i - radius[i]\n# right = i + radius[i]\n# if radius[i] > radius[max_r_idx]:\n# max_r_idx = i\n \n# max_left = max_r_idx - radius[max_r_idx] + 1\n# max_right = max_r_idx + radius[max_r_idx]\n# return inter_s[max_left : max_right].replace('#', '')\n\n # 遍历第一个位置,在向两扩张前,先做初始化,考虑对称点和mx-i\n # 从而减少比较次数\n if len(s) == 0 or s is None:\n return s\n \n inter_s = '$#' + '#'.join(list(s)) + '#@'\n radius = [0 for _ in range(len(inter_s))]\n max_r_idx = 0\n mx = 0\n id = 0\n for i in range(1, len(inter_s)-1):\n # 半径初始化\n # 2 * id - i是i关于id的对称点\n # radius[i]至少是对称点的值或者是mx-i\n # 后面还会再扩张\n # id是当前位置之前的一个轴的下标\n # mx = id + radius[id]\n if i < mx:\n radius[i] = min(radius[2 * id - i], mx - i)\n else:\n radius[i] = 1\n left = i - radius[i]\n right = i + radius[i]\n while inter_s[left] == inter_s[right]:\n radius[i] += 1\n left = i - radius[i]\n right = i + radius[i]\n if radius[i] > radius[max_r_idx]:\n max_r_idx = i\n if i + radius[i] > mx:\n mx = i + radius[i]\n id = i\n \n max_left = max_r_idx - radius[max_r_idx] + 1\n max_right = max_r_idx + radius[max_r_idx]\n return inter_s[max_left : max_right].replace('#', '')\n\nif __name__ == '__main__':\n print(Solution().longestPalindrome('babad'))\n print(Solution().longestPalindrome('cbbd'))\n print(Solution().longestPalindrome('abb'))\n print(Solution().longestPalindrome('a'))\n","sub_path":"longest_palindrome.py","file_name":"longest_palindrome.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"271026493","text":"# Section1: Inserting and Getting Book data #\ndef CodeMaker(LanguagesAbbreviations, CategoryAbbreviations, Language, Category, Spreadsheet):\n #makes a unique ID for a book using its language, category and its spreadsheet.\n from openpyxl import load_workbook\n if Language in LanguagesAbbreviations and Category in CategoryAbbreviations:\n Current_Workbook = load_workbook(Spreadsheet)\n Current_Worksheet = Current_Workbook[Category]\n Last_Occupied_Row = Current_Worksheet.max_row\n Id_Number = Last_Occupied_Row + 1\n Language_Ab = LanguagesAbbreviations[Language]\n Category_Ab = CategoryAbbreviations[Category]\n Code = f'{Language_Ab}-{Category_Ab}/{Id_Number}'\n print(Code)\n return Code\n else:\n return 1\n\ndef InsertBook(BookName, Price, Author, Publisher, Audience, Language, Catagory):\n # inserts a book into a spreadsheet using its data (It takes Languages like \"Malayalam\" not M).\n Prohibited = ['', ' ']\n\n # TODO: Outsource the following three variables.\n Languages_Abbreviations = {'English': 'E', 'Malayalam': 'M', 'Hindi': 'H'}\n Spreadsheet_Addresses = {'M': 'Spreadsheets\\Book_Details\\Malayalam_books.xlsx', 'E': 'Spreadsheets\\Book_Details\\English_books.xlsx', 'H': 'Spreadsheets\\Book_Details\\Hindi_books.xlsx'}\n Category_Abbreviations = {'Fiction': 'FC', 'NonFiction': 'NF', 'SelfHelp': 'SF', 'Magazine': 'MG'}\n\n if BookName not in Prohibited and Author not in Prohibited and Publisher not in Prohibited:\n if Catagory.lower() != 'select' and Language != 'select':\n if Language in Languages_Abbreviations and Catagory in Category_Abbreviations:\n from openpyxl import load_workbook\n workbook = load_workbook(Spreadsheet_Addresses[Languages_Abbreviations[Language]])\n worksheet = workbook[Catagory]\n Book_Details = [BookName, Price,\n CodeMaker(Languages_Abbreviations, Category_Abbreviations, Language,\n Catagory, Spreadsheet_Addresses[Languages_Abbreviations[Language]]), Author,\n Publisher, Audience]\n if not Book_Details[2] == 1:\n worksheet.append(Book_Details)\n print(Book_Details)\n else:\n return [1, \"The language or the category is wrong :(\"]\n else:\n return 1\n else:\n return 1\n else:\n return 1\n\ndef FetchBookDetails(BookCode):\n #Returns a list of book detail from a book code.\n # can be used to autofill details into forms\n book_details = []\n from openpyxl import load_workbook\n Categories = {'FC': 'Fiction', 'NF': 'NonFiction', 'SH': 'SelfHelp', 'MG': 'Magazine'}\n Languages = {'M': 'Spreadsheets\\Book_Details\\Malayalam_books.xlsx', 'E': 'Spreadsheets\\Book_Details\\English_books.xlsx'}\n if str(type(BookCode)) == \"\":\n if not BookCode == '' and not BookCode == ' ':\n if '-' in BookCode and '/' in BookCode:\n BookCode = BookCode.split('-')\n LanguageIndex = BookCode[1].split('/')\n BookCode[1] = LanguageIndex[0]\n BookCode.append(LanguageIndex[1])\n BookCode[1] = BookCode[1].upper()\n BookCode[2] = BookCode[2].upper()\n if BookCode[0] in Languages:\n if BookCode[1] in Categories:\n workbook = load_workbook(Languages[BookCode[0]])\n worksheet = workbook[Categories[BookCode[1]]]\n for cell in range(1, 7):\n book_details.append(worksheet.cell(int(BookCode[2]) + 1, column=cell).value)\n return book_details\n else:\n return [1, 'The catagory is wrong :(']\n else:\n return [1, 'The language code is not specified:(']\n else:\n return [1, 'The code is not correctly written :(']\n else:\n return [1, \"You Didn't write any code :(\"]\n else:\n return [1, 'Please only enter a string']\n# --End of Section 1-- #\n\n# Section2: Book Statistics\ndef FindOverdueBooks():\n from openpyxl import load_workbook\n import datetime\n borrowed_book_details = []\n Borrowed_Books_Data = load_workbook(\"Borrowed_books.xlsx\")\n DataSheet = Borrowed_Books_Data['DataSheet']\n for row in range(2, DataSheet.max_row + 1):\n returned = DataSheet.cell(row=row, column=6).value\n if not returned:\n R_Date = DataSheet.cell(row=row, column=3).value\n R_Month = DataSheet.cell(row=row, column=4).value\n R_Year = DataSheet.cell(row=row, column=5).value\n Original_Return_Date = datetime.date(R_Year, R_Month, R_Date)\n today = datetime.date.today()\n time_left_for_return = Original_Return_Date - today\n if time_left_for_return.days <= 0:\n Book_Details = []\n for column in range(1, 3):\n Book_Details.append(DataSheet.cell(row=row, column=column).value)\n borrowed_book_details.append(Book_Details)\n return borrowed_book_details\n# --End of section 2-- #","sub_path":"Functionality/BMT.py","file_name":"BMT.py","file_ext":"py","file_size_in_byte":5376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"421787077","text":"from tensorflow.python.ops.rnn_cell import _linear\nfrom tensorflow.python.util import nest\n\nfrom my.tensorflow import flatten, reconstruct\n\n\ndef linear(args, output_size, bias, bias_start=0.0, scope=None):\n if args is None or (nest.is_sequence(args) and not args):\n raise ValueError(\"`args` must be specified\")\n if not nest.is_sequence(args):\n args = [args]\n\n flat_args = [flatten(arg, 1) for arg in args]\n flat_out = _linear(flat_args, output_size, bias, bias_start=bias_start, scope=scope)\n out = reconstruct(flat_out, args[0], 1)\n return out\n\n\n","sub_path":"my/tensorflow/nn.py","file_name":"nn.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"343805189","text":"from mcpi.minecraft import Minecraft\nimport random\n\nmc = Minecraft.create()\n\nplayerPos = mc.player.getPos()\nox = playerPos.x\noy = playerPos.y\noz = playerPos.z\ngoldx = ox+random.randint(-10,10)\ngoldz = oz+random.randint(-10,10)\ngoldy = mc.getHeight(goldx,goldz)\n\nwhile True:\n playerPos = mc.player.getPos()\n x = playerPos.x\n y = playerPos.y\n z = playerPos.z\n mc.postToChat(\"GOLD: %d, %d, %d\" %(goldx,goldy,goldz))\n mc.postToChat(\" NOW: %d, %d, %d\" %(x,y,z))\n if int(goldx) == int(x):\n mc.postToChat(\"*\"*50)\n break\n","sub_path":"lectureData/day15/r3.py","file_name":"r3.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"407156462","text":"def collatz(number):\n if (number % 2) == 0:\n return number // 2\n else:\n return 3 * number + 1\n\nnumber = 0\nexecute = True\n\nprint('Enter a number:')\n\ntry:\n number = int(input())\n \n if number == 0:\n execute = False\n \nexcept ValueError:\n print('Invalid input value!')\n execute = False\n \nwhile execute:\n number = collatz(number)\n print(str(number))\n if number == 1:\n break\n","sub_path":"Other/collatzSequence.py","file_name":"collatzSequence.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"56412844","text":"import rospy\r\nfrom sensor_msgs.msg import Image\r\nfrom cefpython3 import cefpython as cef\r\nimport codecs\r\nimport autopy\r\n#import tensorflow.keras\r\nfrom PIL import Image, ImageOps\r\nimport numpy as np\r\nimport cv2\r\nimport threading\r\nimport base64\r\nimport tkinter as tk\r\nimport sys\r\nfrom gtts import gTTS\r\nimport playsound\r\nrun = True\r\n\r\n\r\n\r\nclass LoadHandler(object):\r\n\tdef OnLoadingStateChange(self,browser,is_loading,**_):\r\n\t\tpass\r\n\r\ndef say(text):\r\n\ttts = gTTS(text=text,lang='th')\r\n\ttts.save('sound.mp3')\r\n\tplaysound.playsound('sound.mp3', True)\r\n\r\ndef command(func):\r\n\ta=[]\r\n\tb=[]\r\n\tx_temp=[]\r\n\tfor i in range(10):\r\n\t\tb_time=time.time()\r\n\t\ta.append(random.randrange(1, 255))\r\n\t\tb.append(random.randrange(1, 255))\r\n\t\tx_temp.append(int(b_time-a_time))\r\n\ty = [a,b,x_temp]\r\n\tfunc.Call(y)\r\n\r\ndef command(function1,function2):\r\n\tglobal fun1,fun2\r\n\tfun1 = function1\r\n\tfun2 = function2\r\n\r\ndef setBindings(browser):\r\n\tbindings = cef.JavascriptBindings()\r\n\tbindings.SetFunction(\"setup\",command)\r\n\tbrowser.SetJavascriptBindings(bindings)\r\n\r\ndef move():\r\n\tpass\r\n\r\ndef callback(data):\r\n\tprint(data.data)\r\n\tif not run :\r\n\t\texit()\r\n\t#rospy.loginfo(rospy.get_caller_id() + \"I heard %s\", data.data)\r\n\r\ndef saveImg():\r\n\tbitmap_object = autopy.bitmap.capture_screen()\r\n\tbitmap_object.save('img/path.png')\r\n\tim = Image.open(r\"img/path.png\")\r\n\tleft = 0\r\n\ttop = 720\r\n\tright = 400\r\n\tbottom = 1000\r\n\tim1 = im.crop((left, top, right, bottom))\r\n\tim1.save(\"pathreal.png\")\r\n\ttry:\r\n\t\tretval, buffer = cv2.imencode('.jpg', cv2.imread(\"pathreal.png\"))\r\n\t\tjpg_as_text = base64.b64encode(buffer)\r\n\t\tglobal fun2\r\n\t\tfun2.Call(\"data:image/jpeg;base64,/\"+str(jpg_as_text)[3:-1]) \r\n\texcept:\r\n\t\tpass\r\n\r\ndef loop_camera():\r\n\tglobal run\r\n\twhile run:\r\n\t\tsaveImg()\r\n\r\n\r\ndef main(frame):\r\n\twith codecs.open(\"joystick.html\",\"r\",encoding=\"utf-8\") as file:\r\n\t\tglobal html_code\r\n\t\thtml_code = file.read()\r\n\tsys.excepthook = cef.ExceptHook\r\n\twindow_info = cef.WindowInfo(frame.winfo_id())\r\n\twindow_info.SetAsChild(frame.winfo_id(),[0,0,1200,900])\r\n\tcef.Initialize()\r\n\tbrowser = cef.CreateBrowserSync(\r\n\t\twindow_info,\r\n\t\turl=cef.GetDataUrl(html_code))\r\n\tbrowser.SetClientHandler(LoadHandler())\r\n\tsetBindings(browser)\r\n\tcef.MessageLoop()\r\n\r\nif __name__ == \"__main__\":\r\n\tsay(\"hello sorlab\")\r\n\troot = tk.Tk()\r\n\troot.title(\"BUEN AI Cashier\")\r\n\troot.geometry('1200x900+0+0')\r\n\tframe = tk.Frame(root, height=900)\r\n\tframe.pack(side='top', fill='x')\r\n\tthread = threading.Thread(target=main, args=(frame,))\r\n\tthread.start()\r\n\tthread_camera = threading.Thread(target=loop_camera)\r\n\tthread_camera.start()\r\n\troot.mainloop()\r\n\trun = False\r\n\t#listener()\r\n\t\"\"\"\r\n\trun = False\r\n\tprocess.raise_exception()\r\n\tprocess.join()\r\n\t\"\"\"\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"602029064","text":"class MyStack:\n def __init__(self):\n self.arr = []\n self.ctr = -1\n\n def push(self, val):\n self.arr.append(val)\n self.ctr += 1\n\n def pop(self):\n if self.ctr == -1:\n return None\n tmp = self.arr.pop()\n self.ctr -= 1\n return tmp\n\n def count(self):\n if self.ctr == -1:\n return 0\n return self.ctr + 1\n\nclass MyQueue:\n def __init__(self):\n self.arr1 = MyStack()\n self.arr2 = MyStack()\n self.cur = self.arr1\n self.buf = self.arr2\n\n def enqueue(self, val):\n self.cur.push(val)\n\n def dequeue(self):\n if self.buf.count() == 0:\n self.buf.push(self.cur.pop())\n\n if self.buf.count() == 0:\n return None\n\n return self.buf.pop()\n\n def size(self):\n return self.buf.count() + self.cur.count()\n\ndef doit():\n N_ELEM = 10\n q = MyQueue()\n for i in range(0, N_ELEM):\n q.enqueue(i)\n print('stack created with {} elements'.format(N_ELEM))\n print('deque:{}'.format(q.dequeue()))\n\n for i in range(N_ELEM, 2*N_ELEM):\n q.enqueue(i)\n print('stack added with {} more elements'.format(N_ELEM))\n\n print('current stack snapshot:'.format(N_ELEM))\n ret = ''\n while q.size() > 0:\n ret += str(q.dequeue()) + \",\"\n print(ret)\n\ndoit()\n\n","sub_path":"3/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"237351796","text":"import argparse\nfrom overrides import overrides\nfrom typing import List\n\nfrom sacrerouge.commands import MetricSetupSubcommand\nfrom sacrerouge.common.util import flatten\nfrom sacrerouge.data import MetricsDict\nfrom sacrerouge.data.types import ReferenceType, SummaryType\nfrom sacrerouge.metrics import Metric, DocumentBasedMetric\nimport numpy as np\nimport time\nimport spacy\nimport logging\nlogger = logging.getLogger()\nlogger.disabled = True\n\nfrom sacrerouge.common import DATA_ROOT\nfrom sacrerouge.commands import MetricSetupSubcommand\n\nimport tqdm\nnlp = spacy.load('en_core_web_sm')\n\ntry:\n import bert_score\nexcept ImportError:\n BERTSCORE_FFCI_INSTALLED = False\n\n @Metric.register('bertscore-ffci')\n class BertScoreFFCI(DocumentBasedMetric):\n def __init__(self, *args, **kwargs):\n pass\n\n def score_multi_all(self, *args, **kwargs):\n raise NotImplementedError('Please install the \"bert_score\" python library library to use BertScoreFFCI')\nelse:\n BERTSCORE_FFCI_INSTALLED = True\n\n @Metric.register('bertscore-ffci')\n class BertScoreFFCI(DocumentBasedMetric):\n def __init__(self,\n model_type: str = None,\n num_layers: int = None,\n nthreads: int = 4,\n batch_size: int = 64,\n lang: str = 'en',\n verbose: bool = False) -> None:\n super().__init__()\n self.model_type = model_type\n self.num_layers = num_layers\n\n # self.model_type = \"roberta-base\"\n # self.num_layers = 10\n self.nthreads = nthreads\n self.batch_size = batch_size\n self.lang = lang\n self.verbose = verbose\n\n def _get_unique_references(self, references_list: List[List[str]]) -> List[str]:\n unique_references = set()\n for references in references_list:\n for reference in references:\n unique_references.add(reference)\n return list(unique_references)\n\n def _run(self,\n summaries_list: List[List[SummaryType]],\n references_list: List[List[ReferenceType]]) -> List[List[MetricsDict]]:\n summaries_list = [[flatten(summary) for summary in summaries] for summaries in summaries_list]\n references_list = [[flatten(reference) for reference in references] for references in references_list]\n\n # Create the candidate and reference lists for passing to the scoring function\n input_candidates = []\n input_references = []\n empty_inputs = set()\n for i, (summaries, references) in enumerate(zip(summaries_list, references_list)):\n for j, summary in enumerate(summaries):\n if len(summary) == 0:\n empty_inputs.add((i, j))\n else:\n input_candidates.append(summary)\n input_references.append(references)\n\n f1s = []\n precisions = []\n recalls = []\n for (summary, references) in tqdm.tqdm(zip(input_candidates, input_references), total=len(input_candidates)):\n summary_doc = nlp(summary)\n source_doc = nlp(references[0])\n\n summary_sents = [sent.text for sent in summary_doc.sents]\n source_sents = [sent.text for sent in source_doc.sents]\n cur_scores_f1s = []\n cur_scores_precisions = []\n cur_scores_recalls = []\n for sent in summary_sents:\n # Score the summaries\n cur_precisions, cur_recalls, cur_f1s = bert_score.score(\n source_sents,\n [sent] * len(source_sents),\n model_type=self.model_type,\n num_layers=self.num_layers,\n idf=False,\n nthreads=self.nthreads,\n batch_size=self.batch_size,\n lang=self.lang,\n verbose=self.verbose\n )\n cur_f1s_list = cur_f1s.cpu().tolist()\n top_3 = np.array(cur_f1s_list).argsort()[-3:][::-1]\n top_3_scores = [cur_f1s_list[x] for x in top_3]\n cur_scores_f1s.append(np.mean(top_3_scores))\n\n cur_precisions_list = cur_precisions.cpu().tolist()\n top_3 = np.array(cur_precisions_list).argsort()[-3:][::-1]\n top_3_scores = [cur_precisions_list[x] for x in top_3]\n cur_scores_precisions.append(np.mean(top_3_scores))\n\n cur_recalls_list = cur_recalls.cpu().tolist()\n top_3 = np.array(cur_recalls_list).argsort()[-3:][::-1]\n top_3_scores = [cur_recalls_list[x] for x in top_3]\n cur_scores_recalls.append(np.mean(top_3_scores))\n f1s.append(np.mean(cur_scores_f1s))\n precisions.append(np.mean(cur_scores_precisions))\n recalls.append(np.mean(cur_scores_recalls))\n\n # Remap the scores to the summaries\n index = 0\n metrics_lists = []\n for i, summaries in enumerate(summaries_list):\n metrics_lists.append([])\n for j, summary in enumerate(summaries):\n if (i, j) in empty_inputs:\n precision, recall, f1 = 0.0, 0.0, 0.0\n else:\n # precision = precisions[index].item()\n # recall = recalls[index].item()\n f1 = f1s[index]\n precision = precisions[index]\n recall = recalls[index]\n index += 1\n metrics_lists[-1].append(MetricsDict({\n 'bertscore-ffci': {\n 'p': precision,\n 'r': recall,\n 'f1': f1,\n }\n }))\n\n return metrics_lists\n\n def score_multi_all(self,\n summaries_list: List[List[SummaryType]],\n references_list: List[List[ReferenceType]]) -> List[List[MetricsDict]]:\n return self._run(summaries_list, references_list)\n\n\n@MetricSetupSubcommand.register('bertscore-ffci')\nclass BertScoreFFCISetupSubcommand(MetricSetupSubcommand):\n @overrides\n def add_subparser(self, parser: argparse._SubParsersAction):\n description = 'Setup the BERTScore-ffci metric'\n self.parser = parser.add_parser('bertscore-ffci', description=description, help=description)\n self.parser.set_defaults(subfunc=self.run)\n\n @overrides\n def run(self, args):\n try:\n import bert_score\n print('BertScoreFFCI setup success')\n except ImportError:\n print('Please pip install \"bert_score\" to complete setup')\n\n","sub_path":"sacrerouge/metrics/bertscore-ffci.py","file_name":"bertscore-ffci.py","file_ext":"py","file_size_in_byte":7106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"99358719","text":"import cv2\nimport numpy as np\nimport os\nfrom random import shuffle\nfrom tqdm import tqdm\n\nTRAIN_DIR = '/home/zinary/Documents/project/images'\nTEST_DIR = '/home/zinary/Documents/project/images'\nIMG_SIZE = 50\nLR = 1e-3\n\nMODEL_NAME = 'skin-{}-{}-'.format(LR,'6conv-basic-video')\n\ndef label_img(img):\n word_label = img.split(\" \")[0]\n if word_label == \"Ringworm\" : return [1,0]\n elif word_label == \"Psoriasis\" : return [0,1]\n \ndef create_training_data():\n training_data = []\n for img in tqdm(os.listdir(TRAIN_DIR)) :\n label = label_img(img)\n path = os.path.join(TRAIN_DIR,img)\n img = cv2.resize(cv2.imread(path,cv2.IMREAD_GRAYSCALE),(IMG_SIZE,IMG_SIZE))\n training_data.append([np.array(img),np.array(label)])\n shuffle(training_data)\n np.save('traindata.npy',training_data)\n return training_data\n\ndef process_testing_data():\n testing_data = []\n for img in tqdm(os.listdir(TEST_DIR)):\n path = os.path.join(TEST_DIR,img)\n img_num = img.split(\" \")[0]\n print(img_num)\n img = cv2.resize(cv2.imread(path,cv2.IMREAD_GRAYSCALE),(IMG_SIZE,IMG_SIZE))\n testing_data.append([np.array(img),img_num])\n print(testing_data)\n shuffle(testing_data)\n np.save('testdata.npy',testing_data)\n return testing_data\n\n\n \ntrain_data = create_training_data()\n# If you have already created the dataset:\n# train_data = np.load('traindata.npy',allow_pickle=True)\nprint(\"success\")\n\n\nimport tflearn\nfrom tflearn.layers.conv import conv_2d, max_pool_2d\nfrom tflearn.layers.core import input_data, dropout, fully_connected\nfrom tflearn.layers.estimator import regression\nimport tensorflow as tf\ntf.reset_default_graph()\nconvnet = input_data(shape=[None, IMG_SIZE, IMG_SIZE, 1], name='input')\n\nconvnet = conv_2d(convnet, 32, 5, activation='relu')\nconvnet = max_pool_2d(convnet, 5)\n\nconvnet = conv_2d(convnet, 64, 5, activation='relu')\nconvnet = max_pool_2d(convnet, 5)\n\nconvnet = conv_2d(convnet, 32, 5, activation='relu')\nconvnet = max_pool_2d(convnet, 5)\n\nconvnet = conv_2d(convnet, 64, 5, activation='relu')\nconvnet = max_pool_2d(convnet, 5)\n\nconvnet = conv_2d(convnet, 32, 5, activation='relu')\nconvnet = max_pool_2d(convnet, 5)\n\nconvnet = conv_2d(convnet, 64, 5, activation='relu')\nconvnet = max_pool_2d(convnet, 5)\n\nconvnet = fully_connected(convnet, 1024, activation='relu')\nconvnet = dropout(convnet, 0.8)\n\nconvnet = fully_connected(convnet, 2, activation='softmax')\nconvnet = regression(convnet, optimizer='adam', learning_rate=LR, loss='categorical_crossentropy', name='targets')\n\nmodel = tflearn.DNN(convnet, tensorboard_dir='log')\n\n\ntrain = train_data[:-500]\ntest = train_data[-500:]\n\nX = np.array([i[0] for i in train]).reshape(-1,IMG_SIZE,IMG_SIZE,1)\nY = [i[1] for i in train]\n\ntest_x = np.array([i[0] for i in test]).reshape(-1,IMG_SIZE,IMG_SIZE,1)\ntest_y = [i[1] for i in test]\n\n\nmodel.fit({'input': X}, {'targets': Y}, n_epoch=5, validation_set=({'input': test_x}, {'targets': test_y}), \nsnapshot_step=500, show_metric=True, run_id=MODEL_NAME)\nprint(\"success 2\")\n\n\nmodel.save(MODEL_NAME)\n\n\nimport matplotlib.pyplot as plt\n\n# if you need to create the data:\ntest_data = process_testing_data()\n# if you already have some saved:\n# test_data = np.load('testdata.npy',allow_pickle=True)\n\nfig=plt.figure()\n\nfor num,data in enumerate(test_data[:1]):\n # cat: [1,0]\n # dog: [0,1]\n \n img_num = data[1]\n img_data = data[0]\n \n y = fig.add_subplot(1,1,num+1)\n orig = img_data\n \n data = img_data.reshape(IMG_SIZE,IMG_SIZE,1)\n model_out = model.predict([data])[0]\n print(model_out)\n print(img_num) \n if np.argmax(model_out) == 1: str_label='Ringworm'\n else: str_label='Psoriasis'\n \n y.imshow(orig,cmap='gray')\n plt.title(\"found \"+str_label+\" in \"+img_num)\n y.axes.get_xaxis().set_visible(False)\n y.axes.get_yaxis().set_visible(False)\n plt.show()\n","sub_path":"clasify.py","file_name":"clasify.py","file_ext":"py","file_size_in_byte":3885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"255424358","text":"from argparse import Action, ArgumentParser\n\nclass DriverAction(Action):\n def __call__(self, parser, namespace, values, option_string=None):\n driver, destination = values\n namespace.driver = driver.lower()\n namespace.destination = destination\n\n def create_parser():\n parser = ArgumentParser(description=\"\"\" back up postgres database locally and maybe to aws s3 if im not lazy\"\"\")\n parser.add_argument(\"url\", help =\"URL of database to backup\")\n parser.add_argument(\"--driver\",\n help = \"how and where to store backup\",\n nargs =2,\n action = DriverAction,\n required = True)\n return parser\n\n","sub_path":"cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"204450846","text":"from django.db.models import F, Sum, Case, When\nfrom django import http\nfrom rest_framework import serializers, viewsets, mixins\n\nfrom core.models import Carrier, Review\n\nclass CarrierSerializer(serializers.HyperlinkedModelSerializer):\n rating = serializers.ReadOnlyField()\n\n class Meta:\n model = Carrier\n fields = ('id', 'name', 'rating')\n\n\nclass CarrierViewSet(mixins.RetrieveModelMixin,\n mixins.ListModelMixin,\n viewsets.GenericViewSet):\n\n def get_queryset(self):\n case = Case(When(\n review__status=Review.APPROVED,\n then=F('review__rating')\n ))\n queryset = Carrier.objects\\\n .annotate(rating=Sum(case))\\\n .order_by('-rating')\n return queryset\n serializer_class = CarrierSerializer\n","sub_path":"api/carrier.py","file_name":"carrier.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"483747724","text":"import json\nimport os\nimport random\nimport bottle\n\nfrom api import ping_response, start_response, move_response, end_response\n\n\n# Moving towards a tail is safe as long as that snake does not have food witihn reach.\n# If it is te only possible move, that move should be made anyway\n\n\n@bottle.route('/')\ndef index():\n return '''\n Battlesnake documentation can be found at\n https://docs.battlesnake.io.\n '''\n\n\n@bottle.route('/static/')\ndef static(path):\n \"\"\"\n Given a path, return the static file located relative\n to the static folder.\n\n This can be used to return the snake head URL in an API response.\n \"\"\"\n return bottle.static_file(path, root='static/')\n\n\n@bottle.post('/ping')\ndef ping():\n \"\"\"\n A keep-alive endpoint used to prevent cloud application platforms,\n such as Heroku, from sleeping the application instance.\n \"\"\"\n return ping_response()\n\n\n@bottle.post('/start')\ndef start():\n data = bottle.request.json\n\n \"\"\"\n TODO: If you intend to have a stateful snake AI,\n initialize your snake state here using the\n request's data if necessary.\n \"\"\"\n print(json.dumps(data))\n\n color = \"#00FF00\"\n\n return start_response(color)\n\n\n@bottle.post('/move')\ndef move():\n data = bottle.request.json\n\n foodposition = []\n\n for food in data['food']['data']:\n foodposition.append((food['x'], food['y']))\n\n my_head = (data['you']['body']['data'][0]['x'], data['you']['body']['data'][0]['y'])\n my_length = len((data['you']['body']['data']))\n\n snakePositions = []\n myPositions = []\n\n for pos in data['you']['body']['data']:\n myPositions.append((pos['x'], pos['y']))\n\n snake_heads = []\n\n for snakes in data['snakes']['data']: ## alla ormar\n x = snakes['body']['data'][0]['x']\n y = snakes['body']['data'][0]['y']\n snake_heads.append((x, y))\n\n for pos in snakes['body']['data']: ## alla ormens positioner\n snakePositions.append((pos['x'], pos['y']))\n\n snake_heads.remove(my_head)\n\n snake_head_area = []\n for snake_head in snake_heads:\n snake_head_area.append((snake_head[0]-1, snake_head[1]))\n snake_head_area.append((snake_head[0]+1, snake_head[1]))\n snake_head_area.append((snake_head[0], snake_head[1]+1))\n snake_head_area.append((snake_head[0], snake_head[1]-1))\n\n walls = []\n width = data['height']\n for i in range(width + 1):\n walls.append((0 - 1, i))\n walls.append((i, 0 - 1))\n walls.append((width, i))\n walls.append((i, width))\n\n stuffToAvoid = []\n\n for position in myPositions:\n stuffToAvoid.append(position)\n\n for position in walls:\n stuffToAvoid.append(position)\n\n for position in snakePositions:\n stuffToAvoid.append(position)\n\n xhead = my_head[0]\n yhead = my_head[1]\n\n possiblemoves = []\n\n if (xhead + 1, yhead) not in stuffToAvoid and safe_path(xhead + 1, yhead, stuffToAvoid):\n possiblemoves.append('right')\n if (xhead, yhead + 1) not in stuffToAvoid and safe_path(xhead, yhead + 1, stuffToAvoid):\n possiblemoves.append('down')\n if (xhead - 1, yhead) not in stuffToAvoid and safe_path(xhead - 1, yhead, stuffToAvoid):\n possiblemoves.append('left')\n if (xhead, yhead - 1) not in stuffToAvoid and safe_path(xhead, yhead - 1, stuffToAvoid):\n possiblemoves.append('up')\n\n ##Find closest food\n currentDist = 1000000\n\n for i in foodposition:\n xfood = i[0]\n yfood = i[1]\n dist = ((abs(xhead - xfood)) + (abs(yhead - yfood)))\n if (dist < currentDist):\n closestFoodPos = (xfood, yfood)\n currentDist = dist\n\n xdistancetofood = abs(xhead - closestFoodPos[0])\n ydistancetofood = abs(yhead - closestFoodPos[1])\n\n # foodtotheright = ((xhead - closestFoodPos[0]) < 0)\n # foodtothetop = ((yhead - closestFoodPos[1]) > 0)\n\n prioritymoves = []\n\n if (xdistancetofood >= ydistancetofood) and ((xhead - closestFoodPos[0]) < 0) and 'right' in possiblemoves:\n prioritymoves.append('right')\n\n if (xdistancetofood >= ydistancetofood) and ((xhead - closestFoodPos[0]) > 0) and 'left' in possiblemoves:\n prioritymoves.append('left')\n\n if (ydistancetofood >= xdistancetofood) and ((yhead - closestFoodPos[1]) > 0) and 'up' in possiblemoves:\n prioritymoves.append('up')\n\n if (ydistancetofood >= xdistancetofood) and ((yhead - closestFoodPos[1]) < 0) and 'down' in possiblemoves:\n prioritymoves.append('down')\n\n if (xhead + 1, yhead) in snake_head_area and 'right' in prioritymoves:\n prioritymoves.remove('right')\n # prioritymoves.append('right')\n\n if (xhead - 1, yhead) in snake_head_area and 'left' in prioritymoves:\n prioritymoves.remove('left')\n # prioritymoves.append('left')\n\n if (xhead, yhead + 1) in snake_head_area and 'down' in prioritymoves:\n prioritymoves.remove('down')\n # prioritymoves.append('down')\n\n if (xhead, yhead - 1) in snake_head_area and 'up' in prioritymoves:\n prioritymoves.remove('up')\n # prioritymoves.append('up')\n\n prioritymoves.append(random.choice(possiblemoves))\n direction = prioritymoves[0]\n\n return move_response(direction)\n\n\n# int x,y or tuple (NEXT STEP)\n\n##Only looks for dead end\ndef safe_path(x, y, stuffToAvoid):\n right = (x + 1, y)\n left = (x - 1, y)\n down = (x, y + 1)\n up = (x, y - 1)\n\n if right in stuffToAvoid and left in stuffToAvoid and down in stuffToAvoid and up in stuffToAvoid:\n safe = False\n else:\n safe = True\n\n return safe\n\n\n##def snake_head_area(snake_heads, my_head):\n## avoid_heads = []\n## snake_heads1 = snake_heads\n## snake_heads1.remove(my_head)\n##\n## for heads in snake_heads1:\n## avoid_heads.append((heads[0]+1, heads[1]))\n## avoid_heads.append((heads[0] - 1, heads[1]))\n## avoid_heads.append((heads[0], heads[1] + 1))\n## avoid_heads.append((heads[0], heads[1] - 1))\n##\n## return avoid_heads\n\n\n# def safetyLevel(x,y, stuffToAvoid):\n\n\n@bottle.post('/end')\ndef end():\n data = bottle.request.json\n\n \"\"\"\n TODO: If your snake AI was stateful,\n clean up any stateful objects here.\n \"\"\"\n print(json.dumps(data))\n\n return end_response()\n\n\n# Expose WSGI app (so gunicorn can find it)\napplication = bottle.default_app()\n\nif __name__ == '__main__':\n bottle.run(\n application,\n host=os.getenv('IP', '0.0.0.0'),\n port=os.getenv('PORT', '8080'),\n debug=os.getenv('DEBUG', True)\n )\n","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"400806588","text":"import csv\nimport Graph\n\n\nroutes = {}\ncity2num = {}\nnum2city = {}\nwith open('../Data/GraphData.csv', newline='', encoding='utf-8-sig') as csvfile:\n\tfilereader = csv.reader(csvfile, delimiter=',')\n\t# Skip the header\n\tnext(filereader)\n\tfor row in filereader:\n\t\t# Count unique city first\n\t\tif row[0] not in city2num:\n\t\t\tlabel = int(len(city2num))\n\t\t\tcity2num[row[0]] = label\n\t\t\tnum2city[label] = row[0]\n\t\tif row[1] not in city2num:\n\t\t\tlabel = int(len(city2num))\n\t\t\tcity2num[row[1]] = label\n\t\t\tnum2city[label] = row[1]\n\n\t\ttemp = (row[1], int(row[2]))\n\t\tif row[0] not in routes:\n\t\t\troutes[row[0]] = [temp]\n\t\telse:\n\t\t\troutes[row[0]].append(temp)\n\nflightroutes = Graph.Graph(len(city2num))\nfor key in routes:\n\tv1 = city2num[key]\n\tpairs = routes[key]\n\tfor pair in pairs:\n\t\tv2 = city2num[pair[0]]\n\t\tw = pair[1]\n\t\tflightroutes.addEdge(v1, v2, w, True)\n\n\"\"\"\nfor key in num2city:\n\ttcost = flightroutes.outDegree(key)\n\tprint(num2city[key],': ',tcost,sep='')\n\nfor key in num2city:\n\ttcost = flightroutes.outCost(key)\n\tprint(num2city[key],': ',tcost,sep='')\n\"\"\"\ntopSortRoutes = flightroutes.topologicalSort()\nfor num in topSortRoutes:\n\tprint(num2city[num])\n\nflightroutes.dijkstra(0)\n","sub_path":"Graphs/Python/GraphDistanceDriver.py","file_name":"GraphDistanceDriver.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"95578982","text":"import flask as f\nimport flask_login\n\nfrom ..api import rule\nfrom ..api._endpoint import ApiEndpoint, maybe_login_required\nfrom ..entities._entity import NotFound\nfrom ..entities.commit import Commit\nfrom ..entities.run import Run, RunSerializer\nfrom ..entities.summary import Summary\n\n\nclass RunEntityAPI(ApiEndpoint):\n serializer = RunSerializer()\n\n def _get(self, run_id):\n try:\n run = Run.one(id=run_id)\n except NotFound:\n self.abort_404_not_found()\n return run\n\n @maybe_login_required\n def get(self, run_id):\n \"\"\"\n ---\n description: Get a run.\n responses:\n \"200\": \"RunEntity\"\n \"401\": \"401\"\n \"404\": \"404\"\n parameters:\n - name: run_id\n in: path\n schema:\n type: string\n tags:\n - Runs\n \"\"\"\n run = self._get(run_id)\n return self.serializer.one.dump(run)\n\n @flask_login.login_required\n def delete(self, run_id):\n \"\"\"\n ---\n description: Delete a run.\n responses:\n \"204\": \"204\"\n \"401\": \"401\"\n \"404\": \"404\"\n parameters:\n - name: run_id\n in: path\n schema:\n type: string\n tags:\n - Runs\n \"\"\"\n summaries = Summary.all(run_id=run_id)\n for summarie in summaries:\n summarie.delete()\n run = self._get(run_id)\n run.delete()\n return self.response_204_no_content()\n\n\nclass RunListAPI(ApiEndpoint):\n serializer = RunSerializer()\n\n @maybe_login_required\n def get(self):\n \"\"\"\n ---\n description: Get a list of runs.\n responses:\n \"200\": \"RunList\"\n \"401\": \"401\"\n parameters:\n - in: query\n name: sha\n schema:\n type: string\n tags:\n - Runs\n \"\"\"\n sha = f.request.args.get(\"sha\")\n if sha:\n runs = Run.search(filters=[Commit.sha == sha], joins=[Commit])\n else:\n runs = Run.all(order_by=Run.timestamp.desc(), limit=500)\n return self.serializer.many.dump(runs)\n\n\nrun_entity_view = RunEntityAPI.as_view(\"run\")\nrun_list_view = RunListAPI.as_view(\"runs\")\n\nrule(\n \"/runs/\",\n view_func=run_list_view,\n methods=[\"GET\"],\n)\nrule(\n \"/runs//\",\n view_func=run_entity_view,\n methods=[\"GET\", \"DELETE\"],\n)\n","sub_path":"conbench/api/runs.py","file_name":"runs.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"418324780","text":"DAY = '7'\nPUZ = 'b'\n# Unfinished and incorrect\ninfile_name = \"./dat/day\" + DAY + \"-\" + 'a' + \"-in.dat\"\noutfile_name = \"./res/day\" + DAY + \"-\" + PUZ + \"-out.dat\"\n\ninfile = open(infile_name, 'r')\n#BEGIN:\n\n# I think part 1 can be solved by finding the one name only mentioned\n# once, but I doubt part 2 can so I'm going to build the tree\n\nclass Node:\n\tname = \"\"\n\tweight = -1\n\tchildren = []\n\tparent = None\n\ntree = {}\t\t # store nodes\nid_for_node = {} # returns id for node name\nparent_for_node = {} # returns parent node\n\n#Build tree\nfor line in infile:\n\t# Load node name and weight, save to object\n\tline = line[:-1]\n\traw_node = line.split(\" \")\n\tnode = Node()\n\tnode.name = raw_node[0]\n\tnode.weight = int(str(raw_node[1])[1:-1])\n\t# Has this node been mentioned? If so, find its parent\n\tif node.name in id_for_node:\n\t\tparent_id = parent_for_node[str(node.name)]\n\t\tnode.parent = tree[parent_id] # get parent\n\t\tnode.parent.children.append(node) \t# record this as child\n\t# Otherwise, save its ID\n\tid_for_node[node.name] = id(node) # save reference to name dict\n\ttree[id(node)] = node # save object to tree\n\t# Check if it has children and record their mention\n\tif len(raw_node) > 2: # this means it has -> children\n\t\tfor x in range(3, len(raw_node)): # for each child\n\t\t\traw_node[x] = str(raw_node[x]).replace(\",\", \"\") # trim commas\n\t\t\tif raw_node[x] in id_for_node:\n\t\t\t\tchild = tree[id_for_node[str(raw_node[x])]]\n\t\t\t\tchild.parent = node\n\t\t\telse:\n\t\t\t\tid_for_node[raw_node[x]] = -1 # record -1 because they have no id\n\t\t\tparent_for_node[str(raw_node[x])] = id(node)\n\troot_node = node\n\ninfile.close()\n#Check up tree\nwhile root_node.parent != None:\n\troot_node = root_node.parent\n\n\n\nprint(result)\noutfile = open(outfile_name, 'w')\noutfile.write(str(result))\noutfile.close()","sub_path":"src/day7-b.py","file_name":"day7-b.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"96656822","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function, unicode_literals\nimport json\nimport re\n\nGROWTH_RATES = {\n 'Slow': 'slow',\n 'MediumFast': 'medium',\n 'Fast': 'fast',\n 'MediumSlow': 'medium-slow',\n 'Erratic': 'slow-then-very-fast',\n 'Fluctuating': 'fast-then-very-slow',\n}\n\nPSEUDOFORMS = [\n 421,\n 422,\n 423,\n 649,\n 716,\n 773,\n 854,\n 855,\n]\n\nDEX_REGEX = re.compile(r'^(\\d+) - \\[(\\d+)\\]')\n\ndef make_identifier(name):\n \"\"\"Make a string safe to use as an identifier.\n\n Valid characters are lowercase alphanumerics and \"-\". This function may\n raise ValueError if it can't come up with a suitable identifier.\n\n This function is useful for scripts which add things with names.\n \"\"\"\n if isinstance(name, bytes):\n identifier = name.decode('utf-8')\n else:\n identifier = name\n identifier = identifier.lower()\n identifier = identifier.replace(u'+', u' plus ')\n identifier = re.sub(u'[ _–]+', u'-', identifier)\n identifier = re.sub(u\"['./;’(),:]\", u'', identifier)\n identifier = identifier.replace(u'é', u'e')\n identifier = identifier.replace(u'\\u2640', '-f')\n identifier = identifier.replace(u'\\u2642', '-m')\n\n if identifier.startswith('route-'):\n identifier = 'galar-' + identifier\n\n if not identifier.replace(u\"-\", u\"\").isalnum():\n raise ValueError(identifier)\n return identifier\n\ndata = json.load(open('C:\\\\Users\\\\antialiasis\\\\Documents\\\\TCoD\\\\Flask\\\\tcod\\\\tcod\\\\data-files\\\\pokemon.json'))\nforms_data = json.load(open(r'C:\\\\Users\\\\antialiasis\\\\Documents\\\\TCoD\\\\Flask\\\\tcod\\\\scripts\\\\data-files\\\\forms.json'))\narmor_dex_file = open('C:\\\\Users\\\\antialiasis\\\\Documents\\\\TCoD\\\\Flask\\\\tcod\\\\tcod\\\\data-files\\\\armor-dex.txt')\ntundra_dex_file = open('C:\\\\Users\\\\antialiasis\\\\Documents\\\\TCoD\\\\Flask\\\\tcod\\\\tcod\\\\data-files\\\\tundra-dex.txt')\n\narmor_dex = {}\nfor line in armor_dex_file:\n match = DEX_REGEX.match(line)\n if not match:\n raise ValueError(\"Malformatted armor dex line!\", line)\n armor_dex[int(match.group(2))] = int(match.group(1))\n\ntundra_dex = {}\nfor line in tundra_dex_file:\n match = DEX_REGEX.match(line)\n if not match:\n raise ValueError(\"Malformatted armor dex line!\", line)\n tundra_dex[int(match.group(2))] = int(match.group(1))\n\nregion = \"Galar\"\nregion_ident = make_identifier(region)\nfirst_form_id = 901\n\nprint(\"BEGIN;\")\nprint(\"INSERT INTO regions (id, identifier) VALUES (8, '%s') ON CONFLICT DO NOTHING;\" % region_ident)\nprint(\"INSERT INTO region_names (region_id, local_language_id, name) SELECT id, 9, '%s' FROM regions WHERE identifier = '%s' ON CONFLICT DO NOTHING;\" % (region, region_ident))\nprint(\"INSERT INTO pokedexes (id, region_id, identifier, is_main_series) SELECT 26, id, '%s', true FROM regions WHERE identifier = '%s' ON CONFLICT DO NOTHING;\" % (region_ident, region_ident))\nprint(\"INSERT INTO pokedexes (id, region_id, identifier, is_main_series) SELECT 27, id, '%s', true FROM regions WHERE identifier = '%s' ON CONFLICT DO NOTHING;\" % ('isle-of-armor', region_ident))\nprint(\"INSERT INTO pokedexes (id, region_id, identifier, is_main_series) SELECT 28, id, '%s', true FROM regions WHERE identifier = '%s' ON CONFLICT DO NOTHING;\" % ('crown-tundra', region_ident))\nprint(\"INSERT INTO generations (id, main_region_id, identifier) SELECT 8, id, '%s' FROM regions WHERE identifier = '%s' ON CONFLICT DO NOTHING;\" % ('generation-viii', region_ident))\nprint(\"INSERT INTO version_groups (id, identifier, generation_id, \\\"order\\\") VALUES (19, 'lets-go', 7, 19) ON CONFLICT DO NOTHING;\")\nprint(\"INSERT INTO version_groups (id, identifier, generation_id, \\\"order\\\") VALUES (20, 'sword-shield', 8, 20) ON CONFLICT DO NOTHING;\")\n\nevolution_map = {}\nname_map = {}\n\nfor pokemon in data:\n species_id = None\n if pokemon['id'] < first_form_id:\n # Not a form\n name_map[pokemon['name']] = pokemon\n species_id = pokemon['id']\n else:\n species_id = name_map[pokemon['name'].rsplit(' ', 1)[0]]['id']\n if pokemon['evolutions']:\n for evolution in pokemon['evolutions']:\n if re.search(r'-\\d+$', evolution['species']) is not None:\n evolution_map[evolution['species'].rsplit('-', 1)[0]] = species_id\n else:\n evolution_map[evolution['species']] = species_id\n\npokemon_order = 956\n\nfor pokemon in data:\n pokemon_ident = None\n pokemon_form_ident = None\n form_ident = None\n species = None\n form_num = 0\n if pokemon['id'] < first_form_id:\n pokemon_ident = make_identifier(pokemon['name'])\n pokemon_form_ident = pokemon_ident\n species = pokemon\n if pokemon['name'] not in evolution_map and False:\n print(\"INSERT INTO evolution_chains (id) SELECT MAX(id) + 1 FROM evolution_chains;\")\n print(\"INSERT INTO pokemon_species (id, identifier, generation_id, evolves_from_species_id, evolution_chain_id, color_id, shape_id, habitat_id, gender_rate, capture_rate, base_happiness, is_baby, hatch_counter, has_gender_differences, growth_rate_id, forms_switchable, is_legendary, is_mythical, \\\"order\\\") SELECT %s, '%s', %s, %s, %s, %s, 1, NULL, -1, %s, 70, false, %s, false, %s, false, %s, %s, %s ON CONFLICT (id) DO UPDATE SET capture_rate = excluded.capture_rate;\" % (\n pokemon['id'],\n pokemon_ident,\n 7 if pokemon_ident in ('meltan', 'melmetal') else 8,\n evolution_map[pokemon['name']] if pokemon['name'] in evolution_map else 'NULL',\n ('(SELECT evolution_chain_id FROM pokemon_species WHERE id = \\'%s\\')' % evolution_map[pokemon['name']]) if pokemon['name'] in evolution_map else '(SELECT MAX(evolution_chain_id) + 1 FROM pokemon_species)',\n '(SELECT id FROM pokemon_colors WHERE identifier = \\'%s\\')' % pokemon['color'].lower(),\n pokemon['catch_rate'],\n pokemon['hatch_cycles'],\n '(SELECT id FROM growth_rates WHERE identifier = \\'%s\\')' % GROWTH_RATES[pokemon['exp_group']],\n \"true\" if pokemon_ident in ('zacian', 'zamazenta', 'eternatus', 'kubfu', 'urshifu', 'regieleki', 'regidrago', 'glastrier', 'spectrier', 'calyrex') else \"false\",\n \"true\" if pokemon_ident in ('zarude',) else \"false\",\n pokemon['id']\n ))\n\n print(\"INSERT INTO pokemon_species_names (pokemon_species_id, local_language_id, name, genus) VALUES (%s, 9, E'%s', '') ON CONFLICT DO NOTHING;\" % (\n pokemon['id'],\n pokemon['name'].encode('unicode-escape')\n ))\n\n print(\"INSERT INTO pokemon_dex_numbers (species_id, pokedex_id, pokedex_number) VALUES (%s, 1, %s) ON CONFLICT DO NOTHING;\" % (pokemon['id'], pokemon['id']))\n if pokemon['galar_dex'] and pokemon['galar_dex'] != \"foreign\":\n print(\"INSERT INTO pokemon_dex_numbers (species_id, pokedex_id, pokedex_number) VALUES (%s, 26, %s) ON CONFLICT DO NOTHING;\" % (pokemon['id'], pokemon['galar_dex']))\n if pokemon['id'] in armor_dex:\n print(\"INSERT INTO pokemon_dex_numbers (species_id, pokedex_id, pokedex_number) VALUES (%s, 27, %s) ON CONFLICT DO NOTHING;\" % (pokemon['id'], armor_dex[pokemon['id']]))\n if pokemon['id'] in tundra_dex:\n print(\"INSERT INTO pokemon_dex_numbers (species_id, pokedex_id, pokedex_number) VALUES (%s, 28, %s) ON CONFLICT DO NOTHING;\" % (pokemon['id'], tundra_dex[pokemon['id']]))\n\n else:\n name, form_num = pokemon['name'].rsplit(' ', 1)\n species = name_map[name]\n pokemon_ident = make_identifier(name)\n pokemon_form_ident = pokemon_ident\n\n if str(species['id']) in forms_data:\n form_ident = forms_data[str(species['id'])][int(form_num)]\n if form_ident:\n if form_ident == 'dusk-mane':\n form_ident = 'dusk'\n elif form_ident == 'dawn-wings':\n form_ident = 'dawn'\n elif form_ident.endswith('-core'):\n form_ident = form_ident[:-5]\n elif form_ident == 'original-color':\n form_ident = 'original'\n elif form_ident == '50-percent':\n form_ident = '50'\n elif form_ident == '10-percent':\n form_ident = '10'\n pokemon_form_ident += '-' + form_ident\n\n pokemon_order += 1\n # print(\"SELECT '%s', '%s', '%s';\" % (pokemon_ident, pokemon['id'], species['id']))\n print(\"INSERT INTO pokemon (id, identifier, species_id, height, weight, base_experience, \\\"order\\\", is_default) VALUES (%s, '%s', %s, %s, %s, 65, %s, %s) ON CONFLICT DO NOTHING;\" % (\n pokemon['id'] if pokemon['id'] < first_form_id else (\"COALESCE((SELECT id FROM pokemon WHERE identifier = '%s'), (SELECT MAX(id) + 1 FROM pokemon))\" % (pokemon_ident if species['id'] in PSEUDOFORMS else pokemon_form_ident)),\n pokemon_ident if species['id'] in PSEUDOFORMS else pokemon_form_ident,\n species['id'],\n int(pokemon['height'] * 10),\n int(pokemon['weight'] * 10),\n pokemon_order,\n \"true\" if pokemon['id'] < first_form_id else \"false\"\n ))\n\n for i, t in enumerate(pokemon['types']):\n print(\"INSERT INTO pokemon_types (pokemon_id, type_id, slot) SELECT %s, id, %s FROM types WHERE identifier = '%s' ON CONFLICT DO NOTHING;\" % (\n \"(SELECT id FROM pokemon WHERE identifier = '%s')\" % (pokemon_ident if species['id'] in PSEUDOFORMS else pokemon_form_ident),\n i + 1,\n make_identifier(t)\n ))\n\n for i, stat in enumerate(pokemon['base_stats']):\n print(\"INSERT INTO pokemon_stats (pokemon_id, stat_id, base_stat, effort) VALUES (%s, %s, %s, %s) ON CONFLICT DO NOTHING;\" % (\n \"(SELECT id FROM pokemon WHERE identifier = '%s')\" % (pokemon_ident if species['id'] in PSEUDOFORMS else pokemon_form_ident),\n i + 1,\n stat,\n pokemon['ev_yield'][i]\n ))\n\n print(\"INSERT INTO pokemon_forms (id, identifier, form_identifier, pokemon_id, introduced_in_version_group_id, is_default, is_battle_only, is_mega, form_order, \\\"order\\\") VALUES (%s, '%s', %s, %s, %s, true, false, false, 1, (SELECT MAX(\\\"order\\\") + 1 FROM pokemon_forms)) ON CONFLICT DO NOTHING;\" % (\n pokemon['id'] if pokemon['id'] < first_form_id else (\"(COALESCE((SELECT id FROM pokemon_forms WHERE identifier = '%s'), (SELECT MAX(id) + 1 FROM pokemon_forms)))\" % pokemon_form_ident),\n pokemon_form_ident,\n form_ident and (\"'%s'\" % form_ident) or 'NULL',\n \"(SELECT id FROM pokemon WHERE identifier = '%s')\" % (pokemon_ident if species['id'] in PSEUDOFORMS else pokemon_form_ident),\n 19 if pokemon_ident in ('meltan', 'melmetal') else 20\n ))\n\n if pokemon['id'] > 893:\n form_name = (\"E'%s %s'\" % (' '.join((word.capitalize() if word != 'galar' else 'Galarian') for word in form_ident.split('-')), species['name'])).encode('unicode-escape') if form_ident else 'NULL'\n\n print(\"INSERT INTO pokemon_form_names (pokemon_form_id, local_language_id, form_name, pokemon_name) VALUES (%s, 9, %s, %s) ON CONFLICT DO NOTHING;\" % (\n pokemon['id'] if pokemon['id'] < first_form_id else (\"(SELECT id FROM pokemon_forms WHERE identifier = '%s')\" % pokemon_form_ident),\n form_name,\n form_name\n ))\n\nprint(\"COMMIT;\")\n","sub_path":"scripts/add-swsh-pokemon.py","file_name":"add-swsh-pokemon.py","file_ext":"py","file_size_in_byte":11245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"272693694","text":"import json\r\nimport os\r\nimport shutil\r\nimport json\r\n\r\ndef parse():\r\n personId = 1\r\n\r\n with open('./ImageSet3/thermal_annotations.json', 'r') as f:\r\n annotated = json.load(f)\r\n \r\n images = annotated['images']\r\n categories = annotated['categories']\r\n annotations = annotated['annotations']\r\n images = annotated['images']\r\n imagesWithHumans = []\r\n fullresult = []\r\n for anno in annotations:\r\n if anno['category_id'] == 1:\r\n result = {}\r\n imageId = anno['image_id']\r\n for image in images:\r\n if image['id'] == imageId:\r\n res = [ sub['fileName'] for sub in fullresult ]\r\n if image['file_name'] in res: \r\n row = next(item for item in fullresult if item[\"fileName\"] == image['file_name'])\r\n # row['bbox'] = [anno['bbox'],row['bbox']]\r\n row['bbox'].append(anno['bbox'])\r\n else:\r\n result['bbox']=[anno['bbox']]\r\n result['category_id']=1\r\n result['fileName']=image['file_name']\r\n fullresult.append(result) \r\n imagesWithHumans.append(image['file_name']) \r\n \r\n # print(imagesWithHumans)\r\n if not os.path.exists('./labels'):\r\n os.mkdir('./labels')\r\n for result in fullresult:\r\n if len(result) > 0:\r\n filename = result['fileName'].replace('thermal_8_bit','').replace('.jpeg','.json')\r\n with open('./labels'+filename, \"w+\") as outfile: \r\n json.dump(result, outfile) \r\n if not os.path.exists('./human_images'):\r\n os.mkdir('./human_images')\r\n for i in imagesWithHumans:\r\n shutil.copy('./ImageSet3/'+i,'./human_images') \r\n \r\nif __name__ == \"__main__\":\r\n parse()\r\n","sub_path":"Project_Stage_Final/Python Code/parseJson.py","file_name":"parseJson.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"559977586","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed May 29 09:18:51 2019\r\n\r\n@author: user\r\n\"\"\"\r\n\r\n# What is ORM?\r\n# Object Relational Mapping \r\n# Technique for storing, retrieving, updating and\r\n# deleting in a relational database from an\r\n# object oriented program\r\n# There is a data layer that manages \r\n# the translation between the 2 concepts\r\n# a library of classes and functions SQL alchemy\r\n# is one such guy\r\n# problems - inheritance , polymorphism\r\n# rich class mapping are all issues\r\n# each object roughly maps to a row\r\n# Data layer - CRUD - saving\r\n# pass an object to the data layer and\r\n# that would insert a row\r\n# Read\r\n# when you select rows each row should get\r\n# created as objects with constructors et al.\r\n# Handling forieign keys and relationships become important\r\nfrom sqlalchemy import Column,Integer, String, create_engine, exc, orm\r\nfrom sqlalchemy.ext.declarative import declarative_base\r\nfrom sqlalchemy.orm import sessionmaker\r\n# The engine in sql alchemy is the DB-API interface roughly for connnecting to \r\n# a database - this of it as the connection-- object\r\nengine=create_engine(\"sqlite:///emp.db\")\r\n# Think of a session maker as a holding zone(buffer) for a connection that you make\r\n# This class sessionmaker is now ready to execute transactions after binding it\r\n# but will enter a transaction state i.e begin transaction for commits and rollback only when\r\n# a query is executed as in session.query()\r\nsession= sessionmaker(bind=engine)()\r\n# you can do session.commit() and session.rollback() after query execution\r\n# Now what is this declaritive base\r\n# This is the mapping of a table name to an object\r\nBase=declarative_base()\r\n# provides a bunch of table definitions from sqlite \r\n# I define a class called user and say that it inherits properties from base\r\n# __tablename__ refers to the table that I am mapping this class to and and \r\n# the mapping columns to the columns of the class\r\n\r\nclass User(Base):\r\n __tablename__=\"rand\"\r\n pk=Column(Integer, primary_key=True)\r\n n=Column(Integer)\r\n \r\n def __init__(self,pk,n):\r\n self.pk= pk\r\n self.n= n\r\nuser = User(84,10)\r\n# This represents one instance of the class that is mapped to a row in \r\n# the database\r\nsession.add(user)\r\nsession.commit()\r\n# session has a built in function called query\r\n#I can construct a class mapped to a table\r\n# pass that class to the session\r\n# and query it for returning objects\r\nresult=[r.pk for r in session.query(User).all()]\r\n\r\n\r\n# Please read this code and tell me what filter does\r\n# Please state the parameter of filter\r\n\"\"\" def update_state(chat_id, state):\r\n try:\r\n value = Users.query.filter(Users.chat_id == str(chat_id)).first()\r\n value.state = str(state)\r\n db.session.flush()\r\n db.session.commit()\r\n #db.session.close()\r\n except:\r\n print('Error in def update_state')\r\nOnce you have a set of valid objects retrieved you can commit\r\nupdate is just changing values \r\nand delete is thru the delete\r\nRead the code of d3p8 for a greater understanding of this. \r\nFocus on the update and delete functions\r\n\"\"\"\r\n\r\n\r\n","sub_path":"day3/d3p7.py","file_name":"d3p7.py","file_ext":"py","file_size_in_byte":3110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"469324512","text":"from sympy import *\nfrom sympy.abc import t, n\n\ndef main():\n a0 = integrate(2 / pi, (t, -pi / 2, pi / 2))\n print(\"a0 = \")\n pprint(a0)\n\n an = integrate((2 / pi) * cos(n * t), (t, -pi / 2, pi / 2))\n print(\"an = \")\n pprint(an)\n\n bn = together(integrate((2 / pi) * sin(n * t), (t, -pi / 2, pi / 2)))\n print(\"bn = \")\n pprint(bn)\n\n print(\"f(x) = \")\n armonicos = 10\n serie = (a0/2) + 1\n for i in range(1, armonicos + 1):\n serie = serie + (an * cos(n*(t - pi/4))).subs(n, i)\n for j in range(1, armonicos + 1):\n serie = serie + (bn * sin(n*(t - pi/4))).subs(n, j)\n pprint(serie)\n\n plotting.plot(serie, ylim=(-3, 5), xlim=(-10, 10))\n\n \n\nif __name__ == \"__main__\":\n main()","sub_path":"series de Fourier/fourier3.py","file_name":"fourier3.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"600493537","text":"\n# coding: utf-8\n\n# # Face Detection In Python Using OpenCV\n\nimport numpy as np\nimport cv2\nimport time\nimport sys\n\n\ndef detect_faces(f_cascade, colored_img, scaleFactor = 1.1):\n img_copy = np.copy(colored_img)\n gray = cv2.cvtColor(img_copy, cv2.COLOR_BGR2GRAY)\n \n faces = f_cascade.detectMultiScale(gray, scaleFactor=scaleFactor, minNeighbors=5);\n \n for (x, y, w, h) in faces:\n cv2.rectangle(img_copy, (x, y), (x+w, y+h), (0, 255, 0), 2)\n \n return img_copy\n\n# XML training files for Haar cascade are stored in `opencv/data/haarcascades/` folder.\n\nhaar_face_cascade = cv2.CascadeClassifier('data/haarcascade_frontalface_alt.xml')\nlbp_face_cascade = cv2.CascadeClassifier('data/lbpcascade_frontalface.xml')\n\ntest = cv2.imread(sys.argv[1])\nfaces_detected_img = detect_faces(lbp_face_cascade, test)\ncv2.imshow('Faces Image', faces_detected_img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n","sub_path":"Face/Face-Detection-LBP.py","file_name":"Face-Detection-LBP.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"58114303","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nZurich Instruments LabOne Python API Example.\r\n\r\nDemonstrate how to connect to a Zurich Instruments Device and obtain streaming\r\nscope data from one or two scope channels.\r\n\"\"\"\r\n\r\n# Copyright 2018 Zurich Instruments AG\r\n\r\nfrom __future__ import print_function\r\nimport time\r\nimport warnings\r\nimport numpy as np\r\nimport zhinst.utils\r\n\r\n\r\ndef run_example(device_id, do_plot=False, scope_stream_rate=12, scope_inputselects=[16, 32]):\r\n \"\"\"\r\n Run the example: Connect to a Zurich Instruments Device via the Data Server,\r\n generate a constant signal on the auxillary outputs and demodulate it in\r\n order to observe a sine wave in the demodulator X and Y output. Acquire the\r\n demodulator X and Y output on the scope's streaming channels using subscribe\r\n and poll (the Scope Module does not support the scopes's streaming\r\n nodes). Obtains a fixed number of scope samples (defined below as\r\n num_scope_samples).\r\n\r\n Requirements:\r\n\r\n MF or UHF Instrument with DIG Option (HF2 does not support scope\r\n streaming).\r\n\r\n Arguments:\r\n\r\n device_id (str): The ID of the device to run the example with. For\r\n example, `dev2006` or `uhf-dev2006`.\r\n\r\n do_plot (bool, optional): Specify whether to plot the acquired\r\n data. Default is no plot output. Plotting requires the matplotlib\r\n module.\r\n\r\n scope_stream_rate: The rate of the scope streaming data, the data will be\r\n set at a rate of clockbase/2**rate. For example:\r\n 8 - sets the sampling rate to 7.03 MHz\r\n 9 - \" 3.50 MHz\r\n ...\r\n 16 - \" 27.5 kHz\r\n\r\n scope_inputselect (list of int, optional): A list containing one or two\r\n input signals to measure with the scope\r\n (/dev..../scopes/0/channels/{0,1}/inputselect). For example, [16,\r\n 32]. Example values (see the User Manual for more info):\r\n 0 - signal input 0,\r\n 1 - signal input 1,\r\n 2 - signal output 0,\r\n 3 - signal output 1,\r\n 16 - demod 0 X,\r\n 32 - demod 0 Y.\r\n\r\n Returns:\r\n\r\n data (dict of numpy arrays): The last dictionary as returned by poll.\r\n\r\n scope_samples(list of dict): A list of dictionaries. Each entry in the is\r\n a dictionary with the keys timestamp and value holding the data obtained\r\n for one scope channel.\r\n\r\n Raises:\r\n\r\n Exception: If the specified device is not an MF or UHF with the DIG\r\n Option.\r\n\r\n RuntimeError: If the device is not \"discoverable\" from the API.\r\n\r\n See the \"LabOne Programing Manual\" for further help, available:\r\n - On Windows via the Start-Menu:\r\n Programs -> Zurich Instruments -> Documentation\r\n - On Linux in the LabOne .tar.gz archive in the \"Documentation\"\r\n sub-folder.\r\n \"\"\"\r\n\r\n apilevel_example = 6 # The API level supported by this example.\r\n # Call a zhinst utility function that returns:\r\n # - an API session `daq` in order to communicate with devices via the data server.\r\n # - the device ID string that specifies the device branch in the server's node hierarchy.\r\n # - the device's discovery properties.\r\n # This example can't run with HF2 Instruments or instruments without the DIG option.\r\n required_devtype = r'UHFLI|MF' # Regular expression of supported instruments.\r\n required_options = ['DIG']\r\n required_err_msg = \"This example requires the DIG Option on either UHFLI or MF instruments (HF2 is unsupported).\"\r\n (daq, device, _) = zhinst.utils.create_api_session(device_id, apilevel_example,\r\n required_devtype=required_devtype,\r\n required_options=required_options,\r\n required_err_msg=required_err_msg)\r\n zhinst.utils.api_server_version_check(daq)\r\n\r\n # Enable the API's log.\r\n daq.setDebugLevel(0)\r\n\r\n # Create a base configuration: Disable all available outputs, awgs, demods, scopes,...\r\n zhinst.utils.disable_everything(daq, device)\r\n\r\n # The value of the instrument's ADC sampling rate.\r\n clockbase = daq.getInt('/{}/clockbase'.format(device))\r\n rate = clockbase/2**scope_stream_rate\r\n\r\n # Now configure the instrument for this experiment.\r\n auxout_channel = 0\r\n demod_channel = 0\r\n osc_index = 0\r\n num_samples_period = 16\r\n frequency = rate/num_samples_period\r\n exp_setting = [\r\n ['/%s/auxouts/%d/outputselect' % (device, auxout_channel), -1], # Auxout manual mode.\r\n ['/%s/auxouts/%d/offset' % (device, auxout_channel), 1],\r\n ['/%s/auxouts/%d/limitlower' % (device, auxout_channel), -10],\r\n ['/%s/auxouts/%d/limitupper' % (device, auxout_channel), 10],\r\n ['/%s/oscs/%d/freq' % (device, osc_index), frequency]]\r\n node_branches = daq.listNodes('/{}/'.format(device), 0)\r\n if 'DEMODS' in node_branches:\r\n # NOTE we don't need to obtain any demodulator data directly from the\r\n # DEMODS branch for this example (it is obtained directly by the scope\r\n # within the device using a feedback channel in the firmware), but we\r\n # need to configure the demodulator input and the frequency of the\r\n # output signal on out_mixer_c.\r\n exp_setting.append(['/%s/demods/%d/timeconstant' % (device, demod_channel), 0.])\r\n exp_setting.append(['/%s/demods/%d/oscselect' % (device, demod_channel), osc_index])\r\n # ADCSELECT: Specify which source signal the demodulator should use as its input.\r\n exp_setting.append(['/%s/demods/%d/adcselect' % (device, demod_channel), auxout_channel + 4])\r\n daq.set(exp_setting)\r\n\r\n # Perform a global synchronisation between the device and the data server:\r\n # Ensure that the signal input and output configuration has taken effect\r\n # before calculating the signal input autorange.\r\n daq.sync()\r\n\r\n ####################################################################################################################\r\n # Configure the scope's channels and streaming nodes.\r\n # Note: Nodes not listed below not effect the scope streaming data, e.g. (scopes/0/{time,length,trig*,...}).\r\n ####################################################################################################################\r\n #\r\n # 'channels/0/bwlimit' : bandwidth limit the scope data. Enabling bandwidth\r\n # limiting avoids antialiasing effects due to subsampling when the scope\r\n # sample rate is less than the input channel's sample rate.\r\n # Bool:\r\n # 0 - do not bandwidth limit\r\n # 1 - bandwidth limit\r\n daq.setInt('/%s/scopes/0/channels/*/bwlimit' % device, 1)\r\n # 'channel/0/channels/*/inputselect' : the input channel for the scope:\r\n # 0 - signal input 1\r\n # 1 - signal input 2\r\n # 2, 3 - trigger 1, 2 (front)\r\n # 8-9 - auxiliary inputs 1-2\r\n # The following inputs are additionally available with the DIG option:\r\n # 10-11 - oscillator phase from demodulator 3-7\r\n # 16-23 - demodulator 0-7 x value\r\n # 32-39 - demodulator 0-7 y value\r\n # 48-55 - demodulator 0-7 R value\r\n # 64-71 - demodulator 0-7 Phi value\r\n # 80-83 - pid 0-3 out value\r\n # 96-97 - boxcar 0-1\r\n # 112-113 - cartesian arithmetic unit 0-1\r\n # 128-129 - polar arithmetic unit 0-1\r\n # 144-147 - pid 0-3 shift value\r\n # Here, we specify the demod 0 X and y values for channels 1 and 2, respectively.\r\n daq.setInt('/%s/scopes/0/channels/0/inputselect' % device, scope_inputselects[0])\r\n if len(scope_inputselects) > 1:\r\n daq.setInt('/%s/scopes/0/channels/1/inputselect' % device, scope_inputselects[1])\r\n # 'channels/0/channels/*/limit{lower,upper}\r\n # Set the scope limits for the data to values far outside legal values\r\n # allowed by the firmware; the firmware will clamp to the smallest/largest\r\n # value of the legal lower/upper limits.\r\n #\r\n # NOTE: In order to obtain the best possible bit resolution in the scope,\r\n # these values should be set according to the magnitude of the signals being\r\n # measured in the scope.\r\n daq.setDouble('/%s/scopes/0/channels/*/limitlower' % device, -10e9)\r\n daq.setDouble('/%s/scopes/0/channels/*/limitupper' % device, 10e9)\r\n # 'stream/rate' : specifies the rate of the streaming data, the data will be set at a rate of clockbase/2**rate.\r\n # 7 - sets the samplint rate to 14.06 MHz (maximum rate supported by 1GbE)\r\n # 8 - 7.03 MHz (maximum rate supported by USB)\r\n # 9 - \" 3.50 MHz\r\n # ...\r\n # 16 - \" 27.5 kHz\r\n daq.setDouble('/%s/scopes/0/stream/rate' % device, scope_stream_rate)\r\n\r\n # Perform a global synchronisation between the device and the data server: Ensure that the settings have taken\r\n # effect on the device before enabling streaming and acquiring data.\r\n daq.sync()\r\n\r\n # Enable the scope streaming nodes:\r\n daq.setInt('/%s/scopes/0/stream/enables/0' % device, 1)\r\n if len(scope_inputselects) > 1:\r\n daq.setInt('/%s/scopes/0/stream/enables/1' % device, 1)\r\n\r\n # Ensure buffers are flushed before subscribing.\r\n daq.sync()\r\n\r\n # Subscribe to the scope's streaming samples in the ziDAQServer session.\r\n stream_nodepath = '/{}/scopes/0/stream/sample'.format(device)\r\n daq.subscribe(stream_nodepath)\r\n\r\n # We will construct arrays of the scope streaming samples and their timestamps.\r\n num_scope_samples = int(1e5) # Critical parameter for memory consumption.\r\n # Preallocate arrays.\r\n scope_samples = [{'value': np.nan*np.ones(num_scope_samples), 'timestamp': np.zeros(num_scope_samples, dtype=int)},\r\n {'value': np.nan*np.ones(num_scope_samples), 'timestamp': np.zeros(num_scope_samples, dtype=int)}]\r\n\r\n n = 0 # The number of scope samples acquired on each channel.\r\n num_blocks = 0 # Just for statistics.\r\n poll_count = 0\r\n timeout = 60\r\n t_start = time.time()\r\n while n < num_scope_samples:\r\n if time.time() - t_start > timeout:\r\n raise Exception(\"Failed to acquired %d scope samples after %f s. Num samples acquired\")\r\n data = daq.poll(0.02, 200, 0, True)\r\n poll_count += 1\r\n if stream_nodepath not in data:\r\n # Could be the case for very slow streaming rates and fast poll frequencies.\r\n print(\"Poll did not return any subscribed data.\")\r\n continue\r\n num_blocks_poll = len(data[stream_nodepath])\r\n num_blocks += num_blocks_poll\r\n print(\"Poll #\", poll_count, \" returned \", num_blocks_poll, \" blocks of streamed scope data\",\r\n \"blocks processed \", num_blocks, \", samples acquired \", n, \".\", sep=\"\", end='\\r')\r\n for b, block in enumerate(data[stream_nodepath]):\r\n if block['flags'] & 1:\r\n message = \"Block {} from poll indicates dataloss (flags: {})\".format(b, block['flags'])\r\n warnings.warn(message)\r\n continue\r\n if block['flags'] & 2:\r\n # This should not happen.\r\n message = \"Block {} from poll indicates missed trigger (flags: {})\".format(b, block['flags'])\r\n warnings.warn(message)\r\n continue\r\n if block['flags'] & 3:\r\n message = \"Block {} from poll indicates transfer failure (flags: {})\".format(b, block['flags'])\r\n warnings.warn(message)\r\n assert block['datatransfermode'] == 3, \\\r\n \"The block's datatransfermode states the block does not contain scope streaming data.\"\r\n num_samples_block = len(block['wave'][:, 0]) # The same for all channels.\r\n if num_samples_block + n > num_scope_samples:\r\n num_samples_block = num_scope_samples - n\r\n ts_delta = int(clockbase*block['dt']) # The delta inbetween timestamps.\r\n for (i,), channelenable in np.ndenumerate(block['channelenable']):\r\n if not channelenable:\r\n continue\r\n # 'timestamp' is the last sample's timestamp in the block.\r\n ts_end = block['timestamp'] - (len(block['wave'][:, i]) - num_samples_block)*ts_delta\r\n ts_start = ts_end - num_samples_block*ts_delta\r\n scope_samples[i]['timestamp'][n:n + num_samples_block] = np.arange(ts_start, ts_end, ts_delta)\r\n scope_samples[i]['value'][n:n + num_samples_block] = \\\r\n block['channeloffset'][i] + block['channelscaling'][i]*block['wave'][:num_samples_block, i]\r\n n += num_samples_block\r\n daq.sync()\r\n daq.setInt('/%s/scopes/*/stream/enable' % device, 0)\r\n daq.unsubscribe('*')\r\n\r\n print()\r\n print(\"Total blocks processed \", num_blocks, \", samples acquired \", n, \".\", sep=\"\")\r\n\r\n expected_ts_delta = 2**scope_stream_rate\r\n for c, channel_samples in enumerate(scope_samples):\r\n # Check for sampleloss\r\n nan_count = np.sum(np.isnan(scope_samples[c]['value']))\r\n zero_count = np.sum(scope_samples[c]['timestamp'] == 0)\r\n diff_timestamps = np.diff(scope_samples[c]['timestamp'])\r\n min_ts_delta = np.min(diff_timestamps)\r\n max_ts_delta = np.max(diff_timestamps)\r\n if nan_count:\r\n nan_index = np.where(np.isnan(scope_samples[c]['value']))[0]\r\n warnings.warn(\"Scope channel %d values contain %d/%d nan entries (starting at index %d).\"\r\n % (c, nan_count, len(scope_samples[c]['value']), nan_index[0]))\r\n if zero_count:\r\n warnings.warn(\"Scope channel %d timestamps contain %d entries equal to 0.\" % (c, zero_count))\r\n ts_delta_mismatch = False\r\n if min_ts_delta != expected_ts_delta:\r\n index = np.where(diff_timestamps == min_ts_delta)[0]\r\n warnings.warn(\"Scope channel %d timestamps have a min_diff %d (first discrepancy at pos: %d). \"\r\n \"Expected %d.\" % (c, min_ts_delta, index[0], expected_ts_delta))\r\n ts_delta_mismatch = True\r\n if max_ts_delta != expected_ts_delta:\r\n index = np.where(diff_timestamps == max_ts_delta)[0]\r\n warnings.warn(\"Scope channel %d timestamps have a max_diff %d (first discrepenacy at pos: %d). \"\r\n \"Expected %d.\" % (c, max_ts_delta, index[0], expected_ts_delta))\r\n ts_delta_mismatch = True\r\n dt = (channel_samples['timestamp'][-1] - channel_samples['timestamp'][0])/float(clockbase)\r\n print(\"Samples in channel\", c, \"span\", dt, \"s at a rate of\", rate/1e3, \"kHz.\")\r\n assert not nan_count, \"Detected NAN in the array of scope samples.\"\r\n assert not ts_delta_mismatch, \"Detected an unexpected timestamp delta in the scope data.\"\r\n\r\n if do_plot:\r\n import matplotlib.pyplot as plt\r\n\r\n # Get the instrument's ADC sampling rate.\r\n clockbase = daq.getInt('/{}/clockbase'.format(device))\r\n\r\n n = num_samples_period*5\r\n plt.figure(1)\r\n plt.clf()\r\n for c, channel_samples in enumerate(scope_samples):\r\n t = (channel_samples['timestamp'][0:n] - channel_samples['timestamp'][0])/clockbase\r\n plt.plot(t*1e6, channel_samples['value'][0:n])\r\n plt.draw()\r\n plt.grid(True)\r\n plt.xlabel(r'Time [$\\mu$s]')\r\n plt.ylabel(r'Amplitude [V]')\r\n plt.autoscale(enable=True, axis='x', tight=True)\r\n dt = (scope_samples[0]['timestamp'][-1] - scope_samples[0]['timestamp'][0])/clockbase\r\n plt.title(r'Scope streaming data portion (total duration acquired %.1f s)' % dt)\r\n\r\n return data, scope_samples\r\n","sub_path":"Drivers/python_libs/linux/zhinst/examples/common/example_scope_dig_stream.py","file_name":"example_scope_dig_stream.py","file_ext":"py","file_size_in_byte":15841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"504460107","text":"\nfrom Week3.LinearAlgebra.UtilityClass.UtilityClass import Utility\n\n\nclass InverseMatrix:\n def __init__(self):\n self.util = Utility()\n\n x = [[12, 7, 3],\n [4, 5, 6],\n [7, 8, 9]]\n\n def inverse_matrix(self):\n try:\n print(\"Original Matrix : \")\n for v in range(len(self.x)):\n print(self.x[v])\n # getting inverse of matrix\n c = self.util.get_inverse_matrix(self.x)\n print(\"Inverse of matrix : \")\n for value in range(len(c)):\n print(c[value])\n except Exception as e:\n print(e)\n\n\n# instantiation\nInverseMatrix_object = InverseMatrix()\nInverseMatrix_object.inverse_matrix()\n\n\n\n","sub_path":"Week3/LinearAlgebra/InverseMatrix.py","file_name":"InverseMatrix.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"191616315","text":"import csv\nfrom Temp_function import t\nfrom time import time, sleep\n\n\nwith open('data.csv', mode = 'a') as data:\n data_writer = csv.writer(data, delimiter = ',', quotechar = '\"', quoting = csv.QUOTE_MINIMAL)\n \n while True:\n data_writer.writerow([time(),t()])\n data.flush()\n print('bing')\n sleep(300)\n \n ","sub_path":"Sensor/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"262623374","text":"from . import main\nfrom flask import render_template, request, redirect, url_for, abort\nfrom ..models import User, Pitches, Comments, UpVote\nfrom flask_login import login_required, current_user\nfrom .forms import EditProfile, PitchForm, CommentForm\nfrom .. import db, photos\n\n\n\n@main.route('/')\ndef home():\n pitches=Pitches.query.filter_by(category='Blog Pitch')\n identification = Pitches.user_id\n posted_by = User.query.filter_by(id=identification).first()\n user = User.query.filter_by(id=current_user.get_id()).first()\n\n return render_template('pitches.html', pitches=pitches, posted_by=posted_by, user=user)\n\n\n@main.route('/new_pitch', methods=['GET','POST'])\n@login_required\ndef pitch_form():\n pitch_form = PitchForm()\n if pitch_form.validate_on_submit():\n category=pitch_form.pitch_category.data\n text = pitch_form.pitch_text.data\n new_pitch = Pitches(category=category, text=text, user=current_user)\n new_pitch.save_pitch()\n return redirect(url_for('main.home'))\n return render_template('new_pitch.html', pitch_form=pitch_form )\n\n\n@main.route('/categories/')\ndef categories(pitch_category):\n pitch = Pitches.get_category(pitch_category)\n identification = Pitches.user_id\n posted_by = User.query.filter_by(id=identification).first()\n return render_template('categories.html', pitch=pitch, posted_by=posted_by)\n\n\n@main.route('/comments/', methods=['GET','POST']) \n@login_required\ndef pitch_comments(pitch_id):\n comments = Comments.get_comments(pitch_id)\n\n pitch = Pitches.query.get(pitch_id)\n pitch_posted_by = pitch.user_id\n user = User.query.filter_by(id=pitch_posted_by).first()\n\n form = CommentForm()\n if form.validate_on_submit():\n comment = form.pitch_comment.data \n new_comment = Comments(comment=comment, pitch_id=pitch_id, user_id=current_user.get_id())\n new_comment.save_comment()\n return redirect(url_for('main.pitch_comments',pitch_id = pitch_id))\n\n return render_template('comments.html', comment_form=form, comments=comments, pitch = pitch, user=user)\n\n\n@main.route('/user/', methods=['GET','POST'])\n@login_required\ndef profile(name):\n user = User.query.filter_by(username=name).first()\n if user is None:\n abort(404)\n\n form=EditProfile()\n if form.validate_on_submit():\n user.about=form.about.data\n db.session.add(user)\n db.session.commit()\n return redirect(url_for('.profile', name=user.username))\n return render_template('profile/profile.html', user=user, form=form)\n\n\n@main.route('/user//edit/pic', methods=['POST'])\n@login_required\ndef update_pic(name):\n user=User.query.filter_by(username=name).first()\n if 'photo' in request.files:\n filename=photos.save(request.files['photo'])\n path=f'photos/{filename}'\n user.avatar=path\n db.session.commit()\n return redirect(url_for('main.profile', name=name ))\n\n","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"575897861","text":"# Copyright (c) 2015 Midokura SARL\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom tempest_lib.common.utils import data_utils\n\nfrom tempest import config\n\nfrom neutron_fwaas.tests.tempest_plugin.services import client\n\nCONF = config.CONF\n\n\nclass FWaaSClientMixin(object):\n\n @classmethod\n def resource_setup(cls):\n super(FWaaSClientMixin, cls).resource_setup()\n manager = cls.manager\n cls.firewalls_client = client.FirewallsClient(\n manager.auth_provider,\n CONF.network.catalog_type,\n CONF.network.region or CONF.identity.region,\n endpoint_type=CONF.network.endpoint_type,\n build_interval=CONF.network.build_interval,\n build_timeout=CONF.network.build_timeout,\n **manager.default_params)\n cls.firewall_policies_client = client.FirewallPoliciesClient(\n manager.auth_provider,\n CONF.network.catalog_type,\n CONF.network.region or CONF.identity.region,\n endpoint_type=CONF.network.endpoint_type,\n build_interval=CONF.network.build_interval,\n build_timeout=CONF.network.build_timeout,\n **manager.default_params)\n cls.firewall_rules_client = client.FirewallRulesClient(\n manager.auth_provider,\n CONF.network.catalog_type,\n CONF.network.region or CONF.identity.region,\n endpoint_type=CONF.network.endpoint_type,\n build_interval=CONF.network.build_interval,\n build_timeout=CONF.network.build_timeout,\n **manager.default_params)\n\n def create_firewall_rule(self, **kwargs):\n body = self.firewall_rules_client.create_firewall_rule(\n name=data_utils.rand_name(\"fw-rule\"),\n **kwargs)\n fw_rule = body['firewall_rule']\n self.addCleanup(self._delete_wrapper,\n self.firewall_rules_client.delete_firewall_rule,\n fw_rule['id'])\n return fw_rule\n\n def create_firewall_policy(self, **kwargs):\n body = self.firewall_policies_client.create_firewall_policy(\n name=data_utils.rand_name(\"fw-policy\"),\n **kwargs)\n fw_policy = body['firewall_policy']\n self.addCleanup(self._delete_wrapper,\n self.firewall_policies_client.delete_firewall_policy,\n fw_policy['id'])\n return fw_policy\n\n def create_firewall(self, **kwargs):\n body = self.firewalls_client.create_firewall(\n name=data_utils.rand_name(\"fw\"),\n **kwargs)\n fw = body['firewall']\n self.addCleanup(self._delete_wrapper,\n self.firewalls_client.delete_firewall,\n fw['id'])\n return fw\n","sub_path":"neutron_fwaas/tests/tempest_plugin/tests/fwaas_client.py","file_name":"fwaas_client.py","file_ext":"py","file_size_in_byte":3330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"454507686","text":"import unittest\nfrom os import path\n\nfrom numpy import array, allclose\nfrom pandas import read_csv\n\nfrom ..model_comparison import predict\n\ndirname, filename = path.split(path.abspath(__file__))\n\n\nclass SavedModelTests(unittest.TestCase):\n \"\"\"\n This unit test checks that the predictions for 1000 guides match the predictions we expected in Nov 2016.\n This unit test can fail due to randomness in the model (e.g. random seed, feature reordering).\n \"\"\"\n\n def test_predictions_nopos(self):\n df = read_csv(path.join(dirname, \"1000guides.csv\"), index_col=0)\n predictions = predict(array(df[\"guide\"].values), None, None)\n self.assertTrue(allclose(predictions, df[\"truth nopos\"].values, atol=1e-1))\n\n def test_predictions_pos(self):\n df = read_csv(path.join(dirname, \"1000guides.csv\"), index_col=0)\n predictions = predict(\n array(df[\"guide\"].values),\n array(df[\"AA cut\"].values),\n array(df[\"Percent peptide\"].values),\n )\n self.assertTrue(allclose(predictions, df[\"truth pos\"].values, atol=1e-1))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"gRNAScores/azimuth/tests/test_saved_models.py","file_name":"test_saved_models.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"350078160","text":"import sys\r\nsys.path.append('D:\\Program Files\\Tinysoft\\Analyse.NET')\r\nimport TSLPy3 as ts\r\nimport pandas as pd\r\nimport datetime\r\n# from mongodb_functions import mongodb_client\r\nimport re\r\n\r\n\r\nclass CtaTickData(object):\r\n \"\"\"Tick数据\"\"\"\r\n # ----------------------------------------------------------------------\r\n def __init__(self):\r\n EMPTY_STRING = ''\r\n EMPTY_FLOAT = 0.0\r\n EMPTY_INT = 0\r\n\r\n \"\"\"Constructor\"\"\"\r\n self.vtSymbol = EMPTY_STRING # vt系统代码 CF705 StockName\r\n self.symbol = EMPTY_STRING # 合约代码 CF1705 StockID\r\n self.exchange = EMPTY_STRING # 交易所代码\r\n\r\n\r\n # 成交数据\r\n self.lastPrice = EMPTY_FLOAT # 最新成交价\r\n self.volume = EMPTY_INT # 最新成交量\r\n self.amount = EMPTY_INT #成交金额\r\n self.cjbs = EMPTY_INT # 周期内成交笔数\r\n self.yclose = EMPTY_FLOAT #上一收盘价\r\n self.preSettlement = EMPTY_FLOAT #上一日结算价\r\n\r\n self.preOpenInterest = EMPTY_INT # 昨持仓量\r\n self.openInterest = EMPTY_INT # 持仓量\r\n\r\n self.upperLimit = EMPTY_FLOAT # 涨停价\r\n self.lowerLimit = EMPTY_FLOAT # 跌停价\r\n\r\n # tick的时间\r\n self.tradingDay = EMPTY_STRING # 交易日期\r\n self.date = EMPTY_STRING # 日期\r\n self.time = EMPTY_STRING # 时间\r\n self.datetime = None # python的datetime时间对象\r\n\r\n # 五档行情\r\n self.bidPrice1 = EMPTY_FLOAT\r\n self.askPrice1 = EMPTY_FLOAT\r\n self.bidVolume1 = EMPTY_INT\r\n self.askVolume1 = EMPTY_INT\r\n\r\nclass CtaDailyData(object):\r\n \"\"\"Tick数据\"\"\"\r\n # ----------------------------------------------------------------------\r\n def __init__(self):\r\n EMPTY_STRING = ''\r\n EMPTY_FLOAT = 0.0\r\n EMPTY_INT = 0\r\n\r\n \"\"\"Constructor\"\"\"\r\n self.vtSymbol = EMPTY_STRING\r\n self.commodity = EMPTY_STRING\r\n self.date = EMPTY_STRING\r\n\r\n\r\n # 成交数据\r\n self.close = EMPTY_FLOAT\r\n self.open = EMPTY_FLOAT\r\n self.high = EMPTY_FLOAT\r\n self.low = EMPTY_FLOAT\r\n\r\n self.settlement = EMPTY_FLOAT\r\n self.volume = EMPTY_INT\r\n self.openint = EMPTY_FLOAT\r\n self.margin = EMPTY_FLOAT\r\n\r\n\r\n\r\n\r\n\r\nclass tslFunctions():\r\n def __init__(self):\r\n self.mc = None\r\n #登录\r\n def tsl_login(self):\r\n ts.ConnectServer(\"tsl.tinysoft.com.cn\", 443)\r\n dl = ts.LoginServer(\"htccqh\", \"xx\") # Tuple(ErrNo,ErrMsg) 登陆用户\r\n if dl[0] == 0:\r\n print(\"登陆成功\")\r\n print(\"服务器设置:\", ts.GetService())\r\n ts.SetComputeBitsOption(64) # 设置计算单位\r\n print(\"计算位数设置:\", ts.GetComputeBitsOption())\r\n else:\r\n print(dl[1])\r\n\r\n #STR转GBK\r\n def tsbytestostr(self, data):\r\n if isinstance(data, (tuple, list)):\r\n lendata = len(data)\r\n ret = []\r\n for i in range(lendata):\r\n ret.append(self.tsbytestostr(data[i]))\r\n elif isinstance(data, dict):\r\n ret = {}\r\n for i in data:\r\n ret[self.tsbytestostr(i)] = self.tsbytestostr(data[i])\r\n elif isinstance(data, bytes):\r\n ret = data.decode('gbk')\r\n else:\r\n ret = data\r\n return ret\r\n\r\n #取交易日LIST\r\n def getTradeDays(self,start,end):\r\n daysList = self.tsbytestostr(ts.RemoteExecute(\r\n \"begt:=strtodate('%s');endt:=strtodate('%s');return datetostr(spec(specdate(nday3(tradedays(begt,endt),sp_time()),endt),'SH000001'));\" % (\r\n start, end), {}))\r\n return daysList[1]\r\n\r\n def getDailyFuturesCode(self,BegDate,EndDate,section='郑州商品交易所;上海期货交易所;大连商品交易所;中国金融期货交易所;上海国际能源交易中心'):\r\n allContractsCode =pd.DataFrame(self.tsbytestostr(ts.RemoteExecute(\r\n '''return select thisrow as '代码', spec(datetostr(inttodate(base(703018))),thisrow) as '最后交易日',\\\r\n spec(datetostr(inttodate(base(703002,0))),thisrow) as '变动日'\\\r\n from getbk('%s') end; '''%section,{}))[1])\r\n specDayContracts1 = allContractsCode[allContractsCode['变动日']<=EndDate]\r\n specDayContracts2 = specDayContracts1[specDayContracts1['最后交易日'] >= BegDate]\r\n return specDayContracts2['代码']\r\n\r\n def getDailyFuturesDetails(self,BegDate,EndDate,symbol):\r\n detailsDF=pd.DataFrame(self.tsbytestostr(ts.RemoteExecute(\r\n '''N:=TradeDays(StrToDate('%s'),StrToDate('%s'));\r\n return nday(N, 'DATE', datetimetostr(sp_time()),\r\n 'CLOSE', close(),\r\n 'HIGH', high(),\r\n 'LOW', low(),\r\n 'OPEN',open(),\r\n 'AMOUNT',amount(),\r\n \"SETTLEMENT\",Settlement(),\r\n \"OPENINT\",OpenInterest(),\r\n \"VOL\",vol(),\r\n 'CONTRACT',base(703001),\r\n 'COMMODITY',base(703003),\r\n 'MARGIN',FuturesTradingMarginRate(sp_time(),0));'''%(BegDate,EndDate),\r\n {'StockID': symbol, \"CurrentDate\": ts.LocalCallFunc(\"StrToDate\", [EndDate])[1]}))[1])\r\n try:\r\n detailsDF['COMMODITY'] = [x.upper() for x in detailsDF['COMMODITY']]\r\n except Exception as e:\r\n print('-------------------')\r\n print(e)\r\n print('%s合约没有数据!!!'%symbol)\r\n print('-------------------')\r\n return detailsDF\r\n\r\n def getTickDetails(self, BegDate, EndDate, contract_code,symbol):\r\n # tick_details = pd.DataFrame(self.tsbytestostr(ts.RemoteExecute( '''a:=select [\"StockID\"],[\"StockName\"],[\"date\"],[\"price\"],[\"vol\"],[\"amount\"],[\"cjbs\"],[\"yclose\"],[\"syl1\"],[\"syl2\"],[\"buy1\"],[\"sale1\"],[\"bc1\"],[\"sc1\"] from tradetable datekey %s+21/24 to %s+16/24 of '%s' end;b:=update a set ['date']=datetimetostr(['date']) end;return a;''' % (\r\n # ts.LocalCallFunc(\"StrToDate\", [BegDate])[1], ts.LocalCallFunc(\"StrToDate\", [EndDate])[1], contract_code),{}))[1])\r\n # tick_details.to_csv('%s%s_%s.csv'%(path,symbol,EndDate),index=False)\r\n # return tick_details\r\n\r\n # tick_details = pd.DataFrame(self.tsbytestostr(ts.RemoteExecute(\r\n # '''a:=select [\"StockID\"],[\"StockName\"],[\"date\"],[\"price\"],[\"vol\"],[\"amount\"],[\"cjbs\"],[\"yclose\"],[\"syl1\"],[\"syl2\"],[\"buy1\"],[\"sale1\"],[\"bc1\"],[\"sc1\"] from tradetable datekey %s+21/24 to %s+16/24 of '%s' end;b:=update a set ['date']=datetimetostr(['date']) end;return a;''' % (\r\n # ts.LocalCallFunc(\"StrToDate\", [BegDate])[1], ts.LocalCallFunc(\"StrToDate\", [EndDate])[1], contract_code),\r\n # {}))[1])\r\n\r\n if self.mc is None:\r\n # self.mc = mongodb_client()\r\n self.mc.dbConnect()\r\n\r\n\r\n\r\n # dateList=self.getTradeDays(\r\n # (datetime.datetime.strptime(BegDate, '%Y-%m-%d') - datetime.timedelta(3)).strftime('%Y-%m-%d'), EndDate)\r\n # BegDateAdj=dateList[max(0,dateList.index(BegDate)-1)]\r\n\r\n tick_dict = self.tsbytestostr(ts.RemoteExecute(\r\n '''a:=select [\"StockID\"],[\"StockName\"],[\"date\"],[\"price\"],[\"vol\"],[\"amount\"],[\"cjbs\"],[\"yclose\"],[\"syl1\"],[\"syl2\"],[\"buy1\"],[\"sale1\"],[\"bc1\"],[\"sc1\"] from tradetable datekey %s to %s+0.9999999 of '%s' end;b:=update a set ['date']=datetimetostr(['date']) end;return a;''' % (\r\n ts.LocalCallFunc(\"StrToDate\", [BegDate])[1], ts.LocalCallFunc(\"StrToDate\", [EndDate])[1], contract_code),\r\n {}))[1]\r\n\r\n # datetime.datetime.strptime(tick_dict['date'][0], '%Y-%m-%d %H:%M:%S').replace(microsecond=500000)\r\n last_tick_datetime = None\r\n count = 0\r\n for d in tick_dict:\r\n tick = CtaTickData()\r\n tick.vtSymbol = d['StockName']\r\n\r\n tick.symbol = d['StockID'] # ���约代码 CF1705 StockID\r\n # tick.exchange = EMPTY_STRING # 交易所代码\r\n\r\n # 成交数据\r\n tick.lastPrice = d['price'] # 最新成交价\r\n tick.volume = d['vol'] #最新成交量\r\n tick.amount = d['amount'] # 成交金额\r\n tick.cjbs = d['cjbs'] # 周期内成交笔数\r\n tick.yclose = d['yclose'] # 上一收盘价\r\n tick.preSettlement = d['syl2'] # 上一日结算价\r\n\r\n # tick的时间\r\n\r\n # 转换为datetime格式\r\n try:\r\n if len(d['date'])>10:\r\n tick.datetime = datetime.datetime.strptime(d['date'], '%Y-%m-%d %H:%M:%S') # python的datetime时间对象\r\n else:\r\n tick.datetime = datetime.datetime.strptime(d['date'], '%Y-%m-%d')\r\n tick.date = tick.datetime.strftime('%Y-%m-%d') # 日期\r\n tick.time = tick.datetime.strftime('%H:%M:%S') # 时间\r\n # tick.tradingDay = d['price'] # 交易日期\r\n except Exception as ex:\r\n # 抛弃本tick\r\n print('日期转换错误:%s,error:%s' % (d['date'], ex))\r\n continue\r\n\r\n # 1档行情\r\n tick.bidPrice1 = d['buy1']\r\n tick.askPrice1 = d['sale1']\r\n tick.bidVolume1 = d['bc1']\r\n tick.askVolume1 = d['sc1']\r\n\r\n # 修正毫秒\r\n if tick.datetime.replace(microsecond=0) == last_tick_datetime:\r\n # 与上一个tick的时间(去除毫秒后)相同,修改为500毫秒\r\n tick.datetime = tick.datetime.replace(microsecond=500000)\r\n tick.time = tick.datetime.strftime('%H:%M:%S.%f')\r\n\r\n else:\r\n tick.datetime = tick.datetime.replace(microsecond=0)\r\n tick.time = tick.datetime.strftime('%H:%M:%S.%f')\r\n\r\n # 记录最新tick的时间\r\n last_tick_datetime = tick.datetime\r\n if symbol=='TC':\r\n symbol = 'ZC'\r\n if symbol == 'RO':\r\n symbol = 'OI'\r\n if symbol == 'ER':\r\n symbol = 'RI'\r\n if symbol == 'WS':\r\n symbol = 'WH'\r\n if symbol == 'ME':\r\n symbol = 'MA'\r\n\r\n self.mc.dbInsert('FUTURE_TICK_DB','TS_%s_TickDatas'%symbol,d=tick.__dict__)\r\n count = count + 1\r\n print('写入合约%s完成,共%d条'%(contract_code,count))\r\n return\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n getDatas=tslFunctions()\r\n getDatas.tsl_login()\r\n\r\n BegDate='2018-12-28'\r\n EndDate='2019-01-05'\r\n # getDatas.getTickDetails(BegDate, BegDate, 'cu1902', re.findall(\"[A-Za-z]+\",'cu1905')[0].upper())\r\n # #补周六\r\n # a = []\r\n # for day in pd.date_range('2013-07-05', '2018-12-17'):\r\n # if day.weekday() == 5:\r\n # a.append(datetime.datetime.strftime(day, '%Y-%m-%d'))\r\n\r\n # codeList=getDatas.getDailyFuturesCode(BegDate, EndDate)\r\n dayList= getDatas.getTradeDays(BegDate, EndDate)\r\n\r\n #补周六\r\n for day in pd.date_range(BegDate, EndDate):\r\n if day.weekday() == 5:\r\n dayList.append(datetime.datetime.strftime(day, '%Y-%m-%d'))\r\n # dayList=EndDate\r\n from tqdm import tqdm\r\n tdqmDayList=tqdm(dayList)\r\n # tqdmList=tqdm(codeList)\r\n initialDB=True\r\n for day in tdqmDayList:\r\n codeList=getDatas.getDailyFuturesCode(day, day)\r\n tqdmCodeList = tqdm(codeList)\r\n if initialDB:\r\n listCode=list(set([re.findall(\"[A-Za-z]+\", x)[0].upper() for x in codeList]))\r\n if getDatas.mc is None:\r\n getDatas.mc = mongodb_client()\r\n getDatas.mc.dbConnect()\r\n\r\n for code in listCode:\r\n getDatas.mc.dbDelete('FUTURE_TICK_DB','TS_%s_TickDatas'%code,{'date':{'$gte':BegDate,'$lte':EndDate}})\r\n print('del %s Done!'%code)\r\n initialDB=False\r\n\r\n\r\n for contract in tqdmCodeList:\r\n print(\"--------------------------------------------\")\r\n print(day)\r\n getDatas.getTickDetails(day, day, contract,re.findall(\"[A-Za-z]+\",contract)[0].upper())\r\n","sub_path":"databases/TinySoft/tslFunctions.py","file_name":"tslFunctions.py","file_ext":"py","file_size_in_byte":12230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"397122064","text":"# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\"./models_softmax_batch_110_0005/mnist_test_model\"\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# ==============================================================================\r\n\"\"\"A very simple MNIST classifier.\r\nSee extensive documentation at\r\nhttps://www.tensorflow.org/get_started/mnist/beginners\r\n\"\"\"\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport numpy as np\r\nimport argparse\r\nimport sys\r\nimport time\r\nfrom models_ss import Generator, Discriminator\r\n\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\n\r\nimport tensorflow as tf\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\n# Code by Parag Mital (github.com/pkmital/CADL)\r\ndef montage(images):\r\n if isinstance(images, list):\r\n images = np.array(images)\r\n img_h = images.shape[1]\r\n img_w = images.shape[2]\r\n n_plots = int(np.ceil(np.sqrt(images.shape[0])))\r\n m = np.ones((images.shape[1] * n_plots + n_plots + 1, images.shape[2] * n_plots + n_plots + 1)) * 0.5\r\n for i in range(n_plots):\r\n for j in range(n_plots):\r\n this_filter = i * n_plots + j\r\n if this_filter < images.shape[0]:\r\n this_img = images[this_filter]\r\n m[1 + i + i * img_h:1 + i + (i + 1) * img_h,\r\n 1 + j + j * img_w:1 + j + (j + 1) * img_w] = this_img\r\n return m\r\n\r\nnp.random.seed(0)\r\ntf.set_random_seed(0)\r\n\r\nNUM_ITERATIONS=1000\r\nFLAGS = None\r\nbatch_size=110\r\nmodel_file=\"./testing/mnist_test_model\"#\"./models_semisupervised_55/mnist_test_model\"\r\noutput_dir=\"./output\"\r\ndef generate_identity():\r\n return tf.ones([1,784])\r\n\r\ndef uniform_data_gen(batch_size):\r\n return np.random.uniform(0.0,1.0,(batch_size,100))\r\n\r\ndef normal_data_gen(batch_size):\r\n return np.random.normal(0.0,1.0,(batch_size,100))\r\n\r\ndef calculate_loss(true_logit,true_prob,true_features,labels,fake_logit,fake_prob,fake_features):#labels WILL be onehot\r\n #add \"FAKE\" class\r\n ss_labels=tf.pad(labels,[[0,0],[0,1]],\"CONSTANT\")\r\n #ss_labels=tf.concat([labels,tf.zeros([tf.shape(labels)[0], 1])],axis=1)\r\n #Classifier Loss= L_unsupervised+L_supervised\r\n #L_supervised=cross-entropy loss of true labelled data (true data labelled true but misclassified)\r\n #L_unsupervised=cross-entropy loss of (1- prob true data labelled fake)+ \r\n # cross-entropy loss of (fake data labelled as fake)\r\n # =cross entropy loss of (true data labelled true) + cross entropy loss of (fake data labelled fake)\r\n #Note this is the standard GAN minimax equation:\r\n #L_unsupervised=CE-loss of (D(X) correctly labelled) + CE-loss of D(G(z)) correctly labelled)\r\n l_sup=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=ss_labels,logits=true_logit))\r\n l_unsup=tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.zeros(tf.shape(true_prob)[0]),logits=true_prob[:,-1]))+\\\r\n tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones(tf.shape(fake_prob)[0]),logits=fake_prob[:,-1]))\r\n disc_loss=l_sup+l_unsup\r\n #Generator class\r\n #minimize the l2 distance between two features\r\n l_unsup_gen=tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones(tf.shape(true_prob)[0]),logits=true_prob[:,-1]))+\\\r\n tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.zeros(tf.shape(fake_prob)[0]),logits=fake_prob[:,-1]))\r\n gen_loss=tf.reduce_mean(tf.square(true_features-fake_features))\r\n return gen_loss, disc_loss\r\n\r\ndef train_gan(args):\r\n # Import data\r\n mnist = input_data.read_data_sets(FLAGS.data_dir,one_hot=True)\r\n\r\n gen=Generator()\r\n disc=Discriminator()\r\n\r\n keep_prob=tf.placeholder(tf.float32, None)\r\n is_training=tf.placeholder(tf.bool, None)\r\n\r\n x = tf.placeholder(tf.float32, [None, 784])\r\n y_labels = tf.placeholder(tf.int32, [None,10])\r\n y, y_prob, y_feature = disc.classify(tf.reshape(x,[-1,28,28,1]),keep_prob,is_training)\r\n\r\n noise=tf.placeholder(tf.float32,[None,100])\r\n\r\n fake_x=gen.generate(noise,keep_prob,is_training)\r\n fake_y, fake_y_prob, fake_y_feature= disc.classify(fake_x,keep_prob,is_training,reuse=True)\r\n\r\n #generators\r\n gen_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,scope=\"GAN/Generator\")\r\n disc_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,scope=\"GAN/Discriminator\")\r\n\r\n #disc_reg=tf.contrib.layers.apply_regularization(tf.contrib.layers.l2_regularizer(1e-8), disc_vars)\r\n #gen_reg=tf.contrib.layers.apply_regularization(tf.contrib.layers.l2_regularizer(1e-8), gen_vars)\r\n\r\n gen_loss, disc_loss = calculate_loss(y, y_prob, y_feature, y_labels, fake_y, fake_y_prob, fake_y_feature)\r\n\r\n disc_train_step = tf.train.AdamOptimizer(0.0005,beta1=0.5).minimize(disc_loss,var_list=disc_vars)\r\n gen_train_step = tf.train.AdamOptimizer(0.0005,beta1=0.5).minimize(gen_loss,var_list=gen_vars)\r\n\r\n #classifier accuracy\r\n y_labels_mod=tf.pad(y_labels,[[0,0],[0,1]])\r\n correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_labels_mod, 1))\r\n classifier_accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\r\n\r\n #discriminator accuracy - assumes all data is fake\r\n fake_test_labels=tf.concat([tf.zeros([tf.shape(fake_y)[0], 10]), tf.ones([tf.shape(fake_y)[0],1])], 1)\r\n predict_fake = tf.equal(tf.argmax(fake_y, 1), tf.argmax(fake_test_labels, 1))\r\n fake_id_accuracy = tf.reduce_mean(tf.cast(predict_fake, tf.float32))\r\n\r\n #discriminator accuracy - assumes all data is real\r\n real_test_labels=tf.concat([tf.zeros([tf.shape(y)[0], 10]), tf.ones([tf.shape(y)[0],1])], 1)\r\n predict_real = tf.equal(tf.argmax(y, 1), tf.argmax(real_test_labels, 1))\r\n real_id_accuracy = 1- tf.reduce_mean(tf.cast(predict_real, tf.float32))\r\n\r\n\r\n init=tf.global_variables_initializer()\r\n sess = tf.Session()\r\n sess.run(init)\r\n\r\n saver=tf.train.Saver()\r\n if \"--load\" in args or \"--test\" in args:\r\n saver.restore(sess,model_file)\r\n\r\n show_z=normal_data_gen(16)\r\n g_loss=0\r\n d_loss=0\r\n past_glosses=[]\r\n past_dlosses=[]\r\n\r\n #Train\r\n\r\n if \"--test\" not in args:\r\n start=time.time()\r\n\r\n batches_in_epoch=55000//batch_size\r\n num_epochs=1\r\n for _ in range(50):#num_epochs*batches_in_epoch+1):\r\n #for _ in range(50):\r\n print(\"Iteration \",_,\" of \",str(batches_in_epoch))\r\n batch_xs, batch_ys = mnist.train.next_batch(batch_size)\r\n uniform_noise=normal_data_gen(batch_size)\r\n d_loss, d_steps, g_loss, g_steps = sess.run([disc_loss, disc_train_step, gen_loss, gen_train_step], feed_dict={keep_prob:0.7, is_training:True, \\\r\n x: batch_xs, y_labels: batch_ys, noise: uniform_noise})\r\n \r\n #uniform_noise=normal_data_gen(110)\r\n #g_loss,g_steps=sess.run([gen_loss, gen_train_step], feed_dict={keep_prob:0.7, is_training:True,\\\r\n # x: batch_xs, y_labels: batch_ys, noise: uniform_noise})\r\n \r\n print(\"Discriminator loss: \",d_loss, d_steps)\r\n print(\"Generator loss: \",g_loss, g_steps)\r\n\r\n if _%10 == 0:\r\n past_glosses.append(g_loss)\r\n past_dlosses.append(d_loss)\r\n\r\n if _%50 == 0:\r\n print(\"\\nTESTING GENERATORS OUTPUT\\n\")\r\n for it in range(1):\r\n x_val,y_val=sess.run([fake_x,fake_y],feed_dict={keep_prob:1.0, is_training:False, noise: show_z})\r\n print(\"y val: \",y_val)\r\n imgs = [img[:,:,0] for img in x_val]\r\n m = montage(imgs)\r\n gen_img = m\r\n plt.axis('off')\r\n plt.imshow(gen_img,cmap=\"gray\")\r\n plt.savefig(\"%s/it%d.png\"%(output_dir,_))\r\n plt.clf()\r\n #plt.show()\r\n\r\n plt.plot(np.linspace(0,len(past_dlosses),len(past_dlosses)),past_dlosses,label=\"dloss\")\r\n plt.plot(np.linspace(0,len(past_glosses),len(past_glosses)),past_glosses,label=\"gloss\")\r\n plt.title(\"DCGAN Loss\")\r\n plt.xlabel(\"Iteration\")\r\n plt.ylabel(\"Loss\")\r\n plt.legend()\r\n plt.savefig(\"%s/progress.png\"%output_dir)\r\n plt.clf()\r\n #plt.show()\r\n\r\n if \"--save\" in args:\r\n saver.save(sess, model_file)\r\n end=time.time()\r\n print(\"time elapse: \", str(end-start))\r\n \r\n #Testing classifier\r\n accuracy_l = []\r\n for _ in range(20):\r\n batch = mnist.test.next_batch(500, shuffle=False)\r\n accuracy_l.append(classifier_accuracy.eval(session=sess,feed_dict={x: batch[0], \r\n y_labels: batch[1], \r\n keep_prob: 1.0,\r\n is_training:True}))\r\n print(accuracy_l)\r\n print('test classifier accuracy %g' % np.mean(accuracy_l))\r\n #Testing discriminator\r\n fake_identification = []\r\n real_identification = []\r\n for _ in range(20):\r\n batch_1 = mnist.test.next_batch(250, shuffle=False)\r\n \r\n real_identification.append(real_id_accuracy.eval(session=sess,feed_dict={x: batch_1[0], \r\n y_labels: batch_1[1], \r\n keep_prob: 1.0,\r\n is_training:True}))\r\n fake_identification.append(fake_id_accuracy.eval(session=sess,feed_dict={noise: normal_data_gen(250), \r\n keep_prob: 1.0,\r\n is_training:True}))\r\n print(\"success in identifying fakes\")\r\n print(fake_identification)\r\n print(\"success in identifying reals\")\r\n print(real_identification)\r\n print('test classifier accuracy %g' % np.mean(fake_identification+real_identification))\r\n\r\n\r\ndef main(_):\r\n train_gan(_)\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\r\n '--data_dir',\r\n type=str,\r\n default='/tmp/tensorflow/mnist/input_data',\r\n help='Directory for storing input data')\r\n FLAGS, unparsed = parser.parse_known_args()\r\n tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)","sub_path":"mnist_semisupervised/comparisons/mnist_semisupervised.py","file_name":"mnist_semisupervised.py","file_ext":"py","file_size_in_byte":11020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"45843710","text":"from mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfig = plt.figure()\nax = fig.add_subplot(111,projection='3d')\n\ntheta = np.linspace(0, 2 * np.pi, 200)\nx = np.sqrt(5)*np.cos(theta)\ny = np.sqrt(5)*np.sin(theta)\nax.plot(x,y,np.sqrt(5/2),'g', alpha =0.6 )\n\nlen = 10\nx1, x2 = np.meshgrid(np.linspace(0,5,len),np.linspace(0,5,len))\nz=(x1*x2)**0.5\nax.plot_surface(x1, x2, z, color='r',alpha=0.3)\n\nax.plot([np.sqrt(5/2)], [np.sqrt(5/2)], [np.sqrt(5/2)], markerfacecolor='b', markeredgecolor='b', marker='o', markersize=5, alpha=0.7)\n\nax.set_xlabel('$X$', rotation=150)\nax.set_ylabel('$Y$')\nax.set_zlabel('$Z$', rotation=0)\n\nax.legend()\n\nplt.show()\n","sub_path":"ProblemNo_3.20.py","file_name":"ProblemNo_3.20.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"329428183","text":"import os, sys, json, time\n\ncfg = None\nwith open(sys.argv[1], 'r') as jf:\n cfg = json.load(jf)\n\ntotal_line = 0\n\nsupported_ext = (\n 'c', # include .h, .hpp\n 'cpp',\n 'c++',\n 'tcl',\n )\n\ndef extract_files():\n dst_files = []\n global total_line\n for subdir, dirs, files in os.walk(cfg['source_root_dir']):\n skip = False\n for f in files:\n full_path = os.path.join(subdir, f)\n\n if cfg['exclude_files_prefix_with']:\n for prefix in cfg['exclude_files_prefix_with']:\n if f.startswith(prefix):\n print('skip %s' % f)\n skip = True\n break\n\n if cfg['exclude_subdir']:\n for d in cfg['exclude_subdir']:\n if full_path.startswith(cfg['source_root_dir'] + d):\n skip = True\n print('skip %s' % full_path)\n break\n\n if skip:\n continue\n\n if cfg['all_of_them']:\n pass\n else:\n f_name, f_ext = os.path.splitext(f)\n if f_ext not in cfg['expected_file_type'] or f_name not in cfg['specific_files']:\n continue\n num_lines = sum(1 for line in open(full_path))\n print('adding %s' % full_path)\n dst_files.append((full_path, num_lines,))\n total_line += num_lines\n return dst_files\n\ndef gen_tex(src_files):\n tex = {}\n for src in src_files:\n ext = src[0].split('.')[-1]\n #print ('ext: %s' % ext)\n if ext in supported_ext:\n tex[src[0]] = ('\\\\lstinputlisting[language=%s]{%s}' % (ext, src[0]), src[1])\n else:\n tex[src[0]] = ('\\\\lstinputlisting{%s}' % (src[0]), src[1])\n\n return tex\n\ndef gen_main_tex(include_files):\n incs = []\n for f in include_files:\n incs.append('\\\\include{%s}' % f.split('.')[0])\n\n tex = '''\n\\\\documentclass{book}\n\n\\\\input{input/utils}\n\\\\input{input/lst}\n\\\\input{input/more-key}\n\\\\input{input/new-cmd}\n\n\\\\title{\\\\hbf %s}\n\\\\date{\\\\today}\n\\\\parindent 0em\n\\\\begin{document}\n\\\\maketitle\n\\\\tableofcontents\n\\\\chapter{%s(%d)}\n%s\n\\\\end{document}\n ''' % (cfg['pdf_title'], cfg['pdf_title'], total_line, '\\n\\n'.join(incs))\n main = cfg['pdf_out'] + '.tex'\n with open(main, 'w') as m:\n m.write(tex)\n\nif __name__ == '__main__':\n files = extract_files()\n tex = gen_tex(files)\n\n with open(cfg['output_tex_file'], 'w') as t:\n for k, v in tex.iteritems():\n #sec_name = k.replace('\\\\', '/')\n sec_name = k.replace(cfg['source_root_dir'], '')\n sec_name = sec_name.replace('_', '\\\\_')\n t.write('\\\\section{%s(%d)}\\n%s\\n\\n' % (sec_name, v[1], v[0]))\n #time.sleep(0.5)\n\n gen_main_tex([cfg['output_tex_file']])\n\n # see http://en.wikibooks.org/wiki/LaTeX/Source_Code_Listings, part `Supported languages`\n # 'ABAP' ,'IDL4' ,'PL/I'\n # ,'ACSL' ,'inform' ,'Plasm'\n # ,'Ada' ,'Java' ,'POV'\n # ,'Algol' ,'JVMIS' ,'Prolog'\n # ,'Ant' ,'ksh' ,'Promela'\n # ,'Assembler' ,'Lisp' ,'Python'\n # ,'Awk' ,'Logo' ,'R'\n # ,'bash' ,'make' ,'Reduce'\n # ,'Basic' ,'Mathematica' ,'Rexx'\n # ,'C' ,'Matlab' ,'RSL'\n # ,'C++' ,'Mercury' ,'Ruby'\n # ,'Caml' ,'MetaPost' ,'S'\n # ,'Clean' ,'Miranda' ,'SAS'\n # ,'Cobol' ,'Mizar' ,'Scilab'\n # ,'Comal' ,'ML' ,'sh'\n # ,'csh' ,'Modelica' ,'SHELXL'\n # ,'Delphi' ,'Modula-2' ,'Simula'\n # ,'Eiffel' ,'MuPAD' ,'SQL'\n # ,'Elan' ,'NASTRAN' ,'tcl'\n # ,'erlang' ,'Oberon-2' ,'TeX'\n # ,'Euphoria' ,'OCL' ,'VBScript'\n # ,'Fortran' ,'Octave' ,'Verilog'\n # ,'GCL' ,'Oz' ,'VHDL'\n # ,'Gnuplot' ,'Pascal' ,'VRML'\n # ,'Haskell' ,'Perl' ,'XML'\n # ,'HTML' ,'PHP' ,'XSLT'\n","sub_path":"src2pdf.py","file_name":"src2pdf.py","file_ext":"py","file_size_in_byte":3826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"69210749","text":"#coding:UTF-8\nimport tensorflow as tf\n\n#输入\ninput1 = tf.placeholder(tf.int32)#placeholder(dtype,shape),定义一个3行2列的矩阵\n#输出\n#output = tf.matmul(input1,input2)#matmul(),矩阵乘法\noutput = input1\n#执行\nwith tf.Session() as sess:\n result = sess.run(output,feed_dict = {input1:1})\n print(result)","sub_path":"GNN_opt_test/output.py","file_name":"output.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"256224997","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 ('django_tutalk', '0002_auto_20151111_1534'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='TuTalkEvent',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('event_type', models.CharField(max_length=32)),\n ('event_text', models.CharField(max_length=32)),\n ('timestamp', models.DateTimeField(auto_now_add=True)),\n ('participant', models.ForeignKey(to='django_tutalk.Participant')),\n ('task', models.ForeignKey(to='django_tutalk.Task')),\n ],\n ),\n ]\n","sub_path":"django_tutalk/migrations/0003_tutalkevent.py","file_name":"0003_tutalkevent.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"524271636","text":"#!/usr/bin/python\n\"\"\"\nThis is the most simple example to showcase Containernet.\n\"\"\"\nfrom mininet.net import Containernet\nfrom mininet.node import Controller,RemoteController\nfrom mininet.cli import CLI\nfrom mininet.link import TCLink\nfrom mininet.log import info, setLogLevel\nfrom time import sleep\nsetLogLevel('info')\nn_hosts=30\nassert n_hosts > 1\nnet = Containernet(controller=Controller)\ninfo('*** Adding controller\\n')\nc0 = RemoteController( 'c0', ip='127.0.0.1' )\nnet.addController(c0)\ninfo('*** Adding docker containers\\n')\n\ndocker_hosts=[net.addDocker('d1', ip='10.0.0.1', dimage=\"hadoop:new\",cpuset_cpus=\"0,1\",ports=[8088, 50070], port_bindings={8088:8088,50070:50070},)]\nswitches = [net.addSwitch('s1')]\nnet.addLink(docker_hosts[-1], switches[-1])\ncpu_set=(2, 3)\nfor i in range(2,n_hosts+1):\n docker_hosts.append(net.addDocker('d{}'.format(i), ip='10.0.0.{}'.format(i),\n dimage=\"hadoop:new\",cpuset_cpus=\"{},{}\".format(cpu_set[0],cpu_set[1]),\n mem_limit=\"6500m\", memswap_limit=\"50m\"))\n switches.append(net.addSwitch('s{}'.format(i)))\n net.addLink(docker_hosts[-1], switches[-1])\n cpu_set = cpu_set[0]+2,cpu_set[1]+2\n if cpu_set[1] > 35:\n cpu_set = (0, 1)\ninfo('*** Creating switch links\\n')\nfor s1,s2 in zip(switches[:-1],switches[1:]):\n net.addLink(s1, s2, cls=TCLink, bw=1000)\n\ninfo('*** Starting network\\n')\nnet.start()\n\n\nmaster = docker_hosts[0]\nworkers = docker_hosts[1:]\n\n# StrictHostKeyChecking no\nmaster.cmd(\"\"\"bash -c \"echo '10.0.0.1' >> /usr/local/hadoop/etc/hadoop/masters\" \"\"\")\nfor host in docker_hosts:\n host.cmd(\"\"\"bash -c \"echo ' StrictHostKeyChecking no' >> /etc/ssh/ssh_config\" \"\"\")\n host.cmd(\"service ssh start\")\n host.cmd(\"\"\"bash -c \"echo '10.0.0.1 master ' >> /etc/hosts\" \"\"\")\n host.cmd(\"\"\"bash -c \"echo '10.0.0.1 hadoop-master ' >> /etc/hosts\" \"\"\")\n\n\nw_ips=[]\nfor w in workers:\n ip = w.IP()\n w_ips.append(ip)\n master.cmd(\"\"\"bash -c \"echo '{}' >> /usr/local/hadoop/etc/hadoop/slaves\" \"\"\".format(w))\n\n#for wor in workers:\n# for ip in w_ips:\n# wor.cmd(\"\"\"bash -c \"echo '{}' >> /usr/local/hadoop/etc/hadoop/slaves\" \"\"\".format(w))\n\nfor wor in docker_hosts:\n wor.cmd(\"\"\"bash -c \"echo '10.0.0.1 d1' >> /etc/hosts\" \"\"\".format(w))\n for w in workers:\n wor.cmd(\"\"\"bash -c \"echo '{} {}' >> /etc/hosts\" \"\"\".format(w.IP(), w))\n\n wor.cmd(\"\"\"bash -c \"echo '{}' >> /usr/local/hadoop/etc/hadoop/slaves\" \"\"\".format(w))\n\ninfo (\"# DO PINGALL\\n\")\nnet.pingAllFull()\n\ninfo (\"# Start Hadoop in the cluster\\n\")\ninfo (\"# Format HDFS\\n\")\ninfo (master.cmd('bash -c \"/usr/local/hadoop/bin/hdfs namenode -format -force\"'))\nsleep(2)\ninfo (\"# Launch HDFS\\n\")\ninfo (master.cmd('bash -c \"/usr/local/hadoop/sbin/start-dfs.sh\"'))\nsleep(2)\ninfo (\"# Launch YARN\\n\")\ninfo (master.cmd('bash -c \"/usr/local/hadoop/sbin/start-yarn.sh\"'))\nsleep(2)\ninfo (\"# Create a directory for the user\\n\")\ninfo (master.cmd('bash -c \"/usr/local/hadoop/bin/hdfs dfs -mkdir -p /user/root\"'))\nsleep(2)\npi_cmd=\"hadoop jar /usr/local/hadoop/share/hadoop/mapreduce/hadoop-mapreduce-examples-2.7.2.jar pi 400 400\"\ninfo (master.cmd(pi_cmd))\n\n\ninfo('*** Running CLI\\n')\n#CLI(net)\ninfo('*** Stopping network')\nnet.stop()\n\n\n'''\nw_ips=[]\nfor w in workers:\n ip = w.IP()\n w_ips.append(ip)\n master.cmd(\"\"\"bash -c \"echo '{}' >> /root/hadoop-2.7.6/etc/hadoop/slaves\" \"\"\".format(ip))\n\nfor wor in workers:\n for ip in w_ips:\n wor.cmd(\"\"\"bash -c \"echo '{}' >> /root/hadoop-2.7.6/etc/hadoop/slaves\" \"\"\".format(ip))\n\n\ninfo (\"# Start Hadoop in the cluster\\n\")\ninfo (\"# Format HDFS\\n\")\ninfo (master.cmd('bash -c \"/root/hadoop-2.7.6/bin/hdfs namenode -format -force\"'))\nsleep(2)\ninfo (\"# Launch HDFS\\n\")\ninfo (master.cmd('bash -c \"/root/hadoop-2.7.6/sbin/start-dfs.sh\"'))\nsleep(2)\ninfo (\"# Launch YARN\\n\")\ninfo (master.cmd('bash -c \"/root/hadoop-2.7.6/sbin/start-yarn.sh\"'))\nsleep(2)\ninfo (\"# Create a directory for the user\\n\")\ninfo (master.cmd('bash -c \"/root/hadoop-2.7.6/bin/hdfs dfs -mkdir -p /user/root\"'))\nsleep(1)\npi_cmd=\"/root/hadoop-2.7.6/bin/hadoop jar /root/hadoop-2.7.6/share/hadoop/mapreduce/hadoop-mapreduce-examples-2.7.6.jar pi 20 100\"\n#info (master.cmd(pi_cmd))\ninfo('*** Running CLI\\n')\nCLI(net)\ninfo('*** Stopping network')\nnet.stop()\n'''\n","sub_path":"examples/hadoop.py","file_name":"hadoop.py","file_ext":"py","file_size_in_byte":4281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"226653530","text":"\"\"\"\nThe maze II 505\nhttps://leetcode.com/articles/the-maze-ii/\nhttps://discuss.leetcode.com/topic/77472/similar-to-the-maze-easy-understanding-java-bfs-solution\nhttps://discuss.leetcode.com/topic/77975/python-solution-with-explanation-dijkstra-s-algorithm/2\n\"\"\"\nfrom sys import maxsize\nfrom queue import Queue\nfrom heapq import heappush, heappop\n\ndef getPath(start, end, maze):\n \"\"\"\n BFS solution\n \"\"\"\n if not maze:\n return -1\n m, n = len(maze), len(maze[0])\n q = Queue()\n q.put(start)\n distance = [[maxsize for _ in range(n)] for _ in range(m)]\n # distance = [maxsize * n] * m # don't usie this, the 4th columns will be all 0\n distance[start[0]][start[1]] = 0\n # distance[0][4] = 0\n # print(distance)\n while not q.empty():\n cur = q.get()\n # print(cur[0], cur[1])\n for dir in [(0,1), (0,-1), (1,0), (-1,0)]:\n x = cur[0]\n y = cur[1]\n count = 0\n while 0<=x+dir[0] xobjetivo:\n x -= 1\n distancia +=1\n else:\n x+=1\n distancia += 1\n while y != yobjetivo:\n if y > yobjetivo:\n y -= 1\n distancia +=1\n else:\n y +=1\n distancia += 1\n return distancia\n\ndef sujeiraMaisProxima(x,y):\n\n #Retorna a posição que existe sujeira\n resultado = np.where(espaco == 2)\n contador = 0\n\n #Retorno do método\n posicaoSujeira = []\n\n #Número estipulado usando tamanho da matriz\n menorDistancia = 6 * 6\n\n #Verifica qual é a sujeira mais proxima da posicao x y\n while contador < len(resultado[0]):\n sujeira = [resultado[0][contador], resultado[1][contador]]\n d = calcularDistancia(y,x,sujeira[0], sujeira[1])\n if (d < menorDistancia):\n menorDistancia = d\n posicaoSujeira.clear()\n posicaoSujeira.append(sujeira[0])\n posicaoSujeira.append(sujeira[1])\n contador += 1\n\n return posicaoSujeira\n\ndef posicaoMaisProximaSujeira(x, y, sujeira, espaco):\n\n #Todos as posições adjacentes da posição atual (x,y) que não são paredes\n listaAdjacente = []\n\n abaixo = [x, y + 1]\n acima = [x, y -1]\n esquerda = [x - 1,y]\n direita =[x+1, y]\n\n # Número estipulado usando tamanho da matriz\n menorDistancia = 6 * 6\n\n #Retorno do método\n retornoAdjacente = []\n\n if(espaco[acima[1]][acima[0]] != 1):\n #Posicao x, y e acao\n adjacente = [acima[1], acima[0], 0]\n listaAdjacente.append(adjacente)\n if(espaco[abaixo[1]][abaixo[0]] != 1):\n # Posicao x, y e acao\n adjacente = [abaixo[1], abaixo[0], 1]\n listaAdjacente.append(adjacente)\n if (espaco[esquerda[1]][esquerda[0]] != 1):\n # Posicao x, y e acao\n adjacente = [esquerda[1], esquerda[0], 2]\n listaAdjacente.append(adjacente)\n if (espaco[direita[1]][direita[0]] != 1):\n # Posicao x, y e acao\n adjacente = [direita[1], direita[0], 3]\n listaAdjacente.append(adjacente)\n\n #Buscar posição adjacente com menor distância da sujeira\n for item in listaAdjacente:\n d = calcularDistancia(item[0], item[1], sujeira[0], sujeira[1])\n if(d < menorDistancia):\n menorDistancia = d\n retornoAdjacente.clear()\n retornoAdjacente.append(item[0])\n retornoAdjacente.append(item[1])\n retornoAdjacente.append(item[2])\n\n return retornoAdjacente\n\ndef agenteObjetivo(x, y, estado, objObtido, espaco, sujeira):\n acoes = [\"acima\", \"abaixo\", \"esquerda\", \"direita\", \"aspirar\", \"NoOp\"]\n\n if(objObtido == 0):\n return acoes[5]\n elif (estado == 2):\n return acoes[4]\n\n #Verifica qual é o próximo passo\n proximaPosicao = posicaoMaisProximaSujeira(x,y, sujeira, espaco)\n\n return acoes[proximaPosicao[2]]\n\ndef checkObj(espaco):\n for lista in espaco:\n for elemento in lista:\n if(elemento == 2):\n return 1\n return 0\n\ndef geraAmbiente():\n pass\n\n#Pergunta\nagente = input(\"Escolha um agente: Agente Reativo Simples (1) ou Agente Baseado em Objetivo(2)\")\n\n# Gera o espaço da sala como uma matriz 6x6\nespaco = [[0 for n in range(7)] for n in range(7)]\n\n# Gera sujeira\nespaco = (np.random.rand(7, 7) > 0.7) * 2\n\n# Delimita as paredes\nfor y in [0, 6]:\n for x in range(7):\n espaco[y][x] = 1\n espaco[x][y] = 1\n\n#Pegar perceppção\nposxy = [1, 1]\n\n# Variáveis de mapeamento do ultimo movimento\nx_dir = 1 # 0 = esquerda, 1 = direita\ny_dir = 1 # 0 = acima, 1 = abaixo\n\npontos = 0\nsujeira = 0\n\n# Execução do ambiente\nwhile True:\n\n #Verifica qual agente utilizar\n if(agente == \"1\"):\n acao = agenteReativoSimples(posxy[0], posxy[1],espaco[posxy[1]][posxy[0]])\n elif(agente == \"2\"):\n\n #Verifica se ainda tem sujeira\n check = checkObj(espaco)\n\n #Busca sujeira mais próxima da posição atual\n if(sujeira == 0):\n sujeira = sujeiraMaisProxima(posxy[0], posxy[1])\n\n percepcao = espaco[posxy[1]][posxy[0]]\n acao = agenteObjetivo(posxy[0], posxy[1], percepcao, check, espaco, sujeira)\n\n\n if(acao != \"NoOp\"):\n pontos += 1\n print(f\"Estado da percepcao: {percepcao} Ação escolhida: {acao}\")\n if(acao == \"aspirar\"):\n sujeira = 0\n\n\n #Verifica as ações\n if(acao == \"acima\"):\n posxy = [posxy[0], (posxy[1]-1)]\n elif(acao == \"abaixo\"):\n posxy = [posxy[0], (posxy[1]+1)]\n elif(acao == \"esquerda\"):\n posxy = [(posxy[0]-1), posxy[1]]\n elif(acao == \"direita\"):\n posxy = [(posxy[0]+1), posxy[1]]\n elif(acao == \"aspirar\"):\n espaco[posxy[1]][posxy[0]] = 0\n elif(acao == \"NoOp\"):\n print(f\"Pontos: {pontos}\")\n break\n exibir(espaco)\n\n#A sua solução é extensível para um mundo 3 x 3? E para um mundo 6 x 6? Explique sua resposta.\n#No momento não funcionado com mundos diferentes de 6x6 porem a solução é extensivel para mundos de tamanhos diferentes a partir de pequenas adaptações no código\n#Exemplo: Linha 170: está criando uma matriz 6x6\n#Exeplo: Linha 176: criando parades para um mundo 6x6\n#Entre outras modificações que poderiam receber outro valor\n\n#É possível ter todo o espaço limpo efetivamente? Justifique sua resposta.\n#Sim. É sempre verificado se ainda há sujeira no tabuleiro e é sempre verificado a menor distancia ta posição até a sujeira","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"231241377","text":"#!/usr/bin/env python3\nSomething\nimport wpilib\nfrom wpilib.drive import DifferentialDrive\n\n\nclass MyRobot(wpilib.SampleRobot):\n\n def robotInit(self):\n self.frontLeft = wpilib.Talon(0)\n self.rearLeft = wpilib.Talon(1)\n self.left = wpilib.SpeedControllerGroup(self.frontLeft, self.rearLeft)\n\n self.frontRight = wpilib.Talon(2)\n self.rearRight = wpilib.Talon(3)\n self.right = wpilib.SpeedControllerGroup(self.frontRight, self.rearRight)\n\n self.drive = DifferentialDrive(self.left, self.right)\n self.stick2 = wpilib.Joystick(0)\n self.stick = wpilib.Joystick(1)\n\n def disabled(self):\n while self.isDisabled():\n wpilib.Timer.delay(0.01)\n\n def operatorControl(self):\n timer = wpilib.Timer()\n timer.start()\n i = -1\n while self.isOperatorControl() and self.isEnabled():\n # if self.stick.getRawButton(2):\n # # self.drive.arcadeDrive(self.stick.getY(), self.stick.getX())\n # self.drive.arcadeDrive(1, 0)\n # # self.drive.tankDrive(self.stick.getY() * -0.7, self.stick2.getY() * -0.7, True)\n # else:\n # # self.drive.arcadeDrive(self.stick.getY(), self.stick.getX())\n # self.drive.arcadeDrive(1, 0)\n # # self.drive.tankDrive(self.stick.getY() * 0.7, self.stick2.getY() * 0.7, True)\n # # i = i * self.stick.getRawAxis(4)\n # # Move a motor with a Joystick\n self.drive.arcadeDrive(0.4, 0)\n\n if timer.hasPeriodPassed(1.0):\n print(\"Analog 8: %s\" % self.ds.getBatteryVoltage())\n\n wpilib.Timer.delay(0.02)\n\n def autonomous(self):\n timer = wpilib.Timer()\n timer.start()\n while self.isAutonomous() and self.isEnabled():\n if timer.get() < 3.0:\n self.drive.tankDrive(-0.1, -1)\n else:\n self.drive.tankDrive(0., 0)\n\n wpilib.Timer.delay(0.01)\n\n\nif __name__ == '__main__':\n wpilib.run(MyRobot)\n","sub_path":"robot_backup.py","file_name":"robot_backup.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"138443094","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the saveThePrisoner function below.\ndef saveThePrisoner(prisoners, sweets, chair):\n rem_sweets = sweets%prisoners\n chair_reached = chair+rem_sweets-1\n if chair_reached%prisoners == 0:\n return prisoners\n elif chair_reached%prisoners > 0:\n return chair_reached%prisoners\n else:\n return chair_reached\n\n\n \nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n t = int(input())\n\n for t_itr in range(t):\n nms = input().split()\n\n n = int(nms[0])\n\n m = int(nms[1])\n\n s = int(nms[2])\n\n result = saveThePrisoner(n, m, s)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","sub_path":"Easy/SaveThePrisoners.py","file_name":"SaveThePrisoners.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"529875981","text":"# polos.py\n\nclass Polo():\n def __init__(self, color, size, price=99.00, style=None):\n self.color = color\n self.size = size\n self.price = price\n self.style = style\n\nif __name__ == \"__main__\":\n\n #df = DataFrame(...)\n # df.head()\n polo1 = Polo(color=\"Blue\", size=\"L\", price=4.99) # a new \"instance\" of the class\n print(polo1.color)\n print(polo1.price)\n\n polo2 = Polo(color=\"Yello\", size=\"Small\") # a new \"instance\" of the class\n print(polo2.color)\n print(polo2.price)","sub_path":"polos.py","file_name":"polos.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"550366947","text":"from dataclasses import dataclass\n\nimport numpy as np\nfrom qibo.config import log, raise_error\n\nfrom qibolab.instruments.port import Port\n\nFREQUENCY_LIMIT = 500e6\n\n\n@dataclass\nclass QbloxOutputPort_Settings:\n channel: str = None\n qubit: str = None\n attenuation: int = 60\n offset: float = 0.0\n hardware_mod_en: bool = True\n gain: float = 1.0\n nco_freq: int = 0\n nco_phase_offs: float = 0\n\n\n@dataclass\nclass ClusterRF_OutputPort_Settings(QbloxOutputPort_Settings):\n lo_enabled: bool = True\n lo_frequency: int = 2_000_000_000\n\n\n@dataclass\nclass ClusterBB_OutputPort_Settings(QbloxOutputPort_Settings):\n pass\n\n\n@dataclass\nclass QbloxInputPort_Settings:\n channel: str = None\n acquisition_hold_off: int = 0\n acquisition_duration: int = 1000\n hardware_demod_en: bool = True\n\n\nclass QbloxOutputPort(Port):\n \"\"\"qibolab.instruments.port.Port interface implementation for Qblox instruments\"\"\"\n\n def __init__(self, module, sequencer_number: int, number: int):\n self.module = module\n self.sequencer_number: int = sequencer_number\n self.port_number: int = number - 1\n self.channel = None # To be discontinued\n self.qubit = None # To be discontinued\n\n self._settings = QbloxOutputPort_Settings()\n\n @property\n def attenuation(self) -> str:\n \"\"\"Attenuation that is applied to this port.\"\"\"\n if self.module.device:\n self._settings.attenuation = self.module.device.get(f\"out{self.port_number}_att\")\n return self._settings.attenuation\n\n @attenuation.setter\n def attenuation(self, value):\n if isinstance(value, (float, np.floating)):\n value = int(value)\n if isinstance(value, (int, np.integer)):\n if value > 60:\n log.warning(f\"Qblox attenuation needs to be between 0 and 60 dB. Adjusting {value} to 60dB\")\n value = 60\n\n elif value < 0:\n log.warning(f\"Qblox attenuation needs to be between 0 and 60 dB. Adjusting {value} to 0\")\n value = 0\n\n if (value % 2) != 0:\n log.warning(\n f\"Qblox attenuation needs to be a multiple of 2 dB. Adjusting {value} to {round(value/2) * 2}\"\n )\n value = round(value / 2) * 2\n else:\n raise_error(ValueError, f\"Invalid attenuation {value}\")\n\n self._settings.attenuation = value\n if self.module.device:\n self.module._set_device_parameter(self.module.device, f\"out{self.port_number}_att\", value=value)\n\n @property\n def offset(self):\n \"\"\"DC offset that is applied to this port.\"\"\"\n if self.module.device:\n self._settings.offset = self.module.device.get(f\"out{self.port_number}_offset\")\n return self._settings.offset\n\n @offset.setter\n def offset(self, value):\n if isinstance(value, (int, np.integer)):\n value = float(value)\n if isinstance(value, (float, np.floating)):\n if value > 2.5:\n log.warning(f\"Qblox offset needs to be between -2.5 and 2.5 V. Adjusting {value} to 2.5 V\")\n value = 2.5\n\n elif value < -2.5:\n log.warning(f\"Qblox offset needs to be between -2.5 and 2.5 V. Adjusting {value} to -2.5 V\")\n value = -2.5\n else:\n raise_error(ValueError, f\"Invalid offset {value}\")\n\n self._settings.offset = value\n if self.module.device:\n self.module._set_device_parameter(self.module.device, f\"out{self.port_number}_offset\", value=value)\n\n # Additional attributes needed by the driver\n @property\n def hardware_mod_en(self):\n \"\"\"Flag to enable hardware modulation.\"\"\"\n if self.module.device:\n self._settings.hardware_mod_en = self.module.device.sequencers[self.sequencer_number].get(f\"mod_en_awg\")\n return self._settings.hardware_mod_en\n\n @hardware_mod_en.setter\n def hardware_mod_en(self, value):\n if not isinstance(value, bool):\n raise_error(ValueError, f\"Invalid hardware_mod_en {value}\")\n\n self._settings.hardware_mod_en = value\n if self.module.device:\n self.module._set_device_parameter(\n self.module.device.sequencers[self.sequencer_number], \"mod_en_awg\", value=value\n )\n\n @property\n def nco_freq(self):\n \"\"\"nco_freq that is applied to this port.\"\"\"\n\n if self.module.device:\n self._settings.nco_freq = self.module.device.sequencers[self.sequencer_number].get(f\"nco_freq\")\n\n return self._settings.nco_freq\n\n @nco_freq.setter\n def nco_freq(self, value):\n if isinstance(value, (float, np.floating)):\n value = int(value)\n if isinstance(value, (int, np.integer)):\n if value > FREQUENCY_LIMIT:\n log.warning(\n f\"Qblox nco_freq needs to be between -{FREQUENCY_LIMIT} and {FREQUENCY_LIMIT} MHz. Adjusting {value} to {FREQUENCY_LIMIT} MHz\"\n )\n value = int(FREQUENCY_LIMIT)\n\n elif value < -FREQUENCY_LIMIT:\n log.warning(\n f\"Qblox nco_freq needs to be between -{FREQUENCY_LIMIT} and {FREQUENCY_LIMIT} MHz. Adjusting {value} to -{FREQUENCY_LIMIT} MHz\"\n )\n value = int(-FREQUENCY_LIMIT)\n else:\n raise_error(ValueError, f\"Invalid nco_freq {value}\")\n\n self._settings.nco_freq = value\n if self.module.device:\n self.module._set_device_parameter(\n self.module.device.sequencers[self.sequencer_number], \"nco_freq\", value=value\n )\n\n @property\n def nco_phase_offs(self):\n \"\"\"nco_phase_offs that is applied to this port.\"\"\"\n\n if self.module.device:\n self._settings.nco_phase_offs = self.module.device.sequencers[self.sequencer_number].get(f\"nco_phase_offs\")\n return self._settings.nco_phase_offs\n\n @nco_phase_offs.setter\n def nco_phase_offs(self, value):\n if isinstance(value, (int, np.integer)):\n value = float(value)\n if isinstance(value, (float, np.floating)):\n value = value % 360\n else:\n raise_error(ValueError, f\"Invalid nco_phase_offs {value}\")\n\n self._settings.nco_phase_offs = value\n if self.module.device:\n self.module._set_device_parameter(\n self.module.device.sequencers[self.sequencer_number], \"nco_phase_offs\", value=value\n )\n\n\nclass ClusterRF_OutputPort(QbloxOutputPort):\n def __init__(self, module, sequencer_number: int, number: int):\n super().__init__(module, sequencer_number, number)\n self._settings = ClusterRF_OutputPort_Settings()\n\n @property\n def lo_enabled(self):\n \"\"\"Flag to enable local oscillator.\"\"\"\n\n if self.module.device:\n if self.module.device.is_qrm_type:\n self._settings.lo_enabled = self.module.device.get(f\"out{self.port_number}_in{self.port_number}_lo_en\")\n elif self.module.device.is_qcm_type:\n self._settings.lo_enabled = self.module.device.get(f\"out{self.port_number}_lo_en\")\n return self._settings.lo_enabled\n\n @lo_enabled.setter\n def lo_enabled(self, value):\n if not isinstance(value, bool):\n raise_error(ValueError, f\"Invalid lo_enabled {value}\")\n\n self._settings.lo_enabled = value\n if self.module.device:\n if self.module.device.is_qrm_type:\n self.module._set_device_parameter(\n self.module.device, f\"out{self.port_number}_in{self.port_number}_lo_en\", value=value\n )\n elif self.module.device.is_qcm_type:\n self.module._set_device_parameter(self.module.device, f\"out{self.port_number}_lo_en\", value=value)\n\n @property\n def lo_frequency(self):\n \"\"\"Local oscillator frequency for the given port.\"\"\"\n if self.module.device:\n if self.module.device.is_qrm_type:\n self._settings.lo_frequency = self.module.device.get(\n f\"out{self.port_number}_in{self.port_number}_lo_freq\"\n )\n elif self.module.device.is_qcm_type:\n self._settings.lo_frequency = self.module.device.get(f\"out{self.port_number}_lo_freq\")\n return self._settings.lo_frequency\n\n @lo_frequency.setter\n def lo_frequency(self, value):\n if isinstance(value, (float, np.floating)):\n value = int(value)\n if isinstance(value, (int, np.integer)):\n if value > 18e9:\n log.warning(f\"Qblox lo_frequency needs to be between 2e9 and 18e9 Hz. Adjusting {value} to 18e9 Hz\")\n value = int(18e9)\n\n elif value < 2e9:\n log.warning(f\"Qblox lo_frequency needs to be between 2e9 and 18e9 Hz. Adjusting {value} to 2e9 Hz\")\n value = int(2e9)\n else:\n raise_error(ValueError, f\"Invalid lo-frequency {value}\")\n\n self._settings.lo_frequency = value\n if self.module.device:\n if self.module.device.is_qrm_type:\n self.module._set_device_parameter(\n self.module.device, f\"out{self.port_number}_in{self.port_number}_lo_freq\", value=value\n )\n elif self.module.device.is_qcm_type:\n self.module._set_device_parameter(self.module.device, f\"out{self.port_number}_lo_freq\", value=value)\n\n # Note: for qublos, gain is equivalent to amplitude, since it does not bring any advantages\n # we plan to remove it soon.\n @property\n def gain(self):\n \"\"\"Gain that is applied to this port.\"\"\"\n\n if self.module.device:\n self._settings.gain = self.module.device.sequencers[self.sequencer_number].get(f\"gain_awg_path0\")\n return self._settings.gain\n\n @gain.setter\n def gain(self, value):\n if isinstance(value, (int, np.integer)):\n value = float(value)\n if isinstance(value, (float, np.floating)):\n if value > 1.0:\n log.warning(f\"Qblox offset needs to be between -1 and 1. Adjusting {value} to 1\")\n value = 1.0\n\n elif value < -1.0:\n log.warning(f\"Qblox offset needs to be between -1 and 1. Adjusting {value} to -1\")\n value = -1.0\n else:\n raise_error(ValueError, f\"Invalid offset {value}\")\n\n self._settings.gain = value\n if self.module.device:\n self.module._set_device_parameter(\n self.module.device.sequencers[self.sequencer_number], \"gain_awg_path0\", \"gain_awg_path1\", value=value\n )\n\n\nclass ClusterBB_OutputPort(QbloxOutputPort):\n # Note: for qblox, gain is equivalent to amplitude, since it does not bring any advantages\n # we plan to remove it soon.\n\n def __init__(self, module, sequencer_number: int, number: int):\n super().__init__(module, sequencer_number, number)\n self._settings = ClusterBB_OutputPort_Settings()\n\n @property\n def gain(self):\n \"\"\"Gain that is applied to this port.\"\"\"\n\n if self.module.device:\n self._settings.gain = self.module.device.sequencers[self.sequencer_number].get(f\"gain_awg_path0\")\n return self._settings.gain\n\n @gain.setter\n def gain(self, value):\n if isinstance(value, (int, np.integer)):\n value = float(value)\n if isinstance(value, (float, np.floating)):\n if value > 1.0:\n log.warning(f\"Qblox offset needs to be between -1 and 1. Adjusting {value} to 1\")\n value = 1.0\n\n elif value < -1.0:\n log.warning(f\"Qblox offset needs to be between -1 and 1. Adjusting {value} to -1\")\n value = -1.0\n else:\n raise_error(ValueError, f\"Invalid offset {value}\")\n\n self._settings.gain = value\n if self.module.device:\n self.module._set_device_parameter(\n self.module.device.sequencers[self.sequencer_number], \"gain_awg_path0\", value=value\n )\n\n\nclass QbloxInputPort:\n def __init__(self, module, output_sequencer_number: int, input_sequencer_number: int, number: int):\n self.module = module\n self.output_sequencer_number: int = output_sequencer_number\n self.input_sequencer_number: int = input_sequencer_number\n self.port_number: int = number - 1\n self.channel = None # To be discontinued\n self.qubit = None # To be discontinued\n\n self.acquisition_hold_off = 4 # To be discontinued\n\n self._settings = QbloxInputPort_Settings()\n\n @property\n def hardware_demod_en(self):\n \"\"\"Flag to enable hardware demodulation.\"\"\"\n\n if self.module.device:\n self._settings.hardware_demod_en = self.module.device.sequencers[self.input_sequencer_number].get(\n f\"demod_en_acq\"\n )\n return self._settings.hardware_demod_en\n\n @hardware_demod_en.setter\n def hardware_demod_en(self, value):\n if not isinstance(value, bool):\n raise_error(ValueError, f\"Invalid hardware_demod_en {value}\")\n\n self._settings.hardware_demod_en = value\n if self.module.device:\n self.module._set_device_parameter(\n self.module.device.sequencers[self.input_sequencer_number], \"demod_en_acq\", value=value\n )\n\n @property\n def acquisition_duration(self):\n \"\"\"Duration of the pulse acquisition, in ns. It must be > 0 and multiple of 4.\"\"\"\n\n if self.module.device:\n self._settings.acquisition_duration = self.module.device.sequencers[self.output_sequencer_number].get(\n f\"integration_length_acq\"\n )\n return self._settings.acquisition_duration\n\n @acquisition_duration.setter\n def acquisition_duration(self, value):\n if isinstance(value, (float, np.floating)):\n value = int(value)\n if isinstance(value, (int, np.integer)):\n if value < 4:\n log.warning(f\"Qblox hardware_demod_en needs to be > 4ns. Adjusting {value} to 4 ns\")\n value = 4\n if (value % 4) != 0:\n log.warning(\n f\"Qblox hardware_demod_en needs to be a multiple of 4 ns. Adjusting {value} to {round(value/4) * 4}\"\n )\n value = round(value / 4) * 4\n\n else:\n raise_error(ValueError, f\"Invalid acquisition_duration {value}\")\n\n self._settings.acquisition_duration = value\n if self.module.device:\n self.module._set_device_parameter(\n self.module.device.sequencers[self.output_sequencer_number], \"integration_length_acq\", value=value\n )\n","sub_path":"src/qibolab/instruments/qblox/port.py","file_name":"port.py","file_ext":"py","file_size_in_byte":14799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"609812986","text":"import os\nimport urllib\nimport zipfile\nimport pandas as pd\n\ndef make_tmp(tmp='tmp'):\n if not os.path.exists(tmp):\n os.mkdir(tmp)\n\ndef download(filename):\n url = 'http://www.mercadopublico.cl/Portal/att.ashx?id=5'\n urllib.urlretrieve(url, filename)\n\ndef extractfiles(filename, tempdir):\n zip_ref = zipfile.ZipFile(filename, 'r')\n zip_ref.extractall(tempdir)\n zip_ref.close()\n\ndef get_data(tempdir):\n name = 'Licitacion_Publicada.csv'\n filename = os.path.join(tempdir, name)\n aux = pd.read_csv(filename, skiprows=3)\n return aux\n\ndef get_codes(df, pattern):\n aux = pd.np.array([])\n if type(pattern) is str:\n pattern = [pattern]\n for p in pattern:\n for x in df.columns[2:5]:\n a = df[df[x].str.contains(p, case=False)].rbiGoodAndService.unique()\n aux = pd.np.append(aux, a)\n return pd.np.unique(aux)\n\ndef main():\n tempdir = 'tmp'\n make_tmp(tempdir)\n filename = os.path.join(tempdir, 'filename.zip')\n download(filename)\n extractfiles(filename, tempdir)\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"mp.py","file_name":"mp.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"451470266","text":"from datetime import datetime\n\nfrom django.db.models import Q\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\nfrom django.utils.deprecation import MiddlewareMixin\n\nfrom user.models import UserTicketModel\n\n\nclass UserAuthMiddle(MiddlewareMixin):\n\n def process_request(self, request):\n # 个人中心 商品增加删除 购物车\n need_login = ['/axf/mine/', '/axf/addCart/', '/axf/delCart/', '/axf/cart/', '/axf/selectAll/',\n '/axf/changeCartState/', '/axf/showMoney/', '/axf/pay/', '/axf/clearAll/',\n '/axf/orderListWaitPay/', '/axf/orderListPayed/',\n ]\n if request.path in need_login:\n ticket = request.COOKIES.get('ticket')\n if not ticket:\n return HttpResponseRedirect(reverse('user:login'))\n user_ticket = UserTicketModel.objects.filter(ticket=ticket).first()\n if user_ticket:\n if datetime.utcnow() > user_ticket.out_time.replace(tzinfo=None):\n UserTicketModel.objects.filter(user=user_ticket.user).delete()\n return HttpResponseRedirect(reverse('user:login'))\n else:\n request.user = user_ticket.user\n UserTicketModel.objects.filter(Q(user=user_ticket.user) & ~Q(ticket=ticket)).delete()\n\n else:\n return HttpResponseRedirect(reverse('user:login'))\n\n else:\n return None","sub_path":"爱鲜蜂项目/utils/UserAuthMiddleware.py","file_name":"UserAuthMiddleware.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"87929595","text":"from django import forms\n\nfrom .models import Product\n\nclass ProductForm(forms.ModelForm):\n\ttitle = forms.CharField(label = '',\n\t\twidget = forms.TextInput(attrs = {\"placeholder\": \"Your title\"}))\n\tdescription = forms.CharField(\n\t\t\t\t\t\trequired = False,\n\t\t\t\t\t\twidget = forms.Textarea(\n\t\t\t\t\t\t\tattrs={\n\t\t\t\t\t\t\t\"class\": \"new_class_name\",\n\t\t\t\t\t\t\t\"id\": \"my_id_for_textarea\",\n\t\t\t\t\t\t\t\"rows\": 20,\n\t\t\t\t\t\t\t\"cols\":50\n\t\t\t\t\t\t\t}))\n\n\tclass Meta: \n\t\tmodel = Product\n\t\tfields = [\n\t\t\t'title',\n\t\t\t'description',\n\t\t\t'price']\n\n\tdef clean_title(self, *args, **kwargs):\n\t\ttitle = self.cleaned_data.get(\"title\")\n\t\tif not \"CFE\" in title: \n\t\t\traise forms.ValidationError(\"this is not a valid title\")\n\t\telse: \n\t\t\treturn title\n\n\n\nclass RawProductForm(forms.Form):\n\ttitle = forms.CharField(label = '', widget = forms.TextInput(attrs = {\"placeholder\": \"your title\"}))\n\tdescription = forms.CharField(\n\t\t\t\t\t\trequired = False,\n\t\t\t\t\t\twidget = forms.Textarea(\n\t\t\t\t\t\t\tattrs={\n\t\t\t\t\t\t\t\"class\": \"new_class_name\",\n\t\t\t\t\t\t\t\"id\": \"my_id_for_textarea\",\n\t\t\t\t\t\t\t\"rows\": 10,\n\t\t\t\t\t\t\t\"cols\":10\n\t\t\t\t\t\t\t}))\n\tprice = forms.DecimalField(initial = 99.99)\n","sub_path":"products/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"618257629","text":"import nibabel as nib\nimport numpy as np\nimport os\nfrom os.path import join\nfrom src.utils.preprocessing import flip_plane, normalize_image\n\nto_int = lambda b: 1 if b else 0\n\nclass Subject:\n def __init__(self,\n data_path,\n id):\n\n self.data_path = data_path\n self._id = id\n\n self.subject_filepath = join(self.data_path, self.id)\n\n self.T2_FILE = join(self.subject_filepath,'T2.nii.gz')\n self.T1_FILE = join(self.subject_filepath,'T1.nii.gz')\n self.GT_FILE = join(self.subject_filepath,'label.nii.gz')\n self.ROIMASK_FILE = join(self.subject_filepath,'mask.nii.gz')\n\n self.data_augmentation = False\n\n\n\n @property\n def id(self):\n return self._id\n\n def get_affine(self):\n return nib.load(self.T1_FILE).affine\n\n def load_channels(self, normalize=False):\n modalities = []\n modalities.append(nib.load(self.T2_FILE))\n modalities.append(nib.load(self.T1_FILE))\n\n channels = np.zeros(modalities[0].shape + (2,), dtype=np.float32)\n\n for index_mod, mod in enumerate(modalities):\n if self.data_augmentation:\n channels[:, :, :, index_mod] = flip_plane(np.asarray(mod.dataobj), plane=self.data_augmentation)\n else:\n channels[:,:,:,index_mod] = np.asarray(mod.dataobj)\n\n if normalize:\n channels[:, :, :, index_mod] = normalize_image(channels[:,:,:,index_mod], mask = self.load_ROI_mask() )\n\n\n return channels\n\n def load_labels(self):\n labels_proxy = nib.load(self.GT_FILE)\n\n if self.data_augmentation:\n labels = flip_plane(np.asarray(labels_proxy.dataobj), plane=self.data_augmentation)\n else:\n labels = np.asarray(labels_proxy.dataobj)\n\n unique_labels = np.unique(labels)\n unique_labels = np.sort(unique_labels)\n for it_u_l, u_l in enumerate(unique_labels):\n labels[np.where(labels == u_l)] = it_u_l\n return labels\n\n def load_ROI_mask(self):\n\n roimask_proxy = nib.load(self.ROIMASK_FILE)\n if self.data_augmentation:\n mask = flip_plane(np.asarray(roimask_proxy.dataobj), plane=self.data_augmentation)\n else:\n mask = np.asarray(roimask_proxy.dataobj)\n\n return mask.astype('bool')\n\n\n def get_subject_shape(self):\n\n proxy = nib.load(self.T1_FILE)\n return proxy.shape\n\n\nclass Loader():\n\n def __init__(self, data_path):\n self.data_path = data_path\n\n @staticmethod\n def create(config_dict):\n return Loader(config_dict['data_dir'])\n\n def load_subject(self, id):\n subject = Subject(id, self.data_path)\n\n return subject\n\n\n def load_subjects(self):\n\n subject_list = []\n data_path = self.data_path\n if not isinstance(self.data_path, list):\n data_path = [data_path]\n\n for path in data_path:\n for subject in os.listdir(path):\n subject_list.append(Subject(path,subject))\n\n return subject_list\n\n def _get_value(self, value):\n '''\n Checks that the value is not a nan, and returns None if it is\n '''\n if value == 'nan':\n return None\n\n if isinstance(value, str):\n # if value.isnumeric():\n # return int(value)\n\n # Check if it can be casted to a float...\n try:\n return float(value)\n except ValueError:\n pass\n\n return value","sub_path":"database/iSeg/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":3538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"210875998","text":"import json\nimport scrapy\nimport requests\nfrom pathlib import Path\n\nclass AudioBibleSpider(scrapy.Spider):\n \n\n name = 'audio-bible-full-name'\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n\t\t# change the language version number the three following line\n\t\t# Iu Mien New Roman: 233 ARA: 1608\n self.bible_id = '1957-full'\n self.base_url = \"https://events.bible.com/api/bible/chapter/3.1?id=1957&reference=\"\n self.start_urls = [\n 'https://events.bible.com/api/bible/chapter/3.1?id=1957&reference=GEN.1'\n ]\n\n def parse(self, response):\n print(\"XXXXXXXXXXXXXXXXXXX\")\n print(response)\n data = json.loads(response.body.decode('utf-8'))\n mp3_url = None\n if data['audio'] is not None:\n mp3_url = 'https:' + data['audio'][0]['download_urls']['format_mp3_32k']\n\n\n text = data['content']\n\n if 'verses' not in response.meta:\n verses = {}\n else:\n verses = response.meta['verses']\n\n\n book = data['reference']['human'].split(\" \")\n book.pop(-1)\n book = \" \".join(book)\n chapter = data['reference']['usfm'][0].split(\".\")[1]\n\n next_chapter = data['next']\n if next_chapter is not None:\n next_chapter = next_chapter['usfm'][0]\n\n if book not in verses:\n verses[book] = {}\n\n if chapter not in verses[book]:\n verses[book][chapter] = {}\n\n verses[book][chapter]['mp3'] = mp3_url\n \n\n if next_chapter is None:\n yield verses\n else:\n yield scrapy.Request(\n self.base_url+next_chapter,\n callback=self.parse,\n meta={'verses': verses}\n )\n","sub_path":"bible/spiders/audio-spider-full-name.py","file_name":"audio-spider-full-name.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"132473113","text":"#run command\n#python3 get-nouns-and-label.py 'input/POS-nouns' 'output/POS-output.txt'\n\nimport sys\nimport re\n\ndef listAllFile(fullPath, listSubDir = 0):\n from os import listdir\n from os.path import isfile, join, isdir\n\n onlyfiles = []\n for f in listdir(fullPath):\n tf = join(fullPath, f)\n if isfile(tf):\n onlyfiles.append(tf)\n elif (listSubDir):\n temp = listAllFile(tf, listSubDir)\n onlyfiles = onlyfiles + temp\n return onlyfiles\n\n\nprint('can only find *.POS file')\nprint('')\noutputFile = open(sys.argv[2], 'w+')\nfor f in listAllFile(sys.argv[1], 1):\n if (re.search(\"\\.POS$\", f) != None or re.search(\"\\.pos$\", f) != None):\n print('process file ', f)\n inputData = open(f, 'r').read()\n temp = re.findall(\"[a-zA-Z1-9][a-zA-Z1-9-]+/[A-Z]+\", inputData)\n outputFile.write(\"\\n\".join(temp) + \"\\n\")\n else:\n print(\"no pos file in \", f)\noutputFile.close()\n","sub_path":"get-nouns-and-label.py","file_name":"get-nouns-and-label.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"647610343","text":"def sort(l, n):\n\t# MIN-MAX Variables\n\tMIN, MAX = min(l), max(l)\n\t# OFFSET to count offset from negative end to zero\n\tOFFSET = 0 if MIN >= 0 else -(MIN)+1\n\n\t# If there is a negative no., then add offset\n\tif OFFSET:\n\t\tfor i in range(n):\n\t\t\tl[i] += OFFSET\n\t\tMIN += OFFSET\n\t\tMAX += OFFSET\n\n\t# Count list to store the count of occurences\n\tcount_list = [0]*(MAX-MIN+1)\n\t\n\t# Count the occurences & make if linear by adding previous count\n\tfor i in range(n):\n\t\tcount_list[l[i]-MIN] += 1\n\tfor i in range(1, len(count_list)):\n\t\tcount_list[i] += count_list[i-1]\n\n\t# Create an output array with initial value as OFFSET\n\toutput = [-(OFFSET)]*n\n\tfor i in l:\n\t\toutput[count_list[i-1]-1] += i\n\t\tcount_list[i-1] -= 1\n\n\treturn output\n\n\nif __name__ == \"__main__\":\n # Inputs\n numberList = [23, 6, 3, 7, 34, 9, 55, 1, -4, 4, -3, -3, -2, -100]\n n = len(numberList)\n\n # Unsorted List Output\n print(numberList)\n\n # Sorting List\n numberList = sort(numberList, n)\n\n # Sorted List Output\n print(numberList)","sub_path":"Python/Sorting/CountingSort.py","file_name":"CountingSort.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"335455218","text":"#coding:utf8\nimport tensorflow as tf\n# from cityhash import CityHash64\n\nfrom .flags import *\n\n# 参考这篇博客 如何用 SparseFeature 结合 Dataset 处理离散特征的\n# https://blog.csdn.net/yujianmin1990/article/details/80384994\n# dataset + estimator\n# https://cloud.tencent.com/developer/article/1063010\n\n# instance format: \nclass DataIterator(object):\n\n def __init__(self, params):\n self._params = params\n\n # uid user_features topic ad_features conv\n def decode_csv(self, record):\n # assert length\n records = tf.string_split([record], \"\\t\")\n query_features = tf.string_split(records.values[1:2], \",\")\n\n # user feature\n user_input = tf.string_to_number(query_features.values[:116], tf.int64)\n user_input = tf.mod(user_input, FLAGS.vocab_size)\n user_input = tf.reshape(user_input, [FLAGS.user_input_length])\n\n cross_input = tf.string_to_number(query_features.values[116:], tf.int64)\n cross_input = tf.mod(cross_input, FLAGS.vocab_size)\n cross_input = tf.reshape(cross_input, [FLAGS.cross_input_length])\n\n hist_click_seq = tf.string_to_number(query_features.values[116:121], tf.int64)\n hist_click_seq = tf.mod(hist_click_seq, FLAGS.vocab_size)\n hist_click_seq = tf.reshape(hist_click_seq, [FLAGS.max_hist_click_length])\n\n # 在样本中增加一列 fake data\n hist_click_length = tf.string_to_number(records.values[5], tf.int64)\n\n # ad topic feature\n doc_topic_features = tf.string_split(records.values[2:3], \",\")\n doc_topic_features = tf.string_to_number(doc_topic_features.values, tf.int64)\n doc_topic_features = tf.mod(doc_topic_features, FLAGS.vocab_size)\n doc_topic_features = tf.reshape(doc_topic_features, [FLAGS.cross_input_length])\n\n # ad feature\n doc_features = tf.string_split(records.values[3:4], \",\")\n # campaign shape: B 1\n target_ad = tf.string_to_number(doc_features.values[0], tf.int64)\n target_ad = tf.mod(target_ad, FLAGS.vocab_size)\n\n ad_input = tf.string_to_number(doc_features.values, tf.int64)\n ad_input = tf.mod(ad_input, FLAGS.vocab_size)\n ad_input = tf.reshape(ad_input, [FLAGS.ad_input_length])\n\n # label\n labels = tf.string_to_number(records.values[4:5], tf.float32)\n labels = tf.reshape(labels, [-1])\n\n pcxr = tf.string_to_number(records.values[-1], tf.float32)\n pcxr = tf.reshape(pcxr, [-1])\n # return query_features, doc_features, labels\n # return query_features, doc_topic_features, doc_features, labels\n # return user_input, cross_input, doc_features, labels\n return user_input, cross_input, ad_input, hist_click_seq, hist_click_length, target_ad, labels\n\n def input_fn(self, input_file, shuffle=True):\n params = self._params\n dataset = tf.data.TextLineDataset(input_file)\n if shuffle:\n dataset = dataset.shuffle(buffer_size=params[\"shuffle_buffer_size\"], seed=123)\n dataset = dataset.map(self.decode_csv, num_parallel_calls=params['num_parallel_calls']) \\\n .repeat(params[\"epoch\"]) \\\n .batch(params[\"batch_size\"])\n dataset = dataset.apply(tf.data.experimental.ignore_errors())\n iterator = dataset.make_initializable_iterator()\n return iterator\n\n def hdfs_input_fn(self, input_file, shuffle=True):\n params = self._params\n dataset = tf.data.TextLineDataset.list_files(input_file)\n dataset = dataset.interleave(lambda filename: (tf.data.TextLineDataset(filename)), cycle_length=64)\n if shuffle:\n dataset = dataset.shuffle(buffer_size=params[\"shuffle_buffer_size\"], seed=123)\n dataset = dataset.map(self.decode_csv, num_parallel_calls=params['num_parallel_calls']) \\\n .repeat(params[\"epoch\"]) \\\n .batch(params[\"batch_size\"])\n dataset = dataset.apply(tf.data.experimental.ignore_errors())\n iterator = dataset.make_initializable_iterator()\n return iterator\n","sub_path":"din/src/data_iterator.py","file_name":"data_iterator.py","file_ext":"py","file_size_in_byte":3896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"494172229","text":"import argparse\n\ndef run(args):\n with open(\"./expscripts/{}.sh\".format(args.name), \"w\") as file:\n file.write(\n'#!/bin/bash \\n\\\n# \\n\\\n#$ -N {} \\n\\\n#$ -S /bin/bash \\n\\\n#$ -o /pub/users/xpavlu10/log.txt \\n\\\n#$ -e /pub/users/xpavlu10/err.txt \\n\\\n#$ -q long.q@@gpu \\n\\\n#$ -l ram_free=3500M,mem_free=3500M,gpu=1 \\n\\\n\\n\\\nulimit -a\\n\\\n\\n\\\nulimit -t unlimited \\n\\\n\\n\\\nulimit -a \\n\\\n\\n\\\ncd /pub/users/xpavlu10/conv-tasnet \\n\\\n\\n\\\nunset PYTHONHOME \\n\\\nunset PYTHONPATH \\n\\\n\\n\\\nsource ../anaconda3/bin/activate \\n\\\nconda --version \\n\\\necho \"Enviroment activated\" \\n\\\npython --version \\n\\\n\\n\\\nset -eu \\n\\\ncommment=\"{}\" \\n\\\ncpt_dir=exp/$(date +\"%y-%m-%d-%H-%M-%S\")_$comment \\n\\\n\\n\\\ngpu=0 \\n\\\nmixofmix=1 \\n\\\nknown_percent={} \\n\\\nepochs={} \\n\\\n# constrainted by GPU number & memory \\n\\\nbatch_size={} \\n\\\ncache_size=8 \\n\\\n./nnet/train.py \\\\ \\n\\\n--gpu $gpu \\\\ \\n\\\n--epochs $epochs \\\\ \\n\\\n--batch-size $batch_size \\\\ \\n\\\n--checkpoint $cpt_dir \\\\ \\n\\\n--mixofmix $mixofmix \\\\ \\n\\\n--known_percent $known_percent \\\\ \\n\\\n> ./$cpt_dir.train.log 2>&1'.format(args.name, args.comment, args.known_percent, args.epochs, args.batch_size))\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\n \"Generates experiment script\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\"--name\",\n type=str,\n default=\"\",\n help=\"Name of the experiment script\")\n parser.add_argument(\"--comment\",\n type=str,\n default=\"\",\n help=\"Comment for current experiment\")\n parser.add_argument(\"--batch-size\",\n type=int,\n default=16,\n help=\"Number of utterances in each batch\")\n parser.add_argument(\"--epochs\",\n type=int,\n default=150,\n help=\"Number of training epochs\")\n parser.add_argument(\"--known-percent\",\n type=int,\n default=16,\n help=\"Number of utterances in each batch\")\n args = parser.parse_args()\n \n run(args)","sub_path":"generate_experiment_script.py","file_name":"generate_experiment_script.py","file_ext":"py","file_size_in_byte":2217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"392623482","text":"\nimport tensorflow as tf\nimport numpy as np\nfrom helpers import *\n\nmodelName = 'sat-base'\n\ninput_image = tf.placeholder(tf.float32, shape=(None, 1500, 1500, 3))\nlabel_image = tf.placeholder(tf.float32, shape=(None, 1500, 1500, 1))\n\nis_train = tf.placeholder_with_default(True, ())\nglobal_step = tf.Variable(0, trainable=False)\n\n\nnorm_coef = 0.0005\n\nkeep_prob = tf.cond(is_train, lambda: tf.identity(0.5), lambda: tf.identity(1.0))\n\nlearning_rate = tf.train.exponential_decay(0.0005, global_step, 100, 0.99, staircase=True)\ntf.summary.scalar('learning_rate', learning_rate)\n\n\n\nlayer, bias = conv(input_image, \"conv0\", width=7, stride=2, out_depth=64)\nlayer = tf.nn.relu(layer + bias)\n\nlayer, bias = conv(layer, \"conv1\", width=4, stride=1, out_depth=64)\nlayer = tf.nn.relu(layer + bias)\n\nlayer, bias = conv(layer, \"conv2\", width=7, stride=2, out_depth=128)\nlayer = tf.nn.relu(layer + bias)\n\nlayer, bias = conv(layer, \"conv3\", width=3, stride=1, out_depth=128)\nlayer = tf.nn.relu(layer + bias)\n\nlayer, bias = conv(layer, \"conv4\", width=3, stride=1, out_depth=256)\nlayer = tf.nn.relu(layer + bias)\n\nlayer = tf.nn.dropout(layer, keep_prob, name=\"dropout0\")\n\nlayer, bias = conv(layer, \"conv5\", width=16, stride=2, out_depth=32, transpose=True)\nlayer = tf.nn.relu(layer + bias)\n\nlayer, bias = conv(layer, \"conv6\", width=16, stride=2, out_depth=1, transpose=True)\nlayer = layer + bias\n\nresult = tf.nn.sigmoid(layer)\n\n\nerror = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(layer, label_image))\ntf.summary.scalar('error', error)\n\nfull_error = error + norm_coef * tf.reduce_sum(tf.get_collection(\"l2_losses\"))\ntf.summary.scalar('full_error', full_error)\n\ntrain = tf.train.AdamOptimizer(learning_rate).minimize(full_error, global_step=global_step)\n\n\n# tf.summary.image('input_image', input_image)\n# tf.summary.image('label_image', label_image)\n# tf.summary.image('predicted_image', result)\n\nsummary = tf.summary.merge_all()","sub_path":"model_base.py","file_name":"model_base.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"572531589","text":"# Uses python3\ndef Huge_Fib(n,m):\n v1, v2, v3 = 1, 1, 0 \n for rec in bin(n)[3:]:\n calc = (v2*v2) % m\n v1, v2, v3 = (v1*v1+calc) % m, ((v1+v3)*v2) % m, (calc+v3*v3) % m\n if rec == '1': v1, v2, v3 = (v1+v2) % m, v1, v2\n print(v2) \n\nn,m = map(int, input().split()) \nHuge_Fib(n,m)\n\n","sub_path":"Algorithmic Toolbox/week2_algorithmic_warmup/5_fibonacci_number_again/fibonacci_huge.py","file_name":"fibonacci_huge.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"27879482","text":"#!/usr/bin/env py3\n#coding=utf-8\n# date 2018-12-04 11:08:03\n# author calllivecn \n\n\nimport threading \n\nimport multiprocessing as mp\n\nqueue = mp.Queue()\n\n\ndef thread1(q):\n while True:\n\n if q.empty():\n break\n\n print(q.get())\n\n\n\nth = threading.Thread(target=thread1, args=(queue,))\nth.start()\n\n\nwhile True:\n data = input(\"Enter:\")\n queue.put(data)\n\n","sub_path":"queue__/mutli-queue.py","file_name":"mutli-queue.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"380609433","text":"#NOTE: This is the original code for OSCS, you can edit it as you wish :)\nimport random\n\ngreetings = ['hola', 'hello', 'hi', 'Hi', 'hey!','hey']\n\nquestion = ['What are you?','What is your name?','What can you do?']\nresponses = ['I am OPCS which stands for: Open Source Conversation System, I am ment to be recreated and edited by users']\n\nquestion2 = ['Tell me a joke','Say a joke','']\nresponses2 = ['2 guys walk into a bar, the third one ducks',\"Why didn't the invisible man take the job offer? Because he just couldn't see himself doing it\"]\n\nquestion3 = ['Flip a coin','flip a coin']\nresponses3 = ['The coin landed on heads','The coin landed on tails']\n\nwhile True:\n userInput = input(\">>> \")\n if userInput in greetings:\n random_greeting = random.choice(greetings)\n print(random_greeting)\n elif userInput in question:\n random_response = random.choice(responses)\n print(random_response)\n elif userInput in question2:\n random_response2 = random.choice(responses2)\n print(random_response2)\n elif userInput in question3:\n random_response3 = random.choice(responses3)\n print(random_response3)\n else:\n print(\"I did not understand, try again\")\n \n","sub_path":"OSCS.py","file_name":"OSCS.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"499359228","text":"\nimport random\narr_numbers = list(range(1, 11))\nrandom.shuffle(arr_numbers)\n\ndef merge( arrA, arrB ):\n elements = len( arrA ) + len( arrB )\n merged_arr = [0] * elements\n # TO-DO\n # we iterate over the arrays\n for i in range(0, len(merged_arr)):\n \t# we check if the first array has reached the length of 0, if it has, we append everything on arrB\n if len(arrA) == 0:\n merged_arr.append(arrB[0])\n del arrB[0]\n del merged_arr[0]\n # we check if the second array has reached the length of 0, if it has, we append everything on arrA\n elif len(arrB) == 0:\n merged_arr.append(arrA[0])\n del arrA[0]\n del merged_arr[0]\n # if any of the arrays have reached length of 0...\n else:\n \t# we check if the current value in arrA is greater than value in arrB\n if arrA[0] > arrB[0]:\n \t# if it is, we append the current the current value in arrB\n merged_arr.append(arrB[0])\n # and remove the value from the array\n del arrB[0]\n del merged_arr[0]\n # we check if the current value in arrA is less than value in arrB\n elif arrA[0] < arrB[0]:\n \t# if it is, we append the current the current value in arrA\n merged_arr.append(arrA[0])\n # and remove the value from the array\n del arrA[0]\n del merged_arr[0]\n\n return merged_arr\n\ndef merge_sort(arr):\n # first thing we need to do is split the array in the middle as long as the array is greater than 0\n\n # BASES CASES\n if len(arr) == 1:\n return arr\n if len(arr) == 0:\n \treturn arr\n else:\n # we declare our middle\n middle = len(arr) // 2\n # we call recursively and set arrA to be the array's middle, all the way until to reaches length of 1\n arrA = merge_sort(arr[:middle])\n # we call recursively and set arrB to be the array's middle, all the way until to reaches length of 1\n arrB = merge_sort(arr[middle:])\n\n return merge(arrA, arrB)\n\n# STRETCH: implement an in-place merge sort algorithm\ndef merge_in_place(arr, start, mid, end):\n # TO-DO\n\n return arr\n\ndef merge_sort_in_place(arr, l, r): \n # TO-DO\n\n return arr\n\n\n# STRETCH: implement the Timsort function below\n# hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt\ndef timsort( arr ):\n\n return arr\n","sub_path":"src/recursive_sorting/recursive_sorting.py","file_name":"recursive_sorting.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"168056389","text":"# This is a program to solve the Stokes type system for \n# estimating the motion of clouds with velocity coming from \n# a stokes flow in a lid driven cavity.\n\nfrom dolfin import *\n\n# Create mesh and define function space.\n\nmesh = UnitSquare(100,100)\n# Define function spaces (P2-P1)\nV = VectorFunctionSpace(mesh, \"CG\", 2)\nQ = FunctionSpace(mesh, \"CG\", 1)\nW = V * Q\n# Determining the exact velocity with which the image will be \n# moved by solving a stokes problem with some given boundary \n# conditions.\n\nRe = 1000\nnu = 1.0/Re\nalpha = 0.031\n\n# Output file\nout_file = File(\"velocity.pvd\")\n\n# Define test functions\n(v,q) = TestFunctions(W)\n\n# Define trial functions\nw = Function(W)\n(u,p) = (as_vector((w[0], w[1])), w[2])\n\n# Define boundary conditions\ndef right(x, on_boundary): return x[0] > (1.0 - DOLFIN_EPS)\ndef left(x, on_boundary): return x[0] < DOLFIN_EPS\ndef bottom(x, on_boundary): return x[1] < DOLFIN_EPS\ndef top(x, on_boundary):return x[1] > 1.0 - DOLFIN_EPS \n\n\nclass Boundary(Expression):\n def eval(self, value, x):\n value[0] = x[1]\n value[1] = -x[0]\n def value_shape(self):\n return (2,)\nlid = Boundary()\n\nbc0 = DirichletBC(W.sub(0), lid, bottom)\nbc1 = DirichletBC(W.sub(0), lid, left)\nbc2 = DirichletBC(W.sub(0), lid, right)\nbc3 = DirichletBC(W.sub(0), lid, top)\n\nnoslip = DirichletBC(W.sub(0), (0,0), \"x[0] < DOLFIN_EPS || x[0] > 1.0 - DOLFIN_EPS || x[1] < DOLFIN_EPS\")\n\n\n#lid = DirichletBC(W.sub(0), (1,0), \"x[1] > 1.0 - DOLFIN_EPS\")\n\npref = DirichletBC(W.sub(1), 0, \"x[0] < DOLFIN_EPS && x[1] < DOLFIN_EPS\", \"pointwise\")\n\n\nbcs = [bc0, bc1, bc2, bc3, pref]\n\n# Tentative velocity step\nF = inner(grad(u)*u, v)*dx \\\n + nu*inner(grad(u), grad(v))*dx \\\n - div(v)*p*dx \\\n - q*div(u)*dx\n\ndw = TrialFunction(W)\ndF = derivative(F, w, dw)\nnsproblem = NonlinearVariationalProblem(F, w, bcs, dF)\nsolver = NonlinearVariationalSolver(nsproblem)\nsolver.solve()\n(ue,pe) = w.split()\n\n#plot(ue)\n # plot(pe)\n\n\n # Image data and its derivatives\nclass Image(Expression):\n def eval(self, value, x):\n value[0] = exp(-50*(pow((x[0]-0.5),2.0) + \\\n pow((x[1]-0.5),2.0)))\nE = Image()\n\nclass MyExpression0(Expression):\n def eval(self, value, x):\n value[0] = -2*50*(x[0]-0.5)*E(x)\nEx = MyExpression0()\n\nclass MyExpression1(Expression):\n def eval(self, value, x):\n value[0] = -2*50*(x[1]-0.5)*E(x)\nEy = MyExpression1()\n\nEt = -(Ex*w[0] + Ey*w[1])\ngradE = as_vector((Ex,Ey))\n\n # Define Variational Problem\n(u, p) = TrialFunctions(W)\n(v, q) = TestFunctions(W)\nw = Function(W)\n\nclass MyExpression3(Expression):\n def eval(self, value, x):\n value[0] = -Et(x)*Ex(x)\n value[1] = -Et(x)*Ey(x)\n def value_shape(self):\n return (2,)\nf = MyExpression3()\n\na = nu*inner(grad(u), grad(v))*dx \\\n - div(v)*p*dx - q*div(u)*dx \\\n +(inner(gradE,u))*(inner(gradE,v))*dx\\\n \nL = -(Et*Ex*v[0] + Et*Ey*v[1])*dx\n\n\nsolve(a==L, w, bcs)\n(vel, p) = w.split()\n#plot(vel)\n #interactive()\n # Save the solution to file\nout_file << vel\nL2error = errornorm(ue,vel,'L2')\nL2norm = norm(ue, 'L2')\nprint(L2error)\nprint(L2norm)\n # plot(p)\n#interactive()\n \n \n\n\n","sub_path":"cloud/NS/NS.py","file_name":"NS.py","file_ext":"py","file_size_in_byte":3131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"608065507","text":"def search_bb(list, target):\n \"\"\"Returns the index (a number) of the target \n in the given list, or -1 if absent\n Params:\n list - a list of items\n target - a target to search for\n \"\"\"\n # tup = enumerate(list)\n # for i, j in enumerate(list):\n # if j == target:\n # return i\n # return -1\n\n for index in range(len(list)):\n if list[index] == target:\n return index\n return -1\n\n # for i in list:\n # if i == target:\n # return index\n # index += 1\n # else:\n # return -1\n\n# print(search(['John','Paul','George','Ringo'], 'George'))\n# #=> 2\n\n# print(search(['John','Paul','George','Ringo'], 'Yoko'))\n# #=> -1\n\n\n########alt method\ndef alt_search(list, target):\n \"\"\"Returns the index (a number) of the target \n in the given list, or -1 if absent\"\"\"\n for i, item in enumerate(list): #each item & index\n if item == target: #compare\n return i #if found\n return -1 #if not in list\n\n\n#########time it\nimport time\n\ndef wall_search(list, target):\n \"\"\"Returns the index (a number) of the target \n in the given list, or -1 if absent\"\"\"\n start = time.time() #start stopwatch\n for i, item in enumerate(list):\n if item == target:\n end = time.time() #stop stopwatch (need to end and return twice in case dont get here)\n print(\"time:\",end-start) #time elapsed <--wall-clock time\n return i\n end = time.time() #stop stopwatch\n print(\"time:\",end-start) #time elapsed\n return -1\n\n##############operation count\ndef search(list, target):\n\n comparisons = 0 #count comparisons\n for i, item in enumerate(list):\n comparisons += 1 #count comparison about to do\n if item == target:\n print(\"comps:\",comparisons) #num operations\n return i\n print(\"comps:\",comparisons) #num operations\n return -1\n\nprint(search(['John','Paul','George','Ringo'], 'George'))\n#=> 2 comps: 3\n\nprint(search(['John','Paul','George','Ringo'], 'Yoko'))\n#=> -1 comps: 4\n\nprint (search(list(range(10**6)), -1))\n#=> comps: 1000000, -1\n\nprint (search(list(range(10**6)), 50))\n#=> comps: 51, 50","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"198685566","text":"import matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib import gridspec\nimport numpy as np\nfrom matplotlib import rc\nrc('font',**{'family':'serif'})\nrc('text', usetex=True)\nrc('text.latex',unicode=True)\nrc('text.latex',preamble=r'\\usepackage[T2A]{fontenc}')\nrc('text.latex',preamble=r'\\usepackage[utf8]{inputenc}')\nrc('text.latex',preamble=r'\\usepackage[russian]{babel}')\nimport pylab\nimport sys\nimport os\n\ndef cm2inch(*tupl):\n inch = 2.54\n if isinstance(tupl[0], tuple):\n return tuple(i/inch for i in tupl[0])\n else:\n return tuple(i/inch for i in tupl)\n#inputfilename = os.path.join(sys.argv[1], sys.argv[2])\n#outputfilename = os.path.join(sys.argv[1], sys.argv[3])\n\ninputfilename = \"D:/results/cubic_1000/CubicSensor_average_0.txt\"\nt, x, Dx, xhat_UMF, mErr_UMF, DErr_UMF, DErrTheor_UMF = np.loadtxt(inputfilename, delimiter = ' ', usecols=(0,1,2,3,4,5,6), unpack=True, dtype=float)\n\ninputfilename = \"D:/results/cubic_1000/CubicSensor_average_0.txt\"\nxhat_MUMF_1000, mErr_MUMF_1000, DErr_MUMF_1000, DErrTheor_MUMF_1000 = np.loadtxt(inputfilename, delimiter = ' ', usecols=(7,8,9,10), unpack=True, dtype=float)\n\ninputfilename = \"D:/results/cubic_100/CubicSensor_average_0.txt\"\nxhat_MUMF_100, mErr_MUMF_100, DErr_MUMF_100, DErrTheor_MUMF_100 = np.loadtxt(inputfilename, delimiter = ' ', usecols=(3,4,5,6), unpack=True, dtype=float)\n\ninputfilename = \"D:/results/cubic_25/CubicSensor_average_0.txt\"\nxhat_MUMF_25, mErr_MUMF_25, DErr_MUMF_25, DErrTheor_MUMF_25 = np.loadtxt(inputfilename, delimiter = ' ', usecols=(3,4,5,6), unpack=True, dtype=float)\n\nfrom pylab import *\n\nf = plt.figure(num=None, figsize=cm2inch((12,9)), dpi=200)\nplt.subplots_adjust(left=0.06, bottom=0.07, right=0.98, top=0.95, wspace=0.1)\nax = plt.subplot(111)\n\n#ls_m = (0, ())\nls_D = (0, ())\nls_D1 = (0, (1,1))\nls_D2 = (0, (3,1))\n#ls_Dth = (0, (1, 1))\n\nalpha_UT = 0.5\nparams_UT = {\n 'color' : 'black', \n 'alpha' : alpha_UT,\n 'linewidth' : 2.5,\n }\nalpha_UMF = 0.7\nparams_UMF = {\n 'color' : 'black', \n 'alpha' : alpha_UMF,\n 'linewidth' : 2.5,\n }\n\nalpha_MUMF = 1.0\nparams_MUMF = {\n 'color' : 'black', \n 'alpha' : alpha_MUMF,\n 'linewidth' : 1.5,\n }\n\n\n\nax.plot(t[1:], DErr_MUMF_25[1:], **params_MUMF, linestyle=ls_D2, label='$D[x_t - \\hat{x}_t]$, $D[x_{T} - \\hat{x}_T] = ' + \"{:.2f}\".format(DErr_MUMF_25[-1]) + '$ МУМНФ (25)')\nax.plot(t[1:], DErr_MUMF_100[1:], **params_MUMF, linestyle=ls_D1, label='$D[x_t - \\hat{x}_t]$, $D[x_{T} - \\hat{x}_T] = ' + \"{:.2f}\".format(DErr_MUMF_100[-1]) + '$ МУМНФ (100)')\n\nax.plot(t[1:], DErr_UMF[1:], **params_UMF, linestyle=ls_D, label='$D[x_t - \\hat{x}_t]$, $D[x_{T} - \\hat{x}_T] = ' + \"{:.2f}\".format(DErr_UMF[-1]) + '$ УМНФ')\n\nax.plot(t[1:], DErr_MUMF_1000[1:], **params_MUMF, linestyle=ls_D, label='$D[x_t - \\hat{x}_t]$, $D[x_{T} - \\hat{x}_T] = ' + \"{:.2f}\".format(DErr_MUMF_1000[-1]) + '$ МУМНФ (1000)')\n\n\nax.set_ylim(-0.01, 0.6)\nax.legend(loc=4)\nplt.tight_layout()\nplt.show()\n\n\n","sub_path":"CMNFvsUT/OutputScripts/pics_IEEPR/cubic.py","file_name":"cubic.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"606798625","text":"import numpy as np\nfrom scipy import interpolate\nimport matplotlib.pyplot as plt\n\nmat1 = {}\n\nx = np.arange(0.0,10.0)\ny = np.exp(-x/3.0)\n\nf = interpolate.interp1d(x,y)\n\nx1 = np.linspace(0.0,9.0,1000)\ny1 = f(x1)\n\nmat1['x'] = x\nmat1['y'] = y\n\n# plt.plot(x,y,'ro',x1,y1,'-b')\n\n\nx2 = np.arange(-5.01,5.01,0.25)\ny2 = np.arange(-5.01,5.01,0.25)\n\nxx,yy = np.meshgrid(x2,y2) # Generates a 2D mesh\n\nzz = xx**2+yy**2\n\nf2 = interpolate.interp2d(xx,yy,zz,kind='quintic') #kind cubic throws from BVL errors\n\nx3 = np.arange(-5.01,5.01,0.05)\ny3 = np.arange(-5.01,5.01,0.05)\n\nz3 = f2(x3,y3)\n\nmat1['x3'] = x3\nmat1['y3'] = y3\nmat1['z3'] = z3\n\nplt.figure(2)\nplt.contourf(xx,yy,zz)\n\nplt.figure(3)\nplt.contourf(x3,y3,z3)\nplt.show()","sub_path":"tutorial2/interpolat.py","file_name":"interpolat.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"214119618","text":"from class_class import MyClass\r\n\r\nclass Program:\r\n def __init__(self, name):\r\n self.name = name\r\n self.allmyclasses = []\r\n\r\n def addclass(self, classname, attributes = [], methods = []):\r\n newclass = MyClass(classname)\r\n self.allmyclasses.append(newclass)\r\n for aattribute in attributes:\r\n newclass.addattribute(aattribute[0], aattribute[1])\r\n for amethod in methods:\r\n newclass.addmethod(amethod[0],amethod[1])\r\n\r\n def printprogram(self):\r\n for aclass in self.allmyclasses:\r\n aclass.printclass()","sub_path":"programclass.py","file_name":"programclass.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"111762226","text":"# -*- coding: utf-8 -*-\nfrom sklearn.externals import joblib\n\n\ndef main():\n pca = joblib.load('pca.pkl')\n vocab = joblib.load('vocab.pkl')\n count = 0\n for i, j in enumerate(pca):\n count = i\n print(count)\n united = pca[vocab['United_States']]\n print(united)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"hotate/chapter09/knock86.py","file_name":"knock86.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"159219740","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Author : Bhishan Poudel\n# Date : Mar 24, 2016\n# Program : Fig 9.2 (page 195 of James B. Hartle)\n# Plot of effective and Newtonian potential for Schwarzschild geom\n# V_eff(r) = -M/r + l^2/2r^2 - Ml^2/r^3\n# V_eff(x) = -1/x + 0.5 A^2/x^2 - A^2/x^3\n# where, x = r/M and A = l/M = 4.3 for this example\n# V_eff(x) = -1/x + 9.2/x^2 - 18.5/x^3\n\n# Imports\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nx = np.arange(0.001, 40.0, 0.001)\n\ny = np.array( (-1.0/x) + (9.2/(x**2)) - (18.5/(x**3)) )\ny2 = np.array( (-1.0/x) + (9.2/(x**2)) )\n\n\n# Set axes limits\nplt.ylim(-0.04,0.06)\n\n# Plots\nplt.plot(x,y,color='k')\nplt.plot(x,y2,color='k',linestyle=\"--\")\n\n# Draw hr line at x=0\nplt.axhline(y=0.0,color='k',linestyle='-')\n\n# Text annotation\nplt.annotate('Newtonian', xy=(9, 0.02))\n\n# labels\nplt.xlabel(r'$\\frac{r}{M}$')\nplt.ylabel(r'$V_{eff}$')\n\n# tickmarks\nplt.xticks(np.arange(min(x), max(x)+1, 10.0))\nplt.yticks(np.arange(-0.02, 0.04+0.001, 0.02))\n\n# Save figure to png\nplt.savefig(\"fig_9_2_page_195.png\",dpi = 200, height = 14, width = 14)\n\n\n# show the plot\nplt.show()\n","sub_path":"Python/plotting/some_plots/fig_9_2_page_195.py","file_name":"fig_9_2_page_195.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"588109439","text":"#!/usr/bin/env python3\n\n# Utilities to extract stuff from RSO files.\n# RSO files are like SO files in Linux or DLL files in Windows, so they contain mostly code but sometimes other binary data.\n# In some VC Arcade games, some RSO files contain the system specific emulation code, as well as the emulated ROMs.\n\n# Invaluable source: https://github.com/sepalani/librso/blob/master/rvl/rso.py\n\n# The actual binary data is in the \"Sections\".\n# The externals table lists different offset within different sections to make available to use by other code. (including ROMs)\n# The internals table is a bit unknown.\n\n# Unless otherwise mentioned, all \"offset\" is relative to the beginning of the file.\n# It seems that all offsets are aligned to 4 bytes, there is null padding between file portions with odd lenghts.\n# Unless otherwise mentioned, each value is 4 bytes\n\n#HEADER:\n\n#Info\n#headerValues[0] = Next RSO Entry\n#headerValues[1] = Previous RSO Entry\n#headerValues[2] = Section Count\n#headerValues[3] = Section Table Offset\n#headerValues[4] = Name Offset\n#headerValues[5] = Name Size\n#headerValues[6] = Version\n#headerValues[7] = BSS Section Size\n\n#SectionInfo\n#headerValues[8] = 4x1 byte values - Has Prolog, Has Epilog, Has Unresolved, Has BSS\n#headerValues[9] = Prolog Offset\n#headerValues[10] = Epilog Offset\n#headerValues[11] = Unresolved Offset\n\n#RelocationTables:\n#headerValues[12] = Internals Relocation Table Offset\n#headerValues[13] = Internals Relocation Table Size\n#headerValues[14] = Externals Relocation Table Offset\n#headerValues[15] = Externals Relocation Table Size\n\n#Exports:\n#headerValues[16] = Exports Offset\n#headerValues[17] = Exports Size\n#headerValues[18] = Exports Name Offset\n\n#Imports\n#headerValues[19] = Imports Offset\n#headerValues[20] = Imports Size\n#headerValues[21] = Imports Name Offset\n\n#end of header, the rest of the file is different portions, whose positions is given in the header, or in other tables.\n\n#SECTION TABLE:\n#Starts at position \"Section Table Offset\" in header\n#For each section (0 - section count-1):\n # Section offset\n # Section length, in bytes\n#Some sections have both 0 offset and 0 length. Ignoring them.\n#Some sections have both 0 offset but a positive length. Not sure what this means. Ignoring them.\n\n#SECTION:\n#Starts at the position and has the length determined by the values in the section table.\n#The content is the actual binary data. Most often Wii binary code, but sometimes ROM content.\n\n#NAME:\n#The name of the entire library.\n#Starts at the position and has the length specified in header.\n\n#EXPORTS TABLE:\n#Contains the list of export points in the different sections.\n#Starts at position \"Exports Offset\" in header. The size in bytes is specified in header. The number of entries is the size in bytes / 16.\n#For each entry:\n #Name offset (offset of the name in the Exports Name table, relative to the start of the export name table)\n #Data Offset (relative to section start, i.e. 0=first byte in the section)\n #Section index (0-section count-1)\n #??? (large value, not referenced elsewhere in the file)\n\n#EXPORT NAMES:\n#Starts at position \"Exports Name Offset\" in header. Size is not specified anywhere.\n#Contains a number of nullterminated names without any alignment.\n#The position of a name is specified in the exports table.\n\n#EXTERNALS RELOCATION TABLE\n#Starts point and Size specified at \"Externals Relocation Table Offset\" and \"Size\" in header.\n#Not sure what this is.\n\n#IMPORTS TABLE, IMPORT NAMES, INTERNALS RELOCATION TABLE:\n#Similar to EXTERNALS counterparts.\n\n\nimport struct\n\nclass rso(object):\n def __init__(self, inputFile):\n self.file = inputFile\n\n def getExport(self, name, dataLength):\n self.file.seek(0)\n headerValues = struct.unpack(\">22I\", self.file.read(22*4))\n\n exportTableOffset = headerValues[16]\n exportTableLength = headerValues[17]\n exportNamesOffset = headerValues[18]\n\n for exportTableEntryPosition in range(0, exportTableLength, 4*4):\n\n self.file.seek(exportTableOffset + exportTableEntryPosition)\n exportTableEntry = struct.unpack(\">4I\", self.file.read(4*4))\n \n namePosition = exportTableEntry[0]\n dataPosition = exportTableEntry[1]\n sectionIndex = exportTableEntry[2]\n\n nameCandidate = self.readNullTerminatedString(exportNamesOffset + namePosition)\n\n if name == nameCandidate:\n\n sectionTableEntry = self.getSectionTableEntry(sectionIndex)\n\n sectionOffset = sectionTableEntry[0]\n sectionLength = sectionTableEntry[1]\n\n assert dataPosition + dataLength <= sectionLength\n\n self.file.seek(sectionOffset + dataPosition)\n \n data = self.file.read(dataLength)\n\n assert len(data) == dataLength\n return data\n\n def getSectionTableEntry(self, sectionIndex):\n self.file.seek(0)\n headerValues = struct.unpack(\">22I\", self.file.read(22*4))\n\n sectionTableOffset = headerValues[3]\n sectionCount = headerValues[2]\n\n assert sectionIndex < sectionCount\n\n self.file.seek(sectionTableOffset + sectionIndex*2*4)\n return struct.unpack(\">2I\", self.file.read(2*4))\n\n\n def getAllExports(self):\n self.file.seek(0)\n headerValues = struct.unpack(\">22I\", self.file.read(22*4))\n\n exportTableOffset = headerValues[16]\n exportTableLength = headerValues[17]\n exportNamesOffset = headerValues[18]\n\n exports = []\n\n for exportTableEntryOffset in range(0, exportTableLength, 4*4):\n\n self.file.seek(exportTableOffset + exportTableEntryOffset)\n exportTableEntry = struct.unpack(\">4I\", self.file.read(4*4))\n \n nameOffset = exportTableEntry[0]\n\n name = self.readNullTerminatedString(exportNamesOffset + nameOffset)\n\n exports.append(name)\n\n return exports\n\n def readNullTerminatedString(self, startOffset):\n self.file.seek(startOffset)\n ba = bytearray()\n while True:\n b = self.file.read(1)\n \n if b[0] == 0:\n return ba.decode('ascii')\n else:\n ba.extend(b)\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"rso.py","file_name":"rso.py","file_ext":"py","file_size_in_byte":6310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"205148554","text":"# -*- coding: utf-8 -*-\r\n\r\n# 파일 처리\r\n# open 함수\r\n# open(파일명, 모드, [옵션 - encoding, newline ...])\r\n\r\noutput_file_name = \"file_01.txt\"\r\n\r\n# open 함수를 사용한 파일 생성 예제\r\n# open 함수의 두번째 매개변수(모드)의 값을 w 로\r\n# 지정하게 되면 쓰기 모드로 동작하여 \r\n# 파일이 생성됩니다.\r\n# 주의사항( W 모드로 파일에 접근하는 경우 \r\n# 기존의 파일이 존재한다면, 내용이 삭제됩니다. )\r\noutput_file = open(output_file_name, \"w\")\r\n\r\n# open 함수를 통해서 얻은 파일 객체는\r\n# 사용이 끝난 후, 반드시 close 메소드를 통해\r\n# 리소스를 해재해야만 합니다.\r\noutput_file.close()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"day_06/file_01.py","file_name":"file_01.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"535651094","text":"import os\nimport subprocess\nimport time\n\nimport docker.errors\nimport pandas as pd\nimport pytest\nimport requests\nfrom ebonite.build.builder.docker_builder import create_docker_client\nfrom ebonite.build.runner.base import LocalTargetHost, TargetHost\nfrom ebonite.core.objects.core import Model\nfrom sklearn.linear_model import LinearRegression\n\nfrom tests.client.test_func import func\n\n\ndef has_docker():\n if os.environ.get('SKIP_DOCKER_TESTS', None) == 'true':\n return False\n try:\n subprocess.check_output('which docker', shell=True)\n with create_docker_client() as client:\n client.images.list()\n return True\n except (subprocess.CalledProcessError, ImportError, requests.exceptions.ConnectionError,\n docker.errors.DockerException):\n return False\n\n\ndef has_local_image(img_name: str) -> bool:\n if not has_docker():\n return False\n with create_docker_client() as client:\n try:\n client.images.get(img_name)\n except docker.errors.ImageNotFound:\n return False\n return True\n\n\ndef is_container_running(container_name, host: TargetHost = None):\n if has_docker():\n time.sleep(.1)\n host = host or LocalTargetHost()\n with create_docker_client(host.get_host()) as client:\n containers = client.containers.list()\n return any(container_name == c.name for c in containers)\n\n\ndef stop_container(container_name: str, host: TargetHost = None):\n host = host or LocalTargetHost()\n with create_docker_client(host.get_host()) as client:\n containers = client.containers.list()\n if any(container_name == c.name for c in containers):\n client.containers.get(container_name).stop()\n\n\ndef rm_container(container_name: str, host: TargetHost = None):\n host = host or LocalTargetHost()\n with create_docker_client(host.get_host()) as client:\n containers = client.containers.list()\n if any(container_name == c.name for c in containers):\n client.containers.get(container_name).remove(force=True)\n\n\ndef rm_image(image_tag: str, host: TargetHost = None):\n host = host or LocalTargetHost()\n with create_docker_client(host.get_host()) as client:\n tags = [t for i in client.images.list() for t in i.tags]\n if any(image_tag == t for t in tags):\n client.images.remove(image_tag, force=True)\n\n\ndef train_model():\n reg = LinearRegression()\n data = pd.DataFrame([[1, 1], [2, 1]], columns=['a', 'b'])\n reg.fit(data, [1, 0])\n return reg, data\n\n\ndef create_test_model(name):\n model = Model.create(func, \"kek\", name)\n return model\n\n\n@pytest.fixture\ndef model():\n model = Model.create(func, \"kek\", \"Test Model\")\n return model\n","sub_path":"tests/build/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"454884812","text":"import time\nimport datetime\nimport calendar\nimport re\n\n\nRD_PORT = '8080'\n\nSERVER_IP = 'monitor.confine-project.eu'\nSERVER_PORT = '80'\n\nDB_IP = 'monitor.confine-project.eu'\nDB_PORT= '8091'\n\nCONTROLLER_IP = 'controller.confine-project.eu'\nCONTROLLER_PORT= '8080'\n\nTIMEPERIOD = 300\n\nLAST_SEEN_SEQ_NUMBER = 0\n\ndef convert_secs_to_time_elapsed(secs):\n if(secs):\n return((datetime.timedelta(seconds = secs)))\n\n\ndef get_most_recent_sequence_number(page):\n #TODO: Remove the use of max=0 and instead use first key as max, then compare. After this change make changes in collect().\n max=0\n for key in page.keys():\n if int(key) > max:\n max = int(key)\n\n return max\n\ndef get_timestamp():\n timestamp = time.time()\n return timestamp\n\ndef find_recent_timestamp(max_so_far, absolute_value):\n if absolute_value > max_so_far:\n return absolute_value\n else:\n return max_so_far\n\ndef convert_epoch_to_date_time_dict(epoch):\n date_time= time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime(epoch))\n return ({'time': date_time})\n\ndef convert_epoch_to_date_time_dict_attributes_strip_zeroes(epoch):\n '''\n epoch to date as {year, month, date, hour, minute,second}\n leading zeroes in dates are stripped. 04 ->4, 00->0\n\\ '''\n date_time= time.strftime(\"%Y-%m-%d-%H-%M-%S\", time.gmtime(epoch))\n (year, month, date, hour, minute, second) = date_time.split('-')\n return ({'year':re.sub(\"^0+(?!$)\",'', year),'month':re.sub(\"^0+(?!$)\",'', month),\n 'date': re.sub(\"^0+(?!$)\",'', date), 'hour': re.sub(\"^0+(?!$)\",'', hour),\n 'minute':re.sub(\"^0+(?!$)\",'', minute), 'second': re.sub(\"^0+(?!$)\",'', second)})\n\ndef convert_epoch_to_date_time_dict_attributes(epoch):\n date_time= time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime(epoch))\n (date, local_time) = date_time.split()\n (year, month, date) = date.split('-')\n (hour, minute, second) = local_time.split(':')\n return ({'year':year,'month': month, 'date': date, 'hour': hour, 'minute':minute, 'second': second})\n\n\ndef convert_epoch_to_date_time_javascript(epoch):\n date_time= convert_epoch_to_date_time_dict_attributes(epoch)\n date_time['month'] = int (date_time['month']) -1\n return date_time\n\n\ndef convert_bytes_to_human_readable(bytes=[]):\n '''\n Accepts a list\n Returns updated values\n '''\n\n length = len(bytes)\n for index in range(length):\n value = bytes2human(bytes[index])\n bytes[index]= value\n return bytes\n\n\ndef bytes2human(n):\n # http://code.activestate.com/recipes/578019\n # >>> bytes2human(10000)\n # '9.8K'\n # >>> bytes2human(100001221)\n # '95.4M'\n symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')\n prefix = {}\n for i, s in enumerate(symbols):\n prefix[s] = 1 << (i+1)*10\n for s in reversed(symbols):\n if n >= prefix[s]:\n value = float(n) / prefix[s]\n return '%.1f%s' % (value, s)\n return \"%sB\" % n\n\n\ndef split_arguments_return_dict(arguments):\n '''\n Accepts an argument of the form [start_time=2013-03-14&end_time=2013-03-16&limit=123] or any combination of elements\n in the list.\n\n Returns a dict of the form {'start_time_epoch':epoch, 'end_time_epoch':epoch, 'limit':123, 'start_time_year' =year,\n 'start_time_month' = month, 'start_time_day' = day, 'end_time_day,month,year'=...}, whichever exists.\n\n The default values are {'start_time_year,month,day':\"\", 'end_time':\"{}\", 'limit':1000, start_time_epoch= \"\",\n end_time_epoch= \"{}\"}\n '''\n\n ret_dict = {'start_time_epoch':\"\", 'end_time_epoch':\"{}\", 'start_time_year': None,'start_time_month': None,\n 'start_time_day': None,'end_time_year': None,'end_time_month': None,\n 'end_time_day': None,'limit':100}\n\n arguments_list = arguments.split('&')\n for value in arguments_list:\n temp = value.split('=')\n if(len(temp)==2):\n type = compare_and_return_argument(temp[0])\n if type:\n if type!='limit':\n epoch= convert_time_to_epoch(temp[1])\n ret_dict[type+'_epoch']=epoch\n ret_dict[type+'_year'] = return_year_month_day_from_time(temp[1]).tm_year\n ret_dict[type+'_month'] = return_year_month_day_from_time(temp[1]).tm_mon\n ret_dict[type+'_day'] = return_year_month_day_from_time(temp[1]).tm_mday\n else:\n ret_dict[type]=int(temp[1])\n else:\n continue\n\n return ret_dict\n\n\ndef compare_and_return_argument(type):\n if(type == 'start_time'):\n return 'start_time'\n elif(type == 'end_time'):\n return 'end_time'\n elif(type == 'limit'):\n return 'limit'\n else:\n return None\n\ndef return_year_month_day_from_time(date_time, pattern ='%Y-%m-%d'):\n return(time.strptime(date_time, pattern))\n\ndef convert_time_to_epoch(date_time,pattern = '%Y-%m-%d'):\n #date_time = '2007-02-05'\n\n epoch = int(calendar.timegm(time.strptime(date_time, pattern)))\n return epoch\n\nconvert_time_to_epoch('2013, 4, 20, 12, 0','%Y, %m, %d, %H, %M')\n","sub_path":"server/couchbase/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":5126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"53973062","text":"import os\nfrom os.path import exists\n\nimport pytest\n\nfrom pip._internal.cli.status_codes import PREVIOUS_BUILD_DIR_ERROR\nfrom pip._internal.locations import write_delete_marker_file\nfrom tests.lib import need_mercurial\nfrom tests.lib.local_repos import local_checkout\n\n\ndef test_cleanup_after_install(script, data):\n \"\"\"\n Test clean up after installing a package.\n \"\"\"\n script.pip(\n 'install', '--no-index', '--find-links=%s' % data.find_links, 'simple'\n )\n build = script.venv_path / \"build\"\n src = script.venv_path / \"src\"\n assert not exists(build), \"build/ dir still exists: %s\" % build\n assert not exists(src), \"unexpected src/ dir exists: %s\" % src\n script.assert_no_temp()\n\n\n@pytest.mark.network\ndef test_no_clean_option_blocks_cleaning_after_install(script, data):\n \"\"\"\n Test --no-clean option blocks cleaning after install\n \"\"\"\n build = script.base_path / 'pip-build'\n script.pip(\n 'install', '--no-clean', '--no-index', '--build', build,\n '--find-links=%s' % data.find_links, 'simple', expect_temp=True,\n )\n assert exists(build)\n\n\n@pytest.mark.network\n@need_mercurial\ndef test_cleanup_after_install_editable_from_hg(script, tmpdir):\n \"\"\"\n Test clean up after cloning from Mercurial.\n\n \"\"\"\n script.pip(\n 'install',\n '-e',\n '%s#egg=ScriptTest' %\n local_checkout(\n 'hg+https://bitbucket.org/ianb/scripttest',\n tmpdir.join(\"cache\"),\n ),\n expect_error=True,\n )\n build = script.venv_path / 'build'\n src = script.venv_path / 'src'\n assert not exists(build), \"build/ dir still exists: %s\" % build\n assert exists(src), \"expected src/ dir doesn't exist: %s\" % src\n script.assert_no_temp()\n\n\ndef test_cleanup_after_install_from_local_directory(script, data):\n \"\"\"\n Test clean up after installing from a local directory.\n \"\"\"\n to_install = data.packages.join(\"FSPkg\")\n script.pip('install', to_install, expect_error=False)\n build = script.venv_path / 'build'\n src = script.venv_path / 'src'\n assert not exists(build), \"unexpected build/ dir exists: %s\" % build\n assert not exists(src), \"unexpected src/ dir exist: %s\" % src\n script.assert_no_temp()\n\n\ndef test_cleanup_req_satisifed_no_name(script, data):\n \"\"\"\n Test cleanup when req is already satisfied, and req has no 'name'\n \"\"\"\n # this test confirms Issue #420 is fixed\n # reqs with no 'name' that were already satisfied were leaving behind tmp\n # build dirs\n # 2 examples of reqs that would do this\n # 1) https://bitbucket.org/ianb/initools/get/tip.zip\n # 2) parent-0.1.tar.gz\n dist = data.packages.join(\"parent-0.1.tar.gz\")\n\n script.pip('install', dist)\n script.pip('install', dist)\n\n build = script.venv_path / 'build'\n assert not exists(build), \"unexpected build/ dir exists: %s\" % build\n script.assert_no_temp()\n\n\ndef test_cleanup_after_install_exception(script, data):\n \"\"\"\n Test clean up after a 'setup.py install' exception.\n \"\"\"\n # broken==0.2broken fails during install; see packages readme file\n result = script.pip(\n 'install', '-f', data.find_links, '--no-index', 'broken==0.2broken',\n expect_error=True,\n )\n build = script.venv_path / 'build'\n assert not exists(build), \"build/ dir still exists: %s\" % result.stdout\n script.assert_no_temp()\n\n\ndef test_cleanup_after_egg_info_exception(script, data):\n \"\"\"\n Test clean up after a 'setup.py egg_info' exception.\n \"\"\"\n # brokenegginfo fails during egg_info; see packages readme file\n result = script.pip(\n 'install', '-f', data.find_links, '--no-index', 'brokenegginfo==0.1',\n expect_error=True,\n )\n build = script.venv_path / 'build'\n assert not exists(build), \"build/ dir still exists: %s\" % result.stdout\n script.assert_no_temp()\n\n\n@pytest.mark.network\ndef test_cleanup_prevented_upon_build_dir_exception(script, data):\n \"\"\"\n Test no cleanup occurs after a PreviousBuildDirError\n \"\"\"\n build = script.venv_path / 'build'\n build_simple = build / 'simple'\n os.makedirs(build_simple)\n write_delete_marker_file(build_simple)\n build_simple.join(\"setup.py\").write(\"#\")\n result = script.pip(\n 'install', '-f', data.find_links, '--no-index', 'simple',\n '--build', build,\n expect_error=True, expect_temp=True,\n )\n\n assert result.returncode == PREVIOUS_BUILD_DIR_ERROR, str(result)\n assert \"pip can't proceed\" in result.stderr, str(result)\n assert exists(build_simple), str(result)\n","sub_path":"tests/functional/test_install_cleanup.py","file_name":"test_install_cleanup.py","file_ext":"py","file_size_in_byte":4568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"471006364","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport numpy as np\nfrom core.config import cfg\nimport modeling.FPN as fpn\nimport utils.blob as blob_utils\nfrom datasets import json_dataset\nimport roi_data.fast_rcnn\n\n\nclass CollectAndDistributeFpnRpnProposalsOp(object):\n def __init__(self, train):\n self._train = train\n\n def forward(self, inputs, outputs):\n # inputs is\n # [rpn_rois_fpn2, ..., rpn_rois_fpn6,\n # rpn_roi_probs_fpn2, ..., rpn_roi_probs_fpn6]\n # If training with Faster R-CNN, then inputs will additionally include\n # + [roidb, im_info]\n rois = collect(inputs, self._train)\n if self._train:\n # During training we reuse the data loader code. We populate roidb\n # entries on the fly using the rois generated by RPN.\n # im_info: [[im_height, im_width, im_scale], ...]\n im_info = inputs[-1].data\n im_scales = im_info[:, 2]\n roidb = blob_utils.deserialize(inputs[-2].data)\n output_blob_names = roi_data.fast_rcnn.get_fast_rcnn_blob_names()\n json_dataset.add_proposals(roidb, rois, im_scales)\n blobs = {k: [] for k in output_blob_names}\n roi_data.fast_rcnn.add_fast_rcnn_blobs(blobs, im_scales, roidb)\n for i, k in enumerate(output_blob_names):\n blob_utils.py_op_copy_blob(blobs[k], outputs[i])\n else:\n # For inference we have a special code path that avoids some data\n # loader overhead\n distribute(rois, None, outputs, self._train)\n\n\ndef collect(inputs, is_training):\n cfg_key = 'TRAIN' if is_training else 'TEST'\n post_nms_topN = cfg[cfg_key].RPN_POST_NMS_TOP_N\n k_max = cfg.FPN.RPN_MAX_LEVEL\n k_min = cfg.FPN.RPN_MIN_LEVEL\n num_lvls = k_max - k_min + 1\n roi_inputs = inputs[:num_lvls]\n score_inputs = inputs[num_lvls:]\n if is_training:\n score_inputs = score_inputs[:-2]\n\n # rois are in (for each time frame ti)\n # [[batch_idx, x0t0, y0t0, x1t0, y2t0, x0t1, y0t1, x1t1, y2t1], ...] format\n # Combine predictions across all levels and retain the top scoring\n rois = np.concatenate([blob.data for blob in roi_inputs])\n scores = np.concatenate([blob.data for blob in score_inputs]).squeeze()\n inds = np.argsort(-scores)[:post_nms_topN]\n rois = rois[inds, :]\n return rois\n\n\ndef distribute(rois, label_blobs, outputs, train):\n \"\"\"To understand the output blob order see return value of\n roi_data.fast_rcnn.get_fast_rcnn_blob_names(is_training=False)\n \"\"\"\n lvl_min = cfg.FPN.ROI_MIN_LEVEL\n lvl_max = cfg.FPN.ROI_MAX_LEVEL\n lvls = fpn.map_rois_to_fpn_levels(rois[:, 1:], lvl_min, lvl_max)\n\n outputs[0].reshape(rois.shape)\n outputs[0].data[...] = rois\n\n # Create new roi blobs for each FPN level\n # (See: modeling.FPN.add_multilevel_roi_blobs which is similar but annoying\n # to generalize to support this particular case.)\n rois_idx_order = np.empty((0, ))\n for output_idx, lvl in enumerate(range(lvl_min, lvl_max + 1)):\n idx_lvl = np.where(lvls == lvl)[0]\n blob_roi_level = rois[idx_lvl, :]\n outputs[output_idx + 1].reshape(blob_roi_level.shape)\n outputs[output_idx + 1].data[...] = blob_roi_level\n rois_idx_order = np.concatenate((rois_idx_order, idx_lvl))\n rois_idx_restore = np.argsort(rois_idx_order)\n blob_utils.py_op_copy_blob(rois_idx_restore.astype(np.int32), outputs[-1])\n","sub_path":"lib/ops/collect_and_distribute_fpn_rpn_proposals.py","file_name":"collect_and_distribute_fpn_rpn_proposals.py","file_ext":"py","file_size_in_byte":3562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"423144671","text":"#002 - Matriz Transposta\n\nm = {}\n\nlin = int(input('Linha: '))\ncol = int(input('Coluna: '))\n\nfor l in range(1, lin+1):\n linha = []\n for c in range(1, col+1):\n elem = int(input(f'Pos {l}, {c}: '))\n linha.append(str(elem))\n m[(l,c)] = linha\n\n M = list(m.values())\n\n mTransp = [[M[c][l] for c in range(len(M))] for l in range(len(M[0]))]\n\nfor a in mTransp:\n for b in a:\n print(b, end=' ')\n print()\n","sub_path":"Revisões - UFRPE/Lista #5 - Dicionários.py/002 - Matriz Transposta.py","file_name":"002 - Matriz Transposta.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"282961833","text":"import unittest\nimport os\nimport struct\nimport shutil\n\nimport bf2\n\nimport modcolmesh\n\nclass TestColMeshRead(unittest.TestCase):\n\n def setUp(self):\n self.path_colmesh = os.path.join(*['tests', 'samples', 'evil_box', 'meshes', 'evil_box.collisionmesh'])\n\n def test_can_read_header(self):\n with open(self.path_colmesh, 'rb') as meshfile:\n colmesh = modcolmesh.ColMesh()\n colmesh._read_header(meshfile)\n \n self.assertTrue(colmesh.u1 == 0)\n self.assertTrue(colmesh.version == 10)\n\n def test_can_read_geoms(self):\n with open(self.path_colmesh, 'rb') as meshfile:\n colmesh = modcolmesh.ColMesh()\n colmesh._read_geoms(meshfile)\n self.assertTrue(meshfile.tell() == 1511)\n \n self.assertTrue(len(colmesh.geoms) == colmesh.geomnum == 1)\n \n geom0 = colmesh.geoms[0]\n self.assertTrue(geom0.subgeomnum == 1)\n \n subgeom0 = geom0.subgeoms[0]\n self.assertTrue(subgeom0.lodnum == 3)\n \n lod0 = subgeom0.lods[0]\n lod1 = subgeom0.lods[1]\n lod2 = subgeom0.lods[2]\n self.assertTrue(lod0.coltype == 0)\n self.assertTrue(lod0.facenum == 12)\n self.assertTrue(lod0.u7 == 49)\n self.assertTrue(lod0.ynum == 3)\n self.assertTrue(lod0.znum == 12)\n self.assertTrue(lod0.anum == 36)\n\n def test_can_read_colmesh(self):\n colmesh = modcolmesh.ColMesh()\n colmesh.load(self.path_colmesh)\n \n # this is specific test for data in sample\n #@unittest.skip('test for sample data')\n def test_for_data(self):\n def __copy_from_export(copy_from, copy_to, objects):\n mod_path = bf2.Mod().root\n export_path = os.path.join(*copy_from)\n samples_path = os.path.join(*copy_to)\n\n for object_name in objects:\n exported_object_path = os.path.join(\n mod_path,\n export_path,\n object_name,\n 'meshes',\n object_name + '.collisionmesh')\n samples_object_path = os.path.join(\n mod_path,\n samples_path,\n object_name,\n 'meshes',\n object_name + '.collisionmesh')\n \n # raise the \n shutil.copy(exported_object_path, samples_object_path)\n\n objects = [\n 'evil_box',\n 'evil_tri', \n 'evil_plane',\n 'evil_plane_90',\n ]\n __copy_from_export(\n ['objects', 'staticobjects', 'test'],\n ['readme', 'assets', 'apps', 'python3', 'mesher', 'tests', 'samples'],\n objects)\n object_name = objects[2]\n path_samples = os.path.join('tests', 'samples')\n path_colmesh = os.path.join(path_samples, object_name, 'meshes', object_name+'.collisionmesh')\n\n colmesh = modcolmesh.ColMesh()\n colmesh.load(path_colmesh)\n print(path_colmesh)\n \n geom0 = colmesh.geoms[0]\n subgeom0 = geom0.subgeoms[0]\n lod0 = subgeom0.lods[0]\n \n for i in range(lod0.vertnum):\n print('vertex[{}]: {}'.format(i, lod0.vertices[i]))\n pass\n print('vertices({})\\n'.format(lod0.vertnum))\n\n for i in range(lod0.facenum):\n print('face[{}]: {}'.format(i, lod0.faces[i]))\n pass\n print('facenum({})\\n'.format(lod0.facenum))\n \n for i in range(lod0.ynum):\n print('ydata[{}]: {}'.format(i, lod0.ydata[i]))\n pass\n print('ynum({})\\n'.format(lod0.ynum))\n\n for i in range(lod0.znum):\n value = lod0.zdata[i]\n face = lod0.faces[value]\n print('zdata[{}]: {}'.format(i, value))\n pass\n print('znum({})\\n'.format(lod0.znum))\n \n for i in range(lod0.anum):\n vertex = lod0.vertices\n \n value = lod0.adata[i]\n face = lod0.faces[value]\n print('adata[{}]: {}'.format(i, value))\n pass\n print('anum({})\\n'.format(lod0.anum))\n raise\n\n @unittest.skip('bad i\\o intensive test, depends on local meshes...')\n def test_can_read_collisions_PR_REPO(self):\n counter = 0\n for dir, dirnames, filenames in os.walk(os.path.join(bf2.Mod().root, 'objects')):\n for filename in filenames:\n ext = filename.split('.')[-1].lower()\n if ext == 'collisionmesh' and 'test' not in dir:\n counter += 1\n filepath = os.path.join(bf2.Mod().root, dir, filename)\n try:\n colmesh = modcolmesh.ColMesh()\n colmesh.load(filepath)\n \n for geom in colmesh.geoms:\n for sub in geom.subgeoms:\n for lod in sub.lods:\n if lod.facenum > 10 and lod.facenum < 30:\n print(filepath)\n print(lod.facenum)\n for face in lod.faces:\n print(face)\n for zdata in lod.zdata:\n print(zdata)\n raise\n except struct.error:\n print('Failed to load {} struct'.format(filepath))\n #raise\n except Exception as e:\n print('Failed to load {}'.format(filepath))\n print(e)\n raise\n print(counter)\n raise\n \nif __name__ == '__main__':\n unittest.main()\n","sub_path":"deprecated/tests_colmesh_read.py","file_name":"tests_colmesh_read.py","file_ext":"py","file_size_in_byte":6106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"227330547","text":"import core.crawler as cl\r\nfrom extra.config import MENU,DEFAULT_SEMESTER\r\nimport getpass\r\nimport numpy as np\r\nimport time\r\n\r\n\r\nif __name__ == \"__main__\":\r\n bot = cl.Crawler()\r\n username = input('Input username: ')\r\n password = getpass.getpass('Input password: ')\r\n appcode = input('Input your captcha AppCode: ')\r\n # bot.get_captcha()\r\n # captchacode = input('Input captcha code: ')\r\n while not bot.login_status:\r\n captchacode = bot.get_captcha(appcode)\r\n bot.login(username, password, captchacode)\r\n if bot.login_status:\r\n flag = True\r\n while flag:\r\n print(MENU)\r\n choice = input('Input your choice: ')\r\n if choice == '1':\r\n semester = input('Input semester(Default:2019-2020-1): ')\r\n if not semester:\r\n semester = DEFAULT_SEMESTER\r\n courses = bot.get_selected_courses(semester)\r\n print('='*60)\r\n for c in courses:\r\n print(c)\r\n elif choice == '2':\r\n semester = input('Input semester(Default:2019-2020-1): ')\r\n if not semester:\r\n semester = DEFAULT_SEMESTER\r\n keywords = input('Input keywords(split with space):')\r\n courses_info = {}\r\n all_info = bot.search_course_info(semester)\r\n all_info = np.array(all_info)\r\n for kw in keywords.split():\r\n courses_info[kw] = all_info[all_info[:,2]==kw]\r\n print('='*60)\r\n print(courses_info)\r\n elif choice == '3':\r\n semester = input('Input semester(Default:2019-2020-1): ')\r\n if not semester:\r\n semester = DEFAULT_SEMESTER\r\n sleep_time = input('Input interval time(Suggest: 10): ')\r\n if not sleep_time:\r\n sleep_time = '10'\r\n sleep_time = float(sleep_time)\r\n id1_list = []\r\n id2_list = []\r\n input_flag = True\r\n while input_flag:\r\n input_id = input('Input course ID[split with space(example:\"60510082 200\")]:')\r\n input_id = input_id.split()\r\n id1_list.append(input_id[0])\r\n id2_list.append(input_id[1])\r\n continue_flag = input('Input next ID?[y/n]: ').lower()\r\n if continue_flag == 'n':\r\n input_flag = False\r\n msg = ''\r\n attempt_count = 1\r\n while id1_list:\r\n remove_count = 0\r\n for i in range(len(id1_list)):\r\n try:\r\n msg = bot.select_course(semester,id1_list[i-remove_count],id2_list[i-remove_count])\r\n if '成功' in msg or '冲突' in msg or '学位课' in msg:\r\n id1_list.pop(i-remove_count)\r\n id2_list.pop(i-remove_count)\r\n remove_count += 1\r\n print(str(attempt_count) + ': ' + msg)\r\n except:\r\n bot.login_status = False\r\n while not bot.login_status:\r\n captchacode = bot.get_captcha(appcode)\r\n bot.login(username, password, captchacode) \r\n attempt_count += 1\r\n time.sleep(sleep_time)\r\n else:\r\n print('Please input correct option!')\r\n choice = input('='*60 + '\\nBack to menu?[y/n]: ').lower()\r\n if choice == 'n':\r\n flag = False\r\n else:\r\n exit(0)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"223207964","text":"\n#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nfrom sys import argv\nfrom lxml import etree\nimport re\nfrom pprint import pprint\nimport yaml\nfrom natsort import natsorted\n\nhostname = argv[1]\nclient_prefix = [\"CF\", \"VO\", \"OV\", \"UTP\"]\n\ndef extreme_ports_to_list(vlanports_str):\n ports = set()\n if vlanports_str == \"\":\n return []\n vlanports_list = vlanports_str.split(\",\")\n for x in vlanports_list:\n prefix = \"\"\n if \":\" in x:\n prefix = x.split(\":\")[0].strip()\n x = x.split(\":\")[1]\n if re.search(\"-\", x):\n z = x.split(\"-\")\n z = range(int(z[0].lstrip()), int(z[1].lstrip())+1)\n for y in z:\n if prefix == \"\":\n ports.add(str(y))\n else:\n ports.add(prefix+\":\"+str(y))\n else:\n if prefix == \"\":\n ports.add(x.lstrip())\n else:\n ports.add(prefix+\":\"+x)\n ports = set(ports)\n ports = list(ports)\n return ports\n\ndef list_to_extreme_ports(extreme_ports_list):\n p = \"\"\n if extreme_ports_list == []:\n return p\n last = -2\n start = -1\n\n for item in natsorted(set(extreme_ports_list)):\n\n if int(item) != int(last)+1:\n if start != -1:\n if start == last:\n p = p+str(last)+\", \"\n else:\n p = p+str(start)+\"-\"+str(last)+\", \"\n start = item\n last = item\n if start == last:\n p = p+str(last)\n else:\n p = p+str(start)+\"-\"+str(last)\n\n return p\n\ndef generate_port_info(hostname):\n p = etree.XMLParser(huge_tree=True)\n tree = etree.parse(\"./extreme_xml/\"+hostname+\".unnet.ru.xml\", p)\n ports_list = tree.xpath(r'./xos-module-vlan/ports/port/text()')\n port_info = list()\n for port in ports_list:\n port = str(port)\n port_type = \"unknown\"\n description_string = \"\"\n \n enabled = tree.xpath(r'./xos-module-vlan/ports/port[text() = \"{port}\"]/../enabled/text()'.format(port=port))[0]\n \n try:\n cir_rate = tree.xpath(r'./xos-module-vlan/ports/port[text() = \"{port}\"]/../cirRate/text()'.format(port=port))[0]\n except:\n cir_rate = \"\"\n \n try:\n burst_size = tree.xpath(r'./xos-module-vlan/ports/port[text() = \"{port}\"]/../burstSize/text()'.format(port=port))[0]\n except:\n burst_size = \"\"\n \n try:\n display_string = tree.xpath(r'./xos-module-vlan/ports/port[text() = \"{port}\"]/../displayString/text()'.format(port=port))[0]\n except:\n display_string = \"\"\n \n port_info.append({\"port_num\": str(port),\n \"enabled\": int(enabled),\n \"display_string\": str(display_string),\n \"description_string\": str(description_string),\n \"port_type\": str(port_type),\n \"cir_rate\": str(cir_rate),\n \"burst_size\": str(burst_size),\n \"acl\": {\"acl_name\": \"\",\n \"directions\": \"\"}\n })\n return port_info \n\ndef generate_vlan_info(hostname):\n p = etree.XMLParser(huge_tree=True)\n tree = etree.parse(\"./extreme_xml/\"+hostname+\".unnet.ru.xml\", p)\n vlan_name_list = tree.xpath(r'./xos-module-vlan/vlan/name/text()')\n vlan_info = list()\n for vlan_name in vlan_name_list:\n primary_ip_address = \"\"\n primary_netmask = \"\"\n ip_secondary_list = \"\"\n ip_forwarding = 0\n \n vlan_id = tree.xpath(r'./xos-module-vlan/vlan/name[text() = \"{vlan_name}\"]/../tag/text()'.format(vlan_name=vlan_name))[0]\n \n S = str()\n description = tree.xpath(r'./xos-module-vlan/vlan/name[text() = \"{vlan_name}\"]/../description/text()'.format(vlan_name=vlan_name))\n description = S.join(description)\n \n vman_mode = tree.xpath(r'./xos-module-vlan/vlan/name[text() = \"{vlan_name}\"]/../vManMode/text()'.format(vlan_name=vlan_name))[0]\n \n S = str()\n tag_ports = tree.xpath(r'./xos-module-vlan/vlanPort/vlanName[text() = \"{vlan_name}\"]/../taggedPorts/text()'.format(vlan_name=vlan_name))\n tag_ports = S.join(tag_ports)\n tag_ports = extreme_ports_to_list(tag_ports)\n extreme_tag_ports = list_to_extreme_ports(tag_ports)\n \n S = str()\n untag_ports = tree.xpath(r'./xos-module-vlan/vlanPort/vlanName[text() = \"{vlan_name}\"]/../untaggedPorts/text()'.format(vlan_name=vlan_name))\n untag_ports = S.join(untag_ports)\n untag_ports = extreme_ports_to_list(untag_ports)\n extreme_untag_ports = list_to_extreme_ports(untag_ports)\n \n S = str()\n primary_ip_address = tree.xpath(r'./xos-module-vlan/vlanIpAddress/vlanName[text() = \"{vlan_name}\"]/../secondaryAddr[text() = \"{secondary}\"]/../ipaddress/text()'.format(vlan_name=vlan_name, secondary=\"0\"))\n primary_ip_address = S.join(primary_ip_address)\n \n if primary_ip_address:\n primary_netmask = tree.xpath(r'./xos-module-vlan/vlanIpAddress/vlanName[text() = \"{vlan_name}\"]/../ipaddress[text() = \"{primary_ip_address}\"]/../netmask/text()'.format(vlan_name=vlan_name, primary_ip_address=primary_ip_address))[0]\n \n ip_forwarding = tree.xpath(r'./xos-module-vlan/vlanIpAddress/vlanName[text() = \"{vlan_name}\"]/../ipForwarding/text()'.format(vlan_name=vlan_name))[0]\n \n secondary_ip_address_list = tree.xpath(r'./xos-module-vlan/vlanIpAddress/vlanName[text() = \"{vlan_name}\"]/../secondaryAddr[text() = \"{secondary}\"]/../ipaddress/text()'.format(vlan_name=vlan_name, secondary=\"1\"))\n \n ip_secondary_dict = dict()\n ip_secondary_list = list()\n if secondary_ip_address_list:\n for ip in secondary_ip_address_list:\n ip_secondary_dict = dict()\n netmask = tree.xpath(r'./xos-module-vlan/vlanIpAddress/vlanName[text() = \"{vlan_name}\"]/../ipaddress[text() = \"{ip}\"]/../netmask/text()'.format(vlan_name=vlan_name, ip=ip))[0]\n ip_secondary_dict[\"ip_address\"] = str(ip)\n ip_secondary_dict[\"netmask\"] = str(netmask)\n ip_secondary_list.append(ip_secondary_dict)\n vlan_info.append({\"vlan_name\": str(vlan_name),\n \"vlan_id\": int(vlan_id),\n \"ports\": {\"tag\": tag_ports,\n \"untag\": untag_ports\n },\n \"extreme_ports\": {\"tag\": extreme_tag_ports,\n \"untag\": extreme_untag_ports\n },\n \"ip\": {\"primary\": {\"ip_address\": str(primary_ip_address),\n \"netmask\": str(primary_netmask)\n },\n \"secondary\": ip_secondary_list,\n \"forwarding\": int(ip_forwarding),\n },\n \"description\": str(description),\n \"vman_mode\": int(vman_mode),\n \"acl\": {\"acl_name\": \"\",\n \"directions\": \"\"}\n })\n return vlan_info\n\ndef generate_eaps_info(hostname):\n p = etree.XMLParser(huge_tree=True)\n tree = etree.parse(\"./extreme_xml/\"+hostname+\".unnet.ru.xml\", p)\n eaps_domain_list = tree.xpath(r'./xos-module-eaps/eapsDomainCfg/domainName/text()')\n #eaps_global_enabled = tree.xpath(r'./xos-module-eaps/eapsGlobalCfg/enable/text()')[0]\n eaps_info = list()\n for eaps_domain in eaps_domain_list:\n enabled = tree.xpath(r'./xos-module-eaps/eapsDomainCfg/enable/text()')[0]\n primary_port = tree.xpath(r'./xos-module-eaps/eapsDomainCfg/primaryPort/text()')[0]\n secondary_port = tree.xpath(r'./xos-module-eaps/eapsDomainCfg/secondaryPort/text()')[0]\n \n mode = tree.xpath(r'./xos-module-eaps/eapsDomainCfg/mode/text()')[0]\n control_vlan = tree.xpath(r'./xos-module-eaps/eapsDomainMbrVlan/domainName[text() = \"{eaps_domain}\"]/../type[text() = \"{vlan_type}\"]/../memberVlan/text()'.format(eaps_domain=eaps_domain, vlan_type=\"1\"))[0]\n \n protected_vlan_list = tree.xpath(r'./xos-module-eaps/eapsDomainMbrVlan/domainName[text() = \"{eaps_domain}\"]/../type[text() = \"{vlan_type}\"]/../memberVlan/text()'.format(eaps_domain=eaps_domain, vlan_type=\"2\"))\n \n protected_vlan_list = map(str, protected_vlan_list)\n \n eaps_info.append({\"eaps_domain\": str(eaps_domain),\n \"enabled\": int(enabled),\n \"primary_port\": str(primary_port),\n \"secondary_port\": str(secondary_port),\n \"control_vlan\": str(control_vlan),\n \"protected_vlan_list\": protected_vlan_list,\n \"mode\": int(mode)\n })\n return eaps_info\n\ndef generate_static_route_info(hostname):\n p = etree.XMLParser(huge_tree=True)\n tree = etree.parse(\"./extreme_xml/\"+hostname+\".unnet.ru.xml\", p)\n route_list = tree.xpath(r'./xos-module-rtmgr/ipRouteEntry/ipRouteDest/text()')\n route_info = list()\n for network in route_list:\n if network != \"0.0.0.0\":\n mask = tree.xpath(r'./xos-module-rtmgr/ipRouteEntry/ipRouteDest[text() = \"{network}\"]/../ipRouteMask/text()'.format(network=network))[0]\n metric = tree.xpath(r'./xos-module-rtmgr/ipRouteEntry/ipRouteDest[text() = \"{network}\"]/../ipRouteMetric1/text()'.format(network=network))[0]\n nexthop = tree.xpath(r'./xos-module-rtmgr/ipRouteEntry/ipRouteDest[text() = \"{network}\"]/../ipRouteNextHop/text()'.format(network=network))[0]\n vr = tree.xpath(r'./xos-module-rtmgr/ipRouteEntry/ipRouteDest[text() = \"{network}\"]/../vrName/text()'.format(network=network))[0]\n route_info.append({\"network\": str(network),\n \"mask\": str(mask),\n \"metric\": str(metric),\n \"nexthop\": str(nexthop),\n \"vr\": str(vr)\n })\n\n return route_info\n\ndef generate_meter_info(hostname):\n p = etree.XMLParser(huge_tree=True)\n tree = etree.parse(\"./extreme_xml/\"+hostname+\".unnet.ru.xml\", p)\n meter_list = tree.xpath(r'./xos-module-acl/config_meter/meterName/text()')\n meter_info = list()\n for meter_name in meter_list:\n cir_rate = tree.xpath(r'./xos-module-acl/config_meter/meterName[text() = \"{meter_name}\"]/../cirRate/text()'.format(meter_name=meter_name))[0]\n burst_size = tree.xpath(r'./xos-module-acl/config_meter/meterName[text() = \"{meter_name}\"]/../burstSize/text()'.format(meter_name=meter_name))[0]\n meter_info.append({\"meter_name\": str(meter_name),\n \"cir_rate\": str(cir_rate),\n \"burst_size\": str(burst_size)\n })\n return meter_info\n\ndef generate_miscellaneous_info(hostname, vlan_info):\n node = hostname.split(\"-\")[0]\n loopback_ip = filter(lambda vlan: vlan[\"vlan_name\"] == \"Loopback\", vlan_info)[0][\"ip\"][\"primary\"][\"ip_address\"]\n nssa_ip_address = filter(lambda vlan: vlan[\"vlan_name\"] == \"vlan231-\"+node+\"-nssa\", vlan_info)[0][\"ip\"][\"primary\"][\"ip_address\"]\n backbone_ip_address = filter(lambda vlan: vlan[\"vlan_id\"] == 242, vlan_info)[0][\"ip\"][\"primary\"][\"ip_address\"]\n nssa_ip_address_list = nssa_ip_address.split(\".\")\n nssa_ip_address_list[3] = str(int(nssa_ip_address_list[3])-1)\n nssa_area = \".\".join(nssa_ip_address_list)\n \n miscellaneous_info = { \"hostname\": hostname,\n \"node\": node,\n \"loopback_ip\": loopback_ip,\n \"backbone_ip_address\": backbone_ip_address,\n \"nssa_area\": nssa_area\n }\n return miscellaneous_info\n\ndef generate_switch_inventory():\n with open('./switches.cfg', 'r') as infile:\n switches_cfg = infile.readlines()\n\n switches_inventory = dict()\n\n for line in switches_cfg:\n if not re.match(r'^#', line):\n hostname = line.split(\":\")[0]\n vendor = line.split(\":\")[1].replace(\"\\n\", \"\")\n switches_inventory[hostname] = vendor\n\n return switches_inventory\n\ndef set_port_type_and_edp_ports(switches_inventory, switch_info):\n edp_enabled_ports_list = list()\n\n i = 0\n for port in switch_info[\"ports\"]:\n if re.match(\".*-sw\\d+\", port[\"display_string\"]):\n if port[\"display_string\"] in switches_inventory.keys():\n if switches_inventory[port[\"display_string\"]] == \"e\":\n switch_info[\"ports\"][i][\"port_type\"] = \"extreme_switch\"\n edp_enabled_ports_list.append(switch_info[\"ports\"][i][\"port_num\"])\n else:\n switch_info[\"ports\"][i][\"port_type\"] = \"non_extreme_switch\"\n elif re.match(\".*-olt-data$\", port[\"display_string\"]):\n switch_info[\"ports\"][i][\"port_type\"] = \"olt-data\"\n elif port[\"display_string\"].split(\".\")[0] in client_prefix:\n switch_info[\"ports\"][i][\"port_type\"] = \"client\"\n i += 1\n\n switch_info[\"edp_ports\"] = edp_enabled_ports_list\n return switch_info\n\ndef set_elrp_ports_to_vlan(switch_info):\n edp_enabled_ports_list = switch_info[\"edp_ports\"]\n\n i = 0 \n for vlan in switch_info[\"vlans\"]:\n tag_ports = vlan[\"ports\"][\"tag\"]\n untag_ports = vlan[\"ports\"][\"untag\"]\n all_ports = tag_ports+untag_ports\n elrp_ports_list = list(set(all_ports) - set(edp_enabled_ports_list))\n extreme_elrp_ports = list_to_extreme_ports(elrp_ports_list)\n switch_info[\"vlans\"][i][\"elrp\"] = {\"ports_list\": elrp_ports_list,\n \"extreme_ports\": extreme_elrp_ports\n }\n i += 1\n return switch_info\n\ndef set_acl_info_to_vlan_and_port(hostname):\n p = etree.XMLParser(huge_tree=True)\n tree = etree.parse(\"./extreme_xml/\"+hostname+\".unnet.ru.xml\", p)\n acl_list = tree.xpath(r'./xos-module-acl/aclIfEntry/aclName/text()')\n for acl_name in acl_list:\n direction = tree.xpath(r'./xos-module-acl/aclIfEntry/aclName[text() = \"{acl_name}\"]/../aclIfDirection/text()'.format(acl_name=acl_name))[0]\n acl_info = {\"direction\": str(direction),\n \"acl_name\": str(acl_name)\n }\n port_num = \"\"\n vlan_name = \"\"\n try:\n port_num = tree.xpath(r'./xos-module-acl/aclIfEntry/aclName[text() = \"{acl_name}\"]/../port/text()'.format(acl_name=acl_name))[0]\n except:\n pass\n else:\n port = filter(lambda port: port[\"port_num\"] == port_num, switch_info[\"ports\"])[0]\n port[\"acl\"] = acl_info\n \n try:\n vlan_name = tree.xpath(r'./xos-module-acl/aclIfEntry/aclName[text() = \"{acl_name}\"]/../vlan/text()'.format(acl_name=acl_name))[0]\n except:\n pass\n else:\n vlan = filter(lambda port: vlan[\"vlan_name\"] == vlan_name, switch_info[\"vlans\"])[0]\n vlan[\"acl\"] = acl_info\n\nport_info = generate_port_info(hostname)\nvlan_info = generate_vlan_info(hostname)\neaps_info = generate_eaps_info(hostname)\nroute_info = generate_static_route_info(hostname)\nmeter_info = generate_meter_info(hostname)\nmiscellaneous_info = generate_miscellaneous_info(hostname, vlan_info)\n\nswitch_info = {\"vlans\": vlan_info,\n \"ports\": port_info,\n \"eapses\": eaps_info,\n \"static_route\": route_info,\n \"meters\": meter_info,\n \"miscellaneous\": miscellaneous_info\n }\n\nswitches_inventory = generate_switch_inventory()\nswitch_info = set_port_type_and_edp_ports(switches_inventory, switch_info)\nswitch_info = set_elrp_ports_to_vlan(switch_info)\nset_acl_info_to_vlan_and_port(hostname)\n\nwith open('./extreme_yml/'+hostname+'.unnet.ru.yml', 'w') as outfile:\n noalias_dumper = yaml.dumper.SafeDumper\n noalias_dumper.ignore_aliases = lambda self, data: True\n yaml.dump(switch_info, outfile, Dumper=noalias_dumper, default_flow_style=False)\n","sub_path":"xml_to_yml.py","file_name":"xml_to_yml.py","file_ext":"py","file_size_in_byte":16352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"143194764","text":"import random\r\nimport pandas as pd\r\n\r\n\r\nclass Player:\r\n def __init__(self, name, faction):\r\n self.name = name\r\n self.skill = random.choice(player_skills)\r\n self.win = 0\r\n self.loss = 0\r\n self.faction = faction\r\n\r\n self.battle_mod = self.skill + faction.faction_bonus\r\n\r\n if self.loss == 0:\r\n self.win_rate = self.win\r\n else:\r\n self.win_rate = self.win / (self.loss + self.win)\r\n\r\n def get_stats(self):\r\n summary = \"Name: {}, Battle Mod: {}, Faction: {}, Win%: {}\".format(self.name, self.battle_mod, self.faction.name, self.win_rate)\r\n return summary\r\n\r\n def do_battle(self):\r\n battle_score = self.battle_mod + random.uniform(1, 20)\r\n return battle_score\r\n\r\n def battle_results(self, victory):\r\n if victory:\r\n self.win += 1\r\n self.faction.increment_wins()\r\n else:\r\n self.loss += 1\r\n self.faction.increment_losses()\r\n\r\n\r\nclass Faction:\r\n def __init__(self, name):\r\n self.name = name\r\n self.faction_bonus = random.choice(faction_power_levels)\r\n self.losses = 0\r\n self.wins = 0\r\n self.win_rate = 0\r\n self.players = 0\r\n\r\n def get_faction_bonus(self):\r\n return self.faction_bonus\r\n\r\n def get_name(self):\r\n return self.name\r\n\r\n def increment_wins(self):\r\n self.wins += 1\r\n\r\n def increment_losses(self):\r\n self.losses += 1\r\n\r\n def get_win_rate(self):\r\n self.win_rate = self.wins / (self.wins + self.losses)\r\n return self.win_rate\r\n\r\n def increment_players(self):\r\n self.players += 1\r\n\r\n @property\r\n def get_stats(self):\r\n summary = 'Name: {}, Battle Mod: {}, Win%: {}%'.format(\r\n self.name, self.faction_bonus, round(self.get_win_rate(),4))\r\n return summary\r\n\r\n @property\r\n def get_data(self):\r\n data = [self.name, self.faction_bonus, round(self.get_win_rate(), 4), self.players]\r\n return data\r\n\r\n\r\ndef choose_faction():\r\n # create some code to do weighted choice towards the more powerful armies\r\n chosen_faction = random.choice(faction_list)\r\n chosen_faction.increment_players()\r\n\r\n return chosen_faction\r\n\r\n\r\ndef now_go_battle(player_1, player_2):\r\n if player_1.do_battle() > player_2.do_battle():\r\n player_1.battle_results(victory=True)\r\n player_2.battle_results(victory=False)\r\n else:\r\n player_1.battle_results(victory=False)\r\n player_2.battle_results(victory=True)\r\n\r\n\r\nfaction_names = [\"Orks\",\r\n \"Salamanders\",\r\n \"Tyranids\",\r\n \"Sisters of Battle\",\r\n \"Genestealer Cult\",\r\n \"Iron Hands\",\r\n \"Space Wolves\",\r\n \"Ultramarines\",\r\n \"Eldar\",\r\n \"Dark Elder\",\r\n \"Ynnari\",\r\n \"Imperial Guard\",\r\n \"Imperial Knights\",\r\n \"Adeptus Mechanicus\",\r\n \"Imperial Fists\",\r\n \"Blood Angels\",\r\n \"Dark Angels\",\r\n \"Necrons\",\r\n \"Chaos Space Marines\",\r\n \"Chaos Daemons\",\r\n \"Adeptus Custodes\",\r\n \"Tempestus Scions\",\r\n \"Black Templars\"]\r\n\r\nfaction_power_levels = random.choices(\r\n population=[1, 2, 3, 4, 5],\r\n weights=[0.15, 0.25, 0.3, 0.2, 0.10],\r\n k=100\r\n)\r\n\r\nplayer_skills = random.choices(\r\n population=[1, 2, 3, 4, 5],\r\n weights=[0.15, 0.25, 0.3, 0.2, 0.10],\r\n k=100\r\n)\r\n\r\n# create the factions and put them in a list\r\nfaction_list = []\r\n\r\nfor faction in faction_names:\r\n faction_list.append(Faction(faction))\r\n\r\n# generate 100 players\r\nplayer_list = []\r\n\r\nfor i in range(1, 5000):\r\n player_list.append(Player(name=i, faction=choose_faction()))\r\n\r\n# play a whole bunch of games\r\nfor i in range(1, 100000):\r\n now_go_battle(random.choice(player_list), random.choice(player_list))\r\n\r\n# report the results\r\nresults = []\r\n\r\nfor faction in faction_list:\r\n results.append(faction.get_data)\r\n\r\ndf = pd.DataFrame(results,columns=['Name','Battle Mod', 'Win Rate', \"Total Players\"], dtype=float)\r\nprint(df.sort_values(by='Win Rate', ascending=False))\r\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"12152305","text":"import json\nimport math\n\n\ndef load_data_output_content(filepath):\n with open(filepath, 'r', encoding='windows-1251') as file_handler:\n return json.load(file_handler)\n\n\ndef get_smallest_bar(content):\n smallest_bar = min(content, key=lambda seats: seats['SeatsCount'])\n return smallest_bar\n\n\ndef get_biggest_bar(content):\n biggest_bar = max(content, key=lambda seats: seats['SeatsCount'])\n return biggest_bar\n\n\ndef get_closest_bar(content, longitude, latitude):\n for bar in content:\n diff_of_coords = math.sqrt((longitude -\n bar['geoData']['coordinates'][0]) ** 2 +\n ((latitude -\n bar['geoData']['coordinates'][1]) ** 2))\n bar['geoData']['coordinates'] = diff_of_coords\n closest_bar = min(content,\n key=lambda coords: coords['geoData']['coordinates'])\n return closest_bar\n\n\ndef print_smallest_bar(smallest_bar):\n print('Smallest bar: \\n%s has %s seats in saloon.\\n' %\n (smallest_bar['Name'], smallest_bar['SeatsCount']))\n\n\ndef print_biggest_bar(biggest_bar):\n print('Biggest bar: \\n%s has %s seats in saloon.\\n' %\n (biggest_bar['Name'], biggest_bar['SeatsCount']))\n\n\ndef print_closest_bar(closest_bar):\n print(\"Closest bar: \\n%s is closest to you. Address: %s\" %\n (closest_bar['Name'], closest_bar['Address']))\n\n\nif __name__ == '__main__':\n input_path = input('Please enter way to JSON file: ')\n try:\n content = load_data_output_content(input_path)\n longitude = float(input(\"Please enter longitude: \"))\n latitude = float(input('Please enter latitude: '))\n except (ValueError, FileNotFoundError):\n print('Error! Check input information and JSON file for correctness.')\n else:\n smallest_bar = get_smallest_bar(content)\n print_smallest_bar(smallest_bar)\n biggest_bar = get_biggest_bar(content)\n print_biggest_bar(biggest_bar)\n closest_bar = get_closest_bar(content, longitude, latitude)\n print_closest_bar(closest_bar)\n","sub_path":"bars.py","file_name":"bars.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"431320145","text":"import Poem.django_logging\nimport logging, urllib\nimport http.client\n\nimport json\nfrom Poem.poem.models import Profile, MetricInstance, Metrics\nfrom urllib.parse import urlparse\nfrom Poem import settings\nfrom django.core.cache import cache\n\nLOG_INSTANCE = logging.getLogger('POEMIMPORTPROFILES')\n\nclass SyncException(Exception):\n def __init__(self, value):\n self.parameter = value\n\n def __str__(self):\n return repr(self.parameter)\n\nclass PoemSync(object):\n def __init__(self, url=\"\", profile_list=None):\n self._base_url = url\n self._has_error = False\n self._raise_exception = True\n self._profile_exist_list = []\n self._profile_list = profile_list\n\n def _raise_error(self, error_str):\n self._has_error = True\n msg_str = \"SyncException : %s\" % (error_str)\n LOG_INSTANCE.error(msg_str)\n if self._raise_exception:\n raise SyncException(msg_str)\n else:\n return None\n\n def update_obj(self, obj, dict_ob):\n for key, val in dict_ob.items():\n if hasattr(obj, key):\n setattr(obj, key, val)\n\n def sync_metricinstances(self, list_object, pobj):\n pobj.metric_instances.all().delete()\n for mins_dict in list_object:\n MetricInstance.objects.create(profile=pobj, metric=mins_dict['metric'],\n service_flavour=mins_dict['atp_service_type_flavour'],\n vo=mins_dict['vo'], fqan=mins_dict['fqan'])\n\n def sync_metrics(self, objs):\n metricsindb = []\n newmetrics = set([t['metric'] for t in objs])\n if not cache.get('metrics'):\n metricsindb = set([e['name'] for e in Metrics.objects.values('name')])\n cache.set('metrics', metricsindb)\n else:\n metricsindb = set(cache.get('metrics'))\n diff = newmetrics.difference(metricsindb)\n if diff:\n cache.set('metrics', metricsindb | diff)\n Metrics.objects.bulk_create([Metrics(name=m) for m in diff])\n\n def sync_profile(self, p_dict):\n \"\"\" Sync A profile Object and all its components \"\"\"\n # clear the Error flag\n self._has_error = False\n try:\n key='vo'\n try: p_dict[key]\n except KeyError: key='atp_vo'\n pobj1 = Profile(name=p_dict['name'],\n version=p_dict['version'],\n vo=p_dict[key],\n description=p_dict['description'])\n try:\n pobj = Profile.objects.get(name=p_dict['name'], version=p_dict['version'])\n self._profile_exist_list.append(pobj)\n except Profile.DoesNotExist:\n pobj = None\n\n if self._has_error:\n raise SyncException('Unable to Sync')\n except ValueError as ve:\n return self._raise_error(\"From sync_profile ValueError: (%s): %s\" % (p_dict['name'], ve))\n except KeyError as ke:\n return self._raise_error(\"From sync_profile KeyError: (%s): %s\" % (p_dict['name'], ke))\n except SyncException as ex:\n return self._raise_error('From sync_profile: (%s): %s' % (p_dict['name'], ex))\n\n try:\n pobj = Profile.objects.get(name=p_dict['name'], version=p_dict['version'])\n pobj.description = pobj1.description\n pobj.vo = pobj1.vo\n except Profile.DoesNotExist:\n pobj = pobj1\n\n try:\n pobj.save()\n except Exception as e:\n return self._raise_error('Saving Profile: %s' % e)\n\n self.sync_metricinstances(p_dict['metric_instances'], pobj)\n self.sync_metrics(p_dict['metric_instances'])\n\n pobj.save()\n LOG_INSTANCE.info('Synchronized profile %s' % (pobj))\n return pobj\n\n def sync_object_list(self, object_list, function_name):\n ob_list = []\n res = self._raise_exception\n self._raise_exception = False\n for ob in object_list:\n # from poem instance import selectively\n if self._profile_list and ob['name'] not in self._profile_list:\n continue\n obj = function_name(ob)\n ob_list.append(obj)\n self._raise_exception = res\n return ob_list\n\n def get_data_url(self, url, append):\n if not url:\n url = self._base_url\n try:\n o = urlparse(url)\n if o.scheme.startswith('file'):\n dcstr = json.loads(open('/'+o.path).read())\n else:\n if o.scheme.startswith('https'):\n conn = http.client.HTTPSConnection(host=o.netloc,\n key_file=settings.HOST_KEY,\n cert_file=settings.HOST_CERT)\n else:\n conn = http.client.HTTPConnection(host=o.netloc)\n conn.putrequest('GET', o.path+'?'+o.query)\n conn.endheaders()\n dcstr = json.loads(conn.getresponse().read())\n except IOError as er:\n self._raise_error(\"Error Occurred while Retrieving URL: %s%s : %s\" % (url, append, er))\n except Exception as er:\n self._raise_error(\"Error Occurred while JSON decode: %s\" % (er))\n return dcstr\n\n def sync_profile_list_from_url(self, url=None):\n return self.sync_object_list(self.get_data_url(url, ''), self.sync_profile)\n","sub_path":"poem/Poem/poem/management/update_profile.py","file_name":"update_profile.py","file_ext":"py","file_size_in_byte":5464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"429447003","text":"#3B车间设计\n\n\n\n\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .models import *\nimport json,time,random\nfrom itertools import chain\nfrom django.core import serializers\nfrom Agv import AgvCar\nimport sys\n# Create your views here.\nclass Ag:\n\tc = AgvCar.AgvCar(r'E:\\wrd\\3B\\test1\\app1\\agv_path\\BModeTest', r'E:\\wrd\\3B\\test1\\app1\\agv_path\\turn.csv', r'E:\\wrd\\3B\\test1\\app1\\agv_path\\distance.csv')\n\tdef get():\n\t\treturn Ag.c\ndef test(request):\n\t# c = AgvCar.AgvCar(r'E:\\wrd\\3B\\test1\\app1\\agv_path\\BModeTest', r'E:\\wrd\\3B\\test1\\app1\\agv_path\\turn.csv', r'E:\\wrd\\3B\\test1\\app1\\agv_path\\distance.csv')\n\tc=Ag.get()\n\tprint(c.FindNextPoint(3, 1))\n\tprint(r'搜索路径&计算距离')\n\tprint(c.FindPath(1, 24), '距离', c.CalcDistance(c.FindPath(1, 24)))\n\treturn HttpResponse(c.FindNextPoint(1, 24))\n#创建订单号\ndef create_order():\n\ta=time.strftime('%Y%m%d%H%M%S')\n\ta='CIG3B_'+a\n\titems=['1','2','3','4','5','6','7','8','9','a','s','d','f','g','h','j','k','q','w','e','r','t','y','u','i','p','z','x','c','v','b','n','m']\n\trandom.shuffle(items)\n\tnum=a+str('').join(items)[0:5]\n\tif Order.objects.filter(order_sn=num):\n\t\tcreate_order()\n\treturn num\ndef ask(request):\n\tdata=json.loads(request.body.decode('utf-8'))\n\tor_num=create_order()\n\tline=data['0']['line']\n\twtype=data['0']['type']\n\tif wtype=='1' and len(data)==2:\n\t\tprint('送完成品的只有一个点')\n\t\treturn HttpResponse('error')\n\tif Order.objects.filter(line_id=line,order_state='未完成'):\n\t\tprint('未完成')\n\t\treturn HttpResponse('existed')\n\tfor a,b in data.items():\n\t\tprint(b['count'],b['line'],b['gid'])\n\t\tline=b['line']\n\t\tgid=b['gid']\n\t\tcount=b['count']\n\t\tif line==''or gid==''or count=='':\n\t\t\tprint('返回0x01,状态改为5')\n\t\t\tsta=State.objects.all().get(sta_number='5')\n\t\t\tc=Car.objects.get(car_number=num)\n\t\t\tc.car_state=sta\n\t\t\tc.save()\n\t\t\treturn HttpResponse('0x01')\n\t\t# if Order.objects.all().count()>1000000:\n\t\tif not Order.objects.filter(order_sn=or_num):\n\t\t\tdate=time.strftime('%Y/%m/%d %H:%M:%S')\n\t\t\tli_num=Linebody.objects.all().get(line_id=line)\n\t\t\tprint(li_num)\n\t\t\to=Order()\n\t\t\to.line_id=li_num\n\t\t\to.order_sn=or_num\n\t\t\to.order_time=date\n\t\t\to.work_type=wtype\n\t\t\tif int(gid) in [10,11,12,13,14]:\n\t\t\t\tif wtype == '1':\n\t\t\t\t\tprint('送pcb的只能是0类型送料这个状态')\n\t\t\t\t\treturn HttpResponse('error')\n\t\t\t\to.different_car='1'\n\t\t\to.save()\n\t\t\tprint('总订单数目'+str(Order.objects.all().count()))\n\n\t\tordd=Order.objects.get(order_sn=or_num)\n\t\tgoid=Goods.objects.get(goods_id=gid)\n\t\to_de=Order_de()\n\t\to_de.order_sn=ordd\n\t\to_de.goods_id=goid\n\t\to_de.goods_count=count\n\t\to_de.save()\n\treturn HttpResponse(or_num+'
'+line+'
'+date)\n\n#显示小车路线\ndef show_car(request):\n\talldata=[]\n\tfor a in range(1,5):\n\t\t#返回所需数据\n\t\tlists=[]\n\t\tlists.append(a)\n\t\tcar=Car.objects.get(car_number=str(a))\n\t\tdata=Car.objects.select_related().all().values(\n\t\t\t\t'car_state__sta_name',\n\t\t\t\t'car_mark',\n\t\t\t\t'distination',\n\t\t\t\t).filter(car_number=str(a))\n\t\tlists.append(data[0]['car_state__sta_name'])\n\t\tlists.append(data[0]['car_mark'])\n\t\tlists.append(data[0]['distination'])\n\t\t# if car.order_set.filter(order_state='未完成'):\n\t\t# \tline_id=car.order_set.filter(order_state='未完成').values()[0]['line_id_id']\n\t\t# \tline_station=Linebody.objects.get(line_id=line_id).station_number\n\t\t# \tlists.append(line_station)\n\t\t# \tsn=car.order_set.filter(order_state='未完成').values()[0]['order_sn']\n\t\t# \torder=Order.objects.get(order_sn=sn)\n\t\t# \tgid=order.order_de_set.values().order_by('goods_id_id')\n\t\t# \tfor x in gid:\n\t\t# \t\tgstation=Goods.objects.get(goods_id=x['goods_id_id']).goods_station\n\t\t# \t\tlists.append(gstation)\n\t\t# \t\tprint(gstation)\n\t\t# \tprint(lists)\n\t\talldata.append(lists)\n\tprint(alldata)\n\t\n\n\t#转换为jsonstr\n\tdata=json.dumps(list(alldata),ensure_ascii=False)\n\t\n\t#json转为list\n\t# data=json.loads(data)\n\t# print(type(data))\n\treturn HttpResponse(data)\n\n\n\n#显示完成订单\ndef over_order(request):\n\tdata=Order_de.objects.select_related().all().values(\n\t\t'order_sn__line_id',\n\t\t'order_sn__order_sn',\n\t\t'order_sn__order_state',\n\t\t'order_sn__line_id__station_number',\n\t\t'order_sn__order_time',\n\t\t'order_sn__car_number',\n\t\t'order_sn__car_number__car_state__sta_name',\n\t\t'order_sn__work_type',\n\t\t'order_sn__finish_time',\n\t\t'order_sn__total_time',\n\t\t'goods_id',\n\t\t'goods_count',\n\t\t'goods_id__goods_name',\n\t\t'goods_id__goods_station',\n\t\t).filter(order_sn__order_state='完成')\n\treturn render(request,'over.html',locals())\n\n#显示未完成订单\ndef show_order(request):\n\tdata=Order_de.objects.select_related().all().values(\n\t\t'order_sn__line_id',\n\t\t'order_sn__order_sn',\n\t\t'order_sn__order_state',\n\t\t'order_sn__line_id__station_number',\n\t\t'order_sn__order_time',\n\t\t'order_sn__car_number',\n\t\t'order_sn__car_number__car_state__sta_name',\n\t\t'order_sn__work_type',\n\t\t# 'order_sn__finish_time',\n\t\t# 'order_sn__total_time',\n\t\t'goods_id',\n\t\t'goods_count',\n\t\t'goods_id__goods_name',\n\t\t'goods_id__goods_station',\n\t\t).filter(order_sn__order_state='未完成')\n\treturn render(request,'show.html',locals())\n\t# return HttpResponse(data)\n#ajax数据\ndef show_data(request):\n\tdata=Order_de.objects.select_related().all().values(\n\t\t'order_sn__line_id',\n\t\t'order_sn__order_sn',\n\t\t'order_sn__order_state',\n\t\t'order_sn__line_id__station_number',\n\t\t'order_sn__order_time',\n\t\t'order_sn__car_number',\n\t\t'order_sn__car_number__car_state__sta_name',\n\t\t'order_sn__work_type',\n\t\t# 'order_sn__total_time',\n\t\t'goods_id',\n\t\t'goods_count',\n\t\t'goods_id__goods_name',\n\t\t'goods_id__goods_type',\n\t\t'goods_id__goods_station',\n\t\t).filter(order_sn__order_state='未完成')\n\tdata=json.dumps(list(data))\n\t# print(data)\n\treturn HttpResponse(data)\n\n#接受小车状态\ndef car_sta(request):\n\tcar_data=json.loads(request.body.decode('utf-8'))\n\tstate=car_data['car_state']\n\tnum=car_data['car_number']\n\tpos=car_data['position']\n\tprint(car_data)\n\tcarr=Car.objects.filter(car_number=num)\n\t\n\ttm=time.strftime('%Y/%m/%d %H:%M:%S')\n\tif int(state)==0:\n\n\t#判断是不是重复发送0\n\t\tif Order.objects.filter(order_state=\"未完成\",car_number=num):\n\t\t\torder=Order.objects.filter(order_state=\"未完成\",car_number=num).order_by('id')[0]\n\t\t\t#返回站点代码\n\t\t\tif Car.objects.filter(car_number=num,car_state='3'):\n\t\t\t\t#先判断是哪个工作类型\n\t\t\t\tif Order.objects.get(order_state=\"未完成\",car_number=num).work_type=='1':\n\t\t\t\t\t#物料站点号\n\t\t\t\t\tcarr.update(distination='0x03')\n\t\t\t\t\tprint('再X去完成品地点0x03')\n\t\t\t\t\t#存入小车下一个目的地\n\t\t\t\t\tcarr.update(distination='0x03')\n\t\t\t\t\treturn HttpResponse('0x03')\n\t\t\t\telse:\n\t\t\t\t\t#站点号\n\t\t\t\t\tline_number=order.line_id#线体号\n\t\t\t\t\tzd=Linebody.objects.filter(line_id=line_number)[0]\n\t\t\t\t\tprint('站x点'+zd.station_number)\n\t\t\t\t\t#存入小车下一个目的地\n\t\t\t\t\tcarr.update(distination=zd.station_number)\n\t\t\t\t\treturn HttpResponse(zd.station_number)\n\n\n\t\t\t#如果重复发1,判断工作类型\n\t\t\tif Car.objects.filter(car_number=num,car_state='1'):\n\t\t\t\t#返回站点\n\t\t\t\tif Order.objects.get(order_state=\"未完成\",car_number=num).work_type=='1':\n\t\t\t\t\tline_number=order.line_id#线体号\n\t\t\t\t\tzd=Linebody.objects.filter(line_id=line_number)[0]\n\t\t\t\t\tprint('先去站点'+zd.station_number)\n\t\t\t\t\t#存入小车下一个目的地\n\t\t\t\t\tcarr.update(distination=zd.station_number)\n\t\t\t\t\treturn HttpResponse(zd.station_number)\n\t\t\t\telse:\n\t\t\t\t\t#物料站点号\n\t\t\t\t\tgid=order.order_de_set.filter(order_state='0').values().order_by('goods_id')[0]['goods_id_id']\n\t\t\t\t\tsn=Goods.objects.filter(goods_id=gid)[0]\n\t\t\t\t\tprint('物@料'+sn.goods_station)\n\t\t\t\t\t#存入小车下一个目的地\n\t\t\t\t\tcarr.update(distination=sn.goods_station)\n\t\t\t\t\treturn HttpResponse(sn.goods_station)\n\n\t\t\t\n\t\t\t\n\t\t\tif Car.objects.filter(car_number=num,car_state='2'):\n\t\t\t\torder=Order.objects.filter(car_number=num,order_state='未完成').order_by('id')[0]\n\t\t\t\t#两个以上的物料点\n\t\t\t\tif order.order_de_set.all().count()>1:\n\t\t\t\t\tsta=State.objects.all().get(sta_number='1')\n\t\t\t\t\tc=Car.objects.get(car_number=num)\n\t\t\t\t\tc.car_state=sta\n\t\t\t\t\tc.save()\n\t\t\t\t\torsn=order.order_de_set.all().values().order_by('goods_id')[0]['order_sn_id']\n\t\t\t\t\t#查询未完成的物料点\n\t\t\t\t\tif Order_de.objects.filter(order_sn=orsn,order_state='0'):\n\t\t\t\t\t\t#物料站点号\n\t\t\t\t\t\tgid=order.order_de_set.filter(order_state='0').values().order_by('goods_id')[0]['goods_id_id']\n\t\t\t\t\t\tsn=Goods.objects.filter(goods_id=gid)[0]\n\t\t\t\t\t\tprint('物x料'+sn.goods_station)\n\t\t\t\t\t\t#存入小车下一个目的地\n\t\t\t\t\t\tcarr.update(distination=sn.goods_station)\n\t\t\t\t\t\treturn HttpResponse(sn.goods_station)\n\t\t\t\t#状态改为3\n\t\t\t\tsta=State.objects.all().get(sta_number='3')\n\t\t\t\tc=Car.objects.get(car_number=num)\n\t\t\t\tc.car_state=sta\n\t\t\t\tc.save()\n\t\t\t\t#先判断是哪个工作类型\n\t\t\t\tif Order.objects.get(order_state=\"未完成\",car_number=num).work_type=='1':\n\t\t\t\t\t#物料站点号\n\t\t\t\t\tprint('再X去完成品地点0x03')\n\t\t\t\t\t#存入小车下一个目的地\n\t\t\t\t\tcarr.update(distination='0x03')\n\t\t\t\t\treturn HttpResponse('0x03')\n\t\t\t\telse:\n\t\t\t\t\t#站点号\n\t\t\t\t\tline_number=order.line_id#线体号\n\t\t\t\t\tzd=Linebody.objects.filter(line_id=line_number)[0]\n\t\t\t\t\tprint('站x点'+zd.station_number)\n\t\t\t\t\t#存入小车下一个目的地\n\t\t\t\t\tcarr.update(distination=zd.station_number)\n\t\t\t\t\treturn HttpResponse(zd.station_number)\n\n\n\t\t#分配任务\n\t\telif Order.objects.filter(order_state=\"未完成\",car_number=None,different_car='0') and int(num) in [1,2,3,4]:\n\t\t\torder=Order.objects.filter(order_state=\"未完���\",car_number=None,different_car='0').order_by('id')[0]\n\t\t\tcar=Car.objects.all().get(car_number=num)\n\t\t\tcarr.update(car_mark=pos)\n\t\t\tif order.work_type=='1':#判断先去哪个目的地\n\t\t\t\tline_number=order.line_id#线体号\n\t\t\t\tzd=Linebody.objects.filter(line_id=line_number)[0]\n\t\t\t\tdis=zd.station_number\n\t\t\telse:\n\t\t\t\tgid=order.order_de_set.all().values().order_by('goods_id')[0]['goods_id_id']\n\t\t\t\tsn=Goods.objects.filter(goods_id=gid)[0]\n\t\t\t\tdis=sn.goods_station\n\t\t\t#判断小车停的前后位置或者是让小车到点之后才发状态0\n\t\t\tc=Ag.get()\n\t\t\tlu=c.CalcDistance(c.FindPath(int(pos),int(dis)))#计算是不是最小的距离\n\t\t\tcar_list=[1,2,3,4]\n\t\t\tcar_list.pop(int(num)-1)\n\t\t\tcar_lu=[]\n\t\t\tcar_lu.append(lu)\n\t\t\tprint(car_list)\n\t\t\tfor i in car_list:\n\t\t\t\tca=Car.objects.all().get(car_number=i)\n\t\t\t\tcar_lu.append(c.CalcDistance(c.FindPath(int(ca.car_mark),int(dis))))\n\t\t\t\tprint(c.CalcDistance(c.FindPath(int(ca.car_mark),int(dis))))\n\t\t\tprint(car_lu)\n\t\t\tif lu == min(*car_lu):\n\t\t\t\torder.car_number=car\n\t\t\t\torder.save()\n\t\t\t\tprint('create ok')\n\t\t\t\t#状态改为1\n\t\t\t\tsta=State.objects.all().get(sta_number='1')\n\t\t\t\tc=Car.objects.get(car_number=num)\n\t\t\t\tc.car_state=sta\n\t\t\t\tc.save()\n\t\t\t\t#判断订单的工作类型,0表示送料,1表示送完成品\n\t\t\t\tif Order.objects.get(order_state=\"未完成\",car_number=num).work_type=='1':\n\t\t\t\t\t#先去站点号\n\t\t\t\t\tline_number=order.line_id#线体号\n\t\t\t\t\tzd=Linebody.objects.filter(line_id=line_number)[0]\n\t\t\t\t\tprint('先去站点'+zd.station_number)\n\t\t\t\t\t#存入小车下一个目的地\n\t\t\t\t\tcarr.update(distination=zd.station_number)\n\t\t\t\t\treturn HttpResponse(zd.station_number)\n\t\t\t\telse:\n\t\t\t\t\t#物料站点号\n\t\t\t\t\tgid=order.order_de_set.all().values().order_by('goods_id')[0]['goods_id_id']\n\t\t\t\t\tsn=Goods.objects.filter(goods_id=gid)[0]\n\t\t\t\t\tprint('物料'+sn.goods_station)\n\t\t\t\t\t# return HttpResponse()\n\t\t\t\t\t#存入小车下一个目的地\n\t\t\t\t\tcarr.update(distination=sn.goods_station)\n\t\t\t\t\treturn HttpResponse(sn.goods_station)\n\t\t\telse:\n\t\t\t\tprint('no')\n\t\t\t\treturn HttpResponse()\n\n\t\telif Order.objects.filter(order_state=\"未完成\",car_number=None,different_car='1') and num=='5':\n\t\t\torder=Order.objects.filter(order_state=\"未完成\",car_number=None,different_car='1').order_by('id')[0]\n\t\t\tcar=Car.objects.all().get(car_number=num)\n\t\t\torder.car_number=car\n\t\t\torder.save()\n\t\t\tprint('create ok')\n\t\t\t#状态改为1\n\t\t\tsta=State.objects.all().get(sta_number='1')\n\t\t\tc=Car.objects.get(car_number=num)\n\t\t\tc.car_state=sta\n\t\t\tc.save()\n\n\t\t\t#物料站点号\n\t\t\tgid=order.order_de_set.all().values().order_by('goods_id')[0]['goods_id_id']\n\t\t\tsn=Goods.objects.filter(goods_id=gid)[0]\n\t\t\tprint('物料'+sn.goods_station)\n\t\t\t# return HttpResponse()\n\t\t\t#存入小车下一个目的地\n\t\t\tCar.objects.filter(car_number=num).update(distination=sn.goods_station)\n\t\t\treturn HttpResponse(sn.goods_station)\n\t\telif Car.objects.filter(car_number=num,car_state='4'):\n\t\t\tsta=State.objects.all().get(sta_number='5')\n\t\t\tc=Car.objects.get(car_number=num)\n\t\t\tc.car_state=sta\n\t\t\tc.save()\n\t\t\tprint('没有订单返回0x01,状态改为5',c.default_mark)\n\t\t\t#存入小车下一个目的地\n\t\t\tCar.objects.filter(car_number=num).update(distination=c.default_mark)\n\t\t\treturn HttpResponse(c.default_mark)\n\t\telif Car.objects.filter(car_number=num,car_state='5'):\n\t\t\t\n\t\t\t\n\t\t\tprint('no order')\n\t\t\treturn HttpResponse('')\n\t\telse:\n\t\t\tsta=State.objects.all().get(sta_number='5')\n\t\t\tc=Car.objects.get(car_number=num)\n\t\t\tc.car_state=sta\n\t\t\tc.save()\n\t\t\tprint('默认回到原点',c.default_mark)\n\t\t\t#存入小车下一个目的地\n\t\t\tCar.objects.filter(car_number=num).update(distination=c.default_mark)\n\t\t\treturn HttpResponse(c.default_mark)\n\n\n\n\telif int(state)==2:\n\t\tc=Ag.get()\n\t\tnext_mark=c.FindNextPoint(int(pos),int(carr.values()[0]['distination']))\n\t\tprint(carr.values()[0]['distination'],'目的地')\n\t\tMark.objects.filter(mark_id=pos).update(mark_state='0')\n\t\tprint('当前点',pos,'下个点',next_mark)\n\t\t#查询下个点是否被占用\n\t\tif Mark.objects.filter(mark_id=next_mark,mark_state='1'):\n\t\t\treturn HttpResponse('左')\n\t\tMark.objects.filter(mark_id=next_mark).update(mark_state='1')\n\t\tcarr.update(car_mark=pos)\n\t\treturn HttpResponse('')\n\n\n\n\telif int(state)==4:\n\t\t#完成送料\n\t\tif Car.objects.filter(car_number=num,car_state='3'):\n\t\t\to=Order.objects.get(car_number=num,order_state=\"未完成\")\n\t\t\t# print(type(order))\n\t\t\to.finish_time=tm\n\t\t\to.order_state='完成'\n\t\t\t# print(type(o.order_time))\n\t\t\tod=time.mktime(time.strptime(o.order_time,'%Y/%m/%d %H:%M:%S'))\n\t\t\tfi=time.mktime(time.strptime(tm,'%Y/%m/%d %H:%M:%S'))\n\t\t\tif float(fi-od)<3600:\n\t\t\t\tfen=time.localtime(fi-od)\n\t\t\t\ttime_cha=time.strftime('%M:%S',fen)\n\t\t\telif float(fi-od)<86400:\n\t\t\t\tfen=time.localtime(fi-od)\n\t\t\t\ttime_cha=time.strftime('%H:%M:%S',fen)\n\t\t\telse:\n\t\t\t\tfen=time.localtime(fi-od)\n\t\t\t\ttime_cha=time.strftime('%d天%H:%M:%S',fen)\n\t\t\to.total_time=time_cha\n\t\t\to.save()\n\n\t\t\t# #上一个状态置零\n\t\t\t# c=Car.objects.get(car_number=num)\n\t\t\t# Mark.objects.filter(mark_id=c.car_mark).update(mark_state='0')\n\t\t\t# #把现在的点导进去\n\t\t\t# lsta=Linebody.objects.get(line_id=o.line_id)\n\t\t\t# mark=Mark.objects.get(mark_id=lsta.station_number)\n\t\t\t# mark.mark_state='1'\n\t\t\t# mark.save()\n\t\t\t# Car.objects.filter(car_number=num).update(car_mark=mark)\n\n\n\t\t\t#站位号\n\t\t\tsta=State.objects.all().get(sta_number='4')\n\t\t\tc=Car.objects.get(car_number=num)\n\t\t\tc.car_state=sta\n\t\t\tc.save()\n\n\t\t\tprint('送料完成')\n\t\t\treturn HttpResponse('')\n\t\telif Car.objects.filter(car_number=num,car_state='1'):\n\t\t\to=Order.objects.get(car_number=num,order_state=\"未完成\")\n\t\t\t#两个放料时间\n\t\t\t# if Order.objects.filter(down_time=''):\n\t\t\t# \to.down_time=tm\n\t\t\to.save()\n\t\t\tprint('装料')\n\n\t\t\t# #上一个状态置零\n\t\t\t# c=Car.objects.get(car_number=num)\n\t\t\t# Mark.objects.filter(mark_id=c.car_mark).update(mark_state='0')\n\t\t\t# #把现在的点导进去\n\t\t\t# gid=o.order_de_set.all().values()[0]['goods_id_id']\n\t\t\t# sn=Goods.objects.filter(goods_id=gid)[0]#order_sn\n\n\t\t\t# mark=Mark.objects.get(mark_id=sn.goods_station)\n\t\t\t# mark.mark_state='1'\n\t\t\t# mark.save()\n\t\t\t# Car.objects.filter(car_number=num).update(car_mark=mark)\n\t\t\t# print(sn.goods_station)\n\n\t\t\t#修改物料点完成状态\n\t\t\torsn=o.order_de_set.filter(order_state='0').values().order_by('goods_id')[0]['id']\n\t\t\t\n\t\t\tOrder_de.objects.filter(id=orsn,order_state='0').update(order_state='1')\n\n\t\t\tsta=State.objects.all().get(sta_number='2')\n\t\t\tc=Car.objects.get(car_number=num)\n\t\t\tc.car_state=sta\n\t\t\tc.save()\n\t\t\treturn HttpResponse('taking')\n\n\t\telif Car.objects.filter(car_number=num,car_state='5'):\n\t\t\t#上一个状态置零\n\t\t\t# c=Car.objects.get(car_number=num)\n\t\t\t# Mark.objects.filter(mark_id=c.car_mark).update(mark_state='0')\n\t\t\t# #把现在的点导进去\n\t\t\t# mark=Mark.objects.get(mark_id='0x01')\n\t\t\t# mark.mark_state='1'\n\t\t\t# mark.save()\n\t\t\t# Car.objects.filter(car_number=num).update(car_mark=mark)\n\n\t\t\tprint('到达原点')\n\t\t\treturn HttpResponse('')\n\t\telse:\n\t\t\tprint('状态四错误')\n\t\t\treturn HttpResponse('')\n\telse:\n\t\tprint('return or send error')\n\t\treturn HttpResponse('return')\n\n","sub_path":"3B/test1/app1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":16445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"102737980","text":"from flask import Flask\nfrom flask import render_template\n\n# name app after the namespace with __name__\n# __main__ if run from cmd line\n# simple_app if referenced in another file\napp = Flask(__name__)\n\n# define routes - can use multiple which is useful for building API\n@app.route('/')\n@app.route('/') # capture whatever comes after / as name arg\ndef index(name='Jake'):\n return render_template('index.html', name=name)\n\n\n@app.route('/add//') # typing params\n@app.route('/add//')\n@app.route('/add//')\n@app.route('/add//')\ndef add(num1, num2):\n # flask needs to have a string as a return\n context = {'num1' : num1, 'num2' : num2}\n return render_template('add.html', **context)\n\n# port; software port to listen on, like a door\n# 0.0.0.0; listen on all addresses that can get here\napp.run(port=8000, host='0.0.0.0')\n","sub_path":"flask/simple_app/simple_app.py","file_name":"simple_app.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"341538213","text":"# TC: O(n^2)\ndef twoNumberSum(array, targetSum):\n for i in range(len(array)):\n for j in range(i + 1, len(array)):\n if array[i] + array[j] == targetSum:\n return sorted([array[i], array[j]])\n\n return []\n\n\n# TC: O(n)\ndef twoNumberSum1(array, targetSum):\n nums = {}\n for num in array:\n potential_match = targetSum - num\n if potential_match in nums:\n return sorted([potential_match, num])\n else:\n nums[num] = True\n return []\n\n\n# TC(nlog(n))\ndef twoNumberSum2(array, targetSum):\n array.sort()\n left = 0\n right = len(array) - 1\n while left < right:\n currentSum = array[left] + array[right]\n if currentSum == targetSum:\n return [array[left], array[right]]\n elif currentSum < targetSum:\n left += 1\n elif currentSum > targetSum:\n right -= 1\n\n return []\n","sub_path":"two_number_sum.py","file_name":"two_number_sum.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"309186384","text":"\"\"\"\nTest basic routing functionality on a complex topology\n\nCreates a topology like:\n\n h0 -- r0 == r1 == r2 -- h3 row A\n / \\ / \\ / \\ row B\nh1 -- r3 == r4 == r5 == r6 -- h4 row C\n \\ / \\ / \\ / row D\n h2 -- r7 == r8 == r9 -- h5 row E\n\nThick lines represent links with higher latencies.\n\nEnsure that all hosts on one side of the network can reach the hosts on the other\nside. Fail a subset of the links and ensure this is still the case.\n\"\"\"\n\nimport sim\nimport sim.api as api\nimport sim.basics as basics\n\n\nclass GetPacketHost (basics.BasicHost):\n \"\"\"\n A host that expects to see a ping\n \"\"\"\n pings = 0\n def handle_rx (self, packet, port):\n if isinstance(packet, basics.Ping):\n self.pings += 1\n\n\ndef launch ():\n h0 = GetPacketHost.create(\"h0\")\n h1 = GetPacketHost.create(\"h1\")\n h2 = GetPacketHost.create(\"h2\")\n h3 = GetPacketHost.create(\"h3\")\n h4 = GetPacketHost.create(\"h4\")\n h5 = GetPacketHost.create(\"h5\")\n\n r0 = sim.config.default_switch_type.create(\"r0\")\n r1 = sim.config.default_switch_type.create(\"r1\")\n r2 = sim.config.default_switch_type.create(\"r2\")\n r3 = sim.config.default_switch_type.create(\"r3\")\n r4 = sim.config.default_switch_type.create(\"r4\")\n r5 = sim.config.default_switch_type.create(\"r5\")\n r6 = sim.config.default_switch_type.create(\"r6\")\n r7 = sim.config.default_switch_type.create(\"r7\")\n r8 = sim.config.default_switch_type.create(\"r8\")\n r9 = sim.config.default_switch_type.create(\"r9\")\n\n # Row A\n h0.linkTo(r0)\n r0.linkTo(r1, latency=3)\n r1.linkTo(r2, latency=3)\n r2.linkTo(h3)\n\n # Row B\n r3.linkTo(r0)\n r0.linkTo(r4)\n r4.linkTo(r1)\n r1.linkTo(r5)\n r5.linkTo(r2)\n r2.linkTo(r6)\n\n # Row C\n h1.linkTo(r3)\n r3.linkTo(r4, latency=3)\n r4.linkTo(r5, latency=3)\n r5.linkTo(r6, latency=3)\n r6.linkTo(h4)\n\n # Row D\n r3.linkTo(r7)\n r7.linkTo(r4)\n r4.linkTo(r8)\n r8.linkTo(r5)\n r5.linkTo(r9)\n r9.linkTo(r6)\n\n # Row E\n h2.linkTo(r7)\n r7.linkTo(r8, latency=3)\n r8.linkTo(r9, latency=3)\n r9.linkTo(h5)\n\n \"\"\"\n Included again for convenience.\n\n h0 -- r0 == r1 == r2 -- h3 row A\n / \\ / \\ / \\ row B\n h1 -- r3 == r4 == r5 == r6 -- h4 row C\n \\ / \\ / \\ / row D\n h2 -- r7 == r8 == r9 -- h5 row E\n \"\"\"\n\n def test_tasklet ():\n good = True\n\n yield 15\n\n # Have each LHS host ping every RHS host\n api.userlog.debug(\"Sending test pings\")\n\n h0.ping(h3)\n h0.ping(h4)\n h0.ping(h5)\n\n h1.ping(h3)\n h1.ping(h4)\n h1.ping(h5)\n\n h2.ping(h3)\n h2.ping(h4)\n h2.ping(h5)\n\n yield 15\n\n if h3.pings != 3:\n api.userlog.error(\"h3 got %s packets instead of 3\", h3.pings)\n good = False\n if h4.pings != 3:\n api.userlog.error(\"h4 got %s packets instead of 3\", h4.pings)\n good = False\n if h5.pings != 3:\n api.userlog.error(\"h5 got %s packets instead of 3\", h5.pings)\n good = False\n\n # Remove a subset of links\n api.userlog.debug(\"Failing several links\")\n\n # Row B\n r3.unlinkTo(r0)\n r4.unlinkTo(r1)\n r5.unlinkTo(r2)\n\n # Row C\n r4.unlinkTo(r5)\n\n # Row D\n r7.unlinkTo(r4)\n r8.unlinkTo(r5)\n r9.unlinkTo(r6)\n\n \"\"\"\n After removing downed links:\n\n h0 -- r0 == r1 == r2 -- h3\n \\ \\ \\\n h1 -- r3 == r4 r5 == r6 -- h4\n \\ \\ \\\n h2 -- r7 == r8 == r9 -- h5\n \"\"\"\n\n yield 10\n\n # Now have each RHS host ping every LHS host\n api.userlog.debug(\"Re-sending test pings\")\n\n h3.ping(h0)\n h3.ping(h1)\n h3.ping(h2)\n\n h4.ping(h0)\n h4.ping(h1)\n h4.ping(h2)\n\n h5.ping(h0)\n h5.ping(h1)\n h5.ping(h2)\n\n yield 20\n\n if h0.pings != 3:\n api.userlog.error(\"h0 got %s packets instead of 3\", h0.pings)\n good = False\n if h1.pings != 3:\n api.userlog.error(\"h1 got %s packets instead of 3\", h1.pings)\n good = False\n if h2.pings != 3:\n api.userlog.error(\"h2 got %s packets instead of 3\", h2.pings)\n good = False\n\n if good:\n api.userlog.debug(\"Test passed successfully!\")\n\n # End the simulation and (if not running in interactive mode) exit.\n import sys\n sys.exit(0)\n\n api.run_tasklet(test_tasklet)\n","sub_path":"simulator/testing/test_complex_failures.py","file_name":"test_complex_failures.py","file_ext":"py","file_size_in_byte":4205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"305054686","text":"class queue:\n def __init__(self):\n self.a=[]\n self.size=0\n def push(self,b):\n self.a.append(b)\n self.size = self.size+1\n \n def pop(self):\n if self.empty():\n return None\n else:\n self.size = self.size-1 \n return self.a.pop(0)\n\n def isEmpty(self):\n return not self.a\n def back(self):\n if self.empty():\n return None\n else:\n print(self.a[0])\n def front(self):\n if self.empty():\n return None\n else:\n print(self.a[len(self.a)-1])\n def empty(self):#이부분은 구상이 잘안되서 구글을 보고 코드를 짜고 이해했습니다.\n if (self.size >0):\n \n return False\n else:\n print(\"더이상 수가 없슨니다.\")\n return True\nque = queue()\nwhile(1):\n pan = int(input(\"숫자를 입력하려면 1번, front숫자를 확인하려면 2번, back숫자를 확인하려면 3번,front숫자를 빼려면4번, 리스트를 확인하려면 5번\"))\n if pan == 1:\n print(111) \n while(1):\n h = input(\"숫자를 입력하세요! 끝내려면 z를 입력하세요\")\n if h=='z':\n break \n else : \n que.push(h)\n elif pan == 2:\n que.back()\n elif pan == 3:\n que.front()\n elif pan == 4:\n print(que.pop())\n elif pan == 5:\n print(que.a)\n break","sub_path":"classqueue.py","file_name":"classqueue.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"538273783","text":"import discord\nfrom discord.ext import commands\nimport asyncio\n\n \n \nclass mod:\n def __init__(self, bot):\n self.bot = bot\n \n\n async def get_ban(self, name_or_id):\n '''Get a ban in the guild.'''\n for ban in await self.guild.bans():\n if name_or_id.isdigit():\n if ban.user.id == int(name_or_id):\n return ban\n if str(ban.user).lower().startswith(name_or_id.lower()):\n return ban \n\n @commands.command()\n @commands.has_permissions(kick_members = True)\n async def mute(self, ctx, user : discord.User, time = None):\n if time != None:\n time = int(time)\n t = time * 60\n await ctx.channel.set_permissions(user, send_messages=False)\n ctx.send(f\"Done, {user.mention} is now muted and will be unmuted after str{time}minutes!\")\n await asyncio.sleep(t)\n await ctx.channel.set_permissions(user, send_messages=True)\n else:\n await ctx.channel.set_permissions(user, send_messages=False)\n await ctx.send(f\"Done, {user.mention} is now permanently muted.\")\n \n @commands.command()\n @commands.has_permissions(ban_members=True)\n async def unmute(self, ctx, user: discord.Member):\n '''Unmute someone'''\n await ctx.channel.set_permissions(user, send_messages=True) \n ctx.send(f\"Done, {user.mention} is unmuted\") \n\n\n @commands.command()\n @commands.has_permissions(administrator = True)\n async def dm(self, ctx, user: discord.Member, *, message):\n \"\"\"DM someone xD\"\"\"\n await user.send(str(message))\n await ctx.message.delete() \n await ctx.send(\"It was at time. :white_check_mark: \")\n\n\n @commands.command()\n @commands.has_permissions(kick_members = True)\n async def warn(self, ctx, user: discord.Member, *, reason):\n \"\"\"Sends that warning.\"\"\"\n embed = discord.Embed(color=0xf52338, title=f\"WARNING From {ctx.author.guild.name}**.\", description=f\"By ctx.author.name \\n Reason ==> {reason}\")\n await user.send(embed=embed)\n await ctx.message.delete()\n\n @commands.command()\n @commands.has_permissions(kick_members = True)\n async def kick(self, ctx, user : discord.Member, *, reason = None):\n '''OFC kick anyone'''\n if reason != None:\n await ctx.send(f\"Done, {user.mention} is kicked, reason = {reason} \")\n \n embed=discord.Embed(title=f\"Kicked From {ctx.author.guild.name}\", description =f\"You have been kicked from **{ctx.author.guild.name}** by **{ctx.message.author.name}**, Reason ==> **{reason}**!\", color=0xf52338)\n await user.send(embed=embed)\n await ctx.guild.kick(user, reason = reason)\n \n else:\n reason = \"Unspecified\"\n await ctx.send(f\"Done, {user} is kicked, reason = Unspecified \")\n \n embed=discord.Embed(title=f\"Kicked From {ctx.author.guild.name}\", description = f\"You have been kicked from **{ctx.author.guild.name}** by **{ctx.message.author.name}**, Reason ==> **Not Specified**!\", color=0xf52338)\n await user.send(embed=embed)\n await ctx.guild.kick(user, reason = reason)\n \n \n\n @commands.command()\n @commands.has_permissions(ban_members = True)\n async def ban(self, ctx, user : discord.User, *, reason = None):\n if reason != None:\n \n await ctx.send(f\"Done, {user} is banned, reason = {reason} \")\n embed=discord.Embed(title=f\"Banned From {ctx.author.guild.name}\", description = f\"You have been Banned from **{ctx.author.guild.name}** by **{ctx.message.author.name}**, Reason ==> **{reason}**!\", color=0xf52338)\n await user.send(embed=embed)\n await ctx.guild.ban(user, reason = reason)\n\n else:\n \n await ctx.send(f\"Done, {user} is banned, reason = {reason} \")\n embed=discord.Embed(title=f\"Banned From {ctx.author.guild.name}\",description = f\"You have been Banned from **{ctx.author.guild.name}** by **{ctx.message.author.name}**, Reason ==> **Not Specified**!\", color=0xf52338)\n await user.send(embed=embed)\n await ctx.guild.ban(user, reason = \"Unspecified\")\n \n\n @commands.command()\n @commands.has_permissions(ban_members=True)\n async def unban(self, ctx, name_or_id, *, reason=None):\n '''Unban a member from the guild'''\n ban = await ctx.get_ban(name_or_id)\n if not ban:\n return await ctx.send('No user found.')\n await ctx.guild.unban(ban.user, reason=reason)\n await ctx.send(f'Unbanned *{ban.user}* from the server.')\n \n @commands.command()\n @commands.has_permissions(ban_members=True)\n async def softban(self, ctx, member: discord.Member, *, reason=None):\n '''Kicks a members and deletes their messages.'''\n await member.ban(reason=f'Softban - {reason}')\n await member.unban(reason='Softban unban.')\n await ctx.send(f'Done. {member.name} was softbanned.')\n\n @commands.command()\n @commands.has_permissions(ban_members=True)\n async def hackban(self, ctx, user_id: int, *, reason=None):\n '''Bans a user that is currently not in the server.\n Only accepts user IDs.\n '''\n await ctx.guild.ban(discord.Object(id=user_id), reason=reason)\n await ctx.send(f'*{self.bot.get_user(user_id)}* just got hackbanned!')\n \n @commands.command()\n @commands.has_permissions(manage_messages = True)\n async def purge(self, ctx,*, amount):\n if ctx.author.permissions_in(ctx.channel).manage_messages:\n try:\n amount = await ctx.channel.purge(limit=int(amount)+1)\n \n await ctx.channel.send(':white_check_mark: Deleted {} message(s)'.format(len(amount)-1))\n \n except discord.errors.Forbidden:\n await ctx.send(\"I do not have the manage messages permission to perform this action.\")\n else:\n await ctx.send(\"You don't have premissions to use this command.\")\n\n\ndef setup(bot):\n bot.add_cog(mod(bot))\n \n","sub_path":"cogs/mod.py","file_name":"mod.py","file_ext":"py","file_size_in_byte":6180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"195888601","text":"from django.urls import path, include\nfrom django.contrib.auth import views as auth_views\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('index', views.index, name='index'),\n path('profile', views.profile, name='profile'),\n path('login', views.login, name='login'),\n path('logout', views.logout, name='logout'),\n path('approve', views.approve, name='approve'),\n path('delete', views.delete, name='delete'),\n path('edit', views.edit, name='edit'),\n path('postnotice', views.postnotice, name='postnotice'),\n path('loginpage', views.index, name='index'),\n path('postednotice', views.postednotice, name=\"postednotice\"),\n path('pendingnotice', views.pendingnotice, name=\"pendingnotice\"),\n path('leavemanagement', views.leave_management, name='leavemanagement'),\n path('new_notice', views.new_notice, name=\"new_notice\"),\n]\n","sub_path":"myDjangoCollegewebproject-master/myDjangoCollegewebproject-master/macsdept/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"362693717","text":"import json\nimport os\n\nimport htmlgenerator.generator\n\nfrom collections import OrderedDict\nfrom itertools import islice\nimport datetime\nimport time\nimport pygal\nfrom pygal.style import Style\n\nfrom .tools import display\n\ndef time_flatten(data, factor=1):\n ret = [0 for _ in range(24)]\n\n for key, value in data.items():\n ret[int(int(key)/100)] += value/factor\n\n return ret\n\nclass StatsBot:\n def __init__(self, subreddit, data_file, output_dir):\n \"\"\"Basic constructor\"\"\"\n self._subreddit = subreddit\n self._data_file = data_file\n self._output_dir = output_dir\n \n if not os.path.exists(self._output_dir):\n os.makedirs(self._output_dir)\n \n with open(self._data_file) as df:\n self._data = json.load(df)\n\n self._page = htmlgenerator.generator.HtmlGenerator()\n self._page.title = 'Statistiques de r/'+self._subreddit\n\n def __del__(self):\n self._page.write(os.path.join(self._output_dir,'index.html'))\n \n def generate(self):\n start_time = time.time()\n self._page.header().h1('Statistiques de r/'+self._subreddit, align='center')\n\n section = self._page.section()\n\n # Daily activity\n\n day_activity = pygal.Radar()\n day_activity.title = 'Activité en fonction de l\\'heure'\n day_activity.x_labels = map(str, range(0, 24))\n day_activity.add('Posts', time_flatten(self._data['posts']['time']['all'], self._data['posts']['count']))\n day_activity.add('Commentaires', time_flatten(self._data['comments']['time']['all'], self._data['comments']['count']))\n with open(os.path.join(self._output_dir,'activity.svg'), 'wb') as act:\n act.write(day_activity.render())\n\n section.embed(src='activity.svg', id='activity', tipe='image/svg+xml', style='margin-left: 25%;', width='50%')\n\n # Weekly activity\n\n week_activity = pygal.Radar()\n week_activity.title = 'Activité en fonction du jour'\n\n weekdays = OrderedDict([(0, \"Monday\"), (1, \"Tuesday\"), (2, \"Wednesday\"), (3, \"Thursday\"), (4, \"Friday\"), (5, \"Saturday\"),(6, \"Sunday\")])\n\n week_activity.x_labels = weekdays.values()\n\n posts_week_activity = OrderedDict()\n comments_week_activity = OrderedDict()\n for n,day in weekdays.items():\n posts_week_activity[day] = sum(self._data['posts']['time'][str(n)].values())\n comments_week_activity[day] = sum(self._data['comments']['time'][str(n)].values())\n\n week_activity.add('Posts', posts_week_activity.values())\n week_activity.add('Comments', comments_week_activity.values())\n with open(os.path.join(self._output_dir,'week_activity.svg'), 'wb') as week_act:\n week_act.write(week_activity.render())\n\n section.embed(src='week_activity.svg', id='activity', tipe='image/svg+xml', style='margin-left: 25%;', width='50%')\n\n # User flairs\n\n ## Comments\n\n try:\n user_flairs_ranking = OrderedDict(sorted(self._data['comments']['flair-presence'].items(),key=lambda t: t[1],reverse=True))\n except KeyError:\n pass\n else:\n section = self._page.section()\n user_flairs_graph = pygal.HorizontalBar()\n user_flairs_graph.title = 'Distribution des flairs des utilisateurs'\n\n user_flairs_ref_value = max(user_flairs_ranking.values())/5\n\n data_for_graph_user_flairs = OrderedDict()\n with open(os.path.join(self._output_dir, 'user_flairs.txt'), 'w') as user_flairs:\n for k, v in user_flairs_ranking.items():\n if float(v) >= user_flairs_ref_value:\n try:\n data_for_graph_user_flairs[k] = v\n except:\n raise\n user_flairs.write(\"{flair} {hits}\\n\".format(flair=k, hits=v))\n\n data_for_graph_user_flairs = OrderedDict(sorted(data_for_graph_user_flairs.items(), key=lambda t: t[1]))\n\n user_flairs_graph.x_labels = data_for_graph_user_flairs.keys()\n user_flairs_graph.add('Poster flairs', data_for_graph_user_flairs.values())\n\n with open(os.path.join(self._output_dir,'user_flairs.svg'), 'wb') as user_flairs_file:\n user_flairs_file.write(user_flairs_graph.render())\n \n section.embed(src='user_flairs.svg', id='posts_subjects', tipe='image/svg+xml', style='margin-left: 25%;', width='50%')\n section.p('{link}'.format(url='user_flairs.txt', link='All data here'), klass=\"raw-link\")\n\n ## Posts\n\n try:\n posts_user_flairs_ranking = OrderedDict(sorted(self._data['posts']['flair-presence'].items(),key=lambda t: t[1],reverse=True))\n except KeyError:\n pass\n else:\n section = self._page.section()\n posts_user_flairs_graph = pygal.HorizontalBar()\n posts_user_flairs_graph.title = 'Distribution des flairs des posteurs'\n\n posts_user_flairs_ref_value = max(posts_user_flairs_ranking.values())/5\n\n data_for_graph_posts_user_flairs = OrderedDict()\n with open(os.path.join(self._output_dir, 'posts_user_flairs.txt'), 'w') as posts_user_flairs:\n for k, v in posts_user_flairs_ranking.items():\n if float(v) >= posts_user_flairs_ref_value:\n try:\n data_for_graph_posts_user_flairs[k] = v\n except:\n raise\n posts_user_flairs.write(\"{flair} {hits}\\n\".format(flair=k, hits=v))\n\n data_for_graph_posts_user_flairs = OrderedDict(sorted(data_for_graph_posts_user_flairs.items(), key=lambda t: t[1]))\n\n posts_user_flairs_graph.x_labels = data_for_graph_posts_user_flairs.keys()\n posts_user_flairs_graph.add('Poster flairs', data_for_graph_posts_user_flairs.values())\n\n with open(os.path.join(self._output_dir,'posts_user_flairs.svg'), 'wb') as posts_user_flairs_file:\n posts_user_flairs_file.write(posts_user_flairs_graph.render())\n \n section.embed(src='posts_user_flairs.svg', id='posts_subjects', tipe='image/svg+xml', style='margin-left: 25%;', width='50%')\n section.p('{link}'.format(url='posts_user_flairs.txt', link='All data here'), klass=\"raw-link\")\n\n # Post flairs\n\n try:\n posts_subjects_ranking = OrderedDict(sorted(self._data['posts']['subject-presence'].items(), key=lambda t: t[1]))\n except KeyError:\n pass\n else:\n section = self._page.section()\n try:\n del posts_subjects_ranking['None']\n except KeyError:\n pass\n bar_chart = pygal.HorizontalBar()\n bar_chart.title = 'Distribution des catégories de posts'\n\n bar_chart.x_labels = posts_subjects_ranking.keys()\n bar_chart.add('Posts', posts_subjects_ranking.values())\n with open(os.path.join(self._output_dir,'posts_subjects.svg'), 'wb') as posts_subjects:\n posts_subjects.write(bar_chart.render())\n \n section.embed(src='posts_subjects.svg', id='posts_subjects', tipe='image/svg+xml', style='margin-left: 25%;', width='50%')\n\n duration = time.time() - start_time\n duration_string = ' (en '+display.float(duration, 3)+' secondes). '\n duration_string += str(self._data['comments']['count'])+' commentaires analysés, '\n duration_string += str(self._data['posts']['count'])+' posts analysés.'\n foot = self._page.footer().p(\"Généré le \"+datetime.datetime.now().strftime('%Y-%m-%d à %H:%M %Z')+duration_string.format(duration))\n foot.append(' Code source disponible sur ')\n foot.append(htmlgenerator.markup.HtmlAnchor('GitHub', 'http://github.com/dopsi/flairstats'))\n foot.append('.')\n \ndef StatsBotGenerator(config_file):\n \"\"\"Generate a list-like container of StatsBot objects\"\"\"\n with open(config_file) as cf:\n json_config = json.load(cf)\n\n for i in json_config['bots']:\n yield StatsBot(i['subreddit'], i['data-file'], i['output-dir'])\n\ndef autorun():\n \"\"\"Autorun function of this module\"\"\"\n home = os.getenv('HOME')\n config_file = os.path.join(home, '.config/flairstats/config.json')\n if not os.path.exists(config_file):\n raise FileNotFoundError(config_file)\n\n statsbots = StatsBotGenerator(config_file)\n\n for bot in statsbots:\n bot.generate()\n\nif __name__ == '__main__':\n autorun()\n","sub_path":"flairstats/statsbot.py","file_name":"statsbot.py","file_ext":"py","file_size_in_byte":8681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"1604459","text":"from datetime import datetime\n\nfrom django.contrib.auth.models import User\n\nfrom profiles.models import UserProfile\nfrom fb.models import FacebookProfile\n\nclass FacebookBackend(object):\n \"\"\"Facebook authentication backend.\n \"\"\"\n\n def authenticate(self, oauth_token, fb_id, name, user_id=None):\n \"\"\"Authenticates user via Facebook API and saves user information.\n \"\"\"\n try:\n # Find existing user\n facebook_user = FacebookProfile.objects.get(pk=fb_id, name=name)\n user = facebook_user.user\n\n # Update user's access token\n facebook_user.oauth_token = oauth_token\n facebook_user.save()\n \n # Set last visit to now\n user.userprofile.last_visit_date = datetime.now()\n user.userprofile.save()\n\n except FacebookProfile.DoesNotExist: # If requested user has not yet been registered\n # Create or get User and add FacebookProfile\n if user_id == None:\n user = User.objects.create_user(fb_id)\n user.save()\n \n # Create UserProfile to hold information\n userprofile = UserProfile(user=user)\n userprofile.save()\n \n else:\n user = User.objects.get(pk=user_id)\n\n facebook_user = FacebookProfile(user=user, pk=fb_id, oauth_token=oauth_token)\n facebook_user.save()\n\n return user\n\n def get_user(self, user_id):\n \"\"\"Returns the given user from user_id\n \"\"\"\n try:\n return User.objects.get(pk=user_id)\n except User.DoesNotExist:\n return None","sub_path":"fb/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"20877015","text":"# -*- coding: utf-8 -*-\n#-------------------------------------------------------------------------------\n## Description\n\"\"\"\nThis script runs when Houdini nodes are created.\n\nThis code is basaed on\n\"\"\"\n#-------------------------------------------------------------------------------\n\nmanager_color = (0, 0.4, 1)\ngenerator_color = (0.8, 0.8, 0.8)\n\n# Common node type colors. These colors affect these types in all contexts.\n# Node names are matched identically with keys.\ncommon_type_colors = {\n\n ### Gray ###\n \"null\": (0.36, 0.36, 0.36),\n \"cam\": (0.36, 0.36, 0.36),\n \"merge\": (0.36, 0.36, 0.36),\n \"output\": (0.36, 0.36, 0.36),\n\n ### Blue: Disk Output ###\n \"df_alembic_export\": (0, 0.4, 1),\n \"PRT_ROPDriver\": (0, 0.4, 1),\n \"rop_geometry\": (0, 0.4, 1),\n \"rop_alembic\": (0, 0.4, 1),\n \"ropnet\": (0, 0.4, 1),\n\n ### Yellow: Disk Input ###\n \"file\": (1, 0.8, 0),\n \"filecache\": (1, 0.8, 0),\n \"filemerge\": (1, 0.8, 0),\n \"alembic\": (1, 0.8, 0),\n \"alembicarchive\": (1, 0.8, 0),\n\n ### Purple Blue: Dop I/O ###\n \"dopimport\": (0.6, 0.6, 1),\n \"dopimportfield\": (0.6, 0.6, 1),\n \"dopimportrecords\": (0.6, 0.6, 1),\n \"dopio\": (0.6, 0.6, 1),\n\n ### Purple ###\n \"dopnet\": (0.4, 0, 0.6),\n\n ### Green: Geometry Fetch ###\n \"object_merge\": (0, 0.4, 0),\n\n ### Dark Green ###\n \"geo\": (0, 0.267, 0)\n\n\n}\n\n# Node type information.\nnode = kwargs[\"node\"]\nnode_type = node.type()\nnode_type_name = node_type.name()\ntype_category_name = node_type.category().name().lower()\n\n\n# Start with no node color:\nnode_color = None\n\n# Manager nodes (sopnet, chopnet, ropnet, etc).\nif node_type.isManager():\n node_color = manager_color\n\n# Common node types (nulls, switches, etc) are colored the same across\n# different contexts.\nelif node_type_name in common_type_colors:\n node_color = common_type_colors[node_type_name]\n\n\n# If we found a color mapping, set the color of the node.\nif node_color is not None:\n node.setColor(hou.Color(node_color))\n","sub_path":"scripts/OnCreated.py","file_name":"OnCreated.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"306601549","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\nfrom setuptools import find_packages\nfrom setuptools import setup\n\n\nrequirements = [\n r.strip() for r in open(\"requirements.txt\") if r.strip() and not r.strip().startswith(\"#\")\n]\n\ndesc = \"Software package vulnerabilities database.\"\n\nsetup(\n name=\"vulnerablecode\",\n version=\"20.10\",\n license=\"Apache-2.0\",\n description=desc,\n long_description=desc,\n author=\"nexB Inc. and others\",\n author_email=\"info@aboutcode.org\",\n url=\"https://github.com/nexB/vulnerablecode\",\n packages=find_packages(),\n include_package_data=True,\n zip_safe=False,\n classifiers=[\n # complete classifier list: http://pypi.python.org/pypi?%3Aaction=list_classifiers\n \"Development Status :: 4 - Beta\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3\",\n \"Topic :: Utilities\",\n ],\n keywords=[\n \"open source\",\n \"vulnerability\",\n \"package\",\n ],\n install_requires=requirements,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"77185342","text":"import psycopg2\nimport pytest\n\n\n@pytest.fixture\ndef db():\n \"\"\"\n Create a new database for running the test\n Drop it at the end\n \"\"\"\n connection = psycopg2.connect(dbname=\"postgres\")\n connection.set_session(autocommit=True)\n cursor = connection.cursor()\n test_db_name = \"test_septentrion\"\n # create test database to running the test\n cursor.execute(f\"DROP DATABASE IF EXISTS {test_db_name}\")\n cursor.execute(f\"CREATE DATABASE {test_db_name}\")\n\n params = connection.get_dsn_parameters()\n params[\"dbname\"] = test_db_name\n yield params\n\n cursor.execute(f\"DROP DATABASE {test_db_name}\")\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"76950523","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2017/8/28 AM11:52\n# @Author : Qiming Zhang\n# @File : LexicographicalNumbers\nclass Solution(object):\n def lexicalOrder(self, n):\n \"\"\"\n :type n: int\n :rtype: List[int]\n \"\"\"\n result = []\n def solve(m):\n result.append(m)\n if m * 10 <= n: solve(m * 10)\n if m < n and m % 10 < 9: solve(m + 1)\n solve(1)\n return result\n\n\n def lexicalOrderNonRecursion(self, n):\n s = [1]\n res = []\n while s:\n num = s.pop()\n res.append(num)\n if num < n and num % 10 < 9:\n s.append(num + 1)\n if num * 10 <= n:\n s.append(num * 10)\n return res\n","sub_path":"Math/LexicographicalNumbers.py","file_name":"LexicographicalNumbers.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"549994738","text":"\n# coding: utf-8\n\n# ### function to calculate minimum probility p_min to check given condition\n\n# In[2]:\n\ndef p_minimum(n,trail_cap,B_cap,B_bar):\n p_min = 1.0;\n for i in range(0,n):\n p_min *= trail_cap[i].wt\n p_min = p_min * B_cap[nrounds - 1 - (n + 1)]; \n p_min = B_bar/p_min\n #print(B_bar,p_min)\n return p_min\n\n\n# ### function to check given inputs are available in highways path list or not \n\n# In[3]:\n\ndef highwaylist():\n alph,bet,gam,pro = [],[],[],[]\n with open('alph.txt') as ip1, open('bet.txt') as ip2, open('gam.txt') as ip3, open('pro.txt') as ip4:\n for i1,i2,i3,i4 in zip(ip1,ip2,ip3,ip4):\n hw.append(NMTS(int(i1.strip()),int(i2.strip()),int(i3.strip()),float(i4.strip()))) \n \n\n\n# ### function to calculate weight \n\n# In[4]:\n\ndef weight(alpha1,beta1,gamma1): \n x1= (alpha1 << 1)& mask\n y1= (beta1 << 1)& mask\n z1= (gamma1 << 1)& mask\n not_x=(x1^mask)\n eq=((not_x)^y1)&(not_x^z1)\n s=eq&(alpha1^beta1^gamma1^(y1))\n if(s==0): \n h=bin((~eq)& mask)\n wt=(h[1:].count(\"1\"))\n return math.pow(2,-wt)\n else:\n return -200\n\n\n# In[5]:\n\ndef PDDT1(n,p_thres,k,wt,da,db,dc,s,maxddt,ddt,m):\n if(n==k):\n ddt.append(NMTS(da,db,dc,wt))\n if(wt>=s):\n maxddt.append(NMTS(da,db,dc,wt))\n return \n \n for z in range(0,2):\n new_da= (da & ((2 ** m) - 1))\n new_db= (db & ((2 ** m) - 1))\n new_dc= (dc | (z<= p_thres or ((z==1) and (k+1)!=n)): \n PDDT1(n,p_thres,k+1,wt,da,db,new_dc,s,maxddt,ddt,m+1) \n \n if(len(ddt)==0):\n return 0,ddt,maxddt\n else:\n return 1,ddt,maxddt\n \n\n\n# In[6]:\n\n##fucntion to find output for which weight is max\n\n\n# In[7]:\n\ndef PDDT(n,p_thres,k,wt,da,db,dc,s,maxddt,ddt,m):\n if(n==k):\n ddt.append(NMTS(da,db,dc,wt))\n if(wt>=s):\n s=wt\n maxddt.append(NMTS(da,db,dc,s))\n return \n \n for z in range(0,2):\n new_da= (da & ((2 ** m) - 1))\n new_db= (db & ((2 ** m) - 1))\n new_dc= (dc | (z<= p_thres or ((z==1) and (k+1)!=n)): \n PDDT(n,p_thres,k+1,wt,da,db,new_dc,s,maxddt,ddt,m+1) \n \n if(len(ddt)==0):\n return 0,ddt,maxddt\n else:\n return 1,ddt,maxddt\n \n \n\n\n# ### function to perform left and right circular rotation \n\n# In[8]:\n\n\n#right circular shifts\ndef ROR(x,r):\n x = ((x << (SPECK_TYPE - r)) + (x >> r)) & mask\n return x\n\n#left circular shifts\ndef ROL(x,r):\n x = ((x >> (SPECK_TYPE - r)) + (x << r)) & mask\n return x\n\n\n# ### main function for threshold search\n\n# In[9]:\n\ndef threshold_search(n,nrounds,hw,B_cap,B_bar,B_barlist,st0,st1,op,w1):\n if(n == 0): \n B_cap_temp[nrounds-1]=w1*B_cap[nrounds-1-(n+1)]\n if(B_cap_temp[nrounds-1]>B_bar):\n B_barlist[n]=w1\n trail_cap[n]= NMTS(ROL(st1,alpha),st0,op,w1)\n st1=op\n st0=ROL(st0,beta)^st1\n return threshold_search(n+1,nrounds,hw,B_cap,B_bar,B_barlist,st0,st1,op,w1)\n else:\n return B_bar,B_cap \n \n if((n > 0) & (n != (nrounds - 1))):\n st1=ROR(st1,alpha)\n p_min=p_minimum(n,trail_cap,B_cap,B_bar)\n croad=[]\n #function that check output is in highway and weight is greater than p_min or not, if it is update croad\n maxddt,ddt,max_p=[],[],0\n ck,ddt,maxddt=PDDT1(SPECK_TYPE,0.1,0,1,st1,st0,0,p_min,maxddt,ddt,1)\n if(ck==1):\n for i in range(0,len(maxddt)):\n croad.append(NMTS(maxddt[i].dx,maxddt[i].dy,maxddt[i].dz,maxddt[i].wt))\n \n #opcheck_in_highways(0,p_min,st1,st0)\n #if croad is still empty then fill it with max probility value for other outputs except highway\n if(len(croad) == 0):\n crddt,ddt,max_p=[],[],0\n #print(st1,st0,max_p)\n ck,ddt,crddt=PDDT(SPECK_TYPE,0,0,1,st1,st0,0,max_p,crddt,ddt,1)\n #max_p,output,ck=max(0,st1,st0)\n if(ck==1):\n for i in range(0,len(crddt)):\n croad.append(NMTS(crddt[i].dx,crddt[i].dy,crddt[i].dz,crddt[i].wt))\n else:\n return B_bar,B_cap\n \n #check the inputs in highway or not \n crhw = []\n temphw=[]\n maxddt,ddt,max_p=[],[],0\n ck,ddt,maxddt=PDDT(SPECK_TYPE,0.1,0,1,st1,st0,0,max_p,maxddt,ddt,1)\n if(ck==1):\n for i in range(0,len(ddt)):\n crhw.append(NMTS(ddt[i].dx,ddt[i].dy,ddt[i].dz,ddt[i].wt))\n \n for i in range(0,len(croad)):\n crhw.append(NMTS(croad[i].dx,croad[i].dy,croad[i].dz,croad[i].wt))\n\n \n p_r=1\n for i in range(0,n):\n p_r *= trail_cap[i].wt\n for i in range(0,len(crhw)):\n B_cap_temp[nrounds-1]= p_r * crhw[i].wt * B_cap[nrounds - 1 - (n + 1)]\n if(B_cap_temp[nrounds-1]>B_bar):\n B_barlist[n]=p_r * crhw[i].wt\n trail_cap[n]=NMTS(ROL(crhw[i].dx,alpha),crhw[i].dy,crhw[i].dz,crhw[i].wt)\n st1=crhw[i].dz\n st0=ROL(st0,beta)^st1\n return threshold_search(n+1,nrounds,hw,B_cap,B_bar,B_barlist,st0,st1,op,w1)\n else:\n return B_bar,B_cap\n return B_bar,B_cap\n \n if(n ==(nrounds - 1)):\n st1=ROR(st1,alpha)\n crddt,ddt,max_p=[],[],0\n ck,ddt,crddt=PDDT(SPECK_TYPE,0.1,0,1,st1,st0,0,max_p,crddt,ddt,1)\n if(ck==1):\n p=crddt[0].wt\n op=crddt[0].dz\n else:\n crddt,ddt,max_p=[],[],0\n ck,ddt,crddt=PDDT(SPECK_TYPE,0,0,1,st1,st0,0,max_p,crddt,ddt,1)\n if(ck==1):\n p=crddt[0].wt\n op=crddt[0].dz\n if(p>=0.1):\n hw.append(NMTS(st1,st0,op,p))\n \n if(ck==0):\n return B_bar,B_cap \n p_r=1\n for i in range(0,n):\n p_r *= trail_cap[i].wt\n B_cap_temp[nrounds-1]=p * p_r\n if(B_cap_temp[nrounds-1]>B_bar):\n B_barlist[n]=B_cap_temp[nrounds-1]\n trail_cap[n]=NMTS(ROL(st1,alpha),st0,op,p)\n B_bar=B_cap_temp[nrounds-1]\n for i in range(0,len(B_cap)):\n B_cap[i]=B_barlist[i]\n B_bar=B_cap_temp[n] \n for i in range(0,len(trail_cap)):\n print(trail_cap[i].dx,trail_cap[i].dy,trail_cap[i].dz,trail_cap[i].wt)\n return B_bar,B_cap\n else:\n return B_bar,B_cap\n \n\n\n# In[10]:\n\nimport random\nimport math \n#alpha beta are for left and right circular shift \nalpha, beta = 7,2\n#speck total number of round epresented by nrounds\nnrounds,n,s=9,0,0\nSPECK_TYPE=16\nmask,wshift = 2 ** 16 - 1, 15\n#B_cap,B_bar=[0.00048,0.00048,0.0625,0.00048,0.00048,0.00048,0.00048,0.00048,0.00048],1.7763568394002505e-15\nB_cap,B_bar=[2**(-11),2**(-22),2**(-33),2**(-38),2**(-49),2**(-60),2**(-71),2**(-82),2**(-91)],2 ** (-91)\nB_barlist=[0]*nrounds\n#B_cap,B_bar=[2**(-11),2**(-22),2**(-33),2**(-38)],2 ** (-38)\ntrail_cap,trail_bar=[0]*nrounds, [0]*nrounds\ncroad,hw,B_cap_temp=[],[],[0]*nrounds\n#st0=0xA60\n#st1=0x4205\nmax_p,output=0,0\nmaxddt,ddt,max_p=[],[],0\nprint (\"%.30f\" % B_bar)\nclass NMTS(object):\n \"\"\"__init__() functions as the class constructor\"\"\"\n def __init__(self, dx=None, dy=None, dz=None, wt=None):\n self.dx = dx\n self.dy = dy\n self.dz = dz\n self.wt = wt\n \nhighwaylist()\nfor ch in range(14378,len(hw)):\n #print(n,nrounds,B_bar,hw[ch].dx,hw[ch].dy,hw[ch].dz,hw[ch].wt)\n B_bar,B_cap =threshold_search(n,nrounds,hw,B_cap,B_bar,B_barlist,hw[ch].dx,hw[ch].dy,hw[ch].dz,hw[ch].wt)\n print(B_bar,ch)\n\n","sub_path":"SPECK16/TH16-HW.py","file_name":"TH16-HW.py","file_ext":"py","file_size_in_byte":7930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"399984657","text":"def sol():\n N, M = map(int, input().split())\n edge = [[] for _ in range(N)]\n\n for _ in range(M):\n a, b = map(int, input().split())\n a -= 1\n b -= 1\n edge[a].append(b)\n\n dp = [0] * (1 << N)\n dp[0] = 1\n\n for mask in range(1 << N):\n for digit in range(N):\n if mask & (1 << digit) != 0:\n other = mask ^ (1 << digit)\n for back in edge[digit]:\n if other & (1 << back) != 0:\n break\n else:\n dp[mask] += dp[other]\n\n print(dp)\n print(dp[(1 << N) - 1])\n\nsol()","sub_path":"AtCoder/abc/041d.py","file_name":"041d.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"574931144","text":"# Authors: Paul Boniol, Themis Palpanas\n# Date: 08/07/2020\n# copyright retained by the authors\n# algorithms protected by patent application FR2005261\n# code provided as is, and can be used only for research purposes\n#\n# Reference using:\n#\n# P. Boniol and T. Palpanas, Series2Graph: Graph-based Subsequence Anomaly Detection in Time Series, PVLDB (2020)\n#\n# P. Boniol and T. Palpanas and M. Meftah and E. Remy, GraphAn: Graph-based Subsequence Anomaly Detection, demo PVLDB (2020)\n#\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport math\nfrom scipy.stats import gaussian_kde\nfrom scipy.signal import argrelextrema\nfrom sklearn.decomposition import PCA\nfrom scipy.signal import argrelextrema\nimport networkx as nx\nfrom networkx.drawing.nx_agraph import graphviz_layout\n\n\nfrom .series2graph_tools import *\n\n\nclass Series2Graph():\n\n\tdef __init__(self,pattern_length,latent=None,rate=30):\n\t\tself.pattern_length = pattern_length\n\t\tself.rate = rate\n\t\tif latent is not None:\n\t\t\tself.latent = latent\n\t\telse:\n\t\t\tself.latent = self.pattern_length//3\n\n\t\tself.graph = {}\n\n\tdef fit(self,ts,index=0):\n\t\tmin_df_r = min(ts[index].values)\n\t\tmax_df_r = max(ts[index].values)\n\n\t\tdf_ref = []\n\t\tfor i in np.arange(min_df_r, max_df_r,(max_df_r-min_df_r)/100):\n\t\t\ttmp = []\n\t\t\tT = [i]*self.pattern_length\n\t\t\tfor j in range(self.pattern_length - self.latent):\n\t\t\t\ttmp.append(sum(x for x in T[j:j+self.latent]))\n\t\t\tdf_ref.append(tmp)\n\t\tdf_ref = pd.DataFrame(df_ref)\n\t\t\n\t\tphase_space_1 = build_phase_space(ts[index].values,self.latent,self.pattern_length)\n\n\t\tpca_1 = PCA(n_components=3)\n\t\tpca_1.fit(phase_space_1)\n\t\treduced = pd.DataFrame(pca_1.transform(phase_space_1),columns=[str(i) for i in range(3)])\n\t\treduced_ref = pd.DataFrame(pca_1.transform(df_ref),columns=[str(i) for i in range(3)])\n\n\t\tv_1 = reduced_ref.values[0]\n\n\t\tR = get_rotation_matrix(v_1,[0.0, 0.0, 1.0])\n\t\tA = np.dot(R,reduced.T)\n\t\tA_ref = np.dot(R,reduced_ref.T)\n\t\tA = pd.DataFrame(A.T,columns=['0','1','2'])\n\t\tA_ref = pd.DataFrame(A_ref.T,columns=['0','1','2'])\n\t\n\t\tres_point,res_dist = get_intersection_from_radius(A,'0','1',rate=self.rate)\n\t\tnodes_set,node_weight = nodes_extraction(A,'0','1',res_point,res_dist,self.rate)\n\t\tlist_edge,node_evo,time_evo = edges_extraction(A,'0','1',nodes_set,rate=self.rate)\n\t\n\t\tG = nx.DiGraph(list_edge)\n\t\n\t\tdict_edge = {}\n\t\tfor edge in list_edge:\n\t\t\tif str(edge) not in dict_edge.keys():\n\t\t\t\tdict_edge[str(edge)] = list_edge.count(edge)\n\n\t \n\t\tresult = {\n\t\t\t\"Graph\": G,\n\t\t\t\"list_edge\": list_edge,\n\t\t\t\"edge_in_time\": time_evo,\n\t\t\t\"pca_proj\": pca_1,\n\t\t\t\"rotation_matrix\": R,\n\t\t\t\"edge_weigth\": dict_edge,\n\t\t\t\"proj_A\":A,\n\t\t\t\"node_weigth\":node_weight,\n\t\t\t\"node_set\": nodes_set,\n\t\t\t}\n\n\t\tself.graph = result\n\n\tdef score(self,query_length):\n\t\tall_score = []\n\t\tdegree = nx.degree(self.graph[\"Graph\"])\n\t\tfor i in range(0,len(self.graph[\"edge_in_time\"])-int(query_length)):\n\t\t\tP_edge = self.graph[\"list_edge\"][self.graph[\"edge_in_time\"][i]:self.graph[\"edge_in_time\"][i+int(query_length)]]\n\t\t\tscore,len_score = score_P_degree(self.graph[\"edge_weigth\"],P_edge,degree)\n\t\t\tall_score.append(score)\n\n\t\tall_score = [-score for score in all_score]\n\t\tall_score = np.array(all_score)\n\t\tall_score = (all_score - min(all_score))/(max(all_score) - min(all_score))\n\t\t#all_score = running_mean(all_score,self.pattern_length)\n\n\t\tself.all_score = all_score\n\n\t#to optimize\n\tdef plot_graph(self):\n\t\tedge_size = []\n\t\tfor edge in self.graph[\"Graph\"].edges():\n\t\t\tedge_size.append(self.graph[\"list_edge\"].count([edge[0],edge[1]]))\n\t\tedge_size_b = [float(1+(e - min(edge_size)))/float(1+max(edge_size) - min(edge_size)) for e in edge_size]\n\t\tedge_size = [min(e*50,30) for e in edge_size_b]\n\t\tpos = nx.nx_agraph.graphviz_layout(nx.Graph(self.graph[\"list_edge\"]),prog=\"fdp\")\n\t\t\n\t\tplt.figure(figsize=(30,30))\n\t\tdict_node = []\n\t\tfor node in self.graph[\"Graph\"].nodes():\n\t\t\tdict_node.append(1000*self.graph[\"node_weigth\"][int(node.split(\"_\")[0])][int(node.split(\"_\")[1])])\n\t\tnx.draw(self.graph[\"Graph\"],pos, node_size=dict_node,with_labels=True,width=edge_size)\n\n","sub_path":"SourceCode/src/series2graph/series2graph.py","file_name":"series2graph.py","file_ext":"py","file_size_in_byte":4042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"238187322","text":"from __future__ import absolute_import, division, print_function\n\nfrom MDLSTM.utils import _shape, get_blocks\nimport tensorflow as tf\nfrom six.moves import xrange\nfrom tensorflow.contrib.framework.python.ops import variables\nfrom tensorflow.contrib.rnn.python.ops.core_rnn_cell import rnn_cell_impl\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.ops import rnn_cell_impl, array_ops, math_ops, nn_ops, random_ops, rnn, variable_scope\n\n\n\ndef ndlstm_base_unrolled(inputs, noutput, scope=None, reverse=False):\n with variable_scope.variable_scope(scope, \"LSTM_Seq_Unrolled\", [inputs]):\n length, batch_size, _ = _shape(inputs)\n lstm_cell = rnn_cell_impl.BasicLSTMCell(noutput, state_is_tuple=False)\n state = array_ops.zeros([batch_size, lstm_cell.state_size])\n output_u = []\n inputs_u = array_ops.unstack(inputs)\n if reverse:\n inputs_u = list(reversed(inputs_u))\n for i in xrange(length):\n if i > 0:\n variable_scope.get_variable_scope().reuse_variables()\n output, state = lstm_cell(inputs_u[i], state)\n output_u += [output]\n if reverse:\n output_u = list(reversed(output_u))\n outputs = array_ops.stack(output_u)\n return outputs\n\n\ndef ndlstm_base_dynamic(inputs, noutputs, scope=None, reverse=False):\n with variable_scope.variable_scope(scope, \"Sequence_LSTM\", [inputs]):\n _, batch_size, _ = _shape(inputs)\n lstm_cell = rnn_cell_impl.BasicLSTMCell(noutputs, state_is_tuple=True)\n lstm_cell.zero_state(batch_size, tf.float32)\n sequence_length = int(inputs.get_shape()[0])\n sequence_lengths = math_ops.to_int64(array_ops.fill([batch_size], sequence_length))\n if reverse:\n inputs = array_ops.reverse_v2(inputs, [0])\n outputs, _ = rnn.dynamic_rnn(lstm_cell, inputs, sequence_lengths, dtype=tf.float32, time_major=True)\n if reverse:\n outputs = array_ops.reverse_v2(outputs, [0])\n return outputs\n\ndef ndlstm_base(inputs, noutputs, scope=None, reverse=False, dynamic=True):\n if dynamic:\n return ndlstm_base_dynamic(inputs, noutputs, scope=scope, reverse=reverse)\n else:\n return ndlstm_base_unrolled(inputs, noutputs, scope=scope, reverse=reverse)\n\ndef sequence_to_final(inputs, noutputs, scope=None, name=None, reverse=False):\n \"\"\"Run an LSTM across all steps and return only the final state.\n\n Args:\n inputs: (seq_len, batch_size, depth) tensor\n noutputs: size of the output vector\n scope: optional scope name\n name: optional output tensor name\n reverse: switch to run in reverse\n\n Returns:\n batch of size (batch_size, noutputs)\n \"\"\"\n with variable_scope.variable_scope(scope, \"Sequence_to_Final\", [inputs]):\n seq_length, batch_size, _ = _shape(inputs)\n lstm = rnn_cell_impl.BasicLSTMCell(noutputs, state_is_tuple=False)\n state = array_ops.zeros([batch_size, lstm.state_size])\n inputs_u = array_ops.unstack(inputs)\n if reverse:\n inputs_u = list(reversed(inputs_u))\n\n for i in xrange(seq_length):\n if i > 0:\n variable_scope.get_variable_scope().reuse_variables()\n output, state = lstm(inputs_u[i], state)\n outputs = array_ops.reshape(output, [batch_size, noutputs], name=name)\n return outputs\n\n\ndef sequence_softmax(inputs, noutputs, scope=None, name=None, linear_name=None):\n \"\"\"Run a softmax layer over all time_steps of an input sequence\n\n Args:\n inputs: (seq_length, batch_size, depth) tensor\n noutputs: output_depth\n scope: optional scope name\n name: optional name for output tensor\n linear_name: optional name for linear (pre-softmax) output\n\n Returns:\n A tensor of size (seq_length, batch_size, noutputs)\n \"\"\"\n seq_length, _, ninputs = _shape(inputs)\n inputs_u = array_ops.unstack(inputs)\n outputs_u = []\n with variable_scope.variable_scope(scope, \"Sequential_Softmax\", [inputs]):\n initial_w = random_ops.truncated_normal([0 + ninputs, noutputs], stddev=0.1)\n initial_b = constant_op.constant(0.1, shape=[noutputs])\n w = variables.model_variable(\"weights\", initializer=initial_w)\n b = variables.model_variable(\"biases\", initializer=initial_b)\n for i in xrange(seq_length):\n with variable_scope.variable_scope(scope, \"Sequence_Softmax_Step\", [inputs_u[i]]):\n linear = nn_ops.xw_plus_b_v1(inputs_u[i], w, b, name=linear_name)\n output = nn_ops.softmax(linear)\n outputs_u += [output]\n outputs = array_ops.stack(outputs_u, name=name)\n return outputs\n\n\ndef images_to_sequence(tensor):\n batch_size, h, w, channels = _shape(tensor)\n transposed = array_ops.transpose(tensor, [2, 0, 1, 3])\n return array_ops.reshape(transposed, [w, batch_size*h, channels])\n\ndef sequence_to_images(tensor, batch_size):\n w, seq_length, channels = _shape(tensor)\n h = seq_length // batch_size\n reshaped = array_ops.reshape(tensor, [w, batch_size, h, channels])\n return array_ops.transpose(reshaped, [1, 2, 0, 3])\n\n\ndef horizontal_lstm(images, num_filters_out, scope=None):\n with variable_scope.variable_scope(scope, \"Horizontal_LSTM\", [images]):\n batch_size, _, _, _ = _shape(images)\n sequence = images_to_sequence(images)\n with variable_scope.variable_scope(\"lr\"):\n hidden_sequence_lr = ndlstm_base(sequence, num_filters_out//2)\n with variable_scope.variable_scope(\"rl\"):\n hidden_sequence_rl = ndlstm_base(sequence, num_filters_out - num_filters_out//2, reverse=True)\n\n output_sequence = array_ops.concat([hidden_sequence_lr, hidden_sequence_rl], 2)\n output = sequence_to_images(output_sequence, batch_size)\n return output\n\ndef separable_lstm(images, num_filters_out, kernel_size=None, nhidden=None, scope=None):\n with variable_scope.variable_scope(scope, \"Separable_LSTM\", [images]):\n if nhidden is None:\n nhidden = num_filters_out\n if kernel_size is not None:\n images = get_blocks(images, kernel_size)\n with variable_scope.variable_scope(\"horizontal_pass\"):\n hidden = horizontal_lstm(images, nhidden)\n with variable_scope.variable_scope(\"vertical_pass\"):\n transposed = array_ops.transpose(hidden, [0, 2, 1, 3])\n output_transposed = horizontal_lstm(transposed, num_filters_out)\n output = array_ops.transpose(output_transposed, [0, 2, 1, 3])\n return output\n\ndef reduce_to_sequence(images, num_filters_out, scope=None):\n \"\"\"Reduce an image to a sequence by scanning an LSTM over it vertically\n\n Args:\n images: (batch_size, height, width, channels)\n num_filters_out: output layer depth\n scope: optional scope name\n\n Return:\n A (width, batch_size, num_filters_out) sequence\n\n \"\"\"\n with variable_scope.variable_scope(scope, \"Reduce_to_Sequence\", [images]):\n batch_size, h, w, channels = _shape(images)\n transposed = array_ops.transpose(images, [1, 0, 2, 3])\n reshaped = array_ops.reshape(transposed,\n [h, batch_size*w, channels])\n reduced = sequence_to_final(reshaped, num_filters_out)\n output = array_ops.reshape(reduced, [batch_size, w, num_filters_out])\n return output\n\n\ndef reduce_to_final(images, num_filters_out, nhidden=None, scope=None):\n \"\"\" Reduce an image to afinal state by running two lstms\n\n Args:\n images: (batch_size, height, width, channels) tensor\n num_filters_out: output layer depth\n nhidden: hidden layer depth (defaults to num_filters_out)\n scope: optional scope name\n\n Return:\n A (batch_size, num_filters_out) tensor\n \"\"\"\n with variable_scope.variable_scope(scope, \"Reduce_to_Final\", [images]):\n nhidden = nhidden or num_filters_out\n batch_size, h, w, channels = _shape(images)\n transposed = array_ops.transpose(images, [1, 0, 2, 3])\n reshaped = array_ops.reshape(transposed, [h, batch_size*w, channels])\n with variable_scope.variable_scope(\"reduce1\"):\n reduced = sequence_to_final(reshaped, nhidden)\n transposed_hidden = array_ops.reshape(reduced, [batch_size, w, nhidden])\n hidden = array_ops.transpose(transposed_hidden, [1, 0, 2])\n with variable_scope.variable_scope(\"reduce2\"):\n output = sequence_to_final(hidden, num_filters_out)\n return output\n","sub_path":"MDLSTM/lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":8592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"437942395","text":"from abc import ABC, abstractmethod\nimport pracownik\n\n\nclass Klient(ABC):\n __klienci = []\n def __init__(self):\n Klient.__klienci.append(self)\n print('Dodaję klienta ', end='')\n\n\n @staticmethod\n def znajdzKlienta(nazwa_klienta):\n for p in Klient.__klienci:\n if p.getName() == nazwa_klienta:\n print('Znalazłem klienta', p.getName())\n return p\n print('W bazie nie ma takiego klienta')\n\n\n @staticmethod\n def spotkajSie(nazwa_klienta, spotkptr):\n kl = Klient.znajdzKlienta(nazwa_klienta)\n if kl == None:\n nazwa_klienta = input('Podaj prawidłową nazwę klienta: ')\n Klient.spotkajSie(nazwa_klienta, spotkptr)\n return\n else:\n kl._spotkajSie(spotkptr)\n\n\n @abstractmethod\n def _spotkajSie(self, spotkptr):\n pass\n\n\n @staticmethod\n def wypiszKlientow():\n for k in Klient.__klienci:\n print(k.getName())\n\n\n @abstractmethod\n def getName(self):\n pass\n\n\n\nclass Indywidualny(Klient):\n def __init__(self, imie_nazwisko):\n super().__init__()\n self.__imie_nazwisko = imie_nazwisko\n print('(indywidualnego):', self.getName())\n\n\n def _spotkajSie(self, spotkptr):\n spotkptr.dolaczIndywidualny(self)\n\n\n def getName(self):\n return self.__imie_nazwisko\n\n\n\nclass Firma(Klient):\n def __init__(self, nazwa_firmy):\n super().__init__()\n self.__nazwa_firmy = nazwa_firmy\n self.__przedstawiciele = []\n print('(firmę):', self.getName())\n\n\n def dodajPrzedstawiciela(self, przedstawicielptr):\n self.__przedstawiciele.append(przedstawicielptr)\n string = 'Dodaję przedstawiciela firmy ' + self.getName() + ': ' + przedstawicielptr.getName()\n print(string)\n\n\n @staticmethod\n def nowyPrzedstawiciel(): #input\n string = input('Przedstawiciela której firmy chcesz dodać? ')\n firma = Klient.znajdzKlienta(string)\n if firma == None:\n Firma.nowyPrzedstawiciel()\n return\n string = input('Podaj imię i nazwisko nowego przedstawiciela firmy: ')\n p = pracownik.PrzedstawicielKlienta(string, firma)\n firma.dodajPrzedstawiciela(p)\n\n\n def wypiszPrzedstawicieli(self):\n string = 'Przedstawiciele firmy ' + self.getName() + \":\"\n print(string)\n for p in self.__przedstawiciele:\n print(p.getName())\n\n\n def _spotkajSie(self, spotkptr):\n print('Który z przedstawicieli jest na spotkaniu?')\n self.wypiszPrzedstawicieli()\n string = input('Podaj imię i nazwisko przedstawiciela: ')\n for p in self.__przedstawiciele:\n if p.getName() == string:\n spotkptr.dolacz(p)\n return\n print('Firma nie posiada takiego przedstawiciela')\n self._spotkajSie(spotkptr)\n\n\n def getName(self):\n return self.__nazwa_firmy\n","sub_path":"CRM_project/Python/klient.py","file_name":"klient.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"136814692","text":"# This file is part of Indico.\n# Copyright (C) 2002 - 2019 CERN\n#\n# Indico is free software; you can redistribute it and/or\n# modify it under the terms of the MIT License; see the\n# LICENSE file for more details.\n\nfrom __future__ import unicode_literals\n\nfrom flask import session\n\nfrom indico.core import signals\nfrom indico.core.db import db\nfrom indico.modules.categories import logger\nfrom indico.modules.categories.models.categories import Category\n\n\ndef create_category(parent, data):\n category = Category(parent=parent)\n data.setdefault('default_event_themes', parent.default_event_themes)\n data.setdefault('timezone', parent.timezone)\n category.populate_from_dict(data)\n db.session.add(category)\n db.session.flush()\n signals.category.created.send(category)\n logger.info('Category %s created by %s', category, session.user)\n return category\n\n\ndef delete_category(category):\n category.is_deleted = True\n db.session.flush()\n signals.category.deleted.send(category)\n logger.info('Category %s deleted by %s', category, session.user)\n\n\ndef move_category(category, target_category):\n category.move(target_category)\n logger.info('Category %s moved to %s by %s', category, target_category, session.user)\n\n\ndef update_category(category, data, skip=()):\n category.populate_from_dict(data, skip=skip)\n db.session.flush()\n signals.category.updated.send(category)\n logger.info('Category %s updated by %s', category, session.user)\n","sub_path":"indico/modules/categories/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"495856845","text":"#test program to download photos and shove them in a directory\r\nimport os\r\nimport shutil \r\n# import barcode\r\nfrom xlrd import open_workbook\r\nfrom googleImagesDownloader import *\r\nfrom barcode.writer import ImageWriter\r\n\r\n\r\n'''\r\n\tThis is a comment\r\n'''\r\ndef moveImToFolder():\r\n # Path of the \r\n # source: \"/mnt/c/Users/derri/Desktop/Coding/work/downloads/\"\r\n # destination: \"/mnt/c/Users/derri/Desktop/Coding/work/Covers\"\r\n source = os.getcwd() + \"/downloads/\"\r\n destination = os.getcwd() + \"/Covers\"\r\n\r\n print(\"Source: \" + source)\r\n print(\"Destination\" + destination)\r\n\r\n if not os.path.exists(destination):\r\n os.makedirs(destination)\r\n\r\n i = 0\r\n\r\n for f in os.listdir(source):\r\n i+=1\r\n imgPath = source + f + \"/\"\r\n print(imgPath)\r\n for ff in os.listdir(imgPath):\r\n # print(ff)\r\n # print(os.getcwd())\r\n if ff.endswith(\".jpg\"):\r\n prevName = imgPath + ff\r\n newName = imgPath + f + \".jpg\"\r\n os.rename(prevName, newName)\r\n shutil.move(newName, destination)\r\n\r\n # Removes \".../downloads/\" directory\r\n shutil.rmtree(source)\r\n print(\"Total number of items: \" + str(i))\r\n\r\ndef moveBarcodesToFolder():\r\n # source = \"/mnt/c/Users/derri/Desktop/Coding/visStudioTest/\"\r\n # destination = \"/mnt/c/Users/derri/Desktop/Coding/visStudioTest/Barcode\"\r\n source = os.getcwd() + \"/\"\r\n destination = os.getcwd() + \"/Barcode\"\r\n\r\n print(\"Source: \" + source)\r\n print(\"Destination: \" + destination)\r\n\r\n if not os.path.exists(destination):\r\n os.makedirs(destination)\r\n \r\n for f in os.listdir(source):\r\n if f.endswith(\".png\"):\r\n shutil.move(source+f, destination)\r\n\r\n\r\n# main:\r\ndef downloadEverything():\r\n if downloadCovers() is True:\r\n print(\"Printing barcodes as there is a file\")\r\n downloadBarcodes()\r\n\r\ndef downloadCovers():\r\n # downloads the barcodes\r\n # you probably should rewrite this\r\n #loc = (\"/mnt/c/Users/derri/Desktop/Coding/work/excel/test.xls\")\r\n loc = os.getcwd() + \"/ExcelFolder/testExcel.xls\"\r\n print(loc)\r\n\r\n if not os.path.exists(loc):\r\n print(\"1\")\r\n return False\r\n else:\r\n wb = open_workbook(loc, \"rb\")\r\n sheet = wb.sheet_by_index(0)\r\n sheet.cell_value(0,0)\r\n\r\n newBooksList = []\r\n\r\n for i in range(sheet.nrows):\r\n if (sheet.cell_value(i,0) != \"STOCK CODE\"):\r\n newBooksList.append(sheet.cell_value(i,0))\r\n print(sheet.cell_value(i,0))\r\n else:\r\n #to skip the ISBN name label\r\n print(\"1\")\r\n\r\n print(newBooksList)\r\n\r\n for book in newBooksList:\r\n if book == '':\r\n print (\"2\")\r\n else:\r\n downloadimages(book)\r\n print()\r\n\r\n moveImToFolder()\r\n return True\r\n\r\ndef downloadBarcodes():\r\n # To start the barcode\r\n import barcode\r\n ISBN = barcode.get_barcode_class('isbn13')\r\n excelFile = (\"/mnt/c/Users/derri/Desktop/Coding/visStudioTest/testExcel.xls\")\r\n wb = open_workbook(excelFile, \"rb\")\r\n sheet = wb.sheet_by_index(0)\r\n sheet.cell_value(0,0)\r\n\r\n for i in range(sheet.nrows):\r\n if (sheet.cell_value(i,0) != \"STOCK CODE\" and sheet.cell_value(i,0) != \"\"):\r\n # print(sheet.cell_value(i,0))\r\n # print(type(sheet.cell_value(i,0)))\r\n # print(type('9781456123789'))\r\n num = sheet.cell_value(i,0)\r\n barcode = ISBN(num, writer = ImageWriter())\r\n # filename = barcode.save(\"/mnt/c/Users/derri/Desktop/Coding/visStudioTest/Barcode\"+sheet.cell_value(i,0))\r\n filename = barcode.save(sheet.cell_value(i,0))\r\n\r\n\r\n else:\r\n #just skip to the next one\r\n print(\"No isbn\")\r\n\r\n moveBarcodesToFolder()\r\n\r\n\r\n","sub_path":"ImagesDownloader.py","file_name":"ImagesDownloader.py","file_ext":"py","file_size_in_byte":3893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"173600027","text":"from django.urls import path\nfrom rest_framework_simplejwt.views import (\n TokenRefreshView,\n)\nfrom .views import(\n CustomTokenObtainPairView,\n RegisterView,\n UserProfileDetail,\n UserProfileUpdate,\n UserDiseaseHistory\n)\n\nurlpatterns = [\n path('login/', CustomTokenObtainPairView.as_view(), name='token_obtain_pair'),\n path('login/refresh/', TokenRefreshView.as_view(), name='token_refresh'),\n path('register/', RegisterView.as_view(), name='user_register'),\n path('profile/', UserProfileDetail, name='user_profile'),\n path('profile/update/', UserProfileUpdate, name='user_profile_update'),\n path('disease-history/', UserDiseaseHistory, name='user_disease_history'),\n\n]\n","sub_path":"account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"645914619","text":"import time\r\ndef selection_Sort(data,drawData,timeTick):\r\n\r\n for i in range(len(data)):\r\n min_x = i\r\n\r\n for item in range(i+1, len(data)):\r\n if data[item] < data[min_x]:\r\n min_x = item\r\n\r\n data[i], data[min_x] = data[min_x], data[i]\r\n drawData(data, ['green' if x == i or x == i+1 else 'red' for x in range(len(data))] )\r\n time.sleep(timeTick)\r\n","sub_path":"selectionsort.py","file_name":"selectionsort.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"421467589","text":"#check your neural network input\n#feed-forward network\nimport numpy as np\ndef balance(input_x=[],weights_x=[],a=[],b=[]):\n import numpy as np\n x = input_x\n w = weights_x\n x = np.array(x)\n w = np.array(w)\n x = np.reshape(x,-1)\n w = np.reshape(w,-1)\n #print(x)\n #print(w)\n x_comb = len(x)\n w_comb = len(w)\n #print(x_comb,w_comb)\n x_sh = x.reshape(a[0],a[1])\n w_sh = w.reshape(b[0],b[1])\n if a[0] == b[1]:\n print(\"Dot product Possible 😁\",[a[0],b[1]])\n else:\n print(\"Invalid data-shape-feed..dot-product fails😭\") \n","sub_path":"weights-inputs.py","file_name":"weights-inputs.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"601772917","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.9-x86_64/egg/tests/test_pid_storage.py\n# Compiled at: 2020-04-03 13:49:55\n# Size of source mod 2**32: 826 bytes\nimport pytest\nfrom konduit.load import server_from_file\nfrom konduit.load import store_pid, pop_pid\nfrom konduit.server import stop_server_by_pid\n\n@pytest.mark.unit\ndef test_pid_storage():\n file_path = 'yaml/konduit.yaml'\n store_pid(file_path, 123)\n pid = pop_pid(file_path)\n assert pid == 123\n\n\n@pytest.mark.integration\ndef test_pid_creation_removal():\n file_path = 'yaml/konduit.yaml'\n running_server = server_from_file(file_path, start_server=True)\n pid = running_server.process.pid\n store_pid(file_path=file_path, pid=(running_server.process.pid))\n del running_server\n recov_pid = pop_pid(file_path=file_path)\n assert pid == recov_pid\n stop_server_by_pid(recov_pid)","sub_path":"pycfiles/konduit-0.1.8-py3.7/test_pid_storage.cpython-37.py","file_name":"test_pid_storage.cpython-37.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"19626834","text":"# -*- coding: utf-8 -*-\n\"\"\"\n===============================================\nconfig module\n===============================================\n\n========== ====================================\n========== ====================================\n Module config module\n Date 2019-03-26\n Author heewinkim\n========== ====================================\n\n*Abstract*\n\n * config 읽기 모듈입니다.\n\n >>> EXAMPLE\n py_config = PyConfig()\n print(py_config.log_path)\n\n===============================================\n\"\"\"\n\nimport os\nimport configparser\n\ncurrent_dir = os.path.dirname(os.path.abspath(__file__))\n\n\nclass PyConfig(object):\n \"\"\"\n PyConfig 클래스\n\n 스냅스 API 운영시 configuration에 대한\n 처리를 담당하는 클래스 입니다.\n\n \"\"\"\n\n def __init__(self,config_dirpath=current_dir):\n \"\"\"\n common 파일 로드 및 데이터 저장\n\n :param config_dirpath: py_api.conf 파일 경로\n \"\"\"\n configFilePath = config_dirpath + \"/py_api.conf\"\n\n self.config = configparser.ConfigParser()\n self.config.read(configFilePath, encoding='utf-8')\n\n self.log_path = self.config[\"LOG_INFO\"][\"LOG_PATH\"]\n self.log_rotate = bool(self.config[\"LOG_INFO\"][\"LOG_ROTATE\"]=='True')\n\n self.td_ip = self.config[\"LOG_INFO\"][\"TD_IP\"]\n self.td_port = self.config[\"LOG_INFO\"][\"TD_PORT\"]\n self.td_tag = self.config[\"LOG_INFO\"][\"TD_TAG\"]\n\n\n","sub_path":"utilpack/core/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"149735575","text":"from scipy.optimize import newton\nimport math\n\n\nclass Twu:\n def __init__(self, boil_temp, specific_gravity):\n self.boilTemp = boil_temp\n self.specificGravity = specific_gravity\n self.alkaneCriticalTemperature = self.calc_alkane_critical_temp()\n self.alpha = self.calc_alpha()\n self.alkaneCriticalVolume = self.calc_alkane_critical_volume()\n self.alkaneSpecificGravity = self.calc_alkane_specific_gravity()\n self.alkaneMolecularWeight = self.calc_alkane_mw()\n self.alkaneCriticalPressure = self.calc_alkane_critical_pressure()\n self.criticalTemperature = self.calc_critical_temperature()\n self.criticalVolume = self.calc_critical_volume()\n\n def calc_alkane_critical_temp(self):\n tb = self.boilTemp\n tc = tb * (0.533272 + (0.191017e-3 * tb) + (0.779681e-7 * tb ** 2) - (0.284376e-10 * tb ** 3) + (\n 0.959468e28 / tb ** 13)) ** (-1)\n return tc\n\n def calc_alpha(self):\n return 1 - (self.boilTemp / self.alkaneCriticalTemperature)\n\n def calc_alkane_critical_volume(self):\n vc = (1 - (\n 0.419869 - 0.505839 * self.alpha - 1.56436 * self.alpha ** 3 - 9481.70 * self.alpha ** 14)) ** (-8)\n return vc\n\n def calc_alkane_specific_gravity(self):\n sg = 0.843593 - 0.128624 * self.alpha - 3.36159 * self.alpha ** 3 - 13749.5 * self.alpha ** 12\n return sg\n\n def objective_function(self, theta):\n a = math.exp((5.71419 + 2.71579*theta - 0.286590*theta**2 - 39.8544/theta - 0.122488/theta**2))\n return a - 24.7522*theta + 35.3155*theta**2 - self.boilTemp\n\n def calc_alkane_mw(self):\n mw_guess = self.boilTemp/(10.44 - 0.0052*self.boilTemp)\n theta_guess = math.log(mw_guess)\n theta = newton(self.objective_function, theta_guess)\n return math.exp(theta)\n\n def calc_alkane_critical_pressure(self):\n a = 3.83354\n b = 1.19629\n c = 34.8888\n d = 36.1952\n e = 104.193\n return (a + b*self.alpha**0.5 + c*self.alpha + d*self.alpha**2 + e*self.alpha**4)**2\n\n def calc_critical_temperature(self):\n a = 0.362456\n b = 0.0398285\n c = 0.948125\n delta_sg_t = math.exp(5*(self.alkaneSpecificGravity - self.specificGravity))-1\n ft = delta_sg_t*(-a/self.boilTemp**0.5 + (b - c/self.boilTemp**0.5)*delta_sg_t)\n tc = self.alkaneCriticalTemperature*((1 + 2*ft)/(1 - 2*ft))**2\n return tc\n\n def calc_critical_volume(self):\n a = 0.466590\n b = 0.182421\n c = 3.01721\n delta_sg_v = math.exp(4*(self.alkaneSpecificGravity**2 - self.specificGravity**2)) - 1\n fv = delta_sg_v*(a/self.boilTemp**0.5 + (-b + c/self.boilTemp**0.5)*delta_sg_v)\n vc = self.alkaneCriticalVolume*((1 + 2*fv)/(1 - 2*fv))**2\n return vc\n\n\nif __name__ == '__main__':\n var = Twu(919.34, 1.097)\n\n print(\"The Boiling point is {:0.2f} R\".format(var.boilTemp))\n print(\"The specific gravity is {:0.3f}\".format(var.specificGravity))\n print(\"The alkane specific gravity is {:0.3f}\".format(var.alkaneSpecificGravity))\n print(\"The alkane critical temperature is {:0.2f} R\".format(var.alkaneCriticalTemperature))\n print(\"The alkane critical volume {:0.2f} ft3 lb-1 mol-1\".format(var.alkaneCriticalVolume))\n print(\"The alkane critical pressure is {:0.2f} psia\".format(var.alkaneCriticalPressure))\n print(\"The component critical temperature is {:0.2f} R\".format(var.criticalTemperature))\n print(\"The component critical volume is {:0.3f} ft3 lb-1 mol-1\".format(var.criticalVolume))\n","sub_path":"twu.py","file_name":"twu.py","file_ext":"py","file_size_in_byte":3579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"217265580","text":"from configs.collection_names import RECIPES, USER_RECIPES\nfrom util.database import *\nfrom random import randint\ndb = DB()\n\nsuperVs = [ 'eb35b81adafd11eb892559354efcec79',\n '31f9a248dafe11eb892559354efcec79', \n '4f31261adafe11eb892559354efcec79',\n '81a431bedafe11eb892559354efcec79',\n '9f0cf330dafe11eb892559354efcec79',\n 'e1c10018dafe11eb892559354efcec79',\n 'f014d838dafe11eb892559354efcec79',\n '0010aba4daff11eb892559354efcec79',\n '17f78c60daff11eb892559354efcec79',\n '609a46ecdaff11eb892559354efcec79']\n\nmeal_types = [\n \"Chinese cuisine\",\"French cuisine\",\"Italian cuisine\",\"Indian cuisine\",\n \"Japanese cuisine\",\"Greece cuisine\",\"Spanish cuisine\",\n \"Thai cuisine\",\"Turkish cuisine\",\"Indonesian cuisine\",\n \"Korean cuisine\",\"Mongolian cuisine\",\"Filipino cuisine\",\n \"Malaysian cuisine\",\"Singaporean cuisine\",\"Vietnamese cuisine\",\n \"Canadian cuisine\",\"American cuisine\",\"Mexican cuisine\", \"Mediterranean cuisine\",\n \"Cuisines of the Balkans\",\"Portuguese cuisine\",\"Dutch cuisine\",\"Cuisines of the Islands of the North Atlantic\",\n \"German cuisine\",\"Central European cuisine\",\"Russian cuisine\",\"Ukrainian cuisine\",\"Caucasian cuisine\",\n \"Eastern European cuisine\",\"Nordic cuisines\",\"Baltic cuisines\",\n \"Iranian cuisine\",\"South Caucasus cuisine\",\"Arab cuisine\",\"Pakistani cuisine\",\n \"Nepalese cuisine\",\"Bangladeshi cuisine\",\"Central Asian cuisine\",\n \"Central American cuisine\",\"Argentinian cuisine\",\"Colombian cuisine\",\n \"Brazilian cuisine\",\"Venezuelan cuisine\",\"Caribbean cuisine\",\"Latin American cuisine\",\n \"Central African cuisine\",\"East African cuisine\",\"North African cuisine\",\"Southern African cuisine\",\n \"West African cuisine\",\n]\n\ntotal = 0\nfor uid in superVs:\n rids = db.get_one_from_collection(USER_RECIPES, 'user_id', uid)['recipe_list']\n print('now user ', uid, '\\n')\n for r in rids:\n rid = r['recipe_id']\n total += 1\n db.update_one_from_collection(RECIPES, '_id', rid, meal_type=[meal_types[randint(0,len(meal_types)-1)]])\n if total % 100 == 0:\n print('now {} recipe edited'.format(total))\n\nprint('totally {} recipe edited'.format(total))","sub_path":"COMP9900/capstoneproject-comp9900-h18a-yyds/YYDSFinalSoftwareQuality/backend/dbLoading/dataedit.py","file_name":"dataedit.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"426427019","text":"import requests\nfrom lxml import etree\n\nheaders = {\"user-agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36\"}\n\nstart_url = \"https://en.wikipedia.org/wiki/Brain\"\nhostname = \"https://en.wikipedia.org\"\n\nwith open(\"C:\\\\Users\\\\acer\\\\Desktop\\\\wiki\\\\wikiLink.dict\", \"rt\") as f:\n list_url = f.read().split(\"\\n\")\n\nwith open(\"C:\\\\Users\\\\acer\\\\Desktop\\\\wiki\\\\wiki.dict\", \"rb\") as f:\n dict_list = f.read().decode(\"utf-8\").split(\"\\n\")\n\nwith open(\"C:\\\\Users\\\\acer\\\\Desktop\\\\wiki\\\\wikiNone.dict\", \"rb\") as f:\n none_list = f.read().decode(\"utf-8\").split(\"\\n\")\n\nlist_url.remove(\"\")\ndict_list.remove(\"\")\nnone_list.remove(\"\")\n\nurl_set = set(list_url)\ndict_set = set(dict_list)\nnone_set = set(none_list)\n\nurl_set.add(start_url)\n\n\n\ndef getDict(url, headers):\n print(\"Get:\" + url + \"\\n\")\n html = requests.get(url, headers = headers).text\n html = etree.HTML(html)\n cur_eng = html.cssselect(\"title\")[0].text[:-12]\n temp_tag = html.cssselect(\"#p-lang .body .interwiki-zh a\")\n if temp_tag != []:\n cur_chi = temp_tag[0].attrib[\"title\"][:-10]\n else:\n cur_chi = \" \"\n s = cur_eng + \":\" + cur_chi\n if cur_chi == \" \" and cur_eng not in none_set:\n none_set.add(cur_eng)\n with open(\"C:\\\\Users\\\\acer\\\\Desktop\\\\wiki\\\\wikiNone.dict\", \"ab\") as f:\n f.write((cur_eng + \"\\n\").encode(\"utf-8\"))\n elif s not in dict_set and cur_chi != \" \":\n dict_set.add(s)\n with open(\"C:\\\\Users\\\\acer\\\\Desktop\\\\wiki\\\\wiki.dict\", \"ab\") as f:\n f.write((s+\"\\n\").encode(\"utf-8\"))\n print(\"Write: \" + s + \" successfully!\\n\")\n\n next_urls = html.cssselect(\"#mw-content-text .mw-parser-output > p a\")\n for next_url in next_urls:\n try:\n rel_url = next_url.attrib[\"href\"]\n except:\n continue\n if rel_url[1:5] == \"wiki\" and \"https://en.wikipedia.org\" + rel_url not in url_set:\n url_set.add(\"https://en.wikipedia.org\" + rel_url)\n\n with open(\"C:\\\\Users\\\\acer\\\\Desktop\\\\wiki\\\\wikiLink.dict\", \"ab\") as f:\n f.write((\"https://en.wikipedia.org\" + rel_url + \"\\n\").encode(\"utf-8\"))\n getDict(\"https://en.wikipedia.org\" + rel_url, headers)\nif list_url == []:\n with open(\"C:\\\\Users\\\\acer\\\\Desktop\\\\wiki\\\\wikiLink.dict\", \"ab\") as f:\n f.write((start_url+\"\\n\").encode(\"utf-8\"))\n getDict(start_url, headers)\nelse:\n getDict(list_url[-1], headers)","sub_path":"python-web-scraping/wiki/wikiDict.py","file_name":"wikiDict.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"401981138","text":"\"\"\"\n * Copyright (C) 2021 Axis Communications AB, Lund, Sweden\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\n\"\"\" model.py\n Defines the model's structure and configuration.\n\"\"\"\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras import backend as K\n\n\ndef _residual_block(x, n_filters, strides=1):\n \"\"\" Produces a residual convolutional block as seen in\n https://en.wikipedia.org/wiki/Residual_neural_network\n\n Args:\n x: The input tensor\n n_filters (int): The number of filters for the convolutional layers\n\n Returns:\n x: The output tensor\n \"\"\"\n shortcut = x\n\n x = Conv2D(n_filters, 3, strides=strides, padding='same')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n\n x = Conv2D(n_filters, 3, padding='same')(x)\n x = BatchNormalization()(x)\n\n shortcut = Conv2D(n_filters, 1, strides=strides, padding='same')(shortcut)\n shortcut = BatchNormalization()(shortcut)\n\n x = Add()([shortcut, x])\n x = Activation('relu')(x)\n return x\n\n\ndef create_model(blocks=4, n_filters=16):\n \"\"\" Defines and instantiates a model.\n\n Args:\n blocks (int): The number of residual blocks to apply. Each such block\n halves the width and height of its input.\n n_filters (int): The number of filters in the first residual block.\n This number is doubled for each residual block.\n\n Returns:\n model: The instantiated but uncompiled model.\n \"\"\"\n img_in = Input(shape=(256, 256, 3))\n\n x = img_in\n for block_index in range(blocks):\n x = _residual_block(x, n_filters * 2 ** block_index)\n x = _residual_block(x, n_filters * 2 ** (block_index + 1), strides=2)\n\n # Global max pooling is not supported on the Edge TPU yet\n # but this is an equivalent procedure made of supported operations\n side_size = K.int_shape(x)[-2]\n x = MaxPooling2D(side_size)(x)\n x = Flatten()(x)\n\n x = Dense(64, activation='relu')(x)\n person_pred = Dense(1, activation='sigmoid', name='A_person_pred')(x)\n car_pred = Dense(1, activation='sigmoid', name='B_car_pred')(x)\n\n return Model(img_in, [person_pred, car_pred], name='person_car_indicator')\n","sub_path":"tensorflow-to-larod/env/training/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"227765196","text":"import math\n\nWIDTH = 100\nBALLS = {i: 30 + i for i in range(21)}\nUPPER_BOUND = 2 * sum(BALLS.values())\n\n\ndef distance(r_top, r_second):\n return (\n math.sqrt((r_top + r_second) ** 2 - (WIDTH - r_top - r_second) ** 2)\n + r_top\n - r_second\n )\n\n\noptimize_cache = {}\n\n\ndef optimize(top, bitmask):\n if not bitmask:\n return 2 * BALLS[top]\n if (top, bitmask) in optimize_cache:\n return optimize_cache[(top, bitmask)]\n ret = UPPER_BOUND\n for i in range(21):\n if not bitmask & (1 << i):\n continue\n ret = min(ret, distance(BALLS[top], BALLS[i]) + optimize(i, bitmask ^ (1 << i)))\n optimize_cache[(top, bitmask)] = ret\n return ret\n\n\nans = round(1000 * min(optimize(i, ((1 << 21) - 1) ^ (1 << i)) for i in range(21)))\n\nassert 1590933 == ans\n","sub_path":"p222.py","file_name":"p222.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"356383075","text":"import numpy as np\nimport cv2\nimport scipy.signal\nimport random as rng\nfrom matplotlib import pyplot as plt\nimport matplotlib.mlab as mlab\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.utils.data as utils\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\ndef test1(img1,img2): #SIMPLE COLOUR GRAB USING HSV\n # cv2.imwrite(\"pls.jpg\", img2)\n\n img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2HSV)\n img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)\n\n width, height, depth = img1.shape\n width = np.round(width/2).astype(int)\n height = np.round(height/2).astype(int)\n\n # R1 = img1[width,height,2]\n # B1 = img1[width,height,1]\n # G1 = img1[width,height,0]\n\n R1 = 0\n B1 = 0\n G1 = 0\n\n R2 = 0\n B2 = 0\n G2 = 0\n\n for i in range(5):\n for j in range(5):\n R1 += img1[width-2+i,height-2+j,2]\n B1 += img1[width-2+i,height-2+j,1]\n G1 += img1[width-2+i,height-2+j,0]\n\n R2 += img2[width-2+i,height-2+j,2]\n B2 += img2[width-2+i,height-2+j,1]\n G2 += img2[width-2+i,height-2+j,0]\n\n\n # R2 = img2[width,height,2]\n # B2 = img2[width,height,1]\n # G2 = img2[width,height,0]\n\n R1 = R1/25\n R2 = R2/25\n\n B1 = B1/25\n B2 = B2/25\n\n G1 = G1/25\n G2 = G2/25\n\n # print(np.round(R1 - R2))\n # print(np.round(B1 - B2))\n # print(np.round(G1 - G2))\n\n # print(R1 - R2, B1 - B2, G1 - G2)\n\n if(R2 < R1 + 50 and R2 > R1 - 50):\n if(B2 < B1 + 30 and B2 > B1 - 30):\n if(G2 < G1 + 15 and G2 > G1 - 15):\n return 0\n\n\n return 1\n\ndef test2(img1,img2): #ATTEMPT TO DETECT SQUARE SOLDER PADS\n\n img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)\n\n lower = np.array([0, 0, 0], dtype = \"uint8\")\n upper = np.array([255, 80, 255], dtype = \"uint8\")\n mask = cv2.inRange(img2, lower, upper)\n\n mask = np.pad(mask,((10,10),(10,10)),'constant',constant_values=((0, 0),(0,0)))\n\n image, contours, hierarchy = cv2.findContours(mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n img = img2\n count = 0\n\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n img = np.pad(gray,((10,10),(10,10)),'constant',constant_values=((0, 0),(0,0)))\n\n for cnt in contours:\n\n approx = cv2.approxPolyDP(cnt,0.12*cv2.arcLength(cnt,True),True)\n\n\n if len(approx)==4:\n rect = cv2.minAreaRect(cnt)\n width = rect[1][0]\n height = rect[1][1]\n\n if ((width >= 5) and (height > 5)):\n count += 1\n cv2.drawContours(img,[cnt],0,(255),0)\n\n\n # if(count > 1):\n\n # img = np.concatenate((img, mask), axis=1)\n # plt.imshow(img, cmap = 'gray')\n # plt.show()\n\n if(count > 1):\n return 0\n else:\n return 1\n\ndef test3(img1,img2): #CORRELATION TEST\n\n img1 = cv2.resize(img1,None,fx=0.5, fy=0.5, interpolation = cv2.INTER_CUBIC)\n img2 = cv2.resize(img2,None,fx=0.5, fy=0.5, interpolation = cv2.INTER_CUBIC)\n\n img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\n img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\n\n x,y = img1.shape\n area = x*y\n\n img1 = img1 - np.mean(img1)\n img2 = img2 - np.mean(img2)\n\n maxInd1 = np.unravel_index(np.argmax(img1), img1.shape)\n maxInd2 = np.unravel_index(np.argmax(img2), img2.shape)\n\n minInd1 = np.unravel_index(np.argmin(img1), img1.shape)\n minInd2 = np.unravel_index(np.argmin(img2), img2.shape)\n\n max1 = img1[maxInd1]\n min1 = img1[minInd1]\n\n max2 = img2[maxInd2]\n min2 = img2[minInd2]\n\n if(max1 > -1*min1):\n img1 = img1/max1\n else:\n img1 = img1/(-1*min1)\n\n if(max2 > -1*min2):\n img2 = img2/max2\n else:\n img2 = img2/(-1*min2)\n\n\n fft1 = np.pad(img1,((0,img2.shape[0]-1),(0,img2.shape[1]-1)),'constant',constant_values=((0, 0),(0,0)))\n fft2 = np.pad(img2,((0,img1.shape[0]-1),(0,img1.shape[1]-1)),'constant',constant_values=((0, 0),(0,0)))\n\n fft1 = np.fft.fft2(fft1)\n fft2 = np.conjugate(np.fft.fft2(fft2))\n\n corr = np.real(np.fft.ifft2(fft1*fft2))\n corr = np.roll(corr, (corr.shape[0] - 1)//2, axis = 0)\n corr = np.roll(corr, (corr.shape[1] - 1)//2, axis = 1) \n\n # corr = scipy.signal.correlate2d(img1, img2)\n corrMax = np.unravel_index(np.argmax(corr), corr.shape)\n # return (corr[corrMax]/area)\n\n if(corr[corrMax]/area > 0.15):\n return 0\n else:\n return 1\n\ndef test4(img1,img2):\n\n test = cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)\n kernel = np.array([[1, 1, 1], [1, -8, 1], [1, 1, 1]], dtype=np.float32)\n\n imgLaplacian = cv2.filter2D(test, cv2.CV_32F, kernel)\n sharp = np.float32(test)\n imgResult = sharp - imgLaplacian\n\n imgResult = np.clip(imgResult, 0, 255)\n imgResult = imgResult.astype('uint8')\n imgLaplacian = np.clip(imgLaplacian, 0, 255)\n imgLaplacian = np.uint8(imgLaplacian)\n\n bw = cv2.cvtColor(imgResult, cv2.COLOR_BGR2GRAY)\n # img2 = imgResult\n _, bw = cv2.threshold(bw, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)\n\n # plt.imshow(bw)\n # plt.show()\n\n width, height, depth = img2.shape\n width = np.round(width/2).astype(int)\n height = np.round(height/2).astype(int)\n\n lower = np.array([60, 60, 60], dtype = \"uint8\")\n upper = np.array([100, 110, 100], dtype = \"uint8\")\n maskRGB = cv2.inRange(img2, lower, upper)\n\n hsv = cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)\n\n lower = np.array([80, 0, 20], dtype = \"uint8\")\n upper = np.array([120, 40, 100], dtype = \"uint8\")\n maskHSV = cv2.inRange(hsv, lower, upper)\n\n CIE = cv2.cvtColor(img2, cv2.COLOR_BGR2LAB)\n\n\n lower = np.array([55, 120, 120], dtype = \"uint8\")\n upper = np.array([100, 135, 135], dtype = \"uint8\")\n maskCIE = cv2.inRange(CIE, lower, upper)\n\n maskADD = cv2.add(maskHSV,maskRGB)\n mask = maskCIE*maskADD\n\n\n # _, contours, _ = cv2.findContours(mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n # mask = np.zeros(mask.shape).astype('uint8')\n # count = 0\n\n # for cnt in contours:\n\n # approx = cv2.approxPolyDP(cnt,0.12*cv2.arcLength(cnt,True),True)\n\n # if len(approx)==4:\n # rect = cv2.minAreaRect(cnt)\n # width = rect[1][0]\n # height = rect[1][1]\n\n # if ((width >= 5) and (height > 5)):\n # count += 1\n # cv2.drawContours(mask,[cnt],0,(255),-1)\n\n\n\n dist = cv2.distanceTransform(mask, cv2.DIST_L2, 3)\n cv2.normalize(dist, dist, 0, 1.0, cv2.NORM_MINMAX)\n\n _, dist = cv2.threshold(dist, 0.4, 1.0, cv2.THRESH_BINARY)\n\n kernel1 = np.ones((3,3), dtype=np.uint8)\n dist = cv2.dilate(dist, kernel1)\n\n dist_8u = dist.astype('uint8')\n\n _, contours, _ = cv2.findContours(dist_8u, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n markers = np.zeros(dist.shape, dtype=np.int32)\n\n for i in range(len(contours)):\n cv2.drawContours(markers, contours, i, (i+1), -1)\n\n markers = cv2.watershed(img2, markers)\n\n mark = markers.astype('uint8')\n mark = cv2.bitwise_not(mark)\n\n colors = []\n for contour in contours:\n colors.append((rng.randint(0,256), rng.randint(0,256), rng.randint(0,256)))\n # Create the result image\n dst = np.zeros((markers.shape[0], markers.shape[1], 3), dtype=np.uint8)\n # Fill labeled objects with random colors\n for i in range(markers.shape[0]):\n for j in range(markers.shape[1]):\n index = markers[i,j]\n if index > 0 and index <= len(contours):\n dst[i,j,:] = colors[index-1]\n\n\n plt.figure('1')\n\n imgResult = cv2.cvtColor(imgResult, cv2.COLOR_BGR2RGB)\n out = np.concatenate((maskRGB,maskHSV,maskCIE,mask), axis = 1)\n # plt.imshow(maskCIE)\n\n # img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)\n # plt.figure('2')\n # plt.imshow(img2)\n\n # plt.show()\n\ndef test5(img1,img2):\n\n RGB1 = [[0,0,0,0], [0,0,0,0], [0,0,0,0]]\n RGB2 = [[0,0,0,0], [0,0,0,0], [0,0,0,0]]\n\n y1,x1,_ = img1.shape\n y2,x2,_ = img2.shape\n\n img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2HSV)\n img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)\n\n R = img1[:,:,2]\n G = img1[:,:,1]\n B = img1[:,:,0]\n\n RGB1[0][0] = np.sum(R < 63)\n RGB1[0][1] = np.sum(np.logical_and((R >= 63),(R < 127)))\n RGB1[0][2] = np.sum(np.logical_and((R >= 127),(R < 191)))\n RGB1[0][3] = np.sum(R >= 191)\n\n RGB1[1][0] = np.sum(B < 63)\n RGB1[1][1] = np.sum(np.logical_and((B >= 63),(B < 127)))\n RGB1[1][2] = np.sum(np.logical_and((B >= 127),(B < 191)))\n RGB1[1][3] = np.sum(B >= 191)\n\n RGB1[2][0] = np.sum(G < 63)\n RGB1[2][1] = np.sum(np.logical_and((G >= 63),(G < 127)))\n RGB1[2][2] = np.sum(np.logical_and((G >= 127),(G < 191)))\n RGB1[2][3] = np.sum(G >= 191)\n\n R = img2[:,:,2]\n G = img2[:,:,1]\n B = img2[:,:,0]\n\n RGB2[0][0] = np.sum(R < 63)\n RGB2[0][1] = np.sum(np.logical_and((R >= 63),(R < 127)))\n RGB2[0][2] = np.sum(np.logical_and((R >= 127),(R < 191)))\n RGB2[0][3] = np.sum(R >= 191)\n\n RGB2[1][0] = np.sum(B < 63)\n RGB2[1][1] = np.sum(np.logical_and((B >= 63),(B < 127)))\n RGB2[1][2] = np.sum(np.logical_and((B >= 127),(B < 191)))\n RGB2[1][3] = np.sum(B >= 191)\n\n RGB2[2][0] = np.sum(G < 63)\n RGB2[2][1] = np.sum(np.logical_and((G >= 63),(G < 127)))\n RGB2[2][2] = np.sum(np.logical_and((G >= 127),(G < 191)))\n RGB2[2][3] = np.sum(G >= 191)\n\n RGB1 = np.array(RGB1)/(x1*y1)\n RGB2 = np.array(RGB2)/(x2*y2)\n\n # print()\n pls = np.abs(RGB1[0] - RGB2[0])\n maxInd = np.unravel_index(np.argmax(pls), pls.shape)\n print(pls[maxInd])\n # plt.imshow(np.concatenate((img1[:,:,1],img2[:,:,1])))\n # plt.show()\n\n # x = np.zeros(20)\n\n # vals = np.linspace(0.17,0.2,20)\n\n # for i in range(20):\n # x[i] = np.allclose(RGB1,RGB2, 0 ,vals[i])\n\n # print(x)\n\n if(np.allclose(RGB1[0],RGB2[0], 0 ,0.05)):\n return 0\n return 1\n\ndef test6(img1,img2):\n\n lower = np.array([140, 140, 140], dtype = \"uint8\")\n upper = np.array([255, 255, 255], dtype = \"uint8\")\n mask = cv2.inRange(img1, lower, upper)\n\n # kernel = np.array([[1, 1, 1], [1, -8, 1], [1, 1, 1]], dtype=np.float32)\n\n # imgLaplacian = cv2.filter2D(img1, cv2.CV_32F, kernel)\n # sharp = np.float32(img1)\n # img1 = sharp - imgLaplacian\n\n # img1 = np.clip(img1, 0, 255)\n # img1 = img1.astype('uint8')\n\n\n # imgLaplacian = cv2.filter2D(img2, cv2.CV_32F, kernel)\n # sharp = np.float32(img2)\n # img2 = sharp - imgLaplacian\n\n # img2 = np.clip(img2, 0, 255)\n # img2 = img2.astype('uint8')\n\n mask2 = np.pad(mask,((10,10),(10,10)),'constant',constant_values=((0, 0),(0,0)))\n\n image, contours, hierarchy = cv2.findContours(mask2,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n indSquare = None\n count = 0\n flag = 1\n\n for cnt in contours:\n\n approx = cv2.approxPolyDP(cnt,0.1*cv2.arcLength(cnt,True),True)\n\n if len(approx)!=1 and len(approx)!=2:\n count += 1\n rect = cv2.minAreaRect(cnt)\n width = rect[1][0]\n height = rect[1][1]\n\n if ((width >= 2) and (height > 2)):\n\n if flag:\n square = approx[:]\n indSquare = approx[:]\n indSquare = [indSquare]\n flag = 0\n else:\n # print(square.shape, count)\n square = np.concatenate((square, approx))\n # indSquare = np.stack((indSquare, approx), axis = 1)\n indSquare.append(approx)\n\n\n\n\n if(indSquare == None):\n return -1\n\n for sqr in indSquare:\n rect = cv2.boundingRect(sqr[:,0,:])\n x,y,w,h = rect\n cv2.rectangle(mask, (x-10,y-10),(x+w-10,y+h-10),(255),-1)\n\n rect = cv2.minAreaRect(square)\n box = cv2.boxPoints(rect)\n box = np.int0(box-10)\n mask3 = np.array(mask)\n\n cv2.drawContours(mask3,[box],0,(255),-1)\n\n mask = 255 - mask\n\n green1 = cv2.cvtColor(img1, cv2.COLOR_BGR2HSV)[:,:,1].astype(int)\n green2 = cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)[:,:,1].astype(int)\n\n # green1 = img1[:,:,1].astype(int)\n # green2 = img2[:,:,1].astype(int)\n\n\n height, width = green1.shape\n # count = 0\n # mean1 = 0\n # mean2 = 0\n # for i in range(height):\n # for j in range(width):\n\n # if(mask3[i,j] == 0):\n # count += 1\n # mean1 += green1[i,j]\n # mean2 += green2[i,j]\n\n # mean1 = mean1/count\n # mean2 = mean2/count\n # print(mean1,mean2)\n\n # mean1 = np.mean(green1)\n # mean2 = np.mean(green2)\n\n # green2 = green2.astype(int) + (mean1 - mean2)\n # green2 = np.clip(green2,0,255).astype('uint8')\n # green1 = green1.astype('uint8')\n mask = mask.astype('uint8')\n\n out = cv2.subtract(green1,green2, mask = mask)\n out = np.clip(out,0,255)\n out = np.round(out).astype('uint8')\n\n\n mask = 255 - mask\n mask4 = np.array(mask3.astype(int) + mask.astype(int))\n mask4 = np.clip(mask4,0,255) - mask.astype(int)\n mask4 = mask4.astype('uint8')\n\n\n dist = cv2.distanceTransform(mask4, cv2.DIST_L2, 3)\n cv2.normalize(dist, dist, 0, 1.0, cv2.NORM_MINMAX)\n\n _, mask4 = cv2.threshold(dist, 0.4, 1.0, cv2.THRESH_BINARY)\n\n # x = np.clip(out.astype(int) + mask4.astype(int), 0,255)\n # gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\n\n\n count = 0\n mean = 0\n\n for i in range(height):\n for j in range(width):\n\n if(mask4[i,j] != 0):\n count += 1\n mean += out[i,j]\n else:\n out[i,j] = 0\n\n if(count == 0):\n return -1\n plt.imshow(np.concatenate((mask,mask4)))\n plt.show()\n mean = mean/count\n\n # print(mean)\n # gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\n # out = np.concatenate((gray,mask,mask4,out), axis = 1)\n # plt.imshow(out,cmap='gray')\n # plt.show()\n # print(mean)\n\n img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)\n kernel = np.array([[1, 1, 1], [1, -8, 1], [1, 1, 1]], dtype=np.float32)\n imgLaplacian = cv2.filter2D(img2, cv2.CV_32F, kernel)\n sharp = np.float32(img2)\n img2 = sharp - imgLaplacian\n\n img2 = np.clip(img2, 0, 255)\n img2 = img2.astype('uint8')\n\n H = cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)[:,:,0]\n S = cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)[:,:,1]\n V = cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)[:,:,2]\n\n # something = np.concatenate((H,S,V),axis = 1)\n # plt.imshow(something)\n # plt.show()\n\n if(mean > 50):\n return 1\n return 0\n\ndef test7(img2, code, model):\n\n # img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)\n # img2 = cv2.resize(img2, (128,128), interpolation = cv2.INTER_CUBIC)\n # img2 = np.swapaxes(img2, 0,2)\n # img2 = np.swapaxes(img2, 1,2)\n\n if(code[0] != 'R' and code[0] != 'C'):\n return -1\n\n cv2.imwrite('temp/temp/pls.jpg', img2)\n\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n\n\n\n dataset = utils.TensorDataset(torch.from_numpy(img2))\n\n dataloader = utils.DataLoader(dataset)\n def load_dataset():\n data_path = 'temp/'\n train_dataset = torchvision.datasets.ImageFolder(\n root=data_path,\n transform = torchvision.transforms.Compose([\n transforms.Resize(64),\n transforms.CenterCrop(64),\n transforms.ToTensor(),\n normalize,\n ])\n )\n train_loader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size=64,\n num_workers=0,\n shuffle=True\n )\n return train_loader\n\n testloader = load_dataset()\n\n dataiter = iter(testloader)\n images, labels = dataiter.next()\n\n for data in testloader:\n images, labels = data\n outputs = model(images)\n _, predicted = torch.max(outputs.data, 1)\n\n return predicted.numpy()[0]\n\ndef testRotation(img1,img2,componentCode):\n\n\n # kernel = np.array([[1, 1, 1], [1, -8, 1], [1, 1, 1]], dtype=np.float32)\n #\n # imgLaplacian = cv2.filter2D(img2, cv2.CV_32F, kernel)\n # sharp = np.float32(img2)\n # img2 = sharp - imgLaplacian\n #\n # img2 = np.clip(img2, 0, 255)\n # img2 = img2.astype('uint8')\n\n\n # CIE = cv2.cvtColor(img2, cv2.COLOR_BGR2LAB)\n #\n #\n # lower = np.array([100, 125, 125], dtype = \"uint8\")\n # upper = np.array([160, 130, 130], dtype = \"uint8\")\n # maskCIE = cv2.inRange(CIE, lower, upper)\n\n\n out = np.concatenate((img1,img2), axis = 1)\n # print(CIE[45, 77,:])\n\n # circle = cv2.HoughCircles(maskCIE, cv2.HOUGH_GRADIENT, 0.5, 20, param1=50,param2=10,minRadius=0,maxRadius=15)\n # print(circle)\n # for i in circle[0,:]:\n # # draw the outer circle\n # cv2.circle(img2,(i[0],i[1]),i[2],(0,255,0),2)\n # # draw the center of the circle\n # cv2.circle(img2,(i[0],i[1]),2,(0,0,255),3)\n\n plt.imshow(img2)\n plt.show()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":16880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"363295030","text":"\"\"\"\nCopyright 2013 Zynga Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport os, sys\nPARENT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(PARENT_DIR)\nfrom asyncon import *\nfrom migrator import *\n\nclass MB:\n def get(self, param):\n return {\"source\": \"127.0.0.1:11211\", \"destination\":\"10.36.175.180:11211\", \"vblist\":[0,1], \"interface\":\"\"}\n\nmb = MB()\nas_mgr = AsynCon()\nm=Migrator(\"key\", mb, None, as_mgr)\nas_mgr.loop()\n","sub_path":"vba/tests/test_migrator.py","file_name":"test_migrator.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"180476277","text":"import math\nimport random\n\nimport random\nimport numpy as np\n\n\n# from_file = \"/Users/amir/Desktop/fxtime/currency.cvs\"\n\n# file_hourly = \"/Users/amir/Desktop/fxtime/cur_hours.csv\"\n# file_daily = \"/Users/amir/Desktop/fxtime/cur_daily.csv\"\n# des_file = \"/Users/amir/Desktop/fxtime/currency_new_version.csv\"\n#\n# file_read_daily = open(file_daily)\n# file_read_hourly = open(file_hourly)\n# open_file_write = open(des_file, \"a\")\n#\n\n\n\n\ndef sigma(x):\n return 1 / (1 + math.exp(-x))\n\n\n\n\ndef comma(daily, write_to_h):\n daily_r = open(daily)\n\n write_w = open(write_to_h, \"a\")\n\n # line = daily_r.readline()\n\n line = daily_r.readline()\n\n while line != \"\":\n s = line.split()\n mod_line = \",\".join(s)\n write_w.write(mod_line + \"\\n\")\n line = daily_r.readline()\n daily_r.close()\n write_w.close()\n\n\ndef reader_hourly(line, file_write):\n\n splitted = line.split(sep=\"\\t\")\n open_price = splitted[2]\n high_price = splitted[3]\n low_price = splitted[4]\n close_price = splitted[5]\n\n if open_price <= close_price:\n result = (round(sigma(float(open_price)), 5), \"buy\")\n else:\n result = (round(sigma(float(open_price)), 5), \"sell\")\n\n file_write.write(str(result[0]) + \" \")\n file_write.write(str(result[1]) + \"\\n\")\n\n return result\n\n\ndef file_reader_hourly(file_to_read, write_to_file):\n file_read = open(file_to_read)\n file_write = open(write_to_file, \"a\")\n line = file_read.readline()\n\n while line != \"\":\n splitted = line.split(sep=\"\\t\")\n open_price = splitted[3]\n high_price = splitted[4]\n low_price = splitted[5]\n close_price = splitted[6]\n\n if open_price <= close_price:\n result = (sigma(float(open_price)), \"buy\")\n else:\n result = (sigma(float(open_price)), \"sell\")\n\n file_write.write(str(result[0]) + \" \")\n file_write.write(str(result[1]) + \"\\n\")\n\n\ndef file_reader_daily(file_to_read, write_to_file):\n file_read = open(file_to_read)\n open_file_to_write = open(write_to_file, \"a\")\n line = file_read.readline()\n line = file_read.readline()\n\n while line != \"\":\n splitted = line.split(sep=\"\\t\")\n open_price = splitted[2]\n high_price = splitted[3]\n low_price = splitted[4]\n close_price = splitted[5]\n\n if open_price <= close_price:\n result = (round(sigma(float(open_price)), 6), \"buy\")\n else:\n result = (round(sigma(float(open_price)), 6), \"sell\")\n\n open_file_to_write.write(str(result[0]) + \" \")\n open_file_to_write.write(str(result[1]) + \"\\n\")\n\n\n# test\n\n# file_daily = \"/Users/amir/Desktop/fxtime/cur_daily.csv\"\n# file_daily = \"/Users/amir/Desktop/fxtime/cur_hours.csv\"\n\n\nfile_daily_write = \"/Users/amir/Desktop/fxtime/hour.csv\"\nfile_hours_write = \"/Users/amir/Desktop/fxtime/day.csv\"\n\n#\n# file_reader_daily(file_daily, file_daily_write)\n# file_reader_hourly(file_hourly, file_hours_write)\n\n\n# provide_data()\n\n\nfile_hourly = \"/Users/amir/Desktop/fxtime/cur_hours.csv\"\nfile_daily = \"/Users/amir/Desktop/fxtime/cur_daily.csv\"\ndes_file1 = \"/Users/amir/Desktop/fxtime/curr_hours_mod.csv\"\ndes_file2 = \"/Users/amir/Desktop/fxtime/curr_daily_mod.csv\"\n\ncomma(file_daily, des_file2)\ncomma(file_hourly, des_file1)\n\n\ndef reader_daily(line, write_to_file):\n \"\"\"\n :param line: the line to be processed and interpreted.\n :type line: String\n :param write_to_file: file to write to\n :type write_to_file: open File\n :return: tupple of values recveied in the string line\n :rtype: tupple of integer and string\n \"\"\"\n\n str2 = \"\"\n splitted = line.split()\n open_price = splitted[1]\n high_price = splitted[2]\n low_price = splitted[3]\n close_price = splitted[4]\n if open_price <= close_price:\n result = (round(sigma(float(open_price)), 5), \"buy\")\n else:\n result = (round(sigma(float(open_price)), 5), \"sell\")\n \n str2 = str(result[1])\n \n return str2\n\n\n# buy 1 and sell 0\n\ndef provide_output(daily, file_write):\n file_read_d = open(daily)\n open_file = open(file_write, \"a\")\n line = file_read_d.readline()\n line = file_read_d.readline()\n line = file_read_d.readline()\n\n lst = []\n \n c = 1\n while c <= 50:\n if line != \"\":\n splitted = line.split()\n open_price = splitted[1]\n high_price = splitted[2]\n low_price = splitted[3]\n close_price = splitted[4]\n if open_price <= close_price:\n result = (round(sigma(float(open_price)), 5), 0)\n else:\n result = (round(sigma(float(open_price)), 5), 1)\n lst.append(result[1])\n open_file.write(str(result[1]) + \",\")\n line = file_read_d.readline()\n c = c + 1\n\n open_file.close()\n return lst\n\n\ndef provide_data(input_file, file_write):\n file_read_d = open(input_file)\n open_file = open(file_write, \"a\")\n line = file_read_d.readline()\n line = file_read_d.readline()\n\n lst = []\n\n c = 1\n while c <= 1200:\n if line != \"\":\n splitted = line.split()\n open_price = splitted[2]\n high_price = splitted[3]\n low_price = splitted[4]\n close_price = splitted[5]\n if open_price <= close_price:\n result = (round(sigma(float(open_price)), 5), \"buy\")\n else:\n result = (round(sigma(float(open_price)), 5), \"sell\")\n lst.append(result[0])\n open_file.write(str(result[0]) + \", \")\n line = file_read_d.readline()\n\n c = c + 1\n\n\n open_file.close()\n print(len(lst))\n return lst\n","sub_path":"simple_neural_networks_implementation/some_functions.py","file_name":"some_functions.py","file_ext":"py","file_size_in_byte":5662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"601471394","text":"\nimport os\nimport numpy as np\nimport tables\nimport phovea_server.range as ranges\nimport itertools\nfrom phovea_server.dataset_def import ADataSetProvider, AColumn, AMatrix, AStratification, ATable, AVector\n\n__author__ = 'sam'\n\n\ndef assign_ids(ids, idtype):\n import phovea_server.plugin\n\n manager = phovea_server.plugin.lookup('idmanager')\n return np.array(manager(ids, idtype))\n\n\ndef _resolve_categories(attrs):\n cats = attrs['categories']\n if isinstance(cats[0], str) or isinstance(cats[0], str): # categories are strings\n converter = tables.misc.enum.Enum(cats)\n # create a numpy function out of it\n converter = np.vectorize(converter, otypes=['S' + str(max((len(c) for c in cats)))])\n else:\n converter = None\n if 'names' in attrs:\n names = attrs['names']\n colors = attrs['colors']\n if len(names) == len(cats) - 1: # unknown missing\n names.insert(0, 'UNKN@WN')\n colors.insert(0, '#4c4c4c')\n cats = [dict(name=cat, label=name, color=col) for cat, name, col in\n zip(cats, names, colors)]\n\n return cats, converter\n\n\nclass HDFMatrix(AMatrix):\n def __init__(self, group, project):\n super(HDFMatrix, self).__init__(group._v_title, project, group._v_attrs.type.decode('utf-8'))\n self._group = group\n self._project = project\n self.path = self._group._v_pathname\n self._rowids = None\n self._colids = None\n self._range = None\n self.rowtype = self._group._v_attrs.rowtype.decode('utf-8')\n self.coltype = self._group._v_attrs.coltype.decode('utf-8')\n self.value = self._group._v_attrs.value.decode('utf-8')\n self.shape = self._group.data.shape\n if self.value == 'categorical':\n self.categories, self._converter = _resolve_categories(group._v_attrs)\n\n @property\n def range(self):\n if 'range' in self._group._v_attrs:\n return self._group._v_attrs['range']\n if self._range is not None:\n return self._range\n d = self._group.data\n self._range = [np.nanmin(d), np.nanmax(d)]\n return self._range\n\n def idtypes(self):\n return [self.rowtype, self.coltype]\n\n def to_description(self):\n r = super(HDFMatrix, self).to_description()\n r['rowtype'] = self.rowtype\n r['coltype'] = self.coltype\n r['value'] = v = dict(type=self.value)\n if self.value == 'real' or self.value == 'int':\n v['range'] = self.range\n if self.value == 'int' and hasattr(self._group._v_attrs, 'missing'):\n v['missing'] = self._group._v_attrs.missing.decode('utf-8')\n elif self.value == 'categorical':\n v['categories'] = self.categories\n\n if 'center' in self._group._v_attrs:\n v['center'] = self._group._v_attrs['center']\n r['size'] = self.shape\n return r\n\n def mask(self, arr):\n if self.value == 'int' and hasattr(self._group._v_attrs, 'missing'):\n missing = self._group._v_attrs.missing.decode('utf-8')\n import numpy.ma as ma\n return ma.masked_equal(arr, missing)\n\n if self.value == 'categorical' and self._converter is not None:\n return np.array(self._converter(arr))\n return np.array(arr)\n\n def asnumpy(self, range=None):\n n = self._group.data\n if range is None:\n return self.mask(n)\n rows = range[0].asslice()\n cols = range[1].asslice()\n d = None\n if isinstance(rows, list) and isinstance(cols, list):\n # fancy indexing in two dimension doesn't work\n d_help = n[rows, :]\n d = d_help[:, cols]\n else:\n d = n[rows, cols]\n\n if d.ndim == 1:\n # two options one row and n columns or the other way around\n if rows is Ellipsis or (isinstance(rows, list) and len(rows) > 1):\n d = d.reshape((d.shape[0], 1))\n else:\n d = d.reshape((1, d.shape[0]))\n elif d.ndim == 0:\n d = d.reshape((1, 1))\n return self.mask(d)\n\n def rows(self, range=None):\n n = np.array(self._group.rows)\n if range is None:\n return n\n return n[range.asslice()]\n\n def rowids(self, range=None):\n if self._rowids is None:\n self._rowids = assign_ids(self.rows(), self.rowtype)\n n = self._rowids\n if range is None:\n return n\n return n[range.asslice()]\n\n def cols(self, range=None):\n n = np.array(self._group.cols)\n if range is None:\n return n\n return n[range.asslice()]\n\n def colids(self, range=None):\n if self._colids is None:\n self._colids = assign_ids(self.cols(), self.coltype)\n n = self._colids\n if range is None:\n return n\n return n[range.asslice()]\n\n\nclass HDFVector(AVector):\n def __init__(self, group, project):\n super(HDFVector, self).__init__(group._v_title, project, group._v_attrs.type.decode('utf-8'))\n self._group = group\n self._project = project\n self._rowids = None\n self._range = None\n self.idtype = self._group._v_attrs.rowtype.decode('utf-8')\n self.value = self._group._v_attrs.value.decode('utf-8')\n self.shape = len(self._group.data)\n\n @property\n def range(self):\n if 'range' in self._group._v_attrs:\n return self._group._v_attrs['range']\n if self._range is not None:\n return self._range\n d = self._group.data\n self._range = [np.nanmin(d), np.nanmax(d)]\n return self._range\n\n def idtypes(self):\n return [self.idtype]\n\n def to_description(self):\n r = super(HDFVector, self).to_description()\n r['idtype'] = self.idtype\n r['value'] = dict(type=self.value, range=self.range)\n if self.value == 'int' and hasattr(self._group._v_attrs, 'missing'):\n r['value']['missing'] = self._group._v_attrs.missing.decode('utf-8')\n if 'center' in self._group._v_attrs:\n r['value']['center'] = self._group._v_attrs['center']\n r['size'] = [self.shape]\n return r\n\n def mask(self, arr):\n if self.value == 'int' and hasattr(self._group._v_attrs, 'missing'):\n missing = self._group._v_attrs.missing.decode('utf-8')\n import numpy.ma as ma\n return ma.masked_equal(arr, missing)\n return arr\n\n def asnumpy(self, range=None):\n n = self._group.data\n if range is None:\n return self.mask(n)\n d = n[range[0].asslice()]\n if d.ndim == 0:\n d = d.reshape((1,))\n return self.mask(d)\n\n def rows(self, range=None):\n n = np.array(self._group.rows)\n if range is None:\n return n\n return n[range.asslice()]\n\n def rowids(self, range=None):\n if self._rowids is None:\n self._rowids = assign_ids(self.rows(), self.rowtype)\n n = self._rowids\n if range is None:\n return n\n return n[range.asslice()]\n\n\nclass HDFGroup(object):\n def __init__(self, name, offset, data, color):\n self.name = name\n self.data = data\n self.range = ranges.from_slice(offset, offset + len(data))\n self.color = color\n\n def __len__(self):\n return len(self.data)\n\n def dump(self):\n return dict(name=self.name, range=str(self.range), color=self.color)\n\n def dump_desc(self):\n return dict(name=self.name, size=len(self), color=self.color)\n\n\ndef guess_color(name, i):\n name = name.lower()\n colors = dict(male='blue', female='red', deceased='#e41a1b', living='#377eb8')\n if name in colors:\n return colors[name]\n colors = ['#8dd3c7', '#ffffb3', '#bebada', '#fb8072', '#80b1d3', '#fdb462', '#b3de69', '#fccde5', '#d9d9d9', '#bc80bd', '#ccebc5', '#ffed6f']\n return colors[i % len(colors)]\n\n\nclass HDFStratification(AStratification):\n def __init__(self, group, project):\n super(HDFStratification, self).__init__(group._v_title, project, group._v_attrs.type.decode('utf-8'))\n self._group = group\n self._project = project\n self._rowids = None\n self.idtype = self._group._v_attrs.idtype.decode('utf-8')\n self._groups = None\n\n def idtypes(self):\n return [self.idtype]\n\n def to_description(self):\n r = super(HDFStratification, self).to_description()\n r['idtype'] = self.idtype\n if 'origin' in self._group._v_attrs:\n r['origin'] = self._project + '/' + self._group._v_attrs.origin.decode('utf-8')\n r['groups'] = [g.dump_desc() for g in self.groups()]\n r['ngroups'] = len(r['groups'])\n r['size'] = [sum((g['size'] for g in r['groups']))]\n return r\n\n def _rows(self):\n return np.concatenate([g.data for g in self.groups()])\n\n def rows(self, range=None):\n n = self._rows()\n if range is None:\n return n\n return n[range[0].asslice()]\n\n def rowids(self, range=None):\n if self._rowids is None:\n self._rowids = assign_ids(self.rows(), self.idtype)\n n = self._rowids\n if range is None:\n return n\n return n[range.asslice()]\n\n def groups(self):\n if self._groups is None:\n self._groups = []\n i = 0\n values = iter(self._group._v_children.values())\n for j, g in enumerate(sorted(values, key=lambda x: x._v_title)):\n name = g._v_title\n color = g._v_attrs['color'] if 'color' in g._v_attrs else guess_color(name, j)\n length = len(g)\n self._groups.append(HDFGroup(name, i, g, color))\n i += length\n return self._groups\n\n def __getitem__(self, item):\n group = getattr(self._group, item)\n return group\n\n def asjson(self, range=None):\n r = dict(rows=self.rows(range), rowIds=self.rowids(range), groups=[g.dump() for g in self.groups()])\n return r\n\n\nclass HDFColumn(AColumn):\n def __init__(self, attrs, group):\n super(HDFColumn, self).__init__(attrs['name'], attrs['type'])\n self._group = group\n self.key = attrs['key']\n if self.type == 'categorical':\n self.categories, self._converter = _resolve_categories(attrs)\n elif self.type == 'int' or self.type == 'real':\n self.range = attrs['range'] if 'range' in attrs else self.compute_range()\n self.missing = attrs.get('missing', None)\n\n def compute_range(self):\n d = self._group.table.col(self.key)\n return [np.nanmin(d), np.nanmax(d)]\n\n def convert_category(self, vs):\n if self._converter is not None:\n return self._converter(vs)\n return vs\n\n def mask(self, arr):\n if self.type == 'int' and self.missing is not None:\n import numpy.ma as ma\n return ma.masked_equal(arr, self.missing)\n\n if self.type == 'categorical' and self._converter is not None: # convert categorical columns\n return self._converter(arr)\n return arr\n\n def asnumpy(self, range=None):\n n = self._group.table.col(self.key)\n if range is not None:\n n = n[range[0].asslice()]\n return self.mask(n)\n\n def dump(self):\n value = dict(type=self.type)\n if self.type == 'categorical':\n value['categories'] = self.categories\n if self.type == 'int' or self.type == 'real':\n value['range'] = self.range\n if self.type == 'int' and self.missing is not None:\n value['missing'] = self.missing\n return dict(name=self.name, value=value, column=self.key)\n\n\nclass HDFTable(ATable):\n def __init__(self, group, project):\n super(HDFTable, self).__init__(group._v_title, project, group._v_attrs.type.decode('utf-8'))\n self._group = group\n self._project = project\n\n self.columns = [HDFColumn(a, group) for a in group._v_attrs.columns]\n self._rowids = None\n self.idtype = self._group._v_attrs.rowtype.decode('utf-8')\n\n def idtypes(self):\n return [self.idtype]\n\n def to_description(self):\n r = super(HDFTable, self).to_description()\n r['idtype'] = self.idtype\n r['columns'] = [d.dump() for d in self.columns]\n r['size'] = [len(self._group.table), len(self.columns)]\n return r\n\n def rows(self, range=None):\n n = np.array(self._group.rows)\n if range is None:\n return n\n return n[range.asslice()]\n\n def rowids(self, range=None):\n if self._rowids is None:\n self._rowids = assign_ids(self.rows(), self.idtype)\n n = self._rowids\n if range is None:\n return n\n return n[range.asslice()]\n\n def aspandas(self, range=None):\n import pandas as pd\n n = pd.DataFrame.from_records(self._group.table[:])\n # ensure right column order\n n = n[[item.key for item in self.columns]]\n\n # convert categorical enums\n # rename variable to avoid shadowing\n for item in self.columns:\n if item.type == 'categorical':\n n[item.key] = item.convert_category(n[item.key])\n\n if range is None:\n return n\n return n.iloc[range[0].asslice(no_ellipsis=True)]\n\n def filter(self, query):\n # perform the query on rows and cols and return a range with just the matching one\n # np.argwhere\n return ranges.all()\n\n\nclass HDFProject(object):\n def __init__(self, filename, base_dir):\n self.filename = filename\n p = os.path.relpath(filename, base_dir)\n project, _ = os.path.splitext(p)\n project = project.replace('.', '_')\n self._h = tables.open_file(filename, 'r')\n\n self.entries = []\n for group in self._h.walk_groups('/'):\n if 'type' not in group._v_attrs:\n continue\n t = group._v_attrs.type.decode('utf-8')\n if t == 'matrix':\n self.entries.append(HDFMatrix(group, project))\n elif t == 'stratification':\n self.entries.append(HDFStratification(group, project))\n elif t == 'table':\n self.entries.append(HDFTable(group, project))\n elif t == 'vector':\n self.entries.append(HDFVector(group, project))\n\n def __iter__(self):\n return iter(self.entries)\n\n def __len__(self):\n return len(self.entries)\n\n def __getitem__(self, dataset_id):\n for f in self.entries:\n if f.id == dataset_id:\n return f\n return None\n\n\nclass HDFFilesProvider(ADataSetProvider):\n def __init__(self):\n from phovea_server import config\n # check initialization\n if config._c is None:\n config._initialize()\n conf = config.view('phovea_data_hdf')\n from phovea_server.util import glob_recursivly\n base_dir = config.get('dataDir', 'phovea_server')\n self.files = [HDFProject(f, base_dir) for f in glob_recursivly(base_dir, conf.get('glob'))]\n\n def __len__(self):\n return sum((len(f) for f in self))\n\n def __iter__(self):\n return iter((f for f in itertools.chain(*self.files) if f.can_read()))\n\n def __getitem__(self, dataset_id):\n for f in self.files:\n r = f[dataset_id]\n if r is not None:\n return r\n return None\n\n\nif __name__ == '__main__':\n # app.debug1 = True\n\n c = HDFFilesProvider()\n\n\ndef create():\n return HDFFilesProvider()\n","sub_path":"phovea_data_hdf/hdf.py","file_name":"hdf.py","file_ext":"py","file_size_in_byte":14110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"528380858","text":"import json\nimport os\nimport argparse\n\n\nconfig_name = 'config.json'\nparser = argparse.ArgumentParser()\n\nparser.add_argument('--database_name')\nparser.add_argument('--run')\nargs = parser.parse_args()\n\nif os.path.isfile(config_name):\n file = open(config_name, 'r')\n config = json.loads(file.read())\n file.close()\n\n print('{} already exists, remove to reset.'.format(config_name))\nelse:\n \n if args.database_name:\n database_name = args.database_name\n else:\n database_name = input('Choose database name: ')\n\n data = {\n 'database_name': database_name\n }\n\n print(data)\n print('Finished installing.')\n\n with open(config_name, 'w+') as file:\n file.write(json.dumps(data))\n\n\nif args.run:\n from lwpcms.app import app\n app.run(debug=True)\n","sub_path":"install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"452799360","text":"# The MIT License (MIT)\n#\n# Copyright (c) 2020 Jim Bennett\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\"\"\"\ncircuitpython_esp32connection\n================================================================================\n\nA WiFi connection helper for ESP32-based boards\n\n\n* Author(s): Jim Bennett\n\nImplementation Notes\n--------------------\n\n**Hardware:**\n\n**Software and Dependencies:**\n\n* Adafruit CircuitPython firmware for the supported boards:\n https://github.com/adafruit/circuitpython/releases\n* Adafruit's Bus Device library:\n https://github.com/adafruit/Adafruit_CircuitPython_BusDevice\n\"\"\"\n\n# imports\n\n__version__ = \"0.0.0-auto.0\"\n__repo__ = \"https://github.com/jimbobbennett/CircuitPython_ESP32Connection.git\"\n\nimport time\nimport board\nimport busio\nfrom digitalio import DigitalInOut\nimport adafruit_minimqtt as MQTT\nimport adafruit_esp32spi.adafruit_esp32spi_socket as socket\nfrom adafruit_esp32spi import adafruit_esp32spi\nfrom adafruit_esp32spi.adafruit_esp32spi_wifimanager import ESPSPI_WiFiManager\nfrom adafruit_ntp import NTP\nimport adafruit_logging as logging\n\n\ndef __connect(cs_pin, ready_pin, reset_pin, secrets) -> ESPSPI_WiFiManager:\n logger = logging.getLogger(\"log\")\n\n spi = busio.SPI(board.SCK, board.MOSI, board.MISO)\n esp = adafruit_esp32spi.ESP_SPIcontrol(spi, cs_pin, ready_pin, reset_pin)\n\n wifi = ESPSPI_WiFiManager(esp, secrets, attempts=5)\n\n MQTT.set_socket(socket, esp)\n\n logger.debug(\"MAC addr: \" + \", \".join([hex(i) for i in esp.MAC_address]))\n logger.debug(\"Connecting to AP...\")\n\n wifi.connect()\n\n logger.info(\"Connected to \" + str(esp.ssid, \"utf-8\") + \"\\tRSSI: \" + str(esp.rssi))\n logger.debug(\"My IP address is \" + esp.pretty_ip(esp.ip_address))\n\n logger.debug(\"Setting time\")\n\n ntp = NTP(esp)\n while not ntp.valid_time:\n ntp.set_time()\n logger.debug(\"Failed to obtain time, retrying in 1 second...\")\n time.sleep(1)\n\n logger.info(\"Time: \" + str(time.time()))\n\n return wifi\n\n\nclass Connection:\n \"\"\"\n A WiFi connection helper for ESP32-based boards\n \"\"\"\n\n def __init__(self):\n self.wifi = None\n\n def connect(self, secrets) -> ESPSPI_WiFiManager:\n \"\"\"\n Connects to WiFi.\n\n This currently supports the PyBadge with Airlift Featherwing, and PyPortals\n \"\"\"\n try:\n esp32_cs = DigitalInOut(board.ESP_CS)\n esp32_ready = DigitalInOut(board.ESP_BUSY)\n esp32_reset = DigitalInOut(board.ESP_RESET)\n except AttributeError:\n esp32_cs = DigitalInOut(board.D13)\n esp32_ready = DigitalInOut(board.D11)\n esp32_reset = DigitalInOut(board.D12)\n\n self.wifi = __connect(esp32_cs, esp32_ready, esp32_reset, secrets)\n return self.wifi\n","sub_path":"esp32connection.py","file_name":"esp32connection.py","file_ext":"py","file_size_in_byte":3772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"557897868","text":"\"\"\"\nFilename: SillySentenceScrambler.py\nAuthor: The one and only Rebecca Klein!\nDescription: Does what the title suggests. You supply the parts of speech,\nand it supplies the sentences!\n\"\"\"\n\nimport random\n\ndef hashIt(key):\n hV = \"\"\n for ch in key:\n hV += str(ord(ch))\n hVI = int(hV)\n return hVI\n\ndef createPOSBank(filename, bankSize):\n POSBank = [None]*bankSize\n for line in open(filename):\n pair = line.split()\n loc = hashIt(pair[0])%bankSize\n if POSBank[loc] == None:\n POSBank[loc] = []\n POSBank[loc].append(pair)\n return POSBank\n\ndef createWordBank(filename, bankSize):\n wordBank = [None]*bankSize\n for line in open(filename):\n pair = line.split()\n loc = hashIt(pair[1])%bankSize\n if wordBank[loc] == None:\n wordBank[loc] = []\n wordBank[loc].append([pair[1], pair[0]])\n return wordBank\n\ndef determine(pair):\n follower = []\n if pair[0] == \"ProperNoun\":\n follower = [\"verb\"]\n elif pair[0] == \"verb\":\n follower = [\"preposition\", \"determiner\", \"adverb\"]\n elif pair[0] == \"preposition\":\n follower = [\"determiner\"]\n elif pair[0] == \"determiner\":\n follower = [\"noun\", \"adjective\"]\n elif pair[0] == \"adverb\":\n follower = [\"preposition\"]\n elif pair[0] == \"adjective\":\n follower = [\"noun\", \"ProperNoun\"]\n POS = follower[random.randint(0, len(follower)-1)]\n return POS\n\ndef breakDownSentence(sentence, POSBank, wordBank, bankSize):\n line = sentence.split()\n translated = \"\"\n for word in line:\n POS = \"\"\n loc = hashIt(word)%bankSize\n if wordBank[loc] == None:\n POS = addWord(word)\n else:\n for entry in wordBank[loc]:\n if entry[0] == word:\n POS = entry[1]\n if POS == \"\":\n POS = addWord(word)\n translated += \" \" + POS + \" \"\n return translated\n\ndef addWord(word):\n POS = input(\"The part of speech of \" + word + \" is (all lowercase, please): \")\n filename = 'words.txt' #filename = input(\"The file you will write to (new words will be added once the program is run again): \")\n with open(filename, \"a\") as myFile:\n myFile.write(\"\\n\" + POS + \" \" + word)\n return POS\n\ndef constructNewSentence(translated, POSBank, wordBank, bankSize):\n POSs = translated.split()\n sentence = \"\"\n for POS in POSs:\n loc = hashIt(POS)%bankSize\n wordLoc = random.randint(0, len(POSBank[loc])-1)\n sentence += POSBank[loc][wordLoc][1] + \" \"\n return sentence\n\ndef main():\n filename = input(\"Input name of file: \")\n bankSize = 101\n POSBank = createPOSBank(filename, bankSize)\n wordBank = createWordBank(filename, bankSize)\n print(\"Available parts of speech: ProperNoun, determiner (the, a), noun, adjective, preposition (into), verb, adverb (awkwardly).\")\n choice(POSBank, wordBank, bankSize)\n\ndef choice(POSBank, wordBank, bankSize):\n print(\"-----\")\n i = input(\"enter 0 to create a sentence structure from scratch. \\nenter 1 to type a sentence and have me determine the parts of speech and spit out a new sentence. \\nenter 2 to have me create a sentence all by myself. \\nenter anything else to exit the program: \")\n if i == \"0\":\n scratchSentence(POSBank, wordBank, bankSize)\n elif i == \"1\":\n typedSentence(POSBank, wordBank, bankSize)\n elif i == \"2\":\n computeSentence(POSBank, wordBank, bankSize)\n exit()\n\ndef scratchSentence(POSBank, wordBank, bankSize):\n sentenceStructure = input(\"Enter sentence structure (example: ProperNoun verb determiner noun): \").split()\n for POS in sentenceStructure:\n loc = hashIt(POS)%bankSize\n rWord = random.randint(0, len(POSBank[loc])-1)\n print(str(POSBank[loc][rWord][1]), end=\" \")\n print()\n i = input(\"continue entering sentence structures (y/n): \")\n if i == \"y\":\n scratchSentence(POSBank, wordBank, bankSize)\n else:\n choice(POSBank, wordBank, bankSize)\n\ndef typedSentence(POSBank, wordBank, bankSize):\n original = input(\"Enter your sentence (without punctuation or capitalization on anything other than proper nouns): \")\n POSs = breakDownSentence(original, POSBank, wordBank, bankSize)\n newSentence = constructNewSentence(POSs, POSBank, wordBank, bankSize)\n print(newSentence)\n i = input(\"continue typing sentences (y/n): \")\n if i == \"y\":\n typedSentence(POSBank, wordBank, bankSize)\n else:\n choice(POSBank, wordBank, bankSize)\n\ndef computeSentence(POSBank, wordBank, bankSize):\n loc = hashIt(\"ProperNoun\")%bankSize\n pair = POSBank[loc][random.randint(0, len(POSBank[loc])-1)]\n sentence = \"\"\n nounLoc = hashIt(\"noun\")%bankSize\n while True:\n sentence += pair[1] + \" \"\n loc = hashIt(determine(pair))%bankSize\n pair = POSBank[loc][random.randint(0, len(POSBank[loc])-1)]\n if pair[0] == \"ProperNoun\" or pair[0] == \"noun\":\n break\n sentence += pair[1]\n print(sentence)\n i = input(\"continue having me do all the work (y/n): \")\n if i == \"y\":\n computeSentence(POSBank, wordBank, bankSize)\n else:\n choice(POSBank, wordBank, bankSize)\n\n#main()\n","sub_path":"SentenceGeneratorProject/SillySentenceScramblerMKII.py","file_name":"SillySentenceScramblerMKII.py","file_ext":"py","file_size_in_byte":5219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"495184813","text":"import pandas as pd\nfrom statsmodels.tsa.holtwinters import SimpleExpSmoothing, Holt, ExponentialSmoothing\nimport numpy as np\nfrom matplotlib import pyplot\n######计算MAPE\nfrom statsmodels.tsa.seasonal import seasonal_decompose\n\n\ndef mean_absolute_percentage_error(y_true, y_pred):\n y_true, y_pred = np.array(y_true), np.array(y_pred)\n return np.mean(np.abs((y_true - y_pred) / y_true)) * 100\n\n####误差率\ndef error_rate_computed(y_true, y_pred):\n return (y_true - y_pred) / y_true*100\n\ninput_file=pd.read_csv('dataset/avgwage_working_retired.csv')\ndata=input_file['retired']\nsize=8\ntrain=data[0:size]\ntest=data[size:]\nmodel=SimpleExpSmoothing(train).fit(smoothing_level=0.1)\npre_value = model.forecast(len(test))\nprint(\"简单指数平滑法-预测值:\\n\",pre_value)\ntest_mae = mean_absolute_percentage_error(test, pre_value)\nprint('Mean Absolute Percentage Error On Test Set: %.3f' % test_mae)\nerror_rate=error_rate_computed(test, pre_value)\nprint(\"测试误差率:\",error_rate)\n\n####Holt线性趋势预测法\nmodel=Holt(train).fit(smoothing_level=0.1,smoothing_slope=0.05)\npre_value = model.forecast(len(test))\nprint(\"HoltWinter线性趋势-预测值:\\n\",pre_value)\ntest_mae = mean_absolute_percentage_error(test, pre_value)\nprint('Mean Absolute Percentage Error On Test Set: %.3f' % test_mae)\nerror_rate=error_rate_computed(test, pre_value)\nprint(\"测试误差率:\",error_rate)\n\n\nmodel=ExponentialSmoothing(train,trend='add').fit()\n\npre_value = model.forecast(len(test))\nprint(\"HoltWinter指数平滑法-预测值:\\n\",pre_value)\ntest_mae = mean_absolute_percentage_error(test, pre_value)\nprint('Mean Absolute Percentage Error On Test Set: %.3f' % test_mae)\nerror_rate=error_rate_computed(test, pre_value)\nprint(\"测试误差率:\",error_rate)","sub_path":"timeseries/HoltWinter_test.py","file_name":"HoltWinter_test.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"130766553","text":"from __future__ import division\nfrom math import cos, sin, sqrt\nfrom os.path import basename\n\nimport numpy as np\n\nfrom ase.data import chemical_symbols\nfrom ase.data.colors import jmol_colors\nfrom ase.geometry import complete_cell\nfrom ase.gui.repeat import Repeat\nfrom ase.gui.rotate import Rotate\nfrom ase.gui.render import Render\nfrom ase.gui.colors import ColorWindow\nfrom ase.utils import rotate\n\n\nGREEN = '#DDFFDD'\n\n\nclass View:\n def __init__(self, rotations):\n self.colormode = 'jmol' # The default colors\n self.nselected = 0\n self.labels = None\n self.axes = rotate(rotations)\n self.configured = False\n self.frame = None\n\n def set_coordinates(self, frame=None, focus=None):\n if frame is None:\n frame = self.frame\n self.make_box()\n self.bind(frame)\n n = self.images.natoms\n self.X = np.empty((n + len(self.B1) + len(self.bonds), 3))\n self.set_frame(frame, focus=focus, init=True)\n\n def set_frame(self, frame=None, focus=False, init=False):\n if frame is None:\n frame = self.frame\n\n n = self.images.natoms\n\n if self.frame is not None and self.frame > self.images.nimages:\n self.frame = self.images.nimages - 1\n\n if init or frame != self.frame:\n A = self.images.A\n nc = len(self.B1)\n nb = len(self.bonds)\n\n if init or (A[frame] != A[self.frame]).any():\n self.X[n:n + nc] = np.dot(self.B1, A[frame])\n self.B = np.empty((nc + nb, 3))\n self.B[:nc] = np.dot(self.B2, A[frame])\n\n if nb > 0:\n P = self.images.P[frame]\n Af = self.images.repeat[:, np.newaxis] * A[frame]\n a = P[self.bonds[:, 0]]\n b = P[self.bonds[:, 1]] + np.dot(self.bonds[:, 2:], Af) - a\n d = (b**2).sum(1)**0.5\n r = 0.65 * self.images.r\n x0 = (r[self.bonds[:, 0]] / d).reshape((-1, 1))\n x1 = (r[self.bonds[:, 1]] / d).reshape((-1, 1))\n self.X[n + nc:] = a + b * x0\n b *= 1.0 - x0 - x1\n b[self.bonds[:, 2:].any(1)] *= 0.5\n self.B[nc:] = self.X[n + nc:] + b\n\n filenames = self.images.filenames\n filename = filenames[frame]\n if (self.frame is None or\n filename != filenames[self.frame] or\n filename is None):\n if filename is None:\n filename = 'ase.gui'\n filename = basename(filename)\n self.window.title = filename\n\n self.frame = frame\n self.X[:n] = self.images.P[frame]\n self.R = self.X[:n]\n if focus:\n self.focus()\n else:\n self.draw()\n\n def set_colors(self):\n self.colormode = 'jmol'\n self.colors = {}\n for z in np.unique(self.images.Z):\n rgb = jmol_colors[z]\n self.colors[z] = ('#{0:02X}{1:02X}{2:02X}'\n .format(*(int(x * 255) for x in rgb)))\n\n def make_box(self):\n if not self.window['toggle-show-unit-cell']:\n self.B1 = self.B2 = np.zeros((0, 3))\n return\n\n V = self.images.A[0]\n nn = []\n for c in range(3):\n v = V[c]\n d = sqrt(np.dot(v, v))\n if d < 1e-12:\n n = 0\n else:\n n = max(2, int(d / 0.3))\n nn.append(n)\n self.B1 = np.zeros((2, 2, sum(nn), 3))\n self.B2 = np.zeros((2, 2, sum(nn), 3))\n n1 = 0\n for c, n in enumerate(nn):\n n2 = n1 + n\n h = 1.0 / (2 * n - 1)\n R = np.arange(n) * (2 * h)\n\n for i, j in [(0, 0), (0, 1), (1, 0), (1, 1)]:\n self.B1[i, j, n1:n2, c] = R\n self.B1[i, j, n1:n2, (c + 1) % 3] = i\n self.B1[i, j, n1:n2, (c + 2) % 3] = j\n self.B2[:, :, n1:n2] = self.B1[:, :, n1:n2]\n self.B2[:, :, n1:n2, c] += h\n n1 = n2\n self.B1.shape = (-1, 3)\n self.B2.shape = (-1, 3)\n\n def bind(self, frame):\n if not self.window['toggle-show-bonds']:\n self.bonds = np.empty((0, 5), int)\n return\n\n from ase.atoms import Atoms\n from ase.neighborlist import NeighborList\n nl = NeighborList(self.images.r * 1.5, skin=0, self_interaction=False)\n nl.update(Atoms(positions=self.images.P[frame],\n cell=(self.images.repeat[:, np.newaxis] *\n self.images.A[frame]),\n pbc=self.images.pbc))\n nb = nl.nneighbors + nl.npbcneighbors\n\n bonds = np.empty((nb, 5), int)\n self.coordination = np.zeros((self.images.natoms), dtype=int)\n if nb == 0:\n return\n\n n1 = 0\n for a in range(self.images.natoms):\n indices, offsets = nl.get_neighbors(a)\n self.coordination[a] += len(indices)\n for a2 in indices:\n self.coordination[a2] += 1\n n2 = n1 + len(indices)\n bonds[n1:n2, 0] = a\n bonds[n1:n2, 1] = indices\n bonds[n1:n2, 2:] = offsets\n n1 = n2\n\n i = bonds[:n2, 2:].any(1)\n pbcbonds = bonds[:n2][i]\n bonds[n2:, 0] = pbcbonds[:, 1]\n bonds[n2:, 1] = pbcbonds[:, 0]\n bonds[n2:, 2:] = -pbcbonds[:, 2:]\n self.bonds = bonds\n\n def toggle_show_unit_cell(self, key=None):\n self.set_coordinates()\n\n def show_labels(self):\n index = self.window['show-labels']\n if index == 0:\n self.labels = None\n elif index == 1:\n self.labels = ([list(range(self.images.natoms))] *\n self.images.nimages)\n elif index == 2:\n self.labels = self.images.M\n else:\n self.labels = [[chemical_symbols[x]\n for x in self.images.Z]] * self.images.nimages\n\n self.draw()\n\n def toggle_show_axes(self, key=None):\n self.draw()\n\n def toggle_show_bonds(self, key=None):\n self.set_coordinates()\n\n def toggle_show_velocities(self, key=None):\n # XXX hard coded scale is ugly\n self.show_vectors(10 * np.nan_to_num(self.images.V))\n self.draw()\n\n def toggle_show_forces(self, key=None):\n self.show_vectors(np.nan_to_num(self.images.F))\n self.draw()\n\n def hide_selected(self):\n self.images.visible[self.images.selected] = False\n self.draw()\n\n def show_selected(self):\n self.images.visible[self.images.selected] = True\n self.draw()\n\n def repeat_window(self, key=None):\n Repeat(self)\n\n def rotate_window(self):\n return Rotate(self)\n\n def colors_window(self, key=None):\n win = ColorWindow(self)\n self.register_vulnerable(win)\n return win\n\n def focus(self, x=None):\n cell = (self.window['toggle-show-unit-cell'] and\n self.images.A[0].any())\n if (self.images.natoms == 0 and not cell):\n self.scale = 1.0\n self.center = np.zeros(3)\n self.draw()\n return\n\n P = np.dot(self.X, self.axes)\n n = self.images.natoms\n P[:n] -= self.images.r[:, None]\n P1 = P.min(0)\n P[:n] += 2 * self.images.r[:, None]\n P2 = P.max(0)\n self.center = np.dot(self.axes, (P1 + P2) / 2)\n S = 1.3 * (P2 - P1)\n w, h = self.window.size\n if S[0] * h < S[1] * w:\n self.scale = h / S[1]\n elif S[0] > 0.0001:\n self.scale = w / S[0]\n else:\n self.scale = 1.0\n self.draw()\n\n def reset_view(self, menuitem):\n self.axes = rotate('0.0x,0.0y,0.0z')\n self.set_coordinates()\n self.focus(self)\n\n def set_view(self, key):\n if key == 'Z':\n self.axes = rotate('0.0x,0.0y,0.0z')\n elif key == 'X':\n self.axes = rotate('-90.0x,-90.0y,0.0z')\n elif key == 'Y':\n self.axes = rotate('90.0x,0.0y,90.0z')\n elif key == 'Alt+Z':\n self.axes = rotate('180.0x,0.0y,90.0z')\n elif key == 'Alt+X':\n self.axes = rotate('0.0x,90.0y,0.0z')\n elif key == 'Alt+Y':\n self.axes = rotate('-90.0x,0.0y,0.0z')\n else:\n if key == '3':\n i, j = 0, 1\n elif key == '1':\n i, j = 1, 2\n elif key == '2':\n i, j = 2, 0\n elif key == 'Alt+3':\n i, j = 1, 0\n elif key == 'Alt+1':\n i, j = 2, 1\n elif key == 'Alt+2':\n i, j = 0, 2\n\n A = complete_cell(self.images.A[self.frame])\n x1 = A[i]\n x2 = A[j]\n\n norm = np.linalg.norm\n\n x1 = x1 / norm(x1)\n x2 = x2 - x1 * np.dot(x1, x2)\n x2 /= norm(x2)\n x3 = np.cross(x1, x2)\n\n self.axes = np.array([x1, x2, x3]).T\n\n self.set_coordinates()\n\n def get_colors(self, rgb=False):\n if rgb:\n return [tuple(int(rgb[i:i + 2], 16) / 255 for i in range(1, 7, 2))\n for rgb in self.get_colors()]\n\n if self.colormode == 'jmol':\n return [self.colors[Z] for Z in self.images.Z]\n\n scalars = self.get_color_scalars()\n colorscale, cmin, cmax = self.colormode_data\n N = len(colorscale)\n indices = np.clip(((scalars - cmin) / (cmax - cmin) * N +\n 0.5).astype(int),\n 0, N - 1)\n return [colorscale[i] for i in indices]\n\n def get_color_scalars(self, frame=None):\n i = frame or self.frame\n\n if self.colormode == 'tag':\n return self.images.T[i]\n if self.colormode == 'force':\n f = (self.images.F[i]**2).sum(1)**0.5\n return f * self.images.dynamic\n elif self.colormode == 'velocity':\n return (self.images.V[i]**2).sum(1)**0.5\n elif self.colormode == 'charge':\n return self.images.q[i]\n elif self.colormode == 'magmom':\n return self.images.M[i]\n\n def draw(self, status=True):\n self.window.clear()\n axes = self.scale * self.axes * (1, -1, 1)\n offset = np.dot(self.center, axes)\n offset[:2] -= 0.5 * self.window.size\n X = np.dot(self.X, axes) - offset\n n = self.images.natoms\n self.indices = X[:, 2].argsort()\n if self.window['toggle-show-bonds']:\n r = self.images.r * (0.65 * self.scale)\n else:\n r = self.images.r * self.scale\n P = self.P = X[:n, :2]\n A = (P - r[:, None]).round().astype(int)\n X1 = X[n:, :2].round().astype(int)\n X2 = (np.dot(self.B, axes) - offset).round().astype(int)\n disp = (np.dot(self.images.D[self.frame], axes)).round().astype(int)\n d = (2 * r).round().astype(int)\n\n vectors = (self.window['toggle-show-velocities'] or\n self.window['toggle-show-forces'])\n if vectors:\n V = np.dot(self.vectors[self.frame], axes) + X[:n]\n\n colors = self.get_colors()\n circle = self.window.circle\n line = self.window.line\n dynamic = self.images.dynamic\n selected = self.images.selected\n visible = self.images.visible\n ncell = len(self.B1)\n bw = self.scale * 0.15\n for a in self.indices:\n if a < n:\n ra = d[a]\n if visible[a]:\n # Draw the atoms\n if self.moving and selected[a]:\n circle(GREEN, False,\n A[a, 0] - 4, A[a, 1] - 4,\n A[a, 0] + ra + 4, A[a, 1] + ra + 4)\n\n circle(colors[a], selected[a],\n A[a, 0], A[a, 1], A[a, 0] + ra, A[a, 1] + ra)\n\n # Draw labels on the atoms\n if self.labels is not None:\n self.window.text(A[a, 0], A[a, 1],\n str(self.labels[self.frame][a]))\n\n # Draw cross on constrained atoms\n if not dynamic[a]:\n R1 = int(0.14644 * ra)\n R2 = int(0.85355 * ra)\n line((A[a, 0] + R1, A[a, 1] + R1,\n A[a, 0] + R2, A[a, 1] + R2))\n line((A[a, 0] + R2, A[a, 1] + R1,\n A[a, 0] + R1, A[a, 1] + R2))\n\n # Draw velocities or forces\n if vectors:\n line((X[a, 0], X[a, 1], V[a, 0], V[a, 1]), width=2)\n else:\n # Draw unit cell and/or bonds:\n a -= n\n if a < ncell:\n line((X1[a, 0] + disp[0], X1[a, 1] + disp[1],\n X2[a, 0] + disp[0], X2[a, 1] + disp[1]))\n else:\n line((X1[a, 0] + disp[0], X1[a, 1] + disp[1],\n X2[a, 0] + disp[0], X2[a, 1] + disp[1]), width=bw)\n\n if self.window['toggle-show-axes']:\n self.draw_axes()\n\n if self.images.nimages > 1:\n self.draw_frame_number()\n\n self.window.update()\n\n if status:\n self.status()\n\n def draw_axes(self):\n axes_length = 15\n\n rgb = ['red', 'green', 'blue']\n\n for i in self.axes[:, 2].argsort():\n a = 20\n b = self.window.size[1] - 20\n c = int(self.axes[i][0] * axes_length + a)\n d = int(-self.axes[i][1] * axes_length + b)\n self.window.line((a, b, c, d))\n self.window.text(c, d, 'XYZ'[i], color=rgb[i])\n\n def draw_frame_number(self):\n x, y = self.window.size\n self.window.text(x, y, '{0}/{1}'.format(self.frame,\n self.images.nimages),\n anchor='SE')\n\n def release(self, event):\n if event.button in [4, 5]:\n self.scroll_event(event)\n return\n\n if event.button != 1:\n return\n\n selected = self.images.selected\n selected_ordered = self.images.selected_ordered\n\n if event.time < self.t0 + 200: # 200 ms\n d = self.P - self.xy\n hit = np.less((d**2).sum(1), (self.scale * self.images.r)**2)\n for a in self.indices[::-1]:\n if a < self.images.natoms and hit[a]:\n if event.modifier == 'ctrl':\n selected[a] = not selected[a]\n if selected[a]:\n selected_ordered += [a]\n elif len(selected_ordered) > 0:\n if selected_ordered[-1] == a:\n selected_ordered = selected_ordered[:-1]\n else:\n selected_ordered = []\n else:\n selected[:] = False\n selected[a] = True\n selected_ordered = [a]\n break\n else:\n selected[:] = False\n selected_ordered = []\n self.draw()\n else:\n A = (event.x, event.y)\n C1 = np.minimum(A, self.xy)\n C2 = np.maximum(A, self.xy)\n hit = np.logical_and(self.P > C1, self.P < C2)\n indices = np.compress(hit.prod(1), np.arange(len(hit)))\n if event.modifier != 'ctrl':\n selected[:] = False\n selected[indices] = True\n if (len(indices) == 1 and\n indices[0] not in self.images.selected_ordered):\n selected_ordered += [indices[0]]\n elif len(indices) > 1:\n selected_ordered = []\n self.draw()\n\n indices = np.arange(self.images.natoms)[self.images.selected]\n if len(indices) != len(selected_ordered):\n selected_ordered = []\n self.images.selected_ordered = selected_ordered\n\n def press(self, event):\n self.button = event.button\n self.xy = (event.x, event.y)\n self.t0 = event.time\n self.axes0 = self.axes\n self.center0 = self.center\n\n def move(self, event):\n x = event.x\n y = event.y\n x0, y0 = self.xy\n if self.button == 1:\n x0 = int(round(x0))\n y0 = int(round(y0))\n self.draw()\n self.window.canvas.create_rectangle((x, y, x0, y0))\n return\n\n if event.modifier == 'shift':\n self.center = (self.center0 -\n np.dot(self.axes, (x - x0, y0 - y, 0)) / self.scale)\n else:\n # Snap mode: the a-b angle and t should multipla of 15 degrees ???\n a = x - x0\n b = y0 - y\n t = sqrt(a * a + b * b)\n if t > 0:\n a /= t\n b /= t\n else:\n a = 1.0\n b = 0.0\n c = cos(0.01 * t)\n s = -sin(0.01 * t)\n rotation = np.array([(c * a * a + b * b, (c - 1) * b * a, s * a),\n ((c - 1) * a * b, c * b * b + a * a, s * b),\n (-s * a, -s * b, c)])\n self.axes = np.dot(self.axes0, rotation)\n if self.images.natoms > 0:\n com = self.X[:self.images.natoms].mean(0)\n else:\n com = self.images.A[self.frame].mean(0)\n self.center = com - np.dot(com - self.center0,\n np.dot(self.axes0, self.axes.T))\n self.draw(status=False)\n\n def render_window(self, action):\n Render(self)\n\n def show_vectors(self, vectors):\n self.vectors = vectors\n\n def resize(self, event):\n w, h = self.window.size\n self.scale *= (event.width * event.height / (w * h))**0.5\n self.window.size[:] = [event.width, event.height]\n self.draw()\n","sub_path":"gui/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":18114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"596477302","text":"from azure.cosmos.aio import CosmosClient\nimport config\nimport asyncio\n\nHOST = config.settings['host']\nMASTER_KEY = config.settings['master_key']\n\n# ----------------------------------------------------------------------------------------------------------\n# Prerequisites -\n#\n# 1. An Azure Cosmos account -\n# https://azure.microsoft.com/en-us/documentation/articles/documentdb-create-account/\n#\n# 2. Microsoft Azure Cosmos PyPi package -\n# https://pypi.python.org/pypi/azure-cosmos/\n# ----------------------------------------------------------------------------------------------------------\n# Sample - demonstrates how to pass in values for the connection policy retry options.\n#\n# 1. retry_total is the total number of retries to allow. Takes precedence over other counts.\n# Pass in retry_total=0 if you do not want to retry on requests. Default value is 10\n#\n# 2. retry_connect option determines how many connection-related errors to retry on. Default value is 3\n#\n# 3. retry_read option determines how many times to retry on read errors. Default value is 3\n#\n# 4. retry_status determines how many times to retry on bad status codes. Default value is 3\n#\n# 5. retry_on_status_codes is a list of specific status codes to retry on. The default value is an empty list as the\n# SDK has its own retry logic already configured where this is option is taken care of.\n#\n# 6. retry_backoff_factor is a factor to calculate wait time between retry attempts. Defaults to .08 seconds\n#\n# 7. retry_backoff_max option determines the maximum back off time. Default value is 120 seconds (2 minutes)\n#\n# 8. retry_fixed_interval option determines the fixed retry interval in milliseconds.\n# The default value is None as the SDK has its own retry logic configured where this option is taken care of.\n#\n# Note:\n# While these options can be configured, the SDK by default already has retry mechanisms and we recommend to use those.\n# ----------------------------------------------------------------------------------------------------------\n\nasync def change_connection_retry_policy_configs():\n async with CosmosClient(url=HOST, credential=MASTER_KEY, retry_total=10, retry_connect=3,\n retry_read=3, retry_status=3,\n retry_on_status_codes=([]),\n retry_backoff_factor=.08, retry_backoff_max=120, retry_fixed_interval=None) as client:\n print('Client initialized with custom retry options')\n\n\nif __name__ == \"__main__\":\n asyncio.run(change_connection_retry_policy_configs())\n","sub_path":"sdk/cosmos/azure-cosmos/samples/client_user_configs_async.py","file_name":"client_user_configs_async.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"84031039","text":"# Copyright 2015, Rackspace US, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport ConfigParser\nimport io\nimport json\nimport os\nimport yaml\n\nfrom ansible import errors\nfrom ansible.runner.return_data import ReturnData\nfrom ansible import utils\nfrom ansible.utils import template\n\n\nCONFIG_TYPES = {\n 'ini': 'return_config_overrides_ini',\n 'json': 'return_config_overrides_json',\n 'yaml': 'return_config_overrides_yaml'\n}\n\n\nclass ActionModule(object):\n TRANSFERS_FILES = True\n\n def __init__(self, runner):\n self.runner = runner\n\n def grab_options(self, complex_args, module_args):\n \"\"\"Grab passed options from Ansible complex and module args.\n\n :param complex_args: ``dict``\n :param module_args: ``dict``\n :returns: ``dict``\n \"\"\"\n options = dict()\n if complex_args:\n options.update(complex_args)\n\n options.update(utils.parse_kv(module_args))\n return options\n\n @staticmethod\n def return_config_overrides_ini(config_overrides, resultant):\n \"\"\"Returns string value from a modified config file.\n\n :param config_overrides: ``dict``\n :param resultant: ``str`` || ``unicode``\n :returns: ``str``\n \"\"\"\n config = ConfigParser.RawConfigParser(allow_no_value=True)\n config_object = io.BytesIO(resultant.encode('utf-8'))\n config.readfp(config_object)\n for section, items in config_overrides.items():\n # If the items value is not a dictionary it is assumed that the\n # value is a default item for this config type.\n if not isinstance(items, dict):\n config.set('DEFAULT', section, str(items))\n else:\n # Attempt to add a section to the config file passing if\n # an error is raised that is related to the section\n # already existing.\n try:\n config.add_section(section)\n except (ConfigParser.DuplicateSectionError, ValueError):\n pass\n for key, value in items.items():\n config.set(section, key, str(value))\n else:\n config_object.close()\n\n resultant_bytesio = io.BytesIO()\n try:\n config.write(resultant_bytesio)\n return resultant_bytesio.getvalue()\n finally:\n resultant_bytesio.close()\n\n def return_config_overrides_json(self, config_overrides, resultant):\n \"\"\"Returns config json\n\n Its important to note that file ordering will not be preserved as the\n information within the json file will be sorted by keys.\n\n :param config_overrides: ``dict``\n :param resultant: ``str`` || ``unicode``\n :returns: ``str``\n \"\"\"\n original_resultant = json.loads(resultant)\n merged_resultant = self._merge_dict(\n base_items=original_resultant,\n new_items=config_overrides\n )\n return json.dumps(\n merged_resultant,\n indent=4,\n sort_keys=True\n )\n\n def return_config_overrides_yaml(self, config_overrides, resultant):\n \"\"\"Return config yaml.\n\n :param config_overrides: ``dict``\n :param resultant: ``str`` || ``unicode``\n :returns: ``str``\n \"\"\"\n original_resultant = yaml.safe_load(resultant)\n merged_resultant = self._merge_dict(\n base_items=original_resultant,\n new_items=config_overrides\n )\n return yaml.safe_dump(\n merged_resultant,\n default_flow_style=False,\n width=1000,\n )\n\n def _merge_dict(self, base_items, new_items):\n \"\"\"Recursively merge new_items into base_items.\n\n :param base_items: ``dict``\n :param new_items: ``dict``\n :returns: ``dict``\n \"\"\"\n for key, value in new_items.iteritems():\n if isinstance(value, dict):\n base_items[key] = self._merge_dict(\n base_items.get(key, {}),\n value\n )\n elif isinstance(value, list):\n if key in base_items and isinstance(base_items[key], list):\n base_items[key].extend(value)\n else:\n base_items[key] = value\n else:\n base_items[key] = new_items[key]\n return base_items\n\n def run(self, conn, tmp, module_name, module_args, inject,\n complex_args=None, **kwargs):\n \"\"\"Run the method\"\"\"\n if not self.runner.is_playbook:\n raise errors.AnsibleError(\n 'FAILED: `config_templates` are only available in playbooks'\n )\n\n options = self.grab_options(complex_args, module_args)\n try:\n source = options['src']\n dest = options['dest']\n\n config_overrides = options.get('config_overrides', dict())\n config_type = options['config_type']\n assert config_type.lower() in ['ini', 'json', 'yaml']\n except KeyError as exp:\n result = dict(failed=True, msg=exp)\n return ReturnData(conn=conn, comm_ok=False, result=result)\n\n source_template = template.template(\n self.runner.basedir,\n source,\n inject\n )\n\n if '_original_file' in inject:\n source_file = utils.path_dwim_relative(\n inject['_original_file'],\n 'templates',\n source_template,\n self.runner.basedir\n )\n else:\n source_file = utils.path_dwim(self.runner.basedir, source_template)\n\n # Open the template file and return the data as a string. This is\n # being done here so that the file can be a vault encrypted file.\n resultant = template.template_from_file(\n self.runner.basedir,\n source_file,\n inject,\n vault_password=self.runner.vault_pass\n )\n\n if config_overrides:\n type_merger = getattr(self, CONFIG_TYPES.get(config_type))\n resultant = type_merger(\n config_overrides=config_overrides,\n resultant=resultant\n )\n\n # Retemplate the resultant object as it may have new data within it\n # as provided by an override variable.\n template.template_from_string(\n basedir=self.runner.basedir,\n data=resultant,\n vars=inject,\n fail_on_undefined=True\n )\n\n # Access to protected method is unavoidable in Ansible 1.x.\n new_module_args = dict(\n src=self.runner._transfer_str(conn, tmp, 'source', resultant),\n dest=dest,\n original_basename=os.path.basename(source),\n follow=True,\n )\n\n module_args_tmp = utils.merge_module_args(\n module_args,\n new_module_args\n )\n\n # Remove data types that are not available to the copy module\n complex_args.pop('config_overrides')\n complex_args.pop('config_type')\n\n # Return the copy module status. Access to protected method is\n # unavoidable in Ansible 1.x.\n return self.runner._execute_module(\n conn,\n tmp,\n 'copy',\n module_args_tmp,\n inject=inject,\n complex_args=complex_args\n )\n\n","sub_path":"playbooks/plugins/actions/config_template.py","file_name":"config_template.py","file_ext":"py","file_size_in_byte":7954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"352314603","text":"import web #Import the web.py python framework\nimport os #Import os commands\nrender = web.template.render('templates/') #Define where the HTML pages are stored\n\n#Define database connection\ndb = web.database(\n dbn='postgres',\n host='127.0.0.1',\n port=5432,\n user='postgres',\n pw='postgres',\n db='webpy_test',\n)\n\n#Define all of the possible URLs that can be shown, as well as what method to call when each URL is visited.\nurls = (\n '/', 'index', #Home page\n '/new', 'new', #Add the book (NOT THE FORM)\n '/add', 'add', #Adding a book form\n '/book_details/(.+)', 'book_details', #GET method for getting book details. Not reccomended, and used in only one place.\n '/book_details', 'book_details', #POST method for getting book details, more secure/accurate way to get the details.\n '/review', 'review' #Submit a review method\n )\n\n\nclass index: #Define what happens when Homepagw is visited.\n def GET(self):\n global db\n books = db.select('books') #Get all books from database\n reviews = db.select('reviews') #Get all reviews from database\n return render.index(books, reviews, db) #Show index.html file, pass the books, reviews, and db (used for database operations) to the html file.\n\n\nclass add: #Define what happens when a book is added\n def POST(self):\n i = web.input(myfile={}) # Get user input, make sure image file is a dictionary object so that it is saved properly.\n filedir = 'static/images/books' #Directory where book images are stored\n if i.myfile.filename == None or i.myfile.filename == \"\": #If no book image is submitted, make the placeholder image the default image.\n myfilepath = 'static/images/books/placeholder.png'\n else: #If an image is submitted, do the following:\n fileext = i.myfile.filename.split('.')[1] #Get the file extension\n myfilepath = filedir + '/' + i.title + \".\" + fileext #Define the filepath. This is the directory + the book name + file extension\n fout = open(myfilepath, \"wb\") #Create an empty image object in the directory.\n fout.write(i.myfile.file.read()) #Write the image contents to the server\n fout.close() #Safely close the file operation.\n #Insert the book title, author, grade, genre, and image file path in the database\n n = db.insert('books', book_title=i.title, author=i.author, grade=i.grade, image=myfilepath)\n # If user wants to go to the indivdual page:\n if \"revnext\" in i:\n book = db.select('books') #Get all books\n i = web.input()\n bookTitle = i.title #Get the submitted book title\n bookDesc = \"\" #set the description empty, since the book was just added and has no description.\n bookAuthor = i.author #Get submitted author\n qr = db.select('books', where=\"book_title=$bookTitle\", vars=locals()) #Using the submitted title, get the book info from database\n results = list(qr) #Convert the request to a list so that we can do operations with it\n bookId = int(results[0]['id']) #Get the book ID from the database response\n bookGrade = int(results[0]['grade']) #Get the book grade from the database response\n qr2 = db.select('reviews', where=\"book_id=$bookId\", vars=locals()) #Get all reviews that were submitted for this book\n reviews = list(qr2) #Convert to list for operations\n avg_rating1 = 0 #The total star rating. This value will be updated later\n avg_rating2 = 0 #Number of reviews that have stars\n avg = 0 #Average star rating\n for review in reviews: #For each review in the given reviews, do the following -\n if review['rating'] != None: #If there is a star rating submitted, do the following -\n avg_rating1 += review['rating'] #Add the star to the total stars\n avg_rating2 += 1 #Add one to the total number of reviews that have stars\n if avg_rating2 == 0: #If there were no reviews with stars, set the average to 0.\n avg = 0\n else: #If there were star ratings, do the following -\n avg = avg_rating1/avg_rating2 #Divide total by num of reviews with stars\n bookIdstr =str(bookId) #Convert BookID to string for later use\n #Show the individual page with all of the collected values\n return render.book_details(book, bookId, bookTitle, bookDesc, bookAuthor, bookGrade, reviews, avg, db, bookIdstr)\n else: #If user does not want to go to the home page then -\n raise web.seeother('/') #redirect to home page\n\nclass new: #Define what happens when user clicks the \"Add a book\" button\n def GET(self):\n global db #Get the database\n book = db.select('books') #Get all books (Used to make sure book doesn't already exist)\n return render.new(book, db, str) #Pass the books, db object for operations, and string object for operations to the new book form and show form.\n\nclass book_details: #Define what happens when user wants to see individual page\n def POST(self): #POST method - all data is passed through headers, to reduce spam and show accurate results.\n book = db.select('books') #Get all books from database\n i = web.input() #Get \"hidden\" user input.\n bookId = int(i.bookId) #Get the book ID. This value is a hidden input value on each card that holds the book id.\n qr = db.select('books', where=\"id=$bookId\", vars=locals()) #Get book details from database using the ID to get more details.\n results = list(qr) #Convert to list for further operations.\n bookTitle = results[0]['book_title'] #Get the book title from the list\n bookDesc = results[0]['book_description'] #Get the book description from the list\n bookAuthor = results[0]['author'] #Get the book author from the list\n bookGrade = results[0]['grade'] #Get the book grade from the list.\n qr2 = db.select('reviews', where=\"book_id=$bookId\", vars=locals()) #Get all reviews for the selected book.\n reviews = list(qr2) #Convert to list for further operations\n avg_rating1 = 0 #The total star rating. This value will be updated later\n avg_rating2 = 0 #Number of reviews that have stars\n avg = 0 #Average star rating\n for review in reviews: #For each review in the given reviews, do the following -\n if review['rating'] != None: #If there is a star rating submitted, do the following -\n avg_rating1 += review['rating'] #Add the star to the total stars\n avg_rating2 += 1 #Add one to the total number of reviews that have stars\n if avg_rating2 == 0: #If there were no reviews with stars, set the average to 0.\n avg = 0\n else: #If there were star ratings, do the following -\n avg = avg_rating1/avg_rating2 #Divide total by num of reviews with stars\n bookIdstr =str(bookId) #Convert BookID to string for later use\n #Show the individual page with all of the collected values\n return render.book_details(book, bookId, bookTitle, bookDesc, bookAuthor, bookGrade, reviews, avg, db, bookIdstr)\n\n def GET(self):\n book = db.select('books') #Get all books from the database\n i = web.input(bookId=None) #Get URL parameters, set bookId to None by default in case none is given\n bookId = int(i.bookId) #Convert bookId to integer\n qr = db.select('books', where=\"id=$bookId\", vars=locals()) #Get book details from database using the ID to get more details.\n results = list(qr) #Convert to list for further operations.\n bookTitle = results[0]['book_title'] #Get the book title from the list\n bookDesc = results[0]['book_description'] #Get the book description from the list\n bookAuthor = results[0]['author'] #Get the book author from the list\n bookGrade = results[0]['grade'] #Get the book grade from the list.\n qr2 = db.select('reviews', where=\"book_id=$bookId\", vars=locals()) #Get all reviews for the selected book.\n reviews = list(qr2) #Convert to list for later operations\n avg_rating1 = 0 #The total star rating. This value will be updated later\n avg_rating2 = 0 #Number of reviews that have stars\n avg = 0 #Average star rating\n for review in reviews: #For each review in the given reviews, do the following -\n if review['rating'] != None: #If there is a star rating submitted, do the following -\n avg_rating1 += review['rating'] #Add the star to the total stars\n avg_rating2 += 1 #Add one to the total number of reviews that have stars\n if avg_rating2 == 0: #If there were no reviews with stars, set the average to 0.\n avg = 0\n else: #If there were star ratings, do the following -\n avg = avg_rating1/avg_rating2 #Divide total by num of reviews with stars\n bookIdstr =str(bookId) #Convert BookID to string for later use\n #Show the individual page with all of the collected values\n return render.book_details(book, bookId, bookTitle, bookDesc, bookAuthor, bookGrade, reviews, avg, db, bookIdstr)\n\nclass review: #Define what happens when a review is submitted\n def POST(self):\n book = db.select('books') #Get all books from database\n i = web.input() #Get user input\n bookId = int(i.bookId) #Get bookId (Hidden input)\n Desc = i.review #Get text review\n name = i.name #Get reviewer name\n qr = db.select('books', where=\"id=$bookId\", vars=locals()) #Get book details for specific book from database\n results = list(qr) #Convert response to list for operations\n bookTitle = results[0]['book_title'] #Get the book title from the list\n bookDesc = results[0]['book_description'] #Get the book description from the list\n bookAuthor = results[0]['author'] #Get the book author from the list\n bookGrade = results[0]['grade'] #Get the book grade from the list.\n stars = i.stars #Get stars value\n db.insert('reviews', book_id=i.bookId, name=i.name, description=i.review, rating = i.stars) #Insert text review, reviewer name, bookId, and star rating into datbase\n qr2 = db.select('reviews', where=\"book_id=$bookId\", vars=locals()) #Get reviews for specific book\n reviews = list(qr2) #Convert to list for operations\n bookId2 = str(bookId)\n raise web.seeother('/book_details?bookId='+bookId2) #Reload the individual page/reviews\n\n\nif __name__ == \"__main__\": #If current file is run -\n app = web.application(urls, globals()) #Define the web server (this is a webpy feature)\n app.run() #Start the server\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"120236676","text":"from urllib.request import urlopen\nfrom urllib.error import HTTPError,URLError\nfrom bs4 import BeautifulSoup\n\ndef getTitle(url):\n try:\n html = urlopen(url)\n except (HTTPError,URLError) as e:\n return None\n try:\n bs0bj = BeautifulSoup(html.read(),'lxml')\n title = bs0bj.body.h1\n except AttributeError as e:\n return None\n return title\n\nurl = input(\"url:\")\ntitle = getTitle(url)\nif title == None:\n print(\"Title could not be found\")\nelse:\n print(title)\n","sub_path":"gettitle.py","file_name":"gettitle.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"21"} +{"seq_id":"455181356","text":"# 1\t改写冒泡排序,将冒泡排序的最好时间复杂度改成O(n)。\r\ndef sortbuble(li):\r\n n=len(li)\r\n for i in range(n-1):\r\n didswap=True # 标志位 默认是排好的\r\n for j in range(n-1-i):\r\n if li[j]>li[j+1]:\r\n li[j],li[j+1]=li[j+1],li[j]\r\n didswap=False\r\n if didswap:\r\n return li\r\n\r\n return li\r\n# print(sortbuble([2,4,5,-5,-10,8]))\r\n# print(sortbuble([2,4,5,8,10,18]))\r\n\r\n# 2\t将所有的排序使用降序实现。\r\ndef choosesort(li):\r\n n=len(li)\r\n for i in range(n-1):\r\n max_index=i\r\n for j in range(i+1,n):\r\n if li[max_index]li[j] and j>=0:\r\n li[j+1]=li[j]\r\n j-=1\r\n li[j+1]=temp\r\n return li\r\n# print(insertsort(li))\r\n\r\n\r\n# 希尔排序\r\nli=[6,4,2,5,-5,-10,8]\r\n# 通常情况下增量 从大到小 len(li)//2开始,一直到1 ,列表\r\n[3,2,1]\r\ndef insertsort(li,increment):\r\n n = len(li)\r\n for inc in increment:\r\n for k in range(inc):\r\n for i in range(k+inc,n,inc):\r\n temp=li[i]\r\n j=i-inc\r\n while temp>li[j] and j>=0:\r\n li[j+inc]=li[j]\r\n j-=inc\r\n li[j+inc]=temp\r\n print(li)\r\n return li\r\nprint(insertsort(li,[3,2,1]))\r\n\r\n\r\n# 快速\r\nli=[6,4,2,5,-5,-10,8]\r\ndef quick(li,left,right):\r\n if leftli[right]:\r\n right-=1\r\n li[left]=li[right]\r\n\r\n while left=li[right]:\r\n temp.append(li[left])\r\n left+=1\r\n else:\r\n temp.append(li[right])\r\n right+=1\r\n while left<=mid:\r\n temp.append(li[left])\r\n left+=1\r\n while right<=high:\r\n temp.append(li[right])\r\n right+=1\r\n li[low:high+1]=temp\r\n\r\nprint(merge(li,0,len(li)-1))\r\n\r\n\r\n# 3\t能够手写排序算法。(面试) 冒泡、选择、插入、快速(最好)\r\n\r\n\r\n# 4\t使用递归的方式实现折半查找。\r\n# 找临界点\r\n# 对于排好序的列表进行折半查找\r\ndef search(li,key,low,high):\r\n mid=(low+high)//2\r\n if key==li[mid]:\r\n return mid\r\n if low>high:\r\n return -1\r\n if key