diff --git "a/3864.jsonl" "b/3864.jsonl" new file mode 100644--- /dev/null +++ "b/3864.jsonl" @@ -0,0 +1,707 @@ +{"seq_id":"354504162","text":"# -*- coding: utf-8 -*-\nfrom django.db import models, migrations\n\ndef filling_database(apps, schema_editor):\n Item = apps.get_model(\"catalog\", \"Item\")\n for i in xrange(1, 22):\n item = Item(image='catalog/img-{}.jpg'.format(i),\n modified='2015-03-17T10:00:00.000Z',\n created='2015-03-17T10:00:00.000Z')\n item.save()\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('catalog', '0001_initial'),\n ]\n\n operations = [\n migrations.RunPython(filling_database),\n ]\n","sub_path":"demo_catalog/catalog/migrations/0002_filling_database.py","file_name":"0002_filling_database.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"114755974","text":"import numpy\nimport Data_load as dl\n\ndef smooth(x, window_len=100, window='hanning'):\n \"\"\"smooth the data using a window with requested size.\n\n This method is based on the convolution of a scaled window with the signal.\n The signal is prepared by introducing reflected copies of the signal\n (with the window size) in both ends so that transient parts are minimized\n in the begining and end part of the output signal.\n\n input:\n x: the input signal\n window_len: the dimension of the smoothing window; should be an odd integer\n window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'\n flat window will produce a moving average smoothing.\n\n output:\n the smoothed signal\n\n example:\n\n t=linspace(-2,2,0.1)\n x=sin(t)+randn(len(t))*0.1\n y=smooth(x)\n\n see also:\n\n numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve\n scipy.signal.lfilter\n\n TODO: the window parameter could be the window itself if an array instead of a string\n NOTE: length(output) != length(input), to correct this: return y[(window_len/2-1):-(window_len/2)] instead of just y.\n \"\"\"\n\n s = numpy.r_[x[window_len - 1:0:-1], x, x[-2:-window_len - 1:-1]]\n # print(len(s))\n if window == 'flat': # moving average\n w = numpy.ones(window_len, 'd')\n else:\n w = eval('numpy.' + window + '(window_len)')\n\n y = numpy.convolve(w / w.sum(), s, mode='valid')\n return y\n\n\nfrom numpy import *\nfrom pylab import *\nimport os\nimport random\n\ncurrent_path = os.getcwd()\n\nDataX = list()\nDataY = list()\n\nData_Animal_X = list()\nData_Animal_Y = list()\n\nData_Both_X = list()\nData_Both_Y = list()\n\nData_sun_human = list()\nData_sun_human_Y = list()\nData_rain_human = list()\nData_rain_human_Y = list()\nData_sun_none = list()\nData_sun_none_Y = list()\nData_rain_none = list()\nData_rain_none_Y = list()\n\ndl.Data_load(\"Sunny\", \"Animal\", 3, Data_Animal_X, Data_Animal_Y)\n\ndl.Data_load(\"Sunny\", \"Human\", 3, DataX, DataY)\n\n#dl.Data_load(\"Sunny\", \"Both\", 3, Data_Both_X, Data_Both_Y)\n\ndl.Data_load(\"Sunny\", \"Human\", 3, Data_sun_human, Data_sun_human_Y)\n\ndl.Data_load(\"Rain\", \"Human\", 3, Data_rain_human, Data_rain_human_Y)\n\ndl.Data_load(\"Sunny\", \"None\", 3, Data_sun_none, Data_sun_none_Y)\n\ndl.Data_load(\"Rain\", \"None\", 3, Data_rain_none, Data_rain_none_Y)\n\nsun = list()\nrain = list()\nsun_ani = list()\nsun_none = list()\nrain_none = list()\n\nfor i in range(0,10):\n j = random.randrange(0, Data_sun_human.__len__())\n sun.append(Data_sun_human[j])\n j = random.randrange(0, Data_rain_human.__len__())\n rain.append(Data_rain_human[j])\n j = random.randrange(0, Data_Animal_X.__len__())\n sun_ani.append(Data_Animal_X[j])\n j = random.randrange(0, Data_sun_none.__len__())\n sun_none.append(Data_sun_none[j])\n j = random.randrange(0, Data_rain_none.__len__())\n rain_none.append(Data_rain_none[j])\n print(j)\n\ndef smooth_data(datalist, plot_title):\n\n for i in range(0,10):\n t = linspace(-4, 4, 100)\n x = datalist[i]\n xn = x + randn(len(t)) * 0.1\n y = smooth(x)\n\n ws = 31\n\n subplot(211)\n\n plot(x)\n\n windows = ['flat']\n\n title(plot_title)\n subplot(212)\n\n plot(smooth(xn, 10, 'flat'))\n\n title(\"Smoothing\")\n\n show()\n\nsmooth_data(sun,\"Sunny & Human\")\nsmooth_data(rain, \"Rain & Human\")\n\nsmooth_data(sun_none, \"Sunny & None\")\nsmooth_data(rain_none, \"Rain & None\")\n\nsmooth_data(sun_ani, \"Sunny & Animal\")","sub_path":"Data_smooth.py","file_name":"Data_smooth.py","file_ext":"py","file_size_in_byte":3502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"355497407","text":"from menu import Menu\nfrom coffee_maker import CoffeeMaker\nfrom money_machine import MoneyMachine\n\nobj_coffee_maker = CoffeeMaker()\nobj_menu = Menu()\nobj_money_machine = MoneyMachine()\n\nis_machine_on = True\n\nwhile is_machine_on:\n command = input(f\"What would you like? {obj_menu.get_items()}: \")\n if command == \"report\":\n obj_coffee_maker.report()\n elif command == \"off\":\n is_machine_on = False\n else:\n drink = obj_menu.find_drink(command)\n if drink is not None:\n if obj_coffee_maker.is_resource_sufficient(drink):\n if obj_money_machine.make_payment(drink.cost):\n obj_coffee_maker.make_coffee(drink)\n","sub_path":"projects/day016/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"399936675","text":"'''\n Program: project1.py\n Author: Patrick Mann\n Class: CSC 111LB\n Purpose: keeps track of organizations and their descriptions of what they do.\n'''\n\norgs = []\ndef readFile(filename):\n\t'''\n\t\tRead contents of file whose name is filename, and return it.\n\t\tReturn empty string on error.\n\t'''\n\ttry:\n\t\tf = open(filename,'r')\n\t\ttext = f.read()\n\t\tf.close()\n\t\treturn text\n\texcept:\n\t\tprint('Error in readfile: filename='+filename)\n\t\treturn ''\n\ndef getDatabase():\n lines = readFile(\"database.txt\").split(\"\\n\")\n \n global orgs\n orgs = [] # list of all organizations. this is a list of tuples\n current_name = \"\" # the name of the current organization we are reading in\n current_list = [] # the current organization's list of activities\n \n for line in lines:\n \tif line.startswith(\"name:\"):\n \t\tif len(current_name) > 0:\n \t\t\torgs.append([current_name, current_list])\n \t\tcurrent_name = line[5:]\n \t\tcurrent_list = []\n \telif len(line) > 0:\n \t\tcurrent_list.append(line)\n \n orgs.append([current_name, current_list])\n\n# this is the beginning of the main code\ndef main():\n\t'''\n\t\tThe main function that is called at the end of the file, and sets the program in motion.\n\t\tIt contains a while forever loop that dispatches commands to other functions that do\n\t\twork.\n\t'''\n\tprint('This is Project1, which keeps track of organizations and their descriptions.')\n\tprint(\"For a list of commans, type 'help' and press RETURN.\")\n\tprint(\"To stop the program, type 'stop', or 'end' and press RETURN\")\n\tprint()\n\t\n\twhile True:\n\t\tcommand = input('Command? ')\n\t\tif command == 'stop' or command == 'end' or command == 'quit':\n\t\t\tbreak\n\t\telif command == \"help\" or command == \"?\":\n\t\t\thelp()\n\t\telif command == 'list':\n\t\t\tshow(orgs)\n\t\telif command == 'list sorted':\n\t\t\tdisplay(orgs)\n\t\telif command.startswith('find '):\n\t\t\tfind(command[5:])\n\t\telif command.startswith('find activity '):\n\t\t\tfind_activity(command[14:])\n\t\telif command.startswith('describe '):\n\t\t\tdescribe(command[9:])\n\t\telse:\n\t\t\tprint('Unknown command! Try help')\n\ndef help():\n\t'''\n\t\tList of all the commands with a short explanantion\n\t'''\n\tprint(\"stop -- end this application\")\n\tprint(\"end -- same as stop\")\n\tprint(\"help -- get list of commands\")\n\tprint(\"list -- lists all of the organizations\")\n\tprint(\"list sorted -- lists all of the organizations in alphabetical order\")\n\tprint(\"find XXX -- find all organizatoins with a partial name XXX\")\n\tprint(\"find activity XXX -- find all organizatoins with an activity that partially matches XXX\")\n\tprint(\"desribe XXX -- list the acitivies of organization XXX\")\n\ndef show (somelist):\n\t'''\n\t\tprints a numbered list of organizations\n\t'''\n\tfor org in orgs:\n\t\tprint(orgs.index(org) +1, end=\". \")\n\t\tprint(org[0])\n\treturn somelist\n\ndef display (somelist):\n\t'''\n\t\tprints a numbered list of the organizations in an alphabetical order\n\t'''\n\tlistsorted = sorted(orgs)\n\tfor org in listsorted:\n\t\tprint(listsorted.index(org) +1, end=\". \")\n\t\tprint(org[0])\n\treturn somelist\n\ndef find (partial_org_name):\n\t'''\n\t\tfind the organization from the partial name given\n\t'''\n\tprint('The organization based off partialString is ')\n\t\t \ndef find_activity (activity):\n\t'''\n\t\tfind the organizations with the desired activity \n\t'''\n\tprint('The organizations the desired activity are ')\n\ndef describe (org_name):\n\t'''\n\t\tprints a description of the organizations\n\t'''\n\tprint('The description of the desired organization')\n\t\ngetDatabase()\nmain ()\nprint(\"Commands:\\n---------------------\")\nprint(\" stop -- end this program\")\nprint(\" list -- list all the organizations\")\nprint(\" find X -- find all organizations with a partial name X\")\n","sub_path":"CSC 111/Lab 7/CODE7/Project_version0.py","file_name":"Project_version0.py","file_ext":"py","file_size_in_byte":3675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"525482036","text":"import sys\nimport os\nimport threading\nimport socket\nimport time\nimport uuid\nimport datetime\nimport struct\n\nANSI_RESET = \"\\u001B[0m\"\nANSI_RED = \"\\u001B[31m\"\nANSI_GREEN = \"\\u001B[32m\"\nANSI_YELLOW = \"\\u001B[33m\"\nANSI_BLUE = \"\\u001B[34m\"\n\n_NODE_UUID = str(uuid.uuid4())[:8]\n\n\ndef print_yellow(msg):\n print(f\"{ANSI_YELLOW}{msg}{ANSI_RESET}\")\n\n\ndef print_blue(msg):\n print(f\"{ANSI_BLUE}{msg}{ANSI_RESET}\")\n\n\ndef print_red(msg):\n print(f\"{ANSI_RED}{msg}{ANSI_RESET}\")\n\n\ndef print_green(msg):\n print(f\"{ANSI_GREEN}{msg}{ANSI_RESET}\")\n\n\ndef get_broadcast_port():\n return 35498\n\n\ndef get_node_uuid():\n return _NODE_UUID\n\n\nclass NeighborInfo(object):\n\n def __init__(self, delay, broadcast_count, ip=None, tcp_port=None):\n # Ip and port are optional, if you want to store them.\n\n self.delay = delay\n\n self.broadcast_count = broadcast_count\n\n self.ip = ip\n\n self.tcp_port = tcp_port\n\n\nneighbor_information = {}\n\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver_address = (\"\", 0)\nserver.bind(server_address)\nserver.listen(50)\n\nbroadcaster = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nbroadcaster.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)\nbroadcaster.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\nbroadcaster.bind((\"\", get_broadcast_port()))\n\n\ndef send_broadcast_thread():\n node_uuid = get_node_uuid()\n msg = node_uuid + ' ON ' + str(server.getsockname()[1])\n print('my tcp port ' + str(server.getsockname()[1]))\n while True:\n broadcaster.sendto(msg.encode('utf-8'), ('', get_broadcast_port()))\n time.sleep(1)\n\n\ndef receive_broadcast_thread():\n while True:\n data, (ip, port) = broadcaster.recvfrom(4096)\n uuid = data[:8].decode('utf-8')\n tcp_port = int(data[12:].decode('utf-8'))\n\n if uuid != get_node_uuid():\n if uuid in neighbor_information:\n if neighbor_information[uuid].broadcast_count < 10:\n neighbor_information[uuid].broadcast_count += 1\n print_blue(f\"RECV: {data} FROM: {ip}:{port}\")\n else:\n neighbor_information[uuid].broadcast_count = 1\n print_blue(f\"RECV: {data} FROM: {ip}:{port}\")\n th3 = daemon_thread_builder(exchange_timestamps_thread, args=(uuid, ip, tcp_port))\n\n else:\n neighbor = NeighborInfo(None, 1, ip, tcp_port)\n neighbor_information[uuid] = neighbor\n th3 = daemon_thread_builder(exchange_timestamps_thread, args=(uuid, ip, tcp_port))\n\n\ndef tcp_server_thread():\n while True:\n connection, address = server.accept()\n connection.send(str(datetime.datetime.utcnow().timestamp()).encode('utf-8'))\n connection.close()\n\n\ndef exchange_timestamps_thread(other_uuid: str, other_ip: str, other_tcp_port: int):\n try:\n client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n print_yellow(f\"ATTEMPTING TO CONNECT TO {other_uuid}\")\n time.sleep(3)\n client.connect((other_ip, other_tcp_port))\n other_timestamp = float(client.recv(4096).decode('utf-8'))\n current_timestamp = datetime.datetime.utcnow().timestamp()\n other_delay = current_timestamp - other_timestamp\n print_red('the old delay: ' + str(neighbor_information[other_uuid].delay))\n neighbor_information[other_uuid].delay = other_delay\n print_red('the new delay: ' + str(neighbor_information[other_uuid].delay))\n client.close()\n \n except ConnectionRefusedError:\n print('The node ' + other_uuid + ' that you try to connect has left...')\n neighbor_information.pop(other_uuid)\n\n\ndef daemon_thread_builder(target, args=()) -> threading.Thread:\n th = threading.Thread(target=target, args=args)\n th.setDaemon(True)\n th.start()\n return th\n\n\ndef entrypoint():\n th1 = daemon_thread_builder(send_broadcast_thread, args=())\n th2 = daemon_thread_builder(receive_broadcast_thread, args=())\n th4 = daemon_thread_builder(tcp_server_thread, args=())\n th1.join()\n th2.join()\n th4.join()\n\n\ndef main():\n print(\"*\" * 50)\n print_red(\"To terminate this program use: CTRL+C\")\n print_red(\"If the program blocks/throws, you have to terminate it manually.\")\n print_green(f\"NODE UUID: {get_node_uuid()}\")\n print(\"*\" * 50)\n time.sleep(2) # Wait a little bit.\n entrypoint()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"sdss.py","file_name":"sdss.py","file_ext":"py","file_size_in_byte":4609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"62535659","text":"# ----------------------------------------------------------------Importing the Libraries----------------------------------------------------------------\nimport torch.nn as nn\nfrom torch.nn.modules.container import ModuleList\nfrom torchvision import transforms\nimport torch\nfrom torchvision import datasets\nfrom torch.utils.data import DataLoader\nimport torch.functional as F\nimport os\nfrom tqdm import tqdm\nfrom time import sleep\n\n# ----------------------------------------------------------------Hyper Parameters ----------------------------------------------------------------------\n\nbatch_size = 32\nnum_epochs = 100\nlearning_rate = 3e-4\nnum_classes = 10\ncheckpoint_file = 'checkpoints\\\\checkpoint{}.pth.tar'\nload_model = True if os.path.isfile(\"my_checkpoint.pth.tar\") else False\nload_model = False\ndevice_ = 'cuda'if torch.cuda.is_available() else 'cpu'\n\n# ----------------------------------------------------------------Data Transformations-------------------------------------------------------------------\ndata_transforms = transforms.Compose([\n transforms.Resize(32),\n transforms.ToTensor(),\n transforms.Normalize(\n mean = [0.4913997551666284, 0.48215855929893703, 0.4465309133731618],\n std = [0.24703225141799082, 0.24348516474564, 0.26158783926049628]\n )\n])\n# ----------------------------------------------------------------Download the dataset----------------------------------------------------------------\n\n# Download the files mannually because it was taking time \ncifar10_train = datasets.CIFAR10(root = 'data', transform = data_transforms, train =True, download = True)\ncifar10_val = datasets.CIFAR10(root = 'data', transform = data_transforms, train = False, download = True)\n\n# ----------------------------------------------------------------Info about the dataset----------------------------------------------------------------\n\nprint(type(cifar10_train).__mro__)\nprint(cifar10_val._check_integrity)\nprint(cifar10_val.classes)\n\n# ----------------------------------------------------------------Creating DataLoaders-----------------------------------------------------------------\n\ntrain_loader = DataLoader(dataset = cifar10_train, batch_size = batch_size, shuffle = True)\nval_loader = DataLoader(dataset = cifar10_val, batch_size = batch_size, shuffle = True)\n\n# ----------------------------------------------------------------Create the model---------------------------------------------------------------------\n\nclass Net(nn.Module):\n def __init__(self, in_channels=3, num_classes=num_classes):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(in_channels=in_channels, out_channels = 512, kernel_size =3, padding = (1,1))\n self.conv2 = nn.Conv2d(in_channels=512, out_channels = 256, kernel_size =3, padding = (1,1)) \n self.conv3 = nn.Conv2d(in_channels=256, out_channels = 128, kernel_size =3, padding = (1,1)) \n self.relu = nn.ReLU()\n self.pool1 = nn.MaxPool2d(kernel_size=2)\n self.pool2 = nn.MaxPool2d(kernel_size=2)\n self.fc1 = nn.Linear(in_features= 128 * 8 * 8, out_features = 64)\n self.fc2 = nn.Linear(in_features = 64, out_features = num_classes)\n \n def forward(self, x):\n out = self.conv1(x)\n out = self.relu(out)\n out = self.pool1(out)\n out = self.conv2(out)\n out = self.relu(out)\n out = self.pool2(out)\n out = self.conv3(out)\n out = self.relu(out)\n out = out.view(-1, 128 * 8 * 8)\n out = self.fc1(out)\n out = self.relu(out)\n out = self.fc2(out)\n return out\n\n# ----------------------------------------------------------------Test Run----------------------------------------------------------------------------\n\ndef test_model():\n x = torch.rand((1,3,32,32))\n model = Net().to(device_)\n out = model(x)\n print(out.shape)\n del model\n print(\"Test Succesfull\")\n\n\n# ----------------------------------------------------------------Initialize Model----------------------------------------------------------------\n\nmodel = Net().to(device_)\n\n# ----------------------------------------------------------------Declare Optimizer and Loss Function--------------------------------------------------\n\nloss_function = nn.CrossEntropyLoss()\noptimizer = torch.optim.SGD(params = model.parameters(), lr = learning_rate)\n\n# pro tip : to check argument of any functions\n \n\"\"\"import inspect\ninspect.signature(functionname)\n\"\"\"\n\n# ----------------------------------------------------------------Define Train Function----------------------------------------------------------------\n\ndef train():\n total_inputs = 0\n total_loss = 0\n correct = 0\n for epoch in range(num_epochs):\n model.train() #Declaring the training mode\n loop = tqdm(enumerate(train_loader), total = len(train_loader), leave = False)\n for batch_idx, (data, target) in loop:\n data, target = data.to(device_), target.to(device_)\n optimizer.zero_grad()\n output = model(data)\n loss = loss_function(output, target)\n loss.backward()\n optimizer.step()\n total_loss +=loss.item()\n total_inputs += len(target)\n _, predicted = torch.max(output, dim=1)\n correct += int((predicted == target).sum())\n loop.set_description(f\"Epoch [{epoch}/{num_epochs}]\")\n loop.set_postfix(loss = total_loss/total_inputs, accu = \"{0:.0%}\".format(correct/total_inputs)) \n\n print(\"training Completed !!\")\n\n\n# ----------------------------------------------------------------Define Validation Function------------------------------------------------------------\n\ndef val():\n pass\n\n# ---------------------------------------------------------------- Run IF Main --------------------------------------------------------------------------\n\nif __name__ =='__main__':\n train()\n val()","sub_path":"cifar10_implementation.py","file_name":"cifar10_implementation.py","file_ext":"py","file_size_in_byte":5943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"131387887","text":"from django.shortcuts import render\n\nfrom django.http import HttpResponse\n\nimport json\n\ndef join(request):\n\tresponse = \"\"\n\tf = open(\"players.json\", \"r+\")\n\tdata = json.load(f)\n\n\ttry:\n\t\tnew_player = data[\"players\"].index(False)\n\n\t\tdata[\"players\"][new_player] = True\n\t\tresponse = new_player+1\n\n\t\tf.truncate(0)\n\t\tf.seek(0, 0)\n\t\tjson.dump(data, f)\n\texcept ValueError:\n\t\tresponse = \"max\"\n\n\tf.close()\n\n\treturn HttpResponse(response)\n\ndef leave(request, player_no):\n\tf = open(\"players.json\", \"r+\")\n\tdata = json.load(f)\n\n\tdata[\"players\"][int(player_no)-1] = False\n\n\tf.truncate(0)\n\tf.seek(0, 0)\n\tjson.dump(data, f)\n\n\tf.close()\n\n\treturn HttpResponse(\"\")","sub_path":"PiGame/pigame/players/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"2970399","text":"import bs4\nfrom scrapy.contrib.spiders.crawl import CrawlSpider\nimport scrapy\nfrom ..items import LanfangwItem\n\n\nclass LanfangwSpider(CrawlSpider):\n #\n # 爬去蓝房网 规则\n #\n\n name = 'lanfangwspider'\n allowed_domains = ['lanfw.com']\n start_urls = ['http://bj.lanfw.com/']\n\n def parse(self, response):\n data = '''福州厦门泉州漳州龙岩\n平潭三明莆田南平\n北京上海常州盐城'''\n soup = bs4.BeautifulSoup(data, 'lxml')\n\n #\n # 获取 所有城市\n #\n\n citybox = soup.find_all('a')\n for child in citybox:\n city = child.get_text()\n city_id = child.get('href').split('/')[-1]\n site_url = child.get('href') + '/search/'\n\n citys = {\n 'website': '蓝房网', 'web_url': 'lanfw.com',\n 'city': city, 'city_id': city_id\n }\n yield scrapy.Request(site_url, callback=self.parse_city_area, meta=citys)\n\n def parse_city_area(self, response):\n meta = response.meta\n data = response.body\n soup = bs4.BeautifulSoup(data, 'lxml')\n\n #\n # 获取 城市下面的区域\n #\n\n areabox = soup.select('.address')[0]\n areas = areabox.find_all('a')\n for child in areas:\n area = child.get_text()\n area_url = child.get('href')\n if area != '全部':\n meta['area'] = area\n yield scrapy.Request(area_url, callback=self.parse_city_estate, meta=meta)\n\n def parse_city_estate(self, response):\n meta = response.meta\n area = meta['area']\n data = response.body\n soup = bs4.BeautifulSoup(data, 'lxml')\n estatebox = soup.select('.title > h2 > a')\n for child in estatebox:\n estate = child.get_text()\n estate_url = child.get('href')\n estate_id = child.get('href').split('/')[-1]\n item = LanfangwItem()\n item['website'] = meta['website']\n item['web_url'] = meta['web_url']\n item['city'] = meta['city']\n item['city_id'] = meta['city_id']\n item['area'] = area\n item['estate'] = estate\n item['estate_id'] = estate_id\n item['estate_url'] = estate_url\n yield item\n\n #\n # 进行翻页\n #\n\n pages = soup.select('.pages > ul > li > a')\n if pages:\n next_page = soup.select('.pages > ul > li > a')[-1]\n next = next_page.get_text()\n if next == '下一页':\n next_url = next_page.get('href')\n yield scrapy.Request(next_url, callback=self.parse_city_estate, meta=meta)\n","sub_path":"Engineer/house/lanfangw/lanfangw/spiders/lanfangw_spider.py","file_name":"lanfangw_spider.py","file_ext":"py","file_size_in_byte":3448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"209332562","text":"#示例\ncars = ['audi','bmw','subaru','toyota']\nfor car in cars:\n if car == 'bmw':#if有冒号,注意缩进\n print(car.upper())#python中大小写不一样两个字符串不相等\n else:#else有冒号,注意缩进\n print(car.title())\n\n#示例\na = 20\nb = 30\nc = 33\nif aa or b pastalex:\n pastalex = currentalex\n pastlee = currentlee\n elif not alex and currentlee > pastlee:\n pastlee = currentlee\n pastalex = currentalex\n x += 1\n i += 1\n\n return pastalex, pastlee\n\n optimal_alex, optimal_lee = pebble(piles, 0, 1, True)\n return optimal_alex\n\ndef stoner_II(piles):\n n = len(piles)\n for i in range(len(piles) - 2, -1, -1):\n piles[i] += piles[i + 1]\n\n hashmap = {}\n def pebble_II(i, m):\n if (i, m) in hashmap:\n return hashmap[(i, m)]\n\n if i + (2 * m) >= n:\n res = piles[i]\n hashmap[(i, m)] = res\n return hashmap[(i, m)]\n\n res = piles[i] - min(pebble_II(i + x, max(m, x)) for x in range(1, (2 * m) + 1))\n hashmap[(i, m)] = res\n return hashmap[(i, m)]\n\n return pebble_II(0, 1)\n\ndef stoneGameIII(piles) -> int:\n n=len(piles)\n for i in range(len(piles)-2,-1,-1):\n piles[i]+=piles[i+1]\n cache={}\n def dp(i,m):\n if(i,m) in cache:\n return cache[(i,m)]\n if i+2*m>=n:\n res=piles[i]\n cache[(i,m)]=res\n return cache[(i,m)]\n res=piles[i]-min(dp(i+x,max(m,x)) for x in range(1,2*m+1))\n cache[(i,m)]=res\n return cache[(i,m)]\n return dp(0,1)\n\nif __name__ == \"__main__\":\n piles = [2, 9, 7, 4, 4]\n print(stoneGameIII(piles))\n piles = [2, 9, 7, 4, 4]\n print(stoner_II(piles))\n\n piles = [8270,7145,575,5156,5126,2905,8793,7817,5532,5726,7071,7730,5200,5369,5763,7148,8287,9449,7567,4850,1385,2135,1737,9511,8065,7063,8023,7729,7084,8407]\n print(stoneGameIII(piles))\n piles = [8270, 7145, 575, 5156, 5126, 2905, 8793, 7817, 5532, 5726, 7071, 7730, 5200, 5369, 5763, 7148, 8287, 9449,7567, 4850, 1385, 2135, 1737, 9511, 8065, 7063, 8023, 7729, 7084, 8407]\n print(stoner_II(piles))\n\n piles = [7,5,9,9,9,9,5,1,8,6]\n print(stoner(piles))","sub_path":"stone_game_II.py","file_name":"stone_game_II.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"16683634","text":"import datetime\nfrom casexml.apps.phone.analytics import get_sync_logs_for_user, update_analytics_indexes\nfrom dimagi.utils.couch.database import get_db\nfrom django.test import TestCase\nfrom casexml.apps.phone.dbaccessors.sync_logs_by_user import get_last_synclog_for_user\nfrom casexml.apps.phone.models import SyncLog, SimplifiedSyncLog, get_properly_wrapped_sync_log\nfrom corehq.util.test_utils import DocTestMixin\n\n\nclass DBAccessorsTest(TestCase, DocTestMixin):\n maxDiff = None\n\n @classmethod\n def setUpClass(cls):\n cls.user_id = 'lkasdhfadsloi'\n cls.sync_logs = [\n SyncLog(user_id=cls.user_id, date=datetime.datetime(2015, 7, 1, 0, 0)),\n SimplifiedSyncLog(user_id=cls.user_id, date=datetime.datetime(2015, 3, 1, 0, 0)),\n SyncLog(user_id=cls.user_id, date=datetime.datetime(2015, 1, 1, 0, 0))\n ]\n sync_logs_other = [SyncLog(user_id='other')]\n cls.docs = cls.sync_logs + sync_logs_other\n for doc in cls.docs:\n doc.save()\n cls.legacy_sync_logs = [\n SyncLog(user_id=cls.user_id, date=datetime.datetime(2014, 12, 31, 0, 0))\n ]\n for doc in cls.legacy_sync_logs:\n get_db(None).save_doc(doc)\n update_analytics_indexes()\n\n @classmethod\n def tearDownClass(cls):\n for doc in cls.docs:\n doc.delete()\n get_db(None).delete_docs(cls.legacy_sync_logs)\n\n def test_get_sync_logs_for_user(self):\n self.assert_doc_lists_equal(\n get_sync_logs_for_user(self.user_id, 4),\n self.sync_logs + self.legacy_sync_logs)\n\n def test_get_last_synclog_for_user(self):\n self.assert_docs_equal(\n get_last_synclog_for_user(self.user_id), self.sync_logs[0])\n\n def test_get_and_save_legacy_synclog_with_attachm(self):\n legacy_sync_log = self.legacy_sync_logs[0]\n attachment_name = 'test_attach'\n get_db(None).put_attachment(legacy_sync_log._doc, 'test', attachment_name, 'text/plain')\n\n sync_log = get_properly_wrapped_sync_log(legacy_sync_log._id)\n self.assertIn(attachment_name, sync_log._attachments)\n\n # this used to fail for docs with attachments\n sync_log.save()\n\n # cleanup\n def del_attachment():\n get_db(None).delete_attachment(legacy_sync_log._doc, attachment_name)\n del legacy_sync_log._attachments\n\n self.addCleanup(del_attachment)\n self.addCleanup(sync_log.delete)\n","sub_path":"corehq/ex-submodules/casexml/apps/phone/tests/test_dbaccessors.py","file_name":"test_dbaccessors.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"165469960","text":"# Will modify vMath.cpp under ROS to be included here... eventually\n\nimport math\n\n\nclass vector:\n def __init__(self, magnitude, direction, elevation):\n self.magnitude = magnitude\n self.direction = direction\n\n #\n if 0 <= elevation <= 90:\n self.elevation = 90 - math.fabs(elevation)\n elif -90 <= elevation < 0:\n self.elevation = 90 + math.fabs(elevation)\n else:\n print ('You made an error')\n\n self.x = magnitude * math.sin(math.radians(self.elevation)) * math.cos(math.radians(direction))\n self.y = magnitude * math.sin(math.radians(self.elevation)) * math.sin(math.radians(direction))\n self.z = magnitude * math.cos(math.radians(self.elevation))\n","sub_path":"vMath.py","file_name":"vMath.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"645958290","text":"#!/usr/bin/env python\n#coding:utf-8\nimport rrdtool\nimport os\nimport urllib2\nimport json\n\nprometheus_gateway = 'http://192.168.60.62:30868'\ndata_dir = '/var/lib/smokeping/'\n\n\ndef pushMetrics(instance, idc, key, value, method=None):\n def curl_print(url):\n if method:\n print(\n 'curl -X {:s} -H \"Content-Type: application/json;charset=utf-8\" {:s} -d \\'{:s}\\'|python -mjson.tool'.\n format(method, url, metrics))\n else:\n print(\n 'curl -X GET -H \"Content-Type: application/json;charset=utf-8\" {:s}|python -mjson.tool'.\n format(url))\n\n pushgateway = '{}/metrics/job/smokeping-collected-{}/instance/{}'.format(\n prometheus_gateway, idc, instance)\n metrics = 'smokeping_%s{instance=\"%s\", idc=\"%s\"} %d' % (key, instance, idc,\n value)\n print(pushgateway, metrics)\n req = urllib2.Request('{:s}'.format(pushgateway), data=metrics)\n req.add_header('Content-Length', '%d' % len(metrics))\n req.add_header('Content-type', 'application/octet-stream')\n if method:\n curl_print(pushgateway)\n req.get_method = lambda: method\n try:\n objs = json.loads(urllib2.urlopen(req).read())\n return objs\n except all as e:\n print(e)\n\n\ndef getMonitorData(rrd_file):\n rrd_info = rrdtool.info(rrd_file)\n last_update = rrd_info['last_update'] - 60\n args = '-s ' + str(last_update)\n results = rrdtool.fetch(rrd_file, 'AVERAGE', args)\n lost_package_num = int(results[2][0][1])\n average_rrt = 0 if not results[2][0][2] else results[2][0][2] * 1000\n return lost_package_num, round(average_rrt, 4)\n\n\nif __name__ == '__main__':\n idc_list = ['K8S']\n for idc in idc_list:\n rrd_data_dir = os.path.join(data_dir, idc)\n for filename in os.listdir(rrd_data_dir):\n (instance, postfix) = os.path.splitext(filename)\n if postfix == '.rrd':\n (lost_package_num,\n rrt) = getMonitorData(os.path.join(data_dir, idc, filename))\n print(instance, idc, 'rrt', rrt)\n pushMetrics(instance, idc, 'rrt', rrt, method='POST')\n pushMetrics(\n instance,\n idc,\n 'lost_package_num',\n lost_package_num,\n method='POST')\n","sub_path":"available/k8s/smokeping2prometheus.py","file_name":"smokeping2prometheus.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"220364943","text":"from django.conf.urls import url # Removed the include.\nfrom . import views # This line is to import the views.\n\nurlpatterns = [\n url(r'^$', views.index), # Now pointing to the views.py for action!\n url(r'^new$', views.new),\n url(r'^create$', views.create),\n url(r'^(?P\\d+)$', views.show),\n url(r'^(?P\\d+)/edit$', views.edit),\n url(r'^(?P\\d+)/delete$', views.destory),\n]\n","sub_path":"Django/multiple_apps/apps/blogs_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"461800272","text":"\nimport socket\nimport time\nAny = '0.0.0.0'\nmulticast_addr = '224.168.2.9'\nmulticast_port = 1600\n\nsock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,socket.IPPROTO_UDP)\nsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nsock.bind((Any,multicast_port))\nsock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)\nstatus = sock.setsockopt(socket.IPPROTO_IP,socket.IP_ADD_MEMBERSHIP,socket.inet_aton(multicast_addr)+socket.inet_aton(Any))\n\nsock.setblocking(0)\nts=time.time()\nwhile 1:\n try:\n data,addr = sock.recvfrom(1024)\n except socket.error:\n pass\n else:\n print(\"Client 2 : Data Received from:\", addr)\n print(\"and the Received Data is: \",data)\n","sub_path":"Multicasting/multicastingclient2.py","file_name":"multicastingclient2.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"579473970","text":"import numpy as np\r\nfrom pyqmc import pbc, slateruhf\r\nfrom pyscf.pbc import scf\r\n\r\n\r\ndef get_supercell_kpts(supercell):\r\n Sinv = np.linalg.inv(supercell.S).T\r\n u = [0, 1]\r\n unit_box = np.stack([x.ravel() for x in np.meshgrid(*[u] * 3, indexing=\"ij\")]).T\r\n unit_box_ = np.dot(unit_box, supercell.S.T)\r\n xyz_range = np.stack([f(unit_box_, axis=0) for f in (np.amin, np.amax)]).T\r\n kptmesh = np.meshgrid(*[np.arange(*r) for r in xyz_range], indexing=\"ij\")\r\n possible_kpts = np.dot(np.stack([x.ravel() for x in kptmesh]).T, Sinv)\r\n in_unit_box = (possible_kpts >= 0) * (possible_kpts < 1 - 1e-12)\r\n select = np.where(np.all(in_unit_box, axis=1))[0]\r\n reclatvec = np.linalg.inv(supercell.original_cell.lattice_vectors()).T * 2 * np.pi\r\n kpts = np.dot(possible_kpts[select], reclatvec)\r\n return kpts\r\n\r\n\r\ndef get_supercell(cell, S):\r\n \"\"\"\r\n Inputs:\r\n cell: pyscf Cell object\r\n S: (3, 3) supercell matrix for QMC from cell defined by cell.a. In other words, the QMC calculation cell is qmc_cell = np.dot(S, cell.lattice_vectors()). For a 2x2x2 supercell, S is [[2, 0, 0], [0, 2, 0], [0, 0, 2]].\r\n \"\"\"\r\n from pyscf.pbc import gto\r\n\r\n def get_supercell_copies(latvec, S):\r\n Sinv = np.linalg.inv(S).T\r\n u = [0, 1]\r\n unit_box = np.stack([x.ravel() for x in np.meshgrid(*[u] * 3, indexing=\"ij\")]).T\r\n unit_box_ = np.dot(unit_box, S)\r\n xyz_range = np.stack([f(unit_box_, axis=0) for f in (np.amin, np.amax)]).T\r\n mesh = np.meshgrid(*[np.arange(*r) for r in xyz_range], indexing=\"ij\")\r\n possible_pts = np.dot(np.stack([x.ravel() for x in mesh]).T, Sinv.T)\r\n in_unit_box = (possible_pts >= 0) * (possible_pts < 1 - 1e-12)\r\n select = np.where(np.all(in_unit_box, axis=1))[0]\r\n pts = np.linalg.multi_dot((possible_pts[select], S, latvec))\r\n return pts\r\n\r\n scale = np.abs(int(np.round(np.linalg.det(S))))\r\n superlattice = np.dot(S, cell.lattice_vectors())\r\n Rpts = get_supercell_copies(cell.lattice_vectors(), S)\r\n atom = []\r\n for (name, xyz) in cell._atom:\r\n atom.extend([(name, xyz + R) for R in Rpts])\r\n supercell = gto.Cell()\r\n supercell.a = superlattice\r\n supercell.atom = atom\r\n supercell.ecp = cell.ecp\r\n supercell.basis = cell.basis\r\n supercell.exp_to_discard = cell.exp_to_discard\r\n supercell.unit = \"Bohr\"\r\n supercell.spin = cell.spin * scale\r\n supercell.build()\r\n supercell.original_cell = cell\r\n supercell.S = S\r\n supercell.scale = scale\r\n return supercell\r\n\r\n\r\nclass PySCFSlaterPBC:\r\n \"\"\"A wave function object has a state defined by a reference configuration of electrons.\r\n The functions recompute() and updateinternals() change the state of the object, and \r\n the rest compute and return values from that state. \"\"\"\r\n\r\n def __init__(self, supercell, mf, twist=None):\r\n \"\"\"\r\n Inputs:\r\n supercell: object returned by get_supercell(cell, S)\r\n mf: scf object of primitive cell calculation. scf calculation must include k points that fold onto the gamma point of the supercell\r\n twist: (3,) array, twisted boundary condition in fractional coordinates, i.e. as coefficients of the reciprocal lattice vectors of the supercell. Integer values are equivalent to zero.\r\n \"\"\"\r\n for attribute in [\"original_cell\", \"S\"]:\r\n if not hasattr(supercell, attribute):\r\n print('Warning: supercell is missing attribute \"%s\"' % attribute)\r\n print(\"setting original_cell=supercell and S=np.eye(3)\")\r\n supercell.original_cell = supercell\r\n supercell.S = np.eye(3)\r\n\r\n self.parameters = {}\r\n self.real_tol = 1e4\r\n\r\n self.supercell = supercell\r\n if twist is None:\r\n twist = np.zeros(3)\r\n else:\r\n twist = np.dot(np.linalg.inv(supercell.a), np.mod(twist, 1.0)) * 2 * np.pi\r\n self._kpts = get_supercell_kpts(supercell) + twist\r\n kdiffs = mf.kpts[np.newaxis] - self._kpts[:, np.newaxis]\r\n self.kinds = np.nonzero(np.linalg.norm(kdiffs, axis=-1) < 1e-12)[1]\r\n self.nk = len(self._kpts)\r\n print(\"nk\", self.nk, self.kinds)\r\n\r\n self._cell = supercell.original_cell\r\n\r\n self.parameters[\"mo_coeff_alpha\"] = []\r\n self.parameters[\"mo_coeff_beta\"] = []\r\n for kind in self.kinds:\r\n if len(mf.mo_coeff[0][0].shape) == 2:\r\n mca = mf.mo_coeff[0][kind][:, np.asarray(mf.mo_occ[0][kind] > 0.9)]\r\n mcb = mf.mo_coeff[1][kind][:, np.asarray(mf.mo_occ[1][kind] > 0.9)]\r\n else:\r\n mca = mf.mo_coeff[kind][:, np.asarray(mf.mo_occ[kind] > 0.9)]\r\n mcb = mf.mo_coeff[kind][:, np.asarray(mf.mo_occ[kind] > 1.1)]\r\n mca = np.real_if_close(mca, tol=self.real_tol)\r\n mcb = np.real_if_close(mcb, tol=self.real_tol)\r\n self.parameters[\"mo_coeff_alpha\"].append(mca / np.sqrt(self.nk))\r\n self.parameters[\"mo_coeff_beta\"].append(mcb / np.sqrt(self.nk))\r\n self._coefflookup = (\"mo_coeff_alpha\", \"mo_coeff_beta\")\r\n\r\n print(\"scf object is type\", type(mf))\r\n if isinstance(mf, scf.kuhf.KUHF):\r\n # Then indices are (spin, kpt, basis, mo)\r\n self._nelec = [int(np.sum([o[k] for k in self.kinds])) for o in mf.mo_occ]\r\n elif isinstance(mf, scf.khf.KRHF):\r\n # Then indices are (kpt, basis, mo)\r\n self._nelec = [\r\n int(np.sum([mf.mo_occ[k] > t for k in self.kinds])) for t in (0.9, 1.1)\r\n ]\r\n else:\r\n print(\"Warning: not expecting scf object of type\", type(mf))\r\n scale = self.supercell.scale\r\n self._nelec = [int(np.round(n * scale)) for n in self._cell.nelec]\r\n self._nelec = tuple(self._nelec)\r\n\r\n self.iscomplex = np.linalg.norm(self._kpts) > 1e-12\r\n for v in self.parameters.values():\r\n self.iscomplex = self.iscomplex or bool(sum(map(np.iscomplexobj, v)))\r\n print(\"iscomplex:\", self.iscomplex)\r\n if self.iscomplex:\r\n self.get_phase = lambda x: x / np.abs(x)\r\n self.get_wrapphase = lambda x: np.exp(1j * x)\r\n else:\r\n self.get_phase = np.sign\r\n self.get_wrapphase = lambda x: (-1) ** np.round(x / np.pi)\r\n\r\n def evaluate_orbitals(self, configs, mask=None, eval_str=\"PBCGTOval_sph\"):\r\n mycoords = configs.configs\r\n configswrap = configs.wrap\r\n if mask is not None:\r\n mycoords = mycoords[mask]\r\n configswrap = configswrap[mask]\r\n mycoords = mycoords.reshape((-1, mycoords.shape[-1]))\r\n # wrap supercell positions into primitive cell\r\n prim_coords, prim_wrap = pbc.enforce_pbc(self._cell.lattice_vectors(), mycoords)\r\n configswrap = configswrap.reshape(prim_wrap.shape)\r\n wrap = prim_wrap + np.dot(configswrap, self.supercell.S)\r\n kdotR = np.linalg.multi_dot(\r\n (self._kpts, self._cell.lattice_vectors().T, wrap.T)\r\n )\r\n wrap_phase = self.get_wrapphase(kdotR)\r\n # evaluate AOs for all electron positions\r\n ao = self._cell.eval_gto(eval_str, prim_coords, kpts=self._kpts)\r\n ao = [ao[k] * wrap_phase[k][:, np.newaxis] for k in range(self.nk)]\r\n return ao\r\n\r\n def recompute(self, configs):\r\n \"\"\"This computes the value from scratch. Returns the logarithm of the wave function as\r\n (phase,logdet). If the wf is real, phase will be +/- 1.\"\"\"\r\n nconf, nelec, ndim = configs.configs.shape\r\n aos = self.evaluate_orbitals(configs)\r\n aos = np.reshape(aos, (self.nk, nconf, nelec, -1))\r\n self._aovals = aos\r\n self._dets = []\r\n self._inverse = []\r\n for s in [0, 1]:\r\n mo = []\r\n i0, i1 = s * self._nelec[0], self._nelec[0] + s * self._nelec[1]\r\n for k in range(self.nk):\r\n mo_coeff = self.parameters[self._coefflookup[s]][k]\r\n mo.append(np.dot(aos[k, :, i0:i1], mo_coeff))\r\n ne = self._nelec[s]\r\n mo = np.concatenate(mo, axis=-1).reshape(nconf, ne, ne)\r\n phase, mag = np.linalg.slogdet(mo)\r\n self._dets.append((phase, mag))\r\n self._inverse.append(np.linalg.inv(mo))\r\n\r\n return self.value()\r\n\r\n def updateinternals(self, e, epos, mask=None):\r\n s = int(e >= self._nelec[0])\r\n if mask is None:\r\n mask = [True] * epos.configs.shape[0]\r\n eeff = e - s * self._nelec[0]\r\n aos = self.evaluate_orbitals(epos)\r\n self._aovals[:, :, e, :] = np.asarray(aos)\r\n mo = []\r\n for k in range(self.nk):\r\n mo_coeff = self.parameters[self._coefflookup[s]][k]\r\n mo.append(np.dot(aos[k], mo_coeff))\r\n ne = self._nelec[s]\r\n mo = np.concatenate(mo, axis=-1).reshape(len(mask), ne)\r\n ratio, self._inverse[s][mask, :, :] = slateruhf.sherman_morrison_row(\r\n eeff, self._inverse[s][mask, :, :], mo[mask, :]\r\n )\r\n self._updateval(ratio, s, mask)\r\n\r\n # identical to slateruhf\r\n def _updateval(self, ratio, s, mask):\r\n self._dets[s][0][mask] *= self.get_phase(ratio)\r\n self._dets[s][1][mask] += np.log(np.abs(ratio))\r\n\r\n ### not state-changing functions\r\n\r\n # identical to slateruhf\r\n def value(self):\r\n \"\"\"Return logarithm of the wave function as noted in recompute()\"\"\"\r\n return self._dets[0][0] * self._dets[1][0], self._dets[0][1] + self._dets[1][1]\r\n\r\n # identical to slateruhf\r\n def _testrow(self, e, vec, mask=None, spin=None):\r\n \"\"\"vec is a nconfig,nmo vector which replaces row e\"\"\"\r\n s = int(e >= self._nelec[0]) if spin is None else spin\r\n elec = e - s * self._nelec[0]\r\n if mask is None:\r\n return np.einsum(\"i...j,ij...->i...\", vec, self._inverse[s][:, :, elec])\r\n\r\n return np.einsum(\"i...j,ij...->i...\", vec, self._inverse[s][mask, :, elec])\r\n\r\n # identical to slateruhf\r\n def _testcol(self, i, s, vec):\r\n \"\"\"vec is a nconfig,nmo vector which replaces column i\"\"\"\r\n ratio = np.einsum(\"ij,ij->i\", vec, self._inverse[s][:, i, :])\r\n return ratio\r\n\r\n def testvalue(self, e, epos, mask=None):\r\n \"\"\" return the ratio between the current wave function and the wave function if \r\n electron e's position is replaced by epos\"\"\"\r\n s = int(e >= self._nelec[0])\r\n if mask is None:\r\n mask = [True] * epos.configs.shape[0]\r\n nmask = np.sum(mask)\r\n if nmask == 0:\r\n return np.zeros((0, epos.configs.shape[1]))\r\n aos = self.evaluate_orbitals(epos, mask)\r\n mo_coeff = self.parameters[self._coefflookup[s]]\r\n mo = [np.dot(aos[k], mo_coeff[k]) for k in range(self.nk)]\r\n mo = np.concatenate(mo, axis=-1)\r\n mo = mo.reshape(nmask, *epos.configs.shape[1:-1], self._nelec[s])\r\n return self._testrow(e, mo, mask)\r\n\r\n def testvalue_many(self, e, epos, mask=None):\r\n \"\"\" return the ratio between the current wave function and the wave function if \r\n an electron's position is replaced by epos for each electron\"\"\"\r\n s = (e >= self._nelec[0]).astype(int)\r\n if mask is None:\r\n mask = [True] * epos.configs.shape[0]\r\n nmask = np.sum(mask)\r\n if nmask == 0:\r\n return np.zeros((0, epos.configs.shape[1]))\r\n aos = self.evaluate_orbitals(epos, mask)\r\n\r\n ratios = np.zeros(\r\n (epos.configs.shape[0], e.shape[0]),\r\n dtype=complex if self.iscomplex else float,\r\n )\r\n for spin in [0, 1]:\r\n ind = s == spin\r\n mo_coeff = self.parameters[self._coefflookup[spin]]\r\n mo = [np.dot(aos[k], mo_coeff[k]) for k in range(self.nk)]\r\n mo = np.concatenate(mo, axis=-1)\r\n mo = mo.reshape(nmask, *epos.configs.shape[1:-1], self._nelec[spin])\r\n ratios[:, ind] = self._testrow(e[ind], mo, spin=spin)\r\n return ratios\r\n\r\n def gradient(self, e, epos):\r\n \"\"\" Compute the gradient of the log wave function \r\n Note that this can be called even if the internals have not been updated for electron e,\r\n if epos differs from the current position of electron e.\"\"\"\r\n s = int(e >= self._nelec[0])\r\n aograd = self.evaluate_orbitals(epos, eval_str=\"PBCGTOval_sph_deriv1\")\r\n mo_coeff = self.parameters[self._coefflookup[s]]\r\n mograd = [ak.dot(mo_coeff[k]) for k, ak in enumerate(aograd)]\r\n mograd = np.concatenate(mograd, axis=-1)\r\n ratios = np.asarray([self._testrow(e, x) for x in mograd])\r\n return ratios[1:] / ratios[:1]\r\n\r\n def laplacian(self, e, epos):\r\n s = int(e >= self._nelec[0])\r\n ao = self.evaluate_orbitals(epos, eval_str=\"PBCGTOval_sph_deriv2\")\r\n mo_coeff = self.parameters[self._coefflookup[s]]\r\n mo = [\r\n np.dot([ak[0], ak[[4, 7, 9]].sum(axis=0)], mo_coeff[k])\r\n for k, ak in enumerate(ao)\r\n ]\r\n mo = np.concatenate(mo, axis=-1)\r\n ratios = self._testrow(e, mo[1])\r\n testvalue = self._testrow(e, mo[0])\r\n return ratios / testvalue\r\n\r\n def gradient_laplacian(self, e, epos):\r\n s = int(e >= self._nelec[0])\r\n ao = self.evaluate_orbitals(epos, eval_str=\"PBCGTOval_sph_deriv2\")\r\n mo = [\r\n np.dot(\r\n np.concatenate([ak[0:4], ak[[4, 7, 9]].sum(axis=0, keepdims=True)]),\r\n self.parameters[self._coefflookup[s]][k],\r\n )\r\n for k, ak in enumerate(ao)\r\n ]\r\n mo = np.concatenate(mo, axis=-1)\r\n ratios = np.asarray([self._testrow(e, x) for x in mo])\r\n return ratios[1:-1] / ratios[:1], ratios[-1] / ratios[0]\r\n\r\n def pgradient(self):\r\n d = {}\r\n # for parm in self.parameters:\r\n # s = int(\"beta\" in parm)\r\n # # Get AOs for our spin channel only\r\n # i0, i1 = s * self._nelec[0], self._nelec[0] + s * self._nelec[1]\r\n # ao = self._aovals[:, :, i0:i1] # (kpt, config, electron, ao)\r\n # pgrad_shape = (ao.shape[1],) + self.parameters[parm].shape\r\n # pgrad = np.zeros(pgrad_shape)\r\n # # Compute derivatives w.r.t. MO coefficients\r\n # for k in range(self.nk):\r\n # for i in range(self._nelec[s]):\r\n # for j in range(ao.shape[2]):\r\n # pgrad[:, k, j, i] = self._testcol(i, s, ao[k, :, :, j])\r\n # d[parm] = np.array(pgrad)\r\n return d\r\n\r\n def plot_orbitals(self, mf, norb, spin_channel=0, basename=\"\", nx=80, ny=80, nz=80):\r\n from pyqmc.coord import PeriodicConfigs\r\n\r\n grid = np.meshgrid(*[np.arange(n) / n for n in [nx, ny, nz]], indexing=\"ij\")\r\n grid = np.stack([g.ravel() for g in grid]).T\r\n grid = np.linalg.dot(grid, self.supercell.lattice_vectors())\r\n configs = PeriodicConfigs(\r\n grid.reshape((-1, 16, 3)), self._cell.lattice_vectors()\r\n )\r\n nconf, nelec, ndim = configs.configs.shape\r\n ao = self.evaluate_orbitals(configs)\r\n\r\n mo_coeff = np.asarray(mf.mo_coeff)\r\n coeff = []\r\n for kind in self.kinds:\r\n if len(mf.mo_coeff[0][0].shape) == 2:\r\n mca = mo_coeff[spin_channel][kind][:, :norb]\r\n else:\r\n mca = mf.mo_coeff[kind][:, :norb]\r\n mca = np.real_if_close(mca, tol=self.real_tol)\r\n coeff.append(mca)\r\n\r\n mo = []\r\n nsorb = int(np.round(np.linalg.det(self.S) * norb))\r\n for k in range(self.nk):\r\n mo.append(np.dot(ao[k], coeff[k]))\r\n mo = np.concatenate(mo, axis=-1).reshape(-1, nsorb)\r\n\r\n for i in range(nsorb):\r\n fname = basename + \"mo{0}.cube\".format(i)\r\n print(\"writing\", fname, mo[..., i].shape)\r\n self.generate_cube(fname, mo[..., i], nx, ny, nz)\r\n\r\n def generate_cube(self, fname, vals, nx, ny, nz, comment=\"HEADER LINE\\n\"):\r\n import cubetools\r\n\r\n cube = {}\r\n cube[\"comment\"] = comment\r\n cube[\"type\"] = \"\\n\"\r\n cube[\"natoms\"] = self.supercell.natm\r\n cube[\"origin\"] = np.zeros(3)\r\n cube[\"ints\"] = np.array([nx, ny, nz])\r\n cube[\"latvec\"] = self.supercell.lattice_vectors()\r\n cube[\"latvec\"] = cube[\"latvec\"] / cube[\"ints\"][:, np.newaxis]\r\n cube[\"atomname\"] = self.supercell.atom_charges()\r\n cube[\"atomxyz\"] = self.supercell.atom_coords()\r\n cube[\"data\"] = np.reshape(vals, (nx, ny, nz))\r\n with open(fname, \"w\") as f:\r\n cubetools.write_cube(cube, f)\r\n\r\n\r\ndef generate_test_inputs():\r\n import pyqmc\r\n from pyqmc.coord import PeriodicConfigs\r\n from pyscf.pbc import gto, scf\r\n from pyscf.pbc.dft.multigrid import multigrid\r\n from pyscf.pbc import tools\r\n from pyscf import lib\r\n\r\n from_chkfile = True\r\n\r\n if from_chkfile:\r\n\r\n def loadchkfile(chkfile):\r\n cell = gto.cell.loads(lib.chkfile.load(chkfile, \"mol\"))\r\n kpts = cell.make_kpts([1, 1, 1])\r\n mf = scf.KRKS(cell, kpts)\r\n mf.__dict__.update(lib.chkfile.load(chkfile, \"scf\"))\r\n return cell, mf\r\n\r\n cell1, mf1 = loadchkfile(\"mf1.chkfile\")\r\n cell2, mf2 = loadchkfile(\"mf2.chkfile\")\r\n else:\r\n L = 4\r\n cell2 = gto.M(\r\n atom=\"\"\"H {0} {0} {0} \r\n H {1} {1} {1}\"\"\".format(\r\n 0.0, L * 0.25\r\n ),\r\n basis=\"sto-3g\",\r\n a=np.eye(3) * L,\r\n spin=0,\r\n unit=\"bohr\",\r\n )\r\n\r\n print(\"Primitive cell\")\r\n kpts = cell2.make_kpts((2, 2, 2))\r\n mf2 = scf.KRKS(cell2, kpts)\r\n mf2.xc = \"pbe\"\r\n mf2.chkfile = \"mf2.chkfile\"\r\n mf2 = mf2.run()\r\n\r\n print(\"Supercell\")\r\n cell1 = tools.super_cell(cell2, [2, 2, 2])\r\n kpts = [[0, 0, 0]]\r\n mf1 = scf.KRKS(cell1, kpts)\r\n mf1.xc = \"pbe\"\r\n mf1.chkfile = \"mf1.chkfile\"\r\n mf1 = mf1.run()\r\n\r\n # wf1 = pyqmc.PySCFSlaterUHF(cell1, mf1)\r\n wf1 = PySCFSlaterPBC(cell1, mf1, supercell=1 * np.eye(3))\r\n wf2 = PySCFSlaterPBC(cell2, mf2, supercell=2 * np.eye(3))\r\n\r\n configs = pyqmc.initial_guess(cell1, 10, 0.1)\r\n\r\n return wf1, wf2, configs\r\n\r\n\r\ndef test_recompute(wf1, wf2, configs):\r\n p1, m1 = wf1.recompute(configs)\r\n p2, m2 = wf2.recompute(configs)\r\n\r\n print(\"phase\")\r\n print(\"p1\", p1)\r\n print(\"p2\", p2)\r\n print(\"p1/p2\", p1 / p2)\r\n print(\"log magnitude\")\r\n print(\"m1\", m1)\r\n print(\"m2\", m2)\r\n print(\"m1-m2\", m1 - m2)\r\n\r\n p_err = np.linalg.norm(p1 / p2 - p1[0] / p2[0])\r\n m_err = np.linalg.norm(m1 - m2 - m1[0] + m2[0])\r\n assert p_err < 1e-10, (p_err, m_err)\r\n assert m_err < 1e-1, (p_err, m_err)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n from pyqmc.testwf import (\r\n test_updateinternals,\r\n test_wf_gradient,\r\n test_wf_laplacian,\r\n test_wf_gradient_laplacian,\r\n )\r\n\r\n wf1, wf2, configs = generate_test_inputs()\r\n test_recompute(wf1, wf2, configs)\r\n test_updateinternals(wf1, configs)\r\n test_updateinternals(wf2, configs)\r\n test_wf_gradient(wf1, configs)\r\n test_wf_gradient(wf2, configs)\r\n test_wf_laplacian(wf1, configs)\r\n test_wf_laplacian(wf2, configs)\r\n test_wf_gradient_laplacian(wf1, configs)\r\n test_wf_gradient_laplacian(wf2, configs)\r\n","sub_path":"pyqmc/slaterpbc.py","file_name":"slaterpbc.py","file_ext":"py","file_size_in_byte":19484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"177600936","text":"from django.urls import path\nfrom django.contrib.auth.decorators import login_required\n\n\nfrom . import views\n\napp_name = 'movies'\nurlpatterns = [\n path('', login_required(views.index), name='index'),\n path('search_movie/', views.search_movie, name=\"search_movie\"),\n path('/add_favorite/',\n views.add_favorite, name=\"add_favorite\"),\n path('/remove_favorite/',\n views.remove_favorite, name=\"remove_favorite\")\n]\n","sub_path":"mysite/movies/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"614552365","text":"# 2014\n# SAVI McGill: Heming Wen, Prabhat Tiwary, Kevin Han, Michael Smith,\n# Mike Kobierski and Hoai Phuoc Truong\n#\n\nimport json\nimport logging\nimport os\nfrom pprint import pformat\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef get_json_files():\n provision_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'json')\n paths = os.listdir(provision_dir)\n result = []\n for fname in paths:\n if fname.endswith(\".json\"):\n result.append(os.path.join(provision_dir, fname))\n return result\n\ndef update_reply_queue(reply_queue):\n flist = get_json_files()\n for fname in flist:\n with open(fname, 'r') as CONFIG_FILE:\n config = json.load(CONFIG_FILE)\n config['rabbitmq_reply_queue'] = reply_queue\n with open(fname, 'w') as CONFIG_FILE:\n json.dump(config, CONFIG_FILE, indent=4) \n\ndef update_last_known_config(ap, config):\n flist = get_json_files()\n ap_config_name = None\n for fname in flist:\n F = open(fname, 'r')\n prev_config = json.load(F)\n if prev_config['queue'] == ap:\n ap_config_name = F.name\n break\n try:\n LOGGER.debug(F)\n except UnboundLocalError:\n LOGGER.warn(\"WARNING: No accessible files in ap_provision\")\n F.close()\n del F\n prev_config['last_known_config'] = config\n config = prev_config\n #LOGGER.debug(json.dumps(config, indent=4))\n with open(ap_config_name, 'w') as F:\n json.dump(config, F, indent=4)\n LOGGER.info(\"Provision config updated for %s\", ap)","sub_path":"aurora/aurora/ap_provision/writer.py","file_name":"writer.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"468737875","text":"from flask import make_response, jsonify\nfrom flask_restful import Resource, reqparse\nfrom backendflask.adapters.memoryrepository import MemoryRepository\nfrom backendflask.adapters.gcloudrepository import GCloudRepository\nfrom backendflask.domain_models.user import User\nfrom backendflask.domain_models.movie import Movie\nfrom backendflask.domain_models.user import User\nimport json\n\n# DB Connection\ndb = MemoryRepository()\n#db = GCloudRepository()\n\n# Request Parser\nparser = reqparse.RequestParser()\n\nparser.add_argument('personID')\nparser.add_argument('firstName')\nparser.add_argument('lastName')\nparser.add_argument('gender')\nparser.add_argument('emailAddress')\nparser.add_argument('password')\nparser.add_argument('phoneNumber')\nparser.add_argument('watchlist')\nparser.add_argument('watchedMovies')\nparser.add_argument('users')\n\n\nclass User(Resource):\n def get(self, emailAddress: str) -> str:\n user = db.get_user(email_address=emailAddress)\n response = {\n \"successful\": True if user else False,\n \"user\": user.toJSON(),\n }\n if response['successful']:\n return make_response(jsonify(response), 200)\n else:\n return make_response(jsonify(response), 404)\n\n def put(self, personID: str) -> str:\n args = parser.parse_args()\n response = {\n \"successful\": False,\n \"personID\": args['personID'],\n \"firstName\": args['firstName'],\n \"lastName\": args['lastName'],\n \"gender\": args['gender'],\n \"emailAddress\": args['emailAddress'],\n \"password\": args['password'],\n \"phoneNumber\": args['phoneNumber'],\n \"watchlist\": args['watchlist'],\n \"watchedMovies\": args['watchedMovies'],\n \"reviews\": args['reviews'],\n }\n response['successful'] = True if db.update_user(\n User(\n personID=args['personID'],\n firstName=args['firstName'],\n lastName=args['lastName'],\n gender=args['gender'],\n emailAddress=args['emailAddress'],\n password=args['password'],\n phoneNumber=args['phoneNumber'],\n watchlist=[Movie(title=movie.movieTitle)\n for movie in args['watchlist']],\n watchedMovies=[Movie(title=movie.movieTitle)\n for movie in args['watchedMovies']],\n reviews=args['reviews'],\n )\n ) else False\n if response['successful']:\n return make_response(jsonify(response), 201)\n else:\n return make_response(jsonify(response), 400)\n\n def delete(self, personID: str) -> str:\n response = {\n \"successful\": False,\n }\n print(personID, db)\n response['successful'] = True if db.delete_user(\n personID=personID) else False\n print(response['successful'])\n if response['successful']:\n return make_response(jsonify(response), 200)\n else:\n return make_response(jsonify(response), 404)\n","sub_path":"backendflask/api/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":3128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"56328738","text":"#!/usr/bin/python3\n__author__ = 'Aidan'\nfrom sys import argv, stderr\nfrom shutil import copyfile as cp\nfrom os.path import isfile\nfrom py_compile import compile as cpl\n\nclass MainClass:\n def load(self):\n if len(argv)==2 and isfile(argv[1]) and argv[1].split('.')[-1]=='py':self.pyf=argv[1]\n else:\n stderr.write('Only takes one .py file.')\n exit(1)\n return self\n\n def run(self):\n a=cpl(self.pyf)\n a=cp(a,a.replace('__pycache__\\\\', '').replace('.cpython-36',''))\n print(a)\n return input()\n\ndef main():\n global dud; dud=MainClass().load()\n return dud.run()\n\nmain();exit()\n","sub_path":"Little Python Utilities/cpl.py","file_name":"cpl.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"298333414","text":"from django.urls import path\r\n\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n\r\n\t\tpath('register/', views.registerPage, name='register'),\r\n\t\tpath('login/', views.loginPage, name='login'),\r\n\t\tpath('logout/', views.logoutUser, name='logout'),\r\n\r\n\tpath('', views.home, name = 'home'),\r\n\tpath('about/', views.about, name = 'about'),\r\n\tpath('menu/', views.menu, name = 'menu'),\r\n\tpath('contact/', views.contact, name = 'contact'),\r\n\tpath('blog/', views.blog, name = 'blog'),\r\n\tpath('reservation/', views.reservation, name = 'reservation'),\r\n\r\n\tpath('checkout/', views.checkout, name = 'checkout'),\r\n\tpath('complete/', views.paymentcomplete, name = 'complete'),\r\n\r\n]","sub_path":"aromagrill/management/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"362861745","text":"# encoding: utf-8\n\nfrom __future__ import unicode_literals\n\nimport re\nimport hashlib\n\nfrom marrow.util.compat import binary, unicode, native, bytestring\nfrom marrow.util.object import NoDefault\n\nfrom marrow.wsgi.objects.adapters.base import *\n\n\n__all__ = ['ContentLength', 'ContentMD5', 'ContentType', 'Charset']\n\nCHARSET_RE = re.compile(r';\\s*charset=([^;]*)', re.I)\n\n\n\nclass ContentLength(Int):\n def default(self, obj):\n if isinstance(obj.body, binary):\n return len(obj.body)\n \n if isinstance(obj.body, unicode):\n return len(obj.body.encode(obj.encoding))\n \n return -1\n\n\nclass ContentMD5(ReaderWriter):\n def default(self, obj):\n if isinstance(obj.body, binary):\n return hashlib.md5(obj.body).hexdigest()\n\n if isinstance(obj.body, unicode):\n return hashlib.md5(obj.body.encode(obj.encoding)).hexdigest()\n\n return None\n\n\nclass ContentType(ReaderWriter):\n \"\"\"Access the content type, ignoring extended parameters.\n \n If you leave parameters off when assigning a value then existing parameters will be preserved.\n \"\"\"\n \n default = b''\n \n def __get__(self, obj, cls, strip=True):\n value = native(super(ContentType, self).__get__(obj, cls))\n if not value: return None\n return bytestring(value.split(';', 1)[0] if strip else value)\n \n def __set__(self, obj, value):\n value = native(value) if value is not None else ''\n \n if ';' not in value:\n original = native(super(ContentType, self).__get__(obj, None), 'ascii')\n if ';' in original:\n value += ';' + original.split(';', 1)[1]\n \n super(ContentType, self).__set__(obj, bytestring(value, 'ascii'))\n\n\nclass Charset(ReaderWriter):\n \"\"\"Get the charset of the request.\n\n If the request was sent with a charset parameter on the\n Content-Type, that will be used. Otherwise if there is a\n default charset (set during construction, or as a class\n attribute) that will be returned. Otherwise None.\n\n Setting this property after request instantiation will always\n update Content-Type. Deleting the property updates the\n Content-Type to remove any charset parameter (if none exists,\n then deleting the property will do nothing, and there will be\n no error).\n \"\"\"\n \n default = '; charset=\"utf8\"'\n \n def __get__(self, obj, cls):\n content_type = super(Charset, self).__get__(obj, cls)\n if not content_type: return None\n \n charset_match = CHARSET_RE.search(native(content_type, 'ascii'))\n \n if charset_match:\n result = charset_match.group(1).strip('\"').strip()\n return result\n \n return None\n \n def __set__(self, obj, value):\n if not value:\n self.__delete__(obj)\n return\n \n value = native(value)\n content_type = native(super(Charset, self).__get__(obj, None), 'ascii')\n charset_match = CHARSET_RE.search(content_type) if content_type else None\n \n if charset_match:\n content_type = content_type[:charset_match.start(1)] + value + content_type[charset_match.end(1):]\n \n # TODO: Examine what action browsers take.\n # elif ';' in content_type:\n # content_type += ', charset=\"%s\"' % charset\n \n elif content_type:\n content_type += '; charset=\"' + value + '\"'\n \n else:\n content_type = '; charset=\"' + value + '\"'\n \n super(Charset, self).__set__(obj, bytestring(content_type, 'ascii'))\n \n def __delete__(self, obj):\n content_type = CHARSET_RE.sub('', super(Charset, self).__get__(obj, None))\n new_content_type = new_content_type.rstrip().rstrip(';').rstrip(',')\n super(Charset, self).__set__(obj, new_content_type)\n","sub_path":"marrow/wsgi/objects/adapters/content.py","file_name":"content.py","file_ext":"py","file_size_in_byte":3901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"288201380","text":"\"\"\"\nSo, what should be te application interface ...\ninstead of creating a standalone script, i will create separate a class such that\nthe updates can be accessed via a generator ..\n\"\"\"\n\n\nimport numpy as np\n\n\nclass MultiLinearRegression(object):\n iter_count = 0\n\n def __init__(self, inputs, output):\n \"\"\"\n The inputs is supplied such that each column is a complete input vector\n \"\"\"\n assert isinstance(inputs, np.ndarray) and isinstance(output, np.ndarray), \"Please supply Numpy arrays as input arguments\"\n assert inputs.shape[1] == len(output), \"Number of output examples should be equal to number of input examples\"\n self._complexity = 1\n self.output_m = output.reshape(len(output), 1)\n self.input_m = np.vstack( (np.ones_like(self.output_m).transpose(), inputs) )\n self.weights = np.zeros(self.input_m.shape[0]).reshape(self.input_m.shape[0], 1)\n self.n_examples = float(len(output))\n self.n_core_features = self.input_m.shape[0] ## number of rows are number of features + x 0th included\n\n self.epsilon = 0.1\n self.ita = 10\n self.updates = np.ones(self.input_m.shape[0]).reshape(self.input_m.shape[0], 1)*10\n\n self.alpha = 0.8\n self.old_updates = np.zeros(self.input_m.shape[0]).reshape(self.input_m.shape[0], 1)\n\n @property\n def converged(self):\n #print 'complecity inner -->> ', self.complexity\n #print 'iter -->> ', self.iter_count\n self.iter_count += 1\n #print self.iter_count , '\\r'\n mod_g_RSS = float(self.updates.transpose().dot(self.updates))\n #print\n if mod_g_RSS < self.epsilon:\n #print \"regression coverged\\nSolution found\"\n #print self.weights\n return True\n else:\n return False\n\n @converged.setter\n def converged(self, value):\n raise RuntimeError(\"This is a read-only variable\")\n\n @property\n def complexity(self):\n return self._complexity\n\n @complexity.setter\n def complexity(self, cp):\n assert cp > 0 and cp < 5, \"Values allowed between 1 to 5 only\\n\"\n if cp > 1 and self.input_m.shape[0] > 2:\n raise NotImplementedError(\"Not implemented to handle high complexity for multi-dimentional models\")\n self._complexity = cp\n if self.input_m.shape[0] == cp+1:\n return\n self.input_m = self.input_m[:self.n_core_features, :]\n for i in range(2, self._complexity + 1):\n self.input_m = np.vstack((self.input_m, np.power(self.input_m[1, :], i)))\n self.weights = np.zeros(self.input_m.shape[0]).reshape(self.input_m.shape[0], 1)\n self.updates = np.ones(self.input_m.shape[0]).reshape(self.input_m.shape[0], 1) * 10\n self.old_updates = np.zeros(self.input_m.shape[0]).reshape(self.input_m.shape[0], 1)\n\n def create_model(self):\n pass\n\n def _yhat(self):\n return self.input_m.transpose().dot(self.weights)\n\n def __minus_gradient_RSS(self):\n return self.input_m.dot( self.output_m - self._yhat()) * 2.0\n\n def training_error(self):\n z = self.output_m - self._yhat()\n return (z.transpose().dot(z))/self.n_examples\n\n def _next_weight_update(self):\n if not self.converged:\n updates = self.__minus_gradient_RSS()/self.n_examples ## mean squared error cost function\n self.updates = updates\n return True\n else:\n return False\n\n def update_weights(self):\n while self._next_weight_update():\n update = (self.ita * self.updates) + self.alpha*self.old_updates\n self.old_updates = update\n self.weights += update\n if np.any(np.isnan(self.weights)):\n #print 'reset -------------------------------------------'\n self.__reset()\n yield self.weights\n else:\n raise StopIteration\n\n def __reset(self):\n self.weights = np.zeros_like(self.weights)\n self.updates = np.ones_like(self.updates)\n self.old_updates = self.updates.copy()\n self.ita *= 0.6\n\n\"\"\"\ndef test_regression():\n import threading\n import random\n import timeit\n from matplotlib import pyplot\n r_coff = lambda x: random.randint(0, x) + random.random()\n POINTS = 500\n x = np.linspace(0, 10, POINTS)\n x = x.reshape(POINTS, 1)\n y = -x * 10 + np.sin(2 * np.pi * (x) / np.random.randint(10, 30)) * (400 + r_coff(200)) + np.power(x, 2) * 1 + 3000 + np.abs(np.random.randn(POINTS).reshape(POINTS, 1)) * (1000)\n m = MultiLinearRegression(x.T, y)\n m.complexity = 2\n\n for i in m.update_weights():\n pass\n\n print \"Total Iterations -- \", m.iter_count\n print 'Ita -- ', m.ita\n\n pyplot.figure(1)\n\n yh = m._yhat()\n pyplot.plot(x, y, '.r', x, yh, 'g-')\n\n\nif __name__ == \"__main__\":\n import timeit\n time = timeit.timeit('test_regression()', 'from MultipleLinearRegression import test_regression',number=1)\n print \"Time -- \", time\n pyplot.show()\n\n\"\"\"\n\n","sub_path":"MultipleLinearRegression.py","file_name":"MultipleLinearRegression.py","file_ext":"py","file_size_in_byte":5051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"566893254","text":"import numpy as np\nimport pandas as pd\nfrom numba import jit\nimport matplotlib.pyplot as plt\nimport time\nimport os\nfrom matplotlib.pyplot import figure\n\n\n# 164 choices\ncmaps = [\"Accent\", \"Blues\", \"BrBG\", \"BuGn\", \"BuPu\", \"CMRmap\", \"Dark2\", \"GnBu\", \"Greens\", \"Greys\", \"OrRd\", \"Oranges\", \"PRGn\", \"Paired\", \"Pastel1\", \"Pastel2\", \"PiYG\", \"PuBu\", \"PuBuGn\", \"PuOr\", \"PuRd\", \"Purples\", \"RdBu\", \"RdGy\", \"RdPu\", \"RdYlBu\", \"RdYlGn\", \"Reds\", \"Set1\", \"Set2\", \"Set3\", \"Spectral\", \"Wistia\", \"YlGn\", \"YlGnBu\", \"YlOrBr\", \"YlOrRd\", \"afmhot\", \"autumn\", \"binary\", \"bone\", \"brg\", \"bwr\", \"cividis\",\n \"cool\", \"coolwarm\", \"copper\", \"cubehelix\", \"flag\", \"gist_earth\", \"gist_gray\", \"gist_heat\", \"gist_ncar\", \"gist_rainbow\", \"gist_stern\", \"gist_yarg\", \"gnuplot\", \"gnuplot2\", \"gray\", \"hot\", \"hsv\", \"inferno\", \"jet\", \"magma\", \"nipy_spectral\", \"ocean\", \"pink\", \"plasma\", \"prism\", \"rainbow\", \"seismic\", \"spring\", \"summer\", \"tab10\", \"tab20\", \"tab20b\", \"tab20c\", \"terrain\", \"twilight\", \"twilight_shifted\", \"viridis\", \"winter\"]\n\ncmaps_r = [\"Accent_r\", \"Blues_r\", \"BrBG_r\", \"BuGn_r\", \"BuPu_r\", \"CMRmap_r\", \"Dark2_r\", \"GnBu_r\", \"Greens_r\", \"Greys_r\", \"OrRd_r\", \"Oranges_r\", \"PRGn_r\", \"Paired_r\", \"Pastel1_r\", \"Pastel2_r\", \"PiYG_r\", \"PuBu_r\", \"PuBuGn_r\", \"PuOr_r\", \"PuRd_r\", \"Purples_r\", \"RdBu_r\", \"RdGy_r\", \"RdPu_r\", \"RdYlBu_r\", \"RdYlGn_r\", \"Reds_r\", \"Set1_r\", \"Set2_r\", \"Set3_r\", \"Spectral_r\", \"Wistia_r\", \"YlGnBu_r\", \"YlGn_r\", \"YlOrBr_r\", \"YlOrRd_r\", \"afmhot_r\", \"autumn_r\", \"binary_r\", \"bone_r\", \"brg_r\", \"bwr_r\", \"cividis_r\",\n \"cool_r\", \"coolwarm_r\", \"copper_r\", \"cubehelix_r\", \"flag_r\", \"gist_earth_r\", \"gist_gray_r\", \"gist_heat_r\", \"gist_ncar_r\", \"gist_rainbow_r\", \"gist_stern_r\", \"gist_yarg_r\", \"gnuplot2_r\", \"gnuplot_r\", \"gray_r\", \"hot_r\", \"hsv_r\", \"inferno_r\", \"jet_r\", \"magma_r\", \"nipy_spectral_r\", \"ocean_r\", \"pink_r\", \"plasma_r\", \"prism_r\", \"rainbow_r\", \"seismic_r\", \"spring_r\", \"summer_r\", \"tab10_r\", \"tab20_r\", \"tab20b_r\", \"tab20c_r\", \"terrain_r\", \"twilight_r\", \"twilight_shifted_r\", \"viridis_r\", \"winter_r\"]\n\nresolutions = [[1280, 720], [1920, 1080], [2560, 1440], [4096, 2160]]\n\nprint(\"Résolutions proposées: \\n\\t1280x720 \\n\\t1920x1080 \\n\\t2560x1440 \\n\\t4096x2160\")\n\nprint(\"1: Choisir le nombre de fractales à générer (ou '*' pour générer le maximum)\")\nprint(\"2: Choisir la résolution ('*' pour choisir toutes les résolutions, un chiffre entre 1 et 4, 'choice' pour choisir la résolution parmis celles proposées ou 'edit' pour une résolution personnalisée)\")\nprint(\"\\tSi un chiffre est saisie, ce seront les permières résolutions qui seront générées. \\n\\tSi 'choice' est choisie, entrer le chiffre correspondant à la résolution. \\n\\tSi 'edit' est choisi, entrer la hauteur et la largeur de l'image.\")\nprint(\"3: Si la génération doit inclure l'inversion des couleurs en plus des couleurs normales saisir yes, sinon saisir autre chose.\")\n\nchoice_fractals = input(\"How many fractals? \")\nchoice_fractals = len(cmaps) if choice_fractals == \"*\" else choice_fractals\n\nres = input(\"How many resolutions? \")\n\n\nif res == \"*\":\n res = len(resolutions)\nelif res == \"edit\":\n own_width = int(input(\"Width: \"))\n own_height = int(input(\"Height: \"))\nelif res == \"choice\":\n choice_res = int(input(\n \"Which resolution (1: 1280x720; 2: 1920x1080; 3: 2560x1440; 4: 4096x2160)? \"))\n own_width = resolutions[choice_res-1][0]\n own_height = resolutions[choice_res-1][1]\nelse:\n if int(res) > len(resolutions):\n res = len(res)\n else:\n res = res\n\ncolormap = input(\"With reverse or not? \")\ncmaps += cmaps_r if colormap == \"yes\" else cmaps\n\n\ndef check_directory(width, height):\n if not os.path.isdir(\"images\"):\n os.makedirs(\"images\")\n if not os.path.isdir(\"images/{0}x{1}\".format(width, height)):\n os.makedirs(\"images/{0}x{1}\".format(width, height))\n\n\n@jit\ndef i_iteration(c, iteration_max):\n z = complex(0, 0)\n i = 0\n while(abs(z) < 2 and i < iteration_max):\n z = z**2 + c\n i += 1\n return i\n\n\ndef mandelbrot(height, width, iteration_max, cmap='magma'):\n check_directory(width, height)\n imaginary_start = -1\n imaginary_end = 1\n real_start = -2\n real_end = 1\n set = np.zeros((width, height))\n for h, im in enumerate(np.linspace(imaginary_start, imaginary_end, height)):\n for w, re in enumerate(np.linspace(real_start, real_end, width)):\n set[w, h] = i_iteration(complex(re, im), iteration_max)\n filename = \"images/{0}x{1}/{2}_mandlebrot_{3}.png\".format(\n width, height, iteration_max, cmap, )\n plt.imsave(filename, set.T, format=\"png\", cmap=cmap)\n return filename\n\n\ndef main():\n start_script = time.time()\n\n if res == \"edit\" or res == \"choice\":\n ran = 1\n else:\n ran = int(res)\n\n for r in range(ran):\n for i in range(int(choice_fractals)):\n start = time.time()\n figure(dpi=600)\n if res == \"edit\" or res == \"choice\":\n width = own_width\n else:\n width = resolutions[r][0]\n\n if res == \"edit\" or res == \"choice\":\n height = own_height\n else:\n height = resolutions[r][1]\n iteration_max = 100\n cmap = cmaps[i]\n print(\n \"Generating the fractal number {0} with the {1} color map in {2}x{3} resolution.\".format(i, cmap, width, height))\n filename = mandelbrot(height, width, iteration_max, cmap=cmap)\n end = time.time()\n print(f\"{filename} saved in time: {end-start}\")\n print(\"\")\n\n end_script = time.time()\n time_diff = round(end_script-start_script)\n\n if res == \"edit\" or res == \"choice\":\n prt = 1\n else:\n prt = int(res)\n\n print(\"{0} fractals generated in {1}sec.\".format(\n int(choice_fractals)*prt, time_diff))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"mandelbrot_colored.py","file_name":"mandelbrot_colored.py","file_ext":"py","file_size_in_byte":5865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"249733227","text":"\"\"\"\ncreated by Nagaj at 16/05/2021\n\"\"\"\n\n\nclass User:\n def __init__(self, userid, username):\n self.username = username\n self.userid = userid\n self.followers = []\n self.following = []\n print(f\"new user {self} created ..\")\n\n def follow(self, user):\n if self != user and user not in self.following:\n self.following.append(user)\n user.followers.append(self)\n\n def unfollow(self, user):\n if self != user and user in self.following:\n self.following.remove(user)\n user.followers.remove(self)\n\n def __str__(self):\n return self.username\n\n def __repr__(self):\n return self.username\n\n\nuser_1 = User(\"001\", \"john\")\nuser_2 = User(\"002\", \"james\")\nuser_3 = User(\"003\", \"leon\")\nuser_4 = User(\"004\", \"jack\")\n\nprint(user_1.followers)\nprint(user_2.followers)\nprint(user_3.followers)\n\nuser_1.follow(user_2)\nuser_1.follow(user_2)\nuser_1.follow(user_3)\nuser_1.follow(user_1)\nuser_1.follow(user_4)\n\nprint(user_1.following)\n\nprint(user_2.followers)\nprint(user_3.followers)\nprint(user_4.followers)\n\nuser_1.unfollow(user_2)\n\nprint(user_1.following)\nprint(user_2.followers)\nprint(user_3.followers)\n\nuser_1.unfollow(user_3)\nprint(user_3.followers)\n# user_1.id = \"001\"\n# user_1.username = \"john\"\n# user_1.email = \"john@test.com\"\n# print(user_1)\n#\n# print(\"ID\", user_1.id)\n# print(\"username\", user_1.username)\n# print(\"Email\", user_1.email)\n#\n# print(\"#\" * 100)\n# user_2.id = \"002\"\n# user_2.username = \"james\"\n# user_2.email = \"james@test.com\"\n# print(user_2.username)\n#\n# print(\"#\" * 100)\n#\n# user_3.id = \"003\"\n# user_3.username = \"leon\"\n# user_3.email = \"lean@test.com\"\n# print(user_3.username)\n","sub_path":"day_17/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"210268204","text":"\"\"\"\nmethod 2:\nusing a new sequence to track the smallest number of LSI for a given length i\ng[i] means for any LISs of length i - 1, g[i] represents the index of smallest ending number of that LIS sequence in the original input array. \nto maintain g:\nFind **first** number in g so that nums[g[j]] > nums[i], then replace j with i. If such number does not exist, append j at the end of g\ni.e. always maintaining an ascending sorted array when inserting, instead of strictly inserting.\n 1) instead of inserting number, it is inserting index of the number in the original array\n 2) instead of inserting a smaller number, it is overwriting the next bigger number in g\n 3) if it is bigger than all the numbers in g, it appends at the end\n=>\n2) will ensure for a given lengh i, g[i] is the smallest number.\nthis array's final length is equal to the length of the longest increasing subsequence\n\nthis will result in a strictly sorted array of increasing value but recorded in their indices in original array, which allows binary search on O(logn) on new insertion into g\ntime complexity: O(nlogn) to traverse through the orinal array\n\nlist prev record the parents of each nums[i] when g[i] is updated. if it is added in the front of g[i], that means the number is smaller than all numbers that have seen, so it has no parents, parents = None, otherwise, parents = inserting_point - 1\n\nresult: len(g)\n\nindex 0 1 2 3 4 5\nnums [5,4,1,2,3,0]\ng [0] <-index of 5\nprev [None] <- no parents\ng [1] <-index of 4\nprev [None, None] <- no parents\ng [2] <- index of 1\nprev [None, None, None]\ng [2, 3] <- index of 1,2\nprev [None, None, None, 2] <- 2 has parent 1\ng [2, 3, 4] <- index of 1,2,3\nprev [None, None, None, 2, 3] < - 3 has parent 2\ng [5, 3, 4] <- index of 0,2,3\nprev [None, None, None, 2, 3, None] < - 0 is the smallest number, so it has no parent\n\n\"\"\"\nclass Solution:\n \"\"\"\n @param nums: An integer array\n @return: The length of LIS (longest increasing subsequence)\n \"\"\"\n def longestIncreasingSubsequence(self, nums):\n g = []\n prev = []\n for i in range(len(nums)):\n index_to_insert_or_replace = self.binary_search(nums, g, nums[i]) #O(logn)\n if index_to_insert_or_replace < len(g):\n g[index_to_insert_or_replace] = i\n else:\n g.append(i)\n if index_to_insert_or_replace - 1 >= 0:\n prev.append(g[index_to_insert_or_replace - 1])\n else:\n prev.append(None)\n \n self.print_parents(prev, nums, g)\n print (\"g: %s\" % g)\n print (\"prev: %s\" % prev)\n return len(g)\n \n \n def print_parents(self, prev, nums, LIS_sequence):\n if not LIS_sequence:\n return\n index = LIS_sequence[-1]\n result = []\n while index:\n result.append(nums[index])\n index = prev[index]\n result.reverse()\n print (\"one of the LSI: %s\" % result)\n \n \"\"\"\n @return: index of the next bigger number in LIS_sequence that needs to be replaced\n return len(LIS_sequence) if no number in the sequence is larger than target. as the new largest number,\n it needs to be appended in the end of LIS_sequence\n \"\"\"\n def binary_search(self, nums, LIS_sequence, target):\n if not nums:\n return -1\n start, end = 0, len(LIS_sequence) - 1\n while start + 1 < end:\n mid = (start + end) // 2\n if nums[LIS_sequence[mid]] < target:\n start = mid\n else:\n end = mid\n if 0 <= start < len(LIS_sequence):\n if nums[LIS_sequence[start]] >= target:\n return start\n if 0 <= end < len(LIS_sequence):\n if nums[LIS_sequence[end]] >= target:\n return end\n return len(LIS_sequence)\n","sub_path":"lintcode/76.1.py","file_name":"76.1.py","file_ext":"py","file_size_in_byte":3879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"68405436","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport time\n\n\n# feladat URL-je\nURL = \"https://witty-hill-0acfceb03.azurestaticapps.net/lottery.html\"\n\n\ndef test_lottery():\n # oldal betöltése\n browser_options = Options()\n browser_options.headless = True\n browser = webdriver.Chrome(ChromeDriverManager().install(), options=browser_options)\n browser.get(URL)\n\n # TC01 nincs szám\n assert browser.find_element_by_id(\"container\").text == \"\"\n\n # TC02 lottóhúzás\n # click 6 times\n i = 0\n generate = browser.find_element_by_id(\"draw-number\")\n while i < 6:\n generate.click()\n i = i + 1\n\n # kiszedem a számokat és ellenőrzöm, hogy pontosan 6 számot kaptunk\n numbers = browser.find_elements_by_xpath('//*[@class=\"balls\"]')\n assert len(numbers) == 6\n\n # ellenőrzöm hogy a számok 1 és 59 között vannak\n for i in numbers:\n # print(i.text)\n assert 1 <= int(i.text) <= 59\n\n # TC03 hetedik szám, reset ellenőrzöm, hogy továbbra is csak 6 számot kaptunk\n generate.click()\n numbers = browser.find_elements_by_xpath('//*[@class=\"balls\"]')\n assert len(numbers) == 6\n\n # reset gomb megnyomása, ellenőrzöm hogy nem jelenik meg egyetlen szám is\n browser.find_element_by_id(\"reset-numbers\").click()\n assert browser.find_element_by_id(\"container\").text == \"\"\n time.sleep(1)\n\n browser.quit()\n","sub_path":"testproject/test_feladat4.py","file_name":"test_feladat4.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"49820109","text":"\"\"\"Unit tests\"\"\"\nimport sys\nimport os\nsys.path.append(os.path.abspath(\"../../src\"))\n\nimport unittest\nfrom logs.logger_handler import LoggerHandler\n\nclass LoggerHandlerTest(unittest.TestCase):\n \"\"\"Unit tests for LoggerHandler\"\"\"\n\n def setUp(self):\n \"\"\"Setup method to instance an object of Logger Handler\"\"\"\n\n self.debug_message = \"Unit test for debug log\"\n self.info_message = \"Unit test for info log\"\n self.error_message = \"Unit test for error log\"\n self.warning_message = \"Unit test for warning log\"\n \n dir_name = os.path.dirname(os.path.abspath(__file__))\n self.log_file_path = dir_name + \"/test.log\"\n \n self.logger = LoggerHandler(self.log_file_path)\n self.logger.debug(self.debug_message)\n self.logger.info(self.info_message)\n self.logger.error(self.error_message)\n self.logger.warning(self.warning_message)\n\n file = open(self.log_file_path, \"r\")\n self.all_lines_path = file.readlines()\n file.close()\n\n\n def get_if_message_is_in_file(self, message):\n \"\"\"Test if an instance of Customer class is created with required\n \n Keyword arguments:\n message -- the str with the message to search in log file\"\"\"\n \n is_message = False\n for line in self.all_lines_path:\n if line.find(message):\n is_message = True\n \n return is_message\n \n def test_create_logger_handler_object(self):\n \"\"\"Test if an instance of Customer class is created with required\"\"\"\n\n self.assertIsInstance(self.logger, LoggerHandler)\n\n def test_logger_handler_use_singleton_class(self):\n \"\"\"Test singleton class used in logger handler\"\"\"\n\n other_logger = LoggerHandler(self.log_file_path)\n self.assertEqual(self.logger, other_logger)\n\n def test_debug_log_message(self):\n \"\"\"Test debug log message\"\"\"\n \n self.assertTrue(self.get_if_message_is_in_file(self.debug_message))\n \n def test_info_log_message(self):\n \"\"\"Test info log message\"\"\"\n\n self.assertTrue(self.get_if_message_is_in_file(self.info_message))\n \n def test_warning_log_message(self):\n \"\"\"Test warning log message\"\"\"\n \n self.assertTrue(self.get_if_message_is_in_file(self.error_message))\n \n def test_error_log_message(self):\n \"\"\"Test error log message\"\"\"\n\n self.assertTrue(self.get_if_message_is_in_file(self.warning_message))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"movie_rental_store/tests/log_tests/logger_handler_test.py","file_name":"logger_handler_test.py","file_ext":"py","file_size_in_byte":2563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"36893422","text":"from sqlalchemy.dialects.postgresql import insert\nfrom aiopg.sa import create_engine\nfrom datetime import datetime\nimport sqlalchemy as sa\nimport logging\nimport asyncio\nimport uvloop\n\nfrom .models import channels_table, users_table, messages_table\nfrom .utils import get_config, truncate\nfrom .slackbot import SlackBot\n\nconfig = get_config()\nlogger = logging.getLogger()\nbot = SlackBot(config['slack']['token'])\nts = lambda x: datetime.fromtimestamp(float(x))\n\n\n@bot.handler('rtm_start')\nasync def on_rtm_strat(rtm):\n insert_channel = sa.text(\"\"\"\n INSERT INTO channels (id, name) VALUES (:id, :name)\n ON CONFLICT (id) DO UPDATE SET name = :name \"\"\")\n\n insert_user = sa.text(\"\"\"\n INSERT INTO users (id, name, real_name) VALUES (:id, :name, :real_name)\n ON CONFLICT (id) DO UPDATE SET name = :name, real_name = :real_name \"\"\")\n\n logger.info('Loading channels')\n for channel in rtm['channels']:\n await bot.db.execute(insert_channel,\n id=channel['id'], name=channel['name'])\n\n logger.info('Loading users')\n for user in rtm['users']:\n await bot.db.execute(insert_user,\n id=user['id'], name=user['name'],\n real_name=user.get('real_name'))\n\n logger.info('Bot started')\n\n\n@bot.handler('message', subtype=None)\nasync def on_message_sent(event):\n channel_exists = await bot.db.execute(channels_table.select(\n sa.exists([1]).where(channels_table.c.id == event['channel'])))\n\n if not await channel_exists.scalar():\n return\n\n await bot.db.execute(insert(messages_table).values(\n channel_id=event['channel'], user_id=event['user'],\n text=event['text'], timestamp=ts(event['ts'])\n ).on_conflict_do_nothing())\n\n logger.info('New message: ' + truncate(event['text'], 50))\n\n\n@bot.handler('message', subtype='message_changed')\nasync def on_message_edited(event):\n query = sa.text(\"\"\"\n UPDATE messages SET text = :text\n WHERE channel_id = :channel_id AND user_id = :user_id\n AND timestamp = :timestamp \"\"\")\n\n prev_msg = event['previous_message']\n msg = event['message']\n\n await bot.db.execute(query,\n text=msg['text'], channel_id=event['channel'],\n user_id=prev_msg['user'], timestamp=ts(prev_msg['ts']))\n\n logger.info('Message edited: ' + truncate(msg['text'], 50))\n\n\n@bot.handler('channel_joined')\nasync def on_channel_joined(event):\n channel = event['channel']\n logger.info('Join into channel ' + channel['name'])\n insert_stmt = insert(messages_table).on_conflict_do_nothing()\n payload = {'channel': channel['id'], 'count': 1000, 'inclusive': 0}\n\n await bot.send_message(channel['id'], (\n 'Здорова. Отныне я записываю всю историю в этом канале '\n 'и сохраняю в надёжном месте, чтобы не проебалась.'))\n\n while True:\n history = await bot.api_call('channels.history', payload)\n payload['latest'] = history['messages'][-1]['ts']\n\n for message in history['messages']:\n if message['type'] == 'message' and message.get('subtype') is None:\n await bot.db.execute(insert_stmt.values(\n channel_id=channel['id'], user_id=message['user'],\n text=message['text'], timestamp=ts(message['ts'])))\n\n if not history['has_more']:\n break\n\n\n@bot.handler('channel_rename')\nasync def on_channel_rename(event):\n channel = event['channel']\n await bot.db.execute(channels_table.update()\n .where(id=channel['id']).values(name=channel['name']))\n\n logger.info('Rename channel ' + channel['name'])\n\n\n@bot.handler('team_join')\nasync def on_user_join(event):\n user = event['user']\n\n insert_user = users_table.insert().values(\n id=user['id'], name=user['name'],\n real_name=user['real_name'])\n\n await bot.db.execute(insert_user)\n logger.info('New user joined: ' + user['name'])\n\n\n@bot.handler('user_change')\nasync def on_user_change(event):\n user = event['user']\n await bot.db.execute(users_table.update().where(id=user['id'])\n .values(name=user['name'], real_name=user['real_name']))\n\n logger.info('User change ' + user['name'])\n\n\nasync def main():\n engine = await create_engine(**config['database'])\n\n async with engine.acquire() as connection:\n bot.db = connection\n await bot.start_bot()\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO)\n loop = uvloop.new_event_loop()\n asyncio.set_event_loop(loop)\n\n try:\n loop.run_until_complete(main())\n except KeyboardInterrupt:\n if loop.is_running():\n loop.close()\n","sub_path":"historybot/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"458783021","text":"import unittest\nfrom pyramid import testing\n\nclass TestErrorView(unittest.TestCase):\n def setUp(self):\n self.config = testing.setUp()\n\n def tearDown(self):\n testing.tearDown()\n\n def test_it(self):\n class foo:\n name = 'one'\n\n from pyralod.views import error_view\n request = testing.DummyRequest()\n info = error_view(\n {'one':foo(), 'project':'pyralod'}, request)\n self.assertEqual(info['one'].name, 'one')\n self.assertEqual(info['project'], 'pyralod')\n","sub_path":"pyralod/tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"405167960","text":"import time\nfrom datetime import datetime\n\n\nmonth_salary=20000\n#开始工作时间\nstart_hour=10\n\n#结束工作时间\nend_hour=19\n\nwork_time=(end_hour-start_hour)*3600\n\ndef main():\n\n\n #启动时已拥有的money\n current=datetime.now()\n month=current.month\n hour=current.hour\n\n #计算日工资\n big_month=[1,3,5,7,8,10,12]\n day_salary=month_salary/22 if month not in big_month else month_salary/23\n\n #1秒统计一次\n secondSalary=day_salary/work_time\n\n #还没开始工作---\n if hour \" + str(folder))\n exit(1)\n return folder\n\n\n# Tooling for our scripts\ndef get_timestemp():\n return datetime.datetime.now().strftime(\"%Y-%m-%d-%Hh%Mm%Ss\")\n\n","sub_path":"experiments/CONFIGURE_ME.py","file_name":"CONFIGURE_ME.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"646082630","text":"# -*- coding: utf-8 -*-\n# 题目:Frog Jump \n# http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=144875&extra=page%3D1%26filter%3Dsortid%26sortid%3D311%26searchoption%5B3089%5D%5Bvalue%5D%5B5%5D%3D5%26searchoption%5B3089%5D%5Btype%5D%3Dcheckbox%26searchoption%5B3046%5D%5Bvalue%5D%3D28%26searchoption%5B3046%5D%5Btype%5D%3Dradio%26sortid%3D311\nimport math\n# buceket sort一般解决gap的问题\nclass Solution(object):\n def frogJump(self, nums, X, D):\n if X <= D:\n return 0\n n = int(math.ceil((X)/(D+0.0))) # 问题2:math.ceil(里面应该是float)\n buckets = [[float('inf'), -float('inf')] for x in xrange(n)] # [min, max]\n buckets[-1] = [X,X] # 问题: 忘了初始化终点的值\n connectRightSet = set()\n for i in xrange(len(nums)):\n k = (nums[i])/(D)\n buckets[k][0] = min(buckets[k][0], nums[i])\n buckets[k][1] = max(buckets[k][1], nums[i])\n # check connectivity:\n if k < n-1 and k not in connectRightSet:\n if buckets[k][1] + D >= buckets[k+1][0]: # can reach\n connectRightSet.add(k)\n if k > 0 and k-1 not in connectRightSet:\n if buckets[k-1][1] + D >= buckets[k][0]:\n connectRightSet.add(k-1) # 问题1:没考虑到可以往之前的方向联通\n if len(connectRightSet) == n-1:\n return i\n return -1\n\nif __name__ == '__main__':\n sl = Solution()\n nums = [1,3,1,4,2,5]\n X = 7\n D = 3\n assert sl.frogJump(nums, X, D) == 3\n D = 1\n assert sl.frogJump(nums, X, D) == -1\n X = 1\n D = 1\n nums = [1]\n assert sl.frogJump(nums, X, D) == 0\n X = 6\n D = 2\n nums = [4,3,1,4,2,5]\n assert sl.frogJump(nums, X, D) == 2\n X = 10\n D = 2\n nums = [5,7,3,1]\n assert sl.frogJump(nums, X, D) == -1\n X = 10\n D = 2\n nums = [5,7,3,1,9]\n assert sl.frogJump(nums, X, D) == 4\n\n\n\n\n\n","sub_path":"_liveramp_/frog_jump/bucket_sort.py","file_name":"bucket_sort.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"158410705","text":"# example for best practice else block\r\n\r\nfile = None\r\ntry:\r\n file = open('abc.txt', 'r')\r\nexcept FileNotFoundError as e:\r\n print(e.__class__.__name__, e)\r\nelse:\r\n print('File Opened Successfully')\r\n print(\"The content of the file is\")\r\n print(file.read())\r\nfinally:\r\n if file is not None:\r\n file.close()","sub_path":"Error-Handling/else-block/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"285878696","text":"import pandas\nfrom pandas import DataFrame\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.linear_model import LinearRegression\n\ndatos = pandas.read_excel('data/PRÁCTICAS VALORACIÓN AGRARIA_SINTETICOS_REGRESIÓN_AULA.xlsx', sheet_name='EJERCICIO 3')\ndf = DataFrame(datos)\n\nx = df[['PRODUCCIÓN BRUTA (€/kg)', 'EDAD PLANTACIÓN (años)', 'DISTANCIA AL NÚCLEO URBANO (km)',\n 'RIESGO DE HELADA (%)']] # independiente\ny = df['PRECIO COMPRA-VENTA (€/ha)'] # dependiente\n\nprod_bruta = 30\nedad_plantacion = 15\ndistancia_no = 3\nriesgo_helada = 11\n\n# regresion\npoly = PolynomialFeatures(degree=6)\nx_ = poly.fit_transform(x)\n\nlineal = LinearRegression()\nlineal.fit(x_, y)\ny_poly_pred = lineal.predict(x_)\npredict_ = poly.fit_transform([[prod_bruta, edad_plantacion, distancia_no, riesgo_helada]])\n\nprint(f'Resultado regresión: {round(lineal.predict(predict_)[0], 2)}')\n","sub_path":"Problema_3.py","file_name":"Problema_3.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"270067497","text":"from __future__ import print_function\nnum=29\nprime=True\nfor test in range(2,num):\n if(num%test==0 and num!=test):\n print(num,\"equal\",test,\"*\",num/test)\n break\n prime=False\n if prime:\n print(num,\"is a prime number\")\n else:\n print(num,\"is not a prime number\")\nelse:\n print(num,\"is a prime number\")","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"472677537","text":"\"\"\"Custom Keras Layers.\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\n__author__ = \"Han Altae-Tran and Bharath Ramsundar\"\n__copyright__ = \"Copyright 2016, Stanford University\"\n__license__ = \"MIT\"\n\nimport numpy as np\nimport tensorflow as tf\nfrom deepchem.nn import activations\nfrom deepchem.nn import initializations\nfrom deepchem.nn import model_ops\nfrom deepchem.nn.copy import Layer\nfrom deepchem.nn.copy import Input\nfrom deepchem.nn.copy import Dense\nfrom deepchem.nn.copy import Dropout\n\n\ndef affine(x, W, b):\n return tf.matmul(x, W) + b\n\n\ndef tf_affine(x, vm, scope):\n W = vm.var(scope, 'W')\n b = vm.var(scope, 'b')\n\n return tf.matmul(x, W) + b\n\n\ndef sum_neigh(atoms, deg_adj_lists, max_deg):\n \"\"\"Store the summed atoms by degree\"\"\"\n deg_summed = max_deg * [None]\n\n # Tensorflow correctly processes empty lists when using concat\n for deg in range(1, max_deg + 1):\n gathered_atoms = tf.gather(atoms, deg_adj_lists[deg - 1])\n # Sum along neighbors as well as self, and store\n summed_atoms = tf.reduce_sum(gathered_atoms, 1)\n deg_summed[deg - 1] = summed_atoms\n\n return deg_summed\n\n\ndef graph_conv(atoms, deg_adj_lists, deg_slice, max_deg, min_deg, W_list,\n b_list):\n \"\"\"Core tensorflow function implementing graph convolution\n\n Parameters\n ----------\n atoms: tf.Tensor\n Should be of shape (n_atoms, n_feat)\n deg_adj_lists: list\n Of length (max_deg+1-min_deg). The deg-th element is a list of\n adjacency lists for atoms of degree deg.\n deg_slice: tf.Tensor\n Of shape (max_deg+1-min_deg,2). Explained in GraphTopology.\n max_deg: int\n Maximum degree of atoms in molecules.\n min_deg: int\n Minimum degree of atoms in molecules\n W_list: list\n List of learnable weights for convolution.\n b_list: list\n List of learnable biases for convolution.\n\n Returns\n -------\n tf.Tensor\n Of shape (n_atoms, n_feat)\n \"\"\"\n W = iter(W_list)\n b = iter(b_list)\n\n #Sum all neighbors using adjacency matrix\n deg_summed = sum_neigh(atoms, deg_adj_lists, max_deg)\n\n # Get collection of modified atom features\n new_rel_atoms_collection = (max_deg + 1 - min_deg) * [None]\n\n for deg in range(1, max_deg + 1):\n # Obtain relevant atoms for this degree\n rel_atoms = deg_summed[deg - 1]\n\n # Get self atoms\n begin = tf.stack([deg_slice[deg - min_deg, 0], 0])\n size = tf.stack([deg_slice[deg - min_deg, 1], -1])\n self_atoms = tf.slice(atoms, begin, size)\n\n # Apply hidden affine to relevant atoms and append\n rel_out = affine(rel_atoms, next(W), next(b))\n self_out = affine(self_atoms, next(W), next(b))\n out = rel_out + self_out\n\n new_rel_atoms_collection[deg - min_deg] = out\n\n # Determine the min_deg=0 case\n if min_deg == 0:\n deg = 0\n\n begin = tf.stack([deg_slice[deg - min_deg, 0], 0])\n size = tf.stack([deg_slice[deg - min_deg, 1], -1])\n self_atoms = tf.slice(atoms, begin, size)\n\n # Only use the self layer\n out = affine(self_atoms, next(W), next(b))\n\n new_rel_atoms_collection[deg - min_deg] = out\n\n # Combine all atoms back into the list\n activated_atoms = tf.concat(axis=0, values=new_rel_atoms_collection)\n\n return activated_atoms\n\n\ndef graph_gather(atoms, membership_placeholder, batch_size):\n \"\"\"\n Parameters\n ----------\n atoms: tf.Tensor\n Of shape (n_atoms, n_feat)\n membership_placeholder: tf.Placeholder\n Of shape (n_atoms,). Molecule each atom belongs to.\n batch_size: int\n Batch size for deep model.\n\n Returns\n -------\n tf.Tensor\n Of shape (batch_size, n_feat)\n \"\"\"\n\n # WARNING: Does not work for Batch Size 1! If batch_size = 1, then use reduce_sum!\n assert batch_size > 1, \"graph_gather requires batches larger than 1\"\n\n # Obtain the partitions for each of the molecules\n activated_par = tf.dynamic_partition(atoms, membership_placeholder,\n batch_size)\n\n # Sum over atoms for each molecule\n sparse_reps = [\n tf.reduce_sum(activated, 0, keep_dims=True) for activated in activated_par\n ]\n\n # Get the final sparse representations\n sparse_reps = tf.concat(axis=0, values=sparse_reps)\n\n return sparse_reps\n\n\ndef graph_pool(atoms, deg_adj_lists, deg_slice, max_deg, min_deg):\n \"\"\"\n Parameters\n ----------\n atoms: tf.Tensor\n Of shape (n_atoms, n_feat)\n deg_adj_lists: list\n Of length (max_deg+1-min_deg). The deg-th element is a list of\n adjacency lists for atoms of degree deg.\n deg_slice: tf.Tensor\n Of shape (max_deg+1-min_deg,2). Explained in GraphTopology.\n max_deg: int\n Maximum degree of atoms in molecules.\n min_deg: int\n Minimum degree of atoms in molecules\n\n Returns\n -------\n tf.Tensor\n Of shape (batch_size, n_feat)\n \"\"\"\n # Store the summed atoms by degree\n deg_maxed = (max_deg + 1 - min_deg) * [None]\n\n # Tensorflow correctly processes empty lists when using concat\n\n for deg in range(1, max_deg + 1):\n # Get self atoms\n begin = tf.stack([deg_slice[deg - min_deg, 0], 0])\n size = tf.stack([deg_slice[deg - min_deg, 1], -1])\n self_atoms = tf.slice(atoms, begin, size)\n\n # Expand dims\n self_atoms = tf.expand_dims(self_atoms, 1)\n\n # always deg-1 for deg_adj_lists\n gathered_atoms = tf.gather(atoms, deg_adj_lists[deg - 1])\n gathered_atoms = tf.concat(axis=1, values=[self_atoms, gathered_atoms])\n\n maxed_atoms = tf.reduce_max(gathered_atoms, 1)\n deg_maxed[deg - min_deg] = maxed_atoms\n\n if min_deg == 0:\n begin = tf.stack([deg_slice[0, 0], 0])\n size = tf.stack([deg_slice[0, 1], -1])\n self_atoms = tf.slice(atoms, begin, size)\n deg_maxed[0] = self_atoms\n\n return tf.concat(axis=0, values=deg_maxed)\n\n\nclass GraphConv(Layer):\n \"\"\"\"Performs a graph convolution.\n\n Note this layer expects the presence of placeholders defined by GraphTopology\n and expects that they follow the ordering provided by\n GraphTopology.get_input_placeholders().\n \"\"\"\n\n def __init__(self,\n nb_filter,\n n_atom_features,\n init='glorot_uniform',\n activation='linear',\n dropout=None,\n max_deg=10,\n min_deg=0,\n **kwargs):\n \"\"\"\n Parameters\n ----------\n nb_filter: int\n Number of convolutional filters.\n n_atom_features: int\n Number of features listed per atom.\n init: str, optional\n Weight initialization for filters.\n activation: str, optional\n Activation function applied after convolution.\n dropout: float, optional\n Dropout probability.\n max_deg: int, optional\n Maximum degree of atoms in molecules.\n min_deg: int, optional\n Minimum degree of atoms in molecules.\n \"\"\"\n super(GraphConv, self).__init__(**kwargs)\n\n self.init = initializations.get(init) # Set weight initialization\n self.activation = activations.get(activation) # Get activations\n self.nb_filter = nb_filter # Save number of filters\n self.dropout = dropout # Save dropout params\n self.max_deg = max_deg\n self.min_deg = min_deg\n # TODO(rbharath): It's not clear where nb_affine comes from.\n # Is there a solid explanation here?\n self.nb_affine = 2 * max_deg + (1 - min_deg)\n self.n_atom_features = n_atom_features\n\n def build(self):\n \"\"\"\"Construct internal trainable weights.\n\n n_atom_features should provide the number of features per atom.\n\n Parameters\n ----------\n n_atom_features: int\n Number of features provied per atom.\n \"\"\"\n n_atom_features = self.n_atom_features\n\n # Generate the nb_affine weights and biases\n self.W_list = [\n self.init([n_atom_features, self.nb_filter])\n for k in range(self.nb_affine)\n ]\n self.b_list = [\n model_ops.zeros(shape=[\n self.nb_filter,\n ]) for k in range(self.nb_affine)\n ]\n\n self.trainable_weights = self.W_list + self.b_list\n\n def get_output_shape_for(self, input_shape):\n \"\"\"Output tensor shape produced by this layer.\"\"\"\n atom_features_shape = input_shape[0]\n assert len(atom_features_shape) == 2, \\\n \"MolConv only takes 2 dimensional tensors for x\"\n n_atoms = atom_features_shape[0]\n return (n_atoms, self.nb_filter)\n\n def call(self, x, mask=None):\n \"\"\"Execute this layer on input tensors.\n\n This layer is meant to be executed on a Graph. So x is expected to\n be a list of placeholders, with the first placeholder the list of\n atom_features (learned or input) at this level, the second the deg_slice,\n the third the membership, and the remaining the deg_adj_lists.\n\n Visually\n\n x = [atom_features, deg_slice, membership, deg_adj_list placeholders...]\n\n Parameters\n ----------\n x: list\n list of Tensors of form described above.\n mask: bool, optional\n Ignored. Present only to shadow superclass call() method.\n\n Returns\n -------\n atom_features: tf.Tensor\n Of shape (n_atoms, nb_filter)\n \"\"\"\n # Add trainable weights\n self.build()\n\n # Extract atom_features\n atom_features = x[0]\n\n # Extract graph topology\n deg_slice, membership, deg_adj_lists = x[1], x[2], x[3:]\n\n # Perform the mol conv\n atom_features = graph_conv(atom_features, deg_adj_lists, deg_slice,\n self.max_deg, self.min_deg, self.W_list,\n self.b_list)\n\n atom_features = self.activation(atom_features)\n\n if self.dropout is not None:\n atom_features = Dropout(self.dropout)(atom_features)\n\n return atom_features\n\n\nclass GraphGather(Layer):\n \"\"\"Gathers information for each molecule.\n\n The various graph convolution operations expect as input a tensor\n atom_features of shape (n_atoms, n_feat). However, we train on batches of\n molecules at a time. The GraphTopology object groups a list of molecules\n into the atom_features tensor. The tensorial operations are done on this tensor,\n but at the end, the atoms need to be grouped back into molecules. This\n layer takes care of that operation.\n\n Note this layer expects the presence of placeholders defined by GraphTopology\n and expects that they follow the ordering provided by\n GraphTopology.get_input_placeholders().\n \"\"\"\n\n def __init__(self, batch_size, activation='linear', **kwargs):\n \"\"\"\n Parameters\n ----------\n batch_size: int\n Number of elements in batch of data.\n \"\"\"\n super(GraphGather, self).__init__(**kwargs)\n\n self.activation = activations.get(activation) # Get activations\n self.batch_size = batch_size\n\n def build(self, input_shape):\n \"\"\"Nothing needed (no learnable weights).\"\"\"\n pass\n\n def get_output_shape_for(self, input_shape):\n \"\"\"Output tensor shape produced by this layer.\"\"\"\n # Extract nodes and membership\n atom_features_shape = input_shape[0]\n membership_shape = input_shape[2]\n\n assert len(atom_features_shape) == 2, \\\n \"GraphGather only takes 2 dimensional tensors\"\n n_feat = atom_features_shape[1]\n\n return (self.batch_size, n_feat)\n\n def call(self, x, mask=None):\n \"\"\"Execute this layer on input tensors.\n\n This layer is meant to be executed on a Graph. So x is expected to\n be a list of placeholders, with the first placeholder the list of\n atom_features (learned or input) at this level, the second the deg_slice,\n the third the membership, and the remaining the deg_adj_lists.\n\n Visually\n\n x = [atom_features, deg_slice, membership, deg_adj_list placeholders...]\n\n Parameters\n ----------\n x: list\n list of Tensors of form described above.\n mask: bool, optional\n Ignored. Present only to shadow superclass call() method.\n\n Returns\n -------\n tf.Tensor\n Of shape (batch_size, n_feat), where n_feat is number of atom_features\n \"\"\"\n # Extract atom_features\n atom_features = x[0]\n\n # Extract graph topology\n membership = x[2]\n\n # Perform the mol gather\n mol_features = graph_gather(atom_features, membership, self.batch_size)\n\n return self.activation(mol_features)\n\n\nclass GraphPool(Layer):\n \"\"\"Performs a pooling operation over an arbitrary graph.\n\n Performs a max pool over the feature vectors for an atom and its neighbors\n in bond-graph. Returns a tensor of the same size as the input.\n \"\"\"\n\n def __init__(self, max_deg=10, min_deg=0, **kwargs):\n \"\"\"\n Parameters\n ----------\n max_deg: int, optional\n Maximum degree of atoms in molecules.\n min_deg: int, optional\n Minimum degree of atoms in molecules.\n \"\"\"\n self.max_deg = max_deg\n self.min_deg = min_deg\n super(GraphPool, self).__init__(**kwargs)\n\n def build(self, input_shape):\n \"\"\"Nothing needed (no learnable weights).\"\"\"\n pass\n\n def get_output_shape_for(self, input_shape):\n \"\"\"Output tensor shape produced by this layer.\"\"\"\n # Extract nodes\n atom_features_shape = input_shape[0]\n\n assert len(atom_features_shape) == 2, \\\n \"GraphPool only takes 2 dimensional tensors\"\n return atom_features_shape\n\n def call(self, x, mask=None):\n \"\"\"Execute this layer on input tensors.\n\n This layer is meant to be executed on a Graph. So x is expected to\n be a list of placeholders, with the first placeholder the list of\n atom_features (learned or input) at this level, the second the deg_slice,\n the third the membership, and the remaining the deg_adj_lists.\n\n Visually\n\n x = [atom_features, deg_slice, membership, deg_adj_list placeholders...]\n\n Parameters\n ----------\n x: list\n list of Tensors of form described above.\n mask: bool, optional\n Ignored. Present only to shadow superclass call() method.\n\n Returns\n -------\n tf.Tensor\n Of shape (n_atoms, n_feat), where n_feat is number of atom_features\n \"\"\"\n # Extract atom_features\n atom_features = x[0]\n\n # Extract graph topology\n deg_slice, membership, deg_adj_lists = x[1], x[2], x[3:]\n\n # Perform the mol gather\n atom_features = graph_pool(atom_features, deg_adj_lists, deg_slice,\n self.max_deg, self.min_deg)\n\n return atom_features\n\n\nclass AttnLSTMEmbedding(Layer):\n \"\"\"Implements AttnLSTM as in matching networks paper.\n\n References:\n Matching Networks for One Shot Learning\n https://arxiv.org/pdf/1606.04080v1.pdf\n\n Order Matters: Sequence to sequence for sets\n https://arxiv.org/abs/1511.06391\n \"\"\"\n\n def __init__(self,\n n_test,\n n_support,\n n_feat,\n max_depth,\n init='glorot_uniform',\n activation='linear',\n dropout=None,\n **kwargs):\n \"\"\"\n Parameters\n ----------\n n_support: int\n Size of support set.\n n_test: int\n Size of test set.\n n_feat: int\n Number of features per atom\n max_depth: int\n Number of \"processing steps\" used by sequence-to-sequence for sets model.\n init: str, optional\n Type of initialization of weights\n activation: str, optional\n Activation for layers.\n dropout: float, optional\n Dropout probability\n \"\"\"\n super(AttnLSTMEmbedding, self).__init__(**kwargs)\n\n self.init = initializations.get(init) # Set weight initialization\n self.activation = activations.get(activation) # Get activations\n self.max_depth = max_depth\n self.n_test = n_test\n self.n_support = n_support\n self.n_feat = n_feat\n\n def get_output_shape_for(self, input_shape):\n \"\"\"Returns the output shape. Same as input_shape.\n\n Parameters\n ----------\n input_shape: list\n Will be of form [(n_test, n_feat), (n_support, n_feat)]\n\n Returns\n -------\n list\n Of same shape as input [(n_test, n_feat), (n_support, n_feat)]\n \"\"\"\n x_input_shape, xp_input_shape = input_shape #Unpack\n\n return input_shape\n\n def call(self, x_xp, mask=None):\n \"\"\"Execute this layer on input tensors.\n\n Parameters\n ----------\n x_xp: list\n List of two tensors (X, Xp). X should be of shape (n_test, n_feat) and\n Xp should be of shape (n_support, n_feat) where n_test is the size of\n the test set, n_support that of the support set, and n_feat is the number\n of per-atom features.\n\n Returns\n -------\n list\n Returns two tensors of same shape as input. Namely the output shape will\n be [(n_test, n_feat), (n_support, n_feat)]\n \"\"\"\n # x is test set, xp is support set.\n x, xp = x_xp\n\n ## Initializes trainable weights.\n n_feat = self.n_feat\n\n self.lstm = LSTMStep(n_feat, 2 * n_feat)\n self.q_init = model_ops.zeros([self.n_test, n_feat])\n self.r_init = model_ops.zeros([self.n_test, n_feat])\n self.states_init = self.lstm.get_initial_states([self.n_test, n_feat])\n\n self.trainable_weights = [self.q_init, self.r_init]\n\n ### Performs computations\n\n # Get initializations\n q = self.q_init\n #r = self.r_init\n states = self.states_init\n\n for d in range(self.max_depth):\n # Process using attention\n # Eqn (4), appendix A.1 of Matching Networks paper\n e = cos(x + q, xp)\n a = tf.nn.softmax(e)\n r = model_ops.dot(a, xp)\n\n # Generate new aattention states\n y = model_ops.concatenate([q, r], axis=1)\n q, states = self.lstm([y] + states) #+ self.lstm.get_constants(x)\n\n return [x + q, xp]\n\n def compute_mask(self, x, mask=None):\n if not (mask is None):\n return mask\n return [None, None]\n\n\nclass ResiLSTMEmbedding(Layer):\n \"\"\"Embeds its inputs using an LSTM layer.\"\"\"\n\n def __init__(self,\n n_test,\n n_support,\n n_feat,\n max_depth,\n init='glorot_uniform',\n activation='linear',\n **kwargs):\n \"\"\"\n Unlike the AttnLSTM model which only modifies the test vectors additively,\n this model allows for an additive update to be performed to both test and\n support using information from each other.\n\n Parameters\n ----------\n n_support: int\n Size of support set.\n n_test: int\n Size of test set.\n n_feat: int\n Number of input atom features\n max_depth: int\n Number of LSTM Embedding layers.\n init: string\n Type of weight initialization (from Keras)\n activation: string\n Activation type (ReLu/Linear/etc.)\n \"\"\"\n super(ResiLSTMEmbedding, self).__init__(**kwargs)\n\n self.init = initializations.get(init) # Set weight initialization\n self.activation = activations.get(activation) # Get activations\n self.max_depth = max_depth\n self.n_test = n_test\n self.n_support = n_support\n self.n_feat = n_feat\n\n #def build(self, input_shape):\n def build(self):\n \"\"\"Builds this layer.\n \"\"\"\n #_, support_input_shape = input_shape #Unpack\n #n_feat = support_input_shape[1]\n n_feat = self.n_feat\n\n # Support set lstm\n self.support_lstm = LSTMStep(n_feat, 2 * n_feat)\n self.q_init = model_ops.zeros([self.n_support, n_feat])\n self.support_states_init = self.support_lstm.get_initial_states(\n [self.n_support, n_feat])\n\n # Test lstm\n self.test_lstm = LSTMStep(n_feat, 2 * n_feat)\n self.p_init = model_ops.zeros([self.n_test, n_feat])\n self.test_states_init = self.test_lstm.get_initial_states(\n [self.n_test, n_feat])\n\n self.trainable_weights = []\n\n def get_output_shape_for(self, input_shape):\n \"\"\"Returns the output shape. Same as input_shape.\n\n Parameters\n ----------\n input_shape: list\n Will be of form [(n_test, n_feat), (n_support, n_feat)]\n\n Returns\n -------\n list\n Of same shape as input [(n_test, n_feat), (n_support, n_feat)]\n \"\"\"\n return input_shape\n\n def call(self, argument, mask=None):\n \"\"\"Execute this layer on input tensors.\n\n Parameters\n ----------\n argument: list\n List of two tensors (X, Xp). X should be of shape (n_test, n_feat) and\n Xp should be of shape (n_support, n_feat) where n_test is the size of\n the test set, n_support that of the support set, and n_feat is the number\n of per-atom features.\n\n Returns\n -------\n list\n Returns two tensors of same shape as input. Namely the output shape will\n be [(n_test, n_feat), (n_support, n_feat)]\n \"\"\"\n self.build()\n x, xp = argument\n\n # Get initializations\n p = self.p_init\n q = self.q_init\n # Rename support\n z = xp\n states = self.support_states_init\n x_states = self.test_states_init\n\n for d in range(self.max_depth):\n # Process support xp using attention\n e = cos(z + q, xp)\n a = tf.nn.softmax(e)\n # Get linear combination of support set\n r = model_ops.dot(a, xp)\n\n # Not sure if it helps to place the update here or later yet. Will\n # decide\n #z = r\n\n # Process test x using attention\n x_e = cos(x + p, z)\n x_a = tf.nn.softmax(x_e)\n s = model_ops.dot(x_a, z)\n\n # Generate new support attention states\n qr = model_ops.concatenate([q, r], axis=1)\n q, states = self.support_lstm([qr] + states)\n\n # Generate new test attention states\n ps = model_ops.concatenate([p, s], axis=1)\n p, x_states = self.test_lstm([ps] + x_states)\n\n # Redefine\n z = r\n\n #return [x+p, z+q]\n return [x + p, xp + q]\n\n def compute_mask(self, x, mask=None):\n if not (mask is None):\n return mask\n return [None, None]\n\n\ndef cos(x, y):\n denom = (\n model_ops.sqrt(model_ops.sum(tf.square(x)) * model_ops.sum(tf.square(y)))\n + model_ops.epsilon())\n return model_ops.dot(x, tf.transpose(y)) / denom\n\n\nclass LSTMStep(Layer):\n \"\"\" LSTM whose call is a single step in the LSTM.\n\n This layer exists because the Keras LSTM layer is intrinsically linked to an\n RNN with sequence inputs, and here, we will not be using sequence inputs, but\n rather we generate a sequence of inputs using the intermediate outputs of the\n LSTM, and so will require step by step operation of the lstm\n \"\"\"\n\n def __init__(self,\n output_dim,\n input_dim,\n init='glorot_uniform',\n inner_init='orthogonal',\n forget_bias_init='one',\n activation='tanh',\n inner_activation='hard_sigmoid',\n **kwargs):\n\n super(LSTMStep, self).__init__(**kwargs)\n\n self.output_dim = output_dim\n\n self.init = initializations.get(init)\n self.inner_init = initializations.get(inner_init)\n # No other forget biases supported right now.\n assert forget_bias_init == \"one\"\n self.forget_bias_init = initializations.get(forget_bias_init)\n self.activation = activations.get(activation)\n self.inner_activation = activations.get(inner_activation)\n self.input_dim = input_dim\n\n def get_initial_states(self, input_shape):\n return [model_ops.zeros(input_shape), model_ops.zeros(input_shape)]\n\n #def build(self, input_shape):\n def build(self):\n\n self.W = self.init((self.input_dim, 4 * self.output_dim))\n self.U = self.inner_init((self.output_dim, 4 * self.output_dim))\n\n self.b = tf.Variable(\n np.hstack((np.zeros(self.output_dim), np.ones(self.output_dim),\n np.zeros(self.output_dim), np.zeros(self.output_dim))),\n dtype=tf.float32)\n self.trainable_weights = [self.W, self.U, self.b]\n\n def get_output_shape_for(self, input_shape):\n x, h_tm1, c_tm1 = input_shape # Unpack\n return [(x[0], self.output_dim), h_tm1, c_tm1]\n\n def call(self, x_states, mask=None):\n self.build()\n x, h_tm1, c_tm1 = x_states # Unpack\n\n # Taken from Keras code [citation needed]\n z = model_ops.dot(x, self.W) + model_ops.dot(h_tm1, self.U) + self.b\n\n z0 = z[:, :self.output_dim]\n z1 = z[:, self.output_dim:2 * self.output_dim]\n z2 = z[:, 2 * self.output_dim:3 * self.output_dim]\n z3 = z[:, 3 * self.output_dim:]\n\n i = self.inner_activation(z0)\n f = self.inner_activation(z1)\n c = f * c_tm1 + i * self.activation(z2)\n o = self.inner_activation(z3)\n\n h = o * self.activation(c)\n\n ####################################################### DEBUG\n #return o, [h, c]\n return h, [h, c]\n ####################################################### DEBUG\n\n\nclass DTNNEmbedding(Layer):\n \"\"\"Generate embeddings for all atoms in the batch\n \"\"\"\n\n def __init__(self,\n n_embedding=30,\n periodic_table_length=30,\n init='glorot_uniform',\n **kwargs):\n \"\"\"\n Parameters\n ----------\n n_embedding: int, optional\n Number of features for each atom\n periodic_table_length: int, optional\n Length of embedding, 83=Bi\n init: str, optional\n Weight initialization for filters.\n \"\"\"\n self.n_embedding = n_embedding\n self.periodic_table_length = periodic_table_length\n self.init = initializations.get(init) # Set weight initialization\n\n super(DTNNEmbedding, self).__init__(**kwargs)\n\n def build(self):\n\n self.embedding_list = self.init(\n [self.periodic_table_length, self.n_embedding])\n self.trainable_weights = [self.embedding_list]\n\n def call(self, x):\n \"\"\"Execute this layer on input tensors.\n\n Parameters\n ----------\n x: Tensor\n 1D tensor of length n_atoms (atomic number)\n\n Returns\n -------\n tf.Tensor\n Of shape (n_atoms, n_embedding), where n_embedding is number of atom features\n \"\"\"\n self.build()\n atom_features = tf.nn.embedding_lookup(self.embedding_list, x)\n return atom_features\n\n\nclass DTNNStep(Layer):\n \"\"\"A convolution step that merge in distance and atom info of\n all other atoms into current atom.\n\n model based on https://arxiv.org/abs/1609.08259\n \"\"\"\n\n def __init__(self,\n n_embedding=30,\n n_distance=100,\n n_hidden=60,\n init='glorot_uniform',\n activation='tanh',\n **kwargs):\n \"\"\"\n Parameters\n ----------\n n_embedding: int, optional\n Number of features for each atom\n n_distance: int, optional\n granularity of distance matrix\n n_hidden: int, optional\n Number of nodes in hidden layer\n init: str, optional\n Weight initialization for filters.\n activation: str, optional\n Activation function applied\n \"\"\"\n self.n_embedding = n_embedding\n self.n_distance = n_distance\n self.n_hidden = n_hidden\n self.init = initializations.get(init) # Set weight initialization\n self.activation = activations.get(activation) # Get activations\n\n super(DTNNStep, self).__init__(**kwargs)\n\n def build(self):\n self.W_cf = self.init([self.n_embedding, self.n_hidden])\n self.W_df = self.init([self.n_distance, self.n_hidden])\n self.W_fc = self.init([self.n_hidden, self.n_embedding])\n self.b_cf = model_ops.zeros(shape=[\n self.n_hidden,\n ])\n self.b_df = model_ops.zeros(shape=[\n self.n_hidden,\n ])\n #self.b_fc = model_ops.zeros(shape=[self.n_embedding,])\n\n self.trainable_weights = [\n self.W_cf, self.W_df, self.W_fc, self.b_cf, self.b_df\n ]\n\n def call(self, x):\n \"\"\"Execute this layer on input tensors.\n\n Parameters\n ----------\n x: list of Tensor\n should be [atom_features: n_atoms*n_embedding,\n distance_matrix: n_pairs*n_distance,\n atom_membership: n_atoms\n distance_membership_i: n_pairs,\n distance_membership_j: n_pairs,\n ]\n\n Returns\n -------\n tf.Tensor\n new embeddings for atoms, same shape as x[0]\n \"\"\"\n self.build()\n atom_features = x[0]\n distance = x[1]\n distance_membership_i = x[3]\n distance_membership_j = x[4]\n distance_hidden = tf.matmul(distance, self.W_df) + self.b_df\n #distance_hidden = self.activation(distance_hidden)\n atom_features_hidden = tf.matmul(atom_features, self.W_cf) + self.b_cf\n #atom_features_hidden = self.activation(atom_features_hidden)\n outputs = tf.multiply(distance_hidden,\n tf.gather(atom_features_hidden,\n distance_membership_j))\n\n # for atom i in a molecule m, this step multiplies together distance info of atom pair(i,j)\n # and embeddings of atom j(both gone through a hidden layer)\n outputs = tf.matmul(outputs, self.W_fc)\n outputs = self.activation(outputs)\n\n output_ii = tf.multiply(self.b_df, atom_features_hidden)\n output_ii = tf.matmul(output_ii, self.W_fc)\n output_ii = self.activation(output_ii)\n\n # for atom i, sum the influence from all other atom j in the molecule\n outputs = tf.segment_sum(outputs,\n distance_membership_i) - output_ii + atom_features\n\n return outputs\n\n\nclass DTNNGather(Layer):\n \"\"\"Map the atomic features into molecular properties and sum\n \"\"\"\n\n def __init__(self,\n n_embedding=30,\n n_outputs=100,\n layer_sizes=[100],\n output_activation=True,\n init='glorot_uniform',\n activation='tanh',\n **kwargs):\n \"\"\"\n Parameters\n ----------\n n_embedding: int, optional\n Number of features for each atom\n layer_sizes: list of int, optional(default=[1000])\n Structure of hidden layer(s)\n n_tasks: int, optional\n Number of final summed outputs\n init: str, optional\n Weight initialization for filters.\n activation: str, optional\n Activation function applied\n \"\"\"\n self.n_embedding = n_embedding\n self.layer_sizes = layer_sizes\n self.n_outputs = n_outputs\n self.output_activation = output_activation\n self.init = initializations.get(init) # Set weight initialization\n self.activation = activations.get(activation) # Get activations\n\n super(DTNNGather, self).__init__(**kwargs)\n\n def build(self):\n self.W_list = []\n self.b_list = []\n prev_layer_size = self.n_embedding\n for i, layer_size in enumerate(self.layer_sizes):\n self.W_list.append(self.init([prev_layer_size, layer_size]))\n self.b_list.append(model_ops.zeros(shape=[\n layer_size,\n ]))\n prev_layer_size = layer_size\n self.W_list.append(self.init([prev_layer_size, self.n_outputs]))\n self.b_list.append(model_ops.zeros(shape=[\n self.n_outputs,\n ]))\n\n self.trainable_weights = self.W_list + self.b_list\n\n def call(self, x):\n \"\"\"Execute this layer on input tensors.\n\n Parameters\n ----------\n x: list of Tensor\n should be [embedding tensor of molecules, of shape (batch_size*max_n_atoms*n_embedding),\n mask tensor of molecules, of shape (batch_size*max_n_atoms)]\n\n Returns\n -------\n list of tf.Tensor\n Of shape (batch_size)\n \"\"\"\n self.build()\n output = x[0]\n atom_membership = x[1]\n for i, W in enumerate(self.W_list[:-1]):\n output = tf.matmul(output, W) + self.b_list[i]\n output = self.activation(output)\n output = tf.matmul(output, self.W_list[-1]) + self.b_list[-1]\n if self.output_activation:\n output = self.activation(output)\n output = tf.segment_sum(output, atom_membership)\n return output\n\n\nclass DAGLayer(Layer):\n \"\"\"\" Main layer of DAG model\n For a molecule with n atoms, n different graphs are generated and run through\n The final outputs of each graph become the graph features of corresponding\n atom, which will be summed and put into another network in DAGGather Layer\n \"\"\"\n\n def __init__(self,\n n_graph_feat=30,\n n_atom_feat=75,\n max_atoms=50,\n layer_sizes=[100],\n init='glorot_uniform',\n activation='relu',\n dropout=None,\n batch_size=64,\n **kwargs):\n \"\"\"\n Parameters\n ----------\n n_graph_feat: int, optional\n Number of features for each node(and the whole grah).\n n_atom_feat: int, optional\n Number of features listed per atom.\n max_atoms: int, optional\n Maximum number of atoms in molecules.\n layer_sizes: list of int, optional(default=[1000])\n Structure of hidden layer(s)\n init: str, optional\n Weight initialization for filters.\n activation: str, optional\n Activation function applied\n dropout: float, optional\n Dropout probability, not supported here\n batch_size: int, optional\n number of molecules in a batch\n \"\"\"\n super(DAGLayer, self).__init__(**kwargs)\n\n self.init = initializations.get(init) # Set weight initialization\n self.activation = activations.get(activation) # Get activations\n self.layer_sizes = layer_sizes\n self.dropout = dropout\n self.max_atoms = max_atoms\n self.batch_size = batch_size\n self.n_inputs = n_atom_feat + (self.max_atoms - 1) * n_graph_feat\n # number of inputs each step\n self.n_graph_feat = n_graph_feat\n self.n_outputs = n_graph_feat\n self.n_atom_feat = n_atom_feat\n\n def build(self):\n \"\"\"\"Construct internal trainable weights.\n \"\"\"\n\n self.W_list = []\n self.b_list = []\n prev_layer_size = self.n_inputs\n for layer_size in self.layer_sizes:\n self.W_list.append(self.init([prev_layer_size, layer_size]))\n self.b_list.append(model_ops.zeros(shape=[\n layer_size,\n ]))\n prev_layer_size = layer_size\n self.W_list.append(self.init([prev_layer_size, self.n_outputs]))\n self.b_list.append(model_ops.zeros(shape=[\n self.n_outputs,\n ]))\n\n self.trainable_weights = self.W_list + self.b_list\n\n def call(self, x, mask=None):\n \"\"\"Execute this layer on input tensors.\n\n x = [atom_features, parents, calculation_orders, calculation_masks, membership, n_atoms]\n\n Parameters\n ----------\n x: list\n list of Tensors of form described above.\n mask: bool, optional\n Ignored. Present only to shadow superclass call() method.\n\n Returns\n -------\n outputs: tf.Tensor\n Tensor of atom features, of shape (n_atoms, n_graph_feat)\n \"\"\"\n # Add trainable weights\n self.build()\n # Extract atom_features\n # Basic features of every atom: (batch_size*max_atoms) * n_atom_features\n atom_features = x[0]\n # calculation orders of graph: (batch_size*max_atoms) * max_atoms * max_atoms\n # each atom corresponds to a graph, which is represented by the `max_atoms*max_atoms` int32 matrix of index\n # each gragh include `max_atoms` of steps(corresponding to rows) of calculating graph features\n # step i calculates the graph features for atoms of index `parents[:,i,0]`\n parents = x[1]\n # target atoms for each step: (batch_size*max_atoms) * max_atoms\n # represent the same atoms of `parents[:, :, 0]`,\n # different in that these index are positions in `atom_features`\n calculation_orders = x[2]\n calculation_masks = x[3]\n # number of atoms in total, should equal `batch_size*max_atoms`\n n_atoms = x[5]\n\n graph_features_initial = tf.zeros((self.max_atoms * self.batch_size,\n self.max_atoms + 1, self.n_graph_feat))\n # initialize graph features for each graph\n # another row of zeros is generated for padded dummy atoms\n graph_features = tf.Variable(graph_features_initial, trainable=False)\n\n for count in range(self.max_atoms):\n # `count`-th step\n # extracting atom features of target atoms: (batch_size*max_atoms) * n_atom_features\n mask = calculation_masks[:, count]\n current_round = tf.boolean_mask(calculation_orders[:, count], mask)\n batch_atom_features = tf.gather(atom_features, current_round)\n\n # generating index for graph features used in the inputs\n index = tf.stack(\n [\n tf.reshape(\n tf.stack(\n [tf.boolean_mask(tf.range(n_atoms), mask)] *\n (self.max_atoms - 1),\n axis=1), [-1]),\n tf.reshape(tf.boolean_mask(parents[:, count, 1:], mask), [-1])\n ],\n axis=1)\n # extracting graph features for parents of the target atoms, then flatten\n # shape: (batch_size*max_atoms) * [(max_atoms-1)*n_graph_features]\n batch_graph_features = tf.reshape(\n tf.gather_nd(graph_features, index),\n [-1, (self.max_atoms - 1) * self.n_graph_feat])\n\n # concat into the input tensor: (batch_size*max_atoms) * n_inputs\n batch_inputs = tf.concat(\n axis=1, values=[batch_atom_features, batch_graph_features])\n # DAGgraph_step maps from batch_inputs to a batch of graph_features\n # of shape: (batch_size*max_atoms) * n_graph_features\n # representing the graph features of target atoms in each graph\n batch_outputs = self.DAGgraph_step(batch_inputs, self.W_list, self.b_list)\n\n # index for targe atoms\n target_index = tf.stack([tf.range(n_atoms), parents[:, count, 0]], axis=1)\n target_index = tf.boolean_mask(target_index, mask)\n # update the graph features for target atoms\n graph_features = tf.scatter_nd_update(graph_features, target_index,\n batch_outputs)\n\n # last step generates graph features for all target atom\n return batch_outputs\n\n def DAGgraph_step(self, batch_inputs, W_list, b_list):\n outputs = batch_inputs\n for idw, W in enumerate(W_list):\n outputs = tf.nn.xw_plus_b(outputs, W, b_list[idw])\n outputs = self.activation(outputs)\n return outputs\n\n\nclass DAGGather(Layer):\n \"\"\" Gather layer of DAG model\n for each molecule, graph outputs are summed and input into another NN\n \"\"\"\n\n def __init__(self,\n n_graph_feat=30,\n n_outputs=30,\n max_atoms=50,\n layer_sizes=[100],\n init='glorot_uniform',\n activation='relu',\n dropout=None,\n **kwargs):\n \"\"\"\n Parameters\n ----------\n n_graph_feat: int, optional\n Number of features for each atom\n n_outputs: int, optional\n Number of features for each molecule.\n max_atoms: int, optional\n Maximum number of atoms in molecules.\n layer_sizes: list of int, optional\n Structure of hidden layer(s)\n init: str, optional\n Weight initialization for filters.\n activation: str, optional\n Activation function applied\n dropout: float, optional\n Dropout probability, not supported\n \"\"\"\n super(DAGGather, self).__init__(**kwargs)\n\n self.init = initializations.get(init) # Set weight initialization\n self.activation = activations.get(activation) # Get activations\n self.layer_sizes = layer_sizes\n self.dropout = dropout\n self.max_atoms = max_atoms\n self.n_graph_feat = n_graph_feat\n self.n_outputs = n_outputs\n\n def build(self):\n \"\"\"\"Construct internal trainable weights.\n \"\"\"\n\n self.W_list = []\n self.b_list = []\n prev_layer_size = self.n_graph_feat\n for layer_size in self.layer_sizes:\n self.W_list.append(self.init([prev_layer_size, layer_size]))\n self.b_list.append(model_ops.zeros(shape=[\n layer_size,\n ]))\n prev_layer_size = layer_size\n self.W_list.append(self.init([prev_layer_size, self.n_outputs]))\n self.b_list.append(model_ops.zeros(shape=[\n self.n_outputs,\n ]))\n\n self.trainable_weights = self.W_list + self.b_list\n\n def call(self, x, mask=None):\n \"\"\"Execute this layer on input tensors.\n\n x = [graph_features, membership]\n\n Parameters\n ----------\n x: tf.Tensor\n Tensor of each atom's graph features\n\n Returns\n -------\n outputs: tf.Tensor\n Tensor of each molecule's features\n\n \"\"\"\n # Add trainable weights\n self.build()\n atom_features = x[0]\n membership = x[1]\n # Extract atom_features\n graph_features = tf.segment_sum(atom_features, membership)\n # sum all graph outputs\n outputs = self.DAGgraph_step(graph_features, self.W_list, self.b_list)\n return outputs\n\n def DAGgraph_step(self, batch_inputs, W_list, b_list):\n outputs = batch_inputs\n for idw, W in enumerate(W_list):\n outputs = tf.nn.xw_plus_b(outputs, W, b_list[idw])\n outputs = self.activation(outputs)\n return outputs\n","sub_path":"deepchem/nn/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":39939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"116223057","text":"#!/usr/local/Cellar/python/3.7.4_1\n# -*- coding: utf-8 -*-\n# @Time : 2021/2/7 12:33 上午\n# @File : metric.py\n# @Author : 姜小帅\n# @Moto : 良好的阶段性收获是坚持的重要动力之一\n# @Contract: Mason_Jay@163.com\nimport numpy as np\nfrom sklearn.metrics import accuracy_score, f1_score\n\n\ndef flat_accuracy(logits, labels):\n logits = logits.detach().cpu().numpy()\n labels = labels.cpu().numpy()\n pred_flat = np.argmax(logits, axis=1).flatten()\n labels_flat = labels.flatten()\n return accuracy_score(labels_flat, pred_flat)\n\n\ndef flat_f1(logits, labels):\n\n logits = logits.detach().cpu().numpy()\n labels = labels.cpu().numpy()\n pred_flat = np.argmax(logits, axis=1).flatten()\n labels_flat = labels.flatten()\n\n return f1_score(labels_flat, pred_flat)\n\n","sub_path":"ToyBert/metric.py","file_name":"metric.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"80170813","text":"# More complicated functions to implement\n\n# Returns both result of integer division and modulo\ndef int_division(num1, num2):\n div = num1//num2\n mode = num1%num2\n return [div, mode]\n\n# Returns factorial of given number\ndef factorial(num):\n fact = 1\n i = 1\n while i <= num:\n fact = i*fact\n i = i+1\n return fact\n\n# Returns all solutions of given quadratic equation\ndef quadratic_eq(qdr_coef, lin_coef, const):\n disc = (lin_coef**2-4*qdr_coef*const)\n if disc < 0:\n return(\"There is no real solution\")\n elif disc ==0:\n x = -lin_coef/(2*qdr_coef)\n return [x]\n else:\n disc = disc**(1/2)\n x2 = (-lin_coef + disc)/2*qdr_coef\n x1 = (-lin_coef - disc)/2*qdr_coef\n return [x1, x2]\n\n\n\n\n","sub_path":"src/AdvFunctions.py","file_name":"AdvFunctions.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"562561320","text":"import re\nimport socket\nimport threading\nimport time\nimport logging\nimport logstash\n\ntry:\n from setproctitle import setproctitle\nexcept ImportError:\n setproctitle = None\n\ntry:\n from .daemon import Daemon\nexcept ValueError:\n from daemon import Daemon\n\n\n__all__ = ['Server']\n\n\ndef _clean_key(k):\n return re.sub(\n r'[^a-zA-Z_\\-0-9\\.]',\n '',\n re.sub(\n r'\\s+',\n '_',\n k.replace('/', '-').replace(' ', '_')\n )\n )\n\n\nclass Server(object):\n\n def __init__(self, pct_threshold=90, debug=False,\n flush_interval=10000,\n no_aggregate_counters=False,\n expire=0, metadata=None):\n\n if metadata is None:\n metadata = dict()\n\n self.buf = 8192\n self.flush_interval = flush_interval\n self.pct_threshold = pct_threshold\n\n self.no_aggregate_counters = no_aggregate_counters\n self.debug = debug\n self.expire = expire\n\n self.counters = {}\n self.timers = {}\n self.gauges = {}\n\n self.metadata = metadata\n\n def process(self, data):\n # the data is a sequence of newline-delimited metrics\n # a metric is in the form \"name:value|rest\" (rest may have more pipes)\n data.rstrip('\\n')\n\n for metric in data.split('\\n'):\n match = re.match('\\A([^:]+):([^|]+)\\|(.+)', metric)\n\n if match is None:\n debug_log.warning(\n \"Skipping malformed metric: <%s>\" % (metric))\n\n continue\n\n key = _clean_key(match.group(1))\n value = match.group(2)\n rest = match.group(3).split('|')\n mtype = rest.pop(0)\n\n if (mtype == 'ms'):\n self.__record_timer(key, value, rest)\n elif (mtype == 'g'):\n self.__record_gauge(key, value, rest)\n elif (mtype == 'c'):\n self.__record_counter(key, value, rest)\n else:\n debug_log.warning(\n \"Encountered unknown metric type in <%s>\" % (metric))\n\n def __record_timer(self, key, value, rest):\n ts = int(time.time())\n timer = self.timers.setdefault(key, [[], ts])\n timer[0].append(float(value or 0))\n timer[1] = ts\n\n def __record_gauge(self, key, value, rest):\n ts = int(time.time())\n self.gauges[key] = [float(value), ts]\n\n def __record_counter(self, key, value, rest):\n ts = int(time.time())\n sample_rate = 1.0\n\n if len(rest) == 1:\n sample_rate = float(re.match('^@([\\d\\.]+)', rest[0]).group(1))\n\n if sample_rate == 0:\n debug_log.warning(\n \"Ignoring counter with sample rate of zero: <%s>\" % (key))\n\n return\n\n counter = self.counters.setdefault(key, [0, ts])\n counter[0] += float(value or 1) * (1 / sample_rate)\n counter[1] = ts\n\n def on_timer(self):\n \"\"\"Executes flush(). Ignores any errors to make sure one exception\n doesn't halt the whole flushing process.\n \"\"\"\n try:\n self.flush()\n except Exception as e:\n debug_log.exception('Error while flushing: %s', e)\n self._set_timer()\n\n def __flush_counters(self, stats, ts):\n for k, (v, t) in self.counters.items():\n if self.expire > 0 and t + self.expire < ts:\n if self.debug:\n debug_log.debug(\"Expiring counter %s (age: %s)\" % (\n k, ts - t))\n del(self.counters[k])\n\n continue\n v = float(v)\n v = v if self.no_aggregate_counters else v / (\n self.flush_interval / 1000)\n\n if self.debug:\n debug_log.debug(\"Sending %s => count=%s\" % (k, v))\n\n log.info('counter', extra={\n \"label\": \"%s.%s\" % (self.counters_prefix, v),\n \"value\": v,\n \"timestamp\": ts,\n \"dimension\": \"counter\",\n **self.metadata\n })\n\n # Clear the counter once the data is sent\n del(self.counters[k])\n stats += 1\n\n def __flush_gauges(self, stats, ts):\n for k, (v, t) in self.gauges.items():\n if self.expire > 0 and t + self.expire < ts:\n if self.debug:\n debug_log.debug(\"Expiring gauge %s (age: %s)\" % (\n k, ts - t))\n del(self.gauges[k])\n\n continue\n v = float(v)\n\n if self.debug:\n debug_log.debug(\"Sending %s => value=%s\" % (k, v))\n\n log.info('gauge', extra={\n \"label\": \"%s.%s\" % (self.couters_prefix, v),\n \"value\": v,\n \"timestamp\": ts,\n \"dimension\": \"gauge\",\n **self.metadata\n })\n\n stats += 1\n\n def __flush_timers(self, stats, ts):\n for k, (v, t) in self.timers.items():\n if self.expire > 0 and t + self.expire < ts:\n if self.debug:\n debug_log.debug(\"Expiring timer %s (age: %s)\" % (k, ts - t))\n del(self.timers[k])\n\n continue\n\n if len(v) > 0:\n # Sort all the received values. We need it\n # to extract percentiles\n v.sort()\n count = len(v)\n min = v[0]\n max = v[-1]\n\n mean = min\n max_threshold = max\n\n if count > 1:\n thresh_index = int((self.pct_threshold / 100.0) * count)\n max_threshold = v[thresh_index - 1]\n total = sum(v)\n mean = total / count\n\n del(self.timers[k])\n\n if self.debug:\n debug_log.debug(\n \"Sending %s ====> lower=%s, mean=%s, upper=%s, \"\n \"%dpct=%s, count=%s\" % (k, min, mean, max,\n self.pct_threshold,\n max_threshold, count))\n\n log.info('timer', extra={\n \"label\": \"%s.%s\" % (self.counters_prefix, v),\n \"value\": v,\n \"timestamp\": ts,\n \"dimension\": \"timer\",\n \"mean\": mean,\n \"max\": max,\n \"min\": min,\n \"count\": count,\n \"max_threshold\": max_threshold,\n \"pct_threshold\": self.pct_threshold,\n **self.metadata\n })\n\n stats += 1\n\n def flush(self):\n ts = int(time.time())\n stats = 0\n self.__flush_counters(stats, ts)\n self.__flush_gauges(stats, ts)\n self.__flush_timers(stats, ts)\n\n if self.debug:\n debug_log.debug(\"\\n================== Flush completed. \"\n \"Waiting until next flush. \"\n \"Sent out %d metrics =======\" % (stats))\n\n def _set_timer(self):\n self._timer = threading.Timer(self.flush_interval / 1000,\n self.on_timer)\n self._timer.daemon = True\n self._timer.start()\n\n def serve(self, hostname='', port=8125):\n assert type(port) is int, 'port is not an integer: %s' % (port)\n addr = (hostname, port)\n self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self._sock.bind(addr)\n\n import signal\n\n def signal_handler(signal, frame):\n self.stop()\n signal.signal(signal.SIGINT, signal_handler)\n\n self._set_timer()\n\n while 1:\n data, addr = self._sock.recvfrom(self.buf)\n try:\n self.process(data)\n except Exception as error:\n debug_log.error(\"Bad data from %s: %s\", addr, error)\n\n def stop(self):\n self._timer.cancel()\n self._sock.close()\n\n\nclass ServerDaemon(Daemon):\n def run(self, options):\n if setproctitle:\n setproctitle('statsd_to_logstash')\n server = Server(debug=options.debug,\n logstash_host=options.logstash_host,\n logstash_port=options.logstash_port,\n flush_interval=options.flush_interval,\n no_aggregate_counters=options.no_aggregate_counters,\n expire=options.expire, metadata=options.metadata)\n\n server.serve(options.name, options.port)\n\n\ndef run_server():\n import sys\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('-d', '--debug', dest='debug', action='store_true',\n help='debug mode', default=False)\n parser.add_argument('-n', '--name', dest='name',\n help='hostname to run on ', default='')\n parser.add_argument('-p', '--port', dest='port',\n help='port to run on (default: 8125)',\n type=int, default=8125)\n\n parser.add_argument('-lp', '--logstash-port', dest='logstash_port',\n help='Logstash Port (default: 5959)', type=int,\n default=5959)\n parser.add_argument('-lh', '--logstash-host', dest='logstash_host',\n help='Logstash Host (default: localhost)', type=str,\n default='localhost')\n\n parser.add_argument('-m', '--metadata', dest='metadata',\n help='Logstash extra metadata key1=value1,key2=value2',\n type=str)\n\n parser.add_argument(\n '--flush-interval', dest='flush_interval',\n help='how often to send data in millis (default: 10000)', type=int,\n default=10000)\n parser.add_argument(\n '--no-aggregate-counters', dest='no_aggregate_counters',\n help='should statsd report counters as absolute instead of count/sec',\n action='store_true')\n parser.add_argument('-D', '--daemon', dest='daemonize',\n action='store_true', help='daemonize', default=False)\n parser.add_argument('--pidfile', dest='pidfile', action='store',\n help='pid file', default='/var/run/statsd_to_logstash.pid')\n parser.add_argument('--restart', dest='restart', action='store_true',\n help='restart a running daemon', default=False)\n parser.add_argument('--stop', dest='stop', action='store_true',\n help='stop a running daemon', default=False)\n parser.add_argument('--expire', dest='expire',\n help='time-to-live for old stats (in secs)', type=int,\n default=0)\n options = parser.parse_args(sys.argv[1:])\n\n log_level = logging.DEBUG if options.debug else logging.INFO\n\n options.metadata = {\n kv.split('=')[0]: kv.split('=')[1]\n\n for kv in options.metadata.split(',')\n }\n\n log.addHandler(logstash.TCPLogstashHandler(options.logstash_host,\n options.logstash_port))\n debug_log.setLevel(log_level)\n debug_log.info(\"Starting up on %s\" % options.port)\n daemon = ServerDaemon(options.pidfile)\n\n if options.daemonize:\n daemon.start(options)\n elif options.restart:\n daemon.restart(options)\n elif options.stop:\n daemon.stop()\n else:\n daemon.run(options)\n\n\nlog = logging.getLogger(\"statsd.server.report\")\ndebug_log = logging.getLogger(\"statd.server.debug\")\n\nif __name__ == '__main__':\n run_server()\n","sub_path":"statsd_to_logstash/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":11675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"280838981","text":"#!/usr/bin/python3\n\"\"\"\nThis module contains a single class, called Base.\n\"\"\"\nimport json\nimport csv\nfrom tkinter import Tk, Canvas\n\n\nclass Base():\n \"\"\"\n Base class for all the other classes.\n \"\"\"\n __nb_objects = 0\n\n def __init__(self, id=None):\n \"\"\"\n Class constructor.\n \"\"\"\n if id is not None:\n self.id = id\n else:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects\n\n @staticmethod\n def to_json_string(list_dictionaries):\n \"\"\"\n Returns the JSON string representation of the given argument.\n \"\"\"\n if list_dictionaries is None or len(list_dictionaries) == 0:\n return \"[]\"\n else:\n return json.dumps(list_dictionaries)\n\n @classmethod\n def save_to_file(cls, list_objs):\n \"\"\"\n Save the JSON string representationt of list_objs to a file.\n \"\"\"\n list = []\n fn = cls.__name__ + '.json'\n if list_objs is not None:\n for inst in list_objs:\n list.append(inst.to_dictionary())\n with open(fn, 'w', encoding='utf-8') as f:\n f.write(cls.to_json_string(list))\n\n @staticmethod\n def from_json_string(json_string):\n \"\"\"\n Returns the list of the JSON strin representation json_string.\n \"\"\"\n if json_string is None or len(json_string) == 0:\n return []\n else:\n return json.loads(json_string)\n\n @classmethod\n def create(cls, **dictionary):\n \"\"\"\n Returs an instance with all attributes already set.\n \"\"\"\n if cls.__name__ == 'Rectangle':\n dum = cls(10, 10)\n elif cls.__name__ == 'Square':\n dum = cls(10)\n dum.update(**dictionary)\n return dum\n\n @classmethod\n def load_from_file(cls):\n \"\"\"\n Returns a list of instances.\n \"\"\"\n list = []\n fn = cls.__name__ + '.json'\n try:\n with open(fn, 'r') as f:\n data = cls.from_json_string(f.read())\n for dict in data:\n list.append(cls.create(**dict))\n return list\n except:\n return list\n\n @classmethod\n def save_to_file_csv(cls, list_objs):\n \"\"\"\n Serialiezes to CSV.\n \"\"\"\n fn = cls.__name__ + '.csv'\n objs = []\n with open(fn, 'w', newline='') as f:\n writer = csv.writer(f, delimiter=',')\n if list_objs is not None:\n for obj in list_objs:\n l = []\n x = obj.x\n y = obj.y\n id = obj.id\n if cls.__name__ == 'Square':\n size = obj.size\n l = [id, size, x, y]\n else:\n height = obj.height\n width = obj.width\n l = [id, width, height, x, y]\n objs.append(l)\n for obj in objs:\n writer.writerow(obj)\n\n @classmethod\n def load_from_file_csv(cls):\n \"\"\"\n Deserializes from CSV.\n \"\"\"\n list = []\n fn = cls.__name__ + '.csv'\n try:\n with open(fn, 'r') as f:\n reader = csv.reader(f, delimiter=',')\n for row in reader:\n if cls.__name__ == 'Square':\n d = {\n 'id': int(row[0]),\n 'size': int(row[1]),\n 'x': int(row[2]),\n 'y': int(row[3])\n }\n else:\n d = {\n 'id': int(row[0]),\n 'width': int(row[1]),\n 'height': int(row[2]),\n 'x': int(row[3]),\n 'y': int(row[4])\n }\n list.append(cls.create(**d))\n return list\n except:\n return list\n\n def draw(list_rectangles, list_squares):\n \"\"\"\n Draws Rectangles and Squares.\n \"\"\"\n master = Tk()\n c = Canvas(master, width=800, height=800, bg=\"blue\")\n if list_rectangles is not None and len(list_rectangles) != 0:\n for rect in list_rectangles:\n r = rect.to_dictionary()\n h = r.get('height')\n w = r.get('width')\n x = r.get('x', 0)\n y = r.get('y', 0)\n c.create_line(x, y, (x + w), y)\n c.create_line(x + w, y, x + w, y + h)\n c.create_line(x + w, y + h, x, y + h)\n c.create_line(x, y + h, x, y)\n if list_squares is not None and len(list_squares) != 0:\n for sq in list_squares:\n r = sq.to_dictionary()\n h = r.get('size')\n w = r.get('size')\n x = r.get('x', 0)\n y = r.get('y', 0)\n c.create_line(x, y, (x + w), y)\n c.create_line(x + w, y, x + w, y + h)\n c.create_line(x + w, y + h, x, y + h)\n c.create_line(x, y + h, x, y)\n c.pack()\n master.mainloop()\n","sub_path":"0x0C-python-almost_a_circle/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":5288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"438563827","text":"# -*- coding: utf-8 -*-\n\nfrom blog.models import RequestPath\n\n\nIGNORELIST = (\n '/media',\n '/media/css'\n '/media/js'\n)\n\n\nclass CategoryMiddleware(object):\n def process_response(self, request, response):\n full_path = request.get_full_path()\n if request.POST:\n request_type = 'POST'\n else:\n request_type = 'GET'\n for ignore in IGNORELIST:\n if ignore in full_path:\n return response\n path = RequestPath.objects.create(path=request.get_full_path(), request_type=request_type)\n return response\n","sub_path":"blog/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"191423108","text":"from datetime import date\nimport csv\nimport sqlite3\nimport os\n\nStock_file='Data_Stocks.csv'\nData_Bonds='Data_Bonds.csv'\n\nclass Stock:\n\t\n\tdef __init__(self,stock_id,stock_symbol,no_of_shares,purchase_price,current_value,purchase_date):\n\t\tself.stock_id=stock_id\n\t\tself.no_of_shares=no_of_shares\n\t\tself.stock_symbol=stock_symbol\n\t\tself.purchase_price=purchase_price\n\t\tself.current_value=current_value\n\t\tself.purchase_date=purchase_date\n\t\tself.f_date=date(2019,4,28)\n\n\n\tdef calculate_Earning_or_loss(self):\n\t\treturn round((self.current_value-self.purchase_price)*self.no_of_shares,1)\n\n\tdef calculate_yearly_earning_or_loss(self):\n\t\tz=self.purchase_date.split('/')\n\t\tprint(z)\n\t\tcurr_date=date(int(z[2]),int(z[0]),int(z[1]))\n\t\tdiff_date=str(self.f_date - curr_date)\n\t\tdays_count=float(diff_date.split('days')[0])/365.0\n\t\treturn round(((self.current_value - self.purchase_price)/float(self.purchase_price)/days_count),4)*100\n\tdef print_stock_detail(self):\n\t\tstr1='| {:12} | {:14} | {:14} | {:16} | {:15} | \\n'.format(self.stock_symbol,self.no_of_shares,self.purchase_price,self.current_value,self.purchase_date)\n\t\treturn str1\n\n\tdef print_stock_earnings(self):\n\t\ty=float(\"%.2f\" %self.calculate_yearly_earning_or_loss())\n\t\tstr1='| {:14} | {:11} | {:16} | {:13} \\n'.format(self.stock_symbol, self.no_of_shares, self.calculate_Earning_or_loss(),str(y)+'%')\n\t\treturn str1\n\tdef stock_earning(self):\n\t\ty=float(\"%.2f\" %self.calculate_yearly_earning_or_loss())\n\t\treturn self.calculate_Earning_or_loss(),y\n\n\t# def get_stock_symbol()\n\n\n\n\n\n\nclass Bonds(Stock):\n\t\"\"\"docstring for Bonds\"\"\"\n\tdef __init__(self, bond_id,stock_symbol,no_of_shares,purchase_price,current_value,purchase_date,coupon,yield_percentage):\n\t\tsuper(Bonds, self).__init__(bond_id,stock_symbol,no_of_shares,purchase_price,current_value,purchase_date)\n\t\tself.coupon=coupon\n\t\tself.yield_percentage=yield_percentage\n\n\t# i could have added that in the constructor as well but i am doing it this way \n\n\tdef set_coupon_price(self,coupon):\n\t\tself.coupon=coupon\n\t\n\tdef set_yield_percentage(self,yield_percentage):\n\t\tself.yield_percentage=yield_percentage\n\t\n\tdef get_coupon_price(self):\n\t\treturn self.coupon\n\n\tdef get_yield_percentage(self):\n\t\treturn self.yield_percentage\n\n\tdef print_bond_info(self):\n \t\tstr_1='| {:12} | {:14} | {:14} | {:16} | {:15} | {:16}| {:14} |\\n'.format(self.stock_symbol,self.no_of_shares,self.purchase_price,self.current_value,self.coupon,str(self.yield_percentage)+'%',self.purchase_date)\n \t\treturn str_1 \n\tdef print_bond_earning(self):\n \t\ty=float(\"%.2f\" %self.calculate_yearly_earning_or_loss())\n \t\tstr1='| {:14} | {:11} | {:16} | {:13} \\n'.format(self.stock_symbol, self.no_of_shares, self.calculate_Earning_or_loss(),str(y)+'%')\n \t\treturn str1\n\n\tdef bond_earning(self):\n \t\ty=float(\"%.2f\" %self.calculate_yearly_earning_or_loss())\n \t\treturn self.calculate_Earning_or_loss(),y\n\n\n\nclass Investor():\n\t\"\"\"docstring for Investor\"\"\"\n\tdef __init__(self, Id,address,phone_number):\n\t\tself.Id=Id\n\t\tself.address=address\n\t\tself.phone_number=phone_number\n\n\tdef get_phone_number(self):\n\t\treturn self.phone_number\n\n\tdef get_address(self):\n\t\treturn self.address\n\n\tdef display_info(self):\n\t\tstr1='| {:14} | {:11} | {:16} | \\n'.format(self.Id,self.address,self.phone_number)\n\t\treturn str1\n\t\t\ndef printing_stocks_info(list_stocks):\n\tcwd=os.getcwd()\n\tprint(cwd)\n\tfile_path1=os.path.join(cwd,'Info/Stocks_INFO_table.db')\n\tdb_file_name=file_path1\n\tconn=sqlite3.connect(db_file_name)\n\t# Creating Stock table \n\ttry:\t\n\t\tconn.execute('''CREATE TABLE STOCKSINFO \n\t\t\t\t\t\t( ID INT PRIMARY KEY NOT NULL,\n\t\t\t\t\t\t SYMBOL TEXT NOT NULL,\n\t\t\t\t\t\t NO_SHARES INT NOT NULL,\n\t\t\t\t\t\t PURCHASE_PRICE INT NOT NULL,\n\t\t\t\t\t\t CURRENT_PRICE INT NOT NULL,\n\t\t\t\t\t\t PURCHASE_DATE TEXT NOT NULL);''')\n\texcept Exception as e:\n\t\tprint(\"Create table error\",e)\n\t# Inserting in the table\n\tfor x in list_stocks:\n\t\tstatement='''INSERT INTO STOCKSINFO(ID,SYMBOL,NO_SHARES,PURCHASE_PRICE,CURRENT_PRICE,PURCHASE_DATE) VALUES ({},{},{},{},{},{})'''.format(x.stock_id,\"'\"+x.stock_symbol+\"'\",x.no_of_shares,x.purchase_price,x.current_value,\"'\"+x.purchase_date+\"'\")\n\t\t# print(statement)\n\t\ttry:\n\t\t\tconn.execute(statement)\n\t\texcept Exception as e:\n\t\t\t# print(\"Insert Error\",e)\n\t\t\tz=0\n\tconn.commit()\n\tconn.close()\n\n\tfile_path2=os.path.join(cwd,'Info/Stocks_earning_loss_table.db')\n\tdb_file_name=file_path2\n\tconn1=sqlite3.connect(db_file_name)\n\t# Creating Stock table \n\ttry:\t\n\t\tconn1.execute('''CREATE TABLE STOCKSLOSS\n\t\t\t\t\t\t( ID INT PRIMARY KEY NOT NULL,\n\t\t\t\t\t\t SYMBOL TEXT NOT NULL,\n\t\t\t\t\t\t NO_SHARES INT NOT NULL,\n\t\t\t\t\t\t EARNING_LOSS INT NOT NULL,\n\t\t\t\t\t\t YEARLY_EARNING_LOSS INT NOT NULL);''')\n\texcept Exception as e:\n\t\tprint(\"Create table error\",e)\n\t# Inserting in the table\n\tfor x in list_stocks:\n\t\tloss,year_loss=x.stock_earning()\n\t\tstatement='''INSERT INTO STOCKSLOSS(ID,SYMBOL,NO_SHARES,EARNING_LOSS,YEARLY_EARNING_LOSS) VALUES ({},{},{},{},{})'''.format(x.stock_id,\"'\"+x.stock_symbol+\"'\",x.no_of_shares,loss,year_loss)\n\t\ttry:\n\t\t\tconn1.execute(statement)\n\t\texcept Exception as e:\n\t\t\t# print(\"Loss Insert Error\",e)\n\t\t\tz=0\n\tconn1.commit()\n\tconn1.close()\n\n\n\ndef print_bond_info(list_bonds):\n\tdb_file_name='Bonds_INFO_table.db'\n\tconn=sqlite3.connect(db_file_name)\n\t# Creating Stock table \n\ttry:\t\n\t\tconn.execute('''CREATE TABLE BONDSINFO \n\t\t\t\t\t\t( ID INT PRIMARY KEY NOT NULL,\n\t\t\t\t\t\t SYMBOL TEXT NOT NULL,\n\t\t\t\t\t\t NO_SHARES INT NOT NULL,\n\t\t\t\t\t\t PURCHASE_PRICE INT NOT NULL,\n\t\t\t\t\t\t CURRENT_PRICE INT NOT NULL,\n\t\t\t\t\t\t COUPON_PRICE INT NOT NULL,\n\t\t\t\t\t\t YEILD_PERCENT INT NOT NULL,\n\t\t\t\t\t\t PURCHASE_DATE TEXT NOT NULL);''')\n\texcept Exception as e:\n\t\t# print(\"Create table error\",e)\n\t\tz=0\n\t# Inserting in the table\n\tfor x in list_bonds:\n\t\tstatement='''INSERT INTO BONDSINFO(ID,SYMBOL,NO_SHARES,PURCHASE_PRICE,CURRENT_PRICE,COUPON_PRICE,YEILD_PERCENT,PURCHASE_DATE) VALUES ({},{},{},{},{},{},{},{})'''.format(x.stock_id,\"'\"+x.stock_symbol+\"'\",x.no_of_shares,x.purchase_price,x.current_value,x.coupon,x.yield_percentage,\"'\"+x.purchase_date+\"'\")\n\t\t# print(statement)\n\t\ttry:\n\t\t\tconn.execute(statement)\n\t\texcept Exception as e:\n\t\t\tprint(\"Insert Error\",e)\n\tconn.commit()\n\tconn.close()\n\n\n\tdb_file_name='Bonds_earning_loss_table.db'\n\tconn1=sqlite3.connect(db_file_name)\n\t# Creating Stock table \n\ttry:\t\n\t\tconn1.execute('''CREATE TABLE BONDSLOSS\n\t\t\t\t\t\t( ID INT PRIMARY KEY NOT NULL,\n\t\t\t\t\t\t SYMBOL TEXT NOT NULL,\n\t\t\t\t\t\t QUANTITY INT NOT NULL,\n\t\t\t\t\t\t EARNING_LOSS INT NOT NULL,\n\t\t\t\t\t\t YEARLY_EARNING_LOSS INT NOT NULL);''')\n\texcept Exception as e:\n\t\tprint(\"Create table error\",e)\n\t# Inserting in the table\n\tfor x in list_bonds:\n\t\tloss,year_loss=x.bond_earning()\n\t\tstatement='''INSERT INTO BONDSLOSS(ID,SYMBOL,QUANTITY,EARNING_LOSS,YEARLY_EARNING_LOSS) VALUES ({},{},{},{},{})'''.format(x.stock_id,\"'\"+x.stock_symbol+\"'\",x.no_of_shares,loss,year_loss)\n\t\ttry:\n\t\t\tconn1.execute(statement)\n\t\texcept Exception as e:\n\t\t\t# print(\"Loss Insert Error\",e)\n\t\t\tz=0\n\tconn1.commit()\n\tconn1.close()\n\n\n\n\ndef print_investor_info(list_investor):\n\tdb_file_name='Investor_INFO_table.db'\n\tconn=sqlite3.connect(db_file_name)\n\t# Creating Stock table \n\ttry:\t\n\t\tconn.execute('''CREATE TABLE INVESTORSINFO \n\t\t\t\t\t\t( ID INT PRIMARY KEY NOT NULL,\n\t\t\t\t\t\t ADDRESS TEXT NOT NULL,\n\t\t\t\t\t\t PHONE INT NOT NULL);''')\n\texcept Exception as e:\n\t\tprint(\"Create table error\",e)\n\t# Inserting in the table\n\tfor x in list_investor:\n\t\tstatement='''INSERT INTO INVESTORSINFO(ID,ADDRESS,PHONE) VALUES ({},{},{})'''.format(x.Id,\"'\"+x.address+\"'\",x.phone_number)\n\t\t# print(statement)\n\t\ttry:\n\t\t\tconn.execute(statement)\n\t\texcept Exception as e:\n\t\t\tprint(\"Insert Error\",e)\n\tconn.commit()\n\tconn.close()\n\ndef load_stocks():\n\tcwd=os.getcwd()\n\tprint(cwd)\n\tfile_path1=os.path.join(cwd,'Info/Data_Stocks.csv')\n\tStock_file=file_path1\n\tlist_stocks=[]\n\twith open(Stock_file,'r',encoding='utf8') as stk_file:\n\t\tcsvreader=csv.reader(stk_file)\n\t\tfields=next(csvreader)\n\t\tId=1\n\t\tfor row in csvreader:\n\t\t\tstk_name=row[0]\n\t\t\t# print(isinstance(stk_name,str))\n\t\t\tif isinstance(stk_name, str)==False:\n\t\t\t\tprint('Stock Name is not valid, please enter the new Stock Name for the entry ',row)\n\t\t\t\tstk_name=input('Enter the New Stock Name')\n\t\t\t\n\t\t\ttry:\n\t\t\t\tNo_of_shares=int(row[1])\n\t\t\texcept Exception as e:\n\t\t\t\tprint('No_of_shares is not valid, please enter the New No_of_shares for the entry ',row)\n\t\t\t\tNo_of_shares=input('Enter the New No_of_shares')\n\t\t\ttry:\n\t\t\t\tPurchase_price=float(row[2])\n\t\t\texcept Exception as e:\n\t\t\t\tprint('Purchase_price is not valid, please enter the new Purchase_price for the entry ',row)\n\t\t\t\tPurchase_price=input('Enter the New Purchase_price')\t\t\n\t\t\t\n\t\t\ttry:\n\t\t\t\tCurrent_price=float(row[3])\n\t\t\texcept Exception as e:\n\t\t\t\tprint('Current_price is not valid, please enter the new Current_price for the entry ',row)\n\t\t\t\tCurrent_price=input('Enter the New Current_price')\n\t\t\t\n\t\t\tPurchase_date=row[4]\n\t\t\tif isinstance(Purchase_date, str)==False:\n\t\t\t\tprint('Purchase_date is not valid, please enter the new Purchase_date for the entry ',row)\n\t\t\t\tPurchase_date=input('Enter the New Purchase_date')\t\n\t\t\tlist_stocks.append(Stock(Id,stk_name,No_of_shares,Purchase_price,Current_price,Purchase_date)) \n\t\t\tId=Id+1\n\tprinting_stocks_info(list_stocks)\n\ndef load_bonds():\n\tlist_bonds=[]\n\twith open(Data_Bonds,'r',encoding='utf8') as bnd_file:\n\t\tcsvreader=csv.reader(bnd_file)\n\t\tfields=next(csvreader)\n\t\tId=1\n\t\tfor row in csvreader:\n\t\t\tbnd_name=row[0]\n\t\t\tif isinstance(bnd_name, str)==False:\n\t\t\t\tprint('Stock Name is not valid, please enter the new Stock Name for the entry ',row)\n\t\t\t\tbnd_name=input('Enter the New Stock Name')\n\t\t\tNo_of_shares=row[1]\n\t\t\ttry:\n\t\t\t\tNo_of_shares=int(row[1])\n\t\t\texcept Exception as e:\n\t\t\t\tprint('No_of_shares is not valid, please enter the New No_of_shares for the entry ',row)\n\t\t\t\tNo_of_shares=input('Enter the New No_of_shares')\n\t\t\ttry:\n\t\t\t\tPurchase_price=float(row[2])\n\t\t\texcept Exception as e:\n\t\t\t\tprint(e)\n\t\t\t\tprint('Purchase_price is not valid, please enter the new Purchase_price for the entry ',row)\n\t\t\t\tPurchase_price=input('Enter the New Purchase_price')\t\t\n\t\t\t\n\t\t\ttry:\n\t\t\t\tCurrent_price=float(row[3])\n\t\t\texcept Exception as e:\n\t\t\t\tprint('Current_price is not valid, please enter the new Current_price for the entry ',row)\n\t\t\t\tCurrent_price=input('Enter the New Current_price')\n\t\t\t\n\n\t\t\tPurchase_date=row[4]\n\t\t\tif isinstance(Purchase_date, str)==False:\n\t\t\t\tprint('Purchase_date is not valid, please enter the new Purchase_date for the entry ',row)\n\t\t\t\tPurchase_date=input('Enter the New Purchase_date')\t\n\t\t\t\n\t\t\ttry:\n\t\t\t\tCoupon=float(row[5])\n\t\t\texcept Exception as e:\n\t\t\t\tprint('Coupon is not valid, please enter the new Coupon for the entry ',row)\n\t\t\t\tCoupon=input('Enter the New Coupon')\t\n\t\t\t\n\t\t\ttry:\n\t\t\t\tYield=float(row[6])\n\t\t\texcept Exception as e:\n\t\t\t\tprint('Yield is not valid, please enter the new Yield for the entry ',row)\n\t\t\t\tYield=input('Enter the New Yield')\t\n\t\t\t\n\t\t\n\n\t\t\tlist_bonds.append(Bonds(Id,bnd_name,No_of_shares,Purchase_price,Current_price,Purchase_date,Coupon,Yield))\n\t\t\t\n\t\t\t\n\t\t\tId=Id+1\n\tprint_bond_info(list_bonds)\n\ndef load_investor():\n\tlist_investor=[]\n\tlist_investor.append(Investor(1,\"Address1\",704542525))\n\tprint_investor_info(list_investor)\n\n\n\n\n\n\n\n\t\t","sub_path":"StockApp/StockWebapp/Info/stockapi.py","file_name":"stockapi.py","file_ext":"py","file_size_in_byte":11057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"101244688","text":"\n\nfrom xai.brain.wordbase.nouns._writer import _WRITER\n\n#calss header\nclass _WRITERS(_WRITER, ):\n\tdef __init__(self,): \n\t\t_WRITER.__init__(self)\n\t\tself.name = \"WRITERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"writer\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_writers.py","file_name":"_writers.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"165525592","text":"from init_env import init_environment\n\nenv = init_environment(\"\")\n\nimport os\n\nOSENV = os.environ\nCERNLIB = OSENV['CERNLIB']\nenv.Append(LIBPATH = [CERNLIB])\n\nlibs = [\n 'mathlib', 'packlib'\n ]\ncernlibs = []\nfor lib in libs:\n\tcernlibs.append(lib)\nenv.Append(LIBS = cernlibs)\n\nsources = Split(\"\"\"exclurad.f\n multipole_amps.F \"\"\")\n\n\nenv.Program(source = sources, target = 'exclurad')\n\n","sub_path":"radCorr/exclurad/SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"316362310","text":"#!/usr/bin/env python\n\nfrom math import log\nfrom collections import defaultdict\n\n\nclass tfidf:\n def __init__(self):\n self.documents = {}\n self.tokens = defaultdict(lambda: defaultdict(int))\n\n def add_document(self, tokens):\n document_id = len(self.documents)\n self.documents[document_id] = tokens\n for token in tokens:\n self.tokens[token][document_id] += 1\n return document_id\n\n def search(self, token):\n results = [{\n 'document_id': document_id\n } for document_id in self.tokens[token].keys()]\n\n for result in results:\n document_id = result['document_id']\n tf = float(self.tokens[token][document_id]) / len(self.documents[\n document_id])\n idf = log(float(len(self.documents)) / len(self.tokens[token]))\n result['score'] = tf * idf\n result['body'] = self.documents[document_id]\n\n results.sort(reverse=True, key=lambda result: result['score'])\n return results\n","sub_path":"python/tfidf.py","file_name":"tfidf.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"352125022","text":"from collections import OrderedDict\nfrom opengever.document.events import FileAttachedToEmailEvent\nfrom opengever.dossier.events import DossierAttachedToEmailEvent\nfrom opengever.officeconnector import _\nfrom opengever.officeconnector.helpers import create_oc_url\nfrom opengever.officeconnector.helpers import group_payloads_by_parent\nfrom opengever.officeconnector.helpers import is_officeconnector_attach_feature_enabled # noqa\nfrom opengever.officeconnector.helpers import is_officeconnector_checkout_feature_enabled # noqa\nfrom opengever.officeconnector.helpers import parse_document_uids\nfrom opengever.oneoffixx import is_oneoffixx_feature_enabled\nfrom opengever.workspace import is_workspace_feature_enabled\nfrom plone import api\nfrom plone.protect import createToken\nfrom plone.rest import Service\nfrom zExceptions import Forbidden\nfrom zExceptions import NotFound\nfrom zope.annotation.interfaces import IAnnotations\nfrom zope.event import notify\nfrom zope.i18n import translate\nimport json\n\n\nclass OfficeConnectorURL(Service):\n \"\"\"Create oc: URLs for javascript to fetch and pass to the OS.\"\"\"\n\n def render(self):\n pass\n\n def create_officeconnector_url_json(self, payload):\n self.request.response.setHeader('Content-Type', 'application/json')\n\n url = create_oc_url(self.request, self.context, payload)\n\n if url:\n return json.dumps(dict(url=url))\n\n # Fail per default\n self.request.response.setStatus(500)\n\n message = _(\n u'error_oc_url_too_long',\n default=(\n u\"Unfortunately it's not currently possible to attach this \"\n u'many documents. Please try again with fewer documents '\n u'selected.'\n ),\n )\n\n return json.dumps(dict(\n error=dict(\n message=translate(\n message,\n context=self.request,\n )\n )\n ))\n\n\nclass OfficeConnectorAttachURL(OfficeConnectorURL):\n \"\"\"Create oc: URLs for javascript to fetch and pass to the OS.\n\n Instruct where to fetch an OfficeConnector 'attach' action payload for this\n document.\n \"\"\"\n\n def render(self):\n if is_officeconnector_attach_feature_enabled():\n payload = {'action': 'attach'}\n return self.create_officeconnector_url_json(payload)\n\n # Fail per default\n raise NotFound\n\n\nclass OfficeConnectorCheckoutURL(OfficeConnectorURL):\n \"\"\"Create oc: URLs for javascript to fetch and pass to the OS.\n\n Instruct where to fetch an OfficeConnector 'checkout' action payload for\n this document.\n \"\"\"\n\n def render(self):\n if self.context.is_collaborative_checkout():\n # Documents currently being edited in Office Online must not be\n # edited in Office Connector, even if checked out by the same user\n raise Forbidden\n\n if is_officeconnector_checkout_feature_enabled():\n payload = {'action': 'checkout'}\n\n return self.create_officeconnector_url_json(payload)\n\n # Fail per default\n raise NotFound\n\n\nclass OfficeConnectorOneOffixxURL(OfficeConnectorURL):\n \"\"\"Create oc: URLs for javascript to fetch and pass to the OS.\n\n Instruct where to fetch an OfficeConnector 'oneoffixx' action payload for\n this document.\n \"\"\"\n\n def render(self):\n if is_oneoffixx_feature_enabled():\n payload = {'action': 'oneoffixx'}\n\n return self.create_officeconnector_url_json(payload)\n\n # Fail per default\n raise NotFound\n\n\nclass OfficeConnectorPayload(Service):\n \"\"\"Issue JSON instruction payloads for OfficeConnector.\"\"\"\n\n def __init__(self, context, request):\n super(OfficeConnectorPayload, self).__init__(context, request)\n self.uuids = json.loads(request['BODY'])\n\n @staticmethod\n def document_is_valid(document):\n return document and (document.is_shadow_document() or document.has_file())\n\n def get_base_payloads(self):\n # Require an authenticated user\n if not api.user.is_anonymous():\n documents = OrderedDict()\n\n for uuid in self.uuids:\n document = api.content.get(UID=uuid)\n\n if self.document_is_valid(document):\n documents[uuid] = document\n\n else:\n # Fail per default\n raise Forbidden\n\n if documents:\n payloads = []\n\n for uuid, document in documents.items():\n payloads.append(\n {\n 'csrf-token': createToken(),\n 'document-url': document.absolute_url(),\n 'document': document,\n 'uuid': uuid,\n 'version': document.get_current_version_id(),\n }\n )\n\n return payloads\n\n # Fail per default\n raise NotFound\n\n def render(self):\n self.request.response.setHeader('Content-type', 'application/json')\n return json.dumps(self.get_base_payload())\n\n\nclass OfficeConnectorAttachIsMailFileable(OfficeConnectorPayload):\n \"\"\"Check if copy of mail with attachments can be filed in dossier.\n\n Returns True if the document selection allows for a copy of the\n mail to be filed, and False otherwise.\n\n Reasons for why the mail can't be filed could be because the containing\n dossier is in a closed state, or the document selection is spread across\n multiple dossiers, etc.\n\n This determination is made by using the same strategy to find valid\n parent containers as the OfficeConnectorAttachPayload endpoint below.\n\n This is not a regular OfficeConnectorPayload view. It's not getting called\n by OC, but the gever-ui instead. It expects a {\"documents\": list_of_paths}\n mapping in the request body, same as the OfficeConnectorURL endpoints.\n It then resolves those paths to UUIDs, and only then starts using\n functionality from OfficeConnectorPayload to process them as payloads.\n \"\"\"\n\n def __init__(self, context, request):\n super(OfficeConnectorAttachIsMailFileable, self).__init__(context, request)\n self.uuids = []\n\n def render(self):\n self.request.response.setHeader('Content-type', 'application/json')\n\n self.uuids = parse_document_uids(self.request, self.context, action='attach')\n if not self.uuids:\n raise NotFound\n\n payloads = self.get_base_payloads()\n group_payloads_by_parent(payloads, self.request)\n\n # This mirrors the logic that OC does on the client side: Only add\n # BCC if there's exactly one unique BCC address across payloads.\n bcc_addresses = {payload.get('bcc') for payload in payloads}\n if len(bcc_addresses) == 1 and bcc_addresses.pop():\n return json.dumps({'fileable': True})\n\n return json.dumps({'fileable': False})\n\n\nclass OfficeConnectorAttachPayload(OfficeConnectorPayload):\n \"\"\"Issue JSON instruction payloads for OfficeConnector.\n\n Consists of the minimal instruction set with which to perform an attach to\n email action.\n \"\"\"\n def render(self):\n self.request.response.setHeader('Content-type', 'application/json')\n payloads = self.get_base_payloads()\n payloads_by_parent = group_payloads_by_parent(payloads, self.request)\n\n for container_uuid, payloads in payloads_by_parent.items():\n\n if container_uuid and not is_workspace_feature_enabled():\n dossier = api.content.get(UID=container_uuid)\n documents = [p['document'] for p in payloads]\n notify(DossierAttachedToEmailEvent(dossier, documents))\n\n for payload in payloads:\n document = payload['document']\n payload['title'] = document.title_or_id()\n payload['content-type'] = document.get_file().contentType\n payload['download'] = document.get_download_view_name()\n payload['filename'] = document.get_filename()\n del payload['document']\n notify(FileAttachedToEmailEvent(document))\n\n return json.dumps(payloads)\n\n\nclass OfficeConnectorCheckoutPayload(OfficeConnectorPayload):\n \"\"\"Issue JSON instruction payloads for OfficeConnector.\n\n Consists of the minimal instruction set with which to perform a full\n checkout checkin cycle for a file attached to a document.\n \"\"\"\n\n def render(self):\n payloads = self.get_base_payloads()\n\n # Upload API will be included as a registry setting in the future when\n # the plone.api endpoint gets made - for now we've made a custom upload\n # form.\n for payload in payloads:\n # A permission check to verify the user is also able to upload\n document = payload.pop('document')\n authorized = api.user.has_permission('Modify portal content', obj=document)\n\n if authorized:\n if document.is_shadow_document():\n # Oneoffixx is only used for .docx files in opengever.core\n payload['content-type'] = IAnnotations(document).get(\"content-type\")\n else:\n payload['content-type'] = document.get_file().contentType\n\n payload['download'] = document.get_download_view_name()\n\n # for oneoffixx, we checkout the document to fall in the normal\n # checkout-checkin cycle.\n if document.is_shadow_document():\n payload['filename'] = IAnnotations(document).get(\"filename\")\n else:\n payload['filename'] = document.get_filename()\n\n reauth_querystring = '&'.join((\n '_authenticator={}'.format(payload.pop('csrf-token')),\n 'mode=external',\n 'reauth=1',\n ))\n payload['reauth'] = '?'.join(('@@checkout_documents', reauth_querystring))\n payload['status'] = 'status'\n payload['lock'] = '@lock'\n payload['checkout'] = '@checkout'\n payload['upload'] = '@tus-replace'\n payload['checkin'] = '@checkin'\n payload['unlock'] = '@unlock'\n payload['cancelcheckout'] = '@cancelcheckout'\n payload['has_pending_changes'] = document.has_pending_changes\n\n else:\n # Fail per default\n raise Forbidden\n\n self.request.response.setHeader('Content-type', 'application/json')\n\n return json.dumps(payloads)\n\n\nclass OfficeConnectorOneOffixxPayload(OfficeConnectorPayload):\n \"\"\"Issue JSON instruction payloads for OfficeConnector.\n\n Contains the instruction set to generate a document from a oneoffixx\n template (connect-xml), then checkout the corresponding document (checkout-url)\n to open the created document in an editor. From there the normal checkout,\n checkin cycle can begin.\n \"\"\"\n\n @staticmethod\n def document_is_valid(document):\n return document and document.is_shadow_document()\n\n def render(self):\n payloads = self.get_base_payloads()\n\n for payload in payloads:\n # A permission check to verify the user is also able to upload\n authorized = api.user.has_permission(\n 'Modify portal content',\n obj=payload['document'],\n )\n\n if authorized:\n document = payload['document']\n payload['filename'] = IAnnotations(document).get(\"filename\")\n # Oneoffixx is only used for .docx files in opengever.core\n payload['content-type'] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'\n del payload['document']\n payload['connect-xml'] = '@@oneoffix_connect_xml'\n\n else:\n # Fail per default\n raise Forbidden\n\n self.request.response.setHeader('Content-type', 'application/json')\n\n return json.dumps(payloads)\n","sub_path":"opengever/officeconnector/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":12175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"100973208","text":"from collections import Counter\n\n\n# function that loads a lexicon of positive words to a set and returns the set\ndef loadLexicon(fname):\n newLex = set()\n lex_conn = open(fname)\n # add every word in the file to the set\n for line in lex_conn:\n newLex.add(line.strip()) # remember to strip to remove the lin-change character\n lex_conn.close()\n return newLex\n\n\ndef run(path):\n answer = {}\n negLex = loadLexicon('negative-words.txt')\n fin = open(path)\n for line in fin:\n line = line.lower().strip()\n words = line.split(' ')\n res = {}\n for index in [i for i, v in enumerate(words) if v == 'phone']:\n prev_word = words[index - 1]\n if prev_word in negLex:\n res.update({prev_word: 1})\n answer = dict(Counter(res) + Counter(answer))\n\n fin.close()\n return dict(answer)\n\n\nif __name__ == \"__main__\":\n print(run('textfile'))\n","sub_path":"week5_0926/textminer/senticounter.py","file_name":"senticounter.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"185113078","text":"from django.urls import path\n\nfrom users import views\n\napp_name = 'users'\n\nurlpatterns = [\n path('login/', views.login_user, name='login'),\n path('logout/', views.logout_user, name='logout'),\n path('register/', views.registration_view, name='register'),\n path('profile/', views.user_profile, name='profile')\n]\n","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"555853038","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 18-5-30 下午4:55\n\n@author: ronghuaiyang\n\"\"\"\nfrom __future__ import print_function\n\nimport argparse\nimport logging\nimport os\nimport random\nimport time\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import DataLoader\n\nimport utils\nfrom config import Config\nfrom utils.dataset import get_dataset\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_tester(type, opt, device):\n # 准备数据,如果mode是\"mnist\",使用MNIST数据集\n # 可视化,其实就是使用MNIST数据集,训练一个2维向量\n # mnist数据,用于可视化的测试\n if type.startswith(\"mnist\"):\n logger.info(\"构建Mnist测试类\")\n tester = MnistTester(opt, device)\n else:\n logger.info(\"构建人脸测试类\")\n tester = FaceTester(device)\n return tester\n\n\nclass Tester():\n \"\"\"\n 为了适配2种测试:一种是人脸的,一种是实验用的MNIST(为了可视化)\n \"\"\"\n\n def acc(self, model, metric, opt):\n pass\n\n def calculate_features(self, model, opt):\n pass\n\n\nclass MnistTester(Tester):\n def __init__(self, opt, device):\n dataset = get_dataset(train=False, type='mnist', opt=opt)\n self.data_loader = DataLoader(dataset,\n batch_size=32, # 测试 = 3 | 32\n shuffle=True,\n num_workers=0)\n self.device = device\n\n def acc(self, model, opt):\n correct = 0\n start = time.time()\n for index, data in enumerate(self.data_loader):\n imgs_of_batch, label = data\n # bugfix:...found at least two devices, cuda:0 and cpu!\n imgs_of_batch, label = imgs_of_batch.to(self.device), label.to(self.device)\n\n # 预测\n with torch.no_grad():\n output = model.predict(imgs_of_batch)\n\n # 本来还想要再经过一下arcface的metrics,也就是论文的那个s*cos(θ+m),\n # 但是,突然反思了一下,觉得不对,因为那个是需要同时传入label,我靠,我用网络就是为了argmax得到label,你让我传给你label,什么鬼?\n # 显然我是理解错了,对比看了真实人脸的acc代码,在下面FaceTest.acc的实现里,test_performance方法里,\n # 那个根本没有用metrics(也就是arcface的loss),而是直接用resnet的输出,算出两个不同的x1、x2的夹角,\n # 且通过一堆人脸(6000个)得到一个阈值,来判断是不是同一人脸,人家是在做这事!\n #\n # 而我们这个acc,就是要简单的判断是哪个数字,不是要判断2张图是不是同一数字啊。\n\n # 我只要看从resnet出来的向量就可以,argmax的那个就是最像的类别(不用softmax了,softmax只是为了放大而已)\n pred = output.max(1, keepdim=True)[1]\n\n correct += pred.eq(label.view_as(pred)).sum().item()\n\n acc = correct / (index * self.data_loader.batch_size)\n logger.info(\"测试了%d条,正确%d条,正确率:%.4f,耗时:%.2f\",\n index * self.data_loader.batch_size,\n correct, acc, time.time() - start)\n return acc\n\n def calculate_features(self, model, image_paths):\n features = None\n labels = None\n for data, label in self.data_loader:\n data = data.to(self.device) # 放到显存中,用于加速\n # you don't need to calculate gradients for forward and backward phase.防止OOM\n with torch.no_grad():\n __features = model.extract_feature(data)\n __features = __features.cpu() # 用cpu()值替换掉原引用,导致旧引用回收=>GPU内存回收,解决OOM问题\n\n if features is None:\n features = __features.numpy()\n else:\n features = np.concatenate((features, __features.numpy()))\n if labels is None:\n labels = label.numpy()\n else:\n labels = np.concatenate((labels, label.numpy()))\n return features, labels\n\n\nclass FaceTester(Tester):\n\n def __init__(self, device):\n self.device = device\n\n def calculate_features(self, model, dir, face_image_names):\n \"\"\"\n image_paths: 所有的图片的路径(全路径)\n \"\"\"\n image_feature_dict = {}\n\n # image_name 带着1层目录名\n for i, image_name in enumerate(face_image_names):\n image_full_path = os.path.join(dir,image_name)\n image = utils.load_image(image_full_path)\n if image is None: continue\n\n # 转成 cuda tensor\n data = np.array([image])\n data = torch.from_numpy(data)\n data = data.to(self.device)\n\n # logger.debug(\"推断要求输入:%r\", list(model.parameters())[0].shape)\n # logger.debug(\"推断实际输入:%r\", data.shape)\n feature = model.extract_feature(data)[0]\n feature = feature.cpu().detach().numpy() # cpu(显存=>内存),detach(去掉梯度), numpy(tensor转成numpy)\n\n # logger.debug(\"推断实际输出(%s):%r\", image_name, feature.shape)\n # logger.debug(\"推断实际输出:%r\", feature)\n\n image_feature_dict[image_name] = feature\n return image_feature_dict\n\n def load_model(self, model, model_path):\n model_dict = model.state_dict()\n pretrained_dict = torch.load(model_path)\n pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}\n model_dict.update(pretrained_dict)\n model.load_state_dict(model_dict)\n\n def cosin_metric(self, x1, x2):\n \"\"\"\n x1 。x2\n --------- ==> 这个就是x1,x2的夹角θ的cos值,arcface的θ,是和权重W_i的角度,不是两张脸的features:x1、x2的角度,\n |x1|*|x2| 但因为模型导致某一类他们都压缩成一个聚集的类了,变相地导致了,不同类之间的角度就很大,\n \"\"\"\n return np.dot(x1, x2) / (np.linalg.norm(x1) * np.linalg.norm(x2))\n\n def cal_accuracy(self, y_score, y_true):\n \"\"\"\n 从一堆的 脸脸对,得到cosθ差异值,\n 然后用每一个cosθ差异值当阈值,来算正确率,\n 对应最好的正确率的那个阈值,当做最好的阈值。\n 这个算法有点意思。\n\n y_score: 是x1,x2之间的夹角θ的cosθ值,\n 一共有多少个呢?有很多个,一对就是一个,我记得测试数据有6000个,3000个同一个人的脸,3000个不同人的脸,\n \"\"\"\n\n y_score = np.asarray(y_score)\n y_true = np.asarray(y_true)\n best_acc = 0\n best_th = 0\n for i in range(len(y_score)):\n th = y_score[i]\n # y_score是夹角的余弦值,你可以理解成一个夹角,大于这个值(也就是小于某个夹角,余弦是递减的),就是同一人\n # 然后,我用所有的比对的cos值,都试验一遍,效果最好的那个值(也就是某个夹角角度),就是最好的阈值\n y_test = (y_score >= th)\n acc = np.mean((y_test == y_true).astype(int))\n if acc > best_acc:\n logger.debug(\"更好的acc:%r > %r(旧)\", acc, best_acc)\n logger.debug(\"更好的阈值:%r vs %r(旧)\", th, best_th)\n best_acc = acc\n best_th = th\n logger.debug(\"最好的阈值: %r,最好的ACC:%r\", best_th, best_acc)\n\n return (best_acc, best_th)\n\n def test_performance(self, feature_dict, pairs):\n sims = []\n labels = []\n for face1, face2, label in pairs:\n\n feature_1 = feature_dict.get(face1, None)\n feature_2 = feature_dict.get(face2, None)\n if feature_1 is None or feature_2 is None:\n continue\n\n sim = self.cosin_metric(feature_1, feature_2) # 计算cosθ\n sims.append(sim)\n labels.append(label)\n\n acc, th = self.cal_accuracy(sims, labels)\n return acc, th\n\n def extract_face_images(self, face1_face2_label_list):\n face_image_paths = []\n for face1, face2, _ in face1_face2_label_list:\n if face1 not in face_image_paths:\n face_image_paths.append(face1)\n if face1 not in face_image_paths:\n face_image_paths.append(face2)\n return face_image_paths\n\n def acc(self, model, opt):\n \"\"\"\n 重构后的测试入口,它去加载 形如 \"xxx.jpg xxx.jpg 1\"的lfw的测试文件,0/1表示是不是同一个人的脸,\n \"\"\"\n model.eval()\n\n # 加载所有的face1\\face2\\是否同一人\n face1_face2_label_list = self.load_test_pairs(opt.lfw_test_pair_path, opt.test_pair_size)\n # 得到所有的人脸图片名字(包含1层目录)\n face_image_names = self.extract_face_images(face1_face2_label_list)\n\n s = time.time()\n image_feature_dicts = self.calculate_features(model, opt.lfw_root, face_image_names)\n # logger.debug(\"人脸的特征维度:%r\", len(image_feature_dicts))\n t = time.time() - s\n logger.info('[验证]耗时: %.2f秒, 每张耗时:%.4f秒', t, t / len(image_feature_dicts))\n\n acc, th = self.test_performance(image_feature_dicts, face1_face2_label_list)\n logger.info(\"[验证]测试%d对人脸,(最好)正确率%.2f,(适配出来的最好的阈值%.2f)\", len(face1_face2_label_list), acc, th)\n return acc\n\n def caculate_samples(self, model, opt):\n \"\"\"\n 重构后的测试入口,它去加载 形如 \"xxx.jpg xxx.jpg 1\"的lfw的测试文件,0/1表示是不是同一个人的脸,\n \"\"\"\n\n # 仅装载前10个人的脸\n face_dirs = self.load_samples(opt.lfw_root, opt.test_classes)\n start = time.time()\n different_faces = []\n count = 0\n\n for face_dir, file_num in face_dirs:\n # 一个人脸文件夹,包含多个人脸\n file_names = os.listdir(face_dir)\n count += len(file_names)\n full_paths = [os.path.join(face_dir, file_name) for file_name in file_names]\n image_feature_dicts = self.calculate_features(model, full_paths)\n different_faces.append(list(image_feature_dicts.values())) # 只保留value数据,多个人脸\n t = time.time() - start\n\n logger.info('[计算%d个人的%d张人脸] 耗时: %.2f秒, 每张耗时:%.4f秒', opt.len(face_dirs), count, t, t / count)\n\n return different_faces\n\n def load_test_pairs(self, test_file_path, pair_size):\n \"\"\"\n 各加载pair_size的一半的比较对\n \"\"\"\n\n fd = open(test_file_path, 'r')\n lines = fd.readlines()\n fd.close()\n\n random.shuffle(lines) # shuffle一下\n\n positive_list = []\n negtive_list = []\n face1_face2_label_list = []\n\n half_size = pair_size // 2\n\n for line in lines:\n line = line.strip()\n pairs = line.split()\n face1 = pairs[0]\n face2 = pairs[1]\n label = int(pairs[2])\n if label == 1:\n positive_list.append([face1, face2, label])\n if label == 0:\n negtive_list.append([face1, face2, label])\n\n face1_face2_label_list += positive_list[:half_size]\n face1_face2_label_list += negtive_list[:half_size]\n\n logger.info(\"从[%s]加载比较对%d个\", test_file_path, len(face1_face2_label_list))\n return face1_face2_label_list\n\n def load_samples(self, dir, size):\n \"\"\"\n 加载测试集中,人脸最多的前N个人,这个用于embedding显示\n \"\"\"\n\n dirs = os.listdir(dir)\n dirs = [os.path.join(dir, sub_dir) for sub_dir in dirs]\n dirs = [dir for dir in dirs if os.path.isdir(dir)]\n logger.debug(\"从目录[%s],加载测试文件夹:%d 个\", dir, len(dirs))\n dir_files = {}\n for dir in dirs:\n dir_files[dir] = len(os.listdir(dir))\n\n sored_dir_files = [[k, v] for k, v in sorted(dir_files.items(), key=lambda item: item[1])]\n # sored_dir_files = sored_dir_files[-size:]\n sored_dir_files = sored_dir_files[:3]\n logger.debug(\"过滤后,剩余%d个文件夹\", len(sored_dir_files))\n return sored_dir_files\n\n# bin/train.docker 1 test --model arcface_e39_s246948_202110121044_l0.51_a0.00.model\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--model\", default=None, type=str)\n args = parser.parse_args()\n\n logger.info(\"参数配置:%r\", args)\n\n utils.init_log()\n\n opt = Config()\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") # torch.device代表将torch.Tensor分配到的设备的对象\n tester = FaceTester(device)\n model = utils.load_model(args.model,device,opt)\n acc = tester.acc(model, opt)\n logger.info(\"测试acc:%r\", acc)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":13226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"127892649","text":"import os\nimport io\nimport json\nimport unittest\nimport unittest.mock\nfrom pysqa.cmd import command_line\n\n\nclass TestCMD(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.test_dir = os.path.abspath(os.path.dirname(__file__))\n\n @unittest.mock.patch('sys.stdout', new_callable=io.StringIO)\n def assert_stdout_command_line(self, cmd_args, execute_command, expected_output, mock_stdout):\n command_line(\n argv=cmd_args,\n execute_command=execute_command\n )\n self.assertEqual(mock_stdout.getvalue(), expected_output)\n\n def test_help(self):\n self.assert_stdout_command_line(\n [\"--help\"],\n None,\n \"python -m pysqa --help ... coming soon.\\n\",\n )\n\n def test_wrong_option(self):\n self.assert_stdout_command_line(\n [\"--error\"],\n None,\n \"python -m pysqa --help\\n\",\n )\n\n def test_submit(self):\n def execute_command(\n commands,\n working_directory=None,\n split_output=True,\n shell=False,\n error_filename=\"pysqa.err\",\n ):\n return \"1\\n\"\n\n self.assert_stdout_command_line(\n [\n \"--config_directory\", os.path.join(self.test_dir, \"config\", \"slurm\"),\n \"--submit\",\n \"--queue\", \"slurm\",\n \"--job_name\", \"test\",\n \"--working_directory\", \".\",\n \"--cores\", \"2\",\n \"--memory\", \"1GB\",\n \"--run_time\", \"10\",\n \"--command\", \"echo hello\"\n ],\n execute_command,\n \"1\\n\",\n )\n with open(\"run_queue.sh\") as f:\n output = f.readlines()\n content = [\n '#!/bin/bash\\n',\n '#SBATCH --output=time.out\\n',\n '#SBATCH --job-name=test\\n',\n '#SBATCH --chdir=.\\n',\n '#SBATCH --get-user-env=L\\n',\n '#SBATCH --partition=slurm\\n',\n '#SBATCH --time=4320\\n',\n '#SBATCH --mem=1GBG\\n',\n '#SBATCH --cpus-per-task=10\\n',\n '\\n',\n 'echo hello'\n ]\n self.assertEqual(output, content)\n os.remove(\"run_queue.sh\")\n\n def test_delete(self):\n def execute_command(\n commands,\n working_directory=None,\n split_output=True,\n shell=False,\n error_filename=\"pysqa.err\",\n ):\n return \"Success\\n\"\n\n self.assert_stdout_command_line(\n [\n \"--config_directory\", os.path.join(self.test_dir, \"config\", \"slurm\"),\n \"--delete\",\n \"--id\", \"1\"\n ],\n execute_command,\n \"S\\n\"\n )\n\n def test_status(self):\n def execute_command(\n commands,\n working_directory=None,\n split_output=True,\n shell=False,\n error_filename=\"pysqa.err\",\n ):\n with open(os.path.join(self.test_dir, \"config\", \"slurm\", \"squeue_output\")) as f:\n return f.read()\n\n self.assert_stdout_command_line(\n [\n \"--config_directory\", os.path.join(self.test_dir, \"config\", \"slurm\"),\n \"--status\"\n ],\n execute_command,\n json.dumps({\n \"jobid\": [5322019, 5322016, 5322017, 5322018, 5322013], \"user\": [\"janj\", \"janj\", \"janj\", \"janj\", \"maxi\"],\n \"jobname\": [\"pi_19576488\", \"pi_19576485\", \"pi_19576486\", \"pi_19576487\", \"pi_19576482\"],\n \"status\": [\"running\", \"running\", \"running\", \"running\", \"running\"],\n \"working_directory\": [\n \"/cmmc/u/janj/pyiron/projects/2023/2023-04-19-dft-test/job_1\",\n \"/cmmc/u/janj/pyiron/projects/2023/2023-04-19-dft-test/job_2\",\n \"/cmmc/u/janj/pyiron/projects/2023/2023-04-19-dft-test/job_3\",\n \"/cmmc/u/janj/pyiron/projects/2023/2023-04-19-dft-test/job_4\",\n \"/cmmc/u/janj/pyiron/projects/2023/2023-04-19-dft-test/job_5\"\n ]\n }) +\"\\n\"\n )\n\n def test_list(self):\n def execute_command(\n commands,\n working_directory=None,\n split_output=True,\n shell=False,\n error_filename=\"pysqa.err\",\n ):\n pass\n\n self.assert_stdout_command_line(\n [\n \"--config_directory\", os.path.join(self.test_dir, \"config\", \"slurm\"),\n \"--list\",\n \"--working_directory\", os.path.join(self.test_dir, \"config\", \"slurm\"),\n\n ],\n execute_command,\n json.dumps({\n \"dirs\": [os.path.join(self.test_dir, \"config\", \"slurm\")],\n \"files\": sorted([\n os.path.join(self.test_dir, \"config\", \"slurm\", \"squeue_output\"),\n os.path.join(self.test_dir, \"config\", \"slurm\", \"slurm_extra.sh\"),\n os.path.join(self.test_dir, \"config\", \"slurm\", \"slurm.sh\"),\n os.path.join(self.test_dir, \"config\", \"slurm\", \"queue.yaml\"),\n ])\n }) + \"\\n\"\n )\n","sub_path":"tests/test_cmd.py","file_name":"test_cmd.py","file_ext":"py","file_size_in_byte":5226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"249918481","text":"# elements.py\r\n# -*- coding: utf-8 -*-\r\n#\r\n# Copyright © Stephen Day\r\n#\r\n# This module is part of Creoleparser and is released under\r\n# the MIT License: http://www.opensource.org/licenses/mit-license.php\r\n#\r\n\r\nimport re\r\nimport urlparse\r\nimport urllib\r\nimport keyword\r\nimport sys\r\n\r\nimport genshi.builder as bldr\r\nfrom genshi.core import Stream, Markup\r\n\r\nfrom core import (escape_char, esc_neg_look, fragmentize, ImplicitList, P3Template) \r\n\r\nBLOCK_ONLY_TAGS = ['h1','h2','h3','h4','h5','h6',\r\n 'ul','ol','dl',\r\n 'pre','hr','blockquote','address',\r\n 'p','div','form','fieldset','table',\r\n 'noscript']\r\n\r\nBLOCK_TAGS = BLOCK_ONLY_TAGS + ['ins','del','script']\r\n\r\n\r\nMACRO_NAME = r'(?P[a-zA-Z]+([-.]?[a-zA-Z0-9]+)*)'\r\n\"\"\"allows any number of non-repeating hyphens or periods.\r\nUnderscore is not included because hyphen is\"\"\"\r\n\r\n\r\n# use Genshi's HTMLSanitizer if possible (i.e., not on Google App Engine)\r\ntry:\r\n from genshi.filters import HTMLSanitizer\r\nexcept:\r\n SAFE_SCHEMES = frozenset(['file', 'ftp', 'http', 'https', 'mailto', None])\r\n class HTMLSanitizer(object):\r\n def is_safe_uri(self,uri):\r\n if ':' not in uri:\r\n return True # This is a relative URI\r\n chars = [char for char in uri.split(':', 1)[0] if char.isalnum()]\r\n return ''.join(chars).lower() in SAFE_SCHEMES\r\n\r\nsanitizer = HTMLSanitizer()\r\n\r\n__docformat__ = 'restructuredtext en'\r\n\r\nclass WikiElement(object):\r\n \r\n \"\"\"Baseclass for all wiki elements.\"\"\"\r\n \r\n append_newline = False\r\n \"\"\"Determines if newlines are appended to Element(s) during processing.\r\n Should only affect readability of source xml.\r\n \"\"\"\r\n \r\n def __init__(self, tag, token, child_elements=None):\r\n \"\"\"Constructor for WikiElement objects.\r\n\r\n Subclasses may have other keyword arguments. \r\n\r\n :parameters:\r\n tag\r\n The xhtml tag associated with the element.\r\n token\r\n The character string (or strings) that identifies the element\r\n in wiki markup.\r\n child_elements\r\n A list of wiki_elements that will be searched for in the body of the\r\n element. The order of these elements matters, because if an element is\r\n found before the element that encloses it, the enclosing element will\r\n never be found. In cases where this imposes limits (e.g, ``strong`` and\r\n ``em`` should be allowed to nest each other), place the conflicting\r\n elements in a sublist. The parser will then find which comes first.\r\n \"\"\"\r\n self.tag = tag\r\n self.token = token\r\n if child_elements is None:\r\n child_elements = []\r\n self.child_elements = child_elements\r\n\r\n\r\n def _build(self,mo,element_store, environ):\r\n \"\"\"Returns a genshi Element that has ``self.tag`` as the\r\n outermost tag.\r\n\r\n This methods if called exclusively by ``_process``\r\n\r\n :parameters:\r\n mo\r\n match object, usually the one returned by\r\n self.regexp.search(s) \r\n \"\"\"\r\n return bldr.tag.__getattr__(self.tag)(fragmentize(mo.group(1),\r\n self.child_elements,\r\n element_store, environ))\r\n\r\n def re_string(self):\r\n \"\"\"The regular expression pattern that is compiled into ``self.regexp``.\r\n\r\n The regular expression must consume the entire wiki element,\r\n including the tokens. For block elements, the newline on the last\r\n line must be consumed also. group(1) should normally be the\r\n entire string inside the tokens. If not, a custom ``_build``\r\n method will be needed.\r\n \"\"\"\r\n pass\r\n\r\n \r\n def __repr__(self):\r\n return \"<\"+self.__class__.__name__ + \" \" + str(self.tag)+\">\"\r\n\r\n\r\n\r\n def _process(self, mos, text, wiki_elements,element_store, environ):\r\n \"\"\"Returns genshi Fragments (Elements and text)\r\n\r\n This is mainly for block level markup. See InlineElement\r\n for the other method.\r\n \"\"\"\r\n frags = []\r\n end = 0\r\n for mo in mos:\r\n if end != mo.start():\r\n # call again for leading text and extend the result list \r\n frags.extend(fragmentize(text[end:mo.start()],wiki_elements[1:],\r\n element_store, environ))\r\n # append the found wiki element to the result list\r\n built = self._build(mo,element_store, environ)\r\n if built is not None:\r\n frags.append(built)\r\n # make the source output easier to read\r\n if self.append_newline:\r\n frags.append('\\n')\r\n end = mo.end()\r\n # call again for trailing text and extend the result list\r\n if end < len(text):\r\n if not isinstance(wiki_elements[0],(list,tuple)):\r\n wiki_elements = wiki_elements[1:]\r\n frags.extend(fragmentize(text[end:],wiki_elements,\r\n element_store, environ))\r\n\r\n return frags\r\n\r\n\r\nclass BlockElement(WikiElement):\r\n\r\n \"\"\"Block elements inherit form this class\r\n\r\n Wiki elements wanting ``append_newline = True`` should use this\r\n as the base also.\r\n\r\n \"\"\"\r\n\r\n append_newline = True\r\n \r\n\r\nclass InlineElement(WikiElement):\r\n\r\n r\"\"\"For finding generic inline elements\r\n\r\n >>> em = InlineElement('em','//')\r\n >>> mo1 = em.regexp.search('a //word// in a line')\r\n >>> mo2 = em.regexp.search('a //word in a line\\n or two\\n')\r\n >>> mo1.group(0),mo1.group(1)\r\n ('//word//', 'word')\r\n >>> mo2.group(0),mo2.group(1)\r\n ('//word in a line\\n or two', 'word in a line\\n or two')\r\n\r\n Use a list for the ``token`` argument to have different start\r\n and end strings. These must be closed.\r\n\r\n >>> foo = InlineElement('foo',['<<','>>'])\r\n >>> mo = foo.regexp.search('blaa <>\\n')\r\n >>> mo.group(1)\r\n 'here it is '\r\n \r\n \"\"\"\r\n\r\n def __init__(self, tag='', token=''):\r\n super(InlineElement,self).__init__(tag,token)\r\n self.regexp = re.compile(self.re_string(),re.DOTALL)\r\n\r\n def re_string(self):\r\n if isinstance(self.token,str):\r\n content = '(.+?)'\r\n end = '(' + esc_neg_look + re.escape(self.token) + r'|$)'\r\n return esc_neg_look + re.escape(self.token) + content + end\r\n else:\r\n content = '(.+?)'\r\n return esc_neg_look + re.escape(self.token[0]) + content + esc_neg_look + re.escape(self.token[1])\r\n\r\n def _process(self, mos, text, wiki_elements, element_store, environ):\r\n \"\"\"Returns genshi Fragments (Elements and text)\"\"\"\r\n parts = []\r\n end = 0\r\n for mo in mos:\r\n processed = self._build(mo,element_store, environ)\r\n store_id = str(id(processed)) \r\n element_store[store_id] = processed\r\n parts.append(''.join([text[end:mo.start()],'<<<',store_id,'>>>']))\r\n end = mo.end()\r\n # call again for trailing text and extend the result list\r\n if end < len(text):\r\n parts.append(text[end:])\r\n new_text = ''.join(parts)\r\n if not isinstance(wiki_elements[0],(list,tuple)):\r\n wiki_elements = wiki_elements[1:]\r\n frags = fragmentize(new_text,wiki_elements,element_store, environ)\r\n return frags\r\n\r\n\r\nclass SimpleElement(InlineElement):\r\n\r\n r\"\"\"For finding generic inline elements like ``strong`` and ``em``.\r\n\r\n >>> em = SimpleElement({'//':'em'})\r\n >>> mo1 = em.regexp.search('a //word// in a line')\r\n >>> mo2 = em.regexp.search('a //word in a line\\n or two\\n')\r\n >>> mo1.group(0),mo1.group(2)\r\n ('//word//', 'word')\r\n >>> mo2.group(0),mo2.group(2)\r\n ('//word in a line\\n or two', 'word in a line\\n or two')\r\n \r\n \"\"\"\r\n\r\n def __init__(self, token_dict={}):\r\n self.token_dict = token_dict\r\n self.tokens = token_dict.keys()\r\n super(SimpleElement,self).__init__('','')\r\n self.regexp = re.compile(self.re_string(),re.DOTALL)\r\n\r\n def re_string(self):\r\n if isinstance(self.token,basestring):\r\n tokens = '(' + '|'.join([re.escape(token) for token in self.tokens]) + ')'\r\n content = '(.+?)'\r\n end = '(' + esc_neg_look + r'\\1|$)'\r\n return esc_neg_look + tokens + content + end\r\n\r\n def _build(self,mo,element_store, environ):\r\n return bldr.tag.__getattr__(self.token_dict[mo.group(1)])(fragmentize(mo.group(2),\r\n self.child_elements,\r\n element_store, environ))\r\n\r\n\r\nclass LinkElement(InlineElement):\r\n\r\n \"\"\"Superclass for AnchorLinks and ImageLinks. Parses internal, external,\r\n and interwiki links.\r\n \r\n \"\"\"\r\n \r\n def __init__(self,tag, token, delimiter,\r\n interwiki_delimiter,base_urls,links_funcs,default_space_char,space_chars,\r\n base_url,space_char,class_func,path_func):\r\n super(LinkElement,self).__init__(tag,token)\r\n self.regexp = re.compile(self.re_string(),re.DOTALL)\r\n self.delimiter = delimiter\r\n self.interwiki_delimiter = interwiki_delimiter\r\n self.base_urls = base_urls\r\n self.links_funcs = links_funcs\r\n self.default_space_char = default_space_char\r\n self.space_chars = space_chars\r\n self.base_url = base_url\r\n self.space_char = space_char\r\n self.class_func = class_func\r\n self.path_func = path_func\r\n self.content_regexp = re.compile(self.content_re_string(),re.DOTALL)\r\n## self.arg_regexp = re.compile(self.arg_re_string(),re.DOTALL)\r\n self.interwikilink_regexp = re.compile(self.interwikilink_re_string())\r\n self.urllink_regexp = re.compile(self.urllink_re_string(), re.DOTALL)\r\n self.wikilink_regexp = re.compile(self.wikilink_re_string())\r\n\r\n## def arg_re_string(self):\r\n## key = r'((?P\\w+)\\s*\\=)?'\r\n## value = r'(?P.*?)'\r\n## return r'\\s*' + key + r'\\s*' + value + r'\\s*(?P' + \\\r\n## re.escape(self.delimiter) + r'|$)(?P.*)'\r\n\r\n def content_re_string(self):\r\n return r'(?P.*?)(' + re.escape(self.delimiter) + '(?P.*?))?$'\r\n\r\n def interwikilink_re_string(self):\r\n all_wikis = set(self.links_funcs.keys() + self.base_urls.keys())\r\n wiki_id = '(?P' + '|'.join(all_wikis) + ')'\r\n optional_spaces = ' *'\r\n page_name = r'(?P\\S+?( \\S+?)*)' #allows any number of single spaces\r\n return '^' + optional_spaces + wiki_id + \\\r\n re.escape(self.interwiki_delimiter) + ' *' + page_name + \\\r\n optional_spaces + '$'#+ alias\r\n\r\n def urllink_re_string(self):\r\n protocol = r'^\\s*((\\w+?:|/)' \r\n rest_of_url = r'[\\S\\n]*?)\\s*$'\r\n return protocol + rest_of_url #+ alias\r\n\r\n def wikilink_re_string(self):\r\n optional_spaces = ' *'\r\n page_name = r'(?P\\S+?( \\S+?)*?)' #allows any number of single spaces\r\n return '^' + optional_spaces + page_name + optional_spaces + '$'#+ \\\r\n\r\n## def parse_args(self, arg_string):\r\n## args = []\r\n## delimiter = True\r\n## while delimiter:\r\n## mo = self.arg_regexp.match(arg_string)\r\n## key, value, delimiter, tail = mo.group('key'),mo.group('value'),mo.group('delimiter'), mo.group('tail')\r\n## if key:\r\n## args.append((key, value))\r\n## else:\r\n## args.append(value)\r\n## arg_string = tail\r\n## positional_args = []\r\n## kw_args = {}\r\n## for arg in args:\r\n## if isinstance(arg,tuple):\r\n## k, v = arg\r\n## k = str(k).lower()\r\n## if k in keyword.kwlist:\r\n## k = k + '_'\r\n## if k in kw_args:\r\n## if isinstance(v,list):\r\n## try:\r\n## kw_args[k].extend(v)\r\n## except AttributeError:\r\n## v.insert(0,kw_args[k])\r\n## kw_args[k] = v\r\n## elif isinstance(kw_args[k],list):\r\n## kw_args[k].append(v)\r\n## else:\r\n## kw_args[k] = [kw_args[k], v]\r\n## kw_args[k] = ImplicitList(kw_args[k])\r\n## else:\r\n## kw_args[k] = v\r\n## if isinstance(kw_args[k],ImplicitList):\r\n## kw_args[k] = ','.join(kw_args[k])\r\n## else:\r\n## positional_args.append(arg)\r\n##\r\n## return (positional_args, kw_args)\r\n\r\n\r\n def page_name(self,mo):\r\n if 'wiki_id' in mo.groupdict():\r\n space_char = self.space_chars.get(mo.group('wiki_id'),self.default_space_char)\r\n else:\r\n space_char = self.space_char\r\n return mo.group('page_name').replace(' ',space_char)\r\n\r\n def _build(self,mo,element_store, environ):\r\n content_mo = self.content_regexp.match(mo.group(1))\r\n body = content_mo.group('body')\r\n arg_string = content_mo.group('arg_string')\r\n the_class = None\r\n page_name = None\r\n if self.interwikilink_regexp.match(body):\r\n interwikilink_mo = self.interwikilink_regexp.match(body)\r\n link_type = 'interwiki'\r\n base_url = self.base_urls.get(interwikilink_mo.group('wiki_id'))\r\n link_func = self.links_funcs.get(interwikilink_mo.group('wiki_id'))\r\n page_name = self.page_name(interwikilink_mo)\r\n if link_func:\r\n url = link_func(page_name)\r\n else:\r\n url = urllib.quote(page_name.encode('utf-8'))\r\n if base_url:\r\n url = urlparse.urljoin(base_url, url)\r\n elif self.urllink_regexp.match(body):\r\n urllink_mo = self.urllink_regexp.match(body)\r\n link_type = 'url'\r\n if sanitizer.is_safe_uri(urllink_mo.group(1)):\r\n url = urllink_mo.group(1)\r\n else:\r\n url = None\r\n elif self.wikilink_regexp.match(body):\r\n wikilink_mo = self.wikilink_regexp.match(body)\r\n link_type = 'wiki'\r\n page_name = self.page_name(wikilink_mo)\r\n if self.path_func:\r\n the_path = self.path_func(self.tag, page_name, environ)\r\n else:\r\n the_path = urllib.quote(page_name.encode('utf-8'))\r\n url = urlparse.urljoin(self.base_url, the_path)\r\n else:\r\n url = None\r\n\r\n if not url:\r\n return mo.group(0)\r\n else:\r\n if arg_string is not None:\r\n args, kw_args = [arg_string.strip()], {} #self.parse_args(arg_string)\r\n else:\r\n args, kw_args = [], {}\r\n\r\n try:\r\n if self.class_func:\r\n the_class = self.class_func(link_type, url, body, page_name)\r\n return self.emit(element_store, environ,link_type,body,url,the_class, *args, **kw_args)\r\n except TypeError:\r\n return mo.group(0)\r\n \r\n\r\n\r\nclass AnchorElement(LinkElement):\r\n\r\n \"\"\"Finds and builds internal, external, and interwiki links.\r\n\r\n >>> link = AnchorElement('a',('[[',']]'),'|',\r\n ... interwiki_delimiter=':', \r\n ... base_urls=dict(somewiki='http://somewiki.org/',\r\n ... bigwiki='http://bigwiki.net/'),\r\n ... links_funcs={},default_space_char='-',\r\n ... space_chars={'bigwiki':' '},base_url='http://somewiki.org/',\r\n ... space_char='_',class_func=None,path_func=None)\r\n \r\n >>> mo = link.regexp.search(\"[[http://www.google.com| here]]\")\r\n >>> link._build(mo,{},None).generate().render()\r\n 'here'\r\n\r\n >>> mo = link.regexp.search(\" [[somewiki:Home Page|steve]] \")\r\n >>> link._build(mo,{},None).generate().render()\r\n 'steve'\r\n\r\n >>> mo = link.regexp.search(\" [[bigwiki:Home Page]] \")\r\n >>> link._build(mo,{},None).generate().render()\r\n 'bigwiki:Home Page'\r\n\r\n >>> mo = link.regexp.search(\" [[Home Page |Home]]\")\r\n >>> link._build(mo,{},None).generate().render()\r\n 'Home'\r\n \r\n \"\"\"\r\n \r\n\r\n def __init__(self, *args, **kw_args):\r\n super(AnchorElement,self).__init__(*args, **kw_args) \r\n\r\n def emit(self,element_store, environ,link_type,body,url,the_class, alias=None):\r\n if alias:\r\n alias = fragmentize(alias,self.child_elements,element_store, environ)\r\n else:\r\n alias = body.strip()\r\n return bldr.tag.__getattr__(self.tag)(alias,\r\n href=url,\r\n class_=the_class)\r\n\r\n \r\nclass ImageElement(LinkElement):\r\n\r\n def __init__(self, *args, **kw_args):\r\n super(ImageElement,self).__init__(*args, **kw_args) \r\n\r\n def emit(self,element_store, environ,link_type,body,url,the_class, alt=None):\r\n if alt is None:\r\n if link_type == 'url':\r\n alt = urlparse.urlsplit(url).path.split('/')[-1]\r\n else:\r\n alt = body.strip()\r\n return bldr.tag.__getattr__(self.tag)(src=url ,alt=alt, title=alt,\r\n #class_=the_class\r\n ) \r\n \r\n\r\nclass Link(InlineElement):\r\n\r\n \"\"\"Finds and builds links.\"\"\"\r\n \r\n def __init__(self,tag, token):\r\n super(Link,self).__init__(tag,token)\r\n self.regexp = re.compile(self.re_string(),re.DOTALL)\r\n\r\n def _build(self,mo,element_store, environ):\r\n \r\n for tag in self.child_elements:\r\n m = tag.regexp.search(mo.group(1))\r\n if m:\r\n link = tag._build(m,element_store, environ)\r\n if link:\r\n break\r\n else:\r\n link = None\r\n\r\n if link:\r\n return bldr.tag(link)\r\n else:\r\n return mo.group(0)\r\n\r\n\r\nclass Macro(WikiElement):\r\n r\"\"\"Finds and processes inline macro elements.\"\"\"\r\n\r\n def __init__(self, tag, token, func):\r\n super(Macro,self).__init__(tag,token , [])\r\n self.func = func\r\n self.regexp = re.compile(self.re_string())\r\n\r\n\r\n def _process(self, mos, text, wiki_elements,element_store, environ):\r\n \"\"\"Returns genshi Fragments (Elements and text)\"\"\"\r\n assert len(mos) == 1\r\n mo = mos[0]\r\n processed = self._build(mo,element_store, environ)\r\n if isinstance(processed, list):\r\n tail = processed[1]\r\n processed = processed[0]\r\n else:\r\n tail = ''\r\n if isinstance(processed, basestring) and not isinstance(processed,Markup):\r\n text = ''.join([text[:mo.start()],processed,tail,\r\n text[mo.end():]])\r\n else:\r\n store_id = str(id(processed))\r\n element_store[store_id] = processed\r\n text = ''.join([text[:mo.start()],'<<<',store_id,'>>>',tail,\r\n text[mo.end():]])\r\n frags = fragmentize(text,wiki_elements,element_store, environ)\r\n return frags\r\n\r\n\r\n def re_string(self):\r\n content = '(.*?)'\r\n return esc_neg_look + re.escape(self.token[0]) + r'(' + MACRO_NAME + \\\r\n content + ')' + esc_neg_look + re.escape(self.token[1])\r\n\r\n trailing_slash = re.compile(r'(?<=[ \"\\'\\]])/$')\r\n def _build(self,mo,element_store, environ):\r\n arg_string = re.sub(self.trailing_slash,'',mo.group(4))\r\n if self.func:\r\n value = self.func(mo.group('name'),arg_string,None,False,environ)\r\n else:\r\n value = None\r\n if value is None:\r\n return bldr.tag.code(self.token[0],bldr.tag.span(mo.group('name'),class_=\"macro_name\"),\r\n bldr.tag.span(arg_string,class_=\"macro_arg_string\"),\r\n self.token[1],class_=\"unknown_macro\")\r\n elif isinstance(value, (basestring,bldr.Fragment,bldr.Element, Stream)):\r\n return value\r\n else:\r\n raise Exception(\"macros can only return strings and genshi objects\") \r\n \r\n\r\nclass BodiedMacro(Macro):\r\n \"\"\"Finds and processes macros with bodies.\r\n\r\n Does not span across top level block markup\r\n (see BodiedBlockMacro's for that).\"\"\"\r\n\r\n def __init__(self, tag, token, func):\r\n super(BodiedMacro,self).__init__(tag,token , func)\r\n self.func = func\r\n self.regexp = re.compile(self.re_string(),re.DOTALL)\r\n\r\n def re_string(self):\r\n content = r'(?P[ \\S]*?)'\r\n body = '(?P.+)'\r\n return esc_neg_look + re.escape(self.token[0]) + MACRO_NAME + \\\r\n content + '(?[ \\S]*?)', re.escape(self.token[1])])\r\n end = ''.join([esc_neg_look, re.escape(self.token[0]), '/', re.escape(mo.group('name')),\r\n re.escape(self.token[1])])\r\n count = 0\r\n for mo2 in re.finditer(start + '|' + end, mo.group('body')):\r\n if re.match(end,mo2.group(0)):\r\n count = count + 1\r\n else:\r\n count = count - 1\r\n if count > 0:\r\n body = mo.group('body')[:mo2.start()]\r\n tail = ''.join([mo.group('body')[mo2.end():], self.token[0],\r\n '/', mo.group('name'), self.token[1]])\r\n break\r\n else:\r\n body = mo.group('body')\r\n tail = ''\r\n \r\n \r\n \r\n if self.func:\r\n value = self.func(mo.group('name'),mo.group('arg_string'),body,False,environ)\r\n else:\r\n value = None\r\n if value is None:\r\n content_out = [self.token[0],bldr.tag.span(mo.group('name'),class_=\"macro_name\"),\r\n bldr.tag.span(mo.group('arg_string'),class_=\"macro_arg_string\"),\r\n self.token[1],bldr.tag.span(mo.group('body'),class_=\"macro_body\"),\r\n self.token[0] + '/' + mo.group('name') + self.token[1]]\r\n return [bldr.tag.code(content_out,class_=\"unknown_macro\", style=\"white-space:pre-wrap\"),tail]\r\n \r\n elif isinstance(value, (basestring,bldr.Fragment, Stream)):\r\n return [value,tail]\r\n else:\r\n raise Exception(\"macros can only return strings and genshi objects\")\r\n\r\n \r\n\r\nclass BodiedBlockMacro(WikiElement):\r\n \"\"\"Finds and processes block macros with bodies.\r\n\r\n The opening and closing tokens must be are each on a line alone without\r\n leading spaces. These macros can enclose other block level markup\r\n including pre blocks and other BodiedBlockMacro's.\"\"\"\r\n\r\n\r\n def __init__(self, tag, token, func):\r\n super(BodiedBlockMacro,self).__init__(tag,token , func)\r\n self.func = func\r\n self.regexp = re.compile(self.re_string(),re.DOTALL+re.MULTILINE)\r\n\r\n def re_string(self):\r\n arg_string = r'(?P(?![^\\n]*>>[^\\n]*>>)[ \\S]*?)'\r\n start = '^' + re.escape(self.token[0])\r\n body = r'(?P.*\\n)'\r\n end = re.escape(self.token[0]) + \\\r\n r'/(?P=name)' + '(?(?![^\\n]*>>[^\\n]*>>)[ \\S]*?)', re.escape(self.token[1]),r'\\s*?\\n'])\r\n end = ''.join(['^', re.escape(self.token[0]), '/', re.escape(mo.group('name')),\r\n re.escape(self.token[1]),r'\\s*?$'])\r\n count = 0\r\n for mo2 in re.finditer(start + '|' + end, mo.group('body'),re.MULTILINE):\r\n if re.match(end,mo2.group(0)):\r\n count = count + 1\r\n else:\r\n count = count - 1\r\n if count > 0:\r\n body = mo.group('body')[:mo2.start()]\r\n tail = ''.join([mo.group('body')[mo2.end():], self.token[0],\r\n '/', mo.group('name'), self.token[1],'\\n'])\r\n break\r\n else:\r\n body = mo.group('body')\r\n tail = ''\r\n\r\n if self.func:\r\n value = self.func(mo.group('name'),mo.group('arg_string'),body,True,environ)\r\n else:\r\n value = None\r\n if value is None:\r\n return [bldr.tag.pre(self.token[0],bldr.tag.span(mo.group('name'),class_=\"macro_name\"),\r\n bldr.tag.span(mo.group('arg_string'),class_=\"macro_arg_string\"),\r\n self.token[1],'\\n',bldr.tag.span(mo.group('body'),class_=\"macro_body\"),\r\n self.token[0] + '/' + mo.group('name') + self.token[1],\r\n class_=\"unknown_macro\"), tail]\r\n elif (isinstance(value, (Stream, basestring)) or\r\n (isinstance(value,bldr.Element) and value.tag in BLOCK_TAGS)):\r\n return [value, tail]\r\n # Add a p tag if the value is a Fragment or Element that needs one\r\n elif isinstance(value, bldr.Fragment):\r\n return [bldr.tag.p(value), tail]\r\n else:\r\n raise Exception(\"macros can only return strings and genshi objects\")\r\n \r\n \r\nclass RawLink(InlineElement):\r\n \r\n \"\"\"Used to find raw urls in wiki text and build xml from them.\r\n\r\n >>> raw_link = RawLink(tag='a')\r\n >>> mo = raw_link.regexp.search(\" a http://www.google.com url \")\r\n >>> raw_link.href(mo)\r\n 'http://www.google.com'\r\n >>> raw_link._build(mo,{},None).generate().render()\r\n 'http://www.google.com'\r\n \r\n \"\"\"\r\n linking_protocols = ['http','https']\r\n \r\n def __init__(self, tag):\r\n super(RawLink,self).__init__(tag=tag, token=None)\r\n self.regexp = re.compile(self.re_string())\r\n\r\n def re_string(self):\r\n escape = '(' + re.escape(escape_char) + ')?'\r\n #protocol = '((https?|ftp)://'\r\n protocol = '((https?)://'\r\n rest_of_url = r'\\S+?)'\r\n #allow one punctuation character or '**' or '//'. Don't include a placeholder.\r\n look_ahead = r'(?=([>)}\\]]?[,.?!:;\"\\']?(([^a-zA-Z0-9])\\6)?(\\s|$))|<<<)'\r\n return escape + protocol + rest_of_url + look_ahead\r\n\r\n def _build(self,mo,element_store, environ):\r\n if (not mo.group(1)) and (mo.group(3) in self.linking_protocols):\r\n return bldr.tag.__getattr__(self.tag)(self.alias(mo,element_store),\r\n href=self.href(mo))\r\n else:\r\n return self.href(mo)\r\n \r\n def href(self,mo):\r\n \"\"\"Returns the string for the href attribute of the Element.\"\"\"\r\n if sanitizer.is_safe_uri(mo.group(2)):\r\n return mo.group(2)\r\n else:\r\n return \"unsafe_uri_detected\"\r\n\r\n def alias(self,mo,element_store):\r\n \"\"\"Returns the string for the content of the Element.\"\"\"\r\n return self.href(mo)\r\n\r\n\r\nclass URLLink(WikiElement):\r\n \r\n \"\"\"Used to find url type links inside a link.\r\n\r\n The scope of these is within link markup only (i.e., [[url]]\r\n\r\n >>> url_link = URLLink('a','|')\r\n >>> mo = url_link.regexp.search(\" http://www.google.com| here \")\r\n >>> url_link.href(mo)\r\n 'http://www.google.com'\r\n >>> url_link._build(mo,{},None).generate().render()\r\n 'here'\r\n \r\n \"\"\"\r\n\r\n def __init__(self, tag,delimiter):\r\n super(URLLink,self).__init__(tag, '')\r\n self.delimiter = delimiter\r\n self.regexp = re.compile(self.re_string(),re.DOTALL)\r\n\r\n def re_string(self):\r\n protocol = r'^\\s*((\\w+?:|/)' \r\n rest_of_url = r'[\\S\\n]*?)\\s*'\r\n alias = r'(' + re.escape(self.delimiter) + r' *(.*?))? *$'\r\n return protocol + rest_of_url + alias\r\n\r\n def _build(self,mo,element_store, environ):\r\n if not self.href(mo):\r\n return None\r\n return bldr.tag.__getattr__(self.tag)(self.alias(mo,element_store, environ),\r\n href=self.href(mo))\r\n \r\n def href(self,mo):\r\n \"\"\"Returns the string for the href attribute of the Element.\"\"\"\r\n if sanitizer.is_safe_uri(mo.group(1)):\r\n return mo.group(1)\r\n else:\r\n return None \r\n \r\n\r\n def alias(self,mo,element_store, environ):\r\n \"\"\"Returns the string for the content of the Element.\"\"\"\r\n if not mo.group(4):\r\n return self.href(mo)\r\n else:\r\n return fragmentize(mo.group(4),self.child_elements,element_store, environ)\r\n\r\n\r\n\r\nclass InterWikiLink(WikiElement):\r\n\r\n \"\"\"Used to match interwiki links inside a link.\r\n\r\n The search scope for these is only inside links. \r\n\r\n >>> interwiki_link = InterWikiLink('a',\r\n ... delimiter1=':', delimiter2 = '|',\r\n ... base_urls=dict(somewiki='http://somewiki.org/',\r\n ... bigwiki='http://bigwiki.net/'),\r\n ... links_funcs={},default_space_char='_',\r\n ... space_chars={})\r\n >>> mo = interwiki_link.regexp.search(\" somewiki:Home Page|steve \")\r\n >>> interwiki_link.href(mo)\r\n 'http://somewiki.org/Home_Page'\r\n >>> interwiki_link.alias(mo,{},None)\r\n ['steve']\r\n \r\n \"\"\"\r\n\r\n def __init__(self, tag, delimiter1,\r\n delimiter2,base_urls,links_funcs,default_space_char,space_chars):\r\n super(InterWikiLink,self).__init__(tag, '')\r\n self.delimiter1 = delimiter1\r\n self.delimiter2 = delimiter2\r\n #self.regexp = re.compile(self.re_string())\r\n self.base_urls = base_urls\r\n self.links_funcs = links_funcs\r\n self.default_space_char = default_space_char\r\n self.space_chars = space_chars\r\n self.regexp = re.compile(self.re_string())\r\n\r\n def re_string(self):\r\n #all_wikis = set(self.links_funcs.keys() + self.base_urls.keys())\r\n #wiki_id = '(' + '|'.join(all_wikis) + ')'\r\n\r\n wiki_id = r'(\\w+)'\r\n optional_spaces = ' *'\r\n page_name = r'(\\S+?( \\S+?)*)' #allows any number of single spaces\r\n alias = r'(' + re.escape(self.delimiter2) + r' *(.*?))? *$'\r\n return '^' + optional_spaces + wiki_id + optional_spaces + \\\r\n re.escape(self.delimiter1) + optional_spaces + page_name + \\\r\n optional_spaces + alias\r\n\r\n def page_name(self,mo):\r\n space_char = self.space_chars.get(mo.group(1),self.default_space_char)\r\n return mo.group(2).replace(' ',space_char)\r\n\r\n def href(self,mo):\r\n linktype = mo.group(1)\r\n base_url = self.base_urls.get(linktype)\r\n link_func = self.links_funcs.get(linktype)\r\n if not (link_func or base_url):\r\n return None\r\n else:\r\n href = self.page_name(mo)\r\n if link_func:\r\n href = link_func(href)\r\n else:\r\n href = urllib.quote(href.encode('utf-8'))\r\n if base_url:\r\n href = urlparse.urljoin(base_url, href)\r\n return href\r\n\r\n def _build(self,mo,element_store, environ):\r\n if not self.href(mo):\r\n return '[[' + mo.group(0) + ']]'\r\n return bldr.tag.__getattr__(self.tag)(self.alias(mo,element_store, environ),\r\n href=self.href(mo))\r\n def alias(self,mo,element_store, environ):\r\n \"\"\"Returns the string for the content of the Element.\"\"\"\r\n if not mo.group(5):\r\n return ''.join([mo.group(1),self.delimiter1,mo.group(2)])\r\n else:\r\n return fragmentize(mo.group(5),self.child_elements,element_store, environ)\r\n\r\n\r\n\r\nclass WikiLink(WikiElement):\r\n\r\n \"\"\"Used to match wiki links inside a link.\r\n\r\n The search scope for these is only inside links.\r\n\r\n >>> wiki_link = WikiLink('a','|',base_url='http://somewiki.org/',\r\n ... space_char='_',class_func=None, path_func=None)\r\n >>> mo = wiki_link.regexp.search(\" Home Page |Home\")\r\n >>> wiki_link.href(mo)\r\n 'http://somewiki.org/Home_Page'\r\n >>> wiki_link.alias(mo,{},None)\r\n ['Home']\r\n \r\n \"\"\"\r\n\r\n def __init__(self, tag, delimiter,\r\n base_url,space_char,class_func,path_func):\r\n super(WikiLink,self).__init__(tag, '')\r\n self.delimiter = delimiter\r\n self.base_url = base_url\r\n self.space_char = space_char\r\n self.class_func = class_func\r\n self.path_func = path_func\r\n self.regexp = re.compile(self.re_string())\r\n\r\n def re_string(self):\r\n optional_spaces = ' *'\r\n page_name = r'(\\S+?( \\S+?)*?)' #allows any number of single spaces\r\n alias = r'(' + re.escape(self.delimiter) + r' *(.*?))? *$'\r\n return '^' + optional_spaces + page_name + optional_spaces + \\\r\n alias\r\n\r\n def page_name(self,mo):\r\n return mo.group(1).replace(' ',self.space_char)\r\n \r\n def href(self,mo,environ):\r\n if self.path_func:\r\n the_path = self.path_func(self.tag, self.page_name(mo), environ)\r\n else:\r\n the_path = urllib.quote(self.page_name(mo).encode('utf-8'))\r\n return urlparse.urljoin(self.base_url, the_path)\r\n\r\n def _build(self,mo,element_store, environ):\r\n if self.class_func:\r\n the_class = self.class_func(self.page_name(mo))\r\n else:\r\n the_class = None\r\n return bldr.tag.__getattr__(self.tag)(self.alias(mo,element_store, environ),\r\n href=self.href(mo, environ),\r\n class_=the_class)\r\n \r\n def alias(self,mo,element_store, environ):\r\n \"\"\"Returns the string for the content of the Element.\"\"\"\r\n if not mo.group(3):\r\n return mo.group(1)\r\n else:\r\n return fragmentize(mo.group(4),self.child_elements,element_store, environ)\r\n\r\n\r\nclass List(BlockElement):\r\n\r\n \"\"\"Finds list (ordered, unordered, and definition) wiki elements.\r\n\r\n group(1) of the match object includes all lines from the list\r\n including newline characters.\r\n \r\n \"\"\"\r\n\r\n def __init__(self, tag, token,stop_tokens=None):\r\n self.stop_tokens = stop_tokens\r\n super(List,self).__init__(tag, token)\r\n #self.stop_tokens = stop_tokens\r\n self.regexp = re.compile(self.re_string(),re.DOTALL+re.MULTILINE)\r\n\r\n def re_string(self):\r\n \"\"\"This re_string is for finding generic block elements like\r\n lists (ordered, unordered, and definition) that start with a\r\n single token.\r\n \"\"\"\r\n leading_whitespace = r'^([ \\t]*'\r\n only_one_token = re.escape(self.token)+ '(?!' + re.escape(self.token) + ')'\r\n rest_of_list = r'.*?(?:\\n|\\Z))'\r\n only_one_stop_token = '([' + re.escape(self.stop_tokens) + r'])(?!\\3)' \r\n look_ahead = '(?=([ \\t]*' + only_one_stop_token + '|$))'\r\n return leading_whitespace + only_one_token + rest_of_list + \\\r\n look_ahead\r\n\r\n\r\n\r\nclass ListItem(BlockElement):\r\n r\"\"\"Matches the current list item.\r\n\r\n Everything up to the next same-level list item is matched.\r\n\r\n >>> list_item = ListItem('li','#*')\r\n >>> mo = list_item.regexp.search(\"*one\\n**one.1\\n**one.2\\n*two\\n\")\r\n >>> mo.group(3)\r\n 'one\\n**one.1\\n**one.2\\n'\r\n >>> mo.group(0)\r\n '*one\\n**one.1\\n**one.2\\n'\r\n \r\n \"\"\"\r\n \r\n append_newline = False\r\n\r\n def __init__(self, tag, list_tokens):\r\n \"\"\"Constructor for list items.\r\n\r\n :parameters\"\r\n list_tokens\r\n A string that includes the tokens used for lists\r\n \"\"\"\r\n self.list_tokens = list_tokens\r\n super(ListItem,self).__init__(tag, None)\r\n self.regexp = re.compile(self.re_string(),re.DOTALL)\r\n\r\n def re_string(self):\r\n whitespace = r'[ \\t]*'\r\n item_start = '(([' + self.list_tokens + r'])\\2*)'\r\n rest_of_item = r'(.*?(?:\\n|\\Z))'\r\n start_of_same_level_item = r'\\1(?!\\2)'\r\n look_ahead = r'(?=(' + whitespace + start_of_same_level_item + '|$))'\r\n return whitespace + item_start + whitespace + \\\r\n rest_of_item + look_ahead\r\n\r\n def _build(self,mo,element_store, environ):\r\n return bldr.tag.__getattr__(self.tag)(fragmentize(mo.group(3),\r\n self.child_elements,\r\n element_store, environ))\r\n\r\n\r\nclass NestedList(WikiElement):\r\n\r\n r\"\"\"Finds a list in the current list item.\r\n\r\n >>> nested_ul = NestedList('ul','*')\r\n >>> mo = nested_ul.regexp.search('one\\n**one.1\\n**one.2\\n')\r\n >>> mo.group(1)\r\n '**one.1\\n**one.2\\n'\r\n >>> mo.group(0) == mo.group(1)\r\n True\r\n\r\n \"\"\"\r\n\r\n def __init__(self, tag, token):\r\n super(NestedList,self).__init__(tag, token)\r\n self.regexp = re.compile(self.re_string(),re.DOTALL+re.MULTILINE)\r\n\r\n def re_string(self):\r\n look_behind = r'(?<=\\n)' # have to avoid finding a list on the first line\r\n whitespace = r'(\\s*'\r\n rest_of_list = '.*$)'\r\n return look_behind + '^' + whitespace + re.escape(self.token) + \\\r\n rest_of_list\r\n\r\n\r\nclass DefinitionTerm(BlockElement):\r\n\r\n r\"\"\"Processes definition terms.\r\n\r\n >>> term = DefinitionTerm('dt',';',stop_token=':')\r\n >>> mo1,mo2 = term.regexp.finditer(\";term1\\n:def1\\n;term2:def2\\n\")\r\n >>> mo1.group(1), mo2.group(1)\r\n ('term1', 'term2')\r\n >>> mo1.group(0), mo2.group(0)\r\n (';term1\\n', ';term2')\r\n\r\n group(1) of the match object is the term line or up to the first ':'\r\n \r\n \"\"\"\r\n\r\n def __init__(self, tag, token,stop_token):\r\n super(DefinitionTerm,self).__init__(tag, token)\r\n self.stop_token = stop_token\r\n self.regexp = re.compile(self.re_string(),re.DOTALL+re.MULTILINE)\r\n\r\n def re_string(self):\r\n look_ahead = r'(\\n|(?=(' + esc_neg_look + re.escape(self.stop_token) + r'|$)))'\r\n return r'^[ \\t]*' + re.escape(self.token) + r'[ \\t]*(.*?' + \\\r\n re.escape(self.stop_token) + '?)\\s*' + look_ahead \r\n\r\n\r\nclass DefinitionDef(BlockElement):\r\n\r\n r\"\"\"Processes definitions.\r\n\r\n >>> definition = DefinitionDef('dd',':')\r\n >>> mo1,mo2 = definition.regexp.finditer(\":def1a\\ndef1b\\n:def2\\n\")\r\n >>> mo1.group(1), mo2.group(1)\r\n ('def1a\\ndef1b', 'def2')\r\n >>> mo1.group(0), mo2.group(0)\r\n (':def1a\\ndef1b\\n', ':def2\\n')\r\n\r\n group(1) of the match object includes all lines from the defintion\r\n up to the next definition.\r\n \r\n \"\"\"\r\n\r\n def __init__(self, tag, token):\r\n super(DefinitionDef,self).__init__(tag, token)\r\n self.regexp = re.compile(self.re_string(),re.DOTALL+re.MULTILINE)\r\n\r\n def re_string(self):\r\n look_ahead = r'(?=(^[ \\t]*' + re.escape(self.token) + r')|\\Z)'\r\n return r'^[ \\t]*' + re.escape(self.token) + r'?[ \\t]*(.+?)\\s*' + look_ahead \r\n\r\nclass Paragraph(BlockElement):\r\n \"\"\"\"This should be the last outer level wiki element to be searched.\r\n\r\n Anything that is left over will be placed in a paragraphs unless it looks\r\n like block content according to xhtml1 strict. Block content is defined\r\n here as valid children of the element (see BLOCK_TAGS). Only genshi\r\n Element objects will be evaluated (see BLOCK_TAGS). Fragments and stings\r\n are treated as inline while Streams are block content.\r\n \r\n \"\"\"\r\n\r\n def __init__(self, tag):\r\n super(Paragraph,self).__init__(tag,None)\r\n self.regexp = re.compile(self.re_string(),re.DOTALL)#+re.MULTILINE)\r\n\r\n def re_string(self):\r\n return r'^(.*?)\\n?$' \r\n\r\n def _build(self,mo,element_store, environ):\r\n content = fragmentize(mo.group(1), self.child_elements, element_store, environ)\r\n # Check each list item and record those that are block only\r\n block_only_frags = []\r\n for i,element in enumerate(content):\r\n if ((isinstance(element, bldr.Element) and\r\n element.tag in BLOCK_ONLY_TAGS) or\r\n isinstance(element,(Stream,Markup))):\r\n block_only_frags.append(i)\r\n # Build a new result list if needed\r\n if block_only_frags:\r\n new_content = []\r\n last_i = -1\r\n for i in block_only_frags:\r\n if content[last_i+1:i]:\r\n if not (len(content[last_i+1:i])==1 and\r\n content[last_i+1] == '\\n'):\r\n new_content.append(bldr.tag.__getattr__(self.tag)(content[last_i+1:i]))\r\n else:\r\n new_content.append('\\n')\r\n new_content.append(content[i])\r\n last_i = i\r\n if content[last_i+1:]:\r\n new_content.append(bldr.tag.__getattr__(self.tag)(content[last_i+1:]))\r\n return bldr.tag(new_content)\r\n else:\r\n return bldr.tag.__getattr__(self.tag)(content)\r\n \r\n\r\nclass Heading(BlockElement):\r\n\r\n r\"\"\"Finds heading wiki elements.\r\n\r\n >>> h1 = Heading(['h1','h2'],'=')\r\n >>> mo = h1.regexp.search('before\\n = An important thing = \\n after')\r\n >>> mo.group(2)\r\n 'An important thing'\r\n >>> mo.group(0)\r\n ' = An important thing = \\n'\r\n\r\n \"\"\"\r\n \r\n def __init__(self, tag, token):\r\n super(Heading,self).__init__('',token)\r\n self.tags = tag\r\n self.regexp = re.compile(self.re_string(),re.MULTILINE)\r\n\r\n def re_string(self):\r\n whitespace = r'[ \\t]*'\r\n tokens = '(' + re.escape(self.token) + '{1,' + str(len(self.tags)) +'})'\r\n content = '(.*?)'\r\n trailing_markup = '(' + re.escape(self.token) + r'+[ \\t]*)?(\\n|\\Z)'\r\n return '^' + whitespace + tokens + \\\r\n whitespace + content + whitespace + trailing_markup\r\n\r\n def _build(self,mo,element_store, environ):\r\n heading_tag = self.tags[len(mo.group(1))-1]\r\n return bldr.tag.__getattr__(heading_tag)(fragmentize(mo.group(2),\r\n self.child_elements,\r\n element_store, environ))\r\n\r\n\r\nclass Table(BlockElement):\r\n\r\n r\"\"\"Find tables.\r\n\r\n >>> table = Table('table','|')\r\n >>> mo = table.regexp.search(\"before\\n | one | two |\\n|one|two \\n hi\")\r\n >>> mo.group(1)\r\n ' | one | two |\\n|one|two \\n'\r\n >>> mo.group(0) == mo.group(1)\r\n True\r\n \r\n \"\"\"\r\n\r\n def __init__(self, tag, token):\r\n super(Table,self).__init__(tag,token)\r\n self.regexp = re.compile(self.re_string(),re.MULTILINE)\r\n\r\n def re_string(self):\r\n whitespace = r'[ \\t]*'\r\n rest_of_line = r'.*?(\\n|\\Z)'\r\n return '^((' + whitespace + re.escape(self.token) + \\\r\n rest_of_line + ')+)'\r\n\r\n\r\n\r\nclass TableRow(BlockElement):\r\n\r\n r\"\"\"Finds rows in a table.\r\n\r\n >>> row = TableRow('tr','|')\r\n >>> mo = row.regexp.search(' | one | two |\\n|one|two \\n')\r\n >>> mo.group(1)\r\n '| one | two '\r\n >>> mo.group(0)\r\n ' | one | two |\\n'\r\n \r\n \"\"\"\r\n\r\n def __init__(self, tag, token):\r\n super(TableRow,self).__init__(tag,token)\r\n self.regexp = re.compile(self.re_string(),re.MULTILINE)\r\n\r\n def re_string(self):\r\n whitespace = r'[ \\t]*'\r\n content = '(' + re.escape(self.token) + '.*?)'\r\n trailing_token = re.escape(self.token) + '?'\r\n return '^' + whitespace + content + trailing_token + \\\r\n whitespace + r'(\\n|\\Z)'\r\n\r\n\r\nclass TableCell(WikiElement):\r\n\r\n r\"\"\"Finds cells in a table row.\r\n\r\n >>> cell = TableCell('td','|')\r\n >>> mo = cell.regexp.search('| one | two ')\r\n >>> mo.group(1)\r\n 'one'\r\n >>> mo.group(0)\r\n '| one '\r\n \r\n \"\"\"\r\n\r\n def __init__(self, tag, token):\r\n super(TableCell,self).__init__(tag,token )\r\n self.regexp = re.compile(self.re_string())\r\n\r\n def re_string(self):\r\n whitespace = r'[ \\t]*'\r\n content = '(.*?)'\r\n look_ahead = '((?=' + esc_neg_look + re.escape(self.token[0]) + ')|$)'\r\n return esc_neg_look + re.escape(self.token) + whitespace + \\\r\n content + whitespace + look_ahead \r\n\r\n\r\n\r\n##class Link(InlineElement):\r\n##\r\n## \"\"\"Finds and builds links.\"\"\"\r\n## \r\n## def __init__(self,tag, token):\r\n## super(Link,self).__init__(tag,token)\r\n##\r\n## def _build(self,mo,element_store, environ):\r\n## \r\n## for tag in self.child_elements:\r\n## m = tag.regexp.search(mo.group(1))\r\n## if m:\r\n## link = tag._build(m,element_store, environ)\r\n## if link:\r\n## break\r\n## else:\r\n## link = None\r\n##\r\n## if link:\r\n## return bldr.tag(link)\r\n## else:\r\n## return mo.group(0)\r\n\r\nclass Image(InlineElement):\r\n\r\n \"\"\"Processes image elements.\r\n\r\n >>> img = Image('img',('{{','}}'), delimiter='|')\r\n >>> mo = img.regexp.search('{{ picture.jpg | An image of a house }}')\r\n >>> img._build(mo,{},None).generate().render()\r\n '\"An'\r\n\r\n \"\"\"\r\n\r\n def __init__(self, tag, token, delimiter):\r\n super(Image,self).__init__(tag,token )\r\n self.regexp = re.compile(self.re_string())\r\n self.delimiter = delimiter\r\n self.src_regexp = re.compile(r'^\\s*(\\S+)\\s*$')\r\n\r\n def _build(self,mo,element_store, environ):\r\n body = mo.group(1).split(self.delimiter,1)\r\n src_mo = self.src_regexp.search(body[0])\r\n if not src_mo:\r\n return bldr.tag.span('Bad Image src')\r\n if sanitizer.is_safe_uri(src_mo.group(1)):\r\n link = src_mo.group(1)\r\n else:\r\n link = \"unsafe_uri_detected\"\r\n if len(body) == 1:\r\n alias = link\r\n else:\r\n alias = body[1].strip()\r\n return bldr.tag.__getattr__(self.tag)(src=link ,alt=alias, title=alias)\r\n\r\n\r\nclass NoWikiElement(InlineElement):\r\n\r\n \"\"\"Inline no-wiki.\r\n\r\n When two or more end tokens are found together, only last marks\r\n the end of the element.\r\n \r\n \"\"\"\r\n\r\n def __init__(self, tag, token):\r\n super(NoWikiElement,self).__init__(tag,token )\r\n self.regexp = re.compile(self.re_string(),re.DOTALL) \r\n\r\n def _build(self,mo,element_store, environ):\r\n if self.tag:\r\n return bldr.tag.__getattr__(self.tag)(\r\n fragmentize(mo.group(1), self.child_elements,\r\n element_store,environ,\r\n remove_escapes=False))\r\n else:\r\n return bldr.tag(fragmentize(mo.group(1),self.child_elements,\r\n element_store, environ,\r\n remove_escapes=False))\r\n\r\n def re_string(self):\r\n if isinstance(self.token,str):\r\n content = '(.+?' + re.escape(self.token[-1]) + '*)'\r\n return esc_neg_look + re.escape(self.token) + \\\r\n content + re.escape(self.token)\r\n else:\r\n content = '(.+?' + re.escape(self.token[1][-1]) + '*)'\r\n return esc_neg_look + re.escape(self.token[0]) + \\\r\n content + re.escape(self.token[1])\r\n\r\n\r\nclass PreBlock(BlockElement):\r\n \"\"\"A preformatted block.\r\n\r\n If a closing token is found on a line with a space as the first\r\n character, the space will be removed from the output.\r\n \r\n \"\"\"\r\n\r\n def __init__(self, tag, token ):\r\n super(PreBlock,self).__init__(tag,token )\r\n self.regexp = re.compile(self.re_string(),re.DOTALL+re.MULTILINE)\r\n self.regexp2 = re.compile(self.re_string2(),re.MULTILINE)\r\n\r\n def re_string(self):\r\n if isinstance(self.token,str):\r\n return '^' + re.escape(self.token) + r'\\s*?\\n(.*?\\n)' + \\\r\n re.escape(self.token) + r'\\s*?\\n'\r\n else:\r\n start = '^' + re.escape(self.token[0]) + r'\\s*?\\n'\r\n content = r'(.+?\\n)'\r\n end = re.escape(self.token[1]) + r'\\s*?$'\r\n return start + content + end\r\n\r\n def re_string2(self):\r\n \"\"\"Finds a closing token with a space at the start of the line.\"\"\"\r\n if isinstance(self.token,str):\r\n return r'^ (\\s*?' + re.escape(self.token) + r'\\s*?\\n)'\r\n else:\r\n return r'^ (\\s*?' + re.escape(self.token[1]) + r'\\s*?\\n)'\r\n\r\n def _build(self,mo,element_store, environ):\r\n match = self.regexp2.sub(r'\\1',mo.group(1))\r\n \r\n return bldr.tag.__getattr__(self.tag)(\r\n fragmentize(match,self.child_elements,\r\n element_store, environ,remove_escapes=False))\r\n\r\n\r\nclass IndentedBlock(BlockElement):\r\n \"\"\"An indented block.\r\n\r\n \"\"\"\r\n\r\n def __init__(self, tag, token):\r\n super(IndentedBlock,self).__init__(tag,token )\r\n self.regexp = re.compile(self.re_string(),re.MULTILINE)\r\n self.regexp2 = re.compile(self.re_string2(),re.MULTILINE)\r\n\r\n def re_string(self):\r\n return r'^((' + re.escape(self.token) \\\r\n + r'.*?(\\n|\\Z))+)'\r\n\r\n def re_string2(self):\r\n \"\"\"Finds a token at the start of the line.\"\"\"\r\n return r'^' + re.escape(self.token)\r\n\r\n def _build(self,mo,element_store, environ):\r\n match = self.regexp2.sub(r'',mo.group(1)) # removes tokens during processing\r\n return bldr.tag.__getattr__(self.tag)(\r\n fragmentize(match,self.child_elements,\r\n element_store, environ))\r\n\r\n\r\nclass LoneElement(BlockElement):\r\n \"\"\"Element on a line by itself with no content (e.g.,
)\"\"\"\r\n\r\n def __init__(self, tag, token):\r\n super(LoneElement,self).__init__(tag,token )\r\n self.regexp = re.compile(self.re_string(),re.DOTALL+re.MULTILINE)\r\n\r\n def re_string(self):\r\n return r'^(\\s*?' + re.escape(self.token) + r'\\s*?(\\n|\\Z))'\r\n\r\n def _build(self,mo,element_store, environ):\r\n return bldr.tag.__getattr__(self.tag)()\r\n\r\n \r\nclass BlankLine(WikiElement):\r\n\r\n \"\"\"Blank lines divide elements but don't add any output.\"\"\"\r\n\r\n def __init__(self):\r\n super(BlankLine,self).__init__(tag=None,token='' , child_elements=[])\r\n self.regexp = re.compile(self.re_string(),re.MULTILINE)\r\n\r\n def re_string(self):\r\n return r'^\\s*(\\Z|\\n)' # r'^(\\s*\\n)+'\r\n \r\n def _build(self,mo,element_store, environ):\r\n return None\r\n\r\n def _process(self, mos, text, wiki_elements,element_store, environ):\r\n \"\"\"Returns genshi Fragments (Elements and text)\r\n\r\n Custom _process method here just to avoid unnecessary calling of\r\n _build.\r\n \"\"\"\r\n \r\n frags = []\r\n end = 0\r\n for mo in mos:\r\n if end != mo.start():\r\n # call again for leading text and extend the result list \r\n frags.extend(fragmentize(text[end:mo.start()],wiki_elements[1:],\r\n element_store, environ))\r\n end = mo.end()\r\n # call again for trailing text and extend the result list\r\n if end < len(text):\r\n if not isinstance(wiki_elements[0],(list,tuple)):\r\n wiki_elements = wiki_elements[1:]\r\n frags.extend(fragmentize(text[end:],wiki_elements,\r\n element_store, environ))\r\n\r\n return frags\r\n\r\nclass LineBreak(InlineElement):\r\n \"\"\"An inline line break.\"\"\"\r\n\r\n def __init__(self,tag, token, blog_style=False):\r\n self.blog_style = blog_style\r\n super(LineBreak,self).__init__(tag,token )\r\n self.regexp = re.compile(self.re_string(),re.DOTALL)\r\n\r\n def re_string(self):\r\n if self.blog_style:\r\n return '(' + esc_neg_look + re.escape(self.token) + r'\\n?|\\n(?!$))'\r\n else:\r\n return esc_neg_look + re.escape(self.token)\r\n \r\n def _build(self,mo,element_store, environ):\r\n return bldr.tag.__getattr__(self.tag)()\r\n \r\nclass GenericElement(InlineElement):\r\n \"\"\"A generic element.\"\"\"\r\n\r\n def __init__(self,pattern,tag,text_node=None,attrs=None):\r\n super(GenericElement,self).__init__(tag,pattern )\r\n self.attrs = attrs or {}\r\n self.text_node = text_node\r\n self.regexp = re.compile(self.re_string(),re.DOTALL)\r\n \r\n\r\n def re_string(self):\r\n escape = '(' + re.escape(escape_char) + ')*'\r\n return escape + self.token \r\n \r\n def _build(self,mo,element_store, environ):\r\n d = mo.groupdict()\r\n if d.has_key('all') or d.has_key('environ'):\r\n raise Exception('GenericElement patterns cannot have \"all\" or \\\r\n \"environ\" as group names.')\r\n d['all'] = mo.group(0)\r\n d['environ'] = environ\r\n if mo.group(1):\r\n return mo.group(0)[1:]\r\n else:\r\n if isinstance(self.text_node,(Stream, bldr.Fragment,Markup)) or self.text_node is None:\r\n content = self.text_node\r\n elif isinstance(self.text_node, basestring):\r\n if sys.version >= '2.6':\r\n content = self.text_node.format(**d)\r\n else:\r\n content = P3Template(self.text_node).substitute(d) \r\n else:\r\n content = self.text_node(mo, environ)\r\n\r\n if callable(self.attrs):\r\n attrs = self.attrs(mo, environ)\r\n else:\r\n attrs = self.attrs\r\n kwparams = {}\r\n for k,v in attrs.items():\r\n if isinstance(v,(Stream, bldr.Fragment,Markup)) or v is None:\r\n kwparams[k+'_'] = v\r\n elif isinstance(v,basestring):\r\n if sys.version >= '2.6':\r\n kwparams[k+'_'] = v.format(**d)\r\n else:\r\n kwparams[k+'_'] = P3Template(v).substitute(d)\r\n else:\r\n kwparams[k+'_'] = v(mo, environ)\r\n if callable(self.tag):\r\n tag = self.tag(mo, environ)\r\n else:\r\n tag = self.tag\r\n if tag:\r\n return bldr.tag.__getattr__(tag)(content,**kwparams)\r\n else:\r\n return content\r\n \r\n#############################################################################\r\n# The WikeElement classes below are used for parsing macro argument strings # \r\n#############################################################################\r\n\r\nclass ArgString(WikiElement):\r\n \"\"\"Base class for elements used on argument strings\"\"\"\r\n def __init__(self, tag='', token=''):\r\n super(ArgString,self).__init__(tag,token)\r\n self.regexp = re.compile(self.re_string(),re.DOTALL)\r\n\r\n\r\nclass KeywordArg(ArgString):\r\n \"\"\"Finds keyword arguments\"\"\"\r\n\r\n def re_string(self):\r\n return r'(?P\\w[\\w0-9]*) *'+re.escape(self.token) + \\\r\n r' *(?P.*?) *(?=\\w[\\w0-9]* *' + re.escape(self.token) +'|$)'\r\n\r\n def _build(self,mo,element_store, environ):\r\n if mo.group('body') == '':\r\n value = ''\r\n else:\r\n value = fragmentize(mo.group('body'),self.child_elements,\r\n element_store, environ)\r\n if len(value) == 1:\r\n value = value[0]\r\n else:\r\n value = ImplicitList(value)\r\n name = mo.group('key')\r\n return (name, value)\r\n\r\n\r\nclass QuotedArg(InlineElement):\r\n \"\"\"Finds quoted arguments\"\"\"\r\n\r\n def re_string(self):\r\n return esc_neg_look + r'(?P['+ re.escape(self.token) \\\r\n +'])(?P.*?)' + esc_neg_look + '(?P=quote)'\r\n\r\n def _build(self,mo,element_store, environ):\r\n if mo.group('body') == '':\r\n value = ''\r\n else:\r\n frags = fragmentize(mo.group('body'),self.child_elements,element_store, environ)\r\n assert len(frags) == 1\r\n value = frags[0]\r\n return value\r\n \r\nclass ListArg(ArgString):\r\n \"\"\"Finds lists in argument strings \r\n\r\n This is used for positional arguments only.\r\n \r\n \"\"\"\r\n \r\n def re_string(self):\r\n return esc_neg_look + re.escape(self.token[0]) + r'(?P.*?)' + esc_neg_look + re.escape(self.token[1])\r\n\r\n def _build(self,mo,element_store, environ):\r\n if mo.group('body') == '':\r\n value = []\r\n else:\r\n value = fragmentize(mo.group('body'),self.child_elements,element_store, environ)\r\n return value\r\n\r\nclass ExplicitListArg(ListArg):\r\n \"\"\"Only finds lists where the string to be searched is fully enclosed\r\n\r\n This is used for keyword values in argument strings.\r\n \r\n \"\"\"\r\n\r\n def re_string(self):\r\n return '^' + esc_neg_look + re.escape(self.token[0]) +r'(?P.*?)' \\\r\n + esc_neg_look+ re.escape(self.token[1]) + '$'\r\n\r\n\r\nclass WhiteSpace(ArgString):\r\n \"\"\"Breaks up elements but doesn't add any output\"\"\"\r\n\r\n def re_string(self):\r\n return r'[ \\n]+'\r\n\r\n def _build(self,mo,element_store, environ):\r\n return None\r\n\r\n\r\n\r\ndef _test():\r\n import doctest\r\n doctest.testmod()\r\n\r\nif __name__ == \"__main__\":\r\n _test() \r\n","sub_path":"sahriswiki/creoleparser/elements.py","file_name":"elements.py","file_ext":"py","file_size_in_byte":59616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"493671299","text":"import csv\nfrom datetime import datetime\n\n\ndef get_requests_log(logfile_name):\n '''\n A generator for the data in log.csv. Since csv files can contain over 10 \n millions of records, it is not necessary to store all the record in memory\n all at once.\n Input: csv_fname:\n filename/location of the csv.\n Output: log_record \n ''' \n with open(logfile_name, \"r\") as request_logs:\n for request_log in csv.reader(request_logs, delimiter=','):\n yield request_log\n \ndef check_request(row):\n '''\n Helper function to check if each record has the missing information or not\n Input: row from readint the csv\n Output: True or False\n '''\n if len(row[0])>0 and len(row[1])>0 and len(row[2])>0 and len(row[4])>0 and len(row[5])>0 and len(row[6])>0:\n return True\n else:\n return False\n\ndef tuple_to_str(record, ip, start_time):\n '''\n A helper funciton that converts dictionary entry to string for output file\n Input:\n tup: dictionary value in tuple\n key: dictionary key\n t_base: starting timestamp as a base\n Return:\n rslt_str: string in the required format\n '''\n start, end = record[0] + start_time, record[1] + start_time\n start, end = datetime.fromtimestamp(start), datetime.fromtimestamp(end)\n dt_str = str(int(record[1] - record[0]+1))\n counts = str(record[2])\n output = ip+','+str(start)+','+str(end)+','+dt_str+',' + counts\n return output\n\n","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"449890477","text":"import sys\n# addr ev3dev\n# name 00:17:E9:F8:72:06\nimport bluetooth\n\nserverMACAddress = '00:17:E9:F8:72:06'\nport = 3\ns = bluetooth.BluetoothSocket(bluetooth.RFCOMM)\ns.connect((serverMACAddress, port))\n\ncurrentPos = 5\ncurrentAction = 0\n\nmapPos = ['Null', 'A', 'B', 'C', 'D', 'Start', 'End']\nmapAc = ['Null', 'Nothing', 'Pick Up', 'Put Down']\ncommand = []\n\ndef menu():\n done = False\n while not done:\n print(\"SIMPLE EV3-APP MENU:\\n1.Set command for robot\\n2.Show current command\\n3.Reset Command\\n4.Apply command\\n5.Quit\")\n choice = input(\"Your choice: \")\n try:\n choice = int(choice)\n if (choice > 0 and choice < 6):\n if (choice == 1):\n location()\n action()\n elif (choice == 2):\n show()\n elif (choice == 3):\n reset()\n elif (choice == 4):\n apply()\n else:\n print(\"Goodbye\")\n done = True\n else:\n print(\"Invalid option\")\n except:\n print(\"Invalid option\")\n\n\ndef location():\n global currentPos\n done = False\n while not done:\n print(\"Select location:\\n1.A\\n2.B\\n3.C\\n4.D\\n5.Start\\n6.End\\n\")\n choice = input(\"Your choice: \")\n try:\n choice = int(choice)\n if (choice > 0 and choice < 7):\n if (currentPos == choice):\n showPos()\n print(\"Same LOCATION cant be select twice in a row\")\n else:\n currentPos = choice\n done = True\n else:\n print(\"Invalid Option !\\n\")\n except:\n print(\"Invalid Option!\\n\")\n done = False\n\ndef action():\n global command\n global currentAction\n done = False\n while not done:\n print(\"Select action:\\n1.Nothing\\n2.Pick Up\\n3.Drop Down\\n\")\n choice = input(\"Your choice: \")\n try:\n choice = int(choice)\n if (choice > 0 and choice < 4):\n if (currentAction != 1 and currentAction == choice):\n showAction()\n print(\"Same ACTION cant be perform twice in a row!\\n\")\n else:\n currentAction = choice\n command.append({mapPos[currentPos] : mapAc[currentAction]})\n done = True\n else:\n print (\"Invalid Options!\\n\")\n except:\n print(\"Invalid Option!\\n\")\n done = False\n\ndef showPos():\n print (\"The current position of the robot: \", mapPos[currentPos])\n\ndef showAction():\n print (\"The current action of the robot: \", mapAc[currentAction])\n\ndef show():\n for each in command:\n for location, action in each.items():\n print(\"Go to \", location, \" : do \", action)\n # print(str(command))\n\ndef reset():\n global command\n global currentPos\n global currentAction\n command = []\n currentPos = 0\n currentAction = 0\n\ndef apply():\n if (str(command) != \"[]\"):\n # command = [{'C' : 'Pick Up'}, {'A' : 'Put Down'}]\n s.send(str(command))\n done = False\n while not done:\n print(\"Waiting robot response!\")\n data = s.recv(2048)\n if \"done\" in data.decode('ascii'):\n done = True\n print(\"Job Done\")\n elif \"refuse\" in data.decode('ascii'):\n done = True\n print(\"Job Refused\")\n reset()\n else:\n print(\"Define command first\")\nif __name__ == \"__main__\":\n menu()\n s.close()\n # print(\"The command should be in this format A|B. It means, go to A\")\n # text = input('Command format (A|B):') # Note change to the old (Python 2) raw_input\n # if text == \"quit\":\n # break\n # s.send(text)\n# sock.close()\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"647641136","text":"\"\"\"\nThis module contains tests for the\npersonal_info application template tags\n\"\"\"\nfrom django.test import TestCase\nfrom django.template import Template\nfrom django.template import Context\nfrom django.template import TemplateSyntaxError\nfrom django.core.urlresolvers import reverse\n\nfrom apps.personal_info.models import Person\n\n\nclass TemplateTagsTest(TestCase):\n \"\"\"\n This class is the test case for the\n personal_info application template tags\n \"\"\"\n def test_model_get_admin_url(self):\n \"\"\"\n Tests the implementation of models get_admin_url()\n method\n \"\"\"\n person = Person.objects.first()\n info = (person._meta.app_label, person._meta.module_name)\n url = reverse('admin:%s_%s_change' % info, args=(person.pk,))\n self.assertEqual(url, person.get_admin_url())\n\n def test_tag_valid_params(self):\n \"\"\"\n Test the behaviour of the template tag with valid data\n \"\"\"\n person = Person.objects.first()\n template = Template(\n '{% load custom_tags %}{% edit_link object %}'\n )\n rendered = template.render(\n Context({'object': person})\n )\n self.assertIn(person.get_admin_url(), rendered)\n\n def test_tags_invalid_params(self):\n \"\"\"\n Test the behaviour of out template tag when we parse\n something different of Model objects\n \"\"\"\n not_a_model = 'Hello! I am NOT a model instance'\n template = Template(\n '{% load custom_tags %}{% edit_link object %}'\n )\n rendered = template.render(\n Context({'object': not_a_model})\n )\n\n self.assertEqual(rendered, '')\n\n def test_tags_syntax_errors(self):\n \"\"\"\n Test whether the syntax errors are dispatched\n \"\"\"\n render = lambda t: Template(t).render(Context())\n self.assertRaises(\n TemplateSyntaxError,\n render,\n '{% load custom_tags %}{% edit_link object as for %}'\n )\n self.assertRaises(\n TemplateSyntaxError,\n render,\n '{% load custom_tags %}{% edit_link \"quoted\"object %}'\n )\n self.assertRaises(\n TemplateSyntaxError,\n render,\n '{% load custom_tags %}{% edit_link if not %}'\n )\n self.assertRaises(\n TemplateSyntaxError,\n render,\n '{% load custom_tags %}{% edit_link object asd qwd %}'\n )\n","sub_path":"apps/personal_info/tests/tests_templatetags.py","file_name":"tests_templatetags.py","file_ext":"py","file_size_in_byte":2488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"299095877","text":"# GRO722 Laboratoire 2\n# Auteur: Jean-Samuel Lauzon et Jonathan Vincent\n# Hivers 2021\n\nimport torch\nfrom torch import nn\nimport numpy as np\nfrom torch.utils.data import Dataset, DataLoader\n\n# Inclure la base de données, les modèles et les métriques\nfrom dataset import *\nfrom models import *\nfrom metrics import *\n\nif __name__ == '__main__':\n\n # ---------------- Paramètres et hyperparamètres ----------------#\n force_cpu = 1 # Forcer l'utilisation du CPU (si un GPU est disponible)\n training = 0 # Faire l'entrainement sur l'ensemble de donnees\n display_attention = 1 # Affichage des poids d'attention\n learning_curves = 1 # Visualiser les courbes d'apprentissage pendant l'entrainement\n test = 1 # Visualiser la generation sur des echantillons de validation\n batch_size = 100 # Taille des lots\n n_epochs = 50 # Nombre d'iteration sur l'ensemble de donnees\n lr = 0.01 # Taux d'apprentissage pour l'optimizateur\n\n n_hidden = 20 # Nombre de neurones caches par couche \n n_layers = 2 # Nombre de de couches\n\n n_workers = 0 # Nombre de fils pour charger les donnees\n seed = None # Pour repetabilite\n # ------------ Fin des paramètres et hyperparamètres ------------#\n\n # Initialisation des variables\n if seed is not None:\n torch.manual_seed(seed)\n np.random.seed(seed)\n\n # Choix du device\n device = torch.device(\"cuda\" if torch.cuda.is_available() and not force_cpu else \"cpu\")\n\n # Instanciation de l'ensemble de données\n dataset = Fr_En(n_samp=4000, samplelen=[6,10])\n\n # Instanciation du dataloader\n dataload_train = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=n_workers)\n\n print('Number of epochs : ', n_epochs)\n print('Training data : ', len(dataset))\n print('Taille dictionnaires: ', dataset.dict_size)\n print('\\n')\n\n # Instanciation du model\n model = Seq2seq_attn(n_hidden=n_hidden, \\\n n_layers=n_layers, device=device, symb2int=dataset.symb2int, \\\n int2symb=dataset.int2symb, dict_size=dataset.dict_size, max_len=dataset.max_len)\n\n # Afficher le résumé du model\n print('Model : \\n', model, '\\n')\n print('Nombre de poids: ', sum([i.numel() for i in model.parameters() ]))\n\n if training:\n\n # Initialisation affichage\n if learning_curves:\n train_dist =[] # Historique des distances\n train_loss=[] # Historique des coûts\n fig, ax = plt.subplots(1) # Initialisation figure\n\n # Fonction de coût et optimizateur\n criterion = nn.CrossEntropyLoss(ignore_index=2) # ignorer les symboles \n optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n \n for epoch in range(1, n_epochs + 1):\n # Entraînement\n running_loss_train = 0\n dist=0\n for batch_idx, data in enumerate(dataload_train):\n # Formatage des données\n fr_seq, target_seq = data\n fr_seq = fr_seq.to(device).long()\n target_seq = target_seq.to(device).long()\n\n optimizer.zero_grad() # Mise a zero du gradient\n output, hidden, attn = model(fr_seq)# Passage avant\n loss = criterion(output.view((-1, model.dict_size['en'])), target_seq.view(-1))\n \n loss.backward() # calcul du gradient\n optimizer.step() # Mise a jour des poids\n running_loss_train += loss.item()\n\n # calcul de la distance d'édition\n output_list = torch.argmax(output,dim=-1).detach().cpu().tolist()\n target_seq_list = target_seq.cpu().tolist()\n M = len(output_list)\n for i in range(batch_size):\n a = target_seq_list[i]\n b = output_list[i]\n M = a.index(1)\n dist += edit_dist(a[:M],b[:M])/batch_size\n\n # Affichage pendant l'entraînement\n print('Train - Epoch: {}/{} [{}/{} ({:.0f}%)] Average Loss: {:.6f} Average Edit Distance: {:.6f}'.format(\n epoch, n_epochs, batch_idx * batch_size, len(dataload_train.dataset),\n 100. * batch_idx * batch_size / len(dataload_train.dataset), running_loss_train / (batch_idx + 1),\n dist/len(dataload_train)), end='\\r')\n\n print('Train - Epoch: {}/{} [{}/{} ({:.0f}%)] Average Loss: {:.6f} Average Edit Distance: {:.6f}'.format(\n epoch, n_epochs, (batch_idx+1) * batch_size, len(dataload_train.dataset),\n 100. * (batch_idx+1) * batch_size / len(dataload_train.dataset), running_loss_train / (batch_idx + 1),\n dist/len(dataload_train)), end='\\r')\n print('\\n')\n # Affichage graphique\n if learning_curves:\n train_loss.append(running_loss_train/len(dataload_train))\n train_dist.append(dist/len(dataload_train))\n ax.cla()\n ax.plot(train_loss, label='training loss')\n ax.plot(train_dist, label='training distance')\n ax.legend()\n plt.draw()\n plt.pause(0.01)\n\n # Enregistrer les poids\n torch.save(model,'model.pt')\n\n # Terminer l'affichage d'entraînement\n if learning_curves:\n plt.show()\n plt.close('all')\n\n if test:\n # Évaluation\n \n # Chargement des poids\n model = torch.load('model.pt')\n dataset.symb2int = model.symb2int\n dataset.int2symb = model.int2symb\n\n # Affichage des résultats\n for i in range(10):\n # Extraction d'une séquence du dataset de validation\n fr_seq, target_seq = dataset[np.random.randint(0,len(dataset))]\n\n # Évaluation de la séquence\n output, hidden, attn = model(torch.tensor(fr_seq)[None,:].to(device))\n out = torch.argmax(output, dim=2).detach().cpu()[0,:].tolist()\n \n # Affichage\n in_seq = [model.int2symb['fr'][i] for i in fr_seq.detach().cpu().tolist()]\n target = [model.int2symb['en'][i] for i in target_seq.detach().cpu().tolist()]\n out_seq = [model.int2symb['en'][i] for i in out]\n\n out_seq = out_seq[:out_seq.index('')+1]\n in_seq = in_seq[:in_seq.index('')+1]\n target = target[:target.index('')+1]\n \n\n print('Input: ', ' '.join(in_seq))\n print('Target: ', ' '.join(target))\n print('Output: ', ' '.join(out_seq))\n print('')\n if display_attention:\n attn = attn.detach().cpu()[0,:,:]\n plt.figure()\n plt.imshow(attn[0:len(in_seq), 0:len(out_seq)], origin='lower', vmax=1, vmin=0, cmap='pink')\n plt.xticks(np.arange(len(out_seq)), out_seq, rotation=45)\n plt.yticks(np.arange(len(in_seq)), in_seq)\n plt.show()","sub_path":"course3-rnns/lab2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"355603470","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 4 21:52:21 2016\n\n@author: yangyue\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n\n\ndef genvoltagedf(Ymatrix, result1, result2, nodemap, coordinate):\n # print(result1)\n # print(result2)\n if coordinate == \"Rectangular\":\n voltage = np.sqrt(np.square(result1)+np.square(result2))\n angle = 180/np.pi*np.arctan2(result2, result1)\n if coordinate == \"Polar\":\n voltage = result1\n angle = 180/np.pi*result2\n # nodesnum=len(voltage)\n# print(voltage)\n voltagedf = pd.DataFrame(\n data=np.vstack((voltage, angle)).T, columns=['voltage', 'angle'])\n nodemapnew = nodemap.sort_values(by='newindex').reset_index()\n voltagedf['node'] = nodemapnew['original']\n voltagedf = voltagedf.sort_values(by='node').reset_index()\n # voltagedf.sort_values(by='node',inplace=True)\n voltagedf['radangle'] = voltagedf['angle']*np.pi/180\n voltagedf['complexvoltage'] = voltagedf['voltage']*np.cos(voltagedf['radangle'])+1j*voltagedf['voltage']*np.sin(voltagedf['radangle'])\n voltagedf['complexcurrent'] = np.matmul(\n Ymatrix, voltagedf['complexvoltage'].values)\n voltagedf['complexpower'] = np.multiply(\n voltagedf['complexvoltage'].values, np.conj(voltagedf['complexcurrent'].values))\n return voltagedf\n\n\ndef writeNodevoltagetocsv(filename, voltagedf):\n voltagedf.to_csv(\n filename, columns=['node', 'voltage', 'angle', 'complexpower'])\n\n\ndef genbranchpower(voltagedf, branchdf):\n branchdf['startpower'] = 0j\n branchdf['endpower'] = 0j\n branchdf['losspower'] = 0j\n for i, row in branchdf.iterrows():\n startv = voltagedf[voltagedf['node'] == row['rawstart']][\n 'complexvoltage'].values[0]\n endv = voltagedf[voltagedf['node'] == row['rawend']][\n 'complexvoltage'].values[0]\n Y = row['Y']\n Ystart, Yend = row['Ystart'], row['Yend']\n I = Y*(startv-endv)\n startpower = startv*(I.conjugate())+startv*((startv*Ystart).conjugate())\n endpower = endv*((-I).conjugate())+endv*((endv*Yend).conjugate())\n if startpower.real < 0:\n branchdf.ix[i, 'rawstart'], branchdf.ix[i, 'rawend'] = branchdf.ix[\n i, 'rawend'], branchdf.ix[i, 'rawstart']\n startpower, endpower = endpower, startpower\n losspower = startpower+endpower\n branchdf.ix[i, 'startpower'] = startpower\n branchdf.ix[i, 'endpower'] = endpower\n branchdf.ix[i, 'losspower'] = losspower\n return branchdf\n\n\ndef writeBranchpowertocsv(filename, branchdf):\n branchdf.to_csv(filename, columns=['rawstart', 'rawend', 'startpower', 'endpower', 'losspower'], header=[ \\\n 'startnode', 'endnode', 'startpower', 'endpower', 'losspower'])\n","sub_path":"Output.py","file_name":"Output.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"56486686","text":"import numpy as np\nfrom hmmlearn import hmm\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\n\ndf1 = pd.read_csv(\"/media/nehleh/295eaca0-f110-4b79-8cbe-bc99f9f61cbd/nehleh/0_Research/PhD/Data/simulationdata/recombination/clonalframe/RAxML_perSiteLLs.likelihood_GTR\", sep='\\s+', header=None)\nll = df1.to_numpy()\ndata = np.array(ll)\nX = data.reshape((-1,1))\nX = X[1:1000000]\n\nmean = np.mean(X)\nstd = np.std(X)\n# print(mean)\n# print(std)\n\n\na = -2.242906769736397\nastd= .001\nb = -2.2394927233501036\nbstd= .001\n\n\n\nmodel = hmm.GaussianHMM(n_components=2, covariance_type=\"full\" ,algorithm='viterbi' )\n# model.startprob_ = np.array([0.88, 0.12])\nmodel.startprob_ = np.array([0.98, 0.02])\nmodel.transmat_ = np.array([[0.9999, 0.0001] , [0.0001, 0.9999]])\nmodel.means_ = np.array([[a, astd], [b, bstd]])\nmodel.covars_ = np.tile(np.identity(2), (2, 1, 1))\n\n\nposterior = model.predict_proba(X)\n# print(posterior)\nprint(posterior[54150:54200])\nprint(\"------------------------------------------\")\nprint(posterior[56980:57050])\nprint(\"------------------------------------------\")\nprint(posterior[71000:71100])\n\nhiddenStates = model.predict(X)\n# print(hiddenStates)\n\nscore = model.score(X)\n\nfig = plt.figure(figsize=(15,8))\nax = fig.add_subplot(2,1,1)\nax.set_title(\"Hidden Markov Models - ClonalFrame and Recombination -- log probability of the most likely state is \" + str (score))\nax.plot(hiddenStates)\nax.set_ylabel(\"Clonal - NonClonal State\")\n\n\n\nax2 = fig.add_subplot(2,1,2)\nax2.plot(posterior)\nax2.set_ylabel(\"posterior probability for each state\")\nplt.show()\n\n\n\n\n\n\n\n\n\n\n\n\n# newmodel = hmm.GaussianHMM(n_components=2 ,covariance_type=\"full\",params = 'st').fit(X)\n# newmodel.startprob_ = np.array([0.88, 0.12])\n# newmodel.transmat_ = np.array([[0.9999, 0.0001] , [0.0001, 0.9999]])\n# print(newmodel)\n#\n# print(\"emission-means:\")\n# print(newmodel.means_)\n# print(\"emission-covar:\")\n# print(newmodel.covars_)\n#\n# print(newmodel.startprob_)\n# print(newmodel.transmat_)\n#\n#\n# posterior = newmodel.predict_proba(X)\n# hiddenStates = newmodel.predict(X)\n# score = newmodel.score(X)\n#\n# fig = plt.figure(figsize=(15,8))\n# ax = fig.add_subplot(2,1,1)\n# ax.set_title(\"Hidden Markov Models - ClonalFrame and Recombination -- log probability of the most likely state is \" + str (score))\n# ax.plot(hiddenStates)\n# ax.set_ylabel(\"Clonal - NonClonal State\")\n#\n#\n# ax2 = fig.add_subplot(2,1,2)\n# ax2.plot(posterior)\n# ax2.set_ylabel(\"posterior probability for each state\")\n# plt.show()\n\n","sub_path":"HMM.py","file_name":"HMM.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"175331336","text":"# Artificial Neural Network \n\n# Evaluating the ANN - with cross validation score\n\n# Installing Theano\n# pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git\n\n# Installing Tensorflow\n# pip install tensorflow\n\n# Installing Keras\n# pip install --upgrade keras\n\n# Part 1 - Data Preprocessing\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset\ndataset = pd.read_csv('Churn_Modelling.csv')\nX = dataset.iloc[:, 3:13].values\ny = dataset.iloc[:, 13].values\n\n# Encoding categorical data\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nlabelencoder_X_1 = LabelEncoder()\nX[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])\nlabelencoder_X_2 = LabelEncoder()\nX[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])\nonehotencoder = OneHotEncoder(categorical_features = [1])\nX = onehotencoder.fit_transform(X).toarray()\nX = X[:, 1:]\n\n# Splitting the dataset into the Training set and Test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\n\n# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\n\n# Part 2 - Now let's make the ANN!\n\n# Importing the Keras libraries and packages\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Dropout\n\n# Initialising the ANN\nclassifier = Sequential()\n\n# Adding the input layer and the first hidden layer\nclassifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11))\n# classifier.add(Dropout(p = 0.1))\n\n# Adding the second hidden layer\nclassifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu'))\n# classifier.add(Dropout(p = 0.1))\n\n# Adding the output layer\nclassifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))\n\n# Compiling the ANN\nclassifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])\n\n# Fitting the ANN to the Training set\nclassifier.fit(X_train, y_train, batch_size = 10, epochs = 100)\n\n# Part 3 - Making predictions and evaluating the model\n\n# Predicting the Test set results\ny_pred = classifier.predict(X_test)\ny_pred = (y_pred > 0.5)\n\n# Predicting a single new observation\n\"\"\"Predict if the customer with the following informations will leave the bank:\nGeography: France\nCredit Score: 600\nGender: Male\nAge: 40\nTenure: 3\nBalance: 60000\nNumber of Products: 2\nHas Credit Card: Yes\nIs Active Member: Yes\nEstimated Salary: 50000\"\"\"\nnew_prediction = classifier.predict(sc.transform(np.array([[0.0, 0, 600, 1, 40, 3, 60000, 2, 1, 1, 50000]])))\nnew_prediction = (new_prediction > 0.5)\n\n# Making the Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, y_pred)\n\n# Part 4 - Evaluating, Improving and Tuning the ANN\n\n# Evaluating the ANN\n\n# We introduce Bias variance tradeoff\n# you will get variant accuracy of the model when you train several times.\n# Before we have taken the data as training set and teat set and we train the model on trian set and test the model on test dataset\n# This is not the best one we got the variance problem when we get the accuracy on test set , when you run the model again and you test on testset.we can get a very different accuracy.Judging the model performace on only one test set is not super releavant to evaluate the model performace . SO this techinique is called K-fold Cross validation because that will fix this variant problem.This will fix it the training set into 10 fold and we will train our model on 9 fold and test on last remaining fold.we can train the model on 10 combination of training and test set.Take a average of accuracy of 10 evaluation and also compute the standard deviation, you have to look at the variants.Eventually our analysis will be much more relevance,besides we know these 4 catagories.\n#1. High Bias Low variance (small accuracy on low variance)\n#2.High Bias High Variance ( Low accuracy and high variance)\n#3.Low Bias Low Variance (good accuracy small variance)\n#4.Low Bias High Variance (Large accuracy and high variance\n\n# we will build this using keras and scikit learn.\n\n# import kerasClassifier wrapper\nfrom keras.wrappers.scikit_learn import KerasClassifier\n\n# impoet cross validation score for K- fold cross validation\nfrom sklearn.model_selection import cross_val_score\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense\n\n# This functionwill return the classifier from your network.Just build the architecture of your ANN\ndef build_classifier():\n classifier = Sequential()\n classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11))\n classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu'))\n classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))\n classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])\n return classifier\n\n# This classifier is not build based on whole x_train and y_train dataset.It build on cross validation for 10 fold, by each time it's measuring the model performance for one test fold. \n\n# create the clasifier\nclassifier = KerasClassifier(build_fn = build_classifier, batch_size = 10, epochs = 100)\n# create class validation : estimator is classifier , X is data to fit, Y is target variable and cv is the number of fold of train and test set for applying k-fold cross validation.n_job to apply to use number of cpu to get run faster.\n# we will see different training on different train fold run at the same time.\naccuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1)\n# take mean of the all 10 cross validation accuracies\nmean = accuracies.mean()\nvariance = accuracies.std()\n","sub_path":"Artificial_Neural_Networks/ANN_evaluating.py","file_name":"ANN_evaluating.py","file_ext":"py","file_size_in_byte":5953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"169247837","text":"from __future__ import absolute_import\nimport os\nimport io\nimport json\nimport sys\nimport logging\nimport argparse\nfrom subprocess import Popen, PIPE\n\nfrom src.namespace_utils import Bunch, load_namespace, save_namespace\n\n\ndef bool_flag(s):\n \"\"\"\n Parse boolean arguments from the command line.\n\n ..note::\n Usage in argparse:\n parser.add_argument(\n \"--cuda\", type=bool_flag, default=True, help=\"Run on GPU\")\n\n \"\"\"\n if s.lower() in ['off', 'false', '0']:\n return False\n if s.lower() in ['on', 'true', '1']:\n return True\n raise argparse.ArgumentTypeError(\n \"invalid value for a boolean flag (0 or 1)\")\n\n\ndef setup_logger(logfile: str = \"\", loglevel: str = \"INFO\"):\n numeric_level = getattr(logging, loglevel, None)\n if not isinstance(numeric_level, int):\n raise ValueError(\"Invalid log level: %s\" % loglevel)\n logger = logging.getLogger()\n logging.basicConfig(\n format='%(asctime)s: %(levelname)s: %(message)s',\n level=numeric_level, stream=sys.stdout)\n fmt = logging.Formatter('%(asctime)s: %(levelname)s: %(message)s')\n if logfile != \"\":\n logfile_handle = logging.FileHandler(logfile, 'w')\n logfile_handle.setFormatter(fmt)\n logger.addHandler(logfile_handle)\n return logger\n\n\ndef setup_output_dir(args, loglevel):\n \"\"\"Setup the Experiment Folder\n Note that the output_dir stores each run as run-1, ....\n Makes the next run directory. This also sets up the logger\n A run directory has the following structure\n\n * run-1\n * models\n * modelname*.tar.gz\n * vocab\n * namespace_1.txt\n * namespace_2.txt ...\n * config.json\n * githash.log of current run\n * gitdiff.log of current run\n * logfile.log (the log of the current run)\n\n This also changes the config, to add the save directory\n\n Arguments:\n config (``allennlp.common.Params``): The experiment parameters\n loglevel (str): The logger mode [INFO/DEBUG/ERROR]\n Returns\n str, allennlp.common.Params: The filename, and the modified config\n \"\"\"\n if args.config_path is not None:\n FLAGS = load_namespace(args.config_path)\n else:\n FLAGS = Bunch(vars(args))\n output_dir = FLAGS.base_output_dir\n make_directory(output_dir, recursive=True)\n last_run = -1\n for dirname in os.listdir(output_dir):\n if dirname.startswith('run-'):\n last_run = max(last_run, int(dirname.split('-')[1]))\n new_dirname = os.path.join(output_dir, 'run-%d' % (last_run + 1))\n make_directory(new_dirname)\n best_model_dirname = os.path.join(new_dirname, 'models')\n make_directory(best_model_dirname)\n vocab_dirname = os.path.join(new_dirname, 'vocab')\n make_directory(vocab_dirname)\n\n config_file = os.path.join(new_dirname, 'config.json')\n save_namespace(FLAGS, config_file)\n\n # Save the git hash\n process = Popen(\n 'git log -1 --format=\"%H\"'.split(), stdout=PIPE, stderr=PIPE)\n stdout, stderr = process.communicate()\n stdout = stdout.decode('ascii').strip('\\n').strip('\"')\n with open(os.path.join(new_dirname, \"githash.log\"), \"w\") as fp:\n fp.write(stdout)\n\n # Save the git diff\n process = Popen('git diff'.split(), stdout=PIPE, stderr=PIPE)\n stdout, stderr = process.communicate()\n with open(os.path.join(new_dirname, \"gitdiff.log\"), \"w\") as fp:\n stdout = stdout.decode('ascii')\n fp.write(stdout)\n\n # Set up the logger\n logfile = os.path.join(new_dirname, 'logfile.log')\n setup_logger(logfile, loglevel)\n logger = logging.getLogger(__name__)\n logger.info(f\"Read config from {args.config_path}\")\n\n # modify experiment path\n setattr(FLAGS, \"base_output_dir\", new_dirname)\n return FLAGS\n\n\ndef write_config_to_file(filepath, config):\n \"\"\"Writes the config to a json file, specifed by filepath\n \"\"\"\n with io.open(filepath, 'w', encoding='utf-8', errors='ignore') as fd:\n json.dump(fp=fd,\n obj=config.as_dict(quiet=True),\n ensure_ascii=False, indent=4, sort_keys=True)\n\n\ndef make_directory(dirname, recursive=False):\n \"\"\"Constructs a directory with name dirname, if\n it doesn't exist. Can also take in a path, and recursively\n apply it.\n\n .. note::\n The recursive directory structure may cause issues on a windows\n system.\n \"\"\"\n try:\n os.makedirs(dirname, exist_ok=True)\n except OSError:\n raise\n","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"382549544","text":"# week 3 - finger exercises\n##def iterMul(a, b):\n## result = 0\n## while b > 0:\n## result += a\n## b -= 1\n## return result\n\n# Write an iterative function iterPower(base, exp)\n# that calculates the exponential 'base**exp' by\n# simply using successive multiplication.\n# For example, iterPower(base, exp) should compute 'base**exp'\n# by multiplying base times itself exp times.\n# Write such a function below.\n\n# This function should take in two values -\n# base can be a float or an integer;\n# exp will be an integer > 0.\n# It should return one numerical value.\n# Your code must be iterative - use of the\n# ** operator is not allowed. \n\ndef iterPower(base, exp):\n '''\n base: int or float.\n exp: int >= 0\n \n returns: int or float, base^exp\n >>> iterPower(2, 3):\n 8\n >>> iterPower(10, 4):\n 10000\n >>> iterPower(-5, 5):\n -3126\n >>> iterPower(4.5, 3):\n 91.125\n '''\n result = 1\n while exp > 0:\n result = result * base\n exp -= 1\n return result\n\n# Recursive version\n# a * b = a + a + ... + a\n# ---------> b copies\n# OR\n# a * b = a + a + ... + a\n# -------------> b-1 copies\n# = a + a * (b - 1)\n\ndef recurMul(a, b):\n if b == 1:\n return a\n else:\n return a + recurMul(a, b-1)\n\ndef factI(n):\n \"\"\"assumes that n is an int > 0\n returns n!\"\"\"\n res = 1\n while n > 1:\n res = res * n\n n -= 1\n return res\n\ndef factR(n):\n \"\"\"assumes that n is an int > 0\n returns n!\"\"\"\n if n == 1:\n return n\n return n*factR(n-1)\n\n\ndef recurPower(base, exp):\n '''\n base: int or float.\n exp: int >= 0\n \n returns: int or float, base^exp\n >>> recurPower(5, 5):\n 3125\n >>> recurPower(-3, 4):\n -81\n >>> recurPower(4.5, 7):\n 37366.9453125 \n '''\n if exp <= 0:\n return 1\n return base*recurPower(base, exp-1)\n\n\ndef recurPowerNew(base, exp):\n '''\n base: int or float.\n exp: int >= 0\n\n returns: int or float; base^exp\n '''\n\ndef recurPowerNew(base, exp):\n '''\n base: int or float.\n exp: int >= 0\n\n returns: int or float; base^exp\n '''\n # Base case is when exp = 0\n if exp <= 0:\n return 1\n\n # Recursive case 1: exp > 0 and even\n elif exp % 2 == 0:\n return recurPowerNew(base*base, exp/2)\n\n # Otherwise, exp must be > 0 and odd, so use the second\n # recursive case.\n return base * recurPowerNew(base, exp - 1)\n\n\n\n\n\n\n\ndef recurPowerNew(base, exp):\n '''\n base: int or float.\n exp: int >= 0\n\n returns: int or float; base^exp\n '''\n if exp <= 0:\n return 1\n elif exp % 2 == 0:\n return recurPowerNew(base*base, exp/2)\n return base * recurPowerNew(base, exp - 1)\n\n\ndef gcdIter(a, b):\n '''\n a, b: positive integers\n \n returns: a positive integer, the greatest common divisor of a & b.\n >>> gcdIter(2, 12)\n 2\n >>> gcdIter(6, 12)\n 6\n >>> gcdIter(9, 12)\n 3\n >>> gcdIter(17, 12)\n 1\n '''\n testvalue = min(a, b)\n while a % testvalue != 0 or b % testvalue != 0:\n testvalue -= 1\n return testvalue\n\ndef gcdRecur(a, b):\n '''\n a, b: positive integers\n \n returns: a positive integer, the greatest common divisor of a & b.\n '''\n if b == 0:\n return a\n else:\n return gcdRecur(b, a % b)\n \n# Towers of Hanoi\n\ndef printMove(fr, to):\n print('move from ' + str(fr) + ' to ' + str(to))\n\ndef Towers(n, fr, to, spare):\n if n == 1:\n printMove(fr, to)\n else:\n Towers(n-1, fr, spare, to)\n Towers(1, fr, to, spare)\n Towers(n-1, spare, to, fr)\n\n# Fibonacci number\n\ndef fib(x):\n \"\"\"assumes x an int >= 0\n returns Fibonacci of x\"\"\"\n assert type(x) == int and x >= 0\n if x == 0 or x == 1:\n return 1\n else:\n return fib(x-1) + fib(x-2)\n\n\n\ndef isPalindrome(s):\n\n def toChars(s):\n s = s.lower()\n ans = ''\n for c in s:\n if c in 'abcdefghijklmnopqrstuvwxyz':\n ans = ans + c\n return ans\n\n# Recursion on string - palindrome\n\ndef isPal(s):\n if len(s) <= 1:\n return True\n else:\n return s[0] == s[-1] and isPal(s[1:-1])\n return isPal(toChars(s))\n\n# finger exercise L5.6\n\ndef lenIter(aStr):\n '''\n aStr: a string\n \n returns: int, the length of aStr\n '''\n result = 0\n for char in aStr:\n result += 1\n return result\n\n# finger exercise L5.7\n\ndef lenRecur(aStr):\n '''\n aStr: a string\n \n returns: int, the length of aStr\n '''\n result = 0\n if aStr == '':\n return 0\n return 1 + lenRecur(aStr[1:])\n\n\n# finger exercise L5.8\n\ndef isIn(char, aStr):\n '''\n char: a single character\n aStr: an alphabetized string\n \n returns: True if char is in aStr; False otherwise\n '''\n\n if aStr == '':\n return False\n if len(aStr) == 1:\n return aStr == char\n midIndex = len(aStr) / 2\n midChar = aStr[midIndex]\n if char == midChar:\n return True\n elif char < midChar:\n return isIn(char, aStr[:midIndex])\n else:\n return isIn(char, aStr[midIndex:])\n\n# finger exercise L5.9\n\ndef semordnilapWrapper(str1, str2):\n # A single-length string cannot be semordnilap\n if len(str1) == 1 or len(str2) == 1:\n return False\n\n # Equal strings cannot be semordnilap\n if str1 == str2:\n return False\n\n return semordnilap(str1, str2)\n\ndef semordnilap(str1, str2):\n '''\n str1: a string\n str2: a string\n \n returns: True if str1 and str2 are semordnilap;\n False otherwise.\n >>> semordnilap(\"abc\", \"cba\")\n True\n >>> semordnilap(\"god\", \"dog\")\n True\n '''\n if len(str1) != len(str2):\n return False\n if len(str1) == 1:\n return str1 == str2\n if str1[0] == str2[-1]:\n return semordnilap(str1[1:], str2[:-1])\n\ndef fibMetered(x):\n global numCalls\n numCalls += 1\n if x == 0 or x == 1:\n return 1\n else:\n return fibMetered(x-1) + fibMetered(x-2)\n\n\ndef testFib(n):\n for i in range(n+1):\n global numCalls\n numCalls = 0\n print('fib of ' + str(i) + ' = ' + str(fibMetered(i)))\n print('fib called ' + str(numCalls) + ' times')\n\n\n","sub_path":"week 3/wk3_lecture5.py","file_name":"wk3_lecture5.py","file_ext":"py","file_size_in_byte":6218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"647707962","text":"from twilio.rest import Client\nimport sendgrid\nfrom sendgrid.helpers.mail import *\nimport os\n\ndef twilio_send(number, message):\n # Find these values at https://twilio.com/user/account\n account_sid = os.environ['TWILIO_API_KEY']\n auth_token = os.environ['TWILIO_SECRET_KEY']\n source_number = os.environ['TWILIO_SOURCE_NUMBER']\n\n print(\"%s - %s \" % (account_sid, auth_token))\n try:\n client = Client(account_sid, auth_token)\n print(\"client\")\n client.api.account.messages.create(\n to=number,\n from_=source_number,\n body=message)\n print(client.http_client.last_response.status_code)\n return True\n except Exception as e:\n print('Something Happened while sending message to %s - %s' % (message, str(e)))\n return False\n\n return False\n\ndef sendgrid_send(email, message):\n\n sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))\n from_email = Email(\"Clear Your Cabinet New York \")\n to_email = Email(email)\n subject = \"Thank you for signing up for a take-back reminder.\"\n content = Content(\"text/html\", message)\n mail = Mail(from_email, subject, to_email, content)\n response = sg.client.mail.send.post(request_body=mail.get())\n\n return response\n","sub_path":"twilio_mgr/management/commands/helper/sender.py","file_name":"sender.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"638564456","text":"# Copyright 2020 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\")\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport unittest\nimport testing_config # Must be imported before the module under test.\n\nimport mock\nimport webapp2\n\nfrom google.appengine.api import users\n\nimport common\nimport models\n\n\nclass MockHandler(object):\n\n def __init__(self, path):\n self.handler_called_with = None\n self.redirected_to = None\n self.request = self\n self.path = path\n\n @common.strip_trailing_slash\n def handlerMethod(self, *args):\n self.handler_called_with = args\n\n def redirect(self, new_path):\n self.redirected_to = new_path\n\n\nclass CommonFunctionTests(unittest.TestCase):\n\n def test_strip_trailing_slash(self):\n handlerInstance = MockHandler('/request/path')\n handlerInstance.handlerMethod('/request/path')\n self.assertEqual(('/request/path',), handlerInstance.handler_called_with)\n self.assertIsNone(handlerInstance.redirected_to)\n\n handlerInstance = MockHandler('/request/path/')\n handlerInstance.handlerMethod('/request/path/')\n self.assertIsNone(handlerInstance.handler_called_with)\n self.assertEqual('/request/path', handlerInstance.redirected_to)\n\n\nclass BaseHandlerTests(unittest.TestCase):\n\n def setUp(self):\n self.user_1 = models.AppUser(email='registered@example.com')\n self.user_1.put()\n\n request = webapp2.Request.blank('/some/path')\n response = webapp2.Response()\n self.handler = common.BaseHandler(request, response)\n\n def tearDown(self):\n self.user_1.delete()\n\n def test_user_can_edit__anon(self):\n \"\"\"Anon visitors cannot edit features.\"\"\"\n actual = self.handler.user_can_edit(None)\n self.assertFalse(actual)\n\n def test_user_can_edit__normal(self):\n \"\"\"Non-registered signed in users cannot edit features.\"\"\"\n u = users.User(email='user@example.com')\n actual = self.handler.user_can_edit(u)\n self.assertFalse(actual)\n\n def test_user_can_edit__registered(self):\n \"\"\"Users who have been registed by admins may edit features.\"\"\"\n u = users.User(email='registered@example.com')\n actual = self.handler.user_can_edit(u)\n self.assertTrue(actual)\n\n def test_user_can_edit__preferred_domains(self):\n \"\"\"Users signed in with certain email addresses may edit.\"\"\"\n u = users.User(email='user@chromium.org')\n actual = self.handler.user_can_edit(u)\n self.assertTrue(actual)\n\n u = users.User(email='user@google.com')\n actual = self.handler.user_can_edit(u)\n self.assertTrue(actual)\n\n u = users.User(email='user@this-is-not-google.com')\n actual = self.handler.user_can_edit(u)\n self.assertFalse(actual)\n\n u = users.User(email='user@this-is-not.google.com')\n actual = self.handler.user_can_edit(u)\n self.assertFalse(actual)\n","sub_path":"tests/common_test.py","file_name":"common_test.py","file_ext":"py","file_size_in_byte":3218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"443940581","text":"\n\nfrom xai.brain.wordbase.nouns._swede import _SWEDE\n\n#calss header\nclass _SWEDES(_SWEDE, ):\n\tdef __init__(self,): \n\t\t_SWEDE.__init__(self)\n\t\tself.name = \"SWEDES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"swede\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_swedes.py","file_name":"_swedes.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"585186092","text":"# 2588 곱셈\nif __name__ == \"__main__\":\n arr = []\n while True:\n try:\n temp = int(input())\n except:\n break\n else:\n arr.append(temp)\n\n unit = [(arr[-1] - (arr[-1] % 100)) // 100, (arr[-1] - ((arr[-1] // 100) * 100) - (arr[-1] % 10)) // 10, arr[-1] % 10]\n unit.reverse()\n for i in unit:\n print(arr[0] * i)\n print(arr[0] * arr[-1])","sub_path":"Baekjoon/2588.py","file_name":"2588.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"570452780","text":"#%%\r\nimport colour\r\nimport numpy as np\r\ndef get_main_color(R,G,B):\r\n sRGB = [R/255,G/255,B/255]\r\n RGB = np.array(sRGB)\r\n XYZ = colour.sRGB_to_XYZ(sRGB)\r\n Lab = colour.XYZ_to_Lab(XYZ)\r\n LCHab = colour.Lab_to_LCHab(Lab)\r\n L = int(LCHab[0]);C = int(LCHab[1]);ab = int(LCHab[2])\r\n print([L,C,ab])\r\n if C<40:# 1\r\n if L<10:\r\n return 'black'\r\n elif L>90:\r\n return 'white'\r\n else:\r\n return 'gray'\r\n elif ab<45:# 2\r\n if L<30:\r\n return 'brown'\r\n elif L>70:\r\n return 'pink'\r\n else:\r\n return 'red'\r\n elif ab<75:# 3\r\n if L<30:\r\n return 'brown'\r\n else:\r\n return 'orange'\r\n elif ab<105:# 4\r\n return 'yellow'\r\n elif ab<210:# 5\r\n return 'green'\r\n elif ab<315:# 6\r\n return 'blue'\r\n elif ab>330:# 7\r\n if L>50:\r\n return 'pink'\r\n else:\r\n return 'purple'\r\n else:\r\n return 'purple'\r\nget_main_color(5,5,5)\r\n#%%","sub_path":"Graduate School/Python related/Main color analysis/Main color function.py","file_name":"Main color function.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"197961491","text":"from django.core.mail import send_mail, EmailMessage, EmailMultiAlternatives\nfrom ScrumMaster import settings\nfrom smtplib import SMTPException\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User, Group\nfrom django.http import HttpResponseRedirect, JsonResponse, HttpResponse, HttpRequest\nfrom django.urls import reverse\nfrom django.contrib import messages\nfrom django.utils.dateparse import parse_datetime\nfrom .models import *\nfrom .serializer import *\nfrom rest_framework import viewsets, status\nfrom rest_framework.views import APIView\nfrom rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAuthenticated\nfrom rest_framework.decorators import api_view, permission_classes, authentication_classes\nfrom rest_framework_jwt.authentication import JSONWebTokenAuthentication\nfrom rest_framework.serializers import ValidationError\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.response import Response\nfrom django.core import serializers\nfrom django.core.files.storage import FileSystemStorage\nfrom django.conf import settings\nfrom django.views.decorators.csrf import csrf_exempt\nfrom slack import WebClient\nfrom django.template import Template, Context\n\nfrom channels.layers import get_channel_layer\nfrom asgiref.sync import async_to_sync\nimport random\nimport datetime\nimport re\nimport json\nimport hashlib\nimport boto3\nimport html\n\nfrom Scrum.initials import *\n\n\nfrom time import sleep\n\n\n@csrf_exempt\ndef test(request): \n return JsonResponse({'message': 'hello daud'}, status=200)\n \n\n@csrf_exempt\ndef _parse_body(body):\n body_unicode = body.decode('utf-8')\n return json.loads(body_unicode)\n\n@csrf_exempt\ndef connect(request):\n body = _parse_body(request.body)\n connection_id = body['connectionId']\n print('connect successful')\n # Connection(connection_id=connection_id, project_name=\"TestProj\").save()\n\n return JsonResponse(\n {'message': 'connect successfully'}, status=200\n )\n\n\n@csrf_exempt\ndef connect_to_project(request):\n body = _parse_body(request.body)\n connection_id = body['connectionId']\n project_id = body['body']['project_id']\n\n\n proj = ScrumProject.objects.get(pk=project_id)\n print(\"Connecting to project \", project_id, \" with connect id \", connection_id ) \n Connection(connection_id=connection_id, project=proj).save()\n \n\n return JsonResponse(\n {'message': 'connect successfully'}, status=200\n ) \n\n\n@csrf_exempt\ndef disconnect(request):\n body = _parse_body(request.body)\n connection_id = body['connectionId']\n\n Connection.objects.filter(connection_id=connection_id).delete()\n return JsonResponse(\n {'message': 'disconnect successfully'}, status=200\n )\n\ndef _send_to_connection(connection_id, data):\n gatewayapi = boto3.client( \n \"apigatewaymanagementapi\",\n endpoint_url= settings.AWS_WS_GATEWAY, \n region_name= settings.AWS_REGION, \n aws_access_key_id= settings.AWS_ACCESS_KEY_ID,\n aws_secret_access_key= settings.AWS_SECRET_ACCESS_KEY, \n )\n print(settings.AWS_WS_GATEWAY)\n return gatewayapi.post_to_connection(\n ConnectionId=connection_id,\n Data=json.dumps(data).encode('utf-8')\n )\n\n\n\n# @csrf_exempt\n# def send_message(project_id):\n# filtered_usr1 = filtered_users(project_id)\n# filtered_usr = json.dumps({'body': filtered_usr1})\n# print(\"Filter user 1:::::::::::::::::::::::::::::\", filtered_usr1)\n# print(\"Filter user #########################\", filtered_usr)\n# # # Get all current connections\n# connections = Connection.objects.filter(project=project_id)\n\n# output = {\n# 'Message': \"This is websocket\",\n# 'data':filtered_usr1\n# }\n\n# data = {'messages':output}\n# # # Send the message data to all connections\n# for connection in connections:\n# _send_to_connection(\n# connection.connection_id, data\n# )\n \n# return JsonResponse(\n# {'message': 'successfully send'}, status=200\n# )\n\ndef createHistory(name, status, goal_project_id, hours, time_created, user, project, file, goal, message):\n concat_message = message + self.request.user.username\n print(concat_message)\n goal = ScrumGoalHistory (name=name, status=status, time_created = time_created, goal_project_id=goal_project_id, user=user, project=project, file=file, goal_id=goal, done_by=self.request.user, message=concat_message)\n goal.save()\n@csrf_exempt\ndef send_message(request):\n body = _parse_body(request.body)\n username = body['body']['username']\n project_name = body['body']['project_id']\n message = body['body']['message']\n timestamp = body['body']['timestamp']\n token = body['body']['token']\n\n \n\n try:\n Token.objects.get(key=token)\n \n\n \n proj = ScrumProject.objects.get(pk=project_name)\n current_user = ScrumUser.objects.get(nickname=username).user\n\n connections = Connection.objects.filter(project=proj)\n\n my_message = {\"username\":username, \"project_name\":project_name, \"message\":message, \"timestamp\":timestamp}\n\n data = {'messages':[my_message]}\n \n '''\n for connection in connections:\n _send_to_connection(connection.connection_id, data)\n '''\n\n slack_id = ChatSlack.objects.get(username=username, project=proj).slack_user_id\n\n print(slack_id)\n pattern = re.compile(r'@[a-zA-Z]+')\n\n split_message = message.split(\" \")\n # old_answerlist = pattern.findall(message)\n answer_list = pattern.findall(message)\n verify_array = []\n print(answer_list)\n\n\n for answer in answer_list:\n if answer not in verify_array:\n temp = answer\n verify_array.append(temp)\n\n try:\n if temp[-1]== \"\\n\":\n temp = temp[0:-1] \n scrumuser = ScrumUser.objects.get(nickname=temp[1:]).user\n id_slack = ScrumSlack.objects.get(scrumproject=proj, scrum_details=scrumuser).user_id\n message = message.replace(answer, \"<\" + '@' + id_slack + \">\")\n except:\n pass\n print(1)\n try:\n next_message = (split_message[split_message.index(temp)+1])\n if next_message[-1] == \"\\n\":\n next_message = next_message = (split_message[split_message.index(temp)+1])[0:-1]\n nickname = str(temp[1:] + \" \" + next_message)\n \n print((nickname))\n my_nickname = ScrumUser.objects.get(nickname = nickname).nickname\n \n print(\"gotten 2\")\n print(message)\n value = str(answer + \" \" + next_message)\n scrumuser = ScrumUser.objects.get(nickname=value[1:]).user\n print(scrumuser)\n id_slack = ScrumSlack.objects.get(scrumproject=proj, scrum_details=scrumuser).user_id\n print(id_slack)\n new_value = \"<\" +'@' + id_slack + \">\"\n \n message = message.replace(value, new_value)\n\n \n \n except:\n pass\n try:\n second_message = (split_message[split_message.index(temp)+1])\n third_message = (split_message[split_message.index(temp)+2])\n if third_message[-1] =='\\n':\n third_message = (split_message[split_message.index(temp)+2])[0:-1]\n\n value = str(answer + \" \" + second_message + \" \" + third_message)\n print(value)\n print(len(value))\n \n scrumuser = ScrumUser.objects.get(nickname=value[1:]).user\n \n id_slack = ScrumSlack.objects.get(scrumproject=proj, scrum_details=scrumuser).user_id\n \n new_value = \"<\" + '@' + id_slack + \">\"\n \n \n message = message.replace(value, new_value)\n print(\"done\")\n \n\n\n except:\n pass\n \n print(message)\n\n \n\n \n \n \n slack_details = ScrumSlack.objects.get(scrumproject=proj, user_id = slack_id)\n print(\"sent to slack\")\n channel_id = slack_details.channel_id\n bot_access_token = slack_details.access_token\n scrumuser = ScrumUser.objects.get(nickname = username)\n scrum_proj_role = ScrumProjectRole.objects.get(project=proj, user=scrumuser)\n profile_picture = scrum_proj_role.slack_profile_picture \n \n sc = WebClient(bot_access_token)\n \n sc.chat_postMessage(\n \n channel= channel_id,\n username = username,\n text = message,\n #as_user = True,\n #icon_url = profile_picture\n\n\n ).headers['X-Slack-No-Retry'] = 1\n \n return JsonResponse(\n {'message': 'successfully send'}, status=200\n )\n\n except:\n return JsonResponse({'message': 'Token not authenticated'})\n\n\n\n #Fetch all recent Messages for a particular project in the database\n@csrf_exempt\n@permission_classes((IsAuthenticated, ))\n@authentication_classes((JSONWebTokenAuthentication,))\ndef get_recentmessages(request):\n body = _parse_body(request.body)\n connectionId = body['connectionId']\n project_id = body['body']['project_id']\n token = body['body']['token']\n proj = ScrumProject.objects.get(pk=project_id)\n project_name = proj.name\n\n try:\n Token.objects.get(key=token)\n\n #Fetch all recent messages by their project name\n all_messages = ChatMessage.objects.filter(project_name=project_name).order_by('-id')[:80]\n result_list =(list(all_messages.values('username', 'project_name', 'message', 'timestamp', 'profile_picture')))\n \n data = {\"type\":\"all_messages\",\"messages\":result_list[::-1]}\n \n \n _send_to_connection(\n connectionId,\n data\n )\n \n \n return JsonResponse(\n {\"message\":\"all recent messages gotten\"},\n status = 200\n )\n \n\n except:\n return JsonResponse({'message': 'Token not authenticated'})\n\nclass GetAllUsernames(viewsets.ModelViewSet):\n queryset = ScrumProject.objects.all()\n serializer_class = ScrumProjectSerializer\n\n def create(self, request):\n project_id = request.data['project_id']\n project = ScrumProject.objects.get(pk=project_id)\n all_users = []\n\n project_role = ScrumProjectRole.objects.filter(project=project)\n \n for proj in project_role:\n username = proj.user.nickname\n all_users.append(username)\n\n return JsonResponse({\"message\":\"Project Users gotten\", \"data\":all_users})\n\n\n\nclass GetProjectGoals(viewsets.ModelViewSet):\n #queryset = ScrumProject.objects.all()\n #serializer_class = ScrumProjectSerializer\n\n def create(self, request, *args, **kwargs):\n \n print(request.body)\n body = _parse_body(request.body)\n connectionId = body['connectionId']\n project_id = body['body']['project_id']\n token = body['body']['token']\n\n try: \n Token.objects.get(key=token)\n query = ScrumProject.objects.get(pk=project_id)\n slack_installed = query.scrumslack_set.all().exists()\n # slack_app_id = ChatscrumSlackApp.objects.all().first()\n my_data = {\"type\":\"get_goals\", \"project_name\":query.name, \"data\":filtered_users(project_id), \"slack_installed\":slack_installed}\n \n _send_to_connection(connectionId, my_data)\n return JsonResponse({\"message\":\"\"})\n except ScrumProject.DoesNotExist:\n return JsonResponse({'detail': 'Not found.'})\n\n \nclass GetAllMessagesViewSet(viewsets.ModelViewSet):\n queryset = ChatMessage.objects.all()\n serializer_class = ChatMessageSerializer\n\n\n def create(self, request):\n project_name = request.data['project_name']\n token = request.data['token']\n\n try:\n query= ChatMessage.objects.filter(project_name = project_name).order_by('-id')[:80]\n values = list(query.values('username', 'project_name', 'message', 'timestamp', 'profile_picture'))\n data = values[::-1]\n \n \n\n except:\n return JsonResponse({\"message\":\"not found\"})\n\n return JsonResponse({\"message\":data})\n\n\nclass ChangeGoalOwnerViewSet(viewsets.ModelViewSet):\n queryset = ScrumGoal.objects.all()\n serializer_class = ScrumGoalSerializer\n\n\n def create(self, request):\n body = _parse_body(request.body)\n connectionId = body['connectionId']\n project_id = body['body']['project_id']\n from_id = body['body']['from_id'][1:]\n to_id = body['body']['to_id'][1:]\n token = body['body']['token']\n\n try:\n Token.objects.get(key=token)\n scrum_project = ScrumProject.objects.get(id=project_id)\n scrum_project_role = scrum_project.scrumprojectrole_set.get(user=request.user.scrumuser)\n\n if (scrum_project_role.role == \"Developer\" or scrum_project_role.role == \"Quality Analyst\"):\n return JsonResponse({'message':\"You are not allowed to move goal\"})\n\n goal = scrum_project.scrumgoal_set.get(goal_project_id=from_id, moveable=True)\n if goal.moveable == True:\n print(to_id)\n author = ScrumProjectRole.objects.get(id=to_id)\n goal.user = author\n createHistory(goal.name, goal.status, goal.goal_project_id, goal.hours, goal.time_created, goal.user, goal.project, goal.file, goal.id, 'Goal Reassigned Successfully by')\n goal.save()\n data = {'message': 'Goal Reassigned Successfully!', 'data': filtered_users(project_id)}\n connection = Connection.objects.all()\n for connect in connection:\n _send_to_connection(\n connect.connection_id,\n data\n )\n # return JsonResponse({'message': 'Goal Reassigned Successfully!', 'data': filtered_users(project_id)})\n else:\n return JsonResponse({'message': 'Permission Denied: Sprint Period Elapsed!!!', 'data': filtered_users(request.data['project_id'])})\n\n except:\n return JsonResponse({'message':'You are not Authenticated'})\n\n\nclass MoveGoalViewSet(viewsets.ModelViewSet):\n queryset = ScrumGoal.objects.all()\n serializer_class = ScrumGoalSerializer\n\n def create(self, request):\n body = _parse_body(request.body)\n username = body['body']['username']\n user = User.objects.get(username=username)\n request.user = user\n \n \n \n goal_id = body['body']['goal_id'][1:]\n to_id = int(body['body']['to_id'])\n project_id = body['body']['project_id']\n hours = body['body']['hours']\n push_id = body['body']['push_id']\n scrum_project = ScrumProject.objects.get(id=project_id)\n scrum_project_a = scrum_project.scrumprojectrole_set.get(user=request.user.scrumuser)\n scrum_project_b = scrum_project.scrumgoal_set.get(goal_project_id=goal_id, moveable=True).user\n qa_list = ScrumProjectRole.objects.filter(project=scrum_project, role=\"Quality Analyst\")\n goal_item = scrum_project.scrumgoal_set.get(goal_project_id=goal_id, moveable=True)\n connections = Connection.objects.filter(project=scrum_project)\n print(goal_id)\n print(scrum_project_b.user.user)\n print(connections)\n print(goal_item.status)\n login = settings.LOGIN_URL\n \n\n \n if to_id == 4:\n if scrum_project_a.role == 'Developer':\n if request.user != scrum_project_b.user.user:\n data = {'type':'move_goal','message': 'Permission Denied: Unauthorized Deletion of Goal.', 'data': filtered_users(project_id)}\n \n for connect in connections:\n _send_to_connection(connect.connection_id, data)\n return JsonResponse({'message': 'Permission Denied: Unauthorized Deletion of Goal.', 'data': filtered_users(project_id)})\n \n del_goal = scrum_project.scrumgoal_set.get(goal_project_id=goal_id, moveable=True)\n del_goal.visible = False\n del_goal.save() \n createHistory(goal_item.name, goal_item.status, goal_item.goal_project_id, goal_item.hours, goal_item.time_created, goal_item.user, goal_item.project, goal_item.file, goal_item.id, 'Goal Removed Successfully by')\n data = {'type':'move_goal','message': 'Goal Removed Successfully!'}\n\n for connect in connections:\n _send_to_connection(connect.connection_id, data)\n return JsonResponse({'message': 'Goal Removed Successfully!'})\n else: \n group = scrum_project_a.role\n from_allowed = []\n to_allowed = []\n if group == 'Developer':\n if request.user != scrum_project_b.user.user:\n data = {'type':'move_goal','message': 'Permission Denied: Unauthorized Movement of Goal.', 'data': filtered_users(project_id)}\n for connect in connections:\n _send_to_connection(connect.connection_id, data)\n return JsonResponse({'message': 'Permission Denied: Unauthorized Movement of Goal.', 'data': filtered_users(project_id)})\n \n if group == 'Owner':\n from_allowed = [0, 1, 2, 3]\n to_allowed = [0, 1, 2, 3]\n elif group == 'Admin':\n from_allowed = [0, 1, 2]\n to_allowed = [0, 1, 2]\n elif group == 'Developer':\n from_allowed = [0, 1, 2]\n to_allowed = [0, 1, 2]\n elif group == 'Quality Analyst':\n from_allowed = [0, 1, 2, 3]\n to_allowed = [0, 1, 2, 3]\n \n state_prev = goal_item.status\n print(\"=======================PATCH REQUEST DATA======================\")\n print(body['body'])\n \n if (goal_item.status in from_allowed) and (to_id in to_allowed):\n goal_item.status = to_id\n elif group == 'Quality Analyst' and goal_item.status == 2 and to_id == 0:\n goal_item.status = to_id\n elif request.user == scrum_project_b.user.user:\n if goal_item.status == 1 and to_id == 0:\n goal_item.status = to_id\n elif goal_item.status == 0 and to_id == 1:\n goal_item.status = to_id\n else:\n print(request.user.scrumuser)\n data = {'type':'move_goal','message': 'Permission Denied: Unauthorized Movement of Goal.', 'data': filtered_users(project_id)}\n \n for connect in connections:\n _send_to_connection(connect.connection_id, data)\n return JsonResponse({'message': 'Permission Denied: Unauthorized Movement of Goal.', 'data': filtered_users(project_id)})\n else:\n data = {'type':'move_goal','message': 'Permission Denied: Unauthorized Movement of Goal.', 'data': filtered_users(project_id)}\n for connect in connections:\n _send_to_connection(connect.connection_id, data)\n return JsonResponse({'message': 'Permission Denied: Unauthorized Movement of Goal.', 'data': filtered_users(project_id)})\n if goal_item.moveable == True:\n message = 'Goal Moved Successfully!'\n if to_id == 2 and hours :\n goal_item.push_id = push_id\n goal_item.status = to_id\n goal_item.hours = goal_item.hours\n goal_item.push_id = push_id\n message = 'Goal Moved Successfully! Push ID is ' + push_id\n\n for qa in qa_list:\n email = qa.user.user.username\n context = Context({\"nickname\":request.user.scrumuser.nickname, \"goal_id\":goal_id, \"push_id\":push_id, \"qa_nickname\":qa.user.nickname, \"login\":login})\n\n template = Template('''\n \n \n \n \n\n \n
\n \n
\n
\n

Hi

{{qa_nickname}},

\n

\n {{nickname}} has just moved a goal to verify. \n

\n \n

Goal ID: {{goal_id}}

\n

Push ID: {{push_id}}

\n\n \n \n \n \n Login Here\n \n\n\n \n \n\n

Thanks,

\n

Chatscrum Team

\n

© Copyright 2020.

\n \n
\n \n \n \n\n ''')\n content = template.render(context)\n\n qa_email = EmailMessage(\n 'Verify task',\n content, \n settings.DEFAULT_FROM_EMAIL,\n [email]\n )\n\n qa_email.content_subtype = \"html\"\n qa_email.send(fail_silently=False)\n if hours > 8:\n goal_item.status = state_prev\n message = 'Error: Task cannot Exceeds 8hours or less than an hour of completion.'\n elif hours == -1 and goal_item.hours == -1 and to_id > 1:\n goal_item.status = state_prev\n message = 'Error: A Task must have hours assigned.'\n elif hours == -13:\n goal_item.status = state_prev\n if push_id == \"Canceled\":\n message = \"Error, No Work ID assigned\"\n else:\n message = 'Error: A Task must have hours assigned.'\n elif to_id == 2 and state_prev == 1 :\n goal_item.hours = hours\n message = 'Goal Moved Successfully! Hours Applied!'\n for qa in qa_list:\n email = qa.user.user.username\n context = Context({\"nickname\":request.user.scrumuser.nickname, \"goal_id\":goal_id, \"push_id\":push_id, \"qa_nickname\":qa.user.nickname, \"login\":login})\n\n template = Template('''\n \n \n \n \n\n \n
\n \n
\n
\n

Hi

{{qa_nickname}},

\n

\n {{nickname}} has just moved a goal to verify. \n

\n \n

Goal ID: {{goal_id}}

\n

Push ID: {{push_id}}

\n\n \n \n \n \n Login Here\n \n\n\n \n \n\n

Thanks,

\n

Chatscrum Team

\n

© Copyright 2020.

\n \n
\n \n \n \n\n ''')\n content = template.render(context)\n\n qa_email = EmailMessage(\n 'Verify task',\n content,\n settings.DEFAULT_FROM_EMAIL,\n [email]\n )\n\n qa_email.content_subtype = \"html\"\n qa_email.send(fail_silently=False)\n if to_id == 2 and hours < 8 and push_id == \"Null Value\":\n goal_item.status = state_prev\n message = 'Error: No PUSH-ID added.' \n\n\n if state_prev == 1 and to_id == 0:\n goal_item.days_failed = goal_item.days_failed + 1 \n \n self.createHistory(goal_item.name, goal_item.status, goal_item.goal_project_id, goal_item.hours, goal_item.time_created, goal_item.user, goal_item.project, goal_item.file, goal_item.id, 'Goal Moved Successfully by') \n goal_item.save()\n else:\n message = \"Sprint Period Elapsed, The Goal Cannot be Moved!\"\n data = {'type':'move_goal','message': message, 'data': filtered_users(project_id)}\n for connect in connections:\n _send_to_connection(connect.connection_id, {'type':'move_goal', 'data':data})\n return JsonResponse({'message': message, 'data': filtered_users(project_id)})\n\n def createHistory(self, name, status, goal_project_id, hours, time_created, user, project, file, goal, message):\n concat_message = message + self.request.user.username\n print(concat_message)\n goal = ScrumGoalHistory (name=name, status=status, time_created = time_created, goal_project_id=goal_project_id, user=user, project=project, file=file, goal_id=goal, done_by=self.request.user, message=concat_message)\n goal.save()\n return\n\n\nclass DeleteUserViewSet(viewsets.ModelViewSet):\n queryset = ScrumProjectRole.objects.all()\n serializer_class = ScrumProjectRoleSerializer\n\n def create(self, request):\n project_id = request.data['project_id']\n user_role = request.data['user_role']\n intended_user = request.data['intended_user']\n\n project = ScrumProject.objects.get(pk=project_id)\n \n\n role = ScrumProjectRole.objects.get(project=project, user=request.user.scrumuser).role\n\n if role == 'Developer' or role == 'Quality Analyst' or role == 'Admin':\n return JsonResponse({\"message\":\"Permission Denied\", \"data\":filtered_users(project_id)})\n\n # del_user = User.objects.get(pk=intended_user)\n author = ScrumProjectRole.objects.get(project=project, id=intended_user)\n if author.role == \"Owner\":\n return JsonResponse({\"message\":\"You cannot delete an Owner\", \"data\":filtered_users(project_id)})\n author.delete()\n return JsonResponse({\"message\":\"User deleted Successfully\", \"data\":filtered_users(project_id)})\n\n\n\n'''\ndef create_user(request):\n return render(request, \"create_user.html\")\n \ndef init_user(request):\n password = request.POST.get('password', None)\n rtpassword = request.POST.get('rtpassword', None)\n if password != rtpassword:\n messages.error(request, 'Error: Passwords Do Not Match.')\n return HttpResponseRedirect(reverse('Scrum:create_user'))\n user, created = User.objects.get_or_create(username=request.POST.get('username', None))\n if created:\n user.set_password(password)\n group = Group.objects.get(name=request.POST.get('usertype', None))\n group.user_set.add(user)\n user.save()\n scrum_user = ScrumUser(user=user, nickname=request.POST.get('full_name'), age=request.POST.get('age', None))\n scrum_user.save()\n messages.success(request, 'User Created Successfully.')\n return HttpResponseRedirect(reverse('Scrum:create_user'))\n else:\n messages.error(request, 'Error: Username Already Exists.')\n return HttpResponseRedirect(reverse('Scrum:create_user'))\n \ndef scrum_login(request):\n username = request.POST.get('username', None)\n password = request.POST.get('password', None)\n \n login_user = authenticate(request, username=username, password=password)\n if login_user is not None:\n login(request, login_user)\n return HttpResponseRedirect(reverse('Scrum:profile'))\n else:\n messages.error(request, 'Error: Invalid Credentials.')\n return HttpResponseRedirect(reverse('login'))\n \ndef profile(request):\n if request.user.is_authenticated:\n username = request.user.username\n user_info = request.user.scrumuser\n role = request.user.groups.all()[0].name\n goal_list = ScrumGoal.objects.order_by('user__nickname', '-id')\n nums = [x for x in range(4)]\n final_list = []\n item_prev = None\n \n for item in goal_list:\n if item.user != item_prev:\n item_prev = item.user\n final_list.append((item, goal_list.filter(user=item.user).count()))\n else:\n final_list.append((item, 0))\n \n context = {'username': username, 'user_info': user_info, 'role': role, 'goal_list': final_list, 'nums_list': nums}\n return render(request, \"profile.html\", context)\n else:\n messages.error(request, 'Error: Please login first.')\n return HttpResponseRedirect(reverse('login'))\n \ndef scrum_logout(request):\n logout(request)\n return HttpResponseRedirect(reverse('login'))\n \ndef add_goal(request):\n if request.user.is_authenticated:\n name_goal = request.POST.get('name', None)\n group_name = request.user.groups.all()[0].name\n status_start = 0\n if group_name == 'Admin':\n status_start = 1\n elif group_name == 'Quality Analyst':\n status_start = 2\n goal = ScrumGoal(user=request.user.scrumuser, name=name_goal, status=status_start)\n goal.save()\n messages.success(request, 'Goal Added Successfully.')\n return HttpResponseRedirect(reverse('Scrum:profile'))\n else:\n messages.error(request, 'Error: Please login first.')\n return HttpResponseRedirect(reverse('login'))\n \ndef remove_goal(request, goal_id):\n if request.user.is_authenticated:\n if request.user.groups.all()[0].name == 'Developer':\n if request.user != ScrumGoal.objects.get(id=goal_id).user.user:\n messages.error(request, 'Permission Denied: Unauthorized Deletion of Goal.')\n return HttpResponseRedirect(reverse('Scrum:profile'))\n \n del_goal = ScrumGoal.objects.get(id=goal_id)\n del_goal.delete()\n messages.success(request, 'Goal Removed Successfully.')\n return HttpResponseRedirect(reverse('Scrum:profile'))\n else:\n messages.error(request, 'Error: Please login first.')\n return HttpResponseRedirect(reverse('login'))\n \ndef move_goal(request, goal_id, to_id):\n if request.user.is_authenticated:\n goal_item = ScrumGoal.objects.get(id=goal_id)\n group = request.user.groups.all()[0].name\n from_allowed = []\n to_allowed = []\n \n if group == 'Developer':\n if request.user != goal_item.user.user:\n messages.error(request, 'Permission Denied: Unauthorized Movement of Goal.')\n return HttpResponseRedirect(reverse('Scrum:profile'))\n \n if group == 'Owner':\n from_allowed = [0, 1, 2, 3]\n to_allowed = [0, 1, 2, 3]\n elif group == 'Admin':\n from_allowed = [1, 2]\n to_allowed = [1, 2]\n elif group == 'Developer':\n from_allowed = [0, 1]\n to_allowed = [0, 1]\n elif group == 'Quality Analyst':\n from_allowed = [2, 3]\n to_allowed = [2, 3]\n \n if (goal_item.status in from_allowed) and (to_id in to_allowed):\n goal_item.status = to_id\n elif group == 'Quality Analyst' and goal_item.status == 2 and to_id == 0:\n goal_item.status = to_id\n else:\n messages.error(request, 'Permission Denied: Unauthorized Movement of Goal.')\n return HttpResponseRedirect(reverse('Scrum:profile'))\n \n goal_item.save()\n messages.success(request, 'Goal Moved Successfully.')\n return HttpResponseRedirect(reverse('Scrum:profile'))\n else:\n messages.error(request, 'Error: Please login first.')\n return HttpResponseRedirect(reverse('login'))\n'''\n\nclass ScrumFetchViewSet(viewsets.ModelViewSet):\n queryset = User.objects.all()\n serializer_class = ScrumUserFetchSerializer\n\n def create(self, request, username=None, *args, **kwargs):\n print(\"Okayyy\")\n \n email = request.data['username']\n print(email)\n \n \n get_user = User.objects.get(username=email)\n scrum_details = ScrumUser.objects.get(user=get_user)\n full_name = scrum_details.nickname\n \n print('done')\n return JsonResponse(\n {\n 'fullname': full_name,\n 'message': 'Details gotten sucessfully'\n }\n )\n \n\nclass ScrumEmailViewSet(viewsets.ModelViewSet):\n queryset = ScrumEmail.objects.all()\n serializer_class = ScrumEmailSerializer\n\n def create(self, request):\n\n messageTo = request.data['messagebody']\n emailTo = request.data['email']\n sent = send_mail('Invitation Email', 'Hello, You are invited to join chatscrum by clicking this link https://chatscrum.com/createuser . You are required to type ' + messageTo + ' in the project area when logging in. Thanks and regards.', 'admin@linuxjobber.com', [emailTo]) \n if sent:\n return JsonResponse({'message': 'Email sent Successfully.'})\n else:\n return JsonResponse({'message': 'Error: Email not sent.'})\n\n\ndef createDemoUser(request):\n demo_user = User.objects.create(username='demouser' + str(random.random())[2:])\n demo_user_password = 'demopassword' + str(random.random())[2:]\n demo_user.set_password(demo_user_password)\n demo_user.save()\n \n demo_scrumuser = ScrumUser(user=demo_user, nickname='Demo User')\n demo_scrumuser.save()\n \n demo_project_name = 'Demo Project #' + str(demo_user.pk)\n demo_project = ScrumProject(name=demo_project_name)\n demo_project.save()\n \n demo_projectrole = ScrumProjectRole(role=\"Owner\", user=demo_scrumuser, project=demo_project)\n demo_projectrole.save()\n \n demo_projectdemo = ScrumDemoProject(project=demo_project, expiration_date=datetime.datetime.now() + datetime.timedelta(hours=24))\n demo_projectdemo.save()\n \n return JsonResponse({'username': demo_user.username, 'password': demo_user_password, 'project': demo_project_name})\n \n\n\n\n\n\n\nclass ScrumUserViewSet(viewsets.ModelViewSet):\n queryset = ScrumUser.objects.all()\n serializer_class = ScrumUserSerializer\n \n def create(self, request):\n print(\"Testing New user create====================\")\n slack_app_id = ChatscrumSlackApp.objects.all().first().CLIENT_ID\n print(slack_app_id)\n\n \n # Pattern Match For an Email: https://www.regular-expressions.info/email.html\n regex_pattern = re.compile(r'(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)')\n if regex_pattern.match(request.data['email']) == None:\n return JsonResponse({'message': 'Error: Invalid email specified.'})\n if request.data['usertype'] == 'Owner' and ScrumProject.objects.filter(name__iexact=request.data['projname']).count() > 0:\n return JsonResponse({'message': 'Error: That project name is already taken.'})\n if request.data['usertype'] == 'Owner' and len(request.data['projname']) > 50:\n return JsonResponse({'message': 'Error: A project name cannot go over 50 characters.'})\n if len(request.data['full_name']) > 50:\n return JsonResponse({'message': 'Error: A user nickname cannot go over 50 characters.'})\n \n user, created = User.objects.get_or_create(username=request.data['email'], email=request.data['email'])\n if created:\n scrum_user = ScrumUser(user=user, nickname=request.data['full_name'])\n scrum_user.save()\n if request.data['usertype'] == 'Owner':\n scrum_project = ScrumProject(name=request.data['projname'])\n scrum_project.save()\n print(slack_app_id)\n scrum_project_role = ScrumProjectRole(role=\"Owner\", user=scrum_user, project=scrum_project)\n scrum_project_role.save()\n\n user.set_password(request.data['password'])\n user.save()\n return JsonResponse({'message': 'User Created Successfully.', 'client_id': slack_app_id })\n elif user:\n if not request.data['projname']:\n return JsonResponse({'message': 'user already existed as a User. Create new project', 'client_id': slack_app_id})\n print(\"Testing vreationssssssssssss\")\n scrum_user = User.objects.get(email = request.data['email'])\n print(scrum_user.scrumuser.nickname)\n scrum_project = ScrumProject(name=request.data['projname'])\n scrum_project.save()\n scrum_project_role = ScrumProjectRole(role=\"Owner\", user=scrum_user.scrumuser, project=scrum_project)\n scrum_project_role.save()\n print(\"User exist and project created\")\n return JsonResponse({'message': 'Project Created Successfully for already existing User.', 'client_id': slack_app_id})\n else:\n return JsonResponse({'message': 'Error: User with that e-mail already exists.'})\n\n\ndef userBgColor():\n list = [\"#ff8080\", \"#4d4dff\",\"#ff7ff6\", \"#66ffb3\", \"#99ddff\",\"#ffffff\", \"#ffcc80\", \"#ff99ff\",\"#ff0000\", \"#b3ffff\", \"#ffff80\",\"#dfdfdf\",\"#1a8cff\", \"#e085c2\",\"#ffffff\",\"#739900\", \"#739900\", \"#ffad33\", \"#75a3a3\", \"#1a1aff\"]\n color = random.choice(list)\n return color\n\n\ndef filtered_users(project_id):\n project = ScrumProjectSerializer(ScrumProject.objects.get(id=project_id)).data\n time_check = datetime.datetime.utcnow().replace(tzinfo=None)\n for user in project['scrumprojectrole_set']:\n user['scrumgoal_set'] = [x for x in user['scrumgoal_set'] if x['visible'] == True]\n total_hours = 0\n\n try:\n latest_sprint = ScrumSprint.objects.filter(goal_project_id = project_id).latest('ends_on')\n for goal in user['scrumgoal_set']:\n if latest_sprint.ends_on > parse_datetime(goal['time_created']) and latest_sprint.created_on < parse_datetime(goal['time_created']):\n if goal['hours'] != -1 and goal['status'] == 3:\n total_hours += goal['hours']\n print(\"condition Tested okay\")\n except Exception as e:\n pass\n \n\n \n user['total_week_hours'] = total_hours \n \n return project['scrumprojectrole_set']\n\n\nclass ScrumProjectViewSet(viewsets.ModelViewSet):\n queryset = ScrumProject.objects.all()\n serializer_class = ScrumProjectSerializer\n \n def retrieve(self, request, pk=None):\n try:\n queryset = ScrumProject.objects.get(pk=pk)\n slack_installed = queryset.scrumslack_set.all().exists()\n slack_app_id = ChatscrumSlackApp.objects.all().first()\n print(\"======================Slack exists=======================\" )\n return JsonResponse({'project_name': queryset.name,\"slack_app_id\":slack_app_id.CLIENT_ID, \"slack_installed\":slack_installed, 'data': filtered_users(pk)})\n\n except ScrumProject.DoesNotExist:\n return JsonResponse({'detail': 'Not found.'})\n except ChatscrumSlackApp.DoesNotExist:\n return JsonResponse({'project_name': queryset.name, \"slack_installed\":slack_installed, 'data': filtered_users(pk)})\n \nclass ScrumProjectRoleViewSet(viewsets.ModelViewSet):\n queryset = ScrumProjectRole.objects.all()\n serializer_class = ScrumProjectRoleSerializer\n permission_classes = [IsAuthenticatedOrReadOnly]\n\n def destroy(self, request, *args, **kwargs):\n try:\n instance = self.get_object()\n scrum_project = ScrumProject.objects.get(id=instance.project.id)\n scrum_project_role = scrum_project.scrumprojectrole_set.get(user=request.user.scrumuser)\n \n if scrum_project_role.role == \"Owner\":\n self.perform_destroy(instance)\n return JsonResponse({'message': 'User Removed from project'})\n else:\n print(instance.role)\n return JsonResponse({'message': 'Permission Denied: Unauthorized to Delete User.'})\n\n except:\n return JsonResponse({'message': 'User Do not exist'})\n \n def patch(self, request):\n scrum_project = ScrumProject.objects.get(id=request.data['project_id'])\n scrum_project_role = scrum_project.scrumprojectrole_set.get(user=request.user.scrumuser)\n to_id = request.data['id'][1:]\n \n print(request.data['role'])\n print(request.data['id'][1:])\n print(request.data['id'])\n\n author = ScrumProjectRole.objects.get(id=to_id)\n author.role = request.data['role'].capitalize()\n if request.data['role'] == 'quality analyst':\n author.role = 'Quality Analyst'\n author.save()\n \n return JsonResponse({'message': 'User Role Changed!'})\n\nclass ScrumGoalViewSet(viewsets.ModelViewSet):\n queryset = ScrumGoal.objects.all()\n serializer_class = ScrumGoalSerializer\n permission_classes = [IsAuthenticatedOrReadOnly]\n\n def create(self, request):\n user_id = request.data['user'][1:]\n scrum_project = ScrumProject.objects.get(id=request.data['project_id'])\n scrum_project_role = scrum_project.scrumprojectrole_set.get(user=request.user.scrumuser)\n author = ScrumProjectRole.objects.get(id=user_id)\n sprint = ScrumSprint.objects.filter(goal_project_id = request.data['project_id'])\n print(type(request.user))\n if scrum_project_role != author and scrum_project_role.role != 'Owner': \n return JsonResponse({'message': 'Permission Denied: Unauthorized Addition of a Goal.', 'data': filtered_users(request.data['project_id'])})\n \n if len(sprint) < 1:\n return JsonResponse({'message': 'Permission Denied: Sprint not yet started.', 'data': filtered_users(request.data['project_id'])})\n\n if (datetime.datetime.strftime(ScrumSprint.objects.latest('ends_on').ends_on, \"%Y-%m-%d %H:%M:%S\")) < datetime.datetime.strftime(datetime.datetime.now(), \"%Y-%m-%d %H:%M:%S\"):\n return JsonResponse({'message': 'Permission Denied: Last Sprint Period Elapsed.', 'data': filtered_users(request.data['project_id'])})\n\n status_start = 0\n scrum_project.project_count = scrum_project.project_count + 1\n scrum_project.save()\n\n\n\n goal, created = ScrumGoal.objects.get_or_create(user=author, name=request.data['name'], project_id=request.data['project_id'], visible = True, moveable= True,\n defaults = {\n \"user\":author,\n \"status\":status_start,\n \"time_created\": datetime.datetime.now(),\n \"goal_project_id\":scrum_project.project_count,\n } )\n\n # send_message(request.data['project_id'])\n if created:\n return JsonResponse({'message': 'Goal created success.', 'data': filtered_users(request.data['project_id'])})\n\n if goal:\n return JsonResponse({'message': 'Goal already existed.', 'data': filtered_users(request.data['project_id'])})\n\n\n def patch(self, request):\n scrum_project = ScrumProject.objects.get(id=request.data['project_id'])\n scrum_project_a = scrum_project.scrumprojectrole_set.get(user=request.user.scrumuser)\n scrum_project_b = scrum_project.scrumgoal_set.get(goal_project_id=request.data['goal_id'][1:], moveable=True).user\n goal_id = request.data['goal_id'][1:]\n to_id = int(request.data['to_id'])\n goal_item = scrum_project.scrumgoal_set.get(goal_project_id=goal_id, moveable=True)\n\n print(type(request.user))\n print(type(scrum_project_b.user.user))\n\n \n if to_id == 4:\n if scrum_project_a.role == 'Developer':\n if request.user != scrum_project_b.user.user:\n return JsonResponse({'message': 'Permission Denied: Unauthorized Deletion of Goal.', 'data': filtered_users(request.data['project_id'])})\n \n del_goal = scrum_project.scrumgoal_set.get(goal_project_id=goal_id, moveable=True)\n del_goal.visible = False\n del_goal.save() \n self.createHistory(goal_item.name, goal_item.status, goal_item.goal_project_id, goal_item.hours, goal_item.time_created, goal_item.user, goal_item.project, goal_item.file, goal_item.id, 'Goal Removed Successfully by')\n return JsonResponse({'message': 'Goal Removed Successfully!'})\n else: \n group = scrum_project_a.role\n from_allowed = []\n to_allowed = []\n if group == 'Developer':\n if request.user != scrum_project_b.user.user:\n return JsonResponse({'message': 'Permission Denied: Unauthorized Movement of Goal.', 'data': filtered_users(request.data['project_id'])})\n \n if group == 'Owner':\n from_allowed = [0, 1, 2, 3]\n to_allowed = [0, 1, 2, 3]\n elif group == 'Admin':\n from_allowed = [0, 1, 2]\n to_allowed = [0, 1, 2]\n elif group == 'Developer':\n from_allowed = [0, 1, 2]\n to_allowed = [0, 1, 2]\n elif group == 'Quality Analyst':\n from_allowed = [0, 1, 2, 3]\n to_allowed = [0, 1, 2, 3]\n \n state_prev = goal_item.status\n print(\"=======================PATCH REQUEST DATA======================\")\n print(request.data)\n \n if (goal_item.status in from_allowed) and (to_id in to_allowed):\n goal_item.status = to_id\n elif group == 'Quality Analyst' and goal_item.status == 2 and to_id == 0:\n goal_item.status = to_id\n elif request.user == scrum_project_b.user.user:\n if goal_item.status == 1 and to_id == 0:\n goal_item.status = to_id\n elif goal_item.status == 0 and to_id == 1:\n goal_item.status = to_id\n else:\n \n return JsonResponse({'message': 'Permission Denied: Unauthorized Movement of Goal.', 'data': filtered_users(request.data['project_id'])})\n else:\n return JsonResponse({'message': 'Permission Denied: Unauthorized Movement of Goal.', 'data': filtered_users(request.data['project_id'])})\n if goal_item.moveable == True:\n message = 'Goal Moved Successfully!'\n if to_id == 2 and request.data['hours'] :\n goal_item.push_id = request.data['push_id']\n goal_item.status = to_id\n goal_item.hours = goal_item.hours\n goal_item.push_id = request.data['push_id']\n message = 'Goal Moved Successfully! Push ID is ' + request.data['push_id']\n if request.data['hours'] > 8:\n goal_item.status = state_prev\n message = 'Error: Task cannot Exceeds 8hours or less than an hour of completion.'\n elif request.data['hours'] == -1 and goal_item.hours == -1 and to_id > 1:\n goal_item.status = state_prev\n message = 'Error: A Task must have hours assigned.'\n elif request.data['hours'] == -13:\n goal_item.status = state_prev\n if request.data['push_id'] == \"Canceled\":\n message = \"Error, No Work ID assigned\"\n else:\n message = 'Error: A Task must have hours assigned.'\n elif to_id == 2 and state_prev == 1 :\n goal_item.hours = request.data['hours']\n message = 'Goal Moved Successfully! Hours Applied!'\n\n if to_id == 2 and request.data['hours'] < 8 and request.data['push_id'] == \"Null Value\":\n goal_item.status = state_prev\n message = 'Error: No PUSH-ID added.' \n\n\n if state_prev == 1 and to_id == 0:\n goal_item.days_failed = goal_item.days_failed + 1 \n \n self.createHistory(goal_item.name, goal_item.status, goal_item.goal_project_id, goal_item.hours, goal_item.time_created, goal_item.user, goal_item.project, goal_item.file, goal_item.id, 'Goal Moved Successfully by') \n goal_item.save()\n else:\n message = \"Sprint Period Elapsed, The Goal Cannot be Moved!\"\n print(\"noted\")\n return JsonResponse({'message': message, 'data': filtered_users(request.data['project_id'])})\n \n def put(self, request):\n scrum_project = ScrumProject.objects.get(id=request.data['project_id'])\n scrum_project_role = scrum_project.scrumprojectrole_set.get(user=request.user.scrumuser)\n # scrum_project_b = scrum_project.scrumgoal_set.get(goal_project_id=request.data['goal_id'][1:]).user\n if request.data['mode'] == 0:\n from_id = request.data['goal_id'][1:]\n to_id = request.data['to_id'][1:]\n \n if scrum_project_role.role == 'Developer' or scrum_project_role.role == 'Quality Analyst':\n return JsonResponse({'message': 'Permission Denied: Unauthorized Reassignment of Goal.', 'data': filtered_users(request.data['project_id'])})\n \n goal = scrum_project.scrumgoal_set.get(goal_project_id=from_id, moveable=True)\n if goal.moveable == True:\n print(to_id)\n author = ScrumProjectRole.objects.get(id=to_id)\n goal.user = author\n self.createHistory(goal.name, goal.status, goal.goal_project_id, goal.hours, goal.time_created, goal.user, goal.project, goal.file, goal.id, 'Goal Reassigned Successfully by')\n goal.save()\n return JsonResponse({'message': 'Goal Reassigned Successfully!', 'data': filtered_users(request.data['project_id'])})\n else:\n return JsonResponse({'message': 'Permission Denied: Sprint Period Elapsed!!!', 'data': filtered_users(request.data['project_id'])})\n elif request.data['mode'] == '1':\n goal = scrum_project.scrumgoal_set.get(goal_project_id=request.data['goal_id'][1:], moveable=True)\n # goal.file = request.FILES['image']\n \n\n myfile = request.FILES['image']\n fs = FileSystemStorage()\n print(myfile)\n print(myfile.name)\n \n filename = fs.save(myfile.name, myfile)\n file_url = fs.url(filename)\n print(file_url)\n goal.file = filename\n self.createHistory(goal.name, goal.status, goal.goal_project_id, goal.hours, goal.time_created, goal.user, goal.project, goal.file, goal.id, 'Image Added Successfully by')\n goal.save()\n \n return JsonResponse({'message': 'Image Added Successfully', 'data': filtered_users(request.data['project_id'])})\n elif request.data['mode'] == 2:\n goal = scrum_project.scrumgoal_set.get(goal_project_id=request.data['goal_id'][1:], moveable=True)\n scrum_project_b = scrum_project.scrumgoal_set.get(goal_project_id=request.data['goal_id'][1:], moveable=True).user\n if (request.user == scrum_project_b.user.user or scrum_project_role.role == 'Owner') and goal.moveable == True and goal.status == 3:\n\n goal.visible = 0\n goal.save()\n print(request.user.id)\n return JsonResponse({'message': 'Goal Deleted Successfully!'})\n else:\n return JsonResponse({'message': 'Permission Denied: Unauthorized Deletion of Goal.'})\n elif request.data['mode'] == 3:\n print(scrum_project.id)\n if scrum_project.to_clear_TFT == True:\n message = \"Auto Clear TFT toggle OFF!!! \"\n scrum_project.to_clear_TFT = False\n print(\"This toggles============================\")\n else:\n message = \"Auto Clear TFT toggle ON successfully!!!\" \n scrum_project.to_clear_TFT = True\n scrum_project.save() \n print(scrum_project.to_clear_TFT)\n return JsonResponse({'message': message, 'to_clear_board':scrum_project.to_clear_TFT})\n else:\n scrum_project_b = scrum_project.scrumgoal_set.get(goal_project_id=request.data['goal_id'][1:], moveable=True).user\n if scrum_project_role.role != 'Owner' and request.user != scrum_project_b.user.user:\n return JsonResponse({'message': 'Permission Denied: Unauthorized Name Change of Goal.'})\n \n goal = scrum_project.scrumgoal_set.get(goal_project_id=request.data['goal_id'][1:], moveable=True)\n if goal.moveable == True: \n goal.name = request.data['new_name']\n self.createHistory(goal.name, goal.status, goal.goal_project_id, goal.hours, goal.time_created, goal.user, goal.project, goal.file, goal.id, 'Goal Name Changed by')\n goal.save()\n return JsonResponse({'message': 'Goal Name Changed!'})\n else:\n return JsonResponse({'message': 'Permission Denied: Sprint Period Elapsed!!!'})\n def createHistory(self, name, status, goal_project_id, hours, time_created, user, project, file, goal, message):\n concat_message = message + self.request.user.username\n print(concat_message)\n goal = ScrumGoalHistory (name=name, status=status, time_created = time_created, goal_project_id=goal_project_id, user=user, project=project, file=file, goal_id=goal, done_by=self.request.user, message=concat_message)\n goal.save()\n return\n\n# def slack_details(project):\n# slack = project.scrumprojectslack_set.get(project=project)\n# channelObject = dict()\n# channelObject[\"slack_client_id\"] = slack.slack_client_id\n# channelObject[\"slack_client_secret\"] = slack.slack_client_secret\n# channelObject[\"slack_verification_token\"] = slack.slack_verification_token\n# channelObject[\"slack_bot_user_token\"] = slack.slack_bot_user_token\n# print(channelObject)\n# print(\"========================PROJECT======================\")\n# return channelObject\n \ndef jwt_response_payload_handler(token, user=None, request=None):\n project = None\n \n try:\n project = ScrumProject.objects.get(name__iexact=request.data['project']) \n except ScrumProject.DoesNotExist:\n raise ValidationError('The selected project does not exist.');\n\n \n \n if project.scrumprojectrole_set.filter(user=user.scrumuser).count() == 0:\n scrum_project_role = ScrumProjectRole(role=\"Developer\", user=user.scrumuser, project=project, color=userBgColor())\n scrum_project_role.save()\n\n proj_role = project.scrumprojectrole_set.get(user=user.scrumuser)\n nickname = proj_role.user.nickname\n email = proj_role.user.user.username\n login = settings.LOGIN_URL\n\n owners_list = ScrumProjectRole.objects.filter(role=\"Owner\", project=project)\n admin_list = ScrumProjectRole.objects.filter(role=\"Admin\", project=project)\n if project.scrumprojectrole_set.get(user=user.scrumuser).color == \"white\":\n \n proj_role.color = userBgColor()\n print(\"coloooooooooooooooooooooooooooor\" + proj_role.color)\n proj_role.save()\n \n ws_token, created = Token.objects.get_or_create(user=user)\n # try:\n # ws_token, created = Token.objects.get_or_create(user=user)\n # # if (ws_token or created): \n # # ws_token = Token.objects.get(user=user)\n # print(ws_token.key)\n # except:\n # pass\n context = Context({\"nickname\":nickname, \"project\":project, \"email\":email, \"login\":login})\n template = Template(\n '''\n \n \n \n \n
\n
\n \n \n \n \n \n \n \n \n
\n \n \n \n \n \n
\n \n \n \n \n \n \n \n \n \n
\n\n \n \n \n \n \n \n \n \n
\n \n

Hello {{nickname}}!

\n

\n Thank you for signing up. Chatscrum is a simple and organised way to plan and build software.

\n Project: {{project.name}}
\n Email: {{email}}\n


\n \n \n \n \n \n \n \n
\n \n
\n\n

\n Welcome and Happy Building!

\n \n Thanks,
\n Chatscrum Team
\n \n\n\n

\n
\n \n
\n
\n \n
\n
\n
\n\n \n \n '''\n )\n content = template.render(context)\n\n \n\n if created:\n email = EmailMessage(\n 'Welcome to ChatScrum',\n content,\n settings.DEFAULT_FROM_EMAIL, \n [email]\n )\n email.content_subtype = \"html\" \n email.send(fail_silently=False)\n\n for owner in owners_list:\n email=owner.user.user.username\n context = Context({\"nickname\":owner.user.nickname, \"project\":project, \"email\":owner.user.user.username, \"user\":nickname})\n template = Template(\n '''\n \n \n \n \n\n \n \n

Hi

{{nickname}},

\n

\n {{user}} has just joined your project {{project.name}}. \n

\n \n\n

Thanks,

\n

Chatscrum Team

\n \n \n \n \n '''\n )\n\n content=template.render(context)\n owner_email = EmailMessage(\n 'New User Added',\n content,\n settings.DEFAULT_FROM_EMAIL, \n [email]\n )\n owner_email.content_subtype=\"html\"\n owner_email.send(fail_silently=False)\n\n for admin in admin_list:\n email=admin.user.user.username\n context = Context({\"nickname\":admin.user.nickname, \"project\":project, \"email\":admin.user.user.username, \"user\":nickname})\n template = Template(\n '''\n \n \n \n \n\n \n \n

Hi

{{nickname}},

\n

\n {{user}} has just joined your project {{project.name}}. \n

\n \n\n

Thanks,

\n

Chatscrum Team

\n

© Copyright 2020.

\n \n \n \n '''\n )\n\n content=template.render(context)\n admin_email = EmailMessage(\n 'New User Added',\n content,\n settings.DEFAULT_FROM_EMAIL, \n [email]\n )\n admin_email.content_subtype=\"html\"\n admin_email.send(fail_silently=False)\n\n print('Email successfully sent')\n user_slack = bool(proj_role.slack_email)\n if project.scrumslack_set.all().exists():\n project_slack = \"True\"\n slack_username = proj_role.slack_username\n else:\n project_slack = \"False\"\n slack_username = \"empty\"\n\n\n \n return {\n 'token': token,\n 'name': user.scrumuser.nickname,\n 'role': project.scrumprojectrole_set.get(user=user.scrumuser).role,\n 'project_id': project.id,\n 'role_id': project.scrumprojectrole_set.get(user=user.scrumuser).id,\n 'user_slack' : user_slack,\n 'project_name': project.name,\n 'project_slack' : project_slack,\n \"slack_username\": slack_username,\n \"to_clear_board\": project.to_clear_TFT,\n \"ws_token\": ws_token.key\n }\n \n\nclass SprintViewSet(viewsets.ModelViewSet):\n queryset = ScrumSprint.objects.all()\n serializer_class = ScrumSprintSerializer\n\n def get_queryset(self):\n queryset = self.get_project_sprint()\n return queryset\n\n def create(self, request): \n user_id = request.user.id\n scrum_project = ScrumProject.objects.get(id=request.data['project_id'])\n # scrum_project.project_count = scrum_project.project_count + 1\n scrum_project.save()\n # Get the owner of project, the first item.project_id... \n scrum_project_creator = scrum_project.scrumprojectrole_set.all()[0]\n\n scrum_project_role = scrum_project.scrumprojectrole_set.get(user=request.user.scrumuser)\n\n print(user_id)\n\n author_role = ScrumUser.objects.get(user_id=user_id)\n author = author_role.scrumprojectrole_set .all()\n\n sprint_goal_carry = ScrumGoal.objects.filter(project_id = request.data['project_id'], moveable=True) \n \n\n existence = ScrumSprint.objects.filter(goal_project_id = request.data['project_id']).exists()\n now_time = datetime.datetime.now().replace(tzinfo=None) + datetime.timedelta(seconds=10) \n\n\n\n if scrum_project_role.role == 'Admin' or scrum_project_role.role == 'Owner':\n if existence == True: \n last_sprint = ScrumSprint.objects.filter(goal_project_id = request.data['project_id']).latest('ends_on') \n if (datetime.datetime.strftime(last_sprint.ends_on, \"%Y-%m-%d %H-%M-%S\")) < datetime.datetime.strftime(datetime.datetime.now(), \"%Y-%m-%d %H-%M-%S\"):\n sprint = ScrumSprint(goal_project_id=request.data['project_id'], created_on = now_time, ends_on=datetime.datetime.now() + datetime.timedelta(days=7))\n sprint.save()\n self.change_goal_moveability(sprint_goal_carry, scrum_project, scrum_project_role)\n queryset = self.get_project_sprint()\n return JsonResponse({'message': 'Sprint Created Successfully.', 'data':queryset})\n else:\n if (last_sprint.created_on.replace(tzinfo=None) + datetime.timedelta(seconds=20) > now_time):\n queryset = self.get_project_sprint() \n return JsonResponse({'message': 'Not Allowed: Minimum Allowed Sprint Run is 60secs.', 'data':queryset})\n elif (datetime.datetime.strftime(last_sprint.ends_on, \"%Y-%m-%d %H-%M-%S\")) > datetime.datetime.strftime(datetime.datetime.now(), \"%Y-%m-%d\"): \n last_sprint.ends_on = datetime.datetime.now()\n last_sprint.save() \n sprint = ScrumSprint(goal_project_id=request.data['project_id'], created_on = now_time, ends_on=datetime.datetime.now() + datetime.timedelta(days=7))\n sprint.save() \n self.change_goal_moveability(sprint_goal_carry, scrum_project, scrum_project_role)\n queryset = self.get_project_sprint()\n return JsonResponse({'message': 'Last Sprint Ended and New Sprint Created Successfully.', 'data':queryset}) \n else:\n pass \n else: \n sprint = ScrumSprint(goal_project_id=request.data['project_id'], created_on = now_time, ends_on=datetime.datetime.now() + datetime.timedelta(days=7))\n sprint.save()\n self.change_goal_moveability(sprint_goal_carry, scrum_project, scrum_project_role)\n print(self.get_project_sprint())\n queryset = self.get_project_sprint()\n return JsonResponse({'message': 'Sprint Created Successfully.', 'data':queryset}) \n\n else:\n return JsonResponse({'message': 'Permission Denied: Unauthorized Permission to Create New Sprint.'})\n\n\n def change_goal_status(self,sprint_goal_carry):\n for each_goal in sprint_goal_carry:\n if each_goal.status == 0:\n each_goal.time_created = datetime.datetime.now() + datetime.timedelta(seconds=12)\n each_goal.save() \n return\n\n def get_project_sprint(self): \n project_id = self.request.query_params.get('goal_project_id', None)\n if project_id is not None:\n proj_sprint = ScrumSprint.objects.filter(goal_project_id=project_id)\n serializer = ScrumSprintSerializer(proj_sprint, many = True)\n queryset = serializer.data\n return queryset\n\n def change_goal_moveability(self, sprint_goal_carry, scrum_project, scrum_project_role):\n \n if sprint_goal_carry :\n # scrum_project.project_count = scrum_project.project_count\n for each_goal in sprint_goal_carry:\n if each_goal.moveable != False:\n each_goal.moveable = False\n each_goal.save()\n copy_status = [0,1,2]\n if each_goal.status in copy_status and each_goal.visible == 1 :\n goal = ScrumGoal(\n name=each_goal.name,\n status= 0,\n time_created = datetime.datetime.now() + datetime.timedelta(seconds=10), \n # goal_project_id=scrum_project.project_count, \n user=each_goal.user, \n project_id=self.request.data['project_id'],\n moveable = True,\n goal_project_id=each_goal.goal_project_id)\n scrum_project.project_count = scrum_project.project_count + 1 \n goal.save()\n \n # # Save Total number of project goals\n print(scrum_project.project_count)\n scrum_project.save()\n\n else:\n pass \n\n return\n\n\n \n\nclass Events(APIView):\n print(\"Testing from slack=================\")\n channel_layer = get_channel_layer()\n try:\n slack_app = ChatscrumSlackApp.objects.all().first()\n except:\n pass\n \n def get(self, request, *args, **kwargs):\n # Return code in Url parameter or empty string if no code\n sc = WebClient(settings.SLACK_APP_TOKEN)\n auth_code = request.GET.get('code', '')\n the_state = request.GET.get('state', '')\n splitter = the_state.find(\">>>\")\n splitter_s = the_state.find(\"<<\") \n project_id = the_state[:splitter] \n user_email = the_state[(splitter+3):splitter_s]\n real_name = the_state[(splitter_s+3):]\n post_data = request.data\n\n if (project_id[10:] == \"test\"):\n project_id = \"main_chat_testing\"\n scrum_project, created = ScrumProject.objects.get_or_create(name = project_id[10:])\n\n\n# =================================Get Auth code response from slack==============================================\n if(created or scrum_project):\n scrum_project = ScrumProject.objects.get(name=project_id[10:])\n print(\"====================================auth code=================\" + auth_code)\n print(auth_code)\n print(splitter_s)\n print(project_id)\n print(user_email)\n print(\"\\n\")\n print(real_name)\n \n print(\"====================================auth code=================\" )\n if auth_code:\n encoding = {\"Content-Type\":\"text/html\", \"charset\":\"utf-8\"}\n print(encoding)\n client = WebClient(\"\")\n auth_response = client.oauth_v2_access(\n\n client_id=settings.SLACK_CLIENT_ID,\n client_secret= settings.SLACK_CLIENT_SECRET,\n code=auth_code,\n scope=\"channels:read users:read chat:write groups:read channels:history groups:history\" \n )\n\n\n if auth_response[\"ok\"] == True:\n print(auth_response)\n print(\"====================Get usermail etc==========================\")\n # print(auth_response['authed_user']['access_token'])\n print('========this token===========')\n print(auth_response[\"access_token\"])\n print('========this token===========')\n user_sc = WebClient(auth_response['authed_user'][\"access_token\"])\n user_response = user_sc.users_info( \n user=auth_response['authed_user'][\"id\"]\n )\n \n print(\"=============USER DETAILS============\" )\n \n \n \n # print( user_response[\"user\"][\"email\"])\n try:\n print(\"============= INSIDE TRY GET USER============\" )\n my_user, created = User.objects.get_or_create(username=user_email)\n if (my_user or created):\n my_user = User.objects.get(username=user_email)\n user, created= ScrumUser.objects.get_or_create(user__username=user_email)\n if(user or created):\n user = ScrumUser.objects.get(user__username=user_email)\n print(user)\n user_role, created = user.scrumprojectrole_set.get_or_create(user=user, project = scrum_project)\n if (user_role or created):\n user_role = user.scrumprojectrole_set.get(user=user, project=scrum_project)\n print(user_role)\n \n print(\"============= AFTER TRY GET USER============\" )\n except:\n \n html = \"An error occured!!!\" \n return HttpResponse(html)\n\n try:\n get, created = ChatSlack.objects.get_or_create(username=real_name, slack_user_id= auth_response['authed_user']['id'], project=scrum_project)\n if created:\n print(ChatSlack.objects.get(username=real_name, slack_user_id= auth_response['authed_user']['id']).username)\n print('Successsssssss')\n\n except:\n print('failedddd')\n \n \n \n \n i_am = User.objects.get(username=user_email)\n# =========================================Get Room and project=====================================================================\n chat_room,created = ScrumChatRoom.objects.get_or_create(name=project_id, hash=hashlib.sha256(project_id.encode('UTF-8')).hexdigest())\n \n try:\n project_token, created = ScrumSlack.objects.get_or_create(\n scrumproject = scrum_project,\n room = chat_room, \n user_id=auth_response['authed_user'][\"id\"],\n team_name=auth_response['team'][\"name\"],\n team_id=auth_response['team'][\"id\"], \n channel_id=auth_response[\"incoming_webhook\"][\"channel_id\"], \n bot_user_id=auth_response[\"bot_user_id\"], \n access_token=auth_response['authed_user'][\"access_token\"], \n bot_access_token=auth_response[\"access_token\"],\n scrum_details = i_am\n )\n print(SlackApps.objects.filter(scrumproject=scrum_project, user_id = auth_response['authed_user']['id']).exists())\n\n print(auth_response['authed_user'][\"id\"])\n #===============================Update Scrumy user details for Add to slack======================================================================\n user_role.slack_user_id = user_response[\"user\"][\"id\"]\n user_role.slack_email = str(user_response[\"user\"][\"real_name\"]) + \"@gmail.com\"\n user_role.slack_username = user_response[\"user\"][\"name\"]\n user_role.slack_profile_picture = user_response[\"user\"][\"profile\"][\"image_512\"]\n user_role.save()\n\n print(user_response)\n \n \n print(\"===================================================user channel add=========================\")\n except KeyError as error:\n #channel_info = user_sc.api_call(\n # \"channels.info\"\n # )\n \n print(user_response)\n #print(channel_info)\n '''\n project_token, created = ScrumSlack.objects.get_or_create(\n scrumproject = scrum_project,\n room = chat_room, \n user_id=auth_response['authed_user'][\"id\"],\n team_name='',\n team_id=auth_response['team'][\"id\"], \n channel_id=channel_info['channels'][0]['id'], \n bot_user_id='', \n access_token=auth_response['authed_user'][\"access_token\"], \n bot_access_token=''\n )\n print(ScrumSlack.objects.filter(scrumproject=scrum_project, user_id = auth_response['authed_user']['id']).exists())\n '''\n print('Scrumslack add faileddddd')\n print(auth_response['authed_user'][\"id\"])\n #===============================Update Scrumy user details for Add to slack======================================================================\n user_role.slack_user_id = user_response[\"user\"][\"id\"]\n user_role.slack_email = str(user_response[\"user\"][\"real_name\"]) + \"@gmail.com\"\n user_role.slack_username = user_response[\"user\"][\"name\"]\n user_role.slack_profile_picture = user_response[\"user\"][\"profile\"][\"image_512\"]\n user_role.save()\n \n \n print(\"===================================================user channel add=========================\")\n \n return redirect(settings.FRONTEND)\n\n\n \n def post(self, request, *args, **kwargs): \n print(\"=========================REQUEST DATA==================================\") \n post_data = request.data \n print(post_data)\n print(\"========================================================================\")\n\n\n# =========================================URL verification challenge===============================================================\n if post_data.get('type') == 'url_verification':\n print(\"===================================url_verification===========================================================\")\n print(post_data[\"challenge\"])\n return Response(data=post_data,\n status=status.HTTP_200_OK)\n\n if post_data.get('event')[\"type\"] == \"message\":\n retry_count = request.META.get('HTTP_X_SLACK_RETRY_NUM', None)\n\n if retry_count is None:\n \n\n try:\n\n slack_user = ScrumProjectRole.objects.filter(slack_user_id=post_data[\"event\"][\"user\"]).first()\n\n if slack_user is not None: \n print(\"==========================Slack user=================\" + slack_user.user.nickname)\n slack_user_nick = slack_user.user.nickname\n slack_profile_picture = slack_user.slack_profile_picture\n else:\n slack_user_nick = post_data[\"event\"][\"user\"]\n slack_profile_picture = \"https://ca.slack-edge.com/T73UK2WNS-UKRNK9ULR-gd4dbac35d17-24\" \n except ScrumUser.DoesNotExist as error:\n print(\"User Not matched: failed\")\n slack_user_nick = post_data[\"event\"][\"user\"]\n except KeyError as error:\n slack_user = ScrumProjectRole.objects.filter(slack_user_id=post_data[\"event\"][\"username\"]).first()\n return Response(data=post_data,\n status=status.HTTP_200_OK)\n\n try:\n print(post_data['event']['user'])\n scrumslack_details = ScrumSlack.objects.get(channel_id= post_data['event']['channel'], user_id=post_data['event']['user'], team_id=post_data['team_id'])\n project_name = scrumslack_details.scrumproject.name\n slack_details= ScrumSlack.objects.filter(channel_id=post_data[\"event\"][\"channel\"]).first() \n print(\"========================================Slack details================================\") \n print(post_data[\"event\"][\"channel\"])\n print(slack_details) \n if slack_details is not None: \n slack_message = post_data[\"event\"][\"text\"]\n \n\n #slack_message_array = re.split(r'\\s', slack_message)\n print(slack_message)\n\n #for each_word in slack_message_array:\n #match =re.match(r'<@([\\w\\.-]+)>',each_word ) \n #if match:\n #print(match.group(1))\n #try:\n # a = ScrumProjectRole.objects.get(slack_user_id=match.group(1))\n # slack_message = slack_message.replace(each_word, a.user.nickname)\n # print(slack_message)\n # print(\"pattern matched\")\n # except ScrumProjectRole.DoesNotExist as e:\n # slack_message = slack_message.replace(each_word, match.group(1))\n \n \n #else:\n # print(\"pattern not matched\") \n proj = ScrumProject.objects.get(name = project_name)\n \n\n chatRoom = ScrumChatRoom.objects.get(id = slack_details.room_id).hash\n pattern = re.compile(r'<@[a-zA-Z0-9]+>')\n \n answer_list = pattern.findall(slack_message)\n verify_array = []\n print(answer_list)\n\n\n for answer in answer_list:\n if answer not in verify_array:\n temp = answer\n verify_array.append(temp)\n if temp[-1] == '\\n':\n temp = temp[0:-1]\n value = str(temp[2:-1])\n print(value)\n scrumuser = ScrumSlack.objects.get(scrumproject=proj, user_id=value).scrum_details.scrumuser.nickname\n\n\n slack_message = slack_message.replace(answer, '@'+scrumuser)\n actual_message = ChatMessage(username=slack_user_nick, message=slack_message, project_name=project_name, timestamp=datetime.datetime.now().strftime(\"%I:%M %p . %d-%m-%Y\"), profile_picture=slack_user.slack_profile_picture)\n actual_message.save()\n \n proj = ScrumProject.objects.get(name=project_name)\n my_messages = {\"username\":slack_user_nick, \"message\":slack_message, \"project_name\":project_name, \"profile_picture\":slack_user.slack_profile_picture, \"timestamp\":datetime.datetime.now().strftime(\"%I:%M %p . %d-%m-%Y\")}\n data = {\"type\":\"all_messages\", \"messages\":[my_messages]}\n\n connections = Connection.objects.filter(project = proj)\n print(connections)\n for conn in connections:\n _send_to_connection(conn.connection_id, data)\n\n \n\n return Response(data=post_data,\n status=status.HTTP_200_OK)\n\n except KeyError as error:\n # ===========Response for when no client message id\n pass\n\n \n \n \n \n\n return Response(status=status.HTTP_204_NO_CONTENT, headers={'X-Slack-No-Retry':1})\n\n \n\nclass ScrumNoteViewSet(viewsets.ModelViewSet):\n queryset = ScrumNote.objects.all()\n serializer_class = ScrumNoteSerializer\n permission_classes = [IsAuthenticatedOrReadOnly]\n now_time = datetime.datetime.now().replace(tzinfo=None)\n \n def create(self, request):\n user_id = request.data['user'][1:]\n author = ScrumProjectRole.objects.get(id=user_id)\n print(author.role)\n print(request.data['project_id'])\n try:\n note = ScrumNote(user=author, note=request.data['note'], priority=request.data['priority'], time_created=self.now_time, project_id=request.data['project_id'])\n note.save()\n return JsonResponse({'message': 'Note Created Successfully!'})\n except KeyError as error:\n return JsonResponse({'message': 'Priority or notes cannot be an empty field'})\n def put(self, request):\n print(\"This is note deleting\")\n note = ScrumNote.objects.get(id=request.data['id'])\n note.delete()\n return JsonResponse({'message': 'Goal Added and note deleted Successfully!'})\n \n\nclass ScrumWorkIdViewSet(viewsets.ModelViewSet):\n queryset = ScrumWorkId.objects.all()\n serializer_class = ScrumWorkIdSerializer \n \n def create(self, request):\n user_id = request.data['user'][1:]\n author = ScrumProjectRole.objects.get(id=user_id)\n print(author.role)\n print(request.data['project_id'])\n try:\n workid = ScrumWorkId(user=author, workid=request.data['workid'], branch=request.data['branch'], project_id=request.data['project_id'])\n workid.save()\n return JsonResponse({'message': 'Workid added Successfully!'})\n except KeyError as error:\n return JsonResponse({'message': 'Error adding workid'}) \n\n \n def patch(self, request):\n print(\"This is WorkId Updating\")\n workids = ScrumWorkId.objects.get(workid=request.data['workid'])\n print(workids)\n workids.workid = request.data['workid']\n workids.branch = request.data['branch']\n #workids = ScrumWorkId(user=author, workid=request.data['workid'], branch=request.data['branch'])\n workids.save()\n return JsonResponse({'message': 'WorkId Updated Successfully!'}) \n\n def put(self, request):\n print(\"This is WorkId deleting\")\n workid = ScrumWorkId.objects.get(id=request.data['id'])\n workid.delete()\n return JsonResponse({'message': 'WorkId deleted Successfully!'}) \n\nclass ScrumLogViewSet(viewsets.ModelViewSet):\n queryset = ScrumLog.objects.all()\n serializer_class = ScrumLogSerializer\n permission_classes = [IsAuthenticatedOrReadOnly]\n now_time = datetime.datetime.now().replace(tzinfo=None)\n \n def create(self, request):\n user_id = request.data['user'][1:]\n author = ScrumProjectRole.objects.get(id=user_id)\n print(author.role)\n print(request.data['project_id'])\n try:\n log = ScrumLog(user=author, log=request.data['log'], priority=request.data['priority'], time_created=self.now_time, project_id=request.data['project_id'])\n log.save()\n return JsonResponse({'message': 'Created Successfully!', 'data': filtered_users(request.data['project_id'])})\n except KeyError as error:\n return JsonResponse({'message': 'Priority or feature/bug cannot be an empty field'}) \n\n\n def put(self, request):\n print(\"This is log deleting\")\n log = ScrumLog.objects.get(id=request.data['id'])\n log.delete()\n return JsonResponse({'message': 'Goal Assigned and log deleted Successfully!'}) \n","sub_path":"Django/ScrumMaster/Scrum/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":91044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"421733958","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 30 10:55:08 2020\n\n@author: marie\n\"\"\"\n\n#%% Input normalization\nimport os\nimport os.path\nimport pandas as pd\n\nimport setup.utils as utils\n\n\n#%% load data\n\ndef load_data(dataset, data_dir, simulations):\n \n path_in = os.path.join(data_dir, f\"{dataset}_in\")\n \n if (simulations==\"preles\"):\n path_out = os.path.join(data_dir, f\"{simulations}_out\")\n else:\n path_out = os.path.join(data_dir, f\"{dataset}_out\")\n \n X = pd.read_csv(path_in, sep=\";\")\n Y = pd.read_csv(path_out, sep=\";\")\n \n # Remove nows with na values\n rows_with_nan = pd.isnull(X).any(1).to_numpy().nonzero()[0]\n X = X.drop(rows_with_nan)\n Y = Y.drop(rows_with_nan)\n \n return X, Y\n\ndef get_splits(sites, years, datadir, dataset = \"profound\", simulations = None, drop_cols = False, standardized = True,\n colnames = [\"PAR\", \"TAir\", \"VPD\", \"Precip\", \"fAPAR\", \"DOY_sin\", \"DOY_cos\"],\n to_numpy = True):\n \n datadir = os.path.join(datadir, f\"{dataset}\")\n \n X, Y = load_data(dataset = dataset, data_dir = datadir, simulations = simulations)\n \n X[\"date\"] = X[\"date\"].str[:4].astype(int) # get years as integers\n X[\"DOY_sin\"], X[\"DOY_cos\"] = utils.encode_doy(X[\"DOY\"]) # encode day of year as sinus and cosinus\n\n if all([site in X[\"site\"].values for site in sites]):\n row_ind = X['site'].isin(sites)\n print(f\"Returns {sites} from \\n\", X[\"site\"].unique())\n X, Y = X[row_ind], Y[row_ind]\n else: \n print(\"Not all sites in dataset!\")\n \n if standardized:\n X[colnames] = utils.minmax_scaler(X[colnames])\n \n try:\n row_ind = X[\"date\"].isin(years)\n print(f\"Returns valid years from {years} in \\n\", X[\"date\"].unique())\n X, Y = X[row_ind], Y[row_ind]\n except: \n print(\" years specification invalid. Returns all years.\")\n \n try:\n X = X[colnames]\n except:\n print(\"Columns are missing!\")\n \n if simulations != None: \n \n if drop_cols:\n Y= Y.drop(columns=[\"ET\", \"SW\"])\n else:\n X[\"ET\"] = Y[\"ET\"]\n X[\"SW\"] = Y[\"SW\"]\n Y= Y.drop(columns=[\"ET\", \"SW\"])\n else:\n try:\n Y= Y.drop(columns=[\"ET\"])\n except:\n None\n \n if to_numpy:\n X, Y = X.to_numpy(), Y.to_numpy()\n \n return X, Y\n\n\n\n#%%\ndef get_simulations(data_dir, drop_parameters = False):\n\n \n path_in = os.path.join(data_dir, f\"sims_in.csv\")\n path_out = os.path.join(data_dir, f\"sims_out.csv\")\n \n X = pd.read_csv(path_in, sep=\";\")\n X[\"DOY_sin\"], X[\"DOY_cos\"] = utils.encode_doy(X[\"DOY\"])\n \n X = X.drop(columns=[\"DOY\",\"sample\", \"year\", \"CO2\"])\n \n if drop_parameters:\n X = X.drop(columns=[\"beta\",\"X0\", \"gamma\", \"alpha\", \"chi\"])\n\n Y = pd.read_csv(path_out, sep=\";\")\n \n return X.to_numpy(), Y.to_numpy()#, filenames\n\n","sub_path":"python/ms_parallel/setup/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"264277847","text":"import pymongo\nimport tkinter as tk\nfrom tkinter import ttk\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport time\nimport numpy\nimport datetime\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk\nfrom matplotlib.backend_bases import key_press_handler\nmatplotlib.use('TkAgg') # Use tkAgg\n\n\ndef view_all_data():\n Window2 = tk.Toplevel()\n Window2.title(\"View All Data\")\n Window2.geometry(\"640x640\")\n view_all_fig = plt.figure(2, figsize=[6, 6])\n plt.clf()\n matplotlib.dates.DateFormatter('%m-%d %H:%M')\n plt.autoscale(enable=True, axis='x', tight=False)\n plt.title(\"View all data of the voltage of VR\")\n plt.xlabel(\"Time\")\n plt.ylabel(\"Voltage(V)\")\n plt.ylim(-0.5, 3.5)\n\n cursor = mycol.find()\n all_y_plot = [0]*int(mycol.count_documents({}))\n count = 0\n all_dates = [0]*int(mycol.count_documents({}))\n for document in cursor:\n all_y_plot[count] = float(document[\"Random_Num\"])\n dt_object = datetime.datetime.fromtimestamp(document[\"Time_stamp\"])\n all_dates[count] = dt_object\n count += 1\n\n x_format = matplotlib.dates.DateFormatter('%m/%d %H:%M:%S')\n plt.gca().xaxis.set_major_formatter(x_format)\n # beautify the x-labels\n plt.gcf().autofmt_xdate()\n plt.autoscale(enable=True, axis='x', tight=True)\n plt.plot(all_dates, all_y_plot, 'r')\n\n # A tk.DrawingArea.\n view_all_canvas = FigureCanvasTkAgg(view_all_fig, master=Window2)\n # canvas.draw()\n view_all_canvas.get_tk_widget().grid(row=0, column=0, columnspan=3)\n\n view_all_toolbar_frame = tk.Frame(Window2)\n view_all_toolbar_frame.grid(row=1, column=0, columnspan=2)\n view_all_toolbar_frame = NavigationToolbar2Tk(\n view_all_canvas, view_all_toolbar_frame)\n view_all_toolbar_frame.update()\n\n\ndef on_key_press(event):\n print(\"you pressed {}\".format(event.key))\n key_press_handler(event, canvas, toolbar)\n\n\ndef update_plot():\n plt.figure(1)\n global graph_update_time\n global title1\n title1_str = \"Current time: \" + time.asctime(time.localtime(time.time()))\n title1.configure(text=title1_str)\n if time.time()-graph_update_time >= 60:\n plt.clf()\n x_format = matplotlib.dates.DateFormatter('%m-%d %H:%M')\n plt.autoscale(enable=True, axis='x', tight=False)\n plt.title(\"Voltage of VR\")\n plt.xlabel(\"Time\")\n plt.ylabel(\"Voltage(V)\")\n plt.ylim(-0.5, 3.5)\n graph_update_time = time.time()\n cursor = mycol.find(sort=[(\"_id\", pymongo.DESCENDING)]).limit(10)\n count = 0\n dates = [0]*10\n for document in cursor:\n y_plot[count] = float(document[\"Random_Num\"])\n # For debug\n # print(str(document[\"Random_Num\"]))\n dt_object = datetime.datetime.fromtimestamp(document[\"Time_stamp\"])\n dates[count] = dt_object\n count += 1\n\n x_format = matplotlib.dates.DateFormatter('%m/%d %H:%M:%S')\n plt.gca().xaxis.set_major_formatter(x_format)\n # beautify the x-labels\n plt.gcf().autofmt_xdate()\n plt.autoscale(enable=True, axis='x', tight=True)\n plt.plot(dates, y_plot, 'b')\n\n fig.canvas.draw()\n fig.canvas.flush_events()\n Window1.after(1, update_plot)\n\n\ndef list_time():\n cursor = mycol.find()\n list1 = []\n for documents in cursor:\n # print((documents[\"Time_stamp\"]))\n list1.append(time.asctime(time.localtime(documents[\"Time_stamp\"])))\n #print(datetime.datetime.strptime(time.asctime(time.localtime(documents[\"Time_stamp\"])), \"%a %b %d %H:%M:%S %Y\").timestamp())\n for i in range(0, 20):\n try:\n next(cursor)\n except StopIteration:\n break\n list_time_box[\"values\"] = list1\n Window1.after(10, list_time)\n\n\ndef listed_time_selected():\n if list_time_box.get() == '':\n return\n Window3 = tk.Toplevel()\n Window3.title(\"View Data\")\n Window3.geometry(\"640x640\")\n fig = plt.figure(3, figsize=[6, 6])\n plt.figure(3)\n plt.clf()\n matplotlib.dates.DateFormatter('%m-%d %H:%M')\n plt.autoscale(enable=True, axis='x', tight=False)\n plt.title(\"View data of the voltage of VR\")\n plt.xlabel(\"Time\")\n plt.ylabel(\"Voltage(V)\")\n plt.ylim(-0.5, 3.5)\n\n selected_time = int(datetime.datetime.strptime(\n list_time_box.get(), \"%a %b %d %H:%M:%S %Y\").timestamp())\n #print(datetime.datetime.strptime(selected_time, \"%a %b %d %H:%M:%S %Y\").timestamp())\n cusor = mycol.find()\n count = 0\n documents_time = []\n documents_volt = []\n\n for documents in cusor:\n if selected_time == int(documents[\"Time_stamp\"]):\n count += 1\n if count != 0:\n documents_time.append(\n datetime.datetime.fromtimestamp(documents[\"Time_stamp\"]))\n documents_volt.append(documents[\"Random_Num\"])\n count += 1\n if count >= 20:\n break\n\n x_format = matplotlib.dates.DateFormatter('%m/%d %H:%M:%S')\n plt.gca().xaxis.set_major_formatter(x_format)\n # beautify the x-labels\n plt.gcf().autofmt_xdate()\n plt.autoscale(enable=True, axis='x', tight=True)\n plt.plot(documents_time, documents_volt, 'g')\n\n canvas = FigureCanvasTkAgg(fig, master=Window3) # A tk.DrawingArea.\n # canvas.draw()\n canvas.get_tk_widget().grid(row=0, column=0, columnspan=3)\n\n toolbar_frame = tk.Frame(Window3)\n toolbar_frame.grid(row=1, column=0, columnspan=2)\n toolbar_frame = NavigationToolbar2Tk(canvas, toolbar_frame)\n toolbar_frame.update()\n\n\ny_plot = [0]*10\nx_plot = [0]*10\ngraph_update_time = 0\n\nmyclient = pymongo.MongoClient('mongodb://192.168.0.13:27017')\nprint(myclient.list_database_names())\nmydb = myclient[\"test_database\"]\nmycol = mydb[\"VR_test\"]\n\n\n# It is about the GUI\nWindow1 = tk.Tk()\nWindow1.title(\"Analysis\")\nWindow1.geometry('1024x768')\ntitle1 = tk.Label(Window1, text=\"Current time:\")\ntitle1.grid(row=0, column=0, sticky='w', columnspan=3)\nbtn1 = tk.Button(Window1, text=\"View all data\", command=view_all_data)\nbtn1.grid(row=1, column=0, sticky='w')\nlist_label = tk.Label(Window1, text=\"View values in specific time interval\")\nlist_label.grid(row=1, column=1, sticky='e')\nlist_time_box = ttk.Combobox(Window1)\nlist_time_box.grid(row=1, column=2)\nbtn2 = tk.Button(Window1, text=\"GO\", command=listed_time_selected)\nbtn2.grid(row=1, column=3, sticky='w')\n\nfig = plt.figure(figsize=[6, 6])\nx_format = matplotlib.dates.DateFormatter('%m-%d %H:%M')\nplt.autoscale(enable=True, axis='x', tight=False)\nplt.title(\"Voltage of VR\")\nplt.xlabel(\"Time\")\nplt.ylabel(\"Voltage(V)\")\nplt.ylim(0, 3.5)\n\n\ncanvas = FigureCanvasTkAgg(fig, master=Window1) # A tk.DrawingArea.\n# canvas.draw()\ncanvas.get_tk_widget().grid(row=3, column=0, columnspan=4)\n\ntoolbar_frame = tk.Frame(Window1)\ntoolbar_frame.grid(row=4, column=0, columnspan=4)\ntoolbar = NavigationToolbar2Tk(canvas, toolbar_frame)\ntoolbar.update()\n\n\ncanvas.mpl_connect(\"key_press_event\", on_key_press)\n\n\nWindow1.after(1, update_plot)\nWindow1.after(10, list_time)\nWindow1.mainloop()\n","sub_path":"tkmodel.py","file_name":"tkmodel.py","file_ext":"py","file_size_in_byte":6992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"171603608","text":"\nimport statistics\n\ndef load_data_from_file(filename):\n fitnesses = []\n with open(filename) as fp:\n lines = fp.readlines()[1:]\n for line in lines:\n run_num, fitness = line.split(',')\n fitness = fitness.strip()\n fitnesses.append(float(fitness))\n\n return fitnesses\n\nif __name__ == '__main__':\n files = [\n 'canada.json.csv', 'canada.json.times.csv',\n 'western_sahara.json.csv', 'western_sahara.json.times.csv',\n 'uruguay.json.csv', 'uruguay.json.times.csv'\n ]\n\n for filename in files:\n print(\"{}:\".format(filename))\n values = load_data_from_file(filename)\n print(\"Average: {:.4f}\".format(statistics.mean(values)))\n print(\"Best: {:.4f}\".format(min(values)))\n print(\"-------------------------------------------------\")\n","sub_path":"tsp-project-master/testing/final/analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"594328642","text":"import requests\n\n\nclass ServiceRegistry(object):\n def __init__(self, host:str, port:int, scheme='http'):\n self._base_url = '{}://{}:{}'.format(scheme, host, port)\n\n def register(self, app):\n url = '{}/services'.format(self._base_url)\n resp = requests.post(url, json=app.to_dict())\n return resp.ok\n\n @property\n def enabled_service_names(self):\n url = '{}/services/names'.format(self._base_url)\n resp = requests.get(url)\n if resp.ok:\n return resp.json()['services']\n return []\n\n @property\n def enabled_services(self):\n url = '{}/services'.format(self._base_url)\n resp = requests.get(url)\n if resp.ok:\n return resp.json()['services']\n return {}\n","sub_path":"axial/service/registry.py","file_name":"registry.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"580101290","text":"from Components.Converter.Converter import Converter\r\nfrom Components.Element import cached\r\nfrom Tools.Directories import fileExists\r\nfrom Components.Converter.Poll import Poll\r\nimport time\r\nimport os\r\n\r\nweather_city = '711665'\r\ntime_update = 20\r\ntime_update_ms = 30000\r\n\r\nclass YWeather(Poll, Converter):\r\n\tcity = 0\r\n\tcountry = 1\r\n\tdirection = 2\r\n\tspeed = 3\r\n\thumidity = 4\r\n\tvisibility = 5\r\n\tpressure = 6\r\n\tpressurenm = 7\r\n\twtext = 8\r\n\ttemp = 9\r\n\tpicon = 10\r\n\r\n\tdef __init__(self, type):\r\n\t\tConverter.__init__(self, type)\r\n\t\tPoll.__init__(self)\r\n\t\tif type == \"city\":\r\n\t\t\tself.type = self.city\r\n\t\telif type == \"country\":\r\n\t\t\tself.type = self.country\r\n\t\telif type == \"direction\":\r\n\t\t\tself.type = self.direction\r\n\t\telif type == \"speed\":\r\n\t\t\tself.type = self.speed\r\n\t\telif type == \"humidity\":\r\n\t\t\tself.type = self.humidity\r\n\t\telif type == \"visibility\":\r\n\t\t\tself.type = self.visibility\r\n\t\telif type == \"pressure\":\r\n\t\t\tself.type = self.pressure\r\n\t\telif type == \"pressurenm\":\r\n\t\t\tself.type = self.pressurenm\r\n\t\telif type == \"text\":\r\n\t\t\tself.type = self.wtext\r\n\t\telif type == \"temp\":\r\n\t\t\tself.type = self.temp\r\n\t\telif type == \"picon\":\r\n\t\t\tself.type = self.picon\r\n\t\tself.poll_interval = time_update_ms\r\n\t\tself.poll_enabled = True\r\n\r\n\t@cached\r\n\tdef getText(self):\r\n\t\txweather = {'ycity':\"city\", 'ycountry':\"code\", 'ydirection':\"361\", 'yspeed':\"spd\", 'yhumidity':\"hmd\", 'yvisibility':\"vis\", 'ypressure':\"bar\", 'ytext':\"...\", 'ytemp':\"tmp\", 'ypicon':\"3200\"}\r\n\t\tdirect = 0\r\n\t\tinfo = \"\"\r\n\t\tif fileExists(\"/usr/lib/enigma2/python/Plugins/Extensions/Weather/Config/Location_id\"):\r\n\t\t\tweather_city = open(\"/usr/lib/enigma2/python/Plugins/Extensions/Weather/Config/Location_id\").read()\r\n\t\telse:\r\n\t\t\tweather_city = 715693\r\n\t\ttry:\r\n\t\t\tif fileExists(\"/tmp/yweather.xml\"):\r\n\t\t\t\tif int((time.time() - os.stat(\"/tmp/yweather.xml\").st_mtime)/60) >= time_update:\r\n\t\t\t\t\tos.system(\"rm /tmp/yweather.xml\")\r\n\t\t\t\t\tos.system(\"wget -P /tmp -T2 'http://weather.yahooapis.com/forecastrss?w=%s&u=c' -O /tmp/yweather.xml\" % weather_city)\r\n\t\t\telse:\r\n\t\t\t\tos.system(\"wget -P /tmp -T2 'http://weather.yahooapis.com/forecastrss?w=%s&u=c' -O /tmp/yweather.xml\" % weather_city)\r\n\t\texcept:\r\n\t\t\tpass\r\n\r\n\t\tif not fileExists(\"/tmp/yweather.xml\"):\r\n\t\t\tos.system(\"echo -e 'None' >> /tmp/yweather.xml\")\r\n\t\tfor line in open(\"/tmp/yweather.xml\"):\r\n\t\t\tif line.find(\" -1:\r\n\t\t\t\txweather['ycity'] = line.split('city')[1].split('\"')[1]\r\n\t\t\t\txweather['ycountry'] = line.split('country')[1].split('\"')[1]\r\n\t\t\telif line.find(\" -1:\r\n\t\t\t\txweather['ydirection'] = line.split('direction')[1].split('\"')[1]\r\n\t\t\t\txweather['yspeed'] = line.split('speed')[1].split('\"')[1]\r\n\t\t\telif line.find(\" -1:\r\n\t\t\t\txweather['yhumidity'] = line.split('humidity')[1].split('\"')[1]\r\n\t\t\t\txweather['yvisibility'] = line.split('visibility')[1].split('\"')[1]\r\n\t\t\t\txweather['ypressure'] = line.split('pressure')[1].split('\"')[1]\r\n\t\t\telif line.find(\" -1:\r\n\t\t\t\txweather['ytext'] = line.split('text')[1].split('\"')[1]\r\n\t\t\t\txweather['ypicon'] = line.split('code')[1].split('\"')[1]\r\n\t\t\t\txweather['ytemp'] = line.split('temp')[1].split('\"')[1]\r\n\r\n\t\tif self.type == self.city:\r\n\t\t\tinfo = xweather['ycity']\r\n\t\telif self.type == self.country:\r\n\t\t\tinfo = xweather['ycountry']\r\n\t\telif self.type == self.direction:\r\n\t\t\tdirect = int(xweather['ydirection'])\r\n\t\t\tif direct >= 0 and direct <= 20:\r\n\t\t\t\tinfo = _('N')\r\n\t\t\telif direct >= 21 and direct <= 35:\r\n\t\t\t\tinfo = _('Nne')\r\n\t\t\telif direct >= 36 and direct <= 55:\r\n\t\t\t\tinfo = _('Ne')\r\n\t\t\telif direct >= 56 and direct <= 70:\r\n\t\t\t\tinfo = _('Ene')\r\n\t\t\telif direct >= 71 and direct <= 110:\r\n\t\t\t\tinfo = _('E')\r\n\t\t\telif direct >= 111 and direct <= 125:\r\n\t\t\t\tinfo = _('Nse')\r\n\t\t\telif direct >= 126 and direct <= 145:\r\n\t\t\t\tinfo = _('Se')\r\n\t\t\telif direct >= 146 and direct <= 160:\r\n\t\t\t\tinfo = _('Sse')\r\n\t\t\telif direct >= 161 and direct <= 200:\r\n\t\t\t\tinfo = _('S')\r\n\t\t\telif direct >= 201 and direct <= 215:\r\n\t\t\t\tinfo = _('Ssw')\r\n\t\t\telif direct >= 216 and direct <= 235:\r\n\t\t\t\tinfo = _('Sw')\r\n\t\t\telif direct >= 236 and direct <= 250:\r\n\t\t\t\tinfo = _('Wsw')\r\n\t\t\telif direct >= 251 and direct <= 290:\r\n\t\t\t\tinfo = _('W')\r\n\t\t\telif direct >= 291 and direct <= 305:\r\n\t\t\t\tinfo = _('Wnw')\r\n\t\t\telif direct >= 306 and direct <= 325:\r\n\t\t\t\tinfo = _('Nw')\r\n\t\t\telif direct >= 326 and direct <= 340:\r\n\t\t\t\tinfo = _('Nnw')\r\n\t\t\telif direct >= 341 and direct <= 360:\r\n\t\t\t\tinfo = _('N')\r\n\t\t\telif direct == 361 :\r\n\t\t\t\tinfo = _(' ')\r\n\r\n\t\telif self.type == self.speed:\r\n\t\t\tinfo = xweather['yspeed'] + ' km/h'\r\n\t\telif self.type == self.humidity:\r\n\t\t\tinfo = xweather['yhumidity'] + ' mb'\r\n\t\telif self.type == self.visibility:\r\n\t\t\tinfo = xweather['yvisibility'] + ' km'\r\n\t\telif self.type == self.pressure:\r\n\t\t\tinfo = xweather['ypressure'] + ' mb'\r\n\t\telif self.type == self.pressurenm:\r\n\t\t\tif xweather['ypressure'] != \" \":\r\n\t\t\t\tinfo = \"%d mmHg\" % round(float(xweather['ypressure']) * 0.75)\r\n\t\t\telse:\r\n\t\t\t\tinfo = \" \"\r\n\t\telif self.type == self.wtext:\r\n\t\t\t\t\t\tinfo = xweather['ytext']\r\n\t\telif self.type == self.temp:\r\n\t\t\tif info != \" \":\r\n\t\t\t\tif xweather['ytemp'][0] != '-' and xweather['ytemp'][0] != '0':\r\n\t\t\t\t\tinfo = '+' + xweather['ytemp'] + '%s' % unichr(176).encode(\"latin-1\")\r\n\t\t\t\telse:\r\n\t\t\t\t\tinfo = xweather['ytemp'] + '%s' % unichr(176).encode(\"latin-1\")\r\n\t\t\telse:\r\n\t\t\t\tinfo = xweather['ytemp']\r\n\t\telif self.type == self.picon:\r\n\t\t\tinfo = xweather['ypicon']\r\n\t\treturn info\r\n\r\n\ttext = property(getText)\r\n\r\n\tdef changed(self, what):\r\n\t\tConverter.changed(self, (self.CHANGED_POLL,))\r\n","sub_path":"egami-common/usr/lib/enigma2/python/Components/Renderer/YWeather.py","file_name":"YWeather.py","file_ext":"py","file_size_in_byte":5480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"303158329","text":"import os\nimport yaml\nimport logging\nimport subprocess as sp\nfrom pathlib import Path\nimport re\n\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.INFO)\n\nclass NvimHelper(object):\n '''\n Helper functions for basic nvim ui interactions.\n '''\n\n def __init__(self, nvim):\n self.nv = nvim\n\n def echo(self, msg):\n self.nv.command('echo \"' + msg + '\"')\n\n def input_yesno(self, ques):\n ans = self.nv.funcs.input(ques + ' (y/n): ')\n return (re.match(r'^(yes|y)$', ans, flags=re.IGNORECASE) is not None)\n\ndef load_config(configdir):\n with open(configdir + '/prj.yaml', 'r') as f:\n return yaml.load(f)\n\ndef listfiles(config):\n fs = []\n for d in config['dirs']:\n cmd = 'find {} -type f {}'.format(d, ' -or '.join(\n ['-name \"*.' + ext + '\"' for ext in config['filetypes']]))\n log.info(cmd)\n fs += sp.check_output(cmd, shell=True).splitlines()\n return fs\n\n\ndef listdirs(config):\n cmd = 'find {} -type d'.format(' '.join(config['dirs']))\n log.info(cmd)\n try:\n return sp.check_output(cmd, shell=True).splitlines()\n except sp.CalledProcessError as e:\n error(e.output)\n return []\n\n\ndef get_project_dir():\n d = (Path(os.getcwd()) / '.project')\n log.info(str(d))\n try:\n if d.is_dir():\n return str(d)\n except OSError as e:\n error(e)\n return None\n\n\ndef create_tags_db(config):\n tags_path = Path('/tmp/prjdb')\n if (tags_path.exists()):\n log.info('tags_path exists')\n return\n log.info('Creating tags database...')\n tags_path.mkdir(parents=True, exist_ok=True)\n cmd = 'gtags --file - ' + str(tags_path)\n proc = sp.Popen(cmd, shell=True, stdin=sp.PIPE, stdout=sp.PIPE)\n for name in listfiles(config):\n proc.stdin.write(name + b'\\n')\n proc.stdin.close()\n proc.wait()\n log.info('done.')\n\n\n# def find_definition(symbol):\n# cmd = ('GTAGSROOT=$(pwd) GTAGSDBPATH=/tmp/prjdb '\n# 'global --result grep {}'.format(symbol))\n# log.info(cmd)\n# try:\n# return [\n# s.decode('utf-8')\n# for s in sp.check_output(cmd, shell=True).splitlines()\n# ]\n# except sp.CalledProcessError as e:\n# error(e.output)\n# return []\n\n\n# def find_references(symbol):\n# cmd = ('GTAGSROOT=$(pwd) GTAGSDBPATH=/tmp/prjdb '\n# 'global -r --result grep {}'.format(symbol))\n# log.info(cmd)\n# return [f.decode('utf-8')\n# for f in sp.check_output(cmd, shell=True).splitlines()]\n\n\n# def parse_tagline(line):\n# m = re.match(r'(.*?):(.*?):.*', line)\n# fname = m.group(1)\n# lineno = int(m.group(2))\n# return (fname, lineno)\n","sub_path":"rplugin_xx/python3/wsp/nvim_helper.py","file_name":"nvim_helper.py","file_ext":"py","file_size_in_byte":2704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"487347966","text":"from behave import when, then, given\nimport subprocess\nimport time\nimport os\nimport requests\nimport logging\nimport select\nimport socket\nimport fcntl\nfrom time import sleep\nfrom docker import Client\nfrom container import Container, ExecException\n\nDOCKER_CLIENT = Client()\nLOG_FORMAT='%(asctime)s - %(name)s - %(levelname)s - %(message)s'\nlogging.basicConfig(format=LOG_FORMAT)\n\n@when(u'container is ready')\ndef container_is_started(context):\n context.container = Container(context.image, name=context.scenario.name)\n context.container.start()\n\n@then(u'the image should contain label {label}')\n@then(u'the image should contain label {label} {check} value {value}')\ndef label_exists(context, label, check=\"with\", value=None):\n metadata = DOCKER_CLIENT.inspect_image(context.image)\n config = metadata['Config']\n\n try:\n labels = config['Labels']\n except KeyError:\n raise Exception(\"There are no labels in the %s image\" % context.image)\n\n try:\n actual_value = labels[label]\n except KeyError:\n raise Exception(\"Label %s was not found in the %s image\" % (label, context.image))\n\n if not value:\n return True\n\n if check == \"with\" and actual_value == value:\n return True\n elif check == \"containing\" and actual_value.find(value) >= 0:\n return True\n\n raise Exception(\"The %s label does not contain %s value, current value: %s\" % (label, value, actual_value))\n\n@then(u'check that page is not served')\ndef check_page_is_not_served(context):\n # set defaults\n port = 80\n wait = 30\n timeout = 0.5\n expected_status_code = 200\n path = '/'\n expected_phrase = None\n # adjust defaults from user table\n for row in context.table:\n if row['property'] == 'port':\n port = row['value']\n if row['property'] == 'expected_status_code':\n expected_status_code = int(row['value'])\n if row['property'] == 'wait':\n wait = int(row['value'])\n if row['property'] == 'timeout':\n timeout = row['value']\n if row['property'] == 'expected_phrase':\n expected_phrase = row['value']\n if row['property'] == 'path':\n path = row['value']\n try:\n handle_request(context, port, wait, timeout, expected_status_code, path, expected_phrase)\n except:\n return True\n raise Exception(\"Page was served\")\n\n\n@then(u'check that page is served')\ndef check_page_is_served(context):\n # set defaults\n port = 80\n wait = 30\n timeout = 0.5\n expected_status_code = 200\n path = '/'\n expected_phrase = None\n # adjust defaults from user table\n for row in context.table:\n if row['property'] == 'port':\n port = row['value']\n if row['property'] == 'expected_status_code':\n expected_status_code = int(row['value'])\n if row['property'] == 'wait':\n wait = int(row['value'])\n if row['property'] == 'timeout':\n timeout = row['value']\n if row['property'] == 'expected_phrase':\n expected_phrase = row['value']\n if row['property'] == 'path':\n path = row['value']\n handle_request(context, port, wait, timeout, expected_status_code, path, expected_phrase)\n\ndef handle_request(context, port, wait, timeout, expected_status_code, path, expected_phrase):\n logging.info(\"Checking if the container is returning status code %s on port %s\" % (expected_status_code, port))\n \n start_time = time.time()\n\n ip = context.container.ip_address\n latest_status_code = 0\n \n while time.time() < start_time + wait:\n try:\n response = requests.get('http://%s:%s%s' % (ip, port, path), timeout = timeout, stream=False)\n except Exception as ex:\n # Logging as warning, bcause this does not neccessarily means\n # something bad. For example the server did not boot yet.\n logging.warn(\"Exception caught: %s\" % repr(ex))\n else:\n latest_status_code = response.status_code\n logging.info(\"Response code from the container on port %s: %s (expected: %s)\" % (port, latest_status_code, expected_status_code))\n if latest_status_code == expected_status_code:\n if not expected_phrase:\n # The expected_phrase parameter was not set\n return True\n\n if expected_phrase in response.text:\n # The expected_phrase parameter was found in the body\n logging.info(\"Document body contains the '%s' phrase!\" % expected_phrase)\n return True\n else:\n # The phrase was not found in the response\n raise Exception(\"Failure! Correct status code received but the document body does not contain the '%s' phrase!\" % expected_phrase,\n \"Received body:\\n%s\" % response.text) # XXX: better diagnostics\n\n time.sleep(1)\n raise Exception(\"handle_request failed\", expected_status_code) # XXX: better diagnostics \n\n@then(u'container log should not contain {message}')\ndef log_not_contains_msg(context, message):\n try:\n log_contains_msg(context, message)\n raise Exception(\"log contains %s\" % message)\n except:\n pass\n\n@then(u'container log should contain {message}')\ndef log_contains_msg(context, message):\n found = True\n found_messages = []\n start_time = time.time()\n\n # TODO: Add customization option for timeout\n while time.time() < start_time + 30:\n logs = context.container.get_output()\n if message in logs:\n logging.info(\"Message '%s' was found in the logs\" % message)\n return\n # TODO: Add customization option for sleep time\n time.sleep(1)\n else:\n logging.error(\"Message '%s' was not found in the logs\" % message)\n raise Exception(\"expect_message failed\", message)\n\n@then(u'run {cmd} in container and immediately check its output for {output_phrase}')\n@then(u'run {cmd} in container and immediately check its output contains {output_phrase}')\ndef run_command_immediately_expect_message(context, cmd, output_phrase):\n output = context.container.execute(cmd=cmd)\n if not output_phrase in output:\n raise Exception(\"run_command_expect_message didn't find message\", output)\n return True\n\n@then(u'run {cmd} in container and immediately check its output does not contain {output_phrase}')\ndef run_command_immediately_unexpect_message(context, cmd, output_phrase):\n try:\n run_command_immediately_expect_message(context, cmd, output_phrase)\n except:\n return True\n raise Exception(\"commmand output contains prohibited text\")\n\n@then(u'run {cmd} in container and check its output does not contain {output_phrase}')\ndef run_command_unexpect_message(context, cmd, output_phrase):\n try:\n run_command_expect_message(context, cmd, output_phrase)\n except:\n return True\n raise Exception(\"commmand output contains prohibited text\")\n\n@then(u'run {cmd} in container and check its output for {output_phrase}')\n@then(u'run {cmd} in container and check its output contains {output_phrase}')\n@then(u'run {cmd} in container')\ndef run_command_expect_message(context, cmd, output_phrase):\n start_time = time.time()\n while time.time() < start_time + 80:\n last_output = None\n try:\n output = context.container.execute(cmd=cmd)\n if output_phrase in output:\n return True\n except ExecException as e:\n last_output = e.output\n time.sleep(1)\n raise Exception(\"run_command_expect_message didn't find message\", last_output)\n\n\n@then('file {filename} should contain {phrase}')\ndef file_should_contain(context, filename, phrase):\n run_command_expect_message(context, 'cat %s' % filename, phrase)\n\n@given(u'sti build {application}')\n@given(u'sti build {application} from {path}')\ndef sti_build(context, application, path='.'):\n context.image = context.config.userdata.get('IMAGE', 'ctf')\n image_id = \"integ-\" + context.image\n command = \"sti build --loglevel=5 --force-pull=false --context-dir=%s %s %s %s\" % (path, application, context.image, image_id)\n logging.info(\"Executing new STI build...\")\n if _execute(command):\n logging.info(\"STI build succeeded, image %s was built\" % image_id)\n else:\n logging.error(\"STI build failed, check logs!\")\n context.container = Container(image_id, name=context.scenario.name)\n context.container.start()\n\n\n@given(u'container is started with env')\n@when(u'container is started with env')\ndef start_container(context):\n env = {}\n for row in context.table:\n env[row['variable']] = row['value']\n context.container = Container(context.image, name=context.scenario.name)\n context.container.start(environment = env)\n\n@given(u'image is built')\ndef image(context):\n pass\n\n@given(u'container is started as uid {uid}')\n@when(u'container is started as uid {uid}')\ndef start_container(context, uid):\n if uid < 0:\n raise Exception(\"UID %d is negative\" % uid)\n context.container = Container(context.image, save_output = False)\n context.container.start(user = uid)\n\n\n@then(u'check that port {port} is open')\ndef check_port_open(context, port):\n start_time = time.time()\n\n ip = context.container.ip_address\n logging.info(\"connecting to %s port %s\" % (ip, port))\n while time.time() < start_time + 30:\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(1)\n s.connect((ip, int(port)))\n s.close()\n return True\n except Exception as ex:\n logging.debug(\"not connected yes %s\" %ex)\n time.sleep(1)\n raise Exception(\"Port %s is not open\" %port)\n\n@then(u'file {file_name} should exist')\n@then(u'file {file_name} should exist and be a {file_type}')\n#TODO: @then(u'file {file_name} should exist and have {permission} permissions')\ndef check_file_exists(context, file_name, file_type = None):\n try:\n context.container.execute(\"test -e %s\" % file_name)\n except ExecException:\n raise Exception(\"File %s does not exist\" % file_name)\n\n if file_type:\n if file_type == \"directory\":\n try:\n context.container.execute(\"test -d %s\" % file_name)\n except ExecException:\n raise Exception(\"File %s is not a directory\" % file_name)\n elif file_type == \"symlink\":\n try:\n context.container.execute(\"test -L %s\" % file_name)\n except ExecException:\n raise Exception(\"File %s is not a symlink\" % file_name)\n\n return True\n\ndef _execute(command, log_output = True):\n \"\"\"\n Helper method to execute a shell command and redirect the logs to logger\n with proper log level.\n \"\"\"\n\n logging.debug(\"Executing '%s' command...\" % command)\n\n try:\n proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n\n levels = {\n proc.stdout: logging.DEBUG,\n proc.stderr: logging.ERROR\n }\n\n fcntl.fcntl(\n proc.stderr.fileno(),\n fcntl.F_SETFL,\n fcntl.fcntl(proc.stderr.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK,\n )\n\n fcntl.fcntl(\n proc.stdout.fileno(),\n fcntl.F_SETFL,\n fcntl.fcntl(proc.stdout.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK,\n )\n\n if log_output:\n while proc.poll() == None:\n readx = select.select([proc.stdout, proc.stderr], [], [])[0]\n for output in readx:\n line = output.readline()[:-1]\n logging.log(levels[output], line)\n\n retcode = proc.wait()\n\n if retcode is not 0:\n logging.error(\"Command '%s' returned code was %s, check logs\" % (command, retcode))\n return False\n\n except subprocess.CalledProcessError as e:\n logging.error(\"Command '%s' failed, check logs\" % command)\n return False\n\n return True\n","sub_path":"tests/steps/steps.py","file_name":"steps.py","file_ext":"py","file_size_in_byte":12140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"569394852","text":"from matplotlib import pyplot as plt\nimport numpy as np\nfrom sklearn.datasets import load_iris\nfrom threshold import fit_model, predict\n\ndata = load_iris()\nfeatures = data.data\nfeature_names = data.feature_names\ntarget = data.target\ntarget_names = data.target_names\n\nlabels = target_names[target]\nplength = features[:, 2]\n\n# Looking at data chart we can se that setona has big differene in petal lenght.\n# So, it's easy to separate from the rest of iris\n# Build array of booleans\nis_setosa = (labels == 'setosa')\nmax_setosa = plength[is_setosa].max()\nmin_non_setosa = plength[~is_setosa].min()\nprint(\"Maximum of setosa: {}.\" .format(max_setosa))\nprint(\"Minimum of others: {}.\" .format(min_non_setosa))\n\n# As we can see that setosa is easy to detect\n# We can remove setosa from the features\nfeatures = features[~is_setosa]\nlabels = labels[~is_setosa]\n\n# Build new target\nis_virginica = (labels == 'virginica')\n\n# Initialize best_acc to impossibly low value\nbest_acc = -1.0\nfor fi in range(features.shape[1]):\n # Test all possiblie thresholds\n thresh = features[:, fi]\n\n for t in thresh:\n # get the vector for feature 'fi'\n feature_i = features[:, fi]\n # Apply threshold\n pred = (feature_i > t)\n acc = (pred == is_virginica).mean()\n rev_acc = (pred == ~is_virginica).mean()\n\n if rev_acc > acc:\n reverse = True\n acc = rev_acc\n else:\n reverse = False\n\n if acc > rev_acc:\n best_acc = acc\n best_fi = fi\n best_t = t\n best_reverse = reverse\n\nprint(best_fi, best_t, best_reverse, best_acc)\n\ndef is_virginica_test(fi, t, reverse, example):\n # Apply threshold model to a new example\n test = example[fi] > t\n\n if reverse:\n test = not test\n return test\n\ncorrect = 0.0\n\nfor ei in range(len(features)):\n # select all but the one at position 'ei'\n training = np.ones(len(features), bool)\n training[ei] = False\n testing = ~training\n model = fit_model(features[training], is_virginica[training])\n predictions = predict(model, features[testing])\n correct += np.sum(predictions == is_virginica[testing])\nacc = correct / float(len(features))\nprint('Accuracy: {0:.1%}'.format(acc))\n","sub_path":"demos/iris/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"175269335","text":"# 문제\n# SWEA 5186 - [파이썬 S/W 문제해결 구현 1일차] 시작하기 - 이진수2\n\n# 나의 코드\nT = int(input())\n\nfor tc in range(T):\n num = float(input())\n result = ''\n count = 0\n \n # 십진수 => 이진수\n while count <= 13:\n num = num * 2\n result += str(num)[0]\n num = num - int(num)\n count += 1\n if num == 0.0:\n break\n\n if count > 13:\n print(\"#%d overflow\" %(tc+1))\n else:\n print(\"#%d %s\" %(tc+1, result))\n","sub_path":"SWEA/5186_이진수2.py","file_name":"5186_이진수2.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"347536283","text":"from . import base\nfrom . import fileutil\n\n\nclass LineFileUtil(base.Base):\n \"\"\"File Manager\n Handles I/O and generation.\n \"\"\"\n\n def __init__(self, path, line, create, fd=None):\n \"\"\"Constructor.\n\n Args:\n path (string): the path to the file.\n line (int): length of line.\n create (bool): true if need to create.\n fd (int): If set, will use given fd.\n \"\"\"\n super(LineFileUtil, self).__init__()\n\n self._file = fileutil.FileUtil(path, create, fd)\n\n self._path = str(self._file)\n\n self._current = 0\n\n self._linelen = line\n\n self._numlines = len(self._file) / self._linelen\n\n self.logger.info(\n \"Initialized file successfully, %d lines of %d chars each.\"\n %\n (self._numlines, self._linelen)\n )\n\n def __str__(self):\n \"\"\"Gets the string represintation.\n\n Returns:\n (str): Path.\n \"\"\"\n return self._path\n\n def __len__(self):\n \"\"\"Gets the length\n Returns:\n int: file length.\n \"\"\"\n return self._numlines\n\n def read(self, line=None):\n \"\"\"Reads a single line from the file.\n\n Args:\n (int) line: line to read from.\n Return:\n (string): The line read.\n \"\"\"\n\n if line and line > -1:\n self.goto(line)\n self._current = line\n\n self.logger.debug(\n \"Reading from %s\"\n %\n (\n self._file\n )\n )\n\n read = self._file.read()\n\n self.logger.debug(\n \"Read %s from %s\"\n %\n (\n repr(read),\n self._file\n )\n )\n\n self._current += 1\n\n return read\n\n def write(self, data, line=None):\n \"\"\"Writes a single line from the file.\n\n Args:\n (int) line: The line number to write to.\n (stirng) data: The data to write\n \"\"\"\n\n if line and line > -1:\n self.goto(line)\n\n self.logger.debug(\n \"Writing %s to %s\"\n %\n (\n repr(data),\n self._file\n )\n )\n\n self._file.write(data)\n\n self._numlines = len(self._file) / self._linelen\n\n def goto(self, line):\n \"\"\"Jumps to line.\n\n Args:\n (int) line: The offset to jump to\n \"\"\"\n\n if (line > self._numlines):\n self.logger.error(\n \"Tried to jump to nonexistant line %d out of %d\"\n %\n (line, self._numlines)\n )\n raise RuntimeError(\n \"Tried to jump to nonexistant line %d out of %d\"\n %\n (line, self._numlines)\n )\n\n self.logger.debug(\n \"Going to line %d.\"\n %\n line\n )\n\n self._current = line\n\n self._file.goto(line*self._linelen)\n\n def end(self):\n \"\"\"Checks if at end of file.\n\n Return:\n (bool): True if at end.\n \"\"\"\n return self._current == self._numlines\n\n def delete(self):\n \"\"\"Deletes the file.\n \"\"\"\n return self._file.delete()\n\n def getfd(self):\n \"\"\"Gets the file descriptor.\n\n Return:\n (int): File descriptor\n \"\"\"\n return self._file.getfd()\n","sub_path":"04-filesort/03-threaded/linefileutil.py","file_name":"linefileutil.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"300120710","text":"#encoding: utf-8\n'''\n方策(Policy)クラス\n'''\n\nimport blackjack\nfrom collections import defaultdict\nimport re\n\nfrom random import choice\n\nclass Policy:\n def __init__(self):\n # 方策\n # 構造: Aceを保持[yes, no] - プレイヤーのトータル数 - ディーラーのオープンしているカード - hit(True or False)]\n self.policy = [defaultdict(lambda: defaultdict(lambda: True)), defaultdict(lambda: defaultdict(lambda: True))]\n\n # 出力ヘッダの準備\n self.print_bar = \"-------\" + \"--------------\" * 9\n self.print_header = \" |\"\n for i in xrange(12, 22, 1):\n self.print_header += \" %02d \" % (i)\n\n def hit(self, player_total, player_has_ace, dealer_face_value):\n '''\n 方策の取得(hitするかどうか)\n arguments:\n プレイヤーのトータル数\n プレイヤーがAceをもっているかどうか\n ディーラーのオープンしているカード\n return:\n 方策 True:hit, False:stand\n '''\n ace_index = 1\n if player_has_ace:\n ace_index = 0\n return self.policy[ace_index][player_total][dealer_face_value]\n\n def set(self, player_total, player_has_ace, dealer_face_value, hit):\n '''\n 方策の設定\n arguments:\n プレイヤーのトータル数\n プレイヤーがAceをもっているかどうか\n ディーラーのオープンしているカード\n 方策 True:hit, False:stand\n '''\n ace_index = 1\n if player_has_ace:\n ace_index = 0\n self.policy[ace_index][player_total][dealer_face_value] = hit\n\n def output(self):\n '''\n 現状の出力\n '''\n print(re.sub('-----', '[ace]', self.print_bar, 1))\n print(self.print_header)\n print(self.print_bar)\n print_format = \"\"\n for i in xrange(2, 12, 1):\n print_format += \"%02d |\" % (i)\n for j in xrange(12, 22, 1):\n action = 'stand'\n if self.hit(j, True, i):\n action = 'hit'\n print_format += \"%06s \" % (action)\n print_format += \"\\n\"\n print(print_format)\n print(self.print_bar)\n \n print(re.sub('-------', '[noace]', self.print_bar, 1))\n print(self.print_header)\n print(self.print_bar)\n print_format = \"\"\n for i in xrange(2, 12, 1):\n print_format += \"%02d |\" % (i)\n for j in xrange(12, 22, 1):\n action = 'stand'\n if self.hit(j, False, i):\n action = 'hit'\n print_format += \"%06s \" % (action)\n print_format += \"\\n\"\n print(print_format)\n print(self.print_bar)\n\n \ndef test():\n policy = Policy()\n policy.policy[0][12][4] = False\n policy.output()\n\nif __name__ == '__main__':\n test()\n","sub_path":"blackjack_policy.py","file_name":"blackjack_policy.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"361039584","text":"#encoding:utf-8\nimport os\nimport re\n\n'''\n把CUP下文件名中带Adapter的代码全部注掉\n'''\n\nif __name__ == '__main__':\n for file_name in os.listdir(\".\"):\n\n if \"Adapter\" in file_name:\n print(file_name)\n with open(file_name, 'r', encoding='utf-8') as f:\n contents = f.readlines()\n\n contents.insert(0, '/*')\n contents.append('*/')\n \n with open(file_name, 'w', encoding='utf-8') as f:\n contents = \"\".join(contents)\n f.write(contents)\n","sub_path":"commit_adapter.py","file_name":"commit_adapter.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"328068217","text":"# -*- coding:utf-8 -*-\n#\n# @lc app=leetcode.cn id=92 lang=python3\n#\n# [92] 反转链表 II\n#\n# https://leetcode-cn.com/problems/reverse-linked-list-ii/description/\n#\n# algorithms\n# Medium (41.13%)\n# Total Accepted: 7.6K\n# Total Submissions: 18K\n# Testcase Example: '[1,2,3,4,5]\\n2\\n4'\n#\n# 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。\n#\n# 说明:\n# 1 ≤ m ≤ n ≤ 链表长度。\n#\n# 示例:\n#\n# 输入: 1->2->3->4->5->NULL, m = 2, n = 4\n# 输出: 1->4->3->2->5->NULL\n#\n#\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\n\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n def __str__(self):\n tmp = []\n node = self\n while node:\n tmp.append(repr(node.val))\n node = node.next\n tmp.append('None')\n return ' -> '.join(tmp)\n\n __repr__ = __str__\n\n\ndef build_list_node(nums):\n head = node = ListNode(None)\n for i in nums:\n node.next = ListNode(i)\n node = node.next\n return head.next\n\n\nclass Solution:\n def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:\n \"\"\"\n 使用头指针, 先走m-1步\n 将m+1到n的节点插入到m前面\n \"\"\"\n\n if not head or not head.next:\n return head\n\n new_head = ptr = ListNode(None)\n new_head.next = head\n\n for _ in range(m-1):\n ptr = ptr.next\n edge_ptr = ptr.next\n for _ in range(n-m):\n tmp = edge_ptr.next\n edge_ptr.next = edge_ptr.next.next\n tmp.next = ptr.next\n ptr.next = tmp\n return new_head.next\n\nif __name__ == \"__main__\":\n l = build_list_node(range(1,10))\n print(Solution().reverseBetween(l, 2, 9))\n","sub_path":"92.反转链表-ii.py","file_name":"92.反转链表-ii.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"482977719","text":"\n\n#calss header\nclass _GOING():\n\tdef __init__(self,): \n\t\tself.name = \"GOING\"\n\t\tself.definitions = [u'how quickly you do something: ', u'how easy or difficult something is: ', u'the condition of the ground for walking or riding, etc.: ', u'an occasion when someone leaves somewhere: ']\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/_going.py","file_name":"_going.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"539316574","text":"from bs4 import BeautifulSoup\nimport requests\nimport re\nfrom datetime import datetime\nimport lxml\nimport sys\nimport multiprocessing as mp\n\nmembers_list ={ 'ellapresso':'뇸뇸',\n '9992':'또르',\n 'changbokLee':'복이',\n 'x86kernel':'ㄷㄷ',\n 'samkookji77':'레힙',\n 'th787706':'감동란',\n 'cafemug':'컴공돌이',\n 'SeongMinSeok':'퐁퐁',\n 'rnhappysmile':'해피스마일',\n 'jonghwajoa':'오홍',\n 'ccppoo':'ccpo',\n 'msnodeve':'싸이클러',\n 'haeyoonjo':'깃토리',\n 'Tonoff':'깃허브초보',\n 'horace-velmont':'1컴',\n 'Seonghy':'방탄성현단',\n 'ljhg1124':'뇌가말랑',\n 'Chanmi-Kim':'하준',\n 'Mengkko':'맹코',\n 'WG19':'깃☆',\n 'Chanmi-Kim':'하준'\n}\n\ndef check_past_data(self):\n # 이전에 사용자에 대한 정보를 조회했던 경우 (pickle된 자료)\n # 역직렬화 이후, self.latest가 today와 일치하지 않는 경우 파싱\n # 아닌경우, 역직렬화 한 내용을 가지고 요청한 자료형태로 반환 (최근 7일, 연속, 최근 한달, 등등)\n pass\n\n# class htmlgetter(threading.Thread):\nclass htmlgetter():\n def __init__(self, name):\n # threading.Thread.__init__(self)\n self.name =name\n self.url='https://github.com/'+self.name\n self.today =datetime.today().strftime(\"%Y-%m-%d\")\n # 모든 html 내용 (whole html of the site)\n self.html=None\n # html에서 해당 날짜에 커밋 횟수가 들어있는 html내용\n self.commit_data=None\n # 커밋한 횟수, 날짜가 튜플로 들어 있는 리스트\n self.contents=[]\n # 나중에 잔디 디스코드 봇 만들 때 쓰일 지표(날짜)\n # (이전에 커밋한 내용 pickle 할 예정)\n self.latest =self.today\n # 최근 30일, 최근 7일, 연속 커밋 기록용\n self.status=[0,0,0]\n # 오늘 커밋을 했는지 안했는지\n self.today_ =False\n\n def run(self):\n try:\n with requests.get(self.url) as grass:\n self.html = grass.text\n self.html =BeautifulSoup(self.html, 'lxml')\n self.commit_data=self.html.find_all('rect', class_='day')\n for day in self.commit_data:\n self.contents.append((int(day.get(\"data-count\")), day.get(\"data-date\")))\n # print(self.commit_data)\n # self.commit_data=self.html.find_all('rect', class_='day')\n # self.commit_data=self.html.find_all('rect', class_='day', attrs={'data-date':self.today})\n\n except:\n print(\"No user named :\" + self.name)\n return\n\ndef check_status(users):\n for user in users:\n flag=True\n for i in range(-1,-len(user.contents), -1):\n if(user.contents[i][0]):\n if(flag):\n user.status[2]+=1\n if(i>=-30):\n user.status[0]+=1\n if(i>=-7):\n user.status[1]+=1\n else:\n flag=False\n if(user.contents[-1][0]):\n user.today_=True\n\n members_status=[]\n # 30일\n members_status.append(sorted([(user.name,user.status[0]) for user in users if user.status[0] >0], key=lambda v :v[1], reverse=True))\n # 7일\n members_status.append(sorted([(user.name,user.status[1]) for user in users if user.status[1] >0], key=lambda v :v[1], reverse=True))\n # 연속\n members_status.append(sorted([(user.name,user.status[2]) for user in users if user.status[2] >0], key=lambda v :v[1], reverse=True))\n return members_status\n\ndef print_table(members_status, members):\n print('연속 커밋')\n for user in members_status[2]:\n print('{} : {}'.format(members_list[user[0]], user[1]))\n print('\\n최근 30일동안 커밋')\n for user in members_status[0]:\n print('{} : {}'.format(members_list[user[0]], user[1]))\n print('\\n최근 7일동안 커밋')\n for user in members_status[1]:\n print('{} : {}'.format(members_list[user[0]], user[1]))\n print('\\n오늘 커밋')\n for x in members:\n if(x.today_):\n print(' ',members_list[x.name], x.contents[-1][0], '회')\n print('\\n오늘 커밋 안한사람(클라이언트 세션 GMT +0 기준)')\n for x in members:\n if not x.today_:\n print(' ',members_list[x.name])\n\ndef main():\n yes_grass =[]; no_grass=[]\n # key == id, value == nickname\n\n num_cpus = int(mp.cpu_count())\n print(num_cpus)\n users = [htmlgetter(id) for id in members_list.keys()]\n processes = []\n for x in users:\n proc = mp.Process(target=x.run)\n proc.start()\n processes.append(proc)\n for proc in processes:\n proc.join()\n\n for x in users :\n print(x.name, x.contents)\n\n # members_status =check_status(users)\n # print_table(members_status, users)\n\nif __name__=='__main__':\n import time\n s=time.time()\n main()\n print('\\n\\n걸린 시간:',(time.time()-s))\n","sub_path":"git_crawlers/git_web_multiprocess.py","file_name":"git_web_multiprocess.py","file_ext":"py","file_size_in_byte":5183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"241045535","text":"a,b = map(int,input().split())\nc = []\ncc = []\nfor i in range(a):\n d,e = input().split()\n c.append(d)\nc.reverse()\nfor i in range(b):\n sum = 0\n cc.append(input())\n for k in range(c.__len__()-cc[i].__len__()+1):\n j = 0\n while j < cc[i].__len__():\n if cc[i][j] == c[k]:\n j += 1\n k += 1\n else:\n break\n if j == cc[i].__len__():\n sum += 1\n if k >= c.__len__()-1:\n break\n print(sum)\n","sub_path":"Code/CodeRecords/2211/60654/293579.py","file_name":"293579.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"252912944","text":"\"\"\"\n@author Yuqi Hu\n@date Sep. 13th 2020\n@version 1.0\n@purpose This File serves as the main clustering algorithm of this project.\n## IMPORTANT NOTES:\n* Direction: From row to colum, each entry means the shortest time to travel from ith place to jth place.\n* Assumption:\n - All points are connected.\n - Each point can travel to other points within an exisited time span.\n - We do not consider each point will be visited again based on time graph (Even if in reality there exists `B` on the track from `A` to `C`, note as `A-B-C`, but `time(A-C)` is less than `time(A-B) + time(B-C)`.)\n## APIs\n* `clustering(matrix, cluster_N)`\n * `matrix` is a 2D array which serves as a sqaure matrix.\n * `cluster_N` is an integer that the user wants to divide the points set into.\n * Return Type is a diction in the form of `{index : point_indices_list_correponding_to_the_centroids}`. `index` is an integer, and `point_indices_list_correponding_to_the_centroids` is a list of integer indices of points.\n\"\"\"\n\nimport copy\nfrom collections import defaultdict\n\nclass cluster:\n \"\"\"\n #################\n ### APIs FUNC ###\n #################\n \"\"\"\n\n # API func.\n def clustering(matrix, cluster_N):\n # Validation\n if cluster_N > len(matrix) or cluster_N <= 0:\n print(\"Ilegal input!\")\n return {}\n\n # Separation\n result = cluster.categorization(matrix, cluster_N)\n for i in range(len(result)):\n if len(result[i]) == 0:\n return cluster.categorization(matrix, cluster_N, True)\n return result\n\n \"\"\"\n #################\n ### MAIN ALGO ###\n #################\n \"\"\"\n\n def categorization(point_lst, N, centroid_zero_flag=False, iter_time=1000):\n \"\"\"\n ######################\n ### HELPERS ###\n ######################\n \"\"\"\n\n def dist(a, b):\n sum = 0\n for i in range(0, len(a)):\n sum += (a[i] - b[i]) ** 2\n return sum ** (1 / 2)\n\n def mid_point(point_lst):\n total_num = len(point_lst)\n if total_num == 0:\n return None\n len_element = len(point_lst[0])\n a = []\n for i in range(0, len_element):\n a.append(0)\n for i in range(0, total_num):\n for j in range(0, len_element):\n a[j] += point_lst[i][j]\n for i in range(0, len_element):\n a[i] = a[i] / total_num\n return a\n\n def closer_to(s, centroids_lst):\n centroids_num = len(centroids_lst)\n dict_closer_to = {}\n for i in range(0, centroids_num):\n dict_closer_to.update({dist(s, centroids_lst[i]): i})\n return dict_closer_to[min(dict_closer_to)]\n\n def get_centroids_lst(point_lst, N):\n centroids_lst = [mid_point(point_lst)]\n point_lst = copy.deepcopy(point_lst)\n N -= 1\n while N != 0:\n dict_get_centroids_lst = {}\n for i in range(len(point_lst)):\n sum = [0]\n for centroid in centroids_lst:\n sum[0] += dist(centroid, point_lst[i])\n dict_get_centroids_lst.update({sum[0] : i})\n centroids_lst.append(point_lst.pop(dict_get_centroids_lst[max(dict_get_centroids_lst)]))\n N -= 1\n return centroids_lst\n\n def get_centroids_lst_zero(point_lst, N):\n zero_centroids_lst = []\n for i in range(N):\n zero_centroids_lst.append(point_lst[i])\n return zero_centroids_lst\n\n \"\"\"\n #################\n ### CORE ALGO ###\n #################\n \"\"\"\n\n centroids_lst = None\n if centroid_zero_flag:\n centroids_lst = get_centroids_lst_zero(point_lst, N)\n else:\n centroids_lst = get_centroids_lst(point_lst, N)\n\n dict = None\n inter_count = 0\n previous_centroids_lst = copy.deepcopy(centroids_lst)\n while inter_count < iter_time:\n dict = defaultdict(list)\n for i in range(len(point_lst)):\n closest_centroid_pos = closer_to(point_lst[i], centroids_lst)\n dict[closest_centroid_pos].append(i)\n for i in range(N):\n temp_centroid = mid_point([point_lst[x] for x in dict[i]])\n if temp_centroid:\n centroids_lst[i] = temp_centroid\n inter_count += 1\n if previous_centroids_lst == centroids_lst:\n break\n previous_centroids_lst = copy.deepcopy(centroids_lst)\n return dict\n","sub_path":"maps/clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":4736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"417711178","text":"import os\nimport numpy as np\nfrom PIL import Image\nimport glob\n\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\n\n\nclass MVTecAD(torchvision.datasets.MNIST):\n def __init__(self, root, category, train, transform=None):\n self.root = root\n self.category = category\n self.train = train\n self.transform = transform\n \n self.train_dir = os.path.join(root, category, 'train')\n self.test_dir = os.path.join(root, category, 'test')\n \n self.normal_class = ['good']\n self.abnormal_class = os.listdir(self.test_dir)\n self.abnormal_class.remove(self.normal_class[0])\n \n if train:\n img_paths = glob.glob(os.path.join(\n self.train_dir, self.normal_class[0], '*.png'))\n self.img_paths = sorted(img_paths)\n self.labels = len(self.img_paths) * [1]\n else:\n img_paths = []\n labels = []\n for c in os.listdir(self.test_dir):\n paths = glob.glob(os.path.join(\n self.test_dir, c, '*.png'))\n img_paths.extend(sorted(paths))\n if c == self.normal_class[0]:\n labels.extend(len(paths) * [1])\n else:\n labels.extend(len(paths) * [0])\n \n self.img_paths = img_paths\n self.labels = labels \n\n def __getitem__(self, index):\n img_path, target = self.img_paths[index], self.labels[index]\n\n img = Image.open(img_path).convert('RGB')\n\n if self.transform is not None:\n img = self.transform(img)\n\n return img, target\n\n def __len__(self):\n return len(self.img_paths)\n \n \n\ndef main(isize=32, batchsize=49):\n transform = transforms.Compose([\n transforms.Resize(isize),\n transforms.CenterCrop(isize),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)), ])\n \n dataset = MVTecAD(\n root='data/mvtec',\n category='metal_nut',\n train=True,\n transform=transform)\n \n loader = torch.utils.data.DataLoader(\n dataset=dataset,\n batch_size=batchsize,\n shuffle=False,\n num_workers=4,\n drop_last=True)\n \n for i, batch in enumerate(loader):\n imgs, labels = batch\n torchvision.utils.save_image(imgs, '{}-batch-{}.png'.format(category, i), nrow=7, normalize=True)\n print(imgs.shape, labels.shape)\n \n \n\nif __name__ == '__main__':\n main()\n ","sub_path":"lib/mvtec.py","file_name":"mvtec.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"3796033","text":"import scrapy\nfrom news.items import NewsItem\nitems = {}\nclass investigationSpider(scrapy.Spider):\n name = 'times'\n allowed_domains = ['nytimes.com']\n custom_settings = {\n \"DOWNLOAD_DELAY\": 1,\n \"CONCURRENT_REQUESTS_PER_DOMAIN\":4,\n \"BOT_NAME\":'inv',\n \"DEPTH_LIMIT\": 10,\n }\n def start_requests(self):\n urls = ['https://www.nytimes.com']\n for url in urls:\n yield scrapy.Request(url=url, callback = self.frontpage)\n def frontpage (self,response):\n for headline in response.xpath('//h2[@class=\"story-heading\"]'):\n try:\n title = headline.xpath('./a/text()').extract()[0]#.strip().replace(u'\\u2018','').replace(u'\\u2019','')\n link = headline.xpath('./a/@href').extract()[0].strip()\n items[title] = link\n except:\n continue\n if link:\n yield scrapy.Request(url=link, callback = self.read_story)\n for section in response.xpath('//ul[@class=\"mini-navigation-menu\"]//a/@href').extract():\n yield scrapy.Request(url=section, callback = self.section)\n def read_story(self, response):\n storyItem = NewsItem()\n storyItem['url'] = response.request.url\n storyItem['title'] = response.xpath('//h1/text()').extract()[0]\n story = \"\"\n try:\n date = response.xpath('//meta[@itemprop=\"datePublished\"]/@content').extract()[0]\n# date = response.xpath('//time[@class=\"dateline\"]/text()')[0].extract()\n storyItem['date'] = date\n for i in response.xpath('//body//article[@id=\"story\"]//p[@class=\"story-body-text story-content\"]'):\n for j in i.xpath('.//text()').extract():\n stringpart = j.strip()#.replace('\\u2019',\"'\").replace('\\u201d',\"'\").replace('\\u201c',\"'\")\n story = ''.join([story,' ', stringpart])\n storyItem['text'] = story\n except:\n storyItem['text'] = ''\n pass\n if len(storyItem['text']) > 1000:\n yield storyItem\n\n for link in response.xpath('//article[@id=\"story\"]//a/@href').extract():\n if (link.find('#') == -1) & (link.find('index.html') == -1) & (link.find('/by/')==-1) & (link.find('news-event') == -1) & (link.find('newsletter') == -1): \n yield scrapy.Request(url=link, callback = self.read_story) \n \n def section(self, response):\n if response.xpath('//div[@class=\"abColumn\"]'):\n for i in response.xpath('//div[contains(@class, \"columnGroup\")]/div[contains(@class, \"story\") or contains(@class, \"ledeStory\")]'):\n link = i.xpath('.//a/@href').extract()[0]\n title = i.xpath('.//a/text()').extract()[-1]\n yield scrapy.Request(url=link, callback = self.read_story)\n elif response.xpath('//ol[@class=\"story-menu\"]'):\n for i in response.xpath('//article'):\n link = i.xpath('.//a/@href').extract()[0]\n title = i.xpath('.//a/text()').extract()[-1]\n if title.strip() == '':\n title = i.xpath('.//h2/text()').extract()[-1]\n yield scrapy.Request(url=link, callback = self.read_story)\n","sub_path":"news_clustering_poc/nytimes_scraping/news/news/spiders/nytspider.py","file_name":"nytspider.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"450671950","text":"# -*- coding: utf-8 -*-\nfrom SPARQLWrapper import JSON, SPARQLWrapper\nimport dbpediaknowledge\nimport json\nimport sys\n\nargs = sys.argv\nword = args[1]\n\nsparql = SPARQLWrapper('http://ja.dbpedia.org/sparql')\nsparql.setReturnFormat(JSON)\n\nsparql = SPARQLWrapper(endpoint='http://ja.dbpedia.org/sparql', returnFormat='json')\nsparql.setQuery(\"\"\"\n PREFIX rdfs: \n select distinct ?label where {{\n ?a rdfs:label ?label.\n FILTER (regex (?label, \"^{0} \") || (regex (?label, \"^{0}\") && regex (?label, \"{0}$\")))\n }}LIMIT 5\n \"\"\".format(word))\nresults = sparql.query().convert()\n\nresults_3 = json.dumps(results[\"results\"][\"bindings\"],ensure_ascii=False)\nresults_4 = results_3.replace('{\"label\": {\"type\": \"literal\", \"xml:lang\": \"ja\", \"value\": \"', '')\nresults_5 = results_4.replace('\"}}', '')\nresults_7 = results_5.replace('[', '')\nresults_8 = results_7.replace(']', '')# ここまで文字削除\nresults_6 = results_8.split(', ')\n\nfor item in results_6:\n print(item)","sub_path":"test10.py","file_name":"test10.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"652779715","text":"import json\nimport serial\n\ns = serial.Serial('/dev/ttyACM0', 9600)\n\nwhile True:\n line = s.readline().decode('utf-8')\n\n try:\n data = json.loads(line)\n print(data)\n except json.decoder.JSONDecodeError:\n print('Invalid JSON received. Waiting for next message.')\n","sub_path":"input-relay/receiver.py","file_name":"receiver.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"135419667","text":"# -*- encoding=utf8 -*-\n__author__ = \"Lee.li\"\n\"\"\"\n命名规则:\n1.模块尽量使用小写命名,首字母保持小写,尽量不要用下划线(除非多个单词,且数量不多的情况)\n2.类名使用驼峰(CamelCase)命名风格,首字母大写,私有类可用一个下划线开头\n3.函数名一律小写,如有多个单词,用下划线隔开,私有函数在函数前加一个下划线_\n4.变量名首字母尽量小写, 如有多个单词,用下划线隔开,后续字母大写\n5.常量采用全大写,如有多个单词,使用下划线隔开\n\"\"\"\nimport configparser # 配置文件分析器\nimport os\n\ndef analysis_config(path,section):\n \"\"\"\n 读取配置文件并且获得的值返回一个列表,对单个的value,到时候可以用[0]来取到\n :param path: 路径,要写绝对路径 D:/scriprt/auto_test.air/Common/config.ini\n :param section: 你需要在配置文件中查找的值\n :return:\n \"\"\"\n config = configparser.ConfigParser() # 实现插值的配置器\n config.read(path) # 读取和分析文件名或可读取的文件名\n result = config.get(\"config\",section) # configf是配置文件中的打标签,需要根据配置文件中填写\n result_list = result.split(\",\") # 用逗号分隔,存储在列表中\n return result_list\n\ndef get_script_list(file_Path):\n \"\"\"\n 这是一个处理TestCase目录下的模块脚本文件,获取文件名称\n :param file_Path: 文件路径,就是TestCase的路径\n :return: 返回值是是TestCase下所有需要测试的用例脚本\n \"\"\"\n dir_List = os.listdir(file_Path) # 返回包含目录中文件名的列表\n script_List = [] # 定义一个空列表,用来存储脚本模块\n for i in range(len(dir_List)):\n mode_Name = dir_List[i].split(\".\") # 把模块文件分割成[\"name\",\"py\"]的形式赋值给mode_Name\n if mode_Name[0] != \"__init__\" and mode_Name[0] != \"__pycache__\": # 去除构造函数和运行文件\n if mode_Name[1].lower() == \"py\": # 获取所需要的模块py文件\n script_List.append(mode_Name[0]) # 把满足上两个条件的的模块名称添加给script_List\n return script_List\n","sub_path":"multi_processframe/Tools/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"167247851","text":"from __future__ import annotations\n\nfrom ruamel.yaml import YAML\n\n\nclass Config:\n def __init__(self, path: Path):\n self.path = path\n print(f'Config path: {self.path.absolute()}')\n\n self.data = None\n self.yaml = YAML()\n\n def load(self):\n if self.path.exists():\n with open(self.path, 'r') as file:\n self.data = self.yaml.load(file)\n return self.data\n\n def save(self):\n with open(self.path, 'w') as file:\n self.yaml.dump(self.data, file)\n","sub_path":"vision-core/src/bsmu/vision/core/config/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"285748047","text":"'''\r\n@Author: your name\r\n@Date: 2020-04-01 17:17:50\r\n@LastEditTime: 2020-04-01 21:59:47\r\n@LastEditors: Please set LastEditors\r\n@Description: In User Settings Edit\r\n@FilePath: \\疫情可视化\\data\\risk.py\r\n'''\r\nimport json\r\nimport os.path as p\r\n\r\n\r\npath = p.join(p.dirname(__file__), \"risk.json\")\r\nwith open(path, mode='r', encoding='utf8') as file:\r\n stream = file.read()\r\n dataset = json.loads(stream)\r\n# Tdata = []\r\n# Time = []\r\n# for time in dataset:\r\n# Time.append(time)\r\n# tt = []\r\n# for city in dataset[time]:\r\n# t = []\r\n# t.append(city)\r\n# t.append((dataset[time][city][\"province_confirmedCount\"] - dataset[time][city][\"province_curedCount\"]))\r\n# tt.append(t)\r\n# Tdata.append(tt)\r\n# # print(Time)\r\n# # print(Tdata)\r\n# data = {}\r\n# for i in range(len(Time)):\r\n# data[Time[i]] = []\r\n# for city in Tdata[i]:\r\n# t = []\r\n# t.append(city[0])\r\n# t.append(city[1])\r\n# if i >= len(Time) -2:\r\n# t.append(0)\r\n# else :\r\n# v1 , v2 , flag = 0 , 0 , 1\r\n# v1 = city[1]\r\n# for city1 in Tdata[i+2]:\r\n# if city1[0] == city[0] :\r\n# flag = 1\r\n# v2 = city1[1]\r\n# break\r\n# if flag == 0 or v1 == 0:\r\n# t.append(0)\r\n# else :\r\n# v = v2 / v1\r\n# x = v ** (1/3) - 1\r\n# t.append(x)\r\n# data[Time[i]].append(t)\r\nfinal = {}\r\nfor time in dataset:\r\n final[time] = []\r\n ymax = 0\r\n for a in dataset[time]:\r\n if ymax < a[2] :\r\n ymax = a[2]\r\n # k = 100\r\n # while True:\r\n # if (k*ymax<=160 and (k+100)*ymax>160) or (k*ymax>=-160 and (k+100)*ymax<-160) :\r\n # break\r\n # k = k + 100\r\n # if k == 1000:\r\n # break\r\n for a in dataset[time]:\r\n t = []\r\n t.append(a[0])\r\n t.append(a[1])\r\n t.append(a[2] * 300)\r\n final[time].append(t)\r\npath = p.join(p.dirname(__file__), \"risk.json\")\r\nwith open(path, mode='w', encoding='utf8') as file:\r\n json.dump(final,file,ensure_ascii=False)","sub_path":"疫情可视化/data/risk.py","file_name":"risk.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"28168459","text":"#!/usr/bin python\n# -*- coding:utf-8 -*-\n\nimport os\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nimport json\nfrom collections import Counter\n\ndef readListFromTxt(filePath):\n infoList = []\n if os.path.exists(filePath):\n f = open(filePath,'r',encoding='utf-8')\n while True:\n line = f.readline()\n if line:\n temp = line.strip()\n infoList.append(temp)\n else:\n break\n f.close()\n return infoList\n\ndef washData(string):\n \"\"\"\n 1 去除“<>”内容\n 2 去除空格\n \"\"\"\n if string:\n temp = re.sub('<.*?>',' ',string)\n string = temp.replace('\\r','').replace('\\n','').replace('\\t','')\n return string\n\ndef getYearList(spanlistsoup):\n resultList = []\n for spansoup in spanlistsoup:\n resultList.append(spansoup.string.strip())\n return resultList\n\ndef getNumList(alistsoup):\n resultList = []\n for asoup in alistsoup:\n if asoup.find('span'):\n resultList.append(asoup.find('span').string.strip())\n return resultList\n\ndef getInfoPartOne(soup):\n name = ''\n intro = ''\n tags = ''\n hdx = ''\n idx = ''\n chatTupleList = []\n\n if soup.find('div',id='gs_bdy').find('div',id='gs_bdy_ccl',role='main'):\n bodysoup = soup.find('div', id='gs_bdy').find('div', id='gs_bdy_ccl', role='main')\n # name,intro,tags\n if bodysoup.find('div',class_='gsc_lcl',role='main',id='gsc_prf_w')\\\n .find('div',id='gsc_prf').find('div',id='gsc_prf_i'):\n nameIntroTagsSoup = bodysoup.find('div', class_='gsc_lcl', role='main', id='gsc_prf_w') \\\n .find('div', id='gsc_prf').find('div', id='gsc_prf_i')\n if nameIntroTagsSoup.find('div',id='gsc_prf_in'):\n name = nameIntroTagsSoup.find('div', id='gsc_prf_in').string.strip()\n if nameIntroTagsSoup.find('div',class_='gsc_prf_il'):\n introsoup = nameIntroTagsSoup.find('div', class_='gsc_prf_il')\n intro = washData(str(introsoup))\n if nameIntroTagsSoup.find('div',class_='gsc_prf_il',id='gsc_prf_int'):\n tagsoup = nameIntroTagsSoup.find('div', class_='gsc_prf_il', id='gsc_prf_int')\n tags = washData(str(tagsoup))\n # h,i\n if bodysoup.find('div',class_='gsc_rsb',role='navigation').\\\n find('div',class_='gsc_rsb_s gsc_prf_pnl',id='gsc_rsb_cit',\\\n role='region').find('table',id='gsc_rsb_st'):\n hisoup = bodysoup.find('div', class_='gsc_rsb', role='navigation'). \\\n find('div', class_='gsc_rsb_s gsc_prf_pnl', id='gsc_rsb_cit', \\\n role='region').find('table', id='gsc_rsb_st').find('tbody')\n if hisoup.find_all('tr') and len(hisoup.find_all('tr'))==3:\n hsoup = hisoup.find_all('tr')[1]\n if hsoup.find_all('td') and len(hsoup.find_all('td'))==3:\n hdx = hsoup.find_all('td')[1].string.strip()\n isoup = hisoup.find_all('tr')[2]\n if isoup.find_all('td') and len(isoup.find_all('td'))==3:\n idx = isoup.find_all('td')[1].string.strip()\n # print(hdx,idx)\n # chat\n if bodysoup.find('div', class_='gsc_rsb', role='navigation'). \\\n find('div', class_='gsc_rsb_s gsc_prf_pnl', id='gsc_rsb_cit', \\\n role='region').find('div',class_='gsc_g_hist_wrp',dir='rtl').\\\n find('div',class_='gsc_md_hist_b'):\n chatsoup = bodysoup.find('div', class_='gsc_rsb', role='navigation'). \\\n find('div', class_='gsc_rsb_s gsc_prf_pnl', id='gsc_rsb_cit', \\\n role='region').find('div', class_='gsc_g_hist_wrp', dir='rtl'). \\\n find('div', class_='gsc_md_hist_b')\n if chatsoup.find_all('span') and chatsoup.find_all('a'):\n # \\ and len(chatsoup.find_all('span'))==len(chatsoup.find_all('a')):\n spanlistsoup = chatsoup.find_all('span')\n yearList = getYearList(spanlistsoup)\n alistsoup = chatsoup.find_all('a')\n numList = getNumList(alistsoup)\n if len(yearList)/2 == len(numList):\n yearList = yearList[:int(len(yearList)/2)]\n # print(len(yearList),yearList)\n # print(len(numList),numList)\n if len(yearList) == len(numList):\n chatTupleList = list(zip(yearList,numList))\n\n return name,intro,tags,hdx,idx,chatTupleList\n\ndef getPaperNumMap(quotesoup):\n resultList = []\n if quotesoup.find_all('span',class_='gsc_a_h gsc_a_hc gs_ibl'):\n allspansoup = quotesoup.find_all('span', class_='gsc_a_h gsc_a_hc gs_ibl')\n for spansoup in allspansoup:\n if spansoup.string:\n resultList.append(spansoup.string.strip())\n return dict(Counter(resultList))\n\nif __name__ == '__main__':\n # urlhead = 'https://scholar.google.com.hk'\n urlhead = 'https://scholar.google.com'\n headers = {'content-type': 'application/x-www-form-urlencoded',\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',\n 'x-chrome-uma-enabled': '1',\n 'x-client-data': 'CKi1yQEIhrbJAQijtskBCMG2yQEI+pzKAQipncoB'}\n\n # fnameList = os.listdir('./data/targetName/')\n fnameList = ['economics.txt']\n outputDir = './data/output'\n for fname in fnameList:\n print('---------file name:',fname)\n fpath = os.path.join('./data/targetName',fname)\n targetNameList = readListFromTxt(fpath)\n # fw = open(os.path.join(outputDir,fname),'aw',encoding='utf-8')\n\n # print(len(targetNameList))\n # print(targetNameList)\n # searchAuthorLeft = 'https://scholar.google.com.hk/citations?view_op=search_authors&mauthors='\n searchAuthorLeft = 'https://scholar.google.com/citations?view_op=search_authors&mauthors='\n # searchAuthorRight = '&hl=zh-CN&oi=ao'\n searchAuthorRight = '&hl=en&oi=ao'\n for i in range(len(targetNameList)):\n targetName = targetNameList[i]\n print('file name:',fname,i+1,'【'+ targetName +'】')\n\n searchAuthorMiddle = '+'.join(targetName.strip().replace('\\'','%27').split(' '))\n searchUrl = searchAuthorLeft + searchAuthorMiddle + searchAuthorRight\n # searchUrl = 'https://scholar.google.com.hk/citations?view_op=search_authors&mauthors=Antonios+G.+Mikos&hl=zh-CN&oi=ao'\n # searchUrl = 'https://scholar.google.com.hk/citations?view_op=search_authors&mauthors=Craig+B.+Thompson&hl=zh-CN&oi=ao'\n # searchUrl = 'https://scholar.google.com/citations?view_op=search_authors&mauthors=Thomas+A.+Moore&hl=zh-CN&oi=ao'\n # print(searchUrl)\n\n r = requests.get(url=searchUrl,headers=headers)\n html = r.content.decode('utf-8')\n soup = BeautifulSoup(html,'lxml')\n # print(soup)\n if soup.find('div',id='gs_top').find('div',id='gs_bdy'):\n onesoup = soup.find('div',id='gs_top').find('div',id='gs_bdy')\n if onesoup.find('div',id='gs_bdy_ccl',role='main').find('div',id='gsc_sa_ccl'):\n twosoup = onesoup.find('div',id='gs_bdy_ccl',role='main').find('div',id='gsc_sa_ccl')\n if twosoup.find('div',class_='gsc_1usr gs_scl'):\n threesoup = twosoup.find('div', class_='gsc_1usr gs_scl')\n # print(threesoup)\n catched_name = ''\n if threesoup.find('div',class_='gsc_oai').find('h3',class_='gsc_oai_name').find('a'):\n urltail = threesoup.find('div', class_='gsc_oai').\\\n find('h3', class_='gsc_oai_name').find('a').get('href')\n if threesoup.find('div', class_='gsc_oai'). find('h3', class_='gsc_oai_name').find('a').find('span'):\n catched_name = threesoup.find('div', class_='gsc_oai'). \\\n find('h3', class_='gsc_oai_name').find('a').find('span').string\n # print(urltail)\n # print(catched_name)\n\n # 获取到person homepage url link(个人主页)\n personUrl = urlhead + urltail #https://scholar.google.com/citations?user=wVOesBEAAAAJ&hl=zh-CN\n print('个人主页:',personUrl)\n session = requests.Session()\n\n # 获取第一部分信息\n reget = session.get(url=personUrl, headers=headers)\n html = reget.content.decode('utf-8')\n soup = BeautifulSoup(html,'lxml')\n name, intro, tags, hdx, idx, chatTupleList = getInfoPartOne(soup)\n # print(name,intro,tags,hdx,idx)\n # print(chatTupleList)\n\n # 获取第二部分信息\n quoteListStr = ''\n # 初始化数据\n cstartNum = 0\n data = {'cstart': cstartNum, 'pagesize': 100, 'json': 1}\n # url = 'https://scholar.google.com/citations?user=WXQ7lBQAAAAJ&hl=zh-CN&cstart=0&pagesize=100'\n postUrl = personUrl + '&cstart=' + str(cstartNum) + '&pagesize=100'\n # print(data)\n # print(postUrl)\n # 发送post请求\n repost = session.post(url=postUrl,data=data,headers=headers)\n rejson = json.loads(repost.text)\n while repost.status_code==200 and rejson['B']:\n quoteitemsoup = rejson['B']\n # print(quoteitemsoup)\n quoteListStr = quoteListStr + quoteitemsoup\n cstartNum = cstartNum + 100\n data['cstart'] = cstartNum\n postUrl = personUrl + '&cstart=' + str(cstartNum) + '&pagesize=100'\n repost = session.post(url=postUrl, data=data, headers=headers)\n rejson = json.loads(repost.text)\n quotesoup = BeautifulSoup(quoteListStr)\n # print(type(quotesoup))\n # print(quotesoup)\n paperNumMap = getPaperNumMap(quotesoup)\n # print(paperNumMap)\n\n # final 整合数据\n # paperNum = ''\n # for k,v in paperNumMap.items():\n # paperNum = paperNum + str(k) + ':' + str(v) + ' '\n # chatStr = ''\n # for chatTuple in chatTupleList:\n # chatStr = chatStr + chatTuple[0] + ':' + chatTuple[1] + ' '\n\n # outputLine = name.replace(',',',') + ',' + str(personUrl) + ',' + intro.replace(',',',') + ',' \\\n # + tags.replace(',',',') + ',' + hdx + ',' \\\n # + idx + ',' + chatStr.strip()\\\n # + ',' + paperNum.strip()\n # print(outputLine)\n # fw = open(os.path.join(outputDir, fname), 'a', encoding='utf-8')\n # fw.write(outputLine + '\\n')\n # fw.close()\n\n # 为了统一数据格式,这里缓存原始数据\n div = '#DIV#'\n outputLine = 'target_name:' + targetName + div +\\\n 'catched_name:' + catched_name + div + \\\n 'person_url:' + personUrl + div + \\\n 'name:' + name + div + \\\n 'intro:' + intro + div + \\\n 'tags:' + tags + div + \\\n 'hdx:' + str(hdx) + div + \\\n 'idx:' + str(idx) + div + \\\n 'chat_tuple_list:' + str(chatTupleList) + div + \\\n 'year_result_list:' + str(paperNumMap) + div\n print(outputLine)\n\n fw = open(os.path.join(outputDir, fname), 'a', encoding='utf-8')\n fw.write(outputLine + '\\n')\n fw.close()\n","sub_path":"spiderAcademicStatistics/spider_google_scholar_2.py","file_name":"spider_google_scholar_2.py","file_ext":"py","file_size_in_byte":13013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"260231953","text":"import numpy as np\nimport random, math\nimport matplotlib.pyplot as plt\nfrom visualization import plane_visualization\n\ndef position_initialization(num_bodies, g_distance, radius):\n x, y, z = [], [], []\n f = 1.15\n phi = 2*math.pi*random.random()\n theta = math.pi*random.random()\n\n g1_coord = [0.5*g_distance*math.cos(phi) * np.sin(theta),\n 0.5*g_distance*math.sin(phi)*np.sin(theta),\n 0.5*g_distance*math.cos(theta)]\n\n g2_coord = [-g1_coord[0], -g1_coord[1], -g1_coord[2]]\n\n x = np.random.normal(g1_coord[0], radius[0]/f, num_bodies[0])\n y = np.random.normal(g1_coord[1], radius[0]/f, num_bodies[0])\n z = np.random.normal(g1_coord[2], radius[0]/f, num_bodies[0])\n\n x = np.concatenate((x,np.random.normal(g2_coord[0], radius[1]/f, num_bodies[1])))\n y = np.concatenate((y,np.random.normal(g2_coord[1], radius[1]/f, num_bodies[1])))\n z = np.concatenate((z,np.random.normal(g2_coord[2], radius[1]/f, num_bodies[1])))\n\n r_bodies = np.column_stack((x, y, z))\n r_galaxies = np.row_stack((g1_coord, g2_coord))\n\n return r_bodies, r_galaxies\n\ndef velocity_initialization(num_bodies, g1_mass, g2_mass, r_bodies, r_galaxies, R_1, R_2, epsilon):\n G = 1\n v_bodies = np.zeros((num_bodies[0]+num_bodies[1],3))\n v_galaxies = np.zeros((2,3))\n\n for i in range(num_bodies[0]):\n speed = np.sqrt(G*g1_mass/(R_1[i]+epsilon))\n v_bodies[i,:] = [-(r_bodies[i,1]-r_galaxies[0,1])/(R_1[i]+epsilon)*speed, (r_bodies[i,0]-r_galaxies[0,0])/(R_1[i]+epsilon)*speed, 0]\n\n for j in range(num_bodies[0], num_bodies[0]+num_bodies[1]):\n speed = np.sqrt(G*g2_mass/(R_2[j]+epsilon))\n v_bodies[j,:] = [-(r_bodies[j,1]-r_galaxies[1,1])/(R_2[j]+epsilon)*speed, (r_bodies[j,0]-r_galaxies[1,0])/(R_2[j]+epsilon)*speed, 0]\n\n v_galaxies[0,:] = [-1,0,0]\n v_galaxies[1,:] = [1,0,0]\n\n return v_bodies, v_galaxies\n","sub_path":"initialization.py","file_name":"initialization.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"521056763","text":"import requests\nfrom bs4 import BeautifulSoup\nimport multiprocessing\nimport pickle\nfrom tqdm import tqdm\n\ndef load_poem(link):\n poem_html = requests.get(link).text\n poem_soup = BeautifulSoup(poem_html, 'html.parser')\n poem_text = poem_soup.find('div', class_='poem-text').text.replace('\\r','')\n poem_sourse = poem_soup.find('div', class_='poemsource')\n if poem_sourse:\n poem_sourse = poem_sourse.text.replace('\\n','').replace('\\r','')\n else:\n poem_sourse = None\n name = poem_soup.find('h1', class_='poemtitle').text.replace('\\n','').replace('\\r','')\n\n return {\n 'name':name,\n 'source':poem_sourse,\n 'text':poem_text\n }\n\ndef load_data():\n html_doc=requests.get('http://rupoem.ru/love.aspx').text\n html_doc = html_doc.replace('\\r\\n',' ')\n\n soup = BeautifulSoup(html_doc, 'html.parser')\n author_urls = [ 'http://rupoem.ru'+link.get('href') for link in soup.find_all('a')[5:-47] ]\n\n links_to_poems = []\n for auth_url in tqdm(author_urls):\n auth_doc=requests.get(auth_url).text\n auth_soup = BeautifulSoup(auth_doc, 'html.parser')\n poetry_table = auth_soup.find_all('table', class_ = 'catlink')\n if poetry_table:\n for link in poetry_table[0].find_all('a'):\n links_to_poems.append('http://rupoem.ru'+link.get('href'))\n\n\n pool = multiprocessing.Pool()\n poems = pool.map(load_poem, links_to_poems)\n\n with open('data/poems.pkl', 'wb') as f:\n pickle.dump(poems, f)\n \n print(\"Words loaded: \", sum([ len(p['text'].split()) for p in poems ]) )\n \nif __name__ == \"__main__\": \n load_data()","sub_path":"loadrusspoetry.py","file_name":"loadrusspoetry.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"159187221","text":"import cv2\nimport pickle\nimport os\n\n\ndef read_feature_file(path):\n with open(path, \"rb\") as open_file:\n des = pickle.load(open_file)\n return des\n\ndef get_top_k_result(match_list=None, k=10):\n result = (sorted(match_list, key=lambda l: l[1], reverse=True))\n return result[:k]\n\n\ndef get_sift_des(img, sift):\n kp, des = sift.detectAndCompute(img, None)\n return des\n\nclass SIFTInterface():\n\n def __init__(self, query_img):\n self.SIMILARITY_THRESHOLD = 0.75\n self.sift_folder = \"dataset/sift_bin\"\n self.sift_list = os.listdir(self.sift_folder)\n self.sift = cv2.xfeature2d.SIFT_create()\n self.kp, self.des = get_sift_des(query_img, self.sift)\n\n def get_similar_img(self, des, sift_list):\n matches_list = []\n for idx, sift_file in enumerate(sift_list):\n print (\"{0} / {1}\".format(idx+1, len(sift_list)))\n sift_file_path = os.path.join(self.sift_folder, sift_file)\n features = read_feature_file(sift_file_path)\n\n if features == None:\n continue\n\n bf = cv2.BFMatcher()\n matches = bf.knnMatch(self.des, features, k=2)\n good = []\n for m, n in matches:\n if m.distance < self.SIMILARITY_THRESHOLD * n.distance:\n good.append([m])\n matches_list.append([sift_file, len(good)])\n\n del features, good\n if idx == 100:\n break\n\n result = get_top_k_result(match_list=matches_list, k=10)\n\n return result\n\n\n\n\n def read_feature_file(path):\n with open(path, \"rb\") as open_file:\n des = pickle.load(open_file)\n return des\n\n def get_top_k_result(match_list=None, k=10):\n result = (sorted(match_list, key=lambda l: l[1], reverse=True))\n return result[:k]\n\n def get_sift_des(img, sift):\n kp, des = sift.detectAndCompute(img, None)\n return des","sub_path":"StyleSim/Jikimi/py36_sift/get_sift_indexer.py","file_name":"get_sift_indexer.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"463105792","text":"import math\nfrom sqlalchemy import create_engine, MetaData\nfrom sqlalchemy.orm import scoped_session, sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\n\nSession = sessionmaker(autocommit=False, autoflush=True)\nsession = scoped_session(Session)\n\nconvention = {\n \"ix\": 'ix_%(column_0_label)s',\n \"uq\": \"uq_%(table_name)s_%(column_0_name)s\",\n \"ck\": \"ck_%(table_name)s_%(column_0_name)s\",\n \"fk\": \"fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s\",\n \"pk\": \"pk_%(table_name)s\"\n}\n\nsql_alchemy_metadata = MetaData(naming_convention=convention)\n\nBase = declarative_base(metadata=sql_alchemy_metadata)\nBase.query = session.query_property()\n\n\ndef init_db(db_uri):\n engine = create_engine(db_uri, pool_recycle=3600)\n Session.configure(bind=engine)\n Base.metadata.bind = engine\n Base.metadata.create_all(bind=engine)\n\n\nclass db():\n @staticmethod\n def drop_all():\n Base.metadata.drop_all(Base.metadata.bind)\n\n @staticmethod\n def create_all():\n Base.metadata.create_all(Base.metadata.bind)\n\n session = session\n\n\nclass Page():\n def __init__(self, items, page: int, page_size: int, total: int):\n self.items = items\n self.prev_page = None\n self.next_page = None\n self.has_prev = page > 1\n if self.has_prev:\n self.prev_page = page - 1\n prev_items = (page - 1) * page_size\n self.has_next = prev_items + len(items) < total\n if self.has_next:\n self.next_page = page + 1\n self.total = total\n self.pages = int(math.ceil(total / float(page_size)))\n\n\ndef paginate(query, page: int, page_size: int = 25):\n if page <= 0:\n raise AttributeError('page must be >= 1')\n if page_size <= 0:\n raise AttributeError('page_size must be >= 1')\n\n items = query.limit(page_size).offset((page - 1) * page_size).all()\n total = query.order_by(None).count()\n\n return Page(items, page, page_size, total)\n","sub_path":"app/database/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"637521515","text":"\"\"\"new\n\nRevision ID: 0c1502e5ff59\nRevises: 492a3521b7c2\nCreate Date: 2020-07-02 22:38:17.254112\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = '0c1502e5ff59'\ndown_revision = '492a3521b7c2'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('logs', sa.Column('user_id', sa.Integer(), nullable=True))\n op.drop_column('logs', 'result')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('logs', sa.Column('result', mysql.VARCHAR(length=1024), nullable=True))\n op.drop_column('logs', 'user_id')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/0c1502e5ff59_new.py","file_name":"0c1502e5ff59_new.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"130753019","text":"from django.shortcuts import render\nimport requests\n\n# Create your views here.\ndef index(request):\n try:\n \n S = requests.Session()\n \n URL = \"https://zh.wikipedia.org/w/api.php\"\n txtQuery = request.GET['txtQuery']\n \n PARAMS = {\n \"action\": \"parse\",\n \"page\": txtQuery,\n \"prop\": \"text\",\n \"format\": \"json\"\n }\n \n response = S.get(url=URL, params=PARAMS)\n wikiData = response.json()\n '''wikiFile = open('wikiFile', 'rt')\n wikiData = wikiFile.read()\n wikiFile.close()'''\n \n except:\n wikiData = \"\" \n \n return render(request, 'index.html', locals())","sub_path":"mainsite/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"644566555","text":"\"\"\"Map the columns btw gtfs and data base.\"\"\"\r\nimport logging\r\n\r\nfrom mixer.glogger import logger\r\nfrom utilities.decorator import logged\r\nimport mixer.gtfs.mapper.settings as SETTINGS\r\n\r\n\r\nclass Model(object):\r\n \"\"\"Change the name of the dataframe columns.\"\"\"\r\n\r\n def __init__(self, dict_df_normalized):\r\n \"\"\"Constructor.\"\"\"\r\n self.dict_mapper = SETTINGS.dict_mapper\r\n self.dict_df_normalized = dict_df_normalized\r\n\r\n def remap_df(self, table):\r\n \"\"\"Remap the df columns to db columns.\"\"\"\r\n msg = \"Remap df {}\".format(table)\r\n logger.log(logging.INFO, msg)\r\n df = self.dict_df_normalized[table]\r\n nt = self.dict_mapper[table]\r\n df = df.rename(columns=nt.mapping)\r\n\r\n return df[nt.sub_cols]\r\n\r\n @logged(level=logging.INFO, name=logger)\r\n def main(self):\r\n \"\"\"Map each df columns.\"\"\"\r\n dict_df_mapped = dict()\r\n dict_df_mapped[\"Gtfs\"] = self.remap_df(\"Gtfs\")\r\n dict_df_mapped[\"Agency\"] = self.remap_df(\"Agency\")\r\n dict_df_mapped[\"Calendar\"] = self.remap_df(\"Calendar\")\r\n dict_df_mapped[\"CalendarDate\"] = self.remap_df(\"CalendarDate\")\r\n dict_df_mapped[\"Route\"] = self.remap_df(\"Route\")\r\n dict_df_mapped[\"Stop\"] = self.remap_df(\"Stop\")\r\n dict_df_mapped[\"Trip\"] = self.remap_df(\"Trip\")\r\n dict_df_mapped[\"StopTime\"] = self.remap_df(\"StopTime\")\r\n dict_df_mapped[\"Shape\"] = self.remap_df(\"Shape\")\r\n dict_df_mapped[\"TripToDate\"] = self.remap_df(\"TripToDate\")\r\n\r\n return dict_df_mapped\r\n","sub_path":"mixer/gtfs/mapper/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"123519686","text":"from core.controllers.planes.planes_controller import PlanesController\nfrom core.models.planes.plane import Plane\nfrom utils.context import Context, Parameter\nfrom utils.reader import read_txt\nfrom utils.writer import write_2_json\n\n\ndef planes_2_json():\n planes = read_txt('{0}/planes_sample.txt'.format(Context.get(Parameter.BASE_RESOURCE_PATH)))\n planes_list = []\n for line in planes:\n if line:\n planes_list.append(parse_line_from_planes_source(line).__dict__)\n write_2_json(planes_list, 'resources/planes.json')\n\n\ndef parse_line_from_planes_source(line):\n parts = line.replace('\\\"', '').split(',')\n manufacturer = parts[1].strip()\n model = parts[2].strip()\n capacity = parts[8].strip()\n speed = parts[10].strip()\n return Plane(manufacturer, model, capacity, speed)\n\n\ndef planes_2_db():\n planes = read_txt('{0}/ACFTREF.txt'.format(Context.get(Parameter.BASE_RESOURCE_PATH)))\n plane_ctrl = PlanesController()\n for line in planes:\n if line:\n plane = parse_line_from_planes_source(line)\n plane_ctrl.create(plane)\n\n\nplanes_2_db()\n# write_2_json()\n# planes_2_json()\n","sub_path":"core/processor.py","file_name":"processor.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"89377704","text":"import numpy as np\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction.text import TfidfVectorizer, HashingVectorizer, \\\n CountVectorizer\nfrom sklearn.model_selection import cross_val_score, KFold\nfrom sklearn import metrics\nfrom scipy.stats import sem # standard error of the mean\nimport warnings\nwarnings.simplefilter(\"once\")\n\ndef evaluate_cross_validation(clf, X, y, K):\n # Create a k-fold cross validation iterator of k=5 folds\n kf = KFold(n_splits=K, shuffle=True, random_state=0)\n cv = kf.split(X, y)\n # By default the score used is the one returned by score method of the\n # estimator (accuracy)\n scores = cross_val_score(clf, X, y, cv=cv)\n print(scores)\n print(\"Mean score: {0:.3f} (+/- {1:.3f})\".format(np.mean(scores),\n sem(scores)))\n\nnews = fetch_20newsgroups()\n\nSPLIT_PERC = 0.75\nsplit_size = int(len(news.data) * SPLIT_PERC)\nX_train = news.data[:split_size]\nX_test = news.data[split_size:]\ny_train = news.target[:split_size]\ny_test = news.target[split_size:]\n\n# Creating 3 different classification pipelines\n\n# Countvectorizer creates a dictionary of words from the text corpus. Then each\n# instance is converted to a vector of numeric features where each element will\n# be the count of the number of times a particular word appears in the document.\nclf_1 = Pipeline([\n ('vect', CountVectorizer()),\n ('clf', MultinomialNB()),\n])\n\n# HashingVectorizer implements a hashing function that maps tokens into feature\n# indexes, and then computes the count as in CountVectorizer.\nclf_2 = Pipeline([\n ('vect', HashingVectorizer(non_negative=True)),\n ('clf', MultinomialNB()),\n])\n\n# TfidfVectorizer uses a calculation called Term Frequency Inverse Document\n# Frequency (TF-IDF). This is a statistic for measuring the importance of a\n# word in a document or corpus. Intuitively, it looks for words that are more\n# frequent in the current document, compared with their frequency in the whole\n# corpus of documents. This is a way to normalize the results and avoid words\n# that are too frequent, and thus not useful to characterize the instances.\nclf_3 = Pipeline([\n ('vect', TfidfVectorizer()),\n ('clf', MultinomialNB()),\n])\n\n# clfs = [clf_1, clf_2, clf_3]\n#\n# for clf in clfs:\n# evaluate_cross_validation(clf, X_train, y_train, 5)\n\n# Trying to improve results by trying to parse the text documents into tokens\n# with a different regular expression.\nclf_4 = Pipeline([\n ('vect', TfidfVectorizer(\n token_pattern=r\"\\b[a-z0-9_\\-\\.]+[a-z][a-z0-9_\\-\\.]+\\b\")),\n ('clf', MultinomialNB()),\n])\n\n# evaluate_cross_validation(clf_4, X_train, y_train, 5)\n\n# Another parameter that we can use is stop_words: this argument allows us to\n# pass a list of words we do not want to take into account, such as too frequent\n# words, or words we do not a priori expect to provide information about the\n# particular topic.\ndef get_stop_words():\n stopwordsfile = '/usr/local/share/nltk_data/corpora/stopwords/english'\n result = set()\n with open(stopwordsfile, 'r') as f:\n for line in f.readlines():\n result.add(line.strip())\n return result\n\nclf_5 = Pipeline([\n ('vect', TfidfVectorizer(\n stop_words=get_stop_words(),\n token_pattern=r\"\\b[a-z0-9_\\-\\.]+[a-z][a-z0-9_\\-\\.]+\\b\")),\n ('clf', MultinomialNB()),\n])\n\n# evaluate_cross_validation(clf_5, X_train, y_train, 5)\n\n# Let's keep this vectorizer and start looking at the MultinomialNB parameters.\n# The most important parameter is alpha, which is a smoothing parameter. Let's\n# set it to a lower value of 0.01 (defualt is 1.0).\n\nclf_6 = Pipeline([\n ('vect', TfidfVectorizer(\n stop_words=get_stop_words(),\n token_pattern=r\"\\b[a-z0-9_\\-\\.]+[a-z][a-z0-9_\\-\\.]+\\b\")),\n ('clf', MultinomialNB(alpha=0.1)),\n])\n\nevaluate_cross_validation(clf_6, X_train, y_train, 5)\n\n# Let's evaluate the performance on the test data\ndef train_and_evaluate(clf, X_train, X_test, y_train, y_test):\n clf.fit(X_train, y_train)\n print(\"Accuracy on training set:\")\n print(clf.score(X_train, y_train))\n print(\"Accuracy on testing set:\")\n print(clf.score(X_test, y_test))\n y_pred = clf.predict(X_test)\n\n print(\"Classification Report:\")\n print(metrics.classification_report(y_test, y_pred))\n print(\"Confusion matrix:\")\n print(metrics.confusion_matrix(y_test, y_pred))\n\ntrain_and_evaluate(clf_6, X_train, X_test, y_train, y_test)\n\nprint(\"\\nNumber of features:\",\n len(clf_6.named_steps['vect'].get_feature_names()))\nprint(\"\\nExamples of feature names:\")\nprint(clf_6.named_steps['vect'].get_feature_names()[20000:20100])\n","sub_path":"machine_learning/naive_bayes_classifier/naivebayes_newsgroups.py","file_name":"naivebayes_newsgroups.py","file_ext":"py","file_size_in_byte":4741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"465568863","text":"import networkx as nx\nimport matplotlib.pyplot as plt\n\n# i.e. central start node, k arms with m intermediate nodes on each arm between start and home\n# one home per arm\n# optimal solution: drop off everyone at start and let them walk?\n\n# rewritten, utilize formula: locations = 1 + homes * (intermediates + 1)\ndef snowflake_maker(locations, homes, intermediates):\n # initialize starting values\n G = nx.Graph()\n\n # color map to distinguish homes from start from intermediate locations\n color_map = []\n\n # let start be numbered 0\n G.add_node(0)\n color_map.append('green')\n\n # let homes be numbered (1 -> # homes)\n G.add_nodes_from(range(1, homes + 1))\n color_map += ['red' for i in range(1, homes + 1)]\n\n # let intermediate nodes be numbered (# homes + 1 -> # locations)\n G.add_nodes_from(range(homes + 1, locations))\n color_map += ['blue' for i in range(homes + 1, locations)]\n\n # add edges\n for i in range(1, homes + 1):\n v = homes + i\n G.add_edge(0, v)\n\n for j in range(1, intermediates):\n for i in range(1, homes + 1):\n u = j * homes + i\n v = ((j + 1) * homes) + i\n G.add_edge(u, v)\n\n for j in range(1, homes + 1):\n u = (intermediates * homes) + j\n G.add_edge(u, j)\n\n # draw and return graph\n plot_graph(G, color_map)\n return G\n\n# plot the graph\ndef plot_graph(G, color_map):\n nx.draw(G, node_color=color_map, with_labels=True, font_weight='bold')\n labels = nx.get_edge_attributes(G, 'weight')\n nx.draw_networkx_edge_labels(G, pos=nx.spring_layout(G), edge_labels=labels)\n plt.show()\n\n","sub_path":"snowflake_graph_maker.py","file_name":"snowflake_graph_maker.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"255776478","text":"# Example of boxenplot using tips dataset\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfont_param = {'size': 12, 'fontweight': 'semibold',\n 'family': 'serif', 'style': 'normal'}\n\nsns.set(style=\"whitegrid\", color_codes=True)\n\n# Load the example dataset\ntips = pd.read_csv(\"tips.csv\")\n\n\n# Draw a boxen plot of total bill vs day\nx = \"day\"\ny = \"total_bill\"\nhue = \"smoker\"\norder=['Thur', 'Fri', 'Sat', 'Sun']\ndata = tips\n\ng = sns.catplot(x=x, y=y, data=data, kind='boxen', hue=hue, order=order)\ng.despine(left=True)\nplt.title('boxen plot of total bill vs day', font_param, pad=0.4)\n\ng.savefig('boxen_tips.pdf')\nplt.show()\n\n","sub_path":"seaborn/catplot/catplot_boxen.py","file_name":"catplot_boxen.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"173377249","text":"#!/usr/bin/env python\n\n# ASuMa, Mar 2018\n# Read parse data in MST-parser format, from reference and test files\n# and evaluate the accuracy of the test parses.\n# See main() documentation below for usage details\n\nimport platform\nimport getopt, sys\n\ndef version():\n \"\"\"\n Prints Python version used\n \"\"\"\n print(\"Code writen for Python3.6.4. Using: %s\"%platform.python_version())\n\ndef Load_File(filename):\n \"\"\"\n Loads a data file\n \"\"\"\n with open(filename) as file:\n data = file.readlines()\n print(\"Finished loading\")\n\n # remove initial newlines, if any\n while data[0] == \"\\n\":\n data.pop(0)\n\n return data\n\ndef Get_Parses(data):\n \"\"\"\n Reads parses from data into two structures:\n - sentences: a dictionary of indexed split sentence strings\n - parses: a list of lists containing the split links of each parse\n [\n [[link1-parse1][link2-parse1] ... ]\n [[link1-parse2][link2-parse2] ... ]\n ...\n ]\n Each list is splitted into tokens using space.\n \"\"\"\n parses = []\n sentences = {}\n parse_num = 0\n new_flag = True\n for line in data:\n if line == \"\\n\":\n # get rid of sentences with no links\n if (not new_flag):\n if (len(sentences[parse_num]) == 0):\n sentences.pop(parse_num)\n parse_num -= 1\n #dictionary.pop(parse_num) # not needed, it will be re-written\n parse_num += 1\n new_flag = True\n continue\n if new_flag:\n sentences[parse_num] = line.split() # split ignores diff spacing between words\n new_flag = False\n parses.append([])\n continue\n parses[parse_num].append(line.split())\n\n return parses, sentences\n\ndef MakeSets(parse):\n \"\"\"\n Gets a list with links (without full sentence) and\n and makes sets for each link's ids\n \"\"\"\n link_sets = [{(link[0], link[1]), (link[2], link[3])} for link in parse]\n return link_sets\n\ndef Evaluate_Parses(test_parses, test_sentences, ref_parses, ref_sentences, verbose, ignore):\n \"\"\"\n Compares test_parses against ref_parses link by link\n counting errors\n \"\"\"\n evaluated_parses = 0 # reference parses not found in test\n total_links = 0 # in gold standard\n #extra_links = 0 # links present in test, but not in ref\n missing_links = 0 # links present in ref, but not in test\n ignored_links = 0 # ignored links, if ignore is active\n score = 0 # parse quality counter\n\n for ref_key, ref_sent in ref_sentences.items():\n # search if the current ref_sentence was wholly parsed in test_sentences\n test_key = [key for key, sentence in test_sentences.items() if sentence == ref_sent]\n if len(test_key) == 0:\n if verbose:\n print(\"Skipping sentence not found in test parses:\")\n print(ref_sent)\n continue\n test_sentences.pop(test_key[0]) # reduce the size of dict to search\n\n current_missing = 0\n current_evaluated = 0\n current_ignored = 0\n ref_sets = MakeSets(ref_parses[ref_key]) # using sets to ignore link directions\n test_sets = MakeSets(test_parses[test_key[0]])\n sent_length = str(len(ref_sent))\n\n # loop over every ref link and try to find it in test\n for ref_link in ref_sets:\n total_links += 1\n if ignore:\n if (('0', '###LEFT-WALL###') in ref_link) or ((sent_length, \".\") in ref_link):\n current_ignored += 1\n continue\n current_evaluated += 1\n if ref_link in test_sets:\n test_sets.remove(ref_link) \n else:\n current_missing += 1 # count links not contained in test\n\n # skip parse if there are no links left after ignore\n if current_ignored == len(ref_sets):\n continue\n\n evaluated_parses += 1\n\n if verbose:\n print(\"Sentence: {}\".format(\" \".join(ref_sent)))\n print(\"Missing links: {}\".format(current_missing))\n print(\"Extra links: {}\".format(len(test_sets)))\n\n ignored_links += current_ignored\n score += 1 - float(current_missing) / float(current_evaluated) # adds this parse's relative score\n #extra_links += len(test_sets) # count links not contained in reference\n missing_links += current_missing\n\n score /= evaluated_parses # averages the score\n print(\"\\nParse quality: {:.2%}\".format(score))\n print(\"A total of {} parses evaluated, {:.2%} of reference file\".format(evaluated_parses, float(evaluated_parses) / len(ref_sentences)))\n print(\"A total of {} links\".format(total_links))\n print(\"{:.2f} ignored links per sentence\".format(ignored_links / evaluated_parses))\n print(\"{:.2f} missing links per sentence\".format(missing_links / evaluated_parses))\n #print(\"{:.2f} extra links per sentence\\n\".format(extra_links / evaluated_parses))\n #print(\"A total of {} extra links\".format(extra_links))\n\ndef main(argv):\n \"\"\"\n Evaluates parses compared to given gold standard (GS).\n For each parse, loops through all links in GS and checks if those\n 2 word-instances are also connected in parse to evaluate.\n\n Parses must be in format:\n Sentence to evaluate\n # word1 # word2\n # word2 # word3\n ...\n\n Another sentence to evaluate\n # word1 # word2\n ...\n\n Usage: ./parse_evaluator.py -t -r [-v] [-i]\n\n testfile file with parses to evaluate\n goldfile file with reference (gold standard) parses\n -v verbose\n -i don't ignore LEFT-WALL and end-of-sentence dot, if any\n\n \"\"\"\n\n version()\n\n test_file = ''\n ref_file = ''\n verbose = False\n ignore_WALL = True\n\n try:\n opts, args = getopt.getopt(argv, \"ht:r:vi\", [\"test=\", \"reference=\", \"verbose\", \"ignore\"])\n except getopt.GetoptError:\n print(\"Usage: ./parse_evaluator.py -t -r [-v] [-i]\")\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print(\"Usage: ./parse_evaluator.py -t -r \")\n sys.exit()\n elif opt in (\"-t\", \"--test\"):\n test_file = arg\n elif opt in (\"-r\", \"--reference\"):\n ref_file = arg\n elif opt in (\"-v\", \"--verbose\"):\n verbose = True\n elif opt in (\"-i\", \"--ignore\"):\n ignore_WALL = False\n\n test_data = Load_File(test_file)\n test_parses, test_sentences = Get_Parses(test_data) \n ref_data = Load_File(ref_file)\n ref_parses, ref_sentences = Get_Parses(ref_data) \n Evaluate_Parses(test_parses, test_sentences, ref_parses, ref_sentences, verbose, ignore_WALL)\n\nif __name__ == '__main__':\n main(sys.argv[1:])","sub_path":"src/parse_evaluator/parse_evaluator.py","file_name":"parse_evaluator.py","file_ext":"py","file_size_in_byte":6981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"145440368","text":"\"\"\"Runs the streamlit app.\nCall this file in the terminal (from the `datathon-starter` dir)\nvia `streamlit run app.py`.\n\"\"\"\n\nimport pandas as pd\nimport streamlit as st\nimport missingno as msno\nimport time\n\nfrom pandas_profiling import ProfileReport\nfrom streamlit_pandas_profiling import st_profile_report\nfrom typing import List\nfrom typing import Mapping\n\nfrom prefect.client.client import Client\n\nfrom prefect.tasks.prefect.flow_run import StartFlowRun\nfrom prefect.engine.results.local_result import LocalResult\n\n\nR_DATASETS_URL = 'https://vincentarelbundock.github.io/Rdatasets'\nDATASET_URLS = {\n 'SmokeBan': f'{R_DATASETS_URL}/csv/AER/SmokeBan.csv',\n 'airquality': f'{R_DATASETS_URL}/csv/datasets/airquality.csv',\n 'TeachingRatings': f'{R_DATASETS_URL}/csv/AER/TeachingRatings.csv',\n} # A few example datasets to get you started\nDATASET_DOCS_URLS = {\n 'SmokeBan': f'{R_DATASETS_URL}/doc/AER/SmokeBan.html',\n 'airquality': f'{R_DATASETS_URL}/doc/datasets/airquality.html',\n 'TeachingRatings': f'{R_DATASETS_URL}/doc/AER/TeachingRatings.html',\n}\nDATASET_TITLES = {\n 'SmokeBan': 'Do Workplace Smoking Bans Reduce Smoking?',\n 'airquality': 'New York Air Quality Measurements',\n 'TeachingRatings': 'Impact of Beauty on Instructor\\'s Teaching Ratings',\n}\n\n\ndef create_prefect_flow_run(flow_name: str,\n project_name: str,\n task_refs: List,\n params: Mapping) -> str:\n \"\"\"Creates new prefect flow run for given flow id, parameters, task references\n and API server URL to send GraphQL requests to.\n Returns results value and state from a Prefect flow run.\n \"\"\"\n\n try:\n flow_run = StartFlowRun(flow_name=flow_name,\n project_name=project_name,\n parameters=params)\n flow_run_id = flow_run.run()\n client = Client()\n while True:\n time.sleep(10)\n flow_run_info = client.get_flow_run_info(flow_run_id)\n flow_state = flow_run_info.state\n task_runs_info = flow_run_info.task_runs\n if flow_state.is_finished():\n task_res_locs = {}\n for task_run in task_runs_info:\n # Return ref if ref string is a substring of any task slug\n ref = next((ref_str for ref_str in task_refs\n if ref_str in task_run.task_slug), None)\n if ref:\n task_id = task_run.id\n task_state = client.get_task_run_state(task_id)\n task_res_locs[ref] = task_state._result.location\n task_results = {}\n for ref, loc in task_res_locs.items():\n local_res = LocalResult()\n result = local_res.read(loc)\n task_results[ref] = result.value\n return task_results, flow_state, task_res_locs\n except ValueError as err:\n raise err\n\n\ndef sidebar():\n \"\"\"Write Streamlit commands here to display text and widgets in the sidebar.\n Replace the code within this function with your own\n interactive components and UI.\n \"\"\"\n\n st.sidebar.markdown(\n \"\"\"\n ## Datasets\n Three datasets from [R datasets]({}) are provided:\n - Do Workplace Smoking Bans Reduce Smoking\n - New York Air Quality Measurements\n - Impact of Beauty on Instructor's Teaching Ratings\n \"\"\".format(R_DATASETS_URL)\n )\n datasets = [None] + list(DATASET_URLS.keys())\n dataset_item = st.sidebar.selectbox('Which dataset are you interested in?',\n options=datasets)\n\n # Stop execution until a valid dataset is selected\n if not dataset_item:\n st.stop()\n url = DATASET_URLS[dataset_item]\n doc = DATASET_DOCS_URLS[dataset_item]\n # Read first row of csv file\n raw = pd.read_csv(url)\n data = raw.loc[:, ~raw.columns.str.contains('Unnamed')]\n columns = data.columns.tolist()\n\n st.sidebar.subheader('Model Specification')\n st.success(f'Successfully loaded dataset: {dataset_item}')\n st.info(f'URL found [here]({url}). Documentation found [here]({doc}).')\n\n cat_cols = st.sidebar.multiselect('Are there any categorical variables?',\n options=columns)\n transformed_cols = st.sidebar.multiselect('Select columns to transform',\n options=columns)\n transf = st.sidebar.selectbox('Log or arcsinh transform?',\n options=['log', 'arcsinh'])\n endog = st.sidebar.selectbox('Select an endogenous variable'\n ' (must be numeric)',\n options=[None] + columns)\n exog = [col for col in columns if col != endog]\n na_strategies = {\n 'Complete case': 'cc',\n 'Fill-in': 'fi',\n 'Fill-in with indicators': 'fii',\n 'Grand model': 'gm',\n 'MICE': 'mice',\n }\n na_strategy_name = st.sidebar.selectbox(\n 'How should missing values be dealt with?',\n options=[\n 'Complete case',\n 'Fill-in',\n 'Fill-in with indicators',\n 'Grand model',\n 'MICE'\n ])\n na_values_string = st.sidebar.text_input(\n 'Are there any text values that should be recognised as NA?'\n ' (separate values with a comma)',\n 'Missing, missing, not found'\n )\n na_values = [s.strip() for s in na_values_string.split(',')]\n na_strategy = na_strategies[na_strategy_name]\n return {'url': url,\n 'cat_cols': cat_cols,\n 'transformed_cols': transformed_cols,\n 'transf': transf,\n 'endog': endog,\n 'exog': exog,\n 'na_values': na_values,\n 'na_strategy': na_strategy,\n 'data': data,\n 'item': dataset_item}\n\n\ndef main():\n \"\"\"Write Streamlit commands here to display text and data in the app.\n Replace the code within this function with your own data workflow and UI.\n\n Streamlit API reference:\n https://docs.streamlit.io/en/stable/api.html\n \"\"\"\n\n # Configures the default settings\n st.set_page_config(page_title='datathon-starter',\n page_icon='🛠️',\n layout='wide')\n\n # Page title and header\n st.title('🛠️📊')\n st.title('Starter code for data applications')\n st.subheader('MIT License')\n st.markdown(\n \"\"\"\n ---\n 🙌 Build your own data app\n\n Modify pre-existing code and implement empty functions:\\n\n 1. Data tasks are found in `server/tasks.py`\n 2. Data workflows are found in `server/pipeline.py`\n 3. The Streamlit app's UI code is found in `app.py`\n ---\n 🚀 Try a quick example\n\n From the sidebar *(click on > if closed)*:\\n\n 1. Select a dataset\n 2. Select all categorical variables in the multiselect widget\n 3. Select an endogenous variable in the chosen dataset\n\n From the main UI below:\\n\n 4. Press the \"Run workflow\" button\n ---\n \"\"\"\n )\n\n # Example app\n params = sidebar() # Display sidebar in Streamlit app\n # Drop `data` and return its value\n data = params.pop('data')\n # Drop dataset `item` code and return its value\n item = params.pop('item')\n title = DATASET_TITLES[item]\n st.subheader(f'{title}')\n st.text('A random sample of 5 rows:')\n st.table(data.sample(5)) # Display random sample as a static table\n\n # Column container for buttons\n col1, col2, col3 = st.beta_columns(3)\n # Data profiling\n if col1.button('🔬 Data profiling report'):\n profile_report = ProfileReport(data, explorative=True)\n st_profile_report(profile_report)\n # Missing value analysis\n if col2.button('🔎 Missing value plots'):\n # Check if there are any missing values\n if pd.notna(data).all().all():\n st.warning('No missing values in dataset')\n else:\n fig1 = msno.matrix(data).get_figure()\n st.pyplot(fig1)\n fig2 = msno.heatmap(data).get_figure()\n st.pyplot(fig2)\n fig3 = msno.dendrogram(data).get_figure()\n st.pyplot(fig3)\n # Run data workflow\n if col3.button('✨ Run workflow!'):\n st.write('---')\n # Stop execution until a valid endogenous variable is selected\n if not(params.get('endog')):\n st.warning('Please select an endogenous variable')\n st.stop()\n flow_name = 'e2e_pipeline'\n project_name = 'datathon-starter'\n task_refs = ['wrangle_na']\n params = {'url': params.get('url'),\n 'sep': params.get('sep'),\n 'strategy': params.get('na_strategy')}\n results, state_msg = create_prefect_flow_run(flow_name,\n project_name,\n task_refs,\n params)\n # Check if all tasks were successfully executed\n if 'fail' in state_msg:\n # List of each state's (name, state message) in the workflow\n st.warning(state_msg)\n st.info('Please view the Flow logs on the Prefect Server\\'s'\n ' [UI](localhost:8080).')\n # If all tasks were successfully executed\n else:\n # Unpack results\n preprocessed_data, conf_int_chart = results\n # Success!\n st.balloons()\n st.success(state_msg)\n # Retrieve results from prefect flow run\n st.subheader('Pre-processed Data')\n st.dataframe(preprocessed_data)\n st.subheader('Regression Results')\n st.text('Dot and whisker plot of coefficients'\n ' and their confidence intervals:')\n # Plot regression coefficient's confidence intervals\n st.altair_chart(conf_int_chart, use_container_width=True)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"client/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":10167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"238874494","text":"import os\nimport sys\nimport yagmail\nimport json\nimport io\nimport random\nimport string\nfrom flask import request\nfrom datetime import date\nfrom PyPDF2 import PdfFileWriter, PdfFileReader\nfrom reportlab.pdfgen import canvas\nfrom reportlab.lib.pagesizes import letter\nfrom dotenv import load_dotenv\nfrom .models import db, User\n\n# Change current working directory to directory 'functions.py' is in.\nos.chdir(os.path.dirname(os.path.abspath(__file__)))\nload_dotenv()\n\nfile_paths = {\n 'en': '../static/pdf/form.pdf',\n 'es': '../static/pdf/spanish_form.pdf'\n}\n\ndef application_process(request, group_code=None, lang=None):\n application_id = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(24))\n write_pdf(application_id, request, lang)\n add_to_database(application_id, request, group_code=group_code)\n email_registrar(application_id, request)\n os.remove(f'{application_id}.pdf')\n\ndef write_pdf(application_id, request, lang):\n today_date = date.today().strftime('%m%d%y')\n\n packet = io.BytesIO()\n can = canvas.Canvas(packet, pagesize=letter)\n can.drawString(180, 732, request.form['name_last'].title())\n can.drawString(410, 732, request.form['name_first'].title())\n can.drawString(190, 715, request.form['name_middle'].title())\n can.drawString(405, 715, request.form['name_suffix'])\n\n can.drawString(525, 698, ' '.join(request.form['ssn'])) # SSN\n can.drawString(282, 683, 'X') # Gen/Spec\n # can.drawString(405, 683, 'X') # Dem Prim\n # can.drawString(503, 683, 'X') # Republican Primary\n can.drawString(212, 670, '03') # Month of Election\n can.drawString(261, 670, '23') # Day of Election\n can.drawString(310, 670, '21') # Year of Election\n can.drawString(428, 670, request.form['registered_county']) #City/County\n # can.drawString(409, 658, 'X') # Vote by Mail in All Elections Yes\n # can.drawString(442, 658, 'X') # Vote by Mail in All Elections No\n # can.drawString(126, 633, 'X') # Dem Primary Ballots\n # can.drawString(234, 633, 'X') # Rep Primary Ballots\n # can.drawString(331, 633, 'X') # No Primary Ballots\n\n can.drawString(165, 614, request.form['address'])\n can.drawString(535, 614, request.form['apt'])\n can.drawString(145, 596, request.form['city'])\n can.drawString(408, 596, ' '.join(request.form['zip']))\n\n can.drawString(198, 480, request.form['former_name'])\n can.drawString(198, 464, request.form['former_address'])\n # can.drawString(158, 448, 'City')\n # can.drawString(398, 448, 'State')\n # can.drawString(477, 448, ' '.join('20171'))\n can.drawString(525, 464, request.form['date_moved'])\n\n can.drawString(128, 301, 'X' if request.form.get(\n 'assistance_check') == 'true' else '',)\n can.drawString(210, 258, request.form['assistant_name'])\n # can.drawString(510, 258, 'Assistant Phone')\n can.drawString(210, 240, request.form['assistant_address'])\n can.drawString(560, 240, request.form['assistant_apt'])\n can.drawString(150, 226, request.form['assistant_city'])\n can.drawString(385, 226, request.form['assistant_state'])\n can.drawString(482, 226, ' '.join(request.form['assistant_zip']))\n can.drawString(210, 176, request.form['assistant_name'])\n if request.form['assistant_name']:\n can.drawString(460, 176, today_date)\n\n can.drawString(165, 565, request.form['different_address'])\n can.drawString(545, 565, request.form['different_apt'])\n can.drawString(145, 548, request.form['different_city'])\n can.drawString(322, 548, request.form['different_state'])\n can.drawString(418, 548, ' '.join(request.form['different_zip']))\n can.drawString(558, 548, request.form['different_country'] if request.form['different_city'] else '')\n can.drawString(175, 509, request.form['email'])\n can.drawString(275, 115, f'/s/ {request.form[\"signature\"].strip().title()}')\n can.setFont('Helvetica', 10)\n can.drawString(320, 135, 'This absentee ballot request contains an electronic signature.')\n can.drawString(485, 115, today_date[0:2])\n can.drawString(525, 115, today_date[2:4])\n can.drawString(565, 115, today_date[4:6])\n\n can.save()\n packet.seek(0)\n new_pdf = PdfFileReader(packet)\n existing_pdf = PdfFileReader(file_paths[lang], 'rb')\n output = PdfFileWriter()\n page = existing_pdf.getPage(0)\n page.mergePage(new_pdf.getPage(0))\n output.addPage(page)\n\n with open(f'{application_id}.pdf', 'wb') as output_pdf_file:\n output.write(output_pdf_file)\n\n\ndef add_to_database(application_id, request, group_code):\n if group_code is not None:\n group_code = group_code.lower()\n elif request.cookies.get('group'):\n group_code = request.cookies.get('group').lower()\n elif group_code is None:\n group_code = ''\n\n new_voter = User(\n application_id=application_id,\n name=(f'{request.form[\"name_first\"].title()} {request.form[\"name_middle\"].title()} {request.form[\"name_last\"].title()}').replace(\n ' ', ' ').strip(),\n county=request.form['registered_county'],\n email=request.form['email'],\n phonenumber=request.form['phonenumber'],\n full_address=(request.form['address'] + ((' ' + request.form['apt']) if request.form['apt'] else '') + ', ' + request.form['city'] + ', ' + 'VA' + ' ' + request.form['zip']),\n ip=request.environ.get('HTTP_X_REAL_IP', request.remote_addr),\n group_code=group_code,\n lat=request.form['lat'],\n long=request.form['long']\n )\n\n db.session.add(new_voter)\n db.session.commit()\n\n\ndef email_registrar(application_id, request):\n emails_to_send = []\n with open('../static/localities_info.json') as file:\n localities = json.load(file)\n if 'localhost' not in request.url_root:\n emails_to_send.append(\n localities[request.form['registered_county']]['email'])\n if request.form.get('email'):\n emails_to_send.append(request.form.get('email'))\n\n if len(emails_to_send) > 0:\n yagmail.SMTP(os.environ[\"GMAIL_SENDER_ADDRESS\"], os.environ[\"GMAIL_SENDER_PASSWORD\"]).send(\n to=([email for email in emails_to_send]),\n subject=(\n f'Absentee Ballot Request - Applicant-ID: {application_id}'),\n contents=\"\"\"\n Registrar, attached is a voter application for absentee ballot. The voter sent it through eAbsentee.org and the voter is CC'd here.\n
\n Voter, no further action is required on your part. An absentee ballot will be mailed soon to the address you designated. To check on the status of your application, visit the Virginia elections website. Please allow the registrar at least five days to process it.\n
\n Votante, no necesita hacer nada más. Una papeleta para votar en ausencia será pronto enviada por correo al lugar designado. Para checar el estado de su aplicación, visite la página de las elecciones de Virginia. Favor de permitir al registrador, al mínimo, cinco días para tratarla.\n \"\"\",\n attachments=(f'{application_id}.pdf')\n )\n","sub_path":"eAbsentee/form/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"67970614","text":"def isPalindrome(userInput):\n palindrome = True\n iterationLimit = int(len(userInput) / 2)\n\n iterationCount = 0\n for char in userInput:\n iterationCount += 1\n\n oppositeLetter = userInput[0 - iterationCount]\n if oppositeLetter != char:\n palindrome = False\n \n if iterationCount == iterationLimit:\n break\n\n return palindrome\n\n# if isPalindrome('sabarwhbcsgtfvcxirjgfnuyyunfgjrixcvftgscbhwrabas'): \n# print('The word is palindrome.')\n# else:\n# print('The word is not a palindrome.')\n\ndef recursivePalindrome(word, position = 1, status = True):\n iterationLimit = int(len(word) / 2)\n\n #base case\n if position == iterationLimit:\n return status\n\n if word[position - 1] == word[0 - position]:\n return recursivePalindrome(word, position + 1, status)\n else:\n return False\n\n\nif recursivePalindrome('sabarwhbcsgtfvcxirjgfnuyyunfgjrixcvftgscbhwrabas'): \n print('The word is palindrome.')\nelse:\n print('The word is not a palindrome.')","sub_path":"palindrome.py","file_name":"palindrome.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"507104689","text":"#!/usr/bin/env python3\n\nimport csv\nimport sys\nfrom pandas import DataFrame\nfrom pandas import Grouper\nimport seaborn as sns\nfrom matplotlib import pyplot\nimport matplotlib.cm as cm\n\njobs = sys.argv[1].split(\",\")\nprefix = sys.argv[2].split(\",\")\n\nfileformat = \".png\"\n\nprint(\"Plotting the job: \" + str(sys.argv[1]))\nprint(\"Plotting with prefix: \" + str(sys.argv[2]))\n\n\n# Color map\ncolorMap = { \"md_file_create\": cm.tab10(0),\n\"md_file_delete\": cm.tab10(1),\n\"md_mod\": cm.tab10(2),\n\"md_other\": cm.tab10(3),\n\"md_read\": cm.tab10(4),\n\"read_bytes\": cm.tab10(5),\n\"read_calls\": cm.tab10(6),\n\"write_bytes\": cm.tab10(7),\n\"write_calls\": cm.tab10(8)\n}\n\nmarkerMap = { \"md_file_create\": \"^\",\n\"md_file_delete\": \"v\",\n\"md_other\": \".\",\n\"md_mod\": \"<\",\n\"md_read\": \">\",\n\"read_bytes\": \"h\",\n\"read_calls\": \"H\",\n\"write_bytes\": \"D\",\n\"write_calls\": \"d\"\n}\n\nlinestyleMap = { \"md_file_create\": \":\",\n\"md_file_delete\": \":\",\n\"md_mod\": \":\",\n\"md_other\": \":\",\n\"md_read\": \":\",\n\"read_bytes\": \"--\",\n\"read_calls\": \"--\",\n\"write_bytes\": \"-.\",\n\"write_calls\": \"-.\"\n}\n\n# Plot the timeseries\ndef plot(prefix, header, row):\n x = { h : d for (h, d) in zip(header, row)}\n jobid = x[\"jobid\"]\n del x[\"jobid\"]\n result = []\n for k in x:\n timeseries = x[k].split(\":\")\n timeseries = [ float(x) for x in timeseries]\n if sum(timeseries) == 0:\n continue\n timeseries = [ [k, x, s] for (s,x) in zip(timeseries, range(0, len(timeseries))) ]\n result.extend(timeseries)\n\n if len(result) == 0:\n print(\"Empty job! Cannot plot!\")\n return\n\n data = DataFrame(result, columns=[\"metrics\", \"segment\", \"value\"])\n groups = data.groupby([\"metrics\"])\n metrics = DataFrame()\n labels = []\n colors = []\n style = []\n for name, group in groups:\n style.append(linestyleMap[name] + markerMap[name])\n colors.append(colorMap[name])\n if name == \"md_file_delete\":\n name = \"file_delete\"\n if name == \"md_file_create\":\n name = \"file_create\"\n metrics[name] = [x[2] for x in group.values]\n labels.append(name)\n\n fsize = (8, 1 + 1.1 * len(labels))\n fsizeFixed = (8, 2)\n fsizeHist = (8, 4)\n\n pyplot.close('all')\n\n if len(labels) < 4 :\n ax = metrics.plot(legend=True, sharex=True, grid = True, sharey=True, markersize=10, figsize=fsizeFixed, color=colors, style=style)\n ax.set_ylabel(\"Value\")\n else:\n ax = metrics.plot(subplots=True, legend=False, sharex=True, grid = True, sharey=True, markersize=10, figsize=fsize, color=colors, style=style)\n for (i, l) in zip(range(0, len(labels)), labels):\n ax[i].set_ylabel(l)\n\n pyplot.xlabel(\"Segment number\")\n pyplot.savefig(prefix + \"timeseries\" + jobid + fileformat, bbox_inches='tight', dpi=150)\n\n # Create a facetted grid\n #g = sns.FacetGrid(tips, col=\"time\", margin_titles=True)\n #bins = np.linspace(0, 60, 13)\n #g.map(plt.hist, \"total_bill\", color=\"steelblue\", bins=bins)\n\n ax = metrics.hist(sharex=True, grid = True, sharey=True, figsize=fsizeHist, bins=10)\n pyplot.savefig(prefix + \"hist\" + jobid + fileformat, bbox_inches='tight', dpi=150)\n\n\n # Plot first 30 segments\n if len(timeseries) <= 50:\n return\n\n if len(labels) < 4 :\n ax = metrics.plot(legend=True, xlim=(0,30), sharex=True, grid = True, sharey=True, markersize=10, figsize=fsizeFixed, color=colors, style=style)\n ax.set_ylabel(\"Value\")\n else:\n ax = metrics.plot(subplots=True, xlim=(0,30), legend=False, sharex=True, grid = True, sharey=True, markersize=10, figsize=fsize, color=colors, style=style)\n for (i, l) in zip(range(0, len(labels)), labels):\n ax[i].set_ylabel(l)\n\n pyplot.xlabel(\"Segment number\")\n pyplot.savefig(prefix + \"timeseries\" + jobid + \"-30\" + fileformat, bbox_inches='tight', dpi=150)\n\n### end plotting function\n\n\n\n#with open('job-io-datasets/datasets/job_codings.csv') as csv_file: # EB: old codings\nwith open('./datasets/job_codings_v4.csv') as csv_file: # EB: v3 codings moved to this repo\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0\n for row in csv_reader:\n if line_count == 0:\n header = row\n line_count += 1\n continue\n job = row[0].strip()\n if not job in jobs:\n continue\n else:\n index = jobs.index(job)\n plot(prefix[index] + \"-ks-\" + str(index), header, row)\n","sub_path":"paper/scripts/plot-single-ks-jobs.py","file_name":"plot-single-ks-jobs.py","file_ext":"py","file_size_in_byte":4216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"381861610","text":"import win32gui, win32ui, win32con, time\r\n\r\nw, h = 1920, 1080\r\nfname_count = 0\r\n\r\n# 28 in 1 sec - with date written to HDD\r\n# 30 in 1 sec - without saving bitmap\r\n\r\ndef take_screenshot():\r\n\r\n # create window handers\r\n win1 = win32gui.FindWindow(None, \"chrome.exe\")\r\n win1_object = win32gui.GetWindowDC(win1)\r\n win1_DC = win32ui.CreateDCFromHandle(win1_object)\r\n win1_DC2 = win1_DC.CreateCompatibleDC()\r\n\r\n # create bitmap handlers\r\n img1 = win32ui.CreateBitmap()\r\n img1.CreateCompatibleBitmap(win1_DC, w, h)\r\n\r\n # capture screenshot\r\n win1_DC2.SelectObject(img1)\r\n win1_DC2.BitBlt((0,0), (w,h), win1_DC, (0,0), win32con.SRCCOPY)\r\n\r\n # writing data to HDD is slow\r\n img1.SaveBitmapFile(win1_DC2, \"test.bmp\")\r\n\r\n # close window handlers\r\n win1_DC.DeleteDC()\r\n win1_DC2.DeleteDC()\r\n win32gui.ReleaseDC(win1, win1_object)\r\n win32gui.DeleteObject(img1.GetHandle())\r\n\r\n\r\ndef benchmark(timeout=1):\r\n count = 0\r\n end_loop = time.time() + (timeout)\r\n while time.time() < end_loop:\r\n take_screenshot()\r\n count += 1\r\n\r\n print(\"Result:\",count,\"pixels in\",timeout,\"seconds!\")\r\n print(\"Average:\",count/timeout,\"pixels per second!\")\r\n return [timeout, count, count/timeout]\r\n\r\ndef func_speed():\r\n start = time.time()\r\n take_screenshot()\r\n return time.time() - start\r\n","sub_path":"Python/!PYTHON/py/screen recorder/tests/with_winapi.py","file_name":"with_winapi.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"407326596","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\ndef printchick(xlist):\n print('%s%d%s'%('总共有',len(xlist),'个解'))\n for i in range (len(xlist)):\n print('%s%d%s%s %d %s %d %s %d'%('解',i+1,':','鸡翁',xlist[i][0],'鸡母',xlist[i][1],'鸡雏',xlist[i][2]))\n\n\n\n\nif __name__ == '__main__':\n alist = []\n for father in range(0,101):\n for mother in range(0,101 - father):\n if 5 * father + 3 * mother + (100 - father - mother) / 3 == 100:\n alist.append((father,mother,100 - father - mother))\n printchick(alist)\n\n print()\n blist = [(father,mother,100 - father - mother) for father in range(0,101) for mother in\n range(0,101 - father) if 5 * father + 3 * mother + (100 - father - mother) / 3 == 100]\n printchick(blist)\n","sub_path":"project6/project/17300680001.py","file_name":"17300680001.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"360631205","text":"import os \r\nadd = input(\"nhập địa chỉ cần tạo thư mục: \")\r\nfoldername = input(\"nhập tên thư mục cần tạo: \")\r\nfilename = input(\"nhập tên file cần tạo: \")\r\nfile = os.path.join(add,foldername)\r\nos.mkdir(file)\r\nos.chdir(file)\r\nf = open(filename, \"x\")\r\nf.close()\r\nprint(\"tạo thành công file\",filename,\"trong\",add,foldername)\r\n","sub_path":"taothumuc.py","file_name":"taothumuc.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"89735557","text":"import copy\n\n'''\nparser.py - parser\nThis module uses RDP to parse lexed Newt code.\n'''\n\nVAL = 'val' # Various tags\nTYPE = 'type'\nNAME = 'name'\nIF = 'if'\nFOR = 'for'\nWHILE = 'while'\nASM = 'asm'\nGOTO = 'goto'\nDEFINE = 'define'\nLBRACK = '{'\nRBRACK = '}'\nSEMI = ';'\nEQ = '='\nOP = 'op'\nLPAR = '('\nRPAR = ')'\nCOMMA = ','\n\ndef expect(stream, token):\n '''\n expect function.\n Used when a token is manditory.\n '''\n try:\n if type(token) == str: # The token is a string\n if stream[0][1] == token:\n stream.pop(0) # Pop the token if we find a match\n return True\n raise SyntaxError('Invalid token %s' % stream[0][0]) # Raise an error otherwise\n else: # The token is iterable, we never really use this\n for t in token: # Iterate over every token\n if stream[0][1] == t: # Match it\n stream.pop(0)\n return True\n raise SyntaxError('Invalid token %s' % stream[0][0])\n except IndexError:\n raise SyntaxError('Not enough tokens') # There aren't enough tokens, yell at somebody\ndef accept(stream, token):\n '''\n accept function.\n Used for optional tokens or for accepting any of a set of tokens.\n '''\n if type(token) == str: # The token is a string\n first = stream[0][1]\n if first == token:\n stream.pop(0) # Pop the token if we find a match\n return True\n return False # If no match was found, just return false\n else: # The token is iterable, this is not really used\n for t in token: # Iterate over every token\n if stream[0][1] == t: # Match it\n stream.pop(0)\n return True\n return False\n\ndef assign(stream):\n '''\n assign function.\n Used for parsing an assign statement.\n '''\n if len(stream) == 5: # The statement is of the form = ;\n if accept(stream, TYPE):\n expect(stream, NAME)\n expect(stream, EQ)\n accept(stream, VAL)\n accept(stream, NAME)\n expect(stream, SEMI)\n return True\n elif len(stream) == 4: # The statement is of the form = ;\n if accept(stream, NAME):\n expect(stream, EQ)\n accept(stream, VAL)\n accept(stream, NAME)\n expect(stream, SEMI)\n return True\n return False\n\ndef arg(stream):\n '''\n arg function.\n Not applied directly to lexed code - used for parsing arguments to functions.\n '''\n if accept(stream, TYPE) or accept(stream, VAL) or accept(stream, NAME): # We found a match\n accept(stream, RPAR) # This could be the end of the stream\n if len(stream) > 1: # But then again, it might not be\n accept(stream, COMMA)\n arg(stream)\n return True\n elif accept(stream, RPAR):\n return True\n return False\ndef call(stream):\n '''\n call function.\n Used for parsing function calls.\n '''\n if accept(stream, NAME):\n expect(stream, LPAR)\n arg(stream)\n expect(stream, SEMI)\n return True\n return False\n\ndef condition(stream):\n '''\n condition function.\n Used for parsing if statements.\n '''\n if accept(stream, IF):\n expect(stream, LPAR)\n accept(stream, VAL)\n accept(stream, NAME)\n expect(stream, OP)\n accept(stream, VAL)\n accept(stream, NAME)\n expect(stream, RPAR)\n expect(stream, LBRACK)\n return True\n return False\n\ndef asm(stream):\n '''\n asm function.\n Used for parsing inline assembly.\n '''\n if accept(stream, ASM):\n expect(stream, LBRACK)\n return True\n return False\n\ndef loop(stream):\n '''\n loop function.\n Used for parsing while loops.\n '''\n if accept(stream, WHILE):\n expect(stream, LPAR)\n accept(stream, VAL)\n accept(stream, NAME)\n expect(stream, OP)\n accept(stream, VAL)\n accept(stream, NAME)\n expect(stream, RPAR)\n expect(stream, LBRACK)\n return True\n return False\n\ndef rep(stream):\n '''\n rep function.\n Used for parsing for loops.\n '''\n if accept(stream, FOR):\n expect(stream, LPAR)\n expect(stream, NAME)\n expect(stream, COMMA)\n accept(stream, VAL)\n accept(stream, NAME)\n expect(stream, COMMA)\n accept(stream, VAL)\n accept(stream, NAME)\n expect(stream, RPAR)\n expect(stream, LBRACK)\n return True\n return False\n\ndef goto(stream):\n '''\n goto function.\n Used for parsing goto statements.\n '''\n if accept(stream, GOTO):\n accept(stream, VAL)\n accept(stream, NAME)\n expect(stream, SEMI)\n\ndef define(stream):\n '''\n define function.\n Used for parsing function definitions.\n '''\n if accept(stream, DEFINE):\n expect(stream, NAME)\n expect(stream, LPAR)\n arg(stream)\n expect(stream, LBRACK)\n return True\n return False\n\ndef end(stream):\n '''\n end function.\n Never applied directly to input, used for checking if a statement just ended.\n '''\n return stream.strip()[0] == '}'\n\nparsers = [assign, call, condition, asm, loop, rep, goto, define] # The parsers\ndef parse(stream):\n '''\n The parse function - used for parsing lexed code.\n '''\n i = 0\n old = copy.copy(stream) # We need a copy of the stream because ours will be broken.\n p = None\n for parser in parsers: # Iterate over every parser\n try:\n parser(stream) # Apply the current parser to the input\n if not stream:\n p = parser # The whole stream was consumed, so this parser is the match\n except Exception as e: # The parser threw and error, so pass over it\n pass\n return p, old\n","sub_path":"src/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":5860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"527086016","text":"def shape(matriz):\n y_size=len(matriz)\n x_size=len(matriz[0])\n for line in matriz:\n print(line)\n if(len(line)!=x_size):\n raise Exception(\"matriz is not valid because its has lines with diferents sizes\")\n\n \n return x_size,y_size\n\ndef transpose(matriz):\n x_shape,y_shape = shape(matriz)\n transpose_matriz = []\n\n for col_cont in range(x_shape):\n line = []\n for row_cont in range(y_shape):\n line.append(matriz[row_cont][col_cont])\n \n transpose_matriz.append(line)\n \n return transpose_matriz\n\nprint(transpose([[1,2,3],[4,5,6]]))","sub_path":"P1LP1/questões aulas/matriz_transposta.py","file_name":"matriz_transposta.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"492212619","text":"#you know what final testin\n#from lab\n#testing 123\n#import matplotlib.pyplot as plt\n\nfrom statistics import mean\nfrom math import log\nimport time\nimport csv\nimport timeit\nimport pickle\nimport sys\n\n\n\ndef extract(number):\n\tts = []\n\twith open('1500comma.csv', newline='') as csvfile:\n\t\tspamreader = csv.reader(csvfile, delimiter=',', quotechar='|')\n\t\tfor row in spamreader:\n\t\t\tts.append(row[number])\n\tdel ts[0]\n\tts=list(map(float, ts))\n\treturn ts\n\n\ndef calculate_band (raw_value, max_value, k):\n\tincrement = max_value/k\n\tif raw_value == max_value:\n\t\tband = k\n\telse:\n\t\tband = int(raw_value//increment+1)\n\treturn band\n\n\n\ndef find_data_size():\n\tlst = []\n\tfor i in list(range(0,1168)):\n\t\tts = extract(i)\n\t\tlst.append(len(ts))\n\tprint('number of stocks')\n\tprint(lst)\n\tprint('number of data point')\n\tprint(len(lst))\n\n#find_data_size()\n# 1168*2517****\n\ndef find_max_min():\n\tstock_list = list(range(0,1168))\n\tts_aggregated = []\t\n\tfor stock_id in stock_list:\n\t\tts1 = extract(stock_id)\n\t\tts_aggregated = ts_aggregated + ts1\n\tprint(max(ts_aggregated))\n\tprint(min(ts_aggregated))\n#find_max_min()\n#1799.23 new 1469.56\n\ndef convert(ts,window_size,number_of_bands,max_value):\n\n\t#increment = (max_value)/(number_of_bands)\n\t#ts2 = [int ((x)//increment+1) for x in ts]\n\tts2 =[calculate_band(x,max_value,number_of_bands) for x in ts]\n\tts3=[]\n\tcount = 0 + window_size\n\twhile (count <= len(ts2)):\n \t\t\tx = ts2[(count-window_size):count]\n \t\t\tz = tuple(x)\n \t\t\tts3.append(z)\n \t\t\tcount = count +1\n\treturn ts3\n\n\n\ndef convert_s(ts,window_size,number_of_bands,max_value):\n\n\tts2 =[calculate_band(x,max_value,number_of_bands) for x in ts]\n\tts3=[]\n\tcount = 0 + window_size\n\twhile (count <= len(ts2)):\n\t\t\t\tx = ts2[(count-window_size):count]\n\t\t\t\tz =''\n\t\t\t\tfor i in x:\n\t\t\t\t\tz=z+str(i)+','\n\t\t\t\tts3.append(z)\n\t\t\t\tcount = count +1\n\treturn ts3\n\n\n'''\ndef calculate_prob (ts):\n\tul = [(x,(ts.count(x)/len(ts))) for x in set(ts)]\n\tul.sort()\n\treturn ul\n'''\n\n\ndef calculate_entropy (alphabet):\n\tprob_list=[x[1] for x in alphabet]\n\t#print(prob_list)\n\t#print(sum(prob_list))\n\n\tentropy = 0\n\tfor p in prob_list:\n\t\tentropy = entropy - p*log(p,2)\n\treturn entropy\n\ndef merge (ts,factor):\n\tmerged_ts = []\n\tcount=0\n\twhile (count+factor-1) <= len(ts)-1:\n\t\tnew_point = mean(ts[count:(count+factor)])\n\t\tmerged_ts.append(new_point)\n\t\tcount = count+factor\n\t#print(merged_ts)\n\treturn merged_ts \n#merge ([1,2,3,4,5,6],6)\n\n\ndef normalise(ts):\n\tts_max = max(ts)\n\tts_min = min(ts)\n\tts_normalised = []\n\tfor a in ts:\n\t\tif a==ts_max:\n\t\t\tb = 100\n\t\t\tts_normalised.append(b)\n\t\telse:\n\t\t\tb = 100*(a-ts_min)/(ts_max-ts_min)\n\t\t\tts_normalised.append(b)\n\treturn ts_normalised\n\n\n\n\n\n# main function \ndef main(stock_list,window_size, number_of_bands, max_value):\n\tprint (\"\\n \")\n\t\n\tstart = timeit.default_timer()\n\n\tincrement = (max_value)/(number_of_bands)\n\tletter_list_agg = []\n\n\tdone1 = 0 \n\tfor stock_id in stock_list:\n\t\tts = extract(stock_id)\n\t\tts=normalise(ts)\n\t\tls = convert_s(ts,window_size,number_of_bands,max_value)\n\t\tletter_list_agg = letter_list_agg + ls\n\t\tdone1 = done1+1\n\t\tsys.stdout.write('\\r')\n\t\tsys.stdout.write(\"%f\" % (done1/1168))\n\t\tsys.stdout.flush()\n\n\tprint (\"\\n \")\n\tprint('---- done preparing data ----')\n\t\t\n\n\tdata_size = len(letter_list_agg)\n\n\tunique_letter = set (letter_list_agg)\n\n\tunique_size = len(unique_letter)\n\n\talphabet = []\n\n\n\tdone2 =0\n\tfor a in unique_letter:\n\t\tp=letter_list_agg.count(a)/data_size\n\t\tl = (a,p)\n\t\talphabet.append(l)\n\t\tdone2 = done2 +1\n\t\tsys.stdout.write('\\r')\n\t\tsys.stdout.write(\"%f\" % (done2/unique_size))\n\t\tsys.stdout.flush()\n\n\n\n\t#ordered_letter_prob = sorted(letter_prob, key=lambda tup: tup[1], reverse=True)\n\t\n\n\tstop = timeit.default_timer()\n\ttime = (stop - start)\n\t\n\t#alphabet.sort()\n\t\n\twith open('output_new.pickle', 'wb') as handle:\n \t\tpickle.dump(alphabet, handle)\n\n\tprint('\\n')\n\n\n\t\n\tprint(alphabet)\n\n\t\n\tprint('----------- n = %d, k = %d, Max = %d -------------' % (window_size, number_of_bands, max_value))\n\n\tprint('\\n')\n\t\n\tprint('Running Time (s): %f' %time)\n\tprint ('Sample size: %d' %data_size)\n\n\n'''\nprint('---- String Version ----')\n\nstock_list = list(range(0,1168)) #1168\nmain(stock_list,5, 100, 100)\n'''\n\ndef run_info():\n\twith open('./data/alphabet1.pickle', 'rb') as handle:\n\t\ta = pickle.load(handle)\n\n\ta.sort()\n\t#print(a)\n\tnon_zero = len(a)\n\tentropy = calculate_entropy(a)\n\tordered_a = sorted(a, key=lambda tup: tup[1], reverse=True)\n\n\tprint ('Number of Non-Zero : %d' %non_zero)\n\tprint (\"Entropy: %f\" %entropy) \n\tprint('Top X:')\n\tprint(ordered_a[0:100])\n\n\t\n\nrun_info()\n\n\n\n","sub_path":"main_alphabet1_string.py","file_name":"main_alphabet1_string.py","file_ext":"py","file_size_in_byte":4460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"608372725","text":"import cv2\nfrom darkflow.net.build import TFNet\nimport time\nimport sys\n\ndef predict_video(video_path):\n # Dictionary for the parameters\n options = {\n 'model': './cfg/yolov2-tiny-voc.cfg',\n 'load': './bin/yolov2-tiny-voc.weights',\n 'threshold': 0.1,\n 'gpu': .5\n }\n\n # Setup the darkflow tensorflow network with the defined options above\n tfnet = TFNet(options)\n\n # Load video\n print(\"Loading video\")\n #capture = cv2.VideoCapture('.\\testassets\\testvideo720p.mp4')\n capture = cv2.VideoCapture(video_path)\n\n # For debugging\n frame_number = 0\n start_time = time.time()\n\n # Start analysis\n while(capture.isOpened()):\n frame_start = time.time()\n ret, frame = capture.read()\n\n if ret:\n results = tfnet.return_predict(frame)\n frame_number += 1\n\n # Inform user to push Q to quit, text in upper left corner.\n frame = cv2.putText(frame, \"Push Q to quit\", (0, 20), cv2.FONT_HERSHEY_DUPLEX, 0.75, (0, 0, 255), 1)\n\n # Create the boxes for things that have been detected\n for result in results:\n tl = (result['topleft']['x'], result['topleft']['y'])\n br = (result['bottomright']['x'], result['bottomright']['y'])\n confidence = result['confidence']\n label = result['label']\n\n # Move label up 20 pixels so its inside the border\n tl_label = (result['topleft']['x'], result['topleft']['y'] + 20)\n\n frame = cv2.rectangle(frame, tl, br, (255, 0, 0), 3)\n\n text = '{}: {:.0f}%'.format(label, confidence * 100)\n frame = cv2.putText(frame, text, tl_label, cv2.FONT_HERSHEY_DUPLEX, 0.75, (0, 0, 255), 1)\n cv2.imshow('frame', frame)\n print('Frame {}, time {}, FPS {:.3f}'.format(frame_number, time.time()-start_time, 1 / (time.time()-frame_start)))\n\n # to manually quit\n if cv2.waitKey(1) & 0xFF == ord('q'):\n print(\"QUITTING\")\n break\n\n capture.release()\n cv2.destroyAllWindows()\n total_time = time.time() - start_time\n print('===')\n print('Total frames: {}, Total time: {:.3f}, Average FPS: {:.3f}'.format(frame_number, total_time, frame_number/total_time))\n\n\nif __name__ == '__main__':\n path = sys.argv[1]\n print(\"\\n=======\\nDesired video path is: {}\\n=======\\n\".format(path))\n predict_video(path)","sub_path":"predictVideo.py","file_name":"predictVideo.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"134011347","text":"import tensorflow as tf\nimport numpy as np\n\ntf.set_random_seed(777)\n\ndef conv2d(x, f=64, k=4, d=2, pad='SAME', name='conv2d'):\n return tf.layers.conv2d(x,\n filters=f, kernel_size=k, strides=d,\n padding=pad, name=name)\n\ndef deconv2d(x, f=64, k=4, d=2, pad='SAME', name='deconv2d'):\n return tf.layers.conv2d_transpose(x,\n filters=f, kernel_size=k, strides=d,\n padding=pad, name=name)\n\t\t\t\t\t\t\t\t\t \ndef batch_norm(x, momentum=0.9, eps=1e-5, is_train=True):\n return tf.layers.batch_normalization(inputs=x,\n momentum=momentum,\n epsilon=eps,\n scale=True,\n training=is_train)\n\nclass InfoGAN:\n\n\tdef __init__(self, s, batch_size=128, input_height=28, input_width=28, input_channel=1,\n\t\t\t\t\tsample_num=10 * 10, sample_size=10, output_height=28, output_width=28,\n\t\t\t dfilters_dim=128, gfilters_dim=64, fc_unit=1024, \n\t\t\t\t\tn_categories=10, z_dim=62, n_continuos_factor = 2,\n\t\t\t conv_kernel_dim = 4, conv_stride = 2, g_lr=1e-3, d_lr=2e-4, is_train=True):\n\t\tself.s = s\n\t\tself.batch_size = batch_size\n\t\tself.is_train = is_train\n\n \n\t\t#Input configuration\n\t\tself.input_height = input_height\n\t\tself.input_width = input_width\n\t\tself.input_channel = input_channel\n\t\tself.image_shape = [self.batch_size, self.input_height, self.input_width, self.input_channel]\n\n\t\t#Output configuration\n\t\tself.sample_num = sample_num\n\t\tself.sample_size = sample_size\n\t\tself.output_height = output_height\n\t\tself.output_width = output_width\n\n\t\t#Networks configuration\n\t\tself.n_cat = n_categories\n\t\tself.n_cont = n_continuos_factor\n\t\tself.z_dim = z_dim\n\t\tself.df_dim = dfilters_dim\n\t\tself.gf_dim = gfilters_dim\n\t\tself.fc_unit = fc_unit\n\t\tself.conv_k = conv_kernel_dim\n\t\tself.conv_s = conv_stride\n\n\t\t#Hiperparameters\n\t\tself.beta1 = 0.5\n\t\tself.beta2 = 0.999\n\t\tself.cat_lambda = 1.0\n\t\tself.cont_lambda = 0.001\n\t\tself.d_lr = d_lr\n\t\tself.g_lr = g_lr\n\t\tself.TINY = 1e-8\n\n\t\t#Variables initialization\n\t\tself.d_real = 0.\n\t\tself.d_fake = 0.\n\n\t\tself.g_loss = 0.\n\t\tself.d_loss = 0.\n\t\tself.q_loss = 0.\n\n\t\tself.d_op = None\n\t\tself.g_op = None\n\t\tself.q_op = None\n\n\t\tself.merged = None\n\t\tself.writer = None\n\t\tself.saver = None\n\n\t\t# Placeholders\n\t\tself.x = tf.placeholder(tf.float32,\n\t\t shape=[None, self.input_height, self.input_width, self.input_channel],\n\t\t name=\"x-image\") # (-1, 28, 28, 1)\n\t\tself.z = tf.placeholder(tf.float32, shape=[None, self.z_dim], name='z-noise') # (-1, 62)\n\t\tself.c = tf.placeholder(tf.float32, shape=[None, self.n_cat + + self.n_cont], name='c') # (-1, 10)\n\n\t\tself.build_infogan() # build InfoGAN model\n\n\tdef classifier(self, x, reuse=None):\n\t\twith tf.variable_scope(\"classifier\", reuse=reuse):\n\t\t\tx = tf.layers.dense(x, units=128, name='d-fc-1')\n\t\t\tx = batch_norm(x, is_train=self.is_train)\n\t\t\tx = tf.nn.leaky_relu(x, alpha=0.1)\n\n\t\t\tlogits = tf.layers.dense(x, units=self.n_cat + self.n_cont, name='d-fc-2')\n\t\t\tprob = tf.nn.sigmoid(logits)\n\n\t\t\treturn prob, logits\n\n\n\tdef discriminator(self, x, reuse=None):\n\t\twith tf.variable_scope(\"discriminator\", reuse=reuse):\n\t\t\tx = conv2d(x, f=self.df_dim, name='d-conv2d-0')\n\t\t\tx = tf.nn.leaky_relu(x, alpha=0.1)\n\t\t\t\n\t\t\tx = conv2d(x, f=self.df_dim *2, name='d-conv2d-1')\n\t\t\tx = batch_norm(x, is_train=self.is_train)\n\t\t\tx = tf.nn.leaky_relu(x, alpha=0.1)\n\n\t\t\tx = tf.layers.flatten(x)\n\n\t\t\tx = tf.layers.dense(x, units=self.fc_unit, name='d-fc-0')\n\t\t\tx = batch_norm(x, is_train=self.is_train)\n\t\t\tx = tf.nn.leaky_relu(x, alpha=0.1)\n\n\t\t\tlogits = tf.layers.dense(x, units=1, name='d-fc-1')\n\t\t\tprob = tf.nn.sigmoid(logits)\n\n\t\t\treturn prob, logits, x\n\n\tdef generator(self, z, c, reuse=None):\n\t\twith tf.variable_scope(\"generator\", reuse = tf.AUTO_REUSE):\n\t\t\tx = tf.concat([z, c], axis=1) # (-1, 74)\n\n\t\t\tx = tf.layers.dense(x, units= self.fc_unit, name='g-fc-0')\n\t\t\tx = batch_norm(x, is_train=self.is_train)\n\t\t\tx = tf.nn.leaky_relu(x, alpha=0.1)\n\n\t\t\tx = tf.layers.dense(x, units= 7*7*self.gf_dim*2, name='g-fc-1')\n\t\t\tx = batch_norm(x, is_train=self.is_train)\n\t\t\tx = tf.nn.leaky_relu(x, alpha=0.1)\n\n\t\t\tx = tf.reshape(x, shape=[-1, 7, 7, self.gf_dim * 2])\n\n\t\t\tx = deconv2d(x, f=self.gf_dim, name='g-conv2d-0')\n\t\t\tx = batch_norm(x, is_train=self.is_train)\n\t\t\tx = tf.nn.leaky_relu(x, alpha=0.1)\n\n\t\t\tx = deconv2d(x, f=1, name='g-conv2d-1')\n\t\t\tx = tf.nn.tanh(x)\n\n\t\t\treturn x\n\n\tdef build_infogan(self):\n\t\t#Build generator G(z,c)\n\t\tself.g = self.generator(self.z, self.c, reuse= not self.is_train)\n\n\t\t#Build discriminators (real e fake) D(x)\n\t\td_real, d_real_logits, _ = self.discriminator(self.x)\n\t\td_fake, d_fake_logits, d_fake_d = self.discriminator(self.g, reuse=True)\n\n\t\t# Classifier Q(x)\n\t\tc_fake, c_fake_logits = self.classifier(d_fake_d)\n\n\t\t# Losses\n\t\tself.d_loss = - tf.reduce_mean(tf.log(d_real + 1e-8) + tf.log(1. - d_fake + 1e-8))\n\t\tself.g_loss = - tf.reduce_mean(tf.log(d_fake + 1e-8))\n\n\t\t#Categorical\n\t\tq_cat = c_fake[:, :self.n_cat]\n\n\t\tcat_dist_prob = tf.ones([self.batch_size, self.n_cat]) * (1.0 / self.n_cat)\n\t\tcat_dist = tf.reduce_sum(tf.log(cat_dist_prob+ 1e-8) * cat_dist_prob, 1)\n\t\tcat_dist_h = tf.reduce_mean(-cat_dist)\n\n\t\tcat_Qcx = tf.reduce_sum(tf.log(q_cat + 1e-8) * self.c[:, :self.n_cat], 1)\n\t\tcat_cond_h = tf.reduce_mean(-cat_Qcx)\n\n\t\tq_cat_loss = self.cat_lambda * (cat_dist_h-cat_cond_h)\n\n\t\t#Continuos\n\t\tq_cont = c_fake[:, self.n_cat:]\n\n\t\tmean = tf.zeros([self.batch_size, self.n_cont])\n\t\tstddev = tf.ones([self.batch_size, self.n_cont])\n\n\t\tepsilon_prior = (self.c[:, self.n_cat:] - mean) / (stddev + self.TINY)\n\t\tcont_dist = tf.reduce_sum( - 0.5 * np.log(2 * np.pi) - tf.log(stddev + self.TINY) - 0.5 * tf.square(epsilon_prior),reduction_indices=1,)\n\t\tcont_dist_h = tf.reduce_mean(-cont_dist)\n\n\t\tepsilon_est = (q_cont - mean) / (stddev + self.TINY)\n\t\tcont_Qcx = tf.reduce_sum( - 0.5 * np.log(2 * np.pi) - tf.log(stddev + self.TINY) - 0.5 * tf.square(epsilon_est),reduction_indices=1,)\n\t\tcont_cond_h = tf.reduce_mean(-cont_Qcx)\n\n\t\t#l2_loss = tf.reduce_mean(tf.reduce_sum(tf.square(self.c[:, self.n_cat:] - q_cont), axis=1))\n\t\t#q_cont_loss = self.cont_lambda * l2_loss\n\n\t\tq_cont_loss = self.cont_lambda * (cont_dist_h - cont_cond_h)\n\n\t\tself.q_loss = - (q_cat_loss + q_cont_loss)\n\n\t\t# Summary\n\t\ttf.summary.histogram(\"z-noise\", self.z)\n\t\ttf.summary.image(\"g\", self.g, 5) # generated images by Generative Model\n\t\ttf.summary.scalar(\"d_loss\", self.d_loss)\n\t\ttf.summary.scalar(\"g_loss\", self.g_loss)\n\t\ttf.summary.scalar(\"q_loss\", q_cat_loss + q_cont_loss)\n\n\t\t# Optimizer\n\t\tt_vars = tf.trainable_variables()\n\t\td_params = [v for v in t_vars if v.name.startswith('d')]\n\t\tg_params = [v for v in t_vars if v.name.startswith('g')]\n\t\tq_params = [v for v in t_vars if v.name.startswith('c') or v.name.startswith('g')]\n\n\t\tself.d_op = tf.train.AdamOptimizer(learning_rate=self.d_lr,\n\t\t beta1=self.beta1, beta2=self.beta2).minimize(self.d_loss, var_list=d_params)\n\t\tself.g_op = tf.train.AdamOptimizer(learning_rate=self.g_lr,\n\t\t beta1=self.beta1, beta2=self.beta2).minimize(self.g_loss, var_list=g_params)\n\t\tself.q_op = tf.train.AdamOptimizer(learning_rate=self.g_lr,\n\t\t beta1=self.beta1, beta2=self.beta2).minimize(self.q_loss, var_list=q_params)\n\n\t\t# Merge summary\n\t\tself.merged = tf.summary.merge_all()\n\n\t\t# Model saver\n\t\tself.saver = tf.train.Saver(max_to_keep=1)\n\t\tself.writer = tf.summary.FileWriter('./model/', self.s.graph)","sub_path":"Data Science/Deep Learning/GANs/ InfoGAN v1 unstable/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"248065821","text":"#!/usr/bin/env python3.5\n# encoding: utf-8\n# Created by leiwei on 2020/10/21 16:06\n\n\nfrom wsgiref.simple_server import make_server\n\n\ndef demo_app(environ,start_response):\n # environ是一个字典\n # print(environ)\n path = environ.get('PATH_INFO',' Not Found')\n\n param = environ.get('QUERY_STRING','')\n\n print(param)\n\n status_code = '200 OK'\n\n if path == '/login':\n response_body = '欢迎来到登录页'\n elif path == '/register':\n response_body = '欢迎来到注册页'\n elif path == '/':\n response_body = '欢迎来到首页'\n else:\n response_body = '你要查找的页面不存在'\n status_code = '404 Page Not Found'\n\n print('path = {}'.format(path))\n start_response(status_code, [('Content-Type','text/html; charset=utf-8')])\n return [response_body.encode('utf8')]\n\n\n\nif __name__ == '__main__':\n # demo_app 是一个函数,用来处理用户的请求\n httpd = make_server('', 8000, demo_app)\n sa = httpd.socket.getsockname()\n print(\"Serving HTTP on\", sa[0], \"port\", sa[1], \"...\")\n # 打开电脑的浏览器,并在浏览器输入地址,可以不用\n\n httpd.serve_forever()\n\n\n\n\n\n","sub_path":"day16_HTTP服务器/08-根据请求路径返回不同内容.py","file_name":"08-根据请求路径返回不同内容.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"375033821","text":"# coding: utf-8\n\nfrom __future__ import unicode_literals, print_function\n\nimport subprocess\n\ndef run_shcmd(cmd, input=None, **kwargs):\n\n show_error_msg = None\n if 'show_error_msg' in kwargs:\n show_error_msg = kwargs['show_error_msg']\n del kwargs['show_error_msg']\n\n proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, \\\n stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, **kwargs)\n out, err = proc.communicate(input=input)\n\n if proc.returncode != 0 and show_error_msg:\n print('>> %s' % cmd)\n print('returned non-zero code from shell('+str(ret_code)+')\\n OUTPUT: '+str(out)+'\\n ERROR: '+str(err)+'\\n')\n\n return out, err, proc.returncode\n\ndef is_name_equal(A, B):\n\n if hasattr(A, \"wrapped\"):\n A = A.wrapped\n\n if hasattr(B, \"wrapped\"):\n B = B.wrapped\n\n if not hasattr(A, \"string\"):\n return False\n\n if not hasattr(B, \"string\"):\n return False\n\n return A.string == B.string\n","sub_path":"frelpt/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"17856749","text":"import configparser\nimport pygame\n\nred = (255,0,0)\nblue = (0,0,255)\nblack = (0,0,0)\ndudeOrange = (170, 85, 0)\n\n\n# read ini\nmgConfig = configparser.ConfigParser()\nmgConfig.read('moongladiator.ini')\n\n# create variables from ini\nscreenwidth = int(mgConfig.get('resolution', 'width'))\nscreenheight = int(mgConfig.get('resolution', 'height'))\n\nenemycount = int(mgConfig.get('npc', 'npccount'))\n\n# set up sprite groups\nallSpriteGroup = pygame.sprite.LayeredUpdates()\n\n\n\n","sub_path":"common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"9060057","text":"import os\nimport sys\nfrom collections import OrderedDict\nfrom unittest import mock\n\nimport torch\nimport torch.optim\nfrom torch import nn\n\nfrom openml import config\nfrom openml.extensions.pytorch import PytorchExtension\nfrom openml.testing import TestBase\n\n\nthis_directory = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(this_directory)\n\n\nclass TestPytorchExtensionFlowSerialization(TestBase):\n\n def setUp(self, n_levels: int = 1):\n super().setUp(n_levels=2)\n self.extension = PytorchExtension()\n config.server = self.production_server\n\n def test_serialize_sequential_model(self):\n with mock.patch.object(self.extension, '_check_dependencies') as check_dependencies_mock:\n model = nn.Sequential(\n nn.LayerNorm(20),\n nn.Linear(20, 64),\n nn.ReLU(),\n nn.Dropout(),\n nn.Linear(64, 2),\n nn.Softmax(dim=0)\n )\n\n fixture_name = 'torch.nn.modules.container.Sequential'\n fixture_description = 'Automatically created pytorch flow.'\n version_fixture = 'torch==%s\\nnumpy>=1.6.1\\nscipy>=0.9' \\\n % torch.__version__\n fixture_parameters = \\\n OrderedDict([('children',\n '[{\"oml-python:serialized_object\": \"component_reference\", '\n '\"value\": {\"key\": \"0\", \"step_name\": \"0\"}}, '\n '{\"oml-python:serialized_object\": \"component_reference\", '\n '\"value\": {\"key\": \"1\", \"step_name\": \"1\"}}, '\n '{\"oml-python:serialized_object\": \"component_reference\", '\n '\"value\": {\"key\": \"2\", \"step_name\": \"2\"}}, '\n '{\"oml-python:serialized_object\": \"component_reference\", '\n '\"value\": {\"key\": \"3\", \"step_name\": \"3\"}}, '\n '{\"oml-python:serialized_object\": \"component_reference\", '\n '\"value\": {\"key\": \"4\", \"step_name\": \"4\"}}, '\n '{\"oml-python:serialized_object\": \"component_reference\", '\n '\"value\": {\"key\": \"5\", \"step_name\": \"5\"}}]')])\n\n structure_fixture = {'torch.nn.modules.activation.ReLU': ['2'],\n 'torch.nn.modules.activation.Softmax': ['5'],\n 'torch.nn.modules.container.Sequential': [],\n 'torch.nn.modules.dropout.Dropout': ['3'],\n 'torch.nn.modules.linear.Linear': ['1'],\n 'torch.nn.modules.linear.Linear' + str(['4']): ['4'],\n 'torch.nn.modules.normalization.LayerNorm': ['0']}\n\n serialization = self.extension.model_to_flow(model)\n structure = serialization.get_structure('name')\n\n self.assertIn(fixture_name, serialization.name)\n self.assertEqual(serialization.class_name[:len(fixture_name)], fixture_name)\n self.assertEqual(serialization.description, fixture_description)\n self.assertEqual(serialization.parameters, fixture_parameters)\n self.assertEqual(serialization.dependencies, version_fixture)\n\n # Remove identifier of each component\n structure_modified = {}\n\n def _cmp(kv):\n k, v = kv\n if len(v) == 0:\n return k\n return v[0]\n\n for key, value in sorted(structure.items(), key=_cmp):\n new_key = key[:key.rfind('.')]\n if new_key not in structure_modified.keys():\n structure_modified[new_key] = value\n else:\n structure_modified[new_key + str(value)] = value\n\n self.assertDictEqual(structure_fixture, structure_modified)\n\n new_model = self.extension.flow_to_model(serialization)\n # compares string representations of the dict, as it potentially\n # contains complex objects that can not be compared with == op\n self.assertEqual(str(model), str(new_model))\n\n self.assertEqual(type(new_model), type(model))\n self.assertIsNot(new_model, model)\n\n self.assertEqual(check_dependencies_mock.call_count, 7)\n","sub_path":"tests/test_extensions/test_pytorch_extension/test_pytorch_serialization.py","file_name":"test_pytorch_serialization.py","file_ext":"py","file_size_in_byte":4420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"406495903","text":"# input = [1, 2, 1, 4, 5, 6, 6] ... output [1,2,4,5,6]\n\ndef remove_duplicates(l):# worst case [1,2,4,5,6]\n result = {}\n for val in l: # n times\n if not val in result: # 1, 2, 3, 4 ... n - 1 # Balanced tree as a result we would get n * log n\n result[val] = 1 #(n * n - 1) /2 = O(n squared)\n return list(result.keys()) # n times 1 (dont count colisions)\n\nprint(remove_duplicates([1, 2, 1, 4, 5, 6, 6]))\n ","sub_path":"Engineering Interview Improve Problem-Solving in Python!/template/Section 2 Coding Interview Questions 1 - 10/02-Delete-duplicates.py","file_name":"02-Delete-duplicates.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"473353807","text":"#!/usr/bin/env python\nimport argparse\nimport pymssql\nimport json\n\n#get the lcmMediaId from DB.\ndef getMediaId(contentProviderMediaName):\n #test db\n conn = pymssql.connect(host='CHELLSSSQL23.karmalab.net', user='TravCatalog', password='travel', database='LodgingCatalogMaster_Phoenix')\n #prod db\n #conn = pymssql.connect(host='LodgingCatalogMaster.ch.expeso.com', user='TravCatalog', password='travel', database='LodgingCatalogMaster_Phoenix')\n cur = conn.cursor()\n cur.execute('SELECT * FROM media WHERE contentprovidermedianame =%s',contentProviderMediaName)\n row = cur.fetchone()\n mediaid = None\n while row:\n mediaid =row[0]\n break\n return mediaid\n\ndef main(messages_file, records):\n print ('> Messages: %s; Records: %d' % (messages_file, records))\n message_number = 0\n with open(messages_file, 'r') as msgs_file:\n for message in msgs_file:\n if message_number >= records and records > 0:\n break\n if message.startswith('> '):\n continue\n try:\n jsonMsg = json.loads(message)\n mediaid = getMediaId(jsonMsg['fileName'])\n if(mediaid != None):\n jsonMsg['domainFields']['lcmMediaId']=str(mediaid)\n print (json.dumps(jsonMsg))\n except (RuntimeError, TypeError, NameError):\n print ('> %s error' % message_number)\n message_number += 1\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\n 'messages_file', help='File with the messages to write. One message per line'\n )\n parser.add_argument(\n '--records', default=-1, help='Number of messages to read'\n )\n args = parser.parse_args()\n main(args.messages_file, int(args.records))\n","sub_path":"test/generateLCMMediaId.py","file_name":"generateLCMMediaId.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"223462154","text":"# -*- coding: UTF-8 -*-\n\n# 协程显示当前时间\n# Example of coroutine displaying the current date every second during 5 seconds using the sleep() function:\n\nimport asyncio\nimport datetime\n\nasync def display_date(loop):\n end_time=loop.time()+5.0\n while True:\n print(datetime.datetime.now())\n if loop.time()+1.0>end_time:\n break\n await asyncio.sleep(1)\n\nloop=asyncio.get_event_loop()\nloop.run_until_complete(display_date(loop))\nloop.close()","sub_path":"study/coroutine/coroutine1.py","file_name":"coroutine1.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"517711007","text":"\"\"\"add column domain_uuid\n\nRevision ID: ccf354a6e23a\nRevises: 1ca34807f018\nCreate Date: 2019-01-07 14:35:14.413207\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'ccf354a6e23a'\ndown_revision = '1ca34807f018'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('archived_domain', sa.Column('uuid', sa.Text(length=36), nullable=True))\n op.add_column('domain', sa.Column('uuid', sa.Text(length=36), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('domain', 'uuid')\n op.drop_column('archived_domain', 'uuid')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/ccf354a6e23a_add_column_domain_uuid.py","file_name":"ccf354a6e23a_add_column_domain_uuid.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"583542294","text":"from decouple import config\nfrom pathlib import Path\nimport dj_database_url\nimport os\n\n# Build paths inside the project like this: BASE_DIR / 'subdir'.\nBASE_DIR = Path(__file__).resolve().parent.parent\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = config('SECRET_KEY', default='django-insecure-dfv22x*65_x&xp_x@v$s*&ieo()*@3!*499lxdfaqgk$(gbw3x')\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = config('DEBUG', default=False, cast=bool)\n\nALLOWED_HOSTS = ['*']\n\n# Application definition\n\nINSTALLED_APPS = [\n 'home.apps.HomeConfig',\n 'user_profile.apps.UserProfileConfig',\n 'project.apps.ProjectConfig',\n\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\n # 3rd Party Libraries\n 'social_django', # Social Media Login\n 'crispy_forms', # Crispy Form for django\n 'phonenumber_field', # phone number field for whatsapp number\n 'rest_framework', # django rest framework\n]\n\nMIDDLEWARE = [\n # Middleware used for deployment on Heroku (Put it at the top)\n 'whitenoise.middleware.WhiteNoiseMiddleware',\n\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n\n # Middleware to handle Login through Social Media Platform requests\n 'social_django.middleware.SocialAuthExceptionMiddleware'\n]\n\nROOT_URLCONF = 'contrihub.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n\n # Context Preprocessors for Social media login\n 'social_django.context_processors.backends',\n 'social_django.context_processors.login_redirect'\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'contrihub.wsgi.application'\n\n# Database\n# https://docs.djangoproject.com/en/3.2/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': BASE_DIR / 'db.sqlite3',\n }\n}\nimport dj_database_url\n\ndb_from_env = dj_database_url.config()\nDATABASES['default'].update(db_from_env)\nDATABASES['default']['CONN_MAX_AGE'] = 500\n\n# Password validation\n# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n# Internationalization\n# https://docs.djangoproject.com/en/3.2/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'Asia/Kolkata'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/3.2/howto/static-files/\n\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'assets'),\n)\n\nSTATIC_URL = '/static/'\nSTATIC_ROOT = 'static'\nSTATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'\n\n# Default primary key field type\n# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field\n\nDEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'\n\nAUTHENTICATION_BACKENDS = (\n 'social_core.backends.github.GithubOAuth2', # for Github authentication\n 'django.contrib.auth.backends.ModelBackend', # Default Django Authentication Backend\n)\n\nSOCIAL_AUTH_GITHUB_KEY = config('SOCIAL_AUTH_GITHUB_KEY', default=\"\")\nSOCIAL_AUTH_GITHUB_SECRET = config('SOCIAL_AUTH_GITHUB_SECRET', default=\"\")\nSOCIAL_AUTH_GITHUB_SCOPE = [\n 'user:email', # For Reading user's email\n 'public_repo' # For creating issues by Admins and Mentors\n]\n\nLOGIN_URL = 'authorize'\nLOGOUT_URL = 'logout'\nLOGIN_REDIRECT_URL = 'home'\n\nCRISPY_TEMPLATE_PACK = 'bootstrap4'\n\n# Email Setup\nEMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\nEMAIL_HOST = config('EMAIL_HOST', default=\"\")\nEMAIL_PORT = config('EMAIL_PORT', default=\"\")\nEMAIL_HOST_USER = config('EMAIL_HOST_USER', default=\"\")\nEMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD', default=\"\")\nEMAIL_USE_TLS = config('EMAIL_USE_TLS', default=True, cast=bool)\nEMAIL_USE_SSL = config('EMAIL_USE_SSL', default=False, cast=bool)\n\nAVAILABLE_PROJECTS = config('AVAILABLE_PROJECTS', default=\"ContriHUB-21\",\n cast=lambda v: [s.strip() for s in v.split(',')])\nLABEL_MENTOR = config('LABEL_MENTOR', default=\"mentor\")\nLABEL_LEVEL = config('LABEL_LEVEL', default=\"level\")\nLABEL_POINTS = config('LABEL_POINTS', default=\"points\")\nLABEL_RESTRICTED = config('LABEL_RESTRICTED', default=\"restricted\")\nLABEL_BONUS = config('LABEL_BONUS', default=\"bonus\")\nDEPENDABOT_LOGIN = config('DEPENDABOT_LOGIN', default=\"dependabot[bot]\")\n\nMAX_SIMULTANEOUS_ISSUE = config('MAX_SIMULTANEOUS_ISSUE', default=2, cast=int)\n\nDAYS_PER_ISSUE_FREE = config('DAYS_PER_ISSUE_FREE', default=1, cast=int)\nDAYS_PER_ISSUE_VERY_EASY = config('DAYS_PER_ISSUE_VERY_EASY', default=1, cast=int)\nDAYS_PER_ISSUE_EASY = config('DAYS_PER_ISSUE_EASY', default=1, cast=int)\nDAYS_PER_ISSUE_MEDIUM = config('DAYS_PER_ISSUE_MEDIUM', default=2, cast=int)\nDAYS_PER_ISSUE_HARD = config('DAYS_PER_ISSUE_HARD', default=3, cast=int)\n\nDEFAULT_FREE_POINTS = config('DEFAULT_FREE_POINTS', default=0, cast=int)\nDEFAULT_VERY_EASY_POINTS = config('DEFAULT_VERY_EASY_POINTS', default=2, cast=int)\nDEFAULT_EASY_POINTS = config('DEFAULT_EASY_POINTS', default=10, cast=int)\nDEFAULT_MEDIUM_POINTS = config('DEFAULT_MEDIUM_POINTS', default=20, cast=int)\nDEFAULT_HARD_POINTS = config('DEFAULT_HARD_POINTS', default=30, cast=int)\n","sub_path":"contrihub/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":6527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"465861854","text":"# -*- coding: utf-8 -*-\nimport sys\nimport os\n\nlive_path = os.path.dirname(os.path.realpath(__file__))\ncore_path = os.path.split(live_path)[0]\nroot_path = os.path.split(core_path)[0]\nparent_path = os.path.split(root_path)[0]\nsys.path.append(parent_path)\n\nimport threading\nfrom tkinter import *\nimport tkinter.font as tkFont\nimport time\nimport grequests\nimport pandas as pd\nimport midas.bin.env as env\nfrom midas.core.data.engine import main_session\nimport midas.core.data.models as models\nfrom decimal import Decimal\nimport decimal\nfrom bs4 import BeautifulSoup\n\ntarget_symbols = [\n '603192',\n '603088',\n '600336',\n '605183',\n '002354',\n '603595'\n]\n\ntarget_symbols = list(set(target_symbols))\n\nclass Console():\n def __init__(self):\n self.init_market()\n self.root = Tk()\n self.root.title('Stars')\n # a = tkFont.families()\n # self.lbl = Label(self.root, fg='#00c66d', bg='#141624', justify=LEFT, text=\"\", font=tkFont.Font(family=\"Helvetica\", size=14)) #蓝绿\n # self.lbl = Label(self.root, fg='#00a99b', bg='#0e162f', justify=LEFT, text=\"\", font=tkFont.Font(family=\"Helvetica\", size=14)) #蓝蓝\n self.lbl = Label(self.root, fg='#a9b7c6', bg='#2b2b2b', justify=LEFT, text=\"\", font=tkFont.Font(family=\"Helvetica\", size=15)) # pycharm style\n self.display_msg = ''\n self.updateGUI()\n\n def init_market(self):\n symbol2code = {}\n self.stock_map = {}\n for stock in main_session.query(models.DailyBasic).all():\n ts_code = stock.ts_code\n market = ts_code.split('.')[1].lower()\n symbol = ts_code.split('.')[0]\n code = '{market}{symbol}'.format(market=market, symbol=symbol)\n symbol2code[symbol] = code\n\n if symbol.startswith('300'):\n limit_rate = 0.2\n elif symbol.startswith('301'):\n limit_rate = 0.2\n elif symbol.startswith('688'):\n limit_rate = 0.2\n else:\n limit_rate = 0.1\n\n self.stock_map[code] = {\n 'circ_mv': float(stock.circ_mv),\n 'limit_rate': limit_rate,\n }\n\n batch_size = 500\n self.req_list = []\n for i in range(0, len(target_symbols), batch_size):\n keys = []\n for symbol in target_symbols[i:i + batch_size]:\n try:\n query_key = symbol2code[symbol]\n keys.append(query_key)\n except Exception as e:\n continue\n\n self.req_list.append(grequests.get('http://hq.sinajs.cn/list={}'.format(','.join(keys))))\n\n def update_market(self):\n responses = grequests.map(self.req_list)\n # print('====== {} ======'.format(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())))\n displays = []\n for response in responses:\n res = response.text.strip().split(';\\n')\n for i in res:\n try:\n j = i.split(',')\n name = j[0].split('=\"')[1]\n code = j[0].split('=\"')[0].split('_')[-1]\n symbol = code[2:]\n yesterday_closing_price = float(j[2])\n current_price = float(j[3])\n today_max_price = float(j[4])\n buy_one_price = float(j[6])\n buy_one_vol = float(j[10])\n vol = float(j[8]) / 100\n\n limit_rate = self.stock_map[code]['limit_rate']\n # today_limit_price = round(yesterday_closing_price * (1 + limit_rate), 2)\n today_limit_price = Decimal(str(yesterday_closing_price * (1 + limit_rate))).quantize(Decimal('0.00'), rounding=decimal.ROUND_HALF_UP)\n today_limit_price = float(today_limit_price)\n\n chg = (current_price / yesterday_closing_price - 1)\n chg_rate = chg / limit_rate\n\n chg_display = '{}%'.format(round(chg * 100, 2))\n circ_mv = self.stock_map[code]['circ_mv']\n\n # last_vol = self.symbol2vol[symbol]\n # vol_rate = round(vol / last_vol, 2)\n\n type = 1\n if today_max_price == today_limit_price: # 摸过板的\n # if_display = True\n if buy_one_price < today_limit_price: # 开板\n # if_display = True\n type = 3\n elif buy_one_price * buy_one_vol < 10000000: # 封单小于1kw\n # if_display = True\n type = 4\n else:\n # if_display = True\n type = 5\n elif chg > 0.7 * limit_rate:\n # if_display = True\n type = 1\n\n if type == 1:\n displays.append({\n 'note': '{code} {name:4}\\t {chg}\\t {price}\\t {circ_mv}亿\\t 未板'.format(code=code, name=name, chg=chg_display,\n price=round(current_price, 2), circ_mv=int(circ_mv)),\n 'chg_rate': chg_rate\n })\n elif type == 2:\n displays.append({\n 'note': '{code} {name:4}\\t {chg}\\t {price}\\t {circ_mv}亿\\t {buy_one_vol}手'.format(code=code, name=name, chg=chg_display,\n price=round(current_price, 2), circ_mv=int(circ_mv), buy_one_vol=int(buy_one_vol / 100)),\n 'chg_rate': chg_rate\n })\n elif type == 3:\n displays.append({\n 'note': '{code} {name:4}\\t {chg}\\t {price}\\t {circ_mv}亿\\t ***'.format(code=code, name=name, chg=chg_display,\n price=round(current_price, 2), circ_mv=int(circ_mv)),\n 'chg_rate': chg_rate\n })\n elif type == 4:\n displays.append({\n 'note': '{code} {name:4}\\t {chg}\\t {price}\\t {circ_mv}亿\\t {cost}万 <<<<<<'.format(code=code, name=name, chg=chg_display,\n price=round(current_price, 2), circ_mv=int(circ_mv), cost=round(buy_one_price * buy_one_vol / 10000, 1)),\n 'chg_rate': chg_rate\n })\n elif type == 5:\n displays.append({\n 'note': '{code} {name:4}\\t {chg}\\t {price}\\t {circ_mv}亿\\t {cost}万'.format(code=code, name=name, chg=chg_display,\n price=round(current_price, 2), circ_mv=int(circ_mv), cost=round(buy_one_price * buy_one_vol / 10000, 1)),\n 'chg_rate': chg_rate\n })\n\n except Exception as e:\n continue\n\n displays.sort(key=lambda x: x['chg_rate'], reverse=True)\n displays = displays[:50]\n notes = [i['note'] for i in displays]\n self.display_msg = '====== {} ======\\n'.format(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n self.display_msg += '\\n'.join(notes)\n\n def run(self):\n self.lbl.pack()\n self.lbl.after(1000, self.updateGUI)\n self.root.mainloop()\n\n def updateGUI(self):\n time_a = time.time()\n self.update_market()\n self.lbl[\"text\"] = self.display_msg\n self.root.update()\n time_b = time.time()\n cost = time_b - time_a\n self.lbl.after(1000 - int(cost * 1000), self.updateGUI)\n\n\nif __name__ == \"__main__\":\n Console().run()","sub_path":"core/live/_0x27_Stars_Console.py","file_name":"_0x27_Stars_Console.py","file_ext":"py","file_size_in_byte":7850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"420593935","text":"import torch\nfrom torch.utils.data.sampler import Sampler\n\nclass LossBasedSampler(Sampler):\n ########################################################\n ###### Samples batches randomly, with replacement ######\n ###### Items in batch are not shuffled ######\n ###### Weights samples based on loss score ######\n ###### Weights can be updated after each epoch ######\n ########################################################\n\n def __init__(self, data_source, batch_size, weights):\n self.data_len = len(data_source)\n self.batch_size = batch_size\n self.indices = self.find_valid_indices(set(data_source.video_metadata.values()))\n \n weights = [weights[i] for i in self.indices]\n\n self.weights = torch.tensor(weights, dtype=torch.double)\n\n\n def __iter__(self):\n # for i in self.indices:\n # yield list(range((i + 1) - self.batch_size, i + 1))\n\n for i in torch.multinomial(self.weights, num_samples=len(self.indices), replacement=True):\n idx = self.indices[i]\n yield list(range((idx + 1) - self.batch_size, idx + 1))\n\n\n def __len__(self):\n return len(self.indices)\n\n\n def find_valid_indices(self, video_boundaries):\n invalid = set()\n for boundary_index in video_boundaries:\n invalid |= {i for i in range(boundary_index, boundary_index + (self.batch_size - 1))}\n\n valid_indices = [i for i in range(self.data_len) if i not in invalid]\n return [valid_indices[i] for i in torch.randperm(len(valid_indices))]\n\n\n## torch.multinomial\n # each row in return tensor has num_samples\n # tensor row contains indices drawn from probability distribution of input tensor\n # have to set replacement to True\n # if input is a single vector, output is also a single vector","sub_path":"src/utils/loss_based_sampler.py","file_name":"loss_based_sampler.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"447315586","text":"import sys\nimport json\nimport requests\nimport os\n\n\nclass FlyBy(object):\n\n def __init__(self, endpoint):\n self.endpoint = endpoint\n\n def _get_config(self, name):\n response = requests.get(\n \"{}/service/{}\".format(\n self.endpoint, name\n )\n )\n if response.status_code == 200:\n return response.json()\n raise Exception(response.text)\n\n def _set_config(self, service):\n response = requests.post(\n \"{}/service\".format(self.endpoint),\n json=service\n )\n if response.status_code == 200:\n return response.json()\n raise Exception(response.text)\n\n def _delete_config(self, name):\n response = requests.delete(\n \"{}/service/{}\".format(\n self.endpoint, name\n )\n )\n if response.status_code == 200:\n return dict(service_name=name)\n raise Exception(response.text)\n\n def _create_or_update_target_group(self, data):\n response = requests.post(\n \"{}/target\".format(\n self.endpoint\n ),\n json=data\n )\n if response.status_code == 200:\n return response.json()\n raise Exception(response.text)\n\n def _delete_target_group(self, name, tg_name):\n response = requests.delete(\n \"{}/target/{}/{}\".format(\n self.endpoint, name, tg_name\n )\n )\n if response.status_code == 200:\n return response.json()\n raise Exception(response.text)\n\n def create_or_update(self, data):\n try:\n service = self._get_config(data[\"name\"])\n except:\n service = {}\n target_groups = data.pop(\"target_groups\", None)\n service.update(data)\n response = self._set_config(service)\n if target_groups is not None:\n for tg in service.get(\"target_groups\", []):\n exists = bool(filter(\n lambda g: g[\"target_group_name\"] == tg[\"target_group_name\"],\n target_groups\n ))\n if not exists:\n # self._delete_target_group(data[\"name\"], tg[\"target_group_name\"])\n pass\n for tg in target_groups:\n self._create_or_update_target_group(dict(\n service_name=data[\"name\"],\n target_group_name=tg[\"target_group_name\"],\n weight=tg.get(\"weight\", 0)\n ))\n return response\n\n def delete(self, data):\n return self._delete_config(data[\"name\"])\n\n def set_weights(self, data):\n return self.create_or_update(data)\n\n\ndef ca_bundle():\n \"\"\"\n If https endpoints are required for flyby/ground-control, it may be necessary\n to pass in the CA certificate, e.g. for internally signed certificates.\n\n See http://docs.python-requests.org/en/master/user/advanced/ for further details.\n \"\"\"\n if 'ROOT_CA' in os.environ:\n root_ca = os.environ['ROOT_CA'].replace('\\t', \"\")\n certs_file = os.environ.get('CA_FILE', '/etc/ssl/certs/ca-certificates.crt')\n with open(certs_file, 'a') as certs:\n certs.write(root_ca)\n os.environ['REQUESTS_CA_BUNDLE'] = certs_file\n\n\nif __name__ == '__main__':\n ca_bundle()\n payload = json.loads(sys.argv[-1])\n print(json.dumps(\n getattr(FlyBy(payload[\"endpoint\"]), payload[\"action\"])(payload[\"data\"])\n ))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"242152691","text":"\"\"\" 623. K Edit Distance\nhttps://www.jiuzhang.com/solution/k-edit-distance/#tag-other-lang-python\n\"\"\"\n\n\nclass TrieNode:\n def __init__(self):\n self.children = {}\n self.is_word = False\n self.word = None\n\n\nclass Trie:\n def __init__(self):\n self.root = TrieNode()\n\n def insert(self, word):\n if word is None:\n return\n cur = self.root\n for ch in word:\n if ch not in cur.children:\n cur.children[ch] = TrieNode()\n cur = cur.children[ch]\n cur.is_word = True\n cur.word = word\n\n\nclass Solution:\n \"\"\"\n @param words: a set of stirngs\n @param target: a target string\n @param k: An integer\n @return: output all the strings that meet the requirements\n \"\"\"\n\n def kDistance(self, words, target, k):\n if not words or target is None:\n return []\n N = len(target)\n\n trie = Trie()\n for word in words:\n trie.insert(word)\n\n dp = [j for j in range(N+1)]\n results = []\n self.dfs(target, k, N, trie.root, dp, results)\n return results\n\n def dfs(self, target, k, N, node, dp, results):\n if dp[N] <= k and node.is_word:\n results.append(node.word)\n\n next = [0 for _ in range(N+1)]\n # try all branches of node\n for c in node.children:\n next[0] = dp[0] + 1\n for i in range(1, N+1):\n if target[i - 1] == c:\n next[i] = min(dp[i-1], dp[i]+1, next[i-1]+1)\n else:\n next[i] = min(dp[i-1]+1, dp[i]+1, next[i-1]+1)\n self.dfs(target, k, N, node.children[c], next, results)\n\n\ndef main():\n words = [\"abc\", \"abd\", \"abcd\", \"adc\"]\n target = 'ac'\n k = 1\n ans = Solution().kDistance(words, target, k)\n print(ans)\n\n\nmain()\n","sub_path":"lint-623-k-edit-distance/solution2.py","file_name":"solution2.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"351317352","text":"#!/usr/bin/env python3\n\"\"\"\nCBOW module\n\"\"\"\nfrom sklearn.feature_extraction.text import CountVectorizer\n\n\ndef bag_of_words(sentences, vocab=None):\n \"\"\"\n creates a bag of words embedding matrix:\n - sentences: list of sentences to analyze\n - vocab: list of the vocabulary words to use for the analysis\n If None, all words within sentences should be used\n Returns: embeddings, features\n - embeddings: numpy.ndarray of shape (s, f) containing\n the embeddings\n - s: number of sentences in sentences\n - f: number of features analyzed\n features is a list of the features used for embeddings\n \"\"\"\n vector = CountVectorizer(vocabulary=vocab)\n X = vector.fit_transform(sentences)\n features = vector.get_feature_names()\n embeddings = X.toarray()\n\n return embeddings, features\n","sub_path":"supervised_learning/0x0F-word_embeddings/0-bag_of_words.py","file_name":"0-bag_of_words.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"137931103","text":"from io import StringIO, BytesIO\nfrom ftplib import FTP, FTP_TLS, error_perm\nimport logging\nimport ssl\nimport os\nimport paramiko\nimport stat\n\nloglevel_env = os.environ.get(\"LOGLEVEL\", \"INFO\")\n\nlogger = logging.getLogger(\"http-ftp-proxy-microservice\")\nparamikologger = logging.getLogger(\"paramiko\")\nparamikologger.setLevel(loglevel_env)\nparamikologger.addHandler(logging.StreamHandler())\nclass MyFTP_TLS(FTP_TLS):\n \"\"\"Explicit FTPS, with shared TLS session\"\"\"\n\n def ntransfercmd(self, cmd, rest=None):\n conn, size = FTP.ntransfercmd(self, cmd, rest)\n if self._prot_p:\n session = self.sock.session\n if isinstance(self.sock, ssl.SSLSocket):\n session = self.sock.session\n conn = self.context.wrap_socket(\n conn, server_hostname=self.host,\n session=session) # this is the fix\n return conn, size\n\n\nclass FTPClient():\n \"\"\"FTP Client\"\"\"\n\n def __init__(self, user, pwd, ftp_url):\n logger.debug(\"ftp connecting to {} with {}\".format(ftp_url, user))\n try:\n self.client = FTP(ftp_url)\n self.client.login(user, pwd)\n except Exception as e:\n raise e\n\n def test(self):\n return self.client.retrlines(\"LIST\")\n\n def get_stream(self, fpath):\n \"\"\"return a file stream\"\"\"\n r = BytesIO()\n logger.debug(\"fetching {}\".format(fpath))\n self.client.retrbinary(\"RETR {}\".format(fpath), r.write)\n return r\n\n def put(self, fpath, stream):\n return self.client.storbinary(\"STOR {}\".format(fpath), BytesIO(stream))\n\n def get_content(self, fpath):\n \"\"\"return file as string\"\"\"\n resp = self.get_stream(fpath)\n return resp.getvalue()\n\n def rename(self, fromname, toname):\n return self.client.rename(fromname, toname)\n\n def get_type(self, fpath):\n \"\"\"\n Dont rely on LIST output due to diversity of result formats.\n DIR, if \"cd {path}\" command works\n FILE, if \"ls {path}\" command works\n None, otherwise\n \"\"\"\n type = None\n pwd = self.client.pwd()\n try:\n cwd = self.client.cwd(fpath)\n type = \"DIR\"\n except error_perm as e:\n ls_lines = []\n self.client.retrlines(\"LIST {}\".format(fpath), ls_lines.append)\n if len(ls_lines) == 1:\n type = \"FILE\"\n finally:\n self.client.cwd(pwd)\n return type\n\n def dir(self, fpath):\n listing_retrieved = []\n listing_2return = []\n self.client.retrlines(\"NLST {}\".format(fpath),\n listing_retrieved.append)\n for file in listing_retrieved:\n type = self.get_type(file)\n listing_2return.append({\n \"filename\": file,\n \"type\": self.get_type(file)\n })\n if type == \"DIR\":\n listing_2return += self.dir(file)\n return listing_2return\n\n def quit(self):\n self.client.quit()\n\n def set_debuglevel(self,level: int):\n self.client.set_debuglevel(level)\n\n\nclass FTPSClient(FTPClient):\n \"\"\"FTPS Client\"\"\"\n\n def __init__(self, user, pwd, ftp_url):\n logger.debug(\"ftps connecting to {} with {}\".format(ftp_url, user))\n try:\n self.client = MyFTP_TLS(ftp_url)\n self.client.login(user, pwd)\n self.client.prot_p()\n self.client.set_pasv(True)\n except Exception as e:\n raise e\n\n\nclass SFTPClient():\n \"\"\"SFTP Client\"\"\"\n\n def __init__(self, user, pwd, ftp_url):\n logger.debug(\"sftp connecting to {} with {}\".format(ftp_url, user))\n try:\n self.transport = paramiko.Transport((ftp_url, 22))\n self.transport.connect(username=user, password=pwd)\n self.client = paramiko.SFTPClient.from_transport(self.transport)\n except Exception as e:\n raise e\n\n def get_stream(self, fpath):\n \"\"\"return file as string\"\"\"\n r = BytesIO()\n resp = self.client.getfo(fpath, r)\n return r\n\n def put(self, fpath, stream):\n resp = self.client.putfo(BytesIO(stream), fpath)\n return str(resp)\n\n def get_type(self, fpath):\n type = None\n file_stat = None\n try:\n file_stat = self.client.stat(fpath).st_mode\n if stat.S_ISDIR(file_stat):\n type = \"DIR\"\n else:\n type = \"FILE\"\n except Exception as e:\n if fpath == \"\":\n type = \"DIR\"\n else:\n type = None\n return type\n\n def dir(self, fpath):\n listing_2return = []\n listing_retrieved = []\n try:\n listing_retrieved = self.client.listdir(fpath)\n except IOError as e:\n None\n if fpath == \".\":\n dir_path = \"\"\n else:\n dir_path = fpath + \"/\"\n for file in listing_retrieved:\n full_path = dir_path + file\n type = self.get_type(full_path)\n listing_2return.append({\"filename\": full_path, \"type\": type})\n if type == \"DIR\":\n listing_2return += self.dir(full_path)\n return listing_2return\n\n def rename(self, fromname, toname):\n self.client.rename(fromname, toname)\n\n def quit(self):\n self.client.close()\n \n def set_debuglevel(self,level: int):\n pass # Use sepperat logger and os env LOGLEVEL\n\n","sub_path":"service/ftp_client.py","file_name":"ftp_client.py","file_ext":"py","file_size_in_byte":5493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"180166969","text":"import sys\n# sys.stdin=open(\"input.txt\", \"r\")\n\ndef DFS(L, sum, tsum):\n global result\n if sum+(total-tsum)c:\n return\n if L==n:\n if sum>result:\n result=sum\n else:\n DFS(L+1, sum+a[L], tsum+a[L])\n DFS(L+1, sum, tsum+a[L])\n\n\nif __name__==\"__main__\":\n c, n=map(int, input().split())\n a=[0]*n\n result=-2147000000\n for i in range(n):\n a[i]=int(input())\n total=sum(a)\n DFS(0, 0, 0)\n print(result)\n\n\n'''Time Limit Code (me)\ndef DFS(i):\n global max, sum\n if i == n:\n for j in range(n):\n if a[j][1]==1:\n sum+=a[j][0]\n if max31:\n free = 0\n self._free = free\n return style\n\n def write(self, text, c=None):\n \"\"\"\n Add the text to the end of the control using color c which\n should be suitable for feeding directly to wx.NamedColour.\n\n 'text' should be a unicode string or contain only ascii data.\n \"\"\"\n style = self.getStyle(c)\n lenText = len(text.encode('utf8'))\n end = self.control.GetLength()\n## self.control.DocumentEnd()\n self.control.AppendTextRaw(text)\n## self.control.AddStyledText(text)\n self.control.StartStyling(end, 31)\n self.control.SetStyling(lenText, style)\n self.control.EnsureCaretVisible()\n self.control.onUpdateUI(None)\n\n __call__ = write","sub_path":"src/Gui/pnlScript.py","file_name":"pnlScript.py","file_ext":"py","file_size_in_byte":6836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"589499117","text":"import random\nimport datetime\nimport pytz\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand, CommandError\nfrom django.db import Error, transaction, connection\nfrom trade.models import Trader, Deal, Transaction\n\nfrom elizabeth import Generic\n\n\nel = Generic('en')\n\n\nclass Command(BaseCommand):\n def add_arguments(self, parser):\n parser.add_argument('--traders', type=int, default=100, required=False)\n parser.add_argument('--deals', type=int, default=100, required=False)\n parser.add_argument('--transactions', type=int, default=10, required=False)\n\n @staticmethod\n def random_datetime():\n '''tz-aware random datetime within last 10 days'''\n return pytz.timezone(settings.TIME_ZONE).localize(\n datetime.datetime.combine(\n datetime.date.today() - datetime.timedelta(days=random.randint(0, 9)),\n datetime.time(random.randint(0, 23), random.randint(0, 59))\n )\n )\n\n def handle(self, *args, **options):\n try:\n with connection.cursor() as c:\n c.execute('TRUNCATE TABLE trade_trader CASCADE')\n\n with transaction.atomic():\n for i in range(options['traders']):\n trader = Trader(\n name=el.personal.full_name(),\n balance=random.randint(100, 1000)\n )\n trader.save()\n\n for j in range(options['deals']):\n deal = Deal(\n trader=trader,\n amount=random.randint(1, 10),\n result_amount=random.randint(-9, 10),\n datetime=Command.random_datetime()\n )\n deal.save()\n\n for j in range(options['transactions']):\n trans = Transaction(\n trader=trader,\n amount=random.randint(10, 100),\n type=random.randint(1, 2),\n datetime=Command.random_datetime()\n )\n trans.save()\n\n except Error as e:\n raise CommandError('Database error: {}'.format(e))\n\n self.stdout.write('Success')\n","sub_path":"trade/management/commands/test_data.py","file_name":"test_data.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"139082022","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport sys\n\n# get filename\nfilename = 'weak_scaling/mpi_lt_weak_scaling.dat'\n\n# load data\ndata_serial = np.loadtxt('serial/serial_vec.dat') # time, size, error\nt1 = data_serial[1,0]\ndata = np.loadtxt(filename) # number of omp threads, time, size, error\n#t1 = data[0,1]\n\nif len(data[0]) > 3: # with error\n plt.errorbar(data[:,0], t1/data[:,1], yerr=data[:,3])#, label='%d mpi-tasks, N = %d' % (data[i*count,0], data[i*count,3]))\nelse: # without error\n plt.plot(data[:,0], t1/data[:,1])#, label='%d mpi-tasks, N = %d' % (data[i*count,0], data[i*count,3]))\n\n# annotate with size\nfor i in range(0,len(data)):\n plt.annotate('%d' % data[i,2], xy=(data[i,0],t1/data[i,1]))\n\nsize = filename.split('_')[-1].split('.',1)[0]\n\n# plot linear speedup line\nplt.plot([0,data[-1,0]], [1,1], label='Linear weak scaling', color='#BDBDBD', linestyle='--')\n\nplt.xlabel('x times processes and original size (N=1024)')\nplt.ylabel(r'$t_{1} / t_{n}$')\nplt.title('Weak scaling of MPI version') # % parallel_type)\n#plt.legend()\nplt.xlim(xmin=0, xmax=data[-1,0]) #, xmax=18)\nplt.ylim(ymax=1.05)\n\nplt.savefig('weak_scaling/mpi_weak_scaling.pdf')\nplt.show()\n","sub_path":"timings_all/plot_weak_scaling_mpi.py","file_name":"plot_weak_scaling_mpi.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"589156600","text":"import cv2\nimport argparse\n\nfrom videohandler.videoutil import *\nfrom recognition.object_tracking import *\nimport recognition.recognition_conf as recg_conf\n\n# Merge frames into a single frame to display\ndef merge_2x2frames(frame_list): # If # of frames > 4, ignored\n\tglobal h, w\n\t(h, w) = frame_list[0].shape[:2]\n\tzeros = np.zeros((h, w, 3), dtype=\"uint8\")\n\n\tf = []\n\tfor idx in xrange(4):\n\t\tif idx < len(frame_list):\n\t\t\tf.append(frame_list[idx])\n\t\telse:\n\t\t\tf.append(zeros)\n\n\tmerged = np.zeros((h*2, w*2, 3), dtype=\"uint8\")\n\tmerged[0:h, 0:w] = f[0]\n\tmerged[0:h, w:w*2] = f[1]\n\tmerged[h:h*2, 0:w] = f[2]\n\tmerged[h:h*2, w:w*2] = f[3]\n\n\treturn merged\n\n# Convert points to the frame wise\ndef convert_points_on_2x2_frame(x, y):\n\tglobal h, w # Set in merge_2x2frames\n\n\tif x > w:\n\t\tx -= w\n\tif y > h:\n\t\ty -= h\n\n\treturn (x, y)\n\n# Draw path with lines\ndef draw_path(frame, path):\n\tfor i in xrange(1, len(path)):\n\t\tcv2.line(frame, path[i - 1], path[i], (0, 0, 255), 1)\n\n# Mouse handler for the window\ndef mouse_handler(event, x, y, flags, param):\n\tglobal line_start, line_end, line_based_counter\n\n\tif event == cv2.EVENT_LBUTTONDOWN:\n\t\tline_end = None\n\t\tline_based_counter.set_reference_line(None)\n\t\tline_start = convert_points_on_2x2_frame(x, y)\n\n\tif event == cv2.EVENT_LBUTTONUP:\n\t\tline_end = convert_points_on_2x2_frame(x, y)\n\nif __name__ == '__main__':\n\t# construct the argument parse and parse the arguments\n\tap = argparse.ArgumentParser()\n\tap.add_argument(\"-v\", \"--video\",\n\t\thelp=\"path to the (optional) video file\")\n\tap.add_argument(\"-r\", \"--record_video\",\n\t\thelp=\"path to the video file to write (optional)\")\n\tap.add_argument(\"-t\", \"--record_track\", action='store_true',\n\t\thelp=\"record video with the tracking result (valid only if -r is given, optional)\", required=False)\n\tap.add_argument(\"-f\", \"--print_verbose\", action='store_true',\n\t\thelp=\"print the frame number, optional)\", required=False)\n\n\targs = vars(ap.parse_args())\n\trecord_track = args.get(\"record_track\", False)\n\tprint_verbose = args.get(\"print_verbose\", False)\n\n\t# Setup VideoStream (camera or video file) & Writer\n\tvideo_handler = TEVideoHandler()\n\tif args.get(\"video\", False): # if a video path was not supplied, grab the reference to the picamera\n\t\tvideo_handler.initialize_with_file(args[\"video\"])\n\telse:\n\t\tvideo_handler.initialize_with_configured_cam()\n\n\tvideo_writer = TEVideoWriter()\n\tif (args.get(\"record_video\", False)): # to record a video\n\t\tvideo_writer.open(args[\"record_video\"])\n\n\t# Setup user interface\n\tline_start = None\n\tline_end = None\n\tWINDOW_NAME = \"Triton Eye\"\n\tcv2.namedWindow(WINDOW_NAME)\n\tcv2.setMouseCallback(WINDOW_NAME, mouse_handler)\n\n\t# Setup image processing classes\n\tobject_tracker = TEObjectTracker()\n\tline_based_counter = TELineBasedCounter()\n\tcount_in = 0\n\tcount_out = 0\n\n\t# Frame stream processing\n\tnum_frames = 0\n\twhile True:\n\t\t# READING STREAM\n\t\ttry:\n\t\t\tframe = video_handler.read()\n\t\texcept TEInvalidFrameException as e:\n\t\t\tprint(\"Invalid frame exception: maybe it reaches to the end of the file.\")\n\t\t\tbreak\n\n\t\t# Make a copy of the original frame\n\t\toriginal_frame = frame.copy()\n\t\tframe_result = frame.copy()\n\n\t\t# Find objects & show into the frame\n\t\tcontours, frame_mask, frame_post = object_tracker.feed_frame(frame)\n\t\tframe_mask = cv2.cvtColor(frame_mask, cv2.COLOR_GRAY2BGR) \n\t\tframe_post = cv2.cvtColor(frame_post, cv2.COLOR_GRAY2BGR) \n\n\t\tfor cnt in contours:\n\t\t\trect = cv2.minAreaRect(cnt)\n\t\t\tbox = cv2.boxPoints(rect)\n\t\t\tbox_draw = np.int0(box)\n\t\t\tcv2.drawContours(frame, [box_draw], 0, (0, 0, 255), 2)\n\t\t\tcv2.drawContours(frame_mask, [box_draw], 0, (0, 0, 255), 2)\n\t\t\tcv2.drawContours(frame_post, [box_draw], 0, (0, 0, 255), 2)\n\t\t\tcv2.drawContours(frame, [cnt], -1, (0, 255, 0), 2)\n\n\t\t# Draw the result frame with paths\n\t\ttracked_objects = object_tracker.get_tracked_objects()\n\t\tfor sobj in tracked_objects:\n\t\t\tdraw_path(frame_result, sobj.position_list)\n\t\t\tcv2.drawContours(frame_result, [sobj.prev_contour], -1, (0, 255, 0), 2)\n\t\t\tpos = sobj.position_list[-1]\n\t\t\tcv2.putText(frame_result, sobj.ID, pos, cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 0, 0), 1)\n\n\t\t# Update line counter\n\t\tif line_start is not None and line_end is not None and not line_based_counter.is_line_set():\n\t\t\tline_based_counter.set_reference_line((line_start, line_end))\n\t\tcrossing_objects = line_based_counter.feed_objects(tracked_objects)\n\t\tif len(crossing_objects) > 0:\n\t\t\tif print_verbose:\n\t\t\t\tprint(crossing_objects)\n\n\t\t\tfor co in crossing_objects:\n\t\t\t\tif co[1] == True:\n\t\t\t\t\tcount_in += 1\n\t\t\t\telse:\n\t\t\t\t\tcount_out += 1\n\n\t\t# Draw user-defined line\n\t\tif line_start is not None and line_end is not None:\n\t\t\tcv2.line(frame_result, line_start, line_end, (0, 255, 255), 2)\n\n\t\t# After PROCESSING: show the frame to our screen\n\t\tmerged_frame = merge_2x2frames([frame, frame_mask, frame_post, frame_result])\n\t\tif count_in > 0 or count_out > 0:\n\t\t\tcv2.putText(merged_frame, \"IN: \" + str(count_in) + \" OUT: \" + str(count_out),\n\t\t\t\t(20, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 255), 2)\n\t\tcv2.imshow(WINDOW_NAME, merged_frame)\n\n\t\t# record video\n\t\tif video_writer.isopened():\n\t\t\tif record_track:\n\t\t\t\tvideo_writer.record(merged_frame)\n\t\t\telse:\n\t\t\t\tvideo_writer.record(original_frame)\n\n\t\t# if the 'q' key is pressed, stop the loop\n\t\tkey = cv2.waitKey(1) & 0xFF\n\t\tif key == ord(\"q\"):\n\t\t\tbreak\n\n\t\tif print_verbose:\n\t\t\tprint(num_frames)\n\t\tnum_frames += 1\n\n\t# After pressing q (or the end of the frame)\n\t# cleanup the camera and close any open windows\n\tvideo_handler.release()\n\tvideo_writer.release()\n\tcv2.destroyAllWindows()\n","sub_path":"src/triton_eye.py","file_name":"triton_eye.py","file_ext":"py","file_size_in_byte":5487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"346752925","text":"import random\r\n\r\nimport numpy\r\nimport numpy as np\r\nfrom tensorflow import keras\r\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\r\n\r\n\r\ndef prerpareDatasets(t,dataset):\r\n (tokenized, length) = t.tokenize([move.split('.')[1] for move in dataset.split(' ') if len(move.split('.'))>1])\r\n if len(tokenized)!=0:\r\n numb = random.randint(0,len(tokenized)-1)\r\n token = tokenized[:numb]\r\n y = tokenized[numb]\r\n print(token.shape)\r\n return token, y\r\n return None,None\r\ndef getData(t,start,end):\r\n s = open(\"C:\\\\Users\\\\RP\\\\PycharmProjects\\\\ChessAppAI\\\\f.txt\", \"r\").read().split('\\n')[start:end]\r\n x, y = list(), list()\r\n for element in s:\r\n x1, y1 = prerpareDatasets(t, element)\r\n if x1 is not None:\r\n x.append(x1)\r\n y.append(y1)\r\n x = keras.preprocessing.sequence.pad_sequences(x)\r\n y = keras.preprocessing.sequence.pad_sequences(y)\r\n return x,y\r\ndef prepareFit(t,fit):\r\n (tokenized, length) = t.tokenize([move.split('.')[1] for move in fit.split(' ') if len(move.split('.'))>1])\r\n token = tokenized[:]\r\n token = keras.preprocessing.sequence.pad_sequences(token)\r\n token = token[numpy.newaxis, ...]\r\n return token","sub_path":"ChessAppAI/DSManip.py","file_name":"DSManip.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"532357749","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nEn_name = []\r\ndef get_name():\r\n link = 'https://movie.douban.com/top250'\r\n headers = {\r\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',\r\n 'Host':'https://movie.douban.com/'\r\n }\r\n r = requests.get(link,headers=headers)\r\n soup = BeautifulSoup(r.text,'html.parser')\r\n name = soup.find_all('div',class_='hd').a.span[2].text.strip()\r\n print(name)\r\nget_name()","sub_path":"豆瓣top250.py","file_name":"豆瓣top250.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"395040056","text":"from airflow.models import BaseOperator\nfrom airflow.models import Variable\nfrom airflow.utils.decorators import apply_defaults\nfrom airflow.contrib.hooks.aws_hook import AwsHook\n\nimport os\nfrom pyfmpcloud import settings\nfrom pyfmpcloud import stock_time_series as sts\n\naws_hook = AwsHook(\"aws_credentials\")\ncredentials = aws_hook.get_credentials()\naccess_key = credentials.access_key\nsecret_key = credentials.secret_key\nos.environ['AWS_ACCESS_KEY_ID']=access_key\nos.environ['AWS_SECRET_ACCESS_KEY']=secret_key\n\nAPI_KEY = Variable.get('API_KEY')\nsettings.set_apikey(API_KEY)\nbucket = Variable.get('s3_bucket')\n\n\"\"\"\nimport pandas as pd\nimport findspark\nfindspark.init('/home/just/spark-3.0.0-bin-hadoop2.7')\nfrom pyspark.sql import SparkSession\n\"\"\"\n\nclass GetSymbolList(BaseOperator):\n\n ui_color = '#F98866'\n\n @apply_defaults\n def __init__(self,\n call = None,\n *args, **kwargs):\n super(GetSymbolList, self).__init__(*args, **kwargs)\n self.call = call\n\n def execute(self, context):\n self.log.info(\"Getting symbol_list\")\n\n \"\"\"\n spark = SparkSession.builder.appName('symbol_list').getOrCreate()\n self.log.info(\"Spark session Created\")\n \"\"\"\n\n\n symbol_list = sts.symbol_list()\n\n symbol_list = symbol_list.head(5)\n\n self.log.info(\"Symbol List data retrieved from API\")\n\n symbol_list.to_parquet('{}symbol_list.parquet.gzip'.format(bucket))\n #symbol_list.to_csv('{}symbol_list.csv'.format(bucket))\n\n\n \"\"\"\n dfo = symbol_list.select_dtypes('object').astype(str)\n dfn = symbol_list.select_dtypes(exclude='object').astype(str)\n df = dfo.merge(dfn, left_index=True, right_index=True ,how='inner')\n sdf = spark.createDataFrame(df)\n\n sdf.write.mode(\"overwrite\").parquet(bucket + 'symbol_list')\n self.log.info(\"File saved to {} bucket\".format(bucket))\n\n spark.stop()\n self.log.info(\"Spark session Closed\")\n \"\"\"\n","sub_path":"dag/Operators/get_symbol_list.py","file_name":"get_symbol_list.py","file_ext":"py","file_size_in_byte":1993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"87791017","text":"\n# coding: utf-8\n\n# In[1]:\n\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nget_ipython().magic('matplotlib inline')\n\n\n# In[2]:\n\nnp.random.seed(1000)\ny = np.random.standard_normal(20)\n\n\n# In[7]:\n\nx = range(len(y))\n#plt.plot(x, y)\nplt.plot(y)\n\n\n# In[8]:\n\nplt.plot(y.cumsum())\nplt.grid(True)\nplt.axis('tight')\n\n\n# In[9]:\n\nplt.plot(y.cumsum())\nplt.grid(True)\nplt.xlim(-1,20)\nplt.ylim(np.min(y.cumsum()) - 1, np.max(y.cumsum()) + 1)\n\n\n# In[10]:\n\nplt.figure(figsize=(7, 4))\n# the figsize parameter defines the size of the figure in(width, height)\nplt.plot(y.cumsum(), 'b', lw=1.5)\nplt.plot(y.cumsum(), 'ro')\nplt.grid(True)\nplt.axis('tight')\nplt.xlabel('index')\nplt.ylabel('value')\nplt.title('A Simple Plot')\n\n\n# In[ ]:\n\n\n\n","sub_path":"graph/one_dimension.py","file_name":"one_dimension.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"198652303","text":"# coding: utf-8\n\n\"\"\"\n Fetch clean MUPS valve temperature telemetry\n\n This makes use of the temperature correction code provided by Scott Blanchard (to correct\n for a resistor dropout in the thermistor data) and xija thermal model developed by\n Matt Dahmer.\n\n The basic cleaning algorithm is very simple:\n\n - Fetch raw telemetry from the cheta archive.\n - Compute a xija thermal model prediction for the same timespan (actually starting a few\n days in advance to burn out uncertainty in the pseudo-node value).\n - Accept either raw telemetry or corrected data which are within a tolerance (5 degF) of\n the model.\n - In the gaps where the model diverges from both raw and corrected temperatures,\n \"repropagate\" the model starting from the last accepted temperature value.\n This effectively takes out much of the systematic model error, which can be up to\n 15 degF after a transition to a new attitude.\n - In some cases this allows recovery of additional data, while in others the data are\n not recoverable: either due to partial disconnect of the parallel resistor or full\n disconnects where the output voltage exceeds 5.12 V.\n\n The output of this function is a `fetch.Msid` object with some bonus attributes,\n documented below. In particular the output cleaned data are labeled so one knows\n exactly where each data point came from.\n\n The function is fast, and one can get 5 years of cleaned telemetry in a few seconds\n on a modern laptop with SSD drive.\n\n This cleaning technique recovers on average about 90% of data for PM2THV1T. Since\n 2015, about 60% of telemetry is good (no dropout) while 30% is in a recoverable\n fully-dropped state (and 10% is not recoverable).\n\n ```\n def fetch_clean_msid(msid, start, stop=None, dt_thresh=5.0, median=7, model_spec=None,\n version=None):\n Fetch a cleaned version of telemetry for ``msid``.\n\n If not supplied the model spec will come from\n ``xija.get_model_spec.get_xija_model_spec(msid, version=version)``\n (which uses ``$SKA/data/chandra_models/chandra_models/xija/mups_valve/{msid}_spec.json``).\n\n This function returns a `fetch.Msid` object like a normal fetch but with extra attributes:\n\n - vals: cleaned telemetry (either original or corrected telemetry, or xija model prediction)\n - source: label for each vals data point\n - 0: unrecoverable, so use xija model value\n - 1: original telemetry\n - 2: corrected telemetry\n - vals_raw: raw (uncleaned) telemetry\n - vals_nan: cleaned telem but with np.nan at points where data are unrecoverable (this is\n for plotting)\n - vals_corr: telemetry with the MUPS correction applied\n - vals_model: xija model prediction\n\n :param start: start time\n :param stop: stop time (default=NOW)\n :param dt_thresh: tolerance for matching model to data in degF (default=5 degF)\n :param median: length of median filter (default=7, use 0 to disable)\n :param model_spec: file name or URL containing relevant xija model spec\n :param version: version of chandra_models repo (tag, branch, or commit)\n\n :returns: fetch.Msid object\n ```\n\"\"\"\n\nimport os\n\nimport numba\nimport numpy as np\nfrom scipy.interpolate import interp1d\nfrom scipy.ndimage import median_filter\nfrom xija import XijaModel\nfrom xija.get_model_spec import get_xija_model_spec\n\nfrom cheta import fetch_eng\n\n\ndef c2f(degc):\n degf = 32 + degc * 1.8\n return degf\n\n\n# Define MUPS valve thermistor point pair calibration table (from TDB).\npp_counts = np.array(\n [0, 27, 36, 44, 55, 70, 90, 118, 175, 195, 210, 219, 226, 231, 235, 255]\n)\npp_temps = np.array(\n [\n 369.5305,\n 263.32577,\n 239.03652,\n 222.30608,\n 203.6944,\n 183.2642,\n 161.0796,\n 134.93818,\n 85.65725,\n 65.6537,\n 47.3176,\n 33.50622,\n 19.9373,\n 7.42435,\n -5.79635,\n -111.77265,\n ]\n)\n\ncount_to_degf = interp1d(pp_counts, pp_temps)\ndegf_to_counts = interp1d(pp_temps, pp_counts)\n\n\n# Define MUPS valve thermistor voltage point pair calibration table.\ndef count_to_volts(counts):\n return counts / 256 * 5.12\n\n\ndef volts_to_counts(volts):\n return volts / 5.12 * 256\n\n\n# Voltage and Temperature, with and without resistor (see flight note 447 for\n# the source of these numbers).\nvolt_with_resistor = [\n 4.153325779,\n 3.676396578,\n 3.175100371,\n 2.587948965,\n 2.435,\n 2.025223702,\n 1.538506813,\n 1.148359251,\n 0.63128179,\n 0.354868907,\n 0.208375569,\n]\nvolt_without_resistor = [\n 28.223,\n 15,\n 9.1231,\n 5.5228,\n 4.87,\n 3.467,\n 2.249,\n 1.5027,\n 0.7253,\n 0.38276,\n 0.21769,\n]\nvolt_without_resistor_to_volt_with_resistor = interp1d(\n volt_without_resistor, volt_with_resistor\n)\n\n\ndef get_corr_mups_temp(temp):\n \"\"\"Calculate a MUPS valve thermistor corrected temperature.\n Args:\n temp (float, int): Temperature in Fahrenheit to which a correction will be applied.\n\n Returns:\n (float): Corrected temperaure\n\n \"\"\"\n # Convert observed temperature to voltage\n count = degf_to_counts(temp)\n volt = count_to_volts(count)\n\n # Convert voltage as read, assuming no resistor, to what it would be with the resistor\n new_volt = volt_without_resistor_to_volt_with_resistor(volt)\n\n # Convert this new voltage to counts and, in turn, to a new temperature\n new_count = volts_to_counts(new_volt)\n new_temp = count_to_degf(new_count)\n\n return new_temp\n\n\n@numba.jit(nopython=True)\ndef select_using_model(data1, data2, model, dt_thresh, out, source):\n \"\"\"Select from either ``data1`` or ``data2`` using ``model`` to get clean data.\n\n This does a 2-step process:\n\n 1. Select either `data1` or `data2` where either is within `dt_thresh` of `model`.\n 2. Fill in gaps where possible by propagating the model from previous good data,\n thus reducing the impact of model errors.\n\n :param data1: ndarray of data (e.g. observed temperature telemetry)\n :param data2: ndarray of data (e.g. corrected temperature telemetry)\n :param model: ndarray with model prediction for data\n :param dt_thresh: model error tolerance for selecting data1 or data2\n :param out: ndarray where output cleaned data is stored (must be same length as data)\n :param source: ndarray where output source labeling is stored (same length as data)\n \"\"\"\n # Fill in gaps where possible by propagating model from last good data value\n for ii in range(len(data1)):\n if source[ii] != 0:\n # Already got a good value so move on.\n continue\n\n if ii == 0:\n model_prop_ii = model[0]\n else:\n # Propagate model using last point + delta-model\n model_prop_ii = out[ii - 1] + (model[ii] - model[ii - 1]) # noqa\n\n if abs(data1[ii] - model_prop_ii) < dt_thresh:\n out[ii] = data1[ii]\n source[ii] = 1\n elif abs(data2[ii] - model_prop_ii) < dt_thresh:\n out[ii] = data2[ii]\n source[ii] = 2\n else:\n # No good match, use propagated model value and mark as such\n out[ii] = model_prop_ii\n source[ii] = 0\n\n\ndef fetch_clean_msid(\n msid, start, stop=None, dt_thresh=5.0, median=7, model_spec=None, version=None\n):\n \"\"\"Fetch a cleaned version of telemetry for ``msid``.\n\n If not supplied the model spec will come from\n ``xija.get_model_spec.get_xija_model_spec(msid, version=version)``\n (which uses ``$SKA/data/chandra_models/chandra_models/xija/mups_valve/{msid}_spec.json``).\n\n This function returns a `fetch.Msid` object like a normal fetch but with extra attributes:\n\n - vals: cleaned telemetry (either original or corrected telemetry, or xija model prediction)\n - source: label for each vals data point\n - 0: unrecoverable, so use xija model value\n - 1: original telemetry\n - 2: corrected telemetry\n - vals_raw: raw (uncleaned) telemetry\n - vals_nan: cleaned telem but with np.nan at points where data are unrecoverable (this is\n for plotting)\n - vals_corr: telemetry with the MUPS correction applied\n - vals_model: xija model prediction\n\n :param start: start time\n :param stop: stop time (default=NOW)\n :param dt_thresh: tolerance for matching model to data in degF (default=5 degF)\n :param median: length of median filter (default=7, use 0 to disable)\n :param model_spec: file name or URL containing relevant xija model spec\n :param version: version of chandra_models repo (tag, branch, or commit)\n\n :returns: fetch.Msid object\n \"\"\"\n if model_spec is None or not os.path.exists(model_spec):\n # Get spec from $SKA/data/chandra_models/chandra_models/xija/mups_valve/{msid}_spec.json.\n # This function also returns the version of the chandra_models repo but we don't need it.\n model_spec, _ = get_xija_model_spec(msid, version=version)\n\n # NOTE: all temperatures are in degF unless otherwise noted\n\n dat = fetch_eng.Msid(msid, start, stop)\n\n t_obs = dat.vals\n if median:\n t_obs = median_filter(t_obs, size=median)\n t_corr = get_corr_mups_temp(t_obs)\n\n # Model is computed in degC\n mdl = XijaModel(\n model_spec=model_spec, start=dat.times[0] - 400000, stop=dat.times[-1]\n )\n mdl.comp[\"mups0\"].set_data(75) # degC\n mdl.make()\n mdl.calc()\n\n # Interpolate model temperatures (converted to degF with c2f) onto telemetry times\n t_model = np.interp(xp=mdl.times, fp=c2f(mdl.comp[msid].mvals), x=dat.times)\n\n out = np.zeros_like(dat.vals)\n source = np.zeros(len(dat.vals), dtype=int)\n\n # Select all data where either data1 or data2 are within dt_thresh of model\n for data, source_id in [(t_obs, 1), (t_corr, 2)]:\n ok = np.abs(data - t_model) < dt_thresh\n out[ok] = data[ok]\n source[ok] = source_id\n\n select_using_model(\n t_obs, t_corr, t_model, dt_thresh=dt_thresh, out=out, source=source\n )\n\n dat.vals_raw = dat.vals\n\n dat.vals = out\n dat.vals_nan = out.copy()\n\n dat.bads = source == 0\n dat.vals_nan[dat.bads] = np.nan\n\n dat.source = source\n dat.vals_corr = t_corr\n dat.vals_model = t_model\n\n return dat\n","sub_path":"Ska/engarchive/derived/mups_valve.py","file_name":"mups_valve.py","file_ext":"py","file_size_in_byte":10251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"608197578","text":"#!/usr/bin/env python\nimport sys, os\nfrom config import ConfigReader, ReadingError\nfrom accounts import AccountsSetuper, SetupError\nfrom messenger import Messenger\nfrom argparse import ArgumentParser\n\ndef add_options(parser):\n parser.add_argument('-c', '--config-file', nargs=1, dest='config_file',\n help='run commands given in CONFIGFILE', metavar='CONFIGFILE',\n required=True)\n\ndef read_config(config_file):\n reader = ConfigReader(config_file)\n return reader.get_config()\n\ndef main():\n log = Messenger()\n try:\n parser = ArgumentParser()\n add_options(parser)\n options = parser.parse_args()\n email_accounts = read_config(options.config_file[0])\n if not isinstance(email_accounts, list):\n raise ReadingError('Configuration file must be a list of tasks')\n setuper = AccountsSetuper()\n success = setuper.setup(email_accounts)\n if success:\n log.info('\\n==> All tasks executed successfully')\n else:\n raise SetupError('\\n==> Some tasks were not executed successfully')\n except (ReadingError, SetupError) as e:\n log.error('%s' % e)\n exit(1)\n except KeyboardInterrupt:\n log.error('\\n==> Operation aborted')\n exit(1)\n\nif __name__ == '__main__':\n main()\n","sub_path":"mutt/root/usr/lib/muttbot/muttbot.py","file_name":"muttbot.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"197799071","text":"import pytest\n\nfrom orders.models import Order\n\npytestmark = [pytest.mark.django_db]\n\n\ndef test_tinkoff_bank_is_called_by_default(call_purchase, tinkoff_bank, tinkoff_credit):\n call_purchase()\n\n tinkoff_bank.assert_called_once()\n tinkoff_credit.assert_not_called()\n\n\ndef test_tinkoff_bank(call_purchase, tinkoff_bank, tinkoff_credit):\n call_purchase(desired_bank='tinkoff_bank')\n\n tinkoff_bank.assert_called_once()\n tinkoff_credit.assert_not_called()\n\n\ndef test_tinkoff_credit(call_purchase, tinkoff_bank, tinkoff_credit):\n call_purchase(desired_bank='tinkoff_credit')\n\n tinkoff_bank.assert_not_called()\n tinkoff_credit.assert_called_once()\n\n\ndef test_desired_bank_is_saved(call_purchase):\n call_purchase(desired_bank='tinkoff_credit')\n\n order = Order.objects.last()\n\n assert order.desired_bank == 'tinkoff_credit'\n\n\ndef test_by_default_desired_bank_is_empty_string(call_purchase):\n call_purchase()\n\n order = Order.objects.last()\n\n assert order.desired_bank == ''\n\n\ndef test_desired_bank_is_stored_during_gift(api, default_gift_data):\n api.post(\n '/api/v2/courses/ruloning-oboev/gift/',\n {\n **default_gift_data,\n 'desired_bank': 'tinkoff_credit',\n },\n format='multipart', expected_status_code=302)\n\n order = Order.objects.last()\n\n assert order.desired_bank == 'tinkoff_credit'\n","sub_path":"src/orders/tests/configurable_bank/tests_configurable_bank.py","file_name":"tests_configurable_bank.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"144180916","text":"__author__ = 'Administrator'\n\nimport mysql.connector\n\nconfig = {'host':'120.24.235.105',\n 'user':'student2',\n 'password':'student2@',\n 'port':3306,\n 'database':'python',\n 'charset':'utf8'}\n\ncnn = mysql.connector.connect(**config)\n\ncursor = cnn.cursor()\n\n#建表\n\nsql_create_table = 'CREATE TABLE python_4_yuangungun03\\\n (id int(10) NOT NULL AUTO_INCREMENT,\\\n name varchar(10) DEFAULT NULL,\\\n age int(3) DEFAULT NULL,\\\n PRIMARY KEY (id))\\\n ENGINE=MyISAM DEFAULT CHARSET=utf8'\n\n\n#插入数据\n\nsql_insert1 = 'insert into python_4_yuangungun (name, age) values (\"测试数据01\", 24)'\n\nsql_insert2 = 'insert into python_4_yuangungun(name , age) values (%s, %s)'\ndata1 = (\"放羊\", 28)\n\nsql_insert3 = 'insert into python_4_yuangungun(name, age) values (%(name)s, %(age)s)'\ndata2 = {\"name\":\"甜甜\", \"age\":18}\n\nsql_insert4 = 'insert into python_4_yuangungun(name, age) values (%s, %s)'\ndata3 = [\n (\"测试数据1\", 25),\n (\"测试数据2\", 21),\n (\"测试数据3\", 18),\n]\n\n\n#删除数据\n'''\nsql_delete = 'delete from python_4_yuangungun where id > 1'\n'''\n\n#查询数据\nsql_select = 'select * from python_4_yuangungun'\n\ntry:\n #新建表\n\n cursor.execute(sql_create_table)\n\n\n #删除数据\n '''\n cursor.execute(sql_delete)\n '''\n\n #插入数据\n\n cursor.execute(sql_insert1)\n\n cursor.execute(sql_insert2, data1)\n\n cursor.execute(sql_insert3, data2)\n\n cursor.executemany(sql_insert4, data3)\n\n #查询\n\n cursor.execute(sql_select)\n print(cursor.fetchall())\n\nexcept mysql.connector.Error as e:\n print(\"sql error\\n\", e)\nfinally:\n cursor.close()\n cnn.close()","sub_path":"接口自动化/db_Op/dbOp_myisam.py","file_name":"dbOp_myisam.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"562499358","text":"\"\"\"\nThis module implements two types of reaction enumerators using a free energy\nminimization technique, with or without the option of an open entry.\n\"\"\"\n\nfrom itertools import product\nfrom typing import List, Optional\n\nfrom pymatgen.analysis.interface_reactions import (\n GrandPotentialInterfacialReactivity,\n InterfacialReactivity,\n)\nfrom pymatgen.core.composition import Element\n\nfrom rxn_network.core.composition import Composition\nfrom rxn_network.enumerators.basic import BasicEnumerator\nfrom rxn_network.enumerators.utils import get_computed_rxn\n\n\nclass MinimizeGibbsEnumerator(BasicEnumerator):\n \"\"\"\n Enumerator for finding all reactions between two reactants that are predicted by\n thermodynamics; i.e., they appear when taking the convex hull along a straight line\n connecting any two phases in G-x phase space. Identity reactions are automatically\n excluded.\n \"\"\"\n\n CHUNK_SIZE = 10000\n\n def __init__(\n self,\n precursors: Optional[List[str]] = None,\n targets: Optional[List[str]] = None,\n exclusive_precursors: bool = True,\n exclusive_targets: bool = False,\n filter_by_chemsys: Optional[str] = None,\n max_num_constraints: int = 1,\n calculate_e_above_hulls: bool = False,\n quiet: bool = False,\n ):\n \"\"\"\n Args:\n precursors: Optional formulas of precursors.\n targets: Optional formulas of targets; only reactions which make\n these targets will be enumerated.\n calculators: Optional list of Calculator object names; see calculators\n module for options (e.g., [\"ChempotDistanceCalculator\"])\n exclusive_precursors: Whether to consider only reactions that have\n reactants which are a subset of the provided list of precursors.\n Defaults to True.\n exclusive_targets: Whether to consider only reactions that make the\n provided target directly (i.e. with no byproducts). Defualts to False.\n quiet: Whether to run in quiet mode (no progress bar). Defaults to False.\n \"\"\"\n super().__init__(\n precursors=precursors,\n targets=targets,\n exclusive_precursors=exclusive_precursors,\n exclusive_targets=exclusive_targets,\n filter_by_chemsys=filter_by_chemsys,\n quiet=quiet,\n )\n self._build_pd = True\n\n @staticmethod\n def _react_function(\n reactants, products, filtered_entries=None, pd=None, grand_pd=None, **kwargs\n ):\n \"\"\"React method for MinimizeGibbsEnumerator, which uses the interfacial reaction\n approach (see _react_interface())\"\"\"\n\n r = list(reactants)\n r0 = r[0]\n\n if len(r) == 1:\n r1 = r[0]\n else:\n r1 = r[1]\n\n return react_interface(\n r0.composition,\n r1.composition,\n filtered_entries,\n pd,\n grand_pd,\n )\n\n @staticmethod\n def _get_rxn_iterable(combos, open_combos):\n \"\"\"Gets the iterable used to generate reactions\"\"\"\n _ = open_combos # unused argument\n\n return product(combos, [None])\n\n @staticmethod\n def _rxn_iter_length(combos, open_combos):\n _ = open_combos\n return len(combos)\n\n\nclass MinimizeGrandPotentialEnumerator(MinimizeGibbsEnumerator):\n \"\"\"\n Enumerator for finding all reactions between two reactants and an open element\n that are predicted by thermo; i.e., they appear when taking the\n convex hull along a straight line connecting any two phases in Phi-x\n phase space. Identity reactions are excluded.\n \"\"\"\n\n CHUNK_SIZE = 10000\n\n def __init__(\n self,\n open_elem: Element,\n mu: float,\n precursors: Optional[List[str]] = None,\n targets: Optional[List[str]] = None,\n exclusive_precursors: bool = True,\n exclusive_targets: bool = False,\n filter_by_chemsys: Optional[str] = None,\n max_num_constraints=1,\n quiet: bool = False,\n ):\n \"\"\"\n Args:\n open_elem: The element to be considered as open\n mu: The chemical potential of the open element\n precursors: Optional formulas of precursors.\n targets: Optional formulas of targets; only reactions which make\n these targets will be enumerated.\n calculators: Optional list of Calculator object names; see calculators\n module for options (e.g., [\"ChempotDistanceCalculator])\n exclusive_precursors: Whether to consider only reactions that have\n reactants which are a subset of the provided list of precursors.\n Defaults to True.\n exclusive_targets: Whether to consider only reactions that make the\n provided target directly (i.e. with no byproducts). Defualts to False.\n quiet: Whether to run in quiet mode (no progress bar). Defaults to False.\n \"\"\"\n\n super().__init__(\n precursors=precursors,\n targets=targets,\n exclusive_precursors=exclusive_precursors,\n exclusive_targets=exclusive_targets,\n filter_by_chemsys=filter_by_chemsys,\n quiet=quiet,\n )\n self.open_elem = Element(open_elem)\n self.open_phases = [Composition(str(self.open_elem)).reduced_formula]\n self.mu = mu\n self.chempots = {self.open_elem: self.mu}\n self._build_grand_pd = True\n\n @staticmethod\n def _react_function(\n reactants, products, filtered_entries=None, pd=None, grand_pd=None, **kwargs\n ):\n \"\"\"Same as the MinimizeGibbsEnumerator react function, but with ability to\n specify open element and grand potential phase diagram\"\"\"\n r = list(reactants)\n r0 = r[0]\n\n if len(r) == 1:\n r1 = r[0]\n else:\n r1 = r[1]\n\n open_elem = list(grand_pd.chempots.keys())[0]\n\n for reactant in r:\n elems = reactant.composition.elements\n if len(elems) == 1 and elems[0] == open_elem: # skip if reactant = open_e\n return []\n\n return react_interface(\n r0.composition,\n r1.composition,\n filtered_entries,\n pd,\n grand_pd=grand_pd,\n )\n\n\ndef react_interface(r1, r2, filtered_entries, pd, grand_pd=None):\n \"\"\"Simple API for InterfacialReactivity module from pymatgen.\"\"\"\n chempots = None\n\n if grand_pd:\n interface = GrandPotentialInterfacialReactivity(\n r1,\n r2,\n grand_pd,\n pd_non_grand=pd,\n norm=True,\n include_no_mixing_energy=True,\n use_hull_energy=True,\n )\n chempots = grand_pd.chempots\n\n else:\n interface = InterfacialReactivity(\n r1,\n r2,\n pd,\n use_hull_energy=True,\n )\n\n rxns = []\n for _, _, _, rxn, _ in interface.get_kinks():\n rxn = get_computed_rxn(rxn, filtered_entries, chempots)\n rxns.append(rxn)\n\n return rxns\n","sub_path":"src/rxn_network/enumerators/minimize.py","file_name":"minimize.py","file_ext":"py","file_size_in_byte":7149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"463893658","text":"from pygame.locals import *\r\nimport pygame\r\nimport time\r\nfrom random import randint\r\n\r\nclass Apple:\r\n x = [0]\r\n y = [0]\r\n step = 33\r\n direction = 3\r\n length = 10\r\n\r\n updateCountMax = 2\r\n updateCount = 0\r\n\r\n def __init__(self, length):\r\n self.length = length\r\n for i in range(0, 2000):\r\n self.x.append(-100)\r\n self.y.append(-100)\r\n\r\n # initial positions, no collision.\r\n self.x[0] = randint(1,555)\r\n self.y[0] = 0\r\n\r\n\r\n\r\n def update(self):\r\n\r\n self.updateCount = self.updateCount + 1\r\n if self.updateCount > self.updateCountMax:\r\n\r\n # update previous positions\r\n for i in range(self.length - 1, 0, -1):\r\n self.x[i] = self.x[i - 1]\r\n self.y[i] = self.y[i - 1]\r\n\r\n # update position of head of snake\r\n if self.direction == 2:\r\n self.y[0] = self.y[0] - self.step\r\n if self.direction == 3:\r\n self.y[0] = self.y[0] + self.step\r\n\r\n self.updateCount = 0\r\n\r\n def moveUp(self):\r\n self.y = self.y - self.speed\r\n\r\n def moveDown(self):\r\n self.y = self.y + self.speed\r\n\r\n def moveUp(self):\r\n self.direction = 2\r\n\r\n def moveDown(self):\r\n self.direction = 3\r\n\r\n def draw(self, surface, image):\r\n for i in range(0, self.length):\r\n surface.blit(image, (self.x[i], self.y[i]))\r\n\r\n\r\nclass Player:\r\n x = [0]\r\n y = [0]\r\n step = 34\r\n direction = 0\r\n length = 10\r\n\r\n updateCountMax = 2\r\n updateCount = 0\r\n\r\n def __init__(self, length):\r\n self.length = length\r\n for i in range(0, 2000):\r\n self.x.append(-100)\r\n self.y.append(-100)\r\n\r\n # initial positions, no collision.\r\n self.x[0] = randint(1,540)\r\n self.y[0] = 625\r\n\r\n def update(self):\r\n\r\n self.updateCount = self.updateCount + 1\r\n if self.updateCount > self.updateCountMax:\r\n\r\n # update previous positions\r\n for i in range(self.length - 1, 0, -1):\r\n self.x[i] = self.x[i - 1]\r\n self.y[i] = self.y[i - 1]\r\n\r\n # update position of head of snake\r\n if self.direction == 0:\r\n self.x[0] = self.x[0] + self.step\r\n if self.direction == 1:\r\n self.x[0] = self.x[0] - self.step\r\n\r\n self.updateCount = 0\r\n\r\n def moveRight(self):\r\n self.x = self.x + (self.speed * 2)\r\n\r\n def moveLeft(self):\r\n self.x = self.x - (self.speed * 2)\r\n\r\n def moveRight(self):\r\n self.direction = 0\r\n\r\n def moveLeft(self):\r\n self.direction = 1\r\n\r\n def draw(self, surface, image):\r\n for i in range(0, self.length):\r\n surface.blit(image, (self.x[i], self.y[i]))\r\n\r\nclass Game:\r\n\r\n def isCollision(self,x1,y1,x2,y2,bsize):\r\n if (y1 > (630-75)):\r\n if x1 >= x2 and x1 <= x2 + bsize or x2 >= x1 and x2 <= x1 + bsize:\r\n return True\r\n return False\r\n\r\n def isMissed(self, y, h):\r\n if y > (h - 50):\r\n return True\r\n\r\n return False\r\n\r\n def isWall(self, x1,y1,width, height):\r\n if x1 < 0:\r\n return True\r\n if x1 > (width - 1):\r\n return True\r\n if y1 < 0:\r\n return True\r\n if y1 > height:\r\n return True\r\n\r\n return False\r\nclass App:\r\n player = 0\r\n apple = 0\r\n count = 0\r\n w = 0\r\n h = 0\r\n width = 0\r\n height = 0\r\n times_played = 0\r\n\r\n def __init__(self):\r\n self._running = True\r\n self._display_surf = None\r\n self._image_surf = None\r\n self._background_image = None\r\n self._apple_surf = None\r\n self._text = None\r\n self.game = Game()\r\n self.player = Player(1)\r\n self.apple = Apple(1)\r\n self.count = 0\r\n self.width = 600\r\n self.height = 700\r\n self._game_over = False\r\n self.w = None\r\n self.h = None\r\n self._pause = False\r\n self._quit = False\r\n self._times_played = 2\r\n self.moved = False\r\n self.win = False\r\n self.win_image = None\r\n\r\n def on_init(self):\r\n pygame.init()\r\n self._display_surf = pygame.display.set_mode((self.width, self.height), pygame.HWSURFACE)\r\n self.w, self.h = pygame.display.get_surface().get_size()\r\n self.width = (self.w/44) - 1\r\n self.height = (self.h/44) - 1\r\n pygame.display.set_caption('Wookie Auditor Game')\r\n self._running = True\r\n self._image_surf = pygame.image.load(\"lego2.png\").convert()\r\n self._apple_surf = pygame.image.load(\"a.png\").convert()\r\n self.win_image = pygame.image.load(\"winner.png\").convert()\r\n if self.times_played % 2 == 0:\r\n self._background_image = pygame.image.load(\"office.png\").convert()\r\n else:\r\n self._background_image = pygame.image.load(\"office.png\").convert()\r\n\r\n def on_event(self, event):\r\n if event.type == QUIT:\r\n self._running = False\r\n\r\n def on_loop(self):\r\n if self._pause == False:\r\n\r\n if self.moved:\r\n self.player.update()\r\n\r\n # does auditor hit the wall?\r\n for i in range(0, self.player.length):\r\n if self.game.isWall(self.player.x[0], self.player.y[0], self.w, self.h):\r\n if int(self.player.x[0]) < 0:\r\n self.player.x[0] = int(self.width) * 45\r\n\r\n if int(self.player.x[0]) > (int(self.w) - 1):\r\n self.player.x[0] = 0\r\n\r\n if int(self.player.y[0]) < 0:\r\n self.player.y[0] = int(self.height) * 45\r\n\r\n if int(self.player.y[0]) > (int(self.h) - 1):\r\n self.player.y[0] = 0\r\n self.moved = False\r\n\r\n self.apple.update()\r\n\r\n if self.game.isMissed(self.apple.y[0], self.h):\r\n if int(self.apple.y[0]) > int(self.h):\r\n self.apple.y[0] = 0\r\n self.apple.x[0] = randint(1,532)\r\n self.count = self.count + 1\r\n if self.count > 100:\r\n self._pause = True\r\n self.win = True\r\n if int(self.count) % 5 == 0:\r\n self.apple.length = self.apple.length + 1\r\n\r\n for i in range(0, self.apple.length):\r\n if self.game.isCollision(self.apple.x[i], self.apple.y[i], self.player.x[0], self.player.y[0], 62):\r\n self._game_over = True\r\n self._pause = True\r\n pass\r\n\r\n def on_render(self):\r\n self._display_surf.fill((0, 0, 0))\r\n self._display_surf.blit(self._background_image, [0, 0])\r\n self.player.draw(self._display_surf, self._image_surf)\r\n self.apple.draw(self._display_surf, self._apple_surf)\r\n font = pygame.font.SysFont('Calibri', 25, True, False)\r\n text = font.render(\"Conrols Dodged: \" + str(self.count), True, (34,139,34))\r\n self._display_surf.blit(text, [10, 15])\r\n\r\n if self._game_over:\r\n score_font = pygame.font.SysFont('freesansbold.ttf', 50, True, False)\r\n score_text = score_font.render(\"Dodgeg Controls: \" + str(self.count) + \"!\", True, (255, 255, 255))\r\n textRectScore = score_text.get_rect()\r\n textRectScore.center = (self.w // 2, self.h // 5)\r\n self._display_surf.blit(score_text, textRectScore)\r\n large_font = pygame.font.SysFont('freesansbold.ttf', 45, True, False)\r\n large_text = large_font.render('Game Over', True, (255, 0, 0))\r\n textRect = large_text.get_rect()\r\n textRect.center = (self.w // 2, self.h // 2.25)\r\n self._display_surf.blit(large_text, textRect)\r\n l_font = pygame.font.SysFont('freesansbold.ttf', 30, True, False)\r\n l_text = l_font.render('Play Again? Y/N', True, (0, 0, 0))\r\n textRectL = l_text.get_rect()\r\n textRectL.center = (self.w // 2, self.h // 1.75)\r\n self._display_surf.blit(l_text, textRectL)\r\n keys = pygame.key.get_pressed()\r\n if (keys[K_n]):\r\n self._running = False\r\n if (keys[K_y]):\r\n self.times_played = self.times_played + 1\r\n self.count = 0\r\n self.player.x[0] = randint(1,540)\r\n self.player.y[0] = 630\r\n\r\n if self.player.direction == 0:\r\n self.player.direction = 2\r\n else:\r\n self.player.direction = 0\r\n\r\n self.__init__()\r\n self.on_init()\r\n self._game_over = False\r\n self._pause = False\r\n\r\n if self.win:\r\n self._display_surf.blit(self.win_image, [0, 0])\r\n score_font = pygame.font.SysFont('freesansbold.ttf', 25, True, False)\r\n score_text = score_font.render(\"Dodgeg Controls: \" + str(self.count) + \"!\", True, (255, 255, 255))\r\n textRectScore = score_text.get_rect()\r\n textRectScore.center = (self.w // 2, self.h // 5)\r\n self._display_surf.blit(score_text, textRectScore)\r\n large_font = pygame.font.SysFont('freesansbold.ttf', 45, True, False)\r\n large_text = large_font.render('You Won! Wookie goes surfing!', True, (255, 0, 0))\r\n textRect = large_text.get_rect()\r\n textRect.center = (self.w // 2, self.h // 2.25)\r\n self._display_surf.blit(large_text, textRect)\r\n l_font = pygame.font.SysFont('freesansbold.ttf', 30, True, False)\r\n l_text = l_font.render('Play Again? Y/N', True, (0, 0, 0))\r\n textRectL = l_text.get_rect()\r\n textRectL.center = (self.w // 2, self.h // 1.75)\r\n self._display_surf.blit(l_text, textRectL)\r\n keys = pygame.key.get_pressed()\r\n if (keys[K_n]):\r\n self._running = False\r\n if (keys[K_y]):\r\n self.times_played = self.times_played + 1\r\n self.count = 0\r\n self.player.x[0] = randint(1, 540)\r\n self.player.y[0] = 630\r\n\r\n if self.player.direction == 0:\r\n self.player.direction = 2\r\n else:\r\n self.player.direction = 0\r\n\r\n self.__init__()\r\n self.on_init()\r\n self.win = False\r\n self._pause = False\r\n\r\n if self._quit and self._game_over == False:\r\n large_font = pygame.font.SysFont('freesansbold.ttf', 45, True, False)\r\n large_text = large_font.render('Do you want to exit? Y/N', True, (255, 0, 0))\r\n textRect = large_text.get_rect()\r\n textRect.center = (self.w // 2, self.h // 2)\r\n self._display_surf.blit(large_text, textRect)\r\n keys = pygame.key.get_pressed()\r\n\r\n if (keys[K_y]):\r\n self._running = False\r\n if (keys[K_n]):\r\n self._quit = False\r\n self._pause = False\r\n self.player.moveRight()\r\n\r\n if self._pause and self._quit == False and self._game_over == False and self.win == False:\r\n large_font = pygame.font.SysFont('freesansbold.ttf', 45, True, False)\r\n large_text = large_font.render('Paused', True, (255, 201, 20))\r\n textRect = large_text.get_rect()\r\n textRect.center = (self.w // 2, self.h // 4)\r\n self._display_surf.blit(large_text, textRect)\r\n l_font = pygame.font.SysFont('freesansbold.ttf', 30, True, False)\r\n l_text = l_font.render('Press C to continue ot Q to exit', True, (0, 0, 0))\r\n textRectL = l_text.get_rect()\r\n textRectL.center = (self.w // 2, self.h // 2)\r\n self._display_surf.blit(l_text, textRectL)\r\n keys = pygame.key.get_pressed()\r\n\r\n if (keys[K_c]):\r\n self._pause = False\r\n if (keys[K_q]):\r\n self._running = False\r\n\r\n pygame.display.flip()\r\n\r\n def on_cleanup(self):\r\n pygame.quit()\r\n\r\n def on_execute(self):\r\n if self.on_init() == False:\r\n self._running = False\r\n\r\n while (self._running):\r\n pygame.event.pump()\r\n keys = pygame.key.get_pressed()\r\n\r\n if (keys[K_RIGHT]):\r\n self.player.moveRight()\r\n self.moved = True\r\n if (keys[K_LEFT]):\r\n self.player.moveLeft()\r\n self.moved = True\r\n if (keys[K_ESCAPE]):\r\n self._quit = True\r\n self._pause = True\r\n if (keys[K_SPACE]):\r\n self._pause = True\r\n\r\n self.on_loop()\r\n self.on_render()\r\n\r\n if int(self.count) < 5:\r\n time.sleep(100.0 / 10000.0);\r\n elif int(self.count) >= 5 and int(self.count) < 10:\r\n time.sleep(75.0 / 10000.0);\r\n elif int(self.count) >= 10 and int(self.count) < 20:\r\n time.sleep(50.0 / 10000.0);\r\n elif int(self.count) >= 20 and int(self.count) < 30:\r\n time.sleep(25.0 / 10000.0);\r\n elif int(self.count) >= 30:\r\n time.sleep(15.0 / 10000.0);\r\n self.on_cleanup()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n theApp = App()\r\n theApp.on_execute()","sub_path":"Racer.py","file_name":"Racer.py","file_ext":"py","file_size_in_byte":13588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"257150695","text":"# programacion aplicada a suits\r\n\r\nabogados={\r\n 'mike':{'juicios':[('julio',3),('agosto',1),('octubre',4)],\r\n 'sueldo':100,\r\n 'empresas':{'google','samsung','ciac'} },\r\n 'rachel':{'juicios':[('enero',3),('marzo',4),('julio',8)],\r\n 'sueldo':70,\r\n 'empresas':{'google','codelco'}},\r\n 'harvey':{'juicios':[('enero',5),('febrero',12),('julio',24)],\r\n 'sueldo':1000,\r\n 'empresas':{'mesa verde','samsung'}}\r\n #...\r\n }\r\n\r\ndef juicios_por_mes(abogados):\r\n juicios={}\r\n for diccionario in abogados.values():\r\n for mes,cantidad in diccionario['juicios']:\r\n if mes not in juicios:\r\n juicios[mes]=0\r\n juicios[mes]+=cantidad\r\n return juicios\r\n\r\ndef total_juicios(abogado):\r\n total=0\r\n for mes,cantidad in abogados[abogado]['juicios']:\r\n total+=cantidad\r\n return total\r\n\r\ndef quien_trabajo(empresa):\r\n lista=[]\r\n for abogado,diccionario in abogados.items():\r\n if empresa in diccionario['empresas']:\r\n lista.append(abogado)\r\n return lista\r\n\r\ndef se_conocen(abogado_1,abogado_2):\r\n empresas_1=abogados[abogado_1]['empresas']\r\n empresas_2=abogados[abogado_2]['empresas']\r\n return bool(empresas_1&empresas_2)\r\n\r\ndef se_conocen_alternativo(abogado_1,abogado_2): #alternativo\r\n empresas_1=abogados[abogado_1]['empresas']\r\n empresas_2=abogados[abogado_2]['empresas']\r\n if len(empresas_1 & empresas_2)==0:\r\n return False\r\n return True\r\n","sub_path":"ejercicios/21 conjuntos/05 - abogados/Code/suits.py","file_name":"suits.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"391471771","text":"#!/usr/bin/env python3\n\nimport io\nimport os\nimport sys\nimport tempfile\nfrom shutil import copyfile\nfrom unittest import TestCase, main\n\nfrom readalongs.app import app\nfrom readalongs.cli import prepare, tokenize\nfrom readalongs.log import LOGGER\n\n\nclass TestTokenizeCli(TestCase):\n LOGGER.setLevel(\"DEBUG\")\n data_dir = os.path.join(os.path.dirname(__file__), \"data\")\n\n # Set this to True to keep the temp dirs after running, for manual inspection\n # but please don't push a commit setting this to True!\n keep_temp_dir_after_running = False\n\n def setUp(self):\n app.logger.setLevel(\"DEBUG\")\n self.runner = app.test_cli_runner()\n if not self.keep_temp_dir_after_running:\n self.tempdirobj = tempfile.TemporaryDirectory(\n prefix=\"tmpdir_test_tokenize_cli_\", dir=\".\"\n )\n self.tempdir = self.tempdirobj.name\n else:\n # Alternative tempdir code keeps it after running, for manual inspection:\n self.tempdir = tempfile.mkdtemp(prefix=\"tmpdir_test_tokenize_cli_\", dir=\".\")\n print(\"tmpdir={}\".format(self.tempdir))\n\n self.xmlfile = os.path.join(self.tempdir, \"fra.xml\")\n _ = self.runner.invoke(\n prepare, [\"-l\", \"fra\", os.path.join(self.data_dir, \"fra.txt\"), self.xmlfile]\n )\n\n def tearDown(self):\n if not self.keep_temp_dir_after_running:\n self.tempdirobj.cleanup()\n\n def test_invoke_tok(self):\n results = self.runner.invoke(\n tokenize, [self.xmlfile, os.path.join(self.tempdir, \"delme\")]\n )\n self.assertEqual(results.exit_code, 0)\n self.assertTrue(os.path.exists(os.path.join(self.tempdir, \"delme.xml\")))\n\n def test_generate_output_name(self):\n results = self.runner.invoke(tokenize, [\"--debug\", self.xmlfile])\n self.assertEqual(results.exit_code, 0)\n self.assertTrue(os.path.exists(os.path.join(self.tempdir, \"fra.tokenized.xml\")))\n\n def test_with_stdin(self):\n with io.open(self.xmlfile) as f:\n inputtext = f.read()\n results = self.runner.invoke(tokenize, \"-\", input=inputtext)\n self.assertEqual(results.exit_code, 0)\n self.assertIn(\n \"Ceci est une phrase\", results.output\n )\n\n def test_file_already_exists(self):\n results = self.runner.invoke(tokenize, [self.xmlfile, self.xmlfile])\n self.assertNotEqual(results.exit_code, 0)\n self.assertIn(\"use -f to overwrite\", results.output)\n\n def test_bad_input(self):\n results = self.runner.invoke(tokenize, \"- -\", input=\"this is not XML!\")\n self.assertNotEqual(results.exit_code, 0)\n self.assertIn(\"Error parsing\", results.output)\n # LOGGER.warning(\"Output: {}\".format(results.output))\n # LOGGER.warning(\"Exception: {}\".format(results.exception))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"test/test_tokenize_cli.py","file_name":"test_tokenize_cli.py","file_ext":"py","file_size_in_byte":2919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"507786137","text":"#\r\n#introdução a programação de computadores\r\n#Professor: Jucimar JR\r\n#EQUIPE 4\r\n#\r\n#Bruno de Oliveira Freire - 1615310030\r\n#Igor Menezes Sales Vieira - 1615310007\r\n#Matheus Mota de Souza - 1615310016\r\n#Nadine da Cunha Brito - 1615310040\r\n#Nickso Patrick Façanha Calheiros - 1615310059\r\n#Thiago Santos Borges - 1615310023\r\n#\r\n\r\nN = int(input(\"N:\"))\r\ncont = 1\r\nH = 0\r\nwhile cont < (N+1):\r\n print(\"1/\",cont)\r\n H = H + (1/cont)\r\n cont = cont + 1\r\nprint(\"O resultado da serie \",H)\r\n","sub_path":"lista3/ipc_lista3.50.py","file_name":"ipc_lista3.50.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"494864146","text":"import os\n\nTEMP_DIRS=[\n 'config/{}',\n # 'data/{}/scan',\n # 'data/{}/selectelectrode/raw',\n # 'data/{}/selectelectrode/spike',\n 'data/{}/raw',\n 'data/{}/stimsig',\n 'data/{}/artifact_removal',\n # 'data/{}/spike',\n # 'data/{}/dataset',\n]\n\ndef makedirs_(path):\n if not os.path.exists(path):\n os.makedirs(path)\n\ndef render(exps):\n for exp in exps:\n for dr in TEMP_DIRS:\n path = dr.format(exp)\n makedirs_(path)","sub_path":"maxone_code/init_dirtree.py","file_name":"init_dirtree.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"633013949","text":"price = 0\r\ntotal = 0\r\ndecision = \"Y\"\r\nwhile decision == \"Y\":\r\n while price != -1 and price >= 0:\r\n total = total + price\r\n price = eval ( input ( \"Enter item price ( -1 to finish): \"))\r\n\r\n if price < 0 and price != -1:\r\n print ( \"\\nThe price cannot be a negative number.\")\r\n decision = str ( input ( \"\\nDo you want to start over?(Y/N) \" ))\r\n decision = decision.upper()\r\n price = 0\r\n print()\r\n\r\n else:\r\n total = total + (total * 0.11)\r\n decision = \"N\"\r\n print (\"\\nTotal Price:\\t$\",\"{0:.2f}\".format(total), sep = \"\")\r\n\r\ni = input (\"Enter anything to close...\")\r\n \r\n","sub_path":"Work 8 ( Price calculation Heavily validated)/Price thingy HEAAAAAVILY VALIDATED.py","file_name":"Price thingy HEAAAAAVILY VALIDATED.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"70872748","text":"'''\nDetermine whether an integer is a palindrome. Do this without extra space.\n\nclick to show spoilers.\n\nSome hints:\nCould negative integers be palindromes? (ie, -1)\n\nIf you are thinking of converting the integer to string, note the restriction of using extra space.\n\nYou could also try reversing an integer. However, if you have solved the problem \"Reverse Integer\", you know that the reversed integer might overflow. How would you handle such case?\n\nThere is a more generic way of solving this problem.\n'''\n\nclass Solution(object):\n def isPalindrome(self, x):\n \"\"\"\n :type x: int\n :rtype: bool\n \"\"\"\n x_s = str(x)\n middle_idx = len(x_s)//2\n\n for i in range(middle_idx):\n init = x_s[i]\n end = x_s[(len(x_s) - 1) - i]\n if init != end:\n return(False)\n \n return(True)\n\nif __name__ == \"__main__\":\n print(Solution().isPalindrome(123) == False)\n print(Solution().isPalindrome(12321) == True)","sub_path":"python/Easy/009_Palindrome_Number.py","file_name":"009_Palindrome_Number.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"515579194","text":"def intToRoman(num):\n \"\"\"\n :type num: int\n :rtype: str\n \"\"\"\n roman = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]\n rep = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']\n \n output = \"\"\n i = 0\n while num > 0:\n for _ in range(num//roman[i]):\n output = output + rep[i]\n num = num-roman[i]\n i = i + 1\n return output\n\nnumber = 3\nprint(intToRoman(number))","sub_path":"int_to_roman.py","file_name":"int_to_roman.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"493134685","text":"import cv2\nimport numpy as np\n\n\nclass SuspendTracking:\n\n def __init__(self, teta=3, zeta=5):\n self.teta = teta # Scalar for std influence\n self.cnt = 1 # Number of elapse frame for mean and std measures\n self.zeta = zeta\n\n self.objectHist = None\n\n self.mean = 0\n self.std = 0\n self.lost_cnt = 0\n\n def init(self, labROI):\n self.objectHist = cv2.calcHist([labROI], [1, 2], None, [\n 24, 24], [0, 256, 0, 256])\n # self.show_hist(self.objectHist, \"Object\")\n\n def calc_candidate_hist(self, lab_frame, track_box):\n mask = self.mask_roi(lab_frame, track_box)\n candidate_hist = cv2.calcHist([lab_frame], [1, 2], mask, [\n 24, 24], [0, 256, 0, 256])\n # self.show_hist(candidate_hist, \"Candidate\")\n return candidate_hist\n\n def isLost(self, lab_frame, track_box):\n candidateHist = self.calc_candidate_hist(lab_frame, track_box)\n bh_distance = cv2.compareHist(\n self.objectHist, candidateHist, cv2.HISTCMP_BHATTACHARYYA)\n prev_mean = self.mean\n prev_std = self.std\n\n adaptive_threshold = self.calc_adaptive_threshold(\n prev_mean, prev_std, self.teta)\n\n print(\"bh={:.4f} and adaptive threshold = {:.4f}\".format(\n bh_distance, adaptive_threshold))\n\n if (((bh_distance >= adaptive_threshold) and (adaptive_threshold != 0) or\n (adaptive_threshold >= 1))):\n if self.lost_cnt == self.zeta:\n print(\"=====================================================================================\")\n print(\"Suspending tracking, target lost {} times, Distance > Threshold\".format(self.lost_cnt))\n print(\"=====================================================================================\")\n self.cnt = 1\n self.mean = 0\n self.std = 0\n self.lost_cnt = 0\n return True\n else:\n self.lost_cnt += 1\n else:\n self.lost_cnt = 0 # Target found, reset lost counter\n self.mean = self.calc_new_mean(bh_distance, prev_mean, self.cnt)\n self.std = self.calc_new_std(\n bh_distance, prev_mean, self.mean, prev_std, self.cnt)\n self.cnt += 1\n\n return False\n\n @staticmethod\n def calc_new_mean(distance, prev_mean, cnt):\n mean = prev_mean + (distance - prev_mean) / cnt\n return mean\n\n @staticmethod\n def calc_new_std(distance, prev_mean, new_mean, prev_std, cnt, eps=1e-11):\n std = (cnt - 2) * (prev_std ** 2) + \\\n (distance - prev_mean) * (distance - new_mean)\n std = np.sqrt(std / (cnt - 1 + eps))\n return std\n\n @staticmethod\n def calc_adaptive_threshold(mean, std, teta):\n threshold = mean + teta * std\n return threshold\n\n # Mask the object in the frame. Return masked object\n @staticmethod\n def mask_roi(frame, track_box):\n mask = np.zeros(frame.shape[:2], dtype=\"uint8\")\n cv2.ellipse(mask, track_box, 255, -1)\n cv2.imshow(\"Masked Roi\", mask)\n return mask\n\n @staticmethod\n def show_hist(hist, type):\n bin_count = hist.shape[0]\n bin_w = 24\n img = np.zeros((256, bin_count * bin_w, 3), np.uint8)\n for i in range(bin_count):\n h = int(hist[i])\n cv2.rectangle(img, (i * bin_w + 2, 255), ((i + 1) * bin_w - 2, 255 - h),\n (int(255.0 * i / bin_count), 255, 255), -1)\n img = cv2.cvtColor(img, cv2.COLOR_LAB2BGR)\n cv2.imshow(str(type) + ' a & b Hist', img)\n","sub_path":"CVProject/SuspendTrackingLAB.py","file_name":"SuspendTrackingLAB.py","file_ext":"py","file_size_in_byte":3714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"328154995","text":"from common import headers\nfrom async_run import async_run\nimport asyncio\nimport aiohttp\nimport math\nfrom bs4 import BeautifulSoup as bs\n\n\ndef hh_salary_parse(salary: str):\n salary = salary.replace(u'\\xa0', '')\n\n min_val = max_val = math.nan\n currency = cur_type = 'none'\n if salary != 'з/п не указана':\n lst = salary.split(' ')\n if lst[-1] == 'руки':\n cur_type = 'net'\n for _ in range(2):\n lst.pop()\n else:\n cur_type = 'gross'\n for _ in range(3):\n lst.pop()\n\n currency = lst.pop()\n if len(lst) == 4:\n min_val, max_val = lst[1], lst[3]\n elif lst[0] == 'от':\n min_val = lst[1]\n else:\n max_val = lst[1]\n return float(min_val), float(max_val), currency, cur_type\n\n\ndef hh_bs_parse_dom(content):\n res = {}\n dom = bs(content, 'html.parser')\n title = dom.find('div', {'class': 'vacancy-title'})\n res['name'] = title.findChildren()[0].get_text()\n\n res['salary_min'], res['salary_max'], res['salary_currency'], res['salary_type'] = hh_salary_parse(\n title.findChildren()[1].get_text()\n )\n company_name = dom.find('a', {'class': 'vacancy-company-name'})\n if company_name:\n filtered_text = company_name.get_text().replace(u'\\xa0', ' ')\n res['company_name'] = filtered_text\n return res\n\n\nasync def parse_vacancy(session, url):\n results = {}\n try:\n async with session.get(url) as resp:\n if resp.ok:\n content = await resp.text()\n results = await async_run(hh_bs_parse_dom, content)\n results['url'] = str(resp.url).split('?')[0]\n results['site'] = 'hh.ru'\n except Exception as err:\n print(f'error: {err}')\n return results\n\n\nasync def parse_page(session, url, params):\n async with session.get(url, params=params) as resp:\n if resp.ok:\n content = await resp.text()\n a_tags = bs(content, 'html.parser').find_all('a', {'class': 'bloko-link',\n 'data-qa': 'vacancy-serp__vacancy-title'})\n return [tag['href'] for tag in a_tags]\n else:\n return []\n\n\nasync def hh_search_and_parse(search_query, pages=10, connections_limit=0):\n \"\"\"\n Search job offers on sites, parse and save to DB\n :param search_query: string\n :param pages: int, maximum number of pages\n :param connections_limit: limit connections if needed\n \"\"\"\n search_url = \"https://hh.ru/search/vacancy\"\n params = {'text': search_query}\n conn = aiohttp.TCPConnector(limit=connections_limit)\n async with aiohttp.ClientSession(headers=headers, connector=conn) as session:\n async with session.get(search_url, params=params) as resp:\n params = range(0, pages)\n urls = await asyncio.gather(*[parse_page(session, resp.url, {'page': param}) for param in params],\n return_exceptions=False)\n res = await asyncio.gather(*[parse_vacancy(session, url) for x in urls for url in x if url],\n return_exceptions=False)\n return res\n","sub_path":"HW2/hhru_parser.py","file_name":"hhru_parser.py","file_ext":"py","file_size_in_byte":3255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"394599166","text":"\"\"\"The navie algorithm that directly trains ranking models with clicks.\n\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\nimport os\nimport random\nimport sys\nimport tensorflow as tf\n\nfrom tensorflow import dtypes\nfrom ultra.learning_algorithm.base_algorithm import BaseAlgorithm\nimport ultra.utils\n\n\nclass NavieMTLAlgorithm(BaseAlgorithm):\n \"\"\"The navie algorithm that directly trains ranking models with input labels.\n\n \"\"\"\n\n def __init__(self, data_set, exp_settings, forward_only=False):\n \"\"\"Create the model.\n\n Args:\n data_set: (Raw_data) The dataset used to build the input layer.\n exp_settings: (dictionary) The dictionary containing the model settings.\n forward_only: Set true to conduct prediction only, false to conduct training.\n \"\"\"\n print('Build NavieAlgorithm')\n\n self.hparams = ultra.utils.hparams.HParams(\n learning_rate=0.05, # Learning rate.\n max_gradient_norm=5.0, # Clip gradients to this norm.\n loss_funcs=['sigmoid_cross_entropy', 'mse_loss'], # Select Loss function\n loss_enable_sigmoid=True, # whether enable sigmoid on prediction when calculate loss\n # Set strength for L2 regularization.\n l2_loss=0.0,\n grad_strategy='ada', # Select gradient strategy\n tasks=[\"click\", \"watchtime\"],\n output_acts=['identity', 'identity'],\n enable_esmm=False,\n esmm_stop_gradient=False\n )\n self.hparams.parse(exp_settings['learning_algorithm_hparams'])\n print(\"hparams:\", self.hparams)\n self.exp_settings = exp_settings\n self.model = None\n self.max_candidate_num = exp_settings['max_candidate_num']\n self.feature_size = data_set.feature_size\n self.learning_rate = tf.Variable(\n float(self.hparams.learning_rate), trainable=False)\n\n # Feeds for inputs.\n self.is_training = tf.placeholder(tf.bool, name=\"is_train\")\n self.docid_inputs = [] # a list of top documents\n self.letor_features = tf.placeholder(tf.float32, shape=[None, self.feature_size],\n name=\"letor_features\") # the letor features for the documents\n self.labels = [] # the labels for the documents (e.g., clicks)\n for i in range(self.max_candidate_num):\n self.docid_inputs.append(tf.placeholder(tf.int64, shape=[None],\n name=\"docid_input{0}\".format(i)))\n self.labels.append(tf.placeholder(tf.float32, shape=[None, len(self.hparams.tasks)],\n name=\"label{0}\".format(i)))\n\n self.global_step = tf.Variable(0, trainable=False)\n\n # Build model\n self.outputs = self.ranking_model(\n self.max_candidate_num, scope='ranking_model', forward_only=True) # forward_only: do not use bias tower\n for task_idx in range(0, len(self.hparams.tasks)):\n loss_func = self.hparams.loss_funcs[task_idx]\n output_act = self.hparams.output_acts[task_idx]\n print(\"loss func:\", loss_func)\n print(\"output_act:\", output_act)\n #if str(loss_func) == 'sigmoid_cross_entropy':\n if str(output_act) == 'sigmoid':\n print(\"sigmoid on task \", self.hparams.tasks[task_idx])\n output = tf.nn.sigmoid(self.outputs[task_idx])\n else:\n print(\"identity on task \", self.hparams.tasks[task_idx])\n output = self.outputs[task_idx]\n if task_idx == 0:\n self.output = output\n #self.output = self.outputs[task_idx]\n else:\n if self.hparams.enable_esmm:\n print(\"enable esmm for task %s when calculate test metric\" % self.hparams.tasks[task_idx])\n output = tf.nn.sigmoid(self.outputs[0]) * output\n self.output += output\n #self.output += self.outputs[task_idx]\n\n # reshape from [max_candidate_num, ?] to [?, max_candidate_num]\n reshaped_labels = tf.transpose(tf.convert_to_tensor(tf.reduce_sum(self.labels, axis=-1)))\n print(\"reshaped_labels:\", reshaped_labels)\n print(\"self.output:\", self.output)\n pad_removed_output = self.remove_padding_for_metric_eval(\n self.docid_inputs, self.output)\n print(\"pad_removed_output:\", pad_removed_output)\n for metric in self.exp_settings['metrics']:\n for topn in self.exp_settings['metrics_topn']:\n metric_value = ultra.utils.make_ranking_metric_fn(\n metric, topn)(reshaped_labels, pad_removed_output, None)\n tf.summary.scalar(\n '%s_%d' %\n (metric, topn), metric_value, collections=['eval'])\n\n if not forward_only:\n # Build model\n self.rank_list_size = exp_settings['selection_bias_cutoff']\n train_outputs = self.ranking_model(\n self.rank_list_size, scope='ranking_model', forward_only=forward_only) # [batch_size, rank_list_size]\n train_labelss = self.labels[:self.rank_list_size] # [rank_list_size, batch_size, task_num]\n\n for task_idx, task in enumerate(self.hparams.tasks):\n train_labels = [tf.squeeze(tf.slice(train_label, [0,task_idx], [-1,1]), axis=-1) for train_label in train_labelss]\n print(\"train_labels:\", train_labels)\n train_output = train_outputs[task_idx]\n if task_idx == 1 and self.hparams.enable_esmm:\n print(\"enable esmm for task %s when calculate loss\" % self.hparams.tasks[task_idx])\n if self.hparams.esmm_stop_gradient:\n print(\"stop gradient on click when calculate loss\")\n pred_click = tf.stop_gradient(tf.nn.sigmoid(train_outputs[0]))\n else:\n pred_click = tf.nn.sigmoid(train_outputs[0])\n train_output = train_output * pred_click\n tf.summary.scalar(\n 'Max_output_score_%s' %task,\n tf.reduce_max(train_output),\n collections=['train'])\n tf.summary.scalar(\n 'Min_output_score_%s' %task,\n tf.reduce_min(train_output),\n collections=['train'])\n\n # reshape from [rank_list_size, ?] to [?, rank_list_size]\n reshaped_train_labels = tf.transpose(\n tf.convert_to_tensor(train_labels))\n print(\"reshaped_train_labels:\", reshaped_train_labels)\n pad_removed_train_output = self.remove_padding_for_metric_eval(\n self.docid_inputs, train_output)\n\n tf.summary.scalar(\n 'Max_output_score_without_pad_%s' %task,\n tf.reduce_max(pad_removed_train_output),\n collections=['train'])\n tf.summary.scalar(\n 'Min_output_score_without_pad_%s' %task,\n tf.reduce_min(pad_removed_train_output),\n collections=['train'])\n\n loss = None\n if self.hparams.loss_funcs[task_idx] == 'sigmoid_cross_entropy':\n print(\"sigmoid_cross_entropy loss on task \", self.hparams.tasks[task_idx])\n loss = self.sigmoid_loss_on_list(\n train_output, reshaped_train_labels, enable_sigmoid=self.hparams.loss_enable_sigmoid)\n elif self.hparams.loss_funcs[task_idx] == 'pairwise_loss':\n print(\"pairwise_loss on task \", self.hparams.tasks[task_idx])\n loss = self.pairwise_loss_on_list(\n train_output, reshaped_train_labels)\n elif self.hparams.loss_funcs[task_idx] == \"mse_loss\":\n print(\"mse_loss on task \", self.hparams.tasks[task_idx])\n loss = self.mse_loss_on_list(\n train_output, reshaped_train_labels)\n else:\n print(\"softmax_loss on task \", self.hparams.tasks[task_idx])\n loss = self.softmax_loss(\n train_output, reshaped_train_labels)\n if task_idx == 0:\n self.loss = loss\n else:\n self.loss += loss\n params = tf.trainable_variables()\n if self.hparams.l2_loss > 0:\n loss_l2 = 0.0\n for p in params:\n loss_l2 += tf.nn.l2_loss(p)\n tf.summary.scalar(\n 'L2 Loss',\n tf.reduce_mean(loss_l2),\n collections=['train'])\n self.loss += self.hparams.l2_loss * loss_l2\n\n # Select optimizer\n self.optimizer_func = tf.train.AdagradOptimizer\n if self.hparams.grad_strategy == 'sgd':\n self.optimizer_func = tf.train.GradientDescentOptimizer\n\n # Gradients and SGD update operation for training the model.\n opt = self.optimizer_func(self.hparams.learning_rate)\n self.gradients = tf.gradients(self.loss, params)\n if self.hparams.max_gradient_norm > 0:\n self.clipped_gradients, self.norm = tf.clip_by_global_norm(self.gradients,\n self.hparams.max_gradient_norm)\n self.updates = opt.apply_gradients(zip(self.clipped_gradients, params),\n global_step=self.global_step)\n tf.summary.scalar(\n 'Gradient Norm',\n self.norm,\n collections=['train'])\n else:\n self.norm = None\n self.updates = opt.apply_gradients(zip(self.gradients, params),\n global_step=self.global_step)\n tf.summary.scalar(\n 'Learning Rate',\n self.learning_rate,\n collections=['train'])\n tf.summary.scalar(\n 'Loss', tf.reduce_mean(\n self.loss), collections=['train'])\n for task_idx in range(0, len(self.hparams.tasks)):\n output_act = self.hparams.output_acts[task_idx]\n #if self.hparams.loss_funcs[task_idx] == 'sigmoid_cross_entropy':\n if str(output_act) == 'sigmoid':\n print(\"sigmoid on task \", self.hparams.tasks[task_idx])\n train_output = tf.nn.sigmoid(train_outputs[task_idx])\n else:\n print(\"identity on task \", self.hparams.tasks[task_idx])\n train_output = train_outputs[task_idx]\n if task_idx == 0:\n train_output_sum = train_output\n else:\n if self.hparams.enable_esmm:\n print(\"enable esmm for task %s when calculate train metric\" % self.hparams.tasks[task_idx])\n train_output = tf.nn.sigmoid(train_outputs[0]) * train_output\n train_output_sum += train_output\n print(\"train_output_sum:\", train_output_sum)\n print(\"train_labelss:\", train_labelss)\n reshaped_train_labels_sum = tf.transpose(\n tf.reduce_sum(tf.convert_to_tensor(train_labelss), axis=-1))\n print(\"reshaped_train_labels_sum:\", reshaped_train_labels_sum)\n pad_removed_train_output = self.remove_padding_for_metric_eval(\n self.docid_inputs, train_output_sum)\n for metric in self.exp_settings['metrics']:\n for topn in self.exp_settings['metrics_topn']:\n metric_value = ultra.utils.make_ranking_metric_fn(metric, topn)(\n reshaped_train_labels_sum, pad_removed_train_output, None)\n tf.summary.scalar(\n '%s_%d' %\n (metric, topn), metric_value, collections=['train'])\n\n self.train_summary = tf.summary.merge_all(key='train')\n self.eval_summary = tf.summary.merge_all(key='eval')\n self.saver = tf.train.Saver(tf.global_variables())\n\n def step(self, session, input_feed, forward_only):\n \"\"\"Run a step of the model feeding the given inputs.\n\n Args:\n session: (tf.Session) tensorflow session to use.\n input_feed: (dictionary) A dictionary containing all the input feed data.\n forward_only: whether to do the backward step (False) or only forward (True).\n\n Returns:\n A triple consisting of the loss, outputs (None if we do backward),\n and a tf.summary containing related information about the step.\n\n \"\"\"\n\n # Output feed: depends on whether we do a backward step or not.\n if not forward_only:\n input_feed[self.is_training.name] = True\n output_feed = [\n self.updates, # Update Op that does SGD.\n self.loss, # Loss for this batch.\n self.train_summary # Summarize statistics.\n ]\n else:\n input_feed[self.is_training.name] = False\n output_feed = [\n self.eval_summary, # Summarize statistics.\n self.output # Model outputs\n ]\n outputs = session.run(output_feed, input_feed)\n if not forward_only:\n # loss, no outputs, summary.\n return outputs[1], None, outputs[-1]\n else:\n return None, outputs[1], outputs[0] # loss, outputs, summary.\n","sub_path":"ultra/learning_algorithm/navie_mtl_algorithm.py","file_name":"navie_mtl_algorithm.py","file_ext":"py","file_size_in_byte":13963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"15467054","text":"from faker import Faker\nfrom datetime import date, timedelta\nfrom healthid.tests.base_config import BaseConfiguration\nfrom healthid.tests.test_fixtures.consultations import (\n retrieve_consultations)\nfrom healthid.tests.test_fixtures.consultations import (\n retrieve_consultation,\n retrieve_booking,\n book_consultation,\n update_consultation,\n delete_booked_consultation,\n query_all_bookings,\n retrieve_paginated_consultations,\n create_consultations,\n edit_consultation_item,\n delete_consultation_item,\n add_medical_notes,\n query_all_paginated_bookings\n)\nfrom healthid.tests.factories import (\n ConsultationItemFactory, CustomerFactory, CustomerConsultationFactory,\n OutletFactory)\nfrom healthid.utils.messages.consultation_reponses import \\\n CONSULTATION_ERROR_RESPONSES\n\nfake = Faker()\n\n\nclass TestQueryConsultation(BaseConfiguration):\n def setUp(self):\n super(TestQueryConsultation, self).setUp()\n self.consultation_item = ConsultationItemFactory(\n consultation_name=fake.word(),\n description=fake.text(max_nb_chars=50),\n consultant_role=\"Pharmacist\",\n approved_delivery_formats=[\"Telephonic\"],\n business_id=self.business.id,\n minutes_per_session=fake.random_int(min=1, max=60),\n price_per_session=fake.random_int()\n )\n self.new_outlet = OutletFactory(name=fake.word())\n self.customer_2 = CustomerFactory()\n self.customer_consultation = CustomerConsultationFactory(\n customer=self.customer_2)\n\n def test_user_can_retrieve_consultations(self):\n response = self.query_with_token(\n self.access_token, retrieve_consultations)\n self.assertEqual(\n response['data']['consultations'][0]['id'],\n str(self.consultation_item.id))\n\n def test_user_queries_from_a_different_business(self):\n self.consultation_item2 = ConsultationItemFactory(\n consultation_name=fake.word(),\n description=fake.text(max_nb_chars=50),\n consultant_role=\"Pharmacist\",\n approved_delivery_formats=[\"Telephonic\"],\n minutes_per_session=fake.random_int(min=1, max=60),\n price_per_session=fake.random_int()\n )\n response = self.query_with_token(\n self.access_token, retrieve_consultation.format(\n consultation_id=self.consultation_item2.id))\n expected_message = CONSULTATION_ERROR_RESPONSES[\n \"consultation_doesnot_exist_error\"]\n self.assertEqual(response['errors'][0]['message'], expected_message)\n\n def test_consultation_id_doesnot_exist(self):\n consultation_invalid_id = 0\n response = self.query_with_token(\n self.access_token, retrieve_consultation.format(\n consultation_id=consultation_invalid_id))\n expected_message = CONSULTATION_ERROR_RESPONSES[\"invalid_id\"].format(\n consultation_invalid_id)\n self.assertIn(expected_message, response['errors'][0]['message'])\n\n def test_query_booking(self):\n booked_consultation = self.schedule_consultation()\n response = self.query_with_token(\n self.access_token, retrieve_booking.format(\n id=booked_consultation.id\n )\n )\n\n self.assertIsNotNone(response)\n\n def test_book_consultation(self):\n response = self.query_with_token(\n self.access_token,\n book_consultation.format(\n self.customer_consultation.customer.id,\n self.consultation_item.id,\n self.outlet.id,\n date.today() + timedelta(days=3)\n )\n )\n self.assertEqual(\n 'Now',\n response['data']['bookConsultation']['bookConsultation']['status']\n )\n\n def test_update_consultation(self):\n response = self.query_with_token(\n self.access_token,\n update_consultation.format(\n self.customer_consultation.id,\n date.today() + timedelta(days=5)\n )\n )\n self.assertIsNotNone(response)\n\n def test_delete_booked_consultation(self):\n response = self.query_with_token(\n self.access_token_master,\n delete_booked_consultation.format(\n id=self.customer_consultation.id\n ))\n\n self.assertIn(\n 'successfully',\n response['data']['deleteBookedConsultation']['message']\n )\n\n def test_query_paginated_consultations(self):\n response = self.query_with_token(\n self.access_token,\n retrieve_paginated_consultations,\n )\n\n self.assertEqual(\n 1,\n response['data']['totalConsultationsPagesCount']\n )\n\n def test_create_consultation_item(self):\n response = self.query_with_token(\n self.access_token_master,\n create_consultations.format(\n business_id=self.business.id\n )\n )\n\n self.assertIn(\n 'bone marrow',\n response['data']['createConsultationItem']\n ['consultation']['description']\n )\n\n def test_edit_consultation_item(self):\n response = self.query_with_token(\n self.access_token_master,\n edit_consultation_item.format(\n self.consultation_item.id\n )\n )\n\n self.assertEqual(\n f\"{self.consultation_item.id}\",\n response['data']['editConsultationItem']['consultation']['id']\n )\n\n def test_delete_consultation_item(self):\n response = self.query_with_token(\n self.access_token_master,\n delete_consultation_item.format(\n self.consultation_item.id\n )\n )\n\n self.assertIn(\n 'deleted successfully',\n response['data']['deleteConsultationItem']['message']\n )\n\n def test_add_medical_notes(self):\n\n medical_note = 'Medical notes added'\n response = self.query_with_token(\n self.access_token_master,\n add_medical_notes.format(\n self.customer_consultation.id,\n medical_note)\n )\n\n self.assertEqual(\n medical_note,\n response['data']['addMedicalNotes']['addNotes']['medicalNotes']\n )\n\n def test_query_bookings(self):\n self.schedule_consultation()\n response = self.query_with_token(\n self.access_token_master, query_all_bookings\n )\n\n self.assertEqual(\n 'Now',\n response['data']['bookings'][0]['status']\n )\n\n def test_query_paginated_bookings(self):\n self.schedule_consultation()\n response = self.query_with_token(\n self.access_token_master,\n query_all_paginated_bookings\n )\n\n self.assertEqual(\n 'Now',\n response['data']['bookings'][0]['status']\n )\n","sub_path":"healthid/tests/consultation/test_query_consultation.py","file_name":"test_query_consultation.py","file_ext":"py","file_size_in_byte":7031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"335109607","text":"# -*- coding: utf8 -*-\n\n\"\"\"Parser module for Bibliography Analyzer Utility.\nby Tobias Küster, 2015\n\n- parse bib items from simple lists\n- parse bib items from bibtex files\n\"\"\"\n\nimport re\nfrom bib_model import BibItem\n\n\ndef parse_bib(filename, entry_regex, parse_func):\n\t\"\"\"Read file and parse bibliography items.\n\t- filename is the name of the file\n\t- entry_regex is a regular expression matching a single bibliography item\n\t- parse_func is a function mapping that item (a string) to a BibItem\n\t- returns an according list of BibItems\n\t\"\"\"\n\twith open(filename) as f:\n\t\treturn filter(None, (parse_func(item.group()) \n\t\t for item in re.finditer(entry_regex, f.read())))\n\ndef make_parse_func(authors_regex, title_regex, year_regex, author_sep=\",\"):\n\t\"\"\"Create and return a function creating BibItems using regular expressions\n\tfor title, author and year.\n\t\"\"\"\n\tdef func(item):\n\t\t\"\"\"function parsing item (a string) to BibItem object.\n\t\t\"\"\"\n\t\textract = lambda regex: re.search(regex, item).group(1) if regex else None\n\t\ttry:\n\t\t\tauthors = extract(authors_regex)\n\t\t\ttitle = extract(title_regex)\n\t\t\tyear = extract(year_regex)\n\t\t\tauthor_list = [author.strip() for author in authors.split(author_sep)]\n\t\t\treturn BibItem(author_list, title, year)\n\t\texcept Exception as e:\n\t\t\tprint(\"WARNING: Could not parse item: \\n\" + item)\n\t\t\tprint(\"Error was: \", e)\n\t\t\t\n\treturn func\n\ndef parse_bib_from_list(filename):\n\t\"\"\"Parse list of bibliography items from simple text file, assuming format\n\tTITEL: \n\tAUTOR: \n\t\"\"\"\n\tentry_regex = r\"TITEL: .*\\s*AUTOR: .*\"\n\tparse_func = make_parse_func(r\"AUTOR: (.*)\", r\"TITEL: (.*)\", None)\n\treturn parse_bib(filename, entry_regex, parse_func)\n\ndef parse_bib_from_bibtex(filename):\n\t\"\"\"Parse list of bibliography items from Bibtex file. Bibtex is not a \n\tregular language, but assuming that each entry starts and ends at the \n\tbeginning of a line, we can still get some good results with a regex.\n\t\"\"\"\n\tentry_regex = r'''\n\t\t\t(?msx) # flags: multi-line, dot-match-all, verbose\n\t\t\t^@\\w+\\{ # start of line, item type\n\t\t\t.*? # content, can span multiple lines, non-greedy\n\t\t\t^\\} # start of line, closing parens\n\t\t\t'''\n\tattr_regex = r'''\n\t\t\t(?ix) # flags: ignore-case, verbose\n\t\t\t\\s* # leading space\n\t\t\t%s # what to match: author, title, or year\n\t\t\t\\s*=\\s* # space and equals\n\t\t\t[{\\\"'] # opening parens\n\t\t\t(.*) # the actual author, title, or year\n\t\t\t[}\\\"'] # closing parens or quote\n\t\t\t\\,? # optional comma\n\t\t\t'''\n\tparse_func = make_parse_func(attr_regex % \"author\", attr_regex % \"title\", \n\t attr_regex % \"year\", \" and \")\n\treturn parse_bib(filename, entry_regex, parse_func)\n\n\n# just for testing...\nif __name__ == \"__main__\":\n\t# items = parse_bib_from_list(\"AAMAS 2013.txt\")\n\titems = parse_bib_from_bibtex(\"literature.bib\")\n\tfor item in items:\n\t\tprint(item)\n","sub_path":"BibAnalyzer/bib_parser.py","file_name":"bib_parser.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"481608883","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom selenium import webdriver\nimport unittest\n\nclass HiPOUnit(unittest.TestCase):\n def __init__(self, methodName='HiPORunTest', param=None):\n super(HiPOUnit, self).__init__(methodName)\n self.param = param\n\n def setUp(self):\n self.verificationErrors = []\n self.accept_next_alert = True\n\n chromedriver = \"C:/chromedriver.exe\"\n self.driver = webdriver.Chrome(chromedriver)\n\n def tearDown(self):\n self.driver.quit()\n self.assertEqual([], self.verificationErrors)\n\n @staticmethod\n def TestCaseWithClass(testcase_class ,lines, param=None):\n '''\n 依据传入的测试类将其下面全部的测试方法加入测试套\n :param testcase_class:测试类的类名\n :param lines:参数行数(参数文件有多少行参数)\n :param param:参数池是一个dict类型\n :return:无\n '''\n testloader = unittest.TestLoader()\n testnames = testloader.getTestCaseNames(testcase_class)\n suite = unittest.TestSuite()\n i = 0\n while i < lines:\n for name in testnames:\n suite.addTest(testcase_class(name, param=param[i]))\n i = i + 1\n return suite\n\n @staticmethod\n def TestCaseWithFunc(testcase_class, testcase_fun, lines, param=None):\n \"\"\"\n 通过给定的类及其内部的测试方法将测试用例加入测试套件中\n :param testcase_class:testcase类名\n :param testcase_fun:要执行的以test_开头的函数名\n :param lines:参数行数(参数文件有多少行参数)\n :param param:参数池是一个dict类型\n :return:无\n \"\"\"\n suite = unittest.TestSuite()\n i = 0\n while i < lines:\n suite.addTest((testcase_class(testcase_fun, param=param[i])))\n i = i + 1\n return suite","sub_path":"hi_po/hi_po_unit.py","file_name":"hi_po_unit.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"167620996","text":"#!/usr/bin/env python\nimport argparse\n\nimport chainer\nimport chainer.functions as F\nimport chainer.links as L\nfrom chainer import training\nfrom chainer.training import extensions\n\n\n# Network definition\nclass MLP(chainer.Chain):\n\n def __init__(self, num_class, train=True):\n super(MLP, self).__init__()\n with self.init_scope():\n # the size of the inputs to each layer will be inferred\n self.conv1 = L.Convolution2D(None, 64, 3, stride= 1, pad=1)\n self.conv2 = L.Convolution2D(None, 64, 3, stride= 1, pad=1)\n\n self.conv3 = L.Convolution2D(None, 128, 3, stride= 1, pad=1)\n self.conv4 = L.Convolution2D(None, 128, 3, stride= 1, pad=1)\n\n self.conv5 = L.Convolution2D(None, 256, 3, stride= 1, pad=1)\n self.conv6 = L.Convolution2D(None, 256, 3, stride= 1, pad=1)\n self.conv7 = L.Convolution2D(None, 256, 3, stride= 1, pad=1)\n\n self.conv8 = L.Convolution2D(None, 512, 3, stride= 1, pad=1)\n self.conv9 = L.Convolution2D(None, 512, 3, stride= 1, pad=1)\n self.conv10 = L.Convolution2D(None, 512, 3, stride= 1, pad=1)\n\n self.conv11 = L.Convolution2D(None, 512, 3, stride= 1, pad=1)\n self.conv12 = L.Convolution2D(None, 512, 3, stride= 1, pad=1)\n self.conv13 = L.Convolution2D(None, 512, 3, stride= 1, pad=1)\n\n self.fc14 = L.Linear(None, 4096) # n_in -> n_units\n self.fc15 = L.Linear(None, 4096) # n_units -> n_units\n self.fc16 = L.Linear(None, num_class) # n_units -> n_out\n\n def forward(self, x):\n h = F.relu(self.conv1(x))\n h = F.max_pooling_2d(F.local_response_normalization(F.relu(self.conv2(h))), 2, stride=2)\n\n h = F.relu(self.conv3(h))\n h = F.max_pooling_2d(F.local_response_normalization(F.relu(self.conv4(h))), 2, stride=2)\n\n h = F.relu(self.conv5(h))\n h = F.relu(self.conv6(h))\n h = F.max_pooling_2d(F.local_response_normalization(F.relu(self.conv7(h))), 2, stride=2)\n\n h = F.relu(self.conv8(h))\n h = F.relu(self.conv9(h))\n h = F.max_pooling_2d(F.local_response_normalization(F.relu(self.conv10(h))), 2, stride=2)\n\n h = F.relu(self.conv11(h))\n h = F.relu(self.conv12(h))\n h = F.max_pooling_2d(F.local_response_normalization(F.relu(self.conv13(h))), 2, stride=2)\n\n h = F.dropout(F.relu(self.fc14(h)))\n h = F.dropout(F.relu(self.fc15(h)))\n return self.fc16(h)\n\n\n","sub_path":"vgg_model_horce2zebra.py","file_name":"vgg_model_horce2zebra.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"481291196","text":"# Copyright 2021 PerfKitBenchmarker Authors. 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\"\"\"Class to represent a Equinix Virtual Machine object (BareMetal).\n\"\"\"\nfrom perfkitbenchmarker import errors\nfrom perfkitbenchmarker import providers\nfrom perfkitbenchmarker import virtual_machine\nfrom perfkitbenchmarker import vm_util\nfrom perfkitbenchmarker.providers.equinixmetal import util\nfrom six.moves import range\nfrom perfkitbenchmarker import linux_virtual_machine as linux_vm\nCLOUD_CONFIG_TEMPLATE = '''#cloud-config\nusers:\n - name: {0}\n ssh-authorized-keys:\n - {1}\n sudo: ['ALL=(ALL) NOPASSWD:ALL']\n groups: sudo\n shell: /bin/bash\nruncmd:\n - [ passwd, -l, root ]\n - [ chage, -d, -1, -I, -1, -E, -1, -M, 999999, root ]\n'''\n\n\nclass MetalVirtualMachine(virtual_machine.BaseVirtualMachine):\n \"\"\"Object representing a Baremetal Virtual Machine .\"\"\"\n\n CLOUD = providers.EQUINIXMETAL\n # Subclasses should override the default image.\n DEFAULT_IMAGE = None\n \n\n def __init__(self, vm_spec):\n \"\"\"Initialize a BareMetal virtual machine.\n\n Args:\n vm_spec: virtual_machine.BaseVirtualMachineSpec object of the vm.\n \"\"\"\n super(MetalVirtualMachine, self).__init__(vm_spec)\n self.device_id = None\n self.max_local_disks = 1\n self.local_disk_counter = 0\n self.image = self.image or self.DEFAULT_IMAGE\n \n\n def _Create(self):\n \"\"\"Create a BareMetal instance .\"\"\"\n with open(self.ssh_public_key) as f:\n public_key = f.read().rstrip('\\n')\n\n response, retcode = util.MetalAndParse(\n ['device', 'create', \n '--hostname', self.name,\n '--metro', self.zone, #metro\n '--plan', self.machine_type, #plan\n '--operating-system', self.image, #OS\n '--userdata', CLOUD_CONFIG_TEMPLATE.format(\n self.user_name, public_key)\n ])\n if retcode:\n raise errors.Resource.RetryableCreationError('Creation failed: %s' %\n (response,))\n self.device_id = response['id']\n\n @vm_util.Retry()\n def _PostCreate(self):\n \"\"\"Get the instance's data.\"\"\"\n response, retcode = util.MetalAndParse(\n ['device', 'get', '-i', self.device_id])\n for interface in response['ip_addresses']:\n if interface['address_family'] != 4:\n continue\n if interface['public'] == True:\n self.ip_address = interface['address']\n else:\n self.internal_ip = interface['address']\n\n def _Delete(self):\n \"\"\"Delete a BareMetal VM Device.\"\"\"\n\n response, retcode = util.MetalAndParse(\n ['device', 'delete', '-i', self.device_id, '--force'])\n # The command doesn't return the HTTP status code, and the error\n # format is very difficult to parse, so we string\n # search. \n if retcode and '404' in response['errors'][0]['detail']:\n return\n elif retcode:\n raise errors.Resource.RetryableDeletionError('Deletion failed: %s' %\n (response,))\n\n def _Exists(self):\n \"\"\"Returns true if the VM exists.\"\"\"\n\n response, retcode = util.MetalAndParse(\n ['device', 'get', '-i', self.device_id])\n\n return retcode == 0\n\nclass Ubuntu1804BasedEquinixVirtualMachine(\n MetalVirtualMachine, linux_vm.Ubuntu1804Mixin):\n \"\"\"\n Equinix Metal\n \"\"\"\n","sub_path":"perfkitbenchmarker/providers/equinixmetal/equinix_virtual_machine.py","file_name":"equinix_virtual_machine.py","file_ext":"py","file_size_in_byte":3816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"377405439","text":"\nclass MIFARE1k(object):\n SECTORS = 16\n BLOCKSIZE = 4\n BLOCKWITH = 16\n\n def __init__(self, uid, data):\n self.uid = uid\n self.data = data\n\n def __str__(self):\n \"\"\"\n Get a nice printout for debugging and dev.\n \"\"\"\n ret = \"Card: \"\n for i in range(4):\n if i > 0:\n ret = ret + \":\"\n ret = ret + format(self.uid[i], '02x').upper()\n ret = ret + \"\\n\"\n for sector in range(self.SECTORS):\n ret = ret + \"------------------------Sector \" + str(sector)\n if sector < 10:\n ret = ret + \"-\"\n ret = ret + \"------------------------\\n\"\n for b in range(self.BLOCKSIZE):\n block = b + self.BLOCKSIZE * sector\n ret = ret + \"Block \" + str(block)\n if (block) < 10:\n ret = ret + \" \"\n for i in range(self.BLOCKWITH):\n pos = i + block * self.BLOCKWITH\n he = \"0x\" + format(self.data[pos], '02x').upper()\n ret = ret + \" \" + he\n ret = ret + \" \"\n\n for i in range(self.BLOCKWITH):\n pos = i + block * self.BLOCKWITH\n a = \".\"\n if self.data[pos] > 0:\n a = chr(self.data[pos])\n ret = ret + a\n ret = ret + \"\\n\"\n return ret\n\n def get_data(self):\n \"\"\"\n Userdata is Sector 1 til 16, and only the first 3 blocks.\n \"\"\"\n ret = []\n for sector in range(1, self.SECTORS):\n for b in range(self.BLOCKSIZE - 1):\n block = b + self.BLOCKSIZE * sector\n for i in range(self.BLOCKWITH):\n pos = i + block * self.BLOCKWITH\n ret.append(self.data[pos])\n return ret\n\n\n def get_messages(self):\n \"\"\"\n give back all data blocks inside a TLV Messageblock:\n 0x03 0x00-0xFE => 1 byte for message length\n 0x03 0xFF 0x0000-0xFFFE => 2 bytes for message length\n 0xFE => Terminator\n 0x00 => Ignore\n 0xFD => Proprietary TLV => Ignore / To Implement\n \"\"\"\n ret = []\n data = self.get_data()\n buf = []\n T = 0x00 # Store the current tag field\n L = 0x00 # Store the length 1 byte format\n L2 = 0x00 # Store the length 3 bytes format, temp value (MSB)\n Lc = 0 # current length\n for val in data:\n if T == 0x03:\n if L == 0x00:\n L = val\n continue\n if L == 0xFF:\n if L2 == 0x00:\n L2 = val << 8\n continue\n else:\n L = L2 + val\n L2 = 0x00\n continue\n # length is set:\n if Lc < L:\n buf.append(val)\n Lc = Lc + 1\n continue\n if Lc == L:\n if not val == 0xFE:\n print(\"Error: Length and Terminator did not fit!\")\n ret.append(buf)\n buf = []\n Lc = 0x00\n L = 0x00\n T = val\n continue\n T = val # should be 0x00 or 0x03, we only care if it is 0x03 for the next val.\n\n return ret\n\n def __eq__(self, other):\n if other == None:\n return False\n return self.uid == other.uid and self.data == other.data\n","sub_path":"pirc522/mifare1k.py","file_name":"mifare1k.py","file_ext":"py","file_size_in_byte":3643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"40749756","text":"#!/usr/bin/env python\n\nfrom gimpfu import *\nimport gimp\nimport pygtk\npygtk.require(\"2.0\")\nimport gtk\n\n\t#definition de la classe Tile\nclass Tile:\n\tdef __init__(self, x, y, ID):\n\t\tself._x = x\n\t\tself._y = y\n\t\tself._ID = ID\n\tdef _get_x(self):\n\t\treturn self._x\n\tdef _get_y(self):\n\t\treturn self._y\n\tdef _get_ID(self):\n\t\treturn self._ID\n\tx = property(_get_x)\n\ty = property(_get_y)\n\tID = property(_get_ID)\n\ndef messBox(message, GTKtype, modal):\n\tif modal == 0: \n\t\tflag = gtk.DIALOG_DESTROY_WITH_PARENT \n\telse: \n\t\tflag = gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT\n\t\tmsgBox = gtk.MessageDialog(None, flag, GTKtype, gtk.BUTTONS_OK, message)\n\t\tret = msgBox.run()\n\t\tmsgBox.destroy()\n\n\t#retourne les valeurs RVB d'un pixel\ndef getRVB(pixel):\n\tR, V, B = pixel[0], pixel[1], pixel[2]\n\treturn R, V, B\n\ndef tileSetDumper(calque, IDmin, fileName):\n\t\t# init taille et transparence\n\twidth = calque.width / 16\n\theight = calque.height / 16\n\ttransparency = 255\n\ttiles = list()\n\tID = IDmin\n\tstrParasite = str(IDmin)\n\tparasite = calque.parasite_find(\"IDmin\")\n\t\t# Verifie si le tileset a deja ete ecrit dans un fichier\n\tif (type(parasite).__name__ == \"Parasite\"):\n\t\tmessBox(\"TileSet already dumped !\\nNothing to do.\", gtk.MESSAGE_INFO, 1)\n\t\treturn\n\n\t\t# charge les tuiles dans une liste\n\tfor y in range(0, calque.height, 16):\n\t\tfor x in range(0, calque.width, 16):\n\t\t\t\t# evite les tuiles noire pure\n\t\t\tif(getRVB(calque.get_pixel(x, y)) != (0, 0, 0)):\n\t\t\t\ttiles.append(Tile(x, y, ID))\n\t\t\t\tID = ID + 1\n\tcalque.attach_new_parasite(\"IDmin\", 1, strParasite)\n\t\t# nombre total de tuiles\n\tquantity = len(tiles)\n\t\t# ouvre et ecrit le fichier xml\n\tFile = open(fileName, \"w\")\n\tFile.write('\\n')\n\tFile.write('\\n')\n\tFile.write(' \\n')\n\tFile.write(' \\n')\n\tFile.write(' \\n')\n\tFile.write(' \\n')\n\tfor elem in range(len(tiles)):\n\t\tFile.write(' \\n')\n\t\tFile.write(' \\n')\n\t\tFile.write(' false\\n')\n\t\tFile.write(' \\n')\n\t\tFile.write(' \\n')\n\t\tFile.write(' \\n')\n\t\tFile.write(' \\n')\n\t\tFile.write(' \\n')\n\t\tFile.write(' \\n')\n\t\tFile.write(' \\n')\n\tFile.write('')\n\tFile.close()\n\tmessBox(\"TileSet dumped to:\\n.\" + fileName, gtk.MESSAGE_INFO, 1)\n\treturn\n\nregister(\n\t\"tileSetDumper\",\n\t\"Tileset Dumper\",\n\t\"Dump the tileset into an XML file.\",\n\t\"Fabrice Lambert\",\n\t\"Fabrice Lambert\",\n\t\"2012\",\n\t\"Dump to file...\",\n\t\"RGB\",\n\t[\n\t\t(PF_DRAWABLE, \"calque\", \"Layer:\", None),\n\t\t(PF_INT, \"IDmin\", \"Min ID:\", 0),\n\t\t(PF_FILE, \"fileName\", \"File:\", None)\n\t],\n\t[],\n\ttileSetDumper,\n\t\tmenu=\"/Filters/Mes Scripts/Tiles\")\n\nmain()\n","sub_path":"plug-in/gimp/tileSetDumper.py","file_name":"tileSetDumper.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"347844535","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nProject Euler Problem 176\n=======================\n\nThe four rectangular triangles with sides (9,12,15), (12,16,20), (5,12,13)\nand (12,35,37) all have one of the shorter sides (catheti) equal to 12. It\ncan be shown that no other integer sided rectangular triangle exists with\none of the catheti equal to 12.\n\nFind the smallest integer that can be the length of a cathetus of exactly\n47547 different integer sided rectangular triangles.\n\n\"\"\"\n\n\ndef main():\n return \"unimplemented\"\n\n\nif __name__ == \"__main__\":\n import ntpath\n import time\n from common.shared_functions import verify_solution\n\n problem_number = int(ntpath.basename(__file__).replace(\"euler\", \"\").replace(\".py\", \"\"))\n print(\"Retrieving my answer to Euler Problem {0} ...\".format(problem_number))\n\n ts = time.time()\n my_answer = main()\n te = time.time()\n\n print(\"My answer: {1}\".format(problem_number, my_answer))\n\n verification_type = verify_solution(problem_number, my_answer)\n print(\"Verification: {0}\".format(verification_type.name))\n print(\"Took {0} seconds.\".format(te - ts))\n","sub_path":"project-euler/solvers/euler176.py","file_name":"euler176.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"226816852","text":"\"\"\"\nCross-module utilities for the rule engines\n\"\"\"\nfrom enum import Enum\n\nfrom acab.config import AcabConfig\nfrom acab.abstract.printing import util as PrU\n\nutil = AcabConfig.Get()\n\nOPERATOR_S = util(\"Parsing.Structure\", \"OPERATOR_S\")\nROOT_S = util(\"Data.Trie\", \"ROOT_S\")\n#Trie exclusion operator:\nEXOP = Enum('EXOP', 'DOT EX')\n\nPrU.register_modal({EXOP.DOT : util(\"WorkingMemory.TrieWM.Parsing\", \"EXOP.DOT_S\"),\n EXOP.EX : util(\"WorkingMemory.TrieWM.Parsing\", \"EXOP.EX_S\")})\n\nDEFAULT_NODE_DATA = {\n OPERATOR_S : EXOP[util(\"WorkingMemory.TrieWM\", \"DEFAULT_EXOP\")]\n }\n\n\n# Utility Funtions:\ndef node_is_exclusive(node):\n \"\"\" Checks for the exclusion operator in this node \"\"\"\n return node._data[util.OPERATOR_S] is EXOP.EX\n\ndef node_looks_exclusive(node):\n \"\"\" Checks for implicit exclusivity by having 0 or 1 children \"\"\"\n return len(node) <= 1\n\ndef exclusion_matches(contexts, a, b, data):\n \"\"\" Compare the EXOP of a node, with whether that exop\n is in the children of the other node/parent \"\"\"\n logging.info(\"Running exclusion match test: {} {}\".format(str(a), str(b)))\n assert(isinstance(a, TrieNode))\n assert(isinstance(b, TrieNode))\n result = node_is_exclusive(a) and not node_looks_exclusive(b)\n if result:\n logging.info(\"C: {}, Node: {}, {}\".format(node_is_exclusive(a),\n node_is_exclusive(b), str(b)))\n logging.info(\"Mismatch EX num\")\n\n # Don't break out of tests unless this test failed:\n return False, result\n","sub_path":"acab/working_memory/trie_wm/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"69585298","text":"from datetime import datetime\n\nclass Source:\n TWITTER = \"twitter\"\n # FACEBOOK = \"facebook\"\n # INSTAGRAM = \"instagram\"\n\nclass Sentiment:\n GOOD = \"good\"\n BAD = \"bad\"\n NORMAL = \"normal\"\n\nclass Status:\n NEW = \"new\"\n ARCHIVED = \"archived\"\n PENDING = \"pending\"\n DONE = \"done\"\n\nclass Card:\n def __init__(self, id, content, link, date_posted, num_mentions, location):\n self.id = id\n self.content = content\n self.sentiment = Sentiment.NORMAL\n self.source = Source.TWITTER\n self.link = link\n self.status = Status.NEW\n self.year_posted = date_posted.year\n self.month_posted = date_posted.month\n self.day_posted = date_posted.day\n self.hour_posted = date_posted.hour\n self.minute_posted = date_posted.minute\n self.num_mentions = num_mentions\n self.location = location\n\n def to_dict(self):\n return {\n \"id\" : self.id,\n \"content\" : self.content,\n \"sentiment\" : self.sentiment,\n \"source\" : self.source,\n \"link\" : self.link,\n \"status\" : self.status,\n \"yearPosted\" : self.year_posted,\n \"monthPosted\" : self.month_posted,\n \"dayPosted\" : self.day_posted,\n \"hourPosted\" : self.hour_posted,\n \"minutePosted\" : self.minute_posted,\n \"numMentions\" : self.num_mentions,\n \"location\" : self.location\n }\n\nclass Metric:\n def __init__(self):\n self.id = f\"{datetime.now().month}-{datetime.now().year}\"\n self.year = datetime.now().year\n self.month = datetime.now().month\n self.good = 0\n self.normal = 0\n self.bad = 0\n self.mentions = 0\n self.actedItems = 0\n\n def to_dict(self):\n return {\n \"id\" : self.id,\n \"year\" : self.year,\n \"month\" : self.month,\n \"good\" : self.good,\n \"normal\" : self.normal,\n \"bad\" : self.bad,\n \"mentions\" : self.mentions,\n \"actedItems\": self.actedItems\n }\n\n def to_obj(self, metric_dict):\n self.id = metric_dict[\"id\"]\n self.year = metric_dict[\"year\"]\n self.month = metric_dict[\"month\"]\n self.good = metric_dict[\"good\"]\n self.normal = metric_dict[\"normal\"]\n self.bad = metric_dict[\"bad\"]\n self.mentions = metric_dict[\"mentions\"]\n self.actedItems = metric_dict[\"actedItems\"]\n\n def incrementStatusCount(self, status): \n if status == \"normal\":\n self.normal = self.normal + 1\n elif status == \"good\":\n self.good = self.good + 1\n else:\n self.bad = self.bad + 1\n\n\nclass Rank:\n def __init__(self, location):\n self.id = self.__generateId(location)\n self.good = 0\n self.location = location\n self.month = datetime.now().month\n self.year = datetime.now().year\n\n def to_dict(self):\n return {\n \"id\" : self.id,\n \"location\" : self.location,\n \"good\" : self.good,\n \"month\" : self.month,\n \"year\" : self.year\n }\n\n def to_obj(self, rank_dict):\n self.id = rank_dict[\"id\"]\n self.location = rank_dict[\"location\"]\n self.good = rank_dict[\"good\"]\n self.month = rank_dict[\"month\"]\n self.year = rank_dict[\"year\"]\n\n def incrementGoodCount(self, location):\n if (location == self.location and self.__generateId(location) == self.id):\n self.good += 1\n\n def __generateId(self, location):\n monthYear = f\"{datetime.now().month}-{datetime.now().year}\"\n if location is None:\n return f\"{monthYear}-Others\"\n else:\n return f\"{monthYear}-{location.replace(' ', '-')}\"","sub_path":"pananaw-backend/modules/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"175544788","text":"import random\nimport math,datetime\nimport numpy as np\nimport copy\nclass Party:\n '''This is Party Class'''\n def __init__(self,name,deadline):\n self.name = name\n self.utilityspace = {}\n self.response = [\"Yes\",\"No\"]\n self.rv = 0.0\n self.deadline = deadline\n # self.rvlist = [0.12,0.321,0.57,0.75]\n self.rvlist = [i for i in range(5,50,5)] ## utility of rvs\n # self.rvlist = [0.12,0.75]\n self.flag = 1\n self.roundrvlist = []\n self.means_offers = []\n self.gamma = [0]*len(self.rvlist)\n self.new_gamma = [0]*len(self.rvlist)\n self.bayesianutilitylist = []\n self.counterutilitylist = []\n self.strategy = \"boulware\"\n self.countlist = [0]*len(self.rvlist)\n self.lstmlist = [0]*len(self.rvlist)\n self.lstmutilitylist = []\n self.optimallist = []\n self.Probabilitylist = []\n self.roundproblist = []\n\n def checkupdate(self,updateflag,rounds,updaterate):\n if(updateflag==False):\n pass\n else:\n # print(updateflag,updaterate,rounds)\n # print(\"here\")\n if(rounds==1):\n self.rv = random.choice(self.rvlist)\n else:\n if(self.flag==1):\n prob = random.randint(1,5)\n if(prob < 3):\n cur_pos = self.rvlist.index(self.rv)\n if(cur_pos < len(self.rvlist)-1 ):\n if(len(self.rvlist[cur_pos+1:]) > 0):\n self.rv = random.choice(self.rvlist[cur_pos+1:])\n else:\n cur_pos = self.rvlist.index(self.rv)\n if(len(self.rvlist[:cur_pos])>0):\n self.rv = random.choice(self.rvlist[:cur_pos])\n self.flag = -1\n elif(self.flag == -1):\n prob = random.randint(1,5)\n if(prob < 3):\n cur_pos = self.rvlist.index(self.rv)\n if(cur_pos > 0):\n if(len(self.rvlist[:cur_pos])>0):\n self.rv = random.choice(self.rvlist[:cur_pos])\n else:\n cur_pos = self.rvlist.index(self.rv)\n if(cur_pos < len(self.rvlist)-1):\n if(len(self.rvlist[cur_pos+1:]) > 0):\n self.rv = random.choice(self.rvlist[cur_pos+1:])\n self.flag = 1\n if self.strategy == \"optimal\":\n self.utilitylist = self.optimalbidder(self.rvutils[self.rvlist.index(self.rv)],self.deadline) #optimalbidder\n elif self.strategy == \"boulware\":\n self.utilitylist = self.boulwareUtilities(self.rvutils[self.rvlist.index(self.rv)],self.deadline) #boulware\n else:\n # print(\"here\",updaterate,self.rv,\"round number\",rounds,\"party name\",self.name,'rv util',self.rvutils[self.rvlist.index(self.rv)])\n self.utilitylist = self.boulwareUtilities(self.rvutils[self.rvlist.index(self.rv)],self.deadline) #boulware\n # self.utilitylist = self.optimalbidder(self.rvutils[self.rvlist.index(self.rv)],self.deadline) #optimalbidder\n\n\n return self.rv\n\n\n def initialiselistboulware(self,cur_rv):\n if self.strategy == \"optimal\":\n self.utilitylist = self.optimalbidder(cur_rv,self.deadline)\n elif self.strategy == \"boulware\":\n self.utilitylist = self.boulwareUtilities(cur_rv,self.deadline)\n else:\n self.utilitylist = self.boulwareUtilities(cur_rv,self.deadline)\n # self.utilitylist = self.optimalbidder(cur_rv,self.deadline)\n\n\n def offerbid(self,round_number,strategy):\n if(strategy==\"bayesian\"):\n mystrategybid = self.bayesianutilitylist[round_number]\n elif(strategy==\"boulware\"):\n mystrategybid = self.utilitylist[round_number]\n elif(strategy==\"optimal\"):\n mystrategybid = self.utilitylist[round_number]\n elif(strategy==\"counter\"):\n mystrategybid = self.counterutilitylist[round_number]\n elif(strategy==\"lstm\"):\n mystrategybid = self.lstmutilitylist[round_number]\n closest_value = 200\n utility_return = mystrategybid\n # print(\"offering\",mystrategybid,self.name,self.strategy)\n for issue_vals in self.utilityspace:\n temp = min(closest_value,abs(self.utilityspace[issue_vals]-mystrategybid))\n if(temp utility_return):\n # print(\"Oh higher bid offered..accepting..\")\n return \"Yes\",opponent_offered\n else:\n # print(\"Oh lower bid offered..rejecting..\")\n return \"No\",opponent_offered\n\n def boulwareUtilities (self,rv,Deadline):\n # print(\"checkhere\",rv)\n ut = []\n beta = 0.2\n beta = float(1)/beta\n for i in range(1,Deadline+1):\n minm = min(i,Deadline)\n time = float(minm)/Deadline\n curr_ut = rv + (1-rv)*(math.pow(time,beta))\n # print \"================\"\n # print minm\n # print time\n # print beta\n # print \"================\"\n ut.append(float(\"{0:.4f}\".format(curr_ut)))\n ut.reverse()\n return ut\n\n def optimalbidder(self,rv,Deadline):\n ut = []\n ut.append(.25+.25*rv)\n for i in range(1,Deadline):\n ut.append(.25*math.pow(ut[i-1]+1,2))\n ut.reverse()\n return ut\n \n def utilitylistrv(self):\n self.myutilitiesrv = []\n # print(\"check\",self.rvutils)\n for i in range(0,len(self.rvutils)):\n self.myutilitiesrv.append(self.boulwareUtilities(self.rvutils[i],self.deadline)) ###### Boulware\n # self.myutilitiesrv.append(self.optimalbidder(self.rvutils[i],self.deadline)) ####### OptimalBidder \n\n\n def beiliefplot(self):\n # print(\"asfadgdsgdsgdsfsdgdsgsdgdsgdsgsdgsdg\")\n for i in range(0,len(self.rvutils)):\n self.roundproblist.append(1.0/len(self.rvutils))\n self.Probabilitylist.append(copy.deepcopy(self.roundproblist))\n \n def mypedictedrvs(self,roundnum):\n self.predictedrvs = []\n for rvs in self.rvutils:\n self.predictedrvs.append(self.tempgenerate(rvs,self.deadline,roundnum,self.roundrvlist))\n self.Means()\n if(roundnum >= 1):\n # print(\"check here boi\",self.roundrvlist)\n self.calculategamma(self.predictedrvs,self.means_offers,self.roundrvlist,np.mean(self.roundrvlist))\n # print(\"asfafafafew\",self.gamma,\"new gamma here\",self.new_gamma)\n self.updateprobs(self.roundproblist)\n # print(\"let us see\",self.roundproblist,self.Probabilitylist)\n #print(\"--------------------------------------------------------------------\")\n self.generatebayesianutility(roundnum)\n #print(\"final check\",self.bayesianutilitylist)\n #print(\"--------------------------------------------------------------------\")\n\n def tempgenerate(self,i,Deadline,roundnum,RV):\n temp=[0]\n #print str(i) + \" \" + str(RV[roundnum-2])\n t1=0\t\n b=0\n t=0\n #print (str(roundnum) + \" \" + str(len(RV)))\n #print(\"adsfsdfsf\",self.roundrvlist)\n for roundno in range(1,roundnum+1):\n t+=(np.log(float(roundno)/Deadline))*(np.log(float(roundno)/Deadline))\n\n # if(RV[0]-RV[roundno]==0 or (RV[0]-i)==0):\n #print (str(RV[0]) + \" \" + str(RV[roundno]) + \" \" + str(i) +\" \" +str(roundno))\n\n p=np.log ( float(RV[0]-RV[roundno])/ (RV[0]-i) )\n t1=t1+(np.log(float(roundno)/Deadline))*p\n b=float(t1)/t\n #print (\"t: \",t,\"t1: \",t1,\"p: \",p,\"b: \",b,\"check r/d: \",float(roundno)/Deadline)\n # print str(b) + \" \" + str(t1) + \" \" + str(t) + \" \" + str(float(roundno)/Deadline)\n\n x = RV[0] + (i-RV[0])*(math.pow(float(roundno)/Deadline,b))\n\n #print (\"x: \",x, \"RV[0]: \",RV[0], \"i : \",i, \"math: \",math.pow(float(roundno)/Deadline,b) )\n\n x=float(\"{0:.4f}\".format(x))\n temp.append(x)\n #print (\"aditya ------------------temp: \",temp)\n return temp\n\n def Means(self):\n templist = []\n for predictions in self.predictedrvs:\n templist.append(np.mean(predictions))\n self.means_offers = templist\n \n def calculategamma(self,offers,means_offers,RV,mean_RV):\n # print(\"offers here\",offers,len(offers),len(self.gamma),len(self.new_gamma))\n for i in range(0,len(offers)):\n variation=0\n d1=0\n d2=0\n for j in range(1,len(offers[i])):\n variation += (RV[j] - mean_RV) * (offers[i][j]-means_offers[i])\n d1+=math.pow((RV[j] - mean_RV),2)\n d2+=math.pow((offers[i][j]-means_offers[i]),2)\n # print(\"here i am\",\"RV[j] :\",RV[j],\"mean_RV : \",mean_RV,\"offfers :\",offers[i][j],\"means_offers :\",means_offers[i])\n denominator=math.sqrt(d1*d2)\n #if(roundnum>=1):\n self.gamma[i] = float(\"{0:.4f}\".format(float(variation)/denominator))\n self.new_gamma[i]=float(self.gamma[i]+1)/2\n\n\n def updateprobs(self,new_probability):\n #print(self.Probabilitylist)\n new_total=0\n for i in range(0,len(new_probability)):\n new_probability[i]=new_probability[i]*self.new_gamma[i]\n # print \"------\"\n # print new_probability[i]\n # print \"------\"\n new_total+=new_probability[i] \n for i in range(0,len(new_probability)):\n new_probability[i]=float(\"{0:.4f}\".format(new_probability[i]/new_total))\n if(new_probability[i]<=0.0002):\n new_probability[i]=0.0002\n if(new_probability[i]>=0.9998):\n new_probability[i]=0.9998\n # self.Probabilitylist.append(new_probability) ###check here for resolving\n self.Probabilitylist.append(copy.deepcopy(new_probability))\n\n def generatebayesianutility(self,roundnum):\n bayesian_utility = 0\n # print(self.roundproblist)\n for i in range(len(self.roundproblist)):\n bayesian_utility += self.roundproblist[i]*self.myutilitiesrv[i][roundnum]\n self.bayesianutilitylist.append(bayesian_utility)\n\n def updatecounts(self):\n cur_rv = self.rv\n cur_pos =self.rvlist.index(self.rv)\n self.countlist[cur_pos]+=1\n\n def updateprobscounter(self):\n for i in range(0,len(self.rvlist)):\n self.roundproblist[i] = self.countlist[i]/np.sum(self.countlist)\n self.Probabilitylist.append(copy.deepcopy(self.roundproblist))\n\n def counterinitialize(self,rounds):\n if(rounds >=1):\n self.updatecounts()\n #print(\"checking counter\",self.countlist)\n self.updateprobscounter()\n #print(\"checking counter problist\",self.roundproblist)\n self.generatecounterutility(rounds)\n #print(\"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\")\n #print(self.counterutilitylist)\n #print(\"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\")\n def generatecounterutility(self,roundnum):\n counter_utility = 0\n for i in range(0,len(self.roundproblist)):\n counter_utility += self.roundproblist[i]*self.myutilitiesrv[i][roundnum]\n self.counterutilitylist.append(counter_utility)\n \n def findclosest(self,cur_rv):\n temp = []\n for i in range(len(self.rvlist)):\n temp.append(abs(cur_rv-self.rvlist[i]))\n ans = temp.index(min(temp))\n ans = self.rvlist[ans]\n return ans\n def lstmcountsupdate(self,rounds,test_count):\n cur_rv = self.lstmrv[test_count][rounds-1]\n cur_rv = self.findclosest(cur_rv)\n cur_pos = self.rvlist.index(cur_rv)\n self.lstmlist[cur_pos]+=1\n\n def updatelstmpreds(self):\n for i in range(len(self.rvlist)):\n self.roundproblist[i] = self.lstmlist[i]/np.sum(self.lstmlist)\n self.Probabilitylist.append(copy.deepcopy(self.roundproblist))\n\n def generate_lstmrules(self,roundnum):\n lstm_utlity = 0\n for i in range(len(self.roundproblist)):\n lstm_utlity += self.roundproblist[i]*self.myutilitiesrv[i][roundnum]\n self.lstmutilitylist.append(lstm_utlity)\n\n def lstminitialize(self,updaterate,rounds,test_count):\n # print(\"Lstm here\")\n self.lstmrv = np.load('LSTM/Meeting_Data_100_9hyp/Preds/pred_meet'+str(updaterate)+'.npy')\n self.lstmrv = self.lstmrv.reshape(300,99)\n # print(\"here\",self.lstmrv.shape)\n if(rounds>=1):\n self.lstmcountsupdate(rounds,test_count)\n self.updatelstmpreds()\n self.generate_lstmrules(rounds)\n\n\n","sub_path":"parties.py","file_name":"parties.py","file_ext":"py","file_size_in_byte":14660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"332575029","text":"import ConfigParser\nimport logging\nfrom cStringIO import StringIO\n\nfrom plone.registry.interfaces import IRegistry\nfrom zope.component import getUtility\nfrom zope.interface import implements\nfrom zope.component.hooks import getSite\nfrom zope.annotation.interfaces import IAnnotations\n\nfrom ordf.handler import init_handler\nfrom gu.z3cform.rdf.fresnel.fresnel import Fresnel\n#from org.ausnc.rdf.interfaces import IFresnelLensesModified\nfrom gu.z3cform.rdf.interfaces import IORDF\nfrom gu.plone.rdf.interfaces import IRDFSettings\nfrom rdflib import plugin, URIRef\n\nLOG = logging.getLogger(__name__)\n\nPROPLABELQUERY = \"\"\"\nPREFIX rdf:\nPREFIX rdfs:\nPREFIX owl:\n\nSELECT DISTINCT ?p ?l\nWHERE {\n {\n ?p rdf:type rdf:Property .\n ?p rdfs:label ?l .\n } UNION {\n ?p rdf:type owl:ObjectProperty .\n ?p rdfs:label ?l .\n } UNION {\n ?p rdf:type owl:DatatypeProperty .\n ?p rdfs:label ?l .\n } UNION {\n ?p rdf:type owl:AnnotationProperty .\n ?p rdfs:label ?l .\n } UNION {\n ?p rdf:type owl:SymmetricProperty .\n ?p rdfs:label ?l .\n }\n}\n\"\"\"\n\n#### Utilites\n\nclass ORDFUtility(object):\n # TODO: rethink this utility, and maybe make it easier to fetch content, or fresnel lenses based on context / browser layer.\n # e.g. make this utility the central API entry point\n implements(IORDF)\n\n # TODO: need to find a way to reset this even in a multi-ZEO client setup\n fresnel = None\n handler = None\n\n # TODO: check if it is ok to cache handler forever (e.g... connection to store not closed or unexpectedly closed on graph.glose()?)\n def getHandler(self):\n if self.handler is None:\n registry = getUtility(IRegistry)\n settings = registry.forInterface(IRDFSettings, check=False)\n if settings.ordf_configuration:\n conf_str = \"[ordf]\\n\" + settings.ordf_configuration\n cp = ConfigParser.SafeConfigParser()\n cp.readfp(StringIO(conf_str.encode('utf-8')))\n config = dict(cp.items('ordf'))\n else:\n config = dict()\n self.handler = init_handler(config)\n return self.handler\n\n def getLocalStore(self):\n portal = getSite()\n # next step could be necessary\n # portal = getToolByName(portal, 'portal_url').getPortalObject()\n portal_annotations = IAnnotations(portal)\n store = portal_annotations.get('gu.plone.rdf')\n if store is None:\n store = portal_annotations['gu.plone.rdf'] = plugin.get('ZODB', plugin.Store)()\n return store\n\n def getFresnel(self):\n if self.fresnel is None:\n LOG.info(\"reading fresnel graph from triple store\")\n #rdfhandler = self.getHandler()\n registry = getUtility(IRegistry)\n settings = registry.forInterface(IRDFSettings, check=False)\n formatgraphuri = URIRef(settings.fresnel_graph_uri)\n store = self.getLocalStore()\n # TODO: make it optional to store application data in ZODB or external triple store\n formatgraph = Fresnel(store=store,\n identifier=formatgraphuri)\n LOG.info(\"compiling fresnel graph\")\n formatgraph.compile()\n\n # TODO: maybe cache property labels from external store in formatgraph\n # proplabels = rdfhandler.query(PROPLABELQUERY)\n # for row in proplabels:\n # formatgraph.add((row['p'], RDFS.label, row['l']))\n # \n #\n # an alternative to deal with multiple data sources\n # >>> unionGraph = ReadOnlyGraphAggregate([g1, g2])\n # >>> uniqueGraphNames = set(\n # ... [graph.identifier for s, p, o, graph in unionGraph.quads(\n # ... (None, RDF.predicate, None))])\n # >>> len(uniqueGraphNames)\n\n # FIXME: compiled graph is cached until restart of instance\n self.fresnel = formatgraph\n return self.fresnel\n\n def getURI(self, context, request=None):\n # TODO: implement this:\n # check request for parameters / uri elements and look at content to determine URI\n # for rdf-graph.\n raise NotImplementedError()\n\n def getGraph(self, context, request=None):\n # TODO: implement this:\n # fetch graph with current handler and return it.\n raise NotImplementedError()\n\n def clearCache(self):\n self.fresnel = None\n","sub_path":"src/gu/plone/rdf/component.py","file_name":"component.py","file_ext":"py","file_size_in_byte":4602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"372558931","text":"#------------------------------------------------------------------------------\r\n#\r\n# Yusuf DURSUN\r\n# Python üzerinde Parçacık Sürü Optimizasyonunun Kullanılarak Knapsack(Sırt Çantası) Probleminin Dinamik Bir Şekilde Çözülmesi\r\n#\r\n#------------------------------------------------------------------------------\r\n\r\n# Include project dependencies...\r\nimport matplotlib.pyplot as plt\r\nimport random\r\nimport math\r\n\r\n\r\n# Defining global variables [Important: Other variables and running the algorithm are at the bottom of the page]...\r\nitems = ['TV', 'Camera', 'Projector', 'Walkman', 'Radio', 'Mobile phone', 'Laptop']\r\nprices = [35, 85, 135, 10, 25, 2, 94]\r\nkg = [2, 3, 9, 0.5, 2, 0.1, 4]\r\nmaxKg = 25\r\n\r\n\r\n#The function we are trying to maximize...\r\ndef function_max(x):\r\n t = f_total_value(x)\r\n return t + f_total_kg(x, t)\r\n\r\n#If we take all the items\r\ndef f_total_value(x):\r\n total = 0\r\n for i in range(len(x)):\r\n total += x[i] * prices[i] # peice * price\r\n return total\r\n\r\n\r\ndef f_total_kg(x, reset_elem):\r\n total = 0\r\n for i in range(len(x)):\r\n total += x[i] * kg[i] # piece * kg\r\n\r\n if total <= maxKg:\r\n if total <= reset_elem:\r\n return reset_elem - total\r\n else:\r\n return 0\r\n else:\r\n return - reset_elem\r\n\r\n \"\"\"\r\n If kilogram exceeds maxKg;\r\n by returning the negative of the 1st function value as penalty point from the function,\r\n resets the result value so that it does not take the existing value...\r\n \"\"\"\r\n\r\n\r\n\r\n# Our particle class...\r\nclass Particle:\r\n def __init__(self, startingValues):\r\n self.position = [] # Particle position\r\n self.speed = [] # Particle speed\r\n self.pBest = [] # Individual best position\r\n self.pBestapproach = -1 # Individual best approach\r\n self.approach = -1 # individual approach\r\n\r\n for i in range(particles_number):\r\n self.speed.append(random.uniform(-1, 1))\r\n self.position.append(startingValues[i])\r\n\r\n # Calculate fitness for function...\r\n def calculate(self, function):\r\n self.approach = function(self.position)\r\n\r\n # Check if current position, Individual is best...\r\n if self.approach > self.pBestapproach or self.pBestapproach == -1:\r\n self.pBest = self.position\r\n self.pBestapproach = self.approach\r\n\r\n # Update new particle rate...\r\n def speed_update(self, group_max_position):\r\n w = 0.99 # The coefficient of the desire to maintain the previous velocity of the particle.\r\n c1 = 1.99 # The coefficient of the desire to protect her own best.\r\n c2 = 1.99 # Coefficient of willingness to get the best value of the swarm.\r\n\r\n for i in range(particles_number):\r\n r1 = random.random()\r\n r2 = random.random()\r\n\r\n individ_speed = c1 * r1 * (self.pBest[i] - self.position[i])\r\n social_speed = c2 * r2 * (group_max_position[i] - self.position[i])\r\n self.speed[i] = w * self.speed[i] + individ_speed + social_speed\r\n\r\n # Calculating new positions according to the newly updated particle velocity...\r\n def position_update(self, bounds):\r\n for i in range(particles_number):\r\n max_jump = (bounds[i][1] - bounds[i][0])\r\n\r\n if self.speed[i] < -max_jump:\r\n self.speed[i] = -max_jump\r\n elif self.speed[i] > max_jump:\r\n self.speed[i] = max_jump\r\n\r\n self.position[i] = self.position[i] + self.speed[i]\r\n\r\n if self.position[i] > bounds[i][1]: # If position is above the upper limit value, pull to the upper limit value\r\n self.position[i] = bounds[i][1]\r\n elif self.position[i] < bounds[i][0]: # If position is below the lower limit value, pull to the lower limit value\r\n\r\n self.position[i] = bounds[i][0]\r\n else:\r\n self.position[i] = round(self.position[i])\r\n\r\nclass PSO:\r\n curr_price, curr_kg, group_max_position, grupMaxapproach = [], [], [], -1\r\n\r\n def __init__(self, function, startingValues, bounds, piece_number, swarm_size, maxIter, printSteps = True): # function_max, startingValues, bounds, piece_number=7, maxIter=0.1\r\n global particles_number\r\n\r\n particles_number = len(startingValues)\r\n self.grupMaxapproach = -1 # Best approach for group\r\n self.group_max_position = [] # Best position for the group\r\n\r\n # Let's assign initial values ​​to our version...\r\n swarm = []\r\n for i in range(swarm_size):\r\n swarm.append(Particle(startingValues))\r\n\r\n # Optimization cycle start...\r\n counter = 0\r\n while counter < maxIter:\r\n counter += 1\r\n\r\n # Calculation of the functional suitability of the particles in the swarm...\r\n for j in range(swarm_size):\r\n swarm[j].calculate(function)\r\n\r\n # Checking whether the current thread is the global best and making the necessary updates...\r\n if swarm[j].approach > self.grupMaxapproach or self.grupMaxapproach == -1:\r\n self.group_max_position = list(swarm[j].position)\r\n self.grupMaxapproach = float(swarm[j].approach)\r\n\r\n # Updating the speed and positions in the herd...\r\n for j in range(swarm_size):\r\n swarm[j].speed_update(self.group_max_position)\r\n swarm[j].position_update(bounds)\r\n\r\n total_price = 0\r\n total_kg = 0\r\n for i in range(piece_number):\r\n total_price += self.group_max_position[i] * prices[i]\r\n total_kg += self.group_max_position[i] * kg[i]\r\n self.curr_price.append(total_price)\r\n self.curr_kg.append(total_kg)\r\n\r\n if printSteps:\r\n print(self.group_max_position)\r\n\r\n # Printing the results...\r\n def printResult(self):\r\n print('\\n\\nRESULTS:\\n\\n')\r\n total_price = 0\r\n total_kg = 0\r\n for i in range(len(self.group_max_position)):\r\n print(items[i], ': ', self.group_max_position[i], ' pcs', sep='')\r\n total_price += self.group_max_position[i] * prices[i]\r\n total_kg += self.group_max_position[i] * kg[i]\r\n print('#' * 50, '\\nProfit Earned: ', total_price, ',\\nKilogram: ', total_kg, sep='')\r\n\r\n # Plot the results to the screen [If we do not want to save the result image to the computer, the parameter named 'fileName' must be empty!]...\r\n def plotRes(self, fileName = ''):\r\n plt.plot(self.curr_kg, self.curr_price)\r\n plt.xlabel('Kilogram (kg)')\r\n plt.ylabel('Profit made')\r\n plt.title('Profit by Results - Kilogram Chart')\r\n plt.grid(True)\r\n\r\n if not(fileName == ''): # If the variable 'fileName' is not empty, save the file with that name in png format...\r\n fileName = fileName+\".png\"\r\n plt.savefig(fileName)\r\n\r\n plt.show()\r\n plt.close()\r\n\r\n\r\n# Assigning the starting and limit values ​​and running the algorithm...\r\n\r\n# startingValues = [0, 0, 0, 0, 0, 0, 0] # Baslangiç degerleri [x1, x2...]\r\n# bounds = [(0, 12), (0, 8), (0, 2), (0, 50), (0, 12), (0, 250), (0, 6)] # Sınır değerler [(x1_min,x1_max),(x2_min,x2_max)...]\r\n\r\nprint('[item_name: lower_qty - upper_qty]\\n', sep='')\r\nstartingValues = []\r\nbounds = []\r\nfor i in range(len(items)):\r\n startingValues.append(0) # Initial values ​​[x1, x2...]\r\n bounds.append((startingValues[i], math.floor(maxKg/kg[i]))) # Limit values ​​[(x1_min,x1_max),(x2_min,x2_max)...]\r\n print(items[i], ': ', bounds[i][0], ' - ', bounds[i][1], sep='')\r\nprint('\\nincluding the total ', len(items), ' there is a variable...\\n\\n', sep='')\r\n\r\npso = PSO(function_max, startingValues, bounds, piece_number=len(items), swarm_size=100, maxIter=50, printSteps=True)\r\npso.printResult()\r\npso.plotRes(fileName='test')\r\n\r\n# Algorithm end :)","sub_path":"knapsack_pso.py","file_name":"knapsack_pso.py","file_ext":"py","file_size_in_byte":8105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"297814266","text":"import pyttsx3\r\nfrom gtts import gTTS\r\nimport speech_recognition as sr\r\nimport os\r\nimport re\r\nimport webbrowser\r\nimport wikipedia\r\nimport smtplib\r\nimport requests\r\nimport datetime\r\nimport random\r\n#import subprocess\r\nimport sys\r\nimport pycurl\r\nfrom pyowm import OWM\r\nimport urllib\r\nfrom urllib.request import urlopen\r\nimport re\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.support.ui import WebDriverWait \r\nfrom selenium.webdriver.support import expected_conditions as EC \r\nfrom selenium.webdriver.common.keys import Keys \r\nfrom selenium.webdriver.common.by import By \r\nimport wolframalpha\r\nfrom PyDictionary import PyDictionary\r\nfrom datetime import date\r\nimport calendar\r\nfrom bs4 import BeautifulSoup as soup\r\nimport psutil\r\nfrom nltk.corpus import wordnet\r\nfrom textblob import TextBlob\r\nimport cv2\r\nfrom time import sleep\r\nimport numpy as py\r\nimport time\r\n\r\nengine = pyttsx3.init('sapi5')\r\nvoices = engine.getProperty('voices')\r\nengine.setProperty('voice', voices[len(voices)-1].id)\r\n\r\ndictionary=PyDictionary()\r\n \r\ndef speak(audio):\r\n print('Ignis : ' + audio)\r\n engine.say(audio)\r\n engine.runAndWait()\r\n\r\ndef talkToMe(audio):\r\n \"speaks audio passed as argument\"\r\n\r\n print(audio)\r\n for line in audio.splitlines():\r\n os.system(\"say \" + audio)\r\n\r\ndef is_internet():\r\n try:\r\n urlopen('https://www.google.com', timeout=1)\r\n return True\r\n except urllib.error.URLError as Error:\r\n return False\r\n\r\nif is_internet():\r\n speak(\"Internet is active\")\r\nelse:\r\n speak(\"Internet disconnected\")\r\n sys.exit()\r\n\r\ndef myCommand():\r\n \"listens for commands\"\r\n\r\n r = sr.Recognizer()\r\n\r\n with sr.Microphone() as source:\r\n print('Ready...')\r\n r.pause_threshold = 1\r\n r.adjust_for_ambient_noise(source, duration=1)\r\n audio = r.listen(source)\r\n\r\n try:\r\n command = r.recognize_google(audio).lower()\r\n print('You said: ' + command + '\\n')\r\n\r\n #loop back to continue to listen for commands if unrecognizable speech is received\r\n except sr.UnknownValueError:\r\n speak('Your last command couldn\\'t be heard.')\r\n command = myCommand();\r\n\r\n return command\r\n\r\n\r\ndef assistant(command):\r\n \"if statements for executing commands\"\r\n\r\n if 'hi' in command or 'hello' in command or 'ignis' in command or 'hey' in command:\r\n hour = int(datetime.datetime.now().hour)\r\n if hour>=0 and hour<12:\r\n speak(\"Good Morning!\")\r\n speak(\"I am ignis. Please tell me how may I help you.\")\r\n\r\n elif hour>=12 and hour<18:\r\n speak(\"Good Afternoon!\")\r\n speak(\"I am ignis. Please tell me how may I help you.\")\r\n\r\n else:\r\n speak(\"Good Evening!\")\r\n speak(\"I am ignis. Please tell me how may I help you.\")\r\n\r\n elif 'meaning' in command:\r\n try:\r\n speak('Tell me the word')\r\n word=myCommand()\r\n print(PyDictionary.meaning(word))\r\n speak('Here is your answer')\r\n except exception as e:\r\n print(e)\r\n\r\n elif 'whatsapp' in command:\r\n driver = webdriver.Chrome('C:/Users/praveen kumar/Downloads/chromedriver_win32/chromedriver.exe')\r\n driver.get('https://web.whatsapp.com/') \r\n wait = WebDriverWait(driver, 600)\r\n target = 'Frn Kishore Clg'\r\n string = \"Message sent using Python!!!\"\r\n x_arg = '//span[contains(@title,' + target + ')]'\r\n group_title = wait.until(EC.presence_of_element_located((\r\n By.XPATH, x_arg))) \r\n group_title.click() \r\n inp_xpath = '//div[@class=\"input\"][@dir=\"auto\"][@data-tab=\"1\"]'\r\n input_box = wait.until(EC.presence_of_element_located(( \r\n By.XPATH, inp_xpath))) \r\n for i in range(100): \r\n input_box.send_keys(string + Keys.ENTER) \r\n time.sleep(1) \r\n \r\n elif 'synonym' in command:\r\n try:\r\n speak('Tell me the word')\r\n word=myCommand()\r\n syn = list()\r\n ant = list()\r\n for synset in wordnet.synsets(word):\r\n for lemma in synset.lemmas():\r\n syn.append(lemma.name()) \r\n if lemma.antonyms(): \r\n ant.append(lemma.antonyms()[0].name())\r\n print('Synonyms: ' + str(syn))\r\n except exception as e:\r\n print(e)\r\n\r\n elif 'antonym' in command:\r\n try:\r\n speak('Tell me the word')\r\n word=myCommand()\r\n syn = list()\r\n ant = list()\r\n for synset in wordnet.synsets(word):\r\n for lemma in synset.lemmas():\r\n syn.append(lemma.name()) \r\n if lemma.antonyms(): \r\n ant.append(lemma.antonyms()[0].name())\r\n print('Antonyms: ' + str(ant))\r\n except exception as e:\r\n print(e)\r\n\r\n elif 'translate' in command or 'translation' in command:\r\n speak('Tell me the word')\r\n word=myCommand()\r\n translator=TextBlob(word)\r\n print(translator.translate(from_lang='en', to='ta'))\r\n\r\n elif 'languages' in command:\r\n speak('I\\'m currently programmed to speak english')\r\n\r\n elif 'news' in command:\r\n try:\r\n news_url=\"https://news.google.com/news/rss\"\r\n Client=urlopen(news_url)\r\n xml_page=Client.read()\r\n Client.close()\r\n soup_page=soup(xml_page,\"xml\")\r\n news_list=soup_page.findAll(\"item\")\r\n # Print news title, url and publish date\r\n for news in news_list[:5]:\r\n print(news.title.text)\r\n print(news.link.text)\r\n print(news.pubDate.text)\r\n print('-'*60)\r\n except Exception as e:\r\n print(e)\r\n \r\n elif 'search' in command:\r\n new=2\r\n taburl=\"http://google.com/?#q=\"\r\n speak('What should i search ?')\r\n term=myCommand()\r\n webbrowser.open(taburl+term,new=new)\r\n\r\n elif 'google chrome' in command or 'in google chrome' in command:\r\n os.startfile(\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe\")\r\n\r\n elif 'who are you' in command or 'who you are' in command:\r\n speak('Hi! I\\'m ignis your virtual assistant')\r\n\r\n elif 'made you' in command or 'built you' in command or 'invented you' in command:\r\n speak('Kishore R, Praveen kumar K, Praveen P, Monesh S, mentored by Rengaraj alias muralidharan from saranathan college of engineering, Information Technology department.')\r\n\r\n elif 'wikipedia' in command or 'tell me about' in command:\r\n try:\r\n speak('Searching Wikipedia...')\r\n command = command.replace(\"wikipedia\", \"\")\r\n command = command.replace(\"tell me about\", \"\")\r\n results = wikipedia.summary(command, sentences=2)\r\n speak(\"According to Wikipedia\")\r\n speak(results)\r\n \r\n except exception as e:\r\n print(e)\r\n speak(\"Couldn't get you!!!\");\r\n\r\n elif 'in which language are you written' in command or 'language used' in command:\r\n speak('I\\m written in python')\r\n\r\n \r\n elif 'open drive' in command or 'open directory' in command:\r\n speak('Which drive?')\r\n drive = myCommand()\r\n if drive=='c drive' or drive=='c directory' or drive=='c colon':\r\n os.startfile('C:')\r\n elif drive=='d drive' or drive=='d directory' or drive=='d colon':\r\n os.startfile('D:')\r\n elif drive=='e drive' or drive=='e directory' or drive=='e colon':\r\n os.startfile('E:')\r\n elif drive=='f drive' or drive=='f directory' or drive=='f colon':\r\n os.startfile('F:')\r\n else:\r\n speak('Please tell the correct drive!!');\r\n \r\n \r\n elif 'play music' in command:\r\n music_dir = 'E:\\\\Music'\r\n songs = os.listdir(music_dir)\r\n os.startfile(os.path.join(music_dir, random.choice(songs)))\r\n speak('Okay, here is your music! Enjoy!')\r\n sys.exit()\r\n\r\n elif 'current weather' in command or 'current temperature' in command:\r\n try:\r\n reg_ex = re.search('current weather in (.*)', command)\r\n if reg_ex:\r\n city = reg_ex.group(1)\r\n owm = OWM(API_key='ab0d5e80e8dafb2cb81fa9e82431c1fa')\r\n obs = owm.weather_at_place(city)\r\n w = obs.get_weather()\r\n k = w.get_status()\r\n x = w.get_temperature(unit='celsius')\r\n speak('Current weather in %s is %s. The maximum temperature is %0.2f and the minimum temperature is %0.2f degree celcius' % (city, k, x['temp_max'], x['temp_min']))\r\n except exception as e:\r\n print('Sry, cannot find details about your city')\r\n \r\n\r\n elif 'battery percentage' in command or 'charge percentage' in command:\r\n speak(f\"Remaining battery is {psutil.sensors_battery().percent}%\")\r\n\r\n \r\n elif 'open website' in command:\r\n reg_ex = re.search('open website (.+)', command)\r\n if reg_ex:\r\n domain = reg_ex.group(1)\r\n url = 'https://www.' + domain\r\n webbrowser.open(url)\r\n speak('Done! task completed')\r\n else:\r\n pass\r\n\r\n elif \"what's up\" in command or 'how are you' in command:\r\n stMsgs = ['Just doing my thing!', 'I am fine!', 'Nice!', 'I am nice and full of energy']\r\n speak(random.choice(stMsgs))\r\n\r\n elif 'microsoft word' in command:\r\n os.startfile()\r\n \r\n \r\n elif 'joke' in command:\r\n try:\r\n res = requests.get('https://icanhazdadjoke.com/',headers={\"Accept\":\"application/json\"})\r\n if res.status_code == requests.codes.ok:\r\n talkToMe(str(res.json()['joke']))\r\n else:\r\n speak('oops!I ran out of jokes')\r\n except exception as e:\r\n print(e)\r\n speak(\"Couldn't get you!!!\")\r\n\r\n elif 'notepad' in command:\r\n speak('Tell the file name')\r\n filename=myCommand()\r\n if os.path.isfile('D:\\\\Ignis\\\\'+filename):\r\n speak('Say the content to write')\r\n ipt=myCommand()\r\n f=open(filename,\"a\")\r\n f.write(ipt)\r\n speak('Text written successfully')\r\n os.startfile('D:\\\\Ignis\\\\'+filename)\r\n else:\r\n f=open(filename,\"w+\")\r\n speak('Say the content to write')\r\n ipt=myCommand()\r\n f.write(ipt)\r\n speak('Text written successfully')\r\n os.startfile('D:\\\\Ignis\\\\'+filename)\r\n \r\n \r\n elif 'the time' in command:\r\n strTime = datetime.datetime.now().strftime(\"%H:%M:%S\") \r\n speak(f\"The time is {strTime}\")\r\n\r\n elif 'the day' in command or 'day' in command:\r\n now = datetime.datetime.now()\r\n speak(now.strftime(\"%A\"))\r\n \r\n\r\n elif 'date' in command:\r\n today=date.today()\r\n d2 = today.strftime(\"%B %d, %Y\")\r\n speak(d2)\r\n\r\n elif 'open command prompt' in command or 'open cmd' in command or 'command prompt' in command or 'cmd' in command:\r\n os.startfile('C:\\\\Users\\\\praveen kumar\\\\AppData\\\\Roaming\\\\Microsoft\\\\Windows\\\\Start Menu\\\\Programs\\\\System Tools\\\\Command Prompt')\r\n\r\n elif 'nothing' in command or 'abort' in command or 'stop' in command or 'bye' in command:\r\n speak('okay')\r\n speak('Bye, have a good day.')\r\n sys.exit()\r\n \r\n elif 'email' in command or 'mail' in command:\r\n try:\r\n speak('Recipient mail ID?')\r\n recipient = myCommand()\r\n if (recipient.find('@') < recipient.find('.') and '@' in recipient and len(recipient) > 5):\r\n speak('What should I say?')\r\n content = myCommand()\r\n\r\n #init gmail SMTP\r\n mail = smtplib.SMTP('smtp.gmail.com', 587)\r\n\r\n #identify to server\r\n mail.ehlo()\r\n\r\n #encrypt session\r\n mail.starttls()\r\n\r\n #login\r\n mail.login('pk9489114199@gmail.com', 'kannanpraveen')\r\n\r\n #send message\r\n mail.sendmail('pk9489114199@gmail.com', recipient.replace(\" \",\"\"), content)\r\n\r\n #end mail connection\r\n mail.close()\r\n\r\n speak('Email sent.')\r\n else:\r\n speak('Please check the mail ID')\r\n\r\n except exception as e:\r\n print(e)\r\n speak(\"Sorry, I am not able to send this email\")\r\n\r\n else:\r\n speak('I don\\'t know what you mean!')\r\n\r\n\r\nspeak('I am ready for your command')\r\n\r\n#loop to continue executing multiple commands\r\nwhile True:\r\n assistant(myCommand())\r\n","sub_path":"ignis.py","file_name":"ignis.py","file_ext":"py","file_size_in_byte":12883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"295658844","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\n__author__ = 'Nb'\n\n'''\nfrom collections import OrderedDict\n\nfrom .LexicalAnalyser import RawTokenStream, TokenStream, ToRawTokenStream, SerialiseRawTokenStream\nfrom .Parser import SyntaxStream, SyntaxTree, TokeniseSyntaxStream\nfrom .Python import ParsePythonKeyword, ParsePythonConfig, SyntaxisePythonConfig\n\n\n__all__ = (\n 'LexicalAnalyser',\n 'Parser',\n 'Syntax',\n 'Token',\n)\n\n\ndef compile_config(config: OrderedDict) -> str:\n return SerialiseRawTokenStream(\n ToRawTokenStream(\n TokeniseSyntaxStream(\n SyntaxisePythonConfig(\n config\n ))))\n\n\ndef dump_config(config: OrderedDict, file: str):\n with open(file, 'w', encoding='utf-8') as config_file:\n config_file.write(compile_config(config))\n\n\ndef parse_config(file: str) -> OrderedDict:\n with open(file, 'r', encoding='utf-8') as content:\n return ParsePythonConfig(\n SyntaxTree(\n ParsePythonKeyword(\n SyntaxStream(\n TokenStream(\n RawTokenStream(\n content.read()\n ))))))\n\n\ndef diagnostic(file: str):\n with open(file, 'r', encoding='utf-8') as content:\n print('\\n=========== Raw Token Stream =========')\n raw = RawTokenStream(content.read())\n print(raw)\n print('\\n============= Token Stream ===========')\n token = TokenStream(raw)\n print(token)\n print('\\n============ Syntax Stream ===========')\n syntax = ParsePythonKeyword(SyntaxStream(token))\n print(syntax)\n print('\\n============ Syntax Tree =============')\n tree = SyntaxTree(syntax)\n print(tree)\n print('\\n=============== Python ===============')'''\n# print(ParsePythonConfig(tree))","sub_path":"Experimental/Parser/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"157482573","text":"import numpy as np\r\nimport gym\r\n\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Activation, Flatten\r\nfrom keras.optimizers import Adam\r\n\r\nfrom rl.agents.dqn import DQNAgent\r\nfrom rl.policy import EpsGreedyQPolicy, BoltzmannQPolicy\r\nfrom rl.memory import SequentialMemory\r\n\r\nENV_NAME = 'LunarLander-v2'\r\nAGENT_NAME = 'weight512.agent'\r\n\r\nenv = gym.make(ENV_NAME)\r\nnp.random.seed(123)\r\nenv.seed(123)\r\nnb_actions = env.action_space.n\r\n\r\nmodel = Sequential()\r\nmodel.add(Flatten(input_shape=(1,) + env.observation_space.shape))\r\nmodel.add(Dense(512))\r\nmodel.add(Activation('relu'))\r\nmodel.add(Dense(512))\r\nmodel.add(Activation('relu'))\r\nmodel.add(Dense(512))\r\nmodel.add(Activation('relu'))\r\nmodel.add(Dense(512))\r\nmodel.add(Activation('relu'))\r\nmodel.add(Dense(nb_actions))\r\nmodel.add(Activation('linear'))\r\n\r\npolicy = EpsGreedyQPolicy()\r\nmemory = SequentialMemory(limit=1000000, window_length=1)\r\ndqn = DQNAgent(model=model, nb_actions=nb_actions, memory=memory, nb_steps_warmup=10000, target_model_update=1e-2,\r\n policy=policy)\r\ndqn.compile(Adam(lr=1e-3), metrics=['mse'])\r\ndqn.load_weights(AGENT_NAME)\r\ntests = dqn.test(env, nb_episodes=100, visualize=True)\r\nrewards = tests.history['episode_reward']\r\n\r\nprint(sum(rewards) / len(rewards))\r\n","sub_path":"code/restore_agent.py","file_name":"restore_agent.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"251149609","text":"import random\nimport timeit\nimport memory_profiler\n\n# use a generator expression if all you're doing is iterating once\n# Referenced: https://www.youtube.com/watch?v=bD05uGo_sVI&t=459s\n# Generator better in terms of performances and memory\n# as not holding everything in memory\n# List: Seconds:\t1.3081\n# Generator: Seconds: 0.0001\n\n\nplayers = ['Root', 'Stokes', 'Burns', 'Buttler', 'Ali', 'Anderson']\nroles = ['Bowler', 'Bat', \"Keeper\", 'Fielder', 'All Rounder']\n\n\n# list\ndef players_list(num_players):\n result = []\n for i in range(num_players):\n person = {\n 'id': i,\n 'name': random.choice(players),\n 'position': random.choice(roles)\n }\n result.append(person)\n return result\n\n\n# generator\ndef players_gen(num_players):\n for i in range(num_players):\n person = {\n 'id': i,\n 'name': random.choice(players),\n 'position': random.choice(roles)\n }\n yield person\n\n\nstart_time = timeit.default_timer()\n\nprint(f\"Memory:\\t{memory_profiler.memory_usage()}MB\")\n# a = players_list(1000000)\nb = players_gen(1000000)\n# c = list(players_gen(1000000)) # lose speed gain of Generator\nprint(next(b))\nprint(next(b))\n\nprint(f\"{round(timeit.default_timer() - start_time,4)} secs\")\nprint(f\"Memory:\\t{memory_profiler.memory_usage()}MB\")\n","sub_path":"python/list_vs_generator.py","file_name":"list_vs_generator.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"571450265","text":"n = int(input())\r\nnominal = input().split()\r\n\r\nfor i in range(len(nominal)):\r\n nominal[i] = int(nominal[i])\r\n\r\nnominal.sort()\r\nnominal.reverse()\r\n\r\nfor i in range(len(nominal)):\r\n i = i + 1\r\n a = nominal[0:i]\r\n b = nominal[i:len(nominal)]\r\n suma = 0\r\n sumb = 0\r\n for number in a:\r\n suma = suma + number\r\n for number in b:\r\n sumb = sumb + number\r\n if suma > sumb:\r\n print(len(a))\r\n break\r\n","sub_path":"blizneci.py","file_name":"blizneci.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"591566461","text":"# -*- coding: utf-8 -*-\n\n\nfrom optionaldict import optionaldict\nfrom wechatpy.client.api.base import BaseWeChatAPI\n\n\nclass WeChatOA(BaseWeChatAPI):\n \"\"\"\n OA管理\n\n https://work.weixin.qq.com/api/doc/90000/90135/90264\n \"\"\"\n\n def get_template_detail(self, template_id):\n \"\"\"\n 查询审批模板的详情\n https://work.weixin.qq.com/api/doc/90000/90135/91982\n\n :param template_id: 模板Id\n :return:\n \"\"\"\n data = {\n 'template_id': template_id\n }\n return self._post(\n 'oa/gettemplatedetail',\n data=data\n )\n\n def get_approval_info(self, start_time, end_time, cursor, size=100, filters=None):\n \"\"\"\n 批量获取审批单号\n https://work.weixin.qq.com/api/doc/90000/90135/91816\n\n :param start_time: 开始时间戳\n :param end_time: 结束时间戳,请求的参数endtime需要大于startime, 起始时间跨度不能超过31天;\n :param cursor: 分页查询游标,默认为0,后续使用返回的next_cursor进行分页拉取\n :param size: 一次请求拉取审批单���量,默认值为100,上限值为100\n :param filters: 请自行查看文档\n :return:\n \"\"\"\n data = optionaldict({\n 'starttime': str(start_time),\n 'endtime': str(end_time),\n 'cursor': cursor,\n 'size': size,\n 'filter': filters\n })\n\n return self._post(\n 'oa/getapprovalinfo',\n data=data\n )\n\n def get_approval_detail(self, sp_no):\n \"\"\"\n 获取审批申请详情\n https://work.weixin.qq.com/api/doc/90000/90135/91983\n\n :param sp_no: 审批单编号\n :return:\n \"\"\"\n data = {\n 'sp_no': sp_no\n }\n return self._post(\n 'oa/getapprovaldetail',\n data=data\n )\n\n def apply_event(self, creator_userid, template_id, use_template_approver, approver, apply_data, summary_list,\n notifyer=None, notify_type=None):\n \"\"\"\n 提交审批申请,这个函数的参数比较复杂,具体请查看官方文档\n https://work.weixin.qq.com/api/doc/90000/90135/91853\n\n :param creator_userid: 申请人userid,此审批申请将以此员工身份提交,申请人需在应用可见范围内\n :param template_id: 模板id。可在“获取审批申请详情”、“审批状态变化回调通知”中获得,也可在审批模板的模板编辑页面链接中获得。暂不支持通过接口提交[打卡补卡][调班]模板审批单。\n :param use_template_approver: 审批人模式:0-通过接口指定审批人、抄送人(此时approver、notifyer等参数可用); 1-使用此模板在管理后台设置的审批流程,支持条件审批。\n :param approver: 具体参数查看官方文档,审批流程信息,用于指定审批申请的审批流程,支持单人审批、多人会签、多人或签,可能有多个审批节点,仅use_template_approver为0时生效。\n :param apply_data: 具体参数查看官方文档,审批申请数据,可定义审批申请中各个控件的值,其中必填项必须有值,选填项可为空,数据结构同“获取审批申请详情”接口返回值中同名参数“apply_data”\n :param summary_list: 具体参数查看官方文档,摘要信息,用于显示在审批通知卡片、审批列表的摘要信息,最多3行\n :param notifyer: 抄送人节点userid列表,仅use_template_approver为0时生效。\n :param notify_type: 抄送方式:1-提单时抄送(默认值); 2-单据通过后抄送;3-提单和单据通过后抄送。仅use_template_approver为0时生效。\n :return:\n \"\"\"\n data = optionaldict({\n 'creator_userid': creator_userid,\n 'template_id': template_id,\n 'use_template_approver': use_template_approver,\n 'approver': approver,\n 'notifyer': notifyer,\n 'notify_type': notify_type,\n 'apply_data': apply_data,\n 'summary_list': summary_list\n })\n return self._post(\n 'oa/applyevent',\n data=data\n )\n","sub_path":"wechatpy/work/client/api/oa.py","file_name":"oa.py","file_ext":"py","file_size_in_byte":4309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"412798277","text":"#!/usr/bin/env python2.7\n\nfrom setuptools import setup, Extension\n\nfrom src.version import softwareVersion\n\nwith open('README.md') as f:\n README = f.read()\n\nsetup(\n name='pybitmessage',\n version=softwareVersion,\n description=\"Reference client for Bitmessage: \"\n \"a P2P communications protocol\",\n long_description=README,\n license='MIT',\n url='https://bitmessage.org',\n install_requires=['msgpack-python'],\n extras_require={\n 'pyopencl': ['pyopencl']\n },\n classifiers=[\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python :: 2.7 :: Only\",\n \"Topic :: Internet\",\n \"Topic :: Security :: Cryptography\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n package_dir={'pybitmessage': 'src'},\n packages=[\n 'pybitmessage',\n 'pybitmessage.bitmessageqt',\n 'pybitmessage.pyelliptic',\n 'pybitmessage.socks',\n ],\n package_data={\n 'pybitmessage': ['bitmsghash/*.cl', 'sslkeys/*.pem'],\n 'pybitmessage.bitmessageqt': ['*.ui', 'translations/*.qm'],\n },\n ext_modules=[\n Extension(\n name='pybitmessage.bitmsghash.bitmsghash',\n sources=['src/bitmsghash/bitmsghash.cpp'],\n libraries=['crypto']\n )\n ],\n zip_safe=False,\n entry_points={\n #'console_scripts': ['pybitmessage = pybitmessage.main:main'],\n },\n scripts=['src/pybitmessage']\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"621026417","text":"#! /usr/bin/env python\n\n\nimport sys\nfrom Bio import GenBank\nfrom Bio import Entrez\nfrom Bio import SeqIO\nfrom BioSQL import BioSeqDatabase\nfrom chlamdb.biosqldb.manipulate_biosqldb import load_db\nfrom chlamdb.biosqldb.manipulate_biosqldb import query_yes_no\nfrom chlamdb.biosqldb import manipulate_biosqldb\n\n\ndef import_gbk(gbk_name,\n server_name,\n db_name,\n sqlite=False):\n\n\n records = [i for i in SeqIO.parse(gbk_name, 'genbank')]\n\n if len(records)>1:\n print (\"genbank file contains more than one record, is it plasmid(s) and chromosome(s)? (if the assembly contain more than one contig, contactenate contigs into a single record before importing it the the sql database)\")\n try:\n db_name.load(records)\n except:\n print (gbk_name, \"already into db?\")\n pass\n server_name.adaptor.commit()\n\n\ndef create_cds_tables(one_gbk,\n biodb_name):\n\n '''\n\n Create one protein CDS and one rRNA table for each genbank record.\n The genbak should already be loaded into the biosql database.\n Columns of the protein encoding cds table:\n\n - taxon_id index\n - accession index\n - locus_tag index\n - protein_id index\n - start\n - stop\n - strand\n - gene\n - product\n - translation\n\n :param one_gbk:\n :return:\n '''\n\n import re\n server, db = manipulate_biosqldb.load_db(biodb_name)\n\n sql = 'create database if not exists feature_tables;'\n server.adaptor.execute(sql,)\n server.commit()\n\n sql_cds = 'CREATE table IF NOT EXISTS feature_tables.genomes_cds_%s (prot_primary_id INT AUTO_INCREMENT PRIMARY KEY,' \\\n ' taxon_id INT,' \\\n ' genome_accession VARCHAR(40),' \\\n ' start INT,' \\\n ' end INT,' \\\n ' strand INT,' \\\n ' gene varchar(20),' \\\n ' product TEXT,' \\\n ' translation TEXT, ' \\\n ' INDEX taxon_id(taxon_id), ' \\\n ' INDEX genome_accession(genome_accession))' % biodb_name\n\n sql_rrna = 'CREATE table IF NOT EXISTS feature_tables.genomes_rrna_%s (rrna_primary_id INT AUTO_INCREMENT PRIMARY KEY,' \\\n ' taxon_id INT,' \\\n ' genome_accession VARCHAR(40),' \\\n ' start INT,' \\\n ' end INT,' \\\n ' strand INT,' \\\n ' product TEXT,' \\\n ' INDEX taxon_id(taxon_id), ' \\\n ' INDEX genome_accession(genome_accession))' % biodb_name\n\n sql_synonyms = 'CREATE table IF NOT EXISTS feature_tables.cds_accessions_%s (prot_primary_id INT,' \\\n ' id_type varchar(40),' \\\n ' id_name varchar(40),' \\\n ' INDEX id_name(id_name),' \\\n ' INDEX id_type(id_type),' \\\n ' FOREIGN KEY (prot_primary_id) REFERENCES genomes_cds_%s(prot_primary_id))' % (biodb_name, biodb_name)\n\n server.adaptor.execute(sql_cds,)\n server.adaptor.execute(sql_rrna,)\n server.adaptor.execute(sql_synonyms,)\n server.commit()\n\n with open(one_gbk, 'r') as f:\n records = SeqIO.parse(f, 'genbank')\n for record in records:\n accession = record.id.split('.')[0]\n sql = 'select taxon_id from bioentry as t1 inner join biodatabase as t2 on t1.biodatabase_id=t2.biodatabase_id ' \\\n ' where t2.name=\"%s\" and t1.accession=\"%s\"' % (biodb_name,\n accession)\n taxon_id = server.adaptor.execute_and_fetchall(sql,)[0][0]\n\n for feature in record.features:\n if feature.type == 'CDS' and not 'pseudo' in feature.qualifiers:\n start = re.sub('>|<','', str(feature.location.start))\n end = re.sub('>|<','', str(feature.location.end))\n strand = feature.strand\n try:\n gene = feature.qualifiers['gene'][0]\n except:\n gene = '-'\n try:\n product = feature.qualifiers['product'][0]\n except:\n product = '-'\n locus_tag = feature.qualifiers['locus_tag'][0]\n try:\n old_locus_tag = feature.qualifiers['old_locus_tag'][0]\n except:\n old_locus_tag = False\n\n try:\n protein_id = feature.qualifiers['protein_id'][0]\n except:\n protein_id = '.'\n try:\n translation = feature.qualifiers['translation'][0]\n except:\n translation = '-'\n\n sql1 = 'INSERT INTO feature_tables.genomes_cds_%s(taxon_id, genome_accession, start, end, strand, gene, product, translation) ' \\\n 'values(%s, \"%s\", %s, %s, %s, \"%s\", \"%s\", \"%s\")' % (biodb_name,\n taxon_id,\n accession,\n start,\n end,\n strand,\n gene,\n product,\n translation)\n server.adaptor.execute(sql1,)\n server.commit()\n\n sql = 'SELECT LAST_INSERT_ID();'\n\n cds_id = server.adaptor.execute_and_fetchall(sql, )[0][0]\n sql2 = 'INSERT into feature_tables.cds_accessions_%s(prot_primary_id, id_type, id_name) values (' \\\n ' %s, \"%s\", \"%s\")'\n\n server.adaptor.execute(sql2 % (biodb_name, cds_id, 'protein_id', protein_id),)\n server.adaptor.execute(sql2 % (biodb_name, cds_id, 'locus_tag', locus_tag),)\n\n if old_locus_tag:\n server.adaptor.execute(sql2 % (biodb_name, cds_id, 'old_locus_tag', old_locus_tag),)\n\n server.commit()\n\n elif feature.type == 'rRNA':\n start = re.sub('>|<','', str(feature.location.start))\n end = re.sub('>|<','', str(feature.location.end))\n strand = feature.strand\n try:\n product = feature.qualifiers['product'][0]\n except:\n product = '-'\n sql = 'insert into feature_tables.genomes_rrna_%s (taxon_id, genome_accession, start, end, strand, product) values (' \\\n ' %s, \"%s\", %s, %s, %s, \"%s\")' % (biodb_name, taxon_id, accession, start, end, strand, product)\n\n server.adaptor.execute(sql,)\n server.commit()\n else:\n continue\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-g\", '--gbk', type=str, help=\"gbk file\", nargs='+')\n parser.add_argument(\"-d\", '--db_name', type=str, help=\"db name\", required=True)\n parser.add_argument(\"-r\", '--remove_db', type=str, help=\"remove db\")\n parser.add_argument(\"-s\", '--sqlite_db', type=str, help=\"use sqlite3 database\", default=False)\n\n args = parser.parse_args()\n\n server, db = load_db(args.db_name, args.sqlite_db)\n\n if args.gbk:\n for gbk in args.gbk:\n import_gbk(gbk, server, db)\n create_cds_tables(gbk, args.db_name)\n\n if args.remove_db:\n if query_yes_no(\"Remove databse %s?\" % args.remove_db):\n del server[args.remove_db]\n server.commit()\n","sub_path":"db_setup/chlamdb-load-gbk.py","file_name":"chlamdb-load-gbk.py","file_ext":"py","file_size_in_byte":8044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"520728488","text":"from collections import defaultdict, namedtuple\nfrom typing import List\n\nfrom django import template\nfrom django.urls import reverse\n\nfrom exchange.controllers import is_exchange_acceptable, is_exchange_cancellable\nfrom exchange.models import Exchange\nfrom friprosveta.models import Activity\nfrom timetable.models import WEEKDAYS, WORKHOURS, Allocation\n\nregister = template.Library()\n\n\ndef _exchange_sorted_helper(exchange: Exchange):\n day_map = {}\n hour_map = {}\n for i, (d, _) in enumerate(WEEKDAYS):\n day_map[d] = i\n for i, (h, _) in enumerate(WORKHOURS):\n hour_map[h] = i\n\n result = day_map.get(exchange.allocation_from.day, -1) * 100 + hour_map.get(\n exchange.allocation_from.start, -1\n )\n if exchange.allocation_to:\n result += day_map.get(exchange.allocation_to.day, -1) * 10 + hour_map.get(\n exchange.allocation_to.start, -1\n )\n return result\n\n\n@register.inclusion_tag(\"exchange/template_exchange_list.html\")\ndef render_exchanges(\n exchanges,\n show_subject=True,\n third_person=False,\n manager_student=None,\n show_student=True,\n show_finalized=False,\n show_cancelled=False,\n show_cancel_link=True,\n):\n \"\"\"Directive-like helper.\n\n Args:\n exchanges (List[Exchange]): A list of exchanges.\n show_subject (bool): Whether to show the subject preceding everything else.\n show_student (bool): Whether to show the student's name, if SPECIFIC_STUDENT.\n third_person (bool): Whether to output third person perspective noun forms.\n manager_student (Student): The student that would accept the exchange. If None, no accept links are generated.\n show_finalized (bool): Whether to display finalized exchanges.\n show_cancelled (bool): Whether to display cancelled exchanges.\n show_cancel_link (bool): Whether to display the cancel button, if available.\n \"\"\"\n filtered_exchanges = exchanges\n if not show_finalized:\n filtered_exchanges = [e for e in filtered_exchanges if not e.is_finalized()]\n if not show_cancelled:\n filtered_exchanges = [e for e in filtered_exchanges if not e.is_cancelled()]\n\n # sort exchanges\n sorted_exchanges = sorted(filtered_exchanges, key=_exchange_sorted_helper)\n\n view_models = []\n vm = namedtuple(\n \"ExchangeViewModel\",\n [\n \"type\",\n \"allocation_from\",\n \"allocation_to\",\n \"initiator_student\",\n \"requested_finalizer_student\",\n \"date_created\",\n \"date_finalized\",\n \"cancelled\",\n \"subject\",\n \"has_initiator_student\",\n \"accept_link\",\n \"cancel_link\",\n ],\n )\n for ex in sorted_exchanges:\n subject = Activity.from_timetable_activity(\n ex.allocation_from.activityRealization.activity\n ).subject\n view_models.append(\n vm(\n subject=\"{}\".format(subject.name),\n type=ex.get_type().name,\n allocation_from=\"{} at {}\".format(\n ex.allocation_from.day, ex.allocation_from.start\n ),\n allocation_to=\"{} at {}\".format(\n ex.allocation_to.day, ex.allocation_to.start\n ),\n has_initiator_student=ex.initiator_student is not None,\n initiator_student=\"{} {}\".format(\n ex.initiator_student.name.title(),\n ex.initiator_student.surname.title(),\n )\n if ex.initiator_student is not None\n else None,\n requested_finalizer_student=\"{}\".format(\n str(ex.requested_finalizer_student)\n ),\n date_created=\"{}\".format(str(ex.date_created)),\n date_finalized=\"{}\".format(str(ex.date_finalized)),\n cancelled=bool(ex.date_cancelled),\n accept_link=reverse(\n \"accept_exchange\",\n kwargs={\n \"timetable_slug\": ex.allocation_from.timetable.slug,\n \"exchange_id\": ex.id,\n },\n )\n if manager_student and is_exchange_acceptable(ex, manager_student)\n else None,\n cancel_link=reverse(\n \"cancel_exchange\",\n kwargs={\n \"timetable_slug\": ex.allocation_from.timetable.slug,\n \"exchange_id\": ex.id,\n },\n )\n if manager_student and is_exchange_cancellable(ex, manager_student)\n else None,\n )\n )\n\n return {\n \"exchanges\": view_models,\n \"show_subject\": show_subject,\n \"show_student\": show_student,\n \"show_cancel_link\": show_cancel_link,\n \"source_word\": \"Their\" if not third_person else \"From\",\n \"destination_word\": \"for your\" if not third_person else \"to\",\n }\n","sub_path":"exchange/templatetags/exchange_helpers.py","file_name":"exchange_helpers.py","file_ext":"py","file_size_in_byte":5029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"456929575","text":"#!/usr/bin/env python\n\nimport argparse\nimport os\nfrom textwrap import dedent\n\n\ndef get_args():\n parser = argparse.ArgumentParser(description='Build ssh config file.')\n parser.add_argument('deploy_host',\n help='Hostname or IP of deploy host')\n parser.add_argument('--user',\n default='ubuntu',\n help='User on deploy host')\n parser.add_argument('--dest',\n default='~/.ssh/config',\n help='Default destination')\n\n args = parser.parse_args()\n return args\n\n\ndef main():\n args = get_args()\n\n config = os.path.expanduser(args.dest)\n dest_dir = os.path.dirname(config)\n\n os.makedirs(os.path.expanduser(dest_dir), exist_ok=True)\n with open(config, 'w') as fp:\n fp.write(dedent(f\"\"\"\n Host *\n StrictHostKeyChecking no\n \n Host deploy_host\n Hostname {args.deploy_host}\n User {args.user}\n StrictHostKeyChecking no\n ConnectTimeout 5\n ConnectionAttempts 20\n\n \"\"\"))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"ci_scripts/host_config.py","file_name":"host_config.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"339929231","text":"from random import randint\r\nprint('THERE ARE 4 DOORS. BEHIND ONE OF THESE DOORS THERE IS A PRIZE')\r\nprint('OF ONE MILLION DOLLARS. I WILL TELL YOU ONE OF THE DOORS THAT DOES NOT')\r\nprint('CONTAIN THE PRIZE. YOU MUST SELECT ONE OF THE OTHER THREE')\r\nprint('THERE ARE 10 TRIALS')\r\nprint('GOOD LUCK!!!!')\r\nwin=0\r\nlost=0\r\nfor j in range(1,10):\r\n porta=[0,0,0,0,0]\r\n i=randint(1,4)\r\n porta[i]=100\r\n if (i==4):\r\n k=i-3\r\n i1=i\r\n i2=3\r\n i3=2\r\n elif (i==3):\r\n k=i-1\r\n i1=1\r\n i2=i\r\n i3=4\r\n elif(i==2):\r\n k=i+1\r\n i3=4\r\n i2=1\r\n i1=i\r\n else:\r\n k=i+1\r\n i2=4\r\n i1=3\r\n i3=i\r\n #print('i =',i,'k = ',k)\r\n #print('door ',k,' = ',porta[k])\r\n print('door ',i1,' door ',i2,' or door ',i3,' contains the prize',' door ',k,' does NOT contain it')\r\n num=eval(input('choose one of these other three doors:'))\r\n while(num==k):\r\n print('choose either ',i1,' or ',i2,' or ',i3)\r\n num=eval(input('choose one of these other three doors:'))\r\n if (porta[num]==100):\r\n print('You chose correctly!!!!')\r\n win=win+1\r\n else:\r\n lost=lost+1\r\nprint('you chose correctly ',win,' of the 10 times')\r\n\r\n","sub_path":"chap5#14-1.py","file_name":"chap5#14-1.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"458708584","text":"\n'''\nHobbit:\n100hp\n10dmg\n100speed\n\nElf:\n150hp\n20dmg\n50speed\n\nDwarf:\n150hp\n50dmg\n10speed\n\nOrc:\n150hp\n50dmg\n25speed\n\n'''\n\n# Parent Character class\nclass Character():\n\n def __init__(self, health, damage, speed):\n self.health = health\n self.damage = damage\n self.speed = speed\n\n def show_health(self):\n return self.health\n \n def attack(self, enemy):\n enemy.health = enemy.health - self.damage\n\n def heal(self, potion):\n self.health = self.health + potion\n\n def buff_attack(self, potion):\n self.damage = self.damage + potion\n\n# Hobbit class\nclass Hobbit(Character):\n\n def __init__(self, health, damage, speed):\n super(Hobbit, self).__init__(health, damage, speed)\n\n# Elf class\nclass Elf(Character):\n\n def __init__(self, health, damage, speed):\n super(Elf, self).__init__(health, damage, speed)\n\n def double_damange_shot(self, enemy):\n enemy.health = enemy.health - self.damage * 2\n\n def double_enemy_shot(self, enemy_1, enemy_2):\n self.attack(enemy_1)\n self.attack(enemy_2)\n\n# Dwarf class\nclass Dwarf(Character):\n\n def __init__(self, health, damage, speed):\n super(Dwarf, self).__init__(health, damage, speed)\n\n# Orc class\nclass Orc(Character):\n\n def __init__(self, health, damage, speed):\n super(Orc, self).__init__(health, damage, speed)\n\n\ndef battle_of_the_green_forest():\n\n Elf_A = Elf(120, 20, 50)\n Elf_B = Elf(120, 20, 50)\n Elf_C = Elf(120, 20, 50)\n\n Orc_A = Orc(150, 50, 25)\n Orc_B = Orc(150, 50, 25)\n\n Orc_B.attack(Elf_B)\n Elf_A.attack(Orc_A)\n\n print(Elf_A.health)\n print(Elf_B.health)\n print(Elf_C.health)\n print(Orc_A.health)\n print(Orc_B.health)\n\ndef battle_of_the_wet_snow_biome():\n\n potion = 20\n\n Dwarf_A = Dwarf(150, 50, 10)\n Dwarf_B = Dwarf(150, 50, 10)\n\n Elf_A = Elf(120, 20, 50)\n\n Dwarf_B.attack(Elf_A)\n Dwarf_A.attack(Dwarf_B)\n Elf_A.heal(potion)\n\n print(Dwarf_A.health)\n print(Dwarf_B.health)\n print(Elf_A.health)\n\ndef battle_of_grassy_plains():\n\n Elf_A = Elf(120, 20, 50)\n Elf_B = Elf(120, 20, 50)\n Elf_C = Elf(120, 20, 50)\n Elf_D = Elf(120, 20, 50)\n\n Hobbit_A = Hobbit(100, 10, 100)\n\n Dwarf_A = Dwarf(150, 50, 10)\n\n Orc_A = Orc(150, 50, 25)\n Orc_B = Orc(150, 50, 25)\n Orc_C = Orc(150, 50, 25)\n Orc_D = Orc(150, 50, 25)\n Orc_E = Orc(150, 50, 25)\n\n # From left to right\n Elf_C.attack(Orc_A)\n Dwarf_A.attack(Orc_A)\n Hobbit_A.attack(Orc_E)\n\n Orc_A.attack(Elf_A)\n Orc_A.attack(Elf_B)\n Orc_B.attack(Elf_B)\n Orc_D.attack(Orc_A)\n\n print(Elf_C.health)\n print(Elf_D.health)\n print(Elf_A.health)\n print(Elf_B.health)\n print(Dwarf_A.health)\n print(Hobbit_A.health)\n print(Orc_A.health)\n print(Orc_B.health)\n print(Orc_C.health)\n print(Orc_D.health)\n print(Orc_E.health)\n\nElf_A = Elf(150, 20, 50)","sub_path":"Hacker's Course - C1/Week 2/lotr_simulator.py","file_name":"lotr_simulator.py","file_ext":"py","file_size_in_byte":2893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"405595505","text":"import configparser\nimport logging\nimport userbot\n\nconfig = configparser.ConfigParser()\nconfig.read(\"config.ini\")\n\nuserbot.api_id = int(config[\"BotConfig\"][\"api_id\"])\nuserbot.api_hash = config[\"BotConfig\"][\"api_hash\"]\n\nif config[\"BotConfig\"][\"useProxy\"] == \"True\":\n userbot.proxy = (\n int(config[\"BotConfig\"][\"proxyType\"]),\n config[\"BotConfig\"][\"proxyURL\"],\n int(config[\"BotConfig\"][\"proxyPort\"]))\nelse:\n userbot.proxy = ()\n\nuserbot.COMMAND_HEADER = config[\"PluginsConfig\"][\"COMMAND_HEADER\"]\nuserbot.disableCommandList = config[\"PluginsConfig\"][\"disableCommand\"].split(\" \")\n\nloggingObj = __import__(\"logging\")\nlogging.basicConfig(format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s',\n level=getattr(loggingObj, config[\"BotConfig\"][\"logLevel\"].upper(), logging.INFO))\n\nuserbot.pluginDict = {}\n\nuserbot.start()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"510019768","text":"# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://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__author__ = \"lizlooney@google.com (Liz Looney)\"\n\n# Python Standard Library\nfrom datetime import datetime, timedelta, timezone\nimport json\nimport logging\nimport math\nimport os\nimport time\nimport traceback\n\n# Other Modules\nfrom google.oauth2 import service_account\nimport googleapiclient.discovery\nimport tensorflow as tf\nfrom tensorflow.core.util import event_pb2\n\n# My Modules\nimport action\nimport blob_storage\nimport constants\nimport exceptions\nimport storage\nimport tflite_creator\nimport util\n\nBUCKET = ('%s' % constants.PROJECT_ID)\n\nSTARTING_MODELS = {\n 'SSD MobileNet v2 320x320': {\n 'pipeline_config': 'tf2/20200711/ssd_mobilenet_v2_320x320_coco17_tpu-8/pipeline.config',\n 'checkpoint': 'tf2/20200711/ssd_mobilenet_v2_320x320_coco17_tpu-8/checkpoint/ckpt-0',\n },\n 'SSD MobileNet V2 FPNLite 320x320': {\n 'pipeline_config': 'tf2/20200711/ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8/pipeline.config',\n 'checkpoint': 'tf2/20200711/ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8/checkpoint/ckpt-0',\n },\n 'SSD MobileNet V1 FPN 640x640': {\n 'pipeline_config': 'tf2/20200711/ssd_mobilenet_v1_fpn_640x640_coco17_tpu-8/pipeline.config',\n 'checkpoint': 'tf2/20200711/ssd_mobilenet_v1_fpn_640x640_coco17_tpu-8/checkpoint/ckpt-0',\n },\n 'SSD MobileNet V2 FPNLite 640x640': {\n 'pipeline_config': 'tf2/20200711/ssd_mobilenet_v2_fpnlite_640x640_coco17_tpu-8/pipeline.config',\n 'checkpoint': 'tf2/20200711/ssd_mobilenet_v2_fpnlite_640x640_coco17_tpu-8/checkpoint/ckpt-0',\n },\n}\n\ndef validate_starting_model(s):\n if s not in STARTING_MODELS:\n try:\n return storage.validate_uuid(s)\n except:\n message = \"Error: '%s is not a valid argument.\" % s\n logging.critical(message)\n raise exceptions.HttpErrorBadRequest(message)\n return s\n\n\ndef get_starting_model_names():\n names = list(STARTING_MODELS.keys())\n return names\n\ndef start_training_model(team_uuid, description, dataset_uuids_json,\n starting_model, max_running_minutes, num_training_steps, create_time_ms):\n # Call retrieve_model_list to update all models (which may have finished training) and update\n # the team_entity.\n model_entities = retrieve_model_list(team_uuid)\n\n found_starting_model = starting_model in STARTING_MODELS\n if found_starting_model:\n starting_model_uuid = None\n starting_model_entity = None\n original_starting_model = starting_model\n user_visible_starting_model = starting_model\n starting_model_data = STARTING_MODELS[starting_model]\n config_template_blob_name = 'static/training/models/%s' % (\n starting_model_data['pipeline_config'])\n fine_tune_checkpoint = 'gs://%s/static/training/models/%s' % (\n BUCKET, starting_model_data['checkpoint'])\n else:\n # starting_model is the model_uuid of one of the user's own models.\n starting_model_uuid = starting_model\n # retrieve_model_entity will raise HttpErrorNotFound\n # if the team_uuid/starting_model_uuid is not found\n starting_model_entity = retrieve_model_entity(team_uuid, starting_model_uuid)\n if starting_model_entity['trained_checkpoint_path'] == '':\n message = 'Error: Trained checkpoint not found for model_uuid=%s.' % starting_model_uuid\n logging.critical(message)\n raise exceptions.HttpErrorNotFound(message)\n original_starting_model = starting_model_entity['original_starting_model']\n if original_starting_model not in STARTING_MODELS:\n message = 'Error: Original starting model is not longer supported: %s' % original_starting_model\n logging.critical(message)\n raise exceptions.HttpErrorNotFound(message)\n # user_visible_starting_model is the description field of the model entity.\n user_visible_starting_model = starting_model_entity['description']\n starting_model_data = STARTING_MODELS[original_starting_model]\n config_template_blob_name = 'static/training/models/%s' % (\n starting_model_data['pipeline_config'])\n fine_tune_checkpoint = starting_model_entity['trained_checkpoint_path']\n # Remove trailing .index if it's there.\n if fine_tune_checkpoint.endswith('.index'):\n fine_tune_checkpoint = fine_tune_checkpoint[:-6]\n\n dataset_uuid_list = json.loads(dataset_uuids_json)\n dataset_entities = storage.retrieve_dataset_entities(team_uuid, dataset_uuid_list)\n if len(dataset_entities) != len(dataset_uuid_list):\n message = 'Error: One or more datasets not found for dataset_uuids=%s.' % dataset_uuids_json\n logging.critical(message)\n raise exceptions.HttpErrorNotFound(message)\n\n previous_training_steps = 0\n dataset_uuids = []\n train_input_path = []\n eval_input_path = []\n train_frame_count = 0\n eval_frame_count = 0\n train_negative_frame_count = 0\n eval_negative_frame_count = 0\n train_dict_label_to_count = {}\n eval_dict_label_to_count = {}\n sorted_label_list = None\n label_map_path = None\n if starting_model_entity is not None:\n previous_training_steps = starting_model_entity['total_training_steps']\n dataset_uuids.extend(starting_model_entity['dataset_uuids'])\n train_input_path.extend(starting_model_entity['train_input_path'])\n eval_input_path.extend(starting_model_entity['eval_input_path'])\n train_frame_count += starting_model_entity['train_frame_count']\n eval_frame_count += starting_model_entity['eval_frame_count']\n train_negative_frame_count += starting_model_entity['train_negative_frame_count']\n eval_negative_frame_count += starting_model_entity['eval_negative_frame_count']\n util.extend_dict_label_to_count(train_dict_label_to_count, starting_model_entity['train_dict_label_to_count'])\n util.extend_dict_label_to_count(eval_dict_label_to_count, starting_model_entity['eval_dict_label_to_count'])\n sorted_label_list = starting_model_entity['sorted_label_list']\n label_map_path = starting_model_entity['label_map_path']\n\n for dataset_entity in dataset_entities:\n dataset_uuids.append(dataset_entity['dataset_uuid'])\n train_input_path.append(dataset_entity['train_input_path'])\n eval_input_path.append(dataset_entity['eval_input_path'])\n train_frame_count += dataset_entity['train_frame_count']\n eval_frame_count += dataset_entity['eval_frame_count']\n train_negative_frame_count += dataset_entity['train_negative_frame_count']\n eval_negative_frame_count += dataset_entity['eval_negative_frame_count']\n util.extend_dict_label_to_count(train_dict_label_to_count, dataset_entity['train_dict_label_to_count'])\n util.extend_dict_label_to_count(eval_dict_label_to_count, dataset_entity['eval_dict_label_to_count'])\n if sorted_label_list is None:\n sorted_label_list = dataset_entity['sorted_label_list']\n label_map_path = dataset_entity['label_map_path']\n elif sorted_label_list != dataset_entity['sorted_label_list']:\n message = \"Error: The datasets contain different labels and cannot be used together.\"\n logging.critical(message)\n raise exceptions.HttpErrorBadRequest(message)\n\n # Create the pipeline.config file and store it in cloud storage.\n bucket = util.storage_client().get_bucket(BUCKET)\n pipeline_config = (bucket.blob(config_template_blob_name).download_as_string().decode('utf-8')\n .replace('TO_BE_CONFIGURED/eval_input_path', json.dumps(eval_input_path))\n .replace('TO_BE_CONFIGURED/fine_tune_checkpoint', fine_tune_checkpoint)\n .replace('TO_BE_CONFIGURED/label_map_path', label_map_path)\n .replace('TO_BE_CONFIGURED/num_classes', str(len(sorted_label_list)))\n .replace('TO_BE_CONFIGURED/num_examples', str(eval_frame_count))\n .replace('TO_BE_CONFIGURED/num_training_steps', str(num_training_steps))\n .replace('TO_BE_CONFIGURED/num_visualizations', str(min(100, eval_frame_count)))\n .replace('TO_BE_CONFIGURED/train_input_path', json.dumps(train_input_path))\n .replace('TO_BE_CONFIGURED/warmup_steps_1000', str(min(1000, num_training_steps)))\n .replace('TO_BE_CONFIGURED/warmup_steps_2000', str(min(2000, num_training_steps)))\n )\n\n packageUris = [\n 'gs://%s/static/training/object_detection-0.1_2.5.0.tar.gz' % BUCKET,\n 'gs://%s/static/training/slim-0.1.tar.gz' % BUCKET,\n 'gs://%s/static/training/pycocotools-2.0.tar.gz' % BUCKET,\n ]\n region = 'us-central1' # Choices are us-central1 or europe-west4\n runtimeVersion = '2.5' # Not supported beginning August 13, 2022\n pythonVersion = '3.7'\n\n # storage.model_trainer_starting will raise HttpErrorUnprocessableEntity\n # if the max_running_minutes exceeds the team's remaining_training_minutes.\n model_uuid = storage.model_trainer_starting(team_uuid, max_running_minutes)\n model_folder = blob_storage.get_model_folder(team_uuid, model_uuid)\n\n try:\n pipeline_config_path = blob_storage.store_pipeline_config(model_folder, pipeline_config)\n\n model_dir = blob_storage.get_model_folder_path(model_folder)\n job_dir = model_dir\n checkpoint_dir = model_dir\n\n train_job_id = __get_train_job_id(model_uuid)\n scheduling = {\n 'maxRunningTime': '%ds' % int(max_running_minutes * 60),\n }\n train_training_input = {\n 'scaleTier': 'BASIC_TPU',\n 'packageUris': packageUris,\n 'pythonModule': 'object_detection.model_main_tf2',\n 'args': [\n '--model_dir', model_dir,\n '--pipeline_config_path', pipeline_config_path,\n '--checkpoint_every_n', str(100),\n '--use_tpu', 'true',\n ],\n 'region': region,\n 'jobDir': job_dir,\n 'runtimeVersion': runtimeVersion,\n 'pythonVersion': pythonVersion,\n 'scheduling': scheduling,\n }\n train_job = {\n 'jobId': train_job_id,\n 'trainingInput': train_training_input\n }\n\n eval_job_id = __get_eval_job_id(model_uuid)\n eval_training_input = {\n 'scaleTier': 'BASIC_GPU',\n 'packageUris': packageUris,\n 'pythonModule': 'object_detection.model_main_tf2',\n 'args': [\n '--model_dir', model_dir,\n '--pipeline_config_path', pipeline_config_path,\n '--checkpoint_dir', checkpoint_dir,\n ],\n 'region': region,\n 'jobDir': job_dir,\n 'runtimeVersion': runtimeVersion,\n 'pythonVersion': pythonVersion,\n }\n eval_job = {\n 'jobId': eval_job_id,\n 'trainingInput': eval_training_input,\n }\n\n ml = __get_ml_service()\n parent = __get_parent()\n\n # Start the eval job first to because it runs slower than the train job. This helps it to\n # not miss the first checkpoint, but does not completely prevent that.\n try:\n if eval_frame_count > 0:\n eval_job_response = ml.projects().jobs().create(parent=parent, body=eval_job).execute()\n else:\n eval_job_response = None\n except:\n util.log('model_trainer.start_training_model - creating eval job - except %s' %\n traceback.format_exc().replace('\\n', ' ... '))\n raise\n\n try:\n train_job_response = ml.projects().jobs().create(parent=parent, body=train_job).execute()\n except:\n util.log('model_trainer.start_training_model - creating training job - except %s' %\n traceback.format_exc().replace('\\n', ' ... '))\n if eval_job_response is not None:\n # Cancel the eval job.\n ml.projects().jobs().cancel(name=__get_eval_job_name(model_uuid)).execute()\n raise\n\n except:\n # storage.failed_to_start_training will adjust the team's remaining training time and delete\n # any model blobs (such as the pipeline config file) that were created.\n storage.model_trainer_failed_to_start(team_uuid, model_folder, max_running_minutes)\n raise\n\n tensorflow_version = '2'\n model_entity = storage.model_trainer_started(team_uuid, model_uuid, description, model_folder,\n tensorflow_version, dataset_uuids, create_time_ms, max_running_minutes, num_training_steps,\n previous_training_steps, starting_model, user_visible_starting_model,\n original_starting_model, fine_tune_checkpoint,\n sorted_label_list, label_map_path, train_input_path, eval_input_path,\n train_frame_count, eval_frame_count, train_negative_frame_count, eval_negative_frame_count,\n train_dict_label_to_count, eval_dict_label_to_count, train_job_response, eval_job_response)\n __start_monitor_training(team_uuid, model_entity['model_uuid'])\n return model_entity\n\ndef retrieve_model_list(team_uuid):\n model_entities = storage.retrieve_model_list(team_uuid)\n ml = None\n for model_entity in model_entities:\n model_entity, ml = __update_model_entity_job_state(model_entity, ml)\n return model_entities\n\ndef retrieve_model_entity(team_uuid, model_uuid):\n # storage.retrieve_model_entity will raise HttpErrorNotFound\n # if the team_uuid/model_uuid is not found.\n model_entity = storage.retrieve_model_entity(team_uuid, model_uuid)\n model_entity, _ = __update_model_entity_job_state(model_entity)\n return model_entity\n\ndef __update_model_entity_job_state(model_entity, ml=None):\n # If the training and eval jobs weren't done last time we checked, check now.\n if is_not_done(model_entity):\n if ml is None:\n ml = __get_ml_service()\n train_job_name = __get_train_job_name(model_entity['model_uuid'])\n train_job_response = ml.projects().jobs().get(name=train_job_name).execute()\n if model_entity['eval_job']:\n eval_job_name = __get_eval_job_name(model_entity['model_uuid'])\n eval_job_response = ml.projects().jobs().get(name=eval_job_name).execute()\n if __is_alive(eval_job_response['state']):\n # If the training job has failed or been cancelled, cancel the eval job.\n if __is_dead_or_dying(train_job_response['state']):\n ml.projects().jobs().cancel(name=eval_job_name).execute()\n eval_job_response = ml.projects().jobs().get(name=eval_job_name).execute()\n # If the training job succeeded and we have the final eval, cancel the eval job.\n elif (__is_done(train_job_response['state']) and\n model_entity['evaled_steps'] >= model_entity['trained_steps']):\n ml.projects().jobs().cancel(name=eval_job_name).execute()\n eval_job_response = ml.projects().jobs().get(name=eval_job_name).execute()\n else:\n eval_job_response = None\n model_entity = storage.update_model_entity_job_state(\n model_entity['team_uuid'], model_entity['model_uuid'], train_job_response, eval_job_response)\n return model_entity, ml\n\ndef is_not_done(model_entity):\n return (\n __is_not_done(model_entity['train_job_state']) or\n __is_not_done(model_entity['eval_job_state']))\n\ndef is_done(model_entity):\n return (\n __is_done(model_entity['train_job_state']) and\n __is_done(model_entity['eval_job_state']))\n\ndef cancel_training_model(team_uuid, model_uuid):\n # retrieve_model_entity will raise HttpErrorNotFound\n # if the team_uuid/model_uuid is not found.\n model_entity = retrieve_model_entity(team_uuid, model_uuid)\n ml = __get_ml_service()\n if __is_alive(model_entity['train_job_state']):\n try:\n train_job_name = __get_train_job_name(model_uuid)\n ml.projects().jobs().cancel(name=train_job_name).execute()\n except:\n util.log('model_trainer.cancel_training_model - canceling training job - except %s' %\n traceback.format_exc().replace('\\n', ' ... '))\n if model_entity['eval_job']:\n if __is_alive(model_entity['eval_job_state']):\n try:\n eval_job_name = __get_eval_job_name(model_uuid)\n ml.projects().jobs().cancel(name=eval_job_name).execute()\n except:\n util.log('model_trainer.cancel_training_model - canceling eval job - except %s' %\n traceback.format_exc().replace('\\n', ' ... '))\n return storage.cancel_training_requested(team_uuid, model_uuid)\n\ndef __get_ml_service():\n scopes = ['https://www.googleapis.com/auth/cloud-platform']\n credentials = service_account.Credentials.from_service_account_file('key.json', scopes=scopes)\n return googleapiclient.discovery.build(\n serviceName='ml', version='v1', credentials=credentials, cache_discovery=False)\n\ndef __get_parent():\n # TODO(lizlooney): Is the project id here supposed to be our Google Cloud Project ID?\n return 'projects/%s' % constants.PROJECT_ID\n\ndef __get_train_job_id(model_uuid):\n return 'train_%s' % model_uuid\n\ndef __get_eval_job_id(model_uuid):\n return 'eval_%s' % model_uuid\n\ndef __get_train_job_name(model_uuid):\n return '%s/jobs/%s' % (__get_parent(), __get_train_job_id(model_uuid))\n\ndef __get_eval_job_name(model_uuid):\n return '%s/jobs/%s' % (__get_parent(), __get_eval_job_id(model_uuid))\n\ndef __is_alive(state):\n return (state == 'QUEUED' or\n state == 'PREPARING' or\n state == 'RUNNING')\n\ndef __is_dead_or_dying(state):\n return (state == 'FAILED' or\n state == 'CANCELLING' or\n state == 'CANCELLED')\n\ndef __is_not_done(state):\n return (state != '' and\n state != 'SUCCEEDED' and\n state != 'FAILED' and\n state != 'CANCELLED')\n\ndef __is_done(state):\n return not __is_not_done(state)\n\ndef maybe_restart_monitor_training(team_uuid, model_uuid):\n # retrieve_model_entity will raise HttpErrorNotFound\n # if the team_uuid/model_uuid is not found.\n model_entity = retrieve_model_entity(team_uuid, model_uuid)\n\n if ('monitor_training_finished' not in model_entity or\n 'monitor_training_triggered_time_ms' not in model_entity or\n 'monitor_training_active_time_ms' not in model_entity):\n # Some models were trained before these fields were added.\n return False, model_entity\n\n if model_entity['monitor_training_finished']:\n # The monitor training action finished.\n return False, model_entity\n\n if model_entity['monitor_training_triggered_time_ms'] != 0:\n # The monitor training action was not triggered yet. It shouldn't be restarted since it\n # hasn't even started the first time yet.\n return False, model_entity\n\n if model_entity['monitor_training_active_time_ms'] <= model_entity['monitor_training_triggered_time_ms']:\n # The monitor training action was triggered, but not active.\n # Check if it has been <= 3 minutes since it was triggered.\n # Since monitor_training_triggered_time_ms is non-zero, we can use the\n # monitor_training_triggered_time field.\n if datetime.now(timezone.utc) - model_entity['monitor_training_triggered_time'] <= timedelta(minutes=3):\n return False, model_entity\n else:\n # The monitor training action was active after it was triggered.\n # Check if it has been <= 3 minutes since it was active.\n # Since monitor_training_triggered_time_ms and monitor_training_active_time_ms are both\n # non-zero, we can use the monitor_training_triggered_time and monitor_training_active_time\n # fields.\n if datetime.now(timezone.utc) - model_entity['monitor_training_active_time'] <= timedelta(minutes=3):\n return False, model_entity\n\n return True, __start_monitor_training(team_uuid, model_uuid)\n\ndef __start_monitor_training(team_uuid, model_uuid):\n model_entity = storage.prepare_to_start_monitor_training(team_uuid, model_uuid)\n action_parameters = action.create_action_parameters(\n team_uuid, action.ACTION_NAME_MONITOR_TRAINING)\n action_parameters['team_uuid'] = team_uuid\n action_parameters['model_uuid'] = model_uuid\n action.trigger_action_via_blob(action_parameters)\n return model_entity\n\ndef monitor_training(action_parameters):\n team_uuid = action_parameters['team_uuid']\n model_uuid = action_parameters['model_uuid']\n\n model_entity = retrieve_model_entity(team_uuid, model_uuid)\n model_folder = model_entity['model_folder']\n prev_training_done = __is_done(model_entity['train_job_state'])\n\n while True:\n model_entity = storage.monitor_training_active(team_uuid, model_uuid)\n\n if not prev_training_done:\n training_done = __is_done(model_entity['train_job_state'])\n if training_done:\n # Training just finished. Trigger the action to create the tflite model.\n tflite_creator.trigger_create_tflite(team_uuid, model_uuid)\n prev_training_done = training_done\n\n previous_time_ms = model_entity['monitor_training_active_time_ms']\n\n for job_type in ['train', 'eval']:\n dict_path_to_updated = blob_storage.get_event_file_paths(model_folder, job_type)\n for event_file_path, updated in dict_path_to_updated.items():\n if ('dict_event_file_path_to_updated' in model_entity and\n event_file_path in model_entity['dict_event_file_path_to_updated'] and\n model_entity['dict_event_file_path_to_updated'][event_file_path] == updated):\n continue\n largest_step, scalar_summary_items, image_summary_items = __monitor_training_for_event_file(\n model_folder, job_type, event_file_path, action_parameters)\n model_entity = storage.update_model_entity_summary_items(team_uuid, model_uuid, job_type,\n event_file_path, updated, largest_step, scalar_summary_items, image_summary_items)\n\n if is_done(model_entity):\n # If we didn't update the model during the for loop, we are done.\n if model_entity['monitor_training_active_time_ms'] == previous_time_ms:\n model_entity = storage.monitor_training_finished(team_uuid, model_uuid)\n return\n\n if action.remaining_timedelta(action_parameters) > timedelta(minutes=2):\n time.sleep(60)\n action.retrigger_if_necessary(action_parameters)\n\n\ndef __monitor_training_for_event_file(model_folder, job_type, event_file_path, action_parameters):\n largest_step = None\n scalar_summary_items = {}\n image_summary_items = {}\n for record in tf.data.TFRecordDataset(event_file_path):\n action.retrigger_if_necessary(action_parameters)\n event = event_pb2.Event.FromString(record.numpy())\n if not hasattr(event, 'step'):\n continue\n if largest_step is None or event.step > largest_step:\n largest_step = event.step\n if not hasattr(event, 'summary'):\n continue\n for value in event.summary.value:\n if (not hasattr(value, 'metadata') or\n not hasattr(value.metadata, 'plugin_data') or\n not hasattr(value.metadata.plugin_data, 'plugin_name')):\n continue\n if value.metadata.plugin_data.plugin_name == 'scalars':\n item_value = float(tf.make_ndarray(value.tensor))\n if math.isnan(item_value):\n continue\n item = {\n 'step': event.step,\n 'tag': value.tag,\n 'value': item_value\n }\n scalar_summary_items[__make_key(event.step, value.tag)] = item\n elif value.metadata.plugin_data.plugin_name == 'images':\n if job_type == 'train':\n # Don't bother saving training images.\n continue\n image_value = tf.make_ndarray(value.tensor)\n if len(image_value) < 3: # width, height, image bytes\n continue\n width = int(float(image_value[0].decode('utf-8')))\n height = int(float(image_value[1].decode('utf-8')))\n image_bytes = image_value[2]\n # There might be more than one image, but we only look at the first one.\n blob_storage.store_event_summary_image(model_folder, job_type,\n event.step, value.tag, image_bytes)\n item = {\n 'job_type': job_type,\n 'step': event.step,\n 'tag': value.tag,\n 'width': width,\n 'height': height,\n }\n image_summary_items[__make_key(event.step, value.tag)] = item\n return largest_step, scalar_summary_items, image_summary_items\n\ndef __make_key(step, tag):\n return str(step) + '_' + tag\n\n\ndef retrieve_tags_and_steps(team_uuid, model_uuid, job_type, value_type):\n # retrieve_model_entity will raise HttpErrorNotFound\n # if the team_uuid/model_uuid is not found.\n model_entity = retrieve_model_entity(team_uuid, model_uuid)\n model_folder = model_entity['model_folder']\n summary_items_field_name = storage.get_model_entity_summary_items_field_name(job_type, value_type)\n if summary_items_field_name not in model_entity:\n return __retrieve_tags_and_steps_from_event_file(model_folder, job_type, value_type)\n step_and_tag_pairs = []\n for key, item in model_entity[summary_items_field_name].items():\n pair = {\n 'step': item['step'],\n 'tag': item['tag'],\n }\n step_and_tag_pairs.append(pair)\n return step_and_tag_pairs\n\n\ndef retrieve_summary_items(team_uuid, model_uuid, job_type, value_type, dict_step_to_tags):\n # retrieve_model_entity will raise HttpErrorNotFound\n # if the team_uuid/model_uuid is not found.\n model_entity = retrieve_model_entity(team_uuid, model_uuid)\n model_folder = model_entity['model_folder']\n summary_items_field_name = storage.get_model_entity_summary_items_field_name(job_type, value_type)\n if summary_items_field_name not in model_entity:\n return __retrieve_summary_items_from_event_file(model_folder, job_type, value_type, dict_step_to_tags)\n summary_items = []\n for step, tags in dict_step_to_tags.items():\n for tag in tags:\n item = model_entity[summary_items_field_name][__make_key(step, tag)]\n summary_item = {\n 'step': item['step'],\n 'tag': item['tag'],\n }\n if value_type == 'scalar':\n summary_item['value'] = item['value']\n elif value_type == 'image':\n exists, image_url = blob_storage.get_event_summary_image_download_url(\n model_folder, item['job_type'], item['step'], item['tag'], None)\n if not exists:\n continue\n summary_item['value'] = {\n 'width': item['width'],\n 'height': item['height'],\n 'image_url': image_url,\n }\n summary_items.append(summary_item)\n return summary_items\n\n\ndef __retrieve_tags_and_steps_from_event_file(model_folder, job_type, value_type):\n step_and_tag_pairs = []\n dict_path_to_updated = blob_storage.get_event_file_paths(model_folder, job_type)\n for event_file_path, updated in dict_path_to_updated.items():\n for record in tf.data.TFRecordDataset(event_file_path):\n event = event_pb2.Event.FromString(record.numpy())\n if (not hasattr(event, 'step') or\n not hasattr(event, 'summary')):\n continue\n for value in event.summary.value:\n if (not hasattr(value, 'metadata') or\n not hasattr(value.metadata, 'plugin_data') or\n not hasattr(value.metadata.plugin_data, 'plugin_name')):\n continue\n if value_type == 'scalar':\n if value.metadata.plugin_data.plugin_name != 'scalars':\n continue\n elif value_type == 'image':\n if value.metadata.plugin_data.plugin_name != 'images':\n continue\n else:\n continue\n pair = {\n 'step': event.step,\n 'tag': value.tag,\n }\n step_and_tag_pairs.append(pair)\n return step_and_tag_pairs\n\n\ndef __retrieve_summary_items_from_event_file(model_folder, job_type, value_type, dict_step_to_tags):\n summary_items = []\n dict_path_to_updated = blob_storage.get_event_file_paths(model_folder, job_type)\n for event_file_path, updated in dict_path_to_updated.items():\n for record in tf.data.TFRecordDataset(event_file_path):\n event = event_pb2.Event.FromString(record.numpy())\n if (not hasattr(event, 'step') or\n not hasattr(event, 'summary')):\n continue\n step_key = str(event.step)\n if step_key not in dict_step_to_tags:\n continue\n for value in event.summary.value:\n if (not hasattr(value, 'metadata') or\n not hasattr(value.metadata, 'plugin_data') or\n not hasattr(value.metadata.plugin_data, 'plugin_name')):\n continue\n if value.tag not in dict_step_to_tags[step_key]:\n continue\n if value_type == 'scalar':\n if value.metadata.plugin_data.plugin_name != 'scalars':\n continue\n elif value_type == 'image':\n if value.metadata.plugin_data.plugin_name != 'images':\n continue\n else:\n continue\n summary_item = {\n 'step': event.step,\n 'tag': value.tag,\n }\n if value_type == 'scalar':\n item_value = float(tf.make_ndarray(value.tensor))\n if math.isnan(item_value):\n continue\n summary_item['value'] = item_value\n elif value_type == 'image':\n image_value = tf.make_ndarray(value.tensor)\n if len(image_value) < 3: # width, height, image bytes\n continue\n width = int(float(image_value[0].decode('utf-8')))\n height = int(float(image_value[1].decode('utf-8')))\n image_bytes = image_value[2]\n exists, image_url = blob_storage.get_event_summary_image_download_url(\n model_folder, job_type, event.step, value.tag, image_bytes)\n if not exists:\n continue\n summary_item['value'] = {\n 'width': width,\n 'height': height,\n 'image_url': image_url,\n }\n summary_items.append(summary_item)\n return summary_items\n","sub_path":"server/model_trainer.py","file_name":"model_trainer.py","file_ext":"py","file_size_in_byte":32115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"107061215","text":"from matplotlib import pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport keyword\nfrom IPython.display import set_matplotlib_formats\nfrom pprint import pprint\n\ndef clean_col(df):\n df.columns = df.columns \\\n .str.strip() \\\n .str.lower() \\\n .str.replace(' ', '_') \\\n .str.replace('(', '') \\\n .str.replace(')', '') \\\n .str.replace('-','_') \\\n .map(lambda x: 'x'+x if x in keyword.kwlist else x )\n\ndef mushroom_plot(series, clazz, title=None, legend_map=None):\n title = series.name if title is None else title\n svs = series.unique() #series values\n cvs = clazz.unique() #class values\n legend_map = {k: k for k in cvs} if legend_map is None else legend_map\n cvs = sorted(cvs, key=lambda c: np.count_nonzero(clazz==c))\n #print(np.count_nonzero(series=='r'))\n data = {k:\n {\n 'total': np.count_nonzero(series==k),\n **{\n c: np.count_nonzero((series==k) & (clazz==c))\n for c in cvs\n }\n }\n for k in svs\n }\n data = sorted(list(data.items()), key=lambda x: -x[1]['total'])\n #pprint(data)\n #finding the left edge\n left = np.array([0] + list(np.cumsum(list(map(lambda x: x[1]['total'], data)))))\n \n plt.figure(figsize=(20,6))\n \n for i,(color, pe) in enumerate(data):\n #figure out bottom edge\n percent = [pe[c]/pe['total'] for c in cvs]\n bottom = [0] + list(np.cumsum(percent))\n for ic, (bot, b, p) in enumerate(zip(cvs, bottom, percent)):\n plt.bar(left[i], p, color='C{0}'.format(ic), width=pe['total'], align='edge', bottom=b)\n midpoints = (left[1:] + left[:-1])/2\n labels = list(map(lambda x: x[0], data))\n plt.xticks(midpoints, labels)\n plt.xlim(0,left[-1])\n plt.ylim(0,1)\n for l in left:\n plt.axvline(l, ls='dashed', color='gray')\n plt.title(title)\n from matplotlib.patches import Patch\n patches = [Patch(color='C{0}'.format(i)) for i, k in enumerate(cvs)]\n labels = [legend_map.get(k, k) for k in cvs]\n plt.legend(patches, labels)\n return data","sub_path":"patternrekt.py","file_name":"patternrekt.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"507327687","text":"\"\"\"Tests for the typing.NamedTuple overlay.\"\"\"\n\nfrom pytype.pytd import pytd\nfrom pytype.tests import test_base\n\n\nclass NamedTupleTest(test_base.TargetPython3BasicTest):\n \"\"\"Tests for the typing.NamedTuple overlay.\"\"\"\n\n def test_make(self):\n errors = self.CheckWithErrors(\"\"\"\\\n\n import typing\n A = typing.NamedTuple(\"A\", [(\"b\", str), (\"c\", str)])\n a = A._make([\"hello\", \"world\"])\n b = A._make([\"hello\", \"world\"], len=len)\n c = A._make([1, 2]) # Should fail\n d = A._make(A) # Should fail\n def f(e: A) -> None: pass\n f(a)\n \"\"\")\n self.assertErrorLogIs(errors, [\n (6, \"wrong-arg-types\"),\n (7, \"wrong-arg-types\")])\n\n def test_subclass(self):\n errors = self.CheckWithErrors(\"\"\"\\\n\n import typing\n A = typing.NamedTuple(\"A\", [(\"b\", str), (\"c\", int)])\n class B(A):\n def __new__(cls, b: str, c: int=1):\n return super(B, cls).__new__(cls, b, c)\n x = B(\"hello\", 2)\n y = B(\"world\")\n def take_a(a: A) -> None: pass\n def take_b(b: B) -> None: pass\n take_a(x)\n take_b(x)\n take_b(y)\n take_b(A(\"\", 0)) # Should fail\n B() # Should fail\n # _make and _replace should return instances of the subclass.\n take_b(B._make([\"hello\", 0]))\n take_b(y._replace(b=\"world\"))\n \"\"\")\n self.assertErrorLogIs(errors, [\n (14, \"wrong-arg-types\"),\n (15, \"missing-parameter\")])\n\n def test_callable_attribute(self):\n ty = self.Infer(\"\"\"\n\n from typing import Callable, NamedTuple\n X = NamedTuple(\"X\", [(\"f\", Callable)])\n def foo(x: X):\n return x.f\n \"\"\")\n self.assertMultiLineEqual(pytd.Print(ty.Lookup(\"foo\")),\n \"def foo(x: X) -> Callable: ...\")\n\n def test_bare_union_attribute(self):\n ty, errors = self.InferWithErrors(\"\"\"\\\n\n from typing import NamedTuple, Union\n X = NamedTuple(\"X\", [(\"x\", Union)])\n def foo(x: X):\n return x.x\n \"\"\")\n self.assertMultiLineEqual(pytd.Print(ty.Lookup(\"foo\")),\n \"def foo(x: X) -> Any: ...\")\n self.assertErrorLogIs(errors, [(3, \"invalid-annotation\", r\"Union.*x\")])\n\n\nclass NamedTupleTestPy3(test_base.TargetPython3FeatureTest):\n \"\"\"Tests for the typing.NamedTuple overlay in Python 3.6.\"\"\"\n\n def test_basic_namedtuple(self):\n ty = self.Infer(\"\"\"\\\n import typing\n X = typing.NamedTuple(\"X\", [(\"a\", int), (\"b\", str)])\n x = X(1, \"hello\")\n a = x.a\n b = x.b\n \"\"\")\n self.assertTypesMatchPytd(\n ty,\n \"\"\"\\\n import collections\n from typing import Callable, Iterable, Sized, Tuple, Type, TypeVar, Union\n typing = ... # type: module\n x = ... # type: X\n a = ... # type: int\n b = ... # type: str\n _TX = TypeVar('_TX', bound=X)\n class X(tuple):\n __slots__ = [\"a\", \"b\"]\n __annotations__ = ... # type: collections.OrderedDict[str, type]\n __dict__ = ... # type: collections.OrderedDict[str, Union[int, str]]\n _field_defaults = ... # type: collections.OrderedDict[str, Union[int,\n str]]\n _field_types = ... # type: collections.OrderedDict[str, type]\n _fields = ... # type: Tuple[str, str]\n a = ... # type: int\n b = ... # type: str\n def __getnewargs__(self) -> Tuple[int, str]: ...\n def __getstate__(self) -> None: ...\n def __init__(self, *args, **kwargs) -> None: ...\n def __new__(cls: Type[_TX], a: int, b: str) -> _TX: ...\n def _asdict(self) -> collections.OrderedDict[str,\n Union[int, str]]: ...\n @classmethod\n def _make(cls: Type[_TX], iterable: Iterable[Union[int, str]],\n new = ..., len: Callable[[Sized], int] = ...) -> _TX: ...\n def _replace(self: _TX, **kwds: Union[int, str]) -> _TX: ...\n \"\"\")\n\n def test_union_attribute(self):\n ty = self.Infer(\"\"\"\n\n from typing import NamedTuple, Union\n X = NamedTuple(\"X\", [(\"x\", Union[bytes, str])])\n def foo(x: X):\n return x.x\n \"\"\")\n self.assertMultiLineEqual(pytd.Print(ty.Lookup(\"foo\")),\n \"def foo(x: X) -> Union[bytes, str]: ...\")\n\n\ntest_base.main(globals(), __name__ == \"__main__\")\n","sub_path":"pytype/tests/py3/test_typing_namedtuple.py","file_name":"test_typing_namedtuple.py","file_ext":"py","file_size_in_byte":4335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"460754051","text":"\"\"\"\nText widget\n\ninsert at END\n\"\"\"\n\nfrom tkinter import *\n\nroot = Tk()\nroot.title(\"Python GUI | Text\")\n\n# text widget\ntext = Text(root, height=5, width=30)\ntext.pack(fill=BOTH, expand=Y)\n\n# inserting text content\ntext.insert(END, \"INITIAL TEXT\")\ntext.insert(END, \"aaa\")\n\nroot.mainloop()\n","sub_path":"stem1400_modules/module_10_gui/s04_widgets/s0412_text/text_2_insert_1_tail_b.py","file_name":"text_2_insert_1_tail_b.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"177717095","text":"\"\"\"\nAn algorithm for deleting a binary tree.\nData Structure and Algorithmic Thinking with Python\nChapter 6, Problem 9, Page 146\n\"\"\"\n\n\nclass Node:\n\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n\n\ndef delete_tree(root):\n\n if root.left:\n if root.left.left or root.left.right:\n delete_tree(root.left)\n root.left = None\n\n if root.right:\n if root.right.left or root.right.right:\n delete_tree(root.right)\n root.right = None\n\n\nif __name__ == '__main__':\n\n tree = Node(1)\n tree.left = Node(2)\n tree.right = Node(3)\n tree.left.left = Node(4)\n tree.left.right = Node(5)\n tree.right.left = Node(6)\n tree.right.right = Node(7)\n\n try:\n tree\n print(\"tree exists\")\n except NameError:\n print(\"tree doesn't exist\")\n\n delete_tree(tree)\n del tree\n\n try:\n tree\n print(\"tree exists\")\n except NameError:\n print(\"tree doesn't exist\")\n","sub_path":"trees/delete_tree.py","file_name":"delete_tree.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"317609724","text":"#encoding: utf-8\n#autor: Allan Sánchez Iparrazar\n#Rendimiento de autos\n\ndef calcularRendimientoKM_L(kilometros,gasolina):\n rendimiento = kilometros/gasolina\n return rendimiento\n \ndef calcularRendimientoMI_GAL(kilometro,gasolina):\n milla = kilometro/1.609344\n galon = gasolina*0.264172051\n \n rendimiento = milla/galon\n return rendimiento\n \ndef calcularRendimientoKM(kmARecorrer,rendimientoKM_L):\n rendimiento = kmARecorrer/rendimientoKM_L\n return rendimiento\n \n \n\ndef main():\n kilometros = int(input(\"Ingresa la cantidad de kilometros recorridos\"))\n gasolina = int(input(\"ingresa la cantidad en litros de gasolina utilizada\"))\n rendimientoKM_L = calcularRendimientoKM_L(kilometros,gasolina)\n rendimientoMI_GAL = calcularRendimientoMI_GAL(kilometros,gasolina)\n \n \n print(\"\"\"Si recorre %.0f km con %.0f litros de gasolina,\nEl rendimiento en km/l es: %.2f\nEl rendimiento en mi/galon es: %.2f \"\"\"%(kilometros,gasolina,rendimientoKM_L,rendimientoMI_GAL))\n kmARecorrer = int(input(\"¿Cuántos kilómetros vas a recorrer?\"))\n \n rendimientoKM = calcularRendimientoKM(kmARecorrer,rendimientoKM_L)\n \n print(\"Para recorrer %.2f kilometros necesitas %.2f litros de gasolina\"%(kmARecorrer,rendimientoKM))\n\nmain()","sub_path":"rendimiento.py","file_name":"rendimiento.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"165810757","text":"# -*-coding: utf-8-*-\n# Author : Christopher Lee\n# License: Apache License\n# File : fetcher.py\n# Date : 2017-02-20 09-02\n# Version: 0.0.1\n# Description: get movie info.\n\nimport logging\nfrom movie_info.config import (DOUBAN_MOVIE_HEADERS,\n DOUBAN_IMAGE_HEADERS)\nfrom movie_info.util import (download, beautify_dict_output)\nfrom movie_info.parser import (DoubanMovieInfoParser)\nfrom movie_info.engine import (DoubanMovieSearchEngine)\n\n__version__ = '0.0.1'\n__author__ = 'Chris'\n\nlogger = logging.getLogger(__name__)\n\n__all__ = ['DoubanMovieInfo']\n\n\nclass BaseMovieInfo(object):\n _parser = None\n _search_engine = None\n _headers = None\n\n def __init__(self, name, year=None):\n assert isinstance(name, str), TypeError('movie name must be `str` type, not \"{}\"'.format(name))\n self._movie_name = name.strip()\n self._play_year = year\n self._movie_url = ''\n self._movie_info = None\n\n # default keywords\n self._keywords = None\n\n @property\n def movie_info(self):\n if self._movie_info is None:\n self._process()\n\n return self._movie_info\n\n def __str__(self):\n if self.movie_info is None:\n return ''\n\n return '电影名称:{}\\n' \\\n '信息来源:{}\\n' \\\n '详细信息:\\n{}'.format(self._movie_name,\n self.movie_info.get('来源'),\n beautify_dict_output(self.movie_info, '海报数据'))\n\n def __repr__(self):\n cls_name = self.__class__.__name__\n return '<{} {}({})>'.format(cls_name,\n self._movie_name,\n self._movie_url)\n\n def _process(self):\n logger.info('Getting movie information of \"{}\" with engine {}'.format(self._movie_name, self._search_engine))\n self._movie_url = self._find_matching_url(self._search_engine().search(*self.__build_keywords()))\n logger.debug('Get matching movie url: {}'.format(self._movie_url))\n\n if self._movie_url:\n page = download(self._movie_url, headers=self._headers)\n self._movie_info = self._parser(self._movie_url, page).movie_info\n else:\n self._movie_info = {}\n logger.error('Search movie \"{}\" failed'.format(self._movie_name))\n\n def __build_keywords(self):\n keywords = self._keywords or []\n if self._play_year:\n keywords.insert(0, '{}'.format(self._play_year))\n\n keywords.insert(0, self._movie_name)\n logger.debug('Build keywords: {}'.format(self._keywords))\n return keywords\n\n def _find_matching_url(self, results):\n raise NotImplementedError\n\n\nclass DoubanMovieInfo(BaseMovieInfo):\n _search_engine = DoubanMovieSearchEngine\n _parser = DoubanMovieInfoParser\n _headers = DOUBAN_MOVIE_HEADERS\n\n def __init__(self, name, play_year=None):\n super().__init__(name, play_year)\n\n # default keywords\n self._keywords = []\n\n def _find_matching_url(self, results):\n for result in results:\n return result['url']\n\n def _process(self):\n super()._process()\n self.movie_info['海报数据'] = self.__download_poster_image()\n\n def __download_poster_image(self):\n logger.debug('Downloading poster: {}'.format(self.movie_info.get('海报链接', '')))\n return download(self.movie_info.get('海报链接', ''), headers=DOUBAN_IMAGE_HEADERS)\n\n\nif __name__ == '__main__':\n def test(*names):\n for name in names:\n b = DoubanMovieInfo(name)\n print(b)\n\n\n test('美女与野兽', '乘风破浪')\n","sub_path":"movie_info/info.py","file_name":"info.py","file_ext":"py","file_size_in_byte":3697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"601952380","text":"# -*- coding: utf-8 -*-\n\"\"\"This file is a BrookStreet spider created on top of the ATSSpider\n\nscrapy crawl brookstreet -a url=\"http://www.brookstreet.co.uk/searchjobs\" -a mining_job_id=999 -a iteration=1 -a extract=1\n\nsample url:\n http://www.brookstreet.co.uk/searchjobs\n\"\"\"\n\nfrom urlparse import urljoin\nfrom re import compile\n\nfrom scrapy.selector import Selector\nfrom scrapy.http import Request\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, ConvertDateString, HtmlFormatter, RemoveBadElements\n\n\nclass BrookStreet(ATSSpider):\n\n name = \"brookstreet\"\n ref_re = compile(\"Id=(\\d+)\")\n count_re = compile(r\"(\\d+)\")\n total_pages = 0\n page = 1\n\n def parse(self, response):\n sel = Selector(response)\n if not self.expected_job_count_set:\n job_count = sel.xpath(\n \"//div[@class='breadcrumb']/li[1]/text()\"\n ).re(self.count_re)\n if job_count:\n self.expected_job_count = job_count[0]\n self.total_pages = int(job_count[0]) / 25\n\n jobs = sel.xpath(\"//div[@id='ctl00_cphMain_udpJob']/div\")\n for job in jobs:\n job_link = job.xpath(\"./h2/a/@href\").extract()\n if job_link:\n job_url = urljoin(response.url, job_link[0])\n meta = {\n 'title': job.xpath(\"./h2/a/text()\").extract(),\n }\n yield Request(\n url=job_url, meta=meta, callback=self.parse_job_callback()\n )\n\n if self.page <= self.total_pages:\n self.page += 1\n next_url = self.start_urls[0] + '/default.aspx?pg=%s' % self.page\n yield Request(next_url, callback=self.parse)\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n loader.add_value('url', response.url)\n loader.add_value('title', response.meta['title'])\n loader.add_xpath(\n 'jobtype',\n \"//strong[contains(text(), 'Type:')]/following-sibling::span/text()\"\n )\n loader.add_xpath(\n 'location',\n \"//strong[contains(text(), 'Location:')]/following-sibling::span/text()\"\n )\n loader.add_xpath(\n 'baseSalary',\n \"//strong[contains(text(), 'Salary:')]/following-sibling::span/text()\"\n )\n loader.add_xpath(\n 'date',\n \"//strong[contains(text(), 'Start Date:')]/following-sibling::span/text()\",\n ConvertDateString(\"%d %b %Y\")\n )\n loader.add_xpath(\n 'description', \"//p[@class='lead-featured']\",\n RemoveBadElements(['input', 'img']), HtmlFormatter()\n )\n loader.add_value(\n 'referencenumber', response.url, Prefix(\"%s-\" % self.name),\n re=self.ref_re\n )\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/brookstreet.py","file_name":"brookstreet.py","file_ext":"py","file_size_in_byte":2980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"491339528","text":"from Acquisition import aq_base, aq_parent\nfrom zope.interface import Interface\nfrom zope.interface import implements\nfrom zope.component import adapts, getMultiAdapter\nfrom plone.memoize.instance import memoize\nfrom plone.app.portlets.portlets import navigation\nfrom plone.app.layout.navigation.interfaces import INavtreeStrategy\nfrom plone.app.layout.navigation.interfaces import INavigationQueryBuilder\nfrom plone.app.layout.navigation.root import getNavigationRoot\nfrom plone.app.layout.navigation.navtree import buildFolderTree\nfrom plone.app.uuid.utils import uuidToObject\nfrom zope import schema\nfrom zope.formlib import form\nfrom Acquisition import aq_inner\nfrom Products.Five.browser.pagetemplatefile import ViewPageTemplateFile\nfrom Products.CMFPlone import utils\nfrom collective.portlet.sitemap import NavigationExtendedPortletMessageFactory as _\nfrom plone.app.uuid.utils import uuidToObject\nfrom zope.component.hooks import getSite\nfrom plone.app.layout.navigation.interfaces import INavtreeStrategy\nfrom Products.CMFPlone.browser.navtree import SitemapNavtreeStrategy\nfrom zope.interface import implementer\n\n\nclass INavigationExtendedPortlet(navigation.INavigationPortlet) :\n \"\"\"A portlet\n\n It inherits from INavigationPortlet\n \"\"\"\n displayAsSiteMap = schema.Bool(\n title=_(u\"label_display_as_site_map\", default=u\"Display as Site Map\"),\n description=_(u\"help_display_as_site_map\",\n default=u\"If checked display all folders as a site map\"),\n default=True,\n required=False)\n \n siteMapDepth = schema.Int(\n title=_(u\"label_site_map_depth\",\n default=u\"Site map depth\"),\n description=_(u\"help_site_map_depth\",\n default=u\"If previous field is checked set the site map depth\"),\n default=2,\n required=False) \n \n css_class = schema.TextLine(title=_(\n u\"Classe CSS\"),\n description=_(u\"Se indicata, viene aggiunta al markup, allo stesso livello della classe: portlet.\"),\n required=False)\n\nclass Assignment(navigation.Assignment):\n \"\"\"Portlet assignment.\n\n This is what is actually managed through the portlets UI and associated\n with columns.\n \"\"\"\n\n implements(INavigationExtendedPortlet)\n \n name = u''\n root = None\n root_uid = None\n currentFolderOnly = False\n includeTop = False\n topLevel = 1\n bottomLevel = 0\n no_icons = False\n thumb_scale = None\n no_thumbs = False\n displayAsSiteMap = True\n siteMapDepth = 2\n css_class = u''\n \n \n def __init__(\n self,\n name=\"\",\n root_uid=None,\n currentFolderOnly=False,\n includeTop=False,\n topLevel=1,\n bottomLevel=0,\n no_icons=False,\n thumb_scale=None,\n no_thumbs=False,\n displayAsSiteMap=True,\n siteMapDepth = 2,\n css_class = u'',\n ):\n super(Assignment, self).__init__(\n name,\n root_uid,\n currentFolderOnly,\n includeTop,\n topLevel,\n bottomLevel,\n no_icons,\n thumb_scale,\n no_thumbs\n )\n self.displayAsSiteMap = displayAsSiteMap \n self.siteMapDepth = siteMapDepth\n self.css_class = css_class\n \n @property\n def title(self):\n \"\"\"\n Display the name in portlet mngmt interface\n \"\"\"\n if self.name:\n return self.name\n return _(u'Navigation Extended')\n\n\n\nclass Renderer(navigation.Renderer):\n \"\"\"Portlet renderer.\n\n This is registered in configure.zcml. The referenced page template is\n rendered, and the implicit variable 'view' will refer to an instance\n of this class. Other methods can be added and referenced in the template.\n \"\"\"\n \n @memoize\n def getNavRootPath(self):\n topLevel = self.data.topLevel\n root_uid = self.data.root_uid\n \n if root_uid:\n if uuidToObject(root_uid):\n return navigation.getRootPath(\n self.context,\n self.data.currentFolderOnly,\n topLevel,\n root_uid\n )\n return None\n \n override_topLevel = getNavigationTopLevelObject(self.context, getSite())\n if override_topLevel:\n topLevel = override_topLevel.portlet_nav_topLevel\n \n root = getNavigationFolderObject(self.context, getSite())\n if root:\n root_uid = root.UID()\n \n return navigation.getRootPath(\n self.context,\n self.data.currentFolderOnly,\n topLevel,\n root_uid\n )\n \n def heading_link_target(self):\n root = getNavigationFolderObject(self.context, getSite())\n if not self.data.root_uid and root:\n return root.absolute_url()\n return super(Renderer, self).heading_link_target()\n \n def title(self):\n root = getNavigationFolderObject(self.context, getSite())\n title = self.data.name\n if not self.data.root_uid and getattr(root, 'portlet_nav_root', False):\n return getattr(root, 'portlet_nav_root_title', title)\n return title\n \n def root_title(self):\n root = self.getNavRoot()\n title = root.Title()\n if getattr(root, 'portlet_nav_root', False):\n return getattr(root, 'portlet_nav_root_title', title)\n return title\n \n \n def hasName(self):\n title = self.title()\n if self.include_top():\n return False\n return title\n \n @memoize\n def getNavTree(self, _marker=[]):\n if _marker is None:\n _marker = []\n \n context = aq_inner(self.context)\n \n # Special case - if the root is supposed to be pruned, we need to\n # abort here\n queryBuilder = getMultiAdapter((context, self.data), INavigationExtendedQueryBuilder)\n strategy = getMultiAdapter((context, self.data), INavtreeExtendedStrategy)\n return buildFolderTree(context, obj=context, query=queryBuilder(), strategy=strategy)\n \n _template = ViewPageTemplateFile('navigation_extended.pt')\n recurse = ViewPageTemplateFile('navigation_extended_recurse.pt')\n\n\nclass AddForm(navigation.AddForm):\n \"\"\"Portlet add form.\n\n This is registered in configure.zcml. The form_fields variable tells\n zope.formlib which fields to display. The create() method actually\n constructs the assignment that is being added.\n \"\"\"\n schema = INavigationExtendedPortlet\n\n def create(self, data):\n return Assignment(name=data.get('name', u\"\"),\n root_uid=data.get('root_uid', \"\"),\n currentFolderOnly=data.get('currentFolderOnly', False),\n includeTop=data.get('includeTop', False),\n topLevel=data.get('topLevel', 0),\n bottomLevel=data.get('bottomLevel', 0),\n displayAsSiteMap=data.get('displayAsSiteMap', True),\n siteMapDepth=data.get('siteMapDepth', 2),\n css_class=data.get('css_class', u''))\n\n\n\nclass EditForm(navigation.EditForm):\n \"\"\"Portlet edit form.\n\n This is registered with configure.zcml. The form_fields variable tells\n zope.formlib which fields to display.\n \"\"\"\n schema = INavigationExtendedPortlet\n\n\nclass INavigationExtendedQueryBuilder(INavigationQueryBuilder):\n \"\"\"An object which returns a catalog query when called, used to \n construct a navigation tree.\n \"\"\"\n \n def __call__():\n \"\"\"Returns a mapping describing a catalog query used to build a\n navigation structure.\n \"\"\" \n\n\nclass NavigationExtendedQueryBuilder(object):\n \"\"\"Build a navtree query based on the settings in navtree_properties\n and those set on the portlet.\n \"\"\"\n implements(INavigationExtendedQueryBuilder)\n adapts(Interface, INavigationExtendedPortlet)\n\n def __init__(self, context, portlet):\n self.context = context\n self.portlet = portlet\n \n portal_properties = utils.getToolByName(context, 'portal_properties')\n navtree_properties = getattr(portal_properties, 'navtree_properties')\n \n portal_url = utils.getToolByName(context, 'portal_url')\n \n # Acquire a custom nav query if available\n customQuery = getattr(context, 'getCustomNavQuery', None)\n if customQuery is not None and utils.safe_callable(customQuery):\n query = customQuery()\n else:\n query = {}\n \n # Construct the path query\n root_uid = portlet.root_uid\n topLevel = portlet.topLevel\n \n if not root_uid:\n override_topLevel = getNavigationTopLevelObject(self.context, getSite())\n if override_topLevel:\n topLevel = override_topLevel.portlet_nav_topLevel\n folderRoot = getNavigationFolderObject(context, getSite())\n if folderRoot:\n root_uid = folderRoot.UID()\n \n root = uuidToObject(root_uid)\n if root is not None:\n rootPath = '/'.join(root.getPhysicalPath())\n else:\n rootPath = getNavigationRoot(context)\n currentPath = '/'.join(context.getPhysicalPath())\n\n \n # If we are above the navigation root, a navtree query would return\n # nothing (since we explicitly start from the root always). Hence,\n # use a regular depth-1 query in this case.\n if portlet.displayAsSiteMap :\n siteMapDepth = portlet.siteMapDepth\n if topLevel and topLevel > 0:\n siteMapDepth = siteMapDepth + topLevel\n \n query['path'] = {'query' : rootPath, 'depth' : siteMapDepth}\n else :\n if not currentPath.startswith(rootPath):\n query['path'] = {'query' : rootPath, 'depth' : 1}\n else:\n query['path'] = {'query' : currentPath, 'navtree' : 1}\n \n if topLevel and topLevel > 0:\n query['path']['navtree_start'] = topLevel + 1\n # XXX: It'd make sense to use 'depth' for bottomLevel, but it doesn't\n # seem to work with EPI.\n\n # Only list the applicable types\n query['portal_type'] = utils.typesToList(context)\n\n # Apply the desired sort\n sortAttribute = navtree_properties.getProperty('sortAttribute', None)\n if sortAttribute is not None:\n query['sort_on'] = sortAttribute\n sortOrder = navtree_properties.getProperty('sortOrder', None)\n if sortOrder is not None:\n query['sort_order'] = sortOrder\n\n # Filter on workflow states, if enabled\n if navtree_properties.getProperty('enable_wf_state_filtering', False):\n query['review_state'] = navtree_properties.getProperty('wf_states_to_show', ())\n\n self.query = query\n\n def __call__(self):\n return self.query\n\n\nclass INavtreeExtendedStrategy(INavtreeStrategy):\n \"\"\"An object that is used by buildFolderTree() to determine how to\n construct a navigation tree.\n \"\"\"\n \n\n@implementer(INavtreeExtendedStrategy)\nclass NavtreeExtendedStrategy(navigation.NavtreeStrategy):\n \"\"\"The navtree strategy used for the default navigation portlet\n \"\"\"\n adapts(Interface, INavigationExtendedPortlet)\n\n def __init__(self, context, portlet):\n SitemapNavtreeStrategy.__init__(self, context, portlet)\n\n # XXX: We can't do this with a 'depth' query to EPI...\n self.bottomLevel = portlet.bottomLevel or 0\n \n root_uid = portlet.root_uid\n topLevel = portlet.topLevel\n \n if not root_uid:\n override_topLevel = getNavigationTopLevelObject(self.context, getSite())\n if override_topLevel:\n topLevel = override_topLevel.portlet_nav_topLevel\n root = getNavigationFolderObject(self.context, getSite())\n if root:\n root_uid = root.UID()\n \n \n self.rootPath = navigation.getRootPath(context,\n portlet.currentFolderOnly,\n topLevel,\n root_uid)\n \n\ndef getNavigationFolderObject(context, portal):\n return getOverrideObject(context, portal, 'portlet_nav_root')\n\n\ndef getNavigationTopLevelObject(context, portal):\n return getOverrideObject(context, portal, 'portlet_nav_topLevel')\n \n \ndef getOverrideObject(context, portal, attribute, forceReturn=False):\n \n def check_value(value, forceReturn=False):\n if value is None:\n return None\n if forceReturn:\n return True\n if isinstance(value, bool):\n return value\n if isinstance(value, basestring):\n return True\n if isinstance(value, int):\n return True\n \n obj = context\n value = getattr(aq_base(obj), attribute, None)\n while (not check_value(value, forceReturn) and aq_base(obj) is not aq_base(portal)):\n parent = aq_parent(aq_inner(obj))\n if parent is None:\n return None\n obj = parent\n value = getattr(aq_base(obj), attribute, None)\n if aq_base(obj) is aq_base(portal):\n return None\n return obj","sub_path":"collective/portlet/sitemap/navigationextendedportlet.py","file_name":"navigationextendedportlet.py","file_ext":"py","file_size_in_byte":13580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"211240150","text":"#Function for simulation and algorithm of orbit optimization\n\nimport math\nimport numpy as np\nimport vectors\nimport space\nimport planet\nimport unit\nimport random\nfrom constants import G\nimport matplotlib.pyplot as plt\n\n#-----------------------------Arrays of physical quantities------------------------------\narrX = []\narrY = []\ndt = 0.01 #simulation time(standart 0.001)\n#----------------------------------------------------------------------------------------\n\ndef plotter(arrX, arrY, type): #function to plot graphs\n if type == 1:\n plt.figure(1)\n plt.xlabel('x')\n plt.ylabel('y')\n plt.title('Orbit of the spacecraft')\n plt.axis([-3, 3, -3, 3])\n plt.grid(True)\n plt.plot(arrX, arrY)\n plt.show()\n if type == 2:\n plt.figure(2)\n plt.xlabel('dv_max')\n plt.ylabel('delta (10^-3)')\n plt.title('Composed function dependence on available velocity')\n plt.grid(True)\n plt.plot(arrX, arrY)\n plt.show()\n\n\n\n\ndef deviation(dvx1: object, dvy1: object, dvx2: object, dvy2: object, dist, plot: object = False) -> object: #simulation of first half of the orbit\n if plot:\n arrX.clear()\n arrY.clear()\n\n global dt\n unitmass = 1.0\n ut = unit.Unit(np.array([1.0, 0.0, 0.0]), np.array([0.0 + dvx1, 1.0 + dvy1, 0.0]), unitmass)\n sp = space.Space()\n\n planetmass = 1.0 / G\n pl = planet.Planet(planetmass)\n sp.planet = pl\n sp.unit = ut\n pos = ut.pos\n angle = 0\n\n E0 = ut.getEnergy(planetmass)\n A0 = ut.vectorLenc(planetmass)\n\n flag = False\n\n while True: #Condition for the whole orbit\n if (ut.pos[1] < ut.vel[1] * dt) and (ut.pos[0] < 0) and not flag:\n flag = True\n ut.vel[0] += dvx2\n ut.vel[1] += dvy2\n\n elif flag and (ut.pos[0]>0) and (ut.pos[1] > 0):\n #pos_next = ut.pos[1] + ut.vel[1] * dt\n #vel_next = ut.vel + pl.acceleration(ut.pos) * dt\n #ut.vel = (ut.vel * abs(pos_next) + vel_next * abs(ut.pos[1])) / (abs(ut.pos[1]) + abs(pos_next))\n break\n\n angle += math.degrees(0.001 / 57)\n sp.step_rot(dt, dist,angle)\n\n if plot:\n\n arrX.append(ut.pos[0])\n arrY.append(ut.pos[1])\n\n\n E = ut.getEnergy(planetmass)\n A = ut.vectorLenc(planetmass)\n glob_vel = ut.vel\n glob_pos = ut.pos\n\n delta = ((E - E0) ** 2) + vectors.squarelength(A - A0)\n return delta\n\n#----------------------------------------------------------------------------------------------------\n\ndef deviationOpt(): # Orbit optimization\n global dt\n dist = 0.2 # distance between masses\n dvx1 = 0.0 # initial values for fluctuations\n dvy1 = 0.0 #\n dvx2 = 0.0 #\n dvy2 = 0.0 #\n dv_opt = (0,0,0,0)\n #------------------\n delta0 = deviation(0.0,0.0,0.0,0.0, dist) #calculation of delta with no dv\n delta_min = delta0\n\n n = 10\n\n dv_range = [0, 0.0005, 0.001, 0.002, 0.004, 0.006, 0.008, 0.01, 0.012, 0.014, 0.016, 0.018, 0.02, 0.04, 0.05, 0.1, 0.2, 0.3] # amount of available correction velocity\n #dv_range = [0, 0.0001, 0.0005, 0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009, 0.01, 0.02, 0.03, 0.04, 0.05, 0.15]\n #step_range = [1, 10, 10, 10, 50, 50, 50, 50, 70, 80, 100, 150, 200, 300, 600, 1000, 1000, 2000]\n step_range = [1, 70, 70, 70, 80, 90, 100, 100, 150, 160, 200, 250, 300, 400, 500, 1000, 1000, 2000]\n #step_range = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2]\n i = -1\n\n print('delta0=', delta0)\n\n arrDelta = []\n arrVel = []\n arrVelCopm = []\n\n try:\n for dv in dv_range:\n count = 0\n i = i + 1\n#---------------------------------------------------------------------------\n dvx1 = 0.0 # initial values for fluctuations\n dvy1 = 0.0 #\n dvx2 = 0.0 #\n dvy2 = 0.0 #\n dvx1_opt = 0.0\n dvy1_opt = 0.0\n dvx2_opt = 0.0\n dvy2_opt = 0.0\n#-----------------------------------------------------------------------------\n while (count < step_range[i]): # optimization cycle\n count += 1\n deriv = derivatives(dvx1,dvy1,dvx2,dvy2, dist)\n delta = deviation(dvx1, dvy1, dvx2, dvy2, dist, True)\n t = - delta0 / sum((i ** 2 for i in deriv))/n # optimization step\n n = 10\n\n#-------------------------------------------------------------------------------\n# while (opt > 10**(-3)):\n# t = random.uniform(0, 1)\n# opt_dvx1 = abs(deviation(dvx1-t*deriv[0], dvy1,dvx2,dvy2))\n# opt_dvy1 = abs(deviation(dvx1, dvy1 - t * deriv[1], dvx2, dvy2))\n# opt_dvx2 = abs(deviation(dvx1, dvy1, dvx2 - t * deriv[2], dvy2))\n# opt_dvy2 = abs(deviation(dvx1, dvy1, dvx2, dvy2 - t * deriv[3]))\n# opt = (opt_dvx1 + opt_dvy1 + opt_dvx2 + opt_dvy2)/4\n#\n#\n# print(\"searching...\")\n# print(\"opt = \"), opt\n#--------------------------------------------------------------------------------\n\n#---------------Step configuration--------------------------------------\n if (delta < 1*10**(-3)):\n n = 50\n if (delta < 1*10**(-5)):\n n = 1*10**2\n if (delta < 1*10**(-7)):\n n = 1*10**4\n if (delta < 5*10**(-9)):\n n = 1*10**6\n if (delta < 2*10**(-9)):\n n = 1**10**7\n if (delta < 1*10**(-10)):\n n = 5**10**7\n#-----------------------------------------------------------------------\n\n if delta < delta_min: # in case delta in this step < delta_min\n delta_min = delta\n dvx1_opt = dvx1 #|\n dvy1_opt = dvy1 #| Save dv values to use it in simulation\n dvx2_opt = dvx2 #|\n dvy2_opt = dvy2 #|\n dv_opt = (dvx1_opt, dvy1_opt, dvx2_opt, dvy2_opt)\n\n #arrDelta.append(math.log1p(delta))\n #arrVel.append(math.log1p(abs(dvx1) + abs(dvy1) + abs(dvx2) + abs(dvy2)))\n\n\n dvx1 += deriv[0] * t\n dvy1 += deriv[1] * t\n dvx2 += deriv[2] * t\n dvy2 += deriv[3] * t\n\n#--------------- Projection if dv bigger than dv_max--------------------------------------\n if ((dvx1 ** 2) + (dvy1 ** 2) > (dv ** 2)):\n K = dv / (math.sqrt((dvx1 ** 2) + (dvy1 ** 2)))\n dvx1 = K * dvx1\n dvy1 = K * dvy1\n\n if ((dvx2 ** 2) + (dvy2 ** 2) > (dv ** 2)):\n K = dv / (math.sqrt((dvx2 ** 2) + (dvy2 ** 2)))\n dvx2 = K * dvx2\n dvy2 = K * dvy2\n#-----------------------------------------------------------------------------------------\n\n print ('dvx1 = ', dvx1, ' dvy1= ', dvy1, 'dvx2=', dvx2, 'dvy2=', dvy2, ' delta = ', delta, ' ', count)\n print ('dv1 = ', abs(dvx1)+ abs(dvy1), 'dv2 = ', abs(dvx2)+ abs(dvy2), 'dv_max= ', dv)\n print ('')\n\n#-----------------adding result valuens to arrays-----------------------------------------\n arrDelta.append(delta_min*10**3)\n arrVel.append(dv)\n\n #for k in range (len(dv_range)):\n arrVelCopm.append([float(j) for j in dv_opt])\n print(\"arrVelComp = \", arrVelCopm)\n print('')\n\n#-----------------------------------------------------------------------------------------\n except KeyboardInterrupt:\n print('Worked!')\n\n print (\"delta: \" ,arrDelta)\n print (\"dv_max: \", arrVel)\n#-----------------------------------------------------------------------------------------\n\n dist_range = [0.15,0.18,0.2,0.22, 0.24] #Distance for simulated systems with given dv\n arrDelta_real = []\n\n print(\"arrVelCopm length =\", len(arrVelCopm))\n\n\n for dist in dist_range:\n delta_real = [0]\n arrDelta_real = [0]\n for k in range(len(arrVelCopm)-1):\n delta_real = deviation(arrVelCopm[k][0], arrVelCopm[k][1], arrVelCopm[k][2], arrVelCopm[k][3], dist)\n arrDelta_real.append(delta_real*10**3)\n\n plt.figure(3)\n plt.xlabel('dv_max')\n plt.ylabel('delta (10^-3)')\n plt.title('Composed function dependence on available velocity and ')\n plt.grid(True)\n plt.plot(arrVel, arrDelta_real, label = \"d = 0. \")\n\n plt.legend()\n\n\n plt.show()\n\n\n #plotter(arrX,arrY,1)\n #plotter(arrVel, arrDelta, 2)\n\ndef derivatives(dvx1,dvy1,dvx2,dvy2, dist):\n offset = 1*(10**(-10)) #amount of offset(deviation)\n dev_nooff = deviation(dvx1,dvy1,dvx2,dvy2, dist) #derivative with no offset\n part_dx1 = (deviation(dvx1+offset,dvy1,dvx2,dvy2,dist) - dev_nooff) / offset\n part_dy1 = (deviation(dvx1, dvy1+ offset, dvx2, dvy2,dist) - dev_nooff) / offset\n part_dx2 = (deviation(dvx1,dvy1,dvx2 + offset,dvy2,dist) - dev_nooff) / offset\n part_dy2 = (deviation(dvx1, dvy1, dvx2, dvy2 + offset,dist) - dev_nooff) / offset\n return (part_dx1, part_dy1, part_dx2, part_dy2)\n\n","sub_path":"deviation.py","file_name":"deviation.py","file_ext":"py","file_size_in_byte":9324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"3630117","text":"from dicttoxml import dicttoxml\r\nfrom database_creation import Message, db\r\n\r\n\r\ndef filter_messages(filter_parameters: dict):\r\n filtered_messages = db.session.query(Message)\r\n json_size = 0\r\n\r\n if 'title' in filter_parameters['filter']:\r\n json_size += 1\r\n filtered_messages = filtered_messages.filter(Message.title == filter_parameters['filter']['title'])\r\n if 'date' in filter_parameters['filter']:\r\n json_size += 1\r\n filtered_messages = filtered_messages.filter(Message.date == convert_date(filter_parameters['filter']['date']))\r\n if 'from' in filter_parameters['filter']:\r\n json_size += 1\r\n filtered_messages = filtered_messages.filter(Message.sender == filter_parameters['filter']['from'])\r\n if 'to' in filter_parameters['filter']:\r\n json_size += 1\r\n filtered_messages = filtered_messages.filter(Message.recipient == filter_parameters['filter']['to'])\r\n\r\n if json_size == len(filter_parameters['filter']):\r\n return filtered_messages\r\n else:\r\n return None\r\n\r\n\r\ndef convert_to_xml(message_from_database: Message) -> bytes:\r\n message_dict = {'Message': {}}\r\n message_dict['Message']['Header'] = {}\r\n message_dict['Message']['Header']['To'] = message_from_database.recipient\r\n message_dict['Message']['Header']['From'] = message_from_database.sender\r\n message_dict['Message']['Header']['Timestamp'] = message_from_database.date + \"T\" + message_from_database.time\r\n message_dict['Message']['Title'] = message_from_database.title\r\n message_dict['Message']['Body'] = message_from_database.message\r\n\r\n return dicttoxml(message_dict, root=False, attr_type=False)\r\n\r\n\r\ndef send_message_to_db(message_in_dict: dict):\r\n if 'Message' in message_in_dict and 'Header' in message_in_dict['Message'] \\\r\n and 'To' in message_in_dict['Message']['Header'] and 'From' in message_in_dict['Message']['Header'] \\\r\n and 'Timestamp' in message_in_dict['Message']['Header'] and 'Title' in message_in_dict['Message'] \\\r\n and 'Body' in message_in_dict['Message']:\r\n try:\r\n current_id = db.session.query(Message)[-1].id + 1\r\n except:\r\n current_id = 1\r\n\r\n message_in_dict = Message(id=current_id, recipient=message_in_dict['Message']['Header']['To'],\r\n sender=message_in_dict['Message']['Header']['From'],\r\n date=message_in_dict['Message']['Header']['Timestamp'][:10],\r\n time=message_in_dict['Message']['Header']['Timestamp'][11:],\r\n title=message_in_dict['Message']['Title'],\r\n message=message_in_dict['Message']['Body'])\r\n db.session.add(message_in_dict)\r\n db.session.commit()\r\n\r\n return \"Пустое сообщение\"\r\n else:\r\n return None\r\n\r\n\r\ndef convert_date(date: str) -> str:\r\n if date[2] == '.' and date[5] == '.':\r\n date = date.split('.')\r\n date = list(reversed(date))\r\n date = '-'.join(date)\r\n else:\r\n date = \"invalid date format\"\r\n\r\n return date\r\n","sub_path":"secondary.py","file_name":"secondary.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"469966217","text":"import pymysql\nimport json\nimport datetime\n\n\ndef connectMYSQL():\n with open('acesso.json') as json_data:\n d = json.load(json_data)\n\n connection = pymysql.connect(host=d['connection']['host'],\n user=d['connection']['user'],\n password=d['connection']['password'],\n database=d['connection']['database'])\n\n return connection\n\n\n#Cidade\ndef adiciona_cidade(conn, nome):\n with conn.cursor() as cursor:\n try:\n cursor.execute('START TRANSACTION')\n cursor.execute('INSERT INTO cidade (Nome) VALUES (%s)', (nome))\n cursor.execute('COMMIT')\n\n except pymysql.err.IntegrityError as e:\n raise ValueError(f'Não posso inserir {nome} na tabela cidade')\n cursor.execute('COMMIT')\n\n\ndef acha_cidade(conn, id_cidade):\n with conn.cursor() as cursor:\n cursor.execute('SELECT * FROM cidade WHERE id_cidade = %s',\n (id_cidade))\n row_headers = [x[0] for x in cursor.description]\n res = cursor.fetchone()\n dict_user = {}\n if res:\n assa = dict(zip(row_headers, res))\n return assa\n else:\n return None\n\n\ndef muda_nome_cidade(conn, id, novo_nome):\n with conn.cursor() as cursor:\n try:\n cursor.execute(\"START TRANSACTION\")\n cursor.execute('UPDATE cidade SET Nome=%s where id_cidade=%s',\n (novo_nome, id))\n cursor.execute(\"COMMIT\")\n except pymysql.err.IntegrityError as e:\n cursor.execute(\"ROLLBACK\")\n raise ValueError(\n f'Não posso alterar nome do id {id} para {novo_nome} na tabela perigo'\n )\n\n\ndef remove_cidade(conn, id):\n with conn.cursor() as cursor:\n try:\n cursor.execute(\"START TRANSACTION\")\n cursor.execute('DELETE FROM cidade WHERE id_cidade=%s', (id))\n cursor.execute(\"COMMIT\")\n except Exception as e:\n cursor.execute(\"ROLLBACK\")\n print(e)\n\n\ndef lista_cidade(conn):\n with conn.cursor() as cursor:\n cursor.execute('SELECT * from cidade')\n res = cursor.fetchall()\n dict_users = {}\n for i in res:\n dict_users[i[0]] = i[1]\n\n return dict_users\n\n\n# Usuario\ndef adiciona_usuario(conn, nome, email, id_cidade):\n with conn.cursor() as cursor:\n try:\n cursor.execute(\"START TRANSACTION\")\n cursor.execute('CALL add_user (%s,%s,%s)' ,\n (nome, email, id_cidade))\n cursor.execute(\"COMMIT\")\n except pymysql.err.IntegrityError as e:\n cursor.execute(\"COMMIT\")\n raise ValueError(f'Não posso inserir na tabela usuario')\n\n\ndef acha_usuario(conn, id_usuario):\n with conn.cursor() as cursor:\n cursor.execute('SELECT * FROM usuario WHERE id_usuario = %s',\n (id_usuario))\n\n row_headers = [x[0] for x in cursor.description]\n res = cursor.fetchone()\n dict_user = {}\n assa = dict(zip(row_headers, res))\n if res:\n return assa\n else:\n return None\n\n\ndef muda_dados_usuario(conn, id, novo_nome, novo_email, nova_cidade, ativo):\n with conn.cursor() as cursor:\n try:\n if (novo_nome != None):\n cursor.execute(\"START TRANSACTION\")\n cursor.execute(\n 'UPDATE usuario SET Nome=%s where id_usuario=%s',\n (novo_nome, id))\n cursor.execute(\"COMMIT\")\n\n if (novo_email != None):\n cursor.execute(\"START TRANSACTION\")\n cursor.execute(\n 'UPDATE usuario SET Email=%s where id_usuario=%s',\n (novo_email, id))\n cursor.execute(\"COMMIT\")\n\n if (nova_cidade != None):\n cursor.execute(\"START TRANSACTION\")\n cursor.execute(\n 'UPDATE usuario SET id_cidade=\"%s\" where id_usuario=%s',\n (nova_cidade, id))\n cursor.execute(\"COMMIT\")\n\n if (ativo != None):\n cursor.execute(\"START TRANSACTION\")\n cursor.execute(\n 'UPDATE usuario SET ativo=%s where id_usuario=%s',\n (ativo, id))\n cursor.execute(\"COMMIT\")\n except pymysql.err.IntegrityError as e:\n cursor.execute(\"ROLLBACK\")\n raise ValueError(\n f'Não posso alterar nome do id {id} para {novo_nome} na tabela usuario'\n )\n\n\ndef remove_usuario(conn, id):\n with conn.cursor() as cursor:\n cursor.execute('DELETE FROM usuario WHERE id_usuario=%s', (id))\n\n\ndef lista_usuario(conn):\n with conn.cursor() as cursor:\n cursor.execute('SELECT id_usuario,Nome from usuario')\n res = cursor.fetchall()\n dict_users = {}\n for i in res:\n dict_users[i[0]] = i[1]\n\n return dict_users\n\n\n#Passaros\ndef adiciona_passaro(conn, nome):\n with conn.cursor() as cursor:\n try:\n cursor.execute(\"START TRANSACTION\")\n cursor.execute('INSERT INTO passaro (Nome) VALUES (%s)', (nome))\n cursor.execute(\"COMMIT\")\n except pymysql.err.IntegrityError as e:\n raise ValueError(f'Não posso inserir {nome} na tabela passaro')\n cursor.execute(\"ROLLBACK\")\n\n\ndef acha_passaro(conn, nome):\n with conn.cursor() as cursor:\n cursor.execute('SELECT * FROM passaro WHERE id_passaro = %s', (nome))\n row_headers = [x[0] for x in cursor.description]\n res = cursor.fetchone()\n dict_user = {}\n if res:\n assa = dict(zip(row_headers, res))\n return assa\n else:\n return None\n\n\ndef muda_nome_passaro(conn, id, novo_nome):\n with conn.cursor() as cursor:\n try:\n cursor.execute(\"START TRANSACTION\")\n cursor.execute('UPDATE passaro SET Nome=%s where id_passaro=%s',\n (novo_nome, id))\n cursor.execute(\"COMMIT\")\n except pymysql.err.IntegrityError as e:\n raise ValueError(\n f'Não posso alterar nome do id {id} para {novo_nome} na tabela passaro'\n )\n cursor.execute(\"ROLLBACK\")\n\n\ndef remove_passaro(conn, id):\n with conn.cursor() as cursor:\n cursor.execute(\"START TRANSACTION\")\n cursor.execute('DELETE FROM passaro WHERE id_passaro=%s', (id))\n cursor.execute(\"COMMIT\")\n\n\ndef lista_passaro(conn):\n with conn.cursor() as cursor:\n cursor.execute('SELECT * from passaro')\n res = cursor.fetchall()\n dict_users = {}\n for i in res:\n dict_users[i[0]] = i[1]\n return dict_users\n\n\n#POST\ndef adiciona_post(conn, titulo, imagem, texto, creator_id):\n with conn.cursor() as cursor:\n a = \"o\"\n cursor.execute(\n \"select id_post from post ORDER BY id_post DESC LIMIT 1\")\n rs = cursor.fetchone()\n\n if rs:\n print(rs[0])\n rs = rs[0]\n else:\n rs = 0\n cursor.execute('START TRANSACTION')\n try:\n cursor.execute('CALL add_post(\"%s\",\"%s\",\"%s\",%d)' %\n (titulo, imagem, texto, creator_id))\n cursor.execute('COMMIT')\n cursor.execute('START TRANSACTION')\n for ww in texto.split():\n if (ww[0] == \"#\"):\n cursor.execute('CALL tag_bird(%d,%d)' %\n (int(ww[1:]), rs + 1))\n elif (ww[0] == \"@\"):\n cursor.execute('CALL tag_user(%d,%d)' %\n (int(ww[1:]), rs + 1))\n cursor.execute('COMMIT')\n\n return True\n except Exception as e:\n print(e)\n\n cursor.execute('ROLLBACK')\n raise ValueError(a)\n\n\ndef acha_post(conn, id_post):\n with conn.cursor() as cursor:\n cursor.execute('SELECT * FROM post WHERE id_post = %s', (id_post))\n row_headers = [x[0] for x in cursor.description]\n res = cursor.fetchone()\n dict_user = {}\n if res:\n assa = dict(zip(row_headers, res))\n return assa\n else:\n return None\n\n\ndef muda_dados_post(conn,\n id,\n novo_titulo=None,\n nova_imagem=None,\n novo_texto=None,\n ativo=None):\n with conn.cursor() as cursor:\n cursor.execute(\"START TRANSACTION\")\n try:\n if (novo_titulo != None):\n cursor.execute('UPDATE post SET Titulo=%s where id_post=%s',\n (novo_titulo, id))\n\n if (nova_imagem != None):\n cursor.execute('UPDATE post SET Imagem=%s where id_post=%s',\n (nova_imagem, id))\n\n if (novo_texto != None):\n apaga_referencias_de_um_post(conn, id)\n cursor.execute('UPDATE post SET Texto=%s where id_post=%s',\n (novo_texto, id))\n\n for ww in novo_texto.split():\n if (ww[0] == \"#\"):\n cursor.execute('CALL tag_bird(%d,%d)' %\n (int(ww[1:]), id))\n elif (ww[0] == \"@\"):\n cursor.execute('CALL tag_user(%d,%d)' %\n (int(ww[1:]), id))\n\n if (ativo != None):\n cursor.execute('UPDATE post SET ativo=%s where id_post=%s',\n (ativo, id))\n cursor.execute(\"COMMIT\")\n except pymysql.err.IntegrityError as e:\n cursor.execute(\"ROLLBACK\")\n raise ValueError(\n f'Não posso alterar nome do id {id} para {novo_nome} na tabela usuario'\n )\n\n\ndef remove_post(conn, id):\n with conn.cursor() as cursor:\n cursor.execute('START TRANSACTION')\n cursor.execute('UPDATE post SET ativo=0 WHERE id_post=%s', (id))\n cursor.execute('COMMIT')\n\n\ndef lista_post(conn):\n with conn.cursor() as cursor:\n cursor.execute('SELECT * from post WHERE ativo = 1')\n res = cursor.fetchall()\n dict_users = {}\n for i in res:\n dict_users[i[0]] = i[1]\n return dict_users\n\n\ndef lista_post_usuario(conn, id_usuario):\n with conn.cursor() as cursor:\n cursor.execute(\n 'SELECT * from post WHERE ativo = 1 AND id_usuario=%s ORDER BY id_post DESC',\n (id_usuario))\n res = cursor.fetchall()\n dict_users = {}\n for i in res:\n dict_users[i[0]] = i[1]\n return dict_users\n\n\ndef visu_post(conn, id_usuario, id_post, OS, BROWSER, IP, horario=None):\n with conn.cursor() as cursor:\n try:\n a = 0\n cursor.execute(\"SELECT id_browser from browser WHERE Nome=(%s)\",\n (BROWSER))\n res = cursor.fetchone()\n if res:\n browser_id = res[0]\n else:\n cursor.execute(\"START TRANSACTION\")\n cursor.execute(\"INSERT INTO browser (Nome) VALUES (%s)\",\n (BROWSER))\n cursor.execute(\"COMMIT\")\n cursor.execute(\n \"SELECT id_browser from browser WHERE Nome=(%s)\",\n (BROWSER))\n res = cursor.fetchone()[0]\n browser_id = res\n\n cursor.execute(\"SELECT id_OS from OS WHERE Nome=(%s)\", (OS))\n res = cursor.fetchone()\n if res:\n os_id = res[0]\n else:\n cursor.execute(\"START TRANSACTION\")\n cursor.execute(\"INSERT INTO OS (Nome) VALUES (%s)\", (OS))\n cursor.execute(\"COMMIT\")\n cursor.execute(\"SELECT id_OS from OS WHERE Nome=(%s)\", (OS))\n res = cursor.fetchone()[0]\n os_id = res\n\n cursor.execute(\"START TRANSACTION\")\n a = 1\n cursor.execute(\n \"INSERT INTO viu_post (id_usuario,id_post,id_OS,id_browser,IP) VALUES (%d,%d,%d,%d,%s)\"\n % (int(id_usuario), int(id_post), int(os_id), int(browser_id),\n IP))\n a = 2\n cursor.execute(\"COMMIT\")\n\n except Exception as e:\n print(e)\n cursor.execute(\"ROLLBACK\")\n raise ValueError(\"ERRO\", e, \" \\nJUMP: \", a)\n\n\n#REFERENCIAS DO POST\n\n\ndef apaga_referencias_de_um_post(conn, id_post):\n with conn.cursor() as cursor:\n cursor.execute(\"START TRANSACTION\")\n cursor.execute('UPDATE menciona_passaro SET ativo = 0 WHERE id_post=%s',\n (id_post))\n cursor.execute('UPDATE menciona_usuario SET ativo = 0 WHERE id_post=%s',\n (id_post))\n cursor.execute(\"COMMIT\")\n\n#PREFERENCIA\n\ndef adiciona_preferencia(conn,id_usuario,id_passaro):\n with conn.cursor() as cursor:\n try:\n cursor.execute(\"START TRANSACTION\")\n cursor.execute(\"CALL add_preference (%d,%d)\"%(id_usuario,id_passaro))\n cursor.execute(\"COMMIT\")\n except Exception as e:\n cursor.execute(\"ROLLBACK\")\n print(e)\n\n#JOINHAS\n\ndef adiciona_joinhas(conn,id_post,id_usuario,joinha):\n with conn.cursor() as cursor:\n try:\n cursor.execute(\"START TRANSACTION\")\n cursor.execute(\"CALL add_opinion (%d,%d,%d)\"%(id_usuario,id_post,joinha))\n cursor.execute(\"COMMIT\")\n except Exception as e:\n cursor.execute(\"ROLLBACK\")\n print(e)\n\ndef altera_joinhas(conn,id_post,id_usuario,joinha):\n with conn.cursor() as cursor:\n try:\n cursor.execute(\"START TRANSACTION\")\n cursor.execute(\"UPDATE joinha SET joinha = %d WHERE id_post = %d AND id_usuario = %d\"%(joinha,id_post,id_usuario))\n cursor.execute(\"COMMIT\")\n except Exception as e:\n cursor.execute(\"ROLLBACK\")\n print(e)\n\ndef apaga_joinhas(conn,id_post,id_usuario,joinha=None):\n with conn.cursor() as cursor:\n try:\n cursor.execute(\"START TRANSACTION\")\n cursor.execute(\"DELETE FROM joinha WHERE id_post=%s and id_usuario\" % (id_post,id_usuario))\n cursor.execute(\"COMMIT\")\n except Exception as e:\n cursor.execute(\"ROLLBACK\")\n print(e)\n\n#popular de cidade\ndef popular_cidade(conn,id_cidade):\n with conn.cursor() as cursor:\n cursor.execute(\"SELECT id_usuario FROM usuario WHERE id_cidade = %d\" % (id_cidade))\n rs = cursor.fetchall()\n id_usuario = 0\n valor_usuario = 0\n for ss in rs:\n cursor.execute(\"SELECT SUM(joinha.joinha) FROM post INNER JOIN joinha ON joinha.id_post = post.id_post WHERE post.id_usuario = %d\" % (ss[0]))\n res = cursor.fetchone()\n if(res[0]):\n if(res[0] > valor_usuario):\n id_usuario = ss[0]\n return id_usuario\n\n#usuario_referencia_usuario\ndef usuario_referencia_usuario(conn,id_usuario):\n with conn.cursor() as cursor:\n cursor.execute(\"SELECT post.id_usuario FROM post INNER JOIN menciona_usuario ON post.id_post = menciona_usuario.id_post WHERE menciona_usuario.id_usuario = %d\" % (id_usuario))\n res = cursor.fetchall()\n deict = {}\n for i in range(len(res)):\n deict[i] = {\"usuario\" : res[i][0]}\n return deict\n\ndef passaro_imagem(conn):\n with conn.cursor() as cursor:\n cursor.execute(\"SELECT post.Imagem,id_passaro FROM post INNER JOIN menciona_passaro ON post.id_post = menciona_passaro.id_post\")\n res = cursor.fetchall()\n \n \n return res\n\n","sub_path":"Fase2/Testes/projeto.py","file_name":"projeto.py","file_ext":"py","file_size_in_byte":15879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"120153755","text":"from tkinter import *\nfrom Views import AddView\n\ndef main(window = None):\n if window:\n window.withdraw()\n # Crea la Ventana con su titulo\n mainWindow = Tk()\n mainWindow.title('Company Manager')\n mainWindow.geometry('200x200')\n mainWindow.configure(background='#0B4AA9')\n\n # Botones para las funciones principales\n buttonAdd = Button(mainWindow, text = 'Añadir Empleado', command = lambda : AddView.type(mainWindow))\n buttonShow = Button(mainWindow, text = 'Mostrar Empleados')\n\n buttonAdd.pack()\n buttonShow.pack()\n\n mainWindow.mainloop()\n","sub_path":"CompanyManager/Views/MainView.py","file_name":"MainView.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"186604202","text":"import json\nfrom app.service.http_client import http_client\n\n\nservice_name = 'umm'\n\n\ndef create_task(task, jwt):\n body = {\n 'action': 'create_task',\n 'args': {\n 'task': task.__dict__,\n },\n }\n return http_client(service_name, body=body, jwt=jwt)\n\n\ndef update_task(task, jwt):\n body = {\n 'action': 'update_task',\n 'args': {\n 'task': task.__dict__,\n },\n }\n return http_client(service_name, body=body, jwt=jwt)\n\n\ndef create_task_step(task_step, jwt):\n body = {\n 'action': 'create_task_step',\n 'args': {\n 'task_step': task_step.__dict__,\n },\n }\n return http_client(service_name, body=body, jwt=jwt)\n\n\ndef delete_task_steps(task_uuid, start_progress, end_progress, jwt):\n body = {\n 'action': 'delete_task_steps',\n 'args': {\n 'task_uuid': task_uuid,\n 'start_progress': start_progress,\n 'end_progress': end_progress,\n },\n }\n return http_client(service_name, body=body, jwt=jwt)\n\n\ndef get_solutions(uuid, jwt=None):\n body = {\n 'action': 'get_solutions',\n 'args': {\n 'uuid': uuid,\n },\n }\n return http_client(service_name, body=body, jwt=jwt)\n\n\ndef create_solution(solution, jwt):\n return http_client('post', service_name, '/api/solutions', body=json.dumps(solution.__dict__), jwt=jwt)\n\n\ndef delete_solution(id, jwt):\n return http_client('delete', service_name, '/api/solutions/{}'.format(id), jwt=jwt)\n\n\ndef create_artifact(artifact, jwt):\n return http_client('post', service_name, '/api/artifacts', body=json.dumps(artifact.__dict__), jwt=jwt)\n\n\ndef get_artifacts(solution_uuid, type, jwt=None):\n body = {\n 'action': 'get_artifacts',\n 'args': {\n 'solutionUuid': solution_uuid,\n 'type': type,\n },\n }\n return http_client(service_name, body=body, jwt=jwt)\n\n\ndef delete_artifact(id, jwt):\n return http_client('delete', service_name, '/api/artifacts/{}'.format(id), jwt=jwt)\n\n\ndef create_document(document, jwt):\n return http_client('post', service_name, '/api/documents', body=json.dumps(document.__dict__), jwt=jwt)\n\n\ndef get_document(id, jwt=None):\n return http_client('get', service_name, '/api/documents/{}'.format(id), jwt=jwt)\n\n\ndef delete_document(id, jwt):\n return http_client('delete', service_name, '/api/documents/{}'.format(id), jwt=jwt)\n\n\ndef create_deployment(deployment, jwt):\n body = {\n 'action': 'create_deployment',\n 'args': {\n 'deployment': deployment.__dict__,\n },\n }\n return http_client(service_name, body=body, jwt=jwt)\n\n\ndef update_deployment_status(deploymentId, status, jwt):\n body = {\n 'action': 'update_deployment_status',\n 'args': {\n 'deploymentId': deploymentId,\n 'status': status,\n },\n }\n return http_client(service_name, body=body, jwt=jwt)\n","sub_path":"umd-python/app/service/umm_client.py","file_name":"umm_client.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"411879065","text":"\nimport re\n\nclass MetamapApi:\n def __init__(self,question_body,question_type,mm):\n self.question_body=[]\n self.question_body.append(question_body)\n self.mm = mm\n self.words_semantics = dict()\n self.question_type = question_type\n self.semantics=[]\n\n def start_api(self):\n if self.question_type == 'factoid' or self.question_type == 'list':\n concepts, error = self.mm.extract_concepts(self.question_body)\n\n for concept in concepts:\n details = concept[6].split('-')\n semantics = concept[5].split(',')\n word_semantics=[]\n for semantic in semantics:\n semantic = semantic[1:len(semantic)-1]\n word_semantics.append(semantic)\n details = details[1:]\n for detail in details:\n character = re.findall('\\\"', detail)\n if len(character) > 1:\n word = detail[1:len(detail) - 1].lower()\n self.words_semantics[word] = word_semantics\n elif self.question_type == 'summary' or self.question_type == 'ideal_answer':\n concepts, error = self.mm.extract_concepts(self.question_body)\n\n for concept in concepts:\n semantics = concept[5].split(',')\n for semantic in semantics:\n semantic = semantic[1:len(semantic) - 1]\n self.semantics.append(semantic)\n\n\n def get_semantics(self):\n if self.question_type == 'ideal_answer':\n return self.semantics\n else:\n return self.words_semantics\n\n","sub_path":"utilities/metamap_api.py","file_name":"metamap_api.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"639593650","text":"import matplotlib\nmatplotlib.use(\"Qt4Agg\")\n\nfrom PyQt4 import QtGui, QtCore, uic\nimport matplotlib.pyplot as plt\n\nimport AW.UI.ui_cc as ui_cc\nimport json\nfrom apscheduler.schedulers.background import BackgroundScheduler\n\nimport AW.AWCymbiotesAdd as AWCymbiotesAdd\nimport AW.AWLogsSnapshot as AWLogsSnapshot\nimport api_get\nimport datetime\n\n\nSENSOR_TEMP_DICT = {\n \"Sensors\":[\n {\"Header\": \"Header 1\", \"Values\": [\"0\", \"1\", \"2\", \"3\", \"4\"], \"Unit\": \"Unit 1\"},\n {\"Header\": \"Header 2 Very Long Edition\", \"Values\": [\"0\", \"1\", \"2\", \"3\", \"4\"], \"Unit\": \"Unit 2 Long\"},\n {\"Header\": \"Header 3\", \"Values\": [\"0\", \"1\", \"2\", \"3\", \"4\"], \"Unit\": \"Unit 3\"},\n {\"Header\": \"Header 4\", \"Values\": [\"0\", \"1\", \"2\", \"3\", \"4\"], \"Unit\": \"Unit 4\"},\n {\"Header\": \"Header 5\", \"Values\": [\"0\", \"1\", \"2\", \"3\", \"4\"], \"Unit\": \"Unit 5\"}]\n }\n\n#####################################################################\n# Main Application Window\n#####################################################################\nclass MainForm(QtGui.QMainWindow, ui_cc.Ui_MainWindow):\n #######################################################\n # ctor\n #######################################################\n def __init__(self, parent=None):\n super(MainForm, self).__init__(parent)\n self.setupUi(self)\n \n # Cymbiotes\n self.pbCymbiotesRemove.clicked.connect(self.cymbiotesRemove)\n self.pbCymbiotesAdd.clicked.connect(self.cymbiotesAdd)\n \n self.cymbiotesDict = {\"Cymbiotes\": []}\n self.cymbiotesListModel = QtGui.QStandardItemModel()\n self.lvCymbiotes.setModel(self.cymbiotesListModel)\n self.lvCymbiotes.selectionModel().selectionChanged.connect(self.cymbioteSelected)\n self.lvCymbiotes.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)\n \n self.cymbiotesFill()\n self.currentCymbiote = {}\n \n \n \n # Logs\n self.logsDict = {\"Logs\": []}\n self.logsListModel = QtGui.QStandardItemModel()\n self.lvLogs.setModel(self.logsListModel)\n self.lvLogs.selectionModel().selectionChanged.connect(self.logSelected)\n self.lvLogs.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)\n \n \n # Snapshot\n self.pbSnapshot.clicked.connect(self.viewSnapshot)\n \n \n \n # Sensors\n self.sensorsDict = {}\n self.sensorsListModel = QtGui.QStandardItemModel()\n self.lvSensors.setModel(self.sensorsListModel)\n self.lvSensors.selectionModel().selectionChanged.connect(self.sensorSelected)\n self.lvSensors.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)\n \n self.sensorsValuesListModel = QtGui.QStandardItemModel()\n self.lvSensorsValues.setModel(self.sensorsValuesListModel) \n self.lvSensorsValues.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)\n \n # update sensor values scheduler\n self.sensorValueSched = BackgroundScheduler()\n self.sensorValueSched.add_job(self.sensorValuesUpdate, \"interval\", seconds = 1)\n \n self.selectedSensorRow = -1\n self.sensorGraphSched = BackgroundScheduler()\n self.sensorGraphSched.add_job(self.sensorPlotUpdate, \"interval\", seconds = 1)\n\n #######################################################\n # Redraw the list of Cymbiotes in the listview\n #######################################################\n def cymbiotesFill(self):\n # get cymbiotes\n fr = open(\"Data/cymbiotes.json\", \"r+\")\n try:\n self.cymbiotesDict = json.loads(fr.read())\n except:\n self.cymbiotesDict = {\"Cymbiotes\": []}\n fr.close()\n \n self.cymbiotesListModel.clear()\n # fill list\n for cymbiote in self.cymbiotesDict[\"Cymbiotes\"]:\n item = QtGui.QStandardItem(\"{0} | {1}:{2}\".format(cymbiote[\"Name\"], cymbiote[\"IPADDR\"], cymbiote[\"Port\"]))\n self.cymbiotesListModel.appendRow(item)\n \n #######################################################\n # Removes selected Cymbiote from list of monitored Cymbiotes\n #######################################################\n def cymbiotesRemove(self):\n # find selected row and remove from list\n if(self.lvCymbiotes.selectedIndexes() != []):\n row = self.lvCymbiotes.selectedIndexes()[0].row() \n self.cymbiotesDict[\"Cymbiotes\"].pop(row)\n \n # change file contents\n fw = open(\"Data/cymbiotes.json\", \"w+\")\n fw.write(json.dumps(self.cymbiotesDict))\n fw.close()\n \n # reset list and refill\n self.cymbiotesFill()\n \n #######################################################\n # Add Cymbiote to list of monitored Cymbiotes\n # Will pull up dialog window to collect input from user\n #######################################################\n def cymbiotesAdd(self):\n dform = AWCymbiotesAdd.MainForm()\n newCymbiote = dform.add()\n if newCymbiote:\n self.cymbiotesDict[\"Cymbiotes\"].append(newCymbiote)\n \n # change file contents\n fw = open(\"Data/cymbiotes.json\", \"w+\")\n fw.write(json.dumps(self.cymbiotesDict))\n fw.close()\n \n # reset UI and refill\n self.cymbiotesFill()\n \n #######################################################\n # Fills form with info on selected Cymbiote\n # Triggered when new cymbiote selected\n #######################################################\n def cymbioteSelected(self):\n if(self.lvCymbiotes.selectedIndexes() != []):\n row = self.lvCymbiotes.selectedIndexes()[0].row()\n self.currentCymbiote = self.cymbiotesDict[\"Cymbiotes\"][row]\n self.logsFill()\n self.sensorsFill()\n \n # start thread for updating sensor values\n self.sensorValueSched.start()\n else:\n self.currentCymbiote = {}\n \n # end thread for updating sensor values\n self.sensorValueSched.stop()\n \n\n \n \n \n \n #######################################################\n # Fills the lvLogs with datetimes of when logs happened \n #######################################################\n def logsFill(self):\n try:\n self.logsDict = api_get.api_get(self.currentCymbiote[\"IPADDR\"], self.currentCymbiote[\"Port\"],\"LOGS\")\n except:\n self.logsDict = {\"Logs\": []}\n \n self.logsListModel.clear()\n for log in self.logsDict[\"Logs\"]:\n convertedDate = datetime.datetime.strptime(log[\"Datetime\"], \"%Y%m%d%H%M%S\")\n convertedDate = convertedDate.strftime(\"%m/%d/%Y %H:%M:%S\")\n item = QtGui.QStandardItem(convertedDate)\n self.logsListModel.appendRow(item)\n \n #######################################################\n # Fill log text view with log, upon selection in the \n # list view\n #######################################################\n def logSelected(self):\n if(self.lvLogs.selectedIndexes() != []):\n row = self.lvLogs.selectedIndexes()[0].row()\n self.teLogs.setPlainText(\"{0}\".format(self.logsDict[\"Logs\"][row][\"Files\"]))\n else:\n self.teLogs.setPlainText(\"\")\n\n\n\n\n\n \n #######################################################\n # Bring up Snapshot window\n #######################################################\n def viewSnapshot(self):\n if(self.lvLogs.selectedIndexes() != []):\n row = self.lvLogs.selectedIndexes()[0].row()\n \n # get snapshot from API\n logdt = self.logsDict[\"Logs\"][row][\"Datetime\"]\n \n try:\n snapshotDict = api_get.api_get(self.currentCymbiote[\"IPADDR\"], self.currentCymbiote[\"Port\"], \"SNAPSHOT\", logdt)\n except:\n snapshotDict = {\"Files\": {}, \"Sensorshld\": {}}\n \n dform = AWLogsSnapshot.MainForm() \n dform.fillUI(snapshotDict)\n \n \n \n \n \n #######################################################\n # Fills the sensor list. Sensors only. Triggered when \n # a Cymbiote is selected.\n #######################################################\n def sensorsFill(self):\n self.sensorsDict = api_get.api_get(self.currentCymbiote[\"IPADDR\"], self.currentCymbiote[\"Port\"], \"SENSORCSV\")\n \n if self.sensorsDict == {}:\n self.sensorsDict = SENSOR_TEMP_DICT\n \n self.sensorsListModel.clear()\n for sensorHeader in self.sensorsDict[\"Sensors\"]:\n item = QtGui.QStandardItem(\"{0}\".format(sensorHeader[\"Header\"]))\n self.sensorsListModel.appendRow(item)\n \n #######################################################\n # Fills the sensor values list. Values only. Called \n # every 1 seconds\n #######################################################\n def sensorValuesUpdate(self):\n self.sensorsDict = api_get.api_get(self.currentCymbiote[\"IPADDR\"], self.currentCymbiote[\"Port\"], \"SENSORCSV\")\n if self.sensorsDict == {}:\n self.sensorsDict = SENSOR_TEMP_DICT\n \n self.sensorsValuesListModel.clear()\n for sensorHeader in self.sensorsDict[\"Sensors\"]:\n item = QtGui.QStandardItem(\"{0:<7} {1}\".format(sensorHeader[\"Values\"][0], sensorHeader[\"Unit\"]))\n self.sensorsValuesListModel.appendRow(item)\n \n #######################################################\n # Triggered when sensor selected. Will draw a graph\n #######################################################\n def sensorSelected(self):\n if(self.lvSensors.selectedIndexes() != []):\n self.selectedSensorRow = self.lvSensors.selectedIndexes()[0].row()\n self.sensorGraphSched.start()\n else:\n self.selectedSensorRow = -1\n self.sensorGraphSched.stop()\n \n #######################################################\n # Updates plot with data\n #######################################################\n def sensorPlotUpdate(self):\n self.canvasSensor.figure.clear()\n if self.sensorsDict != {} and self.selectedSensorRow != -1:\n data = []\n tempData = self.sensorsDict[\"Sensors\"][self.selectedSensorRow][\"Values\"]\n try:\n for val in tempData:\n data.append(float(val))\n except:\n data = [10, 9, 8, 7, 6, 5]\n ax = self.canvasSensor.figure.add_subplot(111)\n self.canvasSensor.figure.suptitle(self.sensorsDict[\"Sensors\"][self.selectedSensorRow][\"Header\"], name = \"Courier\", weight = \"bold\", fontsize=14)\n ax.set_xlabel(\"Seconds\", name = \"Courier\", fontsize=14)\n ax.set_ylabel(self.sensorsDict[\"Sensors\"][self.selectedSensorRow][\"Unit\"], name = \"Courier\", fontsize=14)\n else:\n data = [1, 2, 3, 4, 5, 10, 3, 2]\n ax = self.canvasSensor.figure.add_subplot(111)\n self.canvasSensor.figure.suptitle(\"ERROR\")\n ax.set_xlabel(\"X Label\")\n ax.set_ylabel(\"Y Label\")\n \n ax.plot(data, \"*-\")\n self.canvasSensor.draw()","sub_path":"pyqt_gui/AW/AWCymbioteController.py","file_name":"AWCymbioteController.py","file_ext":"py","file_size_in_byte":11457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"12841543","text":"#Найти сумму чисел, вводимых с клавиатуры.\n#Количество вводимых чисел заранее неизвестно.\n#Окончание ввода - слово “Стоп”.\n#При ошибке ввода попросить повторить ввод числа.\n\n\ndef f(x):\n try:\n int(x)\n return True\n except ValueError:\n return False\n\ntotal = 0\n\nwhile True:\n value = input('Enter here: ')\n\n if value.lower() == 'stop':\n print(f'total: {total}')\n break\n elif f(value):\n total += int(value)\n else:\n print('Error')\n\n\n\n\n","sub_path":"lesson_7/end_count_sum.py","file_name":"end_count_sum.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"398789667","text":"# Написать класс Animal и Human,сделать так, чтобы некоторые животные \n# были опасны для человека (хищники, ядовитые).\n# Другие - нет. За что будет отвечать метод is_dangerous(animal)\n\nclass Animal():\n\tdef __init__(self, animal_name, anymal_type):\n\t\tself.animal_type = anymal_type\n\t\tself.animal_name = animal_name\n\n\t\n\nclass Human():\n\tdangerous_animals = ['poisonous', 'predator']\n\n\tdef is_dangerous(self, animal):\n\t\treturn animal.animal_type in self.dangerous_animals\n\n\n\nbear = Animal('Bear', 'predator')\nsnake = Animal('Snake', 'poisonous')\nspider = Animal('Spider', 'poisonous')\nbird = Animal('Bird', 'bird')\nfish = Animal('Fish', 'fish')\nanimals = [bear, bird, fish, snake, spider]\n\nh = Human()\n\nfor index, items in enumerate(animals):\n\tprint(index, items.animal_name)\n\nwhile True:\n try:\n n = int(input('Choose number of animal: '))\n if n not in range(len(animals)): \n raise ValueError('It is out of range. Buy!')\n except ValueError as e:\n print(e)\n break\n \n print('\\nYou choose: {}'.format(animals[n].animal_name))\n \n if h.is_dangerous(animals[n]):\n print('This animal is DANGEROUS for you.')\n else:\n print('This animal is NOT dangerous for you :-)')\n","sub_path":"hw3 Class Animal and Human.py","file_name":"hw3 Class Animal and Human.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"153979210","text":"from typing import Tuple as Tup\nimport scipy\nfrom scipy import stats\nfrom statsmodels.nonparametric.kde import KDEUnivariate\nimport numpy as np\nimport pandas as pd\nfrom dscience.core.exceptions import LengthMismatchError, NullValueError\n\n\nclass StatTools:\n @classmethod\n def kde(\n cls, a: np.array, kernel: str = \"gau\", bw: str = \"normal_reference\"\n ) -> Tup[np.array, np.array]:\n \"\"\"\n Calculates univariate KDE with statsmodel.\n (This function turned into a thin wrapper around statsmodel.)\n Note that scipy uses statsmodel for KDE if it's available. Otherwise, it silently falls back to scipy. That's clearly hazardous.\n \"\"\"\n if isinstance(a, pd.Series):\n a = a.values\n dens = KDEUnivariate(a)\n dens.fit(kernel=kernel, bw=bw)\n return dens.support, dens.density\n\n @classmethod\n def ttest_pval(cls, z: pd.Series, a: str, b: str) -> float:\n \"\"\"Calculates a p-value from a t-test between labels a and b.\"\"\"\n s = pd.DataFrame(z)\n neg = s[s.index.get_level_values(\"name\") == a].values\n if len(neg) < 2:\n raise LengthMismatchError(\"Too few ({}) values for {}\".format(len(neg), a), minimum=2)\n pos = s[s.index.get_level_values(\"name\") == b].values\n if len(pos) < 2:\n raise LengthMismatchError(\"Too few ({}) values for {}\".format(len(pos), b), minimum=2)\n pval = scipy.stats.ttest_ind(pos, neg, equal_var=False).pvalue\n if isinstance(pval, float) and np.isnan(pval):\n raise NullValueError(\"NaN for {} and {}\".format(a, b))\n else:\n return pval[0]\n\n\n__all__ = [\"StatTools\"]\n","sub_path":"dscience/calc/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"541474142","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 24 22:36:08 2019\n\n@author: looly\n\"\"\"\nimport tensorflow as tf\n\ntf.config.gpu.set_per_process_memory_fraction(0.3)\ntf.config.gpu.set_per_process_memory_growth(True)\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import MinMaxScaler\n\ndef data_loader():\n # load csv files:\n dataset_train = pd.read_csv('/Lab1/Lab5/train_data_stock.csv')\n dataset_val = pd.read_csv('/Lab1/Lab5/val_data_stock.csv')\n\n # reverse data so that they go from oldest to newest:\n dataset_train = dataset_train.iloc[::-1]\n dataset_val = dataset_val.iloc[::-1]\n\n # concatenate training and test datasets:\n dataset_total = pd.concat((dataset_train['Open'], dataset_val['Open']), axis=0) \n\n # select the values from the “Open” column as the variables to be predicted:\n training_set = dataset_train.iloc[:, 1:2].values\n val_set = dataset_val.iloc[:, 1:2].values\n\n #normalize the data from 0 to 1\n sc = MinMaxScaler(feature_range=(0, 1))\n training_set_scaled = sc.fit_transform(training_set)\n\n\n # split training data into T time steps:\n X_train = []\n y_train = []\n T = 60\n\n for i in range(T, len(training_set)):\n X_train.append(training_set_scaled[i-T:i, 0])\n y_train.append(training_set_scaled[i, 0])\n X_train, y_train = np.array(X_train), np.array(y_train)\n\n # normalize the validation set according to the normalization applied to the training set:\n inputs = dataset_total[len(dataset_total) - len(dataset_val) - 60:].values\n inputs = inputs.reshape(-1, 1)\n inputs = sc.transform(inputs)\n\n # split validation data into T time steps:\n X_val = []\n for i in range(T, T + len(val_set)):\n X_val.append(inputs[i-T:i, 0])\n X_val = np.array(X_val)\n y_val = sc.transform(val_set)\n\n # reshape to 3D array (format needed by LSTMs -> number of samples,timesteps, input dimension)\n X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))\n X_val = np.reshape(X_val, (X_val.shape[0], X_val.shape[1], 1))\n\n return X_train, y_train, X_val, y_val","sub_path":"Lab5/Data_Loader_Task1.py","file_name":"Data_Loader_Task1.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"193172859","text":"# 导入selenium的webdraver\nfrom selenium import webdriver\nimport time\n\n# driver = webdriver.PhantomJS()\ndriver = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true', '--ssl-protocol=TLSv1'])\n# 打开百度\ndriver.get('http://www.baidu.com/')\n\n# 找到搜索框\ndriver.find_element_by_id('kw').send_keys('美女')\n\n# 找到百度一下,点击一下\ndriver.find_element_by_id('su').click()\n\n\n# 截图\ntime.sleep(5)\ndriver.save_screenshot('meinv.png')\n\n# 关闭浏览器\ndriver.quit()","sub_path":"web_crawler/_15.selenium_click.py","file_name":"_15.selenium_click.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"443884106","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n# ----------------------------------------------------------------------------------------------------\n\n\"\"\"Grammars for the ContextFreeGrammarParser are built from production rules, corresponding to the Rule-class below.\nThis means that sentences can be generated (and auto-completed), according to this grammar.\nMoreover, sentences can be parsed according to the same rules.\n\nSee https://www.tutorialspoint.com/automata_theory/context_free_grammar_introduction.htm and\nhttps://en.wikipedia.org/wiki/Context-free_grammar for an introduction to context free grammars.\n\nIf there is a rule \"A -> one\", then that means that to generate something according to rule A, the generated sentence is\n\"one\"\nIn this example \"A\" is the lname. lname stands for left name, as it's on the left of the arrow.\nSentences are produced and parsed from left to right.\n\nThere can be multiple lines in the grammar definition file with the same lname, which simply add ways to produce/parse\nsentences for that lname.\n\nRules can refer to each other via their lname.\nIf a rule A defines a way to start a sentence and refers to B, that means the completion of rule A is one via rule B.\nFor example, the grammar:\nA -> go B\nB -> forward\nB -> backward\ncan generate the sentences \"go forward\" and \"go backward\". And thus parse these sentences as well.\n\nRules can also have variables that will be assigned to when a sentence is parsed.\nFor example, the line:\n\n VP[\"action\": A] -> V_PLACE[A]\n\nadds a rule for the lname VP, with a field called \"action\", which will be set to A.\nThe value for A is determined by a rule with lname V_PLACE, which will determine the value of A.\n\nThe rule\n\n V_PLACE[\"place\"] -> place | put\n\napplies when the text is \"place\" or \"put\".\nWhen that is the case, the rule applies and the text \"place\" is filled in for A.\nThat means when the text \"put\" is typed, the variable \"action\" will be assigned the value \"place\".\n\nThe whole grammar has an entry point, or root rule, from which all the other rules are referred.\nEach rule forms branch upon branch, together building a Tree.\n\nWhen a sentence is parsed, a Tree is built. While this happens, the variables are collected.\nWhen the Tree is completely parsed, the collected variables and their assignments are fetched from the Tree with the get_semantics-method.\nThis returns a string. However, this string represents a (nested) dictionary that maps a variable to a value.\n\nSemantics describe what a sentence means. In this case, it describes what action to perform and with what to perform it.\n\"\"\"\nimport random\nimport re\nimport yaml\nfrom yaml import MarkedYAMLError\nimport itertools\n\n\nclass Alternative:\n def __init__(self, values=[]):\n self.values = values\n\n def __repr__(self):\n return \"Alternative({})\".format(self.values)\n\n\nclass Sequence:\n def __init__(self, values=[]):\n self.values = values\n\n def __repr__(self):\n return \"Sequence({})\".format(self.values)\n\n\nclass Option:\n \"\"\"An option is a continuation of a sentence of where there are multiple ways to continue the sentence.\n These choices in an Option are called called conjuncts.\"\"\"\n\n def __init__(self, lsemantic=\"\", conjs=None):\n \"\"\"Constructor of an Option\n :param lsemantic the name of the semantics that the option is the continuation of. E.g. if the lsemantic is some action, this option might be the object to perform that action with.\n :param conjs the choices in this option\"\"\"\n self.lsemantic = lsemantic\n if conjs:\n self.conjuncts = conjs\n else:\n self.conjuncts = []\n\n def __repr__(self):\n return \"Option(lsemantic='{lsem}', conjs={c})\".format(lsem=self.lsemantic, c=self.conjuncts)\n\n def __eq__(self, other):\n if isinstance(other, Option):\n return self.lsemantic == other.lsemantic and self.conjuncts == other.conjuncts\n\n return False\n\n @staticmethod\n def from_cfg_def(option_definition, left_semantics):\n \"\"\"Parse text from the CFG definition into an Option and the choices it is composed of. \"\"\"\n opt_strs = option_definition.split(\"|\")\n\n for opt_str in opt_strs:\n opt_str = opt_str.strip()\n\n opt = Option(left_semantics)\n\n while opt_str:\n (rname, rsem, opt_str) = parse_next_atom(opt_str)\n is_variable = rname[0].isupper()\n opt.conjuncts += [Conjunct(rname, rsem, is_variable)]\n\n yield opt\n\n\n# ----------------------------------------------------------------------------------------------------\n\n\nclass Conjunct:\n \"\"\"\"A Conjunct is a placeholder in the parse-tree, which can be filled in by an Option or a word\"\"\"\n\n def __init__(self, name, rsemantic=\"\", is_variable=False):\n \"\"\":param name the word or variable\n :param rsemantic what option is the Conjunct part of\n :param is_variable is the conjunct variable or terminal?\"\"\"\n self.name = name\n self.rsemantic = rsemantic\n self.is_variable = is_variable\n\n def __repr__(self):\n return \"Conjunct(name='{name}', rsemantic='{r}', is_variable={v})\".format(name=self.name, r=self.rsemantic,\n v=self.is_variable)\n\n def __eq__(self, other):\n if isinstance(other, Conjunct):\n return self.name == other.name and \\\n self.rsemantic == other.rsemantic and \\\n self.is_variable == other.is_variable\n return False\n\n\n# ----------------------------------------------------------------------------------------------------\n\n\nclass Rule:\n def __init__(self, lname, options=None):\n self.lname = lname\n self.options = options if options else []\n\n def __repr__(self):\n return \"Rule(lname='{lname}', options={opts})\".format(lname=self.lname, opts=self.options)\n\n def __eq__(self, other):\n if isinstance(other, Rule):\n return self.lname == other.lname and self.options == other.options\n\n return False\n\n @staticmethod\n def from_cfg_def(s):\n tmp = s.split(\" -> \")\n if len(tmp) != 2:\n raise Exception(\"Invalid grammar, please use proper ' -> ' arrows\", tmp)\n\n (lname, lsem, outstr) = parse_next_atom(tmp[0].strip())\n\n rule = Rule(lname)\n\n rule.options = list(Option.from_cfg_def(tmp[1], lsem))\n\n return rule\n\n\n# ----------------------------------------------------------------------------------------------------\n\n\nclass Tree:\n def __init__(self, option):\n self.option = option\n self.subtrees = [None for c in self.option.conjuncts]\n self.parent = None\n self.parent_idx = 0\n\n def next(self, idx):\n if idx + 1 < len(self.option.conjuncts):\n return self, idx + 1\n else:\n if self.parent:\n return self.parent.next(self.parent_idx)\n else:\n return None, 0\n\n def add_subtree(self, idx, tree):\n tree.parent = self\n tree.parent_idx = idx\n self.subtrees[idx] = tree\n return tree\n\n def __repr__(self):\n # TODO: Make this print like a tree\n return str(zip(self.option.conjuncts, self.subtrees))\n\n\n# ----------------------------------------------------------------------------------------------------\n\n\ndef parse_next_atom(s):\n \"\"\"\n Returns (name, semantics, remaining_str)\n For example for \"VP[X, Y] foo bar\" it returns:\n (\"VP\", \"X, Y\", \"foo bar\")\n :param s:\n :return: Tuple with the rule's lname, the variables involved and the remaining text: (\"VP\", \"X, Y\", \"foo bar\")\n \"\"\"\n s = s.strip()\n\n for i in range(0, len(s)):\n c = s[i]\n if c == ' ':\n return s[:i], \"\", s[i:].strip()\n elif c == '[':\n j = s.find(\"]\", i)\n if j < 0:\n raise Exception\n return s[:i], s[i + 1:j], s[j + 1:].strip()\n\n return s, \"\", \"\"\n\n\n# ----------------------------------------------------------------------------------------------------\n\n\nclass GrammarParser:\n def __init__(self):\n self.rules = {}\n self.functions = {}\n\n @staticmethod\n def fromfile(filename):\n with open(filename) as f:\n string = f.read()\n return GrammarParser.fromstring(string)\n\n @staticmethod\n def fromstring(string):\n parser = GrammarParser()\n for line in string.replace(\";\", \"\\n\").split(\"\\n\"):\n line = line.strip()\n if line == \"\" or line[0] == '#':\n continue\n parser.add_rule(line)\n\n return parser\n\n def verify(self, target=None):\n if target is None:\n # Try whether all rules in the grammar are valid\n for r in self.rules:\n self.get_tree(r)\n else:\n self.get_tree(target)\n return True\n\n def add_rule(self, s):\n rule = Rule.from_cfg_def(s)\n\n # See if a rule with this lname already exists. If not, add it\n if rule.lname in self.rules:\n original_rule = self.rules[rule.lname]\n original_rule.options += rule.options\n else:\n self.rules[rule.lname] = rule\n\n def set_function(self, name, func):\n self.functions[name] = func\n\n def get_semantics(self, tree):\n \"\"\"Get the semantics of a tree.\n This means that variables are unified with their values, which may be recursively gotten from the tree's subtrees. \"\"\"\n semantics = tree.option.lsemantic\n for i in range(0, len(tree.subtrees)):\n conj = tree.option.conjuncts[i]\n subtree = tree.subtrees[i]\n\n if subtree:\n child_semantics = self.get_semantics(subtree)\n semantics = semantics.replace(conj.rsemantic, child_semantics)\n\n return semantics\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n def parse(self, target, words, debug=False):\n if isinstance(words, basestring):\n words = words.split(\" \")\n\n if not target in self.rules:\n raise Exception(\"Target {} not present in grammar rules\".format(target))\n\n rule = self.rules[target]\n\n for opt in rule.options:\n T = Tree(opt)\n if self._parse((T, 0), words):\n # Simply take the first tree that successfully parses\n semantics_str = self.get_semantics(T).replace(\"<\", \"[\").replace(\">\", \"]\")\n try:\n semantics = yaml.safe_load(semantics_str)\n except MarkedYAMLError as e:\n raise Exception(\"Failed to parse semantics\", semantics_str, e)\n return semantics\n\n return False\n\n def _parse(self, T_idx, words):\n (T, idx) = T_idx\n\n if not T:\n return words == []\n\n if not words:\n return False\n\n conj = T.option.conjuncts[idx]\n\n if conj.is_variable:\n if conj.name not in self.rules:\n return False\n options = self.rules[conj.name].options\n\n elif conj.name[0] == \"$\":\n func_name = conj.name[1:]\n if not func_name in self.functions:\n return False\n options = self.functions[func_name](words)\n\n else:\n if conj.name == words[0]:\n return self._parse(T.next(idx), words[1:])\n else:\n return False\n\n for opt in options:\n subtree = T.add_subtree(idx, Tree(opt))\n ret = self._parse((subtree, 0), words)\n if ret:\n return ret\n\n return False\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n def get_tree(self, lname):\n if lname not in self.rules:\n raise Exception(\"Target {} not present in grammar rules\".format(lname))\n\n rule = self.rules[lname]\n\n alternative_values = []\n for opt in rule.options:\n sequence_values = []\n\n for conj in opt.conjuncts:\n if conj.is_variable:\n tree = self.get_tree(conj.name)\n if tree:\n sequence_values.append(tree)\n else:\n sequence_values.append(conj.name)\n\n alternative_values.append(Sequence(sequence_values))\n\n return Alternative(alternative_values)\n\n @staticmethod\n def _get_all_sentences_from_tree(node, max_sentences):\n \"\"\"\n\n :param node: Node to expand to generate sentences\n :param max_sentences: Maximum allowed number of sentences (to avoid high calculation times)\n :return: List of all possible sentences in the given grammar\n\n TODO: Reuse previously expanded rules to reduce number of expanded nodes.\n E.g. {node1: string_list1, ...} and do a lookup before expanding\n \"\"\"\n if isinstance(node, Alternative):\n string_list = []\n for value in node.values:\n res = GrammarParser._get_all_sentences_from_tree(value, max_sentences)\n string_list += res\n elif isinstance(node, Sequence):\n string_list = []\n for value in node.values:\n res = GrammarParser._get_all_sentences_from_tree(value, max_sentences)\n if string_list:\n string_list = [\" \".join(e) for e in itertools.product(string_list, res)]\n else:\n string_list = res\n elif isinstance(node, str):\n string_list = [node]\n if len(string_list) > max_sentences:\n raise Exception(\"Too many options in grammar.\")\n return string_list\n\n @staticmethod\n def _get_random_sentence_from_tree(node):\n \"\"\"\n :param node: Node to expand to generate sentences\n :return: A randomly generated sentence according to the given node\n \"\"\"\n sentence = \"\"\n if isinstance(node, Alternative):\n sentence = GrammarParser._get_random_sentence_from_tree(random.choice(node.values))\n elif isinstance(node, Sequence):\n word_list = []\n for value in node.values:\n word_list.append(GrammarParser._get_random_sentence_from_tree(value))\n sentence = \" \".join(word_list)\n elif isinstance(node, str):\n sentence = node\n return sentence\n\n def get_random_sentences(self, lname, num, max_num=1e5):\n tree = self.get_tree(lname)\n\n try:\n sentences = self._get_all_sentences_from_tree(tree, max_num)\n random.shuffle(sentences)\n sentences = sentences[:num]\n except:\n sentences = [self._get_random_sentence_from_tree(tree) for _ in range(0, num)]\n\n return sentences\n\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n def to_bnf_grammar(self, lname):\n \"\"\"\n Generate Nuance BNF Format grammar from the grammar used by hmi\n :param lname: The root\n :return: BNF String\n \"\"\"\n bfn_rule_dict = {}\n for name, rule in self.rules.iteritems():\n bfn_rule_dict[rule.lname] = \" | \".join([\" \".join(\"<\" + c.name + \">\"\n if c.is_variable else c.name\n for c in option.conjuncts) for option in rule.options])\n\n string = '#BNF+EMV1.1;\\n!grammar \"BNFEnglish\";\\n!start <{}>;\\n'.format(lname)\n for k, v in bfn_rule_dict.iteritems():\n string += \"<{}>: {};\\n\".format(k, v)\n\n return string\n","sub_path":"hmi/src/hmi/grammar_parser.py","file_name":"grammar_parser.py","file_ext":"py","file_size_in_byte":15785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"36458441","text":"import os\n\nimport pandas as pd\nimport numpy as np\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine\n\nfrom flask import Flask, jsonify, render_template\nfrom flask import redirect, request\nfrom flask_sqlalchemy import SQLAlchemy\nimport json\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import PolynomialFeatures\nimport pickle\n\napp = Flask(__name__)\n\n#################################################\n# Database Setup\n#################################################\n\n# app.config[\"SQLALCHEMY_DATABASE_URI\"] = \"sqlite:///db/Alltypes.sqlite\"\n# db = SQLAlchemy(app)\n\n# # reflect an existing database into a new model\n# Base = automap_base()\n# # reflect the tables\n# Base.prepare(db.engine, reflect=True)\n\n# # Save references to each table\n# Samples_Metadata = Base.classes.sample_metadata\n# Samples = Base.classes.samples\n\n# db =\"sqlite:///db/Alltypes.sqlite\"\ndb =\"postgres://xxlseihlmohnre:6667aa7c4ad666c7e6c92755418ff0486278365bde892a02ab7243afd5ca65ad@ec2-50-19-127-115.compute-1.amazonaws.com:5432/denrnahfu7g51u\"\n\nratio = 1000\n\n\ndef one_var_prediction(pred_model, temperature):\n data = pd.DataFrame(np.array([[temperature]]))\n \n polynomial_features= PolynomialFeatures(degree=2)\n x_poly = polynomial_features.fit_transform(data)\n\n result = pred_model.predict(x_poly) / ratio\n \n prediction = float(result.round(2))\n return prediction\n\ndef two_var_prediction(pred_model, temperature , coal_consumption):\n data = pd.DataFrame(np.array([[coal_consumption * ratio,temperature ]]))\n \n polynomial_features= PolynomialFeatures(degree=2)\n x_poly = polynomial_features.fit_transform(data)\n\n result = pred_model.predict(x_poly) / ratio\n \n prediction = float(result.round(2))\n return prediction\n\n@app.route(\"/\")\ndef index():\n \"\"\"Return the homepage.\"\"\"\n return render_template(\"index.html\")\n\n@app.route(\"/dashboard\")\ndef dashboard():\n \n return render_template(\"dashboard.html\")\n\n@app.route(\"/machinelearning\", methods=[\"GET\", \"POST\"])\ndef machinelearning():\n natural_gas_message = \"\"\n coal_message = \"\"\n natural_gas_refined_message=\"\"\n temperature=\"\"\n\n if request.method == \"POST\":\n #temperature = float(request.form[\"temperature\"])\n # natural gas model\n with open(f'MachineLearning/code/model/linear_regression_gas_TempOnly.pickle', \"rb\") as gas:\n #with open(f'Energy_Source/MachineLearning/code/model/linear_regression_gas_TempOnly.pickle', \"rb\") as gas:\n natural_gas_model = pickle.load(gas)\n temperature = float(request.form[\"temperature\"])\n # data must be converted to df with matching feature names before predict\n natural_gas_message = one_var_prediction(natural_gas_model, temperature)\n \n\n # coal model\n with open(f'MachineLearning/code/model/linear_regression_coal_TempOnly.pickle', \"rb\") as coal:\n #with open(f'Energy_Source/MachineLearning/code/model/linear_regression_coal_TempOnly.pickle', \"rb\") as coal:\n coal_model = pickle.load(coal)\n temperature1 = float(request.form[\"temperature\"])\n coal_message = one_var_prediction(coal_model, temperature1)\n\n # gas model using coal prediction\n with open(f'MachineLearning/code/model/linear_regression_gas_TempCoal.pickle', \"rb\") as gas_refine:\n #with open(f'Energy_Source/MachineLearning/code/model/linear_regression_gas_TempCoal.pickle', \"rb\") as gas_refine:\n gas_refined_model = pickle.load(gas_refine)\n temperature2 = float(request.form[\"temperature\"])\n natural_gas_refined_message = two_var_prediction(gas_refined_model, temperature2, coal_message) \n\n \n return render_template(\"machinelearning.html\", natural_gas_message=natural_gas_message, coal_message=coal_message, temperature=temperature, natural_gas_refined_message=natural_gas_refined_message)\n else:\n return render_template(\"machinelearning_light.html\")\n\n\n@app.route(\"/bio\")\ndef bio():\n \n return render_template(\"bio.html\")\n\n@app.route(\"/credits\")\ndef credits():\n \n return render_template(\"credits.html\")\n\n@app.route(\"/resources\")\ndef resources():\n \n return render_template(\"resources.html\")\n\n@app.route(\"/future\")\ndef future():\n \n return render_template(\"future.html\")\n\n@app.route(\"/now\")\ndef now():\n \n return render_template(\"now.html\") \n\n@app.route(\"/history\")\ndef history():\n \n return render_template(\"history.html\") \n\n@app.route(\"/coal\")\ndef coal():\n \n return render_template(\"indexBarCoal.html\") \n\n@app.route(\"/naturalgas\")\ndef naturalgas():\n \n return render_template(\"indexBarNaturalGas.html\") \n\n@app.route(\"/nuclear\")\ndef nuclear():\n \n return render_template(\"indexBarNuclear.html\") \n\n@app.route(\"/petroleum\")\ndef petroleum():\n \n return render_template(\"indexBarPetroleum.html\") \n\n@app.route(\"/renewable\")\ndef renewable():\n \n return render_template(\"indexBarRenewable.html\") \n\n@app.route(\"/data\")\ndef get_data():\n\n engine = create_engine(db)\n conn = engine.connect()\n \n sql = f\"select * from Alltypes\"\n Alltypes_df = pd.read_sql(sql, conn)\n conn.close()\n return Alltypes_df.to_json(orient=\"records\")\n\n@app.route(\"/data/year\")\ndef get_year():\n engine = create_engine(db)\n conn = engine.connect()\n \n sql = f\"select * from Alltypes\"\n data = pd.read_sql(sql, conn)\n conn.close()\n # Return a list of the column names (sample names)\n yr = (data.columns)[2:]\n yr_reverse = []\n\n for i in range(len(yr)-1 , -1, -1):\n yr_reverse.append(yr[i])\n return jsonify(yr_reverse)\n\n@app.route(\"/data/state\")\ndef get_state():\n engine = create_engine(db)\n conn = engine.connect()\n \n sql = f\"select * from Alltypes\"\n data = pd.read_sql(sql, conn)\n conn.close()\n\n # Return a list of the column names (sample names)\n return jsonify(list(data[\"state\"].head(52)))\n\n@app.route(\"/data/energyType\")\ndef set_energyType():\n energyType = ['Coal','Natural Gas','Petroleum','Nuclear','Renewable']\n\n return jsonify(energyType)\n\n\n@app.route(\"//\")\ndef select_data(energy_type, yr):\n engine = create_engine(db)\n\n sql = f\"select * from Alltypes\"\n\n conn = engine.connect()\n \n data = pd.read_sql(sql, conn)\n conn.close()\n\n tmp_data = data.loc[:,['type','state',yr]]\n \n selected_data = tmp_data[tmp_data['type']==energy_type ]\n\n data = {\n \"State\":selected_data['state'], \n \"consumption\": selected_data[yr]\n }\n # print(data)\n\n data = pd.DataFrame(data)\n return data.to_json(orient=\"records\")\n # return jsonify(data)\n \n@app.route(\"/data//\")\ndef select_data_per_state(energy_type,state):\n \n engine = create_engine(db)\n conn = engine.connect()\n \n sql = f\"select * from Alltypes\"\n data = pd.read_sql(sql, conn)\n conn.close()\n\n tmp = data[data['type'] == energy_type]\n consumption_data_tmp = tmp[tmp['state']==state].iloc[0].tolist()\n\n # test_Data ={}\n\n yr = []\n consumption = []\n # print(consumption_data_tmp)\n for i in range(2,len(data.columns)):\n yr.append( (data.columns)[i])\n consumption.append(consumption_data_tmp[i])\n # print(selected_data.loc[0])\n # print()\n\n # print(yr)\n \n selected_data={\n \"consumption\": consumption,\n \"yr\": yr, \n }\n\n # data = pd.DataFrame(selected_data)\n \n # return data.to_json(orient=\"records\")\n return jsonify(selected_data)\n\n@app.route(\"/energy_type//\")\ndef select_energyType_per_state_year(state,yr):\n engine = create_engine(db)\n\n sql = f\"select * from Alltypes\"\n \n # result = engine.execute(\"sql statement\")\n\n conn = engine.connect()\n \n data = pd.read_sql(sql, conn)\n conn.close()\n tmp = data[data['state'] == state]\n sel_data =tmp[yr].tolist()\n # print(sel_data)\n data_label =['Coal','NaturalGas','Petroleum','Nuclear','Renewable']\n selected_data ={\n \"EnergyType\": data_label, \n \"consumption\" : sel_data\n }\n\n # print(selected_data)\n return jsonify(selected_data)\n\nif __name__ == \"__main__\":\n app.run(port=5006, debug=True)\n # app.run()\n","sub_path":"boredom-busters/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"528235458","text":"import os\nfrom random import Random\nimport json\n\nfrom PIL import Image\nimport numpy as np\n\nfrom render_clock import render_clock\n\ndef _image2vec(im):\n assert im.getbands() == (\"R\", \"G\", \"B\")\n\n ary = np.array(im) / 255.0\n assert(ary.shape == (im.size[0], im.size[1], 3))\n\n ary.resize(1, 3 * im.size[0] * im.size[1])\n\n return ary\n\ndef _generate_example(image_size, rng):\n label = rng.randrange(12 * 60 * 60)\n\n im = render_clock(image_size, label)\n example = _image2vec(im)\n\n return (example, label, im)\n\nclass ClockDataset:\n @staticmethod\n def generate(n_examples, image_size, seed = None):\n cd = ClockDataset()\n\n rng = Random()\n\n if seed is not None:\n rng.seed(seed)\n\n cd.m = cd.n_examples = n_examples\n cd.image_size = image_size\n cd.n_features = 3 * image_size**2\n cd.paths = []\n cd.images = []\n\n cd.X = cd.examples = np.zeros((n_examples, cd.n_features))\n cd.y = cd.labels = np.zeros((n_examples, 1))\n\n for i in range(n_examples):\n X_i, y_i, im = _generate_example(image_size, rng)\n path = \"%06d_%d.png\" % (i, y_i)\n\n cd.paths.append(path)\n cd.images.append(im)\n cd.X[i] = X_i\n cd.y[i] = y_i\n\n cd.metadata = {\n 'image_size': image_size,\n 'paths': cd.paths,\n 'labels': cd.labels.tolist()\n }\n\n return cd\n\n def save(self, path):\n os.makedirs(path, exist_ok = True)\n\n with open(os.path.join(path, \"meta.json\"), \"w\") as metafile:\n json.dump(self.metadata, metafile)\n\n for relative_image_path, im in zip(self.paths, self.images):\n im.save(os.path.join(path, relative_image_path))\n\n @staticmethod\n def load(path, keep_images = False):\n cd = ClockDataset()\n\n with open(os.path.join(path, \"meta.json\")) as metafile:\n cd.metadata = json.load(metafile)\n\n cd.image_size = cd.metadata[\"image_size\"]\n cd.n_features = 3 * cd.image_size**2\n\n cd.m = len(cd.metadata[\"paths\"])\n cd.n_examples = cd.m\n\n cd.y = cd.labels = np.array(cd.metadata[\"labels\"])\n\n cd.images = []\n\n assert cd.y.shape == (cd.m, 1)\n\n cd.X = cd.examples = np.zeros((cd.m, cd.n_features))\n\n for i, relative_image_path in enumerate(cd.metadata[\"paths\"]):\n im = Image.open(os.path.join(path, relative_image_path))\n vec = _image2vec(im)\n\n assert vec.shape == (1, cd.n_features)\n\n cd.X[i] = vec\n\n if keep_images:\n cd.images.append(im)\n","sub_path":"clock_dataset.py","file_name":"clock_dataset.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"172756706","text":"## 739. Daily Temperatures\n\nclass Solution:\n def dailyTemperatures(self, temperatures: List[int]) -> List[int]:\n \n N = len(temperatures)\n result=[0]*N\n \n ## Monotonic decreasing stack\n tempS = []\n i=0\n while itemperatures[tempS[-1]]:\n prev = tempS.pop()\n result[prev]= i-prev\n tempS.append(i)\n i+=1\n \n return result\n \n # temp = [[0,temperatures[0]]]\n # idx=1\n # while idxtemp[-1][1]:\n # # print('->',temp)\n # # print(result[temp[-1][0]], temp[-1][0], idx-temp[-1][0])\n # result[temp[-1][0]]=idx-temp[-1][0]\n # # print(result[temp[-1][0]])\n # temp.pop()\n # temp.append([idx,temperatures[idx]])\n # idx+=1\n # print('-'*20)\n # return result\n \n ## O(N^2) - Rohan's Implementation\n# N = len(temperatures)\n# result = [0]*N\n# i=0\n# while i= screen_size_x and self.vx > 0:\n self.vx *= -1\n if self.poy + self.vy <= 0 and self.vy < 0:\n self.vy *= -1\n elif self.poy + self.vy >= screen_size_y and self.vy > 0:\n self.vy *= -1\n self.v = self.vx, self.vy\n self.objects[i][2] = self.px, self.py, self.v \n self.new_point = self.pox, self.poy\n self.objects[i].append(self.new_point)\n def DrawObjects(self):\n for i in range(0, len(self.objects), 1):\n for j in range(3, len(self.objects[i]) - 1, 1):\n pygame.draw.line(screen, (0, 0, 0), self.objects[i][j], self.objects[i][j + 1], 3)\n pygame.draw.line(screen, (0, 0, 0), self.objects[i][3], self.objects[i][len(self.objects[i]) - 1], 3)\n def Update(self):\n self.RotateObjects(1)\n self.SimulateGravityMovement()\n self.DrawObjects()\n\nPhysics = PhysicsHandler()\nPhysics.CreateObject(5, 0, 50)\nclock = pygame.time.Clock()\nscreen = pygame.display.set_mode((screen_size_x, screen_size_y), 0, 32)\nwhile True:\n clock.tick(60)\n screen.fill((255, 255, 255))\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n Physics.Update()\n pygame.display.update()\n","sub_path":"Physics Project/Backups/Physics Project Backup 3.py","file_name":"Physics Project Backup 3.py","file_ext":"py","file_size_in_byte":5232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"349693523","text":"#!/usr/bin/python\n\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom keras.models import Model\nfrom keras.layers import Input, Lambda, TimeDistributed, Dropout, Permute, Reshape, LSTM, Conv2D, Dense, Activation, MaxPool2D, Flatten, Bidirectional\nfrom keras import backend as K\nfrom keras import regularizers\nimport sys\nimport os\nimport numpy as np\nimport preprocess\nimport argparse\nimport datetime\n\n#CHANGE LABEL_PATH AND IMG_DIR_PATH TO PATHS USED FOR LOCAL DIRECTORY\n\nPATH_BASE = '/Users/Sanjay/Documents/CS_V_Final_Project/'\nIMG_DIR_PATH = PATH_BASE + 'data/words/'\nLABEL_PATH = PATH_BASE + 'data/words.txt'\nIMG_SIZE = (1, 128, 32)\nBATCH_SIZE = 500\nHIDDEN_SIZE = 100\nALPHABET_SIZE = 30\nINPUT_SEQUENCE_LENGTH = 256\nLABEL_LENGTHS = 53\nUSE_DROPOUT = True\nUSE_REGULARIZER = False\n\nclass SimpleHTR():\n\n def __init__(self, mode='train', weights_file=None):\n\n kernels = [5, 5, 3, 3, 3]\n pools = [(2, 2), (2, 1), (2, 1), (2, 2), (2, 1)]\n num_filters = [32, 64, 128, 128, 256]\n num_layers = len(pools)\n\n #self.model = Sequential()\n input_data = Input(name='input', shape=IMG_SIZE) \n conv = input_data\n\n for i in range(0, num_layers):\n conv_name = 'conv' + str(i)\n max_pool_name = 'max_pool' + str(i)\n conv = Conv2D(name=conv_name, kernel_size=(kernels[i], kernels[i]), filters=num_filters[i], activation='relu', data_format='channels_first')(conv)\n conv = MaxPool2D(name=max_pool_name, pool_size=pools[i], strides=pools[i], data_format='channels_first')(conv)\n \n #self.model.add(Permute((2, 1), input_shape=(10, 64)))\n \n inner = Flatten(name='flatten', data_format='channels_first')(conv)\n inner = Reshape((-1, 1), name='reshape')(inner)\n #self.model.add(Permute((2, 1)))\n lstm1 = Bidirectional(LSTM(HIDDEN_SIZE, name='lstm1', return_sequences=True))(inner)\n lstm2 = Bidirectional(LSTM(HIDDEN_SIZE, name='lstm2', return_sequences=True))(lstm1)\n if USE_DROPOUT:\n lstm2 = Dropout(0.1, name='dropout')(lstm2)\n time_dist = TimeDistributed(Dense(ALPHABET_SIZE), name='time_dist')(lstm2)\n inner2 = Dense(ALPHABET_SIZE, name='dense')(time_dist)\n if USE_REGULARIZER:\n inner2 = Dense(ALPHABET_SIZE, name='regularizer', kernel_regularizer=regularizers.l2(0.01))(inner2)\n y_pred = Activation('softmax', name='softmax')(inner2)\n\n assert mode == 'train' or mode == 'test'\n #Model(inputs = input_data, outputs=y_pred).summary()\n if mode == 'train':\n y_true = Input(name='labels',\n shape=[LABEL_LENGTHS], dtype='float32')\n input_length = Input(name='input_length', shape=[1], dtype='int64')\n label_length = Input(name='label_length', shape=[1], dtype='int64')\n \n #BUILDS IN LOSS INTO THE HTR MODEL\n loss_out = Lambda(ctc_lambda_func, output_shape=(1,), name='ctc')([y_pred, y_true, input_length, label_length])\n\n self.model = Model(inputs=[input_data, y_true, input_length, label_length], outputs=loss_out)\n\n self.model.compile(loss={'ctc': lambda y_true, y_pred: y_pred}, optimizer='adam', metrics=['accuracy'])\n #print(self.model.summary())\n\n elif mode == 'test': \n\n self.model = Model(inputs=[input_data], outputs=y_pred)\n #print(self.model.summary())\n\n if weights_file != None:\n try:\n self.model.load_weights(weights_file, by_name=True)\n except:\n print(\"Warning! Weights file does not exist! Neural net not initialized with weights!\")\n \n def train(self, data, batch_size=32, epochs=10, out_file=None):\n dataset_size = list(data.values())[0].shape[0]\n true_vals_dummy = np.zeros(dataset_size)\n self.model.fit(x=data, y=true_vals_dummy, validation_split=0.0, batch_size=batch_size, epochs=epochs, verbose=1)\n if out_file != None:\n self.model.save_weights(out_file)\n\n def predict(self, test_dir_path):\n imgs = preprocess.get_data(LABEL_PATH, test_dir_path, imgs_to_labels=True, one_hot=False, return_list=True)['input']\n out = self.model.predict({'input': imgs})\n out = out[:, 2:, :]\n\n #print(out)\n\n return K.get_value(K.ctc_decode(out, input_length=np.ones(out.shape[0])*out.shape[1],\n greedy=True, beam_width=10, top_paths=2)[0][0])\n\n def predict_from_array(self, imgs):\n out = self.model.predict({'input': imgs})\n out = out[:, 2:, :]\n\n return K.get_value(K.ctc_decode(out, input_length=np.ones(out.shape[0])*out.shape[1],\n greedy=True, beam_width=10, top_paths=2)[0][0])\n\ndef ctc_lambda_func(args):\n y_pred, y_true, input_length, label_length = args\n y_pred = y_pred[:, 2:, :]\n return K.ctc_batch_cost(y_true, y_pred, input_length, label_length) \n\n\ndef main():\n\n parser = argparse.ArgumentParser()\n parser.add_argument('mode', help='Mode in which to operate the neural net, \\'train\\' or \\'test\\'')\n parser.add_argument('-e', '--epochs', help='Number of epochs to train, default 10', type=int)\n parser.add_argument('-w', '--weights', help='Optional pre-loaded weights')\n parser.add_argument('-d', '--data', help='directory of training data')\n parser.add_argument('-t', '--test_data', help='directory of test data')\n args = parser.parse_args()\n\n sess = tf.Session()\n with sess.as_default():\n\n if (args.mode=='test'):\n htr = SimpleHTR(mode='test', weights_file=(args.weights if args.weights else None))\n test_dir_path = \"/Users/Sanjay/Documents/CS_V_Final_Project/data/words/\" + (args.test_data if args.test_data else 'a01/a01-000u')\n responses = htr.predict(test_dir_path)\n for row in responses:\n print(preprocess.numerical_decode(row))\n\n elif args.mode == 'train':\n htr = SimpleHTR(mode='train', weights_file=(args.weights if args.weights else None))\n data = preprocess.get_data(LABEL_PATH, img_dir_path=IMG_DIR_PATH+args.data, imgs_to_labels=True, one_hot=False, return_list=True)\n htr.train(data, epochs=(args.epochs if args.epochs else 10), out_file=(args.weights if args.weights else None))\n \n print('\\n*********************************\\n Training Complete: ' + str(datetime.datetime.now()) + '\\n*********************************\\n\\n')\n \n else:\n raise InvalidArgumentError('No valid mode of operating neural net specified!')\n\nif __name__ == '__main__':\n main()\n","sub_path":"model_original.py","file_name":"model_original.py","file_ext":"py","file_size_in_byte":6794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"618001423","text":"from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_pymongo import PyMongo\nfrom flask_mongoengine import MongoEngine\nimport mongoengine as me\nfrom flask_login import UserMixin\nfrom __init__ import db\n\n\nclass Students(me.Document):\n name = me.StringField(required=True)\n course = me.StringField()\n gender = me.StringField()\n mobile = me.IntField()\n username = me.StringField(required=True, primary_key=True)\n password = me.StringField()\n\n\nclass User(db.Model, UserMixin):\n id = db.Column(db.String, primary_key=True)\n pwd = db.Column(db.String)\n name = db.Column(db.String)\n role = db.Column(db.String)\n dept = db.Column(db.String)\n salary = db.Column(db.Integer)\n\n def __init__(self, id, pwd, name, role, dept, salary):\n self.id = id\n self.pwd = pwd\n self.name = name\n self.role = role\n self.dept = dept\n self.salary = salary\n\n\n# class Students(db.Model):\n# name = db.Column(db.String(20))\n# course = db.Column(db.String(20))\n# gender = db.Column(db.String(10))\n# mobile = db.Column(db.Integer)\n# username = db.Column(db.String(6), primary_key=True)\n# password = db.Column(db.String(8), nullable=False)\n#\n# def __init__(self, name, course, gender, mobile, username, password):\n# self.name = name\n# self.course = course\n# self.gender = gender\n# self.mobile = mobile\n# self.username = username\n# self.password = password\n\n\nclass Books(db.Model):\n book_id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(20))\n author = db.Column(db.String(20))\n price = db.Column(db.Integer)\n\n def __init__(self, book_id, title, author, price):\n self.book_id = book_id\n self.title = title\n self.author = author\n self.price = price\n\n def serialize(self):\n return {\"book_id\": self.book_id, \"title\": self.title, \"author\": self.author, \"price\": self.price}\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"471407166","text":"#スリザーリンク4*4のmaster\nN=4\nM=4\ncol=[[1 for i in range(N)] for j in range(M+1)]\nrow=[[1 for i in range(N+1)] for j in range(M)]\n\ndef link(s,t):\n if s=b:\n c.append(1)\n else:\n c.append(0)\nprint(c)\n \n \n\n\n# In[ ]:\n\n\n#Formulating the First BFS\nbfs=[]\nfor j in range(n):\n if j>=b:\n bfs.append(1)\n else:\n bfs.append(0)\nprint(bfs)\n\n\n# In[1]:\n\n\ndef pivotbland(M,soln,c,bfs): #Question 2(c)\n cn=[] #Executing Phase 1 of Simplex\n cb=[]\n crindex=[]\n crindexb=[]\n N=[]\n B=[]\n count=0\n counter=0\n for i in range(n): #to segregate variables in Basic and Nonbasic matrices\n if bfs[i]==0:\n crindex.append(i)\n cn.append(c[i])\n N.append(M[:,i])\n count=count+1\n \n else: \n crindexb.append(i)\n cb.append(c[i])\n B.append(M[:,i])\n counter=counter+1\n \n cb=np.asarray(cb) # Cb\n cn=np.asarray(cn) # Cn\n B=np.asarray(B) # B\n B=B.transpose() \n N=np.asarray(N) # N\n N=N.transpose()\n \n\n \n cr=[] #Finding the Reduced Cost Coefficient Vector(RCCV)\n Binv=np.linalg.inv(B)\n \n a=np.dot(Binv,N)\n b=np.dot(cb,a)\n cr=cn-b\n cr=np.asarray(cr)\n \n \n \n x=n-m #Checking for optimality\n unbound=[]\n Ares=[]\n count=0 \n for j in cr:\n if j>=0:\n count=count+1\n if count==x:\n ofv1=np.matmul(cb,Binv)\n ofv=np.matmul(ofv1,soln)\n if ofv>0:\n y='infeasible'\n else:\n print('optimality reached at this BFS:', bfs ,'the Objective Function Value at this BFS is:',ofv)\n y='optimal'\n return y\n \n \n x=n-m #checking for unboundedness\n check=[]\n kr=[]\n for k in range(x):\n if cr[k]>=0:\n kr=N[:,k].reshape((m,1))\n count=0\n unbound=np.matmul(Binv,kr)\n for j in unbound:\n if j<=0:\n count=count+1\n if count==m:\n check.append(1)\n \n if len(check)>0:\n y='unbounded'\n return y\n \n p=list(cr)\n for i in range(x):\n if p[i]<0:\n l=i\n break\n v=crindex[l] \n shiftn=M[:,v] # Choosing the NBV to be shifted to BV\n \n shiftn= np.asarray(shiftn)\n shiftn=shiftn.reshape((m,1))\n xb_start=np.matmul(Binv,soln)\n xb_middle=np.dot(Binv,shiftn)\n xb=[]\n xb=xb_start-xb_middle\n xb=np.asarray(xb)\n \n subtract=xb_start-xb # Choosing the BV to be shifted to NBV\n xbl=list(xb)\n for i in range(m):\n if subtract[i]>0 and xbl[i]==min(xbl):\n h=i\n break \n \n else:\n continue\n \n j=crindexb[h]\n bfs=list(bfs)\n bfs[v]=1\n bfs[j]=0\n pivotbland(A,soln,c,bfs)\n\n\n# In[2]:\n\n\npivotbland(M,soln,c,bfs)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Simplex Code.py","file_name":"Simplex Code.py","file_ext":"py","file_size_in_byte":4869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"436388072","text":"import numpy as np\nimport cv2,sys,time\nfrom dataPath import DATA_PATH\n\nif __name__ == '__main__':\n\n filename = DATA_PATH + \"videos/face1.mp4\"\n cap = cv2.VideoCapture(filename)\n\n # Read a frame and find the face region using dlib\n ret,frame = cap.read()\n\n # Detect faces in the image\n faceCascade = cv2.CascadeClassifier(DATA_PATH + 'models/haarcascade_frontalface_default.xml')\n\n frameGray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n faces = faceCascade.detectMultiScale(frameGray,1.3,5)\n x,y,w,h = faces[0]\n\n currWindow = (x,y,w,h)\n # get the face region from the frame\n roiObject = frame[y:y+h,x:x+w]\n hsvObject = cv2.cvtColor(roiObject, cv2.COLOR_BGR2HSV)\n\n # GGGet the mask for calculating histogram of the object and also remove noise\n mask = cv2.inRange(hsvObject, np.array((0., 50., 50.)), np.array((180.,255.,255.)))\n cv2.imshow(\"mask\",mask)\n cv2.imshow(\"Object\",roiObject)\n\n # Find the histogram and normalize it to have values between 0 to 255\n histObject = cv2.calcHist([hsvObject], [0], mask, [180], [0,180])\n cv2.normalize(histObject, histObject, 0, 255, cv2.NORM_MINMAX)\n\n # Setup the termination criteria, either 10 iterations or move by atleast 1 pt\n term_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 )\n i=0\n while(1):\n ret, frame = cap.read()\n\n if ret == True:\n # Convert to hsv color space\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n # find the back projected image with the histogram obtained earlier\n backProjectImage = cv2.calcBackProject([hsv], [0], histObject, [0,180], 1)\n cv2.imshow(\"Back Projected Image\", backProjectImage)\n\n # Compute the new window using CAM shift in the present frame\n rotatedWindow, currWindow = cv2.CamShift(backProjectImage, currWindow, term_crit)\n\n # Get the window used by mean shift\n x,y,w,h = currWindow\n\n # Get the rotatedWindow vertices\n rotatedWindow = cv2.boxPoints(rotatedWindow)\n rotatedWindow = np.int0(rotatedWindow)\n frameClone = frame.copy()\n\n # Display the current window used for mean shift\n cv2.rectangle(frameClone, (x,y), (x+w,y+h), (255, 0, 0), 2, cv2.LINE_AA)\n\n # Display the rotated rectangle with the orientation information\n frameClone = cv2.polylines(frameClone, [rotatedWindow], True, (0, 255, 0), 2, cv2.LINE_AA)\n cv2.putText(frameClone, \"{},{},{},{}\".format(x,y,w,h), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, .8, (0, 0, 255), 2, cv2.LINE_AA)\n cv2.putText(frameClone, \"{}\".format(rotatedWindow), (10, 80), cv2.FONT_HERSHEY_SIMPLEX, .8, (0, 0, 255), 2, cv2.LINE_AA)\n cv2.imshow('CAM Shift Object Tracking Demo',frameClone)\n # cv2.imwrite('{:03d}.jpg'.format(i),frameClone)\n i+=1\n\n k = cv2.waitKey(10) & 0xff\n if k == 27:\n break\n else:\n break\n\n cv2.destroyAllWindows()\n cap.release()\n","sub_path":"Course1/week9/camShift.py","file_name":"camShift.py","file_ext":"py","file_size_in_byte":2844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"389364054","text":"'''\nCreated on Jan 21, 2015\n\n@author: nidhi.aishwarya\n\nDescription : Verify that while creating a template, the Admin can select and update the server firmware. Verify that the firmware is updated before the deployment is initiated.\nTest Flow : 1) Login as Admin user\n 2) Create A template and check the update firmware checkbox and perform verifications\n'''\nfrom tests.globalImports import *\n\ntc_id=utility.get_tc_data(__file__)\n\nclass Testcase(Manager.Manager): \n \"\"\"\n Verify that while creating a template, the Admin can select and update the server firmware. Verify that the firmware is updated before the deployment is initiated.\n \"\"\"\n \n def __init__(self, *args, **kwargs):\n \"\"\"\n Initialization\n \"\"\"\n Manager.Manager.__init__(self, tc_id, *args, **kwargs) \n \n @BaseClass.TestBase.func_exec\n def test_functionality(self): \n \"\"\"\n This is the execution starting function\n \"\"\"\n self.browserObject = globalVars.browserObject\n \n #Check for current logged in user\n self.verifyCurrentUser(userRole='Administrator', loginAsUser=True) \n \n self.get_ServicesPage(\"\",\"Firmware_update_Template\")\n \n self.logout()\n \n \n \n \n \n \n\n","sub_path":"GUI/gui-automation-ASMvNext84UI/tests/firmware/Testcase_NGI_TC_3278.py","file_name":"Testcase_NGI_TC_3278.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"260372215","text":"\"\"\"\nPacket object to hold data between transmission\n\"\"\"\n\n\nclass Packet:\n\n def __init__(self, data, sequence, checksum, actual_data):\n self.data = data\n self.sequence = sequence\n self.checksum = checksum\n # Since corruption is simulated by randomly modifying the data variable,\n # actual_data contains the uncorrupted value whenever a NACK.\n self.actual_data = actual_data\n","sub_path":"Networking/Chapter3/Exercises/StopAndWaitUtility/TCPPacket.py","file_name":"TCPPacket.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"439659110","text":"\"\"\"Integration tests for translating between Fortran and other languages.\"\"\"\n\nimport pathlib\nimport sys\nimport unittest\n\nfrom transpyle.general.code_reader import CodeReader\nfrom transpyle.general.code_writer import CodeWriter\n\nfrom transpyle.fortran.parser import FortranParser\nfrom transpyle.fortran.ast_generalizer import FortranAstGeneralizer\nfrom transpyle.fortran.unparser import Fortran77Unparser\n\nfrom transpyle.python.parser import TypedPythonParserWithComments\nfrom transpyle.python.unparser import TypedPythonUnparserWithComments\n\nfrom test.common import EXAMPLES_F77_FILES, EXAMPLES_PY3_FILES\n\n\nclass Tests(unittest.TestCase):\n\n def test_fortran_to_python(self):\n for input_path in EXAMPLES_F77_FILES:\n reader = CodeReader()\n parser = FortranParser()\n generalizer = FortranAstGeneralizer()\n unparser = TypedPythonUnparserWithComments()\n writer = CodeWriter('.py')\n with self.subTest(input_path=input_path):\n code = reader.read_file(input_path)\n fortran_ast = parser.parse(code, input_path)\n tree = generalizer.generalize(fortran_ast)\n python_code = unparser.unparse(tree)\n writer.write_file(python_code, pathlib.Path('/tmp', input_path.name + '.py'))\n\n @unittest.skip('not ready yet')\n def test_python_to_fortran(self):\n for input_path in EXAMPLES_PY3_FILES:\n reader = CodeReader()\n parser = TypedPythonParserWithComments()\n unparser = Fortran77Unparser()\n writer = CodeWriter('.f')\n with self.subTest(input_path=input_path):\n python_code = reader.read_file(input_path)\n tree = parser.parse(python_code, input_path, mode='exec')\n fortran_code = unparser.unparse(tree)\n writer.write_file(fortran_code, pathlib.Path('/tmp', input_path.name + '.f'))\n\n @unittest.skipIf(sys.version_info[:2] < (3, 6), 'requires Python >= 3.6')\n def test_fortran_to_python_to_fortran(self):\n for input_path in EXAMPLES_F77_FILES:\n parser = FortranParser()\n generalizer = FortranAstGeneralizer()\n unparser = TypedPythonUnparserWithComments()\n python_parser = TypedPythonParserWithComments(default_mode='exec')\n writer = CodeWriter('.f')\n with self.subTest(input_path=input_path):\n fortran_ast = parser.parse('', input_path)\n tree = generalizer.generalize(fortran_ast)\n python_code = unparser.unparse(tree)\n tree = python_parser.parse(python_code)\n fortran_code = unparser.unparse(tree)\n writer.write_file(fortran_code, pathlib.Path('/tmp', input_path.name + '.py.f'))\n","sub_path":"test/fortran/test_integration.py","file_name":"test_integration.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"272454555","text":"import os\nimport sentry_sdk\nfrom sentry_sdk.integrations.celery import CeleryIntegration\nfrom celery import Celery\n\nif os.getenv(\"ENV_TYPE\") == \"prod\":\n sentry_dsn = os.getenv(\"SENTRY_DSN\")\n\n if sentry_dsn:\n sentry_sdk.init(sentry_dsn, integrations=[CeleryIntegration()])\n\nif os.getenv(\"BROKER_URL\"):\n broker_url = os.getenv(\"BROKER_URL\")\nelse:\n broker_host = os.getenv(\"BROKER_HOST\", \"{{cookiecutter.project_slug}}_broker\")\n broker_url = f\"pyamqp://guest@{broker_host}//\"\n\ncelery = Celery(\"{{cookiecutter.project_slug}}\", broker=broker_url)\n\n\n@celery.task(ignore_result=True)\ndef hello():\n print(\"hello world\")\n","sub_path":"{{cookiecutter.project_slug}}/app/{{cookiecutter.project_slug}}/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"503752535","text":"#Melhore o desafio 61, perguntando para o usuario se ele quer mostrar mais alguns termos.\r\n# O programa encerra quando ele diser que quer mostrar 0 termos. \r\nnum = int(input('Digite um numero: '))\r\nraz = int(input('Digite a razão da P.A.: '))\r\nqts = 10\r\nwhile qts != 0:\r\n c = 0\r\n while c != qts:\r\n print(num, '-> ', end='')\r\n num += raz\r\n c += 1\r\n qts = int(input('Mostrar mais quantos? '))\r\nprint('ACABOU!')\r\n ","sub_path":"Mundo 2/Ex062.py","file_name":"Ex062.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"572221105","text":"## project: interactive scatter plot (insured persons vs. compaints, slider per year)\nimport cleaning\nfrom bokeh.layouts import widgetbox, row\nfrom bokeh.models import HoverTool, ColumnDataSource, Slider\nfrom bokeh.plotting import figure\nfrom bokeh.io import curdoc\n\n# load the cleaned dataframe and reset its index\ndf = cleaning.load_clean_data()\ndf = df.set_index(['Jahr'])\n\n#Make the ColumnDataSource: source\nsource = ColumnDataSource(data={'x': df.loc[2002].Versicherte,\n 'y': df.loc[2002].Beschwerden,\n 'name': df.loc[2002].Name})\n\n# Save the minimum and maximum values of the insured persons and compaints columns\nxmin, xmax = min(df.Versicherte), max(df.Versicherte)\nymin, ymax = min(df.Beschwerden), max(df.Beschwerden)\n\n# Create the figure: plot\nplot = figure(title='relationship between no of insured persons and no of complaints', x_axis_label='complaints', y_axis_label='insured persons',\n plot_height = 400, plot_width = 700, x_range=(xmin, xmax), y_range=(ymin, ymax))\n\n# Add a circle glyph to the figure p\nplot.circle(x='x', y='y', fill_alpha=0.5, color='firebrick', size=8, source=source)\n\n# Define the callback function: update_plot\ndef update_plot(attr, old, new):\n '''update slider value based on year'''\n yr = slider.value\n new_data = {'x': df.loc[yr].Versicherte,\n 'y': df.loc[yr].Beschwerden,\n 'name': df.loc[yr].Name}\n source.data = new_data\n plot.title.text = 'Insurance data for %d' % yr\n\n# Make a slider object and attach it to the 'value' property of slider\nslider = Slider(start=2002, end=2017, step=1, value=2002, title='Jahr')\nslider.on_change('value', update_plot)\n\n# Create a HoverTool and add it to the plot\nhover = HoverTool(tooltips=[('name', '@name')])\nplot.add_tools(hover)\n\n# Make a row layout of widgetbox(slider) and plot and add it to the current document\nlayout = row(widgetbox(slider), plot)\ncurdoc().add_root(layout)\n","sub_path":"interact_scatter.py","file_name":"interact_scatter.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"251485816","text":"import math\n\nclass Punto:\n\n def __init__( self, x=0, y=0 ):\n self.x = x\n self.y = y\n \n def __str__( self ):\n return '({}, {})'.format( self.x, self.y )\n \n def cuadrante( self ):\n if self.x == 0 and self.y == 0:\n print( '{} pertenece al origen.'.format( self ) )\n elif self.x > 0 and self.y > 0:\n print( '{} pertenece al primer cuadrante'.format( self ) )\n elif self.x < 0 and self.y > 0:\n print( '{} pertenece al segundo cuadrante'.format( self ) )\n elif self.x < 0 and self.y < 0:\n print( '{} pertenece al tercer cuadrante'.format( self ) )\n elif self.x > 0 and self.y < 0:\n print( '{} pertenece al cuarto cuadrante'.format( self ) )\n \n def vector( self, p ):\n print( 'El vector entre {} y {} es ({}, {})'.format( self, p, (p.x - self.x), (p.y - self.y) ) )\n \n def distancia( self, p ):\n d = math.sqrt( ( p.x - self.x )**2 + ( p.y - self.y )**2 )\n print( 'La distancia entre {} y {} es {}'.format( self, p, d ) )\n\nclass Rectangulo:\n \n def __init__( self, pInicial=Punto(), pFinal=Punto() ):\n self.pInicial = pInicial\n self.pFinal = pFinal\n \n def base_method( self ):\n self.base = abs( self.pFinal.x - self.pInicial.x )\n print( 'La base del rectangulo es {}'.format( self.base ) )\n \n def altura_method( self ):\n self.altura = abs( self.pFinal.y - self.pInicial.y )\n print( 'La altura del rectangulo es {}'.format( self.altura ) )\n \n def area_method( self ):\n self.base = abs( self.pFinal.x - self.pInicial.x )\n self.altura = abs( self.pFinal.y - self.pInicial.y )\n self.area = self.base * self.altura\n print( 'El area del rectangulo es {}'.format( self.area ) )\n\n\nA = Punto(2,3)\nB = Punto(5,5)\nC = Punto(-3,-1)\nD = Punto()\nprint( 'Cuadrantes' )\nA.cuadrante()\nC.cuadrante()\nD.cuadrante()\nprint( 'Vectores' )\nA.vector( B )\nB.vector( A )\nprint( 'Distancia' )\nA.distancia( B )\nB.distancia( A )\nprint( 'Distancia respecto el origen' )\nA.distancia( D )\nB.distancia( D )\nC.distancia( D )\nprint( 'Rectangulo' )\nR = Rectangulo( A, B )\nR.base_method()\nR.altura_method()\nR.area_method()","sub_path":"019SectionPractice.py","file_name":"019SectionPractice.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"432454594","text":"DEBUG = False\n\nSECRET_KEY = 'keep it secret, keep it safe.'\n\nAPP_NAME = 'Sawyer'\nAPP_ROOT = 'http://127.0.0.1:8000'\nAPP_IP = '127.0.0.1'\nAPP_PORT = 8000\n\nMONGODB_SETTINGS = {\n 'db': 'sawyer'\n , 'host': '127.0.0.1'\n , 'port': 27017\n}\n\nAWS = {\n 'access_key_id': 'AKzyxw9876'\n , 'secret_access_key': 'lmnop456'\n , 'verified_sender': 'bruce@wayneindustries.com'\n}\n","sub_path":"conf/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"329513014","text":"import os, sys, io\nimport socket\n\nimport numpy as np\nimport cv2 as cv\nfrom PIL import Image\n\nfrom tensorflow import keras\n\nfrom geom_utility import Rectangle\n\n\ndef simple_model():\n\n model = keras.Sequential()\n\n model.add(keras.layers.Conv2D(256, (3, 3), input_shape=(50, 50, 3), activation=\"relu\"))\n model.add(keras.layers.MaxPooling2D(pool_size=(2, 2)))\n\n model.add(keras.layers.Conv2D(256, (3, 3), activation='relu'))\n model.add(keras.layers.MaxPooling2D(pool_size=(2, 2)))\n\n model.add(keras.layers.Conv2D(256, (3, 3), activation='relu'))\n model.add(keras.layers.MaxPooling2D(pool_size=(2, 2)))\n\n model.add(keras.layers.Flatten())\n\n model.add(keras.layers.Dense(units=1024, activation='relu'))\n model.add(keras.layers.Dropout(0.5))\n\n model.add(keras.layers.Dense(units=256, activation='relu'))\n model.add(keras.layers.Dropout(0.5))\n\n model.add(keras.layers.Dense(units=1, activation=\"sigmoid\"))\n\n return model\n\n\ndef to_num(s):\n try:\n return int(s)\n except ValueError:\n return float(s)\n\n\ndef load_image(data):\n img = Image.open(io.BytesIO(data))\n img.load()\n img = img.resize((150, 150))\n data = np.asarray(img, dtype=np.ubyte)\n return data\n\n\ndef make_thirds_rois_with_150x150sz():\n # sz = (150, 150) hardcoded while\n\n M_roi = Rectangle(x=50, y=0, w=50, h=50)\n G_roi = Rectangle(x=50, y=100, w=50, h=50)\n L_roi = Rectangle(x=0, y=100, w=50, h=50)\n R_roi = Rectangle(x=100, y=100, w=50, h=50)\n\n # 0-X 1-M 2-Y 3-G 4-L 5-R\n return {\n 1: M_roi,\n 3: G_roi,\n 4: L_roi,\n 5: R_roi\n }\n\n\ndef run():\n\n domain_file_address = \"/tmp/yes_no_1.socket\"\n\n model = simple_model()\n model.compile(optimizer=\"adam\", loss='binary_crossentropy', metrics=['accuracy'])\n\n model.load_weights(\"./yes_no_simple_7.weights\")\n\n try:\n os.unlink(domain_file_address)\n except OSError:\n if os.path.exists(domain_file_address):\n raise\n\n sock = socket.socket(family=socket.AF_UNIX)\n sock.bind(domain_file_address)\n sock.listen(1)\n\n regions = make_thirds_rois_with_150x150sz()\n\n while True:\n print('waiting for a connection')\n connection, client_address = sock.accept()\n try:\n print('connection from', client_address)\n window = cv.namedWindow(\"img_for_show\", cv.WINDOW_GUI_NORMAL)\n\n while True:\n data_len = connection.recv(8)\n if data_len:\n data_len = to_num(data_len)\n print(\"Waiting data len:\", data_len)\n\n data = connection.recv(data_len)\n # data = np.fromstring(data, dtype=np.ubyte)\n\n img = load_image(data)\n img_for_show = img[:]\n\n img = img / 255\n\n active_results = [0, 0, 0, 0, 0, 0]\n for key, rect in regions.items():\n section_img = img[rect.y:rect.yh, rect.x:rect.xw]\n section_img = section_img.reshape(1, 50, 50, 3)\n\n result_predict = model.predict(section_img)\n\n if result_predict[0][0] > 0.5:\n active_results[key] = 1\n\n print(str(active_results))\n connection.sendall(bytearray(active_results))\n\n cv.imshow(\"img_for_show\", img_for_show)\n cv.waitKey(250)\n\n else:\n print('no data from', client_address)\n code = cv.destroyAllWindows()\n break\n\n finally:\n # Clean up the connection\n print(\"Closing connection\")\n connection.close()\n\n\nif __name__ == \"__main__\":\n run()\n","sub_path":"tensor_flow_code/recog_yes_no_server.py","file_name":"recog_yes_no_server.py","file_ext":"py","file_size_in_byte":3793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"95787489","text":"from django.db import models\n\n\nclass ActionLogManager(models.Manager):\n \n def perform_create(self, user, action_data): \n from .models import ActionLog\n \n action_log = ActionLog(\n user_id=user.id,\n user_username = user.username,\n perfipheral_pin = action_data.pin,\n perfipheral_name = action_data.name,\n perfipheral_type_id = action_data.peripheral_type.id,\n perfipheral_type_name = action_data.peripheral_type.name,\n perfipheral_created_at = action_data.created_at \n ).save()\n\n return action_log","sub_path":"apps/peripherals/managers.py","file_name":"managers.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"539363471","text":"#\n# A prime is a positive integer X that has exactly two distinct divisors: 1 and X.\n# The first few prime integers are 2, 3, 5, 7, 11 and 13.\n#\n# A prime D is called a prime divisor of a positive integer P if there exists a positive\n# integer K such that D * K = P. For example, 2 and 5 are prime divisors of 20.\n#\n# You are given two positive integers N and M. The goal is to check whether the\n# sets of prime divisors of integers N and M are exactly the same.\n#\n# For example, given:\n#\n# N = 15 and M = 75, the prime divisors are the same: 3, 5;\n# N = 10 and M = 30, the prime divisors aren't the same: 2, 5 is not equal to 2, 3, 5;\n# N = 9 and M = 5, the prime divisors aren't the same: 3 is not equal to 5.\n# Write a function:\n#\n# def solution(A, BArray)\n#\n# that, given two non-empty arrays A and B of Z integers, returns the number of\n# positions K for which the prime divisors of A[K] and B[K] are exactly the same.\n#\n# For example, given:\n#\n# A[0] = 15 B[0] = 75\n# A[1] = 10 B[1] = 30\n# A[2] = 3 B[2] = 5\n# the function should return 1, because only one pair (15, 75) has the same set of prime divisors.\n#\n# Write an efficient algorithm for the following assumptions:\n#\n# Z is an integer within the range [1..6,000];\n# each element of arrays A, B is an integer within the range [1..2,147,483,647].\n#\ndef main():\n doIt([10], [30])\n doIt([15, 10, 3], [75, 30, 5])\n\n\ndef doIt(A, B):\n out(\"Answer : {}\".format( solution(A, B)))\n\ndef out(msg):\n print(msg)\n\ndef solution(A, B):\n if len(A) != len(B):\n return -1\n\n count = 0\n for i in range(0, len(A)):\n a = A[i]\n b = B[i]\n if a < 0:\n return -2\n\n if b < 0:\n return -3\n\n if hasSameFactors(a, b):\n count += 1\n\n return count\n\n\ndef hasSameFactors(a, b):\n # print(\"hasSameFactors a : b : $a : $b\")\n denom = commonDenomintor(a, b)\n return (factorOut(a, denom) and factorOut(b, denom))\n\n\ndef factorOut(N, denom):\n n = N\n newDenom = denom\n while n != 1:\n newDenom = commonDenomintor(n, newDenom)\n # print(\"n : denom : $n : $denom\")\n if newDenom == 1:\n break\n\n n = n / newDenom\n\n return n == 1\n\ndef commonDenomintor(a, b):\n remainder = a % b\n while remainder != 0:\n a = b\n b = remainder\n remainder = a % b\n\n return b\n\n\n\nmain()\n","sub_path":"C0dility/python/src/_0012_Euclidean_algorithm/CommonPrimeDivisors.py","file_name":"CommonPrimeDivisors.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"358643389","text":"'''\nTilengine python example:\n\tRaster effect to simulate depth with scroll strips and linescroll\n'''\n\nfrom tilengine import *\n\n# module variables\nframe = 0\nbasepos = 0\nspeed = 0\npos_background = [0, 0, 0, 0, 0, 0]\n\n# linear interpolation\ndef lerp (x, x0, x1, fx0, fx1):\n\treturn fx0 + (fx1 - fx0)*(x - x0)/(x1 - x0)\n\t\n# load layer assets and basic setup\ndef setup_layer(layer, name):\n\ttilemap = Tilemap.fromfile (name)\n\tlayer.set_map (tilemap)\n\ttln.set_background_color_tilemap (tilemap)\n\n# raster effect callback\ndef raster_effect (line):\n\tpos = -1\n\t\n\tif line == 0:\n\t\tpos = pos_background[0]\n\telif line == 32:\n\t\tpos = pos_background[1]\n\telif line == 48:\n\t\tpos = pos_background[2]\n\telif line == 64:\n\t\tpos = pos_background[3]\n\telif line == 112:\n\t\tpos = pos_background[4]\n\telif line >= 152:\n\t\tpos = lerp (line, 152,224, pos_background[4], pos_background[5])\n\t\t\n\tif pos != -1:\n\t\tbackground.set_position (pos, 0)\n\n\tif line == 0:\n\t\ttln.set_background_color (Color(28,0,140))\n\telif line == 144:\n\t\ttln.set_background_color (Color(0,128,238))\n\n# initialise\ntln = Engine.create (400,240,2,80,1)\nforeground = tln.layers[0]\nbackground = tln.layers[1]\n\n# setup layers\nsetup_layer (foreground, \"Sonic_md_fg1.tmx\")\nsetup_layer (background, \"Sonic_md_bg1.tmx\")\n\n# setup raster callback\nmy_raster_callback = raster_callback_function(raster_effect)\ntln.set_raster_callback (my_raster_callback)\n\n# main loop\nwindow = Window.create()\nwhile window.process():\n\n\t# process user input\n\tif window.get_input (INPUT_RIGHT):\n\t\tspeed = min(speed + 0.04, 1.0)\n\telif speed > 0:\n\t\tspeed = max(speed - 0.02, 0.0)\n\t\t \n\tif window.get_input (INPUT_LEFT):\n\t\tspeed = max(speed - 0.04, -1.0)\n\telif speed < 0:\n\t\tspeed = min(speed + 0.02, 0.0)\n\n\t# scroll\n\tbasepos += speed\n\tpos_foreground = basepos * 3\n\tforeground.set_position (pos_foreground, 0);\n\n\tpos_background[0] = basepos * 0.562\n\tpos_background[1] = basepos * 0.437\n\tpos_background[2] = basepos * 0.375\n\tpos_background[3] = basepos * 0.625\n\tpos_background[4] = basepos * 1.000\n\tpos_background[5] = basepos * 2.000\n\t\n\t# draw frame line by line doing raster effects\n\twindow.draw_frame (frame)\n\tframe += 1\n\t\ntln.delete()\n","sub_path":"bindings/python/platformer.py","file_name":"platformer.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"340562744","text":"#/usr/bin/python3\n\nfrom rich.console import Console\nfrom rich.progress import (\n BarColumn,\n DownloadColumn,\n TextColumn,\n TransferSpeedColumn,\n TimeRemainingColumn,\n Progress,\n TaskID,\n)\n\nconsole = Console(record=True)\n\nprogress = Progress(\n TextColumn(\"[bold blue]{task.fields[filename]}\", justify=\"right\"),\n BarColumn(bar_width=None),\n \"[progress.percentage]{task.percentage:>3.1f}%\",\n \"•\",\n DownloadColumn(),\n \"•\",\n TransferSpeedColumn(),\n \"•\",\n TimeRemainingColumn(),\n console=console,\n)","sub_path":"authority_reconciliation/wikidata_name_game/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"388118472","text":"name = '???'\ncount = 0\n\n\nwhile name[0] != '김' and name[0] !='최' and name[0] != '이' and count < 5 :\n name = input(\"이름을 입력하세요 : \")\n count = count + 1\n\n\nif count == 5 :\n print(\"5회 까지 입력 가능합니다\")\nelse :\n print(\"성이 김, 최, 이 중에 있네요\")\n","sub_path":"kmooc/week5/5주차_01_05.py","file_name":"5주차_01_05.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"617815362","text":"import matplotlib.image as mpimg\nimport io\nimport numpy as np\n\nfrom detector import Detector\n\n\nclass NNFacade():\n \n def __init__(self):\n pass\n \n def execute(self, message, draw=False):\n \n train = True if len(message) == 4 else False\n \n image = NNConnector.fileToImage(message[0])\n gtKeyPoints = NNConnector.byteToKPs(message[1])\n cvKeyPoints = NNConnector.byteToKPs(message[2])\n \n test_pts = Detector(image, gtKeyPoints, cvKeyPoints, train) \n return np.array2string(test_pts(draw))\n \n \n\nclass NNConnector():\n \n def byteToImage(dimensions, encodedImage):\n dims = np.array(dimensions.decode().split(','), dtype=int)\n image = Image.frombytes('RGBA',(dims[0], dims[1]),encodedImage, 'raw')\n return image\n \n def fileToImage(filename):\n image = mpimg.imread(filename)\n return image\n \n def byteToKPs(keypoints, decodeType=None):\n \n if decodeType is None:\n keypoints = keypoints.decode()\n else:\n keypoints = keypoints.decode(decodeType)\n \n KPs = keypoints.split(\"\\n\")\n KPs = KPs if KPs[-1] else KPs[:-1]\n \n finalKPs = np.zeros((len(KPs), 2))\n for i, kp in enumerate(KPs):\n finalKPs[i] = np.array(kp.split(','))\n \n return finalKPs","sub_path":"v1/3D-Unity/ml-imagesynthesis/Assets/Python/NeuralNetwork.py","file_name":"NeuralNetwork.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"111409790","text":"import numpy as np\nfrom docx import Document\nimport os\nimport random\n\ndef get_para_data(output_doc_name, paragraph):\n output_para = output_doc_name.add_paragraph()\n for run in paragraph.runs:\n output_run = output_para.add_run(run.text)\n output_run.bold = run.bold\n output_run.italic = run.italic\n output_run.underline = run.underline\n output_run.font.color.rgb = run.font.color.rgb\n output_run.style.name = run.style.name\n output_para.paragraph_format.alignment = paragraph.paragraph_format.alignment\n\ndef delete_paragraph(paragraph):\n p = paragraph._element\n p.getparent().remove(p)\n p._p = p._element = None\n\n\n\ndef remove_empty_lines(filename):\n if not os.path.isfile(filename):\n print(\"{} does not exist \".format(filename))\n return\n with open(filename) as filehandle:\n lines = filehandle.readlines()\n\n with open(filename, 'w') as filehandle:\n lines = filter(lambda x: x.strip(), lines)\n filehandle.writelines(lines)\n\n\nloadfolder = '/Users/ivanov/Yandex.Disk.localized/PhD/Физика металлов/2019/Задачи РГЗ'\nsavefolder = '/Users/ivanov/Yandex.Disk.localized/PhD/Физика металлов/2019/Варианты РГЗ'\n\n\ntaskslist = []\nfor file in os.listdir(loadfolder):\n if file.endswith(\".docx\"):\n taskslist.append(file)\ntaskslist.sort()\nprint (taskslist)\n\nfirst_doc = Document(os.path.join(loadfolder, taskslist[0]))\nsecond_doc = Document(os.path.join(loadfolder, taskslist[1]))\nthird_doc = Document(os.path.join(loadfolder, taskslist[2]))\nfourth_doc = Document(os.path.join(loadfolder, taskslist[3]))\nfifth_doc = Document(os.path.join(loadfolder, taskslist[4]))\n\n\noutput_doc = Document()\n\n\nfirst_tasks = 6\nsecond_tasks = 7\nthird_tasks = 7\nfourth_tasks = 7\nfifth_tasks = 5\n\nfirst_tasks_list = np.arange(1, first_tasks+1, 1)\nsecond_tasks_list = np.arange(1, second_tasks+1, 1)\nthird_tasks_list = np.arange(1, third_tasks+1, 1)\nfourth_tasks_list = np.arange(1, fourth_tasks+1, 1)\nfifth_tasks_list = np.arange(1, fifth_tasks+1, 1)\n\n\nfor i in range(50):\n ai = first_tasks_list[(i)%len(first_tasks_list)]\n bi = second_tasks_list[(i+random.randrange(-7, 7, 1)) % len(second_tasks_list)]\n ci = third_tasks_list[(i + random.randrange(-7, 7, 1)) % len(third_tasks_list)]\n di = fourth_tasks_list[(i + random.randrange(-7, 7, 1)) % len(fourth_tasks_list)]\n ei = fifth_tasks_list[(i) % len(fifth_tasks_list)]\n\n '''\n get_para_data(output_doc, first_doc.paragraphs[ai])\n get_para_data(output_doc, second_doc.paragraphs[bi])\n get_para_data(output_doc, third_doc.paragraphs[ci])\n get_para_data(output_doc, fourth_doc.paragraphs[di])\n get_para_data(output_doc, fifth_doc.paragraphs[ei])\n\n filename = '%s.docx'%(i+1)\n #savefile = os.path.join(savefolder, filename)\n #output_doc.save(savefile)\n\n #delete_paragraph(first_doc.paragraphs[ai])\n #delete_paragraph(second_doc.paragraphs[bi])\n #delete_paragraph(third_doc.paragraphs[ci])\n #delete_paragraph(fourth_doc.paragraphs[di])\n #delete_paragraph(fifth_doc.paragraphs[ei])\n '''\n print ('%s.'%(i+1), ai, bi, ci, di, ei)\n\n'''\n#correction\nfilelist = []\nfor file in os.listdir(savefolder):\n if file.endswith(\".docx\"):\n filelist.append(file)\nfilelist.sort()\nprint (filelist)\n\nfor i, file in enumerate(filelist):\n task_doc = Document(os.path.join(savefolder, filelist[i]))\n\n for j in range(5*i):\n k = j\n task_doc.paragraphs[j].clear()\n filename = '%s.docx' % (i + 1)\n savefile = os.path.join(savefolder, filename)\n task_doc.save(savefile)\n\n\nfor i, file in enumerate(filelist):\n task_doc = Document(os.path.join(savefolder, filelist[i]))\n\n for paragraph in task_doc.paragraphs:\n if len(paragraph.text) == 0:\n delete_paragraph(paragraph)\n filename = '%s.docx' % (i + 1)\n savefile = os.path.join(savefolder, filename)\n task_doc.save(savefile)\n'''\n\n\n","sub_path":"list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":3952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"329779419","text":"from django import forms\nfrom django.core.exceptions import ValidationError\n\n\ndef words_validators(comment):\n if len(comment) < 4 :\n raise ValidationError('not enough words!')\n\n\n\ndef comment_validators(comment):\n if '发票' in comment or '钱' in comment:\n raise ValidationError('You comment contains invalid words,please check it again.')\n\n\nclass CommentForm(forms.Form):\n name = forms.CharField(max_length=50)\n comment = forms.CharField(\n widget=forms.Textarea(),\n error_messages={\n 'requied': 'please write something'\n },\n validators=[comment_validators,words_validators]\n )\n\n","sub_path":"前端第二课:Django/LessonFiveHomework/firstapp/form.py","file_name":"form.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"281369126","text":"\"\"\"This module contains async actions used to interact\nwith the crawl results cache via the service's API.\n\"\"\"\n\nimport base64\nimport hashlib\nimport httplib\nimport json\nimport logging\n\nimport tornado.httpclient\n\nimport async_actions\nimport crawl_results_cache\nimport crawl_results_cache.jsonschemas\n\n_logger = logging.getLogger(__name__)\n\n\ndef generate_crawl_results_id(docker_image_name, spider_name, crawl_args):\n \"\"\"Given a docker image name, a spider name and the arguments to\n a crawl of the spider, compute the unique ID for the associated\n crawl results.\n \"\"\"\n hash_input = '%s|%s|%s' % (\n docker_image_name,\n spider_name,\n '|'.join(crawl_args),\n )\n return hashlib.sha1(hash_input).hexdigest()\n\n\nclass AsyncAction(async_actions.AsyncAction):\n \"\"\"Abstract base class for all async actions.\"\"\"\n\n def create_log_msg_for_crawl_results_cache_http_client_response(self, response):\n return self.create_log_msg_for_http_client_response(response, 'Crawl Results Cache')\n\n\nclass AsyncReadCrawlResults(AsyncAction):\n \"\"\"Async wrapper around crawl results cache API to read\n crawl results from the cache.\n \"\"\"\n\n # FD = Failure Details\n FD_OK = 0x0000\n FD_ERROR = 0x0080\n FD_ERROR_READING = FD_ERROR | 0x0001\n FD_ERROR_UNEXPECTED_RESPONSE = FD_ERROR | 0x0002\n FD_ERROR_BASE64_DECODING = FD_ERROR | 0x0003\n\n def __init__(self, crawl_results_id, async_state=None):\n AsyncAction.__init__(self, async_state)\n\n self.crawl_results_id = crawl_results_id\n\n self.failure_detail = None\n\n self._callback = None\n\n def read(self, callback):\n assert self._callback is None\n self._callback = callback\n\n msg_fmt = \"Reading crawl results '%s'\"\n _logger.info(msg_fmt, self.crawl_results_id)\n\n url = '%s/%s/crawl_results/%s' % (\n self.config.base_crawl_results_cache_service_url,\n crawl_results_cache.__api_version__,\n self.crawl_results_id,\n )\n\n request = tornado.httpclient.HTTPRequest(url)\n\n http_client = tornado.httpclient.AsyncHTTPClient()\n http_client.fetch(\n request,\n callback=self._on_http_client_fetch_done)\n\n def _on_http_client_fetch_done(self, response):\n _logger.info(self.create_log_msg_for_crawl_results_cache_http_client_response(response))\n\n if response.code not in (httplib.OK, httplib.NOT_FOUND):\n msg_fmt = \"Reading crawl results for '%s' failed\"\n _logger.error(msg_fmt, self.crawl_results_id)\n\n self._call_callback(type(self).FD_ERROR_READING)\n return\n\n if response.code == httplib.NOT_FOUND:\n msg_fmt = \"Reading crawl results for '%s' did not find any crawl results\"\n _logger.info(msg_fmt, self.crawl_results_id)\n\n self._call_callback(type(self).FD_OK)\n return\n\n json_response_body = self.get_json_response_body(\n response,\n crawl_results_cache.jsonschemas.get_crawl_results_response)\n if json_response_body is None:\n msg_fmt = \"Reading crawl results for '%s' got unexpected response from crawl results cache\"\n _logger.error(msg_fmt, self.crawl_results_id)\n\n self._call_callback(type(self).FD_ERROR_UNEXPECTED_RESPONSE)\n return\n\n base64_encoded_crawl_results = json_response_body['base64_encoded_crawl_results']\n try:\n crawl_results = json.loads(base64.b64decode(base64_encoded_crawl_results))\n except Exception:\n msg_fmt = \"Reading crawl results for '%s' encountered error base 64 & json decoding crawl results\"\n _logger.error(msg_fmt, self.crawl_results_id)\n\n self._call_callback(type(self).FD_ERROR_BASE64_DECODING)\n return\n\n msg_fmt = \"Reading crawl results for '%s' completed successfully\"\n _logger.info(msg_fmt, self.crawl_results_id)\n\n self._call_callback(type(self).FD_OK, crawl_results)\n\n def _call_callback(self, failure_detail, crawl_results=None):\n assert self._callback is not None\n assert self.failure_detail is None\n self.failure_detail = failure_detail\n is_ok = not bool(self.failure_detail & type(self).FD_ERROR)\n self._callback(is_ok, crawl_results if is_ok else None, self)\n self._callback = None\n\n\nclass AsyncWriteCrawlResults(AsyncAction):\n \"\"\"Async wrapper around crawl results cache\n API to write crawl results to the cache.\n \"\"\"\n\n # FD = Failure Details\n FD_OK = 0x0000\n FD_ERROR = 0x0080\n FD_ERROR_WRITING = FD_ERROR | 0x0001\n\n def __init__(self,\n crawl_results_id,\n crawl_results,\n ttl_in_seconds,\n async_state=None):\n AsyncAction.__init__(self, async_state)\n\n self.crawl_results_id = crawl_results_id\n self.crawl_results = crawl_results\n self.ttl_in_seconds = ttl_in_seconds\n\n self.failure_detail = None\n\n self._callback = None\n\n def write(self, callback):\n assert self._callback is None\n self._callback = callback\n\n msg_fmt = \"Writing crawl results '%s'\"\n _logger.info(msg_fmt, self.crawl_results_id)\n\n url = '%s/%s/crawl_results/%s' % (\n self.config.base_crawl_results_cache_service_url,\n crawl_results_cache.__api_version__,\n self.crawl_results_id,\n )\n\n headers = {\n 'Content-Type': 'application/json; charset=utf-8',\n }\n\n body = {\n 'base64_encoded_crawl_results': base64.b64encode(json.dumps(self.crawl_results)),\n 'ttl_in_seconds': self.ttl_in_seconds,\n }\n\n request = tornado.httpclient.HTTPRequest(\n url,\n method='PUT',\n headers=headers,\n body=json.dumps(body))\n\n http_client = tornado.httpclient.AsyncHTTPClient()\n http_client.fetch(\n request,\n callback=self._on_http_client_fetch_done)\n\n def _on_http_client_fetch_done(self, response):\n _logger.info(self.create_log_msg_for_crawl_results_cache_http_client_response(response))\n\n if response.code != httplib.OK:\n msg_fmt = \"Writing crawl results for '%s' failed\"\n _logger.error(msg_fmt, self.crawl_results_id)\n\n self._call_callback(type(self).FD_ERROR_WRITING)\n return\n\n msg_fmt = \"Writing crawl results for '%s' succeeded\"\n _logger.info(msg_fmt, self.crawl_results_id)\n\n self._call_callback(type(self).FD_OK)\n\n def _call_callback(self, failure_detail):\n assert self._callback is not None\n assert self.failure_detail is None\n self.failure_detail = failure_detail\n is_ok = not bool(self.failure_detail & type(self).FD_ERROR)\n self._callback(is_ok, self)\n self._callback = None\n","sub_path":"cloudfeaster_services/crawl_results_cache_async_actions.py","file_name":"crawl_results_cache_async_actions.py","file_ext":"py","file_size_in_byte":6908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"48199994","text":"def non_unique(a):\n b = []\n for i in a:\n if a.count(i) > 1:\n b.append(i)\n return b\n\n\nif __name__ == '__main__':\n assert list(non_unique([1, 2, 3, 1, 3])) == [1, 3, 1, 3], \"1st example\"\n assert list(non_unique([1, 2, 3, 4, 5])) == [], \"2nd example\"\n assert list(non_unique([5, 5, 5, 5, 5])) == [5, 5, 5, 5, 5], \"3rd example\"\n assert list(non_unique([10, 9, 10, 10, 9, 8])) == [\n 10, 9, 10, 10, 9], \"4th example\"\n print(\"It is all good. Let's check it now\")\n","sub_path":"non-unique.py","file_name":"non-unique.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"43504658","text":"#!/usr/bin/python 3\nimport time\nimport random\n\nprint(\"THT-Gorkem63 Tarafindan Kodlandi\")\ntime.sleep(3)\n\nprint(\"-Sayi Tahmin Oyunu-\")\ntime.sleep(2)\n\nrnd_int = random.randint(1,100)\n\nwhile True:\n\tentry = int(input(\"Lutfen 1 den 100 e Kadar Bir Sayi Giriniz:\"))\n\tif (entry == rnd_int):\n\t\tprint(\"Bravo! Sansli Sayiyi Buldun :)\")\n\t\tbreak\n\telif (entry < rnd_int):\n\t\tprint (\"Lutfen Daha Yuksek Sayi Giriniz\")\n\telif (entry > rnd_int):\n\t\tprint (\"Lutfen Daha Dusuk Sayi Giriniz\")\n\telse:\n\t\tprint(\"Lutfen Belirtilen Araliklarda Sayi Giriniz!\")\n\n","sub_path":"hafta1.py","file_name":"hafta1.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"630932742","text":"a =[int(i) for i in input().split()]\nb = []\nfor i in range(len(a)):\n if (len(a) == 1):\n b = a\n elif (i == (len(a)-1)):\n b.append(a[i-1] + a[0])\n else:\n b.append(a[i-1] + a[i+1])\n\nfor j in range(len(b)):\n print(b[j], end=' ')\n\n\n# Оптимальное решение без обособления последнего варианта\n# a=[int(i) for i in input().split()]\n# if len(a)>1:\n# for i in range(len(a)):\n# print(a[i-1]+a[i+1-len(a)], end=' ')\n# else:\n# print(a[0], end=' ')","sub_path":"block_2/task_9.py","file_name":"task_9.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"125124971","text":"# 필요한 패키지들\n\nfrom glob import glob\nfrom datetime import datetime\n# PIL는 이미지를 load 할 때, numpy는 array\nfrom PIL import Image\nimport numpy as np\n\nimport tensorflow as tf\n\ntrain_list = glob('E:\\\\LEGO\\\\train\\\\*\\\\*.png')\ntest_list = glob('E:\\\\LEGO\\\\test\\\\*\\\\*.png')\n\n\nlearning_rate = 1e-3 # 학습 주기\nbatch_size = 50 # 학습당 학습량\ndata_size = len(train_list)\nnum_epochs = 50\n\ndef get_label_from_path(path):\n\n return path.split('\\\\')[-2]\n\ndef read_image(path):\n image = np.array(Image.open(path).convert('L'))\n # Channel 1을 살려주기 위해 reshape 해줌\n return image.reshape([image.shape[0], image.shape[1], 1])\n\n# 앞서 만들었던 get_label_from_path 함수를 통해 data_list에 있는 label 이름들을 list에 다 묶어준다\n# 더 쉬운 방법이 있지만, 굳이 함수를 통해 label 들을 얻는 것은 함수도 잘 작동하는지 확인함을 목적을 가지고 있다.\n\ndef onehot_encode_label(path, unique_label_names):\n onehot_label = unique_label_names == get_label_from_path(path)\n onehot_label = onehot_label.astype(np.uint8)\n return onehot_label\n\n\ndef _read_py_function(path, label):\n image = read_image(path)\n label = np.array(label, dtype=np.uint8)\n return image.astype(np.int32), label\n\ndef _random_function(image_decoded, label):\n image_decoded.set_shape([None, None, None])\n image = tf.image.resize_images(image_decoded, [200, 200])\n image = tf.image.random_flip_left_right(image)\n image = tf.image.random_flip_up_down(image)\n image = tf.image.random_brightness(image, max_delta=0.5)\n image = tf.image.random_contrast(image, lower=0.2, upper=2.0)\n return image, label\n\ndef made_train_batch(data_path):\n label_name_list = []\n for path in data_path:\n label_name_list.append(get_label_from_path(path))\n\n unique_label_names = np.unique(label_name_list)\n\n # label을 array 통채로 넣는게 아니고, list 화 시켜서 하나씩 넣기 위해 list로 바꿔주었다.\n label_list = [onehot_encode_label(path,unique_label_names).tolist() for path in data_path]\n\n dataset = tf.data.Dataset.from_tensor_slices((data_path, label_list))\n dataset = dataset.map(\n lambda data_list, label_list: tuple(\n tf.py_func(_read_py_function, [data_list, label_list], [tf.int32, tf.uint8])))\n\n dataset = dataset.map(_random_function)\n dataset = dataset.repeat()\n dataset = dataset.shuffle(buffer_size=(int(len(data_path) * 0.4) + 3 * batch_size))\n dataset = dataset.batch(batch_size)\n\n return dataset\n\n\ndef made_test_batch(data_path):\n label_name_list = []\n for path in data_path:\n label_name_list.append(get_label_from_path(path))\n\n unique_label_names = np.unique(label_name_list)\n\n # label을 array 통채로 넣는게 아니고, list 화 시켜서 하나씩 넣기 위해 list로 바꿔주었다.\n label_list = [onehot_encode_label(path, unique_label_names).tolist() for path in data_path]\n\n dataset = tf.data.Dataset.from_tensor_slices((data_path, label_list))\n dataset = dataset.map(\n lambda data_list, label_list: tuple(\n tf.py_func(_read_py_function, [data_list, label_list], [tf.int32, tf.uint8])))\n\n dataset = dataset.repeat()\n dataset = dataset.shuffle(buffer_size=(int(len(data_path) * 0.4) + 3 * 1))\n dataset = dataset.batch(1)\n\n return dataset\n\n# convolutional network layer 1\ndef conv1(input_data):\n # layer 1 (convolutional layer)\n with tf.name_scope('conv_1'):\n W_conv1 = tf.Variable(tf.truncated_normal([5, 5, 1, 128], stddev=5e-2))\n b1 = tf.Variable(tf.truncated_normal([128], stddev=0.1))\n h_conv1 = tf.nn.conv2d(input_data, W_conv1, strides=[1, 1, 1, 1], padding='SAME')\n h_conv1_relu = tf.nn.relu(tf.add(h_conv1, b1))\n h_conv1_maxpool = tf.nn.max_pool(h_conv1_relu, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n\n return h_conv1_maxpool\n\n# convolutional network layer 2\ndef conv2(input_data):\n\n with tf.name_scope('conv_2'):\n W_conv2 = tf.Variable(tf.truncated_normal([5, 5, 128, 256], stddev=5e-2))\n b2 = tf.Variable(tf.truncated_normal([256], stddev=0.1))\n h_conv2 = tf.nn.conv2d(input_data, W_conv2, strides=[1, 1, 1, 1], padding='SAME')\n h_conv2_relu = tf.nn.relu(tf.add(h_conv2, b2))\n h_conv2_maxpool = tf.nn.max_pool(h_conv2_relu, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n\n return h_conv2_maxpool\n\n# convolutional network layer 3\ndef conv3(input_data):\n print('## FLAGS.stride1 ', 1)\n with tf.name_scope('conv_3'):\n W_conv3 = tf.Variable(tf.truncated_normal([3, 3, 256, 512], stddev=5e-2))\n b3 = tf.Variable(tf.truncated_normal([512], stddev=0.1))\n h_conv3 = tf.nn.conv2d(input_data, W_conv3, strides=[1, 1, 1, 1], padding='SAME')\n h_conv3_relu = tf.nn.relu(tf.add(h_conv3, b3))\n h_conv3_maxpool = tf.nn.max_pool(h_conv3_relu, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n\n return h_conv3_maxpool\n\n# convolutional network layer 3\ndef conv4(input_data):\n\n with tf.name_scope('conv_4'):\n W_conv4 = tf.Variable(tf.truncated_normal([3, 3, 512, 512], stddev=5e-2))\n b4 = tf.Variable(tf.truncated_normal([512], stddev=0.1))\n h_conv4 = tf.nn.conv2d(input_data, W_conv4, strides=[1, 1, 1, 1], padding='SAME')\n h_conv4_relu = tf.nn.relu(tf.add(h_conv4, b4))\n h_conv4_maxpool = tf.nn.max_pool(h_conv4_relu, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n\n return h_conv4_maxpool\n# fully connected layer 1\ndef fc1(input_data):\n input_layer_size = 13 * 13 * 512\n\n with tf.name_scope('fc_1'):\n # 앞에서 입력받은 다차원 텐서를 fcc에 넣기 위해서 1차원으로 피는 작업\n input_data_reshape = tf.reshape(input_data, [-1, input_layer_size])\n W_fc1 = tf.Variable(tf.truncated_normal([input_layer_size, 512], stddev=5e-2))\n b_fc1 = tf.Variable(tf.truncated_normal([512], stddev=0.1))\n h_fc1 = tf.add(tf.matmul(input_data_reshape, W_fc1), b_fc1) # h_fc1 = input_data*W_fc1 + b_fc1\n h_fc1_relu = tf.nn.relu(h_fc1)\n\n return h_fc1_relu\n\n\n# fully connected layer 2\ndef fc2(input_data):\n\n with tf.name_scope('fc_2'):\n W_fc2 = tf.Variable(tf.truncated_normal([512, 256], stddev=5e-2))\n b_fc2 = tf.Variable(tf.truncated_normal([256], stddev=0.1))\n h_fc2 = tf.add(tf.matmul(input_data, W_fc2), b_fc2) # h_fc1 = input_data*W_fc1 + b_fc1\n h_fc2_relu = tf.nn.relu(h_fc2)\n\n return h_fc2_relu\n\n\n# final layer\ndef final_out(input_data):\n with tf.name_scope('final_out'):\n W_fo = tf.Variable(tf.truncated_normal([256, 4], stddev=5e-2))\n b_fo = tf.Variable(tf.truncated_normal([4], stddev=0.1))\n h_fo = tf.add(tf.matmul(input_data, W_fo), b_fo) # h_fc1 = input_data*W_fc1 + b_fc1\n\n # 최종 레이어에 softmax 함수는 적용하지 않았다.\n return h_fo\n\n\n# build cnn_graph\ndef build_model(images, keep_prob):\n # define CNN network graph\n # output shape will be (*,48,48,16)\n r_cnn1 = conv1(images) # convolutional layer 1\n print(\"shape after cnn1 \", r_cnn1.get_shape())\n\n # output shape will be (*,24,24,32)\n r_cnn2 = conv2(r_cnn1) # convolutional layer 2\n print(\"shape after cnn2 :\", r_cnn2.get_shape())\n\n # output shape will be (*,12,12,64)\n r_cnn3 = conv3(r_cnn2) # convolutional layer 3\n print(\"shape after cnn3 :\", r_cnn3.get_shape())\n\n # output shape will be (*,6,6,128)\n r_cnn4 = conv4(r_cnn3) # convolutional layer 4\n print(\"shape after cnn4 :\", r_cnn4.get_shape())\n\n # fully connected layer 1\n r_fc1 = fc1(r_cnn4)\n print(\"shape after fc1 :\", r_fc1.get_shape())\n r_dropout = tf.nn.dropout(r_fc1, keep_prob)\n # fully connected layer2\n r_fc2 = fc2(r_fc1)\n print(\"shape after fc2 :\", r_fc2.get_shape())\n\n ## drop out\n # 참고 http://stackoverflow.com/questions/34597316/why-input-is-scaled-in-tf-nn-dropout-in-tensorflow\n # 트레이닝시에는 keep_prob < 1.0 , Test 시에는 1.0으로 한다.\n r_dropout = tf.nn.dropout(r_fc2, keep_prob)\n print(\"shape after dropout :\", r_dropout.get_shape())\n\n # final layer\n r_out = final_out(r_dropout)\n print(\"shape after final layer :\", r_out.get_shape())\n\n return r_out\n\nX = tf.placeholder(tf.float32, shape=[None, 200, 200, 1])\nY = tf.placeholder(tf.float32, shape=[None, 4])\nkeep_prob = tf.placeholder(tf.float32)\niterator = made_train_batch(train_list).make_initializable_iterator()\ntest_iterator = made_train_batch(test_list).make_initializable_iterator()\n\nprediction = build_model(X, keep_prob)\n# define loss function\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=Y))\n\ntrain = tf.train.AdamOptimizer(learning_rate).minimize(cost)\nlabel_max = tf.argmax(Y, 1)\npre_max = tf.argmax(prediction, 1)\ncorrect_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\nstartTime = datetime.now()\ntrain_next = iterator.get_next()\ntest_next = test_iterator.get_next()\nwith tf.Session() as sess:\n\n sess.run(iterator.initializer)\n sess.run(test_iterator.initializer)\n sess.run(tf.global_variables_initializer())\n saver = tf.train.Saver() # create saver to store training model into file\n\n for step in range(num_epochs):\n avg_cost = 0\n for x in range(int(data_size/batch_size)):\n x_data, y_data = sess.run(train_next)\n cost_val, _ = sess.run([cost, train], feed_dict={X: x_data, Y: y_data, keep_prob: 0.7})\n avg_cost += cost_val / int(data_size/batch_size)\n print(x)\n if(x%4 == 0 ):\n validate_images_, validate_labels_ = sess.run(test_next)\n rv = sess.run([label_max, pre_max, cost, accuracy], feed_dict={X: validate_images_\n , Y: validate_labels_\n , keep_prob: 1.0})\n print('Validation cost:', rv[2], ' accuracy:', rv[3])\n\n now = datetime.now() - startTime\n\n print('step: ', step, 'cost_val : ', avg_cost, 'time', now)\n saver.save(sess, 'E:\\\\LEGO\\\\lego3') # save session\n","sub_path":"Lego/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":10181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"81755715","text":"from lxml import html\r\nimport requests\r\nimport pandas as pd\r\nimport sys\r\n\r\nclass AppCrawler:\r\n def __init__(self, starting_url):\r\n self.starting_url = starting_url\r\n self.apps = []\r\n\r\n def crawl(self):\r\n name, price = self.get_app_from_link(self.starting_url)\r\n return name, price\r\n\r\n def get_app_from_link(self, link):\r\n start_page = requests.get(link)\r\n tree = html.fromstring(start_page.text)\r\n# print(len(tree.xpath('//h1[@class=\"stock-profile f16\"]/text()')))\r\n if len(tree.xpath('//h1[@class=\"stock-profile f16\"]/text()')) > 0:\r\n name = tree.xpath('//h1[@class=\"stock-profile f16\"]/text()')[0]\r\n price = tree.xpath('//td[@id=\"slcontent_0_ileft_0_lastdonetext\"]/text()')[0]\r\n else:\r\n name = \"\"\r\n price = 0\r\n\r\n# code = tree.xpath('//li[@class=\"f14\"]/text()')[1]\r\n\r\n# print(name, price)\r\n# print(code[3:])\r\n# print(price)\r\n\r\n return name, price\r\n\r\nclass App:\r\n\r\n def __init__(self, name, code, price, links):\r\n self.name = name\r\n self.code = code\r\n self.price = price\r\n self.links = links\r\n\r\n def __str__(self):\r\n return (\"Name: \" + self.name.encode('UTF-8') +\r\n \"\\r\\nPrice: \" + self.price.encode('UTF-8') + \"\\r\\n\")\r\n\r\n\r\ncompanies = pd.read_csv('Stocks.csv')\r\n#print(companies.info())\r\nurl = \"https://www.thestar.com.my/business/marketwatch/stocks/?qcounter=\"\r\n#c = 0\r\ndata = pd.read_csv('RawData.csv')\r\ncolname = data.columns.values\r\nnewData = [\"\"] * (companies.shape[0] + 1)\r\nnewData[0]=pd.Timestamp.today()\r\n#print(pd.Timestamp.today())\r\n#print(data.info())\r\nfor i in range(companies.shape[0]):\r\n# c += 1\r\n# if c == 21: break\r\n if i % 10 == 0:\r\n sys.stdout.write(str(i))\r\n else:\r\n sys.stdout.write('.')\r\n crawler = AppCrawler(url+companies.iloc[i][0])\r\n _ , price = crawler.crawl()\r\n newData[i+1] = str(price)\r\n#print(len(newData))\r\ndata.loc[len(data)] = newData\r\n#print(data.iloc[0][0:55])\r\ndata.to_csv('RawData.csv',index=False)\r\n#for app in crawler.apps:\r\n# print(\"xxx\",app)\r\n","sub_path":"Python codes/week1/stock_crawl.py","file_name":"stock_crawl.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"636068464","text":"import numpy as np\nimport pytest\nfrom simulator.linalg import solve_mod_2\nfrom utils import bitstrings\n\n\ndef test_solve_mod_2_easy():\n A = [[0, 1], [1, 1]]\n b = [1, 1]\n assert np.array_equal(solve_mod_2(A, b), [0, 1])\n\n A = [[1], [1]]\n b = [1, 1]\n assert np.array_equal(solve_mod_2(A, b), [1])\n\n b = [1, 0]\n assert solve_mod_2(A, b) is None\n\n\ndef test_solve_mod_2_many():\n n = 5\n for a1 in bitstrings(n):\n for a2 in bitstrings(n):\n # skip linearly dependent case\n a1 = np.array(a1)\n a2 = np.array(a2)\n if not (a1.any() and a2.any() and (a1 != a2).any()):\n continue\n\n # solve full rank linear system Ax = b (of size 5x2) for all possible x\n A = np.array([a1, a2]).T\n for x in bitstrings(2):\n b = (A @ x) % 2\n assert np.array_equal(solve_mod_2(A, b), x)\n","sub_path":"test/unit/test_linalg.py","file_name":"test_linalg.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"553154176","text":"import unittest\nfrom flask import current_app\nfrom app import create_app, db\nfrom app.services.models.patient import Patient\nfrom app.services.models.service import Service\nfrom app.services.models.serviceOrder import ServiceOrder\nfrom app.services.models.servicePayment import ServicePayment\nfrom app.services.models.session import Session, SessionStates, SessionState\nfrom app.services.models.user import User, Doctor\nimport datetime\n\nclass TestSessionStates(unittest.TestCase):\n def setUp(self):\n # new patient \n pass\n\n def tearDown(self):\n ServicePayment.query.delete()\n ServiceOrder.query.delete()\n Patient.query.delete()\n Service.query.delete()\n User.query.delete()\n ServiceOrder.query.delete()\n ServicePayment.query.delete()\n db.session.commit()\n\n # @unittest.skip('not implemented yet')\n def test_createdSessions_has_init_state(self):\n\n patient = Patient(name='patient one with order ', mobileNumber='11111')\n service = Service(name='service for orders x', price=150)\n doctor = Doctor(name='dr. xxxxxxyy', userName='dirkdjf lkdjf l', password='1212121212')\n\n sessions = [Session(), Session(), Session()]\n\n order = ServiceOrder(patient=patient, service=service, sessions=sessions, numberOfSessions=3)\n\n # db.session.add(order)\n # db.session.commit()\n\n for session in order.sessions:\n self.assertEquals(SessionStates.initial, session.state)\n self.assertEquals(session.states.count('id'), 0)\n session.arrived(doctor, notes='this is notes about the arrival state for session ')\n\n self.assertEquals(order.numberOfSessions, 3)\n self.assertEquals(len(order.sessions), 3)\n\n def test_session_in_transition_state(self):\n\n patient = Patient(name='patient one with order ', mobileNumber='11111')\n service = Service(name='service for orders x', price=150)\n user = User(name='test user x', userName='testuserxxx', password='12121212')\n\n sessions = None\n order = ServiceOrder(patient=patient, service=service, sessions=sessions, numberOfSessions=5)\n\n # db.session.add(order)\n # db.session.commit()\n\n self.assertEquals(len(order.sessions), 5)\n\n for session in order.sessions:\n session.arrived(user)\n self.assertTrue(SessionStates.arrived, session.state)\n\n for session in order.sessions:\n session.start(user)\n self.assertTrue(SessionStates.started, session.state)\n self.assertTrue(session.inTransitionState())\n\n for session in order.sessions:\n session.done(user)\n self.assertTrue(SessionStates.done, session.state)\n self.assertFalse(session.inTransitionState())\n\n for session in order.sessions:\n session.states\n session.refund(user)\n self.assertTrue(SessionStates.refunded, session.state)\n self.assertFalse(session.inTransitionState())\n\n def test_refund_state(self):\n\n patient = Patient(name='patient one with order ', mobileNumber='11111')\n service = Service(name='service for orders x', price=150, estimatedTime=20)\n user = User(name='test user x', userName='testuserxxx', password='12121212')\n\n sessions = None\n payment = ServicePayment(amount=120, paymentType=1)\n order = ServiceOrder(patient=patient, service=service, sessions=sessions, numberOfSessions=5,\n payments=[payment])\n self.assertEquals(order.totalPayments, 120)\n\n self.assertTrue(order.refundable)\n\n for session in order.sessions:\n session.service = service\n session.arrived(user)\n self.assertTrue(SessionStates.arrived, session.state)\n\n for session in order.sessions:\n session.start(user)\n self.assertTrue(SessionStates.started, session.state)\n self.assertTrue(session.inTransitionState())\n\n for session in order.sessions:\n session.done(user)\n self.assertTrue(SessionStates.done, session.state)\n self.assertFalse(session.inTransitionState())\n\n order.refundOrder(amount=120, user=user)\n\n for session in order.sessions:\n self.assertEquals(SessionStates.refunded, session.state)\n self.assertFalse(session.inTransitionState())\n self.assertTrue(session.hasState(SessionStates.arrived))\n self.assertTrue(session.hasState(SessionStates.started))\n self.assertTrue(session.hasState(SessionStates.done))\n\n self.assertTrue(session.hasState(SessionStates.refunded))\n self.assertIsInstance( session.getState(SessionStates.done), SessionState )\n self.assertIsInstance( session.getState(SessionStates.done).issueDateTime, datetime.datetime )\n \n def test_sessionTransitionsPerformance(self):\n patient = Patient(name='patient one with order ', mobileNumber='11111')\n service = Service(name='service for orders x', price=150, estimatedTime=20)\n user = User(name='test user x', userName='testuserxxx', password='12121212')\n\n\n payment = ServicePayment(amount=120, paymentType=1)\n order = ServiceOrder(patient=patient, service=service, numberOfSessions=5,\n payments=[payment])\n\n session1 = order.sessions[0]\n session1.service = service\n\n session1.arrived(user)\n\n self.assertTrue(SessionStates.arrived, session1.state)\n\n self.assertIsInstance( session1.service, Service )\n self.assertIsInstance( session1.startDoneTimeDeviation, int )\n self.assertEquals(session1.startDoneTimeDeviation, 0)\n\n session1.start(user, issueDateTime=datetime.datetime.now() - datetime.timedelta(minutes=10) )\n session1.done(user, issueDateTime=datetime.datetime.now() )\n\n self.assertIsInstance( session1.startDoneTimeDeviation, int )\n self.assertEquals(session1.startDoneTimeDeviation, -10)\n self.assertEquals(session1.performanceRatio, 50)\n\n session2 = order.sessions[1]\n session2.service = service\n\n self.assertIsInstance( session2.startDoneTimeDeviation, int )\n self.assertEquals(session2.startDoneTimeDeviation, 0)\n\n session2.start(user, issueDateTime=datetime.datetime.now() - datetime.timedelta(minutes=30) )\n session2.done(user, issueDateTime=datetime.datetime.now() )\n\n self.assertIsInstance( session2.startDoneTimeDeviation, int )\n self.assertEquals(session2.startDoneTimeDeviation, 10)\n\n self.assertEquals(session2.performanceRatio, 150)\n\n\n","sub_path":"app/tests/sessions/testStates.py","file_name":"testStates.py","file_ext":"py","file_size_in_byte":6815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"59618707","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# __author__:\"MrZhu\"\n'''\n__introduce__\nWordRecognized\nmemory = session.service(\"ALMemory\")\nprint memory.getData(\"WordRecognized\")\n'''\n\n\n\"\"\"Example: Use ALSpeechRecognition Module\"\"\"\n\nimport qi\nimport argparse\nimport sys\nimport time\n\n\ndef main(session):\n audio_recorder = session.service(\"ALAudioRecorder\")\n\n audio_recorder.startMicrophonesRecording(\"/data/home/nao/nplus/MrZhu/pytest.wav\", \"wav\", 16000, (0,0,1,0))\n\n time.sleep(3)\n audio_recorder.stopMicrophonesRecording()\n\n\n\n\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--ip\", type=str, default=\"127.0.0.1\",\n help=\"Robot IP address. On robot or Local Naoqi: use '127.0.0.1'.\")\n parser.add_argument(\"--port\", type=int, default=9559,\n help=\"Naoqi port number\")\n\n args = parser.parse_args()\n session = qi.Session()\n try:\n session.connect(\"tcp://\" + args.ip + \":\" + str(args.port))\n except RuntimeError:\n print (\"Can't connect to Naoqi at ip \\\"\" + args.ip + \"\\\" on port \" + str(args.port) +\".\\n\"\n \"Please check your script arguments. Run with -h option for help.\")\n sys.exit(1)\n main(session)","sub_path":"untitled/venv/py2/pepper/Audio/soundget.py","file_name":"soundget.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"604767985","text":"\"\"\"Queries for retrieving, and updating, and inserting schemas\"\"\"\n\nfrom flask import current_app\n\nfrom stickel.db import db_connection\n\n\nclass GlobalQueries:\n\n def __init__(self):\n\n self.db = db_connection('globals')\n #self.db.connect_db()\n\n def select_email_data(self, email_name):\n \"\"\"\n Return the schema (json data) from the db\n :param email_name: string\n :return: json string\n \"\"\"\n #print email_name\n parameters = (email_name,)\n self.db.connect_db()\n db_data = self.db.select_single_param(\"SELECT `schema` FROM `emails` WHERE `name`=%s LIMIT 0,1\", parameters)\n self.db.connection_commit()\n self.db.cursor_close()\n #print 'select_email_data:'\n #print db_data\n if db_data == 'None' or db_data == None or db_data == '':\n return 'None'\n return db_data\n\n def update_schema(self, schema, email_name):\n \"\"\"\n Update the schema in emails table\n :param schema: json string\n :param email_name: string\n :return: 'ok'\n \"\"\"\n parameters = (schema, email_name,)\n self.db.connect_db()\n self.db.update_db_parameters(\"UPDATE `emails` SET `schema`=%s WHERE `name`=%s\", parameters)\n self.db.connection_commit()\n self.db.cursor_close()\n return 'ok'\n\n def insert_new_email(self, email_name):\n \"\"\"\n Insert new record if value does not exist.\n :param email_name: string\n :return: 'ok', or error message\n \"\"\"\n select_parameters = (email_name,)\n insert_parameters = (email_name,)\n select_qry = \"SELECT `id` FROM emails WHERE `name` = %s\"\n insert_qry = \"INSERT INTO emails (name, add_date) VALUES (%s, NOW())\"\n self.db.connect_db()\n output = self.db.insert_unique_db(select_qry, select_parameters, insert_qry, insert_parameters)\n self.db.connection_commit()\n self.db.cursor_close()\n if not output:\n return 'Error: name already exists.'\n else:\n return 'ok'\n","sub_path":"server/app/globals/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"513141531","text":"from django.conf.urls import include, url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.post_list),\n url(r'^post/(?P[0-9]+)/$', views.post_detail, name='post_detail'),\n # começa com ^ \"o início\" - post / significa apenas que após o começo, da URL deve ter a palavra post e /.\n # (?P[0-9]+)- Isso significa que o Django vai levar tudo que você colocar aqui e transferir para uma view como uma variável chamada pk. [0-9] também nos diz que só pode ser um número, não uma letra (tudo entre 0 e 9). + significa que precisa existir um ou mais dígitos.\n # se você digitar http://127.0.0.1:8000/post/5/ em seu navegador, Django vai entender que você está procurando uma view chamada post_detail e transferir a informação de que pk é igual a 5 para aquela view.\n # pk é uma abreviação para primary key (chave primária). Esse nome geralmente é usado nos projetos feitos em Django. Mas você pode dar o nome que quiser às variáveis (lembre-se: minúsculo e _ ao invés de espaços em branco!). Por exemplo: (?P[0-9]+).\n url(r'^post/new/$', views.post_new, name='post_new'),\n url(r'^post/(?P[0-9]+)/edit/$', views.post_edit, name='post_edit'),\n]","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"53146","text":"import os\nimport json\nfrom os import walk\nfrom Utils import Utils\nimport multiprocessing as mp\nimport random\nimport math\n\ndictionary_path = \"./dict\"\npool_size = 8 #mp.cpu_count()\nshared_dict = None\n\n\n\ndef sp_getDictionaries():\n refDicts = {}\n\t\n for (dirpath, dirnames, filenames) in walk('./referemce_dicts/json'):\n\t\n for filename in filenames:\n\t\t\t\n # Construct full path\n fullPath = dirpath + \"/\" + filename\n\t\t\n print(\"Loading \"+filename+\"...\")\n\n\t\t\t# Load reference dict\n data = json.load(open(fullPath, \"r\"))\n\n # Add dictionary item\n refDicts[filename.replace(\".txt\", \"\")] = data\n\t\t\t\t\t\n return refDicts\n\ndef sp_getTextDocument(path):\n\n\twords = Utils.testStripping(path)\n\tresult = {}\n\tfor word in words:\n\n\t\ttry:\n\t\t\tresult[word]\n\t\t\tresult[word] = result['word'] + 1\n\t\texcept:\n\t\t\tresult[word] = 1\n\n\treturn result\n\ndef sp_getTestData():\n\ttestData = []\n\n\t\t\n\t# Generate list of test data\n\tdocument_paths = [{\n\t\t'path': dictionary_path + \"/\" + x,\n\t\t'category': x\n\t} for x in os.listdir(dictionary_path)]\n\tfor document_path in document_paths:\n\t\ttestData.extend([{\n\t\t\t'path': document_path['path'] + \"/\" + doc,\n\t\t\t'category': document_path['category'],\n\t\t\t'text': sp_getTextDocument(document_path['path'] + \"/\" + doc)\n\t\t} for doc in os.listdir(document_path['path'])[901:]])\n\t\n\treturn testData\n\n\t\ndef mp_classify(params):\n\tid = random.random()\n\tdictionaries = params['dict']\n\tdocument = params['case']\n\t\n\tresult = {\n\t\t'category': document['category'],\n\t\t'path': document['path'],\n\t\t'probabilities': {}\n\t}\n\t\n\tfor (key, category_dict) in dictionaries.items():\n\t\t\n\t\t# Set initial probability\n\t\tresult['probabilities'][key] = 0\n\t\t\n\t\t# Count occurrences of word in category_dictionary\n\t\t\n\t\tp = math.log(0.05) # PH = #900 / (900 * 20)\n\t\t\n\t\t\n\t\t\n\t\tfor (word, occurrences) in document['text'].items():\n\t\t\t\n\t\n\t\t\ttry:\n\t\t\t\n\t\t\t\t# Try if word is in category_dictionary\n\t\t\t\tcategory_dict[word]\n\t\t\t\t\n\t\t\t\t# TODO, better way?\n\t\t\t\tfor i in range(occurrences):\n\t\t\t\t\tp += math.log(category_dict[word])\n\t\t\t\t\t\n\t\t\n\t\t\t\t\n\t\t\t\tprint(\"Word: \" + word + \" found \" + occurrences)\n\t\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t\t\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\n\t\t\t\t\n\t\tresult['probabilities'][key] = p\n\t\t\t\n\treturn result\n\n\ndef mp_start_process():\n print('Starting', mp.current_process().name)\n\t\n\t\ndef sp_handler():\n\ttestData = sp_getTestData()\n\trandom.shuffle(testData)\n\tdictionaries = sp_getDictionaries()\n\n\n\t\n\t# Prepare imap data\n\tparamData = [{\n\t\t'case': x,\n\t\t'dict': dictionaries\n\t} for x in testData]\n\t\n\tcorrect = 0\n\ttotal = 0\n\t\n\t\n\tfor param in paramData:\n\t\ttotal += 1\n\t\tdocument_result = mp_classify(param)\n\t\t\n\t\t# Order\n\t\tordered_prob = list(reversed(sorted(document_result['probabilities'].items(), key=lambda x:x[1])))\n\t\t\n\t\t\n\t\tif ordered_prob[0][0].replace(\".json\", \"\") == document_result['category']:\n\t\t\tcorrect += 1\n\t\t\n\t\tprint(ordered_prob[0][0].replace(\".json\", \"\") + \" == \" + document_result['category'] + \" | \" + str(correct) + \"/\" + str(total) + \" | \" + str((correct / total) * 100.0) + \"%\")\n\t\t\n\t\t\n\t\t#for i in ordered_prob:\n\t\t#\tprint(str(i[0]) + \": \" + str(i[1]))\n\t\n\t\n\t\n\treturn\n\t# Create process pool\n\tpool = mp.Pool(\n\t\tprocesses=pool_size,\n\t\t#initializer=mp_start_process\n\t)\n\t\n\tfor document_result in pool.imap_unordered(mp_classify, paramData):\n\t\ttotal += 1\n\t\n\t\t#print(\"-----------\")\n\t\t#print(\"Category: \" + document_result['category'])\n\t\t#print(\"Case: \" + document_result['path'])\n\t\t#print(\"-\")\n\t\t\n\t\t# Order\n\t\tordered_prob = list(reversed(sorted(document_result['probabilities'].items(), key=lambda x:x[1])))\n\t\t\n\t\t\n\t\tif ordered_prob[0][0].replace(\".json\", \"\") == document_result['category']:\n\t\t\tcorrect += 1\n\t\t\n\t\tprint(ordered_prob[0][0].replace(\".json\", \"\") + \" == \" + document_result['category'] + \" | \" + str(correct) + \"/\" + str(total) + \" | \" + str((correct / total) * 100.0) + \"%\")\n\t\t\n\t\t\n\t\t#for i in ordered_prob:\n\t\t#\tprint(str(i[0]) + \": \" + str(i[1]))\n\n\n\t\n\t\n\n\t\n\t\n\t\n\t\"\"\"\"future_results = [pool.apply_async(mp_classify, args=(dictionaries, x, random.random())) for x in testData]\n\tfor res in future_results:\n\t\tprint res.get()\n\t\n\t\tfor document_result in res.get():\n\t\t\tprint(\"-----------\")\n\t\t\tprint(\"Category: \" + document_result['category'])\n\t\t\tprint(\"Case: \" + document_result['path'])\n\t\t\tprint(\"-\")\n\t\t\t\n\t\t\t# Order\n\t\t\tordered_prob = reversed(sorted(document_result['probabilities'].items(), key=lambda x:x[1]))\n\t\t\tfor i in ordered_prob:\n\t\t\t\tprint(str(i[0]) + \": \" + str(i[1]))\n\t\"\"\"\n\t\n\n\t\t\n\t\t\n\n\n\t\"\"\"\"chunks = [testData[x:x+pool_size] for x in xrange(0, len(testData), pool_size)]\n\tfor testDataChunk in chunks:\t\n\t\tresults = [pool.apply_async(mp_classify, args=(dictionaries, x, random.random())) for x in testDataChunk]\n\t\tfinal_result = [p.get() for p in results]\n\t\t\n\t\tprint(\"Chunk Done!...\")\n\t\tfor document_result in final_result:\n\t\t\tprint(\"-----------\")\n\t\t\tprint(\"Category: \" + document_result['category'])\n\t\t\tprint(\"Case: \" + document_result['path'])\n\t\t\tprint(\"-\")\n\t\t\t\n\t\t\t# Order\n\t\t\tordered_prob = reversed(sorted(document_result['probabilities'].items(), key=lambda x:x[1]))\n\t\t\tfor i in ordered_prob:\n\t\t\t\tprint(str(i[0]) + \": \" + str(i[1]))\n\t\"\"\"\n\t\n\t\t\t\n\t\n\t\n\n\t\n\t\nif __name__ == '__main__':\n\tsp_handler()\n\n\n\n","sub_path":"Classify.py","file_name":"Classify.py","file_ext":"py","file_size_in_byte":5134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"238617342","text":"import numpy as np\nfrom RecarrayTools.ReadRecarray import ReadRecarray\nimport os\nfrom ..Tools.ResampleTimeSeries import ResampleTimeSeries\nfrom ._SaveMPN import _SaveMPN\n\ndef _ReadMPN(Date,Minute=False,res=None,DetectGaps=None,Autosave=True,Length=False):\n\t'''\n\tRead the data rotated into a coordinate system where Bx, By, Bz ==\n\tBpol, Btor, Bpar\n\t\n\t'''\n\tpath = MagGlobals.paths['MPN']\n\tif Minute:\n\t\tpath += 'Minute/'\n\telse:\n\t\tpath += 'Full/'\n\tfname = path + '{:08d}.bin'.format(Date)\n\tdtype = MagGlobals.dtypes['MPN']\t\n\t\n\tif not os.path.isfile(fname):\n\t\tprint('Data not found for this date...')\n\t\tif not Autosave:\n\t\t\treturn np.recarray(0,dtype=dtype)\n\n\t\telse:\n\t\t\tprint('Attempting to convert MSO data')\n\t\t\tstatus = _SaveMPN(Date,Minute)\n\t\t\tif not status:\n\t\t\t\tif Length:\n\t\t\t\t\treturn 0\n\t\t\t\telse:\n\t\t\t\t\treturn np.recarray(0,dtype=dtype)\n\tif Length:\n\t\tf = open(path + fname,'rb')\n\t\tn = np.fromfile(f,dtype='int32',count=1)[0]\n\t\tf.close()\n\t\treturn n\t\t\n\tdata = ReadRecarray(fname,dtype)\n\n\n\tif res != None:\n\t\tUTo = np.array(data.ut)\n\t\t\n\t\tlength = np.int32(86400/res)\n\t\tnewdata = np.recarray(length,dtype=dtype)\n\t\t\n\t\t\n\t\tif DetectGaps != None:\n\t\t\tDG = DetectGaps\n\t\telse:\n\t\t\tDG = res\n\n\t\ttags = data.dtype.names\n\t\tnewdata.ut = 24*np.arange(length,dtype='float32')/length\n\t\tnewdata.Date = Date\n\t\tfor t in tags:\n\t\t\tif not t in ['Date','ut']:\n\t\t\t\tnewdata[t] = ResampleTimeSeries(data.ut,data[t],newdata.ut,DG/3600.0,UseSpline=True)\n\n\t\tif DetectGaps != None:\n\t\t\t#set Detect gaps to the largest number of seconds gap (5s is used elsewhere)\n\t\t\tMaxUTGapHr = DetectGaps/3600.0\n\t\t\tbad = np.zeros(length,dtype='bool')\n\t\t\tfor i in range(0,UTo.size-1):\n\t\t\t\tif (UTo[i+1]-UTo[i]) > MaxUTGapHr:\n\t\t\t\t\tb = np.where((newdata.ut > UTo[i]) & ( newdata.ut < UTo[i+1]))[0]\n\t\t\t\t\tbad[b] = True\n\t\t\t\n\t\t\tbaddata = np.where(bad)[0]\n\t\t\ttags = ['BL','BM','BN']\n\t\t\tfor t in tags:\n\t\t\t\tnewdata[t][baddata] = np.float32(np.nan)\n\t\t\t\n\t\treturn newdata\n\telse:\n\t\treturn data\n","sub_path":"PyMess/MAG/_ReadMPN.py","file_name":"_ReadMPN.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"225670075","text":"# 贪心算法\nclass Solution(object):\n def findContentChildren(self, g, s):\n g = sorted(g) # 需求\n s = sorted(s) # 糖果\n child = 0 # 已满足几个孩子\n cookie = 0 # 尝试了几个糖果\n while cookie < len(s) and child < len(g):\n if g[child] <= s[cookie]:\n child += 1\n cookie += 1\n return child\n\n\n # 超出时间限制,自己写的\n def findContentChildren1(self, g, s):\n \"\"\"\n :type g: List[int]\n :type s: List[int]\n :rtype: int\n \"\"\"\n g = sorted(g) # 需求\n s = sorted(s) # 糖果\n cnt = 0\n flag = []\n for index_g,val_g in enumerate(g):\n for index_s, val_s in enumerate(s):\n if val_s >= val_g and index_s not in flag:\n cnt += 1\n flag.append(index_s)\n break\n return cnt\n\n\n\n\n\nif __name__ == '__main__':\n g = [1,2]\n s = [1,2,3]\n print(Solution().findContentChildren(g,s))","sub_path":"贪心/455-分发饼干.py","file_name":"455-分发饼干.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"3324016","text":"import time #libraries\nimport serial\nimport datetime\nimport threading\nimport motor_control\nimport math\n\nk=0\nie=0\n\n#PID values\nkd= 0.0000\nkp= 0.008\nki = 0.008\n#0.0001\n\n#thruster model\nTd= 0 #desired torque\ndensity = 998.2 #kg/m^3\ndiameter = 0.07928 #m\nk3 = 6*10^(-10) #must verify this value\n#rpmd = math.sqrt(Td/(density*diameter^4*k3)) #calculates desired rpm from model and thrust input\nrpmd = 2500 #minimum in air is 2400 because of command 30\n\n#motor direction\nforward= 1\nreverse = 0\ndirection = forward #sets motor direction\n\n#command input\nspeed = 0 #inital speed value\n\n#number of cycles\ndata_loops = 500\n\nstart = time.time()\n\n#sensor reading intializations\nsensor_back = 0\nsensor_back_ADC =0\nsensor_front = 0\nsensor_front_ADC = 0\nconst_front = 58\nconst_back = 25\n\nmotor_running_state = False\nmotor_terminate = False\n\nfile = open(\"testfile.csv\",'w')\nfile.write(\"Time Since Start, Front, Front ADC, Back, Back ADC, RPM \\n\")\n\narduino = serial.Serial(\n\tport='/dev/tty.usbmodem1421',\n\tbaudrate=256000,\n\t#parity=serial.None,\n\tstopbits=serial.STOPBITS_ONE,\n\tbytesize=serial.EIGHTBITS\n)\n#arduino.open()\n\nmotor = motor_control.get_motor_instance()\n\nif direction == forward:\n\tmotor_control.set_forward()\nif direction == reverse:\n\tmotor_control.set_reverse()\n\nprint(\"Serial opened\")\n\nmotor_running_state = True\n\nfor i in range(2):\n\tif direction== forward and speed>110:\n\t\tspeed=110\n\n\tif direction== reverse and speed >80:\n\t\tspeed=80\n\n\tif speed<30:\n\t\tspeed = 0\n\n\tmotor_control.set_speed(speed)\n\ttime.sleep(1)\n\narduino.flush()\n\nprint(\"start loop\")\nfor current_loop in range(data_loops):\n\n\tif direction== forward and speed>110:\n\t\tspeed=110\n\n\tif direction== reverse and speed >80:\n\t\tspeed=80\n\n\tif speed<30:\n\t\tspeed = 0\n\n\tmotor_control.set_speed(int(speed))\n\n\tarduino.reset_input_buffer()\n\tarduino.write(b'R')\n\n\t#first line may be gimped\n\tarduino_adc = arduino.read(4)\n\n\tmotor.write(b'RV1\\r\\n')\n\trevs = motor.read(4)\n\tmotor.reset_input_buffer()\n\tt1= time.time()\n\trpm1= (revs[1] * 255 + revs[0])\n\te1 = rpmd-rpm1\n\n\tmotor.write(b'RV1\\r\\n')\n\trevs = motor.read(4)\n\tmotor.reset_input_buffer()\n\tt2= time.time()\n\trpm2= (revs[1] * 255 + revs[0])\n\te2 = rpmd-rpm2\n\n\tmotor.write(b'RV1\\r\\n')\n\trevs = motor.read(4)\n\tmotor.reset_input_buffer()\n\tt3= time.time()\n\trpm3= (revs[1] * 255 + revs[0])\n\te3 = rpmd-rpm3\n\n\tmotor.write(b'RV1\\r\\n')\n\trevs = motor.read(4)\n\tmotor.reset_input_buffer()\n\tt4= time.time()\n\trpm4= (revs[1] * 255 + revs[0])\n\te4 = rpmd-rpm4\n\n\tmotor.write(b'RV1\\r\\n')\n\trevs = motor.read(4)\n\tmotor.reset_input_buffer()\n\tt5= time.time()\n\trpm5= (revs[1] * 255 + revs[0])\n\te5 = rpmd-rpm5\n\n\tavgrpm = (rpm1+rpm2+rpm3+rpm4+rpm5)/5\n\tprint (\"Measured RPM: \" + str(avgrpm))\n\n\te = rpmd - avgrpm #error term\n\tprint (\"Error Term: \" + str(e))\n\n\tdt = ((t5-t4)+(t4-t3)+(t3-t2)+(t2-t1))/4 #change in time per reading\n\tde = (-e5+8*e4-8*e2+e1)/(12*dt) #derivative term\n\tprint (\"Diff Term: \" + str(de))\n\n\tie = ie+((t2-t1)*(e1+e2)/2)+((t3-t2)*(e3+e2)/2)+((t4-t3)*(e3+e4)/2)+((t5-t4)*(e5+e4)/2) #integral term\n\tprint (\"Integral Term: \" + str(ie))\n\tcommand = kp*e+ki*ie+kd*de #PID line\n\tspeed = 0.81*command+29\n\tspeed= int(speed)\n\tprint (\"Speed: \" + str(speed))\n\n\ttry:\n\t\tmotor.write(b'RV1\\r\\n')\n\t\tsensor_front = (arduino_adc[0]-const_front)/2.9348\n\t\tsensor_front_ADC = arduino_adc[0]\n\t\tsensor_back = (arduino_adc[1]-const_back)/2.8563\n\t\tsensor_back_ADC = arduino_adc[1]\n\t\trevs = motor.read(4)\n\t\tmotor.reset_input_buffer()\n\texcept:\n\t\tprint(\"Something went wrong\")\n\t\tfile.write(\"Err,Err,Err, Err, Err, Err \\n\")\n\t\tprint(arduino_adc)\n\telse:\n\t\t#print(revs)\n\t\trpm = (revs[1] * 255 + revs[0])\n\t\t#print (revs)\n\t\tif current_loop % 50 == 0:\n\t\t\tpercent = int(100 * float(current_loop)/float(data_loops))\n\t\t\tprint(str(percent) + \"% done\")\n\t\t\tprint( \"Sensor Front: \" + str(sensor_front))\n\t\t\tprint( \"Sensor Back: \" + str(sensor_back))\n\t\t\tprint (\"RPM: \" + str(rpm))\n\t\tcurrent = time.time()\n\t\telapsed = current - start\n\t\tfile.write(str(elapsed) + ',')\n\t\tfile.write(str(sensor_front) + ',')\n\t\tfile.write(str(sensor_front_ADC) + ',')\n\t\tfile.write(str(sensor_back) + ',')\n\t\tfile.write(str(sensor_back_ADC) + ',')\n\t\tfile.write(str(rpm) + '\\n')\nprint(\"Done\")\nmotor.write(b'STP\\r\\n')\nmotor.write(b'SM1\\r\\n')\nprint(\"STP\")\nmotor.close()\nfile.close()\nexit()\n","sub_path":"motor-PID-tunedlowRPM.py","file_name":"motor-PID-tunedlowRPM.py","file_ext":"py","file_size_in_byte":4203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"558422938","text":"import re\nimport csv\n\nwords = []\nmatched_words = []\ncounter = 0\n\nwith open(file = 'program.txt', mode = 'r') as read:\n data = read.readlines() \n for line in data: \n for word in line.split(): \n # words.append(word.strip(\".\")) \n words.append(re.sub('[^a-zA-Z0-9]+', '', word))\n\nprint(words)\n\nwith open('mycsvfile.csv', 'w') as f:\n field_names = (['Matching item', 'Frequency of matching items', 'Split items'])\n the_writer = csv.DictWriter(f, fieldnames=field_names)\n the_writer.writeheader()\n\n for i in range(0, len(words), 2):\n counter = 0\n if i+1 < len(words):\n word_to_match = words[i] + words[i+1]\n if word_to_match not in matched_words:\n for j in range(0, len(words), 2):\n if j+1 < len(words):\n current_word = words[j]+words[j+1]\n if word_to_match == current_word:\n counter += 1\n matched_words.append(word_to_match)\n data = {\n 'Matching item': word_to_match,\n 'Frequency of matching items': counter-1,\n 'Split items': [words[i], words[i+1]]\n }\n if data['Frequency of matching items'] > 0:\n the_writer.writerow(data)\n","sub_path":"Assignment01/practice2.py","file_name":"practice2.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"63954465","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/will/projects/moya/moya/tags/widget.py\n# Compiled at: 2015-11-07 06:12:06\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nfrom ..elements.registry import Meta\nfrom ..elements import attributetypes\nfrom ..elements.elementbase import ElementBase, Attribute, LogicElement\nfrom ..logic import DeferNodeContents\nfrom ..tools import textual_list, nearest_word\nfrom ..context.missing import is_missing\nfrom ..context.tools import to_expression\nfrom ..compat import text_type, py2bytes\nfrom .. import errors\nfrom .. import namespaces\nfrom collections import OrderedDict\n\nclass WidgetBase(LogicElement):\n _container = False\n\n class Meta:\n text_nodes = b'text'\n is_call = True\n\n class NoTextMeta:\n text_nodes = None\n is_call = True\n\n def __init__(self, *args, **kwargs):\n self.init_args = (\n args, kwargs)\n super(WidgetBase, self).__init__(*args, **kwargs)\n\n def get_widget_app(self, context):\n app = None\n if self.has_parameter(b'from'):\n app = self.get_parameter(context, b'from') or None\n if app is None:\n try:\n app = self.archive.detect_app(context, self._lib_long_name)\n except:\n app = None\n\n if app is None:\n self.throw(b'widget.ambiguous-app', b\"unable to detect app for this widget (you may need to supply the 'from' attribute)\")\n return app\n\n def logic(self, context):\n widget_frame = context.current_frame\n content = context[b'.content']\n if is_missing(content):\n self.throw(b'widget.content-missing', b'widgets must be called in a content definition')\n td = self.get_all_parameters(context)\n td.pop(b'_if', None)\n _cachekey, _cachefor = self._cache\n cachekey, cachefor = (None, None)\n let_map = self.get_let_map(context)\n widget_app = self.get_widget_app(context)\n if _cachekey and _cachefor:\n with context.data_frame(td):\n cachekey = _cachekey(context)\n cachefor = _cachefor(context).milliseconds\n cachekey = (b'__widget__.{}.{}').format(self.libid, cachekey)\n cache = self.archive.get_cache(b'fragment')\n html = cache.get(cachekey, None)\n if html is not None:\n content.add_markup(self._tag_name, html)\n return\n if b'_caller' not in td:\n td[b'_caller'] = self.get_proxy(context, context[b'.app'])\n\n def on_yield(context, app, content, element, data):\n context.push_frame(widget_frame)\n try:\n with self.defer(context, app=app):\n with context.data_scope(data):\n with content.node():\n yield DeferNodeContents(element)\n finally:\n context.pop_frame()\n\n app = self.get_app(context)\n self.push_call(context, td, widget_app)\n if self._let_dst:\n context[self._let_dst] = let_map\n if self.has_parameter(b'template'):\n template = app.resolve_templates(self.template(context), check=True)\n else:\n template = widget_app.resolve_templates(self._template(context), check=True)\n template_node = content.add_template(self._tag_name, template, app=widget_app)\n yield_stack = context.set_new_call(b'._yield_stack', list)\n yield_stack.append(lambda c, data: on_yield(c, app, content, self, data))\n try:\n if self.widget_element.has_children:\n yield DeferNodeContents(self.widget_element)\n finally:\n yield_stack.pop()\n scope = context.obj\n self.pop_call(context)\n\n if self._container and self.has_children:\n with content.node():\n yield DeferNodeContents(self)\n if b'_return' in scope:\n scope = scope[b'_return']\n if hasattr(scope, b'get_return_value'):\n scope = scope.get_return_value()\n if not scope:\n scope = {}\n if not hasattr(scope, b'items'):\n self.throw(b'widget.return-no-dict', (b'the return value from a widget must be a dict, or None (not {})').format(context.to_expr(scope)))\n template_node.update_template_data(scope)\n if cachekey is not None:\n html = template_node.moya_render(self.archive, context, b'html', {})\n cache = self.archive.get_cache(b'fragment')\n cache.set(cachekey, html, cachefor)\n return\n\n\nclass WidgetBaseContainer(WidgetBase):\n _container = True\n\n\nclass WidgetYield(LogicElement):\n \"\"\"Yield to a widget block\"\"\"\n\n class Help:\n synopsis = b'yield to code block in a widget'\n\n obj = Attribute(b'Data to yield', type=b'expression', required=False, default=None)\n\n def logic(self, context):\n yield_call = context.get_stack_top(b'yield')\n yield_data = self.obj(context) or {}\n yield_data.update(self.get_let_map(context))\n if callable(yield_call):\n for node in yield_call(context, yield_data.copy()):\n yield node\n\n\nclass Widget(ElementBase):\n \"\"\"Create a widget\"\"\"\n\n class Help:\n synopsis = b'create a re-uasable widget'\n\n ns = Attribute(b'XML Namespace', required=False)\n name = Attribute(b'Tag name', required=True)\n template = Attribute(b'Template', type=b'templates', required=False, default=None)\n let = Attribute(b'Let destination', required=False, default=None)\n container = Attribute(b'Is this widget a container?', type=b'boolean', default=True, required=False)\n synopsis = Attribute(b'Short description of the widget')\n undocumented = Attribute(b'Set to yes to disabled documentation for this tag', type=b'boolean', default=False)\n text = Attribute(b'Include text children?', type=b'boolean', default=True)\n cachekey = Attribute(b'Cache key', name=b'cachekey', type=b'text', default=None, required=False)\n cachefor = Attribute(b'Cache time', name=b'cachefor', type=b'timespan', default=None, required=False)\n\n def finalize(self, context):\n params = self.get_parameters(context)\n attributes = {}\n attributes[b'template'] = Attribute(b'Override widget template', name=b'template', type=b'templates', required=False, default=None)\n for signature in self.children(b'signature'):\n for attribute_tag in signature.children(b'attribute'):\n param_map = attribute_tag.get_all_parameters(context)\n if attribute_tag.has_parameter(b'default') and not attribute_tag.has_parameter(b'required'):\n param_map[b'required'] = False\n description = attribute_tag.doc\n name = param_map.pop(b'name')\n attribute = Attribute(description, name=name, evaldefault=True, **param_map)\n attributes[attribute.name] = attribute\n\n attributes[b'from'] = Attribute(b'Application', name=b'from', type=b'application', map_to=b'from', default=None)\n doc = None\n for doc_tag in self.children(b'doc'):\n doc = doc_tag.text.strip()\n\n meta = Meta()\n meta.is_call = True\n\n class Help(object):\n synopsis = params.synopsis\n undocumented = params.undocumented\n\n cls_dict = dict(__doc__=text_type(doc or b''), Meta=meta, Help=Help)\n if self.source_line:\n definition = b'%s (line %s)' % (self._location, self.source_line)\n else:\n definition = self._location\n cls_dict[b'_definition'] = definition\n cls_dict[b'_template'] = self.template\n cls_dict[b'_let_dst'] = params.let\n if self.has_parameters(b'cachekey', b'cachefor'):\n cls_dict[b'_cache'] = (\n self.cachekey, self.cachefor)\n else:\n cls_dict[b'_cache'] = (None, None)\n cls_dict[b'xmlns'] = params.ns or self.lib.namespace or namespaces.default\n cls_dict.update((b'_attribute_' + k, v) for k, v in attributes.items())\n if params.text:\n cls_dict[b'Meta'] = WidgetBase.Meta\n else:\n cls_dict[b'Meta'] = WidgetBase.NoTextMeta\n cls_dict[b'_registry'] = self.archive.registry\n if params.container:\n bases = (\n WidgetBaseContainer,)\n else:\n bases = (\n WidgetBase,)\n tag_class = type(py2bytes(params.name), bases, cls_dict)\n tag_class.widget_element = self\n tag_class.libname = None\n tag_class._definition = definition\n tag_class._lib_long_name = context.get(b'._lib_long_name', None)\n return\n\n\nclass AttributeTag(ElementBase):\n \"\"\"Defines an attribute in a [tag]tag[/tag], [tag]data-tag[/tag] or [tag]widget[/tag].\"\"\"\n\n class Help:\n synopsis = b'define an attribute in a custom tag'\n example = b'\\n \\n Define a top level admin module\\n \\n \\n \\n \\n \\n \\n \\n\\n '\n\n _element_class = b'widget'\n preserve_attributes = [b'doc']\n\n class Meta:\n logic_skip = True\n tag_name = b'attribute'\n\n name = Attribute(b'Name of the attribute', required=True)\n type = Attribute(b'Type of the attribute', required=False, default=b'expression', choices=attributetypes.valid_types)\n required = Attribute(b'Required', type=b'boolean', required=False, default=True)\n default = Attribute(b'Default', required=False, default=None)\n metavar = Attribute(b'Metavar (identifier used in documentation)', required=False)\n missing = Attribute(b'Are missing values allowed?', type=b'boolean', default=True, required=False)\n empty = Attribute(b'Are empty values allowed?', type=b'boolean', default=True, required=False)\n choices = Attribute(b'Valid values for this attribute', type=b'commalist', default=None, required=False)\n\n def post_build(self, context):\n self.doc = context.sub(self.text.strip())\n\n\nclass ArgumentTag(ElementBase):\n \"\"\"\n Defines an argument to a macro.\n\n The text of this tag should document the purpose of the argument.\n\n \"\"\"\n\n class Help:\n synopsis = b'define an argument to a macro'\n example = b'\\n \\n \\n \\n A list (or other sequence) of numbers\\n \\n \\n \\n \\n\\n '\n\n class Meta:\n logic_skip = True\n tag_name = b'argument'\n\n name = Attribute(b'Name of the attribute', required=True)\n required = Attribute(b'Is this argument required?', type=b'boolean', default=True)\n check = Attribute(b'A boolean expression that the attribute must satisfy', type=b'function', default=None)\n default = Attribute(b'A value to use if the argument is not supplied', type=b'function', default=None)\n\n def post_build(self, context):\n self.doc = context.sub(self.text.strip())\n\n\nclass ArgumentValidator(object):\n \"\"\"Checks arguments to a macro call.\"\"\"\n\n def __init__(self, context, element):\n self.doc = []\n self.required = []\n self.checks = []\n self.arg_names = set()\n self.defaults = OrderedDict()\n for arg in element.children():\n if arg._element_type != (namespaces.default, b'argument'):\n raise errors.ElementError((b'{} signature must contain tags only').format(element.parent), element=element)\n name, required, check, default = arg.get_parameters(context, b'name', b'required', b'check', b'default')\n if arg.has_parameter(b'default'):\n self.defaults[name] = default\n required = False\n self.arg_names.add(name)\n if required:\n self.required.append(name)\n if check is not None:\n self.checks.append((name, check))\n self.doc.append({b'name': name, b'required': required, b'check': check})\n\n self.required_set = frozenset(self.required)\n return\n\n def __repr__(self):\n if self.arg_names:\n return (b'').format(textual_list(self.arg_names))\n else:\n return b''\n\n def check(self, context, arg_map, checked_object):\n for k, default in self.defaults.items():\n if k not in arg_map:\n arg_map[k] = default(context)\n\n if not self.arg_names.issuperset(arg_map.keys()):\n for k in self.arg_names:\n if k not in arg_map:\n raise ValueError((b\"'{}' is a required argument to {}\").format(k, checked_object))\n\n for name, check in self.checks:\n try:\n result = check.call(context, arg_map)\n except Exception as e:\n raise ValueError((b\"check failed for argument '{}' with error '{}'\").format(name, e))\n\n if not result:\n raise ValueError((b'{value} is not a valid value for argument {name}').format(name=name, value=to_expression(context, arg_map[name])))\n\n def validate(self, context, element, arg_map):\n for k, default in self.defaults.items():\n if k not in arg_map:\n arg_map[k] = default(context)\n\n if not self.arg_names.issuperset(arg_map.keys()):\n for k in arg_map:\n if k not in self.arg_names:\n nearest = nearest_word(k, self.arg_names)\n if nearest is not None:\n diagnosis = (b\"Did you mean '{}'?\").format(nearest)\n else:\n diagnosis = (b'Valid arguments to this macro are {}.').format(textual_list(sorted(self.arg_names), b'and'))\n element.throw(b'argument-error.unknown-argument', (b\"no argument called '{name}' in {element}'\").format(name=k, element=element), diagnosis=diagnosis)\n\n if not self.required_set.issubset(arg_map.keys()):\n for name in self.required:\n if name not in arg_map:\n element.throw(b'argument-error.required', (b\"argument '{}' is required in {}\").format(name, element), diagnosis=(b'You can pass a value for \\'{name}\\' with let:{name}=\"\" ').format(name=name, element=element))\n\n for name, check in self.checks:\n try:\n result = check.call(context, arg_map)\n except Exception as e:\n element.throw(b'argument-error.check-error', (b\"check for argument '{}' in {} failed with exception: {}\").format(name, element, e), diagnosis=(b\"An exception was thrown when evaluating the expression '{}'.\\n\\nThis could indicate a programming error in the macro or Moya.\").format(check.expression))\n\n if not result:\n diagnosis_msg = b\"{value} is not a valid value for argument '{name}'. Check the calling logic is correct.\"\n element.throw(b'argument-error.check-failed', (b'argument \\'{}\\' failed check \"{}\" in {}').format(name, check.expression, element), diagnosis=diagnosis_msg.format(name=name, value=to_expression(context, arg_map[name]), element=element))\n\n return\n\n\nclass Signature(ElementBase):\n \"\"\"\n Begins a list of attributes and arguments for a [tag]tag[/tag], [tag]data-tag[/tag], [tag]macro[/tag] or [tag]command[/tag].\n\n In the case of tags, the signature should contain [tag]attribute[/tag] tags.\n Macros expect [tag]argument[/tag] tags.\n For a command, the signature should contain [tag]arg[/tag] and [tag]option[/tag] tags.\n\n \"\"\"\n _element_class = b'widget'\n\n class Help:\n synopsis = b'define the attributes / arguments to a tag / macro'\n example = b'\\n \\n Calculate the fibonacci sequence\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n\\n '\n\n class Meta:\n logic_skip = True\n\n def get_validator(self, context):\n return ArgumentValidator(context, self)\n\n def finalize(self, context):\n if self.parent._element_type in ((namespaces.default, b'macro'), (namespaces.default, b'Filter')):\n self.validator = ArgumentValidator(context, self)\n else:\n self.validator = None\n return\n\n\nclass Doc(ElementBase):\n \"\"\"\n Write documentation for a widget or custom tag.\n\n \"\"\"\n _element_class = b'doc'\n\n class Meta:\n logic_skip = True\n\n class Help:\n synopsis = b'document a tag'\n example = b'\\n \\n Renders a single post\\n \\n \\n\\n '","sub_path":"pycfiles/moya-0.6.20-py2.py3-none-any/widget.py","file_name":"widget.py","file_ext":"py","file_size_in_byte":17586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"459221071","text":"import tensorflow as tf, numpy as np, pdb, os, shutil\r\n\r\n# **************\r\n# graph define\r\n# **************\r\n\r\nclass gr001():\r\n def __init__(self, X, Y, Z, Nstep, is_training, mu_x, sd_x, mu_y, sd_y, mu_z, sd_z, Nxi, Nzeta): \r\n\r\n Nx = X.get_shape().as_list()[1]\r\n Ny = Y.get_shape().as_list()[1]\r\n Nz = Z.get_shape().as_list()[1]\r\n\r\n Xn = (X-mu_x)/sd_x\r\n Yn = (Y-mu_y)/sd_y\r\n Zn = (Z-mu_z)/sd_z\r\n\r\n f = lambda xx,units: tf.layers.dense(xx,units=units,kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=1./units), kernel_initializer=tf.random_normal_initializer(stddev=1./np.sqrt(xx.get_shape().as_list()[1])))\r\n\r\n XI = f(Xn,Nxi)\r\n ZETA = f(Zn,Nzeta)\r\n\r\n A = tf.get_variable(name='A',shape=(Nzeta,Nzeta),initializer=tf.constant_initializer(value=np.eye(Nzeta)),regularizer=tf.contrib.layers.l2_regularizer(scale=1./Nzeta))\r\n B = tf.get_variable(name='B',shape=(Nzeta,Nxi),initializer=tf.constant_initializer(value=np.zeros((Nzeta,Nxi))),regularizer=tf.contrib.layers.l2_regularizer(scale=1./Nzeta))\r\n C = tf.get_variable(name='C',shape=(Ny,Nzeta),initializer=tf.random_normal_initializer(stddev=1./np.sqrt(Nzeta)),regularizer=tf.contrib.layers.l2_regularizer(scale=1./Ny))\r\n\r\n Y0n_hat = tf.matmul(ZETA,tf.transpose(C))\r\n err_y = tf.reduce_mean(tf.square(Y0n_hat - Yn))\r\n\r\n def terminate_cond(itr,zeta,xi,err_zeta,err_y):\r\n return tf.less(itr,Nstep)\r\n def update(itr,zeta,xi,err_zeta,err_y):\r\n zeta = tf.matmul(zeta[:-1,:],tf.transpose(A)) + tf.matmul(xi[:-1,:],tf.transpose(B))\r\n yhat = tf.matmul(zeta,tf.transpose(C))\r\n err_y = err_y + tf.reduce_mean(tf.square(yhat - Yn[itr+1:,:]))\r\n err_zeta = err_zeta + tf.reduce_mean(tf.square(zeta - ZETA[itr+1:,:]))\r\n xi = xi[1:,:]\r\n return itr+1,zeta,xi,err_zeta,err_y\r\n (_,ZETA_hat,_,err_zeta,err_y) = tf.while_loop(terminate_cond, update, [0,ZETA,XI,0.,err_y])\r\n\r\n Yn_hat = tf.matmul(ZETA_hat,tf.transpose(C))\r\n self.Yhat = Yn_hat * sd_y + mu_y\r\n\r\n# acount for loss\r\n err_y = tf.identity(err_y,name='err_y')\r\n tf.losses.add_loss(err_y)\r\n tf.losses.add_loss(err_zeta)\r\n\r\n# ****************\r\n# trainer\r\n# ****************\r\n\r\nclass trainer():\r\n def __init__(self):\r\n self.export_dir = './tmp/work011'\r\n (self.Nx, self.Ny, self.Nz,self.Nstep,self.is_training) = [None,] * 5\r\n (self.mu_x ,self.sd_x), (self.mu_y ,self.sd_y), (self.mu_z ,self.sd_z) = [(None,None),] * 3\r\n\r\n def construct(self):\r\n self.X = tf.placeholder(shape=(None,self.Nx),dtype=tf.float32,name='X')\r\n self.Y = tf.placeholder(shape=(None,self.Ny),dtype=tf.float32,name='Y')\r\n self.Z = tf.placeholder(shape=(None,self.Nz),dtype=tf.float32,name='Z')\r\n self.is_training = tf.placeholder(shape=(),dtype=tf.bool,name='is_training')\r\n self.Nstep = tf.placeholder(shape=(),dtype=tf.int32,name='Nstep')\r\n self.Yhat = None\r\n\r\n def pretrain(self,Xval,Yval,Zval):\r\n (self.mu_x ,self.sd_x), (self.mu_y ,self.sd_y), (self.mu_z ,self.sd_z) = map(lambda xx: (np.mean(xx,axis=0), np.std(xx,axis=0),) , (Xval,Yval,Zval))\r\n\r\n def fit(self,Xval,Yval,Zval,Nstep,alpha=1e-2,Nitr=2**10,Nfreq_print=2**10,lmbd=1e-4,silent_mode=True,dev_size=0.1,Nstep_scheduling=False):\r\n (Nt,self.Nx,self.Ny,self.Nz) = (Xval.shape[0],Xval.shape[1],Yval.shape[1],Zval.shape[1])\r\n if Nstep_scheduling:\r\n Nstep_series = np.round(np.linspace(0,Nstep,Nitr)).astype(np.int)\r\n else:\r\n Nstep_series = np.repeat(Nstep,Nitr)\r\n\r\n with tf.Graph().as_default():\r\n#\r\n Nbatch = int(Nt * dev_size)\r\n#\r\n self.pretrain(Xval,Yval,Zval)\r\n self.construct()\r\n \r\n loss = tf.reduce_mean(tf.losses.get_losses()) + lmbd * tf.reduce_mean(tf.losses.get_regularization_losses())\r\n\r\n with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):\r\n trainer = tf.train.AdamOptimizer(alpha).minimize(loss)\r\n saver = tf.train.Saver()\r\n\r\n with tf.Session() as sess:\r\n sess.run(tf.global_variables_initializer())\r\n for itr in range(Nitr):\r\n\r\n t0 = np.random.randint(Nt-Nbatch+1)\r\n (Xbatch,Ybatch,Zbatch) = map(lambda xx: xx[t0:t0+Nbatch,:], (Xval,Yval,Zval))\r\n feed_dict = {self.X: Xbatch, self.Y: Ybatch, self.Z: Zbatch, self.is_training: True, self.Nstep: Nstep_series[itr]}\r\n\r\n sess.run(trainer,feed_dict=feed_dict)\r\n\r\n if (itr % Nfreq_print == 0 or itr == (Nitr-1)) and not silent_mode:\r\n loss_val = sess.run(loss, feed_dict = feed_dict)\r\n print('itr: {0:4d}, loss_val: {1:.2e}'.format(itr,loss_val))\r\n for elm in tf.losses.get_losses() + tf.losses.get_regularization_losses():\r\n print(elm,sess.run(elm,feed_dict))\r\n saver.save(sess,'./tmp/work011.ckpt')\r\n\r\n def predict(self,Xval,Zval,Nstep):\r\n with tf.Session(graph=tf.Graph()) as sess:\r\n self.construct()\r\n saver = tf.train.Saver()\r\n saver.restore(sess,'./tmp/work011.ckpt')\r\n feed_dict = {self.X: Xval, self.Z: Zval, self.is_training: False, self.Nstep: Nstep}\r\n Yhat_val = sess.run(self.Yhat,feed_dict)\r\n return Yhat_val\r\n\r\n\r\nclass trainer001(trainer):\r\n def __init__(self, Nxi, Nzeta):\r\n self.Nxi = Nxi\r\n self.Nzeta = Nzeta\r\n\r\n def construct(self):\r\n trainer.construct(self)\r\n mm = gr001(self.X,self.Y,self.Z,self.Nstep,self.is_training,self.mu_x,self.sd_x,self.mu_y,self.sd_y,self.mu_z,self.sd_z,self.Nxi,self.Nzeta)\r\n self.Yhat = mm.Yhat\r\n\r\n","sub_path":"examples/work011.py","file_name":"work011.py","file_ext":"py","file_size_in_byte":5871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"161612965","text":"#!/usr/bin/env python\n\n'''\nThis script takes output from a pairwise (for now) RBBH run, extracts those orthologs from the respective \nTrinity.fasta output file and renames transcripts in the second fasta file to the corresponding ones in the first\nShould be able to extract all isoforms of each gene. Gives arbitrary isoform numbers to the second set of genes.\n\nusage: extract_rename_cRBH_orthologs.py \n\n'''\nfrom Bio import SeqIO\nimport sys\nimport re\n\n\n\noutfile_first = open(sys.argv[4], \"w\")\noutfile_second = open(sys.argv[5], \"w\")\northos = open(sys.argv[1], \"rU\")\nfirst_fasta = open(sys.argv[2], \"rU\")\nsecond_fasta = open(sys.argv[3], \"rU\")\n\ngenes_first = []\ngenes_second = []\northo_second = {}\n\nfor line in orthos:\n info = line.split('\\t')\n gene_first = info[0]\n gene_first = re.sub(r'_i\\d+', '', gene_first)\n gene_second = info[1]\n gene_second = re.sub(r'_i\\d+', '', gene_second)\n genes_first.append(gene_first)\n genes_second.append(gene_second)\n ortho_second[gene_second] = gene_first\n\n\nfor record in SeqIO.parse(first_fasta, \"fasta\"):\n gene = re.sub(r'_i\\d+', '', record.id)\n if gene in genes_first: \n print ('Writing: ' + record.id)\n SeqIO.write(record, outfile_first, \"fasta\")\n\ngene_list = []\nfor record in SeqIO.parse(second_fasta, \"fasta\"):\n gene = re.sub(r'_i\\d+', '', record.id)\n gene_list.append(gene)\n if gene in genes_second:\n record.id = ortho_second[gene] + '_i' + str(gene_list.count(gene))\n record.description = ortho_second[gene] + '_i' + str(gene_list.count(gene))\n print ('Writing: ' + record.id)\n SeqIO.write(record, outfile_second, \"fasta\")\n\noutfile_first.close()\noutfile_second.close()\northos.close()\nfirst_fasta.close()\nsecond_fasta.close()\n\n\n","sub_path":"deprecated/extract_rename_orthogroups_allisos.py","file_name":"extract_rename_orthogroups_allisos.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"523438006","text":"import tkinter as tk\nfrom collections import Callable\n\nfrom mastermind.game.game import Game\nfrom mastermind.game.visual.enums.abstract_intenum import AbstractIntEnum\nfrom mastermind.game.visual.enums.color import Color\nfrom mastermind.game.visual.enums.input_type import InputType\nfrom mastermind.game.visual.enums.mode import Mode\n\n\ndef switch(enum: AbstractIntEnum, button: tk.Button):\n enum = enum.get_next()\n button.config(text=enum.name)\n return enum\n\n\ndef switch_with_event(enum: AbstractIntEnum, button: tk.Button, event):\n if event.num == 1:\n enum = enum.get_next()\n elif event.num == 3:\n enum = enum.get_previous()\n else:\n enum = enum.get_next()\n button.config(text=enum.name)\n return enum\n\n\nclass Input:\n def __init__(self, parent: tk.Frame, num_slots):\n self.value = tk.IntVar()\n self.value.set(1)\n\n self.input_frame = tk.Frame(parent)\n\n self.entry = tk.Entry(self.input_frame)\n\n self.entry.bind('', lambda event: parent.submit())\n self.show_button_text = False\n self.input_buttons = []\n for i in range(num_slots):\n button = tk.Button(self.input_frame, width='3')\n self._config_button(button, Color.RED)\n button.bind('', self._switch_color(button))\n button.bind('', self._switch_color(button))\n self.input_buttons.append(button)\n\n def _config_button(self, input_button: tk.Button, color: Color):\n c_value = color.get_color_value()\n c_text = c_value\n if self.show_button_text:\n c_text = color.get_text_color()\n\n input_button.config(text=str(color.value), bg=c_value, fg=c_text,\n activebackground=c_value, activeforeground=c_text)\n\n @staticmethod\n def _get_num_input(input_button: tk.Button):\n return int(input_button.cget('text'))\n\n def _next_color(self, input_button):\n def func():\n color = Color(self._get_num_input(input_button)).get_next()\n self._config_button(input_button, color)\n\n return func\n\n def _switch_color(self, input_button):\n def func(event):\n color = None\n if event.num == 1:\n color = Color(int(input_button.cget('text'))).get_next()\n elif event.num == 3:\n color = Color(int(input_button.cget('text'))).get_previous()\n self._config_button(input_button, color)\n\n return func\n\n def get_input(self):\n return [self._get_num_input(button) for button in self.input_buttons]\n\n def show_input(self, input_type: InputType):\n self.entry.grid_remove()\n for button in self.input_buttons:\n button.grid_remove()\n if input_type == input_type.Numbers:\n self.entry.grid(row=0, column=0, columnspan=4)\n elif input_type == input_type.Colors:\n self.show_button_text = False\n for (pos, button) in enumerate(self.input_buttons):\n button.grid(row=0, column=pos)\n self._config_button(button, Color(self._get_num_input(button)))\n elif input_type == input_type.Combo:\n self.show_button_text = True\n for (pos, button) in enumerate(self.input_buttons):\n button.grid(row=0, column=pos)\n self._config_button(button, Color(self._get_num_input(button)))\n\n\nclass InputWindow(tk.Frame):\n def __init__(self, parent: tk.Frame, num_slots, pin_amount, submit_input: Callable):\n super(InputWindow, self).__init__(parent)\n\n self.num_slots = num_slots\n self.pin_amount = pin_amount\n\n self.input_type = InputType.Colors\n self.submit_input = submit_input\n self.inputs = []\n self.add_input()\n self.change_input_button = tk.Button(self, text=self.input_type.name)\n self.change_input_button.bind('', self.switch)\n self.change_input_button.bind('', self.switch)\n self.submit_button = tk.Button(self, text=\"Submit\", command=self.submit)\n\n def switch(self, event):\n self.input_type = switch_with_event(self.input_type, self.change_input_button, event)\n self.setup()\n\n def setup(self):\n \"\"\"\n Packs the widget inside the frame\n \"\"\"\n self.change_input_button.grid(row=0, column=0, sticky='w')\n self.submit_button.grid(row=0, column=1, sticky='e')\n\n for (i, inp) in enumerate(self.inputs):\n self.setup_input(inp, i + 1)\n\n self.grid(row=0, column=0, sticky='nw')\n\n def setup_input(self, inp: Input, index):\n inp.input_frame.grid(row=index + 1, column=0, columnspan=2, sticky='nw')\n inp.show_input(self.input_type)\n\n def add_input(self):\n inp = Input(self, self.num_slots)\n\n self.inputs += [inp]\n self.setup_input(inp, len(self.inputs))\n\n def submit(self):\n if len(self.inputs) > 0:\n if self.input_type == InputType.Numbers:\n pins = [int(num_string) for num_string in self.inputs[0].entry.get().split(\" \")]\n else:\n pins = self.inputs[0].get_input()\n\n self.submit_input(pins)\n\n\nclass FeedbackWindow(tk.Canvas):\n\n def __init__(self, parent: tk.Frame, moves=10, *args, **kwargs):\n super(FeedbackWindow, self).__init__(parent, *args, **kwargs)\n self.feedback_amount = 0\n self.max_feedback = moves\n self.config(bg='black')\n\n def add_feedback(self, int_list, correct, semi_correct):\n size = self.winfo_height() / self.max_feedback - 1\n width = self.winfo_width()\n y1 = self.feedback_amount * size\n y2 = y1 + size\n\n self.create_rectangle((0, y1, width, y2), fill='grey')\n for (i, num) in enumerate(int_list):\n posx = i * size + 5\n color = Color(num)\n self.create_rectangle((posx, y1, posx + size, y2), fill=color.get_color_value())\n self.create_text((posx + size / 2, y1 + size / 2), fill=color.get_text_color(), text=str(num))\n self.create_text((width - 50, y1 + size / 2), fill='black', text=str(correct))\n self.create_text((width - 30, y1 + size / 2), fill='white', text=str(semi_correct))\n\n self.feedback_amount += 1\n\n\nclass MainWindow(tk.Frame):\n def __init__(self, parent: tk.Frame, game: Game, submit_input: Callable):\n super(MainWindow, self).__init__(parent)\n\n self.game = game\n\n self.input_window = InputWindow(self, game.num_slots, game.pin_amount, submit_input)\n self.feedback_window = FeedbackWindow(self)\n\n def setup(self):\n \"\"\"\n Packs the widget inside the frame\n \"\"\"\n self.input_window.setup()\n self.feedback_window.grid(row=0, column=2, columnspan=2, sticky='nsw')\n\n self.grid(row=0, column=0, sticky='nsew')\n\n def give_feedback(self, int_list, correct, semi_correct):\n self.feedback_window.add_feedback(int_list, correct, semi_correct)\n\n\nclass InfoBar(tk.Frame):\n def __init__(self, parent: tk.Frame):\n super(InfoBar, self).__init__(parent)\n self.title_label = tk.Label(self, text=\"Game Status\")\n\n self.gameview = parent\n self.mode = Mode.Classic\n self.mode_button = tk.Button(self, text=self.mode.name)\n self.mode_button.bind('', self.switch)\n self.mode_button.bind('', self.switch)\n self.label = tk.Label(self, text=\"You lost!\")\n\n def switch(self, event):\n self.mode = switch_with_event(self.mode, self.mode_button, event)\n self.gameview.switch_mode(self.mode)\n\n def setup(self):\n \"\"\"\n Packs the widget inside the frame\n \"\"\"\n self.mode_button.grid(row=0, column=1, columnspan=1, sticky=\"e\")\n\n self.grid(row=1, column=0, sticky='ew')\n","sub_path":"src/mastermind/game/visual/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":7847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"359864000","text":"x = 256\ndef checkAnargram(s1, s2):\n l1 , l2 = len(s1), len(s2)\n\n if l1 != l2:\n return False\n \n data = [0] * 256\n\n for i in s1:\n data[ord(i)] += 1\n for i in s2:\n data[ord(i)] -= 1\n\n for i in range (x):\n if data[i]:\n return False\n return True\n\ns1 = input()\ns2 = input()\nif(checkAnargram(s1,s2)):\n print(\"yes\")\nelse:\n print(\"No\")","sub_path":"python solution code/check_two_string_is_anargarm_or_not.py","file_name":"check_two_string_is_anargarm_or_not.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"389269789","text":"import os\nimport sys\n\n# This exists because msvcrt.getwch does not exist\n# on operating systems other than windows.\n# We need to keep compatability with macos as one of our\n# team members has a macbook, and we dont know what our\n# beloved instructor has.\n# The readkey_unix function is from:\n# https://docs.python.org/2/faq/library.html#how-do-i-get-a-single-keypress-at-a-time\n\n# Translate key codes in unix to windows\nKEYMAP = {\n 10: 13,\n 127: 8,\n 10051: 10083,\n 10065: 10072,\n 10066: 10080,\n 10067: 10077,\n 10068: 10075\n}\n\n\ndef readkey() -> int:\n if os.name == 'nt':\n from msvcrt import getwch\n key = ord(getwch())\n if key == 224:\n key = ord(getwch()) + 10000\n return key\n else:\n return readkey_unix()\n\n\ndef readkey_unix():\n import termios\n import fcntl\n fd = sys.stdin.fileno()\n oldterm = termios.tcgetattr(fd)\n newattr = termios.tcgetattr(fd)\n newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO\n termios.tcsetattr(fd, termios.TCSANOW, newattr)\n oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)\n fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)\n try:\n while 1:\n try:\n c = ord(sys.stdin.read(1))\n if c == 27:\n sys.stdin.read(1)\n c = ord(sys.stdin.read(1)) + 10000\n break\n except (IOError, TypeError):\n pass\n finally:\n termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)\n fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)\n return KEYMAP.get(c, c)\n\n\nif __name__ == \"__main__\": # demo\n key = readkey()\n print(key)\n","sub_path":"ui/readkey.py","file_name":"readkey.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"35591625","text":"import scrapy\n\ndef start_urls():\n return [f'https://sh.lianjia.com/xiaoqu/pudong/pg{i}' for i in range(1, 31)]\n\nprint(start_urls()) \n\nclass Pudong(scrapy.Spider):\n name = \"pudong\"\n start_urls = start_urls()\n\n def parse(self, response):\n\n names = response.css('div.info div.title a::text').getall()\n prices = response.css('div.totalPrice span::text').getall()\n for name, price in zip(names, prices):\n yield {\n 'name': name,\n 'price': price\n }","sub_path":"house/house/spiders/pudong.py","file_name":"pudong.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"187340290","text":"import helper\n\n\ndef greeting():\n response = \"I am CSE chatbot. I can help you with the problems about CSE department.\"\n return response\n\n\ndef give_basic_info(info, info_body):\n response = \"The \" + info + \" of HKUST CSE is: \" + \"\\n\"\n response += info_body\n return response\n\n\n# provide general coordinator info\ndef provide_general_coordinator_info():\n program_info = helper.load_program_info()\n response = \"I am sorry that I may not understand what you said. \"\n response += \"But here are some general news about the coordinator in different programs.\\n\\n\"\n response += \"The coordinator for UG programs is Dr. Qiong Luo.\\n\"\n response += \"The coordinator for PG programs is Dr. Kai Chen.\\n\\n\"\n response += \"The coordinator for each program is:\\n\"\n index = 0\n for program in program_info:\n if index != 0:\n response += \"\\n\"\n coordinator = program_info[program][4]\n response += provide_coordinator_info(program, coordinator)\n index += 1\n return response\n\n\n# Staff related info\ndef provide_staff_telephone_number(name, number):\n response = \"\"\n if number == \"information not available\":\n response += \"The telephone number of \" + name + \" is not available.\"\n else:\n response += \"The telephone number of \" + name + \" is: \"\n response += \"(852) 2358 \" + str(number)\n return response\n\n\n# Staff related info\ndef provide_staff_email(name, address):\n response = \"The email of \" + name + \" is: \"\n response += address + \"@cse.ust.hk\"\n return response\n\n\n# Staff related info\ndef provide_staff_room(name, room_number):\n response = \"The room number of \" + name + \" is: \"\n response += str(room_number)\n return response\n\n\n# Staff related info\ndef provide_staff_link(name, link_number):\n response = \"The personal web of \" + name + \" is: \"\n response += str(link_number)\n return response\n\n\n# Staff complete info\ndef provide_staff_info(name, email, tel, room_no, link):\n response = \"The complete set of information of \" + name + \" is:\\n\"\n response += provide_staff_email(name, email) + \"\\n\"\n response += provide_staff_telephone_number(name, tel) + \"\\n\"\n response += provide_staff_room(name, room_no) + \"\\n\"\n response += provide_staff_link(name, link) + \"\\n\"\n return response\n\n\n# Staff position info\ndef provide_staff_position(name, position, type_staff):\n response = \"The position of \" + name + \" is: \"\n response += position + \", \"\n response += \"under the category of \" + type_staff\n return response\n\n\n# Faculty related info\ndef provide_faculty_email(name, address):\n response = \"The email of \" + name + \" is: \"\n response += address\n return response\n\n\n# Faculty related info\ndef provide_faculty_title(name, title):\n response = \"The title of \" + name + \" is: \"\n response += title\n return response\n\n\n# Faculty related info\ndef provide_faculty_research_area(name, title):\n response = \"The research area of \" + name + \" is: \"\n response += title\n return response\n\n\n# Faculty related info\ndef provide_faculty_research_interest(name, title):\n response = \"The research interest of \" + name + \" is: \"\n response += title\n return response\n\n\n# Faculty related info\ndef provide_faculty_tel(name, number):\n response = \"The telephone number of \" + name + \" is: \"\n response += str(number)\n return response\n\n\n# Faculty related info\ndef provide_faculty_profile(name, link):\n response = \"The faculty profile page of \" + name\n response += \" is \" + str(link)\n return response\n\n\n# Faculty related info\ndef provide_faculty_scholar_profile(name, link):\n response = \"The faculty scholar profile page of \" + name\n response += \" is \" + str(link)\n return response\n\n\n# Faculty complete info\ndef provide_faculty_info(name, email, tel, room_no, link, profile_link, scholar_link):\n response = \"The complete information of \" + name + \" is listed as:\\n\"\n response += provide_faculty_email(name, email) + \"\\n\"\n response += provide_faculty_tel(name, tel) + \"\\n\"\n response += provide_staff_room(name, room_no) + \"\\n\"\n response += provide_staff_link(name, link) + \"\\n\"\n response += provide_faculty_profile(name, profile_link) + \"\\n\"\n response += provide_faculty_scholar_profile(name, scholar_link)\n return response\n\n\n# Department contact info\ndef provide_dept_contact_info():\n response = \"The complete information of HKUST CSE is listed as:\\n\"\n response += \"Address: Room 3528 (Lift 25-26)\\n\"\n response += \"Department of Computer Science and Engineering\\n\"\n response += \"The Hong Kong University of Science and Technology\\n\"\n response += \"Clear Water Bay, Kowloon\\n\"\n response += \"Hong Kong\\n\\n\"\n\n response += \"Email: csdept@cse.ust.hk\\n\"\n response += \"Tel: (852) 2358 7000\\n\"\n response += \"Fax: (852) 2358 1477\\n\"\n return response\n\n\n# The basic information about the course\ndef provide_course_info(code, name, credit, exclusion, prerequisite, description):\n response = \"The name of \" + code + \" is \" + name + \".\\n\"\n if type(credit) == int:\n response += \"The credit number is \" + str(int(credit)) + \".\\n\"\n if \"\\\\N\" not in exclusion:\n response += \"It has an exclusion of \" + exclusion + \". \"\n if \"\\\\N\" not in prerequisite:\n response += \"Also, it has a prerequisite of \" + prerequisite + \".\\n\"\n if \"\\\\N\" not in description:\n response += \"A brief description of the course: \" + \"\\n\"\n response += description\n return response\n\n\n# Provide information of course\ndef provide_course_info_by_table(code, information_table):\n try:\n course_information_list = information_table[code]\n except KeyError:\n response = \"Cannot find course name. Please enter another question.\"\n return response\n course_name = course_information_list[1]\n course_credit = course_information_list[2]\n exclusion = course_information_list[3]\n prerequisite = course_information_list[4]\n description = course_information_list[5]\n response = provide_course_info(code, course_name, course_credit, exclusion, prerequisite, description)\n return response\n\n\n# The basic information about the CSE department\ndef provide_basic_dept_info():\n response = \"Computer science is the discipline that studies the structure, function, and applications \" \\\n \"of computers as well as the interconnection of computers. Covering topics in the areas of \" \\\n \"foundations of computer science and computer engineering, artificial intelligence, networking, \" \\\n \"computer graphics, multimedia computing, software and web technologies, and data and knowledge-base \" \\\n \"systems, the Computer Science programs at this University are dedicated to educate students and to \" \\\n \"advance research in computer and information technology; as well as to assist in the development and \" \\\n \"growth of the information industry in the region.\" + \"\\n\\n\"\n response += \"Through the efforts of researchers and engineers, computers have evolved from large, slow, \" \\\n \"expensive, and very specialized systems to small, fast, affordable, and ordinary tools that are \" \\\n \"part of virtually everyone's life. Advances in networking technologies and human-computer \" \\\n \"interfacing \" \\\n \"technologies have further created a digital culture. The ubiquitous nature of computers in today's \" \\\n \"workplace and home environment is making computer literacy a requirement not only for all \" \\\n \"professionals in industrial societies but also for everybody living in the digital culture.\" + \"\\n\\n\"\n response += \"Computer Science is still a young field. Although we have witnessed numerous advances in the past, \" \\\n \"this is only the beginning of a new revolution as the potential of information technology has not \" \\\n \"yet been fully realized. Information technology is in the midst of a revolution as we move from \" \\\n \"explicit interactions with disconnected computing devices to implicit and pervasive interactions \" \\\n \"with highly interconnected, integrated digital resources embedded in the environments in which we \" \\\n \"work, live, learn, and play. The impact of computer science and information engineering will be \" \\\n \"broad and deep. Computer Science programs at HKUST prepare students for exciting challenges and \" \\\n \"new opportunities that help to bring such impact to our lives.\" + \"\\n\\n\"\n response += \"The Department offers a full range of courses to meet the needs of its own students and those from \" \\\n \"other departments. Its programs lead to the BEng, BSc, MSc, MPhil, and PhD degrees. Aside from \" \\\n \"taking computer science courses, students are encouraged to design individual study plans tailored \" \\\n \"to their own interests.\"\n return response\n\n\n# provide staff information (get the information of staff)\ndef provide_staff_people_info(name, position, staff_type):\n response = \"\"\n if position[0] not in [\"a\", \"e\", \"i\", \"o\", \"u\"]:\n response += name + \" is a \" + position + \" in CSE department, belonging to the category of \"\n else:\n response += name + \" is an \" + position + \" in CSE department, belonging to the category of \"\n response += staff_type\n return response\n\n\n# provide the list of faculty based on the research area\ndef provide_faculty_in_research_area(area, faculties):\n response = \"The following faculties are conducting research on \" + area + \": \"\n for i in range(len(faculties)):\n if i != len(faculties) - 1:\n response += faculties[i] + \", \"\n else:\n response += faculties[i] + \".\"\n return response\n\n\n# provide coordinator information\ndef provide_coordinator_info(program, coordinator):\n response = \"The coordinator of \" + program + \" is \" + coordinator + \".\"\n return response\n\n\n# provide information of faculty recruitment\ndef provide_faculty_recruitment():\n response = \"The Department of Computer Science and Engineering of HKUST (https://www.cse.ust.hk/) is inviting \" \\\n \"applications for substantiation-track faculty openings at all levels of Professor, \" \\\n \"Associate Professor and Assistant Professor for the 2020-2021 academic year.\"\n response += \"Detailed information can be found in https://www.cse.ust.hk/admin/recruitment/faculty/.\"\n return response\n\n\n# provide information of course prerequisite\ndef provide_course_prerequisite(course_code, prerequisite):\n if \"\\\\N\" not in prerequisite:\n response = \"The course of \" + course_code + \" has a prerequisite of \" + prerequisite + \".\"\n return response\n response = \"There is no prerequisite for \" + course_code + \". Feel free to enroll in this course.\"\n return response\n\n\n# provide inbound exchange information\ndef provide_inbound_exchange():\n response = \"Exchange students can apply by following the steps below.\\n\"\n response += \"Step 1: Nomination by home institution;\\n\"\n response += \"Step 2: HKUST application;\\n\"\n response += \"Step 3: Post-application procedures.\\n\"\n response += \"Detailed information can be found at: https://studyabroad.ust.hk/inbound\"\n return response\n\n\n# provide outbound exchange information\ndef provide_outbound_exchange():\n response = \"Exchange students can apply by following the steps below.\\n\"\n response += \"Step 1: Nomination by HKUST;\\n\"\n response += \"Step 2: Target institution application;\\n\"\n response += \"Step 3: Post-application procedures.\\n\"\n response += \"Detailed information can be found at: https://studyabroad.ust.hk/outbound\"\n return response\n\n\ndef provide_inbound_outbound_exchange():\n response = \"I am sorry that I may not get your idea. Here are some related information for exchange programs.\\n\\n\"\n response += provide_outbound_exchange()\n response += \"\\n\\n\"\n response += provide_inbound_exchange()\n return response\n\n\n# ask questions about inbound or outbound\ndef query_in_out():\n response = \"Do you want to query the inbound exchange (exchange-in) or outbound exchange (exchange-out)?\"\n response += \"\\n\"\n response += \"<>Inbound Exchange\"\n response += \"\\n\"\n response += \"<>Outbound Exchange\"\n return response\n\n\n# ask questions about job or student\ndef query_job_student():\n response = \"Are you a student or a job seeker?\\n\"\n response += \"<>Student\\n\"\n response += \"<>Job seeker\"\n return response\n\n\n# ask questions about jobs\ndef query_job():\n response = \"Do you want to apply for a faculty position or an ordinary staff?\"\n response += \"<>Faculty position\\n\"\n response += \"<>Ordinary staff\\n\"\n return response\n\n\n# ask questions about student\ndef query_student():\n response = \"Which program do you want to participate?\\n\"\n response += \"Here are some possible choices:\\n\"\n response += \"<>BEng in Computer Science (COMP)\\n\"\n response += \"<>BEng in Computer Engineering (CPEG)\\n\"\n response += \"<>BEng in \"\n return response\n\n\n# provide answers when the chat-bot is not able to answer the question\ndef sorry():\n response = \"Sorry I can't help you. Please try a different one.\"\n return response\n","sub_path":"response_generator.py","file_name":"response_generator.py","file_ext":"py","file_size_in_byte":13362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"270886052","text":"import requests\nimport sys\nimport json\nfrom datetime import datetime\nimport time\nimport pymongo\n\noutputdict = {}\noutputnum = 0\npost_dict = {}\n\nsubreddits = [\"politics\", \"news\", \"worldnews\", \"pics\", \"videos\", \"science\", \"technology\",\n \"sports\", \"upliftingnews\", \"philosophy\", \"twoxchromosomes\", \"democrats\", \"conservative\", \"libertarian\", \"republican\",\n \"liberal\", \"progun\", \"futurology\", \"economics\", \"socialism\", \"whitepeopletwitter\", \"blackpeopletwitter\",\n \"sandersforpresident\", \"atheism\", \"christianity\", \"politicalhumor\", \"selfawarewolves\", \"joebiden\", \"nottheonion\",\n \"teenagers\", \"latestagecapitalism\", \"lgbt\", \"unpopularopinion\", \"leopardsatemyface\"]\n\nkeywords = [\"donald\", \"trump\", \"joe\", \"biden\", \"elon\", \"musk\", \"jeremy blackburn\",\n \"anthony\", \"fauci\", \"mike\", \"pence\", \"kamala\", \"harris\", \"kanye\", \"west\",\n \"adolf\", \"hitler\", \"mao\", \"zedong\", \"joseph\", \"stalin\", \"jesus christ\",\n \"bill\", \"clinton\", \"jefferey\", \"epstein\", \"hillary\", \"clinton\", \"andrew\",\n \"yang\", \"mitch\", \"mcconnel\", \"mark\", \"zuckerberg\", \"tom\", \"cruise\",\n \"bernie\", \"sanders\"]\n\nmyclient = pymongo.MongoClient(\"---\")\nmydb = myclient[\"cs415\"]\nmycol_comp = mydb[\"compressed_comments\"]\nmycol_comp_posts = mydb[\"compressed_posts\"]\n\ndef checkKeywords(checkstring, post_json):\n global outputdict\n global outputnum\n global post_dict\n for keyword in keywords:\n if(checkstring.lower().find(keyword) != -1):\n #print(\"~~~match on: \", checkstring)\n #checks name to see if type comment or post\n if post_json['name'][:2] == 't1':\n outputdict[outputnum] = post_json\n outputnum += 1\n\n obj = {\n\t\t\t\t\t\"_id\": post_json['name'],\n \"comment\": post_json\n\t\t\t\t}\n store = mycol_comp.insert_one(obj)\n #post json\n else :\n #print(\"Post with a keyword\")\n post_dict[post_json['name']] = post_json\n obj = {\n\t\t\t\t\t\"_id\": post_json['name'],\n \"post\": post_json\n\t\t\t\t}\n post_store = mycol_comp_posts.insert_one(post_json)\n return\n\n\ndef searchSubComments(comment):\n #print(\"------\", type(comment['data']['replies']['data']['children']))\n\n replies = comment['data']['replies']['data']['children']\n\n for reply in replies:\n if(reply['kind'] != 't1'): #only get actual comments\n continue\n checkKeywords(reply['data']['body'], reply['data']) #check the text\n if(reply['data']['replies'] != \"\"):\n searchSubComments(reply)\n\n\ndef scanSubreddit(subreddit_name):\n\n r = requests.get(r'https://www.reddit.com/r/' + subreddit_name + '/top/.json?t=day', headers = {'User-agent': 'cs415_crawler'})\n\n subreddit_json = r.json()\n\n for postnum in range(len(subreddit_json['data']['children'])):\n \n post_url = subreddit_json['data']['children'][postnum]['data']['permalink']\n #print(post_url)\n # gets the postnum-th post on the front page of this subreddit\n c = requests.get(r'https://www.reddit.com'+post_url+'.json', headers = {'User-agent': 'cs415_crawler'})\n #print('https://www.reddit.com'+post_url+'.json')\n\n post_json = c.json()\n # comments json will become a list of dictionaries, one dictionary for the actual post and\n # one for the comments.\n\n #if post has any of our peeps in text, add it to the dictionary\n #to get post data, like title text : (post_json[0]['data']['children'][0]['data']['title'])\n checkKeywords(post_json[0]['data']['children'][0]['data']['title'], post_json[0]['data']['children'][0]['data'])\n\n base_comments = post_json[1]['data']['children']\n #num_comments = len(base_comments)\n #print(\"Number of base comments in this post: \", num_comments)\n # gets the number of base level comments in this post.\n\n if(len == 0):\n return #TODO placeholder exit condition\n\n #iterate through ALL base level comments in this post\n for basecomment in base_comments:\n if(basecomment['kind'] != 't1'): #only get actual comments\n continue\n try:\n checkKeywords(basecomment['data']['body'], basecomment['data']) #check the text\n if(basecomment['data']['replies'] != \"\"):\n #print(\"---Subcomments found.\")\n searchSubComments(basecomment)\n except:\n print(\"Unexpected error:\", sys.exc_info()[0])\n print(\"---comment: \", basecomment['data']['body'])\n\ndef main():\n day = 24 * 60 * 60\n while(True):\n now = datetime.now()\n for subreddit in subreddits:\n scanSubreddit(subreddit)\n break\n global outputdict\n global outputnum\n global post_dict\n #TODO change file path\n # with open('sample2.json', \"w\") as outfile:\n # json.dump(outputdict, outfile, indent = 4)\n #print(len(post_dict))\n end = datetime.now()\n #calculate to sleep so we begin crawl at same time tomorrow\n sleep_time = day - (end-now).total_seconds()\n #print(\"A little sleepy\")\n time.sleep(sleep_time) \nmain()","sub_path":"part-1-data-collection/project-1-2-implementation-ds-415-team-main/reddit_request.py","file_name":"reddit_request.py","file_ext":"py","file_size_in_byte":5310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"381567035","text":"\"\"\"\nRegression tests for Ecobee 3.\n\nhttps://github.com/home-assistant/home-assistant/issues/15336\n\"\"\"\n\nfrom homeassistant.components.climate.const import (\n SUPPORT_TARGET_TEMPERATURE, SUPPORT_OPERATION_MODE)\nfrom tests.components.homekit_controller.common import (\n setup_accessories_from_file, setup_test_accessories, Helper\n)\n\n\nasync def test_ecobee3_setup(hass):\n \"\"\"Test that a Ecbobee 3 can be correctly setup in HA.\"\"\"\n accessories = await setup_accessories_from_file(hass, 'ecobee3.json')\n pairing = await setup_test_accessories(hass, accessories)\n\n entity_registry = await hass.helpers.entity_registry.async_get_registry()\n\n climate = entity_registry.async_get('climate.homew')\n assert climate.unique_id == 'homekit-123456789012-16'\n\n climate_helper = Helper(hass, 'climate.homew', pairing, accessories[0])\n climate_state = await climate_helper.poll_and_get_state()\n assert climate_state.attributes['friendly_name'] == 'HomeW'\n assert climate_state.attributes['supported_features'] == (\n SUPPORT_TARGET_TEMPERATURE | SUPPORT_OPERATION_MODE\n )\n\n occ1 = entity_registry.async_get('binary_sensor.kitchen')\n assert occ1.unique_id == 'homekit-AB1C-56'\n\n occ1_helper = Helper(\n hass, 'binary_sensor.kitchen', pairing, accessories[0])\n occ1_state = await occ1_helper.poll_and_get_state()\n assert occ1_state.attributes['friendly_name'] == 'Kitchen'\n\n occ2 = entity_registry.async_get('binary_sensor.porch')\n assert occ2.unique_id == 'homekit-AB2C-56'\n\n occ3 = entity_registry.async_get('binary_sensor.basement')\n assert occ3.unique_id == 'homekit-AB3C-56'\n","sub_path":"tests/components/homekit_controller/specific_devices/test_ecobee3.py","file_name":"test_ecobee3.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"402803668","text":"# coding: utf-8\nfrom __future__ import unicode_literals\n\nimport unittest\ntry:\n from unittest.mock import MagicMock\nexcept ImportError:\n from mock import MagicMock\n\nfrom pyshorteners.shorteners import Shortener, show_current_apis\nfrom pyshorteners.utils import is_valid_url\nfrom pyshorteners.exceptions import (UnknownShortenerException,\n ShorteningErrorException,\n ExpandingErrorException)\n\n\nclass ShortenersTest(unittest.TestCase):\n def setUp(self):\n self.url = 'http://www.google.com'\n self.module = __import__('pyshorteners.shorteners')\n self.test_url = 'http://www.pilgrims.com'\n\n def test_shorteners_type(self):\n shorteners = ['GoogleShortener', 'BitlyShortener', 'TinyurlShortener',\n 'AdflyShortener', 'IsgdShortener', 'SentalaShortener',\n 'GenericExpander', 'OwlyShortener']\n for shortener in shorteners:\n short = Shortener(shortener)\n self.assertEqual(type(short), short.__class__)\n\n def test_googl_shortener(self):\n engine = 'GoogleShortener'\n short = Shortener(engine)\n url = 'http://goo.gl/rjf0oI'\n shorten = short.short(self.test_url)\n self.assertEqual(shorten, url)\n\n self.assertEqual(short.expand(), self.test_url)\n self.assertEqual(short.expanded, self.test_url)\n\n self.assertEqual(short.shorten, url)\n self.assertEqual(short.qrcode(), 'http://chart.apis.google.com/'\n 'chart?cht=qr&chl={}&chs=120x120'.format(shorten))\n\n # test exceptions\n with self.assertRaises(ExpandingErrorException):\n short.expand('http://www.a.co')\n\n def test_readability_shortener(self):\n engine = 'ReadabilityShortener'\n short = Shortener(engine)\n url = 'http://blog.arc90.com/2010/11/30/silence-is-golden/'\n short_url = 'http://rdd.me/tg8if9uj'\n readbility_url = 'http://readability.com/articles/tg8if9uj'\n shorten = short.short(url)\n self.assertEqual(shorten, short_url)\n\n expand = short.expand(shorten)\n self.assertEqual(expand, readbility_url)\n\n # Test wrong url_id\n short = Shortener(engine)\n with self.assertRaises(ExpandingErrorException):\n expand = short.expand('http://www.wqe.cc')\n\n def test_tinyurl_shortener(self):\n engine = 'TinyurlShortener'\n short = Shortener(engine)\n url = 'http://tinyurl.com/nc9m936'\n shorten = short.short(self.test_url)\n self.assertEqual(shorten, url)\n\n self.assertEqual(short.expand(), self.test_url)\n self.assertEqual(short.expand(url), self.test_url)\n\n self.assertEqual(short.expanded, self.test_url)\n self.assertEqual(short.shorten, url)\n self.assertEqual(short.qrcode(), 'http://chart.apis.google.com/'\n 'chart?cht=qr&chl={}&chs=120x120'.format(shorten))\n\n def test_adfly_shortener(self):\n engine = 'AdflyShortener'\n short = Shortener(engine, key='abcd', uid='123')\n url = 'http://www.google.com/'\n\n short.short = MagicMock(return_value='http://adf.ly/test')\n short.short(url)\n short.short.assert_called_with(url)\n\n expand = short.expand('http://adf.ly/test')\n self.assertEqual(expand, 'http://adf.ly/test')\n\n # test with no key params\n with self.assertRaises(TypeError):\n short = Shortener(engine).short('http://www.google.com')\n\n def test_bitly_shortener(self):\n engine = 'BitlyShortener'\n short = Shortener(engine, bitly_api_key='abc', bitly_login='123x')\n url = 'http://www.google.com/'\n short_url = 'http://bit.ly/xxx'\n\n # test with no mock\n with self.assertRaises(ShorteningErrorException):\n short = short.short(url)\n\n # mocking the results\n short.expand = MagicMock(return_value=url)\n short.short = MagicMock(return_value='http://bit.ly/SsdA')\n\n short.short(url)\n short.short.assert_called_with(url)\n short.expand(short_url)\n short.expand.assert_called_with(short_url)\n\n # test with no key params\n with self.assertRaises(TypeError):\n short = Shortener(engine).short('http://www.google.com')\n\n def test_owly_shortener(self):\n engine = 'OwlyShortener'\n short = Shortener(engine, api_key='abc')\n url = 'http://www.google.com/'\n short_url = 'http://ow.ly/xxx'\n\n # test with no mock\n with self.assertRaises(ShorteningErrorException):\n short = short.short(url)\n\n # mocking\n short.short = MagicMock(return_value='http://ow.ly/SsdA')\n short.expand = MagicMock(return_value=url)\n\n short.short(url)\n short.short.assert_called_with(url)\n\n short.expand(short_url)\n short.expand.assert_called_with(short_url)\n\n # test with no key params\n with self.assertRaises(TypeError):\n short = Shortener(engine).short('http://www.google.com')\n\n def test_isgd_shortener(self):\n engine = 'IsgdShortener'\n short = Shortener(engine)\n url = 'http://www.pilgrims.com'\n\n shorten = short.short(url)\n expand = short.expand(shorten)\n self.assertEqual(expand, url)\n self.assertEqual(short.qrcode(), 'http://chart.apis.google.com/'\n 'chart?cht=qr&chl={}&chs=120x120'.format(shorten))\n\n def test_sentala_shortener(self):\n engine = 'SentalaShortener'\n short = Shortener(engine)\n url = 'http://www.pilgrims.com'\n\n shorten = short.short(url)\n expand = short.expand(shorten)\n self.assertEqual(expand, url)\n self.assertEqual(short.qrcode(), 'http://chart.apis.google.com/'\n 'chart?cht=qr&chl={}&chs=120x120'.format(shorten))\n\n def test_qrcx_shortener(self):\n engine = 'QrCxShortener'\n short = Shortener(engine)\n url = 'https://www.facebook.com/'\n\n shorten = short.short(url)\n expand = short.expand(shorten)\n self.assertEqual(expand, url)\n self.assertEqual(short.qrcode(), 'http://chart.apis.google.com/'\n 'chart?cht=qr&chl={}&chs=120x120'.format(shorten))\n\n def test_wrong_shortener_engine(self):\n engine = 'UnknownShortener'\n with self.assertRaises(UnknownShortenerException):\n Shortener(engine)\n\n def test_is_valid_url(self):\n bad = 'www.google.com'\n good = 'http://www.google.com'\n\n self.assertTrue(is_valid_url(good))\n self.assertFalse(is_valid_url(bad))\n\n s = Shortener('TinyurlShortener')\n with self.assertRaises(ValueError):\n url = 'http://12'\n s.short(url)\n\n def test_generic_expander(self):\n # testing new generic expander. Uses another shortener to test\n short = Shortener(\"TinyurlShortener\")\n shorten = short.short(self.test_url)\n\n engine = \"GenericExpander\"\n expander = Shortener(engine)\n\n with self.assertRaises(NotImplementedError):\n expander.short('http://www.test.com')\n\n result_url = expander.expand(shorten)\n # A valid url result is enough for answer\n self.assertEqual(result_url, self.test_url)\n\n def test_show_current_apis(self):\n apis = ['Goo.gl', 'Bit.ly', 'Ad.fly', 'Is.gd', 'Senta.la',\n 'Generic', 'QrCx', 'Ow.ly']\n self.assertEqual(show_current_apis(), apis)\n\n def test_none_qrcode(self):\n shortener = Shortener('TinyurlShortener')\n self.assertIsNone(shortener.qrcode())\n","sub_path":"tests/test_shorteners.py","file_name":"test_shorteners.py","file_ext":"py","file_size_in_byte":7679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"397630086","text":"import tensorflow as tf\nfrom tensorflow.contrib.layers import flatten\nimport numpy as np\n\ndef get_output_size(input, step):\n pass\n\ndef get_mnist():\n from tensorflow.examples.tutorials.mnist import input_data\n\n mnist = input_data.read_data_sets(\"MNIST_data/\", reshape=False)\n return mnist\n\ndef read_data(mnist, datatype='train'):\n X, y = getattr(mnist, datatype).images, getattr(mnist, datatype).labels\n # X_validation, y_validation = mnist.validation.images, mnist.validation.labels\n # X_test, y_test = mnist.test.images, mnist.test.labels\n\n assert(len(X) == len(y))\n\n print(\"Image Shape: {}\".format(X[0].shape))\n print(\"Set: {} samples\".format(len(X)))\n\n return X, y\n\n\ndef normalize_data(X):\n # Pad images with 0s\n X = np.pad(X, ((0, 0), (2, 2),(2, 2), (0, 0)), 'constant')\n \n print(\"Updated Image Shape: {}\".format(X[0].shape))\n return X\n\n\nEPOCHS = 10\nBATCH_SIZE = 128\n\ndef get_LeNet(X):\n mu = 0\n sigma = 0.1\n\n # TODO: Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6.\n conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 1, 6), mean=mu, stddev=sigma))\n conv1_b = tf.Variable(tf.zeros(6))\n conv1 = tf.nn.conv2d(X, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b\n\n # TODO: Activation.\n conv1 = tf.nn.relu(conv1)\n\n # TODO: Pooling. Input = 28x28x6. Output = 14x14x6.\n conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')\n\n # TODO: Layer 2: Convolutional. Output = 10x10x16.\n conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 6, 16), mean=mu, stddev=sigma))\n conv2_b = tf.Variable(tf.zeros(16))\n conv2 = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b\n \n # TODO: Activation.\n conv2 = tf.nn.relu(conv2)\n\n # TODO: Pooling. Input = 10x10x16. Output = 5x5x16.\n conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')\n\n # TODO: Flatten. Input = 5x5x16. Output = 400.\n fc0 = flatten(conv2)\n \n # TODO: Layer 3: Fully Connected. Input = 400. Output = 120.\n fc1_W = tf.Variable(tf.truncated_normal([400, 120], mean=mu, stddev=sigma))\n fc1_b = tf.Variable(tf.zeros(120))\n fc1 = tf.matmul(fc0, fc1_W) + fc1_b\n \n # TODO: Activation.\n fc1 = tf.nn.relu(fc1)\n\n # TODO: Layer 4: Fully Connected. Input = 120. Output = 84.\n fc2_W = tf.Variable(tf.truncated_normal([120, 84], mean=mu, stddev=sigma))\n fc2_b = tf.Variable(tf.zeros(84))\n fc2 = tf.matmul(fc1, fc2_W) + fc2_b\n \n # TODO: Activation.\n fc2 = tf.nn.relu(fc2)\n\n # TODO: Layer 5: Fully Connected. Input = 84. Output = 10.\n fc3_W = tf.Variable(tf.truncated_normal([84, 10], mean=mu, stddev=sigma))\n fc3_b = tf.Variable(tf.zeros(10))\n logits = tf.matmul(fc2, fc3_W) + fc3_b\n\n return logits\n\n\nif __name__ == \"__main__\":\n # Input definitions\n x = tf.placeholder(tf.float32, (None, 32, 32, 1))\n y = tf.placeholder(tf.int32, (None))\n one_hot_y = tf.one_hot(y, 10)\n\n # LeNet definitions\n rate = 0.001\n logits = get_LeNet(x)\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)\n loss_operation = tf.reduce_mean(cross_entropy)\n optimizer = tf.train.AdamOptimizer(learning_rate=rate)\n training_operation = optimizer.minimize(loss_operation)\n\n correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))\n accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n saver = tf.train.Saver()\n\n # Data\n mnist = get_mnist()\n X_train, y_train = read_data(mnist, 'train')\n X_train = normalize_data(X_train)\n X_validation, y_validation = read_data(mnist, 'validation')\n X_validation = normalize_data(X_validation)\n\n def evaluate(X_data, y_data):\n num_examples = len(X_data)\n total_accuracy = 0\n sess = tf.get_default_session()\n for offset in range(0, num_examples, BATCH_SIZE):\n batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]\n accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y})\n total_accuracy += (accuracy * len(batch_x))\n return total_accuracy / num_examples\n\n from sklearn.utils import shuffle\n with tf.Session() as session:\n session.run(tf.global_variables_initializer())\n num_examples = len(X_train)\n for i in range(EPOCHS):\n X_train, y_train = shuffle(X_train, y_train)\n for offset in range(0, num_examples, BATCH_SIZE):\n end = offset + BATCH_SIZE\n batch_X = X_train[offset: end]\n batch_y = y_train[offset: end]\n session.run(training_operation, feed_dict={x: batch_X, y: batch_y})\n \n validation_accuracy = evaluate(X_validation, y_validation)\n print(\"EPOCH {} ...\".format(i+1))\n print(\"Validation Accuracy = {:.3f}\".format(validation_accuracy))\n print()\n \n saver.save(session, './lenet')\n print(\"Model saved\")\n","sub_path":"python/lenet_tf.py","file_name":"lenet_tf.py","file_ext":"py","file_size_in_byte":5109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"143064588","text":"import tkinter as tk\nfrom pynput import mouse\nfrom pynput import keyboard\nfrom pynput.mouse import Button, Controller\nfrom pynput.keyboard import Key, Controller as KeyController\nimport time\nimport pickle\n\nroot= tk.Tk()\nroot.title(\"Recorder\")\n#####################################################################################\n\ndata= []\nptime= time.time()\nlive= True\nspeedx = 1\nkey_listener= None\nmouse_listener= None\ncounter= 0\n\nywait= \"none\"\nout_cap= {}\n\n\n#############################################################\n\nimport pyautogui\nimport pyautogui\n\n\ndef capture_area(data, name):\n reg= (data['left'], data['top'], data['width'], data['height'])\n ss= pyautogui.screenshot(region= reg)\n ss.save(name)\n statusTv['Output Saved']\n return name \n\ndef capture():\n fname= nameE.get()\n screenWidth, screenHeight = pyautogui.size()\n x, y = pyautogui.position()\n width, height = (100, 60)\n sx, sy= width/2, height/2\n \n left= x- sx \n if(left<0):\n left= 0\n top= y- sy \n if(top<0):\n top= 0\n\n if(x+sx>screenWidth):\n width= x+sx- screenWidth\n\n if(y+sy>screenHeight):\n height= y+ sy- screenHeight\n\n reg= ( left, top, width, height)\n ss= pyautogui.screenshot(region= reg)\n\n name= \"imgs/{}__{}_{}.png\".format(fname, x, y)\n ss.save(name)\n return name \n\n\n#############################################################\n\n\n\n\n\ndef on_click(x, y, button, pressed):\n print(\"PRessed is {}\".format(pressed))\n global ywait, out_cap, counter\n if(ywait=='out_br' and pressed):\n out_cap['width']= x - out_cap['left']\n out_cap['height']= y - out_cap['top']\n statusTv['text']= \"Done\"\n ywait= 'none'\n capture_area(out_cap, \"imgs/{}_{}_out.png\".format(nameE.get(), counter))\n counter+= 1\n return live\n\n if(ywait=='out_tl' and pressed):\n out_cap['left']= x\n out_cap['top']= y \n statusTv['text']= \"Select Bottom Right\"\n ywait= 'out_br'\n return live \n\n\n\n #ss= capture()\n global ptime\n #if(pressed):\n # return \n pos= [x,y]\n dur= time.time()- ptime\n data.append({'type': 'mouse', \"dur\":dur, \"pos\":pos, \"btn\": button, \"pressed\":pressed})\n print(str(x)+\" , \"+str(y)+ \" with \"+str(dur))\n ptime= time.time()\n return live\n \ndef on_scroll(x, y, dx, dy):\n global ptime \n pos= [x,y]\n dur= time.time()- ptime\n amount= [dx, dy]\n data.append({'type':'scroll', 'dur': dur, 'pos': pos, 'amount': amount})\n print('Scrolled {0} at {1}'.format('down' if dy < 0 else 'up',(x, y)))\n return live \n\ndef on_press(key):\n global ptime\n print(\"{} pressed\".format(key))\n if key == keyboard.Key.esc:\n stopRec(last= False)\n return False\n if(key== keyboard.Key.home and not is_rec):\n return False \n dur= time.time()- ptime\n data.append({'type':'keypress', 'dur': dur, 'key': key})\n print(\"Key \"+str(key)+\" with \"+str(dur))\n ptime= time.time()\n return live \n\ndef on_release(key):\n global ptime\n print('{0} released'.format(key))\n if key == keyboard.Key.esc:\n stopRec(last= False)\n return False\n if(key== keyboard.Key.home and not is_rec):\n return False \n dur= time.time()- ptime\n data.append({'type':'keyrelease', 'dur': dur, 'key': key})\n print(\"Key \"+str(key)+\" with \"+str(dur))\n ptime= time.time()\n return live \n\ndef save():\n fname= nameE.get()\n name= \"data/{}_{}_input.p\".format(fname, counter)\n pickle.dump(data, open(name, \"wb\"))\n statusTv['text']= \"Recording Saved Successfully\"\n statusTv['fg']= 'green'\n\nis_rec= False\n\ndef startRec():\n global key_listener, mouse_listener, ptime, is_rec\n key_listener = keyboard.Listener(on_press= on_press, on_release=on_release)\n key_listener.start()\n #mouse_listener= mouse.Listener(on_click= on_click, on_scroll= on_scroll)\n mouse_listener= mouse.Listener(on_click= on_click)\n mouse_listener.start()\n print(\"Recording Started\")\n is_rec= True \n ptime= time.time() \n statusTv['text']= \"Press ESC to Stop\"\n statusTv['fg']= \"red\"\n\ndef stopRec(last= True):\n global is_rec\n if(last):\n del data[-1]\n save()\n key_listener.stop() \n mouse_listener.stop() \n is_rec= False \n statusTv['text']= \"Recording Stopped\"\n statusTv['fg']= \"green\"\n\n\n\ndef captureOutput():\n global mouse_listener, ywait\n statusTv['text']= \"Select Top-Left\"\n ywait= \"out_tl\"\n mouse_listener= mouse.Listener(on_click= on_click)\n mouse_listener.start()\n\n\n\n\n\n\n#####################################################################################\nstatusTv= tk.Label(root, text= \"READY\", fg= 'green', font = \"Verdana 12 bold\")\nstatusTv.pack()\nnameE= tk.Entry(root)\nnameE.pack()\nstartB= tk.Button(root, text= \"Start Recording\", width= 25, command= startRec)\nstartB.pack() \nstopB= tk.Button(root, text= \"Stop Recording\", width= 25, command= stopRec)\nstopB.pack() \n\nplayB= tk.Button(root, text= \"Record Input\", width= 25, command= startRec)\nplayB.pack() \n\nplayB= tk.Button(root, text= \"Capture Output\", width= 25, command= captureOutput)\nplayB.pack() \n\n\n\nexitB= tk.Button(root, text= \"Close\", width= 25, command= root.destroy)\nexitB.pack() \n\n#root.attributes('-topmost', True)\n#root.update()\n\nroot.mainloop() ","sub_path":"old/record.py","file_name":"record.py","file_ext":"py","file_size_in_byte":5281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"515471138","text":"import ROOT as r\nfrom numpy import dot, random\nimport numpy as np\nimport json\nfrom utils import writejson\nimport sys, os\nimport copy\n#________________________________________\ndef getEff(resmat,htruth,y):\n nxx = htruth.GetNbinsX()\n xx = y%nxx\n if xx==0: xx=nxx\n yy = int((y-1)/nxx)+1\n if htruth.GetBinContent(xx,yy)==0. or resmat.Integral(0,-1,y,y)==0.:\n return 0.\n return resmat.Integral(0,-1,y,y)/htruth.GetBinContent(xx,yy)\n\n\n#________________________________________\ndef histo2list(histo):\n nbinsx = histo.GetNbinsX()\n binlist = [histo.GetBinContent(x) for x in range(1,nbinsx+1)]\n print (histo.GetBinContent(-1),' ',histo.GetBinContent(nbinsx+1))\n binlist[0]=binlist[0]+histo.GetBinContent(-1)\n binlist[-1]=binlist[-1]+histo.GetBinContent(nbinsx+1)\n\n return binlist\n\n\n#________________________________________\ndef testinputs(truth,resmat,reco):\n myreco = dot(truth,resmat)\n assert(len(myreco)==len(reco)),'check resmat truth failed, not same dimension '\n for i in range(len(myreco)):\n if reco[i]==0.:print('reco bin={} value={}'.format(i,reco[i]))\n if abs(1-myreco[i]/reco[i])>0.005:\n print ('----------------> bin={} failed with diff={}. dot={} reco={}'.format(i, abs(1-myreco[i]/reco[i]),myreco[i], reco[i]))\n\n#________________________________________\ndef gethisto(tfn,hname):\n tfo=None\n h=None\n\n try:\n tfo = r.TFile.Open(tfn)\n except IOError as e:\n print ('I/O error({0}): {1}').format(e.errno, e.strerror)\n except:\n print ('Unexpected error:'), sys.exc_info()[0]\n\n try:\n h = tfo.Get(hname)\n if h==None: \n print ('the histogram={} does not exists'.format(hname))\n sys.exit(3)\n except IOError as e:\n print ('I/O error({0}): {1}'.format(e.errno, e.strerror))\n except:\n print ('Unexpected error:', sys.exc_info()[0])\n\n\n if h!=None:\n hclone=copy.deepcopy(h)\n tfo.Close()\n return hclone\n return h\n\n\n#________________________________________\ndef getSystList(inputfile):\n systs = []\n try:\n infile = open(inputfile, 'r')\n lines = infile.readlines()\n for line in lines:\n if ('#' not in line) and (line is not '\\n') :\n systs.append(line.replace('\\n', ''))\n except:\n sys.exit('The systematics could not be recovered!!')\n\n return systs\n\n\n\n\n\n#________________________________________\nif(__name__==\"__main__\"):\n\n if len(sys.argv)!=3:\n sys.exit('usage: python python/makeresmat.py infile.root variable')\n\n tfn = sys.argv[1]\n hname_data = 'mcdata'\n hname_truth = 'ttbar_truth'\n hname_resmat = 'reco_vs_truth'\n hname_bkg = ['singletop', 'diboson']\n systs = getSystList('python/systematics.txt')\n\n if '.root' not in tfn:\n sys.exit('input file is not a ROOT file')\n\n if not os.path.isfile(tfn):\n sys.exit('inut file does not exist')\n \n h_data = gethisto(tfn,hname_data)\n h_truth = gethisto(tfn,hname_truth)\n h_bkg = [gethisto(tfn,i) for i in hname_bkg]\n \n l_data = histo2list(h_data)\n l_truth = histo2list(h_truth)\n bkg_dict = {}\n for i, j in zip(hname_bkg, h_bkg):\n bkg_dict[i] = histo2list(j)\n\n\n if not os.path.isdir(sys.argv[2]):\n os.mkdir(sys.argv[2])\n\n writejson(sys.argv[2]+'/data.json',l_data)\n writejson(sys.argv[2]+'/truth.json',l_truth)\n writejson(sys.argv[2]+'/bkg.json',bkg_dict)\n\n h_mig = gethisto(tfn,hname_resmat)\n\n nbinsx = h_mig.GetNbinsX()\n nbinsy = h_mig.GetNbinsY()\n\n migration = []\n for y in range(1,nbinsy+1):\n truthbin = []\n norm = h_mig.Integral(0,-1,y,y)\n for x in range(1,nbinsx+1):\n value=0.\n if h_mig.GetBinContent(x,y) >0:\n value = h_mig.GetBinContent(x,y)/norm\n value = value*getEff(h_mig,h_truth,y)\n truthbin.append(value)\n migration.append(truthbin)\n\n writejson(sys.argv[2]+'/resmat.json',migration)\n testinputs(l_truth, migration, l_data)\n\n\n ## Get systematic variations\n\n # For signal\n h_ttbar = gethisto(tfn, 'ttbar')\n l_ttbar = np.array(histo2list(h_ttbar))\n ttbar_syst_dict = {}\n for syst in systs:\n h_syst = gethisto(tfn, 'ttbar_{}'.format(syst))\n l_syst = np.array(histo2list(h_syst))\n ttbar_syst_dict[syst] = (l_syst-l_ttbar) / l_ttbar\n\n writejson(sys.argv[2]+'/ttbar_syst.json', ttbar_syst_dict)\n\n\n ## For backgrounds\n bkg_syst_dict = {}\n for syst in systs:\n syst_dict = {} \n for bkg in hname_bkg:\n h_bkg_syst = gethisto(tfn, '{}_{}'.format(bkg, syst))\n l_bkg_syst = np.array(histo2list(h_bkg_syst))\n syst_dict[bkg] = (l_bkg_syst-np.array(bkg_dict[bkg])) / np.array(bkg_dict[bkg])\n bkg_syst_dict[syst] = syst_dict\n\n writejson(sys.argv[2]+'/bkg_syst.json',bkg_syst_dict)\n","sub_path":"python/makeresmat.py","file_name":"makeresmat.py","file_ext":"py","file_size_in_byte":4906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"448101153","text":"# -*- coding: utf-8 -*-\n# -*- coding: utf-8 -*-\nfrom .main import *\n\n__copyright__ = 'Copyright (C) 2020-2021 yamahubuki, ACT Laboratory'\n__version__ = '1.3.0'\n__license__ = 'MIT'\n__author__ = 'yamahubuki'\n__author_email__ = 'itiro.ishino@gmail.com'\n__url__ = 'https://github.com/actlaboratory/implicitGrantManager'\n\n__all__ = ['implicitGrantManager']\n","sub_path":"implicitGrantManager/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"14975135","text":"\"\"\" Trade_Allocation:1.2.5 \"\"\"\n\n'''-----------------------------------------------------------------------------\n MODULE\n InstrUploadSettings - Defines what instrument checks that shall be performed\n when instruments are uploaded from the external exchanges, and defines\n how to find the isin code of the underlying instrument to a derivative if\n you wish to replace the underlying received from the market with another\n underlying instrument.\n \n (c) Copyright 2000 by Front Capital Systems AB. All rights reserved.\n \n DESCRIPTION\n The FMessageAdaptations module allows the user to define a different\n underlying for a derivative compared to what is sent from AMAS. The \n mapping rules are defined in the map_underlying_isin_dict dictionary\n below. The FMessageAdaptations module also allows the user to set a\n number of collision prevensions to avoid instruments from different\n markets to overwrite one another.\n\n Mapping rules are defined as follows:\n =====================================\n\n In the map_underlying_isin_dict dictionary you define your general rules.\n A typical example would be to use a common EquityIndex as underlying for\n both futures and options. \n \n A python dictionary is created on the format: 'old_isin':'new_isin'\n \n Example:\n \n Eurex sends out the ISIN: DE0008469495, as underlying for futures on the DAX. \n Eurex sends out the ISIN: DE0008469594, as underlying for options on the DAX.\n The desired underlying ISIN for derivatives on DAX is: DE0008469008.\n \n If desired to have the EquityIndex with \"true\" ISIN as underlying for \n derivatives, the dictionary would look as follows:\n\n map_underlying_isin_dict={\n 'DE0008469594':'DE0008469008',\n 'DE0008469495':'DE0008469008'\n } \n \n\n DATA-PREP\n The module FMessageAdaptations can check so that:\n\n 1. Currencies are not overwritten by other instruments with the same INSID.\n 2. Instruments with the same insid but different isin are not overwritten. In\n this case the market name is appended to the INSID.\n 3. We ensure that SWX long name are unique the short name is appended to the\n long name if needed.\n 4. Instruments with the same ISIN but different INSID or CURRENCIES are not\n overwritten. The instrument section of the message is deleted, the orderbook\n and all other related information is created though.\n 5. Bonds that already has expired are not inserted into the ADS. This may\n happen on SWX.\n 6. Replace incoming 00000000 in leg start_day with today's date.\n 7. Replace underlying instrument as specified in InstrUploadSettings.\n 8. Equity index futures are inserted to the page: hedgeChoice.\n 9. CombinationLinks are created for Basis instruments traded on Xetra (EUREX BONDS).\n 10. Equity index are inserted to the page: NonSplitIndexes.\n 11. Equity index are inserted to the page: betaIndexChoice.\n \n REFERENCES\n Regular expressions in python:\n\n http://www.python.org/doc/current/lib/module-re.html\n \n\n ENDDESCRIPTION\n-----------------------------------------------------------------------------'''\ncheck_swx_long = 1 # If same SWX long name append short name to long name\ncheck_insid = 1 # If same INSID but different ISIN append market name to INSID.\ncheck_isin = 1 # If same ISIN but different INSID or CURR, only create orderbook.\ncheck_currency = 1 # If same INSID but existing instrument is of type CURR. Delete message.\ncheck_der_und = 1 # If the value of UND_INSADDR.ISIN exist in the left column in the\n # map_underlying_isin_dict below, then replace it whith the ISIN\n # in the right column. \ncheck_expired_bond = 1 # Delete message if Bond has expired.\ncheck_start_day_leg =\t1 # If START_DAY = 00000000, then START_DAY=TODAY.\ncreate_xetra_basis_comb_link = 1 # Create CombinationLinks for Basis instruments on Xetra.\ninsert_eq_index_fut_into_hedgechoice = 1 # Automatically insert future into hedgeChoice.\ninsert_eq_index_into_nonsplitindexes = 1 # Automatically insert EqIndex into NonSplitIndexes.\ninsert_eq_index_into_betaindexchoice = 1 # Automatically insert EqIndex into betaIndexChoice.\n\nmap_underlying_isin_dict={\n 'DE0008469594':'DE0008469008',\n 'DE0008469495':'DE0008469008',\n 'CH0008616432':'CH0009980894',\n 'CH0008616382':'CH0009980894'\n}\n","sub_path":"Python modules/InstrUploadSettingsTemplate.py","file_name":"InstrUploadSettingsTemplate.py","file_ext":"py","file_size_in_byte":4480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"199867456","text":"from PySide6.QtWidgets import QApplication\nfrom .main_window import MainWindow\nimport sys\n\n\ndef main() -> int:\n app = QApplication()\n app.main_window = MainWindow()\n app.main_window.show()\n return app.exec()\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"src/tat/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"390957521","text":"\"\"\"\nDefinition of TreeNode:\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param root: the root of binary tree\n @return: new root\n \"\"\"\n def upsideDownBinaryTree(self, root):\n # write your code here\n if not root:\n return None\n \n st, node = [], root\n while node:\n st.append(node)\n node = node.left\n \n root = st.pop()\n node = root\n while st:\n n = st.pop()\n node.right = n\n node.left = n.right\n \n node = node.right\n node.left, node.right = None, None\n \n return root","sub_path":"PythonLeetcode/LintCode/649_BinaryTreeUpsideDown.py","file_name":"649_BinaryTreeUpsideDown.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"389960208","text":"import imgkit,os\n\n\ndef html_to_img(input_dir, img_format='jpg'):\n\n html_files = [file for file in os.listdir(input_dir) if file.endswith('.html')]\n\n for html_file in html_files:\n\n input_file_path = os.path.join(input_dir, html_file)\n print(\"Input HTML File : \" + input_file_path)\n\n output_file_dir = os.path.join(input_dir, 'images')\n output_file_path = os.path.join(output_file_dir, os.path.splitext(html_file)[0]+ '.' + img_format)\n print(\"Output JPG File : \" + output_file_path)\n\n \"\"\" options = {\n 'disable-smart-width': False\n }\"\"\"\n\n imgkit.from_file(input_file_path, output_file_path)","sub_path":"src/core/htmltoimg.py","file_name":"htmltoimg.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"144054206","text":"#!usr/bin/env python3\n# coding: utf8\n\nimport sys, os\n\ndef main():\n\ttry:\n\t\taddress = sys.argv[1]\n\texcept:\n\t\taddress = input(\"[addr] : \");\n\n\ttry:\n\t\timage = sys.argv[2]\n\texcept:\n\t\timage = input('[imag] : ')\n\n\tprint('[addr] : ' + address)\n\tprint('[imag] : ' + image)\n\n\thtml_code = \"\"\"\n\n\n\n\t\n\tMail\n\n\n\t\"Image\"\n\n\n\"\"\"\n\n\thtml_file = open('mail.html', \"w\")\n\thtml_file.write(html_code)\n\thtml_file.close()\n\n\tdescription = input(\"[desc] (default is 'Yo Dawg! Lol!') : \")\n\tif description == '':\n\t\tdescription = 'Yo Dawg! Lol!'\n\n\tfile = input(\"[file] (default is '') : \")\n\n\tcommand = 'mutt -e \"set content_type=text/html\" ' + address + ' -s \"' + description + '\" -a ' + file + ' < mail.html'\n\tif file == '':\n\t\tcommand = 'mutt -e \"set content_type=text/html\" ' + address + ' -s \"' + description + '\" < mail.html'\n\n\tprint(command)\n\n\tok = input(\"Ok? [y/N] : \")\n\tif (ok.lower() == \"y\"):\n\t\tprint(\"[...]\")\n\t\tos.system(command)\n\telse:\n\t\tsys.exit(1)\n\nif __name__ == '__main__':\n\tmain()","sub_path":"mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"45719376","text":"import json\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nfrom collections import Counter\nimport string\nimport re\nimport os\nimport threading\nimport vincent\nfrom vincent import AxisProperties,PropertySet,ValueRef\nimport pandas\n\n\n\nemoticons_str = r\"\"\"\n (?:\n [:=;] # Eyes\n [oO\\-]? # Nose (optional)\n [D\\)\\]\\(\\]/\\\\OpP] # Mouth\n )\"\"\"\n\nregex_str = [\n emoticons_str,\n r'<[^>]+>', # HTML tags\n r'(?:@[\\w_]+)', # @-mentions\n r\"(?:\\#+[\\w_]+[\\w\\'_\\-]*[\\w_]+)\", # hash-tags\n r'http[s]?://(?:[a-z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-f][0-9a-f]))+', # URLs\n\n r'(?:(?:\\d+,?)+(?:\\.?\\d+)?)', # numbers\n r\"(?:[a-z][a-z'\\-_]+[a-z])\", # words with - and '\n r'(?:[\\w_]+)', # other words\n r'(?:\\S)' # anything else\n]\n\ntokens_re = re.compile(r'(' + '|'.join(regex_str) + ')', re.VERBOSE | re.IGNORECASE)\nemoticon_re = re.compile(r'^' + emoticons_str + '$', re.VERBOSE | re.IGNORECASE)\n\n\ndef tokenize(s):\n return tokens_re.findall(s)\n\n\ndef preprocess(s, lowercase=False):\n tokens = tokenize(s)\n if lowercase:\n tokens = [token if emoticon_re.search(token) else token.lower() for token in tokens]\n return tokens\npunc=list(string.punctuation)\nstop=stopwords.words('english')+punc+['rt','via','...','0']\n\n\n\ndates=[]\n\ndef activate():\n x=0\n d=[]\n with open('tweets.json') as f:\n for l in f.readlines():\n if x%2==0:\n d.append(json.loads(l)['text'])\n tweet=json.loads(l)\n hash_terms = [t for t in preprocess(tweet['text']) if t.startswith('#')]\n\n if '#itavwal' in hash_terms:\n dates.append(tweet['created_at'])\n\n\n\n\n x=x+1\n else:\n x=x+1\n\n\n #time series hash tag vs dates\n ones = [1] * len(dates)\n idx = pandas.DatetimeIndex(dates)\n kv2 = pandas.Series(ones, index=idx)\n per_minute = kv2.resample('1Min').sum().fillna(0)\n #print(kv2)\n time_chart = vincent.Line(kv2)\n time_chart.axis_titles(x='Time', y='Freq')\n time_chart.to_json('time_chart.json')\n\n#make mega string\n tweet=\"\"\n for i in range(len(d)):\n tweet=tweet+d[i]\n\n#print(tweet)\n\n terms = [t for t in preprocess(tweet) if t not in stop and not t.startswith(('#', '@','amp','RT','\\'','The','\\u2026','http'))]\n c = Counter()\n c.update(terms)\n word_freq=c.most_common(20)\n labels,freq=zip(*word_freq)\n kv={'data':freq,'x':labels}\n bar=vincent.GroupedBar(kv,iter_idx='x')\n #ax = AxisProperties(labels=PropertySet(angle=ValueRef(value=90)))\n #bar.axes[0].properties = ax\n bar.colors(brew='Set1')\n bar.to_json('term_freq.json')\n print(c.most_common(20))\n\n\n\ndef th():\n threading.Timer(5.0,th).start()\n activate()\n print(chr(27) + \"[2J\")\n\nth();\n","sub_path":"Restful_app/textprocessing.py","file_name":"textprocessing.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"384892333","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom .game_entity import GameEntity, SetDataMeta\n\n__author__ = 'fyabc'\n\n\nclass Hero(GameEntity, metaclass=SetDataMeta):\n \"\"\"[NO_DESCRIPTION]\"\"\"\n\n _data = {\n 'id': None,\n 'name': '',\n 'package': 0,\n 'klass': 0,\n 'CAH': [0, 1, 1],\n 'description': '',\n }\n","sub_path":"HearthStone2/HearthStone/game/hero.py","file_name":"hero.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"92612584","text":"\"\"\"\nAuthor: Rajkumar Conjeevaram Mohan\nEmail: rajkumarcm@yahoo.com\n\"\"\"\n\nimport numpy as np\nimport re\n\nclass Data:\n \"\"\"------------------------------------------------------\n Use this to pre-process data for Neural Network training\n ------------------------------------------------------\"\"\"\n\n def load_csv(self, file_name, row_del, col_del, target_col=-1, numeric_target=True, ignore_cols=None):\n \"\"\"\n Assumes the first row to contain header information\n i.e., column names\n :param file_name: Absolute path to the file to be loaded\n :param row_del: delimiter used to separate rows\n :param col_del: delimiter used to separate columns\n :param target_col: Optional, an integer that represents the index of the target column\n :param ignore_cols: Optional, an integer or sequence of integers that represents the index of the columns to be\n ignored\n :return:\n \"\"\"\n file = open(file_name,'r')\n data = file.read()\n file.close()\n\n data = data.split(row_del)[1:]\n N = len(data)\n temp = data[0].split(col_del)\n M = len(temp)-1 # subtract 1 to exclude target column\n del_cols = None\n if ignore_cols is None:\n del_cols = 0\n else:\n del_cols = len(ignore_cols)\n\n A = np.zeros([N,M-del_cols])\n Y = []\n col_indices = np.array(range(M+1),dtype=np.int)\n col_indices = np.argwhere(col_indices != target_col)\n col_indices = np.array(list(filter(lambda x: all(x != ignore_cols),col_indices)))\n\n remove_rows = []\n r = re.compile(\"\\d+\\.?\\d*\")\n r_char = re.compile(\"[a-zA-Z\\-\\_]*\")\n for i in range(N):\n if data[i] != '':\n sample = np.array(data[i].split(col_del))\n temp_list = (sample[col_indices].ravel())\n for j in range(len(temp_list)):\n match = r.search(temp_list[j])\n if match is None:\n print(\"Debug...\")\n A[i,j] = np.float(match.group(0))\n\n if numeric_target:\n match = r.search(sample[target_col])\n Y.append(np.float(match.group(0)))\n else:\n match = r_char.search(sample[target_col])\n Y.append(np.str(match.group(0)))\n else:\n remove_rows.append(i)\n\n remove_rows = np.array(remove_rows,dtype=np.int)\n rows_indices = np.array(range(N),dtype=np.int)\n rows_indices = np.array(list(filter(lambda x: all(x != remove_rows),rows_indices)))\n A = A[rows_indices]\n\n Y = np.array(Y)\n return A,Y\n\n def partition_data(self, X, y, tr_size, shuffle=False):\n \"\"\"\n Splits the data into training, and validation set\n :param X: Array must be in shape: [Samples,Features]\n :param y: Array must be in shape: [Samples]\n :param tr_size: Int that represent the size of training set\n :param shuffle: (Optional) Boolean flag that allow the data to be shuffled prior to partitioning\n :return: X_tr, y_tr, X_vl, y_vl after shuffling (if enabled), and partitioning\n \"\"\"\n N, M = X.shape\n if shuffle:\n indices = np.arange(0,N)\n np.random.shuffle(indices)\n X = X[indices,:]\n y = y[indices]\n\n lim = tr_size\n X_tr = X[:lim, :]\n y_tr = y[:lim]\n X_vl = X[lim:, :]\n y_vl = y[lim:]\n return X_tr, y_tr, X_vl, y_vl\n\n def get_sample(self, X, y, size=1):\n \"\"\"\n As the name suggests, this function simply returns samples\n from given data\n :param X: Array must be of shape: [Samples, Features]\n :param y: Array must be of shape: [Samples]\n :param size: (Optional) Int that controls the number of samples returned\n :return: Sample input X, Sample target y\n \"\"\"\n N, M = X.shape\n indices = np.random.randint(0,N,size)\n X = X[indices,:]\n y = y[indices]\n return X, y\n\nif __name__ == '__main__':\n data = Data()\n X,Y = data.load_csv(file_name='/Users/Rajkumar/Downloads/energydata_complete.csv', \\\n row_del='\\n', \\\n col_del=',', \\\n target_col=1, \\\n numeric_target=False, \\\n ignore_cols=[0,27,28])\n print(\"Debug...\")","sub_path":"DigitRecognition/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"31893195","text":"import sys\nfrom base64 import b64encode\n\nimport requests\n\n\ndef get_token(client_id, client_secret):\n enc_auth = b64encode((client_id + ':' + client_secret).encode('ascii')).decode('ascii')\n resp = requests.post('https://account.kkbox.com/oauth2/token',\n headers={'Authorization': 'Basic ' + enc_auth},\n data={'grant_type': 'client_credentials'})\n if 'error' in resp.json():\n raise ValueError('Unable to retrive token with {} and {}: {}'.format(resp.json()['error']))\n else:\n return resp.json()\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 3:\n print('Usage: get_token.py CLIENT_ID CLIENT_SECRET')\n sys.exit(1)\n\n token = get_token(sys.argv[1], sys.argv[2])\n print(token['access_token'])\n","sub_path":"get_token.py","file_name":"get_token.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"543169366","text":"from flask import Flask, render_template, request, session, redirect, url_for, send_from_directory\nfrom flask.ext.mysql import MySQL\nfrom flask.ext.bcrypt import Bcrypt\nfrom random import choice\nimport os, sys\n\nmysql = MySQL()\n\napp = Flask(__name__)\nbcrypt = Bcrypt(app)\napp.config['SECRET_KEY'] = \"lol secret!\"\napp.config['MYSQL_DATABASE_USER'] = 'root'\napp.config['MYSQL_DATABASE_DB'] = 'wh'\napp.config['MYSQL_DATABASE_HOST'] = 'localhost'\nmysql.init_app(app)\n\n\ndef generatehash(password):\n return bcrypt.generate_password_hash(password)\n\n\ndef checkhash(password, p):\n return bcrypt.check_password_hash(password, p)\n\n\n@app.route('/', methods=['GET', 'POST']) #Max Display: 15 comments\ndef index():\n if request.method == 'POST':\n _comment = request.form['commentinput']\n if len(_comment) > 75:\n return error400(\"Bad Input\")\n else:\n conn = mysql.connect()\n cursor = conn.cursor()\n if 'logged_in' in session:\n cursor.execute(\"INSERT INTO comments (name, content) VALUES (%s,%s)\"\"\",\n (\"~Admin\", _comment))\n conn.commit()\n else:\n cursor.execute(\"INSERT INTO comments (name, content) VALUES (%s,%s)\"\"\",\n (\"Anonymous\", _comment))\n conn.commit()\n cursor = mysql.connect().cursor()\n cursor.execute(\"SELECT name, content from comments order by id desc\")\n commentlist = cursor.fetchmany(15)\n pathname = os.path.dirname(sys.argv[0])\n return render_template(\"index.html\", splash_text=choice(list(open(pathname + '/static/splashes.txt'))), comments=commentlist)\n\n\n@app.route('/stories')\ndef stories():\n cursor = mysql.connect().cursor()\n cursor.execute(\"SELECT id, title, summary, genre from stories order by id desc\")\n storylist = cursor.fetchall()\n return render_template(\"stories.html\", stories=storylist)\n\n\n@app.route('/story/')\ndef story(id):\n cursor = mysql.connect().cursor()\n cursor.execute(\"SELECT * from stories where id=%s\", id)\n data = cursor.fetchone()\n if data is None:\n return redirect(url_for(\"index\"))\n else:\n _storytitle = data[1]\n _storycontent = data[3]\n return render_template(\"storytemplate.html\", story_title=_storytitle, story_content=_storycontent)\n\n\n@app.route('/story/delete/')\ndef storydelete(id):\n conn = mysql.connect()\n cursor = conn.cursor()\n cursor.execute(\"DELETE FROM stories WHERE id=%s\", id)\n conn.commit()\n return redirect(url_for('stories'))\n\n\n@app.route('/story/edit/', methods=['GET', 'POST'])\ndef storyedit(id):\n if request.method == 'POST':\n _storytitle = request.form['title']\n _storysummary = request.form['summary']\n _storycontent = request.form['content']\n _storygenre = request.form['genre']\n conn = mysql.connect()\n cursor = conn.cursor()\n query = \"\"\" UPDATE stories\n SET title = %s, summary = %s, content = %s, genre = %s\n WHERE id = %s \"\"\"\n data = (_storytitle, _storysummary, _storycontent, _storygenre, id)\n cursor.execute(query, data)\n conn.commit()\n return redirect(url_for(\"story\", id=id))\n else:\n cursor = mysql.connect().cursor()\n cursor.execute(\"SELECT * from stories where id=%s\", id)\n _storydata = cursor.fetchone()\n _storytitle = _storydata[1]\n _storysummary = _storydata[2]\n _storycontent = _storydata[3]\n _storygenre = _storydata[4]\n return render_template('submitstory.html', story_title=_storytitle, story_summary=_storysummary,\n story_content=_storycontent, story_genre=_storygenre, id=id, method=\"edit\")\n\n\n@app.route('/about')\ndef about():\n return render_template(\"about.html\")\n\n\n@app.route('/doom')\ndef doom():\n return render_template(\"doom.html\")\n\n\n@app.route('/software')\ndef software():\n return render_template(\"software.html\")\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if request.method == 'POST':\n _username = request.form['username']\n _password = request.form['password']\n cursor = mysql.connect().cursor()\n cursor.execute(\"SELECT * from users where username=%s\", _username)\n data = cursor.fetchone()\n if data is None or checkhash(data[2], _password) == False:\n return render_template(\"login.html\", error=\"Try that again?\")\n else:\n session['logged_in'] = True\n return redirect(url_for('index'))\n return render_template(\"login.html\")\n\n\n@app.route('/logout')\ndef logout():\n if 'logged_in' in session:\n session.pop('logged_in', None)\n return redirect(url_for(\"index\"))\n\n\n@app.route('/submitstory', methods=['GET', 'POST'])\ndef submitstory():\n if request.method == 'POST':\n _storytitle = request.form['title']\n _storysummary = request.form['summary']\n _storycontent = request.form['content']\n _storygenre = request.form['genre']\n conn = mysql.connect()\n cursor = conn.cursor()\n cursor.execute(\"INSERT INTO stories (title, summary, content, genre) VALUES (%s,%s,%s,%s)\"\"\",\n (_storytitle, _storysummary, _storycontent, _storygenre))\n conn.commit()\n cursor.execute(\"SELECT id from stories order by id desc\")\n recentid = str(cursor.fetchone()).replace(\"L\", \"\").replace(\"(\", \"\").replace(\")\", \"\").replace(\",\", \"\")\n return redirect(url_for(\"story\", id=recentid))\n else:\n if 'logged_in' in session:\n return render_template(\"submitstory.html\", method=\"submission\")\n return redirect(url_for(\"error403\"))\n\n\n@app.route('/download/maps/')\ndef downloadmap(mapname):\n return send_from_directory('static/doom-maps/' + mapname + '/', mapname + '.wad', as_attachment=True)\n\n\n@app.errorhandler(500)\ndef error500(e):\n return render_template(\"error.html\", Error_Num=\"500: Server Error\", Error=\"Error 500: Internal Server Error.\")\n\n\n@app.errorhandler(404)\ndef error404(e):\n return render_template(\"error.html\", Error_Num=\"404: Not Found\", Error=\"Error 404: Resource not found.\")\n\n\n@app.errorhandler(403)\ndef error403(e):\n return render_template(\"error.html\", Error_Num=\"403: Forbidden\", Error=\"Error 403: Forbidden.\")\n\n\n@app.errorhandler(401)\ndef error401(e):\n return render_template(\"error.html\", Error_Num=\"401: Access Denied\", Error=\"Error 401: Access Denied.\")\n\n\n@app.errorhandler(400)\ndef error400(e):\n if e == \"Bad Input\":\n return render_template(\"error.html\", Error_Num=\"400: Bad Request\", Error=\"Error 400: Your comment was too \"\n \"large (75 character limit)\")\n return render_template(\"error.html\", Error_Num=\"400: Bad Request\", Error=\"Error 400: Bad Request.\")\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')\n app.debug = True\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":6952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"231786234","text":"#!/usr/bin/python\r\n#\r\n# Copyright 2017 Alibaba Group Holding Limited.\r\n#\r\n# This file is part of Ansible\r\n#\r\n# Ansible is free software: you can redistribute it and/or modify\r\n# it under the terms of the GNU General Public License as published by\r\n# the Free Software Foundation, either version 3 of the License, or\r\n# (at your option) any later version.\r\n#\r\n# Ansible is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n#\r\n# You should have received a copy of the GNU General Public License\r\n# along with Ansible. If not, see http://www.gnu.org/licenses/. \r\n\r\nANSIBLE_METADATA = {'status': ['stableinterface'],\r\n 'supported_by': 'core',\r\n 'version': '1.0'}\r\n\r\nDOCUMENTATION = '''\r\n---\r\nmodule: ecs_ami\r\nversion_added: \"1.0\"\r\nshort_description: Create or Delete User-defined Image\r\ndescription:\r\n - Creates or deletes User-defined Images\r\noptions:\r\n alicloud_access_key:\r\n description:\r\n - Aliyun Cloud access key. If not set then the value of the `ALICLOUD_ACCESS_KEY`, `ACS_ACCESS_KEY_ID`, \r\n `ACS_ACCESS_KEY` or `ECS_ACCESS_KEY` environment variable is used.\r\n required: false\r\n default: null\r\n aliases: ['acs_access_key', 'ecs_access_key','access_key']\r\n alicloud_secret_key:\r\n description:\r\n - Aliyun Cloud secret key. If not set then the value of the `ALICLOUD_SECRET_KEY`, `ACS_SECRET_ACCESS_KEY`,\r\n `ACS_SECRET_KEY`, or `ECS_SECRET_KEY` environment variable is used.\r\n required: false\r\n default: null\r\n aliases: ['acs_secret_access_key', 'ecs_secret_key','secret_key']\r\n alicloud_region:\r\n description:\r\n - The Aliyun Cloud region to use. If not specified then the value of the `ALICLOUD_REGION`, `ACS_REGION`, \r\n `ACS_DEFAULT_REGION` or `ECS_REGION` environment variable, if any, is used.\r\n required: false\r\n default: null\r\n aliases: ['acs_region', 'ecs_region', 'region']\r\n status:\r\n description: create or deregister/delete image\r\n required: false\r\n choices: [ \"present\", \"absent\" ]\r\n default: 'present'\r\n aliases: [ 'state' ]\r\n\r\nfunction: create image\r\n description: Creates or delete User-defined Images in ecs\r\n options:\r\n instance_id:\r\n description:\r\n - instance id of the image to create\r\n required: false\r\n default: null\r\n aliases: [ \"instance\" ]\r\n snapshot_id:\r\n description:\r\n - snapshot id of the image to create, image from system of instance\r\n required: true\r\n default: null\r\n aliases: [ \"snapshot\" ]\r\n image_name:\r\n description:\r\n - The name of the new image to create\r\n required: false\r\n default: null\r\n aliases: [ \"name\" ]\r\n description:\r\n description:\r\n - An optional human-readable string describing the contents and purpose of the AMI.\r\n required: false\r\n default: null\r\n image_version:\r\n description:\r\n - The version of the new image to create.\r\n required: false\r\n default: null\r\n aliases: [ \"version\" ]\r\n disk_mapping:\r\n description:\r\n - An optional list of device hashes/dictionaries with custom configurations (same block-device-mapping\r\n parameters)\r\n - keys allowed are\r\n - device (required=false;) - Disk Device Name value /dev/xvda start to /dev/xvdz, /dev/xvda default system \r\n disk is a snapshot of /dev/xvdb-z is only a snapshot of the data disk\r\n - snapshot_id (required=false;) - Snapshot Id\r\n - disk_size (required=false;) - Size of the disk, in the range [5-2000GB]\r\n required: false\r\n default: null\r\n wait:\r\n description:\r\n - wait for the AMI to be in state 'available' before returning.\r\n required: false\r\n default: \"no\"\r\n choices: [ \"yes\", \"no\" ]\r\n wait_timeout:\r\n description:\r\n - how long before wait gives up, in seconds\r\n required: false\r\n default: 300\r\n images_tags:\r\n description:\r\n - a dictionary of tags to add to the new image; '{\"key\":\"value\"}' and '{\"key\":\"value\",\"key\":\"value\"}'\r\n required: false\r\n default: null\r\n aliases: [ \"tags\" ]\r\n launch_permission:\r\n description:\r\n - Users that should be able to launch the ami. Expects dictionary with a key of user_ids. user_ids should be a\r\n list of account ids and the number no more than 10.\r\n required: false\r\n default: null\r\n\r\nfunction: delete user-defined image\r\n description: delete user-defined image\r\n options:\r\n image_id:\r\n description:\r\n - Image ID to be deregistered.\r\n required: true\r\n default: null\r\n'''\r\n\r\nEXAMPLES = '''\r\n#\r\n# provisioning to create new user-defined image\r\n#\r\n\r\n# basic provisioning example to create image using ecs instance\r\n- name: create image from ecs instance\r\n hosts: localhost\r\n connection: local\r\n vars:\r\n alicloud_access_key: xxxxxxxxxx\r\n alicloud_secret_key: xxxxxxxxxx\r\n alicloud_region: cn-hongkong\r\n instance_id: xxxxxxxxxx\r\n tasks:\r\n - name: create image form ecs instance\r\n ecs_ami:\r\n alicloud_access_key: '{{ alicloud_access_key }}'\r\n alicloud_secret_key: '{{ alicloud_secret_key }}'\r\n alicloud_region: '{{ alicloud_region }}'\r\n instance_id: '{{ instance_id }}'\r\n register: result\r\n - debug: var=result\r\n\r\n# basic provisioning example to create image using snapshot\r\n- name: create image using snapshot\r\n hosts: localhost\r\n connection: local\r\n vars:\r\n alicloud_access_key: xxxxxxxxxx\r\n alicloud_secret_key: xxxxxxxxxx\r\n alicloud_region: cn-hongkong\r\n snapshot_id: xxxxxxxxxx\r\n status: present\r\n tasks:\r\n - name: create image using snapshot\r\n ecs_ami:\r\n alicloud_access_key: '{{ alicloud_access_key }}'\r\n alicloud_secret_key: '{{ alicloud_secret_key }}'\r\n alicloud_region: '{{ alicloud_region }}'\r\n snapshot_id: '{{ snapshot_id }}'\r\n status: '{{ status }}'\r\n register: result\r\n - debug: var=result\r\n\r\n# basic provisioning example to create image using disk mapping\r\n- name: create image using disk mapping\r\n hosts: localhost\r\n connection: local\r\n vars:\r\n alicloud_access_key: xxxxxxxxxx\r\n alicloud_secret_key: xxxxxxxxxx\r\n alicloud_region: cn-hongkong\r\n disk_mapping:\r\n - device: /dev/xvda\r\n disk_size: 5\r\n snapshot_id: xxxxxxxxxx\r\n status: present\r\n tasks:\r\n - name: create image using disk mapping\r\n ecs_ami:\r\n alicloud_access_key: '{{ alicloud_access_key }}'\r\n alicloud_secret_key: '{{ alicloud_secret_key }}'\r\n alicloud_region: '{{ alicloud_region }}'\r\n disk_mapping: '{{ disk_mapping }}'\r\n status: '{{ status }}'\r\n register: result\r\n - debug: var=result\r\n\r\n# advanced example to create image with tagging, version and launch permission\r\n- name: create image\r\n hosts: localhost\r\n connection: local\r\n vars:\r\n alicloud_access_key: xxxxxxxxxx\r\n alicloud_secret_key: xxxxxxxxxx\r\n alicloud_region: cn-hongkong\r\n image_name: image_test\r\n image_version: 4\r\n description: description\r\n images_tags:\r\n - tag_key: key\r\n tag_value: value\r\n disk_mapping:\r\n - device: /dev/xvda\r\n disk_size: 5\r\n snapshot_id: xxxxxxxxxx\r\n status: present\r\n wait: false\r\n wait_timeout: 10\r\n launch_permission: xxxxxxxxxx\r\n tasks:\r\n - name: create image\r\n ecs_ami:\r\n alicloud_access_key: '{{ alicloud_access_key }}'\r\n alicloud_secret_key: '{{ alicloud_secret_key }}'\r\n alicloud_region: '{{ alicloud_region }}'\r\n image_name: '{{ image_name }}'\r\n image_version: '{{ image_version }}'\r\n description: '{{ description }}'\r\n images_tags: '{{ images_tags }}'\r\n disk_mapping: '{{ disk_mapping }}'\r\n status: '{{ status }}'\r\n wait: '{{ wait }}'\r\n wait_timeout: '{{ wait_timeout }}'\r\n launch_permission: '{{ launch_permission }}'\r\n register: result\r\n - debug: var=result\r\n\r\n#\r\n# provisioning to delete user-defined image\r\n#\r\n\r\n# provisioning to delete user-defined image\r\n- name: delete image\r\n hosts: localhost\r\n connection: local\r\n vars:\r\n alicloud_access_key: xxxxxxxxxx\r\n alicloud_secret_key: xxxxxxxxxx\r\n alicloud_region: us-west-1\r\n image_id: xxxxxxxxxx\r\n status: absent\r\n tasks:\r\n - name: delete image\r\n ecs_ami:\r\n alicloud_access_key: '{{ alicloud_access_key }}'\r\n alicloud_secret_key: '{{ alicloud_secret_key }}'\r\n alicloud_region: '{{ alicloud_region }}'\r\n image_id: '{{ image_id }}'\r\n status: '{{ status }}'\r\n register: result\r\n - debug: var=result\r\n'''\r\n\r\nimport time\r\nfrom ast import literal_eval\r\n\r\nimport sys\r\nHAS_ECS = False\r\nHAS_FOOTMARK = False\r\n\r\ntry:\r\n from footmark.exception import ECSResponseError \r\n HAS_FOOTMARK = True \r\nexcept ImportError:\r\n HAS_FOOTMARK = False \r\n\r\ntry:\r\n from ecsutils.ecs import * \r\n HAS_ECS = True \r\nexcept ImportError:\r\n HAS_ECS = False \r\n\r\n\r\ndef create_image(module, ecs, snapshot_id, image_name, image_version, description, images_tags, instance_id,\r\n disk_mapping, wait, wait_timeout, launch_permission):\r\n \"\"\"\r\n Create a user-defined image with snapshots.\r\n\r\n :param module: Ansible module object\r\n :param ecs: authenticated ecs connection object\r\n :param snapshot_id: A user-defined image is created from the specified snapshot.\r\n :param image_name: image name which is to be created\r\n :param image_version: version of image\r\n :param description: description of the image\r\n :param images_tags: tags for the instance\r\n :param instance_id: the specified instance_id\r\n :param disk_mapping: list relating device and disk\r\n :param wait: Used to indicate wait for instance to be running before running\r\n :param wait_timeout: Used to indicate how long to wait, default 300\r\n :param launch_permission: Used to send list of userIds who are permitted to launch ami\r\n :return: id of image\r\n \"\"\"\r\n changed = False\r\n if image_name:\r\n if len(image_name) < 2 or len(image_name) > 128:\r\n module.fail_json(msg='image_name must be 2 - 128 characters long')\r\n\r\n if image_name.startswith('http://') or image_name.startswith('https://'):\r\n module.fail_json(msg='image_name can not start with http:// or https://')\r\n if image_version:\r\n if image_version.isdigit():\r\n if int(image_version) < 1 or int(image_version) > 40:\r\n module.fail_json(msg='The permitted range of image_version is between 1 - 40')\r\n else:\r\n module.fail_json(msg='The permitted range of image_version is between 1 - 40, entered value is {0}'\r\n .format(image_version)) \r\n\r\n if disk_mapping: \r\n for mapping in disk_mapping:\r\n if mapping:\r\n if 'snapshot_id' not in mapping:\r\n module.fail_json(msg='The snapshot_id of system disk is needed for disk mapping.')\r\n\r\n if not('disk_size' in mapping or 'device' in mapping or 'snapshot_id' in mapping):\r\n module.fail_json(msg='The disk_size, device and snapshot_id parameters '\r\n 'are valid for disk mapping.')\r\n\r\n if 'disk_size' in mapping:\r\n map_disk = mapping['disk_size']\r\n if map_disk:\r\n if str(map_disk).isdigit():\r\n if int(map_disk) < 5 or int(map_disk) > 2000:\r\n module.fail_json(msg='The permitted range of disk-size is 5 GB - 2000 GB ')\r\n else:\r\n module.fail_json(msg='The disk_size must be an integer value, entered value is {0}'.format(\r\n map_disk))\r\n\r\n if images_tags:\r\n key = ''\r\n key_val = ''\r\n for tags in images_tags:\r\n if tags:\r\n if 'tag_key' in tags:\r\n key = tags['tag_key']\r\n if 'tag_value' in tags:\r\n key_val = tags['tag_value']\r\n if not key and key_val:\r\n module.fail_json(msg='tag_key must be present when tag_value is present') \r\n\r\n if not snapshot_id and not instance_id and not disk_mapping:\r\n module.fail_json(msg='Either of SnapshotId or InstanceId or disk_mapping, must be present for '\r\n 'create image operation to get performed')\r\n\r\n if (snapshot_id and instance_id) or (snapshot_id and disk_mapping) or (instance_id and disk_mapping):\r\n module.fail_json(msg='Only 1 of SnapshotId or InstanceId or disk_mapping, must be present for '\r\n 'create image operation to get performed')\r\n\r\n # call to create_image method in footmark\r\n try:\r\n changed, image_id, result, request_id = ecs.create_image(snapshot_id=snapshot_id, image_name=image_name,\r\n image_version=image_version, description=description,\r\n images_tags=images_tags,\r\n instance_id=instance_id, disk_mapping=disk_mapping,\r\n wait=wait, wait_timeout=wait_timeout,\r\n launch_permission=launch_permission)\r\n\r\n if 'error code' in str(result).lower():\r\n module.fail_json(msg=result, image_id=image_id, changed=changed, RequestId=request_id)\r\n\r\n except ECSResponseError as e:\r\n module.fail_json(msg='Unable to create image, error: {0}'.format(e))\r\n return changed, image_id, result, request_id\r\n\r\n\r\ndef delete_image(module, ecs, image_id):\r\n \"\"\"\r\n Delete a user-defined image .\r\n\r\n :param module: Ansible module object\r\n :param ecs: authenticated ecs connection object\r\n :param image_id: Unique image id which is to be deleted\r\n :return: Result of an operation\r\n \"\"\"\r\n changed = False\r\n if not image_id:\r\n module.fail_json(msg='image id is required to delete image')\r\n try:\r\n changed, result = ecs.delete_image(image_id=image_id)\r\n if 'error' in (''.join(str(result))).lower():\r\n module.fail_json(msg=result)\r\n\r\n except ECSResponseError as e:\r\n module.fail_json(msg='Unable to delete image, error: {0}'.format(e))\r\n\r\n return changed, result\r\n\r\n\r\ndef main():\r\n if HAS_ECS is False:\r\n print(\"ecsutils required for this module\")\r\n sys.exit(1) \r\n elif HAS_FOOTMARK is False:\r\n print(\"Footmark required for this module\")\r\n sys.exit(1) \r\n else:\r\n argument_spec = ecs_argument_spec()\r\n argument_spec.update(dict(\r\n image_id=dict(),\r\n snapshot_id=dict(aliases=['snapshot']),\r\n description=dict(),\r\n image_name=dict(aliases=['name']),\r\n image_version=dict(aliases=['version']),\r\n disk_mapping=dict(type='list'),\r\n instance_id=dict(aliases=['instance']),\r\n status=dict(default='present', choices=[\r\n 'present', 'absent'\r\n ], aliases=['state']),\r\n images_tags=dict(type='list', aliases=['tags']),\r\n launch_permission=dict(type='list'),\r\n wait=dict(default='no', choices=['yes', 'no', 'Yes', 'No', \"true\", \"false\", \"True\", \"False\"]),\r\n wait_timeout=dict(type='int', default='300')\r\n ))\r\n module = AnsibleModule(argument_spec=argument_spec)\r\n\r\n ecs = ecs_connect(module)\r\n status = module.params['status']\r\n\r\n if status == 'present':\r\n snapshot_id = module.params['snapshot_id']\r\n image_name = module.params['image_name']\r\n image_version = module.params['image_version']\r\n description = module.params['description']\r\n disk_mapping = module.params['disk_mapping']\r\n instance_id = module.params['instance_id']\r\n images_tags = module.params['images_tags']\r\n wait = module.params['wait']\r\n wait_timeout = module.params['wait_timeout']\r\n launch_permission = module.params['launch_permission']\r\n\r\n # Calling create_image method\r\n changed, image_id, result, request_id = create_image(module=module, ecs=ecs, snapshot_id=snapshot_id,\r\n image_name=image_name, image_version=image_version,\r\n description=description, images_tags=images_tags,\r\n instance_id=instance_id, disk_mapping=disk_mapping,\r\n wait=wait, wait_timeout=wait_timeout,\r\n launch_permission=launch_permission)\r\n\r\n module.exit_json(changed=changed, result=result, image_id=image_id, RequestId=request_id)\r\n\r\n elif status == 'absent':\r\n image_id = module.params['image_id']\r\n\r\n (changed, result) = delete_image(module=module, ecs=ecs, image_id=image_id)\r\n module.exit_json(changed=changed, result=result)\r\n\r\n# import module snippets\r\nfrom ansible.module_utils.basic import *\r\n# from ansible.module_utils.ecs import *\r\n\r\n# import ECSConnection\r\nmain()\r\n","sub_path":"lib/ansible/modules/cloud/alicloud/ecs_ami.py","file_name":"ecs_ami.py","file_ext":"py","file_size_in_byte":17752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"612726493","text":"from vpython import *\n\nm = 100 # No steps in x\nc = 1.\ndx = 1. / m\nbeta = 0.8 # beta = c*dt/dx\nu = [0] * (m + 1) # Initial Numeric\nu0 = [0] * (m + 1)\nuf = [0] * (m + 1)\ndt = beta * dx / c\nT_final = 0.5\nn = int(T_final / dt) # N time steps\n\ngraph1 = graph(width=600, height=500, xtitle='x', xmin=0, xmax=1, ymin=0, ymax=1,\n ytitle='u(x), Cyan=exact, Yellow=Numerical',\n title='Advect Eqn: Initial (red), Exact (cyan),Numerical (yellow)')\ninitfn = gcurve(color=color.red)\nexactfn = gcurve(color=color.cyan)\nnumfn = gcurve(color=color.yellow) # Numerical solution\n\n\ndef plotIniExac(): # Plot initial & exact solution\n for i in range(0, m):\n x = i * dx\n u0[i] = exp(-300. * (x - 0.12) ** 2) # Gaussian initial\n initfn.plot(pos=(0.01 * i, u0[i])) # Initial function\n uf[i] = exp(-300. * (x - 0.12 - c * T_final) ** 2) # Exact = cyan\n exactfn.plot(pos=(0.01 * i, uf[i]))\n rate(50)\n\n\nplotIniExac()\n\n\ndef numerical(): # Finds Lax Wendroff solution\n for j in range(0, n + 1): # Time loop\n for i in range(0, m - 1): # x loop\n u[i + 1] = (1. - beta * beta) * u0[i + 1] - (0.5 * beta) * (1. - beta) * u0[i + 2] \\\n + (0.5 * beta) * (1. + beta) * u0[i] # Algorithm\n u[0] = 0.\n u[m - 1] = 0.\n u0[i] = u[i]\n\n\nnumerical()\nfor j in range(0, m - 1):\n rate(50)\n numfn.plot(pos=(0.01 * j, u[j]))\n","sub_path":"Shock_Waves_Solitons/adveclax.py","file_name":"adveclax.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"594999521","text":"import turtle\nimport random\n\n\ndef stvorec(t : turtle.Turtle, posx: int=0, posy: int=0):\n \"\"\" Vykresli stvorec od stredu\n :param t:objekt korytnacka\n :return: None\n \"\"\"\n t.setpos(posx, posy)\n for _ in range(4):\n t.forward(100)\n t.left(90)\n\nt = turtle.Turtle()\nt.shape(\"turtle\")\nt.color(\"red\")\n\nfor _ in range(5):\n px = random.randint(-500, 500)\n py = random.randint(-500, 500)\n stvorec(t, px, py)\n\nturtle.mainloop()\n","sub_path":"Lekcia 3/nahodne_stvorce_korytnacka.py","file_name":"nahodne_stvorce_korytnacka.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"100399490","text":"### Program wyrzucajacy 100 razy moneta, i zwracaacy liczbe wylosowanych\n\nimport random\norzel = 0\nreszka = 0\nfor i in range(100):\n if random.randint(0,1):\n orzel += 1\n else:\n reszka +=1\n\nprint(\"Ilosc orlow:\",orzel)\nprint(\"Ilosc reszek:\",reszka)","sub_path":"Orzel reszka.py","file_name":"Orzel reszka.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"255275838","text":"from flask import Flask\nfrom api.query import simple_page\nfrom services.durable import setUp\n\n\ndef create_app():\n app = Flask(__name__)\n app.register_blueprint(simple_page)\n\n return app\n\n\nif __name__ == \"__main__\":\n app = create_app()\n setUp()\n app.run()\n\n","sub_path":"src/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"289196949","text":"import gi\ngi.require_version(\"Gtk\",\"3.0\")\nfrom gi.repository import Gtk\n\nclass VentanaPrincipal(Gtk.Window):\n def __init__(self):\n Gtk.Window.__init__(self,title=\"Ejemplo de Gtk.Stack y Gtk.StackSwitcher\")\n\n cajaV=Gtk.Box(orientation = Gtk.Orientation.VERTICAL, spacing= 6)\n self.add(cajaV)\n\n stack=Gtk.Stack()\n stack.set_transition_type(Gtk.StackTransitionType.SLIDE_LEFT_RIGHT)\n stack.set_transition_duration(1000)\n\n chkButton=Gtk.CheckButton(\"Púlsame\")\n stack.add_titled(chkButton, \"Púlsame\",\"Boton Púlsame\")\n\n label1=Gtk.Label()\n label1.set_markup(\" A nosa etiqueta\")\n stack.add_titled(label1,\"Etiqueta\",\"Etiqueta para mostrar\")\n\n#El stack es donde estan las cosas, y el switcher las pestañas para cambiar entre ellos, funcionan en conjunto\n stackSelector=Gtk.StackSwitcher()\n stackSelector.set_stack(stack)\n\n cajaV.pack_start(stackSelector, True, True, 0)\n cajaV.pack_start(stack,True,True,0)\n\n self.connect(\"destroy\",Gtk.main_quit)\n self.show_all()\n\nif __name__==\"__main__\":\n ventana=VentanaPrincipal()\n Gtk.main()","sub_path":"UsandoGTKStack.py","file_name":"UsandoGTKStack.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"453311145","text":"# -*- coding: utf-8 -*-\r\n#01.当py文件中中文时一定要使用上面的一个编码注释\r\n#02.设置字符串缺省的编码,如果不这样的话str无法使用\r\nimport sys,re\r\nreload(sys)\r\nsys.setdefaultencoding('utf8')\r\nfh = open('E:\\\\03.Data\\\\2015年底工商数据\\\\E.txt'.encode('gb2312') )\r\nfw = open('E:\\\\03.Data\\\\2015年底工商数据\\\\E2.txt'.encode('gb2312') , \"w+\")\r\ncount = 1\r\nfor line in fh.readlines():\r\n if re.search('[0-9|A-Z|a-z|)].*\\s+\\n\\Z', line)==None:\r\n line = line.replace('\\n','').replace('\\r','') \r\n# print count\r\n #fw.write(line)\r\n fw.write(line.replace('|'.encode('gb2312'),'@@'))\r\n count= count+1\r\nfh.close()\r\nfw.close()\r\n ","sub_path":"modules/filetools/repalceLastCharEnterprise.py","file_name":"repalceLastCharEnterprise.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"284603173","text":"# -*- coding: utf-8 -*-\n\nimport requests, os, sys, shutil\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nTITLE = ''\nALIVE_PROXIES = []\n_PROXY = []\nTIME_TO_WAIT = 30\nROOT = ''\nEXECUTABLE_PATH = 'C:\\\\phantomjs-2.1.1-windows\\\\bin\\\\phantomjs.exe'\nTARGET_LINKS = []\n\ndef proxy_generator():\n global _PROXY\n filename = ''\n with open(os.path.join(ROOT, filename), 'r') as f:\n proxies = [proxy.rstrip() for proxy in f]\n print('{} Proxies Available ...'.format(len(proxies)))\n _PROXY = (['--proxy={}'.format(proxy), '--proxy-type=http'] for proxy in proxies)\n\ndef proxy_regenerator():\n global _PROXY\n print('Switching Proxy ...')\n if ALIVE_PROXIES:\n _PROXY = (proxy for proxy in ALIVE_PROXIES)\n print('{} Proxies Left.'.format(len(ALIVE_PROXIES)))\n else:\n print('Ran Out Of Proxies ...')\n sys.exit()\n\ndef create_driver_using_(service_args):\n print('Using proxy {} ...'.format(service_args[0][8:]))\n return webdriver.PhantomJS(\n executable_path = EXECUTABLE_PATH,\n service_args = service_args\n )\n\ndef fetch_url_list_with(_target_link):\n driver = create_driver_using_(next(_PROXY))\n driver.set_page_load_timeout(TIME_TO_WAIT)\n driver.get(_target_link)\n ul_list = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'Blue_link2')))\n li_list = [li for ul in ul_list for li in ul.find_elements_by_tag_name('li')]\n url_list = [li.find_element_by_tag_name('a').get_attribute('href') for li in li_list]\n driver.quit()\n return url_list\n\ndef save_chapters_with_(url_list):\n proxies_alive = []\n yet_another_url_list = []\n for url in url_list:\n try:\n proxy = next(_PROXY)\n _driver = create_driver_using_(proxy)\n _driver.set_page_load_timeout(TIME_TO_WAIT)\n save_pages_with_(url, _driver)\n except StopIteration:\n yet_another_url_list.append(url)\n proxy_regenerator()\n except Exception as ErrorMessage:\n yet_another_url_list.append(url)\n print(ErrorMessage)\n else:\n proxies_alive.append(proxy)\n finally:\n _driver.quit()\n\n print('{} Chapters Left.'.format(len(yet_another_url_list)))\n return yet_another_url_list, proxies_alive\n\ndef save_pages_with_(url, _driver):\n chapter = url.split('/')[-2]\n folder = os.path.join(ROOT, TITLE, chapter)\n if os.path.exists(folder):\n shutil.rmtree(folder)\n os.makedirs(folder)\n print('Downloading Chapter {} ...'.format(chapter))\n\n _driver.get(url)\n # select = WebDriverWait(_driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, 'select')))\n options = WebDriverWait(_driver, 10).until(EC.presence_of_all_elements_located((By.TAG_NAME, 'option')))\n\n for page in range(1, len(options)+1):\n filename = '{}.png'.format(page)\n print('|--Downloading Page {} ...'.format(page))\n\n src = WebDriverWait(_driver, 10).until(EC.presence_of_element_located((By.ID, 'curPic'))).get_attribute('src')\n r = requests.get(src, stream=True, timeout=10)\n with open(os.path.join(folder, filename), 'wb+') as f:\n for chunk in r.iter_content(1024):\n if chunk:\n f.write(chunk)\n _driver.find_element_by_tag_name('body').send_keys('a')\n\ndef download_comic_book_with(_target_link):\n global TITLE, ALIVE_PROXIES, _PROXY\n TITLE = _target_link[-5:]\n url_list = []\n\n while True:\n try:\n url_list = fetch_url_list_with(_target_link)\n except StopIteration:\n proxy_regenerator()\n except:\n pass\n if url_list:\n break\n\n while True:\n url_list, proxies_alive = save_chapters_with_(url_list)\n ALIVE_PROXIES.extend(proxies_alive)\n if not url_list:\n break\n\ndef main():\n proxy_generator()\n for _target_link in TARGET_LINKS:\n download_comic_book_with(_target_link)\n\nif __name__ == '__main__':\n main()","sub_path":"yet_another_dirty_crawler.py","file_name":"yet_another_dirty_crawler.py","file_ext":"py","file_size_in_byte":4248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"512076463","text":"import json\nimport os\nimport re\n\nfrom .errors import NotFoundError\n\n\nclass API:\n def __init__(self, base_url):\n self.BASE = base_url or 'https://api.brawlapi.cf/v1'\n self.PROFILE = self.BASE + '/player'\n self.CLUB = self.BASE + '/club'\n self.LEADERBOARD = self.BASE + '/leaderboards'\n self.EVENTS = self.BASE + '/events'\n self.MISC = self.BASE + '/misc'\n self.BATTLELOG = self.BASE + '/player/battlelog'\n self.CLUB_SEARCH = self.BASE + '/club/search'\n self.CONSTANTS = 'https://fourjr.herokuapp.com/bs/constants/'\n\n path = os.path.dirname(__file__)\n with open(os.path.join(path, '__init__.py')) as f:\n self.VERSION = re.search(r'^__version__ = [\\'\"]([^\\'\"]*)[\\'\"]', f.read(), re.MULTILINE).group(1)\n with open(os.path.join(path, 'constants.json')) as f:\n self.BRAWLERS = [b['tID'] for b in json.load(f)['characters']]\n\n\ndef bstag(tag):\n tag = tag.strip('#').upper().replace('O', '0')\n allowed = '0289PYLQGRJCUV'\n if len(tag) < 3:\n raise NotFoundError('Tag less than 3 characters.', 404)\n invalid = [c for c in tag if c not in allowed]\n if invalid:\n raise NotFoundError(invalid, 404)\n return tag\n","sub_path":"brawlstats/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"417764302","text":"from django.contrib.auth.decorators import login_required\nfrom django.views.generic import View\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom administration.models import Venue\nfrom administration.forms import VenueForm\nfrom administration.aspects import service_exception_handler\nfrom administration.utilities import Error\n\n\nclass VenueListView(View):\n @staticmethod\n @login_required\n def get(request):\n objects = {\n 'venues': Venue.objects.all(),\n 'form': VenueForm(prefix='venue')\n }\n return render(request, 'administration/venue_list.html', objects)\n\n @staticmethod\n @service_exception_handler\n def post(request):\n form = VenueForm(request.POST, prefix='venue')\n if form.is_valid():\n venue = form.save(commit=False)\n venue.create(request.user.profile)\n return HttpResponse(status=201)\n raise Error(400, {'errors': form.errors})\n\n\nclass VenueDetailView(View):\n @staticmethod\n @login_required\n def get(request, pk):\n venue = Venue.objects.get(pk=pk)\n objects = {\n 'venue': venue,\n 'form': VenueForm(instance=venue, prefix='venue')\n }\n return render(request, 'administration/venue_detail.html', objects)\n\n @staticmethod\n @service_exception_handler\n def post(request, pk):\n venue = Venue.objects.get(pk=pk)\n form = VenueForm(data=request.POST, instance=venue, prefix='storage')\n if form.is_valid():\n venue = form.save(commit=False)\n venue.update(request.user.profile)\n return HttpResponse(status=202)\n raise Error(400, {'errors': form.errors})\n","sub_path":"administration/views/Venues.py","file_name":"Venues.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"102671800","text":"# This is a region plugin for Galaxy Charts and New Frontier, created by the System Plugin Creator Tool\n\n########## GENERAL REGION INFORMATION ##########\n\nName = \"DS9FX Founders Homeworld\"\nControllingEmpire = \"Dominion\"\nSectorNumber = 912\nImagePath = \"\"\nType = \"Single\"\nLocation = [-37900, -26200]\nOnlyInQB = 0\nOnlyMult = 0\nIgnoreRDF = 1\nSystemsFiles = [\"Systems.DS9FXFoundersHomeworld.DS9FXFoundersHomeworld1\"]\nDescription = \"Most recent Homeworld of the Founders.\"\n","sub_path":"scripts/Custom/Systems/Regions/DS9FXFoundersHomeworld.py","file_name":"DS9FXFoundersHomeworld.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"12003671","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 ('post', '0005_auto_20160623_1942'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='theme',\n name='title_ru',\n field=models.CharField(max_length=20, null=True, verbose_name='title', unique=True),\n ),\n migrations.AddField(\n model_name='theme',\n name='title_uk',\n field=models.CharField(max_length=20, null=True, verbose_name='title', unique=True),\n ),\n ]\n","sub_path":"post/migrations/0006_auto_20160624_1358.py","file_name":"0006_auto_20160624_1358.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"427948526","text":"import pygame\n\npygame.init()\n\ndisplay_width = 800\ndisplay_height = 600\n\nblack = (0,0,0)\nwhite = (255,255,255)\n\ngameDisplay = pygame.display.set_mode((display_width,display_height))\npygame.display.set_caption(\"Mein erstes Spielefenster\")\nclock = pygame.time.Clock()\n\ncarImg = pygame.image.load(\"racecar.png\")\n\ndef car(x,y):\n gameDisplay.blit(carImg, (x,y))\n\nxs = (display_width * 0.45)\nys = (display_height * 0.8)\nx_change = 0\ncrashed = False\n\nwhile not crashed:\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n crashed = True\n\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n x_change = -7\n elif event.key == pygame.K_RIGHT:\n x_change = 7\n\n elif event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\n x_change = 0\n\n xs += x_change\n \n\n gameDisplay.fill(white)\n car(xs,ys)\n\n pygame.display.update()\n clock.tick(30)\n\npygame.quit()\n","sub_path":"Sentdex/sentdex_p3.py","file_name":"sentdex_p3.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"106753478","text":"# ==================================================================================================\n# Copyright 2011 Twitter, Inc.\n# --------------------------------------------------------------------------------------------------\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this work except in compliance with the License.\n# You may obtain a copy of the License in the LICENSE file, or at:\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==================================================================================================\n\nfrom __future__ import print_function\n\nimport os\nimport subprocess\nimport sys\n\nfrom twitter.common.dirutil import safe_rmtree\nfrom twitter.pants.base.build_environment import get_buildroot\nfrom twitter.pants.python.code_generator import CodeGenerator\nfrom twitter.pants.targets.python_thrift_library import PythonThriftLibrary\nfrom twitter.pants.thrift_util import calculate_compile_roots, select_thrift_binary\n\n\nclass PythonThriftBuilder(CodeGenerator):\n class UnknownPlatformException(CodeGenerator.Error):\n def __init__(self, platform):\n super(PythonThriftBuilder.UnknownPlatformException, self).__init__(\n \"Unknown platform: %s!\" % str(platform))\n\n def run_thrifts(self):\n def is_py_thrift(target):\n return isinstance(target, PythonThriftLibrary)\n bases, roots = calculate_compile_roots([self.target], is_py_thrift)\n\n for src in roots:\n if not self._run_thrift(src, bases):\n raise PythonThriftBuilder.CodeGenerationException(\n \"Could not generate .py from %s!\" % src)\n\n def _run_thrift(self, source, bases):\n thrift_file = source\n thrift_abs_path = os.path.abspath(os.path.join(self.root, thrift_file))\n\n args = [\n select_thrift_binary(self.config),\n '--gen',\n 'py:new_style',\n '-recurse',\n '-o',\n self.codegen_root\n ]\n\n # Add bases as include paths to try. Note that include paths and compile targets\n # should be uniformly relative, or uniformly absolute (in this case the latter).\n for base in bases:\n args.extend(('-I', os.path.join(get_buildroot(), base)))\n args.append(thrift_abs_path)\n\n po = subprocess.Popen(args, cwd=self.chroot.path())\n rv = po.wait()\n if rv != 0:\n comm = po.communicate()\n print('thrift generation failed!', file=sys.stderr)\n print('STDOUT', file=sys.stderr)\n print(comm[0], file=sys.stderr)\n print('STDERR', file=sys.stderr)\n print(comm[1], file=sys.stderr)\n return rv == 0\n\n @property\n def package_dir(self):\n return \"gen-py\"\n\n def generate(self):\n # autogenerate the python files that we bundle up\n self.run_thrifts()\n\n # Thrift generates code with all parent namespaces with empty __init__.py's. Generally\n # speaking we want to drop anything w/o an __init__.py, and for anything with an __init__.py,\n # we want to explicitly make it a namespace package, hence the hoops here.\n for root, _, files in os.walk(os.path.normpath(self.package_root)):\n reldir = os.path.relpath(root, self.package_root)\n if reldir == '.': # skip root\n continue\n if '__init__.py' not in files: # skip non-packages\n continue\n init_py_abspath = os.path.join(root, '__init__.py')\n module_path = self.path_to_module(reldir)\n self.created_packages.add(module_path)\n if os.path.getsize(init_py_abspath) == 0: # empty __init__, translate to namespace package\n with open(init_py_abspath, 'wb') as f:\n f.write(b\"__import__('pkg_resources').declare_namespace(__name__)\")\n self.created_namespace_packages.add(module_path)\n else:\n # non-empty __init__, this is a leaf package, usually with ttypes and constants, leave as-is\n pass\n\n if not self.created_packages:\n raise self.CodeGenerationException(\n 'No Thrift structures declared in %s!' % self.target)\n","sub_path":"src/python/twitter/pants/python/thrift_builder.py","file_name":"thrift_builder.py","file_ext":"py","file_size_in_byte":4245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"611227923","text":"# QUIZ\n# \n# Implement the lateral shift of the fire \n# by the given velocity (indicated in the \n# variable of the same name).\n\nimport math\nimport numpy\nfrom matplotlib import pyplot\nfrom matplotlib import animation\n\nambient_temperature = 300. # K\nflame_temperature = 1000. # K\nvelocity = 0.003 # m / s\ndx = 0.001 # m\nsize = 200 # grid units\npositions = dx * numpy.arange(size) # m\nh = 0.01 # s\nend_time = 10.0 # s\nnum_steps = int(end_time / h)\n\n# This is used to keep track of the data that we want to plot.\ndata = []\n\ndef heat_conduction():\n temperatures_old = ambient_temperature * numpy.ones(size) # K\n for i in range(size):\n temperatures_old[i] += (flame_temperature - ambient_temperature) * 0.5 \\\n * (1. + math.sin(1. * 2. * math.pi * i / size))\n temperatures_new = numpy.copy(temperatures_old) # K\n\n for step in range(num_steps):\n if step % 100 == 0:\n data.append(([pos for pos in positions], \n [temp for temp in temperatures_old]))\n for i in range(1, size - 1):\n temperatures_new[i] = temperatures_old[i] \\\n -h * velocity / (2*dx) \\\n * (temperatures_old[i+1]-temperatures_old[i-1])\n temperatures_old, temperatures_new = temperatures_new, temperatures_old\n\n return temperatures_old\n\ntemperatures = heat_conduction()\n\ndef plot_me():\n for (pos, temp) in data:\n pyplot.plot(pos, temp)\n axes = pyplot.gca() \n axes.set_xlabel('Position in m')\n axes.set_ylabel('Temperature in K')\n pyplot.show()\n\nplot_me()\n\n\n\n\n","sub_path":"wildfire/wind-shift.py","file_name":"wind-shift.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"580530862","text":"from django.urls import path\nfrom . import *\nfrom . import views\n\nurlpatterns = [\n path('person/', views.person_list, name='person_list'),\n path('create_person/', views.person_create, name = 'create_persons_url'),\n #\n path('add_part/',views.spar_part_add,name='add_part_url'),\n path('spare_parts_manual/', views.spare_parts_manual, name= 'spare_parts_manual_list'),\n path('create_shipper/',views.shipper_create, name= 'create_shipper_url'),\n path('shippers/',views.shippers_list, name= 'shipper_url'),\n #\n\n path('incoming_list/get_/', views.IncomingListDetail.as_view(), name='incom_list_detail_url'),\n path('incoming_list/',views.IncomingList.as_view(),name='incom_list_url'),\n #\n path('deteil_in_stock/',views.DetailInStockView.as_view(),name='detail_in_stock_url'),\n #\n path('tools_test/',views.test, name='test_url'),\n #\n path('create_incoming/', views.CreateIncoming.as_view(),name='create_incoming_url'),\n path('create_incoming//', views.EditIncoming.as_view(), name='edit_incoming_url'),\n path('ajax_create_incoming_filter_spart/',views.tools_ajax_create_incom_filter, name = 'ajax_create_incom_filter'),\n path('ajax_create_incoming_detail//',views.tools_ajax_create_incom_detail,name = 'ajax_create_incom_incom_detail'),\n path('ajax_create_incoming_change_detail//',views.tools_ajax_create_incom_change_detail,name='ajax_create_incom_change_detail'),\n path('ajax_create_incoming_delete_detail//',views.tools_ajax_create_incom_delete_detail,name='ajax_create_incom_delete_detail'),\n\n]\n\n\n\n\"\"\"\n path('detail_incoming/',views.DetailIncoming.as_view(), name = 'detail_incom_url'),\n path('tools_detail_incoming/',views.ToolsDetailIncoming.as_view(), name = 'tools_detail_incoming_url'),\n path('tools_create_incoming/',views.ToolsCreateIncoming.as_view(), name='tools_create_incom_url'),\n path('tools_incom_edit_detail/',views.ToolsIncomEditDetail.as_view(),name='tools_incom_edit_detail_url'),\n path('tools_delete_detail/',views.ToolsIncomDetailDelete.as_view(),name='tools_incom_delete_detail_url'),\n path('tools_save_detail/',views.ToolsIncomDetailSave.as_view(),name='tools_incom_save_detail_url'),\n path('tools_incom_edit/',views.ToolsEditIncom.as_view(),name='tools_edit_incom_url'),\n \n \n\"\"\"\n","sub_path":"srvbd/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"61032972","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\n\"\"\"Module to create custom QDialog\"\"\"\n\nfrom PyQt5 import QtWidgets\nfrom PyQt5 import QtGui\nfrom PyQt5 import QtCore\n\nimport os\nimport json\nimport logging\n\nimport requests\nimport Queue\nimport pandas as pd\n\nfrom collections import OrderedDict\nimport classCustomWidgets\nimport classRestCom\nimport classWorker\n\nimport funcMisc\n\n\nclass ConnectWindow(QtWidgets.QDialog):\n\n \"\"\"Create a simple dialog to add/delete and configure user\"s account\"\"\"\n\n def __init__(self, parent):\n\n QtWidgets.QDialog.__init__(self, parent=parent)\n self._connect_dict = {}\n\n icons_path = os.getcwd() + \"/icons\"\n\n # configure QDialog\n self.setModal(True)\n self.setWindowTitle(\"Login Informations\")\n self.setWindowIcon(QtGui.QIcon(icons_path+\"/main.png\"))\n\n layout_login = QtWidgets.QGridLayout()\n\n # create input widgets\n self.combobox_usr = classCustomWidgets.CustomComboBox(\"user_choice\")\n self.combobox_type = QtWidgets.QComboBox()\n\n self.line_edit_proxies = QtWidgets.QLineEdit()\n self.line_edit_pwd = QtWidgets.QLineEdit()\n self.line_edit_key = QtWidgets.QLineEdit()\n\n self.chkbox_autoconnect = QtWidgets.QCheckBox()\n self.chkbox_remember = QtWidgets.QCheckBox()\n\n self.btn_trash = classCustomWidgets.CustomLabel(\"trash\")\n self.btn_connect = QtWidgets.QPushButton(\"Connect\")\n\n # configure widgets\n self.combobox_type.addItems([\"Live\", \"Demo\"])\n self.chkbox_remember.setChecked(True)\n self.combobox_usr.setEditable(True)\n self.combobox_usr.setInsertPolicy(QtWidgets.\n QComboBox.InsertAlphabetically)\n\n self.line_edit_pwd.setEchoMode(QtWidgets.QLineEdit.Password)\n\n self.btn_trash.set_default_style(\"transparent\",\n \"transparent\",\n \"transparent\")\n self.btn_trash.setPixmap(QtGui.QPixmap(icons_path+\"/trash.png\"))\n\n list_widgets_login = [\n QtWidgets.QLabel(\"Username: \"),\n self.combobox_usr,\n QtWidgets.QLabel(\"Password: \"),\n self.line_edit_pwd,\n QtWidgets.QLabel(\"API key: \"),\n self.line_edit_key,\n QtWidgets.QLabel(\"Proxies: \"),\n self.line_edit_proxies,\n QtWidgets.QLabel(\"Account Type: \"),\n self.combobox_type,\n QtWidgets.QLabel(\"Auto connect on start up: \"),\n self.chkbox_autoconnect,\n QtWidgets.QLabel(\"Remember credentials: \"),\n self.chkbox_remember\n ]\n\n # configure signals\n self.btn_connect.clicked.connect(self.create_connection_dict)\n self.btn_trash.clicked_signal.connect(self.delete_account)\n\n self.combobox_usr.editTextChanged.connect(self.user_edition)\n self.combobox_usr.focus_out_signal.connect(self.add_account)\n\n self.line_edit_pwd.textChanged.connect(self.user_edition)\n self.line_edit_key.textChanged.connect(self.user_edition)\n\n # place widget on layout\n for count, widget in enumerate(list_widgets_login):\n\n if count%2 == 0:\n row = count + 1\n col = 0\n else:\n row = count\n col = 1\n\n layout_login.addWidget(widget, row, col)\n\n # place trash \"button\" and connect button\n layout_login.addWidget(self.btn_trash, 1, 2, 1, 1)\n layout_login.addWidget(self.btn_connect, count+1, 0, 1, 3)\n\n # configure QDialog\n self.setLayout(layout_login)\n self.resize(300, 150)\n self.load_accounts()\n self.exec_()\n\n\n def load_accounts(self):\n\n \"\"\"Load saved accounts in credentials.json\"\"\"\n\n # read config file and credentials\n saved_accounts = funcMisc.read_credentials()\n config = funcMisc.read_config()\n\n list_type = [\"Live\", \"Demo\"]\n acc_type = self.combobox_type.currentText() # get account type\n saved_usr = saved_accounts.keys() # get saved usr\n\n last_usr = config[\"last_usr\"]\n auto_connect = config[\"auto_connect\"]\n\n self.combobox_usr.addItems(sorted(saved_usr)) # add usr to combobox\n\n # set last user used if exists\n idx_last_usr = self.combobox_usr.findText(last_usr)\n\n if idx_last_usr != -1:\n self.combobox_usr.setCurrentIndex(idx_last_usr)\n else:\n pass\n\n # get infos of account selected\n current_usr = str(self.combobox_usr.currentText())\n current_account = saved_accounts[current_usr]\n\n current_pwd = current_account[\"pwd\"]\n current_api_key = current_account[\"api_key\"]\n current_type = current_account[\"type\"]\n current_proxies = current_account[\"proxies\"][\"https\"]\n\n # set infos into inputs widgets\n self.line_edit_pwd.setText(current_pwd)\n self.line_edit_key.setText(current_api_key)\n self.line_edit_proxies.setText(current_proxies)\n\n self.combobox_type.setCurrentIndex(list_type.index(current_type))\n self.chkbox_autoconnect.setCheckState(auto_connect)\n\n # enabled (or not) trash button\n if current_usr == \"\":\n self.btn_trash.setEnabled(False)\n self.btn_connect.setEnabled(False)\n else:\n self.btn_trash.setEnabled(True)\n self.btn_connect.setEnabled(True)\n\n\n def add_account(self):\n\n \"\"\"\n Add a new account to combobox and a new key to\n credentials file. called when combobox user loses focus\n \"\"\"\n\n saved_accounts = funcMisc.read_credentials()\n\n # get set infos\n usr = self.combobox_usr.currentText()\n idx_usr = self.combobox_usr.findText(usr)\n\n api_key = str(self.line_edit_key.text())\n pwd = str(self.line_edit_pwd.text())\n acc_type = str(self.combobox_type.currentText())\n proxies = str(self.line_edit_proxies.text())\n\n # del empty account created if no account saved\n if \"\" in saved_accounts.keys():\n saved_accounts.pop(\"\", None)\n idx_empty = self.combobox_usr.findText(\"\")\n\n # remove empty account from combobox\n if idx_empty != -1:\n self.combobox_usr.removeItem(idx_empty)\n else:\n pass\n\n # if a new user is created\n if idx_usr == -1:\n\n # sort alphabetically users\n saved_users = saved_accounts.keys()\n saved_users.append(str(usr))\n sorted_users = sorted(saved_users)\n idx_new_usr = sorted_users.index(str(usr))\n self.combobox_usr.insertItem(idx_new_usr, usr)\n else:\n pass\n\n # update saved accounts dict\n saved_accounts[str(usr)] = {}\n\n saved_accounts[str(usr)][\"pwd\"] = pwd\n saved_accounts[str(usr)][\"api_key\"] = api_key\n saved_accounts[str(usr)][\"type\"] = acc_type\n saved_accounts[str(usr)][\"proxies\"] = {\"https\": proxies}\n\n # enabled (or not) trash button\n if usr == \"\":\n self.btn_trash.setEnabled(False)\n else:\n self.btn_trash.setEnabled(True)\n\n # write new credentials\n funcMisc.write_credentials(saved_accounts)\n\n\n def delete_account(self):\n\n \"\"\"When user clicks on button trash deletes selected account\"\"\"\n\n saved_accounts = funcMisc.read_credentials()\n\n usr_to_delete = str(self.combobox_usr.currentText())\n idx_usr_to_delete = self.combobox_usr.currentIndex()\n\n # delete key in dict and remove usr in combobox\n saved_accounts.pop(usr_to_delete, None)\n self.combobox_usr.removeItem(idx_usr_to_delete)\n\n # write new credentials\n funcMisc.write_credentials(saved_accounts)\n\n\n def user_edition(self):\n\n \"\"\"User is editing account via inputs widgets.\"\"\"\n\n saved_accounts = funcMisc.read_credentials()\n credentials_path = os.getcwd() + \"/credentials.txt\"\n list_type = [\"Live\", \"Demo\"]\n\n # get user modifications\n usr = str(self.combobox_usr.currentText())\n api_key = str(self.line_edit_key.text())\n pwd = str(self.line_edit_pwd.text())\n acc_type = str(self.combobox_type.currentText())\n proxies = str(self.line_edit_proxies.text())\n\n # user editing name in combobox\n if self.sender().objectName() == \"user_choice\":\n\n # new username not saved yet\n if usr not in saved_accounts.keys():\n\n # clear pwd, api key and proxies widgets\n self.line_edit_pwd.setText(\"\")\n self.line_edit_key.setText(\"\")\n self.line_edit_proxies.setText(\"\")\n\n # username already exists, set known infos\n else:\n saved_pwd = saved_accounts[usr][\"pwd\"]\n saved_api_key = saved_accounts[usr][\"api_key\"]\n saved_acc_type = saved_accounts[usr][\"type\"]\n saved_proxies = saved_accounts[usr][\"proxies\"][\"https\"]\n\n # fill widgets with known infos\n self.line_edit_pwd.setText(saved_pwd)\n self.line_edit_key.setText(saved_api_key)\n self.line_edit_proxies.setText(saved_proxies)\n\n self.combobox_type.setCurrentIndex(list_type\n .index(saved_acc_type))\n self.btn_trash.setEnabled(True)\n\n else:\n\n # if pwd and api key and user are not\n # correctly set disable connection\n if usr == \"\" or pwd ==\"\" or api_key ==\"\":\n self.btn_connect.setEnabled(False)\n else:\n self.btn_connect.setEnabled(True)\n\n # write new credentials\n funcMisc.write_credentials(saved_accounts)\n\n # enabled (or not) trash button\n if usr == \"\":\n self.btn_trash.setEnabled(False)\n else:\n self.btn_trash.setEnabled(True)\n\n\n def create_connection_dict(self):\n\n \"\"\"\n Set connection info, username/pwd and urls. Creates a dict\n with headers correctly set for connection request, usr\n and pwd and urls used to communicate with API\n \"\"\"\n\n # get infos to establish connection with API\n acc_type = str(self.combobox_type.currentText())\n usr = str(self.combobox_usr.currentText())\n pwd = str(self.line_edit_pwd.text())\n api_key = str(self.line_edit_key.text())\n proxies = str(self.line_edit_proxies.text())\n\n graph_state = self.chkbox_remember.checkState()\n auto_connect = self.chkbox_autoconnect.checkState()\n saved_accounts = funcMisc.read_credentials()\n config = funcMisc.read_config()\n\n # set selected account in dict to saved\n saved_accounts[usr] = {}\n\n saved_accounts[usr][\"pwd\"] = pwd\n saved_accounts[usr][\"api_key\"] = api_key\n saved_accounts[usr][\"type\"] = acc_type\n saved_accounts[usr][\"proxies\"] = {\"https\": proxies}\n\n # update config file\n config[\"last_usr\"] = usr\n config[\"auto_connect\"] = auto_connect\n funcMisc.write_config(config)\n\n # delete empty key (created when file is empty)\n if \"\" in saved_accounts.keys():\n saved_accounts.pop(\"\", None)\n\n ig_urls = funcMisc.read_ig_config()\n\n if acc_type == \"Live\":\n base_url = ig_urls[\"base_url\"][\"live\"]\n elif acc_type == \"Demo\":\n base_url = ig_urls[\"base_url\"][\"demo\"]\n\n # save file according to user\"s choice(remember or not)\n if graph_state == 2:\n funcMisc.write_credentials(saved_accounts)\n elif checkbox_state == 0:\n funcMisc.write_credentials({}) # save empty dict\n\n connect_args = {\"urls\": base_url,\n \"identifier\": usr,\n \"password\": pwd,\n \"X-IG-API-KEY\": api_key,\n \"proxies\": proxies\n }\n\n self._set_connect_dict(**connect_args)\n self.on_close()\n\n\n def _get_connect_dict(self):\n\n \"\"\"Getter method\"\"\"\n\n return(self._connect_dict)\n\n\n def _set_connect_dict(self, *args, **kwargs):\n\n \"\"\"\n Setter method. Build a connect_dict with infos\n needed for API connection see API documentation\n for structure of payload, header and get method\n\n :kw param identifier: string, username\n :kw param password: string,\n :kw param X-IG-API-KEY: api key of account\n :kw param proxies: dict proxy to connect through\n :kw param urls: string, base url for interacting with API\n \"\"\"\n\n connect_dict = {}\n\n payload = json.dumps({\"identifier\": kwargs[\"identifier\"] ,\n \"password\": kwargs[\"password\"]\n })\n\n headers = {\"Content-Type\": \"application/json; charset=utf-8\",\n \"Accept\": \"application/json; charset=utf-8\",\n \"X-IG-API-KEY\": kwargs[\"X-IG-API-KEY\"]\n }\n\n proxies = {\"https\": kwargs[\"proxies\"]}\n\n connect_dict[\"base_url\"] = kwargs[\"urls\"]\n connect_dict[\"payload\"] = payload\n connect_dict[\"headers\"] = headers\n connect_dict[\"proxies\"] = proxies\n\n self._connect_dict = connect_dict\n\n\n def on_close(self):\n\n \"\"\"close window\"\"\"\n\n self.close()\n\n\nclass MarketsWindow(QtWidgets.QMainWindow):\n\n \"\"\"\n Create a dialog box to search and manage markets.\n User can search market, manage favorite market, manage prices\n subscription and configure a default template for trading.\n\n -- One QLineEdit to search market\n -- One QListWidget to display search results\n -- One QTreeView to display favorite markets\n -- One QGroupBox to display infos about selected market\n\n It uses a QMainWindow as the statusBar is natively supported\n \"\"\"\n\n def __init__(self, session, parent):\n\n \"\"\"\n :param session: classRestCom instance\n :param parent: classMainWindow instance\n \"\"\"\n\n QtWidgets.QMainWindow.__init__(self, parent=parent)\n\n icons_path = os.getcwd() + \"/icons\"\n\n self.setWindowTitle(\"Manage markets\")\n self.setWindowIcon(QtGui.QIcon(icons_path+\"/markets.png\"))\n\n self.setWindowModality(QtCore.Qt.WindowModal)\n self.setWindowFlags(QtCore.Qt.Dialog)\n\n # get logger\n self.logger_debug = logging.getLogger(\"WuScalp_debug\")\n self.logger_info = logging.getLogger(\"WuScalp_info\")\n\n # add a dummy menu to make a separation between title bar and widgets\n self.menuBar().addMenu(\"\")\n\n self.session = session\n self.req_args = session._get_req_args()\n\n # load favorite markets\n favorite_markets = funcMisc.read_favorites()\n favorite_epics = favorite_markets[\"epic\"]\n favorite_names = favorite_markets[\"name\"]\n\n # headers of QTreeView\n list_headers = [\"Market name\", \"Shortcut\",\n \"Live prices\", \"Show graph\", \"\"]\n\n # list of markets details to be shown\n list_details = [(\"Bid\", \"Min. size\"),\n (\"Ask\", \"Min. stop\"),\n (\"Spread\", \"Min. guaranteed stop\")\n ]\n\n self.dict_lbl_details = OrderedDict()\n\n # init widgets\n widget_main = QtWidgets.QWidget()\n layout_main = QtWidgets.QVBoxLayout()\n\n splitter = QtWidgets.QSplitter()\n\n grpbox_search = QtWidgets.QGroupBox(\"Market search\")\n layout_search = QtWidgets.QGridLayout()\n\n grpbox_favorites = QtWidgets.QGroupBox(\"Favorite markets\")\n layout_favorites = QtWidgets.QGridLayout()\n\n self.grpbox_details = QtWidgets.QGroupBox(\"No markets selected\")\n layout_details = QtWidgets.QGridLayout()\n\n self.tree_favorites = QtWidgets.QTreeView()\n tree_model = classCustomWidgets.CustomTreeModel()\n\n # widget for status bar\n self.widget_permanent = QtWidgets.QWidget()\n layout_permanent = QtWidgets.QHBoxLayout()\n\n self.progress_bar = QtWidgets.QProgressBar()\n self.lbl_status = QtWidgets.QLabel()\n\n self.line_edit_search = classCustomWidgets.CustomLineEdit(\"search\")\n self.list_search = QtWidgets.QListWidget()\n\n # configure grpbox infos\n for count, detail in enumerate(list_details):\n left_text , right_text = detail\n\n static_label_left = QtWidgets.QLabel(left_text+\": \")\n static_label_right = QtWidgets.QLabel(right_text+\": \")\n\n label_left = QtWidgets.QLabel() # to display variable text\n label_right = QtWidgets.QLabel()\n\n layout_details.addWidget(static_label_left, count, 0, 1, 1,\n QtCore.Qt.AlignLeft)\n\n layout_details.addWidget(label_left, count, 1, 1, 1,\n QtCore.Qt.AlignRight)\n\n layout_details.addWidget(static_label_right, count, 4, 1, 1,\n QtCore.Qt.AlignLeft)\n\n layout_details.addWidget(label_right, count, 5, 1, 1,\n QtCore.Qt.AlignRight)\n\n self.dict_lbl_details[left_text] = label_left\n self.dict_lbl_details[right_text] = label_right\n\n # add a vline to separate two columns\n vline = QtWidgets.QFrame()\n vline.setFrameShape(QtWidgets.QFrame.VLine)\n vline.setStyleSheet(\"color:rgb(0,0,0);\")\n\n layout_details.addWidget(vline, 0, 3, 3, 1)\n self.grpbox_details.setLayout(layout_details)\n\n # configure QTreeView\n self.tree_favorites.setAcceptDrops(True)\n self.tree_favorites.setDragEnabled(True)\n self.tree_favorites.setModel(tree_model)\n self.tree_favorites.selectionModel().currentChanged.connect(self.update_details)\n\n # set headers for QTreeView\n for count, header in enumerate(list_headers):\n header_item = QtGui.QStandardItem(header)\n tree_model.setHorizontalHeaderItem(count, header_item)\n header_item.setTextAlignment(QtCore.Qt.AlignCenter)\n\n # configure favorite widgets\n layout_favorites.addWidget(self.tree_favorites, 0, 0, 1, 1)\n layout_favorites.addWidget(self.grpbox_details, 1, 0, 1, 1)\n grpbox_favorites.setLayout(layout_favorites)\n\n # configure grpbox search\n layout_search.addWidget(self.line_edit_search, 0, 0, 1, 1)\n layout_search.addWidget(self.list_search, 1, 0 ,1 ,1)\n grpbox_search.setLayout(layout_search)\n\n # configure line edit\n self.line_edit_search.setText(\"Search a market\")\n self.line_edit_search.set_italic(True)\n\n # configure list\n self.list_search.setDragEnabled(True)\n\n # configure splitter\n splitter.addWidget(grpbox_search)\n splitter.addWidget(grpbox_favorites)\n splitter.setHandleWidth(8)\n\n widget_width = widget_main.geometry().width()\n splitter.setSizes([widget_width/1.75, (widget_width)])\n\n # configure permanent widget\n self.progress_bar.setMaximumSize(200, 18)\n self.lbl_status.setMaximumHeight(18)\n\n layout_permanent.addWidget(self.lbl_status)\n layout_permanent.addWidget(self.progress_bar)\n\n self.widget_permanent.setMaximumHeight(18)\n self.widget_permanent.setLayout(layout_permanent)\n self.widget_permanent.hide()\n\n # connect signals\n self.line_edit_search.text_changed.connect(self.start_search_terms)\n tree_model.item_added.connect(self.favorite_added)\n\n # create a worker, a queue and a thread for searching markets by terms\n self.queue_terms = Queue.Queue()\n self.worker_terms = classWorker.BasicWorker(self.queue_terms)\n self.thread_terms = QtCore.QThread()\n\n # create a worker, a queue and a thread for searching markets by epic\n self.queue_epic = Queue.Queue()\n self.worker_epic = classWorker.BasicWorker(self.queue_epic)\n self.thread_epic = QtCore.QThread()\n\n # move the worker to designated thread\n self.worker_terms.moveToThread(self.thread_terms)\n self.worker_epic.moveToThread(self.thread_epic)\n\n # connect signals and start threads\n self.worker_terms.job_done.connect(self.search_terms_done)\n self.thread_terms.started.connect(self.worker_terms._main)\n self.thread_terms.start()\n\n self.worker_epic.job_done.connect(self.search_epic_done)\n self.thread_epic.started.connect(self.worker_epic._main)\n self.thread_epic.start()\n\n self.worker_epic.stop_signal.connect(self.thread_epic.quit)\n self.thread_epic.finished.connect(self.worker_epic.deleteLater)\n self.thread_epic.finished.connect(self.thread_epic.deleteLater)\n\n self.worker_terms.stop_signal.connect(self.thread_terms.quit)\n self.thread_terms.finished.connect(self.worker_terms.deleteLater)\n self.thread_terms.finished.connect(self.thread_terms.deleteLater)\n\n # load and display favorites saved\n for count, epic in enumerate(favorite_epics):\n\n # create a new item with epic of market dropped\n item_market = QtGui.QStandardItem(favorite_names[count])\n\n # disable child item\n item_market.setFlags(item_market.flags()^QtCore.Qt.ItemIsDropEnabled)\n\n item_market.setData(epic)\n self.tree_favorites.model().setItem(count, item_market)\n self.favorite_added(item_market, startup=True)\n\n # configure main widget\n layout_main.addWidget(splitter)\n widget_main.setLayout(layout_main)\n\n self.statusBar().addPermanentWidget(self.widget_permanent)\n self.setCentralWidget(widget_main)\n self.resize(650, 400)\n self.show()\n\n\n def favorite_added(self, item, startup=False):\n\n \"\"\"\n Search a market by epic, triggered when a\n market is dropped on QTreeView or at startup.\n Add a new row with market name and three widgets:\n - CustomLabel to subscribe/unsubscribe to lighstreamer,\n - CustomLabel to delete favorite,\n - CustomLineEdit to edit shorcuts associated to market\n - CustomCheckBox to choose to display or not a tick graph\n\n :param item: QStandardItem, data contains epic to search\n :kw param startup: boolean, True when window is created\n \"\"\"\n\n\n icons_path = os.getcwd() + \"/icons/\"\n icon_trash = QtGui.QPixmap(icons_path+\"trash.png\")\n\n epic = item.data() # get epic to search\n\n list_object_name = [\"shorcut\", \"live_prices\", \"show_graph\", \"delete\"]\n\n last_row = self.tree_favorites.model().rowCount()\n\n if startup == True: # fisrt start, load favorites saved\n\n favorite_markets = funcMisc.read_favorites()\n\n # get favorites parameters\n favorite_epics = favorite_markets[\"epic\"]\n favorite_shorcuts = favorite_markets[\"shortcut\"]\n graph_status = favorite_markets[\"show_graph\"]\n live_status = favorite_markets[\"live_prices\"]\n\n idx = favorite_markets[favorite_markets[\"epic\"]==epic].index[0]\n\n # configuration of new row to add\n shorcut_saved = favorite_shorcuts[idx]\n live_status_saved = live_status[idx]\n graph_status = graph_status[idx]\n\n if live_status_saved == True:\n style_sheet = \"background-color:#36C431\" # green background\n text_status = \"On\"\n else:\n style_sheet = \"background-color:#ED4049\" # red background\n text_status = \"Off\"\n\n else: # set a default configuration when new favorite is dropped\n shorcut_saved = \"\"\n style_sheet = \"background-color:#ED4049\" # red background\n text_status = \"Off\"\n graph_status = 0\n\n # create widgets for new favorite market\n for count, object_name in enumerate(list_object_name):\n\n # create a layout and a widget to allow centering sub-widget\n tree_layout = QtWidgets.QHBoxLayout()\n tree_widget = QtWidgets.QWidget()\n\n \"\"\"\n for each widget set an object name (identifier) with a string\n describing the widget and the row where the widget is set separated\n by a pipe. Like so we pass two informations inside the\n object name. There is probably a better/cleaner solution.\n \"\"\"\n\n # create a CustomLabel with background color depending of state of subscription\n if object_name == \"live_prices\":\n identifier = \"%s|%d\" %(object_name, last_row-1)\n widget_to_set = classCustomWidgets.CustomLabel(identifier)\n\n widget_to_set.set_italic(True)\n widget_to_set.setAlignment(QtCore.Qt.AlignCenter)\n widget_to_set.setText(text_status)\n\n widget_to_set.setStyleSheet(style_sheet)\n widget_to_set.setFixedWidth(70)\n\n widget_to_set.clicked_signal.connect(self.favorite_changed)\n\n # create a CustomLineEdit to edit shorcut\n elif object_name == \"shorcut\":\n identifier = \"%s|%d\" %(object_name, last_row-1)\n widget_to_set = classCustomWidgets.CustomShortcutLineEdit(identifier)\n\n widget_to_set.setAlignment(QtCore.Qt.AlignCenter)\n widget_to_set.setText(shorcut_saved)\n\n widget_to_set.setStyleSheet(\"border: None\")\n widget_to_set.setFixedWidth(80)\n\n widget_to_set.text_changed.connect(self.favorite_changed)\n\n # create a QCheckBox to show or not a graph\n elif object_name == \"show_graph\":\n identifier = \"%s|%d\" %(object_name, last_row-1)\n widget_to_set = classCustomWidgets.CustomCheckBox(identifier)\n\n widget_to_set.setCheckState(graph_status)\n\n widget_to_set.state_changed.connect(self.favorite_changed)\n\n # create a CustomLabel with a trash icon\n elif object_name == \"delete\":\n identifier = \"%s|%d\" %(object_name, last_row-1)\n widget_to_set = classCustomWidgets.CustomLabel(identifier)\n\n widget_to_set.setPixmap(icon_trash)\n widget_to_set.clicked_signal.connect(self.favorite_changed)\n\n # configure main widget\n tree_layout.addWidget(widget_to_set)\n tree_layout.setAlignment(QtCore.Qt.AlignCenter)\n tree_widget.setLayout(tree_layout)\n\n # add widget to item\n index_model = self.tree_favorites.model().index(last_row-1,\n count +1,\n QtCore.QModelIndex())\n\n self.tree_favorites.setIndexWidget(index_model, tree_widget)\n\n self.tree_favorites.resizeColumnToContents(0)\n\n if startup == True:\n return\n\n self.queue_epic.put((self.session.search_epic, (epic,), {}))\n\n\n def favorite_changed(self, identifier, *args, **kwargs):\n\n \"\"\"\n Update the favorite market selected\n\n :param identifier: str, see favorite_added method for more infos\n \"\"\"\n\n object_name, active_row = identifier.split(\"|\")\n\n favorite_markets = funcMisc.read_favorites()\n favorite_epics = favorite_markets[\"epic\"]\n\n # get active row\n tree_model = self.tree_favorites.model()\n active_row = int(active_row)\n\n # no market in list or previous market has been deleted\n if active_row > tree_model.rowCount() - 1:\n active_row = tree_model.rowCount() - 1\n\n # get item containing the epic (market) modified\n item_epic = self.tree_favorites.model().item(active_row, 0)\n\n try:\n active_epic = item_epic.data()\n except AttributeError:\n return\n\n\n # user want to subscribe/unsubscribe to live price\n if object_name == \"live_prices\":\n label_text = self.sender().text()\n\n # live price currently active\n if \"On\" in label_text:\n style_sheet = \"background-color:#ED4049\"\n text_status = \"Off\"\n status = False\n\n \"\"\"\n If user disable live prices, it is useless to show a graph\n Get the checkbox on the row changed and set it as unchecked\n \"\"\"\n\n # checkbox is on the fourth column of tree view\n index_model = self.tree_favorites.model().index(active_row,\n 3,\n QtCore.QModelIndex())\n\n widget_graph = self.tree_favorites.indexWidget(index_model)\n chkbox_graph = widget_graph.findChildren(classCustomWidgets\n .CustomCheckBox)[0]\n\n graph_state = chkbox_graph.checkState()\n\n # change st of checkbox and preference of market\n chkbox_graph.setCheckState(0)\n favorite_markets.loc[active_row, \"show_graph\"] = 0\n\n else:\n style_sheet = \"background-color:#36C431\"\n text_status = \"On\"\n status = True\n\n # modify appearance of widget\n self.sender().setText(text_status)\n self.sender().setStyleSheet(style_sheet)\n\n # update favorites saved\n favorite_markets.loc[active_row, \"live_prices\"] = status\n\n # user has changed shortcut associated to epic\n elif object_name == \"shorcut\":\n\n # if shortcut invalid already set, display a msg\n if type(self.sender().keysequence) == unicode:\n self.statusBar().showMessage(self.sender().keysequence)\n\n else:\n new_shortcut = self.sender().keysequence\\\n .toString(QtGui.QKeySequence.NativeText)\n favorite_markets.loc[active_row, \"shortcut\"] = new_shortcut\n self.statusBar().showMessage(\"\")\n\n # user won't to show or not a tick graph\n elif object_name == \"show_graph\":\n\n \"\"\"\n If user want to show a graph, a subscription to live prices\n is needed. Get the label of the row modified and change its style\n \"\"\"\n\n # label is on the third column of tree view\n index_model = self.tree_favorites.model().index(active_row,\n 2,\n QtCore.QModelIndex())\n widget_prices = self.tree_favorites.indexWidget(index_model)\n label_prices = widget_prices.findChildren(classCustomWidgets\n .CustomLabel)[0]\n\n label_text = label_prices.text() # get the text currently set\n\n if \"Off\" in label_text: # no subscription\n style_sheet = \"background-color:#36C431\"\n text_status = \"On\"\n status = True\n\n # change style of label and preference of market\n label_prices.setText(\"On\")\n label_prices.setStyleSheet(style_sheet)\n favorite_markets.loc[active_row, \"live_prices\"] = status\n\n state_graph = self.sender().checkState()\n favorite_markets.loc[active_row, \"show_graph\"] = state_graph\n\n # user wants to delete a favorite\n elif object_name == \"delete\":\n self.tree_favorites.setCurrentIndex(tree_model.index(active_row, 0))\n active_index = self.tree_favorites.currentIndex()\n\n item_to_del = self.tree_favorites.model().item(active_row, 0)\n name_to_del = item_to_del.text()\n\n # remove row and update favorite\n if active_index.isValid():\n self.tree_favorites.model().removeRow(active_row, active_index.parent())\n favorite_markets = favorite_markets[favorite_markets.index!=active_row]\n\n # display and log a message\n msg = \"%s deleted from favorites\" %name_to_del\n self.statusBar().showMessage(msg)\n self.logger_info.log(logging.INFO, msg)\n\n funcMisc.write_favorites(favorite_markets) # write new favorites\n\n\n def start_search_terms(self, sender, text, *args, **kwargs):\n\n \"\"\"\n Search market by text entered in CustomLineEdit\n\n :param sender: string object name of sender\n :param text: string, text entered by user\n \"\"\"\n\n if text == \"\" or text == \"Search a market\":\n self.line_edit_search.set_italic(True)\n self.line_edit_search.setText(\"Search a market\")\n return\n\n else:\n self.line_edit_search.set_italic(False)\n\n self.statusBar().showMessage(\"Searching...\")\n self.widget_permanent.show()\n\n self.progress_bar.setRange(0,0)\n self.progress_bar.setValue(100)\n\n if len(text) > 3:\n self.queue_terms.put((self.session.search_terms, (text,), {}))\n\n\n def search_terms_done(self, sender, content, *args, **kwargs):\n\n \"\"\"\n Search by terms finished, add a new row in QListWidget\n\n :param sender: string describing the request that has been made\n :param content: result of the request\n \"\"\"\n\n search_terms_reply = content\n\n # an error occured display msg\n if type(search_terms_reply) == classRestCom.APIError:\n msg = search_terms_reply._get_error_msg()\n self.statusBar().showMessage(msg)\n return\n\n self.list_search.clear() # clear previous result\n\n try:\n markets_name = search_terms_reply[\"instrumentName\"]\n list_epic = search_terms_reply[\"epic\"]\n\n except KeyError: # no market found display and log a msg\n msg = \"No market found for %s \" %self.line_edit_search.text()\n self.logger_info.log(logging.INFO, msg)\n self.statusBar().showMessage(msg)\n return\n\n for count, name in enumerate(markets_name):\n item = QtWidgets.QListWidgetItem()\n epic = list_epic[count]\n\n item.setData(QtCore.Qt.UserRole, epic) # set epic as data of item\n item.setText(name)\n self.list_search.addItem(item)\n\n self.statusBar().showMessage(\"\")\n self.widget_permanent.hide()\n self.progress_bar.setRange(0,100)\n\n\n def search_epic_done(self, sender, content, *args, **kwargs):\n\n \"\"\"\n Search by epic finished, edit favorites saved.\n Favorites are saved as a pandas data frame. See columns name\n or classRestCom.search_epics() to see what infos are saved\n\n :param sender: string describing the request that has been made\n :param content: result of the request\n \"\"\"\n\n favorite_markets = funcMisc.read_favorites()\n\n search_epic_reply = content\n\n # an error occured display a msg\n if type(search_epic_reply) == classRestCom.APIError:\n msg = search_epic_reply._get_error_msg()\n self.statusBar().showMessage(msg)\n return\n\n # get name added\n name = search_epic_reply.loc[0, \"name\"]\n\n # display and log a msg\n msg = \"%s added to favorites\" %name\n self.statusBar().showMessage(msg)\n self.logger_info.log(logging.INFO, msg)\n\n # construct a data frame with favorites\n if favorite_markets.empty == True:\n favorite_to_save = search_epic_reply\n else:\n favorite_to_save = pd.concat([favorite_markets, search_epic_reply])\n\n funcMisc.write_favorites(favorite_to_save)\n\n\n def update_details(self, active_index, *args, **kwargs):\n\n \"\"\"\n Update the QGroupBox with details of the market clicked\n\n :param active_index: int, index of the active item\n \"\"\"\n\n # list to get the infos to update, 2nd item of tuple is a suffix\n list_details = [(\"Min. size\", \" lots\"),\n (\"Min. guaranteed stop\", \" pts\"),\n (\"Min. stop\", \" pts\"),\n (\"Ask\", \"\"),\n (\"Bid\", \"\")]\n\n # get active row\n active_row = active_index.row()\n\n # get item containing the epic (market) clicked\n item_epic = self.tree_favorites.model().item(active_row, 0)\n\n try:\n active_epic = item_epic.data()\n\n except AttributeError: # no markets, empty labels\n\n for tup in list_details:\n col_name, suffix = tup\n label = self.dict_lbl_details[col_name]\n label.setText(\"\")\n\n return\n\n favorite_markets = funcMisc.read_favorites()\n\n # loacte the favorite market clicked\n idx = favorite_markets[favorite_markets[\"epic\"]==active_epic].index[0]\n\n # get name of market\n name = favorite_markets.loc[idx, \"name\"]\n self.grpbox_details.setTitle(name)\n\n # populate the labels\n for tup in list_details:\n col_name, suffix = tup\n detail = str(favorite_markets.loc[idx,col_name])\n label = self.dict_lbl_details[col_name]\n label.setText(detail+suffix)\n\n\n def closeEvent(self, event, *args, **kwargs):\n\n \"\"\"\n Reimplement base method. Stop and delete threads and worker\n\n :param event: QtCore.QCloseEvent\n \"\"\"\n\n self.worker_terms.stop()\n self.worker_epic.stop()\n\n self.thread_epic.wait()\n self.thread_terms.wait()\n\n del self.thread_epic\n del self.thread_terms\n\n del self.worker_epic\n del self.worker_terms\n\n del self.queue_epic\n del self.queue_terms\n\n self.deleteLater()\n\n\nclass OptionsWindow(QtWidgets.QMainWindow):\n\n \"\"\"\n Create a QMainWindow to edit options\n \"\"\"\n\n options_signal = QtCore.pyqtSignal(object) # signal send when options changes\n\n def __init__(self, parent=None, *args, **kwargs):\n\n \"\"\"\n Init GUI. 5 groupboxes are created:\n -- one for ticks curve options and one for trading options.\n They are set in a independant HBox layout and widget.\n -- three groupbox to configure moving average, also set in an\n independant HBox layout and widget\n\n :param parent: QMainWindow\n \"\"\"\n\n icons_path = os.getcwd() + \"/icons\"\n\n QtWidgets.QMainWindow.__init__(self, parent)\n\n self.setWindowIcon(QtGui.QIcon(icons_path+\"/main.png\"))\n self.setWindowTitle(\"Options\")\n\n self.setWindowModality(QtCore.Qt.WindowModal)\n self.setWindowFlags(QtCore.Qt.Dialog)\n\n config = funcMisc.read_config()\n\n widget_main = QtWidgets.QWidget() # will be set as central widget\n layout_main = QtWidgets.QGridLayout()\n\n curves_icons = funcMisc.create_curves_icons()\n\n # init widgets and layouts\n widget_top = QtWidgets.QWidget()\n layout_top = QtWidgets.QHBoxLayout()\n widget_ma_main = QtWidgets.QWidget()\n layout_ma_main = QtWidgets.QHBoxLayout()\n\n widget_ticks_options = self.create_widget_ticks_options(config,\n curves_icons)\n widget_trading_options = self.create_widget_trading_options(config)\n\n # create 3 groupboxes to configure the 3 moving average\n for i in range(3):\n key = \"ma%d_curve\" %(i+1) # key is the same that in config file\n widget_ma_options = self.create_widget_ma_options(key,\n config,\n curves_icons)\n layout_ma_main.addWidget(widget_ma_options)\n\n # set layout to widget\n widget_ma_main.setLayout(layout_ma_main)\n\n # configure top widget\n layout_top.addWidget(widget_ticks_options)\n layout_top.addWidget(widget_trading_options)\n widget_top.setLayout(layout_top)\n\n # configure main widget\n layout_main.addWidget(widget_top)\n layout_main.addWidget(widget_ma_main)\n widget_main.setLayout(layout_main)\n\n self.setCentralWidget(widget_main)\n\n\n def create_widget_ticks_options(self, config, curves_icons, *args, **kwargs):\n\n \"\"\"\n Create ticks chart options widget. User can which prices to plot,\n number of ticks to display changes curve style, color and thickness.\n\n :param config: dict with configuration to set\n :param curves_icons: dict with int as key and QPixmap as values\n \"\"\"\n\n # get config saved\n ticks_color = config[\"ticks_curve\"][\"color\"]\n ticks_style = config[\"ticks_curve\"][\"style\"]\n ticks_width = config[\"ticks_curve\"][\"width\"]\n ticks_lenght = config[\"ticks_curve\"][\"lenght\"]\n ticks_data = config[\"ticks_curve\"][\"data\"]\n\n # init widgets\n widget_ticks_curve = QtWidgets.QGroupBox(\"Ticks chart options\")\n layout_ticks_curve = QtWidgets.QGridLayout()\n\n # object names are the keys used in config file\n btn_ticks_color = classCustomWidgets.CustomPushButton(\"\",\n \"ticks_curve_color\")\n combobox_data = QtWidgets.QComboBox() # prices to show\n combobox_ticks_style = QtWidgets.QComboBox() # curve style\n spinbox_ticks_width = QtWidgets.QDoubleSpinBox() # curve thickness\n spinbox_ticks_lenght = QtWidgets.QDoubleSpinBox() # nb of ticks to show\n\n # configure color buttons\n btn_ticks_color.set_default_style(ticks_color, ticks_color)\n btn_ticks_color.clicked.connect(self.update_options)\n\n # configure spinboxes\n spinbox_ticks_width.setRange(1, 20)\n spinbox_ticks_lenght.setRange(1, 1000)\n\n spinbox_ticks_width.setSingleStep(0.5)\n spinbox_ticks_lenght.setSingleStep(1)\n\n spinbox_ticks_width.setDecimals(1)\n spinbox_ticks_lenght.setDecimals(0)\n\n spinbox_ticks_width.setFixedWidth(90)\n spinbox_ticks_lenght.setFixedWidth(90)\n\n # object names are the keys used in config file\n spinbox_ticks_width.setObjectName(\"ticks_curve_width\")\n spinbox_ticks_lenght.setObjectName(\"ticks_curve_lenght\")\n\n spinbox_ticks_width.setValue(ticks_width)\n spinbox_ticks_lenght.setValue(ticks_lenght)\n\n # connect signals\n spinbox_ticks_width.valueChanged.connect(self.update_options)\n spinbox_ticks_lenght.valueChanged.connect(self.update_options)\n\n spinbox_ticks_lenght.setToolTip(\"Number of ticks displayed\")\n\n # configure combobox\n for count, key in enumerate([\"Midprice\", \"Bid\", \"Offer\"]):\n combobox_data.addItem(key,\n userData=QtCore.QVariant(key))\n\n for count, key in enumerate(curves_icons.keys()):\n combobox_ticks_style.addItem(curves_icons[key], \"\",\n userData=QtCore.QVariant(key))\n\n index_data = [\"Midprice\", \"Bid\", \"Offer\"].index(ticks_data)\n index_ticks_style = combobox_ticks_style.findData(ticks_style)\n\n combobox_ticks_style.setIconSize(QtCore.QSize(100,14))\n\n combobox_data.setCurrentIndex(index_data)\n combobox_ticks_style.setCurrentIndex(index_ticks_style)\n\n # object names are the keys used in config file\n combobox_data.setObjectName(\"ticks_curve_data\")\n combobox_ticks_style.setObjectName(\"ticks_curve_style\")\n\n combobox_data.setFixedWidth(90)\n combobox_ticks_style.setFixedWidth(90)\n\n # connect signals\n combobox_data.currentIndexChanged.connect(self.update_options)\n combobox_ticks_style.currentIndexChanged.connect(self.update_options)\n\n # place widgets on layout\n layout_ticks_curve.addWidget(QtWidgets.QLabel(\"Prices to show:\"), 0, 0)\n layout_ticks_curve.addWidget(combobox_data, 0, 1)\n\n layout_ticks_curve.addWidget(QtWidgets.QLabel(\"Color:\"), 1, 0)\n layout_ticks_curve.addWidget(btn_ticks_color, 1, 1)\n\n layout_ticks_curve.addWidget(QtWidgets.QLabel(\"Style:\"), 2, 0)\n layout_ticks_curve.addWidget(combobox_ticks_style, 2, 1)\n\n layout_ticks_curve.addWidget(QtWidgets.QLabel(\"Thickness:\"), 3, 0)\n layout_ticks_curve.addWidget(spinbox_ticks_width, 3, 1)\n\n layout_ticks_curve.addWidget(QtWidgets.QLabel(\"Lenght:\"), 4, 0)\n layout_ticks_curve.addWidget(spinbox_ticks_lenght, 4, 1)\n\n widget_ticks_curve.setLayout(layout_ticks_curve)\n\n return(widget_ticks_curve)\n\n\n def create_widget_ma_options(self, ma, config, curves_icons, *args, **kwargs):\n\n \"\"\"\n Create a widget to configure moving average curves\n Colors, style, width and period of curves can be edited\n\n :param ma: string, for which moving average the wiget is created\n :param config: dict with configuration to set\n :param curves_icons: dict with int as key and QPixmap as values\n \"\"\"\n\n # get config saved\n ma_color = config[ma][\"color\"]\n ma_style = config[ma][\"style\"]\n ma_width = config[ma][\"width\"]\n ma_period = config[ma][\"period\"]\n ma_show = config[ma][\"show\"]\n\n # init widgets\n grpbox_ma = QtWidgets.QGroupBox(\"Moving average %s\" %ma[2])\n layout_ma = QtWidgets.QGridLayout()\n\n # object names are the keys used in config file\n chkbox_ma = classCustomWidgets.CustomCheckBox(ma+\"_show\")\n btn_ma_color = classCustomWidgets.CustomPushButton(\"\", ma+\"_color\")\n combobox_ma_style = QtWidgets.QComboBox()\n spinbox_ma_width = QtWidgets.QDoubleSpinBox()\n spinbox_ma_period = QtWidgets.QDoubleSpinBox()\n\n # configure color buttons\n btn_ma_color.set_default_style(ma_color, ma_color)\n\n spinbox_ma_period.setRange(1, 1000)\n spinbox_ma_width.setRange(1, 20)\n\n spinbox_ma_width.setSingleStep(0.5)\n spinbox_ma_period.setSingleStep(0.5)\n\n spinbox_ma_width.setDecimals(1)\n spinbox_ma_period.setDecimals(1)\n\n spinbox_ma_period.setValue(ma_period)\n spinbox_ma_width.setValue(ma_width)\n\n # object names are the keys used in config file\n spinbox_ma_period.setObjectName(ma+\"_period\")\n spinbox_ma_width.setObjectName(ma+\"_width\")\n\n spinbox_ma_period.setFixedWidth(90)\n spinbox_ma_width.setFixedWidth(90)\n\n # configure checkbox\n chkbox_ma.setCheckState(ma_show)\n\n # add icons to combobox\n for count, key in enumerate(curves_icons.keys()):\n name = curves_icons[key]\n combobox_ma_style.addItem(curves_icons[key], \"\",\n userData=QtCore.QVariant(key))\n\n # object names are the keys used in config file\n combobox_ma_style.setObjectName(ma+\"_style\")\n\n index_ma_style = combobox_ma_style.findData(ma_style)\n combobox_ma_style.setCurrentIndex(index_ma_style)\n combobox_ma_style.setFixedWidth(90)\n combobox_ma_style.setIconSize(QtCore.QSize(100,14))\n\n # connect signals\n combobox_ma_style.currentIndexChanged.connect(self.update_options)\n chkbox_ma.state_changed.connect(self.update_options)\n btn_ma_color.clicked.connect(self.update_options)\n\n spinbox_ma_period.valueChanged.connect(self.update_options)\n spinbox_ma_width.valueChanged.connect(self.update_options)\n\n # place widgets\n layout_ma.addWidget(QtWidgets.QLabel(\"Period:\"), 0, 0)\n layout_ma.addWidget(spinbox_ma_period, 0, 1)\n\n layout_ma.addWidget(QtWidgets.QLabel(\"Color:\"), 1, 0)\n layout_ma.addWidget(btn_ma_color, 1, 1)\n\n layout_ma.addWidget(QtWidgets.QLabel(\"Style:\"), 2, 0)\n layout_ma.addWidget(combobox_ma_style, 2, 1)\n\n layout_ma.addWidget(QtWidgets.QLabel(\"Tickness:\"), 3, 0)\n layout_ma.addWidget(spinbox_ma_width, 3, 1)\n\n layout_ma.addWidget(QtWidgets.QLabel(\"Show:\"), 4, 0)\n layout_ma.addWidget(chkbox_ma, 4, 1)\n\n grpbox_ma.setLayout(layout_ma)\n\n return(grpbox_ma)\n\n def create_widget_trading_options(self, config, *args, **kwargs):\n\n \"\"\"\n Creates a groupboc to configure trading options. User can edit\n shortcuts for orders, enable or not hedging and guaranteed stop\n\n :param config: dict with configuration to set\n \"\"\"\n\n # get config\n buy_key = config[\"buy_key\"]\n sell_key = config[\"sell_key\"]\n close_key = config[\"close_key\"]\n stop_g = config[\"stop_g\"]\n force_open = config[\"force_open\"]\n\n # init widgets\n widget_trading = QtWidgets.QGroupBox(\"Trading options\")\n layout_trading = QtWidgets.QGridLayout()\n\n # object names are the keys used in config file\n line_edit_buy = classCustomWidgets.CustomShortcutLineEdit(\"buy_key\")\n line_edit_sell = classCustomWidgets.CustomShortcutLineEdit(\"sell_key\")\n line_edit_close = classCustomWidgets.CustomShortcutLineEdit(\"close_key\")\n\n chkbox_force_open = classCustomWidgets.CustomCheckBox(\"force_open\")\n chkbox_stop_g = classCustomWidgets.CustomCheckBox(\"stop_g\")\n\n # init lists to configure line edit in loop\n list_line_edit = [line_edit_buy, line_edit_sell, line_edit_close]\n list_line_name = [\"buy_key\", \"sell_key\", \"close_key\"]\n\n for count, line_edit in enumerate(list_line_edit):\n object_name = list_line_name[count]\n order_key = config[object_name] # get key used\n\n if order_key == \"\": # no shortcut set\n line_edit.setText(\"Enter shortcut\")\n line_edit.set_italic(True)\n else:\n line_edit.setText(order_key)\n line_edit.set_italic(False)\n\n line_edit.setAlignment(QtCore.Qt.AlignCenter)\n line_edit.text_changed.connect(self.update_options)\n line_edit.setMaximumWidth(120)\n\n # configure checkboxes\n chkbox_stop_g.setCheckState(stop_g)\n chkbox_force_open.setCheckState(force_open)\n\n chkbox_force_open.state_changed.connect(self.update_options)\n chkbox_stop_g.state_changed.connect(self.update_options)\n\n # places widgets\n layout_trading.addWidget(QtWidgets.QLabel(\"Buy order: \"), 0, 0)\n layout_trading.addWidget(line_edit_buy, 0, 1, QtCore.Qt.AlignCenter)\n\n layout_trading.addWidget(QtWidgets.QLabel(\"Sell order: \"), 1, 0)\n layout_trading.addWidget(line_edit_sell, 1, 1, QtCore.Qt.AlignCenter)\n\n layout_trading.addWidget(QtWidgets.QLabel(\"Close order: \"),2, 0)\n layout_trading.addWidget(line_edit_close,2, 1, QtCore.Qt.AlignCenter)\n\n layout_trading.addWidget(QtWidgets.QLabel(\"Guaranteed stop: \"),3, 0)\n layout_trading.addWidget(chkbox_stop_g,3, 1, QtCore.Qt.AlignCenter)\n\n layout_trading.addWidget(QtWidgets.QLabel(\"Force open: \"),4, 0)\n layout_trading.addWidget(chkbox_force_open,4, 1, QtCore.Qt.AlignCenter)\n\n widget_trading.setLayout(layout_trading)\n\n return(widget_trading)\n\n\n def update_options(self, sender, *args, **kwargs):\n\n \"\"\"\n Update options. It determines the options to update using\n its object name as it's similar to the keys used in config file\n\n e.g:if oject name is \"ticks_curve_color\", it will update the color\n of the ticks curve. In this case the object name is splitted\n in two string. first string determines which curve to update,\n (here ticks_curve) and second one which options to update (here color)\n\n :param sender: str, int, boolean...depending of widget.\n \"\"\"\n\n config = funcMisc.read_config()\n\n widget = self.sender()\n object_name = str(widget.objectName())\n\n # user updates color of curves\n if type(widget) == classCustomWidgets.CustomPushButton:\n which_curve = \"_\".join(str(object_name).split(\"_\")[:-1])\n\n color = QtWidgets.QColorDialog.getColor()\n config[which_curve][\"color\"] = str(color.name())\n\n # update widget with new options\n widget.set_default_style(color.name(), color.name())\n\n # user edits either style curve or data to plot\n elif type(widget) == QtWidgets.QComboBox:\n which_curve = \"_\".join(str(object_name).split(\"_\")[:-1])\n\n # find the new options\n idx_data = widget.currentIndex()\n data = widget.itemData(idx_data)\n\n which_data = object_name\n\n # updates what data to plot (midprice, bid, offer)\n if \"data\" in object_name:\n config[which_curve][\"data\"] = data\n\n # update the curves style\n else:\n config[which_curve][\"style\"] = data\n\n # user updates trading options or moving average options\n elif type(widget) == classCustomWidgets.CustomCheckBox:\n state = widget.checkState()\n\n # user decides to show or not moving average\n if \"ma\" in object_name:\n which_curve = \"_\".join(str(object_name).split(\"_\")[:-1])\n config[which_curve][\"show\"] = state\n\n # user changes trading options (force open, guaranteed stop)\n else:\n config[object_name] = state\n\n # user updates thickness of curves or moving average period\n elif type(widget) == QtWidgets.QDoubleSpinBox:\n value = widget.value()\n which_curve = \"_\".join(str(object_name).split(\"_\")[:-1])\n\n # either \"period\" or \"width\"\n what = str(object_name).split(\"_\")[-1]\n\n # user updates moving average period\n if \"ma\" in object_name:\n config[which_curve][what] = value\n\n # user updates curves thickness\n else:\n config[which_curve][what] = value\n\n # user edits shortcuts associated to trading action (close, buy, sell)\n elif type(widget) == classCustomWidgets.CustomShortcutLineEdit:\n\n if type(widget.keysequence) == unicode: # means invalid shortcut\n self.statusBar().showMessage(widget.keysequence)\n else:\n\n # get the new shortcut set\n new_shortcut = widget.keysequence\\\n .toString(QtGui.QKeySequence.NativeText)\n config[object_name] = new_shortcut\n self.statusBar().showMessage(\"\")\n\n funcMisc.write_config(config)\n self.options_signal.emit(object_name)\n\n# if __name__ == \"__main__\":\n# import sys\n# # import dev_api\n\n# app = QtWidgets.QApplication(sys.argv)\n# app.setApplicationName(\"WuTrading\")\n\n# a=OptionsWindow(parent = None)\n# # # a.build_window(dummy_result_dict, [])\n# a.show()\n# sys.exit(app.exec_())\n","sub_path":"classDialogBox.py","file_name":"classDialogBox.py","file_ext":"py","file_size_in_byte":55892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"625162693","text":"from datetime import date\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404, render, reverse, redirect\nfrom django.utils.decorators import method_decorator\nfrom account.decorators import post_required\n\n\nfrom .forms import RatingsForm\nfrom .models import Practice\nfrom account.decorators import student_required\n\n\n@login_required\ndef next_practice_item(request):\n student_practice = Practice.objects.filter(\n card__deck__student=request.user.student).order_by('next_practice')\n\n practice = student_practice.filter(\n next_practice__lte=date.today())\n\n if len(practice) > 0:\n practice = practice[0]\n form = RatingsForm(initial={\"id\": practice.id})\n card = practice.card\n context = {\n 'practice': practice,\n 'card': card,\n 'form': form\n }\n return render(request, 'games/flashcards.html', context)\n\n else:\n context = {\n 'next_practice': student_practice.first().next_practice\n }\n return render(request, 'games/flashcards.html', context)\n\n\n@post_required\n@login_required\ndef process_rating(request):\n form = RatingsForm(request.POST)\n if form.is_valid():\n practice_item = get_object_or_404(Practice,\n pk=int(form.cleaned_data['id']))\n practice_item.set_next_practice(int(form.cleaned_data['rating']))\n practice_item.save()\n return redirect('memo:flashcards')\n\n\n@post_required\n@login_required\ndef skip_practice(request, practice_id, redirect):\n practice = Practice.objects.get(pk=int(practice_id))\n practice.delay()\n practice.save()\n return HttpResponseRedirect(reverse(redirect))\n\n\n@login_required\n@student_required\ndef hangman(request):\n return render(request, 'games/hangman.html')\n\n\n@login_required\n@student_required\ndef speed_typing(request):\n return render(request, 'games/speed_typing.html')\n","sub_path":"memorisation/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"554107857","text":"# Single function to take a list, turn it into a series\n# and add it to a dataframe as a new column\nimport pandas as pd\n\n\ndef list_func(df):\n # Get list\n prompt = (input(\"Enter the items for the new column, seperated by commas\"))\n prompt_list = prompt.split(\",\")\n col_name = (input(\"Enter the column header\"))\n items = []\n for i in range(len(prompt_list)):\n item = [prompt_list[i]]\n items.append(item)\n # Turn it into series\n data = pd.Series(items)\n # Add to dataframe as new column\n df[col_name] = data\n print(df)\n","sub_path":"list_to_column.py","file_name":"list_to_column.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"475257259","text":"\nfrom pydantic import BaseModel, Field, validator\n\nfrom src.db.Repository import Repository\n\n\nclass Todos(Repository):\n # async def index(self, add):\n # await add([('', \"\")])\n\n def collection(self):\n return 'todos'\n\n async def saveTodo(self, title: str, description: str):\n data = {\"title\": title,\n \"description\": description}\n\n return await self.save(data=data, collection_name=self.collection())\n\n async def getAll(self, title: str, start: int = 0, limit: int = 0):\n qurey = {}\n if title:\n qurey['title'] = {'$regex': f'.*{title}.*'}\n result = await self.find({\n '$query': qurey, # filter deleted face\n '$orderby': {\n 'updated_at': -1\n }}, self.collection())\n # result.skip(start).limit(limit)\n return result\n","sub_path":"src/servers/models/todo.py","file_name":"todo.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"331641856","text":"import sys,argparse\nimport os,glob\nimport numpy as np\nimport pandas as pd\nimport re,bisect\n\n# import matplotlib\n# matplotlib.use('Agg')\n# import matplotlib.pyplot as plt\n# matplotlib.rcParams['font.size']=16\n# import seaborn as sns\n# sns.set(font_scale=1.2)\n# sns.set_style(\"whitegrid\", {'axes.grid' : False})\n# sns.set_style(\"ticks\",{'ytick.color': 'k','axes.edgecolor': 'k'})\n# matplotlib.rcParams[\"font.sans-serif\"] = [\"Arial\"]\n# matplotlib.rcParams['mathtext.fontset'] = 'custom'\n# matplotlib.rcParams[\"mathtext.rm\"] = \"Arial\"\n\n \n\noutdir = 'f2_loop_genomic_feature'\nos.makedirs(outdir,exist_ok=True)\n\nhms=['K27ACDEL','K27ACEIF','K27ACTPR','K27ACVEC','K27ACWT','K4M3DEL3','K4M3DTPR','K4M3EIF','K4M3PCDH','K4M3WT']\nfor hm in hms:\n hm_df = pd.read_csv('data_loop_bedpe/{}.bedpe'.format(hm),sep='\\t')\n hm_df.index = hm_df.index+1 # index starts from 1\n for anchor_flag in ['anchor1','anchor2']:\n for genomic_feature in ['promoter','exon','intron','genebody']:\n # read the overlapped files\n anchor_file='overlapped/{}_{}_{}.bed'.format(hm,genomic_feature,anchor_flag)\n anchor_df = pd.read_csv(anchor_file,sep='\\t',index_col=4)\n anchor_df = anchor_df[['IfOverlap','Overlapped_genes']]\n col_names = ['{}_{}_IfOverlap'.format(anchor_flag,genomic_feature),'{}_{}_Overlapped_genes'.format(anchor_flag,genomic_feature)] \n anchor_df.columns = col_names\n hm_df = pd.concat([hm_df,anchor_df],axis=1)\n hm_df.to_csv(outdir+os.sep+'{}.csv'.format(hm))\n\n","sub_path":"f4_hichip_SICER_looping/f0_looping_genomic_distribution/py2_overlap_collection.py","file_name":"py2_overlap_collection.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"459028038","text":"from matplotlib import pyplot as plt\nimport numpy as np\nfrom sklearn.mixture import GaussianMixture\nimport pandas as pd\nimport seaborn as sb\nsb.set()\n\n# import dataset\ndata = pd.read_csv('TESS_planets.csv', skiprows=78)\nphysicals = ['pl_orbper', 'pl_orbsmax', 'pl_bmassj', 'pl_dens']\ncol_unit_dict = {\"pl_orbper\":\"Orbital Period [days]\",\n \"pl_orbsmax\":\"Orbit Semi-Major Axis [au]\",\n \"pl_bmassj\":\"Planet Mass [Jupiter mass]\",\n \"pl_dens\":\"Planet Density [g/cm**3]\"}\n\n# ask for column assign data to X variable\ncol = input('Pick a dataset from the following : '+str(physicals)+'\\n')\ncol = str(col)\nX = data[col].dropna()\nX = X.to_numpy().reshape(-1,1)\n\n# Learn the best-fit GaussianMixture models\n# Here we'll use scikit-learn's GaussianMixture model. The fit() method\n# uses an Expectation-Maximization approach to find the best\n# mixture of Gaussians for the data\n\n# fit models with 1-5 components\nN = np.arange(1, 6)\nmodels = [None for i in range(len(N))]\n\nfor i in range(len(N)):\n models[i] = GaussianMixture(N[i]).fit(X)\n\n# compute the AIC and the BIC\nAIC = [m.aic(X) for m in models]\nBIC = [m.bic(X) for m in models]\n\nlist = []\nmixn = input('enter your prefered number of gaussians (leave blank for minimization of BIC): ')\nupper = input('enter the upper limit for the fit (leave blank for max of data): ')\nif mixn == '':\n mixn = np.argmin(BIC)\nif upper == '':\n upper = np.max(X)\nlist.append(int(mixn))\nlist.append(float(upper))\nlist\n\n# limits and dists for plotting\ndef mixture_plot(mixn=np.argmin(BIC), upper=np.max(X)):\n lower = np.min(X)\n M_best = models[mixn]\n x = np.linspace(lower, upper, 5000)\n logprob = M_best.score_samples(x.reshape(-1, 1))\n responsibilities = M_best.predict_proba(x.reshape(-1, 1))\n pdf = np.exp(logprob)\n pdf_individual = responsibilities * pdf[:, np.newaxis]\n\n fig = plt.figure(figsize=(7,5), dpi=150)\n # plot 1: data + best-fit mixture\n ax = plt.subplot2grid((6,2), (0,0), rowspan=4, colspan=2)\n\n ax.hist(X, 30, density=True, histtype='stepfilled',color='xkcd:mauve', alpha=0.5)\n ax.plot(x, pdf, '-',color='xkcd:light pink')\n ax.plot(x, pdf_individual, '-.', color='xkcd:rose', linewidth=1.5)\n ax.text(0.04, 0.96, \"Best-fit Mixture\",\n ha='left', va='top', transform=ax.transAxes)\n ax.set_xlabel(col_unit_dict[col])\n ax.set_ylabel('$p(x)$')\n ax.set_xlim(lower,upper)\n\n # plot 2: AIC and BIC\n ax = plt.subplot2grid((6,2), (4,0), rowspan=2)\n ax.plot(N, AIC, '-k', label='AIC')\n ax.plot(N, BIC, '--k', label='BIC')\n ax.set_xlabel('n. components')\n ax.set_ylabel('information criterion')\n ax.legend(loc=2)\n\n # plot 3: class probability\n ax = plt.subplot2grid((6,2), (4,1), rowspan=2)\n p = responsibilities\n p = p.cumsum(1).T\n for i in range(0,len(p)):\n if i == 0:\n ax.fill_between(x, 0, p[0], color='xkcd:mauve', alpha=0.2*(i+1))\n else:\n im = i-1\n ax.fill_between(x, p[im], p[i], color='xkcd:mauve', alpha=0.2*(i+1))\n ax.set_xlabel('Variable Sample')\n ax.set_ylabel('Probability from \\ngiven gaussian')\n\n plt.tight_layout()\n plt.savefig('mixfit'+col+'.jpg', dpi=150)\n\nmixture_plot(mixn=list[0],upper=list[1])\n","sub_path":"Bayesian_Introduction_Lab/TESSmixes.py","file_name":"TESSmixes.py","file_ext":"py","file_size_in_byte":3213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"575501642","text":"import logging\nfrom random import uniform, randrange\nfrom time import sleep\nfrom argparse import ArgumentParser\n\nimport redis\nimport dill\nimport requests\nimport lxml.html\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\nr = redis.Redis(\n host='192.168.0.17',\n port=6379\n)\n\ns = requests.Session()\n\ndef scrape(url):\n baseurl = 'https://www.website.com'\n \"\"\" Dummy function that just waits a random amount of time \"\"\"\n logger.info(\"Performing task with baseurl=%s and url=%s\", baseurl, url)\n r = s.get(baseurl)\n dom = lxml.html.fromstring(r.text)\n good_links = set()\n for link in dom.xpath('//a/@href'): # select the url in href for all a tags(links)\n if 'http' not in link:\n if link[0] != '/':\n good_links.add(baseurl + '/' + link)\n else:\n good_links.add(baseurl + link)\n elif baseurl in link:\n good_links.add(link)\n return list(good_links)\n \n\ndef create_jobs():\n # Generate N tasks\n r.set('todo-https://www.website.com',0)\n\n\ndef worker():\n while True:\n key = None\n for key in r.scan_iter(match='todo*'):\n break\n\n if key == None:\n return\n print(key)\n r.delete(key)\n url_to_scrape = key.split(b'-')[1].decode('utf-8')\n r.set('doing-'+url_to_scrape,0)\n\n for url in scrape(url_to_scrape):\n if url == url_to_scrape:\n continue\n if not r.exists(\"todo-\"+url) and not r.exists(\"doing-\"+url) and not r.exists(\"done-\"+url):\n r.set('todo-'+url,0)\n r.delete('doing-'+url_to_scrape,0)\n r.set('done-'+url_to_scrape,0)\n print_results()\n\n\ndef print_results():\n print(\"\\nRESULTS\")\n lists = ['todo','doing','done']\n for l in lists:\n num = 0\n for key in r.scan_iter(match=l+'*'):\n num += 1\n print(\"{}: {}\".format(l,num))\n\n\nif __name__ == \"__main__\":\n parser = ArgumentParser(description='A simple task queue')\n parser.add_argument('--create',\n action='store_true',\n help='create jobs' )\n parser.add_argument('--worker',\n action='store_true',\n help='run as a worker' )\n parser.add_argument('--results',\n action='store_true',\n help='print results' )\n\n args = parser.parse_args()\n\n if args.create:\n create_jobs()\n elif args.worker:\n worker()\n elif args.results:\n print_results()\n else:\n parser.print_help()\n","sub_path":"web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":2522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"299404804","text":"GREEN = 1\nORANGE = 2\nRED = 3\n\nCOLOR_CHOICES = (\n (GREEN, 'green'),\n (ORANGE, 'orange'),\n (RED, 'red'),\n)\n\nMOTOR_1_0 = 1.0\nMOTOR_1_4 = 1.4\nMOTOR_1_6 = 1.6\nMOTOR_2_0 = 2.0\n\n\nMOTOR_CHOICES = (\n (MOTOR_1_0, 1.0),\n (MOTOR_1_4, 1.4),\n (MOTOR_1_6, 1.6),\n (MOTOR_2_0, 2.0),\n)\n\n\nVEICULO_CARRO = 'carro'\nVEICULO_MOTO = 'moto'\n\n\n\nVEICULO_CHOICES = (\n (VEICULO_CARRO, 'Carro'),\n (VEICULO_MOTO, 'Moto'),\n)\n","sub_path":"apps/veiculos/choices.py","file_name":"choices.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"10518067","text":"import re\nfrom col.utils.constants import ACTIVE, INACTIVE\nfrom col.repository.c_user_level_repository import UserLevelRepository\nfrom voluptuous import Invalid\nfrom voluptuous.validators import Url\n\n\ndef validate_name(name=None):\n if not re.match(\"^[A-Za-z0-9_-]*$\", name):\n raise Invalid(\"Can contain A-Z a-z 0-9 _ -\")\n if int(len(str(name))) not in range(3, 45, 1):\n raise Invalid(\"Should be between 3 to 45 char long\")\n return name\n\n\ndef string_val(string_val=None):\n if not re.match(\"^[A-Za-z_-]*$\", string_val):\n raise Invalid(\"Can contain A-Z a-z _ -\")\n return string_val\n\n\ndef alphanumreic_val(alphanumreic_val=None):\n if not re.match(\"^[A-Za-z0-9]*$\", alphanumreic_val):\n raise Invalid(\"Can contain A-Z a-z 0-9\")\n return alphanumreic_val\n\n\ndef string_code(string_val=None):\n if not re.match(\"^[A-Za-z_-]*$\", string_val):\n raise Invalid(\"Can contain A-Z a-z _ -\")\n return string_val\n\n\ndef validate_password(pwd=None):\n if not re.match(\"^[-A-Za-z0-9_!@#$%&*()]*$\", pwd):\n raise Invalid(\"Can contain A-Z a-z 0-9 _ - ! @ # $ % & * ( )\")\n if len(pwd) not in range(7, 30, 1):\n raise Invalid(\"Should be between 7 to 30 char long\")\n return pwd\n\n\ndef validate_email(email=None):\n if not re.match(r\"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)\", email):\n raise Invalid(\"Email address not valid\")\n return email\n\n\ndef validate_date(date=None):\n if not re.match(\"\\d\\d\\d\\d-\\d\\d-\\d\\d\", date):\n raise Invalid(\"Should be in format YYYY-MM-DD\")\n return date\n\n\ndef validate_url(url=None):\n if url == \"\":\n pass\n if Url(url):\n raise Invalid(\"Invalid URL\")\n return url\n\n\ndef validate_is_active(is_active=None):\n if is_active not in [ACTIVE, INACTIVE]:\n raise Invalid(\"Invalid value\")\n return is_active\n\n\ndef validate_user_type(user_type=None):\n if UserLevelRepository(user_type).get() is None:\n raise Invalid(\"Invalid user type\")\n return user_type\n","sub_path":"col/utils/validations.py","file_name":"validations.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"218533290","text":"import os\nimport time\nimport random\nimport datetime\nfrom termcolor import colored\nos.system(\"clear\")\npastCrypto = random.randint(1,100)\npastStock = random.randint(1,100)\nturn = 1\nownedCrypto = 0\nownedStock = 0\nmoney = random.randint(100,200)\nbankWithdraw = 100\nworkAmount = 0\nCryptoValue = random.randint(1,10)\nStockValue = random.randint(1,10)\ndiffSetting = \"Random\"\nday = 0\npower = 0\nfame = 0\nprint(\"Type in your name: \")\nname = input(\">\")\nos.system(\"clear\")\nprint(\"Thats a nice name\")\n\ndef bankASCII():\n\tprint(\"\t _._._ _._._\")\n\tprint(\" _| |_ _| |_\")\n\tprint(\" | ... |_._._._._._._._._._._| ... |\")\n\tprint(\" | ||| | o NATIONAL BANK o | ||| |\")\n\tprint(\" | --- | --- --- --- | --- |\")\n\tprint(\" ()) |[-|-]| [-|-] [-|-] [-|-] |[-|-]| ())\")\n\tprint(\" (())) | |---------------------| | (()))\")\n\tprint(\" (())())| --- | --- --- --- | --- |(())())\")\n\tprint(\" (()))()|[-|-]| ::: .---. ::: |[-|-]|(()))()\")\n\tprint(\" ()))(()| | |~|~| |_|_| |~|~| | |()))(()\")\n\tprint(\" || |_____|_|_|_|__|_|_|__|_|_|_|_____| ||\")\n\tprint(\" ~ ~^^ @@@@@@@@@@@@@@/=======\\@@@@@@@@@@@@@@ ^^~ ~\")\n\tprint(\" ^~^~ ~^~^\")\n\nwhile True:\n\ttime = datetime.datetime.now()\n\tday += 1\n\n\tnow = datetime.datetime.now()\n\tif diffSetting in ['1','Random','Easy','random','easy']:\t\n\t\tchance = random.randint(1,2)\n\t\tif chance == 1:\n\t\t\tCryptoValue += random.randint(1,100)\n\t\telse:\n\t\t\tCryptoValue -= random.randint(1,100)\n\t\t\tif CryptoValue < 1:\n\t\t\t\tCryptoValue = CryptoValue * -1\n\t\t\telse:\n\t\t\t\tos.system(\"clear\")\n\t\tchance2 = random.randint(1,2)\n\t\tif chance == 1:\n\t\t\tStockValue += random.randint(1,100)\n\t\telse:\n\t\t\tStockValue -= random.randint(1,100)\n\t\t\tif StockValue < 1:\n\t\t\t\tStockValue = StockValue*-1\n\t\t\telse:\n\t\t\t\tos.system(\"clear\")\n\n\n\tos.system(\"clear\")\n\n\tif money < 5:\n\t\twinner = 0\n\t\tbreak\n\t\t\n\t\n\n\tprint(\"INVEST \\n You have $\" + str(money))\n\tprint(\"Options \\n 1. CryptoCurrency \\n 2. Stocks \\n 3. Bank \\n 4. Your job \\n 5. more\")\n\tif pastCrypto > CryptoValue:\n\t\tprint(colored(\"The CryptoCurrency price has gone down\", \"red\"))\n\telse:\n\t\tprint(colored(\"The CryptoCurrency price has gone up\", \"green\"))\n\t\n\tif pastStock > StockValue:\n\t\tprint(colored(\"The stock price has gone down\", \"red\"))\n\telse:\n\t\tprint(colored(\"The stock price has gone up\", \"green\"))\n\t\n\t\n\t\n\t\n\toptionBuy = input(\">\")\n\tif optionBuy in ['CryptoCurrency','cryptoCurrency','cryptocurrency','1','Crypto','crypto']:\n\t\tprint(\"You cryptocurrency\")\n\t\tprint(\"The current value is \" + str(CryptoValue))\n\t\tprint(\"Buy or sell? \\n Type [B/S]\")\n\t\tbuy = input(\">\")\n\t\tif buy in ['Buy','buy','B','b']:\n\t\t\tos.system(\"clear\")\n\t\t\tif money < CryptoValue :\n\t\t\t\tprint(\"You cannot afford a Digital Coin.\")\n\t\t\telse:\n\t\t\t\tprint(\"You bought a coin!\")\n\t\t\t\tmoney -= CryptoValue\n\t\t\t\tprint(\"Money you have: \" + str(money))\n\t\t\t\townedCrypto += 1\n\t\t\t\tinput(\">\")\n\t\t\t\tos.system(\"clear\")\n\t\telif buy in ['Sell','sell','S','s']:\n\t\t\tprint(\"You decided to sell\")\n\t\t\tif ownedCrypto < 1:\n\t\t\t\tprint(\"You have none to sell.\")\n\t\t\telse:\n\t\t\t\tprint(\"Are you sure you want to sell? \\n Type [Y/N]\")\n\t\t\t\tcryptoSell = input(\">\")\n\t\t\t\tif cryptoSell in ['Yes','yes','Y','y']:\n\t\t\t\t\tprint(\"You chose yes\")\n\t\t\t\t\townedCrypto -= 1\n\t\t\t\t\tmoney += CryptoValue\n\t\t\t\t\tprint(\"You have $\" + str(money))\n\t\t\t\telse:\n\t\t\t\t\tprint(\"You chose no\")\n\t\telse:\n\t\t\tprint(\"You went to sleep. [CHECK SPELLING]\")\n\t\t\t\n\t\n\telif optionBuy in ['2','Stocks','stocks','stcks']:\n\t\tprint(\"You decided stock\")\n\t\tprint(\"The current value is \" + str(StockValue))\n\t\tprint(\"Do you want to buy or sell? \\n Type [B/S]\")\n\t\tbuy = input(\">\")\n\t\tif buy in ['Buy','B','b','buy']:\n\t\t\tprint(\"You decided to buy stock\")\n\t\t\tif money < StockValue :\n\t\t\t\tprint(\"You cannot afford that\")\n\t\t\telse:\n\t\t\t\tprint(\"You decided to buy\")\n\t\t\t\tmoney -= StockValue\n\t\t\t\tprint(\"Your money: \" + str(StockValue))\n\t\t\t\townedStock += 1\n\t\telif buy in ['sell','Sell','s','S']:\n\t\t\tprint(\"You decided to sell your stock\")\n\t\t\tif ownedStock < 1:\n\t\t\t\tprint(\"You have no stock to sell\")\n\t\t\telse:\n\t\t\t\tprint(\"You have \" + ownedStock + \" to sell\")\n\t\t\t\tprint(\"The stock value is \" + StockValue)\n\t\t\t\tprint(\"Are you sure you want to sell? \\n Type [Y/N]\")\n\t\t\t\tstockSell = input(\">\")\n\t\t\t\tif stockSell in ['Y','y','Yes','yes']:\n\t\t\t\t\townedStock -= 1\n\t\t\t\t\tprint(\"You sold your stock\")\n\t\t\t\telse:\n\t\t\t\t\tprint(\"You decided to not sell your stock\")\n\t\telse:\n\t\t\tprint(\"You decided to not buy [Check spelling]\")\n\t\n\telif optionBuy in ['3','Bank','BAnk','bank']:\n\t\tos.system(\"clear\")\n\t\tbankASCII()\n\t\tprint(\"The bank teller smiles at you\")\n\t\tprint(\"The bank teller says: Hello \" + name)\n\t\tprint(\"Would you like to withdraw or deposite? \\n 1. Withdraw \\n 2, Deposit \\n Type in [W\\D]\")\n\t\tbankChoice = input(\">\")\n\t\tif bankChoice in ['W','Withdraw','Withdraw']:\n\t\t\t\tprint(\"You have decided to withdraw money\")\n\t\t\t\tprint(\"You can withdraw up to: \" + str(bankWithdraw))\n\t\t\t\tprint(\"Type in amount you want to withdraw\")\n\t\t\t\twithdraw = input(\">\")\n\t\t\t\tif int(withdraw) > int(bankWithdraw) :\n\t\t\t\t\tprint(\"You cannot withdraw that much\")\n\t\t\t\telse:\n\t\t\t\t\tprint(\"You withdrawed \" + str(withdraw) + \" dollars\")\n\t\t\t\t\tmoney += int(withdraw)\n\t\telif bankChoice in ['Deposite','deposite','2','D','d']:\n\t\t\tprint(\"How much money do you want to put in?\")\n\t\t\tdeposite = input(\">\")\n\t\t\tmoneyAdd = deposite\n\t\t\tif int(deposite) > int(money) :\n\t\t\t\tprint(\"You cannot put that much money in\")\n\t\t\telse:\n\t\t\t\tprint(\"You put in \" + deposite + \" dollars\")\n\t\t\t\tbankWithdraw += int(deposite)\n\t\t\t\tprint(\"You have put $\" + deposite + \" in the bank\")\n\t\t\t\tmoney -= int(deposite)\n\t\telse:\n\t\t\tprint(\"The bank teller looks at you confused\")\n\telif optionBuy in ['4', 'Job','Work','work','Your Job','your Job', 'your job']:\n\t\tworkTime = 10\n\t\twhile int(workTime) > 9:\t\n\t\t\tprint(\"You decided to go to your job.\")\n\t\t\tprint(\"Choose how much to time work:\")\n\t\t\tworkTime = input(\">\")\n\t\t\tif workTime in ['1','2','3','4','5','6','7','8']:\n\t\t\t\tmoneyEarned = int(workTime)*9\n\t\t\t\tmoney += moneyEarned\n\t\t\t\tprint(\"You earned \" + str(moneyEarned))\n\t\t\telse:\n\t\t\t\tprint(\"Please enter a integer or a number less than 9\")\t\n\n\n\n\telif optionBuy in ['More','more','5']:\n\t\tprint(\"welcome to advanced options:\")\n\t\tprint(\"1. Buy food \\n 2. Check time\")\n\t\tadv = input(\">\")\n\t\tif adv in ['1','Buy Food','buy Food','buy food','food','food','buy']:\n\t\t\tos.system(\"clear\")\n\t\t\tprint(\"You decided to buy some food\")\n\t\t\tprint(\"Options: \\n 1. Chips \\n 2. Noodles \\3. Water \\4. Milk\")\n\t\t\tfoodBuy = input(\">\")\n\t\t\tif foodBuy in ['1','Chips','chips']:\n\t\t\t\tprint(\"You decided to buy chips\")\n\t\t\t\tif money < 0.15 :\n\t\t\t\t\tprint(\"You cannot afford that\")\n\t\t\t\telse:\n\t\t\t\t\tprint(\"You bought Chips!\")\n\t\t\t\t\tmoney -= 0.15\n\t\t\t\t\tprint(\"You have $\" + str(money))\n\t\t\n\t\telse:\n\t\t\tprint(\"Current time:\")\n\t\t\tprint(str(time))\n\t\t\tprint(\"Day \" + str(day))\n\t\n\n\n\n\telse:\n\t\tprint(\"Check your spelling\")\n\tinput(\"|Press enter to move on| \\n >\")\n\n\n\tpastCrypto = CryptoValue\n\tpastStock = StockValue\n\tturn += 1\n\n\tif workAmount > 3 and turn > 29 :\n\t\tprint(\"You got paid!\")\n\t\tworkAmount = 1\n\t\tturn = 0\n\telse:\n\t\tos.system(\"clear\")\n\n\tfame = round(money/10 , 2)\n\tpower = round(fame/2)\n\n\nif winner == 0:\n\tprint(\"GAME OVER\")\n","sub_path":"Versions/Game/Version1.1/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":7108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"249799966","text":"import webbrowser\r\n\r\n\r\n# Movie Class that supports required functionality\r\nclass Movie(object):\r\n # This is the Constructor that initializes the object in memory\r\n def __init__(self,\r\n movie_title,\r\n story_line,\r\n poster_image_url,\r\n trailer_youtube_id):\r\n # Instace Variables\r\n self.title = movie_title\r\n self.story_line = story_line\r\n self.poster_image_url = poster_image_url\r\n self.trailer_youtube_url = trailer_youtube_id\r\n\r\n def show_trailer(self):\r\n # Function to open a trailer\r\n webbrowser.open(self.trailer_youtube_id)\r\n","sub_path":"media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"535087469","text":"import pandas as pd\nimport numpy as np\nimport logging\nfrom datetime import datetime\nfrom time import strftime\nimport re\n\n\n# heure = datetime.now()\n# heure_vrai = heure.strftime(\"%d-%m-%Y %H:%M\")\n# logging.basicConfig(filename='app.log', filemode='w',format='%(levelname)s:%(message)s', level=logging.DEBUG)\n# logging.info(\"################Mirna Marie-Joseph, Théo Gauvrit, Kévin Merchadou################\\n################DPN3000 1.0################\\n################\"f'{heure_vrai}################')\n# logging.warning('Lancement analyse')\n\n\nclass Echantillon:\n \"\"\" Parameters used to analyze one fetal sample\n\n Attributes:\n date : date sample\n liste_lignes (list) : extracted from txt file, lines corresponding to fetus\n sexe (str) : fetus sex\n concordance (str) : DNAs match between mother and fetus\n seuil_nbre_marqueurs (int) : marker number which have to be contaminated to declare sample as contaminated\n seuil_taux_conta (int) : one marker is contaminated if his contamination percentage is higher than the value\n seuil_hauteur (int) : spike height to check\n conclusion (int) : contaminated sample (1) or not (0)\n \"\"\"\n\n def __init__(self, date, name, liste_lignes, sexe=None, concordance_mere_foet=None, concordance_pere_foet=None,\n seuil_nbre_marqueurs=2, seuil_taux_conta=5, seuil_hauteur=1 / 3, conclusion=None):\n \"\"\" The constructor for Echantillon class\n\n Parameters:\n date : date sample\n liste_lignes (list) : extracted from txt file, lines corresponding to fetus\n sexe (str) : fetus sex\n concordance (str) : DNAs match between mother and fetus\n seuil_nbre_marqueurs (int) : marker number which have to be contaminated to declare sample as contaminated\n seuil_taux_conta (int) : one marker is contaminated if his contamination percentage is higher than the value\n seuil_hauteur (int) : spike height to check\n conclusion (int) : contaminated sample (1) or not (0)\n\n \"\"\"\n self.date = date\n self.name = name\n self.liste_lignes = liste_lignes\n self.seuil_nbre_marqueurs = seuil_nbre_marqueurs\n self.seuil_taux_conta = seuil_taux_conta\n self.conclusion = conclusion\n self.seuil_hauteur = seuil_hauteur\n self.sexe = sexe\n self.concordance_mere_foet = concordance_mere_foet\n self.concordance_pere_foet = concordance_pere_foet\n\n def get_date(self):\n return self.date\n\n def get_name(self):\n return self.name\n\n def get_seuil_nbre_marqueurs(self):\n \"\"\" Return seuil_nbre_marqueurs\n \"\"\"\n return self.seuil_nbre_marqueurs\n\n def get_seuil_taux_conta(self):\n \"\"\" Return seuil_taux_con\n \"\"\"\n return self.seuil_taux_conta\n\n def get_seuil_hauteur(self):\n \"\"\" Return seuil_hauteur\n \"\"\"\n return self.seuil_hauteur\n\n def get_conclusion(self):\n \"\"\" Return conclusion\n \"\"\"\n return self.conclusion\n\n def get_sexe(self):\n \"\"\" Return sex\n \"\"\"\n return self.sexe\n\n def get_concordance_mere_foet(self):\n \"\"\" Return concordance\n \"\"\"\n return self.concordance_mere_foet\n\n def get_concordance_pere_foet(self):\n \"\"\" Return concordance\n \"\"\"\n return self.concordance_pere_foet\n\n def set_seuil_nbre_marqueurs(self, nb):\n \"\"\" Set seuil_nbre_marqueurs\n \"\"\"\n self.seuil_nbre_marqueurs = nb\n\n def set_seuil_taux_conta(self, taux):\n \"\"\" Set seuil_taux_conta\n \"\"\"\n self.seuil_taux_conta = taux\n\n def set_seuil_hauteur(self, hauteur):\n \"\"\" Set seuil_hauteur\n \"\"\"\n self.seuil_hauteur = hauteur\n\n def set_sexe(self, sexe):\n \"\"\" Set sex\n \"\"\"\n self.sexe = sexe\n\n def set_concordance_mere_foet(self, concordance_mere_foet):\n \"\"\" Set concordance\n \"\"\"\n self.concordance_mere_foet = concordance_mere_foet\n\n def set_concordance_pere_foet(self, concordance_pere_foet):\n \"\"\" Set concordance\n \"\"\"\n self.concordance_pere_foet = concordance_pere_foet\n\n def set_conclusion(self, conclusion):\n \"\"\" Set conclusion\n \"\"\"\n self.conclusion = conclusion\n\n def analyse_donnees(self, mere, foetus, pere, log):\n \"\"\" Analyze data\n For one couple lignes mother/fetus, informative character and conclusion is set\n\n Parameters :\n mere (list) : lines extracted from txt file corresponding to mother\n foetus (list) : lines extracted from txt file corresponding to fetus\n\n Return two dataframes :\n - first one containing information about Name, Conclusion and Details for each marker\n - second one containing global information about sample (Number of informative markers, contaminated markers and free contaminated markers )\n\n \"\"\"\n concordance_mf = 0\n concordance_pf = None\n if len(pere) != 0:\n concordance_pf = 0\n log = log + \"Père détecté.................................\\n\"\n log = log + \"\\n\\nVérification concordance des ADNs entre père et foetus..............................\\n\"\n for Alleles in range(len(foetus)):\n for Allele_Foe in range(3):\n if foetus[Alleles].allele[Allele_Foe] in pere[Alleles].allele:\n if foetus[Alleles].allele[Allele_Foe] != 0.0:\n pere[Alleles].concordance_pere_foetus = \"OUI\"\n concordance_pf = concordance_pf + 1\n log = log + \"Concordance pour marqueur \" + str(\n foetus[Alleles].marqueur) + \" OK..................\\n\"\n break\n else:\n pere[Alleles].concordance_pere_foetus = \"NON\"\n log = log + \"Concordance pour marqueur \" + foetus[\n Alleles].marqueur + \" PAS OK..............\\n\"\n break\n log = log + \"\\n\\nVérification concordance des ADNs entre mère et foetus..............................\\n\"\n for Alleles in range(len(foetus)):\n for Allele_Foe in range(3):\n if foetus[Alleles].allele[Allele_Foe] in mere[Alleles].allele:\n if foetus[Alleles].allele[Allele_Foe] != 0.0:\n foetus[Alleles].concordance_mere_foetus = \"OUI\"\n concordance_mf = concordance_mf + 1\n log = log + \"Concordance pour marqueur \" + str(\n foetus[Alleles].marqueur) + \" OK..................\\n\"\n break\n else:\n foetus[Alleles].concordance_mere_foetus = \"NON\"\n log = log + \"Concordance pour marqueur \" + foetus[Alleles].marqueur + \" PAS OK..............\\n\"\n break\n log = log + \"Vérification concordance des ADns terminée..................................\\n\\n\\n\"\n if concordance_mf != len(foetus):\n resultats, conclusion = self.resultat(concordance_mf, concordance_pf, foetus, mere, pere)\n log = log + \"Concordance des ADNs PAS OK....................\\n\"\n log = log + \"Erreur dans l'échantillon...................\\n\"\n log = log + \"Revérifier s'il vous plaît.............\\n\"\n return resultats, conclusion, log\n else:\n log = log + \"Traitement des 15 autres marqueurs..............................\\n\"\n for nbre_lignes in range(1, len(mere)):\n log = log + \"Traitement du marqueur \" + str(foetus[nbre_lignes].marqueur) + \"..........\\n\"\n pic = foetus[nbre_lignes].foetus_pics()\n log = log + \"Calcul du nombre d'allèles pour le foetus......................\\n\"\n log = log + \"Nombre d'allèles pour le foetus : \" + str(pic) + \".........\\n\"\n log = log + \"Vérification de l'homozygotie de la mère......................\\n\"\n mere[nbre_lignes].homozygotie()\n log = log + \"Mère homozygote : \" + str(mere[nbre_lignes].homozygote) + \"...............\\n\"\n log = log + \"Vérification mère et foetus mêmes allèles......................\\n\"\n foetus[nbre_lignes].allele_semblable(mere[nbre_lignes])\n log = log + \"Code de retour vérification allèles semblables: \" + str(\n foetus[nbre_lignes].informatif) + \"...............\\n\"\n log = log + \"Initialisation du taux de contamination pour calcul à venir...............\\n\"\n foetus[nbre_lignes].taux = 0.0\n log = log + \"Taux initialisé.................................\\n\"\n log = log + \"Si code informatif de retour allèles semblables différent de 2, vérification écho.............\\n\"\n log = log + \"Si écho, affection code informatif 3...............\\n\"\n if foetus[nbre_lignes].informatif != 2:\n log = log + \"Vérification si écho......................\\n\"\n mere[nbre_lignes].echo(foetus[nbre_lignes])\n log = log + \"Code retour vérification écho : \" + str(\n foetus[nbre_lignes].informatif) + \"...............\\n\"\n log = log + \"Début chaîne de traitement...........................\\n\"\n if pic == 3:\n log = log + \"Trois allèles détectés......................\\n\"\n foetus[nbre_lignes].contamination_heterozygote(mere[nbre_lignes])\n log = log + \"Marqueur informatif, affectation du code contamination 1..............\\n\"\n foetus[nbre_lignes].informatif = 1\n log = log + \"Calcul taux de contamination du marqueur..........\\n\"\n foetus[nbre_lignes].contamination = 2\n log = log + \"Calcul terminé....................\\n\"\n elif mere[nbre_lignes].homozygote:\n log = log + \"Mère homozygote.......................\\n\"\n log = log + \"Marqueur non informatif, affectation du code informatif 0............\\n\"\n foetus[nbre_lignes].informatif = 0\n elif pic == 2:\n log = log + \"Deux allèles détectés..............\\n\"\n if foetus[nbre_lignes].informatif == 2:\n log = log + \"Si mêmes allèles, vérification homozygote contaminé...............\\n\"\n foetus[nbre_lignes].verif_homozygote_contamine(self)\n if foetus[nbre_lignes].contamination == 1:\n log = log + \"Homozygote contaminé identifié.....................\\n\"\n log = log + \"Calcul du taux de contamination....................\\n\"\n foetus[nbre_lignes].homozygote_contamine(self)\n log = log + \"Calcul du taux de contamination effectué...........\\n\"\n else:\n if foetus[nbre_lignes].informatif != 3:\n log = log + \"Code calcul écho différent de 3..................\\n\"\n log = log + \"Marqueur informatif, affectation du code informatif 1.............\\n\"\n foetus[nbre_lignes].informatif = 1\n log = log + \"Marqueur non contaminé, affectation du code contamination 0................\\n\"\n foetus[nbre_lignes].contamination = 0\n else:\n log = log + \"Un seul allèle détecté............\\n\"\n if foetus[nbre_lignes].informatif != 3:\n log = log + \"Code informatif différent de 3...........\\n\"\n log = log + \"Marqueur informatif, affectation du code informatif 1.............\\n\"\n foetus[nbre_lignes].informatif = 1\n log = log + \"Marqueur non contaminé, affectation du code contamination 0................\\n\"\n foetus[nbre_lignes].contamination = 0\n log = log + \"\\n\\n\"\n log = log + \"Calcul échantillon contaminé ou non......\\n\"\n log = log + \"Marqueur contaminé si >\" + str(self.seuil_taux_conta) + \".......\\n\"\n log = log + \"Echantillon contaminé si plus de \" + str(\n self.seuil_nbre_marqueurs) + \"marqueurs contaminés...\\n\"\n self.conclusion_echantillon(foetus)\n log = log + \"Calcul échantillon terminé.....\\n\"\n log = log + \"Fin de traitement...........\\n\"\n resultats, conclusion = self.resultat(concordance_mf, concordance_pf, foetus, mere, pere)\n return resultats, conclusion, log\n\n def resultat(self, concordance_mf, concordance_pf, liste_F, liste_M, liste_P):\n \"\"\" Set informative character and conclusion for each marker using code tables\n Code tables are :\n\n Informative code :\n 0 : Homozygous mother\n 1 : Informative marker\n 2 : Same alleles between mother and fetus\n 3 : Stutter\n\n Contamination code :\n 0 : No contamination\n 1 : Homozygous marker contaminated\n 2 : Heterozygous marker contaminated\n\n Samle conclusion code :\n 0 : not contaminated\n 1 : contaminated\n\n Parameters :\n - concordance (int) : DNAs matching markers between mother and fetus\n - list_F (list) : contains fetus lines from txt file\n\n Return two dataframes :\n - first one containing information about Name, Conclusion and Details for each marker\n - second one containing global information about sample (Number of informative markers, contaminated markers and free contaminated markers)\n\n \"\"\"\n resultat = {\"Marqueur\": [], \"Conclusion\": [], \"Concordance Mere/Foetus\": [], \"Détails M/F\": [],\n \"Concordance Pere/Foetus\": [], \"Détails P/F\": []}\n marqueurs_conta = 0\n marqueurs_non_conta = 0\n somme_conta = 0\n if liste_F[0].allele[1] == 0.0:\n self.set_sexe(\"F\")\n else:\n self.set_sexe(\"M\")\n if concordance_mf != 16 and concordance_pf != 16 and concordance_pf != None:\n self.set_concordance_mere_foet(\"NON\")\n self.set_concordance_pere_foet(\"NON\")\n del resultat[\"Conclusion\"]\n for nbres in range(1, len(liste_F)):\n resultat[\"Marqueur\"].append(str(liste_F[nbres].marqueur))\n resultat[\"Concordance Mere/Foetus\"].append(liste_F[nbres].concordance_mere_foetus)\n resultat[\"Concordance Pere/Foetus\"].append(liste_P[nbres].concordance_pere_foetus)\n if liste_F[nbres].concordance_mere_foetus == \"NON\" and liste_P[nbres].concordance_pere_foetus == \"NON\":\n resultat[\"Détails M/F\"].append(\n \"M : \" + str(liste_M[nbres].normalisation(liste_M[nbres].allele)) + \" F: \" + str(\n liste_F[nbres].normalisation(liste_F[nbres].allele)))\n resultat[\"Détails P/F\"].append(\n \"P : \" + str(liste_P[nbres].normalisation(liste_P[nbres].allele)) + \" F : \" + str(\n liste_F[nbres].normalisation(liste_F[nbres].allele)))\n elif liste_F[nbres].concordance_mere_foetus == \"NON\":\n resultat[\"Détails M/F\"].append(\n \"M: \" + str(liste_M[nbres].normalisation(liste_M[nbres].allele)) + \" F : \" + str(\n liste_F[nbres].normalisation(liste_F[nbres].allele)))\n resultat[\"Détails P/F\"].append(\"\")\n elif liste_P[nbres].concordance_pere_foetus == \"NON\":\n resultat[\"Détails P/F\"].append(\n \"P: \" + str(liste_P[nbres].normalisation(liste_P[nbres].allele)) + \" F: \" + str(\n liste_F[nbres].normalisation(liste_F[nbres].allele)))\n resultat[\"Détails M/F\"].append(\"\")\n else:\n resultat[\"Détails M/F\"].append(\"\")\n resultat[\"Détails P/F\"].append(\"\")\n conclusion = pd.DataFrame({\"1\": [\"Non calculé\", \"Non calculé\", \"Non calculé\", self.get_date()]},\n index=[\"Nombre de marqueurs informatifs non contaminés\",\n \"Nombre de marqueurs informatifs contaminés\",\n \"Moyenne du pourcentage de contamination\", \"Date\"])\n resultats = pd.DataFrame(resultat, columns=[\"Marqueur\", \"Concordance Mere/Foetus\", \"Détails M/F\",\n \"Concordance Pere/Foetus\", \"Détails P/F\"])\n return resultats, conclusion\n elif concordance_mf != len(liste_F) and concordance_pf == len(liste_F) or concordance_mf != len(\n liste_F) and concordance_pf == None:\n self.set_concordance_mere_foet(\"NON\")\n self.set_concordance_pere_foet(\"OUI\")\n if concordance_pf == None:\n self.set_concordance_pere_foet(\"ABS\")\n del resultat[\"Conclusion\"]\n del resultat[\"Concordance Pere/Foetus\"]\n del resultat[\"Détails P/F\"]\n for nbres in range(1, len(liste_F)):\n resultat[\"Marqueur\"].append(str(liste_F[nbres].marqueur))\n resultat[\"Concordance Mere/Foetus\"].append(liste_F[nbres].concordance_mere_foetus)\n if liste_F[nbres].concordance_mere_foetus == \"NON\":\n resultat[\"Détails M/F\"].append(\n \"M: \" + str(liste_M[nbres].normalisation(liste_M[nbres].allele)) + \" F: \" + str(\n liste_F[nbres].normalisation(liste_F[nbres].allele)))\n else:\n resultat[\"Détails M/F\"].append(\"\")\n conclusion = pd.DataFrame({\"1\": [\"Non calculé\", \"Non calculé\", \"Non calculé\", self.get_date()]},\n index=[\"Nombre de marqueurs informatifs non contaminés\",\n \"Nombre de marqueurs informatifs contaminés\",\n \"Moyenne du pourcentage de contamination\", \"Date\"])\n resultats = pd.DataFrame(resultat, columns=[\"Marqueur\", \"Concordance Mere/Foetus\", \"Détails M/F\"])\n return resultats, conclusion\n elif concordance_mf == len(liste_F) and concordance_pf == len(liste_F) or concordance_mf == len(\n liste_F) and concordance_pf == None:\n self.set_concordance_mere_foet(\"OUI\")\n self.set_concordance_pere_foet(\"OUI\")\n if concordance_pf == None:\n self.set_concordance_pere_foet(\"ABS\")\n del resultat[\"Concordance Mere/Foetus\"]\n del resultat[\"Concordance Pere/Foetus\"]\n del resultat[\"Détails P/F\"]\n for nbres in range(1, len(liste_F)):\n resultat[\"Marqueur\"].append(str(liste_F[nbres].marqueur))\n if liste_F[nbres].informatif == 0:\n resultat[\"Conclusion\"].append(\"Non informatif\")\n resultat[\"Détails M/F\"].append(\"Mère homozygote\")\n elif liste_F[nbres].informatif == 1:\n if liste_F[nbres].contamination == 0:\n marqueurs_non_conta += 1\n resultat[\"Conclusion\"].append(\"Non contaminé\")\n resultat[\"Détails M/F\"].append(\"\")\n elif liste_F[nbres].contamination == 1:\n marqueurs_conta += 1\n somme_conta = somme_conta + liste_F[nbres].taux\n resultat[\"Conclusion\"].append(\"Contaminé\")\n resultat[\"Détails M/F\"].append(\"Taux contamination : \" + str(liste_F[nbres].taux) + \"%\")\n else:\n marqueurs_conta += 1\n somme_conta = somme_conta + liste_F[nbres].taux\n resultat[\"Conclusion\"].append(\"Contaminé\")\n resultat[\"Détails M/F\"].append(\"Taux contamination : \" + str(liste_F[nbres].taux) + \"%\")\n elif liste_F[nbres].informatif == 2:\n resultat[\"Conclusion\"].append(\"Non informatif\")\n resultat[\"Détails M/F\"].append(\"Allèles semblables\")\n else:\n resultat[\"Conclusion\"].append(\"Non informatif\")\n resultat[\"Détails M/F\"].append(\"Echo\")\n resultats = pd.DataFrame(resultat, columns=[\"Marqueur\", \"Conclusion\", \"Détails M/F\"])\n try:\n moyenne_conta = somme_conta / marqueurs_conta\n except ZeroDivisionError:\n moyenne_conta = 0\n conclusion = pd.DataFrame(\n {\"1\": [int(marqueurs_non_conta), int(marqueurs_conta), round(moyenne_conta, 2), self.get_date()]},\n index=[\"Nombre de marqueurs informatifs non contaminés\", \"Nombre de marqueurs informatifs contaminés\",\n \"Moyenne du pourcentage de contamination\", \"Date\"])\n return resultats, conclusion\n elif concordance_mf == len(liste_F) and concordance_pf != len(liste_F):\n self.set_concordance_mere_foet(\"OUI\")\n self.set_concordance_pere_foet(\"NON\")\n del resultat[\"Concordance Mere/Foetus\"]\n for nbres in range(1, len(liste_F)):\n resultat[\"Concordance Pere/Foetus\"].append(liste_P[nbres].concordance_pere_foetus)\n if liste_P[nbres].concordance_pere_foetus == \"NON\":\n resultat[\"Détails P/F\"].append(\n \"P: \" + str(liste_P[nbres].normalisation(liste_P[nbres].allele)) + \" F: \" + str(liste_P[nbres].normalisation(liste_P[nbres].allele)))\n else:\n resultat[\"Détails P/F\"].append(\"\")\n for nbres in range(1, len(liste_F)):\n resultat[\"Marqueur\"].append(str(liste_F[nbres].marqueur))\n if liste_F[nbres].informatif == 0:\n resultat[\"Conclusion\"].append(\"Non informatif\")\n resultat[\"Détails M/F\"].append(\"Mère homozygote\")\n elif liste_F[nbres].informatif == 1:\n if liste_F[nbres].contamination == 0:\n marqueurs_non_conta += 1\n resultat[\"Conclusion\"].append(\"Non contaminé\")\n resultat[\"Détails M/F\"].append(\"\")\n elif liste_F[nbres].contamination == 1:\n marqueurs_conta += 1\n somme_conta = somme_conta + liste_F[nbres].taux\n resultat[\"Conclusion\"].append(\"Contaminé\")\n resultat[\"Détails M/F\"].append(\"Taux contamination : \" + str(liste_F[nbres].taux) + \"%\")\n else:\n marqueurs_conta += 1\n somme_conta = somme_conta + liste_F[nbres].taux\n resultat[\"Conclusion\"].append(\"Contaminé\")\n resultat[\"Détails M/F\"].append(\"Taux contamination : \" + str(liste_F[nbres].taux) + \"%\")\n elif liste_F[nbres].informatif == 2:\n resultat[\"Conclusion\"].append(\"Non informatif\")\n resultat[\"Détails M/F\"].append(\"Allèles semblables\")\n else:\n resultat[\"Conclusion\"].append(\"Non informatif\")\n resultat[\"Détails M/F\"].append(\"Echo\")\n resultats = pd.DataFrame(resultat,\n columns=[\"Marqueur\", \"Conclusion\", \"Détails M/F\", \"Concordance Pere/Foetus\",\n \"Détails P/F\"])\n try:\n moyenne_conta = somme_conta / marqueurs_conta\n except ZeroDivisionError:\n moyenne_conta = 0\n conclusion = pd.DataFrame(\n {\"1\": [int(marqueurs_non_conta), int(marqueurs_conta), round(moyenne_conta, 2), self.get_date()]},\n index=[\"Nombre de marqueurs informatifs non contaminés\", \"Nombre de marqueurs informatifs contaminés\",\n \"Moyenne du pourcentage de contamination\", \"Date\"])\n return resultats, conclusion\n\n def conclusion_echantillon(self, liste_foetus):\n \"\"\" This concludes about sample contamination or not.\n\n Compare number of contaminated markers (more or equal to 5 %) to seuil_taux_conta.\n If the number is higher than seuil_taux_conta -> sample is contaminated\n Else -> sample is not contaminated\n\n Parameters :\n liste_foetus (list) : contains fetus lines from txt file\n \"\"\"\n compteur = 0\n for lignes in range(1, len(liste_foetus)):\n if liste_foetus[lignes].contamination != 0 and liste_foetus[lignes].taux > self.seuil_taux_conta:\n compteur = compteur + 1\n if compteur > self.seuil_nbre_marqueurs:\n self.conclusion = 1\n else:\n self.conclusion = 0\n\nclass Patient:\n \"\"\" Common informations between mother and fetus\n\n Attributes :\n marqueur (list) : markers list\n allele (list) : alleles list\n hauteur (list) : alleles height list\n informatif (int) : informatif character of marker\n \"\"\"\n\n def __init__(self, marqueur, allele, hauteur, informatif):\n \"\"\" The constructor for Patient class\n\n Parameters :\n marqueur (list) : markers list\n allele (list) : alleles list\n hauteur (list) : alleles height list\n informatif (int) : informatif character of marker\n \"\"\"\n\n self.marqueur = marqueur\n self.allele = allele\n self.hauteur = hauteur\n self.informatif = informatif\n\n def allele_semblable(self, mere):\n \"\"\" Check for each marker if fetus and mother have the same alleles list.\n Because homozygous marker from mother is always non-informative character, we only check similarity for heterozygous marker.\n\n Parameters :\n - mere (list) : mere class object\n\n If Similarite is equal to two, informative code is set to 2.\n \"\"\"\n Similarite = 0\n for Allele in range(3):\n if self.allele[Allele] in mere.allele and self.allele[Allele] != 0.0:\n Similarite = Similarite + 1\n if Similarite == 2:\n self.informatif = 2\n\n def echo(self, foetus):\n \"\"\" Allow to detect stutter.\n Stutter : Fetus alleles are 12 and 8, Mother alleles are 11 and 10. 11 is a stutter because is n-1 (12-1) from fetus alleles\n\n Parameters :\n - foetus (list) : list of fetus object corresponding to each line of the fetus extracted from the txt file\n\n If a stutter is detected, fetus informative code is set to 3.\n\n \"\"\"\n Allele_semblable = 0\n for Allele in range(3):\n if self.allele[Allele] in foetus.allele and self.allele[Allele] != 0.0:\n Allele_semblable = Allele\n if Allele_semblable == 0:\n Allele_Echo = self.allele[Allele_semblable + 1]\n for Alleles_foetus in range(3):\n if foetus.allele[Alleles_foetus] - 1 == Allele_Echo:\n foetus.informatif = 3\n elif Allele_semblable == 1:\n Allele_Echo = self.allele[Allele_semblable - 1]\n for Alleles_foetus in range(3):\n if foetus.allele[Alleles_foetus] - 1 == Allele_Echo:\n foetus.informatif = 3\n \n def normalisation(self,liste_alleles):\n liste_alleles2=[]\n for alleles in range(len(liste_alleles)):\n if liste_alleles[alleles] != 0.0:\n liste_alleles2.append(liste_alleles[alleles])\n return liste_alleles2\n\nclass Mere(Patient):\n \"\"\" Exclusive informations about the mother. Mere class inherits from Patient.\n\n Attributes :\n homozygote (boolean) : set to True if the mother is homozygous for the marker studied\n \"\"\"\n\n def __init__(self, marqueur, allele, hauteur, informatif, homozygote):\n \"\"\" The constructor for Mere class\n\n Parameters :\n - homozygote (boolean) : set to True if the mother is homozygous for the marker studied\n \"\"\"\n\n super().__init__(marqueur, allele, hauteur, informatif)\n self.homozygote = homozygote\n\n def homozygotie(self):\n \"\"\" Detect if the mother is homozygous for the marker stutied.\n If it's true, homozygote is set to True\n \"\"\"\n if self.allele[1] == 0.0:\n self.homozygote = True\n\n\nclass Foetus(Patient):\n \"\"\" Exclusive informations about the fetus. Mere class inherits from Patient.\n\n Attributes :\n - contamination (int) : 0 if the marker is not contaminated. 1 if it is.\n - taux (int) : value corresponding to the contamination\n \"\"\"\n\n def __init__(self, marqueur, allele, hauteur, concordance_mere_foetus, informatif, num_foetus, contamination, taux):\n \"\"\" The constructor for Mere class\n\n Parameters :\n - contamination (int) : 0 if the marker is not contaminated. 1 if it is.\n - taux (int) : value corresponding to the contamination\n \"\"\"\n\n super().__init__(marqueur, allele, hauteur, informatif)\n self.num_foetus = num_foetus\n self.contamination = contamination\n self.taux = taux\n self.concordance_mere_foetus = concordance_mere_foetus\n\n def get_num_foetus(self):\n return self.num_foetus\n\n def foetus_pics(self):\n \"\"\" Count spikes number (alleles number)\n\n Return :\n Spikes number\n \"\"\"\n pic = 0\n if 0.0 not in self.allele:\n self.contamination = 2\n pic = 3\n elif 0.0 == self.allele[1]:\n pic = 1\n else:\n pic = 2\n return pic\n\n def contamination_heterozygote(self, mere):\n \"\"\" Compute contamination value for heterozygous contamination.\n\n Parameters :\n - mere (list) : list of Mere object corresponding to each line of the mother extracted from the txt file\n\n Set taux attribute to value computed.\n \"\"\"\n hauteur_allele_contaminant = 99999999999999999.0\n hauteur_allele_different = None\n taux_contamination = 0\n for allele in range(3):\n if self.hauteur[allele] < hauteur_allele_contaminant:\n hauteur_allele_contaminant = self.hauteur[allele]\n for alleles in range(3):\n if self.allele[alleles] not in mere.allele:\n hauteur_allele_different = self.hauteur[alleles]\n taux_contamination = ((hauteur_allele_contaminant) / (\n hauteur_allele_different + hauteur_allele_contaminant)) * 100\n self.taux = round(taux_contamination, 2)\n\n def verif_homozygote_contamine(self, echantillon):\n \"\"\" Check if the marker is homozygous contaminated\n\n Parameters :\n - echantillon : Echantillon object\n\n If the marker is contaminated, contamination code is set to 1 and informative code is set to 1 too.\n Set taux attribute to value computed.\n \"\"\"\n seuil = echantillon.get_seuil_hauteur()\n if self.hauteur[0] < self.hauteur[1] * seuil or self.hauteur[1] < self.hauteur[0] * seuil:\n self.contamination = 1\n self.informatif = 1\n else:\n self.taux = 0.0\n\n def homozygote_contamine(self, echantillon):\n \"\"\" Compute contamination value for homozygous contamination.\n\n Parameters :\n - echantillon : Echantillon object\n\n Set taux attribute to value computed.\n \"\"\"\n seuil = echantillon.get_seuil_hauteur()\n if self.hauteur[1] < self.hauteur[0] * seuil:\n allele_contaminant = 1\n taux = ((2 * self.hauteur[allele_contaminant]) / (self.hauteur[allele_contaminant] + self.hauteur[0])) * 100\n else:\n allele_contaminant = 0\n taux = ((2 * self.hauteur[allele_contaminant]) / (self.hauteur[allele_contaminant] + self.hauteur[1])) * 100\n self.taux = round(taux, 2)\n\n\nclass Pere(Patient):\n \"\"\" Exclusive informations about the father. Pere class inherits from Patient.\n\n Do not implemented because mother and fetus are enough to conclude.\n \"\"\"\n\n def __init__(self, marqueur, allele, hauteur, informatif, num_pere, concordance_pere_foetus):\n super().__init__(marqueur, allele, hauteur, informatif)\n self.num_pere = num_pere\n self.concordance_pere_foetus = concordance_pere_foetus\n\n def get_num_pere(self):\n return self.num_pere\n\n\ndef lecture_fichier(path_data_frame):\n \"\"\" Read file corresponding to path_data_frame.\n For each line, Mere, Foetus or Pere object are created.\n At the end, one Echantillon object is created.\n\n Parameters :\n - path_data_frame (file)\n\n Return :\n Donnees_Mere (list) : list of Mere object corresponding to each line of the mother extracted from the txt file\n Donnees_Foetus (list) : list of Foetus object corresponding to each line of the fetus extracted from the txt file\n Donnees_Pere (list) : list of Pere object corresponding to each line of the father extracted from the txt file\n Echantillon_F : Echantillon object to summerize the file\n \"\"\"\n logger = logging.getLogger('Lecture du fichier')\n log = \"#### DPNMaker 1.0..............\\n### Mirna Marie-Joseph, Théo Gauvrit, Kévin Merchadou\\n#### Date : 1 avril 2019\\n\\n\"\n log = log + \"Ouverture du fichier.......................................\\n\"\n log = log + \"Chargement des données.......................................\\n\"\n Iterateur = 2\n Donnees_Mere = []\n Donnees_Foetus = []\n Donnees_Pere = []\n Donnees_na = pd.read_csv(path_data_frame, sep='\\t', header=0)\n Donnees = Donnees_na.replace(np.nan, 0.0, regex=True)\n if (Donnees.shape[0] > 32):\n Iterateur = 3\n num_pere = Donnees[\"Sample Name\"].values[2]\n Allele_na = Donnees[[\"Allele 1\", \"Allele 2\", \"Allele 3\"]].values\n Hauteur_na = Donnees[[\"Height 1\", \"Height 2\", \"Height 3\"]].values\n Date_echantillon = re.search(\"(\\d{4}-\\d{2}-\\d{2})\", Donnees[\"Sample File\"].values[0]).group()\n Nom_echantillon = Donnees[\"Sample Name\"].values[0]\n num_foetus = Donnees[\"Sample Name\"].values[1]\n Allele, Hauteur, log = homogeneite_type(Allele_na, Hauteur_na, log)\n for ligne in range(0, Donnees.shape[0] - 1, Iterateur):\n M = Mere(Donnees[\"Marker\"][ligne], Allele[ligne],\n Hauteur[ligne], None, None)\n F = Foetus(Donnees[\"Marker\"][ligne], Allele[ligne + 1],\n Hauteur[ligne + 1], None, None, num_foetus, None, None)\n if (Iterateur == 3):\n P = Pere(Donnees[\"Marker\"][ligne],\n Allele[ligne + 2], Hauteur[ligne + 2], None, num_pere, None)\n Donnees_Pere.append(P)\n Donnees_Mere.append(M)\n Donnees_Foetus.append(F)\n Echantillon_F = Echantillon(Date_echantillon, Nom_echantillon, F)\n log = log + \"Donnees chargees.......................................\\n\"\n return Donnees_Mere, Donnees_Foetus, Donnees_Pere, Echantillon_F, log\n\n\ndef homogeneite_type(list_allele, list_hauteur, log):\n \"\"\" Allow to convert string into float for Alleles and Height values in order to compute contamination.\n\n Parameters :\n - list_allele (list) : alleles list\n - list_height (list) : height list\n\n Return :\n - Allele (list) : converted values\n - Hauteur (list) : converted values\n \"\"\"\n log = log + \"Normalisation des données..........................\\n\"\n iteration = 2\n Allele = []\n Hauteur = []\n Allele.append(list_allele[0])\n Allele.append(list_allele[1])\n Hauteur.append(list_hauteur[0])\n Hauteur.append(list_hauteur[1])\n if len(list_allele) > 32:\n iteration = 3\n Allele.append(list_allele[2])\n Hauteur.append(list_hauteur[2])\n for i in range(iteration, len(list_allele)):\n Al = []\n Ht = []\n for j in range(3):\n Al.append(float(list_allele[i][j]))\n Ht.append(float(list_hauteur[i][j]))\n Allele.append(Al)\n Hauteur.append(Ht)\n log = log + \"Normalisation effectuée..............................\\n\"\n return Allele, Hauteur, log\n\n\nif __name__ == \"__main__\":\n M, F, P, Echantillon_F, log = lecture_fichier('2018-03-27 foetus 90-10_PP16.txt')\n resultats, conclusion, log = Echantillon_F.analyse_donnees(M, F, P, log)\n print(Echantillon_F.get_conclusion())","sub_path":"V0.3/Traitement2.py","file_name":"Traitement2.py","file_ext":"py","file_size_in_byte":37446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"562130864","text":"\n# coding: utf-8\n\n# In[19]:\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import KFold\nfrom sklearn.datasets import load_boston\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, auc\nfrom sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score\nfrom sklearn.model_selection import KFold\nfrom xgboost.sklearn import XGBClassifier\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.model_selection import RandomizedSearchCV\nimport numpy as np\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn import metrics\nfrom sklearn.multiclass import OneVsRestClassifier\nprint(\"Packages Loaded\", flush = True)\n\n# In[3]:\n\n#For merging all files\nimport numpy as np\nimport pandas as pd\nimport os\n#os.chdir('/home/bduser/BigDataLabProjects/ICS/QCRI')\n#%%\nd1 = pd.read_csv('datamatrix.csv')\nd1.drop(d1.columns[[0]], axis=1, inplace=True)\n#Read data matrix\nprint(\"First CSV Loaded\",flush = True)\n#%%\nClass = pd.read_csv(\"Class.csv\")\nClass.drop(Class.columns[[0]], axis=1, inplace=True)\nx = d1\nc = Class\n\n#%%\nn_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)]\nbootstrap = [True, False]\nmax_features = ['auto', 'sqrt', 'log2', None]\n\nrandom_grid = {'n_estimators': n_estimators,'max_features': max_features, 'bootstrap':bootstrap}\nxgb = XGBClassifier(n_jobs=-1)\nsearch_model = RandomizedSearchCV(estimator = xgb, \n param_distributions = random_grid, \n cv = 3, \n n_jobs = -1,\n verbose=51,\n n_iter=50)\nprint(\"Parameter Tuning\")\nsearch_model.fit(x,c.values.ravel())\n\n#%%\nbest_params = search_model.best_params_\nprint(\"Best Parameters Values: \",best_params,flush=True)\nprint(\"Best Score: \",search_model.best_score_,flush=True)\n#%%\nXX = x\nYY = c\n\nn_splits = 3\nkf = KFold(n_splits=n_splits, shuffle=True)\n\ncon = []\nacc = []\nre = []\npr = []\nf1 = []\nauc_val = []\nd = {1,2,3}\nprint(\"Cross-Fold Validation\",flush = True)\nfor e in d:\n print(\"Round: \", e, flush = True)\n for train_index, val_index in kf.split(XX):\n print(train_index)\n print(val_index)\n auc1 = []\n\n print('Modelling', flush = True)\n model = XGBClassifier(**best_params,n_jobs=-1)\n #model = RandomizedSearchCV(estimator = rf, param_distributions = random_grid, cv = 2, n_jobs = -1)\n\n model.fit(XX.iloc[train_index], YY.iloc[train_index].values.ravel())\n #best_random = model.best_estimator_\n print('Predicting', flush = True)\n\n pred = model.predict(XX.iloc[val_index])\n pred_prb = model.predict_proba(XX.iloc[val_index])\n print('Metrics', flush = True)\n for i in [1,2,3,4]:\n fpr, tpr, thresholds = metrics.roc_curve(YY.iloc[val_index], np.max(pred_prb, axis=1), pos_label= i)\n auc1.append(auc(fpr, tpr))\n \n \n matrix = confusion_matrix(YY.iloc[val_index], pred)\n\n acc1 = matrix.diagonal()/matrix.sum(axis=1)\n re1 = recall_score(YY.iloc[val_index], pred, average=None)\n pr1 = precision_score(YY.iloc[val_index], pred, average=None)\n f11 = f1_score(YY.iloc[val_index], pred, average=None)\n \n\n\n acc.append(acc1)\n re.append(re1)\n pr.append(pr1)\n f1.append(f11)\n con.append(matrix)\n auc_val.append(auc1)\n\n\n# In[37]:\n\nAccuracy = pd.DataFrame(acc, columns =['1', '2', '3', '4'])\n\nPrecision = pd.DataFrame(pr, columns =['1', '2', '3', '4'])\n\nRecall = pd.DataFrame(re, columns =['1', '2', '3', '4'])\n\nF1score = pd.DataFrame(f1, columns =['1', '2', '3', '4'])\n\nAUC = pd.DataFrame(auc_val, columns =['1', '2', '3', '4'])\ntin = []\nfin =list(Accuracy.mean())\nfin.append('Accuracy')\nfin\ngin = list(Precision.mean())\ngin.append('Precision')\ngin\ndin = list(Recall.mean())\ndin.append('Recall')\ndin\njam= list(F1score.mean())\njam.append('F1score')\njam\naam = list(AUC.mean())\naam.append('AUC')\naam\ntin.append(fin)\ntin.append(gin)\ntin.append(din)\ntin.append(jam)\ntin.append(aam)\ntin\nprint(tin, flush=True)\nResults_Randomforest = pd.DataFrame(tin,columns =['1', '2', '3', '4', 'Metrics']) \nResults_Randomforest.to_csv('xgb_tuning_output.csv')\n\n","sub_path":"QCRI_Modelling_XGB_tuning.py","file_name":"QCRI_Modelling_XGB_tuning.py","file_ext":"py","file_size_in_byte":4391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"216541319","text":"__all__ = [\n \"build_template\",\n \"get_model\"\n]\n\n\n\n\n\ndef build_template(templatename,binsize=1.0,maxfrac=0.01,mode='top',resolution=0.0,c_subtract=True,twopass=False,template_library='models/library'):\n \"\"\"This routine reads a specified model from the library and turns it into a\n cross-correlation template by subtracting the top-envelope (or bottom envelope),\n if c_subtract is set to True.\"\"\"\n\n import tayph.util as ut\n from tayph.vartests import typetest,postest,notnegativetest\n import numpy as np\n import tayph.operations as ops\n import astropy.constants as const\n from astropy.io import fits\n from matplotlib import pyplot as plt\n from scipy import interpolate\n from pathlib import Path\n typetest(templatename,str,'templatename mod.build_template()')\n typetest(binsize,[int,float],'binsize mod.build_template()')\n typetest(maxfrac,[int,float],'maxfrac mod.build_template()')\n typetest(mode,str,'mode mod.build_template()',)\n typetest(resolution,[int,float],'resolution in mod.build_template()')\n typetest(twopass,bool,'twopass in mod.build_template()')\n\n binsize=float(binsize)\n maxfrac=float(maxfrac)\n resolution=float(resolution)\n postest(binsize,'binsize mod.build_template()')\n postest(maxfrac,'maxfrac mod.build_template()')\n notnegativetest(resolution,'resolution in mod.build_template()')\n ut.check_path(template_library,exists=True)\n template_library=Path(template_library)\n\n c=const.c.to('km/s').value\n\n if mode not in ['top','bottom']:\n raise Exception(f'RuntimeError in build_template: Mode should be set to \"top\" or \"bottom\" ({mode}).')\n wlt,fxt=get_model(templatename,library=template_library)\n\n if wlt[-1] <= wlt[0]:#Reverse the wl axis if its sorted the wrong way.\n wlt=np.flipud(wlt)\n fxt=np.flipud(fxt)\n\n\n if c_subtract == True:\n wle,fxe=ops.envelope(wlt,fxt-np.median(fxt),binsize,selfrac=maxfrac,mode=mode)#These are binpoints of the top-envelope.\n #The median of fxm is first removed to decrease numerical errors, because the spectrum may\n #have values that are large (~1.0) while the variations are small (~1e-5).\n e_i = interpolate.interp1d(wle,fxe,fill_value='extrapolate')\n envelope=e_i(wlt)\n T = fxt-np.median(fxt)-envelope\n absT = np.abs(T)\n T[(absT < 1e-4 * np.max(absT))] = 0.0 #This is now continuum-subtracted and binary-like.\n #Any values that are small are taken out.\n #This therefore assumes that the model has lines that are deep compared to the numerical\n #error of envelope subtraction (!).\n else:\n T = fxt*1.0\n\n if resolution !=0.0:\n dRV = c/resolution\n print(f'------Blurring template to resolution of data ({round(resolution,0)}, {round(dRV,2)} km/s)')\n wlt_cv,T_cv,vstep=ops.constant_velocity_wl_grid(wlt,T,oversampling=2.0)\n print(f'---------v_step is {np.round(vstep,3)} km/s')\n print(f'---------So the resolution blurkernel has an avg width of {np.round(dRV/vstep,3)} px.')\n T_b=ops.smooth(T_cv,dRV/vstep,mode='gaussian')\n wlt = wlt_cv*1.0\n T = T_b*1.0\n return(wlt,T)\n\n\ndef get_model(name,library='models/library',root='models'):\n \"\"\"This program queries a model from a library file, with predefined models\n for use in model injection, cross-correlation and plotting. These models have\n a standard format. They are 2 rows by N points, where N corresponds to the\n number of wavelength samples. The first row contains the wavelengths, the\n second the associated flux values. The library file has two columns that are\n formatted as follows:\n\n modelname modelpath\n modelname modelpath\n modelname modelpath\n\n modelpath starts in the models/ subdirectory.\n Set the root variable if a location is required other than the ./models directory.\n\n Example call:\n wlm,fxm = get_model('WASP-121_TiO',library='models/testlib')\n \"\"\"\n\n from tayph.vartests import typetest,dimtest\n from tayph.util import check_path\n from astropy.io import fits\n from pathlib import Path\n import errno\n import os\n typetest(name,str,'name in mod.get_model()')\n check_path(library,exists=True)\n\n check_path(root,exists=True)\n root = Path(root)\n library = Path(library)\n #First open the library file.\n\n f = open(library, 'r')\n\n x = f.read().splitlines()#Read everything into a big string array.\n f.close()\n n_lines=len(x)#Number of models in the library.\n models={}#This will contain the model names.\n\n for i in range(0,n_lines):\n line=x[i].split()\n value=(line[1])\n models[line[0]] = value\n\n try:\n modelpath=root/models[name]\n except KeyError:\n raise KeyError(f'Model {name} is not present in library at {str(library)}') from None\n\n try:\n modelarray=fits.getdata(modelpath)#Two-dimensional array with wl on the first row and flux on the second row.\n except FileNotFoundError:\n raise FileNotFoundError(f'Model file {modelpath} from library {str(library)} does not exist.')\n dimtest(modelarray,[2,0])\n return(modelarray[0,:],modelarray[1,:])\n","sub_path":"tayph/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"519200537","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n__title__ = ''\n__author__ = 'joeya'\n__mtime__ = '2017/4/14'\n# code is far away from bugs with the god animal protecting\n I love animals. They taste delicious.\n ┏┓ ┏┓\n ┏┛┻━━━┛┻┓\n ┃ ☃ ┃\n ┃ ┳┛ ┗┳ ┃\n ┃ ┻ ┃\n ┗━┓ ┏━┛\n ┃ ┗━━━┓\n ┃ 神兽保佑 ┣┓\n ┃ 永无BUG! ┏┛\n ┗┓┓┏━┳┓┏┛\n ┃┫┫ ┃┫┫\n ┗┻┛ ┗┻┛\n\"\"\"\n'''\n5.开发一个简单的python计算器\n实现加减乘除及拓号优先级解析\n用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) \n- (-4*3)/ (16-3*2) )等类似公式后,\n必须自己解析里面的(),+,-,*,/符号和公式(不能调用eval等类似功能偷懒实现),\n运算后得出结果,结果必须与真实的计算器所得出的结果一致\n建立一个函数,迭代,如果内部有括号则优先运算\n'''\n# import re\n# aaa = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'\n# def jisuan(shuru):\n# pattern = re.compile(r'\\(.*\\)',re.S)\n# aa = re.findall(pattern,shuru)\n# aa = aa[1:-1]\n# print(aa)\n# for one in aa:\n# one1 = one[1:-1]\n# if '(' not in one1 and ')' not in one1:#先把第一层括号中的值计算出来,然后用replace进行替换\n #此处开始计算其中的值,将符号转换\n #计算其中的加减乘除通过字典形式进行转换,这种方法不行\n #还是必须通过if进行判断,先把乘除找出来算完\n # pattern1 = re.compile(r'\\d+\\*\\d+',re.S)\n # oneout = re.findall(pattern1,one1)\n # print(oneout)\n # pattern2 = re.compile(r'%s'%one,re.S)\n # out = re.sub(pattern2,jieguo_one1,aaa)\n # jisuan(out)\n#jisuan()\n# def biaozhunchuli(shuru):\n# for i in shuru:\n# if i in\n# def kuohao(shuru):\n# if '(' not in shuru:\n#\n# return\n# aa = input()\n# print(int(aa))\n#无法int(含小数的数)\n# aa = '2.3'\n# aa = float(2.3)\n# print(aa)\n# 查询float可用\n#print(str(2.333333))\n#abc = '-7'\n#print(float(abc))\n#主函数\n\n# shuru= '1 - 2 * ((60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'\n# shuru = shuru.replace(' ','')\n# pattern = re.compile(r'\\([^()]+\\)',re.S)#nice\n# kuohao_pipei = re.findall(pattern,shuru)\n# print(kuohao_pipei)\n# for eachone in kuohao_pipei:\n# kuohao_answer = kuohao_jisuan(eachone)\n\n\n# import re\n# shuru= '1 - 2 * ((60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'\n# shuru = shuru.replace(' ','')\n# pattern = re.compile(r'\\([^()]+\\)',re.S)#nice\n# kuohao_pipei = re.findall(pattern,shuru)\n# print(kuohao_pipei)\n# while True:\n# for i, one in enumerate(kuohao_pipei):\n# one1 = one[1:-1]\n# print(one1)\n# pattern2 = re.compile(r'\\d+[*/]+\\d+',re.S)\n# chenchu_pipei = re.findall(pattern2,one1)\n# print(chenchu_pipei)#判断没有乘除后进行加减运算\n# answer = str(jisuan(chenchu_pipei[0]))\n# print(answer)\n# print(i)\n# one.replace(chenchu_pipei[0],answer)\n# print(one)\n#\n# while True:\n# for each in chenchu_pipei:\n# pattern3 = re.compile(r'\\d+[*/]\\d+',re.S)\n# jisuan_pipei = re.findall(pattern3,each)\n# print(jisuan_pipei)\n# break\n# break\n\n# def kuo_h_jisuan(string):或许更好\n# '''\n# 本函数上面的优化版,将内部转化为列表形式,格式如[数字符号数字符号。。。]\n# :param string:去除括号没有\n# :return:返回该结果\n# '''\n# ti_h_zz = re.compile(r'/d+',re.S)\n# string = re.sub(ti_h_zz,'')\nimport re\n\ndef fuhao_chuli(string):\n if '--' in string:\n string = string.replace('--','+')\n if '+-' in string:\n string = string.replace('+-','-')\n if '-+' in string:\n string = string.replace('-+','-')\n return string\n\ndef jisuan(string):\n '''\n :param string:格式化后的计算式 ,形式如:A+B,仅含三项,数字+运算符+数字\n :return: 计算结果\n '''\n # 先把运算符取出来\n pattern = re.compile(r'\\d([*+/-])-?\\d', re.S)\n fuhao = re.findall(pattern, string)[0]\n pattern1 = re.compile(r'(.*\\d)[*+/-](-?\\d.*)')\n num = re.findall(pattern1,string)\n num1 = float(num[0][0])\n num2 = float(num[0][1])\n if fuhao == '+':\n jieguo = num1 + num2\n elif fuhao == '-':\n jieguo = num1 - num2\n elif fuhao == '*':\n jieguo = num1 * num2\n elif fuhao == '/':\n if num2 == 0:\n print('分母不可为0')\n jieguo = 'wrong'\n return jieguo\n jieguo = num1 / num2\n jieguo = round(jieguo,7)\n return jieguo\n#一直在正则匹配出问题,需要再熟悉\ndef kuohao_jisuan(string):#本来以为已经解决问题,但是在浮点数处遇到问题,不能以string,太麻烦\n '''\n 该函数将最底层含括号进行运算,思路,先乘除,后加减\n :param string: 内部无括号的计算式,字符形式\n :return: 计算结果\n '''\n if '*' in string or '/' in string:\n #pattern = re.compile(r'\\d+[*/][*/0-9]+',re.S)#'1+2*3*4'\n # pattern = re.compile(r'\\d[*/0-9.]+\\d')#换一种匹配规则:加减中间含乘除的匹配项\n # chen_chu = re.findall(pattern,string)#'2*3*4'\n # #print(chen_chu)\n # for ch_ch_one in chen_chu:\n #print(string)\n pattern_ch_ch = re.compile(r'[0-9.]+[*/]-?[0-9.]+',re.S)#取出乘除的第一项\n zu_chen_chu = re.findall(pattern_ch_ch,string)#'2*3'\n answer = str(jisuan(zu_chen_chu[0]))\n string = string.replace(zu_chen_chu[0],answer)\n return kuohao_jisuan(string)\n else:\n try:\n string = fuhao_chuli(string)\n float(string)\n return string\n except:\n string = fuhao_chuli(string)\n pattern_j_j = re.compile(r'-?[0-9.]+[+-][0-9.]+',re.S)\n zu_jia_jian = re.findall(pattern_j_j,string)\n answer = str(jisuan(zu_jia_jian[0]))\n string = string.replace(zu_jia_jian[0], answer)\n return kuohao_jisuan(string)\n#print(kuohao_jisuan('-6-2*3/4-4*2'))\n#主函数,现将最底层括号匹配,然后计算后返回替代\ndef all_jisuan(string):\n string = string.replace(' ','')\n if '(' not in string and ')' not in string:\n string = kuohao_jisuan(string)\n return string\n else:\n pattern = re.compile(r'\\([^()]+\\)', re.S)#括号开始括号结束,中间没有括号\n base_kh_list = re.findall(pattern,string)\n for base_kh in base_kh_list:\n base_kh1 = base_kh[1:-1]#base_kh为去除括号的算式\n kuohao_out = kuohao_jisuan(base_kh1)\n string = string.replace(base_kh,kuohao_out)\n string = fuhao_chuli(string)\n return all_jisuan(string)\n return string\n #替换之后可能出现*- +- -- /-这样的情况,所以这时候就需要处理\ndef start():\n while True:\n shuru = str(input('\\033[1;31;47m q is out\\ninput:\\n\\033[0m'))\n if shuru == 'q':\n break\n answer = all_jisuan(shuru)\n if '+' in answer:\n answer = answer[1:]\n print(answer)\n\nif __name__ == '__main__':\n start()","sub_path":"python5_2.py","file_name":"python5_2.py","file_ext":"py","file_size_in_byte":7623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"643306493","text":"\"\"\"\nThis file is a quick and dirty script to run some basic tests against\na backupservice site. It checks the config/backup/restore endpoints\nfor a response, and creates/deletes a configuration to make sure a\nbasic use case is successful. This script needed to be modified to\nwork with python 2.6.6, hence the filename and implementation details\n\"\"\"\n\nimport argparse\nimport json\nimport sys\nimport time\n\nimport requests\n\ncustomer = ''\nuser = ''\npassword = ''\nsite = ''\nauth_cookie = ''\nsite_secure = True\n\ntest_volume = 'smokeTestVolume'\nauthenticate_path = \"authenticate/\"\nbackup_service_path = 'backupservice/v1/'\nconfig_path = \"configuration/\"\nbackup_path = \"backup/\"\nrestore_path = \"restore/\"\nstorage_path = \"storage/volume/\"\n\ncontent_type = {\"Content-Type\": \"application/oracle-compute-v3+json\"}\n\ntests_failed = 0\n\n\ndef display_error_message(message):\n print(\"\\033[91m{0}\\033[0m\".format(message))\n\n\ndef display_warning_message(message):\n print(\"\\033[93m{0}\\033[0m\".format(message))\n\n\ndef display_positive_message(message):\n print(\"\\033[94m{0}\\033[0m\".format(message))\n\n\ndef display_success_message(message):\n print(\"\\033[92m{0}\\033[0m\".format(message))\n\n\ndef display_prominent_message(message):\n print(\"\\033[95m{0}\\033[0m\".format(message))\n\n\ndef get_endpoint(path):\n if site_secure is True:\n return \"https://{0}/{1}\".format(site, path)\n return \"http://{0}/{1}\".format(site, path)\n\n\ndef config_input_json(name, enabled, retention_count, interval_type, interval_value):\n if interval_type is \"Minute\":\n interval_inner = \"minuteInterval\"\n elif interval_type is \"Hourly\":\n interval_inner = \"hourlyInterval\"\n elif interval_type is \"DailyWeekly\":\n interval_inner = \"DailyWeekly interval JSON not implemented.\"\n else:\n display_error_message(\"Error in script - unrecognized interval type supplied when creating Configuration.\")\n return -1\n\n json_dict = {\n 'volumeUri': \"http://{0}/{1}{2}/{3}/{4}\".format(site, storage_path, customer, user, test_volume),\n 'name': \"{0}/{1}/{2}\".format(customer, user, name),\n 'enabled': enabled,\n 'backupRetentionCount': retention_count,\n 'interval': {\n interval_type: {\n interval_inner: interval_value\n }\n }\n }\n return json.dumps(json_dict)\n\n\ndef backup_input_json(config_name, name, description):\n return json.dumps({\"backupConfigurationName\": config_name,\n \"name\": name,\n \"description\": description})\n\n\ndef authenticate_json():\n return json.dumps({\"user\": \"{0}/{1}\".format(customer, user),\n \"password\": password})\n\n\ndef test_volume_name():\n return \"{0}/{1}/{2}\".format(customer, user, test_volume)\n\n\ndef check_for_test_volume():\n display_positive_message(\"\\n\\nCreating volume: {0} for testing.\".format(test_volume_name()))\n volume = json.dumps({\"name\": test_volume_name(),\n \"properties\": [\"/oracle/public/storage/default\"],\n \"size\": \"1G\"})\n response = post_object(storage_path, volume)\n\n if response.status_code == 201:\n for i in range(1, 10):\n time.sleep(5)\n get_resp = get_test_volume()\n # debug_output_response_data(get_resp)\n vol_status = json.loads(get_resp.text)[\"status\"]\n if vol_status == \"Online\":\n break\n display_positive_message(\"\\tVolume status is {0}. Waiting for volume to become available.\".format(vol_status))\n else:\n display_error_message(\"Volume: {0} was not able to initialize in time for testing.\".format(test_volume_name()))\n display_error_message(\"Attempting cleanup of volume. This may fail, and manual cleanup may be required.\")\n delete_test_volume()\n sys.exit(99)\n elif response.status_code != 409:\n display_error_message(\"Unable to create or verify existence of volume needed for tests. Receieved: {0}.\\nAborting test script.\".format(response.text))\n sys.exit(99)\n\n display_success_message(\"Volume: {0} is ready for testing.\".format(test_volume_name()))\n\n\ndef delete_test_volume():\n display_positive_message(\"\\n\\nAttempting to cleanup volume used in testing.\")\n volume_path = \"{0}{1}\".format(storage_path, test_volume_name())\n display_positive_message(\"Volume path: {0}\".format(volume_path))\n endpoint = get_endpoint(volume_path)\n del_resp = requests.delete(endpoint, headers=content_type, cookies=auth_cookie)\n\n if del_resp.status_code not in [200, 202, 204]:\n display_error_message(\"Error cleaning up test volume: {0}.\".format(test_volume_name()))\n debug_output_response_data(del_resp)\n display_error_message(\"\\nPlease perform manual cleanup of volume.\")\n else:\n display_success_message(\"Successfully cleaned up test volume.\")\n\n\ndef setup_test_preconditions():\n authenticate()\n check_for_test_volume()\n display_success_message(\"Preconditions for testing have been met. Proceeding to run tests.\\n\\n\")\n\n\ndef authenticate():\n display_positive_message(\"\\n\\nAttempting authentication as {0}\".format(user))\n response = post_object(authenticate_path, authenticate_json())\n if response.status_code != 204:\n display_error_message(\"Unable to authenticate. Received:\\n{0}\\nAborting script.\".format(response.text))\n sys.exit(99)\n\n global auth_cookie\n auth_cookie = response.cookies\n display_success_message(\"Successfully authenticated as {0}.\".format(user))\n\n\ndef get_test_volume():\n endp = get_endpoint(\"{0}{1}\".format(storage_path, test_volume_name()))\n return get_nimbula_object(endp)\n\n\ndef get_nimbula_object(endp):\n return requests.get(endp, headers=content_type, cookies=auth_cookie)\n\n\ndef get_backupservice_object(object_type, object_name):\n endp = get_endpoint(\"{0}{1}{2}/{3}/{4}\".format(backup_service_path, object_type, customer, user, object_name))\n return get_nimbula_object(endp)\n\n\ndef list_backupservice_objects(object_type):\n endp = get_endpoint(\"{0}{1}\".format(backup_service_path, object_type))\n return get_nimbula_object(endp)\n\n\ndef post_object(path, object):\n \"\"\"Used for issuing a POST request to backupservice on the target site\n :param path: Specific endpoint to POST the resource to\n :param object: JSON blob for the resource to be POSTed\n :return:\n \"\"\"\n return requests.post(get_endpoint(path),\n headers=content_type,\n data=object,\n cookies=auth_cookie)\n\n\ndef post_backupservice_object(object_type, object):\n return post_object(\"{0}{1}\".format(backup_service_path, object_type), object)\n\n\ndef delete_object(object_type, object_name):\n \"\"\"Used for issuing a DELETE request to backupservice on the target site\n :param object_type: must be: \"configuration\" , \"backup\" or \"restore\"\n :param object_name: name of the object to delete. This method constructs the full name based on customer and user, so no need to pass that.\n :return:\n \"\"\"\n name = \"{0}/{1}/{2}\".format(customer, user, object_name)\n return requests.delete(get_endpoint(\"{0}{1}{2}\".format(backup_service_path, object_type, name)),\n headers=content_type,\n cookies=auth_cookie)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n\n parser.add_argument('customer', help='Customer to run script as')\n parser.add_argument('user', help='User to run script as')\n parser.add_argument('password', help='Password for user')\n parser.add_argument('site', help='Site to run script against')\n parser.add_argument('--site_insecure', help='Use this flag if site uses HTTP, not HTTPS', action=\"store_true\")\n args = parser.parse_args()\n\n global customer\n customer = args.customer\n global user\n user = args.user\n global password\n password = args.password\n global site\n site = args.site\n\n if args.site_insecure:\n global site_secure\n site_secure = False\n\n\ndef test_case_create_then_delete_configuration():\n \"\"\"Test for basic actions POST/DELETE on Backup Configuration\n Preconditions - configuration with a specific name does not exist on target site\n Steps:\n 1) Create a configuration with the reserved name\n 2) Ensure configuration can be reached by a GET\n 3) Delete that configuration\n 4) Ensure configuration cannot be reached by a GET\n :return:\n \"\"\"\n display_positive_message(\"\\n\\nRunning test case - Create then Delete Configuration.\")\n\n success = True\n\n # precondition - delete config if it exists\n test_config_name = \"testCaseCreateThenDeleteConfiguration_config\"\n display_positive_message(\"Using Backup Configuration with name: {0}/{1}/{2}\".format(customer, user, test_config_name))\n delete_resp = delete_object(config_path, test_config_name)\n if delete_resp.status_code not in [204, 401, 404]:\n display_error_message(\"\\tCould not ensure an object with reserved name: {0} doesn't exist on site. Try deleting object manually. Aborting script.\".format(test_config_name))\n return -1\n\n # preconditions complete - run the test\n\n # step 1\n config_json = config_input_json(test_config_name, False, 1, \"Hourly\", 48)\n\n post_response = post_backupservice_object(config_path, config_json)\n if post_response.status_code != 201:\n display_error_message(\"\\tUnexpected response code encountered while POSTing a configuration for testing.\")\n debug_output_response_data(post_response)\n success = False\n else:\n display_positive_message(\"\\tSuccessful POST for test configuration. Ensuring configuration exists on server...\")\n\n # step 2\n get_resp = get_backupservice_object(config_path, test_config_name)\n if get_resp.status_code != 200:\n display_error_message(\"\\tCould not find configuration after POST.\")\n debug_output_response_data(get_resp)\n success = False\n else:\n display_positive_message(\"\\tFound expected configuration after POST.\")\n\n # step 3\n delete_resp = delete_object(config_path, test_config_name)\n if delete_resp.status_code != 204:\n display_error_message(\"\\tUnexpected response from site trying to cleanup test configuration.\")\n debug_output_response_data(delete_resp)\n success = False\n else:\n display_positive_message(\"\\tSuccessfully DELETED test configuration.\")\n\n # step 4\n get_resp = get_backupservice_object(config_path, test_config_name)\n if get_resp.status_code == 200:\n display_error_message(\"\\tError: Configuration still exists on site after DELETE.\")\n debug_output_response_data(get_resp)\n success = False\n else:\n display_positive_message(\"\\tDELETE successfully removed configuration from site.\")\n\n print_test_result(success)\n\n\ndef check_endpoints():\n types = [config_path, backup_path, restore_path]\n display_positive_message(\"\\n\\nAttempting to reach endpoints for object types: {0}\".format(types))\n success = True\n for service_path in types:\n try:\n get_resp = list_backupservice_objects(config_path)\n if get_resp.status_code is not None:\n display_positive_message(\"\\tSuccessfully reached endpoint for {0} type.\".format(service_path))\n if get_resp.status_code != 200:\n display_error_message(\"\\tReceived status of {0}. Expected 200.\".format(get_resp.status_code))\n debug_output_response_data(get_resp)\n success = False\n else:\n display_error_message(\"\\tNo response from endpoint for {0} type.\".format(service_path))\n success = False\n except:\n display_error_message(\"Error encountered trying to reach endpoint for {0} type.\".format(service_path))\n success = False\n print_test_result(success)\n\n\ndef debug_output_response_data(resp):\n display_prominent_message(\"\\tReceived response containing the following data...\")\n display_prominent_message(\"URL:\")\n display_warning_message(\"\\t{0}\".format(resp.url))\n display_prominent_message(\"Status:\")\n display_warning_message(\"\\t{0}\".format(resp.status_code))\n display_prominent_message(\"Headers:\")\n display_warning_message(\"\\t{0}\".format(resp.headers))\n display_prominent_message(\"Body:\")\n display_warning_message(\"\\t{0}\".format(resp.text))\n display_prominent_message(\"\\tEnd response data...\")\n\n\ndef print_test_result(result):\n if result is False:\n display_error_message(\"Test: FAILED\")\n global tests_failed\n tests_failed += 1\n else:\n display_success_message(\"Test: SUCCESSFUL\")\n\n\ndef main():\n parse_args()\n authenticate()\n check_for_test_volume()\n check_endpoints()\n test_case_create_then_delete_configuration()\n delete_test_volume()\n sys.exit(tests_failed)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"workstuff/smoketest266.py","file_name":"smoketest266.py","file_ext":"py","file_size_in_byte":12996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"190304873","text":"import numpy as np\nimport pandas as pd\nimport pytest\n\nimport dval.score\nfrom dval.metrics import *\nfrom dval.transformations import *\n\nGROUND_TRUTH_MC = [\"a\", \"b\", \"a\", \"b\", \"c\", \"a\", \"a\", \"b\", \"a\", \"c\", \"c\", \"b\"]\nPREDICTED_BEST_MC = [\"a\", \"b\", \"a\", \"b\", \"c\", \"a\", \"a\", \"b\", \"a\", \"c\", \"c\", \"b\"]\nPREDICTED_OK_MC = [\"a\", \"b\", \"a\", \"c\", \"a\", \"a\", \"a\", \"b\", \"b\", \"c\", \"c\", \"b\"]\nPREDICTED_BAD_MC = [\"b\", \"c\", \"b\", \"c\", \"a\", \"b\", \"b\", \"c\", \"b\", \"a\", \"a\", \"c\"]\n\nGROUND_TRUTH_BC = [1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1]\nGROUND_TRUTH_LABEL_BC = [\"a\", \"a\", \"b\", \"a\", \"a\", \"b\", \"b\", \"b\", \"a\", \"b\", \"a\", \"a\"]\n\nPREDICTED_BEST_BC = [1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1]\nPREDICTED_BEST_LABEL_BC = [\"a\", \"a\", \"b\", \"a\", \"a\", \"b\", \"b\", \"b\", \"a\", \"b\", \"a\", \"a\"]\n\nPREDICTED_OK_BC = [1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0]\nPREDICTED_OK_LABEL = [\"a\", \"a\", \"a\", \"b\", \"a\", \"b\", \"a\", \"a\", \"b\", \"b\", \"a\", \"b\"]\n\nPREDICTED_OK_BC_B = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\nPREDICTED_OK_BC_B_LABEL = [\"a\", \"a\", \"a\", \"a\", \"a\", \"a\", \"a\", \"a\", \"a\", \"a\", \"a\", \"a\"]\n\nPREDICTED_BAD_BC = [0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0]\nPREDICTED_BAD_LABEL_BC = [\"b\", \"b\", \"a\", \"b\", \"b\", \"a\", \"a\", \"a\", \"b\", \"a\", \"b\", \"b\"]\n\nGROUND_TRUTH_RG = [0.5, 6, 2, 5.6]\nPREDICTED_BEST_RG = [0.5, 6, 2, 5.6]\nPREDICTED_OK_RG = [0.0, 7.2, 2.1, 4.7]\nPREDICTED_BAD_RG = [5435, -45, 45646, 34]\n\n\nclass TestBinaryClass(object):\n \"\"\"Test transformedscore for Binary Classification\"\"\"\n\n def testOK_accuracy(self):\n accuracy_score = accuracy(GROUND_TRUTH_BC, PREDICTED_OK_BC)\n assert accuracy_score == pytest.approx(0.5)\n assert find_metric(\"accuracy\")(GROUND_TRUTH_BC, PREDICTED_OK_BC) == 0.5\n acc_transformation = apply_transformation(\"accuracy\")\n assert acc_transformation.transform(accuracy_score) == 0.5\n\n def testOKB_accuracy(self):\n accuracy_score = accuracy(GROUND_TRUTH_BC, PREDICTED_OK_BC_B)\n assert accuracy_score == pytest.approx(7 / 12)\n assert find_metric(\"accuracy\")(\n GROUND_TRUTH_BC, PREDICTED_OK_BC_B\n ) == pytest.approx(7 / 12)\n acc_transformation = apply_transformation(\"accuracy\")\n assert acc_transformation.transform(accuracy_score) == pytest.approx(7 / 12)\n\n def testBest_f1(self):\n \"\"\" Compute transformed score for f1\"\"\"\n f1_score = f1(GROUND_TRUTH_BC, PREDICTED_BEST_BC)\n assert f1_score == 1.0\n assert find_metric(\"f1\")(GROUND_TRUTH_BC, PREDICTED_BEST_BC) == 1.0\n f1_transformation = apply_transformation(\"f1\")\n assert f1_transformation.transform(f1_score) == 1\n\n def testOk_f1(self):\n f1_score = f1(GROUND_TRUTH_BC, PREDICTED_OK_BC)\n assert f1_score == pytest.approx(0.571428571428, 1e-10)\n f1_transformation = apply_transformation(\"f1\")\n assert f1_transformation.transform(f1_score) == pytest.approx(\n 0.571428571428, 1e-10\n )\n\n def testOk_precision(self):\n precision_score = precision(GROUND_TRUTH_BC, PREDICTED_OK_BC)\n assert precision_score == pytest.approx(0.57142857142857, 1e-10)\n precision_transformation = apply_transformation(\"precision\")\n assert precision_transformation.transform(precision_score) == pytest.approx(\n 0.57142857142857, 1e-10\n )\n\n def testOk_recall(self):\n recall_score = recall(GROUND_TRUTH_BC, PREDICTED_OK_BC)\n assert recall_score == pytest.approx(0.57142857142857, 1e-10)\n recall_transformation = apply_transformation(\"recall\")\n assert recall_transformation.transform(recall_score) == pytest.approx(\n 0.57142857142857, 1e-10\n )\n\n def testWrongInputs(self):\n with pytest.raises(ValueError):\n assert f1(GROUND_TRUTH_MC, PREDICTED_BEST_MC) == 1.0\n\n\nclass TestMultiClass(object):\n \"\"\" Test transformedscore for Multiclass Classification\"\"\"\n\n\nclass TestRegressionClass(object):\n \"\"\"Test transformed score for \"\"\"\n\n def testOk_mae(self):\n \"\"\"Test transformed MAE\"\"\"\n mae_score = r2(GROUND_TRUTH_RG, PREDICTED_OK_RG)\n assert mae_score == pytest.approx(0.88542736505762865, 1e-10)\n mae_transformation = apply_transformation(\"meanAbsoluteError\")\n assert mae_transformation.transform(mae_score) == pytest.approx(\n 0.5841087186362, 1e-10\n )\n\n def testMSE_1(self):\n mse_score_list = [\n 9.528162521,\n 8.145583091,\n 8.145583091,\n 595.2379125,\n 13.96893799,\n 18.66023933,\n 29.57031075,\n 8.679340484,\n 45.30667017,\n 13.67148759,\n 608,\n 13.67148759,\n 9.726554,\n 9.726554,\n 7.757945897,\n 0.117305083,\n 0.117305083,\n ]\n expected_transformed_list = [\n 1.455358e-04,\n 5.798588e-04,\n 5.798588e-04,\n 0.000000e00,\n 1.715525e-06,\n 1.573950e-08,\n 2.877698e-13,\n 3.400685e-04,\n 0.000000e00,\n 2.309819e-06,\n 0.000000e00,\n 2.309819e-06,\n 1.193481e-04,\n 1.193481e-04,\n 8.543019e-04,\n 9.414146e-01,\n ]\n for (mse_score, expected_score) in zip(\n mse_score_list, expected_transformed_list\n ):\n computed_score = apply_transformation(\"meanSquaredError\").transform(\n mse_score\n )\n assert computed_score == pytest.approx(expected_score, 1e-6)\n\n def testRMSE_1(self):\n rmse_score_list = [\n 0.730243702,\n 0.368069081,\n 0.452083591,\n 1.40265164,\n 0.710223846,\n 0.368069081,\n 1.40265164,\n 0.368134653,\n 0.389765103,\n 0.743558301,\n 0.056568865,\n 0.37111655,\n 0.022074072,\n ]\n expected_transformed_list = [\n 6.502825e-01,\n 8.180154e-01,\n 7.777310e-01,\n 3.947913e-01,\n 6.590988e-01,\n 8.180154e-01,\n 3.947913e-01,\n 8.179837e-01,\n 8.075477e-01,\n 6.444531e-01,\n 9.717231e-01,\n 8.165425e-01,\n 9.889634e-01,\n ]\n for (rmse_score, expected_score) in zip(\n rmse_score_list, expected_transformed_list\n ):\n computed_score = apply_transformation(\"rootMeanSquaredError\").transform(\n rmse_score\n )\n assert computed_score == pytest.approx(expected_score, 1e-6)\n\n def testMissingAndInfiniteScores(self):\n # This test may not be expected behavior and may need to be modified\n score_list = [float(\"-inf\"), float(\"nan\"), math.nan]\n expected_transformed_list = [None, None, None]\n for (score, expected_score) in zip(score_list, expected_transformed_list):\n computed_score = apply_transformation(\"rootMeanSquaredError\").transform(\n score\n )\n assert computed_score is expected_score\n\n\nclass TestTransformations(object):\n \"\"\"Test transformedscore transformations directly\"\"\"\n\n def testTransformedScore0_1Range(self):\n for i in np.arange(0, 1, 0.01):\n # put in a dummy target, metric, and baseline score to do testing\n score = dval.score.Score(\"Hall_of_Fame\", \"f1Macro\", i, 0.5)\n transformation_true = CenterizedNormalizedScoreTransformation(0, 1, True)\n transformation_false = CenterizedNormalizedScoreTransformation(0, 1, False)\n assert score._transform(i, transformation_false) == pytest.approx(i, 1e-8)\n assert score._transform(i, transformation_true) == pytest.approx(\n 1 - i, 1e-8\n )\n\n def testTransformedScoreFiniteRange(self):\n a_vec = np.arange(-12, 6, 1.5)\n for a in a_vec:\n b_vec = np.arange(a + 1, a + 37, 9)\n for b in b_vec:\n for i in np.arange(a, b, 4):\n # put in a dummy target, metric, and baseline score to do testing\n score = dval.score.Score(\"Hall_of_Fame\", \"f1Macro\", i, 0.5)\n transformation_true = CenterizedNormalizedScoreTransformation(\n a, b, True\n )\n transformation_false = CenterizedNormalizedScoreTransformation(\n a, b, False\n )\n assert score._transform(i, transformation_false) == pytest.approx(\n (i - a) / (b - a), 1e-8\n )\n assert score._transform(i, transformation_true) == pytest.approx(\n 1 - ((i - a) / (b - a)), 1e-8\n )\n\n def testTransformedScoreAEqualsB(self):\n # put in a dummy target, metric, and baseline score to do testing\n score = dval.score.Score(\"Hall_of_Fame\", \"f1Macro\", 0.5, 1)\n transformation_false = CenterizedNormalizedScoreTransformation(1, 1, False)\n assert score._transform(0.5, transformation_false) == None\n\n def testTransformedScoreAExceedsB(self):\n # put in a dummy target, metric, and baseline score to do testing\n score = dval.score.Score(\"Hall_of_Fame\", \"f1Macro\", 0.5, 1)\n transformation_false = CenterizedNormalizedScoreTransformation(2, 1, False)\n assert pd.isnull(score._transform(0.5, transformation_false))\n\n def testTransformedScoreInfInf(self):\n for i in np.arange(-50, 50, 0.5):\n # put in a dummy target, metric, and baseline score to do testing\n score = dval.score.Score(\"class\", \"meanSquaredError\", i, 0.5)\n transformation_true = InfInfScoreTransformation(True)\n transformation_false = InfInfScoreTransformation(False)\n assert score._transform(i, transformation_false) == pytest.approx(\n (1 / (1 + math.exp(-i))), 1e-8\n )\n assert score._transform(i, transformation_true) == pytest.approx(\n 1 - 1 / (1 + math.exp(-i)), 1e-8\n )\n\n def testTransformedScore0Inf(self):\n for i in np.arange(-50, 0, 0.5):\n score = dval.score.Score(\"class\", \"meanSquaredError\", i, 0.5)\n transformation_true = ZeroInfScoreTransformation(True)\n transformation_false = ZeroInfScoreTransformation(False)\n assert score._transform(i, transformation_false) is None\n assert score._transform(i, transformation_true) is None\n for i in np.arange(0, 50, 0.5):\n score = dval.score.Score(\"class\", \"meanSquaredError\", i, 0.5)\n transformation_true = ZeroInfScoreTransformation(True)\n transformation_false = ZeroInfScoreTransformation(False)\n assert score._transform(i, transformation_false) == pytest.approx(\n -1 + (2 / (1 + math.exp(-i))), 1e-8\n )\n assert score._transform(i, transformation_true) == pytest.approx(\n 2 - 2 / (1 + math.exp(-i)), 1e-8\n )\n","sub_path":"tests/test_transformedscores.py","file_name":"test_transformedscores.py","file_ext":"py","file_size_in_byte":11111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"530445577","text":"#!/usr/bin/env python\n\"\"\"\nThis file starts reading data (and playing a bagfile) and takes data from the TrackedLaserScan and re-publishes it as\npoint-cloud data to another topic (therefore making it readable to tools such as RViz)\n\"\"\"\nimport numpy as np\nimport rospy\nfrom roslib import message\nfrom collections import namedtuple\nimport sys\nimport subprocess\nfrom bob_perception_msgs.msg import *\nfrom sensor_msgs.msg import PointCloud2, PointField\nimport sensor_msgs.point_cloud2 as pc2\nimport std_msgs.msg\n\n\ndef callback_modded(data):\n global pub, xoff, yoff\n divide = True # Just a flag for me\n multi = 1 # Multiply all values by this\n\n # ---- #\n # Actual Function\n point_list = list(pc2.read_points(data.point_cloud, skip_nans=True, field_names=(\"x\", \"y\", \"z\")))\n print(\"Acquired a List of points. Length: \"+str(len(point_list))+\" || Entry0: \"+str(point_list[0]))\n\n # Currently trying to normalize the data in the array to the position of one of the entries\n # Struggling with the pc2 -> array -> pc2 conversion though\n # Probably a waste of time anyway, since 90-110pts is not enough to display any meaningful data\n # and the maven-X.bag files have only that amount of points.\n # In general, the fact that the points are at x/y-values like x.e+07 is kinda weird\n # According to some quick research, rviz has some known issues with this kind of size of values\n\n if len(point_list)>0 and xoff == 0:\n xoff = point_list[0][0]\n if len(point_list) > 0 and yoff == 0:\n yoff = point_list[0][1]\n redone_list = []\n min_x = 999999999999999999\n max_x = -min_x\n for t in point_list:\n if divide:\n new_t = ((t[0]-xoff) * multi, (t[1]-yoff) * multi, t[2])\n else:\n new_t = (t[0], t[1], t[2])\n redone_list.append(new_t)\n if new_t[0] < min_x:\n min_x = new_t[0]\n if new_t[0] > max_x:\n max_x = new_t[0]\n print(\"\\tmin_x: \"+str(min_x)+\" / max_x: \"+str(max_x))\n\n c = pc2.create_cloud(data.point_cloud.header, data.point_cloud.fields, redone_list)\n # c = data.point_cloud\n pub.publish(c)\n\n\ndef callback(data):\n # Simply publish the pc2 data without any modifications at all\n global pub\n cloud = data.point_cloud\n # cloud.header = data.header # Header of cloud is not set, so copy the original header (from the data)\n # cloud.header.frame_id = \"gps_antenna\"\n pub.publish(cloud)\n\n\ndef republisher(topic_name):\n global pub\n rospy.init_node('laser_scan_extractor', anonymous=True)\n pub = rospy.Publisher(topic_name, PointCloud2, queue_size=10)\n rospy.Subscriber(\"tracked_objects/scan\", TrackedLaserScan, callback)\n\n # and now start spinning so that it doesnt stop\n rospy.spin()\n\n\nif __name__ == '__main__':\n global xoff, yoff\n # these offset from maven-1.bag dont really work aswell, since the original data has data in a completly different\n # region (these offsets are for the c2x data not the trackedlaserscan)\n xoff = 470224.387970\n yoff = 5522444.309280\n # set xoff/yoff to 0 if you want to grab them from the first data point\n topic_name = \"pc2data\"\n if len(sys.argv) > 1:\n bag_name = sys.argv[1]\n else:\n bag_name = \"data/maven-1.bag\"\n player_proc = subprocess.Popen(['rosbag', 'play', bag_name])\n republisher(topic_name)\n player_proc.terminate()\n\n","sub_path":"src/general/pc2_publisher.py","file_name":"pc2_publisher.py","file_ext":"py","file_size_in_byte":3380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"326844314","text":"\"\"\"Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника.\nВ расчете необходимо использовать формулу: (выработка в часах * ставка в час) + премия.\nДля выполнения расчета для конкретных значений необходимо запускать скри��т с параметрами.\"\"\"\n\nfrom sys import argv\n\ntry:\n answer = (int(argv[1]) * int(argv[2]) + int(argv[3]))\nexcept IndexError:\n print(\"Введите верное число аргументов!\")\nexcept ValueError:\n print(\"Введите верные значения аргументов!\")\nelse:\n print(f'Выработка: {argv[1]}\\nСтавка: {argv[2]}\\nПремия: {argv[3]}\\nИтого: {answer}')\n","sub_path":"Lesson4/base_les4_1.py","file_name":"base_les4_1.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"300793974","text":"from models_noa import Bokeh_Generator\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import Dataset, DataLoader\nimport cv2\nimport os\nimport numpy as np\nimport time\nfrom options import opt\nfrom gauss import *\nfrom torch.autograd import Variable\n\nfrom canny import *\n\ntesting_epoch = opt.testing_epoch\ntesting_mode = opt.testing_mode\n\nprint(\"Checking for epoch:\", testing_epoch)\nprint(\"Checking for mode : \", testing_mode)\n\nCHECKPOINTS_DIR = opt.checkpoints_dir\n\nif testing_mode == \"Nat\":\n print(\"Checking for Natural Images\")\n HAZY_DIR = opt.testing_dir_nat\nelse:\n print(\"Checking for Synthetic Images\")\n HAZY_DIR = opt.testing_dir_syn\n\nresult_dir = './EP'+str(testing_epoch)+'_'+HAZY_DIR.replace('.', '').replace('/', '_')+'_'+CHECKPOINTS_DIR.replace('.', '').replace('/', '_')+'_no_attention/'\n\nif not os.path.exists(result_dir):\n os.makedirs(result_dir)\n\n# device = 'cuda:0' if torch.cuda.is_available() else 'cpu'\ndevice = 'cpu' \n\nbokeh_net = Bokeh_Generator()\ncheckpoint = torch.load(os.path.join(CHECKPOINTS_DIR,'netG_'+ str(testing_epoch)+\".pth\"), map_location=torch.device('cpu'))\nbokeh_net.load_state_dict(checkpoint['model_state_dict'])\nbokeh_net.eval()\nbokeh_net.to(device)\n\nk = 2**(1/2)\nsigma = 1.6\nchannels = 1\ngaussian_kernel = 5\n\ngauss_net_k_sigma = GaussianSmoothing(channels*3, gaussian_kernel, sigma)\ngauss_net_k_sigma.to(device)\n\ngauss_net_k3_sigma = GaussianSmoothing(channels*3, gaussian_kernel, (k**5)*sigma)\ngauss_net_k3_sigma.to(device)\n\ngauss_net_k5_sigma = GaussianSmoothing(channels*3, gaussian_kernel, (k**14)*sigma)\ngauss_net_k5_sigma.to(device)\n\ncanny_net = CannyNet(threshold=20.0, use_cuda=False)\nprint('canny network', canny_net)\ncanny_net.to(device)\n\n\n\nif __name__ =='__main__':\n\n total_files = os.listdir(HAZY_DIR)\n ready_samples = os.listdir(result_dir)\n st = time.time()\n\n for m in total_files:\n # m= \"6.png\"\n if str(m) in ready_samples:\n print('Already done {0}', str(m))\n continue\n print(\"Testing image \", str(m))\n\n #img = cv2.cvtColor(cv2.imread(HAZY_DIR + str(m)), cv2.COLOR_BGR2YCR_CB)\n img = cv2.imread(HAZY_DIR + str(m))\n img = cv2.cvtColor(img, cv2.COLOR_BGR2YCR_CB)\n img = img.astype(np.float32)\n h, w, c = img.shape\n img, cr, cb = cv2.split(img)\n \n img=img/255.0\n train_x = np.zeros((1, channels, h, w)).astype(np.float32)\n train_x[0,0,:,:] = img\n\n dataset_torchx = torch.from_numpy(train_x)\n dataset_torchx=dataset_torchx.to(device)\n\n gauss_canny_dataset_input = torch.cat((dataset_torchx, dataset_torchx, dataset_torchx), dim=1)\n\n guass_k_sigma = gauss_net_k_sigma(gauss_canny_dataset_input).to(device)\n guass_k3_sigma = gauss_net_k3_sigma(gauss_canny_dataset_input).to(device)\n guass_k5_sigma = gauss_net_k5_sigma(gauss_canny_dataset_input).to(device)\n\n canny_no_bokeh_batch = Variable(torch.empty([1, channels, h, w])).to(device)\n canny_no_bokeh_batch[0] = canny_net(gauss_canny_dataset_input[0].unsqueeze(0))\n\n output=bokeh_net(dataset_torchx, guass_k_sigma, guass_k3_sigma, guass_k5_sigma, canny_no_bokeh_batch)\n\n output=output*255.0\n output = output.cpu()\n a=output.detach().numpy()\n\n res = a[0,0,:,:]\n\n res = cv2.merge((np.uint8(res), np.uint8(cr), np.uint8(cb)))\n res = cv2.cvtColor(res, cv2.COLOR_YCR_CB2BGR)\n cv2.imwrite(result_dir + str(m),np.uint8(res))\n print('{')\n print('saved image ', str(m), ' at ', str(result_dir))\n print('image height ', str(res.shape[1]))\n print('image width ', str(res.shape[0]))\n print('}\\n')\n\n end = time.time()\n print('Total time taken in secs : '+str(end-st))\n print('Per image (avg): '+ str(float((end-st)/len(total_files))))\n","sub_path":"test_wo_attention.py","file_name":"test_wo_attention.py","file_ext":"py","file_size_in_byte":3887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"243362101","text":"# coding: utf-8\n\nfrom DataModelDict import DataModelDict as DM\n\nfrom potentials.record import PotentialLAMMPS, PotentialLAMMPSKIM\n\ndef Potential(model, name=None, pot_dir=None, kim_id=None):\n \"\"\"\n Class initializer switch for PotentialLAMMPS or PotentialLAMMPSKIM objects.\n\n Parameters\n ----------\n model : str or file-like object\n A JSON/XML data model containing a potential-LAMMPS or a\n potential-LAMMPS-KIM branch.\n name : str, optional\n The record name to use. If not given, this will be set to the\n potential's id.\n pot_dir : str, optional\n The path to a directory containing any artifacts associated with\n the potential. Default value is None, which assumes any required\n files will be in the working directory when LAMMPS is executed.\n kim_id : str, optional\n The full KIM model id indicating the version of a KIM model to use.\n If not given, then the newest known version will be used.\n \n Returns\n -------\n potentials.record.PotentialLAMMPS\n Returned if model contains potential-LAMMPS content.\n potentials.record.PotentialLAMMPSKIM\n Returned if model contains potential-LAMMPS-KIM content.\n \"\"\"\n model = DM(model)\n try:\n # Search for potential-LAMMPS branch\n model.find('potential-LAMMPS')\n except:\n try:\n # Search for potential-LAMMPS-KIM branch\n model.find('potential-LAMMPS-KIM')\n except:\n raise ValueError('Failed to find either potential-LAMMPS or potential-LAMMPS-KIM content')\n else:\n return PotentialLAMMPSKIM(model=model, name=name, id=kim_id)\n else:\n return PotentialLAMMPS(model=model, name=name, pot_dir=pot_dir)","sub_path":"atomman/lammps/Potential.py","file_name":"Potential.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"122201655","text":"# -*- coding: utf-8 -*-:\r\nfrom common import config\r\nfrom elasticsearch import Elasticsearch\r\nfrom common.util.logger import Logger\r\nfrom common.config import config\r\n\r\nclass ESClient(object):\r\n\r\n \"\"\"\r\n Elasticsearch client, used to interact with elasticsearch cluster,\r\n also it can write spark rdd and its higher derivative type like dataframe and so on.\r\n \"\"\"\r\n\r\n def __init__(self, index, type, nodes=None):\r\n self.logger = Logger(self.__class__.__name__).get()\r\n if not nodes:\r\n self.nodes = config.es_hosts\r\n else:\r\n self.nodes = nodes\r\n self.es = Elasticsearch(nodes)\r\n self.es_conf = {}\r\n self.es_conf[\"es.resource\"] = index + \"/\" + type\r\n self.es_conf[\"es.nodes\"] = convertArrayToFlatString(self.nodes)\r\n\r\n def __str__(self):\r\n return \"[ESClient: %s]\" % self.es_conf\r\n\r\n def writeRDD2ES(self, rdd):\r\n try:\r\n rdd.saveAsNewAPIHadoopFile(\r\n path='-',\r\n outputFormatClass=\"org.elasticsearch.hadoop.mr.EsOutputFormat\",\r\n keyClass=\"org.apache.hadoop.io.NullWritable\",\r\n valueClass=\"org.elasticsearch.hadoop.mr.LinkedMapWritable\",\r\n conf=self.es_conf)\r\n except:\r\n self.logger.error(\"Failed to write es(%s)\" % self)\r\n raise\r\n\r\n def writeDF2ES(self, df):\r\n dfRDD = df.rdd.map(lambda row: (None, row.asDict()))\r\n self.writeRDD2ES(dfRDD)\r\n\r\n def createIndex(self):\r\n pass\r\n\r\ndef convertArrayToFlatString(array):\r\n s = \"\"\r\n for i in array:\r\n s += str(i)\r\n s += \",\"\r\n return s[:-1]\r\n","sub_path":"es/es_client.py","file_name":"es_client.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"534301284","text":"#!/usr/bin/python\n# Python\nfrom datetime import datetime\nimport logging\nimport requests\n\n# Libraries\nfrom guildwars2api.v2 import GuildWars2API\n\n# Local\nimport lifestream\n\n\nLifestream = lifestream.Lifestream()\n\nAPIKEY = Lifestream.config.get(\"guildwars2\", \"apikey\")\n\nlogger = logging.getLogger('GW2')\nargs = lifestream.arguments.parse_args()\n\napi = GuildWars2API(\n user_agent=\"Lifestream \",\n api_key=APIKEY)\n\nmy_achivements = api.account_achievements.get()\n\nfetch_list = []\n\nachivements_library = {}\n\nfor achivement in my_achivements:\n if achivement['done']:\n ident = achivement['id']\n fetch_list.append(ident)\n achivements_library[ident] = {}\n achivements_library[ident]['progress'] = achivement\n\nresponse = api.achievements.get(ids=fetch_list)\n\nfor achivement in response:\n ident = achivement['id']\n achivements_library[ident]['info'] = achivement\n\ncategory_list = requests.get(\n \"https://api.guildwars2.com/v2/achievements/categories/\").json()\ncategory_data = {\"ids\": ','.join(str(x) for x in category_list)}\ncategory_fetch = requests.get(\n \"https://api.guildwars2.com/v2/achievements/categories\",\n data=category_data).json()\n\nfor category in category_fetch:\n for achivement_id in category['achievements']:\n if achivement_id in achivements_library:\n achivements_library[achivement_id]['category'] = category\n\nfor ident, achivement in achivements_library.items():\n if not 'info' in achivement:\n continue\n\n icon = False\n if 'icon' in achivement['info']:\n icon = achivement['info']['icon']\n elif \"category\" in achivement:\n icon = achivement['category']['icon']\n else:\n icon = \"https://wiki.guildwars2.com/images/d/d9/Retired_Achievements.png\"\n\n if not icon:\n logger.warn(achivement['info']['name'], \" - has no icon\")\n\n text = achivement['info']['name'] + \" – \" + \\\n achivement['info']['requirement']\n\n# id = hashlib.md5()\n# id.update(text)\n Lifestream.add_entry(\n \"achivement\",\n ident,\n text,\n \"Guild Wars 2\",\n datetime.now(),\n image=icon)\n","sub_path":"imports/gw2.py","file_name":"gw2.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"407666406","text":"import dash\r\nimport dash_core_components as dcc\r\nimport dash_html_components as html\r\nfrom dash.dependencies import Output, Input\r\nimport plotly.graph_objs as go\r\nimport dash_table\r\nimport datetime\r\nimport psycopg2\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\napp = dash.Dash(__name__)\r\nserver = app.server\r\nconn = psycopg2.connect(host=\"dev.vk.edu.ee\", port = 5432, database=\"dbhitsa2019\", user=\"ruuvi_sel\", password=\"ruuvisel\")\r\ncursor = conn.cursor()\r\nquery = \"SELECT * FROM vw_sensorsdata WHERE room='44' ORDER BY date_time DESC\"\r\ndef create_pandas_table(query, database = conn):\r\n table = pd.read_sql_query(query, database)\r\n return table\r\n# Andmetabeli loomine\r\ndf = create_pandas_table(query)\r\ndf[\"sensor\"]=df[\"sensor\"].str.cat(df[[\"valuetype\",\"dimension\"]],sep=\", \")\r\navailable_indicators=df.sensor.unique() \r\navailable_indicators.sort()\r\ndf['date'] = df['date_time'].dt.date\r\n\r\n# Jaotame rakenduse HTML-lehekülg alamjaotusteks div kasutades\r\n\r\napp.layout = html.Div([\r\n html.H3('Sensors Data'), #pealkiri\r\n# Andmetabel HTML-leheküljel \r\n dash_table.DataTable(id='data-table',\r\n page_size=10,\r\n data=df.to_dict('records'),\r\n columns=[{'id': c, 'name': c} for c in df.columns],\r\n fixed_rows={ 'headers': True, 'data': 0 },\r\n style_table={\r\n 'maxHeight': '400px',\r\n 'overflowY': 'scroll',\r\n 'overflowX': 'scroll'\r\n },\r\n style_cell={\r\n 'width': '150px'\r\n }\r\n),\r\nhtml.Div([dcc.Dropdown(\r\n id='indicator',\r\n options=[{'label': i, 'value': i} for i in available_indicators],\r\n value=available_indicators[0])],\r\n style={'padding': '100px 20px 20px 20px'}),\r\nhtml.Div([\r\n html.Div([dcc.Graph( # esimene graafik - mõõtmistulemuste voog\r\n id='graph-1'),\r\n ], style={'display': 'inline-block', 'width': '49%', 'padding': '0 0'}),\r\n\r\n html.Div([dcc.Graph( # teine graafik - päevakeskmised\r\n id='graph-2')],\r\n style={'display': 'inline-block', 'width': '49%', 'float': 'right'})\r\n], style={'padding': '20px 20px 20px 20px'})\r\n])\r\n\r\n@app.callback([Output('graph-1', 'figure'),\r\n Output('graph-2', 'figure')],\r\n [Input('indicator', 'value')])\r\n\r\ndef update_graphs(indicator):\r\n title='Current Data'\r\n layout = go.Layout(title=title, title_x=0.5)\r\n data1=[go.Scatter(x=df[df['sensor']==indicator].date_time[0:20], \r\n y=df[df['sensor']==indicator].data[0:20])]\r\n figure1=go.Figure(data=data1, layout=layout)\r\n table1=df[df['sensor']==indicator].loc[:,['date','data']].groupby(['date']).mean()\r\n data2=[go.Bar(x=table1.data.index, y=table1.data)]\r\n title2='Day Average'\r\n layout2 = go.Layout(title=title2, title_x=0.5)\r\n figure2 = go.Figure(data=data2, layout=layout2);\r\n return [figure1, figure2]\r\n \r\n\r\nif __name__ == '__main__':\r\n app.run_server(debug=True)\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"132507425","text":"from torch import optim\nimport matplotlib.pyplot as plt\n\nfrom feeder.feeder import Feeder\nimport torch.nn as nn\nimport numpy as np\nfrom tqdm import tqdm\nimport torch\nimport torch.utils.data\n\nfrom net.mlp import *\n\n\nclass Processor:\n def __init__(self, train_data_path, train_label_path, test_data_path, test_label_path):\n self.acc = []\n self.loader = {}\n self.loader['train'] = torch.utils.data.DataLoader(\n dataset=Feeder(train_data_path, train_label_path),\n batch_size=128,\n shuffle=True,\n num_workers=4,\n drop_last=True)\n self.loader['test'] = torch.utils.data.DataLoader(\n dataset=Feeder(test_data_path, test_label_path),\n batch_size=128,\n shuffle=True,\n num_workers=4,\n drop_last=True)\n self.loss = nn.CrossEntropyLoss()\n # self.dev = torch.device('cpu')\n self.dev = torch.device('cuda:1')\n self.model = MLP2().to(self.dev)\n self.optimizer = optim.SGD(\n self.model.parameters(),\n lr=0.1,\n momentum=0.9,\n nesterov=True,\n weight_decay=0.0001)\n self.scheduler = torch.optim.lr_scheduler.StepLR(self.optimizer, step_size=20, gamma=0.1)\n\n def train(self, epoch=50):\n self.model.train()\n loss_res = []\n\n pbar = tqdm(range(epoch))\n for i in pbar:\n if i%5 == 0:\n self.test()\n # local_loss = []\n for data, label in self.loader['train']:\n # get data\n data = data.float().to(self.dev)\n label = label.long().to(self.dev)\n\n y = self.model(data)\n loss = self.loss(y, label)\n\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n # local_loss.append(loss.item())\n self.scheduler.step()\n # loss_res.append(np.mean(local_loss))\n print(loss_res)\n\n def show_topk(self, k):\n rank = self.result.argsort()\n hit_top_k = [l in rank[i, -k:] for i, l in enumerate(self.label)]\n accuracy = sum(hit_top_k) * 1.0 / len(hit_top_k)\n self.acc.append(accuracy)\n print('\\tTop{}: {:.2f}%'.format(k, 100 * accuracy))\n\n def test(self, evaluation=True):\n self.model.eval()\n loader = self.loader['test']\n loss_value = []\n result_frag = []\n label_frag = []\n\n for data, label in loader:\n data = data.float().to(self.dev)\n label = label.long().to(self.dev)\n\n with torch.no_grad():\n output = self.model(data)\n\n result_frag.append(output.cpu().numpy())\n if evaluation:\n with torch.no_grad():\n loss = self.loss(output, label)\n loss_value.append(loss.item())\n label_frag.append(label.data.cpu().numpy())\n\n self.result = np.concatenate(result_frag)\n if evaluation:\n self.label = np.concatenate(label_frag)\n # show top-k accuracy\n # 可能性在前k位均视为正确\n for k in [1]:\n self.show_topk(k)\n\n\n\ntrain_data_path = './data/train_feature.pkl'\ntrain_label_path = './data/train_label3.pkl'\ntest_data_path = './data/test_feature.pkl'\ntest_label_path = './data/test_label3.pkl'\np = Processor(train_data_path, train_label_path, test_data_path, test_label_path)\np.train(61)\n\nprint(p.acc)","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"547570601","text":"import statistics as st\n\nres = 1000000\n\ngen, imp = 0, 0\ngenuine = [0]*(res+1)\nimposter = [0]*(res+1)\ngenuine_score = []\nimposter_score = []\n\ninfile = open('L4.txt')\nfor lineNo in infile:\n\ttemp = lineNo.split('\\t')\n\tline = (float(temp[5][:-1]), int(temp[4]))\n\n\tif line[1] == 1:\n\t\tgen += 1\n\t\tgenuine[int(line[0]*res)] += 1\n\t\tgenuine_score.append(line[0])\n\telse:\n\t\timp += 1\n\t\timposter[int(line[0]*res)] += 1\n\t\timposter_score.append(line[0])\n\nprint(len(genuine_score), st.mean(genuine_score), st.stdev(genuine_score))\nprint(len(imposter_score), st.mean(imposter_score), st.stdev(imposter_score))\n\nfor i in range(len(genuine)):\n\tif genuine[i]:\n\t\tprint(i, genuine[i])\n\nfor i in range(len(imposter)):\n\tif imposter[i]:\n\t\tprint(i, imposter[i])\t\t\n\nfor i in range(1, res+1):\n\tgenuine[res-i] += genuine[res-i+1]\n\timposter[i] += imposter[i-1]\n\nfor i in range(len(genuine)):\n\tgenuine[i] /= gen\n\timposter[i] /= imp\n\nfor i in range(len(genuine)):\n\tprint(i/res, '\\t', genuine[i]*100, '\\t', imposter[i]*100)\n\nfinal = []\nfor i in range(res+1):\n\tfinal.append(abs(genuine[i]-imposter[i]))\n\nthreshold = final.index(min(final))\nerrG = genuine[threshold]\nerrI = imposter[threshold]\ndiff = final[threshold]\n\nprint(threshold, errG, errI, diff)\n\n","sub_path":"System Practicum/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"363337508","text":"from django.urls import path\nfrom django.contrib.auth.views import LoginView, LogoutView\n\napp_name = \"auth\"\n\nurlpatterns = [\n path(\n \"login/\",\n LoginView.as_view(\n template_name=\"login/login.html\",\n redirect_authenticated_user=True\n ),\n name=\"login\"\n ),\n path(\"logout/\", LogoutView.as_view(), name=\"logout\"),\n]","sub_path":"login/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"269312015","text":"#Open file with r = read or w = write\nnfile = open(somefile.txt,r)\n\n#When a for loop is run against a file it runs one time for each LINE in the file\nfor i in nfile:\n print(i)\n\n#Count the lines\ncount = 0\nfor i in nfile:\n count = count + 1\nprint(\"There are: \",count, \"lines\")\n\n#To get a count of characters in the file\nnfile = open(somefile.txt,r)\nchr = nfile.read()\nprint(len(chr))\n#Output - some number of characters in the file\n\n#You can also slice with this command\nnfile = open(somefile.txt,r)\nchr = nfile.read()\nprint(chr[:20])\n#Output - The first 20 characters from the file\n\n#Using the \"startswith\" method\nnfile = open(somefile.txt)\nfor i in nfile:\n if i.startswith('From:'):\n print(line)\n\n#Opening a file, finding specific lines and stripping whitespace to keep from seeing extra blank lines\nnfile = open(something.txt)\nfor i in nfile:\n i = i.rstrip()\n if i.startswith('From'):\n print(i)\n\n\n#This will produce the same output, but will skip all lines that don't start with \"From\nnfile = open(something.txt)\nfor i in nfile:\n i = i.rstrip()\n if not i.startswith('From'):\n continue\n print(i)\n\n\n#All of these functions will work by prompting for filename\nofile = input(\"What is the file name: \")\nnfile = open(ofile)\nfor i in nfile:\n i = i.rstrip()\n if i.startswith('From'):\n print(i)","sub_path":"OnlineClasses/Programming for Everybody/Class2/open_manipulate_files.py","file_name":"open_manipulate_files.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"502592779","text":"from typing import Sequence\n\nimport hail as hl\nfrom hail.expr import ArrayExpression, expr_any, expr_array, expr_interval\nfrom hail.matrixtable import MatrixTable\nfrom hail.methods.misc import require_first_key_field_locus\nfrom hail.table import Table\nfrom hail.typecheck import sequenceof, typecheck\nfrom hail.utils.java import Env\nfrom hail.utils.misc import divide_null\nfrom hail.vds.variant_dataset import VariantDataset\nfrom hail import ir\n\n\ndef write_variant_datasets(vdss, paths, overwrite=False, stage_locally=False):\n \"\"\"Write many `vdses` to their corresponding path in `paths`.\"\"\"\n ref_writer = ir.MatrixNativeMultiWriter([f\"{p}/reference_data\" for p in paths], overwrite, stage_locally)\n var_writer = ir.MatrixNativeMultiWriter([f\"{p}/variant_data\" for p in paths], overwrite, stage_locally)\n Env.backend().execute(ir.MatrixMultiWrite([vds.reference_data._mir for vds in vdss], ref_writer))\n Env.backend().execute(ir.MatrixMultiWrite([vds.variant_data._mir for vds in vdss], var_writer))\n\n\n@typecheck(vds=VariantDataset)\ndef to_dense_mt(vds: 'VariantDataset') -> 'MatrixTable':\n \"\"\"Creates a single, dense :class:`.MatrixTable` from the split\n :class:`.VariantDataset` representation.\n\n Parameters\n ----------\n vds : :class:`.VariantDataset`\n Dataset in VariantDataset representation.\n\n Returns\n -------\n :class:`.MatrixTable`\n Dataset in dense MatrixTable representation.\n \"\"\"\n ref = vds.reference_data\n ref = ref.drop(*(x for x in ('alleles', 'rsid') if x in ref.row))\n var = vds.variant_data\n refl = ref.localize_entries('_ref_entries')\n varl = var.localize_entries('_var_entries', '_var_cols')\n varl = varl.annotate(_variant_defined=True)\n joined = refl.join(varl.key_by('locus'), how='outer')\n dr = joined.annotate(\n dense_ref=hl.or_missing(\n joined._variant_defined,\n hl.scan._densify(hl.len(joined._var_cols), joined._ref_entries)\n )\n )\n dr = dr.filter(dr._variant_defined)\n\n def coalesce_join(ref, var):\n\n call_field = 'GT' if 'GT' in var else 'LGT'\n assert call_field in var, var.dtype\n\n merged_fields = {}\n merged_fields[call_field] = hl.coalesce(var[call_field], hl.call(0, 0))\n for field in ref.dtype:\n if field in var:\n merged_fields[field] = hl.coalesce(var[field], ref[field])\n\n return hl.struct(**merged_fields).annotate(**{f: var[f] for f in var if f not in merged_fields})\n\n dr = dr.annotate(\n _dense=hl.zip(dr._var_entries, dr.dense_ref).map(\n lambda tuple: coalesce_join(hl.or_missing(tuple[1].END <= dr.locus.position, tuple[1]), tuple[0])\n )\n )\n dr = dr._key_by_assert_sorted('locus', 'alleles')\n dr = dr.drop('_var_entries', '_ref_entries', 'dense_ref', '_variant_defined')\n return dr._unlocalize_entries('_dense', '_var_cols', list(var.col_key))\n\n\n@typecheck(vds=VariantDataset)\ndef to_merged_sparse_mt(vds: 'VariantDataset') -> 'MatrixTable':\n \"\"\"Creates a single, merged sparse :class:'.MatrixTable' from the split\n :class:`.VariantDataset` representation.\n\n Parameters\n ----------\n vds : :class:`.VariantDataset`\n Dataset in VariantDataset representation.\n\n Returns\n -------\n :class:`.MatrixTable`\n Dataset in the merged sparse MatrixTable representation.\n \"\"\"\n rht = vds.reference_data.localize_entries('_ref_entries', '_ref_cols')\n vht = vds.variant_data.localize_entries('_var_entries', '_var_cols')\n\n # drop 'alleles' key for join\n vht = vht.key_by('locus')\n\n merged_schema = {}\n for e in vds.variant_data.entry:\n merged_schema[e] = vds.variant_data[e].dtype\n\n for e in vds.reference_data.entry:\n if e in merged_schema:\n if not merged_schema[e] == vds.reference_data[e].dtype:\n raise TypeError(f\"cannot unify field {e!r}: {merged_schema[e]}, {vds.reference_data[e].dtype}\")\n else:\n merged_schema[e] = vds.reference_data[e].dtype\n\n ht = rht.join(vht, how='outer').drop('_ref_cols')\n\n def merge_arrays(r_array, v_array):\n\n def rewrite_ref(r):\n ref_block_selector = {}\n for k, t in merged_schema.items():\n if k == 'LA':\n ref_block_selector[k] = hl.literal([0])\n elif k in ('LGT', 'GT'):\n ref_block_selector[k] = hl.call(0, 0)\n else:\n ref_block_selector[k] = r[k] if k in r else hl.missing(t)\n return r.select(**ref_block_selector)\n\n def rewrite_var(v):\n return v.select(**{\n k: v[k] if k in v else hl.missing(t)\n for k, t in merged_schema.items()\n })\n\n return hl.case() \\\n .when(hl.is_missing(r_array), v_array.map(rewrite_var)) \\\n .when(hl.is_missing(v_array), r_array.map(rewrite_ref)) \\\n .default(hl.zip(r_array, v_array).map(lambda t: hl.coalesce(rewrite_var(t[1]), rewrite_ref(t[0]))))\n\n ht = ht.select(\n alleles=hl.coalesce(ht['alleles'], hl.array([ht['ref_allele']])),\n # handle cases where vmt is not keyed by alleles\n **{k: ht[k] for k in vds.variant_data.row_value if k != 'alleles'},\n _entries=merge_arrays(ht['_ref_entries'], ht['_var_entries'])\n )\n ht = ht._key_by_assert_sorted('locus', 'alleles')\n return ht._unlocalize_entries('_entries', '_var_cols', list(vds.variant_data.col_key))\n\n\n@typecheck(vds=VariantDataset, name=str, gq_bins=sequenceof(int))\ndef sample_qc(vds: 'VariantDataset', *, name='sample_qc', gq_bins: 'Sequence[int]' = (0, 20, 60)) -> 'Table':\n \"\"\"Run sample_qc on dataset in the split :class:`.VariantDataset` representation.\n\n Parameters\n ----------\n vds : :class:`.VariantDataset`\n Dataset in VariantDataset representation.\n name : :obj:`str`\n Name for resulting field.\n gq_bins : :class:`tuple` of :obj:`int`\n Tuple containing cutoffs for genotype quality (GQ) scores.\n\n Returns\n -------\n :class:`.Table`\n Hail Table of results, keyed by sample.\n \"\"\"\n\n require_first_key_field_locus(vds.reference_data, 'sample_qc')\n require_first_key_field_locus(vds.variant_data, 'sample_qc')\n\n from hail.expr.functions import _num_allele_type, _allele_types\n\n allele_types = _allele_types[:]\n allele_types.extend(['Transition', 'Transversion'])\n allele_enum = {i: v for i, v in enumerate(allele_types)}\n allele_ints = {v: k for k, v in allele_enum.items()}\n\n def allele_type(ref, alt):\n return hl.bind(\n lambda at: hl.if_else(at == allele_ints['SNP'],\n hl.if_else(hl.is_transition(ref, alt),\n allele_ints['Transition'],\n allele_ints['Transversion']),\n at),\n _num_allele_type(ref, alt)\n )\n\n variant_ac = Env.get_uid()\n variant_atypes = Env.get_uid()\n\n vmt = vds.variant_data\n if 'GT' not in vmt.entry:\n vmt = vmt.annotate_entries(GT=hl.experimental.lgt_to_gt(vmt.LGT, vmt.LA))\n\n vmt = vmt.annotate_rows(**{\n variant_ac: hl.agg.call_stats(vmt.GT, vmt.alleles).AC,\n variant_atypes: vmt.alleles[1:].map(lambda alt: allele_type(vmt.alleles[0], alt))\n })\n\n bound_exprs = {}\n\n bound_exprs['n_het'] = hl.agg.count_where(vmt['GT'].is_het())\n bound_exprs['n_hom_var'] = hl.agg.count_where(vmt['GT'].is_hom_var())\n bound_exprs['n_singleton'] = hl.agg.sum(\n hl.sum(hl.range(0, vmt['GT'].ploidy).map(lambda i: vmt[variant_ac][vmt['GT'][i]] == 1))\n )\n\n bound_exprs['allele_type_counts'] = hl.agg.explode(\n lambda allele_type: hl.tuple(\n hl.agg.count_where(allele_type == i) for i in range(len(allele_ints))\n ),\n (hl.range(0, vmt['GT'].ploidy)\n .map(lambda i: vmt['GT'][i])\n .filter(lambda allele_idx: allele_idx > 0)\n .map(lambda allele_idx: vmt[variant_atypes][allele_idx - 1]))\n )\n\n gq_exprs = hl.agg.filter(\n hl.is_defined(vmt.GT),\n hl.struct(**{f'gq_over_{x}': hl.agg.count_where(vmt.GQ > x) for x in gq_bins})\n )\n\n result_struct = hl.rbind(\n hl.struct(**bound_exprs),\n lambda x: hl.rbind(\n hl.struct(**{\n 'gq_exprs': gq_exprs,\n 'n_het': x.n_het,\n 'n_hom_var': x.n_hom_var,\n 'n_non_ref': x.n_het + x.n_hom_var,\n 'n_singleton': x.n_singleton,\n 'n_snp': (x.allele_type_counts[allele_ints['Transition']]\n + x.allele_type_counts[allele_ints['Transversion']]),\n 'n_insertion': x.allele_type_counts[allele_ints['Insertion']],\n 'n_deletion': x.allele_type_counts[allele_ints['Deletion']],\n 'n_transition': x.allele_type_counts[allele_ints['Transition']],\n 'n_transversion': x.allele_type_counts[allele_ints['Transversion']],\n 'n_star': x.allele_type_counts[allele_ints['Star']]\n }),\n lambda s: s.annotate(\n r_ti_tv=divide_null(hl.float64(s.n_transition), s.n_transversion),\n r_het_hom_var=divide_null(hl.float64(s.n_het), s.n_hom_var),\n r_insertion_deletion=divide_null(hl.float64(s.n_insertion), s.n_deletion)\n )\n )\n )\n variant_results = vmt.select_cols(**result_struct).cols()\n\n rmt = vds.reference_data\n ref_results = rmt.select_cols(\n gq_exprs=hl.struct(**{\n f'gq_over_{x}': hl.agg.filter(rmt.GQ > x, hl.agg.sum(1 + rmt.END - rmt.locus.position)) for x in gq_bins\n })\n ).cols()\n\n joined = ref_results[variant_results.key].gq_exprs\n joined_results = variant_results.transmute(**{\n f'gq_over_{x}': variant_results.gq_exprs[f'gq_over_{x}'] + joined[f'gq_over_{x}'] for x in gq_bins\n })\n return joined_results\n\n\n@typecheck(vds=VariantDataset, samples_table=Table, keep=bool, remove_dead_alleles=bool)\ndef filter_samples(vds: 'VariantDataset', samples_table: 'Table', *,\n keep: bool = True,\n remove_dead_alleles: bool = False) -> 'VariantDataset':\n \"\"\"Filter samples in a :class:`.VariantDataset`.\n\n Parameters\n ----------\n vds : :class:`.VariantDataset`\n Dataset in VariantDataset representation.\n samples_table : :class:`.Table`\n Samples to filter on.\n keep : :obj:`bool`\n Whether to keep (default), or filter out the samples from `samples_table`.\n remove_dead_alleles : :obj:`bool`\n If true, remove alleles observed in no samples. Alleles with AC == 0 will be\n removed, and LA values recalculated.\n\n Returns\n -------\n :class:`.VariantDataset`\n \"\"\"\n if not list(samples_table[x].dtype for x in samples_table.key) == [hl.tstr]:\n raise TypeError(f'invalid key: {samples_table.key.dtype}')\n samples_to_keep = samples_table.aggregate(hl.agg.collect_as_set(samples_table.key[0]), _localize=False)._persist()\n reference_data = vds.reference_data.filter_cols(samples_to_keep.contains(vds.reference_data.col_key[0]), keep=keep)\n reference_data = reference_data.filter_rows(hl.agg.count() > 0)\n variant_data = vds.variant_data.filter_cols(samples_to_keep.contains(vds.variant_data.col_key[0]), keep=keep)\n\n if remove_dead_alleles:\n vd = variant_data\n vd = vd.annotate_rows(__allele_counts=hl.agg.explode(lambda x: hl.agg.counter(x), vd.LA), __n=hl.agg.count())\n vd = vd.filter_rows(vd.__n > 0)\n\n vd = vd.annotate_rows(__kept_indices=hl.dict(\n hl.enumerate(\n hl.range(hl.len(vd.alleles)).filter(lambda idx: (idx == 0) | (vd.__allele_counts.get(idx, 0) > 0)),\n index_first=False)))\n\n vd = vd.annotate_rows(\n __old_to_new_LA=hl.range(hl.len(vd.alleles)).map(lambda idx: vd.__kept_indices.get(idx, -1)))\n\n def new_la_index(old_idx):\n raw_idx = vd.__old_to_new_LA[old_idx]\n return hl.case().when(raw_idx >= 0, raw_idx) \\\n .or_error(\"'filter_samples': unexpected local allele: old index=\" + hl.str(old_idx))\n\n vd = vd.annotate_entries(LA=vd.LA.map(lambda la: new_la_index(la)))\n vd = vd.key_rows_by('locus')\n vd = vd.annotate_rows(alleles=vd.__kept_indices.keys().map(lambda i: vd.alleles[i]))\n vd = vd._key_rows_by_assert_sorted('locus', 'alleles')\n vd = vd.drop('__allele_counts', '__kept_indices', '__old_to_new_LA')\n return VariantDataset(reference_data, vd)\n\n variant_data = variant_data.filter_rows(hl.agg.count() > 0)\n return VariantDataset(reference_data, variant_data)\n\n\n@typecheck(vds=VariantDataset, variants_table=Table, keep=bool)\ndef filter_variants(vds: 'VariantDataset', variants_table: 'Table', *, keep: bool = True) -> 'VariantDataset':\n \"\"\"Filter variants in a :class:`.VariantDataset`, without removing reference\n data.\n\n Parameters\n ----------\n vds : :class:`.VariantDataset`\n Dataset in VariantDataset representation.\n variants_table : :class:`.Table`\n Variants to filter on.\n keep: :obj:`bool`\n Whether to keep (default), or filter out the variants from `variants_table`.\n\n Returns\n -------\n :class:`.VariantDataset`.\n \"\"\"\n if keep:\n variant_data = vds.variant_data.semi_join_rows(variants_table)\n else:\n variant_data = vds.variant_data.anti_join_rows(variants_table)\n return VariantDataset(vds.reference_data, variant_data)\n\n\n@typecheck(vds=VariantDataset, intervals=expr_array(expr_interval(expr_any)), keep=bool)\ndef filter_intervals(vds: 'VariantDataset', intervals: 'ArrayExpression', *, keep: bool = False) -> 'VariantDataset':\n \"\"\"Filter intervals in a :class:`.VariantDataset` (only on variant data for\n now).\n\n Parameters\n ----------\n vds : :class:`.VariantDataset`\n Dataset in VariantDataset representation.\n intervals : :class:`.ArrayExpression` of type :class:`.tinterval`\n Intervals to filter on.\n keep : :obj:`bool`\n Whether to keep, or filter out (default) rows that fall within any\n interval in `intervals`.\n\n Returns\n -------\n :class:`.VariantDataset`\n \"\"\"\n # for now, don't touch reference data.\n # should remove large regions and scan forward ref blocks to the start of the next kept region\n variant_data = hl.filter_intervals(vds.variant_data, intervals, keep)\n return VariantDataset(vds.reference_data, variant_data)\n\n\n@typecheck(vds=VariantDataset, filter_changed_loci=bool)\ndef split_multi(vds: 'VariantDataset', *, filter_changed_loci: bool = False) -> 'VariantDataset':\n \"\"\"Split the multiallelic variants in a :class:`.VariantDataset`.\n\n Parameters\n ----------\n vds : :class:`.VariantDataset`\n Dataset in VariantDataset representation.\n filter_changed_loci : :obj:`bool`\n If any REF/ALT pair changes locus under :func:`.min_rep`, filter that\n variant instead of throwing an error.\n\n Returns\n -------\n :class:`.VariantDataset`\n \"\"\"\n variant_data = hl.experimental.sparse_split_multi(vds.variant_data, filter_changed_loci=filter_changed_loci)\n return VariantDataset(vds.reference_data, variant_data)\n","sub_path":"hail/python/hail/vds/methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":15309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"395094239","text":"# Import smtplib (to allow us to email)\nimport smtplib\n# set the 'from' address,\nfromaddr = 'interviewnotifier@gmail.com\"'\n# set the 'to' addresses,\ntoaddr = ['sarkersantanu@gmail.com']\n#subject\nsubj = \"Google - Pick a interview Slot\"\n#today's date\ndate = \"date\"\n#body\nmessage_text = \"Congrats!\\nYou got a interview with: xxx company\\nGood luck!\\n\"\n#final message\nmsg = \"From: %s\\nTo: %s\\nSubject: %s\\nDate: %s\\n\\n%s\" % ( fromaddr, toaddr, subj, date, message_text )\n\n# setup the email server,\nserver = smtplib.SMTP('smtp.gmail.com', 587)\nserver.ehlo()\nserver.starttls()\n# add my account login name and password,\nserver.login(\"interviewnotifier@gmail.com\", \"4G126E6w6Eg1BBW\")\n\n# Print the email's contents\nprint('From: ' + fromaddr)\nprint('To: ' + str(toaddr))\nprint('Message: ' + msg)\n\n# send the email\nserver.sendmail(fromaddr, toaddr, msg)\n# disconnect from the server\nserver.quit()\n","sub_path":"emailSender.py","file_name":"emailSender.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"323255248","text":"from .handlers import UnitsQueryHandler\nfrom .handlers import CalculatorQueryHandler\nfrom .handlers import CurrencyQueryHandler\nfrom .handlers import PercentagesQueryHandler\nfrom .handlers import TimeQueryHandler\nfrom .handlers import (\n Base16QueryHandler, Base10QueryHandler,\n Base2QueryHandler, Base8QueryHandler\n)\nfrom ..utils import Singleton\n\nclass QueryHandler(metaclass=Singleton):\n def __init__(self):\n self._handlers = [\n UnitsQueryHandler(),\n CalculatorQueryHandler(),\n CurrencyQueryHandler(),\n PercentagesQueryHandler(),\n TimeQueryHandler(),\n Base10QueryHandler(),\n Base16QueryHandler(),\n Base8QueryHandler(),\n Base2QueryHandler()\n ]\n\n def handle(self, query, *handlers, return_raw=False):\n handlers = set(handlers)\n results = []\n for handler in self._handlers:\n if handlers and not handler.__class__ in handlers:\n continue\n result = handler.handle(query)\n if not result:\n continue\n if not return_raw:\n result = map(lambda r: r.to_query_result(), result)\n results.extend(result)\n\n return sorted(results, key=lambda result: result.order)\n","sub_path":"calculate_anything/query/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"377102850","text":"\"\"\"\nPerforms the actual calculations concerning usage and the resulting credit 'billing'\n\"\"\"\nfrom __future__ import annotations\n\nfrom asyncio import CancelledError\nfrom asyncio import Lock\nfrom asyncio import Queue\nfrom asyncio import shield\nfrom decimal import Decimal\nfrom typing import Dict\nfrom typing import cast\n\nfrom aiohttp.web import Application\n\nfrom os_credits.influx.client import InfluxDBClient\nfrom os_credits.log import TASK_ID\nfrom os_credits.log import task_logger\nfrom os_credits.notifications import EmailNotificationBase\nfrom os_credits.notifications import HalfOfCreditsLeft\nfrom os_credits.notifications import send_notification\nfrom os_credits.perun.exceptions import DenbiCreditsUsedMissing\nfrom os_credits.perun.exceptions import GroupNotExistsError\nfrom os_credits.perun.group import Group\nfrom os_credits.prometheus_metrics import worker_exceptions_counter\nfrom os_credits.settings import config\n\nfrom .base_models import Credits\nfrom .base_models import UsageMeasurement\nfrom .billing import calculate_credits\nfrom .models import BillingHistory\nfrom .models import measurement_by_name\n\n\ndef unique_identifier(influx_line: str) -> str:\n \"\"\"Hashes the passed Influx Line and returns an unique ID.\n\n Used to uniquely identify all log messages related to one specific Influx Line.\n Needed since multiple ones are processed in parallel to the logs are scattered. Used\n as :ref:`Logging`.\n\n :param influx_line: String to hash\n :return: Unique ID consisting of 12 numbers\n \"\"\"\n # insert leading zeros if less numbers than 12 but don't use more\n return format(abs(hash(influx_line)), \">012\")[:12]\n\n\nasync def worker(name: str, app: Application) -> None:\n \"\"\"Worker task to process Influx Lines put into the :ref:`Task Queue` by the\n ``/write`` endpoint(:func:`~os_credits.views.influxdb_write`).\n\n Runs inside a ``while True`` loop, and blocks until it retrieves an item from the\n :ref:`Task Queue`.\n\n #. Calls :func:`unique_identifier` to generate a unique ID for the Influx Line\n #. Shields :func:`process_influx_line` by wrapping it in :func:`~asyncio.shield`.\n Must be shielded since the attributes of group objects are retrieved and saved\n with two separate calls to *Perun*. The task **must not** be cancelled between\n the two ``save`` calls.\n #. In case exceptions raised when processing the item or when sending the\n notification log it properly.\n #. Finally, in every case, signal to the queue that the task has been processed.\n\n\n :param name: Name of this worker used for logging\n :param app: Application instance holding the helper class instances\n \"\"\"\n group_locks = cast(Dict[str, Lock], app[\"group_locks\"])\n task_queue = cast(Queue, app[\"task_queue\"])\n while True:\n try:\n influx_line: str = await task_queue.get()\n except CancelledError:\n task_logger.info(\"Worker %s was cancelled when waiting for new item.\", name)\n raise\n try:\n task_id = unique_identifier(influx_line)\n TASK_ID.set(task_id)\n task_logger.debug(\"Worker %s starting task `%s`\", name, task_id)\n\n # do not cancel a running task\n await shield(process_influx_line(influx_line, app, group_locks))\n task_logger.debug(\n \"Worker %s finished task `%s` successfully\", name, task_id\n )\n # necessary since the tasks must continue working despite any exceptions that\n # occurred\n except CancelledError:\n raise\n except Exception as e:\n worker_exceptions_counter.inc()\n task_logger.exception(\n \"Worker %s exited task with unhandled exception: %s, stacktrace \"\n \"attached\",\n name,\n e,\n )\n finally:\n task_queue.task_done()\n\n\nasync def process_influx_line(\n influx_line: str, app: Application, group_locks: Dict[str, Lock]\n) -> None:\n \"\"\"Performs all preliminary task before actually billing a Group/Project.\n\n #. Determine whether the passed item/str/Influx Line is billable/needed\n #. Deserialize it into a :class:`~os_credits.models.UsageMeasurement` by calling\n :func:`~os_credits.credits.models.measurement_by_name`, see :ref:`Metrics and\n Measurements`.\n #. Create a :class:`~os_credits.perun.group.Group` object, see :ref:`Perun`.\n #. If a project whitelist is set in :ref:`Settings`, see whether the group is part\n of it\n #. Calls :func:`update_credits` once the correct :ref:`lock ` could be\n acquired. Catch every notification, see :ref:`Notifications`, and send it.\n\n :param influx_line: String/Influx Line to process\n :param app: Application object holding our helper class instances\n :param group_locks: Dictionary with :ref:`Group Locks`\n \"\"\"\n task_logger.debug(\"Processing Influx Line `%s`\", influx_line)\n # we want to end this task as quickly as possible if the InfluxDB Point is not\n # needed\n try:\n measurement_class = measurement_by_name(influx_line)\n except ValueError:\n task_logger.debug(\"Ignoring since the measurement is not needed/billable\")\n return\n try:\n measurement = measurement_class.from_lineprotocol(influx_line)\n except (KeyError, ValueError):\n task_logger.exception(\n \"Could not convert influx line %s to UsageMeasurement. Appending \"\n \"stacktrace\",\n influx_line,\n )\n return\n perun_group = Group(measurement.project_name, measurement.location_id)\n if (\n config[\"OS_CREDITS_PROJECT_WHITELIST\"] is not None\n and perun_group.name not in config[\"OS_CREDITS_PROJECT_WHITELIST\"]\n ):\n task_logger.info(\n \"Group `%s` is not part of given whitelist (%s). Ignoring measurement\",\n perun_group.name,\n config[\"OS_CREDITS_PROJECT_WHITELIST\"],\n )\n return\n task_logger.info(\n \"Processing UsageMeasurement `%s` - Group `%s`\", measurement, perun_group\n )\n task_logger.debug(\"Awaiting async lock for Group %s\", perun_group.name)\n try:\n # since group_locks is a defaultdict a new Lock is automatically created if\n # necessary\n async with group_locks[perun_group.name]:\n task_logger.debug(\"Acquired async lock for Group %s\", perun_group.name)\n await update_credits(perun_group, measurement, app)\n except EmailNotificationBase as notification:\n task_logger.info(\"Sending notification %s\", notification)\n await send_notification(notification)\n\n\nasync def update_credits(\n group: Group, current_measurement: UsageMeasurement, app: Application\n) -> None:\n \"\"\"Evaluates the measurement and decides what to do.\n\n #. Connect the :ref:`group `\n #. If the amount of used credits is not set yet:\n\n #. If no timestamp of the metric of the current measurement exists this group has\n never been billed before. Initialize the used credits with 0.\n #. If a timestamp exists the group **must** have been billed before and the\n absence of ``credits_used`` is an error in which case\n :exc:`~os_credits.exceptions.DenbiCreditsUsedMissing` is raised.\n #. If the metric has not been billed before store the timestamp of the current\n measurement and send the values to *Perun*.\n #. Retrieve previous measurements of this group and metric especially the one whose\n timestamp is stored in the group. Perform additional tests to make sure that we\n can continue billing this group and metric.\n #. Call :func:`~os_credits.credits.billing.calculate_credits` to let the\n metric calculate how many credits should be billed for the current measurement.\n #. In case of a positive amount of credits to bill do so, store the timestamp of\n current measurement inside the group, create an entry for the :ref:`Credits\n History` and send the changed group attributes to *Perun*.\n\n When taking a look at the test coverage under ``htmlcov/tests/index.html`` this file\n should have a very high value. Whenever you add a corner case or just another simple\n if statement **write a test for it**!\n\n .. todo::\n\n Metrics should decide how to react to a value change, the current behaviour is\n tied to TotalUsageMetrics! Idea: Something like `raise ProceedWithoutBilling` in\n case of a lower value which might be related to a change of the **start**\n parameter of the *OpenStack Usage Exporter*.\n\n :param group: Group whose measurement is processed - Unconnected\n :param current_measurement: Current measurement to process\n :param app: Application instance holding the helper class instances\n :raises EmailNotificationBase: Subclasses of it which are actual notifications can\n be raised throughout the whole codebase.\n :raise DenbiCreditsUsedMissing: See documentation above.\n \"\"\"\n try:\n await group.connect()\n except GroupNotExistsError as e:\n task_logger.warning(\n \"Could not resolve group with name `%s` against perun. %r\", group.name, e\n )\n return\n if group.credits_used.value is None:\n # let's check whether any measurement timestamps are present, if so we are\n # having a problem since this means that this group has been processed before!\n if group.credits_timestamps.value:\n raise DenbiCreditsUsedMissing(\n f\"Group {group.name} has non-empty credits_timestamps and therefore \"\n \"processed before but is missing `credits_used` now. \"\n \"Did someone modify the values by hand? Aborting\"\n )\n else:\n task_logger.info(\n \"Group %s does not have `credits_used` and hasn't been billed before: \"\n \"Initialising with 0\",\n group,\n )\n group.credits_used.value = Decimal(0)\n try:\n last_measurement_timestamp = group.credits_timestamps.value[\n current_measurement.measurement\n ]\n except KeyError:\n task_logger.info(\n \"Group %s has no timestamp of most recent measurement of %s. \"\n \"Setting it to the timestamp of the current measurement.\",\n group,\n current_measurement.measurement,\n )\n # set timestamp of current measurement so we can start billing the group once\n # the next measurements are submitted\n group.credits_timestamps.value[\n current_measurement.measurement\n ] = current_measurement.timestamp\n await group.save()\n return\n task_logger.debug(\n \"Last time credits were billed: %s\",\n group.credits_timestamps.value[current_measurement.measurement],\n )\n\n if current_measurement.timestamp <= last_measurement_timestamp:\n task_logger.warning(\n \"Current measurement is not more recent than the last measurement. HOW? \"\n \"Ignoring\"\n )\n return\n\n # help type checker since it can not infer the type of app['influx_client']\n # statically\n influx_client = cast(InfluxDBClient, app[\"influx_client\"])\n project_measurements = await influx_client.previous_measurements(\n measurement=current_measurement, since=last_measurement_timestamp\n )\n try:\n last_measurement = project_measurements[last_measurement_timestamp]\n except KeyError:\n oldest_measurement_timestamp = list(project_measurements)[0]\n\n group.credits_timestamps.value[\n current_measurement.measurement\n ] = oldest_measurement_timestamp\n task_logger.warning(\n \"InfluxDB does not contains usage values for Group %s for measurement %s \"\n \"at timestamp %s, which means that the period between the last measurement \"\n \"and now cannot be used for credit billing. Setting the timestamp to the \"\n \"oldest measurement between now and the last time measurements were billed \"\n \"inside InfluxDB (%s)\",\n group,\n current_measurement.measurement,\n last_measurement_timestamp,\n oldest_measurement_timestamp,\n )\n await group.save()\n return\n\n # see TODO in __doc__\n if current_measurement.value == last_measurement.value:\n task_logger.info(\n \"Values of this and previously billed measurement do not differ, \"\n \"dropping it.\"\n )\n return\n\n credits_to_bill = calculate_credits(current_measurement, last_measurement)\n group.credits_timestamps.value[\n current_measurement.measurement\n ] = current_measurement.timestamp\n\n previous_group_credits = group.credits_used.value\n group.credits_used.value = group.credits_used.value + credits_to_bill\n # Comparing the actual values makes sure that this case even triggers if\n # credits_to_bill is not zero but so small that its changes are dropped due to\n # rounding\n if previous_group_credits == group.credits_used.value:\n task_logger.info(\n \"Measurement does not change the amount of credits left due to rounding, \"\n \"therefore no changes will be stored inside Perun or the InfluxDB.\"\n )\n return\n task_logger.info(\n \"Credits billed: %f, total Usage: %s/%d\",\n credits_to_bill,\n group.credits_used.value,\n group.credits_granted.value,\n )\n billing_entry = BillingHistory(\n measurement=group.name,\n timestamp=current_measurement.timestamp,\n credits_left=Credits(group.credits_granted.value - group.credits_used.value),\n metric_name=current_measurement.metric.name,\n metric_friendly_name=current_measurement.metric.friendly_name,\n )\n await influx_client.write_billing_history(billing_entry)\n await group.save()\n half_of_credits_granted = Decimal(group.credits_granted.value) / 2\n if (\n previous_group_credits <= half_of_credits_granted\n and group.credits_used.value > half_of_credits_granted\n ):\n raise HalfOfCreditsLeft(group)\n","sub_path":"src/os_credits/credits/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":14189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"146334387","text":"#!/usr/bin/python\n\nimport crunchy\nimport crunchy.bin.crunchy_workbench_gui as gui\nimport math\nimport sys\nimport os\nimport argparse\nimport logging\nimport configparser\nfrom crunchy import helper\nfrom datetime import datetime\nfrom sqlalchemy import MetaData, create_engine\nfrom crunchy import helper_pyqt\nfrom crunchy import quadrature\nimport codecs\nimport traceback\nfrom sqlalchemy import Float\n\nlogging.basicConfig(level=logging.DEBUG)\n\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5 import QtGui\nfrom queue import Queue\n\nfrom collections import OrderedDict\n\ndelimiters = {\n \"tab\" : \"\\t\",\n \"space\" : \" \",\n \"comma\" : \",\",\n \"semicolon\" : \";\",\n}\n\nround_beginning_dict = {\n \"None\": 0,\n \"Year\": 1,\n \"Month\": 2,\n \"Day\": 3,\n \"Hour\": 4,\n \"Minute\": 5,\n \"Second\": 6,\n}\n\n\n\n# The new Stream Object which replaces the default stream associated with sys.stdout\n# This object just puts data in a queue!\nclass WriteStream(object):\n def __init__(self,queue):\n self.queue = queue\n\n def write(self, text):\n self.queue.put(text)\n\n def flush(*args, **kwargs):\n pass\n\n# A QObject (to be run in a QThread) which sits waiting for data to come through a Queue.Queue().\n# It blocks until data is available, and one it has got something from the queue, it sends\n# it to the \"MainThread\" by emitting a Qt Signal\nclass MyReceiver(QObject):\n mysignal = pyqtSignal(str)\n\n def __init__(self,queue,*args,**kwargs):\n QObject.__init__(self,*args,**kwargs)\n self.queue = queue\n\n @pyqtSlot()\n def run(self):\n while True:\n text = self.queue.get()\n self.mysignal.emit(text)\n\n# An example QObject (to be run in a QThread) which outputs information with print\nclass BatchImportWorker(QObject):\n def __init__(self, ui):\n self.parent = ui\n super(BatchImportWorker, self).__init__()\n\n @pyqtSlot()\n def run(self):\n logging.info(\"Started batch import, it might take a while to search for files\")\n self.termination_flag = False\n\n db_url = self.parent.dbUrlLineEdit.text()\n\n\n for key, i in self.parent.interactor_dict.items():\n biw = self.parent.batch_import_wrappers[key]\n interactor_dir = biw.line_edit.text().strip()\n interactor_ext = biw.line_edit_2.text().strip()\n\n if interactor_dir != \"\":\n interactor_files = helper._walk_dir_extension(interactor_dir, interactor_ext)\n interactor = i\n i.set_db_url(db_url)\n\n\n for n, f in enumerate(interactor_files):\n skip_if_already_imported = self.parent.skipImportedCheckBox.checkState()\n try:\n\n if self.termination_flag:\n break\n if interactor.check_if_already_imported(f) and skip_if_already_imported:\n logging.info(\"File %s is already imported.\"%(f))\n continue\n\n # print(self.termination_flag)\n logging.info(\">> Running file %d/%d: %s\"%(n+1, len(interactor_files), f))\n interactor.import_csv(f)\n except Exception as e:\n logging.error(str(e))\n\n logging.info(\"Finished batch import\")\n\n # self.finished.emit()\n\n\nclass ExportWorker(QObject):\n\n def __init__(self, ui):\n self.parent = ui\n super(ExportWorker, self).__init__()\n\n @pyqtSlot()\n def run(self):\n try:\n self.run_wrapper()\n except Exception as e:\n traceback.print_exc()\n logging.error(str(e))\n\n def run_wrapper(self):\n self.termination_flag = False\n\n # out_cols = {}#OrderedDict()\n db_url = self.parent.dbUrlLineEdit.text()\n delimiter = delimiters[self.parent.delimiterComboBox.currentText()]\n\n initialized_interactors = {}\n multi_exporter = crunchy.MultiExporter()\n\n for i in range(self.parent.exportColumnTableWidget.rowCount()):\n item_table = self.parent.exportColumnTableWidget.item(i, 0).text()\n item_col = self.parent.exportColumnTableWidget.item(i, 1).text()\n\n if not item_table in initialized_interactors:\n initialized_interactors[item_table] = self.parent.interactor_dict[item_table]\n initialized_interactors[item_table].set_db_url(db_url)\n\n multi_exporter.add_col(initialized_interactors[item_table], item_col)\n\n\n # Set exporting interval\n if self.parent.intervalCheckBox.isChecked():\n begin_date = self.parent.beginCalendarWidget.selectedDate().toPyDate()\n end_date = self.parent.endCalendarWidget.selectedDate().toPyDate()\n\n begin_time = self.parent.beginTimeEdit.time().toPyTime()\n end_time = self.parent.endTimeEdit.time().toPyTime()\n\n begin_dt = datetime.combine(begin_date, begin_time)\n end_dt = datetime.combine(end_date, end_time)\n\n begin_dt = begin_dt.replace(tzinfo=helper.tzBerlin)\n end_dt = end_dt.replace(tzinfo=helper.tzBerlin)\n\n begin_ts = helper.timestampFromDatetime(begin_dt)\n end_ts = helper.timestampFromDatetime(end_dt)\n print(\"Exporting for \", begin_dt, end_dt)\n else:\n begin_ts = None\n end_ts = None\n\n target_csv = self.parent.exportFileLineEdit.text()\n\n if self.parent.averagingCheckBox.isChecked():\n # round_to_hour = self.parent.roundHourCheckBox.isChecked()\n round_beginning = round_beginning_dict[self.parent.roundComboBox.currentText()]\n time_interval = self.parent.averagingIntervalSpinBox.value()\n multi_exporter.export_csv_averaged(target_csv,\n time_interval,\n delimiter=delimiter,\n round_beginning=round_beginning,\n remove_empty_rows=self.parent.removeEmptyRowsCheckBox.isChecked(),\n begin_ts=begin_ts,\n end_ts=end_ts)\n else:\n multi_exporter.export_csv(target_csv,\n delimiter=delimiter,\n begin_ts=begin_ts,\n end_ts=end_ts)\n\n formatted_timestamps = False\n time_col_idx = multi_exporter.get_index_of_time_col()\n\n if self.parent.timestampsCheckBox.isChecked():\n logging.info(\"Formatting timestamps\")\n time_format = codecs.decode(self.parent.timeFormatLineEdit.text(), \"unicode-escape\")\n tz_str = self.parent.get_current_tz_str()\n if time_col_idx >= 0:\n helper.format_csv_unix_timestamp(target_csv,\n target_csv,\n delimiter,\n time_col_idx,\n time_col_idx+1,\n time_format=time_format,\n tz_str=tz_str)\n formatted_timestamps = True\n\n if self.parent.integrationCheckBox.isChecked():\n logging.info(\"Integrating\")\n # get exported columns\n # select the ones that are of type Float for integration\n col_map = multi_exporter.get_interactor_col_map()\n indices = []\n for n, i in enumerate(col_map):\n if i == None:\n continue\n interactor = i[0]\n col_key = i[1]\n type_ = interactor.get_data_type_from_col_key(col_key)\n # print(issubclass(type_,Float))\n if issubclass(type_,Float) and n != time_col_idx:\n indices.append(n)\n\n # if timestamps were formatted, shift indices\n if formatted_timestamps:\n indices = [i if i < time_col_idx else i+1 for i in indices]\n\n try:\n initial_value = float(self.parent.quadratureInitialValueLineEdit.text())\n except Exception as e:\n logging.error(\"Could not convert the quadrature initial value to float, using 0.\")\n initial_value = 0.\n try:\n quadrature_coefficient = float(self.parent.quadratureCoefficientLineEdit.text())\n except:\n logging.error(\"Could not convert the quadrature coefficient to float, using 1.\")\n quadrature_coefficient = 0.\n\n # print(indices, time_col_idx)\n quadrature.quadrature_csv(target_csv,\n target_csv,\n time_col_idx,\n indices,\n delimiter,\n 1,\n header_line=0,\n initial_value=initial_value,\n coefficient=quadrature_coefficient,\n write_metadata=self.parent.integrationOutputMetadataCheckBox.isChecked())\n\n\n logging.info(\"Finished export\")\n\n\nclass DirectSqlWorker(QObject):\n\n def __init__(self, ui):\n self.parent = ui\n super(DirectSqlWorker, self).__init__()\n\n @pyqtSlot()\n def run(self):\n try:\n db_url = self.parent.dbUrlLineEdit.text()\n cmd = self.parent.directSqlTextEdit.toPlainText()\n\n engine = create_engine(db_url,\n echo=True,\n # strategy='threadlocal',\n )\n metadata = MetaData(engine)\n\n conn = engine.connect()#.execution_options(autocommit=False)\n conn.execute(cmd)\n conn.close()\n\n except Exception as e:\n logging.info(e)\n return\n\n logging.info(\"SQL execute successful\")\n\n\nclass ImportWorker(QObject):\n\n def __init__(self, ui):\n self.parent = ui\n super(ImportWorker, self).__init__()\n\n @pyqtSlot()\n def run(self):\n db_url = self.parent.dbUrlLineEdit.text()\n current_table = self.parent.importTableComboBox.currentText()\n\n if not current_table:\n logging.warning(\"Select a target table\")\n return\n\n interactor = self.parent.interactor_dict[current_table]\n interactor.set_db_url(db_url)\n\n f = self.parent.importFileLineEdit.text()\n\n log_file = self.parent.importLogFileLineEdit.text()\n if log_file == \"\":\n log_file = None\n\n if f == \"\":\n logging.warning(\"Select a file to import\")\n return\n\n f = os.path.normpath(f)\n\n skip_if_already_imported = self.parent.skipImportedCheckBox.checkState()\n try:\n if interactor.check_if_already_imported(f) and skip_if_already_imported:\n logging.info(\"File %s is already imported.\"%(f))\n return\n interactor.import_csv(f, log_file=log_file)\n except Exception as e:\n logging.error(str(e))\n\nclass WorkbenchMainWindow(gui.Ui_MainWindow):\n # config = None\n\n def __init__(self, args):\n # for i in interactors:\n # self.interactor_dict[i.table_name] = i\n\n # super(WorkbenchMainWindow, self).__init__(*args,**kwargs)\n self.interactor_dict = {}\n super(WorkbenchMainWindow, self).__init__()\n\n self.window = QMainWindow()\n self.setupUi(self.window)\n # Bring tabs to first\n self.mainTabWidget.setCurrentIndex(0)\n self.exportTabWidget.setCurrentIndex(0)\n\n self.startBatchImportButton.clicked.connect(self.start_batch_import_thread)\n self.stopBatchImportButton.clicked.connect(self.stop_batch_import_thread)\n self.directSqlButton.clicked.connect(self.start_direct_sql_thread)\n self.importButton.clicked.connect(self.start_import_thread)\n\n self.intervalCheckBox.stateChanged.connect(self.tab_state_changed_closure(self.intervalCheckBox, self.intervalTab))\n self.averagingCheckBox.stateChanged.connect(self.tab_state_changed_closure(self.averagingCheckBox, self.averagingTab))\n self.timestampsCheckBox.stateChanged.connect(self.tab_state_changed_closure(self.timestampsCheckBox, self.timestampsTab))\n self.integrationCheckBox.stateChanged.connect(self.tab_state_changed_closure(self.integrationCheckBox, self.exportIntegrationTab))\n\n self.exportFileSelectButton.clicked.connect(self.select_export_file)\n self.importFileSelectButton.clicked.connect(self.select_import_file)\n self.importLogFileSelectButton.clicked.connect(self.select_import_log_file)\n\n self.exportButton.clicked.connect(self.start_export_thread)\n # QWidget.__init__(self,*args,**kwargs)\n\n\n self.tz_dict = helper.get_all_timezones()\n for continent, cities in self.tz_dict.items():\n self.continentComboBox.addItem(continent)\n self.continentComboBox.currentIndexChanged.connect(self.continent_changed_handle)\n\n if helper_pyqt._select_combo_box_item_if_exists(self.continentComboBox, \"Europe\"):\n helper_pyqt._select_combo_box_item_if_exists(self.cityComboBox, \"Berlin\")\n\n self.columnCheckAllButton.clicked.connect(lambda: self.set_state_columns(Qt.Checked))\n self.columnUncheckAllButton.clicked.connect(lambda: self.set_state_columns(Qt.Unchecked))\n\n self.exportColumnUpButton.clicked.connect(self.move_up)\n self.exportColumnDownButton.clicked.connect(self.move_down)\n self.exportColumnTreeWidget.itemChanged.connect(self.export_item_changed)\n\n self.actionQuit.triggered.connect(self.window.close)\n self.actionLoad_Interactors.triggered.connect(self.load_interactors_handle)\n self.actionLoad_settings.triggered.connect(self.load_settings_handle)\n self.actionSave_settings.triggered.connect(self.save_settings_handle)\n\n self.process_args(args)\n\n\n def save_settings_handle(self):\n result = QFileDialog.getSaveFileName(filter=\"INI files (*.ini)\")[0]\n\n if result:\n self.save_settings(result)\n\n def save_settings(self, path):\n settings = helper_pyqt.WindowSettings(self)\n settings.write_config(path)\n\n config = configparser.RawConfigParser()\n config.optionxform = lambda option: option\n config.read(path)\n\n config[\"DEFAULT\"][\"exportColumnTableWidgetContents\"] \\\n = str(self.get_selected_export_interactor_cols())\n\n with open(path, 'w') as configfile:\n config.write(configfile)\n\n\n def continent_changed_handle(self, index):\n continent = self.continentComboBox.currentText()\n if not continent:\n return\n self.cityComboBox.clear()\n for city in self.tz_dict[continent]:\n self.cityComboBox.addItem(city)\n\n def get_current_tz_str(self):\n return self.continentComboBox.currentText() + \"/\" + self.cityComboBox.currentText()\n\n def process_args(self, args):\n # Interactors File\n interactors_file = args.interactors\n try:\n self.load_interactors_file(interactors_file)\n except Exception as e:\n msg = \"There was a problem with the interactors file: %s\\nNo interactors were loaded:\\n%s\"%(interactors_file, e)\n logging.warning(msg)\n error = QErrorMessage()\n error.showMessage(msg)\n error.exec_()\n\n # UI Config File\n default_conf_path = crunchy.default.workbench_conf_path()\n\n if args.config != None:\n config_file = args.config\n elif os.path.isfile(default_conf_path):\n config_file = default_conf_path\n else:\n config_file = None\n\n if config_file:\n try:\n self.load_settings(config_file)\n except Exception as e:\n msg = \"There was a problem with the config file: %s\\n:\\n%s\"%(config_file, e)\n logging.warning(msg)\n error = QErrorMessage()\n error.showMessage(msg)\n error.exec_()\n\n def load_settings_handle(self):\n result = QFileDialog.getOpenFileName(filter='INI files (*.ini)')[0]\n if result:\n self.load_settings(result)\n\n def load_settings(self, path):\n settings = helper_pyqt.WindowSettings(self)\n settings.read_config(path)\n\n config = configparser.RawConfigParser()\n config.optionxform = lambda option: option\n config.read(path)\n\n if config.has_option(\"DEFAULT\", \"exportColumnTableWidgetContents\"):\n selected_export_interactor_cols \\\n = eval(config[\"DEFAULT\"][\"exportColumnTableWidgetContents\"])\n\n for i in selected_export_interactor_cols:\n interactor = i[0]\n col = i[1]\n self.set_export_column_tree_widget_item_check_state(interactor, col, Qt.Checked)\n\n\n def set_export_column_tree_widget_item_check_state(self, interactor, col, state):\n root = self.exportColumnTreeWidget.invisibleRootItem()\n for index in range(root.childCount()):\n parent = root.child(index)\n if parent.text(0) == interactor:\n for row in range(parent.childCount()):\n child = parent.child(row)\n if child.text(0) == col:\n child.setCheckState(0, state)\n return\n\n def load_interactors_handle(self):\n result = QFileDialog.getOpenFileName()[0]\n\n if result:\n self.load_interactors_file(result)\n\n def clear_export_column_table_widget(self):\n self.exportColumnTableWidget.clear()\n self.exportColumnTableWidget.setColumnCount(2)\n self.exportColumnTableWidget.setRowCount(0)\n item = QTableWidgetItem()\n item.setText(\"Table\")\n self.exportColumnTableWidget.setHorizontalHeaderItem(0, item)\n item = QTableWidgetItem()\n item.setText(\"Column\")\n self.exportColumnTableWidget.setHorizontalHeaderItem(1, item)\n self.exportColumnTableWidget.horizontalHeader().setStretchLastSection(True)\n\n def load_interactors_file(self, interactors_file):\n # Deploy the interactors\n # try:\n self.interactor_dict = crunchy.deploy_interactors(interactors_file)\n # except:\n # raise Exception(\"There was a problem with the config: %s\"%(interactors_file))\n\n self.generate_batch_import_widgets()\n\n self.exportColumnTreeWidget.clear()\n\n self.clear_export_column_table_widget()\n\n self.importTableComboBox.clear()\n\n for key, i in self.interactor_dict.items():\n # self.exportColumnTreeWidget.setHeaderHidden(True)\n\n item = QTreeWidgetItem(self.exportColumnTreeWidget.invisibleRootItem(),[key])\n item.setChildIndicatorPolicy(QTreeWidgetItem.ShowIndicator)\n # item.setExpanded (True)\n\n for col in i.target_col_keys:\n sub_item = QTreeWidgetItem(item,[col])\n sub_item.setCheckState (0, Qt.Unchecked)\n sub_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)\n\n # self.__dict__[\"exportColumnTreeWidgetItem_\"+key+\"_\"+helper.sanitize_col_key(col)] = sub_item\n\n self.importTableComboBox.addItem(key)\n\n def set_state_columns(self, val):\n if self.exportColumnTreeWidget.currentItem() != None:\n item = self.exportColumnTreeWidget.currentItem()\n for i in range(item.childCount()):\n item.child(i).setCheckState(0, val)\n else:\n logging.info(\"Please select a table from the list\")\n\n @pyqtSlot(str)\n def append_text(self,text):\n self.outputTextEdit.moveCursor(QTextCursor.End)\n self.outputTextEdit.insertPlainText(text)\n\n @pyqtSlot()\n def start_batch_import_thread(self):\n self.thread = QThread()\n self.thread.setTerminationEnabled(True)\n\n self.batch_import_worker = BatchImportWorker(self)\n self.batch_import_worker.moveToThread(self.thread)\n\n self.thread.started.connect(self.batch_import_worker.run)\n\n # self.batch_import_worker.finished.connect(self.thread.quit)\n self.thread.finished.connect(self.thread.quit)\n # self.batch_import_worker.finished.connect(self.batch_import_worker.deleteLater)\n # self.thread.finished.connect(self.thread.deleteLater)\n\n self.thread.start()\n\n @pyqtSlot()\n def stop_batch_import_thread(self):\n # self.thread.quit()\n self.batch_import_worker.termination_flag = True\n logging.info(\"Termination request received, waiting to finish current file.\")\n\n @pyqtSlot()\n def start_export_thread(self):\n self.thread = QThread()\n\n self.export_worker = ExportWorker(self)\n self.export_worker.moveToThread(self.thread)\n\n self.thread.started.connect(self.export_worker.run)\n self.thread.start()\n\n @pyqtSlot()\n def start_direct_sql_thread(self):\n self.thread = QThread()\n\n self.direct_sql_worker = DirectSqlWorker(self)\n self.direct_sql_worker.moveToThread(self.thread)\n\n self.thread.started.connect(self.direct_sql_worker.run)\n self.thread.start()\n\n self.thread.finished.connect(self.thread.quit)\n\n # self.thread.finished.connect(self.thread.quit)\n\n @pyqtSlot()\n def start_import_thread(self):\n self.thread = QThread()\n\n self.import_worker = ImportWorker(self)\n self.import_worker.moveToThread(self.thread)\n\n self.thread.started.connect(self.import_worker.run)\n self.thread.start()\n\n def tab_state_changed_closure(self, checkBox, container):\n def result(int):\n if checkBox.isChecked():\n val = True\n else:\n val = False\n helper_pyqt.set_enabled_qwidget_children(container, val, checkBox)\n return result\n\n def select_export_file(self, int):\n result = QFileDialog.getSaveFileName(filter='Comma seperated values (*.csv)')[0]\n if result != \"\" and not result.endswith(\".csv\"):\n result += \".csv\"\n self.exportFileLineEdit.setText(result)\n\n def select_import_file(self, int):\n result = QFileDialog.getOpenFileName()[0]\n self.importFileLineEdit.setText(result)\n\n def select_import_log_file(self, int):\n result = QFileDialog.getSaveFileName()[0]\n self.importLogFileLineEdit.setText(result)\n\n\n def get_selected_export_interactor_cols(self):\n result = []\n for i in range(self.exportColumnTableWidget.rowCount()):\n item_table = self.exportColumnTableWidget.item(i, 0).text()\n item_col = self.exportColumnTableWidget.item(i, 1).text()\n result.append([item_table, item_col])\n return result\n\n def export_item_changed(self, item, column):\n table = item.parent().text(column)\n col = item.text(column)\n # identifier = \"%s:%s\"%(table, col)\n # logging.info(identifier)\n\n if item.checkState(column) == Qt.Checked:\n state = True\n elif item.checkState(column) == Qt.Unchecked:\n state = False\n else:\n return\n\n for i in reversed(range(self.exportColumnTableWidget.rowCount())):\n item_table = self.exportColumnTableWidget.item(i, 0).text()\n item_col = self.exportColumnTableWidget.item(i, 1).text()\n # print(\"lol\")\n if item_table == table and item_col == col:\n self.exportColumnTableWidget.removeRow(i)\n if state:\n row_position = self.exportColumnTableWidget.rowCount()\n self.exportColumnTableWidget.insertRow(row_position)\n item_table = QTableWidgetItem(table)\n item_table.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)\n self.exportColumnTableWidget.setItem(row_position,0, item_table)\n\n item_col = QTableWidgetItem(col)\n item_col.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)\n self.exportColumnTableWidget.setItem(row_position,1,item_col)\n\n # for i in reversed(range(self.exportColumnListWidget.count())):\n # item = self.exportColumnListWidget.item(i)\n # if item.text() == identifier:\n # self.exportColumnListWidget.takeItem(self.exportColumnListWidget.row(item))\n # if state:\n # row_position = self.table.rowCount()\n # table.insertRow(row_position)\n # new_item = QListWidgetItem(identifier)\n # self.exportColumnListWidget.addItem(new_item)\n\n\n # if item.checkState(column) == Qt.Checked:\n # print(\"checked\", item, item.text(column))\n # if item.checkState(column) == Qt.Unchecked:\n # print(\"unchecked\", item, item.text(column))\n\n def move_down(self):\n row = self.exportColumnTableWidget.currentRow()\n column = self.exportColumnTableWidget.currentColumn();\n if row < self.exportColumnTableWidget.rowCount()-1:\n self.exportColumnTableWidget.insertRow(row+2)\n for i in range(self.exportColumnTableWidget.columnCount()):\n self.exportColumnTableWidget.setItem(row+2,i,self.exportColumnTableWidget.takeItem(row,i))\n self.exportColumnTableWidget.setCurrentCell(row+2,column)\n self.exportColumnTableWidget.removeRow(row)\n\n def move_up(self):\n row = self.exportColumnTableWidget.currentRow()\n column = self.exportColumnTableWidget.currentColumn();\n if row > 0:\n self.exportColumnTableWidget.insertRow(row-1)\n for i in range(self.exportColumnTableWidget.columnCount()):\n self.exportColumnTableWidget.setItem(row-1,i,self.exportColumnTableWidget.takeItem(row+1,i))\n self.exportColumnTableWidget.setCurrentCell(row-1,column)\n self.exportColumnTableWidget.removeRow(row+1)\n\n def generate_batch_import_widgets(self):\n if hasattr(self, \"batch_import_wrappers\"):\n for key, val in self.batch_import_wrappers.items():\n val.remove()\n\n self.batch_import_wrappers = {}\n # self.batch_import_horizontal_labels = {}\n # self.batch_import_horizontal_line_edits = {}\n\n for key, i in self.interactor_dict.items():\n biw = self.BatchImportWrapper()\n biw.layout = QHBoxLayout()\n biw.label = QLabel()\n biw.label.setText(key + \" folder\")\n biw.label.setFixedWidth(100)\n\n biw.line_edit = QLineEdit()\n biw.line_edit_2 = QLineEdit()\n biw.line_edit_2.setFixedWidth(60)\n\n # Also inject the line edits to the class namespace\n # This is to make it easier to save the settings for those widgets\n self.__dict__[\"batchImportDirLineEdit_\"+key] = biw.line_edit\n self.__dict__[\"batchImportExtensionLineEdit_\"+key] = biw.line_edit_2\n\n biw.tool_button = QToolButton()\n biw.tool_button.setText(\"...\")\n\n biw.tool_button.clicked.connect(biw.set_dir)\n\n biw.layout.addWidget(biw.label)\n biw.layout.addWidget(biw.line_edit)\n biw.layout.addWidget(biw.line_edit_2)\n biw.layout.addWidget(biw.tool_button)\n\n self.batch_import_wrappers[key] = biw\n self.batchImportWidgetsLayout.addLayout(self.batch_import_wrappers[key].layout)\n\n class BatchImportWrapper:\n def __init__(self):\n self.layout = None\n self.label = None\n self.line_edit = None\n self.line_edit_2 = None\n self.tool_button = None\n\n def set_dir(self):\n self.line_edit.setText(QFileDialog.getExistingDirectory())\n def remove(self):\n helper_pyqt.clear_layout(self.layout)\n\n# from ui_imagedialog import Ui_ImageDialog\n\n# import pdb; pdb.set_trace()\n# ui.dbUrlLineEdit.setText(\"sqlite:///test1.db\")\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"config\", type=str, nargs=\"?\",\n help=\"The input configuration file\")\n\nparser.add_argument(\"-i\", \"--interactors\",type=str, default=crunchy.default.interactor_path(),\n help=\"Path to the interactors config\")\n\n\ndef __main__():\n app = QApplication(sys.argv)\n args = parser.parse_args()\n\n ui = WorkbenchMainWindow(args)\n # ui = WorkbenchMainWindow()\n\n queue = Queue()\n stream = WriteStream(queue)\n sys.stdout = stream\n\n h1 = logging.StreamHandler(stream)\n rootLogger = logging.getLogger()\n rootLogger.addHandler(h1)\n\n # Create thread that will listen on the other end of the\n # queue, and send the text to the textedit in our application\n thread = QThread()\n\n my_receiver = MyReceiver(queue)\n my_receiver.mysignal.connect(ui.append_text)\n my_receiver.moveToThread(thread)\n thread.started.connect(my_receiver.run)\n thread.start()\n\n # palette = QtGui.QPalette()\n # palette.setColor(QtGui.QPalette.Background, QtGui.QColor(\"red\"))\n # ui.outputTextEdit.setPalette(palette)\n\n ui.window.show()\n sys.exit(app.exec_())\n\nif __name__ == \"__main__\":\n __main__()\n\n","sub_path":"crunchy/bin/crunchy_workbench.py","file_name":"crunchy_workbench.py","file_ext":"py","file_size_in_byte":29650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"62407722","text":"# importado metodo utilizado no clear()\nfrom os import system\nimport time\n\n# criando a matriz\nmemoria = []\n\n# ---------------------------------------------------------------------------------------------------------------------------------------\n# metodo para limpar o console\nclear = lambda: system('cls')\n\n# ---------------------------------------------------------------------------------------------------------------------------------------\n# funcao para criar a 'memoria'\ndef createMemory(Xmem,Ymem: int):\n if ((Xmem <= 0) or (Ymem <=0)):\n print('Os valores nao podem ser menores ou iguais a zero')\n return 0\n X = []\n memAloc = []\n i = 0\n while i < Ymem:\n X.append(False)\n i += 1\n i = 0\n while i < Xmem:\n memAloc.append(X.copy())\n i += 1\n return memAloc\n\n# ---------------------------------------------------------------------------------------------------------------------------------------\n# funcao para printar a memoria e seus espacos alocados com X\ndef showMemory(matriz):\n for i in range(0,len(matriz)):\n print('|',end='')\n for j in range(0,len(matriz[i])):\n if (matriz[i][j] == True):\n print(' X |', end='')\n else:\n print(' |', end='')\n print()\n\n# ---------------------------------------------------------------------------------------------------------------------------------------\n# funcao para alocar valores na memoria\ndef alocMemory(X,Y,memory):\n if (len(X) != len(Y)):\n print('Houve algum erro :( \\n tente novamente mais tarde.')\n return -1\n for i in range(0,len(X)):\n memory[X[i]][Y[i]] = True\n return memory\n\n# ---------------------------------------------------------------------------------------------------------------------------------------\n# funcao para desalocar valores na memoria\ndef desalocMemory(qtde, posInit: int, memory):\n count = 0\n verPos = True\n for i in range(0,len(memory)):\n for j in range(0,len(memory[i])):\n if ((count == posInit) and (verPos == True) ):\n count = 0\n verPos = False\n elif ((count < posInit) and (verPos == True)):\n count += 1\n elif ((count <= qtde) and (verPos == False)):\n memory[i][j] = False\n count += 1\n elif ((count > qtde) and (verPos == False)):\n return memory\n \n# ---------------------------------------------------------------------------------------------------------------------------------------\n# first fit\ndef firstFitAloc(aloc: int, memory):\n count = 0\n posX = []\n posY = []\n for i in range(0,len(memory)):\n for j in range(0,len(memory)):\n if (count == aloc):\n memoria = alocMemory(posX,posY,memory)\n return memoria\n elif (memory[i][j] == True):\n count = 0\n posX.clear()\n posY.clear()\n elif (memory[i][j] == False):\n count += 1\n posX.append(i)\n posY.append(j)\n\n# ---------------------------------------------------------------------------------------------------------------------------------------\n# best fit\ndef bestFitAloc(aloc: int, memory):\n count = 0\n posX = []\n posY = []\n for i in range(0,len(memory)):\n for j in range(0,len(memory[i])):\n if (count == aloc):\n return 0\n elif (memory[i][j] == True):\n count = 0\n\n elif (memory[i][j] == False):\n count += 1\n posX.append(i)\n posY.append(j)\n\n# ---------------------------------------------------------------------------------------------------------------------------------------\n# worst fit\ndef WorstFit(matriz,n,teste=False):\n inicio=time.localtime()\n n=int(n)\n local=[]\n compara=[]\n for l in range(len(matriz)):\n for c in range(len(matriz[l])):\n if matriz[l][c]==0:\n compara.append([l,c])\n if len(compara)>len(local):\n local=compara.copy()\n else:\n compara=[]\n if len(local)>=n:\n for i in range(n):\n a=local[i][0]\n b=local[i][1]\n matriz[a][b]=1\n if teste==True:\n erros=0\n sucessos=1\n return matriz,erros,sucessos,inicio.tm_sec\n else:\n if teste==True:\n erros=1\n sucessos=0\n return matriz,erros,sucessos,inicio.tm_sec\n print('\\n')\n return menu(matriz)\n\n# ---------------------------------------------------------------------------------------------------------------------------------------\n\nclear()\nprint('Digite o tamanho da memoria (X,Y) \\n sendo X = linhas e Y = colunas') \nqtdeLinhas = int(input('X: '))\nqtdeColunas = int(input('Y: '))\nprint(f'\\n criando uma memoria com tamanho({qtdeLinhas},{qtdeColunas})')\nmemoria = createMemory(qtdeLinhas,qtdeColunas)\nshowMemory(memoria)\nprint()\nprint()\nmemoria = firstFitAloc(15,memoria)\nmemoria = firstFitAloc(5,memoria)\nmemoria = firstFitAloc(40,memoria)\nshowMemory(memoria)\nprint()\nprint()\nmemoria = desalocMemory(4,3,memoria)\nmemoria = desalocMemory(1,10,memoria)\nmemoria = desalocMemory(3,0,memoria)\nmemoria = desalocMemory(6,30,memoria)\nshowMemory(memoria)","sub_path":"TDE3_alocamento_memoria/alocamentoMemoria.py","file_name":"alocamentoMemoria.py","file_ext":"py","file_size_in_byte":5402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"371463841","text":"import numpy as np\n\nN = int(input())\nA = np.array(input().split(), dtype=np.int32)\nB = np.array(input().split(), dtype=np.int32)\n\nans = 0\npow = 1\nfor digit in range(30) :\n mask = pow*2 - 1\n maskedA = A & mask\n maskedB = B & mask\n\n maskedA.sort()\n maskedB.sort()\n\n sum1, sum2, sum3 = (np.searchsorted(maskedB, bound - maskedA).sum() for bound in [pow, pow*2, pow*3])\n count = sum1 + (sum3 - sum2)\n\n if (N - count) % 2 == 1 :\n ans += pow\n pow *= 2\n\nprint(ans)\n","sub_path":"AtCoder/abc/091d.py","file_name":"091d.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"507224180","text":"import hashlib\nimport re\n\nimport bs4.element\n\nfrom .util import id_str\nfrom .sources import version_urls\nfrom .patches import patch_links, norm_packet_name\nfrom .types import Vsn, VersionDiff, PrePacket, RelPacket\nfrom .cache import from_page, get_soup\n\n__all__ = ('first_heading', 'pre_versions', 'pre_packets',\n 'rel_version', 'rel_packets')\n\n\n@from_page(get_soup, rdoc=\n\"Recalculate first_heading(). Give if its code has changed.\")\ndef first_heading(soup):\n \"\"\"The text of the element with id \"firstHeading\" on this page. This is\n used to identify the type (e.g. release or pre-release) of page.\"\"\"\n return soup.find(id='firstHeading').text.strip() \n\n\nPRE_VER_RE = re.compile(r'(?P\\d[^,]*), protocol (?P\\d+)')\n\n@from_page(get_soup, rdoc=\n\"Recalculate pre_versions(). Give if its code has changed.\")\ndef pre_versions(soup, vsn):\n \"\"\"Return a VersionDiff instance containing the old and new versions\n being compared in this pre-release protocol wiki page.\"\"\"\n vs = []\n para = soup.find(id='mw-content-text').find('p', recursive=False)\n for a in para.findAll('a'):\n m = PRE_VER_RE.match(a.text.strip())\n if m is None: continue\n vs.append(Vsn(\n name = m.group('name'),\n protocol = int(m.group('protocol'))))\n if len(vs) == 2:\n return VersionDiff(*vs)\n else:\n raise AssertionError('[%s] Found %d versions, %r, where 2 are expected'\n ' in the first paragraph: %s' % (vsn.name, len(vs), vs, para))\n\n\n@from_page(get_soup, rdoc=\n'Recalculate pre_packets(). Give if its code has changed.')\ndef pre_packets(soup, vsn):\n \"\"\"Returns an iterator over the `PrePacket' instance for each packet documented\n on this pre-release protocol wiki page. `vsn' should be the canonical `Vsn'\n instance associated with this page.\"\"\"\n seen_names = set()\n table = soup.find(id='Packets').findNext('table', class_='wikitable')\n if table is not None:\n cols = {}\n ncols = 0\n for th in table.findChild('tr').findChildren('th'):\n cols[th.text.strip()] = ncols\n ncols += int(th.get('colspan', '1'))\n\n c_id, c_name, c_doc = 'ID', 'Packet name', 'Documentation'\n assert (cols[c_id], cols[c_name], cols[c_doc], ncols) == (0, 1, 2, 4), \\\n '%r != %r' % ((cols[c_id], cols[c_name], cols[c_doc], ncols), (0, 1, 2, 4))\n\n state, bound = None, None\n for tr in table.findChildren('tr')[1:]:\n ths = tr.findChildren('th')\n if len(ths) == 1 and abs(int(ths[0].get('colspan', '1')) - ncols) <= 1:\n match = re.match(r'(\\S+) (\\S+)bound', ths[0].text.strip())\n if match:\n state = match.group(1).capitalize()\n bound = match.group(2).capitalize()\n continue\n tds = tr.findChildren('td')\n if len(tds) != ncols or any(int(td.get('colspan', '1')) != 1 for td in tds):\n raise AssertionError('[%s] Unrecognised table row: %s' % (vsn.name, tr))\n\n changed = tds[cols[c_doc]+1].text.strip() != '(unchanged)'\n\n if tds[cols[c_id]].find('ins') and tds[cols[c_id]].find('del'):\n # Existing packet with changed packet ID.\n old_id = int(tds[cols[c_id]].find('del').text.strip(), 16)\n new_id = int(tds[cols[c_id]].find('ins').text.strip(), 16)\n assert tds[cols[c_doc]].text.strip() == 'Current'\n elif 'background-color: #d9ead3' in tr.get('style', ''):\n # Newly added packet.\n old_id = None\n new_id = int(tds[cols[c_id]].text.strip(), 16)\n assert changed and tds[cols[c_doc]].text.strip() == ''\n else:\n old_id = int(tds[cols[c_id]].text.strip(), 16)\n if 'text-decoration: line-through' in tr.get('style', ''):\n # Removed packet.\n assert changed\n new_id = None\n else:\n # Existing packet without changed packet ID.\n new_id = old_id\n assert tds[cols[c_doc]].text.strip() == 'Current', \\\n '[%s] [%s] not %r or %r != %r' % (vsn.name,\n tds[cols[c_name]].text.strip(), changed,\n tds[cols[c_doc]].text.strip(), 'Current')\n\n if changed:\n expect = '' if new_id is None else 'Pre'\n assert tds[cols[c_doc]+1].text.strip() == expect, \\\n '[%s] [%s] %r != %r' % (vsn.name, tds[cols[c_name]].text.strip(),\n tds[cols[c_doc]+1].text.strip(), expect)\n\n name = tds[cols[c_name]].text.strip()\n name = norm_packet_name(name, state, bound)\n\n if changed and new_id is not None:\n a = tds[cols[c_doc]+1].find('a')\n assert a is not None, '[%s] [%s] No found in %s' % (\n vsn.name, tds[cols[c_name]].text.strip(), tds[cols[c_doc]+1])\n parts = tds[cols[c_doc]+1].find('a').get('href').split('#', 1)\n assert len(parts) == 2 and parts[0] == '/Pre-release_protocol', \\\n '[%s] [%s] %s' % (vsn.name, tds[cols[c_name]].text.strip(), parts)\n frag = '#' + parts[1]\n frag = patch_links.get((vsn, frag), patch_links.get((None, frag), frag))\n if frag is not None:\n head = soup.find(id=frag[1:])\n assert head is not None, \\\n '[%s] Cannot find \"%s\".' % (vsn.name, frag)\n html = []\n for el in head.find_parent('h4').next_siblings:\n if el.name in ('h4', 'h3', 'h2', 'h1'): break\n if isinstance(el, bs4.element.Tag):\n html.extend(el.stripped_strings)\n elif type(el) in (bs4.element.NavigableString,\n bs4.element.PreformattedString):\n html.append(str(el).strip())\n else:\n assert isinstance(el, bs4.element.PageElement), repr(el)\n html = ''.join(html).replace(id_str(new_id), '{packet-id}')\n if name == 'Handshake':\n html = re.sub(r'See\\s*protocol version numbers\\s*\\(currently.*?\\)',\n '{proto-ver}', html)\n html = hashlib.sha1(html.encode('utf8')).hexdigest()\n url = version_urls[vsn] + frag\n else:\n html, url = None, None\n\n yield PrePacket(\n name=name, old_id=old_id, new_id=new_id, changed=changed,\n state=state, bound=bound, html=html, url=url)\n\n\nREL_VER_RE = re.compile(\n r'\\(currently (?P\\d+)( in Minecraft (?P\\d[^)]*))?\\)')\n\n@from_page(get_soup, rdoc=\n'Recalculate rel_version(). Give if its code has changed.')\ndef rel_version(soup):\n \"\"\"Return a `Vsn' instance giving the Minecraft and protocol version\n specified on this release protocol wiki page.\"\"\"\n td = soup.find('td', string=re.compile('^\\s*Protocol Version\\s*$'))\n td = td.findNextSibling('td')\n assert td.text.strip() == 'VarInt'\n td = td.findNextSibling('td')\n m = REL_VER_RE.search(td.text)\n protocol = int(m.group('protocol')) if m.group('protocol') else None\n return Vsn(name=m.group('name'), protocol=protocol)\n\n\n@from_page(get_soup, rdoc=\n'Recalculate rel_packets(). Give if its code has changed.')\ndef rel_packets(soup, vsn):\n \"\"\"Return an iterator over the `RelPacket' instance for each packet\n documented on this release protocol wiki page. `vsn' should be the\n canonical `Vsn' instance associated with this page.\"\"\"\n content = soup.find(id='mw-content-text')\n for table in content.findChildren('table', class_='wikitable'):\n ths = table.findChildren('tr')[0].findChildren('th')\n tds = table.findChildren('tr')[1].findChildren('td')\n id, state, bound = None, None, None\n for th, td in zip(ths, tds):\n if th.text.strip() == 'Packet ID':\n id = int(td.text.strip(), 16)\n elif th.text.strip() == 'State':\n state = td.text.strip()\n elif th.text.strip() == 'Bound To':\n bound = td.text.strip()\n if id is None:\n continue\n head = table.findPreviousSibling('h4')\n name = norm_packet_name(head.text.strip(), state, bound)\n url = '%s#%s' % (version_urls[vsn], head.find('span')['id'])\n yield RelPacket(name=name, id=id, state=state, bound=bound, url=url)\n","sub_path":"mcdevdata/parsers.py","file_name":"parsers.py","file_ext":"py","file_size_in_byte":8779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"586477463","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable as V\n\nimport cv2\nimport numpy as np\n\nclass MyFrame():\n def __init__(self, net, loss, lr=2e-4, evalmode = False, use_cuda = False, require_iou = False):\n if torch.cuda.is_available():\n use_cuda = True\n self.use_cuda = use_cuda\n if self.use_cuda:\n self.net = net().cuda()\n self.net = torch.nn.DataParallel(self.net, device_ids=range(torch.cuda.device_count()))\n else:\n self.net = net()\n self.optimizer = torch.optim.Adam(params=self.net.parameters(), lr=lr)\n self.require_iou = require_iou\n self.loss = loss(iou = self.require_iou)\n self.old_lr = lr\n if evalmode:\n for i in self.net.modules():\n if isinstance(i, nn.BatchNorm2d):\n i.eval()\n \n def set_input(self, img_batch, mask_batch=None, img_id=None):\n self.img = img_batch\n self.mask = mask_batch\n self.img_id = img_id\n \n def test_one_img(self, img):\n pred = self.net.forward(img)\n pred = torch.argmax(pred)\n \n mask = pred.squeeze().cpu().data.numpy()\n return mask\n \n def test_batch(self):\n self.forward(volatile=True)\n mask = self.net.forward(self.img).cpu().data.numpy()\n mask = np.argmax(mask, dim=1)\n mask = mask.numpy()\n\n print(mask.shape)\n# mask = self.net.forward(self.img).cpu().data.numpy().squeeze(1)\n\n \n return mask, self.img_id\n \n\n \n def forward(self, volatile=False):\n if self.use_cuda:\n self.img = self.img.cuda()\n if self.mask is not None:\n self.mask = self.mask.cuda()\n else:\n self.img = self.img\n if self.mask is not None:\n self.mask = self.mask\n \n def optimize(self):\n self.net.train()\n self.forward()\n self.optimizer.zero_grad()\n prob = self.net.forward(self.img)\n pred = torch.argmax(prob, dim = 1)\n print(pred.shape)\n\n if self.require_iou:\n loss, iou = self.loss(self.mask, pred)\n else:\n loss = self.loss(self.mask, pred)\n loss.backward()\n self.optimizer.step()\n if self.require_iou:\n return loss.item(), iou\n return loss.item()\n \n def save(self, path):\n torch.save(self.net.state_dict(), path)\n \n def load(self, path):\n self.net.load_state_dict(torch.load(path))\n \n def update_lr(self, new_lr, mylog, factor=False):\n if factor:\n new_lr = self.old_lr / new_lr\n for param_group in self.optimizer.param_groups:\n param_group['lr'] = new_lr\n\n print ('update learning rate: %f -> %f' % (self.old_lr, new_lr), file = mylog)\n print ('update learning rate: %f -> %f' % (self.old_lr, new_lr))\n self.old_lr = new_lr\n","sub_path":"multitask_framework.py","file_name":"multitask_framework.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"242189779","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nfrom sklearn.cluster import KMeans\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom skimage.segmentation import felzenszwalb, mark_boundaries\nfrom skimage import data, segmentation, filters, color\nfrom skimage.future import graph\nfrom plot_rag_merge import _weight_mean_color, merge_mean_color\n\n\n# In[2]:\n\n\np1 = np.load('0153MR0008490000201265E01_DRLX.npy',allow_pickle=True)\n\n\n# In[3]:\n\n\np1 = np.delete(p1, 0, 0)\n\n\n# In[4]:\n\n\np1.shape\n\n\n# In[5]:\n\n\nimgplot = plt.imshow(p1)\n\n\n# In[6]:\n\n\nsegments = felzenszwalb(p1, scale=32, sigma=12.5, min_size=15)\n\n\n# In[7]:\n\n\nimgplot = plt.imshow(mark_boundaries(p1, segments))\n\n\n# In[8]:\n\n\ng = graph.rag_mean_color(p1, segments)\n\n\n# In[9]:\n\n\nlabels2 = graph.merge_hierarchical(segments, g, thresh=0.05, rag_copy=True,\n in_place_merge=True,\n merge_func=merge_mean_color,\n weight_func=_weight_mean_color)\n\n\n# In[10]:\n\n\ngraph.show_rag(segments, g, p1)\n\n\n# In[11]:\n\n\nplt.figure()\nout = color.label2rgb(labels2, p1)\nplt.imshow(out)\n\n\n# In[12]:\n\n\np2 = np.load('0172ML0009240000104879E01_DRLX.npy',allow_pickle=True)\np2 = np.delete(p2, 0, 0)\np2.shape\n\n\n# In[13]:\n\n\nimgplot = plt.imshow(p2)\n\n\n# In[14]:\n\n\nsegments = felzenszwalb(p2, scale=20.0, sigma=10.95, min_size=2)\n\n\n# In[15]:\n\n\nimgplot = plt.imshow(mark_boundaries(p2, segments))\n\n\n# In[16]:\n\n\ng = graph.rag_mean_color(p2, segments)\nlabels2 = graph.merge_hierarchical(segments, g, thresh=0.095, rag_copy=True,\n in_place_merge=True,\n merge_func=merge_mean_color,\n weight_func=_weight_mean_color)\n\n\n# In[17]:\n\n\ngraph.show_rag(segments, g, p2)\n\n\n# In[18]:\n\n\nplt.figure()\nout = color.label2rgb(labels2, p2)\nplt.imshow(out)\n\n\n# In[19]:\n\n\np3 = np.load('0172ML0009240340104913E01_DRLX.npy',allow_pickle=True)\np3 = np.delete(p3, 0, 0)\np3.shape\n\n\n# In[20]:\n\n\nimgplot = plt.imshow(p3)\n\n\n# In[21]:\n\n\nsegments = felzenszwalb(p3, scale=50.0, sigma=8, min_size=20)\n\n\n# In[22]:\n\n\nimgplot = plt.imshow(mark_boundaries(p3, segments))\n\n\n# In[23]:\n\n\ng = graph.rag_mean_color(p3, segments)\nlabels2 = graph.merge_hierarchical(segments, g, thresh=0.055, rag_copy=True,\n in_place_merge=True,\n merge_func=merge_mean_color,\n weight_func=_weight_mean_color)\n\n\n# In[24]:\n\n\ngraph.show_rag(segments, g, p3)\n\n\n# In[25]:\n\n\nplt.figure()\nout = color.label2rgb(labels2, p3)\nplt.imshow(out)\n\n\n# In[26]:\n\n\np4 = np.load('0270MR0011860360203259E01_DRLX.npy',allow_pickle=True)\np4 = np.delete(p4, 0, 0)\np4.shape\n\n\n# In[27]:\n\n\nimgplot = plt.imshow(p4)\n\n\n# In[28]:\n\n\nsegments = felzenszwalb(p4, scale=20.75, sigma=18.95, min_size=3)\n\n\n# In[29]:\n\n\nimgplot = plt.imshow(mark_boundaries(p4, segments))\n\n\n# In[30]:\n\n\ng = graph.rag_mean_color(p4, segments)\nlabels2 = graph.merge_hierarchical(segments, g, thresh=0.095, rag_copy=True,\n in_place_merge=True,\n merge_func=merge_mean_color,\n weight_func=_weight_mean_color)\n\n\n# In[31]:\n\n\ngraph.show_rag(segments, g, p4)\n\n\n# In[32]:\n\n\nplt.figure()\nout = color.label2rgb(labels2, p4)\nplt.imshow(out)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Felzen-Rag.py","file_name":"Felzen-Rag.py","file_ext":"py","file_size_in_byte":3363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"1196463","text":"class LaneStatus:\n def __init__(self, n):\n self.zeros = n\n self.players = set()\n\n def put(self, player):\n self.zeros -= 1\n self.players.add(player)\n return self.__whoWins()\n\n def __whoWins(self):\n return self.players.pop() if self.zeros == 0 and len(self.players) == 1 else 0\n\n\nclass TicTacToe:\n\n def __init__(self, n):\n \"\"\"\n Initialize your data structure here.\n :type n: int\n \"\"\"\n self.n = n\n self.lanes = [LaneStatus(n) for r in range(n + n + 2)]\n\n def move(self, row, col, player):\n \"\"\"\n Player {player} makes a move at ({row}, {col}).\n @param row The row of the board.\n @param col The column of the board.\n @param player The player, can be either 1 or 2.\n @return The current winning condition, can be either:\n 0: No one wins.\n 1: Player 1 wins.\n 2: Player 2 wins.\n :type row: int\n :type col: int\n :type player: int\n :rtype: int\n \"\"\"\n ret = self.lanes[row].put(player)\n if ret > 0:\n return ret\n ret = self.lanes[self.n + col].put(player)\n if ret > 0:\n return ret\n if row == col:\n ret = self.lanes[-2].put(player)\n if ret > 0:\n return ret\n if col == self.n - 1 - row:\n ret = self.lanes[-1].put(player)\n if ret > 0:\n return ret\n return 0\n\n\n# Your TicTacToe object will be instantiated and called as such:\nobj = TicTacToe(3)\nparam_1 = obj.move(1, 0, 1)\nparam_1 = obj.move(1, 1, 1)\nparam_1 = obj.move(1, 2, 1)\n","sub_path":"src/design-tic-tac-toe.py","file_name":"design-tic-tac-toe.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"414135295","text":"import logging\nimport sys\nfrom datetime import datetime, timezone\n\nimport dns.resolver\nimport idna\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef check_dot_end(domain):\n return domain[len(domain) - 1] == '.'\n\n\ndef open_file_by_line(filename):\n try:\n with open(filename) as file:\n return file.read().splitlines()\n except OSError as err:\n LOGGER.critical(\"OS error: %s\", format(err))\n except:\n LOGGER.critical(\"Unexpected error:\", sys.exc_info()[0])\n raise\n\n\ndef add_to_queue(queue, domains):\n for domain in domains:\n queue.put(domain)\n LOGGER.info('Added ' + str(queue.qsize()) + ' domains to queue')\n\n\ndef read_file_and_add_to_queue(queue, file):\n add_to_queue(queue, open_file_by_line(file))\n\n\ndef timestamp_now():\n return datetime.now(timezone.utc).astimezone()\n\n\ndef get_decoded_domain(domain):\n try:\n return idna.decode(domain)\n except idna.IDNAError as err:\n LOGGER.critical(\"IDNA Decoding failed: %s\", format(err))\n raise\n\n\ndef get_record(domain, rr_list, answer, timeout=1):\n for RR in rr_list:\n try:\n rr_set = dns.resolver.resolve(domain, RR, lifetime=timeout)\n for i in rr_set.response.answer:\n for j in i.items:\n if dns.rdatatype.to_text(j.rdtype) == 'CNAME':\n continue\n if RR == 'MX':\n answer.setdefault(RR.lower(), []).append(str(j.exchange))\n LOGGER.debug(\"Domain: %s with RR %s result %s\", domain, RR, str(j.exchange))\n else:\n answer.setdefault(RR.lower(), []).append(j.to_text())\n LOGGER.debug(\"Domain: %s with RR %s result %s\", domain, RR, j.to_text())\n\n except dns.resolver.NoAnswer:\n LOGGER.debug(\"No answer for \" + RR + \" \" + domain)\n except dns.resolver.NXDOMAIN:\n LOGGER.debug(\"NXDOMAIN for \" + RR + \" \" + domain)\n except dns.resolver.NoNameservers:\n LOGGER.debug(\"No NS for \" + RR + \" \" + domain)\n except dns.resolver.Timeout:\n LOGGER.debug(\"Timeout for \" + RR + \" \" + domain)\n timeout /= 2\n LOGGER.info(\"Reducing timeout for \" + domain + \" to: \" + str(timeout))\n except:\n LOGGER.critical(\"Other error for \" + RR + \" \" + domain)\n","sub_path":"indexing/searchzone/tasks/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":2376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"62173473","text":"import os\nimport torch\nimport segmentation_models_pytorch as smp\n\ndef build_model(cfg_model):\n \"\"\"\n Build model by config.\n\n Args:\n cfg_model (obj): Model config.\n\n Returns:\n model (obj): Created model.\n \"\"\"\n if hasattr(smp, cfg_model.type):\n _model = getattr(smp, cfg_model.type)\n else:\n raise KeyError(f\"smp library has no model named '{cfg_model.type}'.\")\n model = _model(**cfg_model.args)\n return model\n \ndef build_module(parent_module, cfg_module, has_attr, **kwargs):\n \"\"\"\n Build module by config.\n\n Args:\n parent_module (obj): Upper Module of the module to build.\n \n cfg_module (obj): Module config.\n\n has_attr (bool): If config has module attribute.\n\n Returns:\n module (obj): Created module.\n \"\"\"\n if not has_attr:\n return None\n if hasattr(parent_module, cfg_module.type):\n module = getattr(parent_module, cfg_module.type)\n if hasattr(cfg_module, 'args'):\n module = module(**cfg_module.args, **kwargs)\n else:\n module = module(**kwargs)\n else:\n raise KeyError(f\"{parent_module} has no module named '{cfg_module.type}'.\")\n\n return module\n\ndef save_model(model, saved_dir, file_name, debug=False):\n \"\"\"\n Save model in state_dict format.\n\n Args :\n model (obj : torch.nn.Module) : Model to use\n\n saved_dir (str) : Directory path where to save model\n\n file_name (str) : Name of model to be saved\n\n debug (bool) : Debugging mode (default : False)\n \"\"\"\n if debug:\n return\n\n check_point = {'net': model.state_dict()}\n output_path = os.path.join(saved_dir, file_name)\n torch.save(check_point, output_path)","sub_path":"smp/v2/model_api.py","file_name":"model_api.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"285558639","text":"from __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\nimport random\n# Create your models here.\n\nclass Jugador(models.Model):\n nom = models.CharField( max_length=100,unique=True, help_text='El nom del jugador...')\n diners = models.IntegerField(default=1500)\n casella_Actual = models.ForeignKey('taulell.Casella',on_delete = models.PROTECT,default=0)\n\n colorChoices = (\n ('#DC143C' , 'vermell'),\n ('#7FFF00', 'verd' ),\n ('#0000CD', 'blau' ),\n ('#FFFF00', 'groc'),\n ('#FF00FF', 'rosa'),\n )\n\n color = models.CharField(\n max_length=7,\n choices= colorChoices,\n unique=True,\n help_text=\"Tria un color per aquest jugador\"\n )\n usuari = models.OneToOneField( User )\n\n#----------------\nfrom django.db.models.signals import post_save\n\ndef post_save_user(sender, instance, created, **kwargs):\n if created:\n color = '#%02X%02X%02X' % (random.randint(0,255),\n random.randint(0,255),\n random.randint(0,255))\n new_jugador = Jugador.objects.create(\n nom=instance.username,\n color=color,\n usuari=instance,\n )\n instance.refresh_from_db()\n\npost_save.connect(post_save_user, sender=User)\n","sub_path":"usuaris/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"639739510","text":"def getmsg(filepath):\n arr = []\n arr1 = []\n a = 3\n with open(filepath, 'r') as file: #以读方式打开文件\n contents = file.readlines()\n\n while True: #收集将要出去的内容\n key = input('input what you want to remove:')\n if key == 'q':\n break\n else:\n arr1.append(key)\n\n for i in contents:\n b = i.strip() # 去掉换行的转意字符\n content = list(b)\n for x in arr1:\n while x in content:\n content.remove(x)\n\n temp = ''.join(content)\n arr.append(temp)\n while '' in arr:\n arr.remove('')\n return arr","sub_path":"OP/去除特定字符.py","file_name":"去除特定字符.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"132400775","text":"import requests\r\nfrom lxml import html\r\nimport pandas as pd\r\nurl = \"http://www.myflorida.com/apps/vbs/%21vbs_www.search_r2.matching_ads\"\r\nresponse = requests.request(\"GET\", url)\r\ndoc = html.fromstring(response.text)\r\n\r\ntable = (doc.xpath(\"//form[@id='ReForm']/ancestor::td/table\"))\r\nrows = (table[0].xpath(\"tr\"))\r\nfileout=open('VBS_data.csv','w')\r\ntotal_data=[]\r\nfor i in range(2, len(rows)):\r\n row = rows[i]\r\n ds = row.xpath(\"td\")\r\n data = []\r\n for j in range(0,len(ds)):\r\n d = ds[j]\r\n if(j==1):\r\n data.append(d.xpath(\"a/@href\")[0])\r\n else:\r\n data.append(d.xpath(\"text()|span/text()\")[0])\r\n total_data.append(data)\r\nfileout.close()\r\ndata=pd.DataFrame(total_data)\r\ndata.columns=['Title','Link','Version','AD Type','Begin Date','End Date']\r\ndata.to_csv('VBS_data.csv',header=['Title','Link','Version','AD Type','Begin Date','End Date'],index=None)\r\n#For Filtering\r\nfrom datetime import datetime\r\ncurrent_date=datetime.now()\r\ndatetime_object=[]\r\nindex=[]\r\nk=0\r\ndata_final=[]\r\nfor i in range(0,len(data)):\r\n data_temp=[]\r\n if(datetime.strptime(data.iloc[:,5][i], '%m/%d/%Y')>current_date):\r\n for j in range(0,len(data.columns)):\r\n data_temp.append(data.iloc[:,j][i])\r\n if(len(data_temp)!=0):\r\n data_final.append(data_temp)\r\nnew_data=pd.DataFrame(data_final,columns=data.columns)\r\n\r\nimport os\r\nif('Filtered_VBS_data.csv' in os.listdir()):\r\n os.remove('Filtered_VBS_data.csv')\r\nnew_data.to_csv('Filtered_VBS_data.csv',index=None)\r\n\r\ntitle=list(new_data.iloc[:,0])\r\nlink=list(new_data.iloc[:,1])\r\nversion=list(new_data.iloc[:,2])\r\ntyp=list(new_data.iloc[:,3])\r\nsdate=list(new_data.iloc[:,4])\r\nedate=list(new_data.iloc[:,5])\r\n#Similar to Title, print for link,version etc\r\nfor i in title:\r\n print(i)\r\n","sub_path":"VBS_Scrapper.py","file_name":"VBS_Scrapper.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"606484547","text":"TYPES = {\"cold\": 1, \"slashing\": 2, \"fire\": 3, \"radiation\": 4, \"bludgeoning\": 5}\nLIMIT = 2 ** 100\n\n# Class for group\nclass Group:\n def __init__(self, hp, numbers, dmg, dmg_type, ini, weak, immune,\n virusState, booster = 0):\n self.hp = hp\n self.units = numbers\n self.maxUnits = numbers\n self.boost = booster\n self.dmg = dmg\n self.dmg_type = dmg_type\n self.initiative = ini\n self.weakto = weak\n self.immuneto = immune\n self.isVirus = virusState\n\n # Restore units to max units\n def heal(self):\n self.units = self.maxUnits\n\n # Set the boost to something else\n # Does not take effect if the virus flag is set\n # param newBoost: new boost to take effect\n def set_boost(self, newBoost):\n self.boost = 0 if self.isVirus else newBoost\n\n # Effective power\n # returns: Product of units and damage\n def power(self):\n return self.units * (self.dmg + self.boost)\n\n # Key for targetting order\n # param maxInitiative: Max initiative of the battle\n # returns: key that priporitises power over initiative\n def key(self, maxInitiative):\n return self.power() * (maxInitiative + 1) + self.initiative\n\n # Maximum possible damage that can be inflicted on this group\n # 0 if group has no units, else enemy power affected by types\n # param power: Effective power of enemy group\n # param attackType: Enemy's attack type (int)\n # returns: damage that would be inflicted on this group\n def dmg_possible(self, power, attackType):\n if self.units == 0:\n return 0\n \n return power * (2 if attackType in self.weakto else\n (0 if attackType in self.immuneto else 1)) \n\n # If this unit can attack an enemy, pop and return the best enemy to attack\n # param targetList: List of targets (can be changed in function)\n # param maxInitiative: Max initiative of all groups, used to prioritise\n # returns: best Group to attack, or None if no damage can be done\n def pop_most_vulnerable(self, targetList, maxInitiative):\n # Skip if no targets left or this group has no units left\n if len(targetList) == 0 or self.units <= 0:\n return None\n\n # Get max power to prioritise, similar to maxInitiative\n maxPower = max([group.power() for group in targetList])\n if maxPower == 0: # return if no enemies have health\n return None\n\n # Sort the possible targets\n dmgScale = (maxInitiative + 1) * (maxPower + 1)\n powerScale = maxInitiative + 1\n targetList.sort(key=lambda target:\n target.dmg_possible(self.power(), self.dmg_type) *\n dmgScale + target.power() * powerScale + \n target.initiative)\n\n # Return the best target, if possible\n bestDamage = targetList[-1].dmg_possible(self.power(), self.dmg_type)\n return targetList.pop() if bestDamage > 0 else None\n\n# Create the groups for a side\n# Indexes are based on the input text\n# param lines: lines of text containing side information\n# param virus: Bool for if the group is a virus group\n# returns: List of Group created from information\ndef gen_side(lines, virus):\n output = []\n\n for line in lines:\n parts = line.strip().split()\n \n units = int(parts[0])\n hp = int(parts[4])\n dmg = int(parts[-6])\n dtype = TYPES[parts[-5]] # convert str to int (see global var)\n init = int(parts[-1])\n weak_lst = []\n imm_lst = []\n\n if \"(\" in line and \")\" in line:\n modifiers = line[line.index(\"(\")+1: line.index(\")\")]\n \n for half in modifiers.split(\"; \"):\n listParts = half.split()\n if listParts[0] == \"immune\":\n imm_lst = [TYPES[t.strip(\",\")] for t in listParts[2:]]\n elif listParts[0] == \"weak\":\n weak_lst = [TYPES[t.strip(\",\")] for t in listParts[2:]]\n else:\n raise ValueError(\"Weak/Immune text not recognised\")\n\n output.append(Group(hp, units, dmg, dtype, init,\n weak_lst, imm_lst, virus))\n\n return output\n\n# Generate the two sides based on the file name given\n# param doc_name: name of text file with battle information\n# returns: tuple of two lists: (immune, virus)\ndef gen_groups(doc_name):\n imm_sys = []\n vir_sys = []\n doc = open(doc_name)\n \n for info in doc.read().strip().split(\"\\n\\n\"):\n lines = info.strip().split(\"\\n\")\n if lines[0].strip().split()[0] == \"Immune\":\n imm_sys = gen_side(lines[1:], False)\n elif lines[0].strip().split()[0] == \"Infection:\":\n vir_sys = gen_side(lines[1:], True)\n\n doc.close()\n\n return (imm_sys, vir_sys)\n\n# Calculate the total units for a side\n# param side: List of groups to count\n# returns: Group collective units\ndef side_health(side):\n health = 0\n for group in side:\n health += group.units\n\n return health\n\n# Carry out a battle for the given boost\n# param immu: List of immune groups\n# param viru: List of virus groups\n# param maxInit: Maximum initiative for the battle\n# param boost: Boost for immune system groups\n# returns: True if the immune system wins, else false\ndef battle(immu, viru, maxInit):\n counter = 0\n # Battle until one side is left\n while side_health(immu) > 0 and side_health(viru) > 0:\n # Update every 1000 cycles\n #if counter % 1000 == 0:\n # print([g.units for g in immu])\n # print([g.units for g in viru])\n #counter += 1\n\n # Create order of targetting based on maxInitiative\n targetOrder = sorted(viru + immu,\n key=lambda group: group.key(maxInit), reverse=True)\n #print([g.power() for g in targetOrder])\n \n attacks = {} # Attack mapping attacker to target\n immuTargets = immu[:]\n viruTargets = viru[:]\n for group in targetOrder:\n attacks[group] = group.pop_most_vulnerable(\n immuTargets if group.isVirus else viruTargets, maxInit)\n # End for\n\n \n attackHappened = False # Prevent stalemates\n \n # Carry out attacks\n for group in sorted(targetOrder, key=\n lambda group: group.initiative, reverse=True):\n target = attacks.get(group)\n if target != None:\n unitsLost = min(target.units, # Limit units lost to unit count\n target.dmg_possible(group.power(), group.dmg_type) \\\n // target.hp)\n\n attackHappened = True if attackHappened or unitsLost > 0 \\\n else False # Set if any attacks happen\n \n #print(-unitsLost)\n target.units -= unitsLost\n # End for\n\n # If stalemate detected, count as loss\n if not attackHappened:\n return False\n '''\n for ind in range(-len(immu), 0):\n if immu[ind].units <= 0:\n immu.pop(ind)\n\n for ind in range(-len(viru), 0):\n if viru[ind].units <= 0:\n viru.pop(ind)\n '''\n # End while\n\n #print((side_health(immu), side_health(viru)))\n return side_health(immu) > 0\n\nif __name__ == \"__main__\":\n immuneSys, viruses = gen_groups(\"input.txt\")\n initMax = max([group.initiative for group in immuneSys + viruses])\n\n ''' # Naive method - still works\n booster = 0\n while not battle(immuneSys, viruses, initMax):\n booster += 1\n [group.set_boost(booster) for group in immuneSys]\n [group.heal() for group in immuneSys + viruses]\n \n print(side_health(immuneSys))\n \n '''\n \n booster = 0\n delta = LIMIT\n while delta > 0 and booster < LIMIT:\n [group.set_boost(booster + delta) for group in immuneSys] # set boost\n if not battle(immuneSys, viruses, initMax): # Simulate battle\n booster += delta\n [group.heal() for group in immuneSys + viruses] # Heal\n delta //= 2\n \n booster += 1 # Add 1 to boost, since search will be too low\n [group.set_boost(booster) for group in immuneSys]\n battle(immuneSys, viruses, initMax)\n print(side_health(immuneSys))\n","sub_path":"Small Challenges/Advent of Code/2018/24/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":8416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"88577496","text":"# coding: utf-8\n# user interface for the sudoku game\n\nfrom graphics import *\nfrom algorithm import checkBoard\nfrom copy import deepcopy\n\nclass Button:\n def __init__(self, win, center, width, height, label, outlineColor, internalColor, outlineWidth, \\\n textSize = -1):\n w, h = width * .5, height * .5\n x, y = center.getX(), center.getY()\n self.xmax, self.xmin = x + w, x - w\n self.ymax, self.ymin = y + h, y - h\n p1 = Point(self.xmin, self.ymin)\n p2 = Point(self.xmax, self.ymax)\n self.rect = Rectangle(p1, p2)\n self.rect.setOutline(outlineColor)\n self.rect.setFill(internalColor)\n self.rect.setWidth(outlineWidth)\n self.rect.draw(win)\n self.label = Text(center, label)\n if textSize != -1:\n self.label.setSize(textSize)\n self.label.draw(win)\n \n def clicked(self, p):\n return self.xmin <= p.getX() <= self.xmax and self.ymin <= p.getY() <= self.ymax\n\nclass Grid:\n def __init__(self, win, center, size, text):\n self.text = text\n self.win = win\n self.xmax, self.xmin = center.getX() + size * .5, center.getX() - size * .5\n self.ymax, self.ymin = center.getY() + size * .5, center.getY() - size * .5\n self.rect = Rectangle(Point(self.xmin, self.ymin), Point(self.xmax, self.ymax))\n self.center = center\n self.label = Text(center, text)\n self.active = True\n self.activate()\n self.rect.draw(win)\n self.label.draw(win)\n\n def setText(self, text):\n self.label.undraw()\n self.text = text\n self.label = Text(self.center, text)\n self.label.draw(self.win)\n\n def clicked(self, p):\n return self.xmin <= p.getX() <= self.xmax and self.ymin <= p.getY() <= self.ymax\n\n def highlight(self):\n self.rect.setFill(\"red\")\n\n def unhighlight(self):\n self.rect.setFill(\"white\" if self.active else \"darkgrey\")\n\n def activate(self):\n self.active = True\n self.rect.setFill(\"white\")\n\n def deactivate(self):\n self.active = False\n self.rect.setFill(\"darkgrey\")\n\nclass UserInterface:\n def __init__(self):\n pass\n\n def welcome(self, size = 800):\n win = GraphWin(\"Sudoku\", size, size)\n ratio = size / 800.\n win.setCoords(0, 0, 100, 100)\n text = Text(Point(50, 80), \"Welcome to the sudoku game, please choose a difficulty:\")\n text.setFace(\"courier\")\n text.setSize(int(round(20 * ratio)))\n text.draw(win)\n labelSize = int(round(15 * ratio))\n width = 16.18\n height = 10\n x, y = 50 - width * .5, 65 - height * .5\n veryeasy = Button(win, Point(x, y), width, height, \"Very Easy\", \"grey\", \"green\", 2, labelSize)\n x += width\n easy = Button(win, Point(x, y), width, height, \"Easy\", \"grey\", \"green\", 2, labelSize)\n x, y = 50, y - height\n normal = Button(win, Point(x, y), width, height, \"Normal\", \"grey\", \"cyan\", 2, labelSize)\n x, y = 50 - width * .5, y - height\n hard = Button(win, Point(x, y), width, height, \"Hard\", \"grey\", \"red\", 2, labelSize)\n x += width\n veryhard = Button(win, Point(x, y), width, height, \"Very Hard\", \"grey\", \"red\", 2, labelSize)\n ret = \"\"\n while True:\n p = win.getMouse()\n if veryeasy.clicked(p):\n ret = \"very easy\"\n break\n if easy.clicked(p):\n ret = \"easy\"\n break\n if normal.clicked(p):\n ret = \"normal\"\n break\n if hard.clicked(p):\n ret = \"hard\"\n break\n if veryhard.clicked(p):\n ret = \"very hard\"\n break\n win.close()\n return ret\n\n def drawControlBoard(self, win, ratio, gridSize, blankSize):\n x, y = blankSize + gridSize * .5, blankSize + gridSize * .5\n grids = []\n for i in xrange(10):\n grid = Grid(win, Point(x, y), gridSize, str(i + 1) if i < 9 else \"\")\n if i > 0:\n grid.deactivate()\n x += gridSize\n grids.append(grid)\n return grids\n\n def drawGameBoard(self, win, ratio, gridSize, blankSize, board):\n x, y = blankSize + gridSize * .5, blankSize * 2 + gridSize * 1.5\n grids = []\n for i in xrange(9):\n row = []\n for j in xrange(9):\n grid = Grid(win, Point(x, y), gridSize, str(board[i][j]) if board[i][j] > 0 else \"\")\n if board[i][j] > 0:\n grid.deactivate()\n x += (gridSize + .5 if (j + 1) % 3 == 0 else gridSize)\n row.append(grid)\n x, y = x - gridSize * 9 - 1.5, y + gridSize\n if (i + 1) % 3 == 0:\n y += .5\n grids.append(row)\n return grids\n\n def play(self, board, size = 800):\n win = GraphWin(\"Sudoku\", size, size)\n ratio = size / 800.\n win.setCoords(0, 0, 100, 100)\n gridSize = 9.\n blankSize = (100 - 91) / 3.\n controlBoard = self.drawControlBoard(win, ratio, gridSize, blankSize)\n gameBoard = self.drawGameBoard(win, ratio, gridSize, blankSize, board)\n currentNumber = 1\n point = Point(gridSize * 9.5 + blankSize * 2, gridSize * 9.5 + blankSize * 2)\n checkButton = Button(win, point, gridSize, gridSize, \"check\", \"grey\", \"white\", 2)\n point = Point(gridSize * 9.5 + blankSize * 2, gridSize * 8.5 + blankSize * 2)\n showButton = Button(win, point, gridSize, gridSize, \"show a solution\", \"grey\", \"white\", 2)\n while True:\n p = win.getMouse()\n flag = False\n for i in xrange(9):\n for j in xrange(9):\n if gameBoard[i][j].clicked(p):\n flag = True\n if gameBoard[i][j].active:\n text = str(currentNumber) if currentNumber < 10 else \"\"\n gameBoard[i][j].setText(text)\n break\n if flag:\n continue\n for i in xrange(10):\n if controlBoard[i].clicked(p):\n if i != currentNumber - 1:\n flag = True\n controlBoard[currentNumber - 1].deactivate()\n controlBoard[i].activate()\n currentNumber = i + 1\n break\n if flag:\n continue\n if checkButton.clicked(p):\n currentBoard = deepcopy(board)\n flag = False\n for i in xrange(9):\n for j in xrange(9):\n if gameBoard[i][j].text == \"\":\n gameBoard[i][j].highlight()\n self.sorry(\"Sorry, grid (%d, %d) is empty.\" % (j + 1, i + 1))\n gameBoard[i][j].unhighlight()\n flag = True\n break\n currentBoard[i][j] = int(gameBoard[i][j].text)\n if flag:\n break\n if flag:\n continue\n message = checkBoard(currentBoard)\n if message is not None:\n x1, y1 = message[0]\n x2, y2 = message[1]\n gameBoard[x1][y1].highlight()\n gameBoard[x2][y2].highlight()\n text = \"(%d, %d) (%d, %d)\" % (y1, x1, y2, x2)\n self.sorry(\"Sorry, grids \" + text + \" are conflicted.\")\n gameBoard[x1][y1].unhighlight()\n gameBoard[x2][y2].unhighlight()\n continue\n self.congratulate()\n if showButton.clicked(p):\n for i in xrange(9):\n for j in xrange(9):\n if gameBoard[i][j].active:\n gameBoard[i][j].setText(str(abs(board[i][j])))\n win.getMouse()\n\n def sorry(self, message):\n win = GraphWin(\"Sorry\", 300, 300)\n message = message + \"\\nclick anywhere to continue\"\n text = Text(Point(150, 150), message)\n text.draw(win)\n win.getMouse()\n win.close()\n\n def congratulate(self):\n win = GraphWin(\"Congratulation\", 300, 300)\n text = Text(Point(150, 150), \"Congratulations to YOU! You've solved the game.\\nclick anywhere to quit\")\n text.draw(win)\n win.getMouse()\n quit()\n\n def wait(self):\n win = GraphWin(\"Waiting\", 300, 300)\n text = Text(Point(150, 150), \"Please wait a few seconds to start the game\")\n text.draw(win)\n return win\n","sub_path":"ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":8800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"24169282","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 27 10:21:37 2018\n\n@author: YumingWu\n\"\"\"\n\nimport os\nimport numpy as np\nimport tensorflow as tf\nfrom PIL import Image\nfrom IPython.display import display\nfrom tensorflow.python.framework import graph_util\nfrom matplotlib import pyplot as plt\n\nREGULAR = 0.0\n\n# define the components of the network\ndef conv2d(x, scope, inshape, outshape):\n with tf.variable_scope(scope):\n W = tf.get_variable('weights', shape=[3, 3, inshape, outshape],\n initializer=tf.variance_scaling_initializer(),\n regularizer=tf.contrib.layers.l2_regularizer(REGULAR))\n b = tf.get_variable('bias', shape=[outshape], initializer=tf.constant_initializer(0.0))\n net = tf.nn.conv2d(x, W, [1,1,1,1], padding='SAME')\n net = tf.nn.bias_add(net, b)\n net = tf.nn.relu(net)\n print(scope, net.get_shape().as_list())\n return net\n\ndef pool(x):\n return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='VALID')\n\ndef deconv2d(x,scope,inshape,outshape):\n with tf.variable_scope(scope):\n x_shape = tf.shape(x)\n output_shape = tf.stack([x_shape[0], x_shape[1]*2, x_shape[2]*2, x_shape[3]//2])\n W = tf.get_variable('weights', shape=[2, 2, outshape, inshape],\n initializer=tf.variance_scaling_initializer(),\n regularizer=tf.contrib.layers.l2_regularizer(REGULAR))\n b = tf.get_variable('bias', shape=[outshape], initializer=tf.constant_initializer(0.0))\n net = tf.nn.conv2d_transpose(x, W, output_shape, strides=[1,2,2,1], padding='SAME')\n net = tf.nn.bias_add(net, b)\n net = tf.nn.relu(net)\n print(scope, net.get_shape().as_list())\n return net\n\ndef copy_concat(x1, x2):\n return tf.concat([x1, x2], axis=3)\n\ndef accuracy(predictions, labels):\n predictions[predictions > 0.5] = 1\n predictions[predictions <= 0.5] = 0\n TP = np.nansum(predictions.astype(np.uint8) & labels.astype(np.uint8))\n precision = TP / np.nansum(predictions)\n recall = TP / np.nansum(labels)\n F1 = 2*precision*recall / (precision + recall)\n return F1\n\ndef inference(inputs):\n \n ## down conv\n base = 64\n conv1 = conv2d(inputs, 'conv1', 3, base)\n conv2 = conv2d(conv1, 'conv2', base, base)\n pool1 = pool(conv2)\n conv3 = conv2d(pool1, 'conv3', base, base*2)\n conv4 = conv2d(conv3, 'conv4', base*2, base*2)\n pool2 = pool(conv4)\n conv5 = conv2d(pool2, 'conv5', base*2, base*4)\n conv6 = conv2d(conv5, 'conv6', base*4, base*4)\n pool3 = pool(conv6)\n conv7 = conv2d(pool3, 'conv7', base*4, base*8)\n conv8 = conv2d(conv7, 'conv8', base*8, base*8)\n pool4 = pool(conv8)\n conv9 = conv2d(pool4, 'conv9', base*8, base*16)\n conv10 = conv2d(conv9, 'conv10', base*16, base*16)\n \n # up conv\n deconv4 = deconv2d(conv10, 'deconv4', base*16, base*8)\n deconcat4 = copy_concat(deconv4, conv8)\n upconv8 = conv2d(deconcat4, 'upconv8', base*16, base*8)\n upconv7 = conv2d(upconv8, 'upconv7', base*8, base*8)\n deconv3 = deconv2d(upconv7, 'deconv3', base*8, base*4)\n deconcat3 = copy_concat(deconv3, conv6)\n upconv6 = conv2d(deconcat3, 'upconv6', base*8, base*4)\n upconv5 = conv2d(upconv6, 'upconv5', base*4, base*4)\n deconv2 = deconv2d(upconv5, 'deconv2', base*4, base*2)\n deconcat2 = copy_concat(deconv2, conv4)\n upconv4 = conv2d(deconcat2, 'upconv4', base*4, base*2)\n upconv3 = conv2d(upconv4, 'upconv3', base*2, base*2)\n deconv1 = deconv2d(upconv3, 'deconv1', base*2, base)\n deconcat1 = copy_concat(deconv1, conv2)\n upconv2 = conv2d(deconcat1, 'upconv2', base*2, base)\n upconv1 = conv2d(upconv2, 'upconv1', base, base)\n \n ## output\n with tf.variable_scope('logits'):\n W = tf.get_variable('weights', shape=[1, 1, base, 2],\n initializer=tf.variance_scaling_initializer(),\n regularizer=tf.contrib.layers.l2_regularizer(REGULAR))\n b = tf.get_variable('bias', shape=[2], initializer=tf.constant_initializer(0.0))\n net = tf.nn.conv2d(upconv1, W, [1,1,1,1], padding='SAME')\n net = tf.nn.bias_add(net, b, name='logits')\n return net\n\ndef train(image_dir, eval_dir, epochs, convert_to_pb=True, convert_to_tflite=False):\n \n height = 320\n width = 480\n \n ## build graph\n graph = tf.Graph()\n with graph.as_default():\n inputs = tf.placeholder(dtype=tf.float32, shape=[None, height, width, 3], name='images')\n label = tf.placeholder(dtype=tf.uint8, shape=[None, height, width, 1])\n logits = inference(inputs)\n output = tf.arg_max(tf.nn.softmax(logits, axis=3), 3, name='output')\n \n ## loss\n softmax_loss = tf.losses.softmax_cross_entropy(\n tf.one_hot(tf.reshape(label, shape=(-1, height, width)), 2), logits)\n tf.losses.add_loss(softmax_loss)\n \n loss = tf.losses.get_total_loss()\n \n ## optimizer\n optimizer = tf.train.AdamOptimizer(1e-3).minimize(loss)\n tf.add_to_collection('images', inputs)\n tf.add_to_collection('logits', logits)\n tf.add_to_collection('output', output)\n writer = tf.summary.FileWriter('../log', graph)\n writer.close()\n saver = tf.train.Saver()\n\n ## shuffle images filenames\n eval_list = os.listdir(eval_dir + '/image')\n images_list = []\n gt_list = []\n for path in image_dir:\n path_list = os.listdir(path + '/image')\n images_list += [path + '/image/' + i for i in path_list]\n gt_list += [path + '/gt/' + i[:-3] + 'png' for i in path_list]\n images_list = np.array(images_list)\n gt_list = np.array(gt_list)\n permu = np.random.permutation(images_list.shape[0])\n images_shuffled = images_list[permu].tolist()\n gt_shuffled = gt_list[permu].tolist()\n \n ## training process\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True \n with tf.Session(graph=graph, config=config) as sess:\n tf.global_variables_initializer().run()\n train_plot = []\n valid_plot = []\n print('Initialized')\n for step in range(epochs):\n loss_avg = 0\n for num in range(len(images_shuffled)):\n image_tmp = (np.array(Image.open(images_shuffled[num])) - 127.5) / 127.5\n gt_tmp = np.array(Image.open(gt_shuffled[num])) // 255\n image = np.expand_dims(image_tmp, axis=0)\n gt = np.expand_dims(np.expand_dims(gt_tmp, axis=0), axis=3)\n feed_dict = {inputs: image, label:gt}\n _, predict, l = sess.run(\n [optimizer, output, loss], feed_dict=feed_dict)\n loss_avg += l\n\n loss_avg /= len(images_shuffled) \n eimage = []\n egt = []\n for num in range(len(eval_list) // 2):\n eval_file = eval_dir + '/image/' + eval_list[num]\n eval_gt = eval_dir + '/gt/' + eval_list[num][:-3] + 'png'\n eimage_tmp = (np.array(Image.open(eval_file)) - 127.5) / 127.5\n egt_tmp = np.array(Image.open(eval_gt)) // 255\n eimage.append(eimage_tmp)\n egt.append(egt_tmp)\n eimage = np.array(eimage)\n egt = np.expand_dims(np.array(egt), axis=3)\n feed_dict = {inputs: eimage, label:egt}\n out, l_e = sess.run([output, loss], feed_dict=feed_dict)\n train_plot.append(loss_avg)\n valid_plot.append(l_e)\n print(\"step:%d, training loss:%.7f, evaluation loss:%.7f\"%(step,\n loss_avg, l_e))\n# display(Image.fromarray(egt[1, :, :, 0] * 255).convert(\"L\"))\n# display(Image.fromarray((out[1, :, :, 0] * 255).astype(np.uint8)).convert(\"L\"))\n\n saver.save(sess, \"../models/model_unet.ckpt\")\n \n # plot\n plotx = np.arange(2, epochs)\n plt.plot(plotx, train_plot[2:], color=\"#000000\", linestyle='--', label=\"training\")\n plt.plot(plotx, valid_plot[2:], color=\"#A60628\", label=\"validation\")\n plt.tick_params(labelsize=\"larger\")\n plt.xlabel(\"Training iterations\", fontsize=\"x-large\")\n plt.ylabel(\"loss\", fontsize=\"x-large\")\n plt.title(\"Learning curve\", fontsize=\"x-large\")\n plt.legend(fontsize=\"larger\")\n \n if convert_to_pb:\n input_graph_def = graph.as_graph_def()\n output_graph_def = graph_util.convert_variables_to_constants(\n sess,\n input_graph_def,\n ['output']\n )\n with tf.gfile.GFile('../models/frozen.pb', 'wb') as f:\n f.write(output_graph_def.SerializeToString())\n print(\"convert ckpt to pb\")\n \n if convert_to_tflite:\n converter = tf.contrib.lite.TocoConverter.from_session(sess, [inputs], [output])\n tflite_model = converter.convert()\n open(\"../tflite/test.tflite\", \"wb\").write(tflite_model)\n \n\nif __name__ == '__main__':\n data_dir = ['../data/1', '../data/2', '../data/3', '../data/4', '../data/5']\n eval_dir = '../data/6'\n epochs = 50\n train(data_dir, eval_dir, epochs, convert_to_tflite=False)","sub_path":"build_and_compress/src/unet_source.py","file_name":"unet_source.py","file_ext":"py","file_size_in_byte":9331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"397938698","text":"from django.contrib import admin\nfrom explorer.models import Msite, Fsite, Keyword, Taccount\nfrom articles.models import Article\nfrom articles.models import Source as ASource\nfrom articles.models import Keyword as AKeyword\nfrom tweets.models import Tweet\nfrom tweets.models import Source as TSource\nfrom tweets.models import Keyword as TKeyword\n\nfrom django.utils import timezone\n\nclass MsiteAdmin(admin.ModelAdmin):\n fieldsets = [\n (None, {'fields': ['url', 'name']})\n ]\n list_display = ('name', 'url', 'article_count', 'latest_article')\n search_fields = ['name', 'url']\n ordering = ['name']\n actions_on_top = True\n\n\n def article_count(self, obj):\n return len(Article.objects.filter(url_origin=obj.url))\n\n article_count.short_description = \"Total Articles Archived\"\n\n\n def latest_article(self, obj):\n latest = Article.objects.filter(url_origin=obj.url)\n if latest:\n delta = timezone.now() - latest.latest('date_added').date_added\n t1 = delta.days # Days\n t2 = delta.seconds/3600 # Hours\n t3 = delta.seconds%3600/60 # Minutes\n return '%-2d days %-2d hours %-2d min ago' % (t1, t2, t3)\n else:\n return 'Have not found any articles yet!'\n\n latest_article.short_description = 'Last Found'\n\n\nclass FsiteAdmin(admin.ModelAdmin):\n fieldsets = [\n (None, {'fields': ['url', 'name']})\n ]\n list_display = ('name', 'url', 'cited_count')\n search_fields = ['name', 'url']\n ordering = ['name']\n actions_on_top = True\n\n def cited_count(self, obj):\n return len(ASource.objects.filter(url_origin=obj.url)) + \\\n len(TSource.objects.filter(url_origin=obj.url))\n\n cited_count.short_description = \"Total Cites\"\n\n\nclass KeywordAdmin(admin.ModelAdmin):\n fieldsets = [\n (None, {'fields': ['keyword']})\n ]\n\n\n list_display = ['keyword', 'match_count']\n search_fields = ['keyword']\n actions_on_top = True\n\n def match_count(self, obj):\n return len(AKeyword.objects.filter(keyword=obj.keyword)) + \\\n len(TKeyword.objects.filter(keyword=obj.keyword))\n\n match_count.short_description = \"Total Matches\"\n\nclass TaccountAdmin(admin.ModelAdmin):\n fieldsets = [\n (None, {'fields': ['account']})\n ]\n\n\n list_display = ['account', 'tweet_count', 'latest_tweet']\n search_fields = ['account']\n actions_on_top = True\n\n def tweet_count(self, obj):\n return len(Tweet.objects.filter(user=obj.account))\n\n tweet_count.short_description = \"Total Tweets Archived\"\n\n\n def latest_tweet(self, obj):\n latest = Tweet.objects.filter(user=obj.account)\n if latest:\n delta = timezone.now() - latest.latest('date_added').date_added\n t1 = delta.days # Days\n t2 = delta.seconds/3600 # Hours\n t3 = delta.seconds%3600/60 # Minutes\n return '%-2d days %-2d hours %-2d min ago' % (t1, t2, t3)\n else:\n return 'Have not found any tweets yet!'\n\n latest_tweet.short_description = 'Last Found'\n\n\nadmin.site.register(Msite, MsiteAdmin)\nadmin.site.register(Fsite, FsiteAdmin)\nadmin.site.register(Keyword, KeywordAdmin)\nadmin.site.register(Taccount, TaccountAdmin)","sub_path":"Frontend/explorer/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":3355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"62075443","text":"import argparse\nimport os\nimport sys\n\nimport numpy as np\nimport pandas as pd\nfrom statsmodels.stats import proportion\n\n##############\n# CSV Loading Routines\n##############\n \ndef get_exp_run_data(fname):\n tokens = fname.split('_')\n # (Experiment, Run)\n return (tokens[0], tokens[1])\n\ndef get_csv_file_names(directory='.', csv_suffix='misinc_data.csv'):\n csv_fnames = [f for f in os.listdir(directory) if os.path.isfile(f) and f.endswith(csv_suffix)]\n return csv_fnames\n \n#####################\n# Simple Stats \n#####################\n\ndef get_stats(df, cutoff=1):\n data = df[[c for c in df.columns if not c == 'sequence']]\n total_n = data.sum(axis=1) # All non-corresponding data should be zero\n correct_n = data[[n+'->'+n for n in ['A', 'C', 'T', 'G']]] # Get the columns that correspond to correct incorporations\n misinc_n = total_n - correct_n.sum(axis=1) # Same as above.\n \n # \n rate = misinc_n / total_n\n lb, ub = proportion.proportion_confint(misinc_n, total_n, method='jeffrey')\n \n # Assemble output dataframe\n simp_df = pd.DataFrame()\n simp_df['rate'] = rate\n simp_df['lb'] = lb\n simp_df['ub'] = ub\n simp_df['n'] = total_n\n simp_df['sequence'] = df.sequence\n \n return simp_df\n \ndef write_all_simple_misinc(directory='.', letterorder=['C', 'A', 'T', 'G']):\n csv_fnames = get_csv_file_names(directory=directory)\n \n for fname in csv_fnames:\n df = pd.read_csv(fname, index_col=0)\n simple_df = get_stats(df)\n simple_df.to_csv('simple_'+fname)\n \n#####################\n# Single Position Stats\n#####################\n\ndef get_pos_stats(df, nIdx, cutoff=1, expt=1, letterorder=['C', 'A', 'T', 'G']):\n # Get row of interest\n data = df[[c for c in df.columns if not c == 'sequence' and not c == 'index']].iloc[nIdx]\n nt = df['sequence'].iloc[nIdx]\n total_n = float(data.sum())\n \n # Set up dataframe\n ntCols = ['N->'+c for c in letterorder] + ['N->!N']\n outsCols = ['ct', '%', '%lb', '%ub']\n cols = [x+'_'+out for x in ntCols for out in outsCols] + ['total_n', 'sequence']\n out_df = pd.DataFrame(index=[expt], columns=cols)\n \n out_df['sequence'] = nt\n out_df['total_n'] = total_n \n \n # Do individual nucleotide stats\n for n in letterorder:\n ct = data[nt+'->'+n]\n rate = ct / total_n\n lb, ub = proportion.proportion_confint(ct, total_n, method='jeffrey')\n \n out_df['N->'+n+'_ct'] = ct\n out_df['N->'+n+'_%'] = rate\n out_df['N->'+n+'_%lb'] = lb\n out_df['N->'+n+'_%ub'] = ub\n \n # Do aggregate misincorporation stats\n misinc_n = total_n - out_df['N->%c_ct' % nt]\n lb, ub = proportion.proportion_confint(misinc_n, total_n, method='jeffrey')\n out_df['N->!N_ct'] = misinc_n\n out_df['N->!N_%'] = misinc_n / total_n\n out_df['N->!N_%lb'] = lb\n out_df['N->!N_%ub'] = ub\n \n return out_df\n \ndef write_all_pos_stats(nIdx, directory='.', outfile='summary_all.csv',\n letterorder=['C', 'A', 'T', 'G']):\n csv_fnames = get_csv_file_names(directory=directory)\n # expts = [int(getExpRunData(fname)[0][3:]) for fname in csv_fnames]\n \n # Set ids to be run first, then experiment\n f_ids = ['.'.join(reversed([str(x) for x in get_exp_run_data(fname)])) for fname in csv_fnames]\n \n # eeek this is a hack... wish there were a way to append using the correct columns\n # rather than just use .values and assume the columns are in the same order.\n ntCols = ['N->'+c for c in letterorder] + ['N->!N']\n outsCols = ['ct', '%', '%lb', '%ub']\n cols = [x+'_'+out for x in ntCols for out in outsCols] + ['total_n', 'sequence']\n \n out_df = pd.DataFrame(index=sorted(f_ids), columns=cols)\n \n for fname, f_id in zip(csv_fnames, f_ids):\n row = get_pos_stats(pd.read_csv(fname, index_col=0),\n nIdx, expt=f_id, letterorder=letterorder)\n out_df.ix[f_id] = row.values\n\n # Sort by experiment number\n # NOTE: this is hard-coded for \n out_df['sort_col'] = out_df.index.map(lambda x: int(x.split('.')[0][3:]))\n out_df.sort_values('sort_col', inplace=True)\n out_df.drop('sort_col', axis=1, inplace=True)\n \n out_df.to_csv(outfile)","sub_path":"nextgen4b/analyze/to_csv.py","file_name":"to_csv.py","file_ext":"py","file_size_in_byte":4248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"381705010","text":"# ----------------------------------------------------------------------\n# Copyright (c) 2014 Rafael Gonzalez.\n#\n# See the LICENSE file for details\n# ----------------------------------------------------------------------\n\n#--------------------\n# System wide imports\n# -------------------\n\nfrom __future__ import division, absolute_import\n\n# ---------------\n# Twisted imports\n# ---------------\n\nfrom twisted.logger import Logger\nfrom twisted.internet import reactor, task\nfrom twisted.internet.defer import inlineCallbacks, DeferredList, gatherResults\n\n#--------------\n# local imports\n# -------------\n\nfrom tessw import VERSION_STRING, MQTT_SERVICE, PHOTOMETER_SERVICE, SUPVR_SERVICE\nfrom tessw.logger import setLogLevel\nfrom tessw.service.reloadable import MultiService\n\n# ----------------\n# Module constants\n# ----------------\n\n# Service Logging namespace\nNAMESPACE = 'supvr'\n\n# -----------------------\n# Module global variables\n# -----------------------\n\nlog = Logger(namespace=NAMESPACE)\n\nclass SupervisorService(MultiService):\n\n\n def __init__(self, options, **kargs):\n MultiService.__init__(self)\n setLogLevel(namespace=NAMESPACE, levelStr=options['log_level'])\n self.options = options\n self.photometers = [] # Array of photometers\n self.task = None # Periodic task to poll Photometers\n self.i = 0 # current photometer being sampled\n self._registryDone = {}\n self._errorCount = {} \n \n # -----------\n # Service API\n # -----------\n\n def startService(self):\n log.info('starting {name}', name=SUPVR_SERVICE)\n self.mqttService = self.parent.getServiceNamed(MQTT_SERVICE)\n N = self.options['nphotom']\n for i in range(1, N+1):\n self.photometers.append(self.getServiceNamed(PHOTOMETER_SERVICE + ' ' + str(i)))\n self._registryDone = {phot.label: False for phot in self.photometers}\n self._errorCount = {phot.label: 0 for phot in self.photometers}\n super().startService()\n self.task = reactor.callLater(0, self.getInfo)\n\n\n @inlineCallbacks\n def reloadService(self, options):\n '''\n Reload service parameters\n '''\n log.warn(\"{version} reloading config\", version=VERSION_STRING)\n try:\n options, cmdline_opts = yield deferToThread(read_options)\n except Exception as e:\n log.error(\"Error trying to reload: {excp!s}\", excp=e)\n else:\n log.warn(\"{version} config reloaded ok.\", version=VERSION_STRING)\n self.options = options['global']\n setLogLevel(namespace=self.label, levelStr=self.options['log_level'])\n setLogLevel(namespace=self.namespace, levelStr=self.options['log_messages'])\n yield super().reloadService(options=options)\n \n # --------------\n # Photometer API\n # --------------\n\n def numberOfPhotometers(self):\n return self.options['nphotom']\n\n def registryDone(self):\n self._registryDone = True\n\n def childStopped(self, child):\n log.warn(\"Will stop the reactor asap.\")\n try:\n reactor.callLater(0, reactor.stop)\n except Exception as e:\n log.error(\"could not stop the reactor\")\n\n\n\n def getInfo(self):\n '''Get registry info for all photometers'''\n log.info(\"Getting info from all photometers\")\n N = self.options['nphotom']\n self.task = task.LoopingCall(self.poll)\n self.task.start(self.options['T']//N, now=False)\n deferreds = [photometer.getInfo() for photometer in self.photometers]\n for deferred, photometer in zip(deferreds, self.photometers):\n deferred.addCallback(self._addInfo, photometer.label)\n deferred.addErrback(self._timeout, photometer.label)\n dli = gatherResults(deferreds, consumeErrors=False).addCallback(self._info_complete)\n self.kk = dli\n return dli\n\n\n def isOffline(self, item):\n flag = item[1] == self.options['ncycles']\n if flag:\n log.warn(\"Photometer {label} went offline\", label=item[0])\n return flag\n\n\n def poll(self):\n i = self.i\n label = self.photometers[i].label\n try:\n sample = self.photometers[i].buffer.getBuffer().popleft() \n except IndexError as e:\n ec = self._errorCount[label] + 1\n self._errorCount[label] = min(self.options['ncycles'], ec)\n result_list = map(self.isOffline, self._errorCount.items())\n if all(result_list):\n log.critical(\"No photometer is alive. Stopping the daemon\")\n reactor.stop()\n else:\n # Take out uneeded information\n self._errorCount[label] = 0\n self.photometers[i].handleInfo(sample)\n if self._registryDone[label]:\n sample = self.photometers[i].curate(sample)\n log.info(\"Photometer[{i}] = {sample}\", sample=sample, i=i)\n self.mqttService.addReading(sample)\n else:\n log.warn(\"Not yet registered. Ignoring sample from Photometer[{i}]\",i=i)\n finally:\n self.i = (i + 1) % len(self.photometers)\n\n # --------------\n # Helper methods\n # --------------\n\n def _addInfo(self, photometer_info, *args):\n label = args[0]\n log.debug(\"Passing {label} photometer info ({name}) to register queue\", label=label, name=photometer_info['name'])\n self._registryDone[label] = True\n self.mqttService.addRegisterRequest(photometer_info)\n\n def _info_complete(self, *args):\n log.info(\"Finished getting info from all photometers\")\n\n def _timeout(self, failure, *args):\n log.error(\"Photometer {label} timeout getting info\", label=args[0])\n\n\n","sub_path":"tessw/supervisor.py","file_name":"supervisor.py","file_ext":"py","file_size_in_byte":5876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"285269770","text":"import codecs\nimport xml.sax.saxutils as saxutils\nfrom Security import Security\n\n#######################################################################################################################\n\ndef securityTypeToString(type):\n\tif type == Security.Stock:\n\t\treturn \"Stock\"\n\telif type == Security.Index:\n\t\treturn \"Index\"\n\telse:\n\t\traise StandardError(\"Invalid type \" + str(type))\n\n#######################################################################################################################\n\ndef writeSecurity(security, file, indentation):\n\tfile.write(indentation + \"\\n\")\n\tname = saxutils.escape(security.name)\n\tfile.write(indentation + \"\\t\" + name + \"\\n\")\n\tfile.write(indentation + \"\\t\" + security.symbol + \"\\n\")\n\tfile.write(indentation + \"\\t\" + securityTypeToString(security.type) + \"\\n\")\n\tfile.write(indentation + \"\\t\" + str(security.lastDate) + \"\\n\")\n\tfile.write(indentation + \"\\n\")\n\n#######################################################################################################################\n\ndef writeProject(project, filename, encoding):\n\tfile = codecs.open(filename, \"w\", encoding)\n\n\tfile.write(\"\\n\")\n\n\tfile.write(\"\\n\")\n\n\tfile.write(\"\\t\\n\")\n\t\n\tfor security in project.securities:\n\t\twriteSecurity(security, file, \"\\t\\t\")\n\n\tfile.write(\"\\t\\n\")\n\tfile.write(\"\\n\")\n","sub_path":"python/QuoteLoader/ProjectWriter.py","file_name":"ProjectWriter.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"146262814","text":"def partition(arr, low, high): \n '''\n This function returns partition index of an array.\n ''' \n pivot = arr[high] # let the last elemnt be pivot\n\n i = low - 1 # initializing index of smaller element\n\n for j in range(low, high): # we will loop from low to high - 1\n\n if arr[j] < pivot: # if low elment is lesser than then increment the i and swap them\n\n i += 1\n\n arr[i], arr[j] = arr[j], arr[i]\n \n arr[i + 1], arr[high] = arr[high], arr[i + 1] # when arrangements have done, we have to do one more thing\n # i.e, swap the high element with the element at i + 1 index\n # because only by doing this pivot will satisfy all the conditions\n # element before pivot must be smaller and after pivot it msust be greater\n return (i + 1) # finally return the partition index\n\n\ndef quick_sort(arr, low, high): \n \"\"\"\n This function recursively calls the itsef and partition func untill all the elements get sorted.\n \"\"\"\n \n if low < high: # recursively call the funcn until low index is less than high index\n\n pi = partition(arr, low, high) # store the partition index in variable pi\n \n quick_sort(arr, low, pi - 1) # divide the array from low to (pi - 1)index as pivot element is already at it's place\n quick_sort(arr, pi + 1, high) # and another part from (pi + 1) index to high, as pivot is alredy sorted\n\n return arr # return the array after sorting is comlete\n\n# Driver Code Starts\nif __name__ == \"__main__\":\n arr = list(map(int, input(\"Enter the array elements: \").split()))\n print(quick_sort(arr, 0, len(arr) - 1))\n\n\n\"\"\"\nAnalysis of QuickSort\nTime taken by QuickSort in general can be written as following.\n\nT(n) = T(k) + T(n-k-1) + theta(n)\nThe first two terms are for two recursive calls, the last term is for the partition process. k is the \nnumber of elements which are smaller than pivot.The time taken by QuickSort depends upon the input array \nand partition strategy. Following are three cases.\n\nWorst Case: The worst case occurs when the partition process always picks greatest or smallest element as pivot. \nIf we consider above partition strategy where last element is always picked as pivot, the worst case would occur \nwhen the array is already sorted in increasing or decreasing order. Following is recurrence for worst case.\n\nT(n) = T(0) + T(n-1) + theta(n)\nwhich is equivalent to \nT(n) = T(n-1) + theta(n)\nThe solution of above recurrence is theta(n2).\n\nBest Case: The best case occurs when the partition process always picks the middle element as pivot. Following \nis recurrence for best case.\n\n T(n) = 2T(n/2) + theta(n)\nThe solution of above recurrence is theta(nLogn). It can be solved using case 2 of Master Theorem.\n\nAverage Case:\nTo do average case analysis, we need to consider all possible permutation of array and calculate time taken by \nevery permutation which doesn’t look easy. We can get an idea of average case by considering the case when \npartition puts O(n/9) elements in one set and O(9n/10) elements in other set. Following is recurrence for this case.\n\nT(n) = T(n/9) + T(9n/10) + theta(n)\nSolution of above recurrence is also O(nLogn)\n\nAlthough the worst case time complexity of QuickSort is O(n2) which is more than many other sorting algorithms \nlike Merge Sort and Heap Sort, QuickSort is faster in practice, because its inner loop can be efficiently \nimplemented on most architectures, and in most real-world data. QuickSort can be implemented in different ways \nby changing the choice of pivot, so that the worst case rarely occurs for a given type of data. However, merge \nsort is generally considered better when data is huge and stored in external storage.\n\"\"\"\n","sub_path":"Sorting/quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":3870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"63766759","text":"import numpy as np\nfrom PSO.sko.PSO import PSO\n\ndef demo_func(x):\n return x[0]**2 +x[1]**2 -1\n # x1, x2 = x\n # return -20 * np.exp(-0.2 * np.sqrt(0.5 * (x1 ** 2 + x2 ** 2))) - np.exp(\n # 0.5 * (np.cos(2 * np.pi * x1) + np.cos(2 * np.pi * x2))) + 20 + np.e\n\n\nconstraint_ueq = (\n lambda x: (x[0] - 1) ** 2 + (x[1] - 0) ** 2 - 0.5 ** 2\n ,\n)\n\nmax_iter = 50\npso = PSO(func=demo_func, n_dim=2, pop=40, max_iter=max_iter, lb=[-2, -2], ub=[2, 2]\n , constraint_ueq=constraint_ueq)\npso.record_mode = True\npso.run()\nprint('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)\n\n\n\n\n","sub_path":"MAX_SUMCORE/demo_pso_ani.py","file_name":"demo_pso_ani.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"489587851","text":"import turingarena as ta\nimport networkx as nx\nimport random\n\n\ndef main():\n test_cases = [\n nx.complete_graph(8),\n star_with_extra_edges(14, 19),\n two_touching_cycles(10, 3),\n two_touching_cycles(5, 22),\n ]\n\n for g in test_cases:\n assert nx.is_connected(g)\n assert not nx.is_bipartite(g)\n\n solved_cases = sum(\n evaluate_test_case(g)\n for g in test_cases\n )\n\n print(f\"You solved {solved_cases} cases out of {len(test_cases)}.\")\n\n\ndef evaluate_test_case(g):\n print(f\"Evaluating on graph with {g.order()} nodes and {g.size()} edges...\")\n\n try:\n run_test_case(g)\n except ta.AlgorithmError as e:\n print(\"Test case failed:\")\n print(e.message)\n return False\n else:\n print(\"Test case OK!\")\n return True\n\n\ndef run_test_case(g):\n with ta.run_algorithm(ta.submission.source) as process:\n process.procedures.solve(\n g.order(),\n g.size(),\n [u for u, v in g.edges()],\n [v for u, v in g.edges()],\n )\n\n cycle_len = process.functions.length()\n\n process.check(cycle_len <= ta.parameters['longest_allowed_walk'], f\"cycle too long\")\n\n cycle = [\n process.functions.get_node(i)\n for i in range(cycle_len)\n ]\n\n print(f\"Answer: {cycle}, checking...\")\n\n for i in range(len(cycle)):\n u, v = cycle[i], cycle[(i+1)%len(cycle)]\n process.check(g.has_edge(u, v), f\"there is no edge ({u}, {v})\")\n process.check(len(cycle) % 2 == 1, f\"not in state 'SLURP'\")\n\ndef star_with_extra_edges(N, M):\n g = nx.star_graph(N)\n g.add_edges_from(random.sample(set(nx.non_edges(g)), M - len(g.edges())))\n return g\n\n\ndef two_touching_cycles(a, b):\n return nx.relabel_nodes(nx.compose(\n nx.cycle_graph(a),\n nx.relabel_nodes(nx.cycle_graph(b), lambda u: a + u - 1),\n ), {\n i: j\n for i, j in enumerate(random.sample(range(a+b-1), a+b-1))\n })\n\n\nmain()\n","sub_path":"evaluator.py","file_name":"evaluator.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"651400377","text":"\"\"\"\nImplement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.\n\nIf such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).\n\nThe replacement must be in-place, do not allocate extra memory.\n\nHere are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.\n1,2,3 → 1,3,2\n3,2,1 → 1,2,3\n1,1,5 → 1,5,1\n\"\"\"\n\"\"\"\n1. start from the end of the list and keep looking for first decreasing element.\n2. Starting from that position, look forward to find the element just larger than the element found at step1.\nor\nstarting from the end of the list, search backwards to find the element that is larger than the element found at step1.\n3. swap elements found at step1 and step2.\n4. If you did not find any element at step1, then, reverse the list by keep swapping the elements at\n the edge as you traverse inwards.\n\"\"\"\n\nclass Solution:\n def swap(self,nums,index1,index2):\n temp=nums[index1]\n nums[index1]=nums[index2]\n nums[index2]=temp\n\n def reverse(self,nums,starting_index):\n ending_index=len(nums)-1\n while starting_index nums[index]:\n found_a_larger_number=True\n break\n if found_a_larger_number == True:\n #swap the numbers\n self.swap(nums,index,index2)\n #reverse all the elements from the end to the location where you found the starting number\n self.reverse(nums,index+1)\n #print(nums)\n\nsol=Solution()\narray=[1,2,3]\nfor index in range(10):\n sol.nextPermutation(array)\n print(array)\n","sub_path":"Coding Interview Questions/next_permutation.py","file_name":"next_permutation.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"576876676","text":"# -*- coding: utf-8 -*-\n# @Date : 2019-09-29\n# @Author : Xinyu Gong (xy_gong@tamu.edu)\n# @Link : None\n# @Version : 0.0\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom models_search.building_blocks_search import CONV_TYPE, NORM_TYPE, UP_TYPE, SHORT_CUT_TYPE, SKIP_TYPE\n\n\nclass Controller(nn.Module):\n def __init__(self, args):\n \"\"\"\n init\n :param args:\n :param cur_stage: varies from 0 to ...\n \"\"\"\n super(Controller, self).__init__()\n self.hid_size = args.latent_dim\n self.total_cells = args.total_cells\n self.hx = []\n self.cx = []\n\n self.tokens0 = [len(CONV_TYPE), len(NORM_TYPE), len(UP_TYPE), len(SHORT_CUT_TYPE)]\n self.tokens1 = [len(CONV_TYPE), len(NORM_TYPE), len(UP_TYPE), len(SHORT_CUT_TYPE), len(SKIP_TYPE) ** 1]\n self.tokens2 = [len(CONV_TYPE), len(NORM_TYPE), len(UP_TYPE), len(SHORT_CUT_TYPE), len(SKIP_TYPE) ** 2]\n\n self.tokens = [self.tokens0, self.tokens1, self.tokens2]\n # self.encoders = nn.ModuleList([nn.Embedding(sum(self.tokens), self.hid_size) for i in range(self.cur_stage)])\n # self.decoders = nn.ModuleList([nn.Linear(self.hid_size, token) for token in self.tokens])\n self.lstm = nn.LSTMCell(self.hid_size, self.hid_size)\n self.cell0_encoder = nn.Embedding(sum(self.tokens0), self.hid_size)\n #self.cell0_lstm = nn.LSTMCell(self.hid_size, self.hid_size)\n self.cell0_decoder = nn.ModuleList([nn.Linear(self.hid_size, token) for token in self.tokens0])\n\n self.cell1_encoder = nn.Embedding(sum(self.tokens1), self.hid_size)\n #self.cell1_lstm = nn.LSTMCell(self.hid_size, self.hid_size)\n self.cell1_decoder = nn.ModuleList([nn.Linear(self.hid_size, token) for token in self.tokens1])\n\n self.cell2_encoder = nn.Embedding(sum(self.tokens2), self.hid_size)\n #self.cell2_lstm = nn.LSTMCell(self.hid_size, self.hid_size)\n self.cell2_decoder = nn.ModuleList([nn.Linear(self.hid_size, token) for token in self.tokens2])\n\n self.cell_encoders_list = [self.cell0_encoder, self.cell1_encoder, self.cell2_encoder]\n self.cell_decoders_list = [self.cell0_decoder, self.cell1_decoder, self.cell2_decoder]\n\n def initHidden(self, batch_size):\n return torch.zeros(batch_size, self.hid_size, requires_grad=False).cuda()\n\n def forward(self, x, hidden, cur_cell, index, entire=False): # index represents the output_type of CONV_TYPE/NORM_TYPE...\n # print(cur_cell,index)\n # if index == 0:\n # embed = x\n # else:\n # embed = self.encoder(x)\n # hx, cx = self.lstm(embed, hidden)\n\n # # decode\n # logit = self.decoders[index](hx)\n\n # return logit, (hx, cx)\n if cur_cell == 0:\n if index == 0:\n embed = x\n else:\n embed = self.cell0_encoder(x)\n hx, cx = self.lstm(embed, hidden)\n\n # decode\n logit = self.cell0_decoder[index](hx)\n elif cur_cell == 1:\n if index == 0:\n embed = x\n else:\n embed = self.cell1_encoder(x)\n hx, cx = self.lstm(embed, hidden)\n\n # decode\n logit = self.cell1_decoder[index](hx)\n else:\n if index == 0:\n embed = x\n else:\n embed = self.cell2_encoder(x)\n hx, cx = self.lstm(embed, hidden)\n\n # decode\n logit = self.cell2_decoder[index](hx)\n\n return logit, (hx, cx)\n\n def sample(self, batch_size, with_hidden=False):\n # x = self.initHidden(batch_size)\n hidden = (self.initHidden(batch_size), self.initHidden(batch_size))\n archs = []\n entropies = []\n selected_log_probs = []\n hiddens = []\n for cur_cell in range(self.total_cells):\n x = self.initHidden(batch_size)\n if archs:\n prev_archs = torch.cat(archs, -1)\n prev_hxs, prev_cxs = hidden\n selected_idx = np.random.choice(len(prev_archs), batch_size) # TODO: replace=False\n selected_idx = [int(x) for x in selected_idx]\n\n #selected_archs = []\n selected_hxs = []\n selected_cxs = []\n\n for s_idx in selected_idx:\n #selected_archs.append(prev_archs[s_idx].unsqueeze(0))\n selected_hxs.append(prev_hxs[s_idx].unsqueeze(0))\n selected_cxs.append(prev_cxs[s_idx].unsqueeze(0))\n #selected_archs = torch.cat(selected_archs, 0)\n hidden = (torch.cat(selected_hxs, 0), torch.cat(selected_cxs, 0))\n entropy = []\n actions = []\n selected_log_prob = []\n for decode_idx in range(len(self.cell_decoders_list[cur_cell])):\n # print(cur_cell,decode_idx)\n logit, hidden = self.forward(x, hidden, cur_cell, decode_idx)\n prob = F.softmax(logit, dim=-1) # bs * logit_dim\n log_prob = F.log_softmax(logit, dim=-1)\n # print(\"log_prob:{}\".format(log_prob))\n entropy.append(-(log_prob * prob).sum(1, keepdim=True)) # list[array(bs * 1)]\n action = prob.multinomial(1) # list[bs * 1]\n actions.append(action)\n # print(\"action_data:{}\".format(action.data))\n op_log_prob = log_prob.gather(1, action.data) # list[bs * 1]\n # Example:\n # >>> t = torch.Tensor([[1,2],[3,4]])\n # >>> torch.gather(t, 1, torch.LongTensor([[0,0],[1,0]]))\n # 1 1\n # 4 3\n # [torch.FloatTensor of size 2x2]\n # print(\"op_log_prob:{}\".format(op_log_prob))\n selected_log_prob.append(op_log_prob)\n tokens = self.tokens[cur_cell]\n x = action.view(batch_size) + sum(tokens[:decode_idx])\n x = x.requires_grad_(False)\n\n hiddens.append(hidden[1])\n archs.append(torch.cat(actions, -1)) # batch_size * len(self.decoders)\n selected_log_probs.append(torch.cat(selected_log_prob, -1)) # list(batch_size * len(self.decoders))\n entropies.append(torch.cat(entropy, -1)) # list(bs * 1)\n\n #hiddens = torch.cat(hiddens, -1)\n archs = torch.cat(archs, -1)\n selected_log_probs = torch.cat(selected_log_probs, -1)\n entropies = torch.cat(entropies, -1)\n\n if with_hidden:\n return archs, selected_log_probs, entropies, hiddens\n\n return archs, selected_log_probs, entropies\n\n","sub_path":"models_search/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":6869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"139825204","text":"from tkinter import *\nimport tkinter.messagebox\nimport math\n\ndef get_input(entry, arg):\n entry.insert(END, arg)\n\ndef all_clear(entry):\n entry.delete(0, END)\n\ndef clear(entry):\n entry.delete((len(entry.get())-1), END)\n\ndef calTan(entry):\n input = entry.get().strip()\n result2 = math.tan((int(input)/180)* math.pi)\n all_clear(entry)\n entry.insert(END, result2)\n\ndef calSin(entry):\n input = entry.get().strip()\n resultSin = math.sin((int(input)/180)* math.pi)\n all_clear(entry)\n entry.insert(END, resultSin)\n\ndef calCos(entry):\n input = entry.get().strip()\n result2 = math.cos((int(input)/180)* math.pi)\n all_clear(entry)\n entry.insert(END, result2)\n\ndef calFac(entry):\n input = entry.get().strip()\n result2 = math.factorial(int(input))\n all_clear(entry)\n entry.insert(END, result2)\n\ndef calSquare(entry):\n input = entry.get().strip()\n result2 = int(input) * int(input)\n all_clear(entry)\n entry.insert(END, result2)\n\ndef calCube(entry):\n input = entry.get().strip()\n result2 = int(input) * int(input) * int(input)\n all_clear(entry)\n entry.insert(END, result2)\n\ndef calFabs(entry):\n input = entry.get().strip()\n result2 = math.fabs(int(input))\n all_clear(entry)\n entry.insert(END, result2)\n\ndef calSqrt(entry):\n input = entry.get().strip()\n result2 = math.sqrt(int(input))\n all_clear(entry)\n entry.insert(END, result2)\n\ndef cal(entry):\n input = entry.get()\n try:\n result = str(eval(input.strip()))\n all_clear(entry)\n entry.insert(END, result)\n except ZeroDivisionError:\n print(\"La variable denominateur est égale à 0.\")\n all_clear(entry)\n\n\ndef quitProgram():\n bg.destroy()\n\ndef modeScientifique():\n calScientifique()\n\ndef modeBasique():\n calBasique()\n\ndef calBasique():\n global bg\n bg.title('Calculatrice')\n for btn in list_button_sci:\n btn.destroy()\n # bg.update_idletasks()\n # bg.geometry(400*200)\n global entry\n entry = Entry(justify='right')\n entry.grid(row=0, column=0, columnspan=5, sticky=N+W+S+E)\n\n button_c = Button(text='C', relief=RIDGE,width=5, command =lambda : clear(entry)).grid(row=4,column=1)\n button0 = Button(text='0', relief=RIDGE,width=5, command =lambda : get_input(entry,'0')).grid(row=4,column=2)\n button_ac = Button(text='AC', relief=RIDGE,width=5, command =lambda : all_clear(entry)).grid(row=4,column=3)\n\n button1 = Button(text='1', relief=RIDGE,width=5, command =lambda : get_input(entry,'1')).grid(row=3,column=1)\n button2 = Button(text='2', relief=RIDGE,width=5, command =lambda : get_input(entry,'2')).grid(row=3,column=2)\n button3 = Button(text='3', relief=RIDGE,width=5, command =lambda : get_input(entry,'3')).grid(row=3,column=3)\n\n button4 = Button(text='4', relief=RIDGE,width=5, command =lambda : get_input(entry,'4')).grid(row=2,column=1)\n button5 = Button(text='5', relief=RIDGE,width=5, command =lambda : get_input(entry,'5')).grid(row=2,column=2)\n button6 = Button(text='6', relief=RIDGE,width=5, command =lambda : get_input(entry,'6')).grid(row=2,column=3)\n\n button7 = Button(text='7', relief=RIDGE,width=5, command =lambda : get_input(entry,'7')).grid(row=1,column=1)\n button8 = Button(text='8', relief=RIDGE,width=5, command =lambda : get_input(entry,'8')).grid(row=1,column=2)\n button9 = Button(text='9', relief=RIDGE,width=5, command =lambda : get_input(entry,'9')).grid(row=1,column=3)\n\n\n button_plus = Button(text='+', relief=RIDGE,width=5, command =lambda : get_input(entry,'+')).grid(row=1,column=4)\n button_minus = Button(text='-', relief=RIDGE,width=5, command =lambda : get_input(entry,'-')).grid(row=2,column=4)\n button_multi = Button(text='*', relief=RIDGE,width=5, command =lambda : get_input(entry,'*')).grid(row=3,column=4)\n button_div = Button(text='/', relief=RIDGE,width=5, command =lambda : get_input(entry,'/')).grid(row=4,column=4)\n\n button_point = Button(text='.', relief=RIDGE,width=5, command =lambda : get_input(entry,'.')).grid(row=5,column=2)\n button_equ = Button(text='=', relief=RIDGE,width=5, command =lambda : cal(entry)).grid(row=5,column=3)\n\n\ndef calScientifique():\n global bg\n bg.title('Calculatrice scientifique')\n\n global entry\n global list_button_sci\n\n entry.grid(row=0, column=0, columnspan=7, sticky=N+W+S+E)\n buttonTan = Button(text='tan', relief=RIDGE,width=5, command =lambda : calTan(entry))\n buttonTan.grid(row=1,column=5)\n buttonSin = Button(text='sin', relief=RIDGE,width=5, command =lambda : calSin(entry))\n buttonSin.grid(row=2,column=5)\n buttonCos = Button(text='cos', relief=RIDGE,width=5, command =lambda : calCos(entry))\n buttonCos.grid(row=3,column=5)\n buttonFac = Button(text='x!', relief=RIDGE,width=5, command =lambda : calFac(entry))\n buttonFac.grid(row=1,column=6)\n buttonSquare = Button(text='x2', relief=RIDGE,width=5, command =lambda : calSquare(entry))\n buttonSquare.grid(row=2,column=6)\n buttonCube = Button(text='x3', relief=RIDGE,width=5, command =lambda : calCube(entry))\n buttonCube.grid(row=3,column=6)\n buttonFabs = Button(text='fabs', relief=RIDGE,width=5, command =lambda : calFabs(entry))\n buttonFabs.grid(row=4,column=5)\n buttonSqrt = Button(text='sqrt', relief=RIDGE,width=5, command =lambda : calSqrt(entry))\n buttonSqrt.grid(row=4,column=6)\n\n\n list_button_sci.append(buttonTan)\n list_button_sci.append(buttonSin)\n list_button_sci.append(buttonCos)\n list_button_sci.append(buttonFac)\n list_button_sci.append(buttonSquare)\n list_button_sci.append(buttonCube)\n list_button_sci.append(buttonFabs)\n list_button_sci.append(buttonSqrt)\n\n\n\n\n\nif __name__ == '__main__':\n bg = Tk()\n # create a toplevel menu\n menuBar = Menu(bg)\n # display the menu\n bg.config(menu=menuBar)\n\n # create a lower level menu\n aideMenu = Menu(menuBar)\n menuBar.add_cascade(label=\"Aide\", menu=aideMenu)\n aideMenu.add_command(label=\"Open\")\n aideMenu.add_command(label=\"Save\")\n aideMenu.add_separator()\n aideMenu.add_command(label=\"Exit\", command=quitProgram)\n\n modeMenu = Menu(menuBar)\n menuBar.add_cascade(label=\"Mode\", menu=modeMenu)\n modeMenu.add_command(label=\"Mode basique\", command=calBasique)\n modeMenu.add_command(label=\"Mode scientifique\", command=calScientifique)\n\n\n list_button_sci = []\n\n calBasique()\n bg.mainloop()\n","sub_path":"TP2/tp2_1.py","file_name":"tp2_1.py","file_ext":"py","file_size_in_byte":6397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"117924630","text":"from funktio import mysql_connector\n\n\nclass Tuote(object):\n def __init__(self, nimi, hinta, url):\n self.nimi = nimi\n self.hinta = hinta\n self.url = url\n\n\nfilter2ext = {\n 'komponentit': [\n 'kotelo',\n 'intel_prosessori',\n 'amd_prosessori',\n 'kiintolevy',\n 'emolevy',\n 'näytönohjain',\n 'muisti',\n 'virtalähde'\n ],\n 'oheislaitteet': [\n 'näyttö',\n 'hiiri',\n 'näppäimistö',\n 'näppäimistö+hiiri',\n ]\n}\n\ndef class_specifier(text):\n if text in 'komponentit' or text in 'oheislaitteet':\n return False\n else:\n return True\n\ndef class_component_specifier(_class, text):\n if text in filter2ext.get(_class):\n return False\n else:\n return True\n\ndef retviever(query):\n tuotteita = []\n products = mysql_connector.noutaja(query)\n for product in products:\n tuote = Tuote(product[0], product[1], product[2])\n tuotteita.append(tuote)\n return tuotteita\n\n\ndef main():\n while True:\n preference1 = input('Haluatko komponentteja vai oheislaitteita? (komponentit, oheislaitteet)').lower()\n if class_specifier(preference1):\n print('Väärä syöte!')\n else:\n break\n while True:\n for stuff in filter2ext.get(preference1):\n print(stuff)\n preference2 = input('Valitse jokin yllämainituista!').lower()\n if class_component_specifier(preference1, preference2):\n print('Väärä syöte!')\n else:\n break\n print('Haetaan osia...')\n tuote_array = retviever(preference1 + '_' + preference2)\n while True:\n if len(tuote_array) >= 10:\n preference3 = input('Tuotteita on suuri määrä, haluatko järjestellä ne hinnan mukaan? (yes tai no)').lower()\n if preference3 in 'yes':\n tuote_array = sorted(tuote_array, key=lambda product: product.hinta)\n break\n elif preference3 in 'no':\n break\n else:\n print('Väärä syöte!')\n else:\n break\n\n for stuff in tuote_array:\n print('Nimi: ' + stuff.nimi + ' Hinta: ' + str(stuff.hinta) + '\\nURL: ' + stuff.url + '\\n\\n')\n\nif __name__ == '__main__':\n main()","sub_path":"käyttöliittymä.py","file_name":"käyttöliittymä.py","file_ext":"py","file_size_in_byte":2320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"82735178","text":"# The Ghost Trail\n#\n# Author: Soufian Salim \n#\n# URL: \n\n\"\"\"\nFixtures for the initial state of the world\n\"\"\"\n\nfrom random import randrange\nfrom datetime import datetime\nfrom data import DATA, get_string\nfrom things import World, Location, Character\n\n# root location\nworld = World([\n (get_string(\"dawn\"), get_string(\"morning\"), get_string(\"breakfast\")),\n (get_string(\"midday\"), get_string(\"afternoon\"), get_string(\"lunch\")),\n (get_string(\"evening\"), get_string(\"night\"), get_string(\"dinner\"))\n], datetime(1823, 10, 1))\nworld.temperature = -10\n\n# main three locations\nriverbed = Location(DATA[\"locations\"][\"riverbed\"], world)\nforest = Location(DATA[\"locations\"][\"forest\"], world)\ncave = Location(DATA[\"locations\"][\"cave\"], world)\nclearing = Location(DATA[\"locations\"][\"clearing\"], world)\n\nworld.camp = cave # the cave is \"home\" at the start of the game\n\n# links all three basic locations\nclearing.link(riverbed)\nclearing.link(forest)\nclearing.link(cave)\nriverbed.link(forest)\ncave.link(forest)\ncave.link(riverbed)\n\nforest.supplies[\"firewood\"] = randrange(4, 8)\nforest.supplies[\"leaf\"] = randrange(24, 40)\nforest.supplies[\"twig\"] = randrange(12, 24)\nforest.supplies[\"bark\"] = randrange(6, 12)\nriverbed.supplies[\"stone\"] = randrange(6, 12)\n\n# player character\npc = Character(DATA[\"characters\"][\"player\"], world.camp)\npc.name = \"you\"\npc.skills[\"cooking\"] = 1\npc.skills[\"crafting\"] = 1\npc.skills[\"building\"] = 1\npc.skills[\"foraging\"] = 1\npc.skills[\"hunting\"] = 1\npc.skills[\"fishing\"] = 1\npc.skills[\"trapping\"] = 1\npc.skills[\"herbalism\"] = 1\n\nworld.pc = pc # sets the main character\n","sub_path":"src/world.py","file_name":"world.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"197409299","text":"# Two elements of a binary search tree (BST) are swapped by mistake.\r\n#\n# Recover the tree without changing its structure.\r\n#\n# Example 1:\r\n#\n#\n# Input: [1,3,null,null,2]\r\n#\n#   1\r\n#   /\r\n#  3\r\n#   \\\r\n#   2\r\n#\n# Output: [3,1,null,null,2]\r\n#\n#   3\r\n#   /\r\n#  1\r\n#   \\\r\n#   2\r\n#\n#\n# Example 2:\r\n#\n#\n# Input: [3,1,4,null,null,2]\r\n#\n# 3\r\n# / \\\r\n# 1 4\r\n#   /\r\n#   2\r\n#\n# Output: [2,1,4,null,null,3]\r\n#\n# 2\r\n# / \\\r\n# 1 4\r\n#   /\r\n#  3\r\n#\n#\n# Follow up:\r\n#\n#\n# \tA solution using O(n) space is pretty straight forward.\r\n# \tCould you devise a constant space solution?\r\n#\n#\n\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n \n def recoverTree(self, root: TreeNode) -> None:\n \"\"\"\n Do not return anything, modify root in-place instead.\n \"\"\"\n self.First = None\n self.Second = None\n self.prev = TreeNode(float('-inf'))\n def inorder(root):\n if not root:\n return\n inorder(root.left)\n if self.First is None and self.prev.val > root.val:\n self.First = self.prev\n if self.First and self.prev.val > root.val:\n self.Second = root\n self.prev = root\n inorder(root.right)\n inorder(root)\n self.First.val, self.Second.val = self.Second.val, self.First.val\n \n \n","sub_path":"099-recover-binary-search-tree/recover-binary-search-tree.py","file_name":"recover-binary-search-tree.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"357408441","text":"import json\n\nfrom assignment_5 import db_access\n\ndef send_data(data, handler):\n jsonData = json.dumps(data)\n length = len(jsonData)\n handler.send_response(200)\n handler.send_header(\"Content-Type\", \"application/json; charset=UTF-8\")\n handler.send_header(\"Content-Length\", str(length))\n handler.end_headers()\n handler.wfile.write(jsonData.encode())\n\ndef all_area(info):\n data = db_access.get_all_areas()\n send_data(data, info['handler'])\n\ndef location(info):\n area_id = info['match'].group(1)\n data = db_access.get_locations_for_area(area_id)\n send_data(data, info['handler'])\n\ndef categories(info):\n area_id = info['match'].group(1)\n data = db_access.get_categories_for_area(area_id)\n send_data(data, info['handler'])\n\ndef measurements(info):\n location_id = info['match'].group(1)\n data = db_access.get_measurements_for_location(location_id)\n send_data(data, info['handler'])\n\ndef no_match(info):\n handler = info['handler']\n handler.send_response(404)\n handler.end_headers()\n handler.wfile.write((\"Path \" + info[\"path\"] + \" not found\").encode())\n\ndispatch_get = [\n (r'/area$', all_area),\n (r'/area/(\\d+)/location$', location),\n (r'/location/(\\d+)/measurement$', measurements),\n (r'/area/(\\d+)/category$', categories),\n (r'/area/(\\d+)/average_measurement$', average_measurements),\n (r'/area/(\\d+)/number_locations$', number_of_locations),\n (r'', no_match)\n]\n","sub_path":"get_measures.py","file_name":"get_measures.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"168183466","text":"\"\"\"jsPoziom0 URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom api import views\nfrom django.contrib.staticfiles.urls import static\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n #############\n path('1/', views.zelent1),\n path('1JS/', views.zelent1JS, name=\"1JS\"),\n ##########\n path('2/', views.zelent2),\n path('imageTemplate', views.imageTemplate, name=\"imageTemplate\"),\n path('slider/', views.slider, name=\"slider\"),\n ################\n path('szubienica/', views.szubienica, name=\"szubienica\"),\n path('szubienicaJS/', views.szubienicaJS, name=\"szubienicaJS\"),\n ######################\n path('zaokraglenia/', views.zaokraglenia),\n #######################\n path('5/', views.zelent5),\n path('5JS/', views.zelent5JS, name=\"5JS\"),\n]\n","sub_path":"jsPoziom0/jsPoziom0/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"533900258","text":"#!/usr/bin/env python\n\nimport yaml\nimport json\n\nxlist = range(7)\nxlist.append('First Thing')\nxlist.append('Second Thing')\nxlist.append({})\nxlist[-1][\"ip_address\"] = \"172.16.22.22\"\nxlist[-1][\"attribs\"] = range(8)\n\nwith open(\"xfile.yml\" , \"w\") as f:\n yaml.dump(xlist, f)\n\nwith open(\"xfile.json\" , \"w\") as f:\n json.dump(xlist, f)\n \n","sub_path":"makelistfiles.py","file_name":"makelistfiles.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"58546814","text":"import numpy as np\nfrom keras import Sequential\nfrom keras.initializers import RandomUniform\nfrom keras.layers import Dense\nfrom keras.optimizers import SGD\n\n\nclass NeuralNetwork(object):\n def __init__(self, input_nodes, hidden_nodes, output_nodes, lr=None):\n self.input_nodes = input_nodes\n self.hidden_nodes = hidden_nodes\n self.output_nodes = output_nodes\n self.lr = lr\n self.scales_x = []\n self.scales_y = []\n\n input_kernel_range = np.sqrt(6) / (np.sqrt(input_nodes) + np.sqrt(hidden_nodes))\n input_kernel_initializer = RandomUniform(minval=-input_kernel_range, maxval=input_kernel_range)\n input_layer = Dense(input_nodes,\n kernel_initializer=input_kernel_initializer,\n name='input')\n\n hidden_kernel_range = np.sqrt(6) / (np.sqrt(hidden_nodes) + np.sqrt(output_nodes))\n hidden_kernel_initializer = RandomUniform(minval=-hidden_kernel_range, maxval=hidden_kernel_range)\n hidden_layer = Dense(hidden_nodes,\n kernel_initializer=hidden_kernel_initializer,\n name='hidden')\n\n output_layer = Dense(output_nodes,\n name='output')\n\n self.model = Sequential()\n self.model.add(input_layer)\n self.model.add(hidden_layer)\n self.model.add(output_layer)\n\n def train(self, x_train, y_train):\n self.set_normalize_scales(x_train, y_train)\n x_train = self.normalize(x_train, self.scales_x)\n y_train = self.normalize(y_train, self.scales_y)\n\n optimizer = SGD(lr=self.lr)\n self.model.compile(loss='mse', optimizer=optimizer)\n self.model.fit(x_train, y_train, batch_size=20, epochs=500)\n\n def evaluate(self, x_test, y_test):\n x_test = self.normalize(x_test, self.scales_x)\n y_test = self.normalize(y_test, self.scales_y)\n return self.model.evaluate(x_test, y_test)\n\n def predict(self, x):\n x = self.normalize(x, self.scales_x)\n y = self.model.predict(x)\n return self.unnormalize(y, self.scales_y)\n\n def set_normalize_scales(self, x, y):\n for i in range(x.shape[1]):\n mean, std = x[:, i].mean(), x[:, i].std()\n self.scales_x.append([mean, std])\n for i in range(y.shape[1]):\n mean, std = y[:, i].mean(), y[:, i].std()\n self.scales_y.append([mean, std])\n\n @staticmethod\n def normalize(data, scales):\n for i in range(0, len(scales)):\n mean, std = scales[i]\n data[:, i] = (data[:, i] - mean) / std\n return data\n\n @staticmethod\n def unnormalize(data, scales):\n for i in range(0, len(scales)):\n mean, std = scales[i]\n data[:, i] = data[:, i] * std + mean\n return data\n","sub_path":"neural_network.py","file_name":"neural_network.py","file_ext":"py","file_size_in_byte":2840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"644574573","text":"import json\nimport re\nimport urllib.request\nimport fire\n\nfrom pytube import YouTube\n\napi_key = \"ENTER_YOUR_API_KEY_HERE\"\nmaxResults = 100 # the max is 100\n\n# \nif maxResults > 100:\n maxResults = 100\n\ndump = []\n\ndef getComments(vidID, fName: str='allComments'):\n video_id = vidID\n file_name = fName + '.tsv'\n nextPageToken = \"\"\n stop = False\n count = 0\n\n while not stop:\n url = f\"https://www.googleapis.com/youtube/v3/commentThreads?key={api_key}&textFormat=plainText&part=snippet&videoId={video_id}&t&maxResults={maxResults}&pageToken={nextPageToken}\"\n\n json_url = urllib.request.urlopen(url)\n data = json.loads(json_url.read())\n nPT = 'nextPageToken'\n\n # \n if nPT in data:\n nextPageToken = data['nextPageToken']\n else:\n stop = True\n\n # \n nComments = len(data['items'])\n\n # \n for i in range(nComments):\n print(f'Grabbed comment #{i + (count*maxResults)}')\n put = f\"{data['items'][i]['snippet']['topLevelComment']['snippet']['authorDisplayName']}\\t{data['items'][i]['snippet']['topLevelComment']['snippet']['textDisplay']}\".replace('\\n',\" \").replace('\\r',\" \")\n dump.append(put)\n\n # \n count += 1\n\n # \n with open(file_name, \"w+\", encoding='utf-8') as f:\n f.write(\"\\n\".join(dump))\n \ndef main():\n fire.Fire(getComments)\n \nif __name__ == '__main__':\n main()","sub_path":"DumpAllComments.py","file_name":"DumpAllComments.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"44800710","text":"import socket\nimport threading\nimport SocketServer\nimport sys\nimport os\nimport settings\nimport fnmatch\nimport traceback\n\nclass ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):\n\n\tdef __init__(self, request, client_address, server, client):\n\t\tself.client = client\n\t\tself.request = request\n\t\tself.client_address = client_address\n\t\tself.server = server\n\t\tself.setup()\n\t\ttry:\n\t\t\tself.handle()\n\t\tfinally:\n\t\t\tself.finish()\n\n\tdef send_data(self, data):\n\t\tself.request.sendall('%16d' % len(data))\n\t\tconfirm = self.request.recv(1024)\n\t\tself.request.sendall(data)\n\n\tdef send_data_from(self, path):\n\t\tif os.path.isdir(path):\n\t\t\tself.send_data_from_directory(path)\n\t\telse:\n\t\t\tself.send_data_from_file(path)\n\n\tdef send_data_from_directory(self, path):\n\t\tself.send_data(\"mkdir \" + os.path.basename(path))\n\t\tfile_list = os.listdir(path)\n\t\tfor file in file_list:\n\t\t\tnew_path = os.path.join(path,file)\n\t\t\tself.send_data_from(new_path)\n\t\tself.send_data(\"cd ..\")\n\n\tdef send_data_from_file(self, path):\n\t\tfile = open(path,'rb')\n\t\tdata = file.read()\n\t\tself.send_data(\"cp \" + os.path.basename(path))\n\t\tself.send_data(data)\n\t\tconfirm = self.request.recv(1024)\n\t\tfile.close()\n\n\tdef ls(self, directory):\n\t\tdirs = [ name for name in os.listdir(directory) if os.path.isdir(os.path.join(directory, name)) ]\n\t\tfiles = [ name for name in os.listdir(directory) if os.path.isfile(os.path.join(directory, name)) ]\n\t\tfile_list = sorted(dirs) + sorted(files)\n\t\tresponse = []\n\t\tfor file in file_list:\n\t\t\tabs_path = os.path.join(directory,file)\n\t\t\tis_dir = False\n\t\t\tif os.path.isdir(abs_path):\n\t\t\t\tis_dir = True\n\t\t\tresponse.append({'dir':is_dir, 'path':abs_path, 'size':os.path.getsize(abs_path), 'time':os.path.getmtime(abs_path),\n\t\t\t\t\t\t\t 'user_ip': self.client.ip, 'username':self.client.name})\n\t\tself.send_data(str(response))\n\n\tdef cd(self, path):\n\t\tpath = os.path.normpath(path)\n\t\tif os.path.isdir(path):\n\t\t\tif path in settings.SHARE_DIRECTORY or '..' in path:\n\t\t\t\tpath = settings.SHARE_DIRECTORY\n\t\t\tself.ls(path)\n\t\telse:\n\t\t\tself.request.sendall(\"Not a directory!\")\n\n\tdef cp(self, file_list):\n\t\tfor path in file_list:\n\t\t\tself.send_data_from(path)\n\t\tself.request.sendall(\"cd ..\")\n\n\tdef get_matches(self,directory, pattern):\n\t\t\"\"\"\n\t\t\tintoarce lista cu fisierele care se potrivesc cautarii,\n\t\t\taflate in calea curenta\n\t\t\"\"\"\n\t\tresponse = []\n\t\tfor root, dirs, files in os.walk(directory):\n\t\t\tgood_dirs = fnmatch.filter(dirs, pattern)\n\t\t\tgood_files = fnmatch.filter(files, pattern)\n\t\t\tresponse.extend( {'dir': True, 'path': os.path.join(root, d),\n\t\t\t\t\t\t\t'size': os.path.getsize(os.path.join(root, d)),\n\t\t\t\t\t\t\t'time': os.path.getmtime(os.path.join(root, d)),\n\t\t\t\t\t\t\t'user_ip': self.client.ip, 'username': self.client.name} for d in good_dirs)\n\t\t\tresponse.extend( {'dir': False, 'path': os.path.join(root, f),\n\t\t\t\t\t\t\t'size': os.path.getsize(os.path.join(root, f)),\n\t\t\t\t\t\t\t'time': os.path.getmtime(os.path.join(root, f)),\n\t\t\t\t\t\t\t'user_ip': self.client.ip, 'username': self.client.name} for f in good_files)\n\t\treturn response\n\n\n\tdef search(self, pattern, search_id):\n\t\tresponse = self.client.search(pattern,search_id)\n\t\tself.send_data(str(response))\n\n\tdef get_connections(self, search_id, level):\n#\t\tself.client.searches.append(search_id)\n\t\tcons = self.client.check_connections(level=level, search_id=search_id)\n\t\tself.send_data(str(cons))\n\n\tdef get_command(self, line):\n\t\tline = line.split(' ', 1)\n\t\tcommand = line[0]\n\t\tif len(line) == 2:\n\t\t\targs = line[1]\n\t\telse:\n\t\t\targs = None\n\t\treturn (command, args)\n\n\tdef handle(self):\n\t\ttry:\n\t\t\tcommand = \"\"\n\t\t\twhile command != \"quit\":\n\t\t\t\tcommand, args = self.get_command(self.request.recv(1024))\n\t\t\t\tif command == \"ls\":\n\t\t\t\t\tself.ls(settings.SHARE_DIRECTORY)\n\t\t\t\telif command == \"cd\":\n\t\t\t\t\tself.cd(args)\n\t\t\t\telif command == \"cp\":\n\t\t\t\t\tself.cp(eval(args))\n\t\t\t\telif command == \"search\":\n\t\t\t\t\tsearch_id, pattern = args.split(' ')\n\t\t\t\t\tself.search(pattern, search_id)\n\t\t\t\telif command == \"get_connections\":\n\t\t\t\t\tindex, level = args.split(' ')\n\t\t\t\t\tself.get_connections(index, level)\n\n\t\tfinally:\n\t\t\tpass\n\t\t\t#logout\n\n\nclass ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):\n\tdaemon_threads = True\n\tdef __init__(self, server_address, RequestHandlerClass, client):\n\t\tSocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass)\n\t\tself.client = client\n\n\tdef finish_request(self, request, client_address):\n\t\t\"\"\"Finish one request by instantiating RequestHandlerClass.\"\"\"\n\t\tself.RequestHandlerClass(request, client_address, self, self.client)\n\nclass Server():\n\tdef __init__(self, client, **kwargs):\n\t\tself.port = kwargs.get('port', settings.PORT)\n\t\tself.ip = kwargs.get('ip', settings.HOST)\n\t\tself.socket_server = ThreadedTCPServer((self.ip, self.port), ThreadedTCPRequestHandler, client)\n\t\tself.share_directory = settings.SHARE_DIRECTORY\n\t\tself.online_users = []\n\t\tself.offline_users = []\n\t\tself.server_thread = threading.Thread(target=self.socket_server.serve_forever)\n\t\tself.server_thread.daemon = True\n\t\tself.server_thread.start()\n\t\tself.client = client\n\n\tdef __str__(self):\n\t\tinfo = (self.ip, self.port, self.username, self.share_directory)\n\t\treturn \"ip: %s | port: %s | username: %s | share_directory %s\" % info\n","sub_path":"tests/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"87549397","text":"\nimport docker\n\ndockerfile_path = '../hyperbolics/Docker/'\n\nif __name__ == \"__main__\":\n client = docker.from_env()\n client.images.build(path = dockerfile_path)\n container = client.containers.run(image = 'hyperbolics/gpu', \n name = 'MTNCI-HyperE', \n volumes = {'$PWD' : {'bind': '/root/hyperbolics'}},\n command = 'julia combinatorial/comb.jl -d data/edges/edgelist -m hyper.r64.emb -e 1.0 -p 64 -r 64 -a -s',\n log_config = {\"Type\" : \"json-file\", \"Config\" : {}},\n runtime = 'nvidia',\n detach = True)\n container.logs()\n","sub_path":"preprocessing/docker_test.py","file_name":"docker_test.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"465747760","text":"import random\nrandom.seed(871024)\n\nimport sys\n\nrf = open(\"corpus.txt\", \"r\")\nwf = open(\"train_original.txt\", \"w\")\nappend = False\nsentence = \"\"\nfor line in rf.readlines():\n tmp = line.strip('\\n')\n if append == True:\n case = 0\n if len(tmp) > 1:\n case = random.choice(range(2))\n if case == 0:\n control = random.sample(range(len(tmp)), 1)[0]\n wf.write(sentence + \" \" + str(control + 1) + ' ' + tmp[control] + '\\n')\n else:\n controls = sorted(random.sample(range(len(tmp)), 2))\n wf.write(sentence + \" \" + str(controls[0] + 1) + ' ' + tmp[controls[0]] + ' ' + str(controls[1] + 1) + ' ' + tmp[controls[1]] + '\\n')\n else:\n append = True\n sentence = \" \"\n for c in tmp:\n sentence += c + ' '\n sentence += \"\"\n\n\n\n","sub_path":"HW2_ExplainableAI/src/data_generating.py","file_name":"data_generating.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"457724114","text":"\nimport boto3 \nfrom boto3.dynamodb.conditions import Attr\n\ndef scan_protestors(event):\n \"\"\"\n Returns a dictionary of the number of people who went to protests in certain month\n \n Inputs: event\n \n Output: dictionary with key = month and value = number of people who participated\n that month \n \n \"\"\"\n months = [\"01\",\"02\", \"03\", \"04\", \"05\", \"06\", \"07\", \"08\", \"09\", \"10\", \"11\", \"12\"]\n month_frequency = {}\n dynamodb = boto3.resource('dynamodb', region_name='us-east-1')\n # table = dynamodb.Table('Books')\n table = dynamodb.Table('ProtestorTbl')\n \n # When making a Query API call, we use the KeyConditionExpression parameter to specify the hash key on which we want to query.\n # We're using the Key object from the Boto3 library to specify that we want the attribute name (\"Author\")\n # to equal \"John Grisham\" by using the \".eq()\" method.\n for mon in months:\n count = 0\n resp = table.scan(FilterExpression=Attr('protestdate').begins_with(mon))\n print(\"The query returned the following items:\")\n for item in resp['Items']:\n # print(item)\n count += 1\n month_frequency[mon] = count\n \n print(month_frequency)\n return month_frequency\n \ndef lambda_handler(event, context):\n scan_protestors(event) \n","sub_path":"scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"81215432","text":"import linecache\nimport os\nimport io\nimport requests\nimport datetime\nimport pandas\nimport zipfile\nimport re\nimport gzip\nimport time\nimport gc\nimport linecache\nfrom pandas.tseries.offsets import BMonthEnd, BMonthBegin, BDay\nfrom datetime import date\nfrom subprocess import Popen, PIPE\nfrom celery.utils.log import get_task_logger\nfrom celery.decorators import task\n# from celery.task.schedules import crontab\nfrom celery.task import Task, PeriodicTask\nfrom core.models import (Snapshot, SnapshotRestore, ActiveWallet, ActiveWalletProcess, Salary, FocusGroup,\n CollectionCycle, GenericCashin, ActiveWalletReport)\nfrom django.conf import settings\nfrom django.core.files.base import ContentFile\nfrom django.urls import reverse\nfrom django.contrib.auth.models import User\nfrom sqlalchemy import create_engine, text\nfrom sqlalchemy.dialects.mysql import VARCHAR\nfrom sqlalchemy_utils.functions import database_exists, create_database, drop_database\nfrom core.notification import NotificationClient\nfrom django.db.models import signals\nfrom core import signals as core_signals\nfrom core.services.sql_service import SqlService\nfrom core.utils import TempSignalDisconnect\nfrom middleware.core_middleware import CoreMiddlewareClient\nfrom core.core_barrido import CoreBarridoClient\nfrom core.mifos_client import MifosClient\nfrom core.services.cartera_activa_service import CarteraActivaService\nfrom bondi.bondi_client import BondiClient\nfrom core.parsers import datetime_parser\n\nlogger = get_task_logger(__name__)\n\n\n@task()\ndef generate_snapshot_task(snapshot_id, callback):\n logger.info(\"starting generate_snapshot_task id={}\".format(snapshot_id))\n\n snapshot = Snapshot.objects.get(id=snapshot_id)\n headers = {\n \"Authorization\": \"Basic {}\".format(getattr(settings, \"MAMBU_API_AUTHORIZATION\")),\n \"Content-Type\": \"application/json\"\n }\n payload = {\n \"callback\": callback\n }\n url = getattr(settings, \"MAMBU_API_GENERATE_SNAPSHOT\")\n logger.info(\"generating mambu backup:\")\n logger.info(\"headers: {}\".format(headers))\n logger.info(\"url: {}\".format(url))\n logger.info(\"payload: {}\".format(payload))\n response = requests.post(url, headers=headers, json=payload)\n logger.info(\"response: {}\".format(response.content))\n logger.info(\"status code: {}\".format(response.status_code))\n snapshot.status = \"processing\" if response.status_code == 200 else \"cancelled\"\n snapshot.save()\n\n\n@task()\ndef download_snapshot_task(snapshot_id):\n logger.info(\"starting download_snapshot_task id={}, waiting...\".format(snapshot_id))\n time.sleep(5)\n logger.info(\"now yes, starting download_snapshot_task id={}\".format(snapshot_id))\n\n snapshot = Snapshot.objects.get(id=snapshot_id)\n snapshot.status = \"downloading\"\n snapshot.save()\n\n barrido_client = CoreBarridoClient()\n status = barrido_client.get_system_status_report()\n if status.status_code == 200:\n blocked_date = status.json(object_hook=datetime_parser)\n diff = datetime.datetime.now() - blocked_date['last_blocked_accounts_database_datetime']\n days, seconds = diff.days, diff.seconds\n hours = days * 24 + seconds // 3600\n if hours > 24:\n NotificationClient().send_generic(\"AVISO: Se esta generando una Cartera Activa con las bajas de servicio desactualizadas (mas de 24hs). (Snapshot: {})\".format(snapshot_id))\n else:\n NotificationClient().send_generic(\"AVISO: El proceso de Cartera Activa no pudo verificar la antigüedad de los datos de bajas de servicios (Snapshot: {}). Continuando proceso.\".format(snapshot_id))\n\n headers = {\n \"Authorization\": \"Basic {}\".format(getattr(settings, \"MAMBU_API_AUTHORIZATION\")),\n \"Content-Type\": \"application/json\"\n }\n url = getattr(settings, \"MAMBU_API_ENDPOINT_BACKUP\")\n logger.info(\"downloading mambu backup:\")\n logger.info(\"headers: {}\".format(headers))\n logger.info(\"url: {}\".format(url))\n response = requests.get(url, headers=headers, stream=True)\n logger.info(\"status code: {}\".format(response.status_code))\n logger.info(\"response headers: {}\".format(response.headers))\n local_filename = \"dump-{}.zip\".format(datetime.datetime.now().strftime(\"%m-%d-%y-%H%M%S\"))\n os.makedirs(getattr(settings, \"MEDIA_ROOT\"), exist_ok=True)\n with open(os.path.join(getattr(settings, \"MEDIA_ROOT\"), local_filename), 'wb') as f:\n for chunk in response.iter_content(chunk_size=1024):\n if chunk:\n f.write(chunk)\n snapshot.dump.name = local_filename\n snapshot.status = \"finished\"\n snapshot.save()\n logger.info(\"download complete!\")\n\n\n@task()\ndef snapshot_finish_task():\n logger.info(\"starting snapshot_finish_task\")\n\n try:\n keep_qty = int(getattr(settings, \"SNAPSHOTS_TO_KEEP\", 10))\n logger.info(\"snapshots to keep: {}\".format(keep_qty))\n\n logger.info(\"deleting Snapshot\")\n logger.info(\"Snapshot count before deletion: {}\".format(Snapshot.objects.all().count()))\n keep = Snapshot.objects.all().order_by('-created_at')[:keep_qty].values_list(\"id\", flat=True)\n logger.info(\"Snapshot list to deletion: {}\".format(keep))\n Snapshot.objects.exclude(pk__in=list(keep)).delete()\n logger.info(\"Snapshot count after deletion: {}\".format(Snapshot.objects.all().count()))\n except Exception as e:\n logger.info(\"error snapshot_finish_task: {}\".format(e))\n logger.exception(e)\n pass\n\n\n@task()\ndef restore_snapshot_task(snapshot_restore_id):\n logger.info(\"starting restore_snapshot_task id={}, waiting...\".format(snapshot_restore_id))\n time.sleep(5)\n logger.info(\"now yes, starting restore_snapshot_task id={}\".format(snapshot_restore_id))\n\n snapshot_restore = SnapshotRestore.objects.get(id=snapshot_restore_id)\n snapshot_restore.status = \"processing\"\n snapshot_restore.save()\n engine = create_engine(\"mysql://{}:{}@{}/{}\".format(\n settings.MYSQL_USER,\n settings.MYSQL_PASSWORD,\n settings.MYSQL_HOST,\n snapshot_restore.database_name\n ))\n if database_exists(engine.url):\n logger.info(\"db '{}' already exists, skipping process...\".format(snapshot_restore.database_name))\n return\n\n logger.info(\"creating db '{}'\".format(snapshot_restore.database_name))\n create_database(engine.url)\n snapshot_restore.database_status = \"processing\"\n snapshot_restore.save()\n\n logger.info(\"checking file exists: {}\".format(snapshot_restore.snapshot.dump.path))\n exists = os.path.isfile(snapshot_restore.snapshot.dump.path)\n if exists:\n logger.info(\"file exists\")\n else:\n logger.info(\"file doesn't exists\")\n\n start = time.time()\n logger.info(\"unzip dump {}\".format(snapshot_restore.snapshot.dump.path))\n unzip = Popen([\n \"7z\", \"e\", \"-y\", snapshot_restore.snapshot.dump.path,\n \"-o{}/\".format(settings.MEDIA_ROOT)\n ], stdout=PIPE, stderr=PIPE)\n stdout, stderr = unzip.communicate()\n logger.info(stdout)\n logger.info(stderr)\n logger.info(\"unzip complete in {}s\".format(round(time.time() - start, 2)))\n unzip_dumpfile = \"{}/{}.sql\".format(settings.MEDIA_ROOT, settings.MAMBU_BACKUP_SQL_NAME)\n with open(\"{}/wenance_sed.sql\".format(settings.MEDIA_ROOT), 'w') as sed_dumpfile:\n start = time.time()\n logger.info(\"start sed command gljournalentry and activity\")\n dump_sed = Popen([\n \"sed\", \"-n\", \"-e\", \"/LOCK TABLES `gljournalentry`/,/UNLOCK TABLES/d\",\n \"-e\", \"/LOCK TABLES `activity`/,/UNLOCK TABLES/!p\",\n unzip_dumpfile\n ], stdout=sed_dumpfile, stderr=PIPE)\n stdout, stderr = dump_sed.communicate()\n logger.info(stdout)\n logger.info(stderr)\n logger.info(\"sed gljournalentry complete and activity complete in {}s\".format(round(time.time() - start, 2)))\n\n if os.path.isfile(unzip_dumpfile):\n logger.info(\"removing {}\".format(unzip_dumpfile))\n os.remove(unzip_dumpfile)\n\n with open(sed_dumpfile.name, 'r') as sed_dumpfile:\n\n # engine.execute(\"SET GLOBAL FOREIGN_KEY_CHECKS = 0\")\n # engine.execute(\"SET GLOBAL UNIQUE_CHECKS = 0\")\n # engine.execute(\"SET GLOBAL AUTOCOMMIT = 0\")\n start = time.time()\n logger.info(\"processing dumpfile to mysql\")\n proc = Popen([\n # \"mysql\", \"--net-buffer-length=500M --max_allowed_packet=2G\",\n \"mysql\", \"-h{}\".format(settings.MYSQL_HOST), \"-u{}\".format(settings.MYSQL_USER),\n \"-p{}\".format(settings.MYSQL_PASSWORD), snapshot_restore.database_name\n ], stdout=PIPE, stderr=PIPE, stdin=sed_dumpfile)\n stdout, stderr = proc.communicate()\n logger.info(stdout)\n logger.info(stderr)\n # engine.execute(\"SET GLOBAL FOREIGN_KEY_CHECKS = 1\")\n # engine.execute(\"SET GLOBAL UNIQUE_CHECKS = 1\")\n # engine.execute(\"SET GLOBAL AUTOCOMMIT = 1\")\n if os.path.isfile(sed_dumpfile.name):\n logger.info(\"removing {}\".format(sed_dumpfile.name))\n os.remove(sed_dumpfile.name)\n logger.info(\"restore complete in {}s\".format(round(time.time() - start, 2)))\n snapshot_restore.status = \"finished\"\n snapshot_restore.database_status = \"active\"\n snapshot_restore.save()\n logger.info(\"sending notification\")\n NotificationClient().send_generic(\"Finalizó el Restore del Snapshot id={}\".format(snapshot_restore_id))\n logger.info(\"sending notification complete\")\n\n\n@task()\ndef snapshot_restore_finish_task():\n logger.info(\"starting snapshot_restore_finish_task\")\n\n try:\n keep_restore_qty = int(getattr(settings, \"SNAPSHOTS_RESTORE_TO_KEEP\", 4))\n logger.info(\"snapshots_restore to keep: {}\".format(keep_restore_qty))\n\n logger.info(\"deleting SnapshotRestore\")\n logger.info(\"SnapshotRestore count before deletion: {}\".format(SnapshotRestore.objects.all().count()))\n keep_restore = SnapshotRestore.objects.all().order_by('-created_at')[:keep_restore_qty].values_list(\"id\",\n flat=True)\n SnapshotRestore.objects.exclude(pk__in=list(keep_restore)).delete()\n logger.info(\"SnapshotRestore count after deletion: {}\".format(SnapshotRestore.objects.all().count()))\n logger.info(\"finish snapshot_restore_finish_task\")\n except Exception as e:\n logger.info(\"error snapshot_restore_finish_task: {}\".format(e))\n pass\n\n\n@task()\ndef create_active_wallet_task(active_wallet_id):\n msg = \"Starting create_active_wallet_task id={}, waiting 5 seconds...\".format(active_wallet_id)\n logger.info(msg)\n\n time.sleep(5)\n logger.info(\"Now yes, starting create_active_wallet_task id={}\".format(active_wallet_id))\n\n try:\n active_wallet = ActiveWallet.objects.get(id=active_wallet_id)\n active_wallet.status = \"processing\"\n active_wallet.save()\n\n wenance_db_name = settings.MYSQL_WENANCE_DEV if getattr(settings, \"MYSQL_WENANCE_DEV\",\n False) else active_wallet.snapshot_restore.database_name\n logger.info(\"using MYSQL_DB_NAME={}\".format(wenance_db_name))\n\n wenance_engine = create_engine(\"mysql://{}:{}@{}/{}\".format(\n settings.MYSQL_USER,\n settings.MYSQL_PASSWORD,\n settings.MYSQL_HOST,\n wenance_db_name\n ))\n\n core_barrido_engine = create_engine(\"mysql://{}:{}@{}/{}\".format(\n settings.MYSQL_USER,\n settings.MYSQL_PASSWORD,\n settings.MYSQL_HOST,\n settings.CORE_BARRIDO_DB_NAME,\n ))\n\n mifos_engine = create_engine(\"mysql://{}:{}@{}/{}\".format(\n settings.MIFOS_MYSQL_USER,\n settings.MIFOS_MYSQL_PASSWORD,\n settings.MIFOS_MYSQL_HOST,\n settings.MIFOS_DB_NAME\n ))\n\n if not database_exists(core_barrido_engine.url):\n msg = f\"Creating {core_barrido_engine.url} database ...\"\n logger.info(msg)\n create_database(core_barrido_engine.url)\n logger.info(f\"{msg} Done!\")\n\n\n\n # Create Active wallets\n create_active_wallet(wenance_engine)\n\n # Process salary file\n process_salary_file(wenance_db_name, core_barrido_engine, active_wallet)\n\n # Process cross selling active wallet data\n process_cross_selling(wenance_db_name, core_barrido_engine)\n\n # Process focus group\n process_focus_group(wenance_db_name, core_barrido_engine, active_wallet)\n\n # Update initial active wallet\n create_active_wallet_initial_data_manager(core_barrido_engine, wenance_engine, wenance_db_name)\n\n # Create the csv active wallet file for Debito Directo\n create_csv_active_wallet_file(\"create-cartera-activa-csv.sql\", \"debito_directo\", [\"AyN\"],\n wenance_engine, active_wallet.result)\n\n # Create the csv active wallet file for Cobranzas Atencion al Cliente\n create_csv_active_wallet_file(\"create-cartera-activa-cobranzas-csv.sql\", \"cobranza_atencion_cliente\", [\"AyN\"],\n wenance_engine, active_wallet.resultCollection)\n\n # Create the csv active wallet file for Renos\n create_csv_active_wallet_file(\"create-cartera-reno-csv.sql\", \"reno\", [\"input_firstname\", \"input_lastname\"],\n wenance_engine, active_wallet.resultReno)\n\n # Create the csv active wallet file for cuotas cobradas\n try:\n create_csv_cuotas_cobradas_file('create-cartera-cuotas-cobradas-csv.sql', 'cuotas_cobradas', [\"AyN\"],\n wenance_engine, active_wallet.resultFeesCharged)\n except Exception as exc:\n logger.exception('Exception: ' + str(exc) + ' in cartera activa cuotas cobradas')\n\n # Create the csv active wallet file for mifos\n logger.info('Ingreso al metodo mifos')\n try:\n if \"wenance\" == getattr(settings, \"APP_COMPANY\"):\n create_csv_active_wallet_mifos_file('cartera-activa-cs-mifos.sql', 'mifos_ca', [],\n mifos_engine,\n active_wallet.resultMifosCa)\n except Exception as exc:\n logger.exception('Exception: ' + str(exc) + ' in cartera activa mifos')\n logger.info('Salgo del metodo mifos')\n\n logger.info(f\"{msg} Done!\")\n active_wallet.status = \"finished\"\n active_wallet.status_description = \"Carteras generadas satisfactoriamente!\"\n\n active_wallet.save()\n\n except Exception as error:\n msg = f\"{msg} Fail!: {error}\"\n logger.error(msg)\n active_wallet.status = \"error\"\n active_wallet.status_description = msg\n active_wallet.save()\n raise Exception(msg)\n\n msg = \"Sending notification ... \"\n logger.info(msg)\n NotificationClient().send_generic(\"Ya estan disponibles las Carteras!\")\n logger.info(f\"{msg} Done!\")\n\n\ndef create_active_wallet(db_engine):\n execute_sql_sentence(\"DROP TABLE IF EXISTS cartera_activa_f_ultimo_debito\", db_engine)\n execute_sql_sentence(\"DROP TABLE IF EXISTS cartera_activa\", db_engine)\n execute_sql_script(\"create-cartera-activa.sql\", db_engine)\n\n execute_sql_sentence(\"DROP TABLE IF EXISTS cartera_reno\", db_engine)\n execute_sql_script(\"create-cartera-reno.sql\", db_engine)\n execute_sql_script(\"update-cartera-reno.sql\", db_engine)\n\n\ndef process_salary_file(db_name, db_engine, active_wallet):\n # Drop the temporary table client_salary if exists\n execute_sql_sentence(\"DROP TABLE IF EXISTS client_salary\", db_engine)\n\n fn_s = active_wallet.salary.salary_csv.path\n msg = f\"Processing salary csv file {fn_s} ...\"\n logger.info(msg)\n try:\n # Fill the temporary table client_salary with the data in the csv file\n salary_csv = pandas.read_csv(active_wallet.salary.salary_csv.path, delimiter=\";\", quotechar='\"',\n index_col=0, decimal=\",\")\n salary_csv.to_sql(\"client_salary\", if_exists='replace', con=db_engine)\n logger.info(db_engine.execute(\"describe client_salary\").fetchall())\n logger.info(f\"{msg} Done!\")\n\n # Update the table cartera_activa with the salaries\n msg = \"Updating the table cartera_activa with the salaries ...\"\n logger.info(msg)\n update_sql = text(\n \"UPDATE `{}`.cartera_activa ca JOIN `{}`.client_salary s ON s.dni = ca.dni SET ca.sueldo = s.sueldos;\".format(\n db_name, settings.CORE_BARRIDO_DB_NAME))\n db_engine.execute(update_sql)\n logger.info(f\"{msg} Done!\")\n\n except Exception as error:\n msg = f\"{msg} Fail!: {error}\"\n raise Exception(msg)\n\n\ndef create_csv_active_wallet_file(sql_select_csv_fn, output_csv_fn, columns_name_to_filter, db_engine,\n active_wallet_result, cartera_activa_table_name=\"cartera_activa\"):\n msg = f\"Reading {sql_select_csv_fn} ...\"\n try:\n logger.info(msg)\n sql_file_csv = open(os.path.join(settings.MYSQL_SQL_DIR, sql_select_csv_fn))\n logger.info(f\"{msg} Done!\")\n\n msg = f\"Executing pandas.read_sql for {sql_select_csv_fn} ...\"\n logger.info(msg)\n result = pandas.read_sql(sql=text(sql_file_csv.read().strip().format(cartera_activa_table_name)), con=db_engine)\n logger.info(f\"{msg} Done!\")\n\n pattern = re.compile('[^a-zA-Z0-9\\-._: \\.\\(\\)\\/]')\n msg = f\"Removing characters '{pattern}' by '_' for {sql_select_csv_fn} data ...\"\n logger.info(msg)\n for columns_name in columns_name_to_filter:\n result[columns_name] = result[columns_name].str.replace(pattern, '_')\n logger.info(f\"{msg} Done!\")\n fn = f'{output_csv_fn}_{datetime.datetime.now().strftime(\"%m-%d-%y-%H%M%S\")}.zip'\n msg = f\"Writing csv file {fn}... \"\n logger.info(msg)\n result_csv = result.to_csv(header=False, decimal=',', index=False, encoding='utf-8-sig')\n zipbuff = io.BytesIO()\n with zipfile.ZipFile(zipbuff, \"a\", zipfile.ZIP_DEFLATED, False) as zip_file:\n zip_file.writestr(f\"results_{output_csv_fn}.csv\", result_csv.encode('utf-8-sig'))\n result = None\n result_csv = None\n gc.collect()\n active_wallet_result.save(fn, ContentFile(zipbuff.getvalue()))\n logger.info(f\"{msg} Done!\")\n except Exception as error:\n msg = f\"{msg} Fail!: {error}\"\n raise Exception(msg)\n\n\ndef create_csv_cuotas_cobradas_file(sql_select_csv_fn, output_csv_fn, columns_name_to_filter, db_engine,\n active_wallet_result, cartera_activa_table_name=\"cartera_activa\"):\n msg = f\"Reading {sql_select_csv_fn} ...\"\n try:\n logger.info(msg)\n sql_file_csv = open(os.path.join(settings.MYSQL_SQL_DIR, sql_select_csv_fn))\n\n logger.info(f\"{msg} Done!\")\n d = date.today()\n offset = BMonthEnd()\n date2 = str(offset.rollforward(d) - BDay(2))[:-9]\n date1 = str(offset.rollback(d) - BDay(1))[:-9]\n\n data = sql_file_csv.read().replace('$1', date1).replace('$2', date2)\n\n msg = f\"Executing pandas.read_sql for {sql_select_csv_fn} ...\"\n logger.info(msg)\n result = pandas.read_sql(sql=text(data.format(cartera_activa_table_name)), con=db_engine)\n logger.info(f\"{msg} Done!\")\n\n pattern = re.compile('[^a-zA-Z0-9\\-._: \\.\\(\\)\\/]')\n msg = f\"Removing characters '{pattern}' by '_' for {sql_select_csv_fn} data ...\"\n logger.info(msg)\n for columns_name in columns_name_to_filter:\n result[columns_name] = result[columns_name].str.replace(pattern, '_')\n logger.info(f\"{msg} Done!\")\n fn = f'{output_csv_fn}_{datetime.datetime.now().strftime(\"%m-%d-%y-%H%M%S\")}.zip'\n msg = f\"Writing csv file {fn}... \"\n logger.info(msg)\n result_csv = result.to_csv(header=False, decimal=',', index=False, encoding='utf-8-sig')\n zipbuff = io.BytesIO()\n with zipfile.ZipFile(zipbuff, \"a\", zipfile.ZIP_DEFLATED, False) as zip_file:\n zip_file.writestr(f\"results_{output_csv_fn}.csv\", result_csv.encode('utf-8-sig'))\n result = None\n result_csv = None\n gc.collect()\n active_wallet_result.save(fn, ContentFile(zipbuff.getvalue()))\n logger.info(f\"{msg} Done!\")\n except Exception as error:\n msg = f\"{msg} Fail!: {error}\"\n raise Exception(msg)\n\n\ndef create_csv_active_wallet_mifos_file(sql_select_csv_fn, output_csv_fn, columns_name_to_filter, db_engine,\n active_wallet_result, cartera_activa_table_name=\"cartera_activa\"):\n msg = f\"Reading {sql_select_csv_fn} ...\"\n try:\n logger.info(msg)\n sql_file_csv = open(os.path.join(settings.MYSQL_SQL_DIR, sql_select_csv_fn))\n logger.info(f\"{msg} Done! Paso 1\")\n\n msg = f\"Executing pandas.read_sql for {sql_select_csv_fn} ...\"\n logger.info(msg)\n sql_var = sql_file_csv.read().strip().format(cartera_activa_table_name)\n result = pandas.read_sql(sql=text(sql_var), con=db_engine)\n logger.info(f\"{msg} Done! Paso 2\")\n\n pattern = re.compile('[^a-zA-Z0-9\\-._: \\.\\(\\)\\/]')\n msg = f\"Removing characters '{pattern}' by '_' for {sql_select_csv_fn} data ...\"\n logger.info(msg)\n for columns_name in columns_name_to_filter:\n result[columns_name] = result[columns_name].str.replace(pattern, '_')\n logger.info(f\"{msg} Done! Paso 3\")\n fn = f'{output_csv_fn}_{datetime.datetime.now().strftime(\"%m-%d-%y-%H%M%S\")}.zip'\n msg = f\"Writing csv file {fn}... \"\n logger.info(msg)\n result_csv = result.to_csv(header=False, decimal=',', index=False, encoding='utf-8-sig')\n zipbuff = io.BytesIO()\n with zipfile.ZipFile(zipbuff, \"a\", zipfile.ZIP_DEFLATED, False) as zip_file:\n zip_file.writestr(f\"results_{output_csv_fn}.csv\", result_csv.encode('utf-8-sig'))\n result = None\n result_csv = None\n gc.collect()\n active_wallet_result.save(fn, ContentFile(zipbuff.getvalue()))\n logger.info(f\"{msg} Done! Paso 4\")\n except Exception as error:\n logger.error(error)\n msg = f\"{msg} - Exception mifos file Fail!: {error}\"\n raise Exception(msg)\n\n\ndef process_focus_group(wenance_db_name, db_engine, active_wallet):\n # Drop the temporary table client_focus_group if exists\n execute_sql_sentence(\"DROP TABLE IF EXISTS client_focus_group\", db_engine)\n\n try:\n if active_wallet.focusgroup:\n msg = f\"Processing focus group csv file {active_wallet.focusgroup.focusgroup_csv.path} ...\"\n logger.info(msg)\n focusgroup_csv = pandas.read_csv(active_wallet.focusgroup.focusgroup_csv.path, delimiter=\",\",\n quotechar='\"', index_col=0, decimal=\",\")\n focusgroup_csv.to_sql(\"client_focus_group\", if_exists='replace', con=db_engine)\n logger.info(db_engine.execute(\"describe client_focus_group\").fetchall())\n logger.info(f\"{msg} Done!\")\n\n msg = \"Updating client focus group ...\"\n logger.info(msg)\n update_sql = text(\n \"UPDATE `{}`.cartera_activa ca JOIN {}.client_focus_group f \"\n \"ON f.dni = ca.dni SET ca.Grupo = f.grupo;\".format(\n wenance_db_name, settings.CORE_BARRIDO_DB_NAME)\n )\n db_engine.execute(update_sql)\n logger.info(f\"{msg} Done!\")\n else:\n logger.info(\"Active wallet without focus group!\")\n\n except Exception as error:\n msg = f\"{msg} Fail!: {error}\"\n raise Exception(msg)\n\n\ndef process_cross_selling(db_name, db_engine, ca_table_name = \"cartera_activa\"):\n execute_sql_sentence(\"DROP TABLE IF EXISTS cross_selling_active_wallet\", db_engine)\n\n if getattr(settings, \"MIFOS_URL\", False):\n try:\n msg = \"Getting cross selling active wallet data from FINERACT ... \"\n logger.info(msg)\n mifos_wallet = MifosClient().export_active_wallet()\n logger.info(f\"{msg} Done!\")\n\n if mifos_wallet.status_code == 200:\n msg = \"Cross selling active wallet return status 200! Processing ...\"\n logger.info(msg)\n mifos_wallet_csv = pandas.read_csv(io.BytesIO(mifos_wallet.content), delimiter=\",\", quotechar='\"',\n decimal=\".\")\n mifos_wallet_csv.to_sql(\"cross_selling_active_wallet\", if_exists='replace', con=db_engine)\n logger.info(f\"{msg} Done!\")\n\n msg = \"Indexing cross selling table...\"\n logger.info(msg)\n execute_sql_sentence(\"CREATE INDEX cross_selling_active_wallet__external_id ON cross_selling_active_wallet (externalId)\", db_engine)\n\n msg = \"Updating cartera_activa with cross selling active wallet data...\"\n logger.info(msg)\n update_sql = text(\n \"UPDATE `{}`.{} ca JOIN {}.cross_selling_active_wallet s \"\n \"ON s.externalId = ca.Id_Cliente SET ca.Deuda_crossselling = s.totalDue;\".format(\n db_name, ca_table_name, settings.CORE_BARRIDO_DB_NAME)\n )\n db_engine.execute(update_sql)\n\n logger.info(f\"{msg} Done!\")\n\n else:\n logger.info(\"Error calling cross selling active wallet: {} | {}\".format(mifos_wallet.status_code,\n mifos_wallet.reason))\n\n except Exception as error:\n msg = f\"{msg} Fail!: {error}\"\n raise Exception(msg)\n\n else:\n logger.info(\"Cross selling active wallet process inactive!\")\n\n\ndef execute_sql_script(sql_script_fn, db_engine, cartera_activa_table_name='cartera_activa'):\n msg = f\"Processing SQL file script '{sql_script_fn}'\"\\\n f\"with params '{settings.CORE_BARRIDO_DB_NAME}' as 'core barrido' schema, '{settings.MYSQL_NAME}'\"\\\n f\"as Mambu schema, and '{cartera_activa_table_name}' as 'cartera activa' table ...\"\n try:\n logger.info(msg)\n sql_file = open(os.path.join(settings.MYSQL_SQL_DIR, sql_script_fn))\n sql_script = text(sql_file.read().strip().format(settings.CORE_BARRIDO_DB_NAME, settings.MYSQL_NAME,\n cartera_activa_table_name))\n db_engine.execute(sql_script)\n logger.info(f\"{msg} Done!\")\n\n except Exception as error:\n msg = f\"{msg} Fail!: {error}\"\n raise Exception(msg)\n\n\ndef execute_sql_sentence(sql_sentence, db_engine):\n msg = f\"Executing '{sql_sentence}' ...\"\n try:\n logger.info(msg)\n db_engine.execute(sql_sentence)\n logger.info(f\"{msg} Done!\")\n except Exception as error:\n msg = f\"{msg} Fail!: {error}\"\n raise Exception(msg)\n\n\ndef create_active_wallet_initial_data_manager(core_barrido_engine, wenance_engine, db_name):\n try:\n collection = CollectionCycle.objects.filter(start_process_date=datetime.date.today()).first()\n if collection:\n execute_sql_sentence(\"DROP TABLE IF EXISTS cartera_activa_inicial\", core_barrido_engine)\n\n execute_sql_sentence(\n \"CREATE TABLE cartera_activa_inicial SELECT * FROM `{}`.cartera_activa\".format(db_name),\n core_barrido_engine)\n\n execute_sql_sentence(\"CREATE INDEX cartera_activa_init_ID_IDX USING BTREE ON cartera_activa_inicial (Id)\",\n core_barrido_engine)\n\n else:\n check = core_barrido_engine.execute(\"SHOW TABLES LIKE 'cartera_activa_inicial'\").fetchall()\n if len(check) < 1:\n execute_sql_sentence(\n \"CREATE TABLE cartera_activa_inicial SELECT * FROM `{}`.cartera_activa\".format(db_name),\n core_barrido_engine)\n execute_sql_sentence(\n \"CREATE INDEX cartera_activa_init_ID_IDX USING BTREE ON cartera_activa_inicial (Id)\",\n core_barrido_engine)\n\n execute_sql_script(\"update-cartera-activa.sql\", wenance_engine)\n\n if collection:\n fn = \"create-cartera-activa-inicial-csv.sql\"\n msg = f\"Reading SQL file script {fn} ...\"\n logger.info(msg)\n sql_file_csv = open(os.path.join(settings.MYSQL_SQL_DIR, fn))\n result = pandas.read_sql(sql=text(sql_file_csv.read().strip()), con=core_barrido_engine)\n logger.info(f\"{msg} Done!\")\n\n pattern = '[^a-zA-Z0-9\\-._: \\.\\(\\)\\/]'\n msg = f\"Replacing '{pattern}' by '_' for {fn} data ...\"\n logger.info(msg)\n\n result['AyN'] = result['AyN'].str.replace(pattern, '_')\n logger.info(f\"{msg} Done!\")\n\n fn = \"{}.zip\".format(datetime.datetime.now().strftime(\"%m-%d-%y-%H%M%S\"))\n msg = f\"Generating results for initial active wallet in {fn} ...\"\n logger.info(msg)\n result_csv = result.to_csv(header=False, decimal=',', index=False, encoding='utf-8-sig')\n zipbuff = io.BytesIO()\n with zipfile.ZipFile(zipbuff, \"a\", zipfile.ZIP_DEFLATED, False) as zip_file:\n zip_file.writestr(\"results-cartera-activa-inicial.csv\", result_csv.encode('utf-8-sig'))\n collection.result.save(fn, ContentFile(zipbuff.getvalue()))\n collection.save()\n logger.info(f\"{msg} Done!\")\n\n except Exception as error:\n msg = f\"{msg} Fail!: {error}\"\n raise Exception(msg)\n\n\n@task()\ndef drop_database_task(database_name):\n logger.info(\"drop database {}\".format(database_name))\n drop_database(\"mysql://{}:{}@{}/{}\".format(\n settings.MYSQL_USER,\n settings.MYSQL_PASSWORD,\n settings.MYSQL_HOST,\n database_name\n ))\n\n\n@task()\ndef active_wallet_start_task(active_wallet_process_id):\n logger.info(\"waiting to start active_wallet_start_task id={}\".format(active_wallet_process_id))\n time.sleep(5)\n logger.info(\"now yes, starting active_wallet_start_task id={}\".format(active_wallet_process_id))\n\n active_wallet_process = ActiveWalletProcess.objects.get(id=active_wallet_process_id)\n snapshot_signal_kwargs = {\n 'signal': signals.post_save,\n 'receiver': core_signals.snapshot_handler,\n 'sender': Snapshot,\n }\n with TempSignalDisconnect(**snapshot_signal_kwargs):\n snapshot = Snapshot.objects.create(\n user=active_wallet_process.user,\n )\n callback = \"{}{}\".format(\n getattr(settings, \"APP_BASE_URL\"),\n reverse(\"active_wallet_process_callback\", args=(active_wallet_process.id, snapshot.id))\n )\n generate_snapshot_task(snapshot.id, callback)\n snapshot = Snapshot.objects.get(id=snapshot.id)\n if snapshot.status == \"cancelled\":\n active_wallet_process.change_status(\"failure\")\n else:\n active_wallet_process.change_status(\"mambu_generating\")\n\n\n@task()\ndef active_wallet_finish_task():\n logger.info(\"starting active_wallet_finish_task\")\n\n try:\n keep_qty = getattr(settings, \"SNAPSHOTS_TO_KEEP\", 10)\n keep_restore_qty = getattr(settings, \"SNAPSHOTS_RESTORE_TO_KEEP\", 4)\n logger.info(\"snapshots to keep: {}\".format(keep_qty))\n logger.info(\"snapshots_restore to keep: {}\".format(keep_restore_qty))\n\n logger.info(\"deleting Snapshot\")\n logger.info(\"Snapshot count before deletion: {}\".format(Snapshot.objects.all().count()))\n keep = Snapshot.objects.all().order_by('-created_at')[:keep_qty].values_list(\"id\", flat=True)\n Snapshot.objects.exclude(pk__in=list(keep)).delete()\n logger.info(\"Snapshot count after deletion: {}\".format(Snapshot.objects.all().count()))\n\n logger.info(\"deleting SnapshotRestore\")\n logger.info(\"SnapshotRestore count before deletion: {}\".format(SnapshotRestore.objects.all().count()))\n keep_restore = SnapshotRestore.objects.all().order_by('-created_at')[:keep_restore_qty].values_list(\"id\",\n flat=True)\n SnapshotRestore.objects.exclude(pk__in=list(keep_restore)).delete()\n logger.info(\"SnapshotRestore count after deletion: {}\".format(SnapshotRestore.objects.all().count()))\n logger.info(\"finish active_wallet_finish_task\")\n except Exception as e:\n logger.info(\"error active_wallet_finish_task: {}\".format(e))\n pass\n\n\n@task()\ndef generic_cashin_init_task(generic_cashin_id):\n logger.info(\"waiting to start generic_cashin_init_task id={}\".format(generic_cashin_id))\n time.sleep(5)\n logger.info(\"now yes, starting generic_cashin_init_task id={}\".format(generic_cashin_id))\n\n generic_cashin = GenericCashin.objects.get(id=generic_cashin_id)\n cg_csv = pandas.read_csv(generic_cashin.cashin_csv.path, delimiter=\",\", quotechar='\"', index_col=False, header=0,\n decimal=\".\", usecols=[\"Estado\", \"Importe\", \"Banco\"])\n generic_cashin.bank = cg_csv.head(1).Banco[0]\n resumen = \"Resumen transacciones banco '{}':\".format(generic_cashin.bank)\n data = cg_csv.groupby(['Estado']).Importe.sum()\n for stat, amount in data.iteritems():\n resumen = resumen + \" \" + (stat + \"=\" + str(amount))\n\n generic_cashin.resume = resumen\n\n '''\n name = generic_cashin.cashin_csv.name.replace('results/', '')\n file = generic_cashin.cashin_csv.read()\n\n zipbuff = io.BytesIO()\n with zipfile.ZipFile(zipbuff, \"a\", zipfile.ZIP_DEFLATED, False) as zip_file:ter\n zip_file.writestr(name, file)\n\n generic_cashin.cashin_csv.save(\"{}-{}.zip\".format(name, datetime.datetime.now().strftime(\"%m-%d-%y-%H%M%S\")),\n ContentFile(zipbuff.getvalue())) \n '''\n\n generic_cashin.change_status(\"pending_approve\")\n\n\n@task()\ndef generic_cashin_approve_task(generic_cashin_id):\n generic_cashin = GenericCashin.objects.get(id=generic_cashin_id)\n core_middleware_client = CoreMiddlewareClient()\n\n file = generic_cashin.cashin_csv.read()\n filename = generic_cashin.cashin_csv.name.replace('results/', '')\n\n zipbuff = io.BytesIO()\n with gzip.open(zipbuff, 'wb') as f:\n f.write(file)\n\n response = core_middleware_client.cashin_generic_process(\"generico\",\n consumer_username=generic_cashin.consumer_username,\n file_contents=zipbuff.getvalue(),\n file_name=filename)\n if response.status_code == 202:\n generic_cashin.change_status(\"finished\")\n else:\n generic_cashin.error_detail = response.content\n generic_cashin.change_status(\"error\")\n\n\n@task()\ndef validate_and_auto_process_task():\n logger.info(\"starting validate_and_auto_process_task\")\n snapshot_retore = SnapshotRestore.objects.filter(created_at__date=datetime.date.today()).first()\n if snapshot_retore:\n logger.info(\"validate_and_auto_process_task: restore already created\")\n else:\n logger.info(\"validate_and_auto_process_task: restore not yet created\")\n user = User.objects.filter(username=\"admin\").first()\n if user:\n active_wallet_process = ActiveWalletProcess.objects.create(user=user)\n logger.info(\"validate_and_auto_process_task: active_wallet_process created, id={}\".format(\n active_wallet_process.id))\n else:\n logger.error(\"validate_and_auto_process_task: user 'admin' not exists\")\n\n\n@task()\ndef run_auto_process_task():\n logger.info(\"starting run_auto_process_task\")\n aw_process = ActiveWalletProcess.objects.filter(created_at__date=datetime.date.today(),\n status__in=[\"pending\", \"mambu_generating\", \"downloading\",\n \"restoring\", \"wallet_generating\"]).first()\n if aw_process:\n logger.info(\"run_auto_process_task: process already created\")\n else:\n logger.info(\"run_auto_process_task: process not yet created\")\n user = User.objects.filter(username=\"admin\").first()\n if user:\n active_wallet_process = ActiveWalletProcess.objects.create(user=user)\n logger.info(\"run_auto_process_task: active_wallet_process created, id={}\".format(active_wallet_process.id))\n else:\n logger.error(\"run_auto_process_task: user 'admin' not exists\")\n\n\nclass ActiveWalletCompleteProcess(Task):\n def on_failure(self, exc, task_id, args, kwargs, einfo):\n \"\"\"Error handler.\n\n This is run by the worker when the task fails.\n\n Arguments:\n exc (Exception): The exception raised by the task.\n task_id (str): Unique id of the failed task.\n args (Tuple): Original arguments for the task that failed.\n kwargs (Dict): Original keyword arguments for the task that failed.\n einfo (~billiard.einfo.ExceptionInfo): Exception information.\n Returns:\n None: The return value of this handler is ignored.\n \"\"\"\n logger.info(\"error ActiveWalletCompleteProcess, task_id={}\", task_id)\n logger.exception(exc)\n\n active_wallet_process = ActiveWalletProcess.objects.get(id=args[0])\n active_wallet_process.change_status(\"failure\", failure_reason=\"Step: {}\\nReason: {}\".format(\n active_wallet_process.get_status_display(),\n exc.__str__()\n ))\n\n def run(self, active_wallet_process_id, snapshot_id, *args, **kwargs):\n active_wallet_process = ActiveWalletProcess.objects.get(id=active_wallet_process_id)\n user = active_wallet_process.user\n salary = Salary.objects.last()\n focusgroup = FocusGroup.objects.last()\n snapshot = Snapshot.objects.get(id=snapshot_id)\n active_wallet_process.change_status(\"downloading\")\n download_snapshot_task(snapshot.id)\n snapshot_restore_signal_kwargs = {\n 'signal': signals.post_save,\n 'receiver': core_signals.snapshot_restore_handler,\n 'sender': SnapshotRestore,\n }\n with TempSignalDisconnect(**snapshot_restore_signal_kwargs):\n snapshot_restore = SnapshotRestore.objects.create(\n user=user,\n snapshot=snapshot\n )\n active_wallet_process.change_status(\"restoring\")\n restore_snapshot_task(snapshot_restore.id)\n active_wallet_signal_kwargs = {\n 'signal': signals.post_save,\n 'receiver': core_signals.active_wallet_handler,\n 'sender': ActiveWallet,\n }\n with TempSignalDisconnect(**active_wallet_signal_kwargs):\n active_wallet = ActiveWallet.objects.create(\n user=user,\n snapshot_restore=snapshot_restore,\n salary=salary,\n focusgroup=focusgroup\n )\n active_wallet_process.change_status(\"wallet_generating\")\n create_active_wallet_task(active_wallet.id)\n active_wallet_process.active_wallet = active_wallet\n active_wallet_process.status = \"finished\"\n active_wallet_process.save()\n\n\nclass CleanUp(PeriodicTask):\n run_every = datetime.timedelta(hours=8)\n\n def run(self, *args, **kwargs):\n logger.info(\"starting CleanUp\")\n inspect = self.app.control.inspect()\n for node, tasks in inspect.active().items():\n for current_task in tasks:\n if self.name == current_task.get(\"name\") and not self.request.id == current_task.get(\"id\"):\n logger.info(\"{} is running by worker {}\".format(self.name, node))\n return\n logger.info(\"cleaning\")\n barrido_ui_engine = create_engine(\"mysql://{}:{}@{}\".format(\n settings.MYSQL_USER,\n settings.MYSQL_PASSWORD,\n settings.MYSQL_HOST,\n ))\n databases = [db for (db,) in barrido_ui_engine.execute(\"show databases\") if re.findall(r\"([a-fA-F\\d]{32})\", db)]\n for db in databases:\n queryset = SnapshotRestore.objects.filter(database_name=db)\n if not queryset.exists():\n logger.warning(\n \"deleting snapshot restores with ID's {}\".format(\n \",\".join([str(id) for id in queryset.values_list(\"id\", flat=True)])\n )\n )\n queryset.delete()\n snapshots_orphans = Snapshot.objects.filter(snapshotrestore__isnull=True)\n logger.warning(\n \"deleting snapshots with ID's {}\".format(\n \",\".join([str(id) for id in snapshots_orphans.values_list(\"id\", flat=True)])\n )\n )\n snapshots_orphans.delete()\n\n\n@task()\ndef active_wallet_report_task(active_wallet_report_id):\n logger.info(\"stating active_wallet_report_task id={}\".format(active_wallet_report_id))\n report = ActiveWalletReport.objects.get(id=active_wallet_report_id)\n report.status = \"generating\"\n report.save()\n\n token = getattr(settings, \"BONDI_XPUBTOKEN_CA_REPORT\")\n topic = getattr(settings, \"BONDI_TOPIC_CA_REPORT\")\n message = {\"active_wallet_report_id\": active_wallet_report_id}\n\n logger.info(\"active_wallet_report_task id={} sending message, token={}, topic={}, message={}\".\n format(active_wallet_report_id, token, topic, message))\n response = BondiClient().pub_message(token, topic, message)\n if response:\n logger.info(\"active_wallet_report_task id={} sent successfully\".format(active_wallet_report_id))\n else:\n logger.info(\"active_wallet_report_task id={} sent with error {}:{}\".format(\n active_wallet_report_id, response.status_code, response.reason))\n\n\n@task()\ndef completar_reno(active_wallet_id):\n wa = ActiveWallet.objects.get(id=active_wallet_id)\n cas = CarteraActivaService(wa)\n\n\n@task()\ndef delete_active_wallet_report(active_wallet_report_id):\n logger.info(\"deleting active_wallet_report_manual_task id={}\".format(active_wallet_report_id))\n core_barrido_engine = create_engine(\"mysql://{}:{}@{}/{}\".format(\n settings.MYSQL_USER,\n settings.MYSQL_PASSWORD,\n settings.MYSQL_HOST,\n settings.CORE_BARRIDO_DB_NAME,\n ))\n logger.info(\"DROP TABLE IF EXISTS cartera_activa_{}\".format(active_wallet_report_id))\n core_barrido_engine.execute(\"DROP TABLE IF EXISTS cartera_activa_{}\".format(active_wallet_report_id))\n\n\nclass ActiveWalletReportManual(Task):\n def on_failure(self, exc, task_id, args, kwargs, einfo):\n report = ActiveWalletReport.objects.get(id=args[0])\n report.status = \"error\"\n report.status_description = exc\n logger.exception(exc)\n report.save()\n\n def run(self, active_wallet_report_id):\n logger.info(\"waiting to start active_wallet_report_manual_task id={}\".format(active_wallet_report_id))\n time.sleep(5)\n logger.info(\"now yes, starting active_wallet_report_manual_task id={}\".format(active_wallet_report_id))\n report = ActiveWalletReport.objects.get(id=active_wallet_report_id)\n report.status = \"generating\"\n report.save()\n cas = CarteraActivaService(report)\n cas.prepare()\n cas.jasper_to_sql(report.origin_report, {'Id': VARCHAR(32)})\n report.status = \"processing\"\n report.save()\n process_info_csv(cas, report.salary, 'salary')\n process_info_csv(cas, report.focusgroup, 'focusgroup')\n # Process cross selling active wallet data\n\n # TODO: Encapsular (pasarle el cas)\n wenance_engine = create_engine(\"mysql://{}:{}@{}/{}\".format(\n settings.MYSQL_USER,\n settings.MYSQL_PASSWORD,\n settings.MYSQL_HOST,\n cas.database_name\n ))\n # TODO: Encapsular\n process_cross_selling(cas.database_name, wenance_engine, f\"cartera_activa_{report.id}\")\n\n # Create the csv active wallet file for Debito Directo\n errors = 0\n max_errors = 2\n try:\n create_csv_active_wallet_file(\"create-cartera-activa-csv.sql\", \"debito_directo\", [\"AyN\"],\n cas.barrido_engine, report.result,\n cartera_activa_table_name=f\"cartera_activa_{report.id}\")\n except Exception as exc:\n errors = errors + 1\n logger.error(\"Unable to generate create-cartera-activa-csv (see error bellow)\")\n logger.exception(exc)\n\n # Create the csv active wallet file for Cobranzas Atencion al Cliente\n try:\n create_csv_active_wallet_file(\"create-cartera-activa-cobranzas-csv.sql\", \"cobranza_atencion_cliente\", [\"AyN\"],\n cas.barrido_engine, report.resultCollection,\n cartera_activa_table_name=f\"cartera_activa_{report.id}\")\n except Exception as exc:\n errors = errors + 1\n logger.error(\"Unable to generate create-cartera-activa-cobranzas-csv (see error bellow)\")\n logger.exception(exc)\n\n # Create the csv active wallet file for Renos\n # create_csv_active_wallet_file(\"create-cartera-reno-csv.sql\", \"reno\", [\"input_firstname\", \"input_lastname\"],\n # cas.barrido_engine, report.result,\n # cartera_activa_table_name=f\"cartera_activa_{report.id}\")\n\n if errors >= max_errors:\n raise Exception(\"No CSV report could be generated.\")\n\n report.status = \"finished\"\n report.save()\n logger.info(\"finishing active_wallet_report_manual_task\")\n\n\n@task()\ndef active_wallet_report_callback_task(active_wallet_report_id, report_url):\n logger.info(\"Starting active_wallet_report_callback_task\")\n time.sleep(5)\n report = ActiveWalletReport.objects.get(id=active_wallet_report_id)\n report.status = \"generating\"\n cas = CarteraActivaService(report)\n cas.jasper_to_sql(report_url, {'Id': VARCHAR(32)})\n report.status = \"processing\"\n cas.info_csv_to_ca(report.salary.salary_csv, 'salary')\n # cas.csv_to_sql(report.resultReno.file, 'reno')\n report.status = \"finished\"\n report.save()\n logger.info(\"finishing active_wallet_report_callback_task\")\n # Todo, 1 Almacenar archivo zip\n # Todo, 2 Descomprimir csvs\n # Todo, 3 Crear tabla\n\n\ndef process_info_csv(cartera_activa_service, info_model, info_name):\n if info_model is None:\n return\n logger.info(\"executing process_info_csv from '{}'\".format(info_name))\n csv_element = getattr(info_model, f\"{info_name}_csv\")\n cartera_activa_service.info_csv_to_sql(csv_element, info_name)\n cartera_activa_service.info_sql_to_ca(info_name)\n logger.info(\"finished process_info_csv from '{}'\".format(info_name))\n","sub_path":"core/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":47155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"646244377","text":"class Tape:\n\tdef __init__(self, List=[], empty=0):\n\t\tself.right = List if List != [] else [empty]\n\t\tself.left = []\n\t\tself.curr = 0\n\t\tself.empty = empty\n\tdef move(self, n):\n\t\tself.curr += n\n\t\tif self.curr > len(self.right)-1:\n\t\t\tself.right += [self.empty]*(self.curr+1-len(self.right))\n\t\t\tprint('Expanding to the right')\n\t\telif -self.curr > len(self.left):\n\t\t\tself.left += [self.empty]*(-self.curr-len(self.left))\n\tdef add(self, n):\n\t\tobj = self.get() + n\n\t\tif obj < 0: obj = 0\n\t\telif obj > 255: obj = 255\n\t\telif obj not in range(256): raise ValueError()\n\t\tself.put(obj)\n\tdef inc(self):\n\t\tself.add(1)\n\tdef dec(self):\n\t\tself.add(-1)\n\tdef get(self):\n\t\treturn self.right[self.curr] if self.curr >= 0 else self.left[-self.curr - 1]\n\tdef put(self, what):\n\t\tprint('Putting', what, 'to', self.curr)\n\t\tif self.curr >=0:\n\t\t\tself.right[self.curr] = what\n\t\telse:\n\t\t\tself.left[-self.curr - 1] = what\n\tdef __repr__(self):\n\t\treturn ''.join(self.left[::-1] + ['|'] + self.right)\n\tdef clear_repr(self):\n\t\tl = [str(i) for i in self.left]\n\t\tr = [str(i) for i in self.right]\n\t\tif l:\n\t\t\twhile l and l[-1] == self.empty:\n\t\t\t\tl.pop()\n\t\tif r:\n\t\t\twhile r and r[-1] == self.empty:\n\t\t\t\tr.pop()\n\t\treturn '['+']['.join(l[::-1]+r)+']'\n\t\t\nclass Brain:\n\tdef __init__(self, cmdfname, inpfname):\n\t\tself.tape = Tape()\n\t\twith open(cmdfname) as CMD:\n\t\t\tself.commands = Tape([i for i in CMD.read().split('\\n')[0]], '@')\n\t\twith open(inpfname) as INP:\n\t\t\tself.input = Tape([ord(i) for i in INP.read().split('\\n')[0]])\n\t\tself.output = ''\n\t\tself.debug_marker = 0\n\tdef fuck(self):\n\t\tsym = self.commands.get()\n\t\twhile sym != self.commands.empty:\n\t\t\tprint(self.tape.clear_repr())\n\t\t\tif sym == '!':\n\t\t\t\tself.debug_marker += 1\n\t\t\t\tprint('===DEBUG MARKER:', self.debug_marker, '===')\n\t\t\t\tinput()\n\t\t\telif sym == '>': self.tape.move(1)\n\t\t\telif sym == '<': self.tape.move(-1)\n\t\t\telif sym == '+': self.tape.inc()\n\t\t\telif sym == '-': self.tape.dec()\n\t\t\telif sym == '.': self.output += chr(self.tape.get())\n\t\t\telif sym == ',':\n\t\t\t\tself.tape.put(self.input.get())\n\t\t\t\tself.input.move(1)\n\t\t\telif sym == '[':\n\t\t\t\tif self.tape.get() == 0:\n\t\t\t\t\tcount = 1\n\t\t\t\t\twhile count:\n\t\t\t\t\t\tself.commands.move(1)\n\t\t\t\t\t\tcurr = self.commands.get()\n\t\t\t\t\t\tif curr == '[': count += 1\n\t\t\t\t\t\telif curr == ']': count -= 1\n\t\t\telif sym ==']':\n\t\t\t\tif self.tape.get() != 0:\n\t\t\t\t\tcount = 1\n\t\t\t\t\twhile count:\n\t\t\t\t\t\tself.commands.move(-1)\n\t\t\t\t\t\tcurr = self.commands.get()\n\t\t\t\t\t\tif curr == '[': count -= 1\n\t\t\t\t\t\telif curr == ']': count += 1\n\t\t\t\t\t\n\t\t\tself.commands.move(1)\n\t\t\tsym = self.commands.get()\n\t\tprint('Output:', self.output)\n\t\t\t\nbrain = Brain('brainfuck_commands.txt', 'brainfuck_input.txt')\nbrain.fuck()\n","sub_path":"automata/brainfuck.py","file_name":"brainfuck.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"429000287","text":"\"\"\"\n\nExample 02\n\nProcess an directory with many prn files\n\"\"\"\nimport leviutils\n\n# Pass the directory with input files\nparser = leviutils.parser.PeakFitDirectory(dir=\"/path/to/dir\")\n\n# Export output files ( puts in the same directory given)\nparser.export_files() # Export to columns\n\nparser.export_files(lines=True) # Exports to line format\n","sub_path":"examples/ex02.py","file_name":"ex02.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"625012932","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''Formats raw string dump of readelf.'''\n\ndef full_format(raw_dumped_build):\n\t'''Formats dumped gcc build options to more readable look.'''\n\n\tlines_to_format = raw_dumped_build.splitlines(True)\n\t# Deleting first two and last one element's coz we want to iterate through lines slicing them\n\tdel lines_to_format[:2]\n\tdel lines_to_format[-1:]\n\t# slicing lines (first 13 symbols don't matter for us, by task)\n\tlines_to_format = [line[12:] for line in lines_to_format]\n\t# harvesting binary names and their build-options for constructing dictionary\n\tbinaries = []\n\tbuild_options = []\n\ttemporary_options_container = []\n\n\tfor index, line in enumerate(lines_to_format):\n\t\t# defining binary file name (by task it's without '-')\n\t\tif line[0] != '-':\n\t\t\tbinaries.append(line)\n\t\t\t# !!! if no general build-options given, it's still append blank to build_options list !!!\n\t\t\t# !!! need further deleting for proper 'diff' output, or it's ok? !!!\n\t\t\tbuild_options.append(temporary_options_container)\n\t\t\t# it's important to clear temporary options container for further key:value pairs assignment\n\t\t\ttemporary_options_container = []\n\t\t\tcontinue\n\n\t\ttemporary_options_container.append(line)\n\t\t# last harvest before exiting loop (that's why we need enumerate() - to get index)\n\t\tif index + 1 == len(lines_to_format):\n\t\t\tbuild_options.append(temporary_options_container)\n\n\t# add general build options to every unique build options\n\tfor options in reversed(build_options):\n\t\toptions.extend(build_options[0])\n\tdel build_options[0]\n\n\t# sorting list of options\n\tfor options in build_options:\n\t\toptions.sort(key=str.lower)\n\n\t# now we can easily construct a dictionary\n\tformatted_data = {}\n\tfor binary in binaries:\n\t\tfor options in build_options:\n\t\t\tformatted_data[binary] = options\n\n\treturn formatted_data\n\n\ndef brief_format(raw_dumped_build):\n\t'''Returns only binary filenames '''\n\tlines_to_format = raw_dumped_build.splitlines(True)\n\tdel lines_to_format[:2]\n\tdel lines_to_format[-1:]\n\tformatted_data = []\n\n\tfor line in lines_to_format:\n\t\tif line[12] != '-':\n\t\t\tline = line[12:]\n\t\t\tformatted_data.append(line)\n\n\treturn formatted_data\n\n\nif __name__ == '__main__':\n\t\n\traw_data = '''\n\tString dump of section '.GCC.command.line':\n [ 0] -imultiarch x86_64-linux-gnu\n [ 1d] -D_GNU_SOURCE\n [ 2b] hello.cc\n [ 34] -mtune=generic\n [ 43] -march=x86-64\n [ 51] -frecord-gcc-switches\n [ 67] -fstack-protector-strong\n [ 80] -Wformat\n [ 89] -Wformat-security\n '''\n\tformat(raw_data)","sub_path":"gcc_build_options_dumper/format_gcc_build_options.py","file_name":"format_gcc_build_options.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"257192540","text":"import os\nimport re\nimport warnings\nfrom pprint import pprint\n\nimport requests\nimport urllib3\nfrom bs4 import BeautifulSoup\n\n\ndef export_to_tsv(data: list, filepath: str, encoding='utf-8'):\n with open(filepath, mode='w', encoding=encoding) as outfile:\n for row in data:\n row_text = '\\t'.join(row)\n outfile.write(row_text)\n outfile.write('\\n')\n\n\ndef main():\n wikipedia_url = 'https://en.wikipedia.org/wiki/List_of_j%C5%8Dy%C5%8D_kanji'\n page = requests.get(wikipedia_url)\n\n if page.ok:\n soup = BeautifulSoup(page.content)\n table_classname = 'wikitable'\n kanji_table = soup.find(class_=table_classname)\n if kanji_table is None:\n raise Exception(f'The wikipedia page format has been changed!')\n\n # reference https://stackoverflow.com/a/23377804/8364403\n table_data = []\n table_body = kanji_table.find('tbody')\n rows = table_body.find_all('tr')\n\n for row in rows:\n cols = row.find_all('td')\n # extract the text\n row_data = [e.text.strip() for e in cols]\n if len(row_data) < 2:\n warnings.warn(f'{row_data} does not have enough data!')\n continue\n\n # extract kanji number and the kanji itself\n kanji_number = row_data[0]\n if not re.match(r'\\d+', kanji_number):\n # the first row does not contain only number characters.\n warnings.warn(f'{row_data} has non-number character(s) in the first column!') # noqa\n continue\n # kanji_number is still in string format\n\n kanji = row_data[1]\n if len(kanji) < 1:\n # the kanji text is probably empty.\n warnings.warn(f'{row_data} does not have a kanji in the second column!') # noqa\n else:\n # remove reference annotation added by wikipedia\n # only the the first character and skip trailling annotation\n kanji = kanji[:1]\n\n kanji_data = (kanji_number, kanji)\n table_data.append(kanji_data)\n\n # pprint(table_data)\n # print(len(table_data))\n export_to_tsv(table_data, 'jouyou_kanji_list.tsv')\n else:\n print(page.status_code)\n raise Exception(f'The server responses with status code {page.status_code}!') # noqa\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"600089409","text":"# Python bytecode 2.7 (decompiled from Python 2.7)\n# Embedded file name: e:\\jenkins\\workspace\\client_SERENITY\\branches\\release\\SERENITY\\eve\\client\\script\\ui\\station\\lobby.py\nimport blue\nfrom carbon.common.script.util.format import FmtAmt, CaseFoldCompare\nfrom carbonui.control.basicDynamicScroll import BasicDynamicScroll\nfrom carbonui.control.scrollentries import SE_BaseClassCore\nfrom carbonui.primitives.container import Container\nfrom carbonui.primitives.flowcontainer import FlowContainer\nfrom carbonui.primitives.frame import Frame\nfrom carbonui.primitives.line import Line\nfrom carbonui.primitives.sprite import Sprite\nfrom carbonui.util.various_unsorted import SortListOfTuples, NiceFilter\nfrom eve.client.script.ui.control.buttonGroup import ButtonGroup\nfrom eve.client.script.ui.control.buttons import BigButton, ToggleButtonGroup, ToggleButtonGroupButton, Button\nfrom eve.client.script.ui.control.entries import Get as GetListEntry\nfrom eve.client.script.ui.control.eveIcon import GetLogoIcon, CheckCorpID\nfrom eve.client.script.ui.control.eveLabel import CaptionLabel, EveLabelSmall, EveLabelMedium, Label\nfrom eve.client.script.ui.control.eveScroll import Scroll\nfrom eve.client.script.ui.control.eveWindow import Window\nfrom eve.client.script.ui.control.infoIcon import InfoIcon\nfrom eve.client.script.ui.control.tabGroup import TabGroup\nfrom eve.client.script.ui.control.themeColored import LineThemeColored\nfrom eve.client.script.ui.control.utilMenu import UtilMenu\nfrom eve.client.script.ui.quickFilter import QuickFilterEdit\nfrom eve.client.script.ui.station import stationServiceConst\nimport log\nimport sys\nfrom inventorycommon.util import IsNPC\nimport uthread\nimport carbonui.const as uiconst\nimport localization\nimport telemetry\nimport collections\nimport invCont\nimport invCtrl\nimport const\nimport evegraphics.settings as gfxsettings\nfrom eve.client.script.ui.shared.inventory.invWindow import Inventory as InventoryWindow\nfrom utillib import KeyVal\nCOLOR_UNDOCK = (\n 0.75, 0.6, 0.0, 1.0)\nCOLOR_CQ = (0.0, 0.713, 0.75, 1.0)\nMAX_CORP_DESC_LENGTH = 140\nMAX_CORP_DESC_LINES = 1\nBIGBUTTONSIZE = 48\nSMALLBUTTONSIZE = 32\nBUTTONGAP = 4\nAGENTSPANEL = 'agentsPanel'\nGUESTSPANEL = 'guestsPanel'\nOFFICESPANEL = 'officesPanel'\nINVENTORYPANEL = 'inventoryPanel'\n\nclass LobbyToggleButtonGroupButton(ToggleButtonGroupButton):\n\n @apply\n def displayRect():\n fget = ToggleButtonGroupButton.displayRect.fget\n\n def fset(self, value):\n ToggleButtonGroupButton.displayRect.fset(self, value)\n self.label.width = uicore.ReverseScaleDpi(self.displayWidth) - 6\n buttonHeight = uicore.ReverseScaleDpi(self.displayHeight)\n if self.label.textheight < buttonHeight:\n self.label.top = (buttonHeight - self.label.textheight) / 2\n self.label.align = uiconst.CENTERTOP\n else:\n self.label.top = 0\n self.label.align = uiconst.CENTER\n\n return property(**locals())\n\n\nclass CounterBox(Container):\n _number = 0\n\n def ApplyAttributes(self, attributes):\n Container.ApplyAttributes(self, attributes)\n self.label = Label(parent=self, align=uiconst.CENTER, fontPath='res:/UI/Fonts/EveSansNeue-Expanded.otf', fontsize=10)\n Frame(bgParent=self, texturePath='res:/UI/Texture/Shared/counterFrame.png', cornerSize=8, offset=-1, color=(0.2,\n 0.2,\n 0.2,\n 1))\n if 'text' in attributes:\n self.text = attributes.text\n else:\n self.display = False\n\n @apply\n def text():\n\n def fget(self):\n return self._number\n\n def fset(self, value):\n self._number = value\n self.label.text = value\n self.width = max(14, self.label.textwidth + 8)\n self.height = max(14, self.label.textheight)\n if self.label.text:\n self.display = True\n else:\n self.display = False\n\n return property(**locals())\n\n\nclass Lobby(Window):\n __guid__ = 'form.Lobby'\n __notifyevents__ = [\n 'OnCharNowInStation', 'OnCharNoLongerInStation', 'OnProcessStationServiceItemChange', 'OnAgentMissionChange', 'OnStandingSet', 'OnCorporationChanged', 'OnCorporationMemberChanged', 'OnPrimaryViewChanged', 'OnSetDevice']\n default_windowID = 'lobby'\n default_top = 16\n default_width = 223\n default_captionLabelPath = 'UI/Station/StationServices'\n default_pinned = True\n undockCont = None\n undock_button_is_locked = False\n selectedGroupButtonID = None\n\n @staticmethod\n def default_height(*args):\n return uicore.desktop.height - 100\n\n @staticmethod\n def default_left(*args):\n return uicore.desktop.width - Lobby.default_width - 16\n\n def OnPrimaryViewChanged(self, oldViewInfo, newViewInfo):\n self.UpdateCQButton(newViewInfo.name)\n\n def OnSetDevice(self):\n bottom = self.top + self.height\n if bottom > uicore.desktop.height:\n self.height = max(self.default_minSize[1], uicore.desktop.height - self.top)\n right = self.left + self.width\n if right > uicore.desktop.width:\n self.width = max(self.default_minSize[0], uicore.desktop.width - self.left)\n\n def ApplyAttributes(self, attributes):\n self.viewState = sm.GetService('viewState')\n if not settings.user.ui.Get('stationservicebtns', 1):\n minWidth = BIGBUTTONSIZE + (BIGBUTTONSIZE + BUTTONGAP) * 3 + 14\n minHeight = 495\n else:\n minWidth = SMALLBUTTONSIZE + (SMALLBUTTONSIZE + BUTTONGAP) * 5 + 10\n minHeight = 470\n self.default_minSize = (minWidth, minHeight)\n Window.ApplyAttributes(self, attributes)\n self.stationSvc = sm.GetService('station')\n self.guestScroll = None\n self.sr.serviceAccessCache = {}\n self.SetWndIcon(None)\n self.HideHeader()\n self.scope = 'station'\n self.MakeUnKillable()\n self.MakeUnstackable()\n self.SetTopparentHeight(0)\n main = self.sr.main\n main.clipChildren = True\n self.corpLogoParent = Container(name='corpLogoParent', align=uiconst.TOTOP, height=160, parent=main)\n self.corpName = CaptionLabel(parent=main, align=uiconst.TOTOP, name='corpName', uppercase=False)\n self.undockparent = Container(name='undockparent', align=uiconst.TOTOP, height=78, parent=main)\n self.AddCQButton(parent=self.undockparent)\n self.AddUndockButton(parent=self.undockparent)\n EveLabelMedium(text=localization.GetByLabel('UI/Station/StationServices'), align=uiconst.TOTOP, parent=main, bold=True, padding=(6,\n 6,\n 6,\n 0))\n self.serviceButtons = FlowContainer(name='serviceButtons', align=uiconst.TOTOP, parent=main, contentSpacing=(BUTTONGAP, BUTTONGAP), padding=(6,\n 6,\n 3,\n 6))\n btnGroup = ToggleButtonGroup(name='btnGroup', parent=main, align=uiconst.TOTOP, height=32, padding=(6,\n 6,\n 6,\n 6), idx=-1, callback=self.OnButtonGroupSelection, autoHeight=True)\n self.mainButtonGroup = btnGroup\n self.guestsPanel = Container(name=GUESTSPANEL, parent=main, padding=const.defaultPadding)\n self.quickFilter = QuickFilterEdit(name='quickFilterEdit', parent=self.guestsPanel)\n self.quickFilter.ReloadFunction = lambda : self.ShowGuests()\n self.guestScroll = BasicDynamicScroll(parent=self.guestsPanel, padTop=const.defaultPadding + self.quickFilter.height)\n guestSettingsMenu = UtilMenu(menuAlign=uiconst.TOPRIGHT, parent=self.guestsPanel, align=uiconst.TOPRIGHT, GetUtilMenu=self.SettingMenu, texturePath='res:/UI/Texture/SettingsCogwheel.png', width=18, height=18, iconSize=18)\n self.userType = settings.user.ui.Get('guestCondensedUserList', False)\n self.agentsPanel = Container(name=AGENTSPANEL, parent=main, padding=const.defaultPadding)\n self.agentFinderBtn = Button(label=localization.GetByLabel('UI/AgentFinder/AgentFinder'), parent=self.agentsPanel, align=uiconst.CENTERTOP, func=uicore.cmd.OpenAgentFinder)\n self.agentScroll = Scroll(parent=self.agentsPanel, padTop=const.defaultPadding + self.agentFinderBtn.height)\n self.officesPanel = Container(name=OFFICESPANEL, parent=main, padding=const.defaultPadding)\n self.officesButtons = FlowContainer(name='officesButtons', align=uiconst.TOTOP, parent=self.officesPanel, contentSpacing=(4,\n 4), centerContent=True)\n self.officesScroll = Scroll(parent=self.officesPanel, padTop=const.defaultPadding)\n agentsButton = btnGroup.AddButton(AGENTSPANEL, '
' + localization.GetByLabel('UI/Station/Lobby/Agents'), self.agentsPanel, btnClass=LobbyToggleButtonGroupButton, hint=localization.GetByLabel('Tooltips/StationServices/AgentsTab_descrtiption'))\n agentsButton.name = 'stationInformationTabAgents'\n guestsButton = btnGroup.AddButton(GUESTSPANEL, '
' + localization.GetByLabel('UI/Station/Lobby/Guests'), self.guestsPanel, btnClass=LobbyToggleButtonGroupButton, hint=localization.GetByLabel('Tooltips/StationServices/GuestsTab_description'))\n guestsButton.counter = CounterBox(parent=guestsButton, align=uiconst.TOPRIGHT, left=2, top=-5)\n self.guestsButton = guestsButton\n btnGroup.AddButton(OFFICESPANEL, '
' + localization.GetByLabel('UI/Station/Lobby/Offices'), self.officesPanel, btnClass=LobbyToggleButtonGroupButton, hint=localization.GetByLabel('Tooltips/StationServices/OfficesTab_description'))\n activePanel = settings.user.ui.Get('stationsLobbyTabs', AGENTSPANEL)\n if settings.char.windows.Get('dockshipsanditems', 0):\n self.inventoryPanel = Container(name=INVENTORYPANEL, parent=main)\n self.sr.shipsContainer = Container(parent=self.inventoryPanel, state=uiconst.UI_HIDDEN, padding=const.defaultPadding)\n self.sr.itemsContainer = Container(parent=self.inventoryPanel, state=uiconst.UI_HIDDEN, padding=const.defaultPadding)\n tabs = [[localization.GetByLabel('UI/Station/Ships'), self.sr.shipsContainer, self, 'lobby_ships'], [localization.GetByLabel('UI/Station/Items'), self.sr.itemsContainer, self, 'lobby_items']]\n self.inventoryTabs = TabGroup(name='inventoryPanel', parent=self.inventoryPanel, idx=0)\n self.inventoryTabs.Startup(tabs, 'lobbyInventoryPanel', autoselecttab=True, UIIDPrefix='lobbyInventoryPanelTab')\n self.invButton = btnGroup.AddButton(INVENTORYPANEL, '
' + localization.GetByLabel('UI/Station/Lobby/Hangars'), self.inventoryPanel, btnClass=LobbyToggleButtonGroupButton, hint='%s
%s' % (localization.GetByLabel('Tooltips/StationServices/Hangars'), localization.GetByLabel('Tooltips/StationServices/Hangars_description')))\n elif activePanel == INVENTORYPANEL:\n activePanel = AGENTSPANEL\n btnGroup.SelectByID(activePanel)\n myDefaultView = 'hangar' if session.userid % 2 == 1 else 'station'\n curView = collections.namedtuple('FakeViewInfo', ['name'])(settings.user.ui.Get('defaultDockingView', myDefaultView))\n self.OnPrimaryViewChanged(curView, curView)\n self.LoadOwnerInfo()\n self.LoadServiceButtons()\n if self.destroyed:\n return\n else:\n sm.RegisterNotify(self)\n self.UpdateGuestTabText()\n return\n\n def OnButtonGroupSelection(self, buttonID):\n settings.user.ui.Set('stationsLobbyTabs', buttonID)\n self.selectedGroupButtonID = buttonID\n if buttonID == AGENTSPANEL:\n self.ShowAgents()\n elif buttonID == GUESTSPANEL:\n self.ShowGuests()\n elif buttonID == OFFICESPANEL:\n self.ShowOffices()\n elif buttonID == INVENTORYPANEL:\n if not len(self.sr.shipsContainer.children):\n self.LayoutShipsAndItems()\n\n def SettingMenu(self, menuParent):\n showCompact = settings.user.ui.Get('guestCondensedUserList', False)\n menuParent.AddCheckBox(text=localization.GetByLabel('UI/Chat/ShowCompactMemberList'), checked=bool(showCompact), callback=(self.ShowGuests,\n not showCompact))\n\n def AddCQButton(self, parent):\n scale = 1.0\n self.cqCont = Container(name='cqCont', align=uiconst.TOLEFT_PROP, width=0.5, parent=parent, state=uiconst.UI_PICKCHILDREN, padding=3)\n width = 63 * scale\n height = 34 * scale\n self.cqSpriteCont = Container(name='cq', align=uiconst.CENTERTOP, width=width, height=height, top=3, parent=self.cqCont, state=uiconst.UI_NORMAL)\n self.cqSprites = []\n spacing = 30 * scale\n for i in xrange(3):\n s = Sprite(parent=self.cqSpriteCont, texturePath='res:/UI/Texture/classes/Lobby/{0}.png'.format(i + 1), align=uiconst.CENTERTOP, width=-width, height=height, left=0, state=uiconst.UI_DISABLED)\n s.color = COLOR_CQ\n self.cqSprites.insert(0, s)\n\n self.cqLabel = EveLabelMedium(parent=self.cqCont, align=uiconst.CENTERTOP, top=8 + height, width=100)\n self.UpdateCQButton()\n self.cqSpriteCont.OnClick = self.OnCQClicked\n self.cqSpriteCont.OnMouseEnter = self.OnCQMouseEnter\n self.cqSpriteCont.OnMouseExit = self.OnCQMouseExit\n\n def OnCQClicked(self, *args):\n self.OnCQMouseExit()\n for i, s in enumerate(self.cqSprites):\n uicore.animations.SpGlowFadeIn(s, glowColor=(0.8, 0.8, 0.1, 0.3), glowExpand=1, loops=1, duration=1.0, curveType=uiconst.ANIM_WAVE, timeOffset=(3 - i) * 0.1)\n\n if self.IsInCQ():\n self.EnterHangar()\n else:\n self.EnterCQ()\n\n def OnCQMouseEnter(self, *args):\n self.AnimateCQSprites((0.8, 1, 1))\n\n def OnCQMouseExit(self, *args):\n self.AnimateCQSprites(COLOR_CQ[:3])\n\n def AnimateCQSprites(self, endColor):\n for i, s in enumerate(self.cqSprites):\n uicore.animations.SpColorMorphTo(s, startColor=(s.color.r, s.color.g, s.color.b), endColor=endColor, duration=0.1)\n\n def UpdateCQButton(self, viewName=None):\n isInCQ = False\n if viewName is not None:\n isInCQ = viewName == 'station'\n else:\n isInCQ = self.IsInCQ()\n if isInCQ:\n self.cqLabel.text = '
' + localization.GetByLabel('UI/Commands/EnterHangar') + '
'\n else:\n self.cqLabel.text = '
' + localization.GetByLabel('UI/Commands/EnterCQ') + '
'\n self.cqCont.height = self.cqLabel.height + self.cqSpriteCont.height + 6\n return\n\n def IsInCQ(self):\n viewStateSvc = sm.GetService('viewState')\n currentView = viewStateSvc.GetCurrentView()\n if currentView is not None and currentView.name == 'station':\n return True\n else:\n return False\n return\n\n def AddUndockButton(self, parent):\n scale = 1.0\n self.undockCont = Container(name='undockCont', align=uiconst.TORIGHT_PROP, width=0.5, parent=parent, state=uiconst.UI_PICKCHILDREN, padding=3)\n width = 63 * scale\n height = 34 * scale\n self.undockSpriteCont = Container(name='undock', align=uiconst.CENTERTOP, width=width, height=height, top=3, parent=self.undockCont, state=uiconst.UI_NORMAL)\n self.undockSprites = []\n spacing = 30 * scale\n for i in xrange(3):\n s = Sprite(parent=self.undockSpriteCont, texturePath='res:/UI/Texture/classes/Lobby/{0}.png'.format(i + 1), align=uiconst.CENTERTOP, width=width, height=height, left=0, state=uiconst.UI_DISABLED)\n s.color = COLOR_UNDOCK\n self.undockSprites.append(s)\n\n self.undockLabel = EveLabelMedium(parent=self.undockCont, align=uiconst.CENTERTOP, top=8 + height, width=100)\n self.UpdateUndockButton()\n self.undockCont.height = self.undockLabel.height + height + 6\n self.undockSpriteCont.OnClick = self.OnUndockClicked\n self.undockSpriteCont.OnMouseEnter = self.OnUndockMouseEnter\n self.undockSpriteCont.OnMouseExit = self.OnUndockMouseExit\n if self.undock_button_is_locked:\n self._DisableUndockButton()\n\n def OnUndockClicked(self, *args):\n if sm.GetService('station').PastUndockPointOfNoReturn():\n return\n uthread.new(self.AttemptToUndock).context = 'UndockButtonThread'\n\n def LockCQButton(self):\n self.cqCont.opacity = 0.5\n self.cqCont.state = uiconst.UI_DISABLED\n\n def UnlockCQButton(self):\n self.cqCont.opacity = 1.0\n self.cqCont.state = uiconst.UI_NORMAL\n\n def _DisableUndockButton(self):\n if self.undockCont is not None:\n self.undockCont.opacity = 0.5\n self.undockCont.state = uiconst.UI_DISABLED\n return\n\n def _EnableUndockButton(self):\n if self.undockCont is not None:\n self.undockCont.opacity = 1.0\n self.undockCont.state = uiconst.UI_NORMAL\n return\n\n def LockUndockButton(self):\n self.undock_button_is_locked = True\n self._DisableUndockButton()\n\n def UnlockUndockButton(self):\n self.undock_button_is_locked = False\n self._EnableUndockButton()\n\n def AttemptToUndock(self):\n exiting = sm.GetService('station').Exit()\n if exiting:\n self.LockCQButton()\n\n def OnUndockMouseEnter(self, *args):\n self.AnimateUndockSprites((1, 1, 0.8))\n\n def OnUndockMouseExit(self, *args):\n self.AnimateUndockSprites(COLOR_UNDOCK[:3])\n\n def AnimateUndockSprites(self, endColor):\n if sm.GetService('station').PastUndockPointOfNoReturn():\n return\n for i, s in enumerate(self.undockSprites):\n uicore.animations.SpColorMorphTo(s, startColor=(s.color.r, s.color.g, s.color.b), endColor=endColor, duration=0.1)\n\n def SetUndockProgress(self, undockProgress):\n if undockProgress is None:\n self.UpdateUndockButton()\n return\n else:\n i = int(undockProgress * 3)\n if i < 3:\n self.UpdateUndockButton()\n uicore.animations.SpGlowFadeIn(self.undockSprites[i], glowColor=(1.0,\n 1.0,\n 0.8,\n 0.2), glowExpand=1, loops=1, duration=0.2)\n else:\n self.undockLabel.text = '
' + localization.GetByLabel('UI/Station/UndockingConfirmed') + '
'\n for i, s in enumerate(self.undockSprites):\n uicore.animations.StopAllAnimations(s)\n s.glowColor = (0, 0, 0, 0)\n uicore.animations.SpColorMorphTo(s, startColor=(1, 0.8, 0), endColor=(1,\n 0,\n 0), loops=1000, duration=1, curveType=uiconst.ANIM_WAVE, timeOffset=i * 0.1 - 0.5, includeAlpha=False)\n uicore.animations.SpGlowFadeIn(s, glowColor=(1.0, 1.0, 0.8, 0.2), glowExpand=1, loops=1000, duration=1, curveType=uiconst.ANIM_WAVE, timeOffset=i * 0.1)\n\n return\n\n def UpdateUndockButton(self):\n if self.stationSvc.exitingstation:\n self.undockLabel.text = '
' + localization.GetByLabel('UI/Station/AbortUndock') + '
'\n self.LockCQButton()\n else:\n self.undockLabel.text = '
' + localization.GetByLabel('UI/Neocom/UndockBtn') + '
'\n self.UnlockCQButton()\n\n def EnterCQ(self, *args):\n if self.viewState.HasActiveTransition():\n return\n sm.GetService('cmd').CmdEnterCQ()\n\n def EnterHangar(self, *args):\n if self.viewState.HasActiveTransition():\n return\n sm.GetService('cmd').CmdEnterHangar()\n\n def OnScale_(self, *args):\n return\n height = 0\n for each in self.sr.main.children:\n if each.align in (uiconst.TOTOP, uiconst.TOBOTTOM):\n height += each.padTop + each.height + each.padBottom\n\n height += 160\n self.SetMinSize([self.minsize[0], height])\n\n def LayoutShipsAndItems(self):\n self.sr.itemsContainer.Flush()\n itemsContainer = invCont.StationItems(name='stationItems', parent=self.sr.itemsContainer, showControls=True, state=uiconst.UI_NORMAL)\n self.sr.shipsContainer.Flush()\n shipsContainer = invCont.StationShips(name='stationShips', parent=self.sr.shipsContainer, showControls=True, state=uiconst.UI_NORMAL)\n self.invButton.OnDropData = itemsContainer.OnDropData\n self.sr.itemsContainer.OnDropData = itemsContainer.OnDropData\n self.sr.shipsContainer.OnDropData = shipsContainer.OnDropData\n\n def OnProcessStationServiceItemChange(self, stationID, solarSystemID, serviceID, stationServiceItemID, isEnabled):\n if self.destroyed or stationID != eve.session.stationid:\n return\n for icon in self.serviceButtons.children:\n if hasattr(icon, 'stationServiceIDs') and serviceID in icon.stationServiceIDs:\n self.SetServiceButtonState(icon, [serviceID])\n\n def OnAgentMissionChange(self, actionID, agentID, tutorialID=None):\n if self.selectedGroupButtonID == AGENTSPANEL:\n self.ShowAgents()\n\n def OnCorporationChanged(self, corpID, change):\n blue.pyos.synchro.Yield()\n self.LoadButtons()\n\n def OnStandingSet(self, fromID, toID, rank):\n if self.selectedGroupButtonID == AGENTSPANEL:\n self.ShowAgents()\n\n def SetServiceButtonState(self, button, serviceIDs):\n for serviceID in serviceIDs:\n currentstate = sm.GetService('station').GetServiceState(serviceID)\n if currentstate is not None:\n if self.sr.serviceAccessCache.has_key(serviceID):\n del self.sr.serviceAccessCache[serviceID]\n if not currentstate.isEnabled:\n button.Disable()\n button.serviceStatus = localization.GetByLabel('UI/Station/Lobby/Disabled')\n button.serviceEnabled = False\n else:\n button.Enable()\n button.serviceStatus = localization.GetByLabel('UI/Station/Lobby/Enabled')\n button.serviceEnabled = True\n\n return\n\n def LoadServiceButtons(self):\n parent = self.serviceButtons\n parent.Flush()\n icon = None\n stationservicebtns = settings.user.ui.Get('stationservicebtns', 1)\n btnsize = BIGBUTTONSIZE\n if stationservicebtns:\n btnsize = SMALLBUTTONSIZE\n haveServices = self.GetCurrentStationServices()\n for service in reversed(haveServices):\n button = BigButton(parent=parent, width=btnsize, height=btnsize, name=service.name, align=uiconst.NOALIGN)\n button.Startup(btnsize, btnsize, iconOpacity=0.75)\n button.cmdStr = service.command\n button.stationServiceIDs = service.maskServiceIDs\n button.displayName = service.label\n button.OnClick = (self.OnSvcBtnClick, button)\n button.serviceStatus = localization.GetByLabel('UI/Station/Lobby/Enabled')\n button.serviceEnabled = True\n if hasattr(service, 'iconID'):\n button.SetTexturePath(service.iconID)\n else:\n button.SetTexturePath(service.texturePath)\n self.SetServiceButtonState(button, service.maskServiceIDs)\n button.LoadTooltipPanel = self.LoadServiceButtonTooltipPanel\n\n return\n\n def GetCurrentStationServices(self):\n serviceMask = eve.stationItem.serviceMask\n haveServices = []\n for serviceData in stationServiceConst.serviceData:\n if stationServiceConst.serviceIDAlwaysPresent in serviceData.maskServiceIDs:\n haveServices.append(serviceData)\n continue\n elif serviceMask & sum(serviceData.maskServiceIDs) > 0:\n if serviceData.name == 'navyoffices':\n if not sm.GetService('facwar').CheckStationElegibleForMilitia():\n continue\n elif serviceData.name == 'securityoffice':\n if not sm.GetService('securityOfficeSvc').CanAccessServiceInStation(session.stationid2):\n continue\n haveServices.append(serviceData)\n\n return haveServices\n\n def LoadServiceButtonTooltipPanel(self, tooltipPanel, tooltipOwner, *args):\n tooltipPanel.LoadGeneric3ColumnTemplate()\n command = uicore.cmd.commandMap.GetCommandByName(tooltipOwner.cmdStr)\n tooltipPanel.AddCommandTooltip(command)\n if not tooltipOwner.serviceEnabled:\n tooltipPanel.AddLabelMedium(text=localization.GetByLabel('UI/Station/Lobby/Disabled'), color=(1,\n 0,\n 0,\n 1), bold=True, colSpan=tooltipPanel.columns)\n\n def OnSvcBtnClick(self, btn, *args):\n self.CheckCanAccessService(btn.name)\n sm.GetService('station').LoadSvc(btn.name)\n\n def CheckCanAccessService(self, serviceName):\n for serviceData in stationServiceConst.serviceData:\n if serviceData.name == serviceName:\n corpStationMgr = None\n now = blue.os.GetWallclockTime()\n for stationServiceID in serviceData.maskServiceIDs:\n doCheck = 1\n time, result = (None, None)\n if self.sr.serviceAccessCache.has_key(stationServiceID):\n time, result = self.sr.serviceAccessCache[stationServiceID]\n if time + const.MIN * 5 > now:\n doCheck = 0\n if doCheck:\n if corpStationMgr is None:\n corpStationMgr = sm.GetService('corp').GetCorpStationManager()\n try:\n corpStationMgr.DoStandingCheckForStationService(stationServiceID)\n self.sr.serviceAccessCache[stationServiceID] = (now, None)\n except Exception as e:\n self.sr.serviceAccessCache[stationServiceID] = (now, e)\n sys.exc_clear()\n\n time, result = self.sr.serviceAccessCache[stationServiceID]\n if result is not None:\n raise result\n\n return\n\n def LoadButtons(self):\n if self.destroyed:\n return\n else:\n btns = []\n officeExists = sm.GetService('corp').GetOffice() is not None\n canRent = session.corprole & const.corpRoleCanRentOffice == const.corpRoleCanRentOffice\n canMove = session.corprole & const.corpRoleDirector == const.corpRoleDirector\n if canRent and not officeExists:\n rentLabel = localization.GetByLabel('UI/Station/Lobby/RentOffice')\n btns.append([\n rentLabel, self.RentOffice, None])\n if canMove and officeExists:\n btns.append([localization.GetByLabel('UI/Station/Hangar/UnrentOffice'), self.UnrentOffice, None])\n if canMove:\n isHQHere = sm.GetService('corp').GetCorporation().stationID == session.stationid2\n if not isHQHere:\n hqLabel = localization.GetByLabel('UI/Station/Lobby/MoveHeadquartersHere')\n btns.append([hqLabel, self.SetHQ, None])\n if not officeExists and sm.GetService('corp').HasCorpImpoundedItemsAtStation():\n btns.append([localization.GetByLabel('UI/Inventory/ReleaseItems'), self.ReleaseImpoundedItems, None])\n if sm.GetService('corp').DoesCharactersCorpOwnThisStation():\n mgmtLabel = localization.GetByLabel('UI/Station/Lobby/StationManagement')\n btns.append([mgmtLabel,\n self.OpenStationManagement, None])\n if self.destroyed:\n return\n self.officesButtons.Flush()\n for label, func, args in btns:\n Button(parent=self.officesButtons, label=label, func=func, args=args, align=uiconst.NOALIGN)\n\n return\n\n def ReleaseImpoundedItems(self, *args):\n corpStationMgr = sm.GetService('corp').GetCorpStationManager()\n cost = corpStationMgr.GetQuoteForGettingCorpJunkBack()\n if eve.Message('CrpJunkAcceptCost', {'cost': FmtAmt(cost)}, uiconst.YESNO) != uiconst.ID_YES:\n return\n else:\n corpStationMgr.PayForReturnOfCorpJunk(cost)\n sm.GetService('corp').hasImpoundedItemsCacheTime = None\n self.LoadButtons()\n return\n\n def UnrentOffice(self, *args):\n items = invCtrl.StationCorpHangar(divisionID=None).GetItems()\n asked = False\n if len([ item for item in items if item.ownerID == session.corpid ]):\n asked = True\n if eve.Message('crpUnrentOfficeWithContent', {}, uiconst.YESNO) != uiconst.ID_YES:\n return\n if not asked:\n if eve.Message('crpUnrentOffice', {}, uiconst.YESNO) != uiconst.ID_YES:\n return\n corpStationMgr = sm.GetService('corp').GetCorpStationManager()\n sm.GetService('corp').hasImpoundedItemsCacheTime = None\n corpStationMgr.CancelRentOfOffice()\n return\n\n def OpenStationManagement(self, *args):\n uthread.new(uicore.cmd.OpenStationManagement)\n\n def LoadOwnerInfo(self):\n parent = self.corpLogoParent\n parent.Flush()\n corpID = eve.stationItem.ownerID\n size = 128 if CheckCorpID(corpID) else 64\n logo = GetLogoIcon(itemID=corpID, parent=parent, acceptNone=False, state=uiconst.UI_DISABLED, pos=(0, 8, size, size), align=uiconst.CENTERTOP)\n InfoIcon(typeID=const.typeCorporation, itemID=corpID, left=const.defaultPadding, top=20, align=uiconst.TOPRIGHT, parent=parent, idx=0)\n self.corpLogoParent.height = logo.top + logo.height\n if not CheckCorpID(corpID):\n self.corpName.text = '
' + cfg.eveowners.Get(corpID).name\n self.corpName.display = True\n else:\n self.corpName.display = False\n\n def ImVisible(self):\n return bool(self.state != uiconst.UI_HIDDEN and not self.IsCollapsed() and not self.IsMinimized())\n\n def Load(self, key):\n pass\n\n @telemetry.ZONE_METHOD\n def OnCharNowInStation(self, rec):\n if self.destroyed or not session.stationid2:\n return\n else:\n self.UpdateGuestTabText()\n if self.selectedGroupButtonID == GUESTSPANEL:\n charID, corpID, allianceID, warFactionID = rec\n cfg.eveowners.Prime([charID])\n if self.destroyed:\n return\n newcharinfo = cfg.eveowners.Get(charID)\n idx = 0\n for each in self.guestScroll.GetNodes():\n if each.charID == charID:\n return\n if CaseFoldCompare(each.info.name, newcharinfo.name) > 0:\n break\n idx += 1\n\n filteredGuest = None\n guestFilter = self.quickFilter.GetValue()\n if len(guestFilter):\n filteredGuest = NiceFilter(self.quickFilter.QuickFilter, newcharinfo.name)\n if filteredGuest or len(guestFilter) == 0:\n entry = GetListEntry(self.userEntry, {'charID': charID,'info': newcharinfo,'label': newcharinfo.name,'corpID': corpID,'allianceID': allianceID,'warFactionID': warFactionID})\n self.guestScroll.AddNodes(idx, [\n entry])\n return\n\n @telemetry.ZONE_METHOD\n def OnCharNoLongerInStation(self, rec):\n if self.destroyed or not session.stationid2:\n return\n self.UpdateGuestTabText()\n charID, corpID, allianceID, warFactionID = rec\n if self.selectedGroupButtonID == GUESTSPANEL:\n for entry in self.guestScroll.GetNodes():\n if entry.charID == charID:\n self.guestScroll.RemoveNodes([entry])\n return\n\n def ShowGuests(self, condensed=None, *args):\n if self.selectedGroupButtonID != GUESTSPANEL:\n return\n else:\n if condensed is not None:\n settings.user.ui.Set('guestCondensedUserList', condensed)\n self.SetGuestEntryType()\n guests = sm.GetService('station').GetGuests()\n ownerIDs = guests.keys()\n cfg.eveowners.Prime(ownerIDs)\n guestFilter = self.quickFilter.GetValue()\n if len(guestFilter):\n filterData = [ KeyVal(name=cfg.eveowners.Get(charID).name, charID=charID) for charID in ownerIDs ]\n filterGuests = NiceFilter(self.quickFilter.QuickFilter, filterData)\n ownerIDs = [ each.charID for each in filterGuests ]\n if self.destroyed:\n return\n scrolllist = []\n for charID in ownerIDs:\n if charID not in guests:\n continue\n corpID, allianceID, warFactionID = guests[charID]\n charinfo = cfg.eveowners.Get(charID)\n scrolllist.append((charinfo.name.lower(), GetListEntry(self.userEntry, {'charID': charID,'info': charinfo,'label': charinfo.name,'corpID': corpID,'allianceID': allianceID,'warFactionID': warFactionID})))\n\n scrolllist = SortListOfTuples(scrolllist)\n self.guestScroll.Clear()\n self.guestScroll.AddNodes(0, scrolllist)\n self.UpdateGuestTabText()\n return\n\n def UpdateGuestTabText(self):\n numGuests = len(sm.GetService('station').GetGuests())\n self.guestsButton.counter.text = numGuests\n\n def SetGuestEntryType(self):\n if settings.user.ui.Get('guestCondensedUserList', False):\n self.userEntry = 'ChatUserSimple'\n else:\n self.userEntry = 'User'\n\n def ShowAgents(self):\n try:\n agentsSvc = sm.GetService('agents')\n journalSvc = sm.GetService('journal')\n facWarSvc = sm.StartService('facwar')\n standingSvc = sm.StartService('standing')\n epicArcStatusSvc = sm.RemoteSvc('epicArcStatus')\n if self.selectedGroupButtonID != AGENTSPANEL:\n return\n agentMissions = journalSvc.GetMyAgentJournalDetails()[:1][0]\n agentsInStation = agentsSvc.GetAgentsByStationID()[session.stationid2]\n relevantAgents = []\n missionStateDict = {}\n for each in agentMissions:\n missionState, importantMission, missionType, missionName, agentID, expirationTime, bookmarks, remoteOfferable, remoteCompletable, contentID = each\n agent = agentsSvc.GetAgentByID(agentID)\n missionStateDict[agentID] = missionState\n if missionState not in (const.agentMissionStateAllocated, const.agentMissionStateOffered) or agent.agentTypeID in (const.agentTypeGenericStorylineMissionAgent, const.agentTypeStorylineMissionAgent, const.agentTypeEventMissionAgent, const.agentTypeCareerAgent, const.agentTypeEpicArcAgent):\n relevantAgents.append(agentID)\n\n localRelevantAgents = []\n for agent in agentsInStation:\n if agent.agentID in relevantAgents:\n localRelevantAgents.append(agent.agentID)\n\n if self.destroyed:\n return\n scrolllist = []\n sortlist = []\n for agentID in relevantAgents:\n if not eve.rookieState or agentID in const.rookieAgentList:\n if agentID not in localRelevantAgents:\n missionState = missionStateDict.get(agentID)\n sortlist.append((cfg.eveowners.Get(agentID).name,\n GetListEntry('AgentEntry', {'charID': agentID,'missionState': missionState})))\n\n if sortlist:\n agentLabel = localization.GetByLabel('UI/Station/Lobby/AgentsOfInterest')\n scrolllist.append(GetListEntry('Header', {'label': agentLabel}))\n scrolllist += SortListOfTuples(sortlist)\n unavailableAgents = []\n availableAgents = []\n for agent in agentsInStation:\n if agent.agentID in const.rookieAgentList:\n continue\n if not eve.rookieState or agent.agentID in const.rookieAgentList:\n isLimitedToFacWar = False\n if agent.agentTypeID == const.agentTypeFactionalWarfareAgent and facWarSvc.GetCorporationWarFactionID(agent.corporationID) != session.warfactionid:\n isLimitedToFacWar = True\n if agent.agentTypeID in (const.agentTypeResearchAgent, const.agentTypeBasicAgent, const.agentTypeEventMissionAgent, const.agentTypeCareerAgent, const.agentTypeFactionalWarfareAgent):\n standingIsValid = standingSvc.CanUseAgent(agent.factionID, agent.corporationID, agent.agentID, agent.level, agent.agentTypeID)\n haveMissionFromAgent = agent.agentID in relevantAgents\n if not isLimitedToFacWar and (standingIsValid or haveMissionFromAgent):\n availableAgents.append(agent.agentID)\n else:\n unavailableAgents.append(agent.agentID)\n elif agent.agentTypeID == const.agentTypeEpicArcAgent:\n standingIsValid = standingSvc.CanUseAgent(agent.factionID, agent.corporationID, agent.agentID, agent.level, agent.agentTypeID)\n haveMissionFromAgent = agent.agentID in relevantAgents\n epicAgentAvailable = False\n if haveMissionFromAgent:\n epicAgentAvailable = True\n elif standingIsValid:\n if agent.agentID in relevantAgents or epicArcStatusSvc.AgentHasEpicMissionsForCharacter(agent.agentID):\n epicAgentAvailable = True\n if epicAgentAvailable:\n availableAgents.append(agent.agentID)\n else:\n unavailableAgents.append(agent.agentID)\n if agent.agentTypeID == const.agentTypeAura:\n if sm.GetService('experimentClientSvc').IsTutorialEnabled():\n availableAgents.append(agent.agentID)\n elif agent.agentTypeID in (const.agentTypeGenericStorylineMissionAgent, const.agentTypeStorylineMissionAgent):\n if agent.agentID in localRelevantAgents:\n availableAgents.append(agent.agentID)\n else:\n unavailableAgents.append(agent.agentID)\n\n if availableAgents:\n availableLabel = localization.GetByLabel('UI/Station/Lobby/AvailableToYou')\n scrolllist.append(GetListEntry('Header', {'label': availableLabel}))\n sortlist = []\n for agentID in availableAgents:\n missionState = missionStateDict.get(agentID)\n sortlist.append((cfg.eveowners.Get(agentID).name, GetListEntry('AgentEntry', {'charID': agentID,'missionState': missionState})))\n\n scrolllist += SortListOfTuples(sortlist)\n if unavailableAgents:\n unavailableLabel = localization.GetByLabel('UI/Station/Lobby/NotAvailableToYou')\n scrolllist.append(GetListEntry('Header', {'label': unavailableLabel}))\n sortlist = []\n for agentID in unavailableAgents:\n missionState = missionStateDict.get(agentID)\n sortlist.append((cfg.eveowners.Get(agentID).name, GetListEntry('AgentEntry', {'charID': agentID,'missionState': missionState})))\n\n scrolllist += SortListOfTuples(sortlist)\n if self.destroyed:\n return\n self.agentScroll.Load(fixedEntryHeight=40, contentList=scrolllist)\n except:\n log.LogException()\n sys.exc_clear()\n\n def InteractWithAgent(self, agentID, *args):\n sm.StartService('agents').InteractWith(agentID)\n\n def SetHQ(self, *args):\n if sm.GetService('godma').GetType(eve.stationItem.stationTypeID).isPlayerOwnable == 1:\n raise UserError('CanNotSetHQAtPlayerOwnedStation')\n if eve.Message('MoveHQHere', {}, uiconst.YESNO) == uiconst.ID_YES:\n sm.GetService('corp').GetCorpStationManager().MoveCorpHQHere()\n\n def RentOffice(self, *args):\n if not self.sr.Get('isRentOfficeOpening') or not self.sr.isRentOfficeOpening:\n self.sr.isRentOfficeOpening = 1\n try:\n cost = sm.GetService('corp').GetCorpStationManager().GetQuoteForRentingAnOffice()\n if eve.Message('AskPayOfficeRentalFee', {'cost': cost,'duration': const.rentalPeriodOffice * const.DAY}, uiconst.YESNO) == uiconst.ID_YES:\n officeID = sm.GetService('corp').GetCorpStationManager().RentOffice(cost)\n if officeID:\n office = sm.GetService('corp').GetOffice()\n invCache = sm.GetService('invCache')\n invCache.InvalidateLocationCache(officeID)\n if office is not None:\n folder = invCache.GetInventoryFromId(office.officeFolderID, locationID=session.stationid2)\n folder.List()\n wnd = InventoryWindow.GetIfOpen()\n if not wnd:\n InventoryWindow.OpenOrShow()\n uthread.new(self.LoadButtons)\n if self.selectedGroupButtonID == OFFICESPANEL:\n self.ShowOffices()\n finally:\n self.sr.isRentOfficeOpening = 0\n\n return\n\n def ShowShips(self):\n if self.sr.shipsContainer is None:\n return\n else:\n self.mainButtonGroup.SelectByID(INVENTORYPANEL)\n self.inventoryTabs.ShowPanel(self.sr.shipsContainer)\n return\n\n def ShowItems(self):\n if self.sr.itemsContainer is None:\n return\n else:\n self.mainButtonGroup.SelectByID(INVENTORYPANEL)\n self.inventoryTabs.ShowPanel(self.sr.itemsContainer)\n return\n\n def ReloadOfficesIfVisible(self):\n if self.selectedGroupButtonID == OFFICESPANEL:\n self.ShowOffices()\n\n def ShowOffices(self):\n if self.selectedGroupButtonID != OFFICESPANEL:\n return\n self.LoadButtons()\n corpsWithOffices = sm.GetService('corp').GetCorporationsWithOfficesAtStation()\n cfg.corptickernames.Prime([ c.corporationID for c in corpsWithOffices ])\n scrolllist = []\n for corp in corpsWithOffices:\n data = KeyVal()\n data.corpName = corp.corporationName\n data.corpID = corp.corporationID\n data.corporation = corp\n scrolllist.append((data.corpName.lower(), GetListEntry('OfficeEntry', data=data)))\n\n scrolllist = SortListOfTuples(scrolllist)\n numUnrentedOffices = self.GetNumberOfUnrentedOffices()\n availOfficesLabel = localization.GetByLabel('UI/Station/Lobby/NumAvailableOffices', numOffices=numUnrentedOffices)\n scrolllist.insert(0, GetListEntry('Header', {'label': availOfficesLabel\n }))\n if not self.destroyed:\n self.officesScroll.Load(contentList=scrolllist)\n\n def GetNumberOfUnrentedOffices(self):\n return sm.GetService('corp').GetCorpStationManager().GetNumberOfUnrentedOffices()\n\n def OnCorporationMemberChanged(self, corporationID, memberID, change):\n if memberID == session.charid:\n self.LoadButtons()\n\n def StopAllBlinkButtons(self):\n for each in self.serviceButtons.children:\n if hasattr(each, 'Blink'):\n each.Blink(0)\n\n def BlinkButton(self, whatBtn):\n for each in self.serviceButtons.children:\n if each.name.lower() == whatBtn.lower():\n each.Blink(blinks=40)\n\n\nclass OfficeEntry(SE_BaseClassCore):\n __guid__ = 'listentry.OfficeEntry'\n\n def Startup(self, *args):\n self.Flush()\n main = Container(parent=self, align=uiconst.TOTOP, height=30, state=uiconst.UI_PICKCHILDREN)\n left = Container(parent=main, align=uiconst.TOLEFT, width=50, state=uiconst.UI_PICKCHILDREN)\n icon = Container(parent=left, align=uiconst.TOPLEFT, width=32, height=32, left=3, top=3, state=uiconst.UI_PICKCHILDREN)\n par = Container(parent=main, align=uiconst.TOTOP, height=17, state=uiconst.UI_PICKCHILDREN)\n label = localization.GetByLabel('UI/Station/Lobby/CorpName')\n fieldName = 'corpName'\n l = EveLabelSmall(text=label, parent=par, left=5, top=2, state=uiconst.UI_DISABLED)\n t = EveLabelMedium(text='', parent=par, left=5, state=uiconst.UI_NORMAL)\n setattr(self.sr, fieldName + '_Label', l)\n setattr(self.sr, fieldName + '_Text', t)\n setattr(self.sr, fieldName, par)\n LineThemeColored(parent=self, align=uiconst.TOBOTTOM)\n self.sr.buttonCnt = Container(parent=self, align=uiconst.TOTOP, height=25, state=uiconst.UI_HIDDEN)\n self.sr.icon = icon\n self.sr.main = main\n self.sr.infoicon = InfoIcon(left=32, top=3, parent=left, idx=0)\n\n def Load(self, node):\n self.sr.node = node\n data = node\n self.sr.infoicon.UpdateInfoLink(const.typeCorporation, data.corpID)\n mainHeight = 0\n fieldName = 'corpName'\n infofield = self.sr.Get(fieldName, None)\n fieldText = self.sr.Get(fieldName + '_Text', None)\n fieldLabel = self.sr.Get(fieldName + '_Label', None)\n fieldText.text = data.Get(fieldName, '')\n fieldText.top = fieldLabel.textheight\n infofield.height = fieldText.top + fieldText.textheight + 2\n if infofield.state != uiconst.UI_HIDDEN:\n mainHeight += infofield.height\n self.sr.main.height = mainHeight + 10\n self.sr.icon.Flush()\n\n def LogoThread():\n if not self.destroyed:\n GetLogoIcon(itemID=data.corpID, parent=self.sr.icon, acceptNone=False, align=uiconst.TOALL)\n\n uthread.new(LogoThread)\n self.sr.buttonCnt.Flush()\n if not IsNPC(node.corpID):\n buttonEntries = []\n if eve.session.corpid != node.corpID:\n if sm.GetService('corp').GetActiveApplication(node.corpID) is not None:\n applyLabel = localization.GetByLabel('UI/Corporations/CorpApplications/ViewApplication')\n else:\n applyLabel = localization.GetByLabel('UI/Corporations/CorporationWindow/Alliances/Rankings/ApplyToJoin')\n buttonEntries.append((applyLabel,\n sm.GetService('corp').ApplyForMembership, (node.corpID,),\n 80))\n if len(buttonEntries) > 0:\n self.sr.buttonCnt.state = uiconst.UI_PICKCHILDREN\n self.sr.buttons = ButtonGroup(btns=buttonEntries, parent=self.sr.buttonCnt, unisize=0, line=0)\n self.sr.buttons.top -= 1\n else:\n self.sr.buttonCnt.state = uiconst.UI_PICKCHILDREN\n else:\n self.sr.buttonCnt.state = uiconst.UI_HIDDEN\n return\n\n def GetHeight(self, *args):\n node, width = args\n height = 2\n lw, lh = EveLabelSmall.MeasureTextSize(text=localization.GetByLabel('UI/Station/Lobby/CorpName'))\n tw, th = EveLabelMedium.MeasureTextSize(text=node.corpName)\n multiplier = 1\n height += (lh + th + 15) * multiplier\n height += 5\n if not IsNPC(node.corpID) and eve.session.corpid != node.corpID:\n height += 30\n node.height = height\n return node.height","sub_path":"client/eve/client/script/ui/station/lobby.py","file_name":"lobby.py","file_ext":"py","file_size_in_byte":50216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"131893043","text":"\"\"\"\nmakegraph.py\n\nModule used for generating graph object from PPI and function label data.\n\n\"\"\"\nimport json\nimport csv\nimport numpy as np\nimport pprint\nfrom . import graph\nfrom functools import reduce\n\n\ndef load_labels(labels_fname):\n \"\"\"\n Load file of function labels and formats data into dictionary of \n node name, labels list pairs.\n\n File expected to be tab or space delimited.\n \"\"\"\n with open(labels_fname, 'r') as f:\n data = [row.strip() for row in f.readlines()]\n\n labels_dict = {}\n\n for row in data:\n row_string = row.split(' ')\n row_parts = [s for s in row_string if s is not '']\n name = row_parts[0]\n labels = [l for l in row_parts[1:] if l is not '#']\n labels_dict[name] = labels\n\n return labels_dict\n\n\ndef load_GOlabels(labels_fname):\n \"\"\"\n Same as load_labels function, but formatted for GO annotation file\n\n Tab-delimited\n \"\"\"\n\n print(\"loading GO labels\")\n\n with open(labels_fname, 'r') as f:\n data = [row.strip() for row in f.readlines()]\n\n labels_dict = {}\n\n for row in data:\n row_parts = row.split('\\t')\n name = row_parts[0]\n labels = row_parts[1:]\n labels_dict[name] = labels\n return labels_dict\n\n\ndef mips_from_length(label_list):\n if not label_list:\n return \"UNKNOWN\"\n else:\n if len(label_list[0]) == 2:\n return \"1\"\n elif len(label_list[0]) == 5:\n return \"2\"\n elif len(label_list[0]) == 8:\n return \"3\"\n return \"UNKNOWN\"\n\n\ndef merge_hierarchy_labels(hierarchy_labels_dict_list):\n\n for label_dict in hierarchy_labels_dict_list:\n for protein_name in label_dict.keys():\n # Creates [(MIPS_LEVEL, LABEL_LIST)] for every protein\n label_dict[protein_name] = [\n (mips_from_length(label_dict[protein_name]),\n label_dict[protein_name])\n ]\n\n def merge(accum, new_dict):\n if not accum:\n return new_dict\n else:\n for key in accum.keys():\n if key in new_dict:\n prev = accum[key]\n accum[key] = prev + new_dict[key]\n return accum\n\n a = reduce(merge, hierarchy_labels_dict_list, {})\n return a\n\n\ndef load_dsd_matrix(dsd_fname, labels_dict):\n \"\"\"\n Load DSD matrix and generate graph as an adjacency list. \n Each node owns a dictionary of other node names, dsd value pairs.\n\n Only nodes with known labels from the labels_dict are added to \n the graph.\n\n Returns an array of lists containing [node name, dsd values dict]\n for each node, where dsd value dict contains \n {'other node name': dsd value} pairs.\n \"\"\"\n with open(dsd_fname, 'r') as f:\n csv_reader = csv.reader(f, delimiter='\\t')\n data = [row for row in csv_reader]\n\n full_node_list = []\n\n # Split DSD data into headers and rows\n headers = data[0][1:]\n rows = data[1:]\n\n # Extract name and DSD values for each node\n for i, row in enumerate(rows):\n\n # Unpack row\n name = row[0]\n dsd_list = row[1:]\n\n # Prepare dict of DSD values for given node\n # Add every other node, value pair (converted to float)\n # Only add node if label is known and has non empty labels list\n vals_dict = {}\n for j, val in enumerate(dsd_list):\n other_node = headers[j]\n\n if other_node in labels_dict:\n if not labels_dict[other_node]:\n continue\n vals_dict[other_node] = float(val)\n\n full_node_list.append([name, vals_dict])\n\n return full_node_list\n\n\ndef format_nodes_DSD(node_list=None,\n labels_dict=None,\n label_type=None,\n hierarchy_labels_dict=None):\n \"\"\"\n Maps nodes with DSD values and corresponding function labels \n into set of PPINode objects.\n\n Args:\n node_list (list): List of nodes and corresponding DSD dicts.\n labels_dict (dict): Node, function label pairs.\n label_type (str): Type of function label (e.g. 'mips_1').\n\n Returns:\n List of `PPINode` objects.\n \"\"\"\n\n # Map nodes from DSD matrix with function labels in labels_dict\n new_graph = []\n\n for n in node_list:\n\n # Unpack rows in node_list\n name = n[0]\n dsd_vals_dict = n[1]\n\n # Get corresponding function labels\n try:\n node_labels = labels_dict[name]\n except KeyError:\n node_labels = []\n\n if hierarchy_labels_dict:\n hierarchy_labels = []\n if name in hierarchy_labels_dict:\n hierarchy_labels = hierarchy_labels_dict[name]\n else:\n hierarchy_labels = []\n # Create PPINode object\n node_obj = graph.PPINode(name=name,\n dsd_dict=dsd_vals_dict,\n labels=node_labels,\n label_type=label_type,\n hierarchy_labels=hierarchy_labels)\n\n new_graph.append(node_obj)\n\n return new_graph\n\n\ndef generate_graph_DSD(dsd_filename,\n labels_filename,\n label_type,\n hierarchy_labels_dict=None,\n metric_type='DSD'):\n \"\"\"\n Generates PPIGraph object containing PPINodes for graphs using\n DSD metric values.\n \"\"\"\n # Load and format function labels\n print(\"Loading labels file\")\n if 'GO' in label_type:\n labels_dict = load_GOlabels(labels_filename)\n else:\n labels_dict = load_labels(labels_filename)\n\n if metric_type == 'DSD':\n # Load DSD matrix and format list of nodes\n print(\"Loading DSD file and preparing DSD dicts\")\n node_list = load_dsd_matrix(dsd_filename, labels_dict)\n\n # Create PPINode objects\n print(\"Formatting PPINodes\")\n ppi_nodes = format_nodes_DSD(node_list=node_list,\n labels_dict=labels_dict,\n label_type=label_type,\n hierarchy_labels_dict=hierarchy_labels_dict)\n # Create PPIGraph object\n print(\"Creating new PPIGraph\")\n new_PPIGraph = graph.PPIGraph(node_list=ppi_nodes,\n label_type=label_type,\n metric_type=metric_type)\n\n return new_PPIGraph\n\n\ndef getPPIGraph(matrix_filename, labels_filename, label_type, metric_type,\n hierarchy_files):\n\n hierarchy_labels_dict_list = []\n merged_hierarchy_labels_dict = {}\n if hierarchy_files:\n hierarchy_labels_dict_list = [\n load_labels(hfile) for hfile in hierarchy_files\n ]\n merged_hierarchy_labels_dict = merge_hierarchy_labels(\n hierarchy_labels_dict_list)\n\n return generate_graph_DSD(\n dsd_filename=matrix_filename,\n labels_filename=labels_filename,\n label_type=label_type,\n metric_type=metric_type,\n hierarchy_labels_dict=merged_hierarchy_labels_dict)\n","sub_path":"src/makegraph.py","file_name":"makegraph.py","file_ext":"py","file_size_in_byte":7100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"164719198","text":"import unittest\nfrom collections import OrderedDict, namedtuple\nfrom datetime import datetime, date, time\nfrom decimal import Decimal\nimport json \n\nfrom mudplay.framework.cache import (\n params_snapshot, \n make_hash,\n RedisStore,\n JsonCache,\n)\n\nclass CacheTest(unittest.TestCase):\n def test_params_snapshot(self):\n d1 = dict(a=[1, 2, 3], b=dict(b=[1,2,3], c='abc', e=list('cba')), c=3)\n d2 = dict(a=[2, 3, 1], b=dict(b=[3,2,1], c='abc', e=list('abc')), c=3)\n d3 = dict(a=[1, 2, 3], b=dict(b=[1,2,3], c='cba', e=list('cba')), c=3)\n\n self.assertEqual(make_hash(params_snapshot(d1)), \n make_hash(params_snapshot(d2)))\n\n self.assertNotEqual(make_hash(params_snapshot(d1)), \n make_hash(params_snapshot(d3)))\n\n def test_can_instantiate_redis_store(self):\n config = dict(\n namespace='test',\n host=None, \n port=None, \n db=None,\n )\n redis = RedisStore(**config)\n self.assertEqual(redis.server.config_get('port')['port'], '6379')\n\n \n def test_can_cache_response(self):\n redis_config = dict(\n namespace='test',\n host=None, \n port=None, \n db=None,\n )\n cache = JsonCache(redis_config=redis_config)\n\n Response = namedtuple(\n 'Response', ['data', 'etag', 'last_modified'])\n response = Response(\n data=str(dict(firstname=u'mike', email=u'test@example.org')),\n etag='testtest1234',\n last_modified=datetime.now(),)\n\n path = '/cache/path/test'\n params = dict(key1=2, key2='abc', key3=[1,2,3,'a','b','c'])\n role = 'admin'\n cache.store(response, '/cache/path/test', params, role)\n\n key = cache._make_key(path=path, params=params, role=role)\n cached_resource = cache.redis.get_resource(key)\n self.assertEqual(cached_resource['data'], response.data)\n self.assertEqual(cached_resource['etag'], response.etag)\n\n\n\n","sub_path":"mudplay/tests/test_cache.py","file_name":"test_cache.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"213393799","text":"import pytest\nfrom selenium.webdriver.common.keys import Keys\nfrom unittest import mock\n\nfrom screenpy.actions import (\n AcceptAlert,\n BaseAction,\n Click,\n Debug,\n DismissAlert,\n DoubleClick,\n Enter,\n Enter2FAToken,\n GoBack,\n GoForward,\n HoldDown,\n MoveMouse,\n Open,\n Pause,\n Press,\n RefreshPage,\n Release,\n RespondToThePrompt,\n RightClick,\n Select,\n SwitchTo,\n SwitchToTab,\n)\nfrom screenpy.actions.select import SelectByIndex, SelectByText, SelectByValue\nfrom screenpy import Target\n\n\nclass TestBaseAction:\n def test_perform_as_must_be_overridden(self):\n \"\"\"perform_as must be overridden in subclasses\"\"\"\n\n class SubclassedAction(BaseAction):\n pass\n\n subclassed_action = SubclassedAction()\n\n with pytest.raises(NotImplementedError):\n subclassed_action.perform_as(None)\n\n\nclass TestAcceptAlert:\n def test_can_be_instantiated(self):\n \"\"\"AcceptAlert can be instantiated\"\"\"\n aa = AcceptAlert()\n\n assert isinstance(aa, AcceptAlert)\n\n\nclass TestClick:\n def test_can_be_instantiated(self):\n \"\"\"Click can be instantiated\"\"\"\n c1 = Click.on(None)\n c2 = Click.on_the(None)\n\n assert isinstance(c1, Click)\n assert isinstance(c2, Click)\n\n\nclass TestDebug:\n def test_can_be_instantiated(self):\n \"\"\"Debug can be instantiated\"\"\"\n d = Debug()\n\n assert isinstance(d, Debug)\n\n\nclass TestDismissAlert:\n def test_can_be_instantiated(self):\n \"\"\"DismissAlert can be instantiated\"\"\"\n da = DismissAlert()\n\n assert isinstance(da, DismissAlert)\n\n\nclass TestDoubleClick:\n def test_can_be_instantiated(self):\n \"\"\"DoubleClick can be instantiated\"\"\"\n dc1 = DoubleClick()\n dc2 = DoubleClick.on_the(None)\n\n assert isinstance(dc1, DoubleClick)\n assert isinstance(dc2, DoubleClick)\n\n\nclass TestEnter:\n def test_can_be_instantiated(self):\n \"\"\"Enter can be instantiated\"\"\"\n e1 = Enter.the_text(\"test\")\n e2 = Enter.the_text(\"test\").into(None)\n e3 = Enter.the_keys(\"test\").into(None)\n e4 = Enter.the_text(\"test\").into_the(None)\n e5 = Enter.the_text(\"test\").on(None)\n e6 = Enter.the_keys(\"test\").on(None)\n e7 = Enter.the_text(\"test\").into(None).then_press(None)\n e9 = Enter.the_secret(\"test\")\n e8 = Press.the_keys(\"test\")\n\n assert isinstance(e1, Enter)\n assert isinstance(e2, Enter)\n assert isinstance(e3, Enter)\n assert isinstance(e4, Enter)\n assert isinstance(e5, Enter)\n assert isinstance(e6, Enter)\n assert isinstance(e7, Enter)\n assert isinstance(e8, Enter)\n assert isinstance(e9, Enter)\n\n def test_secret_masks_text(self):\n \"\"\"the_secret sets text_to_log to [CENSORED]\"\"\"\n text = \"Keep it a secret to everybody\"\n e = Enter.the_secret(text)\n\n assert e.text == text\n assert e.text_to_log == \"[CENSORED]\"\n\n def test_text_to_log_humanizes_keys(self):\n \"\"\"unicode key values are turned into human-readable text\"\"\"\n e = Enter.the_text(Keys.ENTER)\n\n assert \"ENTER\" in e.text_to_log\n\n\nclass TestEnter2FAToken:\n def test_can_be_instantiated(self):\n \"\"\"Enter2FAToken can be instantiated\"\"\"\n e1 = Enter2FAToken.into(None)\n e2 = Enter2FAToken.into_the(None)\n\n assert isinstance(e1, Enter2FAToken)\n assert isinstance(e2, Enter2FAToken)\n\n\nclass TestGoBack:\n def test_can_be_instantiated(self):\n \"\"\"GoBack can be instantiated\"\"\"\n gb = GoBack()\n\n assert isinstance(gb, GoBack)\n\n\nclass TestGoForward:\n def test_can_be_instantiated(self):\n \"\"\"GoForward can be instantiated\"\"\"\n gf = GoForward()\n\n assert isinstance(gf, GoForward)\n\n\nclass TestHoldDown:\n def test_can_be_instantiated(self):\n \"\"\"HoldDown can be instantiated\"\"\"\n hd1 = HoldDown.left_mouse_button()\n hd2 = HoldDown.left_mouse_button().on_the(None)\n hd3 = HoldDown(Keys.ALT)\n hd4 = HoldDown.command_or_control_key()\n\n assert isinstance(hd1, HoldDown)\n assert isinstance(hd2, HoldDown)\n assert isinstance(hd3, HoldDown)\n assert isinstance(hd4, HoldDown)\n\n @pytest.mark.parametrize(\n \"platform,expected_key\", [[\"Windows\", Keys.CONTROL], [\"Darwin\", Keys.COMMAND]]\n )\n def test_command_or_control_key(self, platform, expected_key):\n \"\"\"HoldDown figures out which key to use based on platform\"\"\"\n system_path = \"screenpy.actions.hold_down.platform.system\"\n with mock.patch(system_path, return_value=platform):\n hd = HoldDown.command_or_control_key()\n\n assert hd.key == expected_key\n\n def test_description_is_correct(self):\n \"\"\"description is set based on the button or key\"\"\"\n hd1 = HoldDown.left_mouse_button()\n hd2 = HoldDown(Keys.LEFT_ALT)\n hd3 = HoldDown(Keys.SHIFT)\n\n assert hd1.description == \"LEFT MOUSE BUTTON\"\n assert hd2.description == \"ALT\"\n assert hd3.description == \"SHIFT\"\n\n\nclass TestMoveMouse:\n def test_can_be_instantiated(self):\n \"\"\"MoveMouse can be instantiated\"\"\"\n mm1 = MoveMouse.to_the(None)\n mm2 = MoveMouse.on_the(None)\n mm3 = MoveMouse.by_offset(1, 1)\n mm4 = MoveMouse.to_the(None).with_offset(1, 1)\n\n assert isinstance(mm1, MoveMouse)\n assert isinstance(mm2, MoveMouse)\n assert isinstance(mm3, MoveMouse)\n assert isinstance(mm4, MoveMouse)\n\n def test_description_is_set_by_method(self):\n \"\"\"Description is built by what is included\"\"\"\n element_name = \"test_element\"\n coords = (1, 2)\n target = Target.the(element_name).located_by(\"*\")\n mm1 = MoveMouse.to_the(target)\n mm2 = MoveMouse.by_offset(*coords)\n mm3 = MoveMouse.to_the(target).with_offset(*coords)\n\n assert element_name in mm1.description\n assert str(coords) in mm2.description\n assert element_name in mm3.description and str(coords) in mm3.description\n\n\nclass TestOpen:\n def test_can_be_instantiated(self):\n \"\"\"Open can be instantiated\"\"\"\n o1 = Open.browser_on(None)\n o2 = Open.their_browser_on(None)\n\n assert isinstance(o1, Open)\n assert isinstance(o2, Open)\n\n\nclass TestPause:\n def test_can_be_instantiated(self):\n \"\"\"Pause can be instantiated\"\"\"\n p1 = Pause.for_(20)\n p2 = Pause.for_(20).seconds_because(\"test\")\n p3 = Pause.for_(20).milliseconds_because(\"test\")\n\n assert isinstance(p1, Pause)\n assert isinstance(p2, Pause)\n assert isinstance(p3, Pause)\n\n def test_seconds(self):\n \"\"\"Choosing seconds stores the correct time\"\"\"\n duration = 20\n pause = Pause.for_(duration).seconds_because(\"test\")\n\n assert pause.time == duration\n\n def test_milliseconds(self):\n \"\"\"Choosing milliseconds stores the correct time\"\"\"\n duration = 20\n pause = Pause.for_(duration).milliseconds_because(\"Test\")\n\n assert pause.time == duration / 1000.0\n\n def test_units_are_pluralized_correctly(self):\n \"\"\"Unit is pluralized if more than 1\"\"\"\n p1 = Pause.for_(1).second_because(\"test\")\n p2 = Pause.for_(1).milliseconds_because(\"test\")\n p3 = Pause.for_(2).seconds_because(\"test\")\n p4 = Pause.for_(2).milliseconds_because(\"test\")\n\n assert not p1.unit.endswith(\"s\")\n assert not p2.unit.endswith(\"s\")\n assert p3.unit.endswith(\"s\")\n assert p4.unit.endswith(\"s\")\n\n\nclass TestRelease:\n def test_can_be_instantiated(self):\n \"\"\"Release can be instantiated\"\"\"\n r1 = Release.left_mouse_button()\n r2 = Release(Keys.ALT)\n r3 = Release.command_or_control_key()\n\n assert isinstance(r1, Release)\n assert isinstance(r2, Release)\n assert isinstance(r3, Release)\n\n @pytest.mark.parametrize(\n \"platform,expected_key\", [[\"Windows\", Keys.CONTROL], [\"Darwin\", Keys.COMMAND]]\n )\n def test_command_or_control_key(self, platform, expected_key):\n \"\"\"Release figures out which key to use based on platform\"\"\"\n system_path = \"screenpy.actions.hold_down.platform.system\"\n with mock.patch(system_path, return_value=platform):\n r = Release.command_or_control_key()\n\n assert r.key == expected_key\n\n def test_description_is_correct(self):\n \"\"\"description is set based on the button or key\"\"\"\n r1 = Release.left_mouse_button()\n r2 = Release(Keys.LEFT_ALT)\n r3 = Release(Keys.SHIFT)\n\n assert r1.description == \"LEFT MOUSE BUTTON\"\n assert r2.description == \"ALT\"\n assert r3.description == \"SHIFT\"\n\n\nclass TestRefreshPage:\n def test_can_be_instantiated(self):\n \"\"\"RefreshPage can be instantiated\"\"\"\n r = RefreshPage()\n\n assert isinstance(r, RefreshPage)\n\n\nclass TestRespondToThePrompt:\n def test_can_be_instantiated(self):\n \"\"\"RespondToThePrompt can be instantiated\"\"\"\n rttp = RespondToThePrompt.with_(\"test\")\n\n assert isinstance(rttp, RespondToThePrompt)\n\n\nclass TestRightClick:\n def test_can_be_instantiated(self):\n \"\"\"RightClick can be instantiated\"\"\"\n rc1 = RightClick()\n rc2 = RightClick.on_the(None)\n\n assert isinstance(rc1, RightClick)\n assert isinstance(rc2, RightClick)\n\n\nclass TestSelect:\n def test_specifics_can_be_instantiated(self):\n \"\"\"Select's specific classes can be instantiated\"\"\"\n by_index1 = Select.the_option_at_index(0)\n by_index2 = Select.the_option_at_index(0).from_(None)\n by_index3 = Select.the_option_at_index(0).from_the(None)\n by_text1 = Select.the_option_named(\"Option\")\n by_text2 = Select.the_option_named(\"Option\").from_(None)\n by_text3 = Select.the_option_named(\"Option\").from_the(None)\n by_value1 = Select.the_option_with_value(1)\n by_value2 = Select.the_option_with_value(1).from_(None)\n by_value3 = Select.the_option_with_value(1).from_the(None)\n\n assert isinstance(by_index1, SelectByIndex)\n assert isinstance(by_index2, SelectByIndex)\n assert isinstance(by_index3, SelectByIndex)\n assert isinstance(by_text1, SelectByText)\n assert isinstance(by_text2, SelectByText)\n assert isinstance(by_text3, SelectByText)\n assert isinstance(by_value1, SelectByValue)\n assert isinstance(by_value2, SelectByValue)\n assert isinstance(by_value3, SelectByValue)\n\n\nclass TestSwitchTo:\n def test_can_be_instantiated(self):\n \"\"\"SwitchTo can be instantiated\"\"\"\n st1 = SwitchTo.the(None)\n st2 = SwitchTo.default()\n\n assert isinstance(st1, SwitchTo)\n assert isinstance(st2, SwitchTo)\n\n\nclass TestSwitchToTab:\n def test_can_be_instantiated(self):\n \"\"\"SwitchToTab can be instantiated\"\"\"\n stt1 = SwitchToTab(1)\n stt2 = SwitchToTab.on_top()\n\n assert isinstance(stt1, SwitchToTab)\n assert isinstance(stt2, SwitchToTab)\n\n def test_description_describes_chosen_tab(self):\n \"\"\"description is set based on which tab to switch to\"\"\"\n stt1 = SwitchToTab(1)\n stt2 = SwitchToTab.on_top()\n\n assert \"tab #1\" in stt1.description\n assert \"newest tab\" in stt2.description\n","sub_path":"tests/test_actions.py","file_name":"test_actions.py","file_ext":"py","file_size_in_byte":11370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"287548045","text":"import json\nfrom sympy import *\nimport time\n\ndef eq_json(eq):\n data = {}\n data[\"val\"] = latex(eq)\n res_data = {}\n res_data[\"eq\"] = data\n return res_data\n\ndef eq_json_lhs_rhs(function, val):\n data = {}\n data[\"val\"] = latex(Eq(function, val))\n res_data = {}\n res_data[\"eq\"] = data\n return res_data\ndef and_json(arr):\n data = {}\n data[\"and\"] = arr\n return data\n\ndef start_and_json(arr):\n data = {}\n data[\"start\"] = and_json(arr)\n return data\n\ndef or_json(arr):\n data = {}\n data[\"or\"] = arr\n return data\n\ndef var_viet_json(arr):\n data = {}\n data[\"var_viet\"] = arr\n return data\n\ndef start_viet_json(eq):\n data = {}\n data[\"start_viet\"] = eq_json(eq)\n return data\n\ndef longor_json(arr):\n data = {}\n data[\"longor\"] = arr\n return data\n\ndef end_viet_longor(arr):\n data = {}\n data[\"end_viet\"] = longor_json(arr)\n return data\n\ndef solve_eq_step(function, varList):\n for varName in varList:\n exec (varName + \"=Symbol(varName)\")\n exec (\"result = solveset(function,\" + str(varList[0]) + \",domain=S.Reals)\")\n if len(result) == 0:\n return False\n elif len(result) == 1:\n for item in result:\n return eq_json_lhs_rhs(simplify(varList[0]), item)\n else:\n childs = []\n for item in result:\n childs.append(eq_json_lhs_rhs(simplify(varList[0]), item))\n return or_json(childs)\n\ndef solve_eq_viet(function, var, arr_var):\n for varName in arr_var:\n exec (varName + \"=Symbol(varName)\")\n for varName in var:\n exec (varName + \"=Symbol(varName)\")\n exec (\"result = solveset(function,\" + str(var[0]) + \",domain=S.Reals)\")\n datareturn = {}\n root = []\n if len(result) == 0:\n return False\n elif len(result) == 1:\n for item in result:\n childs1 = []\n childs1.append(eq_json_lhs_rhs(simplify(arr_var[0]), item))\n childs1.append(eq_json_lhs_rhs(simplify(arr_var[1]), item))\n datareturn[\"eq_viet\"] = end_viet_longor(and_json(1))\n root.append(latex(item), latex(item))\n datareturn[\"root\"] = root\n return datareturn\n else:\n childs = []\n for item in result:\n childs.append(item)\n childs1 = []\n childs1.append(eq_json_lhs_rhs(simplify(arr_var[0]), childs[0]))\n childs1.append(eq_json_lhs_rhs(simplify(arr_var[1]), childs[1]))\n root.append([latex(childs[0]), latex(childs[1])])\n\n childs2 = []\n childs2.append(eq_json_lhs_rhs(simplify(arr_var[0]), childs[1]))\n childs2.append(eq_json_lhs_rhs(simplify(arr_var[1]), childs[0]))\n datareturn[\"eq_viet\"] = end_viet_longor([and_json(childs1), and_json(childs2)])\n root.append([latex(childs[1]), latex(childs[0])])\n datareturn[\"root\"] = root\n return datareturn\n\ndef eqsys_viet1(arr_eq, arr_var, classification):\n start_time = time.time()\n step = []\n for idx, item in enumerate(classification[\"step_change\"]):\n if idx == 0:\n childs = []\n for eq in item:\n childs.append(eq_json(eq))\n step.append(start_and_json(childs))\n else:\n childs = []\n for eq in item:\n childs.append(eq_json(eq))\n step.append(and_json(childs))\n\n S = classification[\"s_eq\"].rhs\n P = classification[\"p_eq\"].rhs\n X = Symbol('X')\n new_func = Eq(X**2-S*X+P, 0)\n step.append(var_viet_json(arr_var))\n step.append(start_viet_json(new_func))\n step.append(solve_eq_step(new_func, ['X']))\n step_root = solve_eq_viet(new_func, ['X'], arr_var)\n step.append(step_root[\"eq_viet\"])\n data = {}\n data[\"step\"] = step\n data[\"root\"] = step_root[\"root\"]\n data[\"time\"] = time.time() - start_time\n data[\"classification\"] = \"eqsys_viet1\"\n data[\"category\"] = \"eqsys\"\n json_data = json.dumps(data)\n return json_data","sub_path":"source/service/math/Solver/EQSYS_Viet_1.py","file_name":"EQSYS_Viet_1.py","file_ext":"py","file_size_in_byte":3925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"652316181","text":"import os\nimport sys\nimport numpy as np\nimport torch\nimport pytest\n\nsys.path.insert(0, os.path.abspath('..'))\nsys.path.insert(0, os.path.abspath('.'))\nfrom gossipy import CacheItem, CacheKey, Message, Sizeable, set_seed, MessageType\nfrom gossipy.model.handler import ModelHandler\n\ndef test_set_seed() -> None:\n set_seed(42)\n assert np.random.get_state()[1][0] == 42\n assert torch.initial_seed() == 42\n\ndef test_enums():\n pass\n\ndef test_Sizeable():\n s = Sizeable()\n with pytest.raises(NotImplementedError):\n s.get_size()\n\ndef test_Message():\n msg = Message(42, 1, 2, MessageType.PULL, 42)\n assert msg.timestamp == 42\n assert msg.sender == 1\n assert msg.receiver == 2\n assert msg.type == MessageType.PULL\n assert msg.value == 42\n assert msg.get_size() == 1\n assert str(msg) == \"T42 [1 -> 2] {PULL}: 42\"\n\n msg = Message(42, 1, 2, MessageType.PULL, None)\n assert msg.get_size() == 1\n assert str(msg) == \"T42 [1 -> 2] {PULL}: ACK\"\n\n msg = Message(42, 1, 2, MessageType.PULL, \"test\")\n with pytest.raises(TypeError):\n msg.get_size()\n \n class TempClass(Sizeable):\n def get_size(self) -> int:\n return 42\n\n msg = Message(42, 1, 2, MessageType.PULL, TempClass())\n assert msg.get_size() == 42\n\n msg = Message(42, 1, 2, MessageType.PULL, [42, TempClass(), None])\n assert msg.get_size() == 43\n\n msg = Message(42, 1, 2, MessageType.PULL, [42, TempClass(), \"test\"])\n with pytest.raises(TypeError):\n msg.get_size()\n\ndef test_CacheKey_CacheItem():\n\n k1 = CacheKey(1, 2)\n k2 = CacheKey(\"test\")\n i1 = CacheItem(42)\n\n ModelHandler.push_cache(k1, i1)\n ModelHandler.push_cache(k2, \"test\")\n\n assert k1.get() == (1, 2)\n assert k1.get_size() == 1\n assert k2.get_size() == 0\n assert k1.__repr__() == str((1,2))\n s = set([k1])\n assert k1 in s\n k3 = CacheKey(1, 2)\n assert k1 == k3\n assert k1 != k2\n assert not (k1 == (1, 2))\n\n assert i1.value == 42\n assert i1.refs == 1\n i1.add_ref()\n assert i1.refs == 2\n r = i1.del_ref()\n assert i1.refs == 1\n assert r == 42\n assert i1.is_referenced()\n r = i1.del_ref()\n assert r == 42\n assert not i1.is_referenced()\n\n i3 = CacheItem([1,2,3, None, \"test\"])\n assert i3.get_size() == 3\n i4 = CacheItem(\"test\")\n assert i4.get_size() == 0\n\n class TempClass(Sizeable):\n def get_size(self) -> int:\n return 17\n \n t = TempClass()\n i5 = CacheItem(t)\n assert i5.get_size() == 17\n","sub_path":"tests/test_init.py","file_name":"test_init.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"587782491","text":"class Node: \n def __init__(self, key):\n self.key = key\n self.next = None\nclass LinkedList:\n def __init__head(self):\n self.head = None\n\n def printCount(self):\n temp = self.head\n count = 0\n\n while (temp):\n print (temp.key)\n count = count + 1\n temp = temp.next\n print (count)\n\nif __name__ == '__main__':\n llist = LinkedList()\n\n llist.head = Node(1)\n second = Node(2)\n third = Node(3)\n forth = Node(4)\n fifth = Node(8)\n \n llist.head.next = second;\n second.next = third;\n third.next = forth;\n forth.next = fifth;\n\nllist.printCount()","sub_path":"list_length.py","file_name":"list_length.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"265227646","text":"# -*-coding:utf-8 -*\nimport os,sys\n\n\n\nclass Interacteur:\n\t\"\"\"Cette classe gère l'interaction avec l'utilisateur en mode console.\"\"\"\n\tdef __init__(self,messagePauseParDefaut=\"\"):\n\t\tself.messagePauseParDefaut = messagePauseParDefaut\n\n\tdef mettreEnPause(self, chaine=\"\"):\n\t\t\"\"\"Fonction permettant la mise en pause du programme\"\"\"\n\t\tif chaine == \"\":\n\t\t\tchaine = self.messagePauseParDefaut\n\t\tprint(chaine)\n\t\ttry:\n\t\t\tvariableInutile = input()\n\t\t\treturn True\n\t\texcept:\n\t\t\tprint(\"Une erreur s'est produite ; le programme va se fermer.\")\n\t\t\traise SystemExit\n\t\t\treturn False\n\t\n\tdef annoncer(self, message):\n\t\t\"\"\"Affiche un message puis met le programme en pause\"\"\"\n\t\ttry:\n\t\t\tmessage = str(message)\n\t\texcept ValueError:\n\t\t\tprint(\"Une erreur s'est produite car vous devez entrer une chaîne de caractères à afficher. Le programme va se fermer.\")\n\t\t\traise SystemExit\n\t\telse:\n\t\t\tprint(message)\n\t\t\tself.mettreEnPause()\n\n\tdef recupererChoixDuJoueur(self, choixPossibles, messageMenu):\n\t\t\"\"\" recupererChoixDuJoueur (tupleDeChoixPossibles,messageMenuAAfficher) -> int\n\t\tAffiche un menu (avec comme message messageMenu) et demande au joueur de faire un choix (un chiffre). Retourne ce chiffre.\"\"\"\n\t\tchoixBienFait = False\n\t\twhile choixBienFait is not True:\n\t\t\tprint(messageMenu)\n\t\t\tchoix = input()\n\t\t\ttry:\n\t\t\t\tchoix = int(choix)\n\t\t\texcept ValueError:\n\t\t\t\tprint(\"Vous devez entrer un chiffre.\\n\")\n\t\t\t\tchoix = 0\n\t\t\t\tmettreEnPause()\n\t\t\telse:\n\t\t\t\tif choix in choixPossibles:\n\t\t\t\t\tprint(\"Très bien !\")\n\t\t\t\t\tchoixBienFait = True\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Le chiffre que vous avez entré ne correspond à aucun choix.\")\n\t\t\t\t\tmettreEnPause()\n\t\treturn choix\n\n\tdef recupererNombre(self, message):\n\t\t\"\"\"recupererNombre(message) -> int\n\t\tAprès avoir affiché message à l'écran, demande à l'utilisateur de rentrer un entier et le retourne retourne.\"\"\"\n\t\tnombreBienEntre = False\n\t\twhile nombreBienEntre is not True:\n\t\t\tprint(message)\n\t\t\tnombre = input()\n\t\t\ttry:\n\t\t\t\tnombre = int(nombre)\n\t\t\texcept:\n\t\t\t\tprint(\"Vous n'avez pas entré de nombre.\")\n\t\t\t\tnombre = 0\n\t\t\telse:\n\t\t\t\tnombreBienEntre = True\n\t\treturn nombre\n\n\tdef recupererChaine(self, message):\n\t\t\"\"\"recupererChaine(message) -> str\n\t\tAprès avoir affiché message à l'écran, demande à l'utilisateur de rentrer une chaîne de caractères et la retourne.\"\"\"\n\t\tchaineBienEntree = False\n\t\twhile chaineBienEntree is not True:\n\t\t\tprint(message)\n\t\t\tchaine = input()\n\t\t\ttry:\n\t\t\t\tchaine = str(chaine)\n\t\t\texcept:\n\t\t\t\tprint(\"Vous n'avez pas entré de texte.\")\n\t\t\t\tchaine = \"\"\n\t\t\telse:\n\t\t\t\tchaineBienEntree = True\n\t\treturn chaine\n\n\tdef listerNombres(self, min=1, max=100):\n\t\t\"\"\" listerNombres(intMin,intMax) -> list\n\t\tRetourne une liste de nombres allant de intMin à intMax\n\t\tRemarque : intMin < intMax \"\"\"\n\t\tif min > max:\n\t\t\tmin, max = max, min #Maintenant min <= max\n\t\tlisteNombres = []\n\t\twhile min <= max:\n\t\t\tlisteNombres.append(min)\n\t\t\tmin += 1\n\t\treturn listeNombres\n\n\tdef demanderInfosCarte(self,listeMessages, tileset, couleurTransparente, messageErreurChargementTileset, positionSourceBlocVide, positionSourceBlocRempli, nombreCouches):\n\t\t\"\"\"demanderInfosCarte(listeMessages) -> dict\n\t\tDemande à l'utilisateur les infos nécessaires pour la création d'une carte et les retourne dans un dictionnaire. \n\t\tLors de la demande, affiche pour chaque info le message correspondant contenu dans listeMessages.\"\"\"\n\t\tinfosCarte = dict()\n\t\tinfosCarte[\"nom\"] = self.recupererChaine(listeMessages[0])\n\t\tinfosCarte[\"description\"] = self.recupererChaine(listeMessages[1])\n\t\tinfosCarte[\"longueur\"] = self.recupererNombre(listeMessages[2])\n\t\tinfosCarte[\"largeur\"] = self.recupererNombre(listeMessages[3])\n\t\tinfosCarte[\"musique\"] = self.recupererChaine(listeMessages[4])\n\t\tinfosCarte[\"tileset\"] = tileset\n\t\tinfosCarte[\"messageErreurChargementTileset\"] = messageErreurChargementTileset\n\t\tinfosCarte[\"positionSourceBlocVide\"] = positionSourceBlocVide\n\t\tinfosCarte[\"positionSourceBlocRempli\"] = positionSourceBlocRempli\n\t\tinfosCarte[\"couleurTransparente\"] = couleurTransparente\n\t\tinfosCarte[\"nombreCouches\"] = nombreCouches\n\t\treturn infosCarte\n\nif __name__ == \"__main__\": #Simple test de fonctionnement ; ne réalise rien pour le programme\n\tinteracteur = Interacteur(\"Appuyez sur Entrée\") \n\tmenuDeMidi = interacteur.recupererChoixDuJoueur((1,2),\"Que voulez-vous manger aujourd'hui ? \\n1.Poulet frites\\n2.Lapin aux pruneaux\")\n\tinteracteur.mettreEnPause()\n\tif menuDeMidi is 1:\n\t\tprint(\"Poulet frites ? Beurk !\")\n\telif menuDeMidi is 2:\n\t\tprint(\"Du lapin aux pruneaux ? Excellent choix !\")\n\tinteracteur.mettreEnPause()\n\tprint(interacteur.listerNombres(1,100))\n\tinteracteur.mettreEnPause()\n","sub_path":"interactionConsole.py","file_name":"interactionConsole.py","file_ext":"py","file_size_in_byte":4590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"624566539","text":"# -*- coding: utf-8 -*-\n\nimport smtplib\nimport os\nfrom email.mime.application import MIMEApplication\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.utils import formatdate\nfrom nwae.utils.Log import Log\nfrom inspect import getframeinfo, currentframe\n\n\nclass SendMail:\n\n COMMASPACE = ', '\n\n PORT_SSL = 465\n PORT_SMTP = 587\n GMAIL_SMTP = 'smtp.gmail.com'\n\n MAX_TOTAL_FILES_SIZE_MB_EMAIL_ATTCH = 25\n\n MAIL_MODE_SSL = 'ssl'\n MAIL_MODE_SMTP = 'smtp'\n MAIL_MODE_SMTP_STARTTLS = 'smtp-starttls'\n\n @staticmethod\n def prepare_message(\n from_addr,\n to_addrs_list,\n subject,\n text,\n files = None\n ):\n try:\n msg = MIMEMultipart()\n msg['From'] = from_addr\n msg['To'] = SendMail.COMMASPACE.join(to_addrs_list)\n msg['Date'] = formatdate(localtime=True)\n msg['Subject'] = subject\n\n msg.attach(MIMEText(text))\n\n files_allowed = SendMail.__attach_file_check_validity_and_size(\n files_attachment_list = files,\n max_total_files_size = SendMail.MAX_TOTAL_FILES_SIZE_MB_EMAIL_ATTCH\n )\n\n for f in files_allowed or []:\n with open(f, \"rb\") as fil:\n part = MIMEApplication(\n fil.read(),\n Name = os.path.basename(f)\n )\n # After the file is closed\n part['Content-Disposition'] = 'attachment; filename=\"%s\"' % os.path.basename(f)\n msg.attach(part)\n return msg.as_string()\n except Exception as ex:\n errmsg = str(__name__) + ' ' + str(getframeinfo(currentframe()).lineno)\\\n + ': Error creating email message: ' + str(ex)\n Log.error(errmsg)\n raise Exception(errmsg)\n #message = \"\"\"From: %s\\nTo: %s\\nSubject: %s\\n\\n%s\n # \"\"\" % (from_addr, \", \".join(to_addrs_list), subject, text)\n #return message\n\n @staticmethod\n def __attach_file_check_validity_and_size(\n files_attachment_list,\n max_total_files_size = MAX_TOTAL_FILES_SIZE_MB_EMAIL_ATTCH\n ):\n if files_attachment_list is None:\n return []\n\n files_attachment_list_allowed = []\n\n cum_size_mb = 0.0\n for filepath in files_attachment_list:\n if os.path.isfile(filepath):\n Log.info(\n 'File <' + str(__name__) + '> line ' + str(getframeinfo(currentframe()).lineno)\n + ': Attachment file path \"' + str(filepath) + '\" OK'\n )\n else:\n Log.error(\n 'File <' + str(__name__) + '> line ' + str(getframeinfo(currentframe()).lineno)\n + ': Invalid attachment file \"' + str(filepath) + '\", not attaching to email'\n )\n continue\n\n fsize_bytes = os.path.getsize(filepath)\n fsize_mb = round(fsize_bytes / (1024 * 1024), 2)\n\n if fsize_mb+cum_size_mb < max_total_files_size:\n files_attachment_list_allowed.append(filepath)\n cum_size_mb += fsize_mb\n Log.info(\n 'File <' + str(__name__) + '> line ' + str(getframeinfo(currentframe()).lineno)\n + ': Appended file \"' + str(filepath) + '\" as email attachment size ' + str(fsize_mb)\n + 'MB, total cumulative ' + str(cum_size_mb) + 'MB'\n )\n else:\n Log.warning(\n 'File <' + str(__name__) + '> line ' + str(getframeinfo(currentframe()).lineno)\n + ': File \"' + str(filepath) + '\" too big ' + str(fsize_mb)\n + 'MB. Cumulative = ' + str(fsize_mb+cum_size_mb) + ' Not attaching to email'\n )\n return files_attachment_list_allowed\n\n def __init__(\n self,\n mode = MAIL_MODE_SMTP,\n mail_server_url = GMAIL_SMTP,\n mail_server_port = PORT_SMTP\n ):\n self.mode = mode\n self.mail_server_url = mail_server_url\n self.mail_server_port = mail_server_port\n self.__init_smtp()\n return\n\n def __init_smtp(self):\n Log.important(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno) \\\n + ': Trying to initialize mail server \"' + str(self.mail_server_url)\n + '\" port ' + str(self.mail_server_port) + ' using mode \"' + str(self.mode) + '\"...'\n )\n if self.mode == self.MAIL_MODE_SSL:\n # Create a secure SSL context\n # self.context = ssl.create_default_context()\n self.server = smtplib.SMTP_SSL(\n host = self.mail_server_url,\n port = self.mail_server_port,\n # context=self.context\n )\n self.server.ehlo()\n elif self.mode == self.MAIL_MODE_SMTP:\n self.server = smtplib.SMTP(\n host=self.mail_server_url,\n port=self.mail_server_port\n )\n self.server.ehlo()\n else:\n self.server = smtplib.SMTP(\n host = self.mail_server_url,\n port = self.mail_server_port\n )\n self.server.ehlo()\n self.server.starttls()\n Log.important(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno) \\\n + ': SMTP mode \"' + str(self.mode) + '\" successfully initialized.'\n )\n return\n\n def send(\n self,\n user,\n password,\n recipients_list,\n message\n ):\n try:\n if password not in [None, '']:\n self.server.login(\n user = user,\n password = password\n )\n Log.important(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': Login for user \"' + str(user) + '\" successful.'\n )\n else:\n # If no password passed in, no need to do login\n Log.warning(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': Not doing login for user \"' + str(user) + '\", no password given \"' + str(password) + '\"'\n )\n self.server.sendmail(\n from_addr = user,\n to_addrs = recipients_list,\n msg = message\n )\n Log.important(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': Message from '+ str(user) + ' to ' + str(recipients_list)\n + ' sent successfully. Closing server..'\n )\n self.server.close()\n Log.info(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': Mail server \"' + str(self.mail_server_url) + '\" closed'\n )\n except Exception as ex:\n errmsg = str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\\\n + ': Exception sending mail from ' + str(user) + ' to ' + str(recipients_list)\\\n + '. Got exception ' + str(ex) + '.'\n Log.error(errmsg)\n raise Exception(errmsg)\n\n\nif __name__ == '__main__':\n user = '?@gmail.com'\n receivers = ['mapktah@ya.ru']\n subject = 'Test mail Python'\n text = 'Test message from Python client'\n message = SendMail.prepare_message(\n from_addr = user,\n to_addrs_list = receivers,\n subject = subject,\n text = text,\n files = [\n '/tmp/pic1.png',\n '/tmp/pic2.png',\n ]\n )\n\n # message = \"\"\"From: From Kim Bon \n # To: To All\n # Subject: SMTP e-mail test\n #\n # This is a test e-mail message.\n # \"\"\"\n\n mail = SendMail(\n mode = SendMail.MAIL_MODE_SMTP_STARTTLS\n )\n mail.send(\n user = user,\n password = 'password123',\n recipients_list = receivers,\n message = message\n )\n","sub_path":"build/lib/nwae/utils/SendMail.py","file_name":"SendMail.py","file_ext":"py","file_size_in_byte":8284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"260525862","text":"import contextlib\nimport requests\nimport re\nimport sys\nfrom bs4 import BeautifulSoup, NavigableString\nfrom clint.arguments import Args\nfrom clint.textui import colored, columns, indent, puts\n\ndef compile_pos_filters(pos_flag):\n global parts_of_speech\n global pos_abbreviations\n if not pos_flag:\n return None\n return parts_of_speech[pos_abbreviations.index(pos_flag)]\n\ndef find_pos_above_defn(li):\n global parts_of_speech\n prev_sibling = li.parent.find_previous_sibling()\n while prev_sibling:\n if prev_sibling.name in ['h2', 'h3', 'h4']:\n if prev_sibling.find('span')['id'].replace('_', ' ') in parts_of_speech:\n return prev_sibling.find('span')['id']\n prev_sibling = prev_sibling.find_previous_sibling()\n\ndef format_defns(tag):\n defns = []\n li_elems = [e for e in tag if e.name == 'li']\n for li in li_elems:\n pos = find_pos_above_defn(li)\n formatted_definition = []\n for i, elem in enumerate(li):\n with contextlib.suppress(AttributeError):\n if isinstance(elem, NavigableString):\n formatted_definition.append(elem)\n elif elem.name in ['a', 'b']:\n formatted_definition.append(elem.text)\n elif elem.name == 'i':\n formatted_definition.append('[' + elem.text + ']')\n elif elem.name == 'span':\n if elem.attrs['class'][0] in ['ib-content', 'gloss-content']:\n formatted_definition.append('(' + elem.text + ')')\n elif 'form-of-definition' in elem.attrs['class'][0]:\n formatted_definition.append('(' + elem.text + ')')\n elif elem.find('a'):\n for child in elem:\n if isinstance(child, NavigableString):\n formatted_definition.append(child)\n elif child.name == 'a':\n formatted_definition.append(child.text)\n elif elem.name == 'ol':\n formatted_definition += format_inner_ol(elem)\n defns.append([pos, ''.join(formatted_definition).strip()])\n for i, d in enumerate(defns):\n if not d[1]:\n defns.pop(i)\n else:\n d[1] = d[1].replace('\\n', '')\n d[1] = d[1].replace('.(', '.\\n+(')\n d[1] = d[1].replace('.)(', '.)\\n+(')\n match = re.search(r'\\)\\.[a-zA-Z]', d[1])\n if match:\n d[1] = d[1][:match.start()] + match.group()[:1] + '\\n+' + match.group()[2:] + d[1][match.end():]\n match = re.search(r'[a-zA-Z]\\.[a-zA-Z]', d[1])\n if match and match.group() != 'e.g':\n d[1] = d[1][:match.start()] + match.group()[:1] + '\\n+' + match.group()[2:] + d[1][match.end():]\n return defns\n\ndef format_flags(raw_flags, languages_on_page):\n global pos_abbreviations\n\n if not raw_flags:\n formatted_flags = ['English']\n else:\n for flag in raw_flags.all:\n if flag[:2] != '--' or len(flag) < 3:\n puts(colored.red('Invalid flag format'))\n puts(colored.yellow('Use format \"define [word] [--language] [--part of speech]\"'))\n sys.exit()\n\n formatted_flags = [f[2:] for f in raw_flags.all]\n if len(formatted_flags) > 2:\n puts(colored.red('Too many flags'))\n puts(colored.yellow('Use format \"define [word] [--part of speech filter] [--language]\"'))\n sys.exit()\n\n while len(formatted_flags) < 2:\n formatted_flags.append(None)\n\n for i, flag in enumerate(formatted_flags):\n if flag:\n if flag not in pos_abbreviations and flag.title() not in languages_on_page:\n puts(colored.red('Invalid filter: ' + flag))\n puts(colored.yellow('Part-of-speech filters: ' + ', '.join(pos_abbreviations)))\n puts(colored.yellow('Languages available on page: ' + ', '.join(languages_on_page)))\n sys.exit()\n\n pos = None\n lang = 'English'\n counter_pos = 0\n counter_language = 0\n for flag in formatted_flags:\n if flag:\n if flag in pos_abbreviations:\n counter_pos += 1\n pos = flag\n elif flag.title() in languages_on_page:\n counter_language += 1\n lang = flag.title()\n if counter_pos > 1:\n puts(colored.red('Can only filter on 1 part of speech.'))\n puts(colored.yellow('Use format \"define [word] [--part of speech filter] [--language]\"'))\n sys.exit()\n if counter_language > 1:\n puts(colored.red('Can only filter on 1 language.'))\n puts(colored.yellow('Use format \"define [word] [--part of speech filter] [--language]\"'))\n sys.exit()\n return [pos, lang]\n\ndef format_inner_ol(ol):\n formatted_definition = []\n for li in ol.findAll('li', recursive=False):\n for i, elem in enumerate(li):\n with contextlib.suppress(AttributeError):\n if isinstance(elem, NavigableString):\n formatted_definition.append(elem)\n elif elem.name in ['a', 'b']:\n formatted_definition.append(elem.text)\n elif elem.name == 'i':\n formatted_definition.append('[' + elem.text + ']')\n elif elem.name == 'span':\n if elem.attrs['class'][0] == 'ib-content':\n formatted_definition.append('(' + elem.text + ')')\n elif 'form-of-definition' in elem.attrs['class'][0]:\n formatted_definition.append('(' + elem.text + ')')\n elif elem.find('a') and 'HQToggle' not in elem.attrs['class']:\n formatted_definition.append(elem.find('a').text)\n formatted_definition = [d for d in formatted_definition if d.strip() or d == ' ']\n return formatted_definition\n\ndef get_languages(soup):\n global parts_of_speech\n languages = []\n toc = soup.find('div', id='toc')\n if toc:\n for li in toc.findAll('li', class_='toclevel-1'):\n languages.append(li.find('a').find('span', class_='toctext').text)\n else:\n language_headers = None\n for header_level in ['h2', 'h3', 'h4', 'h5']:\n for header in soup.find('div', class_='mw-parser-output').findAll(header_level, recursive=False):\n if header.text == 'English':\n language_headers = header.name\n break\n elif header.text not in parts_of_speech and header.text not in ['Etymology', 'Pronunciation']:\n if not language_headers:\n language_headers = header.name\n break\n for header in soup.find('div', class_='mw-parser-output').findAll(language_headers, recursive=False):\n languages.append(header.text.split('[')[0])\n return languages\n\ndef get_term_display(soup):\n return soup.title.string.split(' - Wiktionary')[0]\n\ndef get_unknown_defn(tags):\n for tag in tags:\n if tag.name == 'ol':\n return '\\n'.join([tag.text for tag in tag.findAll('li')])\n\ndef process_tags(tags, languages, filter_display, language_flag):\n global parts_of_speech\n global pos_abbreviationss\n language_match = False\n capture = False\n to_display = []\n filter_display = [filter_display] if filter_display else parts_of_speech\n\n for tag in tags:\n if tag.name[0] == 'h' and tag.name[1].isnumeric():\n with contextlib.suppress(AttributeError):\n if len(tag.text):\n if tag.text.split('[')[0] == language_flag:\n language_match = True\n elif tag.text.split('[')[0] in languages:\n language_match = False\n elif tag.find('span').text in parts_of_speech and language_match:\n if tag.find('span').text in filter_display:\n capture = True\n to_display.append([4, tag.text.split('[')[0]])\n else:\n capture = False\n elif language_match and 'Etymology' in tag.text.split('[')[0]:\n mod = ' 1' if not tag.text.split('[')[0][-1].isnumeric() else ''\n to_display.append([2, tag.text.split('[')[0] + mod])\n elif tag.name == 'ol':\n defns = [d[1] for d in format_defns(tag)]\n if len(defns) and capture and language_match:\n for i, defn in enumerate(defns):\n if len(defn.split('\\n')) > 1:\n counter = 1\n for subdef in defn.split('\\n'):\n if subdef[0] == '+':\n to_display.append([8, str(counter) + '. ' + subdef[1:]])\n counter += 1\n else:\n to_display.append([6, str(i + 1) + '. ' + subdef])\n else:\n to_display.append([6, str(i + 1) + '. ' + defn])\n if len(to_display) == 1:\n with indent(2):\n puts('[No definitions found for entered term and filters]')\n else:\n etymology_lines = []\n pos_counter = 0\n for i, line in enumerate(to_display):\n if line[1] in filter_display:\n pos_counter += 1\n if pos_counter:\n for i, line in enumerate(to_display):\n if i < len(to_display) - 1:\n if 'Etymology' in line[1] and 'Etymology' in to_display[i + 1][1]:\n to_display.pop(i + 1)\n for i, line in enumerate(to_display):\n if 'Etymology' in line[1]:\n etymology_lines.append(i)\n if len(etymology_lines) == 1:\n to_display.pop(etymology_lines[0])\n for line in to_display:\n with indent(line[0]):\n puts(columns([line[1], 100]))\n else:\n with indent(2):\n puts('[No definitions found for entered term and filters]')\n if language_flag == 'English':\n puts(colored.yellow('(This term may have valid non-English definitions but none in English; check capitalization.)'))\n else:\n puts(colored.yellow('Definition exists, but format not recognized. Possible definition:'))\n with indent(4):\n puts(get_unknown_defn(tags))\n\nif __name__ == '__main__':\n global flags\n global parts_of_speech\n global pos_abbreviations\n \n args = Args()\n term = args[0]\n if not term:\n puts(colored.red('Please enter a term to look up'))\n sys.exit()\n else:\n term = term.replace(' ', '_')\n \n parts_of_speech = ['Noun', 'Verb', 'Adjective', 'Adverb', 'Conjunction', 'Interjection', 'Pronoun', 'Preposition', 'Proper noun', 'Postposition']\n pos_abbreviations = ['n', 'v', 'adj', 'adv', 'conj', 'int', 'pron', 'prep', 'propn', 'post']\n\n terms_to_try = [term, term.lower(), term[0].upper() + term[1:].lower()]\n\n for t in terms_to_try:\n response = requests.get('https://en.wiktionary.org/wiki/' + t)\n if response.status_code != 404:\n break\n\n if response.status_code == 200:\n soup = BeautifulSoup(response.text, 'html.parser')\n languages_on_page = get_languages(soup)\n\n flags = format_flags(args.flags, languages_on_page)\n pos_flag = flags[0]\n language_flag = flags[1]\n\n all_tags = soup.find('div', class_='mw-parser-output').findAll(recursive=False)\n for i, tag in enumerate(all_tags):\n if tag.name not in ['h1', 'h2', 'h3', 'h4', 'h5', 'ol']:\n all_tags.pop(i)\n\n filter_display = compile_pos_filters(pos_flag) if pos_flag else None\n term_display = get_term_display(soup)\n if language_flag != 'English':\n term_display += ' (' + language_flag + ')'\n if pos_flag:\n term_display += ' (part of speech filter: ' + filter_display + ')'\n border = ''.join(['-' for c in term_display])\n puts(colored.yellow(border + '\\n' + term_display.replace('_', ' ') + '\\n' + border))\n process_tags(all_tags, languages_on_page, filter_display, language_flag)\n if len(languages_on_page) > 1:\n if language_flag:\n other_languages = 'Other languages available for term: ' + ', '.join([l for l in languages_on_page if l != language_flag])\n else:\n other_languages = 'Other languages available for term: ' + ', '.join([l for l in languages_on_page if l != 'English'])\n with indent(2):\n puts(columns(['\\n' + other_languages, 100]))\n elif response.status_code == 404:\n puts(colored.red('Term \\'' + term.replace('_', ' ') + '\\' not found on Wiktionary (status code 404)'))\n sys.exit()\n else:\n puts(colored.red('Error from Wiktionary: status code ' + str(response.status_code)))\n sys.exit()\n","sub_path":"define/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"561913361","text":"\"\"\" Dieses Modul definiert die Klasse MainWindow. \n\"\"\"\n\nfrom PyQt5.QtWidgets import QWidget, QMainWindow, QLabel\nfrom PyQt5.QtGui import QStandardItemModel, QStandardItem, QBrush, QColor\nfrom qttool.ui.ui_mainwindow import Ui_MainWindow\nfrom PyQt5.QtCore import Qt\n\nclass MainWindow(QMainWindow, Ui_MainWindow):\n \"\"\" Die Klasse MainWindow ist eine Ableitung aus den Klasse QMainWindow sowie Ui_MainWindow. \n \n Die erstere ist die Qt Standard Klasse für ein Hauptfenster. Die zweite kommt\n aus dem Qt Code Generator. Das Benutzerinterface welches durch diese Klasse aufgebaut wird\n kann durch das Tool Designer, welches Teil von Qt5 ist, erstellt werden.\n \n\n \"\"\"\n\n\n def __init__(self, data):\n super(QMainWindow, self).__init__()\n\n # Set up the user interface from Designer.\n self.setupUi(self)\n\n model = QStandardItemModel(self.listView)\n self.listView.setModel(model)\n\n for idx, item in enumerate(data):\n label = \"\"\n label += \"name: \"+ item['name'] + '\\n'\n label += \"birthday: \"+ item['birthday']\n\n qitem = QStandardItem(label)\n qitem.setCheckable(False)\n qitem.setEditable(False)\n \n # Add the item to the model\n model.appendRow(qitem)\n\n # Ändere die Hintergrundfarbe jedes zweiten Items um diese besser zu unterscheiden\n glitter = QColor(\"#E6E8FA\")\n if idx % 2 == 0:\n model.setData(model.index(idx, 0), QBrush(glitter), Qt.BackgroundRole)\n\n # Setze die Schriftfarbe jedes items auf rot welches das mark Attribut aufweist.\n if \"mark\" in item and item[\"mark\"]:\n model.setData(model.index(idx, 0), QBrush(Qt.red), Qt.ForegroundRole)\n\n \n # Connect up the buttons.\n self.exitButton.clicked.connect(self.close)\n","sub_path":"qttool/qttool/mainwindow.py","file_name":"mainwindow.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"476320029","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport pytest\nfrom mrsimulator.method.event import BaseEvent\nfrom mrsimulator.method.event import ConstantDurationEvent\nfrom mrsimulator.method.event import MixingEvent\nfrom mrsimulator.method.event import SpectralEvent\nfrom mrsimulator.method.frequency_contrib import freq_default\nfrom pydantic import ValidationError\n\n__author__ = \"Deepansh J. Srivastava\"\n__email__ = \"srivastava.89@osu.edu\"\n\n\ndef test_freq_contrib():\n event = BaseEvent(freq_contrib=[\"Quad2_4\", \"Quad2_0\"])\n assert event.json()[\"freq_contrib\"] == [\"Quad2_4\", \"Quad2_0\"]\n assert event.dict()[\"freq_contrib\"] == [\"Quad2_4\", \"Quad2_0\"]\n assert event.json(units=False)[\"freq_contrib\"] == [\"Quad2_4\", \"Quad2_0\"]\n assert np.all(event._freq_contrib_flags() == [0, 0, 0, 1, 0, 1])\n\n event = BaseEvent(freq_contrib=[\"Shielding1_2\"])\n assert np.all(event._freq_contrib_flags() == [0, 1, 0, 0, 0, 0])\n\n event = BaseEvent()\n assert event.dict()[\"freq_contrib\"] == freq_default\n assert np.all(event._freq_contrib_flags() == [1, 1, 1, 1, 1, 1])\n\n\ndef basic_spectral_and_constant_time_event_tests(the_event, type_=\"spectral\"):\n # fraction\n if type_ == \"spectral\":\n assert the_event.fraction == 0.5\n the_event.fraction = 1.2\n assert the_event.fraction == 1.2\n with pytest.raises(ValidationError, match=\"value is not a valid float\"):\n the_event.fraction = \"test\"\n\n # duration\n if type_ == \"constant_duration\":\n assert the_event.duration == 0.5\n the_event.duration = 1.2\n assert the_event.duration == 1.2\n with pytest.raises(ValidationError, match=\"value is not a valid float\"):\n the_event.duration = \"test\"\n\n # magnetic flux density\n assert the_event.magnetic_flux_density == 9.6\n the_event.magnetic_flux_density = 11.7\n assert the_event.magnetic_flux_density == 11.7\n with pytest.raises(ValidationError, match=\"value is not a valid float\"):\n the_event.magnetic_flux_density = \"test\"\n # ensure the default value is T\n assert the_event.property_units[\"magnetic_flux_density\"] == \"T\"\n\n # rotor frequency\n assert the_event.rotor_frequency == 1000\n the_event.rotor_frequency = 2.5e4\n assert the_event.rotor_frequency == 25000\n with pytest.raises(ValidationError, match=\"value is not a valid float\"):\n the_event.rotor_frequency = \"test\"\n # ensure the default value is Hz\n assert the_event.property_units[\"rotor_frequency\"] == \"Hz\"\n\n # rotor angle\n assert the_event.rotor_angle == 54.735 * np.pi / 180\n the_event.rotor_angle = 90 * np.pi / 180\n assert the_event.rotor_angle == 90 * np.pi / 180\n with pytest.raises(ValidationError, match=\"value is not a valid float\"):\n the_event.rotor_angle = \"test\"\n # ensure the default value is radians\n assert the_event.property_units[\"rotor_angle\"] == \"rad\"\n\n # to dict with units\n angle = 90 * np.pi / 180\n\n should_be_units = dict(\n magnetic_flux_density=\"11.7 T\",\n rotor_frequency=\"25000.0 Hz\",\n rotor_angle=f\"{angle} rad\",\n transition_query=[{\"ch1\": {\"P\": [-1]}}],\n )\n should_be = {\n \"magnetic_flux_density\": 11.7,\n \"rotor_frequency\": 25000.0,\n \"rotor_angle\": angle,\n }\n\n if type_ == \"spectral\":\n should_be_units = dict(fraction=1.2, **should_be_units)\n assert the_event.json() == should_be_units\n assert the_event.json(units=False) == {\n \"fraction\": 1.2,\n **should_be,\n \"transition_query\": [{\"ch1\": {\"P\": [-1]}}],\n }\n\n if type_ == \"constant_duration\":\n should_be_units = dict(duration=\"1.2 µs\", **should_be_units)\n assert the_event.json() == should_be_units\n assert the_event.json(units=False) == {\n \"duration\": 1.2,\n **should_be,\n \"transition_query\": [{\"ch1\": {\"P\": [-1.0]}}],\n }\n\n\ndef test_spectral_and_constant_time_events():\n # parse dict with units\n base_event_dictionary = {\n \"magnetic_flux_density\": \"9.6 T\",\n \"rotor_frequency\": \"1 kHz\",\n \"rotor_angle\": \"54.735 deg\",\n }\n evt_dict = {\"fraction\": 0.5, **base_event_dictionary}\n the_event = SpectralEvent.parse_dict_with_units(evt_dict)\n basic_spectral_and_constant_time_event_tests(the_event, type_=\"spectral\")\n\n evt_dict = {\"duration\": \"0.5 µs\", **base_event_dictionary}\n the_event = ConstantDurationEvent.parse_dict_with_units(evt_dict)\n basic_spectral_and_constant_time_event_tests(the_event, type_=\"constant_duration\")\n\n # direct initialization\n magic_angle_in_rad = 54.735 * np.pi / 180\n base_event_dict = dict(\n magnetic_flux_density=9.6, rotor_frequency=1000, rotor_angle=magic_angle_in_rad\n )\n the_event = SpectralEvent(fraction=0.5, **base_event_dict)\n basic_spectral_and_constant_time_event_tests(the_event, type_=\"spectral\")\n\n the_event = ConstantDurationEvent(duration=0.5, **base_event_dict)\n basic_spectral_and_constant_time_event_tests(the_event, type_=\"constant_time\")\n\n\ndef basic_mixing_event_tests(the_event):\n mix = the_event.mixing_query.ch1\n\n # tip angle\n assert mix.tip_angle == np.pi / 2\n mix.tip_angle = 3.2123\n assert mix.tip_angle == 3.2123\n with pytest.raises(ValidationError, match=\"value is not a valid float\"):\n mix.tip_angle = \"test\"\n # ensure the default value is rad\n assert mix.property_units[\"tip_angle\"] == \"rad\"\n\n # phase\n assert mix.phase == 0.0\n mix.phase = 1.745\n assert mix.phase == 1.745\n with pytest.raises(ValidationError, match=\"value is not a valid float\"):\n mix.phase = \"test\"\n # ensure the default value is rad\n assert mix.property_units[\"phase\"] == \"rad\"\n\n # json()\n should_be_units = dict(ch1=dict(tip_angle=\"3.2123 rad\", phase=\"1.745 rad\"))\n should_be = dict(ch1=dict(tip_angle=3.2123, phase=1.745))\n\n should_be_units = dict(mixing_query=should_be_units)\n assert the_event.json() == should_be_units\n assert the_event.json(units=False) == {\"mixing_query\": should_be}\n\n\ndef test_Mixing_event():\n mix_event_dict = {\n \"mixing_query\": {\"ch1\": {\"tip_angle\": \"90 degree\", \"phase\": \"0 rad\"}}\n }\n the_event = MixingEvent.parse_dict_with_units(mix_event_dict)\n basic_mixing_event_tests(the_event)\n\n\ndef check_equal(query, isotopes, channels, res):\n test = SpectralEvent(transition_query=query).permutation(isotopes, channels)\n for i, item in enumerate(res):\n for item2 in item[0]:\n assert item2 in test[i][\"P\"]\n\n for item2 in item[1]:\n assert item2 in test[i][\"D\"]\n\n\ndef test_BaseEvent_permutation():\n # P = -1 D = -1 on A B B A system, channel A, B\n # P = +1 D = -1 on A B B A system, channel A, B\n query = [\n {\"ch1\": {\"P\": [-1], \"D\": [1]}},\n {\"ch1\": {\"P\": [1], \"D\": [-1]}},\n ]\n res = [\n [\n [-1, 0, 0, 0],\n [0, 0, -1, 0],\n ],\n [\n [1, 0, 0, 0],\n [0, 0, 1, 0],\n ],\n ], [[[1, 0, 0, 0], [0, 0, 1, 0]], [[-1, 0, 0, 0], [0, 0, -1, 0]]]\n check_equal(query, [\"A\", \"B\", \"A\", \"B\"], [\"A\", \"B\"], res)\n","sub_path":"src/mrsimulator/method/tests/test_event.py","file_name":"test_event.py","file_ext":"py","file_size_in_byte":7144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"85589821","text":"def fib(n):\n\tprint(\"number at:{}\".format(n))\n\tif n == 0:\n\t\treturn 0\n\telif n == 1:\n\t\treturn 1\n\telse:\n\t\treturn fib(n-1) + fib(n-2)\n\ni = int(input(\"Fibonacci Number: \"))\n\nprint(fib(i))\n","sub_path":"Fibonacci.py","file_name":"Fibonacci.py","file_ext":"py","file_size_in_byte":182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"421130371","text":"from . import views\nfrom .views import OnePost, HomePageView, CreatePostView\nfrom django.urls import path, include\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('about/', views.About.as_view(), name='about'),\n path('', OnePost.as_view(), name='onePost'),\n path('addPost/', CreatePostView.as_view(), name='add'),\n path('list/', HomePageView.as_view(), name='list'),\n # path('', include('posts.urls')),\n]\n","sub_path":"proyecto/cc/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"638051612","text":"from tensorforce.agents import vpg_agent\nfrom CalculateEER import SKGetEER as GetEER\nimport pickle\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\n\ndata = pickle.load(open(\"../Data/PCA_GREYC_2X.pickle\", \"rb\"))\nX = np.array(data['data'])\nY = np.array(data['labels'])\n\nn = X.shape[0]\n\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.30, random_state=42)\nX_valid, X_test, y_valid, y_test = train_test_split(X_test, y_test, test_size=0.5, random_state=42)\ncnnData = pickle.load(open(\"./cnnPredictionsGreyC.pickle\", \"rb\"))\nxgboostData = pickle.load(open(\"./xgboostPredictionsGreyC.pickle\", \"rb\"))\n\ncnnT = cnnData[\"test\"]\nxgT = xgboostData[\"test\"]\n\ncnnV = cnnData[\"valid\"]\nxgV = xgboostData[\"valid\"]\n\nagent = vpg_agent.VPGAgent(\n states=dict(type='float', shape=(2,)),\n actions=dict(type='float', shape=(2,)),\n network=[\n dict(type='dense', size=10),\n dict(type='dense', size=10)\n ]\n)\n\n\ndef getScore(cnn, xg, output, w1, w2):\n combined = (w1*cnn + w2*xg)/(w1+w2)\n eer = GetEER(combined, output)\n return eer\n\n\ndef accuracy(predictions, labels):\n return 100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))/predictions.shape[0]\n\n\ndef getAccuracy(cnn, xg, output, w1, w2):\n combined = (w1 * cnn + w2 * xg) / (w1 + w2)\n acc = accuracy(combined, output)\n return acc\n\n\ndef fitness(w):\n return 1 - getScore(cnnV, xgV, y_valid, abs(w[0]), abs(w[1]))\n\n\nprint(\"Test Acc:\", getAccuracy(cnnT, xgT, y_test, 0.71388465, -1.8276248))\nprint(\"Valid Acc:\", getAccuracy(cnnV, xgV, y_valid, 0.71388465, -1.8276248))\nraise KeyError\n\nstate = [1, 1]\neers = []\nweights = []\nfor i in range(1000):\n action = agent.act(state)\n #print(action)\n reward = 100*fitness(action)\n w = action\n testEER = getScore(cnnT, xgT, y_test, abs(w[0]), abs(w[1]))\n # Add experience, agent automatically updates model according to batch size\n agent.observe(reward=reward, terminal=False)\n eers.append(testEER)\n weights.append(w)\n ind = np.argmin(eers)\n print(i, action, testEER, min(eers), weights[ind])\n state = action\nind = np.argmin(eers)\nprint(min(eers), weights[ind])","sub_path":"CNN/combineXGCNNGreyC.py","file_name":"combineXGCNNGreyC.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"606407464","text":"# Copyright (C) 2014 Ruben Decrop\n# see license.txt\n\nfrom bjk2016.models import RdAccount\nfrom bjk2016 import app\n\ndef test_ruben():\n \"\"\"\n setup the dabatabse records\n :return:\n \"\"\"\n with app.test_request_context():\n ruben = RdAccount.login('ruben@decrop.net', 'qwerty')\n if ruben:\n print('login Ruben OK')\n else:\n print('login Ruben failed')\n\nif __name__ == '__main__':\n test_ruben()\n\n\n","sub_path":"bjk2016/scripts/test_ruben.py","file_name":"test_ruben.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"409352252","text":"from __future__ import absolute_import\n# Copyright (c) 2010-2021 openpyxl\n\nimport pytest\n\nfrom openpyxl.xml.functions import tostring, fromstring\nfrom openpyxl.tests.helper import compare_xml\n\n\n@pytest.fixture\ndef View3D():\n from .._3d import View3D\n return View3D\n\n\nclass TestView3D:\n\n def test_ctor(self, View3D):\n view = View3D()\n xml = tostring(view.to_tree())\n expected = \"\"\"\n \n \n \n \n \n \"\"\"\n diff = compare_xml(xml, expected)\n assert diff is None, diff\n\n\n def test_from_xml(self, View3D):\n src = \"\"\"\n \n \n \n \n \n \n \"\"\"\n node = fromstring(src)\n view = View3D.from_tree(node)\n assert view == View3D(rotX=15, rotY=20, rAngAx=False, perspective=30)\n\n\n@pytest.fixture\ndef Surface():\n from .._3d import Surface\n return Surface\n\n\nclass TestSurface:\n\n def test_ctor(self, Surface):\n surface = Surface(thickness=0)\n xml = tostring(surface.to_tree())\n expected = \"\"\"\n \n \n \n \"\"\"\n diff = compare_xml(xml, expected)\n assert diff is None, diff\n\n\n def test_from_xml(self, Surface):\n src = \"\"\"\n \n \n \n \"\"\"\n node = fromstring(src)\n surface = Surface.from_tree(node)\n assert surface == Surface(thickness=0)\n\n\n@pytest.fixture\ndef _3DBase():\n from .._3d import _3DBase\n return _3DBase\n\n\nclass TestSurface:\n\n def test_ctor(self, _3DBase):\n base = _3DBase()\n xml = tostring(base.to_tree())\n expected = \"\"\"\n \n \n \n \n \n \n \n \n \n \n \"\"\"\n diff = compare_xml(xml, expected)\n assert diff is None, diff\n\n\n def test_from_xml(self, _3DBase):\n src = \"\"\"\n \n \n \n \n \n \n \n \n \n \n \"\"\"\n node = fromstring(src)\n base = _3DBase.from_tree(node)\n assert base == _3DBase()\n","sub_path":"openpyxl/chart/tests/test_3d.py","file_name":"test_3d.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"507611047","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom uncertainties import ufloat\nfrom importar_datos import importar_mag, importar_gdocs\n\nimport sys\n\nsys.path.append(\"..\")\nfrom funciones import fechas, tiempos, donde\n\n\n\"\"\"\nCalcula la velocidad media de los protones del viento solar de SWICA y SWIFA\nen distintas regiones proyectada sobre la normal y luego calcula la ram pressure.\nLa compara con la presión magnética.\n\"\"\"\n\nnp.set_printoptions(precision=4)\n\n\ndef importar_swica(year, month, day, ti, tf):\n\n path = f\"../../../datos/Ecinetica/{year}-{month}-{day}/\"\n\n swica = np.loadtxt(path + \"SWICA.asc\")\n\n t = swica[:, 3] + swica[:, 4] / 60 + swica[:, 5] / 3600 # hdec\n\n density = swica[:, 6]\n\n vel_norm = swica[:, -1]\n vel_mso_xyz = swica[:, 7:10]\n\n return swica, t, density, vel_mso_xyz, vel_norm\n\n\ndef importar_swifa(year, month, day, ti, tf):\n\n path = f\"../../../datos/Ecinetica/{year}-{month}-{day}/\"\n\n swifa = np.loadtxt(path + \"SWIFA.asc\")\n\n t = swifa[:, 3] + swifa[:, 4] / 60 + swifa[:, 5] / 3600 # hdec\n\n density = swifa[:, 6]\n\n vel_norm = swifa[:, -1]\n vel_mso_xyz = swifa[:, 7:10]\n\n inicio = donde(t, ti)\n fin = donde(t, tf)\n\n t_cut = t[inicio:fin]\n vel_cut = vel_mso_xyz[inicio:fin]\n vel_norm_cut = vel_norm[inicio:fin]\n d_cut = density[inicio:fin]\n\n return swifa, t_cut, d_cut, vel_cut, vel_norm_cut\n\n\nmp = 1.67e-27 # kg\nmu_0 = np.pi * 4e-7 # T m / A\nyear, month, day, doy = fechas()\nti_sw, tf_sw = tiempos(\"tiempo inicial y final en el viento solar\\n\")\n# ti_MS, tf_MS = tiempos(\"tiempo inicial y final de la magnetofunda\\n\")\n\nhoja_parametros, hoja_MVA, hoja_Bootstrap, hoja_Ajuste = importar_gdocs()\n\nfila = input(\"En qué fila del gdoc estamos?\\n\")\ntf_MPR = float(hoja_parametros.cell(fila, 6).value)\nti_MPR = tf_MPR - 0.015\nnormal = [\n float(hoja_MVA.cell(fila, 16).value),\n float(hoja_MVA.cell(fila, 17).value),\n float(hoja_MVA.cell(fila, 18).value),\n]\n\nswifa, t_sw, density_sw, vel_sw, vel_norm_sw = importar_swifa(\n year, month, day, ti_sw, tf_sw\n)\n# swica, t_swica, density_swica, vel_swica, vel_norm_swica = importar_swica(\n# year, month, day, tf_sw, tf_MPR\n# )\n\nmag, t_mag, B_mag, posicion = importar_mag(year, month, day, ti_MPR, tf_sw)\nB_norm = np.linalg.norm(B_mag, axis=1) * 1e-9 # Tesla\n\n\n\"\"\" Solar wind \"\"\"\nv_parallel_sw = np.dot(vel_sw, normal)\n\nv_mean_sw = np.mean(v_parallel_sw) # km/s\ndensity_sw_mean = np.mean(density_sw) # 1/cm3\nerror_v_sw = np.std(v_parallel_sw)\nerror_density_sw = np.std(density_sw)\n# print(\n# f\"La velocidad media en el viento solar en dirección de la normal es {v_mean_sw:.3g} km/s\"\n# )\n\nv_sw = ufloat(v_mean_sw, error_v_sw)\nn_sw = ufloat(density_sw_mean, error_density_sw)\np_ram = mp * (v_sw * 1e3) ** 2 * (n_sw * 1e6) # J/m3\n\n\nprint(\n f\"La ram pressure en el SW a partir de los parámetros promedio es {p_ram*1e9:.3g} nPa\"\n)\n\n# inicio_sw = donde(t_mag, ti_sw)\n# fin_sw = donde(t_mag, tf_sw)\n# B_mean_sw = np.mean(B_norm[inicio_sw : fin_sw + 1])\n# p_mag = B_mean_sw ** 2 / (2 * mu_0) # J/m3\n#\n# print(f\"El B medio en el SW a partir de los parámetros promedio es {B_mean_sw:.3g} T\")\n#\n# print(\n# f\"La presión magnética en el SW a partir de los parámetros promedio es {p_mag*1e9:.3g} nPa\"\n# )\n\n#\n# \"\"\" Magnetosheath \"\"\"\n# inicio_ms = donde(t_swica, ti_MS)\n# fin_ms = donde(t_swica, tf_MS)\n#\n# v_parallel_ms = np.dot(vel_swica[inicio_ms : fin_ms + 1], normal)\n#\n# v_mean_ms = np.mean(v_parallel_ms) # km/s\n# density_ms_mean = np.mean(density_swica[inicio_ms : fin_ms + 1]) # 1/cm3\n# print(\n# f\"La velocidad media en la magnetofunda en dirección de la normal es {v_mean_ms:.3g} km/s\"\n# )\n#\n# p_ram_ms = mp * (v_mean_ms * 1e3) ** 2 * (density_ms_mean * 1e6) # J/m3\n#\n# print(\n# f\"La ram pressure en la magnetofunda a partir de los parámetros promedio es {p_ram_ms:.3g} J/m3\"\n# )\n#\n# inicio_ms_mag = donde(t_mag, ti_MS)\n# fin_ms_mag = donde(t_mag, tf_MS)\n# B_mean_ms = np.mean(B_norm[inicio_ms_mag : fin_ms_mag + 1])\n# p_mag_ms = B_mean_ms ** 2 / (2 * mu_0) # J/m3\n#\n# print(\n# f\"El B medio en la magnetofunda a partir de los parámetros promedio es {B_mean_ms:.3g} T\"\n# )\n#\n# print(\n# f\"La presión magnética en la magnetofunda a partir de los parámetros promedio es {p_mag_ms:.3g} J/m3\"\n# )\n#\n#\n# \"\"\" Upstream \"\"\"\n# inicio_up = donde(t_swica, tf_MS - 0.02)\n# v_parallel_up = np.dot(vel_swica[inicio_up : fin_ms + 1], normal)\n#\n# v_mean_up = np.mean(v_parallel_up) # km/s\n# density_up_mean = np.mean(density_swica[inicio_up : fin_ms + 1]) # 1/cm3\n# print(\n# f\"La velocidad media en la región upstream en dirección de la normal es {v_mean_up:.3g} km/s\"\n# )\n#\n# p_ram_up = mp * (v_mean_up * 1e3) ** 2 * (density_up_mean * 1e6) # J/m3\n#\n# print(\n# f\"La ram pressure en la región upstream a partir de los parámetros promedio es {p_ram_up:.3g} J/m3\"\n# )\n#\n# inicio_up_mag = donde(t_mag, tf_MS - 0.02)\n# B_mean_up = np.mean(B_norm[inicio_up_mag : fin_ms_mag + 1])\n# p_mag_up = B_mean_up ** 2 / (2 * mu_0) # J/m3\n#\n# print(\n# f\"El B medio en la región upstream a partir de los parámetros promedio es {B_mean_up:.3g} T\"\n# )\n#\n# print(\n# f\"La presión magnética en la región upstream a partir de los parámetros promedio es {p_mag_up:.3g} J/m3\"\n# )\n\n\n\"\"\" MPR (ojo que acá ya swia no funciona bien ) \"\"\"\n# inicio_mpr = donde(t_swica, ti_MPR)\n# fin_mpr = donde(t_swica, ti_MPR + 0.02)\n# v_parallel_mpr = np.dot(vel_swica[inicio_mpr : fin_mpr + 1], normal)\n#\n# v_mean_mpr = np.mean(v_parallel_mpr) # km/s\n# density_mpr_mean = np.mean(density_swica[inicio_mpr : fin_mpr + 1]) # 1/cm3\n# print(\n# f\"La velocidad media en la región downstream (ojo que acá SWIA no funciona bien) en dirección de la normal es {v_mean_mpr:.3g} km/s\"\n# )\n#\n# p_ram_mpr = mp * (v_mean_mpr * 1e3) ** 2 * (density_mpr_mean * 1e6) # J/m3\n#\n# print(\n# f\"La ram pressure en la región downstream a partir de los parámetros promedio es {p_ram_mpr*1e9:.3g} nPa\"\n# )\ninicio_mpr_mag = donde(t_mag, ti_MPR)\nfin_mpr_mag = donde(t_mag, tf_MPR)\nB_mean_mpr = np.mean(B_norm[inicio_mpr_mag : fin_mpr_mag + 1])\nerror_B = np.std(B_norm[inicio_mpr_mag:fin_mpr_mag])\nB_MPR = ufloat(B_mean_mpr, error_B)\n\np_mag_mpr = B_MPR ** 2 / (2 * mu_0) # J/m3\n\n#\n# print(\n# f\"El B medio en la región downstream a partir de los parámetros promedio es {B_mean_mpr:.3g} T\"\n# )\n\nprint(\n f\"La presión magnética en la región downstream a partir de los parámetros promedio es {p_mag_mpr*1e9:.3g} nPa\"\n)\n","sub_path":"clweb/presiones_outbound.py","file_name":"presiones_outbound.py","file_ext":"py","file_size_in_byte":6467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"547737381","text":"from keras.models import load_model\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndp = pd.read_csv('features.csv')\ndp = dp[:-1]\npred = dp['chg']\nY = pred[1:]\nX = dp[:-1]\n\nX = X.values\nY = Y.values\n\nX = X.astype('float32')\nY = Y.astype('float32')\n\nX = X.reshape((len(X), 1, 3))\n\ntest_x = X[int(len(X)*0.8):]\ntest_y = Y[int(len(Y)*0.8):]\n\nmodel = load_model('LSTM.h5')\n\npredicted = model.predict_on_batch(test_x)\n\npr = predicted.reshape((len(test_y)))\n\nplt.plot(pr)\nplt.plot(test_y)\nplt.show()\n\np = np.zeros(len(pr))\nr = np.zeros(len(pr))\np[0] = 1\nr[0] = 1\n\nfor i in range (1, len(pr)):\n p[i] = p[i-1]*pr[i]\n r[i] = r[i-1]*test_y[i]\n\nplt.plot(p)\nplt.plot(r)\nplt.show()\n\np = np.zeros(len(pr))\nr = np.zeros(len(pr))\np[0] = 1\nr[0] = 1\n\nfor i in range(1, len(test_y)):\n predicted = model.predict_on_batch(test_x[i:i+1])\n p[i] = p[i - 1] * float(predicted[0])\n r[i] = r[i - 1] * test_y[i]\n\nplt.plot(p)\nplt.plot(r)\nplt.show()","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"618295488","text":"import numpy as np\nimport math\n\ndef ranges_trimmer(lidar_ranges_360, is_obstacle_detected):\n ranges_320_to_360=lidar_ranges_360[320:360] #-40 to -1 degree (total 40 values) \n ranges_0_to_40 =lidar_ranges_360[0:40]#0 to 39 degree (total 40 values)\n lidar_ranges_minus_40_to_plus_39=np.concatenate((ranges_320_to_360,ranges_0_to_40 ), axis=0)\n #return lidar_ranges_80\n\n ###################normalizer function###############################\n lidar_ranges_minus_40_to_minus_1 = lidar_ranges_minus_40_to_plus_39[0:40]#-40 to -1 degree (total 40 values)\n lidar_ranges_0_to_39 = lidar_ranges_minus_40_to_plus_39[40:80]#0 to 39 degree (total 40 values)\n\n base_minus_40_to_minus_1=np.zeros(40)\n base_0_to_40=np.zeros(40)\n \n for r in range(40):#0 to 39 == -40 to -1 in range\n r2=40-r#40 , 39 , 38 , ..... , 2, 1\n r2=r2*-1#-40 , -39 , -38 , ...... ,-2 , -1\n base_minus_40_to_minus_1[r]=math.cos(math.radians(r2))*lidar_ranges_minus_40_to_minus_1[r]\n\n for r in range(40):#0 to 39 == 0 to 39 in range\n base_0_to_40[r]=math.cos(math.radians(r))*lidar_ranges_0_to_39[r]\n\n normalized_ranges_minus_40_to_plus_39=np.concatenate((base_minus_40_to_minus_1,base_0_to_40 ), axis=0)# equals to 1.08\n ###########################################################################################\n \"\"\"\n for i in range(80):\n print(str(i-40)+\" : \"+str(normalized_ranges_minus_40_to_plus_39[i]))\n print(\"\")\n \"\"\"\n ##########################10 degrees average taker###########################\n \n average_normalized_range=np.zeros(20)\n for i in range(20):\n for j in range(4):\n average_normalized_range[i]=average_normalized_range[i]+normalized_ranges_minus_40_to_plus_39[(i*4)+j]\n \n if(average_normalized_range[i]/4>6):\n average_normalized_range[i]=6\n #print(average_normalized_range[i])\n else:\n average_normalized_range[i]=average_normalized_range[i]/4\n #print(average_normalized_range[i])\n #print(\"\")\n #############################################################################\n\n #############################################################################\n rover_height=0.45 #45 cm\n max_obstacle_height_to_stop=0.1 #10 cm\n max_scanning_range=1.274 #110 cm\n theta=math.asin(rover_height/max_scanning_range)\n least_scanning_range_after_obstacle=max_scanning_range-(max_obstacle_height_to_stop/math.sin(theta))\n\n ###################################################################33\n obstacle_angles=np.zeros(20)\n left_weight=0\n right_weight=0\n if(is_obstacle_detected==0):\n for i in range(20):\n if(average_normalized_range[i]right_weight):\n is_obstacle_detected=-1\n elif(right_weight>left_weight):\n is_obstacle_detected=1\n return right_weight,left_weight,is_obstacle_detected\n\ndef print_normalized_ranges(normalized_ranges_minus_40_to_plus_39):\n temp2=-40\n for rr in normalized_ranges_minus_40_to_plus_39:\n print(str(temp2)+\" degrees : range = \"+str(rr)+\" meters\")\n temp2=temp2+1\n print(\"\")\n\ndef print_20(ranges):\n i=-10\n for rr in ranges:\n print(str(i)+\" : \"+str(rr))\n i=i+1\n print(\"\")","sub_path":"auto_pilot/src/sensor_processing/lidar_processing_4.py","file_name":"lidar_processing_4.py","file_ext":"py","file_size_in_byte":3821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"135814902","text":"#!/usr/bin/env python\n\"\"\"\nTest of NIDM FSL export tool\n\n\n@author: Camille Maumet \n@copyright: University of Warwick 2013-2014\n\"\"\"\nimport unittest\nimport os\nfrom rdflib.graph import Graph\nimport sys\nimport glob\n\nimport logging\nlogger = logging.getLogger(__name__)\n# Display log messages in console\nlogging.basicConfig(filename='debug.log', level=logging.DEBUG, filemode='w',\n format='%(levelname)s - %(message)s')\n\nRELPATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n# Add FSL NIDM export to python path\nsys.path.append(RELPATH)\n\n# Add nidm common testing code folder to python path\nNIDM_DIR = os.path.join(RELPATH, \"nidm\")\n# In TravisCI the nidm repository will be created as a subtree, however locally\n# the nidm directory will be accessed directly\nlogging.debug(NIDM_DIR)\nif not os.path.isdir(NIDM_DIR):\n NIDM_DIR = os.path.join(os.path.dirname(RELPATH), \"nidm\")\n\nNIDM_RESULTS_DIR = os.path.join(NIDM_DIR, \"nidm\", \"nidm-results\")\nTERM_RESULTS_DIRNAME = \"terms\"\nTEST_DIR = os.path.dirname(os.path.abspath(__file__))\nTEST_DATA_DIR = os.path.join(TEST_DIR, \"data\")\n\npath = os.path.join(NIDM_RESULTS_DIR, \"test\")\nsys.path.append(path)\n\n\nfrom TestResultDataModel import TestResultDataModel\nfrom TestCommons import *\nfrom CheckConsistency import *\n\nfrom ddt import ddt, data\n\n# Find all test examples to be compared with ground truth\ntest_files = glob.glob(os.path.join(TEST_DIR, 'ex*', '*.ttl'))\n# For test name readability remove path to test file\n# test_files = [x.replace(TEST_DIR, \"\") for x in test_files]\nlogging.info(\"Test files:\\n\\t\" + \"\\n\\t\".join(test_files))\n\n\n@ddt\nclass TestFSLResultDataModel(unittest.TestCase, TestResultDataModel):\n\n def setUp(self):\n # Retreive owl file for NIDM-Results\n owl_file = os.path.join(NIDM_RESULTS_DIR, TERM_RESULTS_DIRNAME,\n 'nidm-results.owl')\n import_files = glob.glob(\n os.path.join(os.path.dirname(owl_file),\n os.pardir, os.pardir, \"imports\", '*.ttl'))\n\n gt_dir = os.path.join(TEST_DIR, 'ground_truth')\n\n TestResultDataModel.setUp(self, owl_file, import_files, test_files,\n TEST_DIR, gt_dir)\n\n @data(*test_files)\n def test_class_consistency_with_owl(self, ttl):\n \"\"\"\n Test: Check that the classes used in the ttl file are defined in the\n owl file.\n \"\"\"\n ex = self.load_graph(ttl)\n ex.owl.check_class_names(ex.graph, ex.name, True)\n\n @data(*test_files)\n def test_attributes_consistency_with_owl(self, ttl):\n \"\"\"\n Test: Check that the attributes used in the ttl file comply with their\n definition (range, domain) specified in the owl file.\n \"\"\"\n ex = self.load_graph(ttl)\n ex.owl.check_attributes(ex.graph, \"FSL example001\", True)\n\n @data(*test_files)\n def test_examples_match_ground_truth(self, ttl):\n \"\"\"\n Test03: Comparing that the ttl file generated by FSL and the expected\n ttl file (generated manually) are identical\n \"\"\"\n\n ex = self.load_graph(ttl)\n\n for gt_file in ex.gt_ttl_files:\n logging.info(\"Ground truth ttl: \" + gt_file)\n\n # RDF obtained by the ground truth export\n gt = Graph()\n gt.parse(gt_file, format='turtle')\n\n self.compare_full_graphs(gt, ex.graph, ex.exact_comparison, True)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/test_fsl_export.py","file_name":"test_fsl_export.py","file_ext":"py","file_size_in_byte":3493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"119372968","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 29 22:44:53 2019\n\n@author: Idur\n\"\"\"\n\n# Polynomial Regression\n# Import the dataset\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Imorting the Dataset\n\ndataset = pd.read_csv('Position_Salaries.csv')\nX = dataset.iloc[:, 1:2].values\ny = dataset.iloc[:, 2:].values\n\n# Spliting the dataset into the Training set and Test set\n\"\"\"from sklearn.cross_validation import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\nNote : no need to create Training set and Test set\n\"\"\"\n# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX = sc_X.fit_transform(X)\nsc_y = StandardScaler()\ny = sc_y.fit_transform(y)\n\n\n# Fitting the SVR to the dataset\nfrom sklearn.svm import SVR\nregressor = SVR(kernel = 'rbf')\nregressor.fit(X, y)\n\n# Predicting a new result \ny_pred = sc_y.inverse_transform(regressor.predict(sc_X.transform(np.array([[6.5]]))))\n#y_pred = sc_y.inverse_transform(regressor.predict(sc_X.transform(np.array([[6.5)]])))\n# Visualising the Regression results\nplt.scatter(X, y, color = 'red')\nplt.plot(X,regressor.predict(X), color = 'blue')\nplt.title('Truth or Bluff (Support Vector Regression)')\nplt.xlabel('Position Level')\nplt.ylabel('Salary')\nplt.show()\n\n# Visulising the SVR results (for higher resolution and smoother curve)\n\nX_grid = np.arange(min(X), max(X), 0.1)\nX_grid = X_grid.reshape(len(X_grid), 1)\nplt.scatter(X, y, color = 'red')\nplt.plot(X_grid, regressor.predict(X_grid), color = 'blue')\nplt.title('Truth or Bluff (Regression Model)')\nplt.xlabel('Position Level')\nplt.ylabel('Salary')\nplt.show()\n\n","sub_path":"02_Regression/04SupportVectorRegression/svr.py","file_name":"svr.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"241990101","text":"# sentence = set('the quick brown fox can jump over those lazy dogs')\n\n# print(sentence)\n\n\n# variable = ['apple', 'bannana', 'orange', 'tangering', 'berry']\n\n# variable.append('grapes')\n\n# print(variable)\n\n\n# Uniqueness\ntags = {\n 'python',\n 'coding',\n 'tutorials',\n 'coding'\n}\n\nprint(tags)\n\n# coding won't be listed twice in the print statement\n\n# Nope\nprint(tags[0])\n\nquery_one = 'python' in tags\nquery_two = 'ruby' in tags\n\nprint(query_one)\nprint(query_two)","sub_path":"Basic/set.py","file_name":"set.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"235325678","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# time: 2018/1/29 16:24\n\"\"\"\n主要是该数列必须相差1\n\"\"\"\n\nimport collections\n\n\nclass Solution(object):\n def findLHS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n count = collections.Counter(nums)\n ret = 0\n for n in nums:\n if n + 1 in count:\n ret = max(ret, count[n] + count[n + 1])\n return ret\n\n\nprint(Solution().findLHS([1, 3, 2, 2, 5, 2, 3, 7]))\nprint(Solution().findLHS([1, 1, 1, 1]))\n","sub_path":"python/a594.py","file_name":"a594.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"426187839","text":"import logging\nimport re\nimport xml.etree.ElementTree as ET\n\nfrom defaults import Default, Text\n\nfrom templates import TPL\n\nimport config\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\nclass Spell(Default, Text):\n\tdef __init__(self, xml, bookname):\n\t\tDefault.__init__(self, xml.tag, xml.find('name').text, bookname)\n\t\tself.level = xml.find('level').text\n\t\tself.school = xml.find('school').text\n\t\tself.time = xml.find('castingtime').text\n\t\tself.range = xml.find('range').text\n\t\tself.components = xml.find('components').text\n\t\tself.duration = xml.find('duration').text\n\t\tText.__init__(self, self.parseText(xml.find('description')))\n\t\tself.classes = xml.find('source').text\n\t\tself.ritual = \"NO\" # encounter\n\n\t\tif xml.find('ritual') is not None and xml.find('ritual').text == '1':\n\t\t\tself.ritual = \"YES\"\n\t\n\tdef appendBook(self, bookname):\n\t\tself.source = self.source + ', ' + bookname\n\n\tdef parseText(self, desc, text=[]):\n\t\ttag = re.compile(r'<[^>]+>')\n\t\t\n\t\tif len(text) == 0:\n\t\t\ttext = []\n\n\t\tif type(desc).__name__ == 'str':\n\t\t\treturn desc\n\n\t\tfor line in list(desc):\n\t\t\tif line.tag in ('p', 'b', 'i'):\n\t\t\t\tresult = tag.sub('', ET.tostring(line))\n\t\t\t\t\n\t\t\t\tif re.search('At Higher Levels', result):\n\t\t\t\t\ttext.append(' ')\n\t\t\t\t\tresult = result.replace('. ', '.\\n')\n\t\t\t\telif re.search('spell\\'s damage increase', result):\n\t\t\t\t\ttext.append(' ')\n\n\t\t\t\ttext.append(result)\n\t\t\t\n\t\t\telif line.tag == 'li':\n\t\t\t\ttext.append(\"- {}\".format(line.text))\n\t\t\telif line.tag == 'list':\n\t\t\t\ttext = self.parseText(line, text)\n\n\t\treturn text\n\n\tdef transform(self, transform, subClasses, fullsource):\n\t\ttrans = TPL()\n\n\t\tif not subClasses:\n\t\t\tclasses = self.transformClasses()\n\t\telse:\n\t\t\tclasses = self.classes\n\n\t\tif not fullsource:\n\t\t\tbookname = self.source\n\t\telif re.search(',', self.source):\n\t\t\tbookname = self.transformBookname()\n\t\telse:\n\t\t\tbookname = config.books[self.source]['name']\n\t\n\t\treturn trans.TPL[transform]['spell'].format(\n\t\t\tself.name,\n\t\t\tself.level,\n\t\t\tself.transformSchools(),\n\t\t\tself.time,\n\t\t\tself.range,\n\t\t\tself.components,\n\t\t\tself.duration,\n\t\t\tself.source,\n\t\t\tclasses,\n\t\t\tself.ritual, # encounter\n\t\t\tself.transformText(transform),\n\t\t\tself.addText(transform, trans.TPL[transform]['prefixList']['spelllist'] + classes),\n\t\t\tself.addText(transform, trans.TPL[transform]['prefixList']['booklist'] + bookname)\n\t\t)\n\t\n\tdef transformBookname(self):\n\t\tbookname = ''\n\n\t\tfor book in self.source.replace(' ', '').split(','):\n\t\t\tif len(bookname) == 0:\n\t\t\t\tbookname = config.books[book]['name']\n\t\t\telse:\n\t\t\t\tbookname = bookname + ', ' + config.books[book]['name']\n\n\t\treturn bookname\n\n\tdef transformClasses(self):\n\t\tclassesResult = ''\n\n\t\tfor className in self.classes.split(','):\n\t\t\tfor classListName in config.classesList:\n\t\t\t\tclassName = className.replace(' ', '')\n\n\t\t\t\tif className == classListName:\n\t\t\t\t\tif classesResult != '':\n\t\t\t\t\t\tclassesResult += ', '\n\n\t\t\t\t\tclassesResult += className\n\n\t\treturn classesResult\n\t\n\tdef transformSchools(self):\n\t\tschoolsResult = \"\"\n\n\t\tfor school in config.schoolsList.keys():\n\t\t\tif self.school.find(school) >= 0:\n\t\t\t\tif schoolsResult != '':\n\t\t\t\t\tschoolsResult += ','\n\n\t\t\t\tschoolsResult = schoolsResult + config.schoolsList[school]\n\n\t\treturn schoolsResult\n\n\n","sub_path":"spells/spell.py","file_name":"spell.py","file_ext":"py","file_size_in_byte":3203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"452304720","text":"# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.3'\n# jupytext_version: 1.11.4\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_cbars_legends:\n#\n# Colorbars and legends\n# =====================\n#\n# Proplot includes some useful improvements to the matplotlib API that make\n# working with colorbars and legends :ref:`much easier `.\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_cbars_axes:\n#\n# Axes colorbars and legends\n# --------------------------\n#\n# In matplotlib, colorbars are added to the edges of subplots\n# using the figure method `matplotlib.figure.Figure.colorbar`\n# (e.g., ``fig.colorbar(m, ax=ax, location='right')``.\n# In proplot, this is done using the axes method\n# `proplot.axes.Axes.colorbar` (e.g., ``ax.colorbar(m, loc='r')``.\n# `proplot.axes.Axes.colorbar` preserves subplot aspect ratios and visual symmetry\n# between subplots by allocating new slots in the `proplot.gridspec.GridSpec`\n# rather than \"stealing\" space from the parent subplot (see the\n# :ref:`tight layout ` section for details). Subsequently\n# indexing the `~proplot.gridspec.GridSpec` will automatically ignore\n# slots allocated for colorbars and legends.\n#\n# Proplot tries to make the usage of `proplot.axes.Axes.colorbar`\n# and `proplot.axes.Axes.legend` mutually consistent:\n#\n# * Just like `~proplot.axes.Axes.colorbar`, `proplot.axes.Axes.legend` can\n# draw \"outer\" legends along the edges of subplots when you request\n# a :ref:`side location ` for the legend (e.g., ``loc='right'``\n# or ``loc='r'``). If you draw multiple colorbars and legends on one side,\n# they are \"stacked\" on top of each other.\n# * Just like `~proplot.axes.Axes.legend`, `proplot.axes.Axes.colorbar` can draw\n# \"inset\" colorbars when you request an :ref:`inset location `\n# for the colorbar (e.g., ``loc='upper right'`` or ``loc='ur'``). Inset\n# colorbars have optional background \"frames\" that can be configured with\n# various `~proplot.axes.Axes.colorbar` keywords.\n# * Both `~proplot.axes.Axes.colorbar` and `~proplot.axes.axes.legend` accept\n# `space` and `pad` keywords. `space` controls the absolute separation of the\n# colorbar or legend from the parent subplot edge and `pad` controls the\n# :ref:`tight layout ` padding between the colorbar or legend\n# and the subplot labels.\n#\n# You can also draw colorbars and legends on-the-fly by supplying keyword arguments\n# to various plotting commands. To plot data and draw a colorbar or legend in one go,\n# pass a location (e.g., ``colorbar='r'`` or ``legend='b'``) to the plotting command\n# (e.g., `~proplot.axes.PlotAxes.plot` or `~proplot.axes.PlotAxes.contour`). Use\n# `legend_kw` and `colorbar_kw` to pass keyword arguments to the colorbar and legend\n# functions. Note that `~proplot.axes.Axes.colorbar` can also build colorbars from\n# groups or arbitrary matplotlib artists -- e.g., those created with successive\n# `~proplot.axes.PlotAxes.plot` calls (see :ref:`below `).\n\n# %%\nimport proplot as pplt\nimport numpy as np\nfig = pplt.figure(share=False, refwidth=2.3)\n\n# Colorbars\nax = fig.subplot(121)\nstate = np.random.RandomState(51423)\nm = ax.heatmap(state.rand(10, 10), colorbar='t', cmap='dusk')\nax.colorbar(m, loc='r')\nax.colorbar(m, loc='ll', label='colorbar label')\nax.format(title='Axes colorbars', suptitle='Axes colorbars and legends demo')\n\n# Legends\nax = fig.subplot(122)\nax.format(title='Axes legends', titlepad='0em')\nhs = ax.plot(\n (state.rand(10, 5) - 0.5).cumsum(axis=0), linewidth=3,\n cycle='ggplot', legend='t',\n labels=list('abcde'), legend_kw={'ncols': 5, 'frame': False}\n)\nax.legend(hs, loc='r', ncols=1, frame=False)\nax.legend(hs, loc='ll', label='legend label')\nfig.format(abc=True, xlabel='xlabel', ylabel='ylabel')\n\n# %%\nimport proplot as pplt\nimport numpy as np\nN = 10\nstate = np.random.RandomState(51423)\nfig, axs = pplt.subplots(\n nrows=2, share=False,\n refwidth='55mm', panelpad='1em',\n suptitle='Stacked colorbars demo'\n)\n\n# Repeat for both axes\nargs1 = (0, 0.5, 1, 1, 'grays', 0.5)\nargs2 = (0, 0, 0.5, 0.5, 'reds', 1)\nargs3 = (0.5, 0, 1, 0.5, 'blues', 2)\nfor j, ax in enumerate(axs):\n ax.format(xlabel='data', xlocator=np.linspace(0, 0.8, 5), title=f'Subplot #{j+1}')\n for i, (x0, y0, x1, y1, cmap, scale) in enumerate((args1, args2, args3)):\n if j == 1 and i == 0:\n continue\n data = state.rand(N, N) * scale\n x, y = np.linspace(x0, x1, N + 1), np.linspace(y0, y1, N + 1)\n m = ax.pcolormesh(x, y, data, cmap=cmap, levels=np.linspace(0, scale, 11))\n ax.colorbar(m, loc='l', label=f'dataset #{i+1}')\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_cbars_figure:\n#\n# Figure colorbars and legends\n# ----------------------------\n#\n# In proplot, colorbars and legends can be added to the edge of figures using the\n# figure methods `proplot.figure.Figure.colorbar` and `proplot.figure.Figure.legend`.\n# These methods align colorbars and legends between the edges of the subplot grid\n# rather than the figure. As with :ref:`axes colorbars and legends `,\n# if you draw multiple colorbars or legends on the same side, they are stacked on\n# top of each other. To draw a colorbar or legend alongside particular row(s) or\n# column(s) of the subplot grid, use the `row`, `rows`, `col`, or `cols` keyword\n# arguments. You can pass an integer to draw the colorbar or legend beside a\n# single row or column (e.g., ``fig.colorbar(m, row=1)``), or pass a tuple to\n# draw the colorbar or legend along a range of rows or columns\n# (e.g., ``fig.colorbar(m, rows=(1, 2))``). The space separation between the subplot\n# grid edge and the colorbars or legends can be controlled with the `space` keyword,\n# and the tight layout padding can be controlled with the `pad` keyword.\n\n# %%\nimport proplot as pplt\nimport numpy as np\nstate = np.random.RandomState(51423)\nfig, axs = pplt.subplots(ncols=3, nrows=3, refwidth=1.4)\nfor ax in axs:\n m = ax.pcolormesh(\n state.rand(20, 20), cmap='grays',\n levels=np.linspace(0, 1, 11), extend='both'\n )\nfig.format(\n suptitle='Figure colorbars and legends demo',\n abc='a.', abcloc='l', xlabel='xlabel', ylabel='ylabel'\n)\nfig.colorbar(m, label='column 1', ticks=0.5, loc='b', col=1)\nfig.colorbar(m, label='columns 2 and 3', ticks=0.2, loc='b', cols=(2, 3))\nfig.colorbar(m, label='stacked colorbar', ticks=0.1, loc='b', minorticks=0.05)\nfig.colorbar(m, label='colorbar with length <1', ticks=0.1, loc='r', length=0.7)\n\n# %%\nimport proplot as pplt\nimport numpy as np\nstate = np.random.RandomState(51423)\nfig, axs = pplt.subplots(\n ncols=2, nrows=2, order='F', refwidth=1.7, wspace=2.5, share=False\n)\n\n# Plot data\ndata = (state.rand(50, 50) - 0.1).cumsum(axis=0)\nfor ax in axs[:2]:\n m = ax.contourf(data, cmap='grays', extend='both')\nhs = []\ncolors = pplt.get_colors('grays', 5)\nfor abc, color in zip('ABCDEF', colors):\n data = state.rand(10)\n for ax in axs[2:]:\n h, = ax.plot(data, color=color, lw=3, label=f'line {abc}')\n hs.append(h)\n\n# Add colorbars and legends\nfig.colorbar(m, length=0.8, label='colorbar label', loc='b', col=1, locator=5)\nfig.colorbar(m, label='colorbar label', loc='l')\nfig.legend(hs, ncols=2, center=True, frame=False, loc='b', col=2)\nfig.legend(hs, ncols=1, label='legend label', frame=False, loc='r')\nfig.format(abc='A', abcloc='ul', suptitle='Figure colorbars and legends demo')\nfor ax, title in zip(axs, ('2D {} #1', '2D {} #2', 'Line {} #1', 'Line {} #2')):\n ax.format(xlabel='xlabel', title=title.format('dataset'))\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_cbars:\n#\n# Colorbar features\n# -----------------\n#\n# The `proplot.figure.Figure.colorbar` and `proplot.axes.Axes.colorbar` commands\n# include several new, unique features. Instead of a `~matplotlib.cm.ScalarMappable`,\n# you can pass colormap names, `~matplotlib.colormap.Colormap` instances, lists of\n# colors, or lists of `~matplotlib.artist.Artist` instances to ``colorbar`` and\n# a `~matplotlib.cm.ScalarMappable` will be built from these colors on-the-fly. The\n# associated :ref:`colormap normalizer ` can be specified with the `norm` and\n# `norm_kw` keywords. Lists of artists are passed when you use the `colorbar` keyword\n# with :ref:`1D plot commands ` like `~proplot.axes.PlotAxes.plot`.\n# The colorbar ticks can be manually specified with `values`, or proplot will infer\n# them from the `~matplotlib.artist.Artist` labels (non-numeric labels will be\n# applied to the colorbar as tick labels). This feature is useful for labeling\n# discrete plot elements that bear some numeric relationship to each other.\n#\n# Similar to `proplot.axes.CartesianAxes.format`, you can flexibly specify\n# major tick locations, minor tick locations, and major tick labels using the\n# `locator`, `minorlocator`, `formatter`, `ticks`, `minorticks`, and `ticklabels`\n# keywords. These arguments are passed through the `~proplot.constructor.Locator` and\n# `~proplot.constructor.Formatter` :ref:`constructor functions `.\n# You can easily toggle minor ticks using ``tickminor=True``, and you can change the\n# colorbar width and length with the `width` and `length` keywords. Note that the width\n# is now specified in :ref:`physical units ` -- this helps avoid the common\n# issue where colorbars look \"too skinny\" or \"too fat\" and preserves the look of the\n# figure when its size is changed. The default widths for outer and inset colorbars are\n# controlled with :rcraw:`colorbar.width` and :rcraw:`colorbar.insetwidth`, and the\n# default length for inset colorbars is controlled with :rcraw:`colorbar.insetlength`\n# (the outer colorbar length is always relative to the subplot grid, with a default\n# value of ``1``). You can also specify the size of the colorbar \"extensions\" in\n# physical units rather than relative units using the `extendsize` keyword rather\n# than matplotlib's `extendfrac`. The default sizes for outer and inset colorbars are\n# controlled with :rcraw:`colorbar.extend` and :rcraw:`colorbar.insetextend`. See\n# the `~proplot.axes.Axes.colorbar` documentation for details.\n\n# %%\nimport proplot as pplt\nimport numpy as np\nfig = pplt.figure(share=False, refwidth=2)\n\n# Colorbars from lines\nax = fig.subplot(121)\nstate = np.random.RandomState(51423)\ndata = 1 + (state.rand(12, 10) - 0.45).cumsum(axis=0)\ncycle = pplt.Cycle('algae')\nhs = ax.line(\n data, lw=4, cycle=cycle, colorbar='lr',\n colorbar_kw={'length': '8em', 'label': 'line colorbar'}\n)\nax.colorbar(\n hs, loc='t', values=np.arange(0, 10),\n label='line colorbar', ticks=2\n)\n\n# Colorbars from a mappable\nax = fig.subplot(122)\nm = ax.contourf(\n data.T, extend='both', cmap='algae',\n levels=pplt.arange(0, 3, 0.5)\n)\nfig.colorbar(\n m, loc='r', length=1, # length is relative\n label='interior ticks', tickloc='left'\n)\nax.colorbar(\n m, loc='ul', length=6, # length is em widths\n label='inset colorbar', tickminor=True, alpha=0.5,\n)\nfig.format(\n suptitle='Colorbar formatting demo',\n xlabel='xlabel', ylabel='ylabel', titleabove=False\n)\n\n\n# %% [raw] raw_mimetype=\"text/restructuredtext\"\n# .. _ug_legends:\n#\n# Legend features\n# ---------------\n#\n# The `proplot.figure.Figure.legend` and `proplot.axes.Axes.legend` commands\n# include several new, unique features. Like matplotlib, calling ``legend`` without\n# any arguments automatically fills the legend with the labeled artists in the\n# figure. However unlike matplotlib, you can also call ``legend`` with a list of\n# matplotlib artists as the sole positional argument, and the labels will be\n# retrieved from the objects with `~matplotlib.artist.Artist.get_label`. Labels can\n# be assigned to artists when they are plotted by passing ``label='label'`` to the\n# plotting command or, for the case of 2D arrays passed to :ref:`1D plot commands\n# `, by passing a list of labels using ``labels=['label1', 'label2', ...]``.\n# Labels can also be assigned to ``contour`` plots with ``label='label'`` like\n# any other plot, and the `~matplotlib.contour.ContourSet` objects returned by\n# commands like `~proplot.axes.PlotAxes.contour` can be passed to ``legend``.\n# If you pass legend artists that are grouped into tuples (see this `matplotlib guide\n# `__),\n# the default label will be inferred from the artists in the tuple.\n#\n# You can also draw legends with centered rows by passing ``center=True`` or by passing\n# a list of lists of plot handles to ``legend``. This is accomplished by stacking\n# multiple single-row, horizontally centered legends, then adding an encompassing\n# legend frame. To switch between row-major and column-major order for legend\n# entries, simply use the `order` keyword (the default is ``order='C'``). To modify\n# the legend handles (in particular for `~proplot.axes.PlotAxes.plot` and\n# `~proplot.axes.PlotAxes.scatter` plots), simply pass the relevant properties\n# like `color`, `linewidth`, or `markersize` to ``legend``. To alphabetize the\n# legend entries, you can simply use ``alphabetize=True``. See the\n# `~proplot.axes.Axes.legend` documentation for details.\n\n# %%\nimport proplot as pplt\nimport numpy as np\npplt.rc.cycle = '538'\nfig, axs = pplt.subplots(ncols=2, span=False, share='labels', refwidth=2.3)\nlabels = ['a', 'bb', 'ccc', 'dddd', 'eeeee']\nhs1, hs2 = [], []\n\n# On-the-fly legends\nstate = np.random.RandomState(51423)\nfor i, label in enumerate(labels):\n data = (state.rand(20) - 0.45).cumsum(axis=0)\n h1 = axs[0].plot(\n data, lw=4, label=label, legend='ul',\n legend_kw={'order': 'F', 'title': 'column major'}\n )\n hs1.extend(h1)\n h2 = axs[1].plot(\n data, lw=4, cycle='Set3', label=label, legend='r',\n legend_kw={'lw': 8, 'ncols': 1, 'frame': False, 'title': 'modified\\n handles'}\n )\n hs2.extend(h2)\n\n# Outer legends\nax = axs[0]\nax.legend(hs1, loc='b', ncols=3, title='row major', order='C', facecolor='gray2')\nax = axs[1]\nax.legend(hs2, loc='b', ncols=3, center=True, title='centered rows')\naxs.format(xlabel='xlabel', ylabel='ylabel', suptitle='Legend formatting demo')\n","sub_path":"docs/colorbars_legends.py","file_name":"colorbars_legends.py","file_ext":"py","file_size_in_byte":14369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"175650256","text":"import psico.aaindex\nimport psico.querying\nfrom pymol import cmd\nfrom pathlib import Path\nfrom pytest import approx\n\nDATA_PATH = Path(__file__).resolve().parent / 'data'\n\n\ndef test_hydropathy2b(tmp_path):\n cmd.reinitialize()\n cmd.load(DATA_PATH / '2x19-frag-mse.pdb')\n\n # use cached sample file, skip download\n cmd.set(\"fetch_path\", str(DATA_PATH / \"aaindex\"))\n\n psico.aaindex.hydropathy2b()\n\n b_list = psico.querying.iterate_to_list(\"guide\", \"b\")\n assert b_list == approx([3.8, -0.8, 1.9, 1.9, -1.6, -3.5])\n\n\ndef test_aaindex2b(tmp_path):\n cmd.reinitialize()\n cmd.load(DATA_PATH / '2x19-frag-mse.pdb')\n\n # use cached sample file, skip download\n cmd.set(\"fetch_path\", str(DATA_PATH / \"aaindex\"))\n\n psico.aaindex.aaindex2b(\"LAWE840101\", \"name CA\", \"q\")\n\n b_list = psico.querying.iterate_to_list(\"guide\", \"q\")\n assert b_list == approx([1.02, 0.05, 0.81, 0.81, 2.03, -0.75])\n","sub_path":"tests/test_aaindex.py","file_name":"test_aaindex.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"271281395","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 29 01:47:41 2020\n\n@author: santi\n\"\"\"\n\n### EJERCICIO 6D\n\nb = 1\np = 2\nfuncionando = True\nnum = float(input('Ingrese un numero natural: '))\nwhile num - int(num) != 0 or num <= 0:\n num = float(input('El numero debe ser natural: '))\nwhile funcionando:\n if b**p == num:\n funcionando = False\n posible = True\n elif b**p < num:\n b += 1\n elif p < 6:\n p += 1\n b = 1\n else:\n funcionando = False\n posible = False\nif posible == True:\n print('El numero es igual a '+str(b)+'^'+str(p))\nelse:\n print('La operacion no es posible')","sub_path":"Practica 1 - Python/Ej 6d.py","file_name":"Ej 6d.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"100193970","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\n\"\"\"\n proc.py\n ~~~~~~~\n\n Procedural API for TAP file generation (ie. TapWriter on module-level).\n Call plan, comment, ok, not_ok and write in the sequence order::\n\n plan? (write | ok | not_ok)+ bailout? out\n\n Other control flows might work, but are not officially supported.\n\n (c) BSD 3-clause.\n\"\"\"\n\nfrom __future__ import print_function\n\nfrom .impl import TapDocument\nfrom .api import TapWriter\n\nimport sys\n\n\nwriter = None\ncounter = 0 # counter for tcs, if no plan provided\nplanned = False # was a plan written yet?\n\n\ndef _create():\n global writer\n if writer is None:\n writer = TapWriter()\n\n\ndef plan(first=None, last=None, skip=u'', tests=None,\n tapversion=TapDocument.DEFAULT_VERSION):\n \"\"\"Define a plan. Provide integers `first` and `last` XOR `tests`.\n `skip` is a non-empty message if the whole testsuite was skipped.\n \"\"\"\n _create()\n writer.plan(first, last, skip, tests, tapversion)\n return True\n\n\ndef write(line):\n \"\"\"Add a comment at the current position\"\"\"\n _create()\n writer.write(line)\n\n\ndef ok(description=u'', skip=False, todo=False):\n \"\"\"Add a succeeded testcase entry\"\"\"\n _create()\n\n if skip is True:\n skip = u' '\n elif skip is False:\n skip = u''\n\n if todo is True:\n todo = u' '\n elif todo is False:\n todo = u''\n\n writer.testcase(True, description, skip, todo)\n return True\n\n\ndef not_ok(description=u'', skip=False, todo=False):\n \"\"\"Add a failed testcase entry\"\"\"\n _create()\n writer.testcase(False, description, skip, todo)\n return True\n\n\ndef bailout(comment=''):\n \"\"\"Add Bailout to document\"\"\"\n _create()\n writer.bailout(comment)\n return True\n\n\ndef out():\n \"\"\"Print TAP output to stderr\"\"\"\n _create()\n print(unicode(writer), file=sys.stderr)\n","sub_path":"taptaptap/proc.py","file_name":"proc.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"243407646","text":"class Solution(object):\n def isValidSudoku(self, board):\n \"\"\"\n :type board: List[List[str]]\n :rtype: bool\n \"\"\"\n \n for i in range(9):\n for j in range(9):\n if self.isValidSodukuHelp(board, i, j) is False:\n return False\n \n return True\n \n def isValidSodukuHelp(self, board, i, j):\n if board[i][j] == '.': return True\n \n currVal = board[i][j]\n board[i][j] = '.'\n for i1 in range(9):\n if board[i1][j] == currVal: \n return False\n for i1 in range(9):\n if board[i][i1] == currVal:\n return False\n \n boxRow = i/3\n boxCol = j/3\n for i1 in range(3*boxRow, 3 *(boxRow+1)):\n for j1 in range(3*boxCol, 3*(boxCol+1)):\n if board[i1][j1] == currVal:\n return False\n \n board[i][j] = currVal\n return True","sub_path":"36-Valid-Sudoku/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"76218593","text":"# Copyright 2020 Alexis Lopez Zubieta\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n# sell 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.\nimport logging\nimport os\n\nfrom appimagebuilder.app_dir.app_info.loader import AppInfoLoader\nfrom appimagebuilder.app_dir.file_info_cache import FileInfoCache\nfrom .app_run import AppRun\nfrom .helpers.factory import HelperFactory\nfrom ...recipe import Recipe\n\n\nclass RuntimeGeneratorError(RuntimeError):\n pass\n\n\nclass RuntimeGenerator:\n def __init__(self, recipe: Recipe, file_info_cache: FileInfoCache):\n self._configure(recipe)\n self.app_run_constructor = AppRun\n self.helper_factory_constructor = HelperFactory\n self.file_info_cache = file_info_cache\n\n def _configure(self, recipe):\n self.app_dir = recipe.get_item(\"AppDir/path\")\n self.app_dir = os.path.abspath(self.app_dir)\n\n app_info_loader = AppInfoLoader()\n self.app_info = app_info_loader.load(recipe)\n self.apprun_version = recipe.get_item(\"AppDir/runtime/version\", \"v1.2.3\")\n self.apprun_debug = recipe.get_item(\"AppDir/runtime/debug\", False)\n self.env = recipe.get_item(\"AppDir/runtime/env\", {})\n self.path_mappings = recipe.get_item(\"AppDir/runtime/path_mappings\", [])\n\n def generate(self):\n app_run = self.app_run_constructor(\n self.apprun_version,\n self.apprun_debug,\n self.app_dir,\n self.app_info.exec,\n self.app_info.exec_args,\n )\n self._configure_runtime(app_run)\n self._add_user_defined_settings(app_run)\n\n self._set_path_mappings(app_run)\n\n app_run.deploy()\n\n def _configure_runtime(self, app_run):\n factory = self.helper_factory_constructor(self.app_dir, self.file_info_cache)\n for id in factory.list():\n h = factory.get(id)\n h.configure(app_run)\n\n def _add_user_defined_settings(self, app_run: AppRun) -> None:\n for k, v in self.env.items():\n if k in app_run.env:\n logging.info(\"Overriding runtime env: %s\" % k)\n\n app_run.env[k] = v\n\n def _set_path_mappings(self, app_run: AppRun):\n if self.path_mappings:\n path_mappings_env = \"\"\n for path_mapping in self.path_mappings:\n path_mappings_env += path_mapping + \";\"\n\n app_run.env[\"APPRUN_PATH_MAPPINGS\"] = path_mappings_env\n","sub_path":"appimagebuilder/app_dir/runtime/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":2906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"364012554","text":"import re\n\nimport pymysql\nfrom sqlalchemy import Column, String, DATE, create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\nimport base64\n\nBase = declarative_base()\n\ndb_info = {\n 'user':'test',\n 'passwd':'chaianzhi',\n 'ip':'localhost',\n 'port':'3306',\n 'database':'mytest',\n}\n\nclass Coupon(Base):\n __tablename__ = 'coupon'\n\n id = Column(String(200), primary_key=True)\n deadline = Column(DATE)\n userID = Column(String(200))\n code = Column(String(200))\n\ndef getDbConnect(db_info):\n connect_str = 'mysql+pymysql://{user}:{passwd}@{ip}:{port}/{database}'.format_map(db_info)\n print(connect_str)\n engine = create_engine(connect_str)\n # 根据已有的所有类来创建对应的表\n Base.metadata.create_all(engine)\n DBSession = sessionmaker(engine)\n session = DBSession()\n return session\n\n\ndef parse_base64(line):\n return base64.urlsafe_b64decode(line.encode('UTF-8'))\n\n\ndef addToDB():\n print('addToDB')\n session = getDbConnect(db_info)\n with open('coupon.txt', 'r') as file:\n for line in file.readlines():\n c_id = re.findall(r'.*/.*:(.*)\\'', str(parse_base64(line)))\n print(c_id)\n session.add(Coupon(id=c_id.pop(), code=line))\n session.commit()\n session.close()\n\n\n\nif __name__ == '__main__':\n print('0002')\n addToDB()","sub_path":"0002/0002.py","file_name":"0002.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"547428793","text":"import boto3\n\n# Get the service resource.\ndynamodb = boto3.resource('dynamodb')\ntable = dynamodb.Table('courseadmin')\n\ndef remove_content(contentid):\n table.update_item(\n Key={\n 'courseid': 'courseid1'\n },\n UpdateExpression='SET contents.'+contentid+' = :val1',\n ExpressionAttributeValues={\n ':val1': {\n \"Name\": \"CONTENT REMOVED\",\n \"Description\": \"CONTENT REMOVED\",\n \"url\": \"CONTENT REMOVED\"\n }\n }\n )","sub_path":"team4capstone_courseadmin/remove_content.py","file_name":"remove_content.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"266145929","text":"import time\nimport codecs\nfrom typing import Optional\nfrom logging import getLogger\n\nfrom pyinstrument import Profiler\nfrom pyinstrument.renderers import HTMLRenderer\n\nfrom starlette.routing import Router\nfrom starlette.requests import Request\nfrom starlette.types import ASGIApp, Message, Receive, Scope, Send\n\n\nlogger = getLogger(\"profiler\")\n\n\nclass PyInstrumentProfilerMiddleware:\n def __init__(\n self, app: ASGIApp,\n *,\n server_app: Optional[Router] = None,\n profiler_interval: float = 0.0001,\n profiler_output_type: str = \"text\",\n is_print_each_request: bool = True,\n **profiler_kwargs\n ):\n self.app = app\n self._profiler = Profiler(interval=profiler_interval)\n\n self._server_app = server_app\n self._output_type = profiler_output_type\n self._print_each_request = is_print_each_request\n self._profiler_kwargs: dict = profiler_kwargs\n\n async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:\n # register an event handler for profiler stop\n if self._server_app is not None:\n self._server_app.add_event_handler(\"shutdown\", self.get_profiler_result)\n\n if scope[\"type\"] != \"http\":\n await self.app(scope, receive, send)\n return\n\n self._profiler.start()\n\n request = Request(scope, receive=receive)\n method = request.method\n path = request.url.path\n begin = time.perf_counter()\n\n # Default status code used when the application does not return a valid response\n # or an unhandled exception occurs.\n status_code = 500\n\n async def wrapped_send(message: Message) -> None:\n if message['type'] == 'http.response.start':\n nonlocal status_code\n status_code = message['status']\n await send(message)\n\n try:\n await self.app(scope, receive, wrapped_send)\n finally:\n if scope[\"type\"] == \"http\":\n self._profiler.stop()\n end = time.perf_counter()\n if self._print_each_request:\n print(f\"Method: {method}, \"\n f\"Path: {path}, \"\n f\"Duration: {end - begin}, \"\n f\"Status: {status_code}\")\n print(self._profiler.output_text(**self._profiler_kwargs))\n\n async def get_profiler_result(self):\n if self._output_type == \"text\":\n print(self._profiler.output_text(**self._profiler_kwargs))\n elif self._output_type == \"html\":\n html_name = self._profiler_kwargs.get(\"html_file_name\")\n if html_name is None:\n html_name = \"fastapi-profiler.html\"\n\n \"\"\"\n There are some problems with the args -- output_filename.\n You can check the\n class\n 'from pyinstrument.renderers import HTMLRenderer'\n method\n 'open_in_browser'\n the argument 'output_filename' will become the URL like 'file://xxxx',\n but that code have some bugs on it.\n\n So on my middleware, the args 'html_file_name'\n I suggest use None to instead, or you can use the absolute path.\n\n HTMLRenderer().open_in_browser(\n session=self._profiler.last_session,\n output_filename=html_name,\n )\n\n At last, I rewrite the function to avoid the problem!\n By the way, the html file default save at the root path of your project.\n \"\"\"\n html_code = HTMLRenderer().render(session=self._profiler.last_session)\n with codecs.open(html_name, \"w\", \"utf-8\") as f:\n f.write(html_code)\n","sub_path":"fastapi_profiler/profiler_middleware/profiler.py","file_name":"profiler.py","file_ext":"py","file_size_in_byte":3807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"207407346","text":"import logging\r\n\r\nimport twitchio\r\nfrom twitchio.ext import commands\r\n\r\nfrom classes.storage import Storage\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\n@commands.core.cog(name=\"shop\")\r\nclass ShopCog(object):\r\n \"\"\"\r\n Shop command managed here\r\n \"\"\"\r\n\r\n def __init__(self, bot: commands.Bot, storage: Storage):\r\n self.storage = storage\r\n self.bot = bot\r\n\r\n @commands.command(name=\"shop\")\r\n async def shop(self, ctx: twitchio.Context, shop_name=None, item=None, action=None) -> None:\r\n logger.debug(f\"{shop_name}, {item}, {action}\")\r\n if shop_name is None:\r\n await ctx.send(self.storage.game_data.shop.main_shop_string)\r\n elif item is None:\r\n await ctx.send(self.storage.game_data.shop.shop_string(shop_name))\r\n elif action is None:\r\n await ctx.send(self.storage.game_data.shop.item_dec(shop_name, item))\r\n elif action.strip() == \"buy\":\r\n player = self.storage.game_data.get_player(ctx)\r\n await ctx.send(self.storage.game_data.shop.buy(player, shop_name, item))\r\n else:\r\n await ctx.send(\"Invalid arguments\")\r\n","sub_path":"cogs/shop.py","file_name":"shop.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"634238645","text":"# -*- coding: utf-8 -*-\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# x = np.arange(0,4*np.pi,0.1)\n# y = np.sin(x)\n\n# plt.plot(x,y)\n# plt.title('Sin Component Curve')\n# plt.xlabel('Angle in Radians')\n# plt.ylabel('Output Value')\n# plt.show()\n\n# x = np.arange(0,4*np.pi,0.1)\n# y = (x*180/np.pi)\n# y = np.where(y>360,y-360,y)\n# y = y-180\n\n# plt.plot(x,y)\n# plt.title('Traditional Angle Curve')\n# plt.xlabel('Angle in Radians')\n# plt.ylabel('Output Value')\n# plt.yticks(np.arange(-180,181,step=45))\n# plt.show()\n\nx = 1\ny = 1\ny = np.arctan2(y, x)\nplt.plot(x, y)\n\nx = 2\ny = 1\ny = np.arctan2(y, x)\nplt.plot(x, y)\n\nx = 1\ny = 2\ny = np.arctan2(y, x)\nplt.plot(x, y)\n\n\nplt.title('Arctan2 Curve')\nplt.xlabel('Angle in Radians')\nplt.ylabel('Output Value')\nplt.show()\n","sub_path":"turtles_test/t.py","file_name":"t.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"570498500","text":"\"\"\"This file is a CareersSuning spider created on top of the ATSSpider\n\nscrapy crawl careerssuning -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"http://careers.suning.cn/rps-web/position/show_position_page.htm?model_name=&returnpath=position_society_list.ftl\"\n\nsample url:\n http://careers.suning.cn/rps-web/position/show_position_page.htm?model_name=&returnpath=position_society_list.ftl\n\"\"\"\n\nfrom urlparse import urljoin\nfrom re import compile\n\nfrom scrapy.selector import Selector\nfrom scrapy.http import Request, FormRequest\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, ConvertDateString, Replace\n\n\nclass CareersSuning(ATSSpider):\n\n name = 'careerssuning'\n ref_reg = compile('id=(.*?)[&?]')\n page_number = 1\n\n def parse(self, response):\n sel = Selector(response)\n jobs = sel.xpath(\"//ul[@class='show_list']/li\")\n for job in jobs:\n job_link = job.xpath(\"./p[3]/a/@href\").extract()\n if job_link:\n job_url = urljoin(response.url, job_link[0])\n meta = {\n \"title\": job.xpath(\"./p[3]/a/text()\").extract(),\n \"location\": job.xpath(\"./p[4]/text()\").extract(),\n \"jobcategory\": job.xpath(\"./p[2]/text()\").extract(),\n }\n yield Request(\n job_url, meta=meta, callback=self.parse_job_callback()\n )\n\n next = sel.xpath('//a[@class=\"next\"]').extract()\n if next:\n self.page_number += 1\n form_data = {\n \"id\": \"0\",\n \"type\": \"1\",\n \"ageEnd\": \"0\",\n \"status\": \"1\",\n \"browses\": \"0\",\n \"jobYear\": \"0\",\n \"mailings\": \"0\",\n \"ageBegin\": \"0\",\n \"engageNum\": \"0\",\n \"apployNum\": \"0\",\n \"groupCode\": \"01\",\n \"pageSize\": \"100\",\n \"wantengageNum\": \"0\",\n \"pageNumber\": str(self.page_number),\n }\n yield FormRequest(\n response.url, formdata=form_data, callback=self.parse\n )\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n\n loader.add_value('url', response.url)\n loader.add_value('apply_url', response.url)\n loader.add_value('title', response.meta['title'])\n loader.add_value('location', response.meta['location'])\n loader.add_value('jobcategory', response.meta['jobcategory'])\n loader.add_value(\n 'referencenumber', response.url,\n Prefix(self.name+\"-\"), re=self.ref_reg\n )\n loader.add_xpath(\n 'date', \"//div[@class='sodD_con']/dl/dd[2]/text()\",\n Replace('[^\\d]'), ConvertDateString(\"%Y%m%d\")\n )\n\n loader.add_xpath(\n 'jobtype', \"//div[@class='sodD_con']/dl/dd[5]/text()\"\n )\n loader.add_xpath(\n 'zip_code', \"//div[@class='addressCon']/ul/li[2]/text()\"\n )\n loader.add_xpath(\n 'description', \"//div[@class='sodD_con']/dl/dd[8]/text()\"\n )\n loader.add_xpath(\n 'requirements', \"//div[@class='sodD_con']/dl/dd[9]/text()\"\n )\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/careers_suning.py","file_name":"careers_suning.py","file_ext":"py","file_size_in_byte":3413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"536748373","text":"# -*- coding: utf-8 -*-\r\nprint(\"-\" * 40)\r\nprint(\"TP3 Exo 2 Question 1\")\r\nprint(\"-\" * 40)\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nN = 1000 # Taille echantillon\r\n\r\nintegers1toN = np.arange(1,N+1) # Un vecteur contenant les entiers de 1 a N\r\n\r\nEsp_gY = np.sinh(1.0)\r\nVar_gY = (1.0 - np.exp(-2.))/2.\r\n\r\n############################################\r\n# Completer avec N tirages de la loi uniforme [-1,1]\r\n# et les tirages de Y = exp(X)\r\nX = np.random.rand(N)*2-1\r\nY = np.exp(X)\r\n############################################\r\n\r\n############################################\r\n# Stocker dans 'mean' l'estimation MC de E[g(Y)]\r\n# dans 'var' la variance empirique et dans 'demiLargeurIC'\r\n# la demi-largeur de l'intervalle de confiance \r\n# asymptotique a 95% pour E[g(Y)]\r\nmean = np.mean(Y)\r\nvar = np.var(Y)\r\ndemiLargeurIC = 1.96*np.sqrt(var/N)\r\n############################################\r\n\r\nprint(\"Estimateur MC \\n\")\r\n\r\nprint(\"Esp_gY = %1.3f Var_gY = %1.3f\" %(Esp_gY, Var_gY))\r\nprint(\"mean = %1.3f var = %1.3f\" %(mean,var))\r\nprint(\"Intervalle de confiance 95%% pour E[g(Y)] = [ %1.3f , %1.3f ] \\n\" %(mean - demiLargeurIC, mean + demiLargeurIC))\r\nprint(\"erreur relative = %1.3f\" %(demiLargeurIC/mean))\r\n\r\n############################################\r\n## Trajectoires de la moyenne empirique\r\n############################################\r\nM = 10\r\n\r\n############################################\r\n# Evaluer M trajectoires de l'estimateur empirique I_n\r\nX = np.random.rand(M,N)*2-1\r\nY = np.exp(X)\r\nI_n = np.cumsum(Y, axis = 1) / integers1toN\r\n############################################\r\n\r\n# Affichage des trajectoires\r\nfig = plt.figure()\r\nax = fig.add_subplot(111)\r\nax.plot(integers1toN, I_n.T, color=\"b\")\r\n\r\nax.set_xlim(0, N)\r\nax.set_ylim(1.0, 1.3)\r\nax.axhline(Esp_gY, color=\"r\", label=\"Esperance\")\r\nax.legend(loc=\"best\")\r\nplt.show()","sub_path":"MAP556/PC 3 (TP Python)-20181003/MAP556_PC3_Exo2_Q1.py","file_name":"MAP556_PC3_Exo2_Q1.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"412272322","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 6 23:06:39 2018\n@author: Abhik Banerjee\nThis .py code gives out the GUI for Stegnography.\n\"\"\"\nimport tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import IntVar ,DISABLED ,NORMAL ,filedialog\nfrom steg import giveTo, extract\n\"\"\"\nThe Main Controller.\n\"\"\"\nclass SimpleEncrypt(tk.Tk):\n def __init__(self,*args,**kwargs):\n tk.Tk.__init__(self)\n container=tk.Frame(self)\n self.title(\"Steg101 v1.10\")\n self.iconbitmap('iconf.ico')\n container.pack(side=\"top\",fill=\"both\",expand=\"True\")\n container.grid_rowconfigure(0,weight=1)\n container.grid_columnconfigure(0,weight=1)\n self.frames={}\n for x in (IntroPage,StartPage,HidePage1,HidePage2,HidePage3,RetrievePage):\n frame=x(container,self)\n self.frames[x]=frame\n frame.grid(row=0,column=0,sticky=\"nsew\")\n self.showFrame(IntroPage)\n def showFrame(self,cont):\n frame=self.frames[cont]\n frame.tkraise() \n def showError(self,mess):\n tk.Label(self,text=mess).pack()\nclass IntroPage(tk.Frame):\n def __init__(self,parent,controller):\n ttk.Frame.__init__(self,parent)\n message1=\"\"\"This is a test Application. Please Read the Introduction if\n you are a first-timer. \n \"\"\"\n message2=\"\"\"\n This application is made for basic Stenography. Assuming you know what that is,\n we shall skip it. Steg101 hides your message or text from a file into another file\n without affecting the target file's quality. Right now it can only use Pictures for hiding.\n \n Please note that it is recommended to not use a file multiple times to hide messages many \n messages simultanousely in multiple goes. That being said, you should know that the hide \n option will be disabled once a file is successfully used.\n To hide a message again, you need to restart the application.\"\"\"\n message3=\"\"\"\n Final Note: Please Enter the correct file locations and names in correct format.\n Use \"\\\\\\\\\" or \"/\" and not \"\\\\\" for file path.\"\"\"\n message4=\"\"\"Warning: The Makers would not be held responsible for the actions of the User.\"\"\"\n ttk.Label(self,text=message1,font=(\"Comic Sans MS\",12,'bold')).pack(padx=20,anchor=\"center\")\n ttk.Label(self,text=message2,font=(\"Helvetica\",12)).pack(fill=\"both\",anchor=\"center\")\n ttk.Label(self,text=message3,font=(\"Verdana\",10,\"bold\")).pack(fill=\"both\",anchor=\"center\")\n ttk.Label(self,text=message4,font=(\"Times\",12,\"bold italic underline\")).pack(pady=10,anchor=\"center\")\n ttk.Button(self,text=\"Start\",command=lambda:controller.showFrame(StartPage)).pack(padx=10,pady=(0,20),anchor=\"center\") \n\"\"\" \nThis is the Start Page.\n\"\"\" \nclass StartPage(tk.Frame):\n def __init__(self,parent,controller):\n ttk.Frame.__init__(self,parent)\n label=tk.Label(self,text=\"Welcome to Steg101\\nPlease Select your Action:\",font=(\"Times\",14))\n label.pack(pady=(0,10))\n button1=ttk.Button(self,text=\"Hide ->\",command=lambda:controller.showFrame(HidePage1))\n button1.pack(pady=10,anchor=\"center\")\n button2=ttk.Button(self,text=\"Retrieve ->\",command=lambda:controller.showFrame(RetrievePage))\n button2.pack(pady=10,anchor=\"center\")\n button4=ttk.Button(self,text=\"<-Go Back to Intro\",command=lambda:controller.showFrame(IntroPage))\n button4.pack(pady=10,anchor=\"center\")\n button3=ttk.Button(self,text=\"Quit\",command=controller.destroy)\n button3.pack(pady=10,anchor=\"center\")\n\"\"\"\nIf the User wants to Hide, it will direct to this page. Here the user needs to select whether to hide from a file or\nenter the message directly\n\"\"\"\nclass HidePage1(tk.Frame):\n def __init__(self,parent,controller):\n ttk.Frame.__init__(self,parent)\n tk.Label(self,text=\"Welcome to Steg101\\nHappy Encryption!\",font=(\"Times\",14)).pack(anchor=\"center\")\n tk.Label(self,text=\"Please select:\").pack(anchor=\"n\")\n self.var=IntVar()\n ttk.Radiobutton(self,text=\"Read from a File.\",variable=self.var,value=1).pack(padx=10,pady=10,fill=\"x\")\n ttk.Radiobutton(self,text=\"Enter the Text Directly.\",variable=self.var,value=2).pack(padx=10,pady=10,fill=\"x\")\n ttk.Button(self,text=\"Next->\",command=lambda:self.callPage(controller)).pack(padx=10,pady=20)\n ttk.Button(self,text=\"<-Go Back\",command=lambda:controller.showFrame(StartPage)).pack(padx=10,pady=20)\n self.e3=tk.Label(self)\n button3=ttk.Button(self,text=\"Quit\",command=controller.destroy)\n button3.pack(pady=10,anchor=\"center\")\n def callPage(self,cont):\n x=int(self.var.get())\n if x==1:\n cont.showFrame(HidePage2)\n elif x==2:\n cont.showFrame(HidePage3)\n else:\n self.e3.config(text=\"Please Select a button and then click.\\nOtherwise Go Back!\",font=(\"Verdana\",10,\"bold\"))\n self.e3.pack(padx=10,pady=5,fill=\"both\",expand=\"true\") \n\"\"\"\nIf the User wants to hide after extracting from a file then this page is shown.\n\"\"\" \nclass HidePage2(tk.Frame):\n def __init__(self,parent,controller):\n ttk.Frame.__init__(self,parent)\n tk.Label(self,text=\"Welcome to Steg101\\nHappy Encryption!\",font=(\"Times\",14)).pack()\n tk.Label(self,text=\"Path to Source File:\").pack(padx=20,pady=10)\n self.e1=ttk.Entry(self,validate=\"key\")\n self.e1.insert(0,\"eg:c:\\\\\\\\ProgramFiles\\\\\\\\xyz.txt\")\n self.e1.pack(padx=20,pady=(0,5),fill=\"x\",expand=\"true\")\n ttk.Button(self,text=\"...\",command=lambda:self.browse(self.e1,\"text\")).pack(padx=10,anchor=\"e\")\n tk.Label(self,text=\"Path to Target File:\").pack()\n e2=ttk.Entry(self,validate=\"key\")\n e2.insert(0,\"eg:C:\\\\\\\\ProgramFiles\\\\\\\\xyz.txt\")\n e2.pack(padx=20,pady=(10,5),fill=\"x\",expand=\"true\")\n ttk.Button(self,text=\"...\",command=lambda:self.browse(e2,\"any\")).pack(padx=10,anchor=\"e\")\n self.checkVal=IntVar()\n ch1=ttk.Checkbutton(self,text=\"Encrypt the Text.\",variable=self.checkVal,onvalue=1,offvalue=0)\n ch1.pack(padx=20,fill=\"x\")\n self.button1=ttk.Button(self,text=\"Start Hiding ->\",command=lambda:self.callFunc(str(self.e1.get()),str(e2.get())))\n self.button1.pack(padx=20,pady=10)\n ttk.Button(self,text=\"<- Go Back\",command=lambda:controller.showFrame(StartPage)).pack(pady=10)\n self.e3=tk.Label(self)\n button3=ttk.Button(self,text=\"Quit\",command=controller.destroy)\n button3.pack(pady=10,anchor=\"center\")\n def browse(self,e,ftype):\n if ftype==\"text\":\n browseButton=tk.filedialog.askopenfilename(initialdir=\"/\",title=\"Select File\",filetypes=((\"text files\",\"*.txt\"),(\"all files\",\"*.*\")))\n elif ftype==\"any\":\n browseButton=tk.filedialog.askopenfilename(initialdir=\"/\",title=\"Select File\",filetypes=((\"JPG Files\",\"*.jpg\"),(\"JPEG Files\",\"*.jpeg\"),(\"Bitmap Files\",\"*.bmp\"),(\"MP# Files\",\"*.mp3\"),(\"MP4 Files\",\".mp4\"),(\"MKV Files\",\"*.mkv\"),(\"AVI Files\",\"*.avi\"),(\"All Files\",\"*.*\")))\n if len(browseButton)!=0:\n e.delete(0,\"end\")\n e.insert(0,browseButton)\n def callFunc(self,x,y):\n pathS=str(x)\n pathT=str(y)\n try:\n mess=giveTo(pathT,pathS,1,self.checkVal.get())\n if \"Done\" in mess:\n self.button1.configure(state=DISABLED)\n if self.checkVal.get()==1:\n mess=mess+\" Message Encrypted as well.\"\n tk.Label(self,text=mess,font=(\"Verdana\",10,\"bold\")).pack() \n except OSError:\n self.e3.config(text=\"Invalid Argument\",font=(\"Verdana\",10,\"bold underline\"))\n self.e3.pack(padx=10,pady=10,fill=\"x\")\n\"\"\"\nIf the User wants to hide by entering the message directly, this page is opened.\n\"\"\"\nclass HidePage3(tk.Frame):\n def __init__(self,parent,controller):\n ttk.Frame.__init__(self,parent)\n tk.Label(self,text=\"Welcome to Steg101\\nHappy Encryption!\",font=(\"Times\",14)).pack(anchor=\"center\")\n tk.Label(self,text=\"Please Enter your Message:\").pack(padx=20,pady=10)\n e1=ttk.Entry(self,validate=\"key\")\n e1.insert(0,\"eg:The Quick Brown Fox Jumps Over The Lazy Dog.\")\n e1.pack(padx=20,pady=(0,20),fill=\"x\",expand=\"true\")\n tk.Label(self,text=\"Path to Target File:\").pack()\n e2=ttk.Entry(self,validate=\"key\")\n e2.insert(0,\"eg:C:\\\\\\\\ProgramFiles\\\\\\\\xyz.txt\")\n e2.pack(padx=20,pady=(10,5),fill=\"x\",expand=\"true\")\n ttk.Button(self,text=\"...\",command=lambda:self.browse(e2,\"any\")).pack(padx=10,anchor=\"e\")\n self.checkVal=IntVar()\n ch1=ttk.Checkbutton(self,text=\"Encrypt the Text.\",variable=self.checkVal,onvalue=1,offvalue=0)\n ch1.pack(padx=20,fill=\"x\")\n self.button1=ttk.Button(self,text=\"Start Hiding ->\",command=lambda:self.callFunc(str(e1.get()),str(e2.get())))\n self.button1.pack(padx=20,pady=10)\n ttk.Button(self,text=\"<- Go Back\",command=lambda:controller.showFrame(StartPage)).pack(pady=10)\n self.e3=tk.Label(self)\n button3=ttk.Button(self,text=\"Quit\",command=controller.destroy)\n button3.pack(pady=10,anchor=\"center\")\n def browse(self,e,ftype):\n if ftype==\"any\":\n browseButton=tk.filedialog.askopenfilename(initialdir=\"/\",title=\"Select File\",filetypes=((\"JPG Files\",\"*.jpg\"),(\"JPEG Files\",\"*.jpeg\"),(\"Bitmap Files\",\"*.bmp\"),(\"MP# Files\",\"*.mp3\"),(\"MP4 Files\",\".mp4\"),(\"MKV Files\",\"*.mkv\"),(\"AVI Files\",\"*.avi\"),(\"All Files\",\"*.*\")))\n if len(browseButton)!=0:\n e.delete(0,\"end\")\n e.insert(0,browseButton)\n def callFunc(self,x,y):\n message=str(x)\n pathT=str(y)\n try:\n mess=giveTo(pathT,message,0,self.checkVal.get())\n if \"Done\" in mess:\n self.button1.configure(state=DISABLED)\n tk.Label(self,text=mess,font=(\"Verdana\",10,\"bold underline\")).pack()\n except OSError:\n \n self.e3.config(text=\"Invalid Argument\")\n self.e3.pack(padx=10,pady=10,fill=\"x\") \n\"\"\"\nShould the user select to retrieve, this page is hown\n\"\"\"\nclass RetrievePage(tk.Frame):\n def __init__(self,parent,controller):\n ttk.Frame.__init__(self,parent)\n tk.Label(self,text=\"Welcome to Steg101\\nHappy Encryption!\",font=(\"Times\",14)).pack(anchor=\"center\")\n tk.Label(self,text=\"Please enter the path of the File Used:\").pack(padx=20,pady=10)\n e1=tk.Entry(self,validate=\"key\")\n e1.insert(0,\"eg:c:\\\\ProgramFiles\\\\xyz.txt\")\n e1.pack(padx=10,pady=(20,5),fill=\"x\",expand=\"true\")\n ttk.Button(self,text=\"...\",command=lambda:self.browse(e1,\"any\")).pack(padx=10,anchor=\"e\")\n self.checkVal=IntVar()\n e2=ttk.Checkbutton(self,text=\"Please Select the Checkbox if the message was encrypted\",variable=self.checkVal,onvalue=1,offvalue=0,command=self.turnon)\n e2.pack(padx=10,pady=(20,10),anchor=\"w\")\n self.e4=ttk.Entry(self,state=DISABLED)\n self.e4.bind('',self.focus_in)\n self.e4.bind('',self.focus_out)\n self.e4.pack(padx=20,expand=\"true\",anchor=\"w\")\n self.button1=ttk.Button(self,text=\"Start Retrieval->\",command=lambda:self.callFunc(str(e1.get())))\n self.button1.pack(padx=20,pady=(10,10) )\n ttk.Button(self,text=\"<- Go Back\",command=lambda:controller.showFrame(StartPage)).pack(pady=(10,10))\n self.e3=tk.Label(self)\n button3=ttk.Button(self,text=\"Quit\",command=controller.destroy)\n button3.pack(pady=10,anchor=\"center\")\n def browse(self,e,ftype):\n if ftype==\"any\":\n browseButton=tk.filedialog.askopenfilename(initialdir=\"/\",title=\"Select File\",filetypes=((\"JPG Files\",\"*.jpg\"),(\"JPEG Files\",\"*.jpeg\"),(\"Bitmap Files\",\"*.bmp\"),(\"MP# Files\",\"*.mp3\"),(\"MP4 Files\",\".mp4\"),(\"MKV Files\",\"*.mkv\"),(\"AVI Files\",\"*.avi\"),(\"All Files\",\"*.*\")))\n if len(browseButton)!=0:\n e.delete(0,\"end\")\n e.insert(0,browseButton)\n def turnon(self):\n self.e4.configure(state=NORMAL)\n self.e4.delete(0,\"end\")\n self.e4.insert(0,\"Please Enter the Key\")\n def focus_in(self,event):\n self.e4.delete(0,\"end\")\n def focus_out(self,event):\n self.turnon()\n def callFunc(self,pathf):\n try:\n if self.checkVal.get()==1:\n key=int(self.e4.get())\n mess=extract(pathf,key,1)\n elif self.checkVal.get()==0:\n mess=extract(pathf,26,0)\n mess=\"Message: \"+mess\n self.e3.configure(text=mess,font=(\"Comic Sans MS\",10,\"underline\"))\n self.e3.pack(padx=10,pady=10,fill=\"both\",expand=\"true\") \n except OSError: \n self.e3.config(text=\"Check the Path name format and filename!\",font=(\"Verdana\",10,\"bold\"))\n self.e3.pack(padx=10,pady=10,fill=\"both\",expand=\"true\")\ninst=SimpleEncrypt()\ninst.mainloop()","sub_path":"stegModified.py","file_name":"stegModified.py","file_ext":"py","file_size_in_byte":13003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"326483969","text":"die_surfaces = [{'value' : 1, 'symbol' : 'Infantry'}, \r\n {'value' : 2, 'symbol' : 'Infantry'},\r\n {'value' : 3, 'symbol' : 'Infantry'},\r\n {'value' : 1, 'symbol' : 'Archery'},\r\n {'value' : 1, 'symbol' : 'Cavalry'},\r\n {'value' : 1, 'symbol' : 'Daimyo'}]\r\n\r\ncastles_list = [{'point' : 3, 'name' : 'Kumamoto', 'clan' : 'Shimazu'},\r\n {'point' : 1, 'name' : 'Marugame', 'clan' : 'Chosokabe'}, {'point' : 2, 'name' : 'Matsuyama', 'clan' : 'Chosokabe'},\r\n {'point' : 2, 'name' : 'Takahashi', 'clan' : 'Mori'}, {'point' : 2, 'name' : 'Gassantoda', 'clan' : 'Mori'},\r\n {'point' : 3, 'name' : 'Kitanosho', 'clan' : 'Uesugi'}, {'point' : 4, 'name' : 'Kasugayama', 'clan' : 'Uesugi'},\r\n {'point' : 1, 'name' : 'Inuyama', 'clan' : 'Tokugawa'}, {'point' : 1, 'name' : 'Kiyosu', 'clan' : 'Tokugawa'}, {'point' : 1, 'name' : 'Edo', 'clan' : 'Tokugawa'},\r\n {'point' : 1, 'name' : 'Gifu', 'clan' : 'Oda'}, {'point' : 1, 'name' : 'Odani', 'clan' : 'Oda'}, {'point' : 1, 'name' : 'Matsumoto', 'clan' : 'Oda'}, {'point' : 1, 'name' : 'Azuchi', 'clan' : 'Oda'}]","sub_path":"constant.py","file_name":"constant.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"482345094","text":"import pypyodbc\nimport json\nimport urllib.request\nimport csv\nimport numpy as np\n\n\ndef out_csv(data):\n with open(\"bar_final.csv\", \"w\", newline='') as csv_file:\n writer = csv.writer(csv_file, delimiter=',')\n writer.writerow(['place id', 'name', 'address'])\n for line in data:\n try:\n writer.writerow(line)\n except:\n continue\n\"\"\"\nwith open('C:\\\\Users\\\\mikeb\\\\MobileApp\\\\Swift\\\\radar_sample.json') as data_file:\n data = json.load(data_file)\n print(data[\"result\"][\"name\"])\n\"\"\"\n\n\ndef read_double(path1, path2):\n out = []\n one = []\n two = []\n with open(path1) as csv1:\n read_csv = csv.reader(csv1, delimiter=',')\n for row in read_csv:\n one.append(row)\n with open(path2) as csv2:\n read_csv2 = csv.reader(csv2, delimiter=',')\n for row in read_csv2:\n two.append(row)\n\n for item in two:\n if item not in one:\n out.append(item)\n for item in one:\n if item not in two and item not in out:\n out.append(item)\n return out\n\n\ndef read_single(path):\n # with open('C:\\\\Users\\\\mikeb\\\\MobileApp\\\\Swift\\\\bar2.json') as data_file:\n with open(path) as data_file:\n data = json.load(data_file)\n out = []\n for item in enumerate(data[\"results\"]):\n x = item[1]\n id = item[1][\"id\"]\n name = item[1][\"name\"]\n addr = item[1][\"vicinity\"]\n d = [id, name, addr]\n out.append(d)\n return out\n \"\"\"\n for item in enumerate(data[\"results\"]):\n content = (urllib.request.urlopen(\"https://maps.googleapis.com/maps/api/place/details/json?placeid=\" + item[1][\"place_id\"] + \"&key=AIzaSyAP7OGxkDtr7mT28ZUlXOPcUJ6zmmqRxng\").read()).decode(\"utf-8\")\n result = json.loads(content)\n test = result[\"result\"][\"name\"]\n d = [item[1][\"place_id\"], result[\"result\"][\"name\"], result[\"result\"][\"vicinity\"]]\n # print(item[1][\"place_id\"])\n out.append(d)\n \"\"\"\n# call read double on 2 files\nout = read_double('C:\\\\Users\\\\mikeb\\\\PycharmProjects\\\\JsonExtracter\\\\bar2.csv', 'C:\\\\Users\\\\mikeb\\\\PycharmProjects\\\\JsonExtracter\\\\bars.csv')\nout_csv(out)\n\n","sub_path":"cardinal/JsonExtracter/ExtractJson.py","file_name":"ExtractJson.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"407150026","text":"from smtplib import SMTPServerDisconnected\nfrom django.http import HttpResponse\nfrom django.contrib.auth.hashers import check_password, make_password\nfrom user.models import user,comments,order,make_forget_code\nfrom photographer.models import photographer\nfrom other.models import other\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.conf import settings\nfrom django.core.files import File\nfrom django.utils.timezone import now\nfrom django.core.mail import send_mail\nfrom server.settings import EMAIL_FROM\nimport json\nimport os\n\n\ndef merge_dicts(*dict_args):\n result = {}\n for dictionary in dict_args:\n result.update(dictionary)\n return result\n\n\ndef sendPic(pic):\n return HttpResponse(pic, content_type=\"image/png\")\n\n\ndef getPic(request):\n username = request.POST['username']\n try:\n find_user = user.objects.get(user_name=username)\n except ObjectDoesNotExist:\n return HttpResponse(\"No such user\")\n if request.method == 'POST':\n img = request.POST['img']\n try:\n savepath = os.path.join(settings.MEDIA_ROOT,username)\n with open(savepath,\"w\") as f:\n save_icon = File(f)\n save_icon.write(img)\n print(\"saved\")\n find_user.pic = username\n find_user.save()\n except:\n return HttpResponse(\"icon update failed\")\n return HttpResponse(\"icon updated\")\n else:\n return HttpResponse(\"only POST is accepted\")\n\n\ndef login(request):\n get_email = request.GET['email']\n get_password = request.GET['password']\n response = {\n \"error_code\": 20000,\n \"message\": \"service not available\",\n }\n try:\n try:\n find_user = user.objects.get(email=get_email)\n if check_password(get_password, find_user.user_password):\n response = {\n \"error_code\": 10000,\n \"message\": \"success\",\n \"data\": {\n \"user_id\": find_user.id,\n \"group_id\": find_user.group_id,\n \"address_id\": find_user.address_id,\n \"usercomment_id\": find_user.usercomment_id,\n }\n }\n # sendPic(find_user.small_pic)\n elif get_email is None or get_password is None:\n response = {\n \"error_code\": 10001,\n \"message\": \"blank email or password\",\n }\n elif not check_password(get_password, find_user.user_password):\n response = {\n \"error_code\": 10000,\n \"message\": \"wrong password\",\n }\n except ObjectDoesNotExist:\n response = {\n \"error_code\": 40004,\n \"message\": \"user not found\",\n }\n except:\n response = {\n \"error_code\": 20000,\n \"message\": \"service not available\",\n }\n return HttpResponse(json.dumps(response), content_type=\"application/json\")\n\n\ndef register(request):\n get_username = request.GET['username']\n get_password = request.GET['password']\n get_schoolname = request.GET['schoolname']\n get_email = request.GET['email']\n try:\n if user.objects.filter(user_name=get_username).count() > 0:\n response = {\n \"error_code\": 10000,\n \"message\": \"user already exists\",\n }\n elif user.objects.filter(user_name=get_username).count() == 0:\n user.objects.create(user_name=get_username, user_password=make_password(get_password),\n user_school=get_schoolname,\n email=get_email)\n find_user = user.objects.get(user_name=get_username)\n verify_code = find_user.verify_code\n try:\n title = \"您的邮箱正在被用于注册CyanImg\"\n body = \"点击以下链接来验证您的邮箱\"+\"http://47.103.117.214:65535/api/user/verify?user=\"+get_username+\"&verify=\"+verify_code\n if send_mail(title, body, EMAIL_FROM, [get_email]) == 1:\n response = {\n \"error_code\": 10000,\n \"message\": \"email sent\"\n }\n else:\n response = {\n \"error_code\": 20000,\n \"message\": \"email not sent\"\n }\n except:\n response = {\n \"error_code\": 20000,\n \"message\": \"service not available\",\n }\n except:\n response = {\n \"error_code\": 20000,\n \"message\": \"service not available\",\n }\n return HttpResponse(json.dumps(response), content_type=\"application/json\")\n\n\ndef send_forget_code(request):\n get_email = request.GET['email']\n find_user = user.objects.get(email=get_email)\n forget_code = find_user.forget_code\n mail = get_email\n try:\n title = \"找回您的CyanImg密码\"\n body = \"使用以下救援代码来重设您的CyanImg密码:\"+forget_code\n if send_mail(title,body,EMAIL_FROM,[mail]) == 1:\n response = {\n \"error_code\":10000,\n \"message\":\"email sent\"\n }\n else:\n response = {\n \"error_code\":20000,\n \"message\":\"email not sent\"\n }\n except SMTPServerDisconnected:\n response = {\n \"error_code\":20000,\n \"message\":\"Connection unexpectedly closed\"\n }\n return HttpResponse(json.dumps(response), content_type=\"application/json\")\n\n\ndef verify(request):\n get_user = request.GET['user']\n get_verify_code = request.GET['verify']\n try:\n find_user = user.objects.get(user_name=get_user)\n verify_code = find_user.verify_code\n if get_verify_code == verify_code and not find_user.is_verified:\n find_user.is_verified = True\n find_user.save()\n response = {\n \"error_code\":10000,\n \"message\":\"verified\"\n }\n else:\n response = {\n \"error_code\":10000,\n \"message\":\"incorrect verify code or verified\"\n }\n except Exception as e:\n print(e)\n response = {\n \"error_code\":20000,\n \"message\":\"service not available\"\n }\n return HttpResponse(json.dumps(response), content_type=\"application/json\")\n\n\ndef forget(request):\n get_user = request.GET['user']\n get_forget_code = request.GET['forget']\n new_password = request.GET['newpassword']\n find_user = user.objects.get(user_name=get_user)\n forget_code = find_user.forget_code\n if get_forget_code == forget_code:\n find_user.update(user_password=make_password(new_password))\n find_user.update(forget_code=make_forget_code())\n response = {\n \"error_code\":10000,\n \"message\":\"password reset\"\n }\n else:\n response = {\n \"error_code\":10000,\n \"message\":\"incorrect code\"\n }\n return HttpResponse(json.dumps(response), content_type=\"application/json\")\n\n\ndef search(request):\n get_graphername = request.GET.get('graphername', None)\n get_schoolname = request.GET.get('schoolname', None)\n get_othername = request.GET.get('othername', None)\n\n if get_graphername is not None:\n try:\n find_photographer = photographer.objects.get(graph_name=get_graphername)\n response = {\n \"error_code\": 10000,\n \"data\": {\n \"graph_id\": find_photographer.graph_id(),\n \"graphcomment_id\": find_photographer.graphcomment_id,\n \"graph_name\": find_photographer.graph_name,\n \"graph_school\": find_photographer.graph_name,\n \"email\": find_photographer.email,\n # \"graph_identification\":find_photographer.graph_identification,\n \"experience\": find_photographer.experience,\n \"last_login_time\": str(find_photographer.last_login_time),\n },\n \"message\": \"photographer found\",\n }\n except ObjectDoesNotExist:\n find_photographer = photographer.objects.filter(graph_name__contains=get_graphername)\n if len(find_photographer) > 0:\n response = {\"error_code\": 10000, \"datalist\": {}}\n for i in find_photographer:\n newdata = {str(i.graph_id()): {\n \"graph_id\": i.graph_id(),\n \"graphcomment_id\": i.graphcomment_id,\n \"graph_name\": i.graph_name,\n \"graph_school\": i.graph_name,\n \"email\": i.email,\n # \"graph_identification\":i.graph_identification,\n \"experience\": i.experience,\n \"last_login_time\": str(i.last_login_time),\n }}\n response['datalist'].update(newdata)\n response.update({\"message\": \"photographer found\"})\n else:\n response = {\n \"error_code\": 10000,\n \"message\": \"no such photographer\",\n }\n # sendPic(find_photographer.pic)\n # sendPic(find_photographer.album)\n\n else:\n if get_othername is not None:\n try:\n find_other = other.objects.get(other_name=get_othername)\n response = {\n \"error_code\": 10000,\n \"data\": {\n \"graph_id\": find_other.graph_id(),\n \"graphcomment_id\": find_other.graphcomment_id,\n \"graph_name\": find_other.graph_name,\n \"graph_school\": find_other.graph_name,\n \"email\": find_other.email,\n # \"graph_identification\":find_other.graph_identification,\n \"experience\": find_other.experience,\n \"last_login_time\": str(find_other.last_login_time),\n },\n \"message\": \"photographer found\",\n }\n except ObjectDoesNotExist:\n find_other = photographer.objects.filter(other_name__contains=get_graphername)\n if len(find_other) > 0:\n response = {\"error_code\": 10000, \"datalist\": {}}\n for i in find_other:\n newdata = {str(i.graph_id()): {\n \"graph_id\": i.graph_id(),\n \"graphcomment_id\": i.graphcomment_id,\n \"graph_name\": i.graph_name,\n \"graph_school\": i.graph_name,\n \"email\": i.email,\n # \"graph_identification\":i.graph_identification,\n \"experience\": i.experience,\n \"last_login_time\": str(i.last_login_time),\n }}\n response['datalist'].update(newdata)\n response.update({\"message\": \"other found\"})\n else:\n response = {\n \"error_code\": 10000,\n \"message\": \"no such other\",\n }\n # sendPic(find_other.pic)\n # sendPic(find_other.album)\n\n return HttpResponse(json.dumps(response), content_type=\"application/json\")\n\n\ndef makeComment(request):\n get_user = request.GET['username']\n content = request.GET['content']\n u = user.objects.get(user_name=get_user)\n user_name = u.user_name\n user_school = u.user_school\n group_id = u.group_id\n try:\n comments.objects.create(user_name=user_name,user_school=user_school,comment_content=content)\n response = {\n \"error_code\":10000,\n \"message\":\"comment updated\",\n \"data\":{\n \"username\":user_name,\n \"userschool\":user_school,\n \"commentcontent\":content,\n }\n }\n return HttpResponse(json.dumps(response),content_type=\"application/json\")\n except Exception as e:\n print(e)\n response = {\n \"error_code\": 10000,\n \"message\": \"comment failed\",\n }\n return HttpResponse(json.dumps(response),content_type=\"application/json\")\n\n\ndef makeOrder(request):\n get_user = request.GET['username']\n get_graph = request.GET['graphname']\n # order_time = now()\n total = request.GET['total']\n # update_time = now()\n # order_status = False\n # payment_status = False\n meet_time = request.GET['meettime']\n address = request.GET['address']\n tel = request.GET['tel']\n try:\n find_user = user.objects.get(user_name=get_user)\n find_photographer = photographer.objects.get(graph_name=get_graph)\n order.objects.create(user_name=find_user.user_name,graph_name=find_photographer.graph_name,total=total,update_time=now(),meet_time=meet_time,address=address,tel=tel,user_school=find_user.user_school,graph_school=find_photographer.graph_school)\n response = {\n \"error_code\": 10000,\n \"message\": \"order added\",\n }\n except ObjectDoesNotExist:\n response = {\n \"error_code\": 10000,\n \"message\": \"no such user/grapher\",\n }\n return HttpResponse(json.dumps(response), content_type=\"application/json\")\n\n\ndef changeOrder(request):\n get_order = request.GET['order']\n get_total = request.GET['total']\n get_order_status = request.GET['status']\n get_payment_status = request.GET['paymentstatus']\n get_meet_time = request.GET['meettime']\n get_address = request.GET['address']\n get_tel = request.GET['tel']\n try:\n find_order = order.objects.get(order_id=get_order)\n if get_total is not None:\n find_order.total = get_total\n if get_order_status is not None:\n find_order.order_status = get_order_status\n if get_payment_status is not None:\n find_order.payment_status = get_order_status\n if get_meet_time is not None:\n find_order.meet_time = get_meet_time\n if get_address is not None:\n find_order.address = get_address\n if get_tel is not None:\n find_order.tel = get_tel\n find_order.save()\n response = {\n \"error_code\": 10000,\n \"message\": \"order updated\",\n }\n except ObjectDoesNotExist:\n response = {\n \"error_code\": 10000,\n \"message\": \"no such order\",\n }\n return HttpResponse(json.dumps(response), content_type=\"application/json\")","sub_path":"user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"245774231","text":"import json as JSON\nimport jsonschema\nfrom jsonschema import Draft4Validator\nfrom flask import Blueprint, jsonify, request\n\n\nimport os\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\nMember_schema = JSON.load(open('./schema/Member_schema.json'))\nMember_schema_resolver = jsonschema.RefResolver('file://' + dir_path + '/schema/', Member_schema)\nMember_schema_validator = Draft4Validator(Member_schema, resolver=Member_schema_resolver)\n\nNetwork_schema = JSON.load(open('./schema/Network_schema.json'))\nNetwork_schema_resolver = jsonschema.RefResolver('file://' + dir_path + '/schema/', Network_schema)\nNetwork_schema_validator = Draft4Validator(Network_schema, resolver=Network_schema_resolver)\n\n\nnetwork_api = Blueprint('network_api', __name__)\n\n\n@network_api.route('/network', methods=['GET'])\ndef network_get():\n '''\n Get a list of networks\n It is handler for GET /network\n '''\n \n return jsonify()\n\n\n@network_api.route('/network/', methods=['GET'])\ndef getNetwork(id):\n '''\n Get network, id=ZeroTier network ID (16 hex digits)\n It is handler for GET /network/\n '''\n \n return jsonify()\n\n\n@network_api.route('/network/', methods=['POST'])\ndef updateNetwork(id):\n '''\n Update network\n It is handler for POST /network/\n '''\n \n inputs = request.get_json()\n try:\n Network_schema_validator.validate(inputs)\n except jsonschema.ValidationError as e:\n return jsonify(errors=\"bad request body\"), 400\n \n return jsonify()\n\n\n@network_api.route('/network/', methods=['DELETE'])\ndef deleteNetwork(id):\n '''\n Delete network\n It is handler for DELETE /network/\n '''\n \n return jsonify()\n\n\n@network_api.route('/network//member', methods=['GET'])\ndef network_byNetworkidmember_get(networkid):\n '''\n Get a list of members\n It is handler for GET /network//member\n '''\n \n return jsonify()\n\n\n@network_api.route('/network//member/', methods=['GET'])\ndef getMember(id, networkid):\n '''\n Get member, id=10-digit ZeroTier node ID (a.k.a. ZeroTier address)\n It is handler for GET /network//member/\n '''\n \n return jsonify()\n\n\n@network_api.route('/network//member/', methods=['POST'])\ndef updateMember(id, networkid):\n '''\n Update member\n It is handler for POST /network//member/\n '''\n \n inputs = request.get_json()\n try:\n Member_schema_validator.validate(inputs)\n except jsonschema.ValidationError as e:\n return jsonify(errors=\"bad request body\"), 400\n \n return jsonify()\n","sub_path":"raml/manualspec_includes/py_server/network_api.py","file_name":"network_api.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"369740819","text":"import arbolDistanciaGenetica2 as ae # arbolEspecie\nimport mapa\nimport individuo\nimport planta\nimport random\n\n#recogida de datos\ntierra1 = open(\"tierra1.log\", \"w\")\ntierra2 = open(\"tierra2.log\", \"w\")\ntierra3 = open(\"tierra3.log\", \"w\")\ntierra4 = open(\"tierra4.log\", \"w\")\n\n#Crear territorio\nterritorios = []\ngranValle = mapa.Territorio(25,True,0,[])\ngranValle2 = mapa.Territorio(50,True,0,[])\ngranValle3 = mapa.Territorio(75,True,0,[])\ngranValle4 = mapa.Territorio(100,True,0,[])\nterritorios.append(granValle)\nterritorios.append(granValle2)\nterritorios.append(granValle3)\nterritorios.append(granValle4)\n\n\ncromosoma1 = {\n\t\t'fuerza' : 5,\n\t\t'destreza' : 15,\n\t\t'constitucion' : 5,\n\t\t'velocidad' : 21,\n\t\t'inteligencia' : 4,\n\t\t'percepcion' : 11,\n\t\t'esperanzaVida' : 60,\n\t\t'fecundidad' : 3,\n\t\t'madurezSexual': 10}\ncromosoma2 = {\n\t\t'fuerza' : 5,\n\t\t'destreza' : 6,\n\t\t'constitucion' : 4,\n\t\t'velocidad' : 19,\n\t\t'inteligencia' : 1,\n\t\t'percepcion' : 16,\n\t\t'esperanzaVida' : 60,\n\t\t'fecundidad' : 3,\n\t\t'madurezSexual': 10}\n\ncromosoma3 = {\n\t\t'fuerza' : 6,\n\t\t'destreza' : 4,\n\t\t'constitucion' : 4,\n\t\t'velocidad' : 3,\n\t\t'inteligencia' : 1,\n\t\t'percepcion' : 8,\n\t\t'esperanzaVida' : 60,\n\t\t'fecundidad' : 3,\n\t\t'madurezSexual': 10}\n\ncromosoma4 = {\n\t\t'fuerza' : 4,\n\t\t'destreza' : 5,\n\t\t'constitucion' : 4,\n\t\t'velocidad' : 10,\n\t\t'inteligencia' : 1,\n\t\t'percepcion' : 6,\n\t\t'esperanzaVida' : 60,\n\t\t'fecundidad' : 3,\n\t\t'madurezSexual': 10}\n\ncromosoma5 = {\n\t\t'fuerza' : 4,\n\t\t'destreza' : 5,\n\t\t'constitucion' : 7,\n\t\t'velocidad' : 20,\n\t\t'inteligencia' : 1,\n\t\t'percepcion' : 6,\n\t\t'esperanzaVida' : 60,\n\t\t'fecundidad' : 1,\n\t\t'madurezSexual': 10}\n\n\n#Crear plantas (Se añaden como listas)\nfor i in range(0,8):\n\tgranValle.newPlanta([planta.Planta(5, 10, 5, 10)])\n\tgranValle.newPlanta([planta.Planta(2, 40, 10, 40)])\n\tgranValle.newPlanta([planta.Planta(3, 20, 15, 20)])\n\nfor i in range(0,16):\n\tgranValle2.newPlanta([planta.Planta(5, 10, 5, 10)])\n\tgranValle2.newPlanta([planta.Planta(2, 40, 10, 40)])\n\tgranValle2.newPlanta([planta.Planta(3, 20, 15, 20)])\n\nfor i in range(0,25):\n\tgranValle3.newPlanta([planta.Planta(5, 10, 5, 10)])\n\tgranValle3.newPlanta([planta.Planta(2, 40, 10, 40)])\n\tgranValle3.newPlanta([planta.Planta(3, 20, 15, 20)])\n\nfor i in range(0,33):\n\tgranValle4.newPlanta([planta.Planta(5, 10, 5, 10)])\n\tgranValle4.newPlanta([planta.Planta(2, 40, 10, 40)])\n\tgranValle4.newPlanta([planta.Planta(3, 20, 15, 20)])\n\n#Crear conejos\noCuniculus = ae.ArbolEspecie() # Conejo\nfor tierra in territorios:\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 1, cromosoma2)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 1, cromosoma3)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 1, cromosoma1)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 1, cromosoma4)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 0, cromosoma1)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 0, cromosoma4)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 0, cromosoma2)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 0, cromosoma3)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 1, cromosoma2)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 1, cromosoma3)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 1, cromosoma1)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 1, cromosoma4)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 0, cromosoma1)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 0, cromosoma4)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 0, cromosoma2)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 0, cromosoma3)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 1, cromosoma2)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 1, cromosoma3)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 1, cromosoma1)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 1, cromosoma4)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 0, cromosoma1)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 0, cromosoma4)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 0, cromosoma2)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 0, cromosoma3)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 1, cromosoma2)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 1, cromosoma3)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 1, cromosoma1)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 1, cromosoma4)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 0, cromosoma1)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 0, cromosoma4)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 0, cromosoma2)])\n\tnodo = ae.Nodo(None,None,oCuniculus)\n\ttierra.newConejo([individuo.Conejo(nodo, oCuniculus, 16, 0, cromosoma3)])\n\n#Crear zorros\nCanisVulpini = ae.ArbolEspecie() # Zorro\nfor tierra in territorios:\n\tnodo = ae.Nodo(None,None,CanisVulpini)\n\ttierra.newZorro([individuo.Zorro(nodo, CanisVulpini, 16, 1, cromosoma5)])\n\tnodo = ae.Nodo(None,None,CanisVulpini)\n\ttierra.newZorro([individuo.Zorro(nodo, CanisVulpini, 16, 0, cromosoma5)])\n\t\n\n#Main\t\nfor dia in range(0,200):\n\tif not dia%10:\n\t\ttierra1.write(str(len(territorios[0].plantas))+\",\"+str(len(territorios[0].conejos))+\",\"+str(len(territorios[0].zorros))+\"\\n\")\n\t\ttierra2.write(str(len(territorios[1].plantas))+\",\"+str(len(territorios[1].conejos))+\",\"+str(len(territorios[1].zorros))+\"\\n\")\n\t\ttierra3.write(str(len(territorios[2].plantas))+\",\"+str(len(territorios[2].conejos))+\",\"+str(len(territorios[2].zorros))+\"\\n\")\n\t\ttierra4.write(str(len(territorios[3].plantas))+\",\"+str(len(territorios[3].conejos))+\",\"+str(len(territorios[3].zorros))+\"\\n\")\n\tviajes = []\n\tfor tierra in territorios:\t\n\t\tprint (\"Día \" + str(dia) + \" en \" + str(tierra))\n\t\torgia = []\n\t\tllorones = []\n\t\tvictimas = []\n\t\tturnos = []\n\t\tprint(\"######### DECLARAR #########\")\n\t\tdeclara = tierra.getDeclaraciones()\n\t\tfor theIndividuo in declara:\n\t\t\tprint (str(theIndividuo) + \" \" + str(theIndividuo.nodo.indice))\n\t\t\tprint(\"Energia \" + str(theIndividuo.energia) + \"/\" + str(theIndividuo.getCapacidadEnergia()))\n\t\t\tprint(\"Inventario \" + str(theIndividuo.inventario) + \"/\" + str(theIndividuo.getCapacidadCarga()))\n\t\t\tprint(\"Felicidad \" + str(theIndividuo.felicidad))\n\t\t\tdecision = theIndividuo.getDecision(tierra.getAcciones(theIndividuo, orgia, llorones, victimas), orgia, llorones, victimas) # Decision es una tupla\n\t\t\tturnos.append((theIndividuo, decision))\n\t\t\tprint (decision)\n\t\t\tprint (\"\\n\")\n\t\tprint(\"\\n######### ACTUAR #########\")\n\t\ttierra.getIniciativas(turnos)\n\t\tfor ii in turnos:\n\t\t\tii[0].actuar(ii[1], viajes)\n\t\tprint(\"\\n\\n\\n\")\n\tfor viaje in viajes:\n\t\tviaje[0].viajar(viaje[1],viaje[2])\n\tfor tierra in territorios:\n\t\ttierra.elMundoSeMueve()\ntierra1.close()\ntierra2.close()\ntierra3.close()\ntierra4.close()","sub_path":"watership_V0.1/EX_3.py","file_name":"EX_3.py","file_ext":"py","file_size_in_byte":8086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"466011199","text":"\n\"\"\"Schema and tranform definition for the Reddit dataset.\"\"\"\n\nimport tensorflow as tf\nimport tensorflow_transform as tft\nfrom tensorflow_transform import coders\nfrom tensorflow_transform.tf_metadata import dataset_schema\n\n\ndef make_standard_sql(table_name,\n mode=tf.contrib.learn.ModeKeys.TRAIN):\n \"\"\"Returns Standard SQL string to populate reddit features.\n This query takes ~60s, processing 13.3GB for reddit_comments.2015_12 table,\n and takes ~140s, processing 148GB for reddit_comments.2015_* table.\n Args:\n table_name: the table name to pull the data from.\n multiple tables can be chosen using *, like:\n fh-bigquery.reddit_comments.2015_*\n mode: if the mode is INFER, 'score' field is not populated.\n Returns:\n The standard SQL query to pull the features from the given reddit table.\n \"\"\"\n\n infer_mode = (mode == tf.contrib.learn.ModeKeys.INFER)\n return \"\"\"\nSELECT\n if(score>0,1,0) as score,\n COALESCE(subreddit, '') AS subreddit,\n id as example_id\nFROM\n `{table_name}`\nWHERE\n (score_hidden IS NULL OR score_hidden = false) \n AND\n SUBSTR(parent_id, 1, 2) = 't3' \n AND\n # limit to subs of interest\n subreddit in ('news','pics','ireland')\n \n# extra bit of shuffling when the limit condition is in place\nORDER BY RAND() \n\n# limit to a certain amount of records for developing on\nLIMIT 10000 \n\n\"\"\".format(table_name=table_name)\n\n\ndef make_csv_coder(schema, mode=tf.contrib.learn.ModeKeys.TRAIN):\n \"\"\"Produces a CsvCoder from a data schema.\n Args:\n schema: A tf.Transform `Schema` object.\n mode: tf.contrib.learn.ModeKeys specifying if the source is being used for\n train/eval or prediction.\n Returns:\n A tf.Transform CsvCoder.\n \"\"\"\n column_names += [\n 'score', 'subreddit', 'example_id'\n ]\n return coders.CsvCoder(column_names, schema)\n\n\ndef make_input_schema(mode=tf.contrib.learn.ModeKeys.TRAIN):\n \"\"\"Input schema definition.\n Args:\n mode: tf.contrib.learn.ModeKeys specifying if the schema is being used for\n train/eval or prediction.\n Returns:\n A `Schema` object.\n \"\"\"\n result = {\n 'score': tf.FixedLenFeature(shape=[], dtype=tf.int64),\n 'subreddit': tf.FixedLenFeature(shape=[], dtype=tf.string),\n 'example_id': tf.FixedLenFeature(shape=[], dtype=tf.string)\n }\n return dataset_schema.from_feature_spec(result)\n\n\ndef make_preprocessing_fn(frequency_threshold):\n \"\"\"Creates a preprocessing function for reddit.\n Args:\n frequency_threshold: The frequency_threshold used when generating\n vocabularies for categorical and text features.\n Returns:\n A preprocessing function.\n \"\"\"\n\n def preprocessing_fn(inputs):\n \"\"\"User defined preprocessing function for reddit columns.\n Args:\n inputs: dictionary of input `tensorflow_transform.Column`.\n Returns:\n A dictionary of `tensorflow_transform.Column` representing the transformed\n columns.\n \"\"\"\n # TODO(b/35001605) Make this \"passthrough\" more DRY.\n result = {'score': inputs['score'],\n 'example_id': inputs['example_id'],\n 'subreddit_id': tft.string_to_int(inputs['subreddit'], frequency_threshold=frequency_threshold) \n }\n\n return result\n\n return preprocessing_fn\n \n ","sub_path":"reddit_classifier_basic_tft0dot4_tf1dot4/make_bq_sql.py","file_name":"make_bq_sql.py","file_ext":"py","file_size_in_byte":3233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"139445405","text":"# unwanted words in subjects\r\nsubject_items = [\r\n 'URGENT', \r\n\t'SIGN',\r\n\t'UP',\r\n\t'RETAINER',\r\n\t'PICKUP',\r\n\t'NEW',\r\n\t'CASE',\r\n\t'CLIENT',\r\n\t'LEAD',\r\n\t':',\r\n\t'-',\r\n\t'RE',\r\n\t'FWD',\r\n\t'FW',\r\n\t'SIGN-UP'\r\n\r\n ]\r\n\r\n# unwanted keywords in phone number\r\nphone_items = [\r\n\t'(',\r\n\t')',\r\n\t'-'\r\n]\r\n\r\n# words to look for for signatures\r\nsign_items_pre = [\r\n\t'SIGNATURE',\r\n\t'SIGN',\r\n 'SIGNATURES',\r\n 'SIGNS'\r\n]\r\n\r\n# number of signatures possible\r\nsign_items_post = [\r\n\t'ONE',\r\n\t'TWO',\r\n\t'THREE',\r\n\t'FOUR',\r\n\t'FIVE',\r\n\t'SIX',\r\n\t'SEVEN',\r\n\t'EIGHT',\r\n\t'NINE',\r\n\t'TEN',\r\n\t'ELEVEN',\r\n\t'TWELVE',\r\n\t'1',\r\n\t'2',\r\n\t'3',\r\n\t'4',\r\n\t'5',\r\n\t'6',\r\n\t'7',\r\n\t'8',\r\n\t'9',\r\n\t'10',\r\n\t'11',\r\n\t'12'\r\n]\r\n","sub_path":"KS/MAIN APP_after/MAIN APP/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"78603510","text":"\n# -----------------------------------------------------------------------------------------\n # Created by Soufiane CHAMI # Network Disruptions \n# ---------------------------------------------------------------------------------------\n\n\n\nimport os \nimport pickle\nfrom contextlib import contextmanager\nimport pandas as pd \nimport numpy as np\nimport datetime\nimport gc\nimport time\n\n# Machine learning\n\nimport xgboost as xgb\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import log_loss\nfrom hyperopt import STATUS_OK, Trials, fmin, hp, tpe\nfrom scipy.stats import uniform as sp_rand\nfrom scipy.stats import randint as sp_randint\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n \n \n \n# ---------------------------------------------------------------\n# Preparation \n#----------------------------------------------------------------\n\nprint(os.getcwd()) # check current working directory for debug \n\n\n\n\n\n# --------------------\n# Useful functions \n# --------------------\n\n\n@contextmanager\n\n\ndef timer(title):\n t0 = time.time()\n yield\n print(\"{} - done in {:.0f}s\".format(title, time.time() - t0))\n \n\ndef one_hot_encoder(df, nan_as_category = True):\n original_columns = list(df.columns)\n categorical_columns = [col for col in df.columns if df[col].dtype == 'object']\n df = pd.get_dummies(df, columns= categorical_columns, dummy_na= nan_as_category)\n new_columns = [c for c in df.columns if c not in original_columns]\n return df #, new_columns\n\n\n\ndef get_resource_type(encode=False):\n resource_type= pd.read_csv( 'resource_type.csv', error_bad_lines=False, warn_bad_lines=False)\n resource_type.id=resource_type.id.astype(object)\n \n if(encode):\n resource_type['resource_type']= resource_type['resource_type'].str.replace('resource_type ','')\n cat_cols=['resource_type']\n non_cat_cols = [f for f in resource_type.columns.values if f not in cat_cols]\n resource_type.drop(columns=cat_cols)\n \n df = one_hot_encoder(resource_type[cat_cols])\n resource_type = pd.concat([resource_type[non_cat_cols],df], axis=1, sort=False)\n \n \n return resource_type\n\n\n\ndef get_severity_type(encode=False):\n\n severity_type=pd.read_csv( 'severity_type.csv', error_bad_lines=False, warn_bad_lines=False)\n severity_type.id=severity_type.id.astype(object)\n if(encode):\n severity_type['severity_type']= severity_type['severity_type'].str.replace('severity_type ','')\n\n cat_cols=['severity_type']\n non_cat_cols = [f for f in severity_type.columns.values if f not in cat_cols]\n\n df = one_hot_encoder(severity_type[cat_cols])\n severity_type = pd.concat([severity_type[non_cat_cols],df], axis=1, sort=False)\n\n return severity_type\n\n\n\ndef get_train(encode_Target=False):\n train = pd.read_csv('train.csv', error_bad_lines=False, warn_bad_lines=False)\n train.id=train.id.astype(object)\n# train.fault_severity=train.fault_severity.astype('int')\n train['location']= train['location'].str.replace('location ','')\n train.location=train.location.astype(int)\n train.columns.values[train.columns=='fault_severity']='Target_class'\n if(encode_Target):\n cat_cols=['Target_class']\n non_cat_cols = [f for f in train.columns.values if f not in cat_cols]\n train.drop(columns=cat_cols)\n df = one_hot_encoder(train[cat_cols])\n train = pd.concat([train[non_cat_cols],df], axis=1, sort=False)\n return train\n \n else: # means dont touch the fault_severity and location columns, Just return well formated train file\n return train\n \n \n\ndef get_test(encode=False):\n test = pd.read_csv('test.csv', error_bad_lines=False, warn_bad_lines=False)\n test.id=test.id.astype(object)\n test['location']= test['location'].str.replace('location ','')\n test.location=test.location.astype(int)\n test['Target_class'] = None\n return test\n\n\n\n\ndef get_event_type(encode =False):\n event_type= pd.read_csv('event_type.csv', error_bad_lines=False, warn_bad_lines=False)\n event_type.id=event_type.id.astype(object)\n \n if(encode):\n event_type['event_type']= event_type['event_type'].str.replace('event_type ','')\n\n cat_cols=['event_type']\n non_cat_cols = [f for f in event_type.columns.values if f not in cat_cols]\n\n df = one_hot_encoder(event_type[cat_cols])\n event_type = pd.concat([event_type[non_cat_cols],df], axis=1, sort=False)\n\n return event_type\n\n\n# ------------------------------------------------------\n# Data binning on the log_features cat features \n# ------------------------------------------------------\n\n\ndef get_log_feature(encode =False):\n log_feature = pd.read_csv('log_feature.csv', error_bad_lines=False, warn_bad_lines=False)\n log_feature.id=log_feature.id.astype(object)\n log_feature['log_feature']= log_feature['log_feature'].str.replace('feature ','')\n log_feature['log_feature']= log_feature['log_feature'].astype(int)\n \n log_feature.reset_index(inplace=True)\n log_feature.rename(columns={'index':'count_of_log_feature_seen'},inplace=True)\n log_feature_value_counts = log_feature.log_feature.value_counts().to_dict()\n log_feature['count_log_feature_per_ids'] = log_feature['log_feature'].map(lambda x: log_feature_value_counts[x])\n \n len_col=len(set(log_feature['count_log_feature_per_ids']))\n max_col=max(log_feature['count_log_feature_per_ids'] )\n bin_max = int(max_col/len_col)+1\n bins= [f*10 for f in range(-1, 41)]\n log_feature['binned_log_feature'] = np.digitize(log_feature['log_feature'], bins, right=True)\n \n bins_offset = list(map(lambda x:x+5, bins))\n log_feature['binned_offset_log_feature'] = np.digitize(log_feature['log_feature'], bins_offset, right=True)\n \n log_feature['position_of_log_feature'] = 1\n log_feature['position_of_log_feature'] = log_feature.groupby(['id'])['position_of_log_feature'].cumsum()\n log_feature['log_feature'] = log_feature['log_feature'].astype(int)\n\n return log_feature\n\n# same thing can be applied on the other tables ¯\\(ツ)/¯\n\n\n\n# -----------------------------------------------------------------------------\n# returns the training, validation and testing datasets\n# -----------------------------------------------------------------------------\n\n\n\ndef get_data(encode=False):\n event_type = get_event_type()\n resource_type = get_resource_type(encode=encode)\n severity_type = get_severity_type(encode=encode)\n log_feature = get_log_feature()\n train = get_train()\n test = get_test()\n temp_combined = pd.concat([train, test], axis=0,ignore_index=True)\n log_combined = pd.merge(temp_combined,log_feature,left_on = ['id'], right_on = ['id'],how='left')\n log_combined = pd.merge(log_combined,resource_type,left_on = ['id'], right_on = ['id'],how='left')\n log_combined = pd.merge(log_combined,severity_type,left_on = ['id'], right_on = ['id'],how='left')\n \n test = log_combined.loc[log_combined.Target_class.isin(list(set(log_combined.Target_class))[-1:])] # contain None\n train= log_combined.loc[log_combined.Target_class.isin(list(set(log_combined.Target_class))[:-1])] # not None \n train.Target_class= train.Target_class.astype('int')\n y_train= train['Target_class']\n\n\n # split data \n print(\"Spliting the train/val ..\")\n \n SEED = 1235\n VALID_SIZE = 0.30\n \n x_train= train.loc[:, ~train.columns.isin(['Target_class', 'id'])]\n \n print('Data shapes ...') # control shapes \n print(x_train.shape)\n print(y_train.shape)\n \n # split data into train and test sets\n X_train, X_val, y_train, y_val = train_test_split(x_train, y_train, test_size=VALID_SIZE, random_state=SEED)\n return X_train, X_val, y_train, y_val , test\n\n\n\n\n# -----------------------------------------------------------------------------\n# returns xgboost model with parameters as inputs \n# -----------------------------------------------------------------------------\n\n\n\ndef score(params):\n print(\"Training with params: \")\n print(params)\n num_round = int(params['n_estimators'])\n del params['n_estimators']\n X_train, X_val, y_train, y_val , test= get_data(encode=True)\n dtrain = xgb.DMatrix(X_train, label=y_train)\n dvalid = xgb.DMatrix(X_val, label=y_val)\n watchlist = [(dvalid, 'eval'), (dtrain, 'train')]\n gbm_model = xgb.train(params, dtrain, num_round,\n evals=watchlist,\n verbose_eval=True)\n predictions = gbm_model.predict(dvalid,\n ntree_limit=gbm_model.best_iteration + 1)\n loss = log_loss(y_val, predictions)\n # TODO: Add the importance for the selected features\n print(\"\\tScore {0}\\n\\n\".format(loss))\n # The score function should return the loss (1-score)\n # since the optimize function looks for the minimum\n \n return {'loss': loss, 'status': STATUS_OK}\n\n\n\n\n# -----------------------------------------------------------------------------\n# Sefl tuning: get the best model parameters within the search space \n# -----------------------------------------------------------------------------\n\n\ndef optimize(random_state=1235):\n \"\"\"\n Hyperparams tuning with Random Optimization \n \"\"\"\n \n space = { # space of params tuning \n 'n_estimators': hp.quniform('n_estimators', 100, 1000, 1),\n 'learning_rate': hp.choice('learning_rate', 0.001*np.arange(5, 100, dtype=int)),\n 'eta': hp.quniform('eta', 0.025, 0.5,0.025),\n 'max_depth': hp.choice('max_depth', np.arange(1, 14, dtype=int)),\n 'min_child_weight': hp.quniform('min_child_weight', 1, 20, 1),\n 'subsample': hp.quniform('subsample', 0.1, 1, 0.05),\n 'max_delta_step': hp.choice('max_delta_step', np.arange(0,5, dtype=int)),\n 'gamma': hp.choice('gamma', 0.1*np.arange(0,25, dtype=int)),\n 'colsample_bytree': hp.quniform('colsample_bytree', 0.1, 1, 0.05),\n 'eval_metric': 'mlogloss',\n 'objective': 'multi:softprob',\n 'booster': 'gbtree',\n 'tree_method':'gpu_hist', \n 'predictor':'gpu_predictor',\n 'silent': 1,\n 'num_class': 3,\n 'seed': 1235}\n \n \n # Use the fmin function from Hyperopt to find the best hyperparameters\n best = fmin(score, space, algo=tpe.suggest, max_evals=250)\n \n space.update(best)\n \n return space # return parameters only \n\n\n\n# ---------------------------------------------------------------------------------------------------------------------\n# train xgboost model with tuning parameters or with default ones (chosen by me after the first tuning iteration)\n# ---------------------------------------------------------------------------------------------------------------------\n\n\ndef train_single_classifier(params): # train \"optimal\" model after hyperparams tuning \n \n print(\"Training with params: \")\n print(params)\n num_round = int(params['n_estimators'])\n del params['n_estimators']\n X_train, X_val, y_train, y_val , test = get_data(INPUT_DIR)\n \n #convert to format to inject it to the xgboost\n \n dtrain = xgb.DMatrix(X_train, label=y_train)\n dvalid = xgb.DMatrix(X_val, label=y_val)\n watchlist = [(dvalid, 'eval'), (dtrain, 'train')]\n gbm_model = xgb.train(params, dtrain, num_round,\n evals=watchlist,\n verbose_eval=True)\n #predict \n predictions = gbm_model.predict(dvalid,\n ntree_limit=gbm_model.best_iteration + 1)\n \n #score \n \n score = log_loss(y_val, predictions)\n print(\"Model \\tScore {0}\\n\\n\".format(score))\n \n # save model \n today= datetime.datetime.now()\n model_file_name ='signle_xgboost_'+today.strftime('__%H:%M:%S_%d_%b_%Y_')+\"Score__\" +str(float(\"%0.4f\"%score))+'.pickle.dat'\n pickle.dump(gbm_model, open(model_file_name, \"wb\"))\n print(\"\\n\")\n print(\"Model is save in this directory : \" + os.getcwd())\n print(\"\\n\")\n print(\"Model file_name : \" + model_file_name)\n\n # make _sbumission \n \n \n # prepare test dataset\n \n x_test= test.loc[:, ~test.columns.isin(['Target_class', 'id'])]\n x_test =xgb.DMatrix(x_test)\n predictions_test = gbm_model.predict(x_test)\n cols= ['predict_0', 'predict_1', 'predict_2']\n predictions_test= pd.DataFrame(predictions_test, columns=cols)\n predictions_test['id']= test.id.values\n predictions_test= predictions_test.groupby(['id'], axis=0).mean().reset_index()\n \n \n # save submission \n print(\"\\n\")\n submission_file = 'submission'+today.strftime('__%H:%M:%S_%d_%b_%Y_')+'_score_'+str(float(\"%0.4f\"%score))+'.csv'\n predictions_test.to_csv(submission_file, index=False)\n print(\"submission is made in this directory : \" + os.getcwd() + \"\\n\")\n print(\"submission file_name : \" + submission_file+ \"\\n\")\n \n \n return None #gbm_model, os.getcwd()\n\n\n\n\n\n# -----------------------------------------------------------------------------\n# Run full model, with prams_tuning (True) or with defined params \n# -----------------------------------------------------------------------------\n\n\ndef main(self_tuning = False):\n X_train, X_val, y_train, y_val, test= get_data(True)\n if(self_tuning):\n with timer(\"XGboost: Paramters tuning with Random optimization\"):\n best_hyperparams = optimize(random_state=1235)\n print(\"The best hyperparameters are: \", \"\\n\")\n print(best_hyperparams)\n else: \n print(\"Run XGboost without hyper_params search\")\n\n with timer(\"train single Model and make test submission\"):\n \n try:\n best_hyperparams # will be defined if yo run params tuning ! \n except NameError:\n \n # I added those params as trial, I got them from one of the tuning iterations ietrations I had \n best_hyperparams= {'booster': 'gbtree',\n 'colsample_bytree': 0.95,\n 'eta': 0.225,\n 'gamma': 0.85,\n 'max_depth': 6,\n 'min_child_weight': 5.0,\n 'n_estimators': 112.0,\n 'subsample': 0.95,\n 'eval_metric': 'mlogloss',\n 'num_class': 3,\n 'objective': 'multi:softprob',\n 'seed': 1235,\n 'silent': 1}\n\n \n # train classifier with best_Hyperparamerters \n train_single_classifier(params= best_hyperparams)\n \n \n gc.collect()\n\n\nif __name__ == \"__main__\":\n INPUT_DIR='/path/to/directory/' # directory of the inputs data \n os.chdir(INPUT_DIR)\n with timer(\"Full model run\"):\n main(self_tuning= True)\n \n \n","sub_path":"train_classifier.py","file_name":"train_classifier.py","file_ext":"py","file_size_in_byte":14954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"324055910","text":"##########################\r\n# Space Defenders - Functions\r\n################################\r\nimport pygame as pg\r\nfrom pygame.locals import *\r\nimport random\r\nWIDTH = 600\r\n\r\nwindow = pg.display.set_mode()\r\nclass Objet(object):\r\n \"\"\" classe des objets en général, les autres classes en seront héritières. De plus ca sera la classe des astéroïdes \"\"\"\r\n def __init__(self,x,y,length,width,img,life=[]): # la var genre référence son type (allié,ennemi)\r\n self.x = x\r\n self.y = y\r\n self.length = length\r\n self.width = width\r\n self.img = img\r\n self.life = life\r\n def blit(self):\r\n for i in range(0,len(self.x)):\r\n window.blit(pg.image.load(self.img).convert_alpha(),(self.x[i],self.y[i]))\r\n def move(self):\r\n for i in range(0,len(self.x)): # Faudra refaire pour les bullet(types etc...)\r\n self.y[i] += 0.1\r\n def delete(self,x):\r\n self.y.remove(self.y[x])\r\n self.x.remove(self.x[x])\r\n self.life.remove(self.life[x])\r\n def add(self):\r\n self.x.append(random.randint(0,600-40))\r\n self.y.append(0-self.width)\r\n self.life.append(3)\r\n def manage(self):\r\n if len(self.x) > 0:\r\n adjust = 0\r\n for i in range(0,len(self.x)):\r\n if i < len(self.y):\r\n if self.y[i] + self.width < 0 or self.y[i] > WIDTH:\r\n self.delete(i)\r\n adjust += 1\r\n adjust = 0\r\n for i in range(0,len(self.x)):\r\n i -= adjust\r\n if self.life[i] <= 0:\r\n self.delete(i)\r\n adjust += 1\r\nclass Player(Objet):\r\n \"\"\" classe du joueur \"\"\"\r\n def __init__(self,x,y,length,width,img,life=3):\r\n super().__init__(x,y,length,width,img,life)\r\n def blit(self):\r\n window.blit(pg.image.load(self.img).convert_alpha(),(self.x,self.y))\r\n \r\n def move_left(self):\r\n mvt = 10\r\n self.x -= mvt\r\n def move_right(self):\r\n mvt = 10\r\n self.x += mvt\r\n def move_up(self):\r\n mvt = 10\r\n self.y -= mvt\r\n def move_down(self):\r\n mvt = 10\r\n self.y += mvt\r\n \r\nclass Ennemie(Objet):\r\n \"\"\" classe des ennemis \"\"\"\r\n def __init__ (self,x,y,length,width,img1,img2,life):\r\n super().__init__(x,y,length,width,img1,life)\r\n self.img = []\r\n self.img1 = img1\r\n self.img2 = img2\r\n def add(self):\r\n self.x.append(random.randint(0,600-40))\r\n self.y.append(0-self.width)\r\n self.life.append(1)\r\n if random.randint(0,1) == 0:\r\n self.img.append(self.img1)\r\n else:\r\n self.img.append(self.img2)\r\n def switch(self):\r\n image = self.img[0]\r\n self.img[0] = self.img[1]\r\n self.img[1] = image\r\n def blit(self):\r\n for i in range(0,len(self.x)):\r\n window.blit(pg.image.load(self.img[i]).convert_alpha(),(self.x[i],self.y[i]))\r\n def move(self):\r\n for i in range(0,len(self.x)): # Faudra refaire pour les bullet(types etc...)\r\n self.y[i] += 0.12\r\n\r\nclass Bullet(Objet):\r\n \"\"\" classe des tirs \"\"\"\r\n def __init__(self,x,y,length,width,img,img2,bullettype):\r\n super().__init__(x,y,length,width,img)\r\n self.bullettype = bullettype\r\n self.img2 = img2\r\n def move(self):\r\n for i in range(0,len(self.x)):\r\n if self.bullettype[i] == 0:\r\n self.y[i] -= 0.5\r\n elif self.bullettype[i] == 1:\r\n self.y[i] += 0.5\r\n def delete(self,x):\r\n self.y.remove(self.y[x])\r\n self.x.remove(self.x[x])\r\n self.bullettype.remove(self.bullettype[x])\r\n self.life.remove(self.life[x])\r\n def add(self,x,y,z):\r\n self.bullettype.append(z)\r\n if z == 0:\r\n self.x.append(x+25)\r\n self.y.append(y-20)\r\n elif z ==1:\r\n self.x.append(x+20)\r\n self.y.append(y+60)\r\n self.life.append(1)\r\n \r\n\r\n \r\n\r\n\r\n","sub_path":"func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":4037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"473606519","text":"\nimport unittest\n\n\ndef has_palindrome_permutation(string):\n\n # Check if any permutation of the input is a palindrome\n freq = {}\n\n for ch in string:\n if ch in freq:\n del freq[ch]\n else:\n freq[ch] = True\n\n return len(freq) <= 1\n","sub_path":"Week2/Day4/palindrome.py","file_name":"palindrome.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"51424825","text":"import openmc\n\nmats = openmc.Materials()\n\nmat = openmc.Material(1)\nmat.name = \"Tuballoy\"\nmat.set_density('sum')\nmat.add_nuclide('U234', 2.6428e-06)\nmat.add_nuclide('U235', 3.4597e-04)\nmat.add_nuclide('U238', 4.7702e-02)\nmats.append(mat)\n\nmat = openmc.Material(2)\nmat.name = \"Oralloy\"\nmat.set_density('sum')\nmat.add_nuclide('U234', 4.9175e-04)\nmat.add_nuclide('U235', 4.4851e-02)\nmat.add_nuclide('U238', 2.6306e-03)\nmats.append(mat)\n\nmat = openmc.Material(3)\nmat.name = \"2024 Aluminum\"\nmat.set_density('sum')\nmat.add_element('Mg', 1.0295e-03)\nmat.add_element('Al', 5.7868e-02)\nmat.add_element('Mn', 1.5182e-04)\nmat.add_element('Cu', 1.1550e-03)\nmats.append(mat)\n\nmat = openmc.Material(4)\nmat.name = \"Stainless Steel\"\nmat.set_density('sum')\nmat.add_element('Cr', 1.6532e-02)\nmat.add_element('Fe', 6.3278e-02)\nmat.add_element('Ni', 6.5095e-03)\nmats.append(mat)\n\nmats.export_to_xml()\n","sub_path":"icsbep/ieu-met-fast-001/openmc/case-4/generate_materials.py","file_name":"generate_materials.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"589822244","text":"from Users import Users\r\n\r\n#you are required to do exception handling\r\n\r\ndef processUser():\r\n usersList = []\r\n user_file = open('file/users.txt', 'r')\r\n for ulist in user_file:\r\n list = ulist.split(',')\r\n s = Users(list[0], list[1], int(list[2]))\r\n\r\n usersList.append(s)\r\n return usersList\r\n\r\ndef processTransaction(firstname, month, type):\r\n t_file = open('file/transaction.txt', 'r')\r\n total = 0\r\n for trans in t_file:\r\n list = trans.split(',')\r\n\r\n if list[0] == firstname and list[1] == month and list[2] == type:\r\n total += float(list[3])\r\n return total\r\n\r\ndef registerNewUser(firstname, lastname, age):\r\n userdata = firstname + ',' + lastname +',' + age +'\\n'\r\n user_file = open('file/users.txt', 'a')\r\n user_file.write(userdata)\r\n\r\n","sub_path":"ElDemo/MainProcess.py","file_name":"MainProcess.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"533084266","text":"'''Exercício Python 056: Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas.\nNo final do programa, mostre: a média de idade do grupo, qual é o nome do homem mais velho e quantas\nmulheres têm menos de 20 anos.'''\n\n\n\nmedia = 0\nmaior_idade = 0\nmedia_total = 0\nhomem = '' # é uma STRING que vai receber os nomes\nquant_mulher = 0\nprint('------{}-----')\nfor itens in range(1, 4+1):\n nome = input('\\033[1;31m'+'Digite o nome da {}ª Pessoa: '.format(itens).upper().strip()+'\\033[m')\n idade = int(input('\\033[1;32m'+'Digite a idade da {}ª Pessoa: '.format(itens).upper().strip()+'\\033[m'))\n sexo = input('\\033[1;33m'+'Digite o sexo da {}ª pessoa M ou F: '.format(itens).strip()+'\\033[m').upper()\n media += idade / 4\n# print(sexo)\n if itens == 1 and sexo == 'M':\n maior_idade = idade\n homem = nome\n if sexo == 'M' and idade > maior_idade:\n maior_idade = idade\n homem = nome\n if sexo == 'F' and idade < 20:\n quant_mulher += 1\n\n\n\n\n\nprint('A média de Idade é: {} Anos '.format(media))\nprint('O Nome do Homem mais velho é: {}, e tem {} Anos.'.format(homem, maior_idade))\nprint('A Quantidade de Mulher(S) abaixo de 20 anos é: {}'.format(quant_mulher))\n\n\n\n\n\n\n","sub_path":"Curso_em_video_mundo_2/Exercícios_mundo_2/Exercicio_56_aula_13_FOR_IDADE_SEXO_4_PESSOAS.py","file_name":"Exercicio_56_aula_13_FOR_IDADE_SEXO_4_PESSOAS.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"187286870","text":"\"\"\"Module to hold views associated with object management.\"\"\"\n\nfrom pitch.models import Section, TableAttribute, Area, TrackedObject\nfrom django.shortcuts import (loader, HttpResponse,\n HttpResponseRedirect, reverse)\nfrom django.core import serializers\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.contrib.auth.decorators import permission_required, login_required\nfrom pitch.pitch_supplemental import input_field\nimport ast\nfrom django.contrib.auth.models import User\n\n\n@login_required\ndef mgmt_view(request):\n \"\"\"Splash page to the management system.\"\"\"\n template = loader.get_template('pitch/mgmt.html')\n context = {}\n\n return HttpResponse(template.render(context, request))\n\n\n@login_required\ndef mgmt_areas(request):\n \"\"\"Management Page for areas.\"\"\"\n template = loader.get_template('pitch/mgmt_areas.html')\n user = request.user\n try:\n if request.GET['inactive'] == 'True':\n areas = Area.objects.filter(area_admins=user)\n inactive = 1\n else:\n areas = Area.objects.filter(active_status=True,area_admins=user)\n inactive = 0\n except:\n areas = Area.objects.filter(active_status=True,area_admins=user)\n inactive = 0\n\n context = {\n 'areas': areas,\n 'inactive': inactive,\n }\n\n return HttpResponse(template.render(context, request))\n\n\n@login_required\ndef edit_area(request, area_id):\n \"\"\"Page to edit an area.\"\"\"\n template = loader.get_template('pitch/edit_area.html')\n\n areas = Area.objects.filter(active_status=True)\n area = Area.objects.get(pk=area_id)\n users = User.objects.all()\n context = {\n 'areas': areas,\n 'area': area,\n 'users': users,\n }\n\n return HttpResponse(template.render(context, request))\n\n\n@login_required\ndef save_area(request, area_id):\n \"\"\"View to save the edited area.\"\"\"\n if area_id == '0':\n area = Area()\n else:\n area = Area.objects.get(pk=area_id)\n area.area_name = request.POST['area_name']\n try:\n area.active_status = request.POST['active_status']\n area.active_status = True\n except Exception as e:\n area.active_status = False\n userlist = request.POST.getlist('admin_select')\n area.save()\n area.area_admins.set([User.objects.get(pk=p) for p in userlist])\n if User.objects.get(username='admin') not in area.area_admins.all():\n area.area_admins.add(User.objects.get(username='admin'))\n area.save()\n\n return HttpResponseRedirect(reverse('pitch:mgmt_areas'))\n\n\n@login_required\ndef add_area(request):\n template = loader.get_template(\"pitch/add_area.html\")\n areas = Area.objects.filter(active_status=True)\n users = User.objects.all()\n context = {\n 'areas': areas,\n 'users': users,\n }\n\n return HttpResponse(template.render(context, request))\n\n\n@login_required\ndef delete_area(request,area_id):\n template = loader.get_template(\"pitch/delete_area.html\")\n areas = Area.objects.filter(active_status=True)\n area = Area.objects.get(pk=area_id)\n context = {\n 'areas': areas,\n 'area': area,\n }\n\n return HttpResponse(template.render(context, request))\n\n@login_required\ndef confirm_delete_area(request, area_id):\n area = Area.objects.get(pk=area_id)\n area.delete()\n\n return HttpResponseRedirect(reverse('pitch:mgmt_areas'))\n","sub_path":"Python/Web Development/mgmt_views/areas.py","file_name":"areas.py","file_ext":"py","file_size_in_byte":3398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"571055159","text":"import logging\nlogger = logging.getLogger(__name__)\nfrom apps.common.logger import extra, started, finished, incompleted\n\nfrom models import Suitescaseskeywords\n\n\ndef get_suitescaseskeywords(request, **kwargs):\n logger.info(started, **extra(kwargs))\n\n suitecase_id = request.GET.get('suitecase_id')\n\n suitescaseskeywords = Suitescaseskeywords.objects.Read(suitecase_id=suitecase_id, **kwargs)\n if suitescaseskeywords.get('code') != 200:\n logger.info(incompleted, **extra(kwargs))\n return suitescaseskeywords\n\n suitescaseskeywords_list_of_jsons = []\n suitescaseskeywords_objects = suitescaseskeywords.get('suitescaseskeywords_objects')\n for each in suitescaseskeywords_objects:\n suitescaseskeywords_list_of_jsons.append({'keywordsgroup_id': each.keywordsgroup_id,\n 'keyword_id': each.keyword_id})\n\n logger.info(finished, **extra(kwargs))\n return {'code': 200, 'suitescaseskeywords': suitescaseskeywords_list_of_jsons}\n","sub_path":"apps/tmt/suitescasesparameters/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"410333713","text":"__author__ = 'Yaacov'\n\nimport tkinter as tk\nimport tkinter.ttk as ttk\nimport attackframe, moveframe, castspellframe, performskillframe\nimport verbose as v\n\nverbose_msg=True\n\nclass ChooseActionNtbk(ttk.Notebook):\n def __init__(self, parent, combat, guy):\n ttk.Notebook.__init__(self,parent)\n self.parent = parent\n self.combat = combat\n self.combatant = guy\n self.attack_frame = None\n self.cast_spell_frame = None\n self.move_frame = None\n self.perform_skill_frame = None\n self.initialize()\n\n def initialize(self):\n self.attack_frame = attackframe.AttackFrame(self, self.combat, self.combatant)\n self.add( self.attack_frame, text=\"Attack\")\n self.cast_spell_frame = castspellframe.CastSpellFrame(self, self.combat, self.combatant)\n self.add(self.cast_spell_frame, text=\"Cast Spell\")\n self.move_frame = moveframe.MoveFrame(self, self.combat, self.combatant)\n self.add(self.move_frame, text=\"Move\")\n self.perform_skill_frame = performskillframe.PerformSkillFrame(self, self.combat, self.combatant)\n self.add(self.perform_skill_frame, text=\"Perform Skill\")\n\n self.select(self.attack_frame)","sub_path":"chooseactionsnotebook.py","file_name":"chooseactionsnotebook.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"346352158","text":"from enum import Enum\nimport numpy as np\n\nclass Color(Enum):\n WHITE = 1\n BLACK = 2\n GRAY = 3\n\nclass NodeEdge:\n\n def __init__(self, vertex, weight):\n self.vertex = vertex\n self.weight = weight\n\nclass NodeV:\n\n def __init__(self, vertex, color):\n self.vertex = vertex\n self.color = color\n self.AdjList = []\n self.distance = np.inf\n\nclass Graph:\n\n def __init__(self, filename):\n\n self.vertices = []\n self.n_vertices = 0\n\n #read edges for undirected graph\n def readEdges(string):\n for line in string:\n vertices_data = line.split()\n if (len(vertices_data) < 3):\n weight = 1\n else:\n weight = int(vertices_data[2])\n self.insertEdge(int(vertices_data[0])-1, int(vertices_data[1])-1, weight)\n self.insertEdge(int(vertices_data[1])-1, int(vertices_data[0])-1, weight)\n\n #read edges for directed graph\n def readArcs(string):\n for line in string:\n vertices_data = line.split()\n if (len(vertices_data) < 3):\n weight = 1\n else:\n weight = int(vertices_data[2])\n self.insertEdge(int(vertices_data[0])-1, int(vertices_data[1])-1, weight)\n\n with open(filename, \"r\") as file:\n string = file.readlines()\n\n #Reading number of vertices\n line = string[0].split()\n self.n_vertices = int(line[1])\n\n for i in range (self.n_vertices):\n n = NodeV(i, Color.WHITE)\n self.vertices.append(n)\n\n line = string[1]\n if(\"Edges\" in line):\n readEdges(string[2:])\n elif(\"Arcs\" in line):\n readArcs(string[2:])\n\n def __str__(self):\n string = \"\"\n\n for i in range(0, self.n_vertices):\n string = string + \"vertex:\"+str(i+1) + \"\\n\"\n for edge in self.vertices[i].AdjList:\n string = string + \" |-> \"+str(edge.vertex+1)+\" \"+str(edge.weight)\n string = string + \"\\n\"\n\n return string\n\n def isEmpty(self):\n if (len(self.vertices) == 0):\n return True\n return False\n\n\n #Checks whether vertex g_dest already has an edge with vertex g_src\n # If it doesn't, insert new edge between them\n def insertEdge(self, g_src, g_dest, weight):\n\n newEdge = NodeEdge(g_dest, weight) \n self.vertices[g_src].AdjList.append(newEdge)\n return\n\n #Searches in g_src edge between g_dest and removes it\n def removeEdge(self, g_src, g_dest):\n\n for edge in self.vertices[g_src].AdjList:\n if (edge.vertex == g_dest): \n self.vertices[g_src].AdjList.remove(edge)\n return\n return\n\n #Get the number of vertices adjacents to vertex v\n def getVertexDegree(self, v):\n return len(self.vertices[v].AdjList)\n \n #Checks whether graph is Eulerian \n def isEulerian(self):\n n_odd = 0\n\n for i in range(self.n_vertices):\n if (self.getVertexDegree(i)%2):\n n_odd += 1\n\n return True if (n_odd == 0) else False\n\n \"\"\"\n Depth First Search\n Counts the number of components and how many vertices there are in each of them\n \"\"\"\n def recursiveDFS(self, cur_index, S_Black, L_White):\n\n if (self.vertices[cur_index].color != Color.WHITE):\n return\n\n L_White.remove(cur_index)\n\n cur_vertex = self.vertices[cur_index]\n if(len(cur_vertex.AdjList) > 0):\n\n cur_vertex.color = Color.GRAY\n\n for node in cur_vertex.AdjList:\n self.recursiveDFS(node.vertex, S_Black, L_White)\n\n cur_vertex.color = Color.BLACK\n S_Black.append(cur_index)\n\n def DFS(self):\n \n L_White = []\n S_Black = []\n\n for i in range(0, self.n_vertices):\n self.vertices[i].color = Color.WHITE\n L_White.append(i)\n\n n_vertices_component = []\n\n while(len(L_White) > 0):\n root = L_White[0]\n self.recursiveDFS(root, S_Black, L_White)\n\n n_vertices_component.append(len(S_Black))\n\n \"\"\"\n Breadth First Search\n When element is found, it is returned\n \"\"\"\n def BFS (self, elem):\n L_White = []\n L_Black = []\n Q_Gray = []\n \n for i in range(1, self.n_vertices):\n self.vertices[i].color = Color.WHITE\n L_White.append(i)\n\n Q_Gray.append(0)\n self.vertices[0].color = Color.GRAY\n\n while(len(Q_Gray) != 0):\n q_index = Q_Gray.pop(0)\n adj_list = self.vertices[q_index].AdjList\n\n for node in adj_list:\n\n if(node.vertex == elem):\n print(\"Element found.\")\n return node\n\n if(self.vertices[node.vertex].color == Color.WHITE):\n self.vertices[node.vertex].color = Color.GRAY \n Q_Gray.append(node.vertex)\n L_White.remove(node.vertex)\n \n L_Black.append(q_index)\n self.vertices[q_index].color = Color.BLACK\n\n print(\"Element not found!\")\n return\n\n def printDist(self):\n for vertex in self.vertices:\n for edge in vertex.AdjList:\n print(edge.distance)\n\n \"\"\"\n Dijkstra Algorithm\n Search for the shortest path to each vertex\n \"\"\"\n def dijkstra(self, idx_start):\n\n L_White = []\n for i in range(0, self.n_vertices):\n self.vertices[i].color = Color.WHITE\n self.vertices[i].distance = np.inf\n L_White.append(self.vertices[i])\n\n #setting start for the idx_start \n cur_idx = idx_start\n self.vertices[cur_idx].distance = 0\n\n while(len(L_White) > 0):\n\n #sort L_White according to lowest distance\n L_White = sorted(L_White, key=lambda vertex: vertex.distance)\n cur_vertex = L_White[0]\n\n for node in cur_vertex.AdjList:\n node_vertex = self.vertices[node.vertex]\n cur_distance = cur_vertex.distance + node.weight\n\n if (node_vertex.color == Color.WHITE and cur_distance < node_vertex.distance):\n node_vertex.distance = cur_distance\n \n if (cur_vertex.color == Color.WHITE):\n L_White.remove(cur_vertex)\n cur_vertex.color = Color.BLACK\n\n #putting all final distances in an arraylist\n array_distance = []\n for vertex in self.vertices:\n array_distance.append(vertex.distance)\n\n return array_distance\n","sub_path":"Trabalhos/Trabalho04_Dijkstra/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":6802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"386754387","text":"#!/usr/bin/python\n\nfrom IPython.Shell import IPShellEmbed\n\nimport stackexchange\nimport shelve\nimport pygtk\npygtk.require('2.0')\nimport pynotify\nimport datetime\nimport os\n\nHOMEDIR=\"/home/pfarmer\"\nAPPDIR=\"%s/.so-notify/\" % HOMEDIR\nUSERID=66020\n\nif not os.path.exists(APPDIR):\n os.mkdir(APPDIR)\n\ndata = shelve.open(\"%s/data.shelf\" % APPDIR)\n\nsite = stackexchange.Site(\n \"api.stackoverflow.com\",\n app_key=\"TXgPj5rLtE2Ky-9nCuUVRQ\"\n)\n\ntags = [ \"git\", \"python\", \"bash\" ]\n\nthe_questions = {}\ncreation_date = []\nnotify_tags = []\n\nfor tag in tags:\n questions = site.questions(tagged=tag, sort=\"creation\", pagesize=5)\n key = \"last_id_%s\" % (tag)\n last_id = 0\n for q in questions:\n the_questions[q.id] = (q.title, q, tag)\n creation_date.append((q.json[\"creation_date\"], q.id))\n if q.id > last_id:\n last_id = q.id\n\n\n if data.has_key(key):\n if last_id > data[key]:\n notify_tags.append(tag)\n data[key] = last_id\n else:\n notify_tags.append(tag)\n data[key] = last_id\n\nuser = site.user(USERID)\nrep = user.reputation\n\nuser_key = \"%i-rep\" % USERID\nnotify_rep = 0\n\nif data.has_key(user_key):\n if rep > data[user_key]:\n notify_rep = rep\n data[user_key] = rep\nelse:\n notify_rep = rep\n data[user_key] = rep\n\ndata.close()\n\noutput = open(\"/home/pfarmer/.conky/stackoverflow.txt\", \"w\")\n\noutput.write(\"%s %s\\n\" % (\n str(\"Tag\").ljust(6),\n str(\"Title\").ljust(67)\n))\n\noutput.write(\"%s %s\\n\" % (\n str(\"-\").ljust(6, \"-\"),\n str(\"-\").ljust(67, \"-\")\n))\n\nfor q in sorted(creation_date, key=lambda date:(-date[0])):\n tag = the_questions[q[1]][2]\n title = the_questions[q[1]][0]\n title = title.encode('utf-8')\n title = title.decode('ascii','ignore')\n if len(title) > 67:\n title = str(title[:63]).ljust(67, \".\")\n output.write(\"%s %s\\n\" % (tag.ljust(6), title))\n\ndt = datetime.datetime.now()\nnow = dt.strftime(\"Last updated: %X\")\noutput.write(\"\\n%s - %s\\n\" % (now, site.rate_limit))\n\nif len(notify_tags):\n pynotify.init(\"SO-Notify\")\n message = \"New questions in:\\n\"\n for tag in notify_tags:\n message = message + \"\\t%s\\n\" % tag\n\n if notify_rep > 0:\n message = message + \"\\nRep: %i\\n\" % notify_rep\n # message = message + \"\\n%s\\n\" % str(site.rate_limit)\n\n n = pynotify.Notification(\"StackOverflow\", message)\n n.set_timeout(10000)\n n.show()\nelif notify_rep > 0:\n message = \"Rep: %i\" % notify_rep\n\n n = pynotify.Notification(\"StackOverflow\", message)\n n.set_timeout(10000)\n n.show()\n\n# IPShellEmbed([])()\n","sub_path":"so-notify.py","file_name":"so-notify.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"263614057","text":"#!/usr/bin/python\n\nimport logging\nfrom logging.handlers import RotatingFileHandler\nimport sys\nimport serial\nimport os\n\n# Number of files to keep and size in MB\nNumberOfFiles = 10\nFileSize = 5\n\n\n\nif not os.path.exists('Logs'):\n os.makedirs('Logs')\n\n\nlog_formatter = logging.Formatter('%(asctime)s.%(msecs)03d - %(message)s', datefmt=\"%d/%m/%Y %H:%M:%S\")\n\nlogFile = 'Logs/SerialLog_'+ sys.argv[1] + '.log'\n\nmy_handler = RotatingFileHandler(logFile, mode='a', maxBytes=FileSize*1024*1024, \n backupCount=NumberOfFiles, encoding=None, delay=0)\nmy_handler.setFormatter(log_formatter)\nmy_handler.setLevel(logging.INFO)\n\napp_log = logging.getLogger('root')\napp_log.setLevel(logging.INFO)\n\napp_log.addHandler(my_handler)\n\n#while True:\n# app_log.info(\"data\")\n\t\n\t\n\t\nwith serial.Serial(\"/dev/\"+sys.argv[1], sys.argv[2]) as ser:\n for line in ser:\n app_log.info(line.strip())\n","sub_path":"LogSerial.py","file_name":"LogSerial.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"296437610","text":"import numpy as np\nfrom numpy import zeros\nfrom numpy import dot\nfrom scipy.optimize import least_squares\n\nfrom prototype.utils.quaternion.jpl import C\n\n\nclass FeatureEstimator:\n \"\"\"Feature Estimator\n\n Attributes\n ----------\n max_iter : int\n Maximum iterations\n\n Parameters\n ----------\n max_iter : int\n Maximum iterations (default: 30)\n\n \"\"\"\n def triangulate(self, pt1, pt2, C_C0C1, t_C0_C0C1):\n \"\"\"Triangulate feature observed from camera C0 and C1 and return the\n position relative to camera C0\n\n Parameters\n ----------\n pt1 : np.array - 2x1\n Feature point 1 in pixel coordinates\n pt2 : np.array - 2x1\n Feature point 2 in pixel coordinates\n C_C0C1 : np.array - 3x3\n Rotation matrix from frame C1 to C0\n t_C0_C0C1 : np.array - 3x3\n Translation vector from frame C0 to C1 expressed in C0\n\n Returns\n -------\n p_C0_f : np.array - 3x1\n Returns feature point expressed in C0 in camera coordinates\n\n \"\"\"\n # Convert points to homogenous coordinates and normalize\n pt1 = np.block([[pt1], [1.0]])\n pt2 = np.block([[pt2], [1.0]])\n # pt1 = pt1 / np.linalg.norm(pt1)\n # pt2 = pt2 / np.linalg.norm(pt2)\n\n # Triangulate\n A = np.block([pt1, dot(-C_C0C1, pt2)])\n b = t_C0_C0C1\n result = np.linalg.lstsq(A, b)\n x, residual, rank, s = result\n p_C0_f = x[0] * pt1\n\n return p_C0_f, residual\n\n def initial_estimate(self, cam_model, track, track_cam_states):\n \"\"\"Initial feature estimate\n\n Parameters\n ----------\n cam_model : CameraModel\n Camera model\n track : FeatureTrack\n Feature track\n track_cam_states : list of CameraState\n Camera states where feature track was observed\n debug :\n Debug mode (default: False)\n\n Returns\n -------\n p_C0_f : np.array - 3x1\n Initial estimated feature position expressed in first camera frame\n\n \"\"\"\n # Calculate rotation and translation of first and last camera states\n # -- Get rotation and translation of camera 0 and camera 1\n C_C0G = C(track_cam_states[0].q_CG)\n C_C1G = C(track_cam_states[1].q_CG)\n p_G_C0 = track_cam_states[0].p_G\n p_G_C1 = track_cam_states[1].p_G\n # -- Calculate rotation and translation from camera 0 to camera 1\n C_C0C1 = dot(C_C0G, C_C1G.T)\n t_C1_C0C1 = dot(C_C0G, (p_G_C1 - p_G_C0))\n # -- Convert from pixel coordinates to image coordinates\n pt1 = cam_model.pixel2image(track.track[0].pt).reshape((2, 1))\n pt2 = cam_model.pixel2image(track.track[1].pt).reshape((2, 1))\n\n # Calculate initial estimate of 3D position\n p_C0_f, residual = self.triangulate(pt1, pt2, C_C0C1, t_C1_C0C1)\n\n return p_C0_f, residual\n\n def jacobian(self, x, *args):\n \"\"\"Jacobian\n\n Parameters\n ----------\n cam_model : CameraModel\n Camera model\n track : FeatureTrack\n Feature track\n track_cam_states : list of CameraState\n Camera states where feature track was observed\n\n Returns\n -------\n J : np.array\n Jacobian\n\n \"\"\"\n cam_model, track, track_cam_states = args\n\n N = len(track_cam_states)\n J = zeros((2 * N, 3))\n\n C_C0G = C(track_cam_states[0].q_CG)\n p_G_C0 = track_cam_states[0].p_G\n alpha, beta, rho = x.ravel()\n\n # Form the Jacobian\n for i in range(N):\n # Get camera current rotation and translation\n C_CiG = C(track_cam_states[i].q_CG)\n p_G_Ci = track_cam_states[i].p_G\n\n # Set camera 0 as origin, work out rotation and translation\n # of camera i relative to to camera 0\n C_CiC0 = dot(C_CiG, C_C0G.T)\n t_Ci_CiC0 = dot(C_CiG, (p_G_C0 - p_G_Ci))\n\n # Project estimated feature location to image plane\n h = dot(C_CiC0, np.array([[alpha], [beta], [1]])) + rho * t_Ci_CiC0 # noqa\n\n drdalpha = np.array([\n -C_CiC0[0, 0] / h[2, 0] + (h[0, 0] / h[2, 0]**2) * C_CiC0[2, 0], # noqa\n -C_CiC0[1, 0] / h[2, 0] + (h[1, 0] / h[2, 0]**2) * C_CiC0[2, 0] # noqa\n ])\n drdbeta = np.array([\n -C_CiC0[0, 1] / h[2, 0] + (h[0, 0] / h[2, 0]**2) * C_CiC0[2, 1], # noqa\n -C_CiC0[1, 1] / h[2, 0] + (h[1, 0] / h[2, 0]**2) * C_CiC0[2, 1] # noqa\n ])\n drdrho = np.array([\n -t_Ci_CiC0[0, 0] / h[2, 0] + (h[0, 0] / h[2, 0]**2) * t_Ci_CiC0[2, 0], # noqa\n -t_Ci_CiC0[1, 0] / h[2, 0] + (h[1, 0] / h[2, 0]**2) * t_Ci_CiC0[2, 0] # noqa\n ])\n J[2 * i:(2 * (i + 1)), 0] = drdalpha.ravel()\n J[2 * i:(2 * (i + 1)), 1] = drdbeta.ravel()\n J[2 * i:(2 * (i + 1)), 2] = drdrho.ravel()\n\n return J\n\n def reprojection_error(self, x, *args):\n \"\"\"Reprojection error\n\n Parameters\n ----------\n cam_model : CameraModel\n Camera model\n track : FeatureTrack\n Feature track\n track_cam_states : list of CameraState\n Camera states where feature track was observed\n\n Returns\n -------\n r : np.array\n Residual\n\n \"\"\"\n cam_model, track, track_cam_states = args\n\n # Calculate residuals\n N = len(track_cam_states)\n r = zeros((2 * N, 1))\n C_C0G = C(track_cam_states[0].q_CG)\n p_G_C0 = track_cam_states[0].p_G\n\n alpha, beta, rho = x.ravel()\n\n for i in range(N):\n # Get camera current rotation and translation\n C_CiG = C(track_cam_states[i].q_CG)\n p_G_Ci = track_cam_states[i].p_G\n\n # Set camera 0 as origin, work out rotation and translation\n # of camera i relative to to camera 0\n C_CiC0 = dot(C_CiG, C_C0G.T)\n t_Ci_CiC0 = dot(C_CiG, (p_G_C0 - p_G_Ci))\n\n # Project estimated feature location to image plane\n h = dot(C_CiC0, np.array([[alpha], [beta], [1]])) + rho * t_Ci_CiC0 # noqa\n\n # Calculate reprojection error\n # -- Convert measurment to image coordinates\n z = cam_model.pixel2image(track.track[i].pt).reshape((2, 1))\n # -- Convert feature location to normalized coordinates\n z_hat = np.array([[h[0, 0] / h[2, 0]], [h[1, 0] / h[2, 0]]])\n # -- Reprojcetion error\n r[2 * i:(2 * (i + 1))] = z - z_hat\n\n return r.ravel()\n\n def estimate(self, cam_model, track, track_cam_states, debug=False):\n \"\"\"Estimate feature 3D location by optimizing over inverse depth\n parameterization using Gauss Newton Optimization\n\n Parameters\n ----------\n cam_model : CameraModel\n Camera model\n track : FeatureTrack\n Feature track\n track_cam_states : list of CameraState\n Camera states where feature track was observed\n debug :\n Debug mode (default: False)\n\n Returns\n -------\n p_G_f : np.array - 3x1\n Estimated feature position in global frame\n\n \"\"\"\n # # Calculate initial estimate of 3D position\n p_C0_f, residual = self.initial_estimate(cam_model, track,\n track_cam_states)\n\n # Get ground truth\n if track.ground_truth is not None:\n return track.ground_truth\n\n # Convert ground truth expressed in global frame\n # to be expressed in camera 0\n # C_C0G = C(track_cam_states[0].q_CG)\n # p_G_C0 = track_cam_states[0].p_G\n # p_C0_f = dot(C_C0G, (p_G_f - p_G_C0))\n\n # print(\"true: \", p_C0_f.ravel())\n\n # Create inverse depth params (these are to be optimized)\n alpha = p_C0_f[0, 0] / p_C0_f[2, 0]\n beta = p_C0_f[1, 0] / p_C0_f[2, 0]\n rho = 1.0 / p_C0_f[2, 0]\n theta_k = np.array([alpha, beta, rho])\n\n # z = 1 / rho\n # X = np.array([[alpha], [beta], [1.0]])\n # C_C0G = C(track_cam_states[0].q_CG)\n # p_G_C0 = track_cam_states[0].p_G\n # init = z * dot(C_C0G.T, X) + p_G_C0\n\n # Optimize feature location\n args = (cam_model, track, track_cam_states)\n result = least_squares(self.reprojection_error,\n theta_k,\n args=args,\n jac=self.jacobian,\n verbose=1,\n method=\"lm\")\n\n # if result.cost > 1e-4:\n # return None\n\n # Calculate feature position in global frame\n alpha, beta, rho = result.x.ravel()\n z = 1 / rho\n X = np.array([[alpha], [beta], [1.0]])\n C_C0G = C(track_cam_states[0].q_CG)\n p_G_C0 = track_cam_states[0].p_G\n p_G_f = z * dot(C_C0G.T, X) + p_G_C0\n\n # print(\"ground truth: \", track.ground_truth.ravel())\n # print(\"cost: \", result.cost)\n # print(\"initial: \", init.ravel())\n # print(\"final: \", p_G_f.ravel())\n\n # p_C_f = dot(C_C0G, (p_G_f - p_G_C0))\n # if p_C_f[2, 0] < 2.0:\n # return None\n # if p_C_f[2, 0] > 200.0:\n # return None\n\n return p_G_f\n","sub_path":"prototype/msckf/feature_estimator.py","file_name":"feature_estimator.py","file_ext":"py","file_size_in_byte":9463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"260549997","text":"import pandas as pd\nimport json\nfrom pandas.io.json import json_normalize\n\ndef most_projects(df, group_column):\n \"\"\"\n This takes a dataframe and a column to group by.\n It returns a list of the tuples.\n The tuples contain top 10 most common value in that column and how many times they occur.\n \"\"\"\n\n df_group = df.groupby(group_column)\n df_count = [(k, v[group_column].count()) for k, v in df_group]\n df_count.sort(key = lambda x: x[1], reverse=True)\n return df_count[:10]\n\ndef get_cleaned_proj_names(projects_data):\n \"\"\"\n This takes the raw imported json data. It normalizes the mjtheme_namecode\n field, and then fills in blank name values based on the unique combination\n of code and name where name is not blank.\n This returns a pandas dataframe with all name-column blanks filled in.\n \"\"\"\n proj_themes = json_normalize(projects_data, 'mjtheme_namecode')\n proj_themes = proj_themes.set_index('code')\n unique_themes = proj_themes[proj_themes.name != ''].drop_duplicates()\n proj_themes = unique_themes.join(proj_themes, how = 'inner', rsuffix='_x')\n proj_themes = proj_themes['name'].reset_index()\n return proj_themes\n\n#set the filename and import the data\nfilename = 'data/world_bank_projects.json'\nwith open(filename) as json_file:\n projects_data = json.load(json_file)\n\n#create the two dataframes to go through most_projects()\nworld_bank_projects = pd.DataFrame(projects_data)\nproj_themes = get_cleaned_proj_names(projects_data)\n\n#get the top 10 countries and major project themes\nmost_countries = most_projects(world_bank_projects, 'countryname')\nmost_proj_theme = most_projects(proj_themes, 'name')\n\n#print results\nprint(most_countries)\nprint(most_proj_theme)\n","sub_path":"data_wrangling_json/data_wrangling_json.py","file_name":"data_wrangling_json.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"402461426","text":"import unittest\n\nfrom common import get_context\n\n\nclass TestCase(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.ctx = get_context()\n\n def test_buffer_repr(self):\n buf = self.ctx.buffer(reserve=1024)\n self.assertRegex(repr(buf), r'')\n\n def test_compute_shader_repr(self):\n if self.ctx.version_code < 430:\n self.skipTest('OpenGL 4.3 is not supported')\n\n compute_shader = self.ctx.compute_shader('''\n #version 430\n layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;\n void main() {\n }\n ''')\n\n self.assertRegex(repr(compute_shader), r'')\n\n def test_renderbuffer_and_framebuffer_repr(self):\n rbo = self.ctx.renderbuffer((16, 16))\n self.assertRegex(repr(rbo), r'')\n\n with self.subTest(rbo=rbo):\n fbo = self.ctx.framebuffer(rbo)\n self.assertRegex(repr(fbo), r'')\n\n def test_texture_repr(self):\n texture = self.ctx.texture((4, 4), 3)\n self.assertRegex(repr(texture), r'')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_repr.py","file_name":"test_repr.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"557951285","text":"\"\"\"\nhttp://www.topcoder.com\n\"\"\"\nclass Time:\n def solve(self, seconds):\n rest = seconds\n H = int(rest / 3600)\n rest -= (3600 * H)\n M = int(rest / 60)\n rest -= (60 * M)\n S = rest\n return \"%d:%d:%d\" % (H, M, S)\n\n def whatTime(self, seconds):\n return self.solve(seconds)\n\n\n\nprint(Time().solve(3661))","sub_path":"tpc/srm144_div2.py","file_name":"srm144_div2.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"42741566","text":"from django.conf.urls import url\nfrom humshaugh_table_tennis import views\n\napp_name = 'humshaugh_table_tennis'\n\nurlpatterns = [\n url('^$', views.home, name='home'),\n url('^club-nights/$', views.club_nights, name='club_nights'),\n url('^news/(?P\\d+)/$', views.news, name='news'),\n url('^contact-us/$', views.contact_us, name='contact_us'),\n url('^rules/$', views.rules, name='rules'),\n url('^rules-full/$', views.rules_full, name='rules_full'),\n url('^location/$', views.location, name='location'),\n## url('^login/$', views.login, name='login'),\n\n]\n","sub_path":"humshaugh_table_tennis_project/humshaugh_table_tennis/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"124051225","text":"from lib_algorithms import Queue\n\ndef hotPotato(namelist, num):\n simq = Queue()\n for name in namelist:\n simq.enqueue(name)\n\n while simq.size() > 1:\n for i in range(num):\n simq.enqueue(simq.dequeue())\n print(simq.dequeue())\n\n print(\"---\")\n return simq.dequeue()\n #return simq.items\n\nprint(hotPotato([\"Helen\", \"Bogdan\", \"Sergey\", \"Vitalik\", \"Tanya\", \"Marina\"],7))\n\n\n","sub_path":"Old/queue-HotPotato.py","file_name":"queue-HotPotato.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"617320677","text":"import apply_subject, utill\nimport random\nfrom basic_var import SPC, NOSD, NOB, NOSJ\n\nclass Student:\n def __init__(self, subject):\n self.subject = subject\n \n def __repr__(self):\n return '\\n'\n\n def return_sub(self):\n return self.subject\n\n def set_apply_order(self, nosd, nob, probality=10):\n rs = utill.set_remain_subject()\n count = 0\n while True:\n count += 1\n apply_list = apply_subject.apply([self], nosd, nob, time=30)[0]\n if len(apply_list) == 10: break\n sub_list, class_num, all_list, result = [], [], [], {}\n for block in apply_list.keys():\n sub_list.append(apply_list[block][0])\n class_num.append(apply_list[block][1])\n all_list.append([block, apply_list[block][0], apply_list[block][1]])\n\n research_list = [i for i in range(31, 37)]\n sub_in_research = [i for i in sub_list if i in research_list]\n\n if len(sub_in_research) == 1:\n sub_in_research = sub_in_research[0]\n research_index = sub_list.index(sub_in_research)\n result[sub_list[research_index]] = class_num[research_index]\n # result = {1번째 신청할 과목: 분반, 2번째 신청할 과목: 분반 ...}\n\n count_fixed_sub = len([i for i in range(9) if random.randint(1, probality) == 1])\n not_resear_list = [i for i in sub_list if i not in research_list]\n fixed_sub_list = random.sample(not_resear_list, count_fixed_sub)\n fixed_index = [sub_list.index(i) for i in fixed_sub_list]\n for i in fixed_index:\n result[sub_list[i]] = class_num[i]\n\n non_fixed_list = [i for i in sub_list if i not in fixed_sub_list and i not in research_list]\n random.shuffle(non_fixed_list)\n non_fixed_index = [sub_list.index(i) for i in non_fixed_list]\n for i in non_fixed_index:\n result[sub_list[i]] = class_num[i]\n\n if len(result) != 10:\n raise Exception('10개 과목 적용 실패')\n\n if sub_in_research:\n self.count_fixed = count_fixed_sub + 1\n else:\n self.count_fixed = count_fixed_sub\n\n self.ideal_subject = result\n\n def apply(self, nosd, nob):\n self.apply_result = apply_subject.apply([self], nosd, nob, time=30, fix=True)[0]\n\n def check_result(self):\n ideal_sub_list = [i for i in self.ideal_subject.keys()]\n apply_sub_list = [self.apply_result[i][0] for i in self.apply_result.keys()]\n\n same = 0\n for i in range(len(apply_sub_list)):\n same = i\n if ideal_sub_list[i] != apply_sub_list[i]: break\n\n if self.count_fixed > same:\n self.fix_same = same\n\n else:\n self.fix_same = self.count_fixed\n\n return self.count_fixed - self.fix_same\n\n\n\n\nif __name__ == \"__main__\":\n import pickle\n SPC = utill.SPC # student per class, 분반당 학생수, 현재는 21로 고정\n NOSD = utill.NOSD # Number Of StuDent, 총 학생수\n NOB = utill.NOB # Number Of Block, 블럭 개수\n NOSJ = utill.NOSJ # Number Of SubJect, 공강을 합친 과목 수\n remain_subject = utill.set_remain_subject()\n # remain_subject : 과목에 따른 남은 학생수, 한 딕셔너리 안에 하나의 과목, key는 분반, value는 [블럭, 남은 인원 수]\n\n with open('students.txt', 'rb') as f:\n students = pickle.load(f)\n for s in students:\n r = s.set_apply_order(NOSD, NOB)\n sum_ = 0\n for s in students:\n s.apply(NOSD,NOB)\n a = s.check_result()\n if a == 0: sum_ += 1\n print(sum_)\n\n\n #apply_subject.frm_print(10, 10, students, True)\n result = apply_subject.apply(students, NOSD, NOB, 30, True)\n print(result)\n\n\n\n\n","sub_path":"student_class.py","file_name":"student_class.py","file_ext":"py","file_size_in_byte":3820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"603307627","text":"print(\"Programa Policial\")\r\n\r\ncount = 0\r\ntentativas = \"\"\r\npergunta1 = str(input(\"Telefonou para a vítima? s or n: \"))\r\nwhile(pergunta1 == tentativas):\r\n pergunta1 = str(input(\"Telefonou para a vítima? s or n: \"))\r\n\r\npergunta2 = str(input(\"Esteve no local do crime? s or n: \"))\r\nwhile(pergunta2 == tentativas):\r\n pergunta2 = str(input(\"Esteve no local do crime? s or n: \"))\r\n\r\npergunta3 = str(input(\"Mora perto da vítima? s or n: \"))\r\nwhile(pergunta3 == tentativas):\r\n pergunta3 = str(input(\"Mora perto da vítima? s or n: \"))\r\n\r\npergunta4 = str(input(\"Devia para a vítima? s or n: \"))\r\nwhile(pergunta4 == tentativas):\r\n pergunta4 = str(input(\"Devia para a vítima? s or n: \"))\r\n\r\npergunta5 = str(input(\"Já trabalhou com a vítima? s or n: \"))\r\nwhile(pergunta5 == tentativas):\r\n pergunta5 = str(input(\"Já trabalhou com a vítima? s or n: \"))\r\n\r\n\r\nif(pergunta1 == \"s\"):\r\n count = count + 1\r\n\r\nif(pergunta2 == \"s\"):\r\n count = count + 1\r\n\r\nif(pergunta3 == \"s\"):\r\n count = count + 1\r\n\r\nif(pergunta4 == \"s\"):\r\n count = count + 1\r\n\r\nif(pergunta5 == \"s\"):\r\n count = count + 1\r\n\r\n\r\nif(count == 2 ):\r\n print(\"Suspeita\")\r\n\r\nif(count == 3 or count == 4):\r\n print(\"Cumplice\")\r\n\r\nif(count == 5):\r\n print(\"Assassino\")\r\n\r\nelse:\r\n if(count < 2):\r\n print(\"Inocente\")\r\n\r\n\r\n\r\n\r\n","sub_path":"Programa Policial.py","file_name":"Programa Policial.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"54595648","text":"def toLowerCase(str):\n dic = {'A':'a', 'B':'b', 'C':'c', 'D':'d', 'E':'e', 'F':'f',\n 'G':'g', 'H':'h', 'I':'i', 'J':'j', 'K':'k', 'L':'l',\n 'M':'m', 'N':'n', 'O':'o','P':'p', 'Q':'q', 'R':'r',\n 'S':'s', 'T':'t', 'U':'u', 'V':'v', 'W':'w', 'X':'x',\n 'Y':'y', 'Z':'z'}\n\n res = []\n for ch in str:\n if ch in dic:\n res.append(dic[ch])\n else:\n res.append(ch)\n return ''.join(res)\n\ndef numJewelsInStones(jewels,stones):\n hashMap = {}\n for c in stones:\n if hashMap.get(c) is not None:\n hashMap[c] +=1\n else:\n hashMap[c] =1\n res=0\n for c in jewels:\n if c in hashMap:\n res += hashMap[c]\n return res\n\ndef reverseOnlyLetters(S):\n stack = []\n res = []\n for c in S:\n if c.isalpha():\n stack.append(c)\n for c in S:\n if c.isalpha():\n res.append(stack.pop())\n else:\n res.append(c)\n return \"\".join(res)\n\ndef firstUniqChar(s):\n hashMap = {}\n for ch in s:\n if hashMap.get(ch) is not None:\n hashMap[ch] +=1\n else:\n hashMap[ch] = 1\n for i in range(len(s)):\n if hashMap.get(s[i]) == 1:\n return i\n return -1\n\ndef validPalindrome2(s):\n def isPalindrome(i,j):\n while i 0:\n date_next = list(blocks)[-1].date + timedelta(days=1)\n\n for block in blocks:\n sch = {}\n sch[\"block\"] = block\n try:\n sch[\"signup\"] = EighthSignup.objects.get(scheduled_activity__block=block, user=profile_user)\n except EighthSignup.DoesNotExist:\n sch[\"signup\"] = None\n eighth_schedule.append(sch)\n\n logger.debug(eighth_schedule)\n\n context = {\n \"profile_user\": profile_user,\n \"eighth_schedule\": eighth_schedule,\n \"date_previous\": date_fmt(date_previous),\n \"date_now\": date_fmt(date),\n \"date_next\": date_fmt(date_next),\n \"date\": date,\n \"date_end\": date_end,\n \"skipped_ahead\": skipped_ahead,\n \"custom_date_set\": custom_date_set\n }\n\n if profile_user.is_eighth_sponsor:\n sponsor = EighthSponsor.objects.get(user=profile_user)\n start_date = get_start_date(request)\n eighth_sponsor_schedule = (EighthScheduledActivity.objects.for_sponsor(sponsor)\n .filter(block__date__gte=start_date)\n .order_by(\"block__date\",\n \"block__block_letter\"))\n eighth_sponsor_schedule = eighth_sponsor_schedule[:10]\n\n logger.debug(\"Eighth sponsor {}\".format(sponsor))\n\n context[\"eighth_sponsor_schedule\"] = eighth_sponsor_schedule\n\n return context\n\n\n@login_required\ndef profile_view(request, user_id=None):\n context = get_profile_context(request, user_id)\n if context:\n return render(request, \"eighth/profile.html\", context)\n else:\n return render(request, \"error/403.html\", {\"reason\": \"You may only view your own schedule.\"}, status=403)\n\n\n@login_required\ndef profile_history_view(request, user_id=None):\n if user_id:\n try:\n profile_user = User.objects.get(id=user_id)\n except User.DoesNotExist:\n raise http.Http404\n else:\n profile_user = request.user\n\n if profile_user != request.user and not (request.user.is_eighth_admin or request.user.is_teacher):\n return render(request, \"error/403.html\", {\"reason\": \"You may only view your own schedule.\"}, status=403)\n\n blocks = EighthBlock.objects.get_blocks_this_year()\n blocks = blocks.filter(locked=True)\n blocks = blocks.order_by(\"date\", \"block_letter\")\n\n eighth_schedule = []\n\n for block in blocks:\n sch = {}\n sch[\"block\"] = block\n try:\n sch[\"signup\"] = EighthSignup.objects.get(scheduled_activity__block=block, user=profile_user)\n sch[\"highlighted\"] = (int(request.GET.get(\"activity\") or 0) == sch[\"signup\"].scheduled_activity.activity.id)\n except EighthSignup.DoesNotExist:\n sch[\"signup\"] = None\n eighth_schedule.append(sch)\n\n logger.debug(eighth_schedule)\n\n context = {\n \"profile_user\": profile_user,\n \"eighth_schedule\": eighth_schedule\n }\n\n return render(request, \"eighth/profile_history.html\", context)\n\n\n@login_required\ndef profile_often_view(request, user_id=None):\n if user_id:\n try:\n profile_user = User.objects.get(id=user_id)\n except User.DoesNotExist:\n raise http.Http404\n else:\n profile_user = request.user\n\n if profile_user != request.user and not (request.user.is_eighth_admin or request.user.is_teacher):\n return render(request, \"error/403.html\", {\"reason\": \"You may only view your own schedule.\"}, status=403)\n\n blocks = EighthBlock.objects.get_blocks_this_year()\n blocks = blocks.filter(locked=True)\n\n signups = EighthSignup.objects.filter(user=profile_user, scheduled_activity__block__in=blocks)\n activities = []\n for sch in signups:\n activities.append(sch.scheduled_activity.activity)\n\n oftens = []\n unique_activities = set(activities)\n for act in unique_activities:\n oftens.append({\n \"count\": activities.count(act),\n \"activity\": act\n })\n\n oftens = sorted(oftens, key=lambda x: (-1 * x[\"count\"]))\n\n logger.debug(oftens)\n\n context = {\n \"profile_user\": profile_user,\n \"oftens\": oftens\n }\n\n return render(request, \"eighth/profile_often.html\", context)\n\n\n@login_required\ndef profile_signup_view(request, user_id=None, block_id=None):\n if user_id:\n try:\n user = User.objects.get(id=user_id)\n except User.DoesNotExist:\n raise http.Http404\n else:\n user = request.user\n\n if user != request.user and not request.user.is_eighth_admin:\n return render(request, \"error/403.html\", {\"reason\": \"You may only modify your own schedule.\"}, status=403)\n\n if block_id is None:\n return redirect(request, \"eighth_profile\", user_id)\n\n try:\n block = (EighthBlock.objects\n .prefetch_related(\"eighthscheduledactivity_set\")\n .get(id=block_id))\n except EighthBlock.DoesNotExist:\n if EighthBlock.objects.count() == 0:\n # No blocks have been added yet\n return render(request, \"eighth/profile_signup.html\", {\"no_blocks\": True})\n else:\n # The provided block_id is invalid\n raise http.Http404\n\n serializer_context = {\n \"request\": request,\n \"user\": user\n }\n block_info = EighthBlockDetailSerializer(block, context=serializer_context).data\n activities_list = safe_json(block_info[\"activities\"])\n\n try:\n active_block_current_signup = EighthSignup.objects.get(user=user, scheduled_activity__block__id=block_id)\n active_block_current_signup = active_block_current_signup.scheduled_activity.activity.id\n except EighthSignup.DoesNotExist:\n active_block_current_signup = None\n\n context = {\n \"user\": user,\n \"real_user\": request.user,\n \"activities_list\": activities_list,\n \"active_block\": block,\n \"active_block_current_signup\": active_block_current_signup,\n \"show_eighth_profile_link\": True\n }\n profile_ctx = get_profile_context(request, user_id, block.date)\n if profile_ctx:\n context.update(profile_ctx)\n return render(request, \"eighth/profile_signup.html\", context)\n","sub_path":"intranet/apps/eighth/views/profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":10795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"548677358","text":"\"\"\" GCD_N \"\"\"\ndef gcd(num1, num2):\n \"\"\" find gcd of two numbers \"\"\"\n if num1 == 0:\n return num2\n elif num2 == 0:\n return num1\n else:\n return gcd(num2, num1%num2)\n\n\ndef gcd_n(num, first):\n \"\"\" find gcd of all numbers \"\"\"\n for _ in range(num-1):\n second = int(input())\n first = gcd(first, second)\n return first\n\n\nprint(gcd_n(int(input()), int(input())))\n","sub_path":"PSIT0161AM/W509_GCD_N.py","file_name":"W509_GCD_N.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"398003681","text":"import time\nimport pandas as pd\n\nfrom mlrose.algorithms.decorators import short_name\nfrom mlrose.gridsearch.grid_search_mixin import GridSearchMixin\n\nfrom mlrose.runners._runner_base import _RunnerBase\nfrom mlrose.neural import NNClassifier\n\n\"\"\"\nExample usage:\n from mlrose.runners import NNGSRunner\n\n grid_search_parameters = ({\n 'max_iters': [1, 2, 4, 8, 16, 32, 64, 128], # nn params\n 'learning_rate': [0.001, 0.002, 0.003], # nn params\n 'schedule': [ArithDecay(1), ArithDecay(100), ArithDecay(1000)] # sa params\n })\n\n nnr = NNGSRunner(x_train=x_train,\n y_train=y_train,\n x_test=x_test,\n y_test=y_test,\n experiment_name='nn_test',\n algorithm=mlrose.algorithms.sa.simulated_annealing,\n grid_search_parameters=grid_search_parameters,\n iteration_list=[1, 10, 50, 100, 250, 500, 1000, 2500, 5000, 10000],\n hidden_nodes_set=[[4, 4, 4]],\n activation_set=[mlrose.neural.activation.relu],\n bias=True,\n early_stopping=False,\n clip_max=1e+10,\n max_attempts=500,\n generate_curves=True,\n seed=200972)\n\n results = nnr.run() # GridSearchCV instance returned \n\"\"\"\n\n\n@short_name('nngs')\nclass NNGSRunner(_RunnerBase, GridSearchMixin):\n\n def __init__(self, x_train, y_train, x_test, y_test,\n experiment_name, seed, iteration_list,\n algorithm, grid_search_parameters,\n hidden_nodes_set, activation_set, learning_rates=None, cv=5,\n bias=True, early_stopping=False, clip_max=1e+10,\n max_attempts=500, generate_curves=True,\n output_directory=None):\n super().__init__(problem=None, experiment_name=experiment_name, seed=seed, iteration_list=iteration_list,\n generate_curves=generate_curves, output_directory=output_directory)\n\n self.hidden_nodes_set = hidden_nodes_set\n self.activation_set = activation_set\n self.learning_rates = learning_rates\n # self.bias = bias\n # self.early_stopping = early_stopping\n\n # algorithm grid-search params\n self.grid_search_parameters = grid_search_parameters\n\n # extract nn parameters\n self.parameters = {\n 'hidden_nodes': self.hidden_nodes_set,\n 'activation': self.activation_set,\n 'learning_rate': self.learning_rates\n }\n self.parameters.update(grid_search_parameters)\n self.classifier = NNClassifier(runner=self,\n algorithm=algorithm,\n max_attempts=max_attempts,\n clip_max=clip_max,\n early_stopping=early_stopping,\n bias=bias)\n\n # update short name based on algorithm\n print(self.dynamic_runner_name())\n self._set_dynamic_runner_name(f'nngs_{algorithm.__short_name__}')\n print(self.dynamic_runner_name())\n print(self.runner_name())\n\n self.x_train = x_train\n self.y_train = y_train\n self.x_test = x_test\n self.y_test = y_test\n self.cv = cv\n\n def run(self):\n self._setup()\n print(f'Running {self.dynamic_runner_name()}')\n\n run_start = time.perf_counter()\n sr = self._perform_grid_search(classifier=self.classifier,\n parameters=self.parameters,\n x_train=self.x_train,\n y_train=self.y_train,\n cv=self.cv)\n run_end = time.perf_counter()\n print(f'Run time: {run_end - run_start}')\n\n # pull the stats from the best estimator to here.\n # (as grid search will have cloned this object).\n self.__dict__.update(sr.best_estimator_.runner.__dict__)\n # dump the results to disk\n self._dump_pickle_to_disk(sr, 'grid_search_results')\n\n best = {\n 'best_params': sr.best_params_,\n 'best_score': sr.best_score_,\n 'best_estimator': sr.best_estimator_,\n 'best_loss': sr.best_estimator_.loss,\n 'best_fitted_weights': sr.best_estimator_.fitted_weights # ndarray\n }\n edf = {\n 'cv_results_df': pd.DataFrame(sr.cv_results_)\n }\n self._create_and_save_run_data_frames(extra_data_frames=edf)\n\n return sr\n\n def run_one_experiment_(self, algorithm, total_args, **params):\n if self._extra_args is not None and len(self._extra_args) > 0:\n params = {**params, **self._extra_args}\n\n total_args.update(params)\n total_args.pop('problem')\n user_info = [(k, v) for k, v in total_args.items()]\n\n return self._invoke_algorithm(algorithm=algorithm,\n curve=self.generate_curves,\n user_info=user_info,\n additional_algorithm_args=total_args,\n **params)\n\n","sub_path":"mlrose/runners/nngs_runner.py","file_name":"nngs_runner.py","file_ext":"py","file_size_in_byte":5363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"260870792","text":"import codecs\nimport os\n\nfrom setuptools import setup, find_packages\n\nwith codecs.open(\"README.md\", encoding=\"utf-8\") as f:\n README = f.read()\n\n\ndef get_version_file_path():\n github_actions_path = \"/home/runner/work/gitlabform/gitlabform\"\n if os.path.isfile(github_actions_path + \"/version\"):\n return github_actions_path + \"/version\"\n else:\n return \"version\"\n\n\nsetup(\n name=\"gitlabform\",\n version=open(get_version_file_path()).read(),\n description='Specialized \"configuration as a code\" tool for GitLab projects, groups and more'\n \" using hierarchical configuration written in YAML\",\n long_description=README,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/egnyte/gitlabform\",\n author=\"Egnyte and GitHub Contributors\",\n keywords=[\"gitlab\", \"configuration-as-code\"],\n classifiers=[\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Programming Language :: Python :: 3.10\",\n \"Development Status :: 5 - Production/Stable\",\n \"Intended Audience :: Information Technology\",\n \"Intended Audience :: System Administrators\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: POSIX :: Linux\",\n \"Operating System :: MacOS\",\n \"Operating System :: Microsoft :: Windows\",\n \"Topic :: Software Development :: Version Control :: Git\",\n ],\n packages=find_packages(),\n install_requires=[\n \"certifi\", # we want the latest root certs for security\n \"requests==2.26.0\",\n \"Jinja2==2.11.3\",\n \"MarkupSafe==1.1.1\",\n \"PyYAML==5.4.1\",\n \"luddite==1.0.2\",\n \"cli-ui==0.15.1\",\n \"packaging==21.0\",\n \"mergedeep==1.3.4\",\n ],\n extras_require={\n \"test\": [\n \"pytest==6.2.4\",\n \"xkcdpass==1.19.2\",\n \"pre-commit==2.14.1\", # not really for tests, but for development\n \"coverage==5.5\",\n \"pytest-cov==2.12.1\",\n ],\n },\n entry_points={\n \"console_scripts\": [\n \"gitlabform=gitlabform.run:run\",\n ],\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"534004849","text":"import _collections_abc\n# import sys as _sys\n\n# from itertools import chain as _chain\n# from itertools import repeat as _repeat\n# from itertools import starmap as _starmap\n# from keyword import iskeyword as _iskeyword\n# from operator import eq as _eq\n# from operator import itemgetter as _itemgetter\n# from reprlib import recursive_repr as _recursive_repr\n# from _weakref import proxy as _proxy\n\n# try:\n# from _collections import deque\n# except ImportError:\n# pass\n# else:\n# _collections_abc.MutableSequence.register(deque)\n\n# try:\n# from _collections import defaultdict\n# except ImportError:\n# pass\n\nclass STUserDict(_collections_abc.MutableMapping):\n\n # Start by filling-out the abstract methods\n def __init__(*args, **kwargs):\n if not args:\n raise TypeError(\"descriptor '__init__' of 'STUserDict' object \"\n \"needs an argument\")\n self, *args = args\n if len(args) > 1:\n raise TypeError('expected at most 1 arguments, got %d' % len(args))\n if args:\n dict = args[0]\n elif 'dict' in kwargs:\n dict = kwargs.pop('dict')\n import warnings\n warnings.warn(\"Passing 'dict' as keyword argument is deprecated\",\n DeprecationWarning, stacklevel=2)\n else:\n dict = None\n self._data = {}\n if dict is not None:\n self.update(dict)\n if kwargs:\n self.update(kwargs)\n __init__.__text_signature__ = '($self, dict=None, /, **kwargs)'\n\n def __len__(self): return len(self._data)\n def __getitem__(self, key):\n if key in self._data:\n return self._data[key]\n if hasattr(self.__class__, \"__missing__\"):\n return self.__class__.__missing__(self, key)\n raise KeyError(key)\n def __setitem__(self, key, item): self._data[key] = item\n def __delitem__(self, key): del self._data[key]\n def __iter__(self):\n return iter(self._data)\n\n # Modify __contains__ to work correctly when __missing__ is present\n def __contains__(self, key):\n return key in self._data\n\n # Now, add the methods in dicts but not in MutableMapping\n def __repr__(self): return repr(self._data)\n def __copy__(self):\n inst = self.__class__.__new__(self.__class__)\n inst.__dict__.update(self.__dict__)\n # Create a copy and avoid triggering descriptors\n inst.__dict__[\"_data\"] = self.__dict__[\"_data\"].copy()\n return inst\n\n def copy(self):\n if self.__class__ is STUserDict:\n return STUserDict(self._data.copy())\n import copy\n data = self._data\n try:\n self._data = {}\n c = copy.copy(self)\n finally:\n self._data = data\n c.update(self)\n return c\n\n @classmethod\n def fromkeys(cls, iterable, value=None):\n d = cls()\n for key in iterable:\n d[key] = value\n return d\n","sub_path":"src/roman_datamodels/stuserdict.py","file_name":"stuserdict.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"542532168","text":"import calendar\nimport pytz\nimport decimal\nfrom django.shortcuts import render, redirect\nfrom django.views.generic import TemplateView\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom .forms import RequestForm, AddProjectForm, AssignEmployeeForm\nfrom .models import Requests\nfrom accounts.models import Account, Payroll\nfrom projects.models import WorkDiary, Project, ProjectAssignment\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.http import HttpResponse\nfrom django.core.mail import EmailMessage\nfrom django.template.defaultfilters import slugify\nfrom accounts.models import Account, Payroll\nfrom projects.models import WorkDiary, Project, ProjectAssignment\nfrom datetime import datetime, timedelta\nfrom threading import Timer\nfrom .forms import RequestForm, AddProjectForm, AssignEmployeeForm\nfrom .models import Requests\nfrom .pdf import CreatePdf\nfrom .utils import DateUtils, ProjectsUtils\n\n# Create your views here.\n\n\nclass RequestView(TemplateView):\n template_name = 'management/request.html'\n\n def get(self, request, *args, **kwargs):\n form = RequestForm(initial={'employee': request.user.id})\n requests_by_user = Requests.objects.filter(\n employee=request.user.id).order_by('-date_requested')\n return_data = {'form': form, 'requests_by_user': requests_by_user}\n return render(request, self.template_name, return_data)\n\n def post(self, request, *args, **kwargs):\n form = RequestForm(request.POST)\n if form.is_valid():\n form.save()\n form = RequestForm()\n requests_by_user = Requests.objects.filter(\n employee=request.user.id)\n return redirect('request')\n\n\nclass UpdateRequest(TemplateView):\n\n def post(self, request, *args, **kwargs):\n id = request.POST['id']\n status = request.POST['status']\n confirmed = status or None\n Requests.objects.filter(id=id).update(confirmed=confirmed)\n # subject = 'Request for leave confirmation'\n # messages = 'Your request for leave with subject '+request.POST['subject']+' and content '+request.POST['content']+' was confirmed'\n # from_email = settings.EMAIL_HOST_USER\n return redirect('view_all_requests')\n\n\nclass AdminView(TemplateView):\n template_name = 'management/workdiaries.html'\n\n def get(self, request, *args, **kwargs):\n projects = Project.objects.all()\n day_diff = int(kwargs['day'])\n date_today = datetime.now() - timedelta(days=day_diff)\n previous_day = day_diff + 1\n if day_diff is 0:\n next_day = 0\n else:\n next_day = day_diff - 1\n '''\n Add __date to the datefield to use only the date of the datetime object in the query\n '''\n work_diaries = WorkDiary.objects.filter(\n date__date=date_today).order_by('-date')\n return_data = {'projects': projects, 'work_diaries': work_diaries,\n 'date_now': date_today, 'previous_day': previous_day, 'next_day': next_day}\n return render(request, self.template_name, return_data)\n\n def post(self, request, *args, **kwargs):\n day_diff = int(kwargs['day'])\n previous_day = day_diff + 1\n if day_diff is 0:\n next_day = 0\n else:\n next_day = day_diff - 1\n the_date = request.POST.get('getDiariesByDate')\n the_date = datetime.strptime(the_date, '%m/%d/%Y')\n work_diaries = WorkDiary.objects.filter(date__date=the_date)\n return_data = {'work_diaries': work_diaries, 'previous_day': previous_day,\n 'next_day': next_day, 'date_now': the_date, 'return_today': True}\n return render(request, self.template_name, return_data)\n\n\nclass ConfirmAccountView(TemplateView):\n\n def post(self, request, *args, **kwargs):\n if request.POST.get('confirm') is not None:\n employee = request.POST['id']\n Account.objects.filter(id=employee).update(is_active=True)\n return redirect('all_employees')\n if request.POST.get('decline') is not None:\n employee = request.POST['id']\n account = Account.objects.get(id=employee)\n account.delete()\n return redirect('all_employees')\n\n\nclass DeactivateAccountView(TemplateView):\n\n def post(self, request, *args, **kwargs):\n employee = request.POST['id']\n Account.objects.filter(id=employee).update(is_active=False)\n return redirect('admin', day=0)\n\n\nclass AllEmployeesView(TemplateView):\n template_name = 'management/employees.html'\n\n def get(self, request, *args, **kwargs):\n all_employees = Account.objects.filter(is_active=True)\n projects = Project.objects.all()\n accounts_to_confirm = Account.objects.filter(is_active=False)\n return_data = {'all_employees': all_employees,\n 'accounts_to_confirm': accounts_to_confirm, 'projects': projects}\n return render(request, self.template_name, return_data)\n\n\nclass EmployeeProfileView(TemplateView):\n template_name = 'management/employee-profile.html'\n\n def get(self, request, *args, **kwargs):\n employee_id = kwargs['id']\n employee = Account.objects.get(id=employee_id)\n projects = Project.objects.all()\n return_data = {'employee': employee, 'projects': projects}\n return render(request, self.template_name, return_data)\n\n\nclass ViewRequestsView(TemplateView):\n template_name = 'management/all-requests.html'\n\n def get(self, request, *args, **kwargs):\n all_requests = Requests.objects.all()\n projects = Project.objects.all()\n return_data = {'all_requests': all_requests, 'projects': projects}\n return render(request, self.template_name, return_data)\n\n\nclass ProjectManageView(TemplateView):\n\n template_name = 'management/project.html'\n\n def get(self, request, *args, **kwargs):\n\n project = Project.objects.get(id=kwargs.get('id'))\n assignment = ProjectAssignment.objects.filter(project=project)\n works = WorkDiary.objects.filter(project_assignment=assignment).order_by('-date')\n page = self.request.GET.get('page', 1)\n paginator = Paginator(works, 5)\n try:\n works = paginator.page(page)\n except PageNotAnInteger:\n works = paginator.page(1)\n except EmptyPage:\n works = paginator.page(paginator.num_pages)\n ctx_data = {\n 'works': works,\n 'project': project,\n }\n return render(request, self.template_name, ctx_data)\n\n\nclass ViewReportsByEmployee(TemplateView):\n\n template_name = 'management/reports_by_employee.html'\n\n def get(self, request, *args, **kwargs):\n\n emp_id = kwargs['emp_id']\n emp = Account.objects.get(id=emp_id)\n project_assignments = ProjectAssignment.objects.filter(employee=emp_id)\n page = self.request.GET.get('page', 1)\n paginator = Paginator(project_assignments, 5)\n try:\n project_assignments = paginator.page(page)\n except PageNotAnInteger:\n project_assignments = paginator.page(1)\n except EmptyPage:\n project_assignments = paginator.page(paginator.num_pages)\n projects = []\n for project in project_assignments:\n projects.append(project.id)\n reports = WorkDiary.objects.filter(project_assignment__in=projects).order_by('-date')\n return_data = {'reports': reports, 'employee': emp,\n 'project_assignments': project_assignments, }\n return render(request, self.template_name, return_data)\n\n\nclass ManagementPayrollView(TemplateView):\n template_name = 'management/payroll.html'\n\n def get(self, request, *args, **kwargs):\n '''\n 1. Create payroll record\n '''\n date_now = datetime.now(pytz.utc)\n du = DateUtils()\n date_sep = du.get_year_month_day(date_now)\n d, m, y = date_sep['get_day'], date_sep['get_month'], date_sep['get_year']\n last_day = calendar.monthrange(y, m)[1]\n employees = Account.objects.all().exclude(is_staff=True)\n if d is 15 or d is last_day:\n has_date = Payroll.objects.filter(date__date=date_now.date()).exists()\n if has_date is True:\n pass\n else:\n for emp in employees:\n '''\n 2. Get total hours of employee for the period and generate the invoice\n '''\n pu = ProjectsUtils()\n projects = pu.get_employee_projects_assignments(emp.id)\n date_from = du.get_start_date(date_now)\n diaries = WorkDiary.objects.filter(\n project_assignment__in=projects, date__date__gte=date_from, date__date__lte=date_now)\n total_hours = decimal.Decimal(0.00)\n for d in diaries:\n total_hours = total_hours + decimal.Decimal(d.hours)\n '''\n 3. Get payroll record and generate the invoice\n '''\n AMOUNT_BEFORE_DEDUCTIONS = total_hours * emp.hourly_rate\n PAYROLL_DESCRIPTION = 'Salary for the month'\n # Prepare requirements for pdf creation\n data = {'fname': emp.first_name, 'lname': emp.last_name, 'amount': AMOUNT_BEFORE_DEDUCTIONS,\n 'description': PAYROLL_DESCRIPTION, 'period': date_now.date(), 'total_hours': total_hours}\n template = 'management/payroll-report.html'\n file_path = 'payroll/' + \\\n slugify(emp.first_name + '_' + emp.last_name +\n '_' + str(date_now.date())) + '.pdf'\n style = 'h3 {font-size: 18px; font-weight: bold; text-align: center}' + \\\n 'h4 {font-size: 16px; font-weight: bold}'\n cp = CreatePdf()\n payroll_report = cp.generate_pdf(data, template, file_path, style)\n '''\n Save payroll record\n '''\n p = Payroll(\n date=date_now,\n employee=emp,\n amount_before_deductions=AMOUNT_BEFORE_DEDUCTIONS,\n description=PAYROLL_DESCRIPTION,\n paid=False,\n invoice_file=file_path\n )\n p.save()\n '''\n Now return the payroll records\n '''\n payrolls = Payroll.objects.all()\n return_data = {'payrolls': payrolls}\n return render(request, self.template_name, return_data)\n\n def post(self, request, *args, **kwargs):\n pay_id = request.POST['id']\n status = request.POST['status']\n invoice_file = request.POST['invoice_file']\n paid = status\n Payroll.objects.filter(id=pay_id).update(paid=paid, date_paid=datetime.now(pytz.utc))\n '''\n Send an email to the employee after confirming the payroll\n '''\n message = EmailMessage(\n 'Payroll confirmation',\n 'Hi! Your payroll is successfully confirmed! You may view or download it from the attachment. Thank you.',\n 'gergimarjohnalinsangao@gmail.com',\n ['fantanhoj_ramiger@ymail.com']\n )\n message.attach_file('media/' + invoice_file)\n message.send()\n return redirect('management_payroll')\n\n\nclass AddProjectView(TemplateView):\n\n form_class = AddProjectForm\n template_name = 'management/project-add.html'\n\n def get(self, request, *args, **kwargs):\n form = self.form_class(initial={'user': request.user.id})\n ctx_data = {\n 'form': form,\n }\n return render(request, self.template_name, ctx_data)\n\n def post(self, request, *args, **kwargs):\n form = self.form_class(request.POST)\n if form.is_valid():\n p = form.save()\n return redirect('view_projects', id=p.id)\n ctx_data = {\n 'form': form,\n 'error': 'Can\\'t add project',\n }\n return render(request, self.template_name, ctx_data)\n\n\nclass AssignEmployeeView(TemplateView):\n\n form_class = AssignEmployeeForm\n template = 'management/project-assign-employee.html'\n\n def get(self, request, *args, **kwargs):\n proj_id = kwargs['id']\n form = self.form_class(initial={'project': proj_id})\n ctx_data = {\n 'form': form,\n 'proj_id': proj_id,\n }\n return render(request, 'management/project-assign-employee.html', ctx_data)\n\n def post(self, request, *args, **kwargs):\n form = self.form_class(request.POST)\n if form.is_valid():\n employee = request.POST.get('employee')\n project = request.POST.get('project')\n assigned = ProjectAssignment.objects.filter(\n employee=employee, project=project).exists()\n if assigned is True:\n error = 'Employee is already assigned to this project.'\n else:\n p_id = form.save()\n return redirect('view_projects', id=p_id.id)\n ctx_data = {\n 'form': form,\n 'error': error,\n }\n return render(request, 'management/project-assign-employee.html', ctx_data)\n","sub_path":"management/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"338039168","text":"import copy\nimport inspect\n\nfrom pecan import util as p_u\nimport six\n\n\n_hierarchy = {}\n\n\ndef add_path(c):\n '''adds a named controller to the hierarchy.'''\n if _hierarchy.get(c.__swag['name']):\n raise Exception('name {} already exists in hierarchy'.format(c.__swag['name']))\n _hierarchy[c.__swag['name']] = c\n\n\ndef build_path(swaginfo):\n '''return the route path for a swag metadata item.'''\n if swaginfo.get('parent') is not None:\n return path_join(build_path(get_swag(swaginfo.get('parent'))),\n swaginfo.get('endpoint'))\n return swaginfo.get('endpoint')\n\n\ndef get_controller_paths(controllers):\n '''get a list of paths with methods\n\n returns a list of tuples (controller path, methods).\n\n '''\n def get_methods_for_generic(name):\n methods = []\n generic_handlers = lc.get(name).get('generic_handlers', {})\n for method, func in generic_handlers.items():\n if method == 'DEFAULT':\n methods.append('GET')\n else:\n methods.append(method)\n # TODO drill down through decorators to get true function name\n truename = getrealname(func)\n del lc[truename]\n return methods\n\n lc = copy.deepcopy(controllers)\n paths = []\n # TODO incorporate method decorator, removing functions marked\n if lc.get('index'):\n paths.append(('', get_methods_for_generic('index')))\n if lc.get('_default'):\n paths.append(('', ['*']))\n del lc['_default']\n if lc.get('_route'):\n paths.append(('', ['*']))\n del lc['_route']\n if lc.get('_lookup'):\n del lc['_lookup']\n generic_controllers = [c for c in lc if lc[c].get('generic')]\n for controller in generic_controllers:\n paths.append((controller, get_methods_for_generic(controller)))\n for controller in lc:\n paths.append((controller, ['GET']))\n return paths\n\n\ndef get_controllers(name):\n '''get all the controllers associated with a path\n\n returns a dictionary of controllers indexed by their names.\n\n '''\n c = _hierarchy[name]\n return {k: p_u._cfg(v) for k, v in c.__dict__.items() if p_u.iscontroller(v)}\n\n\ndef get_paths():\n '''return all the registered paths\n\n loops through the hierarchy and retuns a list of tuples containing the\n paths and their methods.\n\n :returns: [(path, methods), ...]\n\n '''\n pathlist = []\n for name in _hierarchy:\n fullpath = build_path(get_swag(name))\n controllers = get_controllers(name)\n paths = get_controller_paths(controllers)\n for path in paths:\n ptuple = (path_join(fullpath, path[0]), path[1])\n pathlist.append(ptuple)\n return pathlist\n\n\ndef get_swag(name):\n '''return the swag metadata from an named controller.'''\n return _hierarchy.get(name).__swag\n\n\ndef getrealname(method):\n '''attempt to get a method's real name.'''\n argspec = inspect.getargspec(method)\n args = argspec[0]\n if args and args[0] == 'self':\n return method.__name__\n if hasattr(method, '__func__'):\n method = method.__func__\n\n func_closure = six.get_function_closure(method)\n\n # NOTE(sileht): if the closure is None we cannot look deeper,\n # so return actual argspec, this occurs when the method\n # is static for example.\n if func_closure is None:\n return method.__name__\n\n closure = next(\n (\n c for c in func_closure if six.callable(c.cell_contents)\n ),\n None\n )\n method = closure.cell_contents\n return getrealname(method)\n\n\ndef methods_get(name):\n '''get all the methods for a named controller.'''\n c = _hierarchy[name]\n mlist = []\n if hasattr(c, 'index') and p_u.iscontroller(c.index):\n cfg = p_u._cfg(c.index)\n if cfg.get('generic_handlers').get('DEFAULT'):\n mlist.append('GET')\n mlist += cfg.get('allowed_methods')\n for i in c.__dict__:\n ii = getattr(c, i)\n if hasattr(ii, '__swag'):\n m = ii.__swag.get('method')\n if m is not None:\n mlist.append(m)\n return mlist\n\n\ndef path_join(part1, part2):\n if len(part2) == 0:\n return part1\n sep = '/'\n if part1[-1] == sep:\n sep = ''\n return part1 + sep + part2\n","sub_path":"pecan_swagger/g.py","file_name":"g.py","file_ext":"py","file_size_in_byte":4323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"165530659","text":"#Read the geometry\nimport numpy as np\nfrom math import sqrt\n#########################################################\n#Function to define no of Electron\n#On Entry \n#element--> name of the element\n#On Exit\n#u--> atomic no\n########################################################\n\ndef no_of_e(element):\n symbol = [\n 'H','He',\n 'Li','Be','B','C','N','O','F','Ne',\n 'Na','Mg','Al','Si','P','S','Cl','Ar',\n 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe',\n 'Co', 'Ni', 'Cu', 'Zn',\n 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr',\n 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru',\n 'Rh', 'Pd', 'Ag', 'Cd',\n 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe',\n 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu',\n 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu',\n 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg',\n 'Tl','Pb','Bi','Po','At','Rn']\n u=symbol.index(element)+1\n return u\n##########################################\n# Calculate the distance between two atoms\n#On Entry \n#a--> position of first atom, in list containing x,y and z\n#b--> position of second atom\n#On return\n#R--> distance between two atoms\n##########################################################\ndef find_distance(a,b):\n x_1=float(a[0])\n x_2=float(b[0])\n y_1=float(a[1])\n y_2=float(b[1])\n z_1=float(a[2])\n z_2=float(b[2])\n R_square =(x_1-x_2)**2+(y_1-y_2)**2+(z_1-z_2)**2\n R=sqrt(R_square)\n \n return R\n##########################################################\n#This function reads the 1 electron Hamiltonian from the disk\n#\n#On Entry\n#file_name--> Name of the file to be read from\n#basis--> Dimension of the basis set\n#\n#On Exit\n#A-->Numpy array with the 1 electron Hamiltonian elements(nbasis,nbasis)\n##########################################################\ndef file_read_1e(file_name,nbasis):\n\n #open the file\n input_file=open(file_name) #open the file\n #read the file using readline to file_content\n file_content=input_file.readlines()# read the content\n #close the file\n input_file.close() \n A=np.zeros([nbasis,nbasis])\n\n for line in file_content:\n V_line=line.rstrip()\n V_line=V_line.split() \n i=int(V_line[0])-1\n j=int(V_line[1])-1\n A[i][j]=float(V_line[2])\n A[j][i]=float(V_line[2])\n return A\n #########################################################\n#This function reads the 2 electron Hamiltonian from the disk\n#\n#On Entry\n#file_name--> Name of the file to be read from\n#basis--> Dimension of the basis set\n#\n#On Exit\n#twoe-->Numpy array with the 2 electron integrals (nbasis,nbasis,nbasis,nbasis)\n##########################################################\ndef read_2_e(file,nbasis):\n\n#read the file\n input_file=open(file) #open the file\n\n file_content=input_file.readlines()# read the content\n\n input_file.close() # close the file\n\n#print(file_content)\n twoe_index=[]\n twoe_value=[]\n\n for line in file_content:\n V_line=line.rstrip()\n V_line=line.split()\n i=int(V_line[0])\n j=int(V_line[1])# change from Dirac to Muliken Ordering\n k=int(V_line[2])\n l=int(V_line[3])\n ijkl=compound_index(i,j,k,l)\n twoe_index.append(ijkl)\n twoe_value.append(V_line[4])\n \n #define the 4 d array\n twoe=np.zeros([nbasis,nbasis,nbasis,nbasis])\n\n for i in range(nbasis):\n for j in range(nbasis):\n for k in range(nbasis):\n for l in range(nbasis):\n ijkl=compound_index(i+1,j+1,k+1,l+1)\n if ijkl in twoe_index:\n ind=twoe_index.index(ijkl)\n twoe[i,j,k,l]=float(twoe_value[ind])\n \n \n return twoe\n \n#####################################################\n# The compound index code \n#\n#on Input \n#i,j,k,l --> four integers\n#\n#On Return \n#ijkl-->gives the compound index of I,J,K,L\n#\n#####################################################\ndef compound_index(i,j,k,l):\n\n if i>j:\n ij=i*(i+1)/2+j\n else:\n ij=j*(j+1)/2+i\n\n if k>l:\n kl=k*(k+1)/2+l\n else:\n kl=l*(l+1)/2+k\n\n if ij>kl:\n ijkl=ij*(ij+1)/2+kl\n else:\n ijkl=kl*(kl+1)/2+ij\n\n return ijkl\n\n#########################################################\n#This function calculate X=S^-1/2\n#\n#On input\n#S--> overlap matrix dimension (nbasis,nbasis)\n#\n#On output\n#X--> the transformation matrix dimension (nbasis,nbasis)\n##########################################################\ndef get_X(matrix,nbasis):\n x=np.zeros([nbasis,nbasis])\n xTemp=np.zeros([nbasis,nbasis])\n temp=np.zeros([nbasis,nbasis])\n lambda_b,L=np.linalg.eigh(matrix) #genarating eigen values and eigen vector\n #print(lambda)\n #print(L)\n for i in range(nbasis):\n temp[i][i]=(lambda_b[i])**(-0.5)\n xTemp=np.matmul(L,temp)\n x=np.matmul(xTemp,L.transpose())\n return x \n \n \n \n","sub_path":"hatreefock/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":4741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"563288828","text":"from django.db import models\n\n\ndef promote(modeladmin, request, queryset):\n queryset.update(created=True)\n\npromote.short_description = \"Update facility Code\"\n# Create your models here.\nclass CodeStatus(models.Model):\n id = models.IntegerField(primary_key=True)\n facility = models.TextField()\n ftype = models.CharField(max_length=32)\n code = models.CharField(max_length=32)\n created = models.BooleanField()\n has_dups = models.BooleanField()\n fuzzy_matched = models.TextField()\n dups = models.TextField()\n pmatch = models.DecimalField(max_digits=5, decimal_places=3)\n fid = models.IntegerField()\n cdate = models.DateTimeField()\n class Meta:\n db_table = u'code_status'\n\n def __unicode__(self):\n if self.created:\n r = \"(*)\"\n else: r = \"\"\n return \"%s %s ===> %s %s ===>%s\"%(self.facility, self.ftype, self.fuzzy_matched, self.ftype, r)\n\nclass Dhis2Mapping(models.Model):\n id = models.IntegerField(primary_key=True)\n name = models.TextField()\n field_slug = models.TextField()\n keyword = models.TextField()\n dhis2_uid = models.TextField()\n dhis2_type = models.TextField()\n dhis2_dataelement = models.TextField()\n cdate = models.DateTimeField()\n\n def __unicode__(self):\n return self.name\n class Meta:\n db_table = u'dhis2_mapping'\n\n","sub_path":"dhis2/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"136497568","text":"import time\nfrom PiStorms import PiStorms\npsm = PiStorms()\n\nimport sys\nfrom collections import deque\n\nMESSAGE = \"P: {}\\nI: {}\\nD: {}\\nKP: {}\\nKI: {}\\nKD: {}\\nSpeed: {}\"\n\nSTEP_SEC = 0.1\nFOLLOW_DIST = 250\n\nOUTOFRANGE = 450\n\nSPINTIME = 1\nSPINTIME_ADD = 0.5\nSPINSPEED = 25\n\nprint(\"DOING\")\nif len(sys.argv) >= 4:\n\tKp = float(sys.argv[1])\n\tKd = float(sys.argv[2])\n\tKi = float(sys.argv[3])\n\tprint(\"PARSED K\")\nelse:\n\tKp = 1\n\tKd = 0.05\n\tKi = 0\n\nif len(sys.argv) >= 5:\n\tSCALAR = float(sys.argv[4])\n\tprint(\"PARSED SCALAR\")\nelse:\n\tSCALAR = 0.5\n\ntime.sleep(0.5)\n\nintKeepTime = 1\n\nintToKeep = int(intKeepTime / STEP_SEC)\n\nintegral = deque([0 for i in range(intToKeep)])\n\ntotalInt = 0\n\ndef setSpeed(speed):\n\tif speed > 100:\n\t\tspeed = 100\n\telif speed < -100:\n\t\tspeed = -100\n\tpsm.BAM1.setSpeedSync(-speed)\n\tif speed == 0:\n\t\tpsm.BAM1.brakeSync()\n\ndef getDistanceToGoal():\n\treturn psm.BAS2.distanceUSEV3() - FOLLOW_DIST\n\ndef waitForSensor(dist,timeout):\n\tt = time.time()\n\n\twhile psm.BAS2.distanceUSEV3() > dist and (not psm.isKeyPressed()):\n\t\tif time.time() - t > timeout:\n\t\t\treturn False\n\treturn True\n\n\n\ncurError = getDistanceToGoal()\n\nwhile not psm.isKeyPressed():\n\ttm = time.time()\n\n\n\twhile psm.BAS2.distanceUSEV3() > OUTOFRANGE and (not psm.isKeyPressed()):\n\t\tspinTime = SPINTIME\n\t\t#move left\n\t\tpsm.BAM1.setSpeed(SPINSPEED)\n\t\tpsm.BAM2.setSpeed(-SPINSPEED)\n\t\tif waitForSensor(OUTOFRANGE, spinTime):\n\t\t\tbreak\n\n\t\tsetSpeed(0)\n\t\tif waitForSensor(OUTOFRANGE, 0.5):\n\t\t\tbreak\n\n\t\t# move to the right\n\t\tpsm.BAM1.setSpeed(-SPINSPEED)\n\t\tpsm.BAM2.setSpeed(SPINSPEED)\n\t\tif waitForSensor(OUTOFRANGE, spinTime * 2):\n\t\t\tbreak\n\n\t\tsetSpeed(0)\n\t\tif waitForSensor(OUTOFRANGE, 0.5):\n\t\t\tbreak\n\n\t\t#move center\n\t\tpsm.BAM1.setSpeed(SPINSPEED)\n\t\tpsm.BAM2.setSpeed(-SPINSPEED)\n\t\tif waitForSensor(OUTOFRANGE, spinTime):\n\t\t\tbreak\n\n\t\tspinTime += SPINTIME_ADD\n\n\toldError = curError\n\tcurError = getDistanceToGoal()\n\n\tcurInt = curError * STEP_SEC\n\ttotalInt += curInt\n\ttotalInt -= integral.popleft()\n\tintegral.append(curInt)\n\t\n\tderiv = (curError - oldError) / STEP_SEC\n\n\tP = curError * Kp\n\tI = totalInt * Ki\n\tD = deriv * Kd\n\n\tsp = SCALAR * (P + I + D)\n\tsetSpeed( sp )\n\n\t# psm.screen.termPrintAt(1, str(curError))\n\t# psm.screen.termPrintAt(2, str(P))\n\t# psm.screen.termPrintAt(3, str(I))\n\t# psm.screen.termPrintAt(4, str(D))\n\t\t\n\t#print(MESSAGE.format(curError,totalInt,deriv,P,I,D,sp))\n\n\tsleept = STEP_SEC - (time.time() - tm)\n\tif sleept < 0:\n\t\tsleept = 0\n\ttime.sleep(sleept)\n\nsetSpeed(0)\n","sub_path":"libs/block_finder/PIDSonicStop.py","file_name":"PIDSonicStop.py","file_ext":"py","file_size_in_byte":2438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"432364823","text":"# Pre Procesamiento de Datos\n\n# Importando Librerias\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing set de datos\ndataset = pd.read_csv('Data.csv')\nX = dataset.iloc[:, :-1].values\ny = dataset.iloc[:, 3].values\n\n# Arreglando Datos Nulos\nfrom sklearn.preprocessing import Imputer\nimputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0)\nimputer.fit(X[:, 1:3])\nX[:, 1:3] = imputer.transform(X[:, 1:3])\n\n# Codificando Datos Categoricos\n# Codificando Variable Independiente\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nlabelencoder_X = LabelEncoder()\nX[:, 0] = labelencoder_X.fit_transform(X[:, 0])\nonehotencoder = OneHotEncoder(categorical_features = [0])\nX = onehotencoder.fit_transform(X).toarray()\n# Codificando Variable Dependiente\nlabelencoder_y = LabelEncoder()\ny = labelencoder_y.fit_transform(y)","sub_path":"RN/datos_categoricos.py","file_name":"datos_categoricos.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"25576584","text":"import sys\nfrom functools import reduce\n\n\ndef xor(x, y):\n if x == y:\n return 0\n else:\n return 1\n\n\ntry:\n while True:\n\n line = sys.stdin.readline().strip()\n if line == '':\n break\n [n, k] = map(int, line.split())\n\n line = sys.stdin.readline().strip()\n\n ciphertext = list(map(int, line))\n plaintext = []\n\n plaintext.append(ciphertext[0])\n plaintext.append(xor(ciphertext[1], plaintext[0]))\n i = 2\n while i < k:\n kvalue = reduce(xor, plaintext[0:i])\n plaintext.append(xor(kvalue, ciphertext[i]))\n i = i+1\n\n i = 0\n while i < n-k:\n kvalue = reduce(xor, plaintext[i+1:k+i])\n plaintext.append(xor(kvalue, ciphertext[k+i]))\n i = i+1\n\n plaintext = map(str, plaintext)\n print(''.join(plaintext))\n\nexcept:\n pass\n","sub_path":"bytedance/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"603171531","text":"class Tool():\n '''\n 格式化输出时间\n '''\n def __init__(self,y,m,d):\n self.y = y\n self.m = m\n self.d = d\n \n def out(self):\n print(\"今年是%s年%s月%s日\"%(self.y,self.m,self.d))\n\n\n @classmethod\n def delDate(cls,date):\n l = str.split(\"-\")\n y = l[0]\n m = l[1]\n d = l[2]\n #return y,m,d \n #return cls(y,m,d) #cls = Tool Tool(y,m,d) = cls(y,m,d)\n return cls(y,m,d).out() #cls = Tool Tool(y,m,d) = cls(y,m,d)\n\nstr = \"2018-9-12\"\nTool.delDate(str)\n\n'''\nstr = \"2018-9-12\"\ntool = Tool.delDate(str)\ntool.out()\n'''\n\n\n'''\nstr = \"2018-9-12\"\ny,m,d = Tool.delDate(str)\ntool = Tool(y,m,d)\ntool.out()\n'''\n\n'''\nstr = \"2018-9-12\"\nl = str.split(\"-\")\ny = l[0]\nm = l[1]\nd = l[2]\n\ntool = Tool(y,m,d)\ntool.out()\n''' \n","sub_path":"05day/09-类方法的小案例.py","file_name":"09-类方法的小案例.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"30719519","text":"import numpy as np\nfrom keras.layers import Input, Dense, Conv2D, MaxPooling2D, Flatten, Dropout\nfrom keras.models import Model, Sequential\n\ndef main():\n\n # training & test data\n delta30 = np.loadtxt('data_fix/delta30.csv',delimiter=',')\n dwdm0 = np.loadtxt('data_fix/dwdm0.csv',delimiter=',')\n dwdm1 = np.loadtxt('data_fix/dwdm1.csv',delimiter=',')\n fyprofile = np.loadtxt('data_fix/fyprofile.csv',delimiter=',')\n delta = np.stack((delta30,delta30),axis=2)\n dwdm = np.stack((dwdm0, dwdm1),axis=2)\n\n x_data = np.stack((delta,dwdm),axis=3)\n y_data = fyprofile\n\n i_train = np.loadtxt('data_fix/i_train.csv',delimiter=',')\n i_val = np.loadtxt('data_fix/i_val.csv',delimiter=',')\n i_train = np.asarray(np.hstack((i_train, i_val))-1,dtype=np.int)\n i_test = np.asarray(np.loadtxt('data_fix/i_test.csv',delimiter=',')-1,dtype=np.int)\n\n x_train = x_data[i_train,:,:,:]\n y_train = y_data[i_train,:]\n x_test = x_data[i_test,:,:,:]\n y_test = y_data[i_test,:]\n\n # define model\n model = Sequential()\n model.add(Conv2D(30, kernel_size=(4, 2), activation='relu', padding='same'))\n # model.add(MaxPooling2D(pool_size=(2, 1)))\n # model.add(Dropout(0.025))\n model.add(Conv2D(60, kernel_size=(4, 2), activation='relu', padding='same'))\n # model.add(MaxPooling2D(pool_size=(2, 1)))\n # model.add(Dropout(0.025))\n model.add(Conv2D(90, kernel_size=(4, 2), activation='relu', padding='same'))\n # model.add(MaxPooling2D(pool_size=(2, 1)))\n model.add(Flatten())\n model.add(Dense(500, activation='relu'))\n # model.add(Dropout(0.05))\n model.add(Dense(8))\n\n inputs = Input(shape=(30, 2, 2))\n outputs = model(inputs)\n\n model = Model(inputs=inputs, outputs=outputs)\n model.compile(optimizer='adam',\n loss='mean_squared_error',\n metrics=['accuracy'])\n\n # training model\n model.fit(x_train, y_train, epochs=10, batch_size=32)\n\n # test model\n score = model.evaluate(x_test, y_test, verbose=1)\n print('Loss : ', score[0])\n print('Accuracy : ', score[1])\n\nif __name__ == '__main__':\n\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"299670503","text":"\"\"\"\nhttps://leetcode.com/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible/\n\nlet dp(n, k) be the number of arrange for n numbers that see k sticks. \n\nIf nums[n-1] is the largest one, then there are dp(n-1, k-1) ways of arrangements.\nElse, there are (n-1) * dp(n-1, k) ways of arrangements. \n\nTime complexity: O(NK)\n\"\"\"\nclass Solution:\n def rearrangeSticks(self, n: int, k: int) -> int:\n MOD = 10 ** 9 + 7\n @cache\n def fn(n, k):\n if n == k: return 1\n if k == 0: return 0\n return ((n-1) * fn(n-1, k) + fn(n-1, k-1)) % MOD\n\n return fn(n, k) % MOD\n\ns = Solution()\nn = 13\nk = 11\nprint(s.rearrangeSticks(n, k))","sub_path":"1866_NumsOfWaysToRearrangeSticksWithKSticksVisible.py","file_name":"1866_NumsOfWaysToRearrangeSticksWithKSticksVisible.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"209649667","text":"'''\n Вывести на экран коды и символы таблицы ASCII, начиная с символа под номером 32 и заканчивая 127-м включительно. \n Вывод выполнить в табличной форме: по десять пар \"код-символ\" в каждой строке.\n'''\n\ndef fun(start, stop, step, text_str = ''):\n if 0 < step < 11:\n lit = chr(start)\n text_str += f'|{lit} = {start}|'\n step -= 1\n start += 1\n fun(start, stop, step, text_str)\n\n elif start <= stop:\n print(text_str)\n fun(start, stop, 10, text_str = '')\n\n\nfun(32, 127, 10)\n\n\n'''\n остаток не выводил т.к. в задании выводить по 10\n'''\n","sub_path":"algorithms_dz/kyznetsov_konstantin_dz_2/dz_2.py","file_name":"dz_2.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"274603328","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 24 11:04:48 2017\n\n@author: gradlab\n\"\"\"\n\n\nimport socket\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\n\nUDP_IP = \"169.254.185.14\"\nUDP_PORT = 30444\n\nsock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\nprint (\"---socket made -----\")\nsock.connect((UDP_IP, UDP_PORT))\nprint (\"---connection established ----\")\n\nsock.send(b\"Bind HTPA series device\")\ntime.sleep(1)\nsock.send(b\"k\")\n\ndatainit=[]\nfor i in range(10):\n datainit.append(sock.recv(1283))\n\n\nsock.send(b\"M\")\ntime.sleep(1)\nsock.send(b\"K\")\n\nxx = np.zeros((10,641),dtype=np.uint16)\n\n#%%\n\n\nwhile True: \n try:\n frame=0\n while frame <10:\n data = sock.recv(1283)\n #print (data[:100])\n frame = data[0]\n #print (\"frame no:\",frame)\n if len(data) == 1283:\n x=np.zeros(641,dtype=np.uint16)\n for i in range(len(x)):\n k=i*2\n x[i]=data[k+1]+256*data[k+2]\n xx[frame-1]=x\n \n datastream = xx.ravel()\n image = datastream[:5120] \n offsets=datastream[5120:6400]\n vdd=datastream[6400]\n tamb=datastream[6401]\n ptat=datastream[6402:]\n img=np.reshape(image,(64,80))\n res=256*(img - img.min())/(img.max() - img.min())\n r=np.uint8(res)\n imgresized = cv2.resize(r,(400,400))\n colormapped_img=cv2.applyColorMap(imgresized,cv2.COLORMAP_JET)\n cv2.imshow(\"image\",colormapped_img)\n if cv2.waitKey(1) & 0xFF == 27:\n sock.send(b\"X\") #to stop data collection\n sock.close()\n cv2.destroyAllWindows()\n break\n except KeyboardInterrupt:\n sock.send(b\"X\") #to stop data collection\n sock.close()\n cv2.destroyAllWindows()\n break\n \n #plt.imshow(img)\n #plt.axis('off')\n #plt.show()\n \n\n#%% \n#while True:\n# try:\n# data = sock.recv(1283)\n# print (data)\n# except KeyboardInterrupt:\n# break\n\n\n","sub_path":"udpconnection.py","file_name":"udpconnection.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"636048521","text":"# import relevant libraries\n\nimport sys\nimport pandas as pd\nfrom telethon.sync import TelegramClient\nfrom telethon.sessions import StringSession\nfrom telethon.tl.functions.channels import JoinChannelRequest\nfrom telethon.tl.functions.messages import ImportChatInviteRequest\nfrom telethon.tl.functions.messages import CheckChatInviteRequest\nimport time\nimport telethon.utils as utils\n\nimport logging\nimport datetime\n\n\n# import sql und telegram login\nimport config\n\n\n\n### configuration:\n\n#name of the logfile (.txt). Logfile is saved in sub directory /log/\nlogname = 'wave2_private'\n\n#input for scaping: (.txt) One group/channel per line. File should be in sub directory /lists/\nlistname = 'wave1_private'\n\n# .csv output (.csv). File will be saved to sub directory /csv/\ncsvname = 'wave2_private'\n\n# invite link required? (1=yes)\nis_invite = 1\n\n# wave, useful if script is executed repeatedly\nwave = 1\n\n# sleep after loop (in secs). Time out is useful as to not make Telegram believe we are a bot\nsleep = 361\n\n\n#log: will be saved to sub directory /log/\n\nlogging.basicConfig(level=logging.INFO, format='%(message)s')\nlogger = logging.getLogger()\nlogger.addHandler(logging.FileHandler('log/' + logname + '_' + datetime.datetime.now().strftime(\"%d.%m.%Y_%H.%M\") + '.txt', 'a'))\nprint = logger.info\n\n# check if script is executed rightfully, as SQL content might get removed\n\ncontinuescript = input('Would you like to continue with this script? (Y/n)')\n\nif continuescript in ['Y', 'y']:\n print('Great. lets continue')\nelse:\n sys.exit()\n\n\ntime.sleep(5.5)\n\n\n# read in input for scraping\nlineList = [line.rstrip('\\n') for line in open(\"lists/\" + listname + '.txt')]\n\nchats = lineList\n\n\n# the actual scraping process\nclient = TelegramClient(StringSession(config.string), config.api_id, config.api_hash)\n\nasync def main():\n for chat in chats:\n time.sleep(5)\n try:\n # try to join\n await client(ImportChatInviteRequest(chat))\n time.sleep(5)\n except:\n print(chat + ' channel/group does not exist or other error. Skipping to next channel...')\n else:\n # if join successful, retrieve chat title\n chatinvite = await client(CheckChatInviteRequest(hash = chat))\n\n try:\n chattitle = chatinvite.channel.title\n except:\n chattitle = chatinvite.chat.title\n print(chattitle + ' seems to be a chat...')\n\n time.sleep(10)\n print('Successfully joined ' + chattitle + '. Starting scraping now...')\n list = []\n async for message in client.iter_messages(chattitle, reverse=True):\n list.append([chattitle, message.chat_id, message.is_private, message.is_group, message.is_channel, is_invite, wave, message.id,\n message.sender_id, message.date, message.text, message.action])\n df = pd.DataFrame(list)\n df.columns = ['chat_title', 'chat_id', 'is_private', 'is_group', 'is_channel', 'is_invite', 'wave', 'message_id', 'message_senderid',\n 'message_date', 'message_text', 'message_action']\n df['message_action'] = df['message_action'].astype(str)\n\n time.sleep(sleep)\n\n\nwith client:\n client.loop.run_until_complete(main())\n\ntime.sleep(5.5)\n\n\n# save data to .csv-file. Can be removed if no .csv output is wished\ntry:\n df.to_csv('csv/' + csvname + '.csv', sep = '-')\nexcept:\n print('Was not able to write .csv')\nelse:\n print('everything worked like a charm. .csv file saved.')\n","sub_path":"scrape_private.py","file_name":"scrape_private.py","file_ext":"py","file_size_in_byte":3571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"354848181","text":"#-*-coding:utf-8 -*-\n'''\n药品种类匹配\n'''\nfrom fuzzywuzzy import fuzz\nfrom fuzzywuzzy import process\ndrug_type={}\ndrug=open(\"dataset/drug.txt\")\nfor line in drug:\n lines=line.strip(\"\\r\\n\").split(' ')\n name=lines[0]\n type=lines[1]\n drug_type[name]=type\n\ndrug_use=open(\"dataset/medicineSortByPrice.csv\",encoding='utf-8')\nmatch_cout=0\nunmatch_cout=0\nfor line in drug_use:\n lines = line.strip(\"\\r\\n\").split(',')\n name=lines[0]\n for str in ['注射液','胶囊','片','(',')','注射用','颗粒','糖浆','口服溶液']:\n name=name.replace(str, '')\n flag = False\n for key,value in drug_type.items():\n for str in ['注射液', '胶囊', '片', '(', ')', '注射用','颗粒','糖浆','口服溶液']:\n key=key.replace(str, '')\n if fuzz.ratio(key,name)>70:\n match_cout=match_cout+1\n flag=True\n break\n if flag==False:\n print(lines[0])\n unmatch_cout=unmatch_cout+1\n\nprint(\"匹配药品数:\",match_cout)\nprint(\"未匹配药品数:\",unmatch_cout)\ndrug.close()\ndrug_use.close()","sub_path":"fraud_detection/drugTypeMatch.py","file_name":"drugTypeMatch.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"362548418","text":"from django.db.models import Q\n\nfrom rest_framework.filters import (\n SearchFilter,\n OrderingFilter,\n)\nfrom rest_framework.generics import(\n ListAPIView, \n RetrieveAPIView,\n RetrieveUpdateAPIView,\n UpdateAPIView,\n DestroyAPIView,\n CreateAPIView,\n)\n\nfrom rest_framework.permissions import (\n AllowAny,\n IsAuthenticated,\n IsAdminUser,\n IsAuthenticatedOrReadOnly\n)\n\nfrom posts.models import Post\nfrom .pagination import PostLimitOffsetPagination, PostPageNumberPagination\nfrom .serializers import PostListSerializer, PostDetailSerializer, PostCreateUpdateSerializer\nfrom .permissions import IsOwnerOrReadOnly\n\nclass PostListAPIView(ListAPIView):\n serializer_class = PostListSerializer\n filter_backends = [SearchFilter, OrderingFilter]\n permission_classes = [AllowAny]\n search_fields = ['title', 'content', 'user__first_name']\n # URL examples\n # 1. Two depth search, first keyword is 'pyk', second keyword is 'edit':\n # http://127.0.0.1:8000/api/posts/?search=pyk&q=edit\n # 2. Search posts contain keyword 'pyk' and ordering in inverse title sequence \n # http://127.0.0.1:8000/api/posts/?search=pyk&ordering=-title\n\n pagination_class = PostPageNumberPagination #PostLimitOffsetPagination\n\n def get_queryset(self, *args, **kargs):\n #queryset_list = super(PostListAPIView, self).get_queryset(*args, **kargs)\n queryset_list = Post.objects.all() # Same meaning as above line\n query = self.request.GET.get('q')\n if query:\n queryset_list = queryset_list.filter(\n Q(title__icontains=query) |\n Q(content__icontains=query) |\n Q(user__first_name__icontains=query) |\n Q(user__last_name__icontains=query)\n ).distinct()\n\n return queryset_list\n\nclass PostDetailAPIView(RetrieveAPIView):\n queryset = Post.objects.all()\n serializer_class = PostDetailSerializer\n lookup_field = 'slug'\n permission_classes = [AllowAny]\n\nclass PostUpdateAPIView(RetrieveUpdateAPIView):\n queryset = Post.objects.all()\n serializer_class = PostCreateUpdateSerializer\n lookup_field = 'slug'\n permission_classes = [IsOwnerOrReadOnly]\n\n def perform_update(self, serializer):\n serializer.save(user=self.request.user)\n\nclass PostDeleteAPIView(DestroyAPIView):\n queryset = Post.objects.all()\n serializer_class = PostDetailSerializer\n lookup_field = 'slug'\n permission_classes = [IsOwnerOrReadOnly]\n\nclass PostCreateAPIView(CreateAPIView):\n queryset = Post.objects.all()\n serializer_class = PostCreateUpdateSerializer\n # permission_classes = [IsAuthenticated]\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)","sub_path":"trydjango19/posts/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"346854908","text":"from textClassification.utils.dataprocessor import dataProcessor\nfrom textClassification.utils.config import Config\nfrom textClassification.model.textCNN import textCNN\nfrom textClassification.model.fastText import fastText\nfrom torchtext.data import BucketIterator\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport torch\nimport argparse\nfrom sklearn.metrics import f1_score, precision_score, recall_score\n\n\n\nclass Runner(object):\n\n def __init__(self):\n parser = argparse.ArgumentParser(description=\"neural networks trainer\")\n parser.add_argument(\"--test\", help=\"validation set\")\n parser.add_argument(\"--train\", help=\"training set\")\n parser.add_argument(\"--dev\", help=\"development set\")\n parser.add_argument(\"--webd\", help=\"word embedding\", required=False)\n\n parser.add_argument(\"--batch\", help=\"batch size\", default=512,\n type=int)\n parser.add_argument(\"--epochs\", help=\"n of epochs\",\n default=10, type=int)\n\n parser.add_argument(\"--seed\", help=\"RNG seed\", default=42, type=int)\n parser.add_argument(\"--optimizer\", default=\"adam\")\n parser.add_argument(\"--lr\", default=0.001, type=float)\n\n parser.add_argument(\"--out\", help=\"output model path\",\n default=\"output\")\n parser.add_argument(\"--model\", default=\"textcnn\")\n parser.add_argument(\"--device\", default=\"cpu\")\n\n self.args = parser.parse_args()\n self.config = Config\n # self.device = torch.device(self.args.device)\n self.device = torch.device(self.args.device)\n\n\n def loss_fn(self, logits, label):\n\n loss = nn.CrossEntropyLoss()(logits, label)\n\n return loss\n\n def evaluate(self, all_label, all_predict):\n\n p = precision_score(all_label, all_predict)\n\n r = recall_score(all_label, all_predict)\n\n f1 = f1_score(all_label, all_predict, average='macro')\n\n return p, r, f1\n\n def train(self, data_iter, model, optimizer):\n for i in range(self.args.epochs):\n model.train()\n epoch_loss = 0.0\n cnt = 0\n predict_all = []\n label_all = []\n print('Epoch', i)\n for batch in data_iter:\n optimizer.zero_grad()\n text, text_len = batch.Phrase\n #[batch, seq_len]\n text = text.transpose(0, 1)\n label = batch.Sentiment\n cnt += 1\n logits, predict = model(text)\n predict = predict.tolist()\n\n assert len(predict) == len(label)\n predict_all.extend(predict)\n\n loss = self.loss_fn(logits, label)\n label = label.tolist()\n label_all.extend(label)\n epoch_loss += loss.item()\n loss.backward()\n optimizer.step()\n\n\n epoch_loss = epoch_loss / cnt\n p, r, f1 = self.evaluate(label_all, predict_all)\n print(\"\\nEpoch\", i, \" train loss: \", epoch_loss,\n \"\\ntrain p: \", p,\n \" train r: \", r,\n \" train f1: \", f1)\n\n # model.save_model()\n\n return model\n\n\n def evaluate(self, all_label, all_predict):\n\n p = precision_score(all_label, all_predict, average='macro')\n\n r = recall_score(all_label, all_predict, average='macro')\n\n f1 = f1_score(all_label, all_predict, average='macro')\n\n\n return p ,r ,f1\n\n def predict(self, data_iter, model):\n\n all_predict = []\n\n for batch in data_iter:\n text, text_len = batch.Phrase\n text = text.transpose(0, 1)\n\n _, predict = model(text)\n predict = predict.tolist()\n all_predict.extend(predict)\n\n return all_predict\n\n\n\n def run(self):\n field_list, data_list = dataProcessor(Config).preprocess()\n TEXT, LABEL = field_list\n train_set, test_set = data_list\n embedding_matrix = TEXT.vocab.vectors\n\n\n\n train_iter = BucketIterator(train_set,\n batch_size=self.args.batch,\n train=True,\n shuffle=True,\n device=-1,\n sort_key=lambda x: len(x.Phrase)\n )\n # dev_iter = BucketIterator(dev_set,\n # batch_size=self.arg.batch,\n # train=False,\n # shuffle=True,\n # device=-1,\n # sort_key=lambda x: len(x.Phrase))\n test_iter = BucketIterator(test_set,\n batch_size=self.args.batch,\n train=False,\n shuffle=False,\n device=-1,\n sort=False)\n\n if self.config.embedding_size == -1:\n self.config.embedding_size = len(TEXT.vocab.itos)\n\n if self.args.model == \"textcnn\":\n model = textCNN(self.config, self.device, pretrain_embedding=embedding_matrix)\n elif self.args.model == \"fastext\":\n model = fastText(self.config, self.device, pretrain_embedding=embedding_matrix)\n else:\n print('None model!')\n\n if self.args.optimizer == \"adam\":\n optimizer = torch.optim.Adam(model.parameters_requires_grads(),\n lr=self.args.lr)\n elif self.args.optimizer == \"adadelta\":\n optimizer = torch.optim.Adadelta(model.parameters_requires_grads(),\n lr=self.args.lr)\n else:\n optimizer = torch.optim.SGD(model.parameters_requires_grads(),\n lr=self.args.lr,\n momentum=0.9)\n print(optimizer)\n model = self.train(train_iter, model, optimizer)\n all_predict = self.predict(test_iter, model)\n\n print(all_predict[0:10])\n\n\n\n\n\n\n\nif __name__ == '__main__':\n Runner().run()\n","sub_path":"textClassification/runClassify.py","file_name":"runClassify.py","file_ext":"py","file_size_in_byte":6261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"536661721","text":"import os\nimport numpy as np\n\n\nclass Fft(object):\n def __init__(self, fs, chunk_size, four_length_second, output_dir_fourier, prefix='four'):\n self.fs = fs\n self.chunk_size = chunk_size\n self.four_length_second = four_length_second\n self.max_frame_count = int(np.floor(self.four_length_second * self.fs /\n self.chunk_size))\n self.name = None\n self.prefix = prefix\n self.output_dir_fourier = output_dir_fourier\n self.count_frame = 0\n self.io_flag = False\n\n def open_file(self):\n filename = os.path.join(self.output_dir_fourier, self.prefix + '_' + self.name + \".bin\")\n try:\n self.file = open(filename, 'wb')\n self.io_flag = True\n except IOError as ie:\n self.io_flag = False\n\n def write_four(self, input_stream):\n \"\"\"\n Записывает звук, преобразованный через Фурье (Вероятно)\n \"\"\"\n if self.count_frame == 0:\n self.open_file()\n self.segment = []\n if self.count_frame == self.max_frame_count:\n # Записывает отрезок и открывает новый\n FFT = np.fft.rfft(self.segment)\n np.array(FFT, dtype=np.csingle).tofile(self.file)\n self.file.close()\n self.open_file()\n self.count_frame = 0\n self.segment = []\n if self.io_flag:\n self.segment.extend(np.frombuffer(input_stream[0], dtype=np.int16))\n #result = np.reshape(result, (frames_per_buffer, 2))\n #Now to access the left channel, use result[:, 0], and for right channel, use result[:, 1]\n self.count_frame += 1\n\n return None\n\n def close_file(self):\n self.file.close()\n","sub_path":"fourier_transformer.py","file_name":"fourier_transformer.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"463950857","text":"from tkinter import *\r\nimport math , random\r\nimport os\r\nfrom tkinter import messagebox\r\nclass Bill_app:\r\n def __init__(self,root):\r\n self.root=root\r\n self.root.geometry(\"1350x700\")\r\n self.root.title(\"RSV HunGry SoluTion\")\r\n bg_colour =\"#0c4f53\"\r\n fg_colour =\"#747810\"\r\n h_colour = \"#BCC6CC\"\r\n #logo = tkinter.PhotoImage(file = \"bill_area.jpg\")\r\n title=Label(self.root,text=\"RSV HunGry SoluTion\",bd= 8,relief=FLAT,bg = bg_colour , fg= fg_colour , font=(\"RIBBON\",27,\"overstrike\",\"italic\"),pady=2).pack(fill= X)\r\n #*******VARIABLES*********\r\n #************COSMETICS*********\r\n self.soap=IntVar()\r\n self.face_cream=IntVar()\r\n self.face_wash=IntVar()\r\n self.spray=IntVar()\r\n self.gel=IntVar()\r\n self.lotion=IntVar()\r\n #***********GROCERY************\r\n self.rice=IntVar()\r\n self.food_oil=IntVar()\r\n self.pulses=IntVar()\r\n self.wheat=IntVar()\r\n self.sugar=IntVar()\r\n self.tea=IntVar()\r\n #*********COLD DRINKS**********\r\n self.maza=IntVar()\r\n self.coke=IntVar()\r\n self.frooti=IntVar()\r\n self.thumbsup=IntVar()\r\n self.limca=IntVar()\r\n self.sprite=IntVar()\r\n\r\n #********Total product price & Tax********\r\n self.cosmetic_price=StringVar()\r\n self.grocery_price=StringVar()\r\n self.cold_drink_price=StringVar()\r\n\r\n self.cosmetic_tax=StringVar()\r\n self.grocery_tax=StringVar()\r\n self.cold_drink_tax=StringVar()\r\n\r\n #*********customer************\r\n self.c_name=StringVar()\r\n self.c_phone=StringVar()\r\n\r\n self.bill_no=StringVar()\r\n x=random.randint(1000,9999)\r\n self.bill_no.set(str(x))\r\n\r\n self.search_bill=StringVar()\r\n\r\n #**********************customer detail frame****************\r\n F1 = LabelFrame(self.root,bd=10,relief=FLAT,text=\"Customer Details\",font = (\"times new roman\",15,\"bold\"),fg=h_colour,bg = bg_colour )\r\n F1.place(x=0,y=80,relwidth=1)\r\n\r\n cname_lbl = Label(F1,text =\"Customer Name\",bg = bg_colour,fg = \"white\" ,font=(\"times new roman\",18,\"bold\")).grid(row=0,column= 0 , padx=20 , pady=5)\r\n cname_txt = Entry(F1,width=18,textvariable=self.c_name, font = \"arial 15\", bd =3 , relief= SOLID).grid(row=0,column = 1,pady=5,padx=10)\r\n \r\n cphn_lbl = Label(F1,text =\"Phone No.\",bg = bg_colour,fg = \"white\" ,font=(\"times new roman\",18,\"bold\")).grid(row=0,column=2 , padx=20 , pady=5)\r\n cphn_txt = Entry(F1,width=18,textvariable=self.c_phone,font = \"arial 15\", bd =3 , relief= SOLID).grid(row=0,column = 3,pady=5,padx=10)\r\n\r\n c_bill_lbl = Label(F1,text =\"Bill Number\",bg = bg_colour,fg = \"white\" ,font=(\"times new roman\",18,\"bold\")).grid(row=0,column= 4 , padx=20 , pady=5)\r\n c_bill_txt = Entry(F1,width=18,textvariable=self.search_bill,font = \"arial 15\", bd =3, relief = SOLID).grid(row=0,column = 5,pady=5,padx=10)\r\n\r\n bill_btn = Button(F1,text=\"Search\",command=self.find_bill,width=8,bd=7,font=\"chewy 12 bold\").grid(row=0,column = 6,padx=10,pady= 10)\r\n\r\n \r\n #******************Cosmetics Frame*********************\r\n F2=LabelFrame(self.root,bd=10,relief=FLAT,text=\"Cosmetics\",font = (\"times new roman\",15,\"bold\"),fg=h_colour,bg = bg_colour )\r\n F2.place(x=0,y=180,width=325,height=380)\r\n\r\n bath_lbl= Label(F2,text=\"Bath soap\",font=(\"times new roman\",16,\"bold\"),bg=bg_colour,fg= fg_colour).grid(row=0,column=0,padx=10,pady=10,sticky=\"w\")\r\n bath_txt=Entry(F2,width=8,textvariable=self.soap,font=(\"times new roman\",16,\"bold\"),bd=2,relief = SOLID).grid(row=0,column=1,padx=10,pady=10)\r\n\r\n face_cream_lbl= Label(F2,text=\"face cream\",font=(\"times new roman\",16,\"bold\"),bg=bg_colour,fg=fg_colour).grid(row=1,column=0,padx=10,pady=10,sticky=\"w\")\r\n face_cream_txt=Entry(F2,width=8,textvariable=self.face_cream,font=(\"times new roman\",16,\"bold\"),bd=2,relief=SOLID).grid(row=1,column=1,padx=10,pady=10)\r\n\r\n face_w_lbl= Label(F2,text=\"face wash\",font=(\"times new roman\",16,\"bold\"),bg=bg_colour,fg=fg_colour).grid(row=2,column=0,padx=10,pady=10,sticky=\"w\")\r\n face_w_txt=Entry(F2,width=8,textvariable=self.face_wash,font=(\"times new roman\",16,\"bold\"),bd=2,relief=SOLID).grid(row=2,column=1,padx=10,pady=10)\r\n\r\n hair_s_lbl= Label(F2,text=\"Hair Spray\",font=(\"times new roman\",16,\"bold\"),bg=bg_colour,fg=fg_colour).grid(row=3,column=0,padx=10,pady=10,sticky=\"w\")\r\n hair_s_txt=Entry(F2,width=8,textvariable=self.spray,font=(\"times new roman\",16,\"bold\"),bd=2,relief=SOLID).grid(row=3,column=1,padx=10,pady=10)\r\n\r\n hair_g_lbl= Label(F2,text=\"Hair Gel\",font=(\"times new roman\",16,\"bold\"),bg=bg_colour,fg=fg_colour).grid(row=4,column=0,padx=10,pady=10,sticky=\"w\")\r\n hair_g_txt=Entry(F2,width=8,textvariable=self.gel,font=(\"times new roman\",16,\"bold\"),bd=2,relief=SOLID).grid(row=4,column=1,padx=10,pady=10)\r\n\r\n\r\n body_lbl= Label(F2,text=\"Body Lotion\",font=(\"times new roman\",16,\"bold\"),bg=bg_colour,fg=fg_colour).grid(row=5,column=0,padx=10,pady=10,sticky=\"w\")\r\n body_s_txt=Entry(F2,width=8,textvariable=self.lotion,font=(\"times new roman\",16,\"bold\"),bd=2,relief=SOLID).grid(row=5,column=1,padx=10,pady=10)\r\n\r\n #******************Drink's*********************\r\n F4=LabelFrame(self.root,bd=10,relief=FLAT,text=\"Drink_s\",font = (\"times new roman\",15,\"bold\"),fg=h_colour,bg = bg_colour )\r\n F4.place(x=300,y=180,width=325,height=380)\r\n\r\n d1_lbl= Label(F4,text=\"MAZA\",font=(\"times new roman\",16,\"bold\"),bg=bg_colour,fg=fg_colour).grid(row=0,column=0,padx=10,pady=10,sticky=\"w\")\r\n d1_txt=Entry(F4,width=8,textvariable=self.maza,font=(\"times new roman\",16,\"bold\"),bd=2,relief=SOLID).grid(row=0,column=1,padx=10,pady=10)\r\n\r\n d2_lbl= Label(F4,text=\"COKE\",font=(\"times new roman\",16,\"bold\"),bg=bg_colour,fg=fg_colour).grid(row=1,column=0,padx=10,pady=10,sticky=\"w\")\r\n d2_txt=Entry(F4,width=8,textvariable=self.coke,font=(\"times new roman\",16,\"bold\"),bd=2,relief=SOLID).grid(row=1,column=1,padx=10,pady=10)\r\n\r\n d3_lbl= Label(F4,text=\"FROOTI\",font=(\"times new roman\",16,\"bold\"),bg=bg_colour,fg=fg_colour).grid(row=2,column=0,padx=10,pady=10,sticky=\"w\")\r\n d3_txt=Entry(F4,width=8,textvariable=self.frooti,font=(\"times new roman\",16,\"bold\"),bd=2,relief=SOLID).grid(row=2,column=1,padx=10,pady=10)\r\n\r\n d4_lbl= Label(F4,text=\"THUMBs Up\",font=(\"times new roman\",16,\"bold\"),bg=bg_colour,fg=fg_colour).grid(row=3,column=0,padx=10,pady=10,sticky=\"w\")\r\n d4_txt=Entry(F4,width=8,textvariable=self.thumbsup,font=(\"times new roman\",16,\"bold\"),bd=2,relief=SOLID).grid(row=3,column=1,padx=10,pady=10)\r\n\r\n d5_lbl= Label(F4,text=\"LIMCA\",font=(\"times new roman\",16,\"bold\"),bg=bg_colour,fg=fg_colour).grid(row=4,column=0,padx=10,pady=10,sticky=\"w\")\r\n d5_txt=Entry(F4,width=8,textvariable=self.limca,font=(\"times new roman\",16,\"bold\"),bd=2,relief=SOLID).grid(row=4,column=1,padx=10,pady=10)\r\n\r\n d6_lbl= Label(F4,text=\"SPRITE\",font=(\"times new roman\",16,\"bold\"),bg=bg_colour,fg=fg_colour).grid(row=5,column=0,padx=10,pady=10,sticky=\"w\")\r\n d6_txt=Entry(F4,width=8,textvariable=self.sprite,font=(\"times new roman\",16,\"bold\"),bd=2,relief=SOLID).grid(row=5,column=1,padx=10,pady=10)\r\n\r\n #******************Grocery Frame*********************\r\n F3=LabelFrame(self.root,bd=20,relief=FLAT,text=\"Grocery\",font = (\"times new roman\",15,\"bold\"),fg=h_colour,bg = bg_colour )\r\n F3.place(x=600,y=180,width=325,height=380)\r\n\r\n g1_lbl= Label(F3,text=\"Rice\",font=(\"times new roman\",16,\"bold\"),bg=bg_colour,fg=fg_colour).grid(row=0,column=0,padx=10,pady=10,sticky=\"w\")\r\n g1_txt=Entry(F3,width=8,textvariable=self.rice,font=(\"times new roman\",16,\"bold\"),bd=2,relief=SOLID).grid(row=0,column=1,padx=10,pady=10)\r\n\r\n g2_lbl= Label(F3,text=\"Food Oil\",font=(\"times new roman\",16,\"bold\"),bg=bg_colour,fg=fg_colour).grid(row=1,column=0,padx=10,pady=10,sticky=\"w\")\r\n g2_txt=Entry(F3,width=8,textvariable=self.food_oil,font=(\"times new roman\",16,\"bold\"),bd=2,relief=SOLID).grid(row=1,column=1,padx=10,pady=10)\r\n\r\n g3_lbl= Label(F3,text=\"pulses\",font=(\"times new roman\",16,\"bold\"),bg=bg_colour,fg=fg_colour).grid(row=2,column=0,padx=10,pady=10,sticky=\"w\")\r\n g3_txt=Entry(F3,width=8,textvariable=self.pulses,font=(\"times new roman\",16,\"bold\"),bd=2,relief=SOLID).grid(row=2,column=1,padx=10,pady=10)\r\n\r\n g4_lbl= Label(F3,text=\"Wheat\",font=(\"times new roman\",16,\"bold\"),bg=bg_colour,fg=fg_colour).grid(row=3,column=0,padx=10,pady=10,sticky=\"w\")\r\n g4_txt=Entry(F3,width=8,textvariable=self.wheat,font=(\"times new roman\",16,\"bold\"),bd=2,relief=SOLID).grid(row=3,column=1,padx=10,pady=10)\r\n\r\n g5_lbl= Label(F3,text=\"Sugar\",font=(\"times new roman\",16,\"bold\"),bg=bg_colour,fg=fg_colour).grid(row=4,column=0,padx=10,pady=10,sticky=\"w\")\r\n g5_txt=Entry(F3,width=8,textvariable=self.sugar,font=(\"times new roman\",16,\"bold\"),bd=2,relief=SOLID).grid(row=4,column=1,padx=10,pady=10)\r\n\r\n g6_lbl= Label(F3,text=\"Tea\",font=(\"times new roman\",16,\"bold\"),bg=bg_colour,fg=fg_colour).grid(row=5,column=0,padx=10,pady=10,sticky=\"w\")\r\n g6_txt=Entry(F3,width=8,textvariable=self.tea,font=(\"times new roman\",16,\"bold\"),bd=2,relief=SOLID).grid(row=5,column=1,padx=10,pady=10)\r\n\r\n #**************Bill Area************\r\n F5=Frame(self.root,bd=2,relief=SOLID)\r\n F5.place(x=950,y=180,width=360,height=380)\r\n bill_title=Label(F5,text=\"BILL AREA\",font=\"chewy 15 bold\",bd =2,relief=SOLID).pack(fill=X)\r\n scrol_y=Scrollbar(F5,orient = VERTICAL)\r\n self.txtarea = Text(F5,yscrollcommand=scrol_y.set)\r\n scrol_y.pack(side=RIGHT,fill=Y)\r\n scrol_y.config(command=self.txtarea.yview)\r\n self.txtarea.pack(fill = BOTH,expand = 1)\r\n \r\n #************Button frame***************\r\n F6 =LabelFrame(self.root,bd=4,relief=SOLID,text=\"BILL MENU\",font = (\"times new roman\",15,\"bold\"),fg=h_colour,bg = bg_colour)\r\n F6.place(x=0,y=560,relwidth=1,height=140)\r\n m1_lbl = Label(F6,text=\"TOTAL COSMETIC PRICE\",bg=bg_colour,fg = \"white\" , font =(\"tomes new roman\",14,\"bold\")).grid(row=0,column=0,padx=20,pady=1,sticky=\"w\")\r\n m1_txt=Entry(F6,width=13,textvariable=self.cosmetic_price,font=\"arial 10 bold\",bd = 3,relief=SOLID).grid(row=0,column=1,padx=10,pady=1)\r\n\r\n m2_lbl = Label(F6,text=\"TOTAL GROCERY PRICE\",bg=bg_colour,fg = \"white\" , font =(\"tomes new roman\",14,\"bold\")).grid(row=1,column=0,padx=20,pady=1,sticky=\"w\")\r\n m2_txt=Entry(F6,width=13,textvariable=self.grocery_price,font=\"arial 10 bold\",bd = 3,relief=SOLID).grid(row=1,column=1,padx=10,pady=1)\r\n\r\n m3_lbl = Label(F6,text=\"TOTAL DRINK_S PRICE\",bg=bg_colour,fg = \"white\" , font =(\"tomes new roman\",14,\"bold\")).grid(row=2,column=0,padx=20,pady=1,sticky=\"w\")\r\n m3_txt=Entry(F6,width=13,textvariable=self.cold_drink_price,font=(\"arial 10 bold\"),bd = 3,relief=SOLID).grid(row=2,column=1,padx=10,pady=1)\r\n\r\n c1_lbl = Label(F6,text=\"COSMETIC Tax\",bg=bg_colour,fg = \"white\" , font =(\"tomes new roman\",14,\"bold\")).grid(row=0,column=2,padx=20,pady=1,sticky=\"w\")\r\n c1_txt=Entry(F6,width=13,textvariable=self.cosmetic_tax,font=\"arial 10 bold\",bd = 3,relief=SOLID).grid(row=0,column=3,padx=10,pady=1)\r\n\r\n c2_lbl = Label(F6,text=\"GROCERY Tax\",bg=bg_colour,fg = \"white\" , font =(\"tomes new roman\",14,\"bold\")).grid(row=1,column=2,padx=20,pady=1,sticky=\"w\")\r\n c2_txt=Entry(F6,width=13,textvariable=self.grocery_tax,font=\"arial 10 bold\",bd = 3,relief=SOLID).grid(row=1,column=3,padx=10,pady=1)\r\n\r\n c3_lbl = Label(F6,text=\"DRINK_S Tax\",bg=bg_colour,fg = \"white\" , font =(\"tomes new roman\",14,\"bold\")).grid(row=2,column=2,padx=20,pady=1,sticky=\"w\")\r\n c3_txt=Entry(F6,width=13,textvariable=self.cold_drink_tax,font=(\"arial 10 bold\"),bd = 3,relief=SOLID).grid(row=2,column=3,padx=10,pady=1)\r\n\r\n #*********button fraame***********\r\n\r\n btn_F=Frame(F6,bd=3,relief=GROOVE)\r\n btn_F.place(x=740,width=585,height=90)\r\n\r\n total_btn = Button(btn_F,text=\"TOTAL\",command=self.total ,bg=bg_colour,fg=\"white\",pady=6,width=11,font=\"arial 10 bold\").grid(row=0,column=0,padx=5,pady=5)\r\n GBILL_btn = Button(btn_F,text=\"GENRATE BILL\",command=self.bill_area,bg=bg_colour,fg=\"white\",pady=6,width=11,font=\"arial 10 bold\").grid(row=0,column=1,padx=5,pady=5)\r\n CLEAR_btn = Button(btn_F,text=\"CLEAR\",command=self.clear_data,bg=bg_colour,fg=\"white\",pady=6,width=11,font=\"arial 10 bold\").grid(row=0,column=2,padx=5,pady=5)\r\n EXIT_btn = Button(btn_F,text=\"EXIT\",command=self.exit_app,bg=bg_colour,fg=\"white\",pady=6,width=11,font=\"arial 10 bold\").grid(row=0,column=3,padx=5,pady=5)\r\n self.welcome_bill()\r\n\r\n def total(self):\r\n self.c_s_p= self.soap.get()*40\r\n self.c_fc_p= self.face_cream.get()*120\r\n self.c_fw_p=self.face_wash.get()*60\r\n self.c_hs_p=self.spray.get()*180\r\n self.c_hg_p=self.gel.get()*140\r\n self.c_bl_p=self.lotion.get()*180\r\n self.total_cosmetic_price=float(\r\n self.c_bl_p+\r\n self.c_fc_p+\r\n self.c_fw_p+\r\n self.c_hg_p+\r\n self.c_hs_p+\r\n self.c_s_p\r\n ) \r\n self.cosmetic_price.set(\"Rs. \"+str(self.total_cosmetic_price))\r\n self.c_tax =round((self.total_cosmetic_price * 0.05),2)\r\n self.cosmetic_tax.set( \"Rs. \" +str(self.c_tax))\r\n\r\n self.D_m_p = self.maza.get()*40\r\n self.D_c_p = self.coke.get()*120\r\n self.D_s_p = self.sprite.get()*60\r\n self.D_f_p = self.frooti.get()*180\r\n self.D_t_p = self.thumbsup.get()*140\r\n self.D_l_p = self.limca.get()*180\r\n\r\n \r\n\r\n\r\n self.total_drink_price=float(\r\n self.D_c_p+\r\n self.D_f_p+\r\n self.D_l_p+\r\n self.D_s_p+\r\n self.D_t_p+\r\n self.D_m_p\r\n ) \r\n self.cold_drink_price.set(\"Rs. \"+str(self.total_drink_price) )\r\n self.d_tax=round((self.total_drink_price* 0.05),2)\r\n self.cold_drink_tax.set( \"Rs. \" +str(self.d_tax))\r\n\r\n self.g_r_p=self.rice.get()*40\r\n self.g_f_p=self.food_oil.get()*180\r\n self.g_d_p=self.pulses.get()*60\r\n self.g_w_p=self.wheat.get()*180\r\n self.g_s_p=self.sugar.get()*140\r\n self.g_t_p=self.tea.get()*180\r\n\r\n self.total_grocery_price=float(\r\n self.g_r_p+\r\n self.g_f_p+\r\n self.g_d_p+\r\n self.g_w_p+\r\n self.g_s_p+\r\n self.g_t_p \r\n ) \r\n self.grocery_price.set( \"Rs. \"+str(self.total_grocery_price))\r\n self.g_tax=round((self.total_grocery_price * 0.05),2)\r\n self.grocery_tax.set( \"Rs. \" +str(self.g_tax))\r\n\r\n self.total_bill=float( self.total_cosmetic_price + self.c_tax + \r\n self.total_drink_price + self.d_tax +\r\n self.total_grocery_price + self.g_tax)\r\n\r\n def welcome_bill(self):\r\n self.txtarea.delete('1.0',END)\r\n self.txtarea.insert(END,\" .....RSV.....\\n .....THANKS FOR COMMING.....\")\r\n self.txtarea.insert(END,f\"\\n BILL NO. : {self.bill_no.get()}\")\r\n self.txtarea.insert(END,f\"\\n Customer Name : {self.c_name.get()}\")\r\n self.txtarea.insert(END,f\"\\n Customer Phone no. : {self.c_phone.get()}\")\r\n self.txtarea.insert(END,f\"\\n ---------------------------------------\")\r\n self.txtarea.insert(END,f\"\\n Product\\t |\\tQTY.\\t|\\tPrice\")\r\n self.txtarea.insert(END,f\"\\n ---------------------------------------\")\r\n\r\n\r\n def bill_area(self):\r\n if self.c_name.get==\"\" or self.c_phone.get()==\"\" :\r\n messagebox.showerror(\"Error \",\"CUSTOMER DETAILS ARE MUST\")\r\n # elif self.c_phone.get() != int(len(10)):\r\n # messagebox.showerror(\"ENTER CORRECT MOBILE NUMBER\")\r\n elif self.cosmetic_price.get()==\"Rs. 0.0\" and self.grocery_price.get()==\"Rs. 0.0\" and self.cold_drink_price.get()==\"Rs. 0.0\" :\r\n messagebox.showerror(\"NO PRODUCTED PURCHASE\")\r\n \r\n\r\n else:\r\n self.welcome_bill()\r\n #*************cosmetics***********\r\n if self.soap.get() != 0:\r\n self.txtarea.insert(END,f\"\\n BATH SOAP\\t\\t{self.soap.get()}\\t\\t{self.c_s_p}\")\r\n if self.face_cream.get() != 0:\r\n self.txtarea.insert(END,f\"\\n FACE CREAM\\t\\t{self.face_cream.get()}\\t\\t{self.c_fc_p}\")\r\n if self.face_wash.get() != 0:\r\n self.txtarea.insert(END,f\"\\n FACE WASH\\t\\t{self.face_wash.get()}\\t\\t{self.c_fw_p}\")\r\n if self.spray.get() != 0:\r\n self.txtarea.insert(END,f\"\\n HAIR SPRAY\\t\\t{self.spray.get()}\\t\\t{self.c_hs_p}\")\r\n if self.gel.get() != 0:\r\n self.txtarea.insert(END,f\"\\n HAIR GEL\\t\\t{self.gel.get()}\\t\\t{self.c_hg_p}\")\r\n if self.lotion.get() != 0:\r\n self.txtarea.insert(END,f\"\\n BODY LOTION\\t\\t{self.lotion.get()}\\t\\t{self.c_bl_p}\")\r\n\r\n #**********drinks*************\r\n if self.maza.get() != 0:\r\n self.txtarea.insert(END,f\"\\n MAZA\\t\\t{self.maza.get()}\\t\\t{self.D_m_p}\")\r\n if self.coke.get() != 0:\r\n self.txtarea.insert(END,f\"\\n COKE\\t\\t{self.coke.get()}\\t\\t{self.D_c_p}\")\r\n if self.frooti.get() != 0:\r\n self.txtarea.insert(END,f\"\\n FROOTI\\t\\t{self.frooti.get()}\\t\\t{self.D_f_p}\")\r\n if self.thumbsup.get() != 0:\r\n self.txtarea.insert(END,f\"\\n THUMBS UP\\t\\t{self.thumbsup.get()}\\t\\t{self.D_t_p}\")\r\n if self.limca.get() != 0:\r\n self.txtarea.insert(END,f\"\\n LIMCA\\t\\t{self.limca.get()}\\t\\t{self.D_l_p}\")\r\n if self.sprite.get() != 0:\r\n self.txtarea.insert(END,f\"\\n SPRITE\\t\\t{self.sprite.get()}\\t\\t{self.D_s_p}\")\r\n\r\n #***********grocery*********\r\n if self.rice.get() != 0:\r\n self.txtarea.insert(END,f\"\\n RICE\\t\\t{self.rice.get()}\\t\\t{self.g_r_p}\")\r\n if self.pulses.get() != 0:\r\n self.txtarea.insert(END,f\"\\n PULSES\\t\\t{self.pulses.get()}\\t\\t{self.g_d_p}\")\r\n if self.food_oil.get() != 0:\r\n self.txtarea.insert(END,f\"\\n FOOD OIL\\t\\t{self.food_oil.get()}\\t\\t{self.g_f_p}\")\r\n if self.wheat.get() != 0:\r\n self.txtarea.insert(END,f\"\\n WHEAT\\t\\t{self.wheat.get()}\\t\\t{self.g_w_p}\")\r\n if self.sugar.get() != 0:\r\n self.txtarea.insert(END,f\"\\n SUGAR\\t\\t{self.sugar.get()}\\t\\t{self.g_s_p}\")\r\n if self.tea.get() != 0:\r\n self.txtarea.insert(END,f\"\\n TEA\\t\\t{self.tea.get()}\\t\\t{self.g_t_p}\")\r\n\r\n \r\n self.txtarea.insert(END,f\"\\n----------------------------------------\")\r\n if self.cosmetic_tax.get()!=\"0.0\":\r\n self.txtarea.insert(END,f\"\\n Cosmetic Tax\\t {self.cosmetic_tax.get()}\")\r\n if self.cold_drink_tax.get()!=\"0.0\":\r\n self.txtarea.insert(END,f\"\\n Cold drinks Tax {self.cold_drink_tax.get()}\")\r\n if self.grocery_tax.get()!=\"0.0\":\r\n self.txtarea.insert(END,f\"\\n Grocery Tax {self.grocery_tax.get()}\")\r\n \r\n self.txtarea.insert(END,f\"\\n----------------------------------------\")\r\n\r\n self.txtarea.insert(END,f\"\\n TOTAL AMOUNT Rs. { str(self.total_bill)}\")\r\n\r\n self.txtarea.insert(END,f\"\\n----------------------------------------\")\r\n self.save_bill()\r\n\r\n\r\n \r\n def save_bill(self):\r\n op = messagebox.askyesno(\"Save BILL \", \"Do you want to save the bill ?\")\r\n if op>0:\r\n self.bill_data = self.txtarea.get('1.0',END)\r\n f1=open(\"Bills/\"+str(self.bill_no.get())+\".txt\",\"w\")\r\n f1.write(self.bill_data)\r\n f1.close()\r\n messagebox.showinfo(\"Saved\",f\"Bill no. : {self.bill_no.get()} saved successfully\")\r\n else :\r\n return\r\n \r\n def find_bill(self):\r\n present=\"no\"\r\n for i in os.listdir(\"D:/BILL_App/Bills\"):\r\n if i.split('.')[0]==self.search_bill.get():\r\n save_path = 'D:/BILL_App/Bills'\r\n name_of_file =str(i)\r\n completeName = os.path.join(save_path, name_of_file) \r\n f1 = open(completeName, \"r\")\r\n self.txtarea.delete('1.0',END)\r\n for d in f1 :\r\n self.txtarea.insert(END,d)\r\n f1.close()\r\n present=\"yes\"\r\n if present == \"no\":\r\n messagebox.showerror(\"ERROR\",\"Invalid Bill Number\")\r\n print(i)\r\n\r\n def clear_data(self):\r\n op = messagebox.askyesno(\"CLEAR\",\"DO YOU WANT TO CLEAR ?\")\r\n if op>0:\r\n # self.root.destroy()\r\n\r\n #**********cosmetic******\r\n self.soap.set(0)\r\n self.face_cream.set(0)\r\n self.face_wash.set(0)\r\n self.spray.set(0)\r\n self.gel.set(0)\r\n self.lotion.set(0)\r\n #***********GROCERY************\r\n self.rice.set(0)\r\n self.food_oil.set(0)\r\n self.pulses.set(0)\r\n self.wheat.set(0)\r\n self.sugar.set(0)\r\n self.tea.set(0)\r\n #*********COLD DRINKS**********\r\n self.maza.set(0)\r\n self.coke.set(0)\r\n self.frooti.set(0)\r\n self.thumbsup.set(0)\r\n self.limca.set(0)\r\n self.sprite.set(0)\r\n\r\n #********Total product price & Tax********\r\n self.cosmetic_price.set(\"\")\r\n self.grocery_price.set(\"\")\r\n self.cold_drink_price.set(\"\")\r\n\r\n self.cosmetic_tax.set(\"\")\r\n self.grocery_tax.set(\"\")\r\n self.cold_drink_tax.set(\"\")\r\n\r\n #*********customer************\r\n self.c_name.set(\"\")\r\n self.c_phone.set(\"\")\r\n\r\n self.bill_no.set(\"\")\r\n x=random.randint(1000,9999)\r\n self.bill_no.set(str(x))\r\n\r\n self.search_bill.set(\"\")\r\n self.welcome_bill(self)\r\n \r\n def exit_app(self):\r\n op = messagebox.askyesno(\"EXIT\",\"DO YOU WANT TO EXIT ?\")\r\n if op>0:\r\n self.root.destroy()\r\n\r\nroot=Tk()\r\nObj = Bill_app(root)\r\nroot.mainloop()\r\n","sub_path":"bill.py","file_name":"bill.py","file_ext":"py","file_size_in_byte":22927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"59683082","text":"#!/usr/bin/env python3\n\nfrom dotenv import load_dotenv\nimport loft_hvac\nimport os\n\nMEETUP_KEY = None\nMEETUP_SECRET = None\nMEETUP_REDIRECT_URI = None\nSLACK_APIKEY = None\nENVIRONMENT = os.getenv('ENVIRONMENT')\nBASE_FOLDER = os.getenv('BASE_FOLDER')\n\nload_dotenv(dotenv_path=BASE_FOLDER + '/.env.local')\n\nif ENVIRONMENT == 'dev':\n MEETUP_KEY = os.getenv('DEV_MEETUP_KEY')\n MEETUP_SECRET = os.getenv('DEV_MEETUP_SECRET')\n MEETUP_REDIRECT_URI = os.getenv('DEV_MEETUP_REDIRECT_URI')\n SLACK_APIKEY = os.getenv('DEV_SLACK_APIKEY')\nelif ENVIRONMENT == 'stage':\n MEETUP_KEY = os.getenv('STAGE_MEETUP_KEY')\n MEETUP_SECRET = os.getenv('STAGE_MEETUP_SECRET')\n MEETUP_REDIRECT_URI = os.getenv('STAGE_MEETUP_REDIRECT_URI')\n SLACK_APIKEY = os.getenv('STAGE_SLACK_APIKEY')\nelif ENVIRONMENT == 'prod':\n MEETUP_KEY = os.getenv('PROD_MEETUP_KEY')\n MEETUP_SECRET = os.getenv('PROD_MEETUP_SECRET')\n MEETUP_REDIRECT_URI = os.getenv('PROD_MEETUP_REDIRECT_URI')\n SLACK_APIKEY = os.getenv('PROD_SLACK_APIKEY')\n\nloft_hvac.initialize()\nloft_hvac.enable_secrets_engine()\n\nloft_hvac.write_secret(\n path='secret/meetup/key',\n secret=dict(key=MEETUP_KEY),\n mount_point='secret'\n)\n\nloft_hvac.write_secret(\n path='secret/meetup/secret',\n secret=dict(key=MEETUP_SECRET),\n mount_point='secret'\n)\n\nloft_hvac.write_secret(\n path='secret/meetup/redirect_uri',\n secret=dict(key=MEETUP_REDIRECT_URI),\n mount_point='secret'\n)\n\nloft_hvac.write_secret(\n path='secret/slack/apikey',\n secret=dict(key=SLACK_APIKEY),\n mount_point='secret'\n)\n","sub_path":"scripts/vault-init.py","file_name":"vault-init.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"250518291","text":"#!/usr/bin/env python\n\n'''\nsimple shortcut for running nosetests via python\nreplacement for *.bat or *.sh wrappers\n'''\n\nimport sys\nimport logging\nfrom os.path import abspath, dirname\n\nimport nose\n\nimport src\n\nimport test_resources\n\n\ndef run_all(argv=None):\n sys.exitfunc = lambda msg = 'Process shutting down...': sys.stderr.write(msg + '\\n')\n\n argv = (set(argv) | {\n '--where=%s' % dirname(abspath(test_resources.__file__)),\n '--with-gae',\n '--gae-application=%s' % dirname(abspath(src.__file__)),\n '--verbose',\n '--without-sandbox',\n '--no-log-capture'\n }) - {'./run_tests.py'}\n\n logging.debug('Running tests with arguments: %r' % argv)\n\n nose.run_exit(\n argv=list(argv),\n defaultTest=abspath(dirname(__file__)),\n )\n\nif __name__ == '__main__':\n run_all(sys.argv)\n","sub_path":"test_resources/run_tests.py","file_name":"run_tests.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"182991006","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed May 18 10:06:58 2016\r\n\r\n@author: Shuo\r\n\"\"\"\r\n\r\n\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\n\r\n#import data and some basic operations\r\nurl = 'https://raw.githubusercontent.com/cs109/2014_data/master/mtcars.csv'\r\nmtcars = pd.read_csv(url, sep = ',', index_col=0)\r\nmtcars.head()\r\nmtcars.shape \r\nmtcars.columns\r\nmtcars.values\r\nmtcars[25:]\r\nmtcars.index\r\nmtcars.ix['Maserati Bora']\r\nmtcars.describe()\r\n(mtcars.mpg >= 20).any()\r\n(mtcars > 0).all()\r\n\r\n#histograms\r\nmtcars['mpg'].hist()\r\nplt.title('Distribution of MPG')\r\nplt.xlabel('Miles Per Gallon')\r\n\r\n#scatterplots\r\nplt.plot(mtcars.cyl, mtcars.mpg, 'o')\r\nplt.xlim(3, 9)\r\nplt.xlabel('Cylinders')\r\nplt.ylabel('MPG')\r\nplt.title('Relationship between cylinders and MPG')\r\n#\r\nplt.plot(mtcars.hp, mtcars.mpg, 'o')\r\nplt.xlabel('Horsepower')\r\nplt.ylabel('MPG')\r\nplt.title('Relationship between horsepower and MPG')\r\n\r\n\r\n#scatter matrix: show scatter plots off diagonal and show pdf on diagonal\r\nfrom pandas.tools.plotting import scatter_matrix\r\nscatter_matrix(mtcars[['mpg', 'hp', 'cyl']], \r\n figsize = (10, 6), alpha = 1, diagonal='kde')\r\n","sub_path":"panda_demo5.py","file_name":"panda_demo5.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"90481048","text":"import numpy as np\nfrom PIL import Image as image\nfrom sklearn.cluster import KMeans #加载Kmeans算法\n\n\ndef RGB2BlackWhite(filename):\n im = image.open(filename)\n (w, h) = im.size\n R = 0\n G = 0\n B = 0\n\n for x in range(w):\n for y in range(h):\n pos = (x, y)\n rgb = im.getpixel(pos)\n (r, g, b) = rgb\n R = R + r\n G = G + g\n B = B + b\n\n rate1 = R * 1000 / (R + G + B)\n rate2 = G * 1000 / (R + G + B)\n rate3 = B * 1000 / (R + G + B)\n\n for x in range(w):\n for y in range(h):\n pos = (x, y)\n rgb = im.getpixel(pos)\n (r, g, b) = rgb\n n = r * rate1 / 1000 + g * rate2 / 1000 + b * rate3 / 1000\n # print \"n:\",n\n if n >= 170:\n im.putpixel(pos, (255, 255, 255))\n else:\n im.putpixel(pos, (0, 0, 0))\n\n im.save(\"blackwhite.png\")\n\nif __name__ == '__main__':\n RGB2BlackWhite('/Users/haodexian/PycharmProjects/chinese_rec/ocr/dataset/test/02484/0.png')\n\n# def loadData(filePath):\n# f = open(filePath,'rb') #以二进制形式打开文件\n# data= []\n# img =image.open(f)#以列表形式返回图片像素值\n# m,n =img.size #获得图片大小\n# for i in range(m):\n# for j in range(n):\n# #将每个像素点RGB颜色处理到0-1范围内\n# x,y,z =img.getpixel((i,j))\n# #将颜色值存入data内\n# data.append([x/256.0,y/256.0,z/256.0])\n# f.close()\n# #以矩阵的形式返回data,以及图片大小\n# return np.mat(data),m,n\n#\n# imgData,row,col =loadData('/Users/haodexian/Desktop/00836的副本.jpg')#加载数据\n# km=KMeans(n_clusters=2)\n# label =km.fit_predict(imgData)\n# label=label.reshape([row,col])\n# pic_new = image.new(\"L\",(row,col))\n# for i in range(row):\n# for j in range(col):\n# if label[i][j] == 0:\n# pic_new.putpixel((i,j),255)\n# else:\n# pic_new.putpixel((i,j),0)\n# pic_new.save(\"result-bull-4.jpg\",\"JPEG\")\n","sub_path":"reviews/utils/color_Kmeans.py","file_name":"color_Kmeans.py","file_ext":"py","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"103330396","text":"def hasSingleCycle(array):\n for i in range(0, len(array)):\n visitedNodes = {}\n idx = i\n visitedNodes[idx] = True\n while len(visitedNodes) <= len(array):\n idx += array[idx]\n if idx > len(array):\n idx = idx % len(array) + 1\n elif idx < 0:\n idx = len(array) - abs(idx % len(array))\n if idx in visitedNodes:\n break\n else:\n visitedNodes[idx] = True\n return True\n return False\n \n\nprint(hasSingleCycle([2, 3, 1, -4, -4, 2]))\n\ndef hasSingleCycleImproved(array):\n numElementsVisited = 0\n currentIdx = 0\n while numElementsVisited < len(array):\n if numElementsVisited > 0 and currentIdx == 0:\n return False\n numElementsVisited += 1\n currentIdx = getNextIdx(currentIdx, array)\n return currentIdx == 0\n\ndef getNextIdx(currentIdx, array):\n jump = array[currentIdx]\n nextIdx = (currentIdx + jump) % len(array)\n return nextIdx if nextIdx >= 0 else nextIdx + len(array)\n\nprint(hasSingleCycleImproved([2, 3, 1, -4, -4, 2]))","sub_path":"medium/hasSingleCycle.py","file_name":"hasSingleCycle.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"555570641","text":"# 2018-07-29\n# Waizung Taam\n# ZBoard\n# ZBoard is a platform for everyone to post messages anonymously.\nfrom flask import Flask, render_template, redirect, url_for, request, \\\n current_app, g\nimport sqlite3\nimport re\nfrom jinja2 import evalcontextfilter, Markup, escape\n\napp = Flask(__name__)\n\ndef get_db():\n if 'db' not in g:\n g.db = sqlite3.connect(\n 'zboard.db', detect_types=sqlite3.PARSE_DECLTYPES)\n g.db.row_factory = sqlite3.Row\n return g.db\n\ndef new_db(app):\n with app.app_context():\n db = get_db()\n with current_app.open_resource('schema.sql') as f:\n db.executescript(f.read().decode())\n\n@app.teardown_appcontext\ndef close_db(e=None):\n db = g.pop('db', None)\n if db is not None:\n db.close()\n\n@app.template_filter()\n@evalcontextfilter\ndef nl2br(eval_ctx, value):\n result = u''.join(u'%s
' % p.replace('\\n', Markup('
'))\n for p in re.compile(r'(?:\\r\\n|\\r|\\n){2,}').split(escape(value)))\n if eval_ctx.autoescape:\n result = Markup(result)\n return result\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n content = request.form['text']\n if content:\n db = get_db()\n db.execute('INSERT INTO post (content) VALUES (?)', (content,));\n db.commit()\n return redirect(url_for('index'))\n posts = get_db().execute(\n 'SELECT content FROM post ORDER BY id DESC').fetchall()\n posts = [post['content'] for post in posts]\n return render_template('index.html', posts=posts)\n\nif __name__ == '__main__':\n # new_db(app)\n app.run(host='0.0.0.0', port=5001, debug=True)\n","sub_path":"Flask/zboard/zboard.py","file_name":"zboard.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"395109838","text":"import numpy as np\nimport os\nimport six.moves.urllib as urllib\nimport sys\nimport tarfile\nimport tensorflow as tf\nimport zipfile\nimport json\nimport time\nimport glob\nimport re\n\nfrom io import StringIO\nfrom PIL import Image, ImageFont\n\nimport matplotlib.pyplot as plt\n\nfrom utils import visualization_utils as vis_util\nfrom utils import label_map_util\n\nfrom multiprocessing.dummy import Pool as ThreadPool\n\nMAX_NUMBER_OF_BOXES = 10\nMINIMUM_CONFIDENCE = 0.2\n\nPATH_TO_LABELS = 'build_models/test17/label_map.pbtxt'\nPATH_TO_TEST_IMAGES_DIR = 'test_images'\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=sys.maxsize, use_display_name=True)\nCATEGORY_INDEX = label_map_util.create_category_index(categories)\n\n# Path to frozen detection graph. This is the actual model that is used for the object detection.\nMODEL_NAME = 'build_models/test17/export_2'\nPATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'\n\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\ndef detect_objects(image_path):\n image = Image.open(image_path)\n image_np = load_image_into_numpy_array(image)\n image_np_expanded = np.expand_dims(image_np, axis=0)\n\n (boxes, scores, classes, num) = sess.run([detection_boxes, detection_scores, detection_classes, num_detections], feed_dict={image_tensor: image_np_expanded})\n\n 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 min_score_thresh=MINIMUM_CONFIDENCE,\n use_normalized_coordinates=True,\n line_thickness=8)\n fig = plt.figure()\n #fig.set_size_inches(16, 9)\n ax = plt.Axes(fig, [0., 0., 1., 1.])\n ax.set_axis_off()\n fig.add_axes(ax)\n\n plt.imshow(image_np, aspect = 'auto')\n fname = image_path.split('/')[1]\n plt.savefig('output/{}'.format(fname), dpi = 300) #org dpi 62\n plt.close(fig)\n\n\n # Get image height width\n (im_width,im_height) = image.size\n\n #image.filename\n slice_imgpath = re.findall(\"(?<=\\/).*(?=\\.)\", image.filename)\n img_name = slice_imgpath[0]\n print(img_name)\n '''for i in scores[0]:\n print(i)'''\n\n '''for i in range(0,len(boxes[0])):\n if scores[0][i] > MINIMUM_CONFIDENCE:\n ymin = boxes[0][i][0]\n xmin = boxes[0][i][1]\n ymax = boxes[0][i][2]\n xmax = boxes[0][i][3]\n (xminn, xmaxx, yminn, ymaxx) = (xmin * im_width, xmax * im_width, ymin * im_height, ymax * im_height)\n\n #crop img\n cropped_image_tensor = tf.image.crop_to_bounding_box(image,int(yminn),int(xminn),int(ymaxx - yminn),int(xmaxx - xminn))\n output_image = tf.image.encode_jpeg(cropped_image_tensor)\n file_name = tf.constant('./output/cropped_images/'+img_name+'_crop_'+str(i)+'.jpg')\n file = tf.write_file(file_name, output_image)\n sess.run(file)'''\n\n\n# TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image-{}.jpg'.format(i)) for i in range(1, 4) ]\nTEST_IMAGE_PATHS = glob.glob(os.path.join(PATH_TO_TEST_IMAGES_DIR,'*.jpg'))\n\n# Load model into memory\nprint('Loading model...')\ndetection_graph = tf.Graph()\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\nprint('detecting...')\nwith detection_graph.as_default():\n with tf.Session(graph=detection_graph) as sess:\n image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\n detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')\n detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')\n num_detections = detection_graph.get_tensor_by_name('num_detections:0')\n\n for image_path in TEST_IMAGE_PATHS:\n detect_objects(image_path)\n\n","sub_path":"tensorflow_api/object_detection/object_detection_runner.py","file_name":"object_detection_runner.py","file_ext":"py","file_size_in_byte":4267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"146316688","text":"##VR1 e VL1 sono le coordinate sul piano dei due vertici più in basso\n##VR2 e VL2 sono le coordinate sul piano dei due vertici più in alto\n##I vertici VR1 e VR2 devono essere allineati, stessa cosa per i vertici VL\n##startH è l'altezza iniziale del primo gradino, endH è l'altezza a cui deve arrivare l'ultimo gradino\n##piena: se TRUE ciascuno dei gradini viene estruso a partire da startH, se FALSE viene preservato lo spazio del sottoscala\n\ndef generaScalaDritta(vR1,vR2,vL1,vL2,startH,endH,nGradini,piena):\n\tdRX = -(vR1[0] - vR2[0])/nGradini\n\tdRY = -(vR1[1] - vR2[1])/nGradini\n\tdLX = -(vL1[0] - vL2[0])/nGradini\n\tdLY = -(vL1[1] - vL2[1])/nGradini\n\tdH = (endH-startH)/nGradini\n\tVR=[]\n\tVL=[]\n\tfor k in range(nGradini+1):\n\t\tVR = VR + [vR1]\n\t\tvR1 = SUM([vR1,[dRX,dRY]])\n\tfor k in range(nGradini+1):\n\t\tVL = VL + [vL1]\n\t\tvL1 = SUM([vL1,[dLX,dLY]])\n\n\tmodels = []\n\tpatterns = []\n\n\tfor k in range(nGradini):\n\t\tV = [VR[k]]+[VR[k+1]]+[VL[k]]+[VL[k+1]]\n\t\tFV = [[0,1,2,3]]\n\t\tmodels = models + [(V,FV)]\n\t\tif piena:\n\t\t\tpatterns = patterns + [[-startH,dH*k,dH]]\n\t\telse:\n\t\t\tif k==0:\n\t\t\t\tpatterns = patterns + [[-startH,dH]]\n\t\t\telse:\n\t\t\t\tpatterns = patterns +[[-startH,-dH*(k-1),2*dH]]\n\n\tscale = []\n\n\tfor k in range(nGradini):\n\t\tscale.append(larModelProduct([models[k],larQuote1D(patterns[k])]))\n\n\tPOLS=[]\n\n\tfor k in range(nGradini):\n\t\tPOLS = POLS + MKPOLS(scale[k])\n\t\t\n\treturn POLS","sub_path":"266319/models/funScalaDritta.py","file_name":"funScalaDritta.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"556618003","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport time\r\n\r\ndx = 1/40 #1/10, 1/20 e 1/40\r\nx = np.arange(-1, 3+dx, dx)\r\na = 1\r\nnx = len(x)\r\nu0x = np.zeros(nx)\r\nvn = np.zeros(nx)\r\nLambda =1.6 #0.8 e 1.6\r\ndt = Lambda*dx\r\nt = np.arange(0, 2.4+dt, dt)\r\nnt = len(t)\r\n\r\nfor i in range(0,nx):\r\n if abs(x[i]) <= 0.5:\r\n u0x[i] = (np.cos(np.pi*x[i]))**2\r\n else:\r\n u0x[i] = 0\r\n \r\nvn_old = np.copy(u0x)\r\n\r\nj = 0\r\nwhile j <= nt:\r\n for k in range(1,nx-1):\r\n # com f = 0\r\n vn[k] = (0.5)*(vn_old[k+1] + vn_old[k-1]) - ((a*Lambda)/(1 + ((a*Lambda)**2)))*(vn_old[k+1] - vn_old[k-1]) \r\n \r\n plt.clf()\r\n plt.plot(x,u0x,'r--', x,vn, 'b-')\r\n plt.ylabel('U (x, t)')\r\n plt.xlabel('x')\r\n plt.grid()\r\n plt.title('Lax-Friedrichs scheme')\r\n plt.show()\r\n time.sleep(0.5)\r\n vn_old = np.copy(vn)\r\n j += 1","sub_path":"ex_Strikwerda_1_6_1.py","file_name":"ex_Strikwerda_1_6_1.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"555153459","text":"import bisect\n\nA, B, Q = map(int, input().split())\nINF = 10**18\nS = [-INF] + [int(input()) for i in range(A)] + [INF]\nT = [-INF] + [int(input()) for i in range(B)] + [INF]\nX = [int(input()) for i in range(Q)]\n\n\nfor x in X:\n d = float(\"inf\")\n i = bisect.bisect_right(S, x)\n j = bisect.bisect_right(T, x)\n for s in [S[i-1], S[i]]:\n for t in [T[j-1], T[j]]:\n d1 = abs(s-x) + abs(t-s)\n d2 = abs(t-x) + abs(t-s)\n d = min(d, d1, d2)\n print(d)\n","sub_path":"Python_codes/p03112/s091877631.py","file_name":"s091877631.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"98995081","text":"import pymysql\r\n\r\nfrom configmgt import ReadConfig\r\n\r\nFILENAME = '51reboot.ini'\r\n\r\ndef connnet():\r\n cfg, ok = ReadConfig(FILENAME, 'rebootdb')\r\n if not ok:\r\n return cfg, False\r\n try:\r\n # conn = pymysql.connect(\r\n # host = \"10.0.2.15\",\r\n # user = \"monkey\",\r\n # password= \"123456\",\r\n # database = \"ops\",\r\n # port = 3306,\r\n # )\r\n conn = pymysql.connect(\r\n host=cfg['host'],\r\n user=cfg['username'],\r\n password=cfg['password'],\r\n database=cfg['database'],\r\n port=int(cfg['port']),\r\n )\r\n except:\r\n return None\r\n return conn\r\n\r\ndef insert(sql):\r\n conn = connnet()\r\n if not conn:\r\n return \"conn db fail\", False\r\n cur = conn.cursor()\r\n\r\n try:\r\n cur.execute(sql)\r\n conn.commit()\r\n return 'Insert succ.', True\r\n except Exception as e:\r\n conn.rollback()\r\n return e, False\r\n finally:\r\n cur.close()\r\n conn.close()\r\n\r\ndef update(sql):\r\n conn = connnet()\r\n if not conn:\r\n return \"conn db fail\", False\r\n cur = conn.cursor()\r\n\r\n try:\r\n cur.execute(sql)\r\n print(cur.rowcount)\r\n if cur.rowcount == 0:\r\n return 'Update fail', False\r\n\r\n conn.commit()\r\n return 'Update succ.', True\r\n except Exception as e:\r\n conn.rollback()\r\n return e, False\r\n finally:\r\n cur.close()\r\n conn.close()\r\n\r\ndef select(sql):\r\n conn = connnet()\r\n if not conn:\r\n return \"conn db fail\", False\r\n cur = conn.cursor()\r\n\r\n try:\r\n cur.execute(sql)\r\n except Exception as e:\r\n return e, False\r\n else:\r\n rows = cur.fetchall()\r\n # 增加一行如果查询为空的情况, 如果为空,则返回查询失败\r\n if len(rows) == 0:\r\n return '', False\r\n else:\r\n return rows, True\r\n finally:\r\n cur.close()\r\n conn.close()\r\n\r\ndef delete(sql):\r\n conn = connnet()\r\n if not conn:\r\n return \"conn db fail\", False\r\n cur = conn.cursor()\r\n\r\n try:\r\n cur.execute(sql)\r\n print(cur.rowcount)\r\n if cur.rowcount == 0:\r\n return 'Delete fail', False\r\n\r\n conn.commit()\r\n return 'Insert succ.', True\r\n except Exception as e:\r\n conn.rollback()\r\n return e, False\r\n finally:\r\n cur.close()\r\n conn.close()\r\n\r\n\r\n\r\ndef main():\r\n\r\n # for i in range(10, 30):\r\n # sql = '''insert into users(username,age,tel,email) values('monkey{}', 12,'132xxx','monkey2@51reboot.com');'''.format(i)\r\n # insertMsg, ok = insert(sql)\r\n # if not ok:\r\n # print(insertMsg)\r\n\r\n # sql = '''delete from users where username = 'monkey10';'''\r\n # deleteMsg, ok = delete(sql)\r\n # if not ok:\r\n # print(deleteMsg)\r\n # sql = '''update users set age = 20 where username = 'monkey11';'''\r\n # msg, ok = update(sql)\r\n # if not ok:\r\n # print(msg)\r\n\r\n sql = '''select * from users;'''\r\n result, ok = select(sql)\r\n print(result)\r\n if not ok:\r\n print(result)\r\n else:\r\n fields = ['id', 'username', 'age', 'tel', 'email']\r\n # for i in result:\r\n # print(dict(zip(fields, i)))\r\n retdata = [ dict(zip(fields, i)) for i in result ]\r\n\r\n import json\r\n print(json.dumps(retdata, indent=8))\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"lesson05/homework/dbutils.py","file_name":"dbutils.py","file_ext":"py","file_size_in_byte":3480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"41828030","text":"from dash import html, dcc, callback, Output, Input, State, ALL, MATCH, ctx\nimport datetime\n\nfrom aegis.visor import funcs\nfrom aegis.help.container import Container\nimport subprocess\n\nSELECTION = set()\n\n\n@callback(\n Output({\"type\": \"delete-simulation-button\", \"index\": MATCH}, \"children\"),\n Input({\"type\": \"delete-simulation-button\", \"index\": MATCH}, \"n_clicks\"),\n State({\"type\": \"delete-simulation-button\", \"index\": MATCH}, \"value\"),\n prevent_initial_call=True,\n)\n@funcs.print_function_name\ndef delete_simulation(_, filename):\n config_path = funcs.get_config_path(filename)\n sim_path = config_path.parent / filename\n\n if filename in SELECTION:\n SELECTION.remove(filename)\n\n subprocess.run([\"rm\", \"-r\", sim_path], check=True)\n subprocess.run([\"rm\", config_path], check=True)\n return \"deleting\"\n\n\n# @callback(\n# Output(\"result-section\", \"children\", allow_duplicate=True),\n# [Input(\"testo\", \"n_clicks\")],\n# [State(\"result-section\", \"children\")],\n# prevent_initial_call=True,\n# )\n# def test(_, children):\n# # children += html.P(\"asdf\")\n# children.append(html.P(\"asdfjkwerj\"))\n# return children\n\n\n@callback(\n Output(\"result-section\", \"children\"),\n Input(\"result-view-button\", \"n_clicks\"),\n Input({\"type\": \"delete-simulation-button\", \"index\": ALL}, \"children\"),\n prevent_initial_call=True,\n)\n@funcs.print_function_name\ndef refresh_result_section(*_):\n paths = funcs.get_sim_paths()\n containers = [Container(path) for path in paths]\n table_elements = [\n # html.Button(id=\"testo\", children=\"testo\"),\n html.Tr(\n [\n html.Th(\n \"ID\", style={\"padding-left\": \"1.3rem\", \"padding-right\": \"0.8rem\"}\n ),\n html.Th(\"DISPLAY\"),\n html.Th(\"CREATED\"),\n # html.Th(\"edited\"),\n html.Th(\"FINISHED\"),\n html.Th(\"EXTINCT\"),\n html.Th(\"ETA\"),\n # html.Th(\"stage\"),\n # html.Th(\"STAGE PER MINUTE\"),\n html.Th(\"FILEPATH\"),\n html.Th(\"DELETE\", style={\"padding-right\": \"1rem\"}),\n ],\n ),\n ]\n\n for container in containers:\n if len(container.get_log()) > 0:\n logline = container.get_log().iloc[-1].to_dict()\n else:\n logline = {\"ETA\": None, \"stage\": None, \"stg/min\": None}\n input_summary = container.get_input_summary()\n output_summary = container.get_output_summary()\n\n if output_summary is None:\n status = [\"not finished\", \"not extinct\"]\n elif output_summary[\"extinct\"]:\n status = [\"finished\", \"extinct\"]\n else:\n status = [\"finished\", \"not extinct\"]\n\n time_of_creation = (\n datetime.datetime.fromtimestamp(input_summary[\"time_start\"]).strftime('%Y-%m-%d %H:%M')\n if input_summary\n else None\n )\n\n time_of_finishing = (\n datetime.datetime.fromtimestamp(input_summary[\"time_start\"]).strftime('%Y-%m-%d %H:%M')\n if output_summary\n else None\n\n )\n # time_of_edit = datetime.datetime.fromtimestamp(\n # container.paths[\"log\"].stat().st_mtime\n # )\n\n element = html.Tr(\n children=[\n html.Td(\n container.basepath.stem,\n style={\"padding-left\": \"1.3rem\", \"padding-right\": \"0.8rem\"},\n ),\n html.Td(\n children=[\n html.Button(\n children=\"display\",\n id={\n \"type\": \"result-checklist\",\n \"index\": container.basepath.stem,\n },\n className=\"checklist\"\n if container.basepath.stem not in SELECTION\n else \"checklist checked\",\n # id={\n # \"type\": \"result-checklist\",\n # \"index\": container.basepath.stem,\n # },\n # options=[{\"label\": \"\", \"value\": \"y\"}],\n # value=[\"y\"] if container.basepath.stem in SELECTION else [],\n ),\n # dcc.Checklist(\n # id={\n # \"type\": \"result-checklist\",\n # \"index\": container.basepath.stem,\n # },\n # options=[{\"label\": \"\", \"value\": \"y\"}],\n # value=[\"y\"] if container.basepath.stem in SELECTION else [],\n # ),\n ]\n ),\n html.Td(html.P(time_of_creation)),\n # date created\n # html.Td(html.P(time_of_edit)),\n html.Td(html.P(time_of_finishing)),\n html.Td(html.P(status[1])),\n html.Td(html.P(logline[\"ETA\"] if time_of_finishing is None else \" \")),\n # html.Td(html.P(logline[\"stage\"])),\n # html.Td(html.P(logline[\"stg/min\"])),\n html.Td(html.P(str(container.basepath))),\n html.Td(\n html.Button(\n \"delete\",\n id={\n \"type\": \"delete-simulation-button\",\n \"index\": container.basepath.stem,\n },\n value=container.basepath.stem,\n ),\n style={\"padding-right\": \"1rem\"},\n ),\n ],\n )\n table_elements.append(element)\n\n return html.Table(children=table_elements, className=\"result-table\")\n\n\n@callback(\n Output({\"type\": \"result-checklist\", \"index\": MATCH}, \"className\"),\n Input({\"type\": \"result-checklist\", \"index\": MATCH}, \"n_clicks\"),\n prevent_initial_call=True,\n)\ndef update_selection(n_clicks):\n sim = ctx.triggered_id[\"index\"]\n if sim not in SELECTION:\n SELECTION.add(sim)\n return \"checked checklist\"\n else:\n SELECTION.remove(sim)\n return \"checklist\"\n","sub_path":"src/aegis/visor/callbacks_results.py","file_name":"callbacks_results.py","file_ext":"py","file_size_in_byte":6297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"389834398","text":"my_dic = {}\n\ndef recursion(N, num):\n if num == 1:\n my_dic[1] = set([N])\n return set([N])\n if num in my_dic:\n return my_dic[num]\n num_list = set([N * int('1'*num)])\n for i in range(1, num // 2 + 1):\n for a in recursion(N, i):\n for b in recursion(N, num-i):\n num_list.add(a + b)\n num_list.add(a - b)\n num_list.add(b - a)\n num_list.add(a * b)\n if a != 0:\n num_list.add(b // a)\n if b != 0:\n num_list.add(a // b)\n my_dic[num] = num_list\n return num_list\n\ndef solution(N, number):\n for answer in range(1, 9):\n if number in recursion(N, answer):\n return answer\n return -1","sub_path":"Programmers/Lv3_N으로 표현.py","file_name":"Lv3_N으로 표현.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"484690949","text":"#!usr/bin/env python\n# Kononov Sergey BD-21\n\nfrom docreader import *\nsys.path.insert(0, 'archive')\nfrom archive import index_data\nimport os, re, shutil\n\n# Create Data directory\nif not os.access('Data', os.F_OK):\n os.mkdir('Data')\n\n# Clear existance data\nfile_list = filter(lambda filename: re.match(r'.*\\.pckl', filename),\n os.listdir('Data'))\nmap(lambda filename: os.remove('Data/' + filename), file_list)\n\n# Parse command line arguments and index data\nif __name__ == '__main__':\n archivation_type = parse_command_line().archivation\n reader = DocumentStreamReader(parse_command_line().files)\n index_data(reader, archivation_type)\n","sub_path":"to_send/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"350936553","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division, unicode_literals\n\nimport io\n\nfrom .. import config\nfrom ..htmlhelpers import findAll, textContent, removeNode, E, addClass, appendChild, clearContents\nfrom ..messages import *\n\ndef processWptElements(doc):\n\ttestData = loadTestData(doc)\n\tpathPrefix = doc.md.wptPathPrefix\n\tif pathPrefix is not None and not pathPrefix.endswith(\"/\"):\n\t\tpathPrefix += \"/\"\n\n\t# elements\n\twptElements = findAll(\"wpt\", doc)\n\tif not wptElements:\n\t\treturn\n\tseenTestNames = set()\n\tfor el in wptElements:\n\t\ttestNames = testNamesFromEl(el, pathPrefix=pathPrefix)\n\t\tfor testName in testNames:\n\t\t\tif testName not in testData:\n\t\t\t\tdie(\"Couldn't find WPT test '{0}' - did you misspell something?\", testName, el=el)\n\t\t\t\tcontinue\n\t\t\tseenTestNames.add(testName)\n\t\tcreateHTML(doc, el, testNames)\n\n\t# elements\n\twptRestElements = findAll(\"wpt-rest\", doc)\n\tif len(wptRestElements) > 1:\n\t\tdie(\"Only one element allowed per document, you have {0}.\", len(wptRestElements))\n\t\twptRestElements = wptRestElements[0:1]\n\tif len(wptRestElements) == 1:\n\t\tif pathPrefix is None:\n\t\t\tdie(\"Can't use without a WPT Path Prefix metadata.\")\n\t\t\treturn\n\t\tprefixedNames = [p for p in testData if p.startswith(pathPrefix) and p not in seenTestNames]\n\t\tif len(prefixedNames) == 0:\n\t\t\tdie(\"Couldn't find any tests with the path prefix '{0}'.\", pathPrefix)\n\t\t\treturn\n\t\tcreateHTML(doc, wptRestElements[0], prefixedNames)\n\n\n\ndef createHTML(doc, blockEl, testNames):\n\tif doc.md.wptDisplay == \"none\":\n\t\tremoveNode(blockEl)\n\telif doc.md.wptDisplay == \"inline\":\n\t\tblockEl.tag == \"ul\"\n\t\taddClass(blockEl, \"wpt-tests-block\")\n\t\tclearContents(blockEl)\n\t\tfor testName in testNames:\n\t\t\t_,_,lastNameFragment = testName.rpartition(\"/\")\n\t\t\tsingleTestEl = E.li({\"class\": \"wpt-test\"},\n\t\t\t\tE.a({\"title\": testName, \"href\": \"http://w3c-test.org/\"+testName}, \"Test: \" + lastNameFragment),\n\t\t\t\t\" \",\n\t\t\t\tE.a({\"href\": \"view-source:w3c-test.org/\"+testName}, E.small(\"(source)\")))\n\t\t\tappendChild(blockEl, singleTestEl)\n\telse:\n\t\tdie(\"Programming error, uncaught WPT Display value in createHTML.\")\n\n\ndef testNamesFromEl(el, pathPrefix=None):\n\ttestNames = []\n\tfor name in [x.strip() for x in textContent(el).split(\"\\n\")]:\n\t\tif name == \"\":\n\t\t\tcontinue\n\t\tif pathPrefix is None:\n\t\t\ttestNames.append(name)\n\t\telse:\n\t\t\tif name.startswith(\"/\"):\n\t\t\t\ttestPath = pathPrefix + name[1:]\n\t\t\telse:\n\t\t\t\ttestPath = pathPrefix + name\n\t\t\ttestNames.append(testPath)\n\treturn testNames\n\n\ndef prefixPlusPath(prefix, path):\n\tif prefix.endswith(\"/\") and path.startswith(\"/\"):\n\t\treturn prefix[:-1] + path\n\telif not prefix.endswith(\"/\") and not path.startswith(\"/\"):\n\t\treturn prefix + \"/\" + path\n\telse:\n\t\treturn prefix + path\n\n\ndef loadTestData(doc):\n\treturn set(x.strip() for x in config.retrieveDataFile(\"wpt-tests.txt\", quiet=True).readlines())\n\n\ndef xor(a, b):\n\treturn bool(a) != bool(b)\n","sub_path":"bikeshed/wpt/wptElement.py","file_name":"wptElement.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"612707730","text":"# 공유기 설치\n# https://www.acmicpc.net/problem/2110\nimport sys\n\nsys.stdin = open('../result/input.txt', 'r')\nsys.stdout = open('../result/output.txt', 'w')\n\nif __name__ == '__main__':\n N, C = map(int, input().split())\n\n home = []\n for _ in range(N):\n data = int(input())\n home.append(data)\n\n home.sort()\n start = abs(home[1] - home[0]) # min\n end = abs(home[-1] - home[0]) # max\n\n result = 0\n while start <= end:\n gap = (end + start) // 2\n\n # 공유기를 놓아 본다\n cnt = 1\n val = home[0]\n for idx in range(1, len(home)):\n if home[idx] >= val + gap:\n val = home[idx]\n cnt += 1\n if cnt >= C:\n result = gap\n start = gap+1\n elif cnt < C:\n end = gap-1\n else:\n start = gap+1\n\n print(result)\n\n\n","sub_path":"algorithm/acmicpc.net/2110.py","file_name":"2110.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"415675985","text":"from tkinter import *\nimport numpy as np\nimport matplotlib.pyplot as plt\nc=0\n\ndef function(x,y):\n #print(taxa)\n eq=taxa*y\n return eq\n\ndef calcular():\n h=0.1 \n c =int((s/h)+1)\n x = np.zeros(c)\n y = np.zeros(c)\n x[0]=0\n y[0]=pvi\n print(x[0],y[0])\n for i in np.arange(1,c):\n y[i]=y[i-1]+(function(x[i-1],y[i-1]))*h\n x[i]=x[i-1]+h\n print(x[i],y[i])\n plt.title('Empréstimos Bancários')\n plt.xlabel('Tempo(meses)')\n plt.ylabel('Saldo(reais)')\n plt.plot(x,y)\n plt.show()\n \n \ndef bt_click():\n z=float(ed.get())\n global pvi\n global taxa\n taxa=z/100\n pvi=int(ed1.get())\n global s\n s=int(ed2.get())\n calcular()\n\njanela = Tk();\ned = Entry(janela)\ned.place(x=110, y=100)\ned1 = Entry(janela)\ned1.place(x=110, y=160)\ned2 = Entry(janela)\ned2.place(x=110, y=220)\nlbl=Label(janela, width=50, text= \"SIMULADOR EMPRÉSTIMO BANCÁRIO: \")\nlbl.place(x=140, y=10)\nlb=Label(janela, width=25, text= \"TAXA DE JUROS (% AO MÊS) : \")\nlb.place(x=98, y=80)\nlb1=Label(janela, width=20, text= \"VALOR EMPRÉSTIMO (PVI): \")\nlb1.place(x=105, y=130)\nlb2=Label(janela, width=20, text= \"QUANTIDADE DE MESES: \")\nlb2.place(x=100, y=190)\nbt=Button(janela, width=20, text =\" Plotar Gráfico\",command= bt_click)\nbt.place(x=400,y=150)\njanela.title(\"Capitalizaçao de Juros\");\njanela.geometry(\"600x300+100+100\")\njanela.mainloop()\n\n\n\n\n\n","sub_path":"SimuladorEmprestimosBancarios.py","file_name":"SimuladorEmprestimosBancarios.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"297257362","text":"import socket\nimport string\nimport random\nfrom time import sleep\nimport mysql.connector\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)\ns.connect(('localhost', 5000))\ncoun = 0\n\n\nwhile True:\n if coun == 0:\n karcis_in = input(\"Karcis : \")\n s.send(karcis_in.encode())\n sleep(1)\n plat_in = input(\"Plat : \")\n s.send(plat_in.encode())\n sleep(1)\n coun = coun + 1\n permission = s.recv(1024)\n permission = permission.decode()\n coun = coun + 1\n if permission == 'Terima kasih':\n print(\"Terima kasih\")\n coun = 0 \n else :\n print(\"Maaf karcis dan plat tidak cocok\")\n coun = 0\n \n ","sub_path":"clientout.py","file_name":"clientout.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"465552026","text":"# coding=utf-8\r\n\r\n\"\"\"\r\n230. Kth Smallest Element in a BST My Submissions QuestionEditorial Solution\r\nTotal Accepted: 42836 Total Submissions: 114833 Difficulty: Medium\r\nGiven a binary search tree, write a function kthSmallest to find the kth smallest element in it.\r\n\r\nNote:\r\nYou may assume k is always valid, 1 ≤ k ≤ BST's total elements.\r\n\r\nFollow up:\r\nWhat if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?\r\n\r\nHint:\r\n\r\nTry to utilize the property of a BST.\r\nWhat if you could modify the BST node's structure?\r\nThe optimal runtime complexity is O(height of BST).\r\n\"\"\"\r\n\r\n\r\n# Definition for a binary tree node.\r\nclass TreeNode(object):\r\n def __init__(self, x):\r\n self.val = x\r\n self.left = None\r\n self.right = None\r\n\r\n\r\nclass Solution(object):\r\n def kthSmallest(self, root, k):\r\n \"\"\"\r\n :type root: TreeNode\r\n :type k: int\r\n :rtype: int\r\n \"\"\"\r\n\r\n def _inorder(root, ret, k):\r\n if root is None or len(ret) >= k:\r\n return\r\n else:\r\n _inorder(root.left, ret, k)\r\n if len(ret) < k:\r\n ret.append(root.val)\r\n _inorder(root.right, ret, k)\r\n\r\n ret = []\r\n _inorder(root, ret, k)\r\n if len(ret) < k:\r\n return\r\n return ret[-1]\r\n\r\n\r\nif __name__ == '__main__':\r\n root = TreeNode(0)\r\n root.left = TreeNode(1)\r\n root.left.left = TreeNode(3)\r\n root.left.right = TreeNode(4)\r\n root.right = TreeNode(2)\r\n root.right.right = TreeNode(5)\r\n root.right.right.left = TreeNode(6)\r\n\r\n print (Solution().kthSmallest(root,8))\r\n","sub_path":"zishell/solution/medium/solution230_kthSmallest.py","file_name":"solution230_kthSmallest.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"191549714","text":"import json\n\nconfig = None\nwith open(\"./config.json\",'r') as load_f:\n config = json.load(load_f)\n\nfrom flask import Flask,request,jsonify\nfrom flask import render_template\napp = Flask(__name__)\n\nimport sys \nsys.path.append(\"./algorithm\") \nfrom algorithm.opinion_extraction.interface import process_news\nfrom algorithm.summarization_extraction.interface import get_abstract\n\nstatus_code = {\n 'success': 0,\n 'fail': -1\n}\n\n# 跨域支持\ndef after_request(resp):\n resp.headers['Access-Control-Allow-Origin'] = '*'\n return resp\n\n@app.route('/',methods=['GET'])\ndef get_index():\n return render_template(\"index.html\")\n\n@app.route('/aidemo/pointview',methods=['GET'])\ndef get_pointview():\n return render_template(\"pointview.html\")\n\n@app.route('/aidemo/summarization',methods=['GET'])\ndef get_summarization():\n return render_template(\"summarization.html\")\n\n@app.route('/aidemo/subway',methods=['GET'])\ndef get_subway():\n return render_template(\"summarization.html\")\n\n@app.route('/apis/viewpoint',methods=['POST'])\ndef viewpoint():\n news =request.get_data().decode('utf-8')\n # news = request.args.get('news')\n try:\n result = process_news(news)\n return jsonify({\"viewpoint\":[\n {\"speaker\": item[0],\"content\":item[1]} for item in result\n ],\"result\":status_code['success']})\n except:\n return jsonify({\"result\":status_code['fail']})\n\n@app.route('/apis/summarization',methods=['POST'])\ndef summatization():\n news =request.get_data().decode('utf-8')\n try:\n abstract = get_abstract(news)\n return jsonify({\"abstract\":abstract,\"result\":status_code['success']})\n except Exception as e:\n #msg = bytes(str(e), encoding = 'utf-8')\n return jsonify({\"result\":status_code['fail'],\"message\":str(e)})\n\napp.after_request(after_request)\napp.run(host='0.0.0.0', port=config['port'], debug=False)\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"452304376","text":"# ------------------------------------------------------------------------------\n# Copyright (c) Lightricks\n# ------------------------------------------------------------------------------\n\nimport os\n\nimport cv2\nimport numpy as np\nfrom .base_dataset import BaseDataset\n\n\nclass MHP(BaseDataset):\n def __init__(self,\n root,\n list_path,\n num_samples=None,\n num_classes=10,\n multi_scale=True,\n flip=True,\n ignore_label=0,\n base_size=2048,\n crop_size=(512, 1024),\n downsample_rate=1,\n scale_factor=16,\n mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]):\n\n super().__init__(ignore_label, base_size, crop_size, downsample_rate, scale_factor, mean, std, )\n\n self.root = root\n self.list_path = list_path\n self.num_classes = num_classes\n\n self.multi_scale = multi_scale\n self.flip = flip\n\n self.img_list = [line.strip().split() for line in open(root + list_path)]\n\n self.files = self.read_files()\n if num_samples:\n self.files = self.files[:num_samples]\n\n self.label_mapping = {}\n # self.label_mapping = {0: ignore_label,\n # 1: ignore_label, 2: ignore_label,\n # 3: ignore_label, 4: ignore_label,\n # 5: ignore_label, 6: ignore_label,\n # 7: 0, 8: 1, 9: ignore_label,\n # 10: ignore_label, 11: 2, 12: 3,\n # 13: 4, 14: ignore_label, 15: ignore_label,\n # 16: ignore_label, 17: 5, 18: ignore_label,\n # 19: 6, 20: 7, 21: 8, 22: 9, 23: 10, 24: 11,\n # 25: 12, 26: 13, 27: 14, 28: 15,\n # 29: ignore_label, 30: ignore_label,\n # 31: 16, 32: 17, 33: 18}\n\n def read_files(self):\n \"\"\"\n read list and creates files list with dict objects that contain\n path for images\n path for annotation (if this is not test)\n name of image\n wight of image = 1\n :return: files list\n \"\"\"\n files = []\n # if this is test folder then there are no labels\n if 'test' in self.list_path:\n for item in self.img_list:\n image_path = item\n name = os.path.splitext(os.path.basename(image_path[0]))[0]\n files.append({\n \"img\": image_path[0],\n \"name\": name,\n })\n else:\n for item in self.img_list:\n image_path, label_path = item\n name = os.path.splitext(os.path.basename(label_path))[0]\n files.append({\n \"img\": image_path,\n \"label\": label_path,\n \"name\": name,\n \"weight\": 1\n })\n return files\n\n def convert_label(self, label, inverse=False):\n \"\"\"\n convert label according to label_mapping\n :param label: label image\n :param inverse: use inverse label_mapping\n :return:\n \"\"\"\n temp = label.copy()\n if inverse:\n for v, k in self.label_mapping.items():\n label[temp == k] = v\n else:\n for k, v in self.label_mapping.items():\n label[temp == k] = v\n return label\n\n def __getitem__(self, index):\n item = self.files[index]\n name = item[\"name\"]\n image = cv2.imread(item[\"img\"], cv2.IMREAD_COLOR)\n size = image.shape\n\n # if there is no annotation (test):\n if 'test' in self.list_path:\n image = self.input_transform(image)\n image = image.transpose((2, 0, 1))\n\n return image.copy(), np.array(size), name\n\n label = cv2.imread(item[\"label\"], cv2.IMREAD_GRAYSCALE)\n label = self.convert_label(label)\n\n image, label = self.gen_sample(image, label, self.multi_scale, self.flip)\n\n return image.copy(), label.copy(), np.array(size), name","sub_path":"lib/datasets/mhp.py","file_name":"mhp.py","file_ext":"py","file_size_in_byte":4260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"72318959","text":"#!python3\nfrom pathlib import Path\nfrom collections import *\nfrom operator import *\nfrom functools import *\nfrom toolz import *\nfrom toolz.curried import *\n\nfile = Path(__file__).with_name('7.txt').open().readlines()\nfile = pipe(file,\n map(str.strip),\n map(methodcaller('split', ' -> ')),\n tuple,\n map(reversed),\n dict\n )\n\nops = {\n 'OR': or_,\n 'AND': and_,\n 'RSHIFT': lambda a,b: (a >> b) & 0xffff,\n 'LSHIFT': lambda a,b: (a << b) & 0xffff,\n 'NOT': lambda a: (~a) & 0xffff,\n}\n\n\n@lru_cache(maxsize=None)\ndef r(name):\n if name.isdigit():\n return int(name)\n print(name,file[name])\n line = file[name].split()\n if len(line) == 3:\n return ops[line[1]](r(line[0]), r(line[2]))\n if len(line) == 2:\n return ops[line[0]](r(line[1]))\n if len(line) == 1:\n return r(line[0])\n\nprint(r('a'))\nfile['b'] = str(r('a'))\n\nr.cache_clear()\n\nprint(r('a'))\n","sub_path":"7/7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"606735656","text":"# Model of one Layer of Neurons using Numpy\r\n# Formula output = (input 0 * weight 0)+...+(input n * weight n)+bias\r\n\r\nimport numpy as np \r\n\r\ninputs =[1,2,3,2.5]\r\n\r\nweights =\t[[0.2,0.8,-0.5,1.0],\r\n\t\t\t[0.5,-0.91,0.26,-0.5],\r\n\t\t\t[-0.26,-0.27,0.17,0.87]]\r\n\r\nbiasis =[2,3,0.5]\r\n\r\noutput = np.dot(weights,inputs) + biasis\r\n\r\nprint(output)","sub_path":"video3/v3exp3.py","file_name":"v3exp3.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"494592582","text":"import numpy\nfrom fractions import Fraction\nimport time\nimport math\n\ntri = []\nSn = []\nM = 20\n\n\ndef pre_work():\n global tri\n global Sn\n now_line = [Fraction(1, 1)] + [(Fraction(0, 1))] * (M+1)\n tri.append(now_line)\n for i in range(1, M+2):\n now_line = [Fraction(1, 1)]\n for j in range(1, M+2):\n # print(i, j, now_line)\n now_line.append(Fraction(tri[i-1][j-1] + tri[i-1][j], 1))\n tri.append(now_line)\n tri_mat = numpy.mat(tri)\n\n now_line = [Fraction(0, 1), Fraction(1, 1)] + [(Fraction(0, 1))] * (M)\n one = numpy.mat([Fraction(1, 1)] + [(Fraction(0, 1))] * (M+1))\n\n Sn.append(now_line)\n Sn_mat = [numpy.mat(Sn[0])]\n for i in range(1, M+1):\n now_line = tri_mat[i+1] - one\n for j in range(i):\n now_line -= tri[i+1][j] * Sn_mat[j]\n now_line = now_line/tri[i+1][i]\n Sn_mat.append(now_line)\n Sn.append(Sn_mat[i].tolist()[0])\n\n # Sn_mat = numpy.mat(Sn)\n for i in range(len(Sn)):\n # print(Sn[i])\n pass\n\n\ndef work(n, m):\n ans = 0\n now = 1\n for i in range(len(Sn[m])):\n ans += now * Sn[m][i]\n # print(ans)\n now *= n\n return int(ans)\n\n\ndef check():\n f = open(\"result_py.txt\", \"w\")\n start = time.time()\n for n in range(1, 100000+1):\n for m in range(1, 21):\n\n ans = work(n, m)\n ans = format(ans,'.2E').replace('+', '').replace('E0', 'E')\n print(\"{%8d,\\t%2d,\\t%s},\"%(n,m,ans), file=f)\n if 0 == n % 10000:\n end = time.time()\n duration = end - start\n print(\"n =\", n, \",\\tTIME:\", duration, \"s\")\n # print(format(ans,'.2E').replace('+', ''))\n f.close()\n\n\n# -- author: lijw --\nif __name__ == '__main__':\n pre_work()\n while True:\n try:\n x = input().split(' ')\n except:\n break\n n = int(x[0])\n m = int(x[1])\n ans = work(n, m)\n #print(ans)\n power = int(math.log(ans, 10))\n ans = (int((ans//(10**(power-3)))/10 + 0.5))/100\n print(\"%.2fE%d\"%(ans,power))\n # print(format(ans,'.2E').replace('+', ''))\n","sub_path":"88. 从1开始的N个连续自然数的M次方之和/088.py","file_name":"088.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"194210167","text":"import uuid\nfrom bottle import route, template, post, request, response\nfrom index import mysqlObject\nimport json\nimport hashlib\nfrom returnstatus import Status\n\n'''\n\tStandard query class for retrieving and setting customer data. \n\t- Things like achievements / goals really should be in their own class.\n\n\tThe idea with these classes is ultimately we apply a route (typically post) which will search for certain things\n\t\tsuch as the userID of the person we want to deal with. Submit query and process data so it's appropriate for JSon.\n\n\tGetCustomerData below essentially is the best example of querying for data, processing it and then returning it as output.\n'''\n\n__author__ = 'chris'\n\nclass customerAPI():\n\t \n\t@post('/api/v1.0/cdata/request')\n\tdef GetCustomerData():\n\n\t\n\t\t#Get user id via POST\n\t\tuserID = request.forms.get('user')\n\t\tqueryData = mysqlObject.Query('SELECT AccountType, Surname, Forename, DOB, ParentID, IsChild, AltParentID, Balance, Stash FROM Accounts WHERE AccountID = %s', [userID] )\n\n\t\t#Just checking to see if any data is actually returned, or what type it is. If it's a None type then we output an empty string\n\t\tif not queryData or not queryData[0]:\n\t\t\treturn Status.ReturnOutputData(5,{'Error':'No Users Found'})\n\t\telse:\n\t\t\t#Otherwise grab data we're after\n\t\t\tdata = queryData[0]\n\n\t\tcustData={\n\t\t\t'accountType' : data[0],\n\t\t\t'surname' : data[1],\n\t\t\t'forename' : data[2],\n\t\t\t'dob' : data[3].strftime(\"%Y-%m-%d\"),\n\t\t\t'parentID' : data[4],\n\t\t\t'altParentID' : data[6],\n\t\t\t'isChild' : data[5],\n\t\t\t'balance' : '{0:.2f}'.format(data[7]),\n\t\t\t'stash': '{0:.2f}'.format(data[8])\n\t\t}\t\n\n\t\t#will return a string via html which includes the status and the above data. After this, it's end of function.\n\t\treturn Status.ReturnOutputData(0,custData)\n\n\n\t@post('/api/v1.0/cdata/requestchildren')\n\tdef GetCustomerChildren():\n\t\t#Near enough does the same as the above, exception with getting children\n\t\tuserID = request.forms.get('user')\n\t\t\n\t\tqueryData = mysqlObject.Query('SELECT AccountID, AccountType, Surname, Forename, DOB, Balance, Stash FROM Accounts WHERE ParentID = %s OR AltParentID = %s', [userID, userID] )\n\n\t\tif not queryData or not queryData[0]:\n\t\t\treturn Status.ReturnOutputData(5,{'Error':'No Children Found'})\n\t\telse:\n\t\t\tdata = queryData\n\n\t\treturnData = {}\n\n\t\tfor child in data:\n\t\t\tcustData={\n\t\t\t\t'accountID' : child[0],\n\t\t\t\t'accountType' : child[1],\n\t\t\t\t'surname' : child[2],\n\t\t\t\t'forename' : child[3],\n\t\t\t\t'dob' : child[4].strftime(\"%Y-%m-%d\"),\n\t\t\t\t'balance' : '{0:.2f}'.format(child[5]),\n\t\t\t\t'stash': '{0:.2f}'.format(child[6])\n\t\t\t}\n\t\t\treturnData[child[0]] = custData\n\n\t\treturn Status.ReturnOutputData(0,returnData)\n\n\n\t@post('/api/v1.0/cdata/registerchild')\n\tdef RegisterNewCustomer():\n\t\tuserID = request.forms.get('user')\n\n\t\t#Below is a bunch of straight up checks. Tedious, but gets the job done.\n\t\tif not userID or not customerAPI.UserIsParent(userID):\n\t\t\treturn Status.ReturnOutputData(6,{'Error':'Not a parent.'})\n\n\t\tstrForename = request.forms.get('forename')\n\t\tif not strForename or strForename == ' ':\n\t\t\treturn Status.ReturnOutputData(4,{'Error':'Missing Forename'})\n\t\t\n\t\tstrSurname = request.forms.get('surname')\n\t\tif not strSurname or strSurname == ' ':\n\t\t\treturn Status.ReturnOutputData(4,{'Error':'Missing Surname'})\n\n\t\tstrDOB = request.forms.get('dob')\n\t\tif not strDOB or strDOB == ' ':\n\t\t\treturn Status.ReturnOutputData(4,{'Error':'Missing DOB'})\n\n\t\tstrUsername = request.forms.get('username')\n\t\tif not strUsername or strUsername == ' ':\n\t\t\treturn Status.ReturnOutputData(4,{'Error':'Missing Username'})\n\n\t\tstrPassword = request.forms.get('password')\n\t\tif not strPassword or strPassword == ' ':\n\t\t\treturn Status.ReturnOutputData(4,{'Error':'Missing Password'})\n\n\n\t\t#We're not currently specifying account types, but the system does cater for it. Default to 0 for now.\n\t\taccountType = 0\n\n\t\t#As it's the current parent registering it, we default the parentID to the userID.\n\t\tparentID = userID\n\t\t#Generate a salt for the hashed password\n\t\tsalt = str(uuid.uuid4()).encode('utf-8')\n\t\t#Minor quirk with how python works with strings and bytes. We re encode (above) and decode (below) to get the correct salt.\n\t\tnewsalt = salt.decode('utf-8')\n\n\t\thashedPW = hashlib.sha224(strPassword.encode('utf-8') + str(newsalt).encode('utf-8')).hexdigest()\n\t\t#Below we use a stored procedure which is stored on the server, this allows us to use the DB engine to then return the created Child Account ID.\n\t\tqueryData = mysqlObject.Query('CALL bank_CreateChild(%s, %s, %s, %s, %s, %s, %s, %s)' ,[ strForename, strSurname, strDOB, accountType, parentID, strUsername, hashedPW, newsalt ])\n\n\t\t#We have the data, so now we just format it for output...\n\t\tchildID = queryData[0][0]\n\t\treturn Status.ReturnOutputData(0,{'childID':childID})\n\n\t@post('/api/v1.0/cdata/transfermoney')\n\tdef TransferMoney():\n\t\tuserID = int(request.forms.get('user'))\n\t\ttargetID = int(request.forms.get('target'))\n\n\t\t#Validate what we're trying to send in is actually money..\n\t\ttry:\n\t\t\tamountToSend = float(request.forms.get('amount'))\n\t\texcept Exception as error:\n\t\t\treturn Status.ReturnOutputData(5,{'Error':'Invalid amount of money specified!'})\n\n\t\t#For security purposes (and being reasonable), we only allow them to transfer at least £1 to their stash.\n\t\tif (amountToSend < 1):\n\t\t\treturn Status.ReturnOutputData(5,{'Error':'Invalid amount of money specified!'})\n\n\t\tamountToSend = float('{0:.2f}'.format(amountToSend))\n\n\t\t#First of all, lets work out whether or not we have a parent or a child...\n\t\tif customerAPI.UserIsParent(userID):\n\t\t\t#We have a parent? Awesome. Lets now just validate that they can only send to their kids.\n\t\t\tqueryData = mysqlObject.Query('SELECT AccountID FROM Accounts WHERE ParentID = %s OR AltParentID = %s', [userID, userID] )\n\n\t\t\tfound = None\n\t\t\tfor candidate in queryData:\n\t\t\t\tif int(candidate[0]) == targetID:\n\t\t\t\t\tfound = True\n\t\t\t\t\tbreak\n\t\t\t\t\n\t\t\tif found == None:\n\t\t\t\t#No one found, return error\n\t\t\t\treturn Status.ReturnOutputData(4,{'Error':'Invalid Target specified (Parent -> Child)'})\n\n\t\t\t#Now lets just verify the parent actually has enough money to move between accounts..\n\t\t\t#This could be done in SQL directly (heck, corporate code will probably mandate both this check and the SQL, but hey)\n\n\t\t\tqueryData = mysqlObject.Query('SELECT Balance FROM Accounts WHERE AccountID = %s', [userID])\n\t\t\tprint(queryData)\n\t\t\tprint(queryData[0][0])\n\t\t\tparentBalance = float(queryData[0][0]) or 0 #If invalid, default to 0 because then it wont work at all!\n\n\t\t\tif (parentBalance - amountToSend < 1):\n\t\t\t\treturn Status.ReturnOutputData(3,{'Error':'Not enough money'}) #Little timmy won't get his pocket money today..\n\n\t\t\t#Otherwise, lets use another stored procedure to do the heavy lifting for us\n\t\t\tqueryData = mysqlObject.Query('CALL bank_transferMoney(%s, %s, %s)', [userID, targetID, amountToSend])\n\t\t\treturn Status.ReturnOutputData(0,{'newbalance':parentBalance - amountToSend, 'sent':amountToSend, 'to': targetID})\n\n\t\telse:\n\t\t\t#Okay, so we have a child in theory. Lets pull down his parents..\n\t\t\tqueryData = mysqlObject.Query('SELECT ParentID, AltParentID FROM Accounts WHERE AccountID = %s', [userID] )\n\n\t\t\t#So check to see if target returned is what we want, that it's a number.\n\t\t\tif not int(queryData[0][0]) == targetID or (type(queryData[0][1]) == 'int' and not int(queryData[0][1]) == targetID):\n\t\t\t\treturn Status.ReturnOutputData(4,{'Error':'Invalid Target specified (Child -> Parent)'})\n\n\t\t\tqueryData = mysqlObject.Query('SELECT Balance FROM Accounts WHERE AccountID = %s', [userID])\n\t\t\tchildBalance = float(queryData[0][0]) or 0 #If invalid, default to 0 because then it wont work at all!\n\n\t\t\tif (childBalance - amountToSend < 1):\n\t\t\t\treturn Status.ReturnOutputData(3,{'Error':'Not enough money'}) \n\n\t\t\t#Otherwise, lets use another stored procedure to do the heavy lifting for us\n\t\t\tqueryData = mysqlObject.Query('CALL bank_transferMoney(%s, %s, %s)', [userID, targetID, amountToSend])\n\t\t\treturn Status.ReturnOutputData(0,{'newbalance':childBalance - amountToSend, 'sent':amountToSend, 'to': targetID})\n\n\t@post('/api/v1.0/cdata/stashtobalance')\n\tdef StashToBalance():\n\t\t#Below, stash to balance and balance to stash are technically the same functions but inverted.\n\n\t\tuserID = int(request.forms.get('user'))\n\t\ttry:\n\t\t\t#Validate amount\n\t\t\tamountToSend = float(request.forms.get('amount'))\n\t\texcept Exception as error:\n\t\t\treturn Status.ReturnOutputData(5,{'Error':'Invalid amount of money specified!'})\n\n\t\t#Validate amount\n\t\tif (amountToSend < 1):\n\t\t\treturn Status.ReturnOutputData(5,{'Error':'Invalid amount of money specified!'})\n\n\t\tqueryData = mysqlObject.Query('SELECT Stash FROM Accounts WHERE AccountID = %s', [userID])\n\t\tbalance = queryData[0][0] or 0 \n\n\t\t#Not enough cash? Aint happening\n\t\tif (balance - amountToSend < 1):\n\t\t\treturn Status.ReturnOutputData(3,{'Error':'Not enough money'}) \n\n\t\tamountToSend = '{0:.2f}'.format(amountToSend)\n\n\t\t#Stored procedure to speed it up. \n\t\tqueryData = mysqlObject.Query('CALL bank_stashToBalance(%s, %s)', [userID, amountToSend])\n\n\t\t#And return all the data.\n\t\treturn Status.ReturnOutputData(0,{'newbalance': queryData[0][0], 'newstash' : queryData[0][1]})\n\t\n\n\t@post('/api/v1.0/cdata/balancetostash')\n\tdef BalanceToStash():\n\t\tuserID = int(request.forms.get('user'))\n\t\ttry:\n\t\t\tamountToSend = float(request.forms.get('amount'))\n\t\texcept Exception as error:\n\t\t\treturn Status.ReturnOutputData(5,{'Error':'Invalid amount of money specified!'})\n\n\t\tif (amountToSend < 1):\n\t\t\treturn Status.ReturnOutputData(5,{'Error':'Invalid amount of money specified!'})\n\n\n\n\t\tqueryData = mysqlObject.Query('SELECT Balance FROM Accounts WHERE AccountID = %s', [userID])\n\t\tbalance = queryData[0][0] or 0 \n\n\t\tif (balance - amountToSend < 1):\n\t\t\treturn Status.ReturnOutputData(3,{'Error':'Not enough money'}) \n\n\t\tamountToSend = '{0:.2f}'.format(amountToSend)\n\n\t\tqueryData = mysqlObject.Query('CALL bank_balanceToStash(%s, %s)', [userID, amountToSend])\n\n\t\treturn Status.ReturnOutputData(0,{'newbalance': queryData[0][0], 'newstash' : queryData[0][1]})\n\t\t\n\t\n\t#Sugar function to double check if a user is a parent or not.\n\tdef UserIsParent(userID):\n\t\tqueryData = mysqlObject.Query('SELECT isChild FROM Accounts WHERE AccountID = %s', [userID])\n\n\t\tif int(queryData[0][0]) == 1:\n\t\t\treturn False\n\t\telse:\n\t\t\treturn True\n\n\n","sub_path":"customerclass.py","file_name":"customerclass.py","file_ext":"py","file_size_in_byte":10272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"452197314","text":"\n\n#This function rotate the list by x number\ndef rotate(lst,x):\n copy = list(lst)\n for i in range(len(lst)):\n if x<0:\n lst[i+x] = copy[i]\n else:\n lst[i] = copy[i-x]\n\n#Taking user input for 3 keys as k,l,m\nk,l,m = input().split()\nk=int(k)\nl=int(l)\nm=int(m)\n#Taking input in str variable\nstr=input()\n\n#Dividing all alphabets and _ in 3 groups in a list\nt1=['a','b','c','d','e','f','g','h','i']\nt2=['j','k','l','m','n','o','p','q','r']\nt3=['s','t','u','v','w','x','y','z','_']\n\n#initalizing list to store key value pair \na1=[]\na2=[]\na3=[]\n\n#enumerate through each element of str and\n#if it matches to corresponding group,add it to that list.\nfor i,j in enumerate(str,0):\n\tif j in t1:\n\t\ta1.append(j)\n\t\t\n\telif j in t2:\n\t\ta2.append(j)\n\t\t\n\telse:\n\t\ta3.append(j)\n\n\n#Calling function to rotate all 3 lists\nrotate(a1,k)\nrotate(a2,l)\nrotate(a3,m)\n\n#initalizing variables\ng=0\nres=[]\np,q,r=0,0,0\n#enumerate through str to check \n#which group this element belongs to\nfor i,j in enumerate(str,0):\t\n\tif j in t1:\n\t\tres.append(a1[p])\n\t\tp+=1\n\telif j in t2:\n\t\tres.append(a2[q])\n\t\tq+=1\n\telse:\n\t\tres.append(a3[r])\n\t\tr+=1\n\n#Printing Result\nfor c in res:\n\tprint(c,end=\"\")\nprint()","sub_path":"ps2.py","file_name":"ps2.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"135281617","text":"import json\nfrom pandas.io.json import json_normalize\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import stopwords\nfrom string import ascii_uppercase, ascii_lowercase, punctuation\nfrom pandas import DataFrame, crosstab, read_csv\nfrom collections import Counter\nfrom math import log, inf\nfrom numpy import vectorize, diag\nfrom functools import partial\nfrom datetime import datetime\n\n\nclass Classifier(object):\n class Vectorize(vectorize):\n def __get__(self, obj, objtype):\n return partial(self.__call__, obj)\n\n def __init__(self, featureLabels):\n self.__stopWords__ = set(stopwords.words('english'))\n self.__transTable__ = str.maketrans(ascii_uppercase + punctuation + \"1234567890\",\n ascii_lowercase + ' ' * (len(punctuation) + 10), '')\n self.__lemmatizer__ = WordNetLemmatizer()\n self.__featureLabels__ = featureLabels\n self.__probabilities__ = {}\n self.__probabilitiesOfLabels__ = {}\n\n def __clean__(self, text):\n text = text.replace(\"https://www.huffingtonpost.com/entry/\", \" \")\n text = text.translate(self.__transTable__)\n tokens = word_tokenize(text)\n removedStopWords = [word for word in tokens if word not in self.__stopWords__]\n normalized = [self.__lemmatizer__.lemmatize(word) for word in removedStopWords]\n return normalized\n\n @Vectorize\n def __predictLabel__(self, line):\n line = self.__clean__(line)\n maxProb = -inf, ''\n for label in self.__featureLabels__:\n min_prob = min(self.__probabilities__[label].values())\n maxProb = max(\n maxProb,\n (\n self.__probabilitiesOfLabels__[label] +\n sum([self.__probabilities__[label].get(word, min_prob) for word in line]),\n label\n )\n )\n return maxProb[1]\n\n def fit(self, train):\n train = train[train['short_description'].notnull()]\n numOfTotalRows = train[train['category'].isin(self.__featureLabels__)].shape[0]\n for label in self.__featureLabels__:\n data = train[train['category'] == label][['short_description', 'headline', 'authors', 'link']]\n merged = \" \".join(\n data['short_description'].tolist() +\n data['headline'].tolist() +\n data['authors'].tolist() +\n data['link'].tolist()\n )\n parsed = self.__clean__(merged)\n total_label = len(parsed)\n # print({i + \" \" + j for i, j in dict(name = \"John\", age = \"36\", country = \"Norway\").items()})\n ## {'name John', 'country Norway', 'age 36'}\n # print({i: i + \" \" + j for i, j in dict(name = \"John\", age = \"36\", country = \"Norway\").items()})\n ## {'name': 'name John', 'age': 'age 36', 'country': 'country Norway'}\n self.__probabilities__[label] = {i: log(float(j / total_label)) for i, j in dict(Counter(parsed)).items()}\n self.__probabilitiesOfLabels__[label] = log(float(data.shape[0] / numOfTotalRows))\n\n def predict(self, data, final_test=False):\n ## First implementation\n data = data[data['short_description'].notnull()]\n data['temp'] = data['short_description'] + \" \" + data['headline'] + \" \" + data['authors'] + \" \" + data['link']\n if not final_test:\n data = data[data['category'].isin(self.__featureLabels__)]\n\n return self.__predictLabel__(data['temp'].tolist())\n\n\nclass TrainTestSelector(object):\n def __init__(self, data, category, oversample):\n self.dataset = data[data['short_description'].notnull()]\n self.category = category\n self.oversample = oversample\n\n def __overSample__(self, train, test=True):\n max_count = max(train['category'].value_counts())\n for label in self.category:\n count = train[train['category'] == label].shape[0]\n if count < max_count:\n train = train.append(train[train['category'] == label].sample(n=max_count - count, replace=True))\n max_count = max(test['category'].value_counts())\n for label in self.category:\n count = test[test['category'] == label].shape[0]\n if count < max_count:\n test = test.append(test[test['category'] == label].sample(n=max_count - count, replace=True))\n return train, test\n\n def divideTestAndTrain(self, train=0.9):\n data = self.dataset\n trainset = DataFrame().reindex_like(data)\n testset = DataFrame().reindex_like(data)\n for label in self.category:\n # TODO: get different part of 80%\n type1 = data[data['category'] == label]\n trainset = trainset.append(type1.iloc[:int(train * type1.shape[0]), :])\n testset = testset.append(type1.iloc[int(train * type1.shape[0]):, :])\n if self.oversample:\n return self.__overSample__(trainset[trainset['category'].notnull()], testset[testset['category'].notnull()])\n else:\n return trainset[trainset['category'].notnull()], testset[testset['category'].notnull()]\n\n\nclass Evaluator(object):\n def __init__(self, predicts, answers):\n pairs = DataFrame(data={'predict': predicts, 'actual': answers})\n self.cnfMatrix = crosstab(pairs['predict'], pairs['actual'])\n\n def accuracy(self):\n return diag(self.cnfMatrix).sum() / self.cnfMatrix.values.sum()\n\n def cnfusionMatrix(self):\n return self.cnfMatrix\n\n def precision(self):\n return DataFrame(diag(self.cnfMatrix) / self.cnfMatrix.sum(axis=1), index=self.cnfMatrix.columns,\n columns=[\"precision\"])\n\n def recall(self):\n return DataFrame(diag(self.cnfMatrix) / self.cnfMatrix.sum(axis=0), index=self.cnfMatrix.columns,\n columns=[\"recall\"])\n\n def resultTable(self, title):\n recall = diag(self.cnfMatrix) / self.cnfMatrix.sum(axis=0)\n precision = diag(self.cnfMatrix) / self.cnfMatrix.sum(axis=1)\n df = DataFrame(columns=self.cnfMatrix.columns)\n df.columns.name = title\n df = df.append(recall, ignore_index=True)\n df = df.append(precision, ignore_index=True)\n df = df.append({self.cnfMatrix.columns[0]: self.accuracy()}, ignore_index=True)\n df.index = ['recall', 'precision', 'accuracy']\n return df.fillna('')\n\n\ncategories = [\n \"POLITICS\",\n \"ENTERTAINMENT\",\n \"TRAVEL\",\n \"BUSINESS\",\n \"COMEDY\", # !\n \"SPORTS\",\n \"HOME & LIVING\", # !\n \"WEDDINGS\",\n \"WOMEN\", # !\n \"IMPACT\", # !\n \"DIVORCE\",\n \"CRIME\",\n \"MEDIA\",\n \"RELIGION\",\n \"TECH\",\n \"MONEY\",\n \"ENVIRONMENT\", # !\n \"WELLNESS\",\n \"HEALTHY LIVING\",\n \"STYLE & BEAUTY\",\n \"STYLE\",\n \"FOOD & DRINK\",\n \"TASTE\",\n \"ARTS\",\n \"ARTS & CULTURE\",\n \"CULTURE & ARTS\",\n \"COLLEGE\",\n \"EDUCATION\",\n \"SCIENCE\",\n \"QUEER VOICES\",\n \"THE WORLDPOST\",\n \"WEIRD NEWS\",\n \"WORLDPOST\",\n \"BLACK VOICES\",\n \"WORLD NEWS\",\n \"GOOD NEWS\",\n \"LATINO VOICES\",\n \"PARENTING\",\n \"PARENTS\",\n \"FIFTY\",\n \"GREEN\",\n]\n\n# nltk.download('stopwords')\n# nltk.download('punkt')\n# nltk.download('wordnet')\n\nstartedAt = datetime.now()\n\n# https://www.kaggle.com/rmisra/news-category-dataset\ndataset = []\nfor line in open('data/News_Category_Dataset_v2.json', 'r'):\n dataset.append(json.loads(line))\n\ndataset = json_normalize(dataset)\ndataset = dataset[['category', 'short_description', 'authors', 'headline', 'link']]\ndataset = dataset.fillna(\"\")\n\nprint(\"===============================\")\nprint(\"preparing dataset done: \", datetime.now() - startedAt)\n\nts = TrainTestSelector(dataset, categories, oversample=False) # TODO: try false value\ntrain, test = ts.divideTestAndTrain()\ncf = Classifier(categories)\ncf.fit(train)\n\nprint(\"===============================\")\nprint(\"training done: \", datetime.now() - startedAt)\n\npredicts = cf.predict(test)\n\nprint(\"===============================\")\nprint(\"predicts done: \", datetime.now() - startedAt)\n\n## TODO: rewrite another Evaluator to evaluate the labels for user\nev = Evaluator(predicts, test['category'].tolist())\n\n\nprint(ev.cnfusionMatrix())\n# print(ev.precision())\n# print(ev.recall())\n# print(ev.accuracy())\nprint(ev.resultTable(\"PHASE 2\"))\n\n\nprint(\"===============================\")\nprint(\"done: \", datetime.now() - startedAt)","sub_path":"ml/main1.py","file_name":"main1.py","file_ext":"py","file_size_in_byte":8461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"191713485","text":"from PageObjects.CardPaymentPage import Pasha_page\nfrom PageObjects.DonationPage import Donate\nfrom Utilities.CustomLogger import LogGen\n\n\nclass Test_03_Payment:\n baseURL = \"https://stripe-samples.github.io/github-pages-stripe-checkout//\"\n\n def test_with_noData_input(self, setup):\n self.driver = setup\n self.driver.get(self.baseURL)\n self.driver.maximize_window()\n actual_title = self.driver.title\n print(\"Title of page is Stripe Checkout Sample\")\n\n self.Dt = Donate(self.driver)\n\n if actual_title == \"Stripe Checkout Sample\":\n assert True\n else:\n assert False\n print(\"Now click on Donate $5 button\")\n self.Dt.ClickOnDonateButton()\n payment_page_title1 = self.driver.title\n print(payment_page_title1)\n\n print(\"user can fill card details now\")\n self.cp = Pasha_page(self.driver)\n self.cp.Click_Pay()\n print(\"REQUIRED:Please enter Email ID\")\n print(\"REQUIRED:Please enter CARD number\")\n print(\"REQUIRED:Please enter Name\")\n print(\"Failed,System not allow to proceed\")\n self.driver.close()\n","sub_path":"testCases/test_Pay_without_filling_Data.py","file_name":"test_Pay_without_filling_Data.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"151530046","text":"\"\"\"\nFile: posterize.py\nProject 7.5\n\nDefines and tests a function for posterizing images.\n\"\"\"\n\nfrom images import Image\n\n\n\"\"\" Write your code here \"\"\"\n\ndef posterize(image,tupleRGB):\n\n black = (0, 0, 0)\n\n white = (255, 255, 255)\n\n for y in range(image.getHeight()):\n\n for x in range(image.getWidth()):\n\n (r, g, b) = image.getPixel(x, y)\n\n average = (r + g + b) // 3\n\n if average < 128:\n\n image.setPixel(x, y, tupleRGB)\n\n else:\n\n image.setPixel(x, y, white)\ndef main():\n filename = input(\"Enter the image file name: \")\n red = int(input(\"Enter an integer [0..255] for red: \"))\n green = int(input(\"Enter an integer [0..255] for green: \"))\n blue = int(input(\"Enter an integer [0..255] for blue: \")) \n image = Image(filename)\n posterize(image, (red, green, blue))\n image.draw()\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"Simple Graphics and Image Processing/posterize/posterize.py","file_name":"posterize.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"233437671","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 17 14:33:35 2019\n\n@author: victor.romano\n\"\"\"\n\nimport pandas as pd\n\ndados = pd.read_csv('Data/aluguel_residencial.csv', sep=';')\n\ndados.drop(columns=['Unnamed: 0'], inplace=True)\n\ndados[dados['Valor'].isnull()] \n\ndados.dropna(subset=['Valor'], inplace=True)\n\nselecao = (dados['Tipo'] == 'Apartamento') & (dados['Condominio'].isnull())\n\ndados = dados[~selecao]\n\ndados = dados.fillna({'Condominio': 0, 'IPTU': 0})\n\ndados.to_csv('Data/aluguel_residencial.csv', sep=';', index=False)","sub_path":"remoção_valores_nulos.py","file_name":"remoção_valores_nulos.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"622469938","text":"import sys\nimport numpy as np\nimport datetime\nimport pandas as pd\n#from pandas.plotting import register_matplotlib_converters\n#register_matplotlib_converters()\n#from netCDF4 import Dataset\nimport timeit\n#from matplotlib import pyplot as plt\n#%load_ext Cython\n#import Cython\n#import json, shutil\nimport pyximport; pyximport.install()\nimport model_boteti_cython as hcy\n\n\n#*****************************************************************************\n#definition of paramater and input files \n\n\ndebug=True\n\nfile_modpar = sys.argv[1]\nfile_init = sys.argv[2]\nfile_input = sys.argv[3]\nspinup = int(sys.argv[4])\n\n\noutputfiles=[]\nfor i in range(5,len(sys.argv)):\n outputfiles=outputfiles+[sys.argv[i]]\n\nfile_modset = \"./config/modset_boteti.dat\"\n\nif file_modpar==\"default\":\n file_modpar = \"./config/modpar_boteti.csv\"\nif file_init==\"default\":\n file_init=\"./config/init_boteti.csv\"\n\n\n\n#*****************************************************************************\ndef evap_calc():\n global glnoftsteps, glrecdate, gltminmax, glpet \n r0 = [16.35261505, 14.95509782, 12.8087226, 10.86376736, 9.847079426, 10.22676382, 11.84785549, 14.00041471, 15.76601788, 16.82545576, 17.20206337, 17.09344496]\n kc= [0.95, 0.9, 0.8, 0.7, 0.63, 0.6, 0.6, 0.63, 0.7, 0.8, 0.9, 0.95]\n glpet=[]\n for ts in range(glnoftsteps):\n curmonth=datetime.datetime.strptime(glrecdate[ts], \"%b-%Y\").month\n temp= 31 * kc[curmonth-1] * 0.0023 * r0[curmonth-1] * (gltminmax[ts][1] - gltminmax[ts][0]) ** 0.5 * (((gltminmax[ts][1] + gltminmax[ts][0]) / 2) + 17.8)\n glpet.append(temp)\n glpet=np.array(glpet)\n print (\"calculated evap...\")\n \n\ndef write_output_cellinundation(file_output):\n global glout_sa\n print (\"writing surface area output file...\")\n glout_sa.astype(int).to_csv(file_output)\n print (\"done\")\n\ndef write_output_totalinundation(file_output):\n global glout_sa\n print (\"writing surface area output file...\")\n glout_sa.astype(int).to_csv(file_output)\n print (\"done\")\n\n\ndef write_output_cellvolume(file_output):\n global glout_sv\n print (\"writing surface volume output file...\")\n glout_sv.astype(int).to_csv(file_output)\n print (\"done\")\n\ndef write_output_cellq(file_output):\n#write discharges for each cell\n global glout_sqout\n print (\"writing discharge output file...\")\n glout_sqout.astype(int).to_csv(file_output)\n print (\"done\")\n\ndef write_output_hydroregions(file_output):\n #write ecoregions for each cell\n global glhydroregions\n print (\"writing hydro regions output file...\")\n glhydroregions.astype(float).to_csv(file_output)\n print (\"done\")\n\ndef write_output_inundateddistance(file_output):\n #write inundated distance\n global glinunddist\n print (\"writing inundated distance output file...\")\n glinunddist.astype(int).to_csv(file_output)\n print (\"done\")\n\n\n\ndef mergecells(glvar,skip):\n #write areas for each cell\n global gloutputflag, glswcellname, glrecdate\n selcells=glvar[:,np.array(gloutputflag)==1]\n cellnames=np.array(glswcellname)\n# print(cellnames)\n tooutput=np.array(gloutputflag)\n selcellnames=cellnames[tooutput==1]\n selcellnames=['Boteti']\n merged=[[0]]\n outputtable=[]\n outputcellnames=[]\n for j,m in enumerate(merged):\n outputcellnames=outputcellnames+[selcellnames[j]]\n current=0\n for i in m:\n current=current+selcells[:,i]\n outputtable=outputtable+[current]\n index=pd.date_range(glrecdate[0], freq=\"M\", periods=len(glrecdate))\n outputFrame=pd.DataFrame(np.array(outputtable).T, index=index, columns=outputcellnames) \n outputFrame=outputFrame.iloc[skip:,:]\n return outputFrame\n\n\ndef write_init(output_file, _ts):\n global glnofswcells, glfin_sv, glfin_fv, glfin_iv\n print(glnofswcells, glfin_sv.shape, glfin_fv.shape, glfin_iv.shape)\n with open(output_file, \"w\") as outf:\n for scell in range(glnofswcells):\n outf.write(\"s_\"+str(scell)+\",\"+str(int(glfin_sv[_ts,scell]))+\"\\n\")\n for scell in range(glnofswcells):\n line=\"f_\"+str(scell)+\",\"+\",\".join([str(np.round(x,2)) for x in glfin_fv[_ts,scell,:].tolist()])\n outf.write(line+\"\\n\")\n for scell in range(glnofswcells):\n line=\"i_\"+str(scell)+\",\"+\",\".join([str(np.round(x,2)) for x in glfin_iv[_ts,scell,:].tolist()])\n outf.write(line+\"\\n\")\n \n\ndef wbalance_calc():\n global glsq_in, glfin_spre, glfin_sqout, glfin_sev, glfin_sinf, glfin_sv, glsv_init, glfin_fv, glfv_init \n global glfin_fev, glfin_finf, glfin_fgwout,glfin_fpre, glfin_iv, gliv_init, glfin_ipre, glfin_iev\n #surface reservoir\n sinflow=glfin_sqin.sum(0)\n srainfall=glfin_spre.sum(0)\n soutflow=glfin_sqout.sum(0)\n sevap=glfin_sev.sum(0)\n sinfiltration=glfin_sinf.sum(0)\n svdelta=glfin_sv[-1,:]-glsv_init\n sinputs=sinflow+srainfall\n soutputs=soutflow+sevap+sinfiltration\n swbal=sinputs-soutputs-svdelta\n# swbalclosure=wbalmerge(swbal)/wbalmerge(svdelta)*100\n swbalclosure=swbal/sinputs*100\n \n #floodplain reservoir\n fvdelta=(glfin_fv[-1,:,:]-glfv_init).sum(1)\n fevap=glfin_fev.sum((0,2))\n finfiltration=glfin_finf.sum((0,2))\n fgwoutflow=glfin_fgwout.sum((0,2)) \n frainfall=glfin_fpre.sum((0,2))\n finputs=finfiltration+frainfall\n foutputs=fgwoutflow+fevap\n print (finputs.shape, foutputs.shape, fvdelta.shape)\n fwbal=finputs-foutputs-fvdelta\n fwbalclosure=fwbal/finputs*100\n# print fvdelta, fevap, frainfall,finfiltration,fgwoutflow\n \n #island reservoir\n ivdelta=(glfin_iv[-1,:,:]-gliv_init).sum(1)\n ievap=glfin_iev.sum((0,2))\n irainfall=glfin_ipre.sum((0,2))\n iinputs=fgwoutflow+irainfall\n ioutputs=ievap\n iwbal=iinputs-ioutputs-ivdelta\n iwbalclosure=iwbal/iinputs*100\n\n return swbalclosure[np.where(glfinalsumflag==1)[0]], fwbalclosure[np.where(glfinalsumflag==1)[0]], iwbalclosure[np.where(glfinalsumflag==1)[0]]\n\n\n\ndef calc_hydroregions(_thresh, skip):\n global glhydroregions\n _poolyears=3\n _sa=mergecells(glfin_sa, 0)\n _sa[_sa>_thresh]=_thresh\n _sa=_sa/_thresh\n _max=_sa.resample(\"A-Jul\").max()\n permanent=_sa.resample(\"A-Jul\").min()\n pastwet=_sa.resample(\"A-Jul\").max().rolling(_poolyears).max()\n pools=pastwet-permanent\n dry=1-pastwet\n glhydroregions=pd.concat([permanent,pools,dry], 1)\n glhydroregions.columns=[\"permanent\",\"pools\",\"dry\"]\n glhydroregions=glhydroregions.iloc[skip:,:]\n\n\ndef calc_inundateddistance(_thresh, _maxdist, skip):\n #write inundated distance\n global glinunddist\n _sa=mergecells(glfin_sa, 0)\n glinunddist=_sa/_thresh\n glinunddist[glinunddist>1]=1\n glinunddist=glinunddist.iloc[skip:,0]*_maxdist\n print (\"done\")\n\n\n\ndef timer():\n global t0\n _t=timeit.default_timer()\n print (_t-t0)\n t0=timeit.default_timer()\n\n \n#*****************************************************************************\ndef read_modset(file_modset):\n global glconvcrit, glmaxiter, glnofswcells, glnofgwcells, glnofoutlets, glnoflinks, gldowncell, gloutputflag, glfinalsumflag, glswcellname\n print(\"reading model setup from \"+file_modset+\"...\")\n with open(file_modset, \"r\") as fmodset:\n #convergence criterion\n glconvcrit=float(fmodset.readline().strip().split(\",\")[1])\n #maxiterations\n glmaxiter=int(fmodset.readline().strip().split(\",\")[1])\n \n # numbers of cells are read\n glnofswcells=int(fmodset.readline().strip().split(\",\")[1])\n glnofgwcells=int(fmodset.readline().strip().split(\",\")[1])\n glnofoutlets=int(fmodset.readline().strip().split(\",\")[1])\n # links between reservoirs are read\n glnoflinks=[]\n gldowncell=[]\n for scell in range(glnofswcells):\n nlinks=int(fmodset.readline().strip().split(\",\")[1])\n glnoflinks.append(nlinks)\n temp=[]\n if nlinks>0:\n for link in range(nlinks):\n temp.append(int(fmodset.readline().strip().split(\",\")[1]))\n gldowncell.append(temp)\n # ouput flag for cells\n gloutputflag=[]\n for scell in range(glnofswcells):\n gloutputflag.append(int(fmodset.readline().strip().split(\",\")[1]))\n\n # final sum flag\n glfinalsumflag=[]\n for scell in range(glnofswcells):\n glfinalsumflag.append(int(fmodset.readline().strip().split(\",\")[1]))\n\n glswcellname=[]\n for scell in range(glnofswcells):\n cellname=fmodset.readline().strip().split(\",\")[1]\n #print(scell,cellname)\n glswcellname.append(cellname)\n glfinalsumflag=np.array(glfinalsumflag)\n print(\"done\")\n\n\n \n \n \n \n#*****************************************************************************\n \n#*****************************************************************************\ndef read_modpar(file_modpar):\n global glgwpar, glunitpar, glexponent, glbpar, glk, glV, gldelay,glstatratio,glfa, glia,glkgw,glfa_total,glnofgwcells,glnofswcells, glnoflinks\n print (\"reading model parameters from: \"+file_modpar)\n with open(file_modpar, \"r\") as fmodpar:\n # spatially constant parameters\n fdet=float(fmodpar.readline().strip().split(\",\")[1])\n idet=float(fmodpar.readline().strip().split(\",\")[1])\n fpor=float(fmodpar.readline().strip().split(\",\")[1])\n ipor=float(fmodpar.readline().strip().split(\",\")[1])\n \n # volume-area parameters\n glbpar=[]\n glexponent=[]\n for scell in range(glnofswcells):\n temp=fmodpar.readline().strip().split(\",\")\n# print(\"vol-area\", temp)\n glexponent.append(float(temp[1]))\n glbpar.append(float(temp[2]))\n\n # outlet parameters\n glk=[]\n glV=[]\n for scell in range(glnofswcells):\n temp2=[]\n temp3=[]\n if glnoflinks[scell] > 0:\n for link in range(glnoflinks[scell]):\n temp=fmodpar.readline().strip().split(\",\")\n# print(\"outlet\", temp)\n temp2.append(float(temp[1]))\n temp3.append(float(temp[2])) \n glk.append(temp2)\n glV.append(temp3)\n \n\n # delay parameter for units\n gldelay=[]\n for scell in range(glnofswcells):\n gldelay.append(int(fmodpar.readline().strip().split(\",\")[1]))\n\n # maun/shakawe rainfall ratio parameters\n glstatratio=[]\n for scell in range(glnofswcells):\n glstatratio.append(float(fmodpar.readline().strip().split(\",\")[1]))\n\n # groundwater reservoir areas and \"transmissivity\"\n glfa=[]\n glia=[]\n glkgw=[]\n glfa_total=[]\n for scell in range(glnofswcells):\n temp=fmodpar.readline().strip().split(\",\")\n# print(\"gw\", temp)\n glfa.append(float(temp[1]))\n glia.append(float(temp[2]))\n glkgw.append(float(temp[3]))\n glfa_total.append(float(temp[1])*glnofgwcells)\n \n \n outletpar=np.zeros([2,30])\n for i,k in enumerate(glk):\n for ii,kk in enumerate(k):\n outletpar[i,ii]=kk\n for i,v in enumerate(glV):\n for ii,vv in enumerate(v):\n outletpar[i,ii+10]=vv\n for i,c in enumerate(gldowncell):\n for ii,cc in enumerate(c):\n outletpar[i,ii+20]=cc\n\n glunitpar=np.array(gldelay).reshape(-1,1)\n glunitpar=np.append(glunitpar, np.array(glstatratio).reshape(-1,1), axis=1)\n glunitpar=np.append(glunitpar, np.array(glbpar).reshape(-1,1), axis=1)\n glunitpar=np.append(glunitpar, np.array(glexponent).reshape(-1,1), axis=1)\n glunitpar=np.append(glunitpar, np.array(glfa).reshape(-1,1), axis=1)\n glunitpar=np.append(glunitpar, np.array(glia).reshape(-1,1), axis=1)\n glunitpar=np.append(glunitpar, np.array(glkgw).reshape(-1,1), axis=1)\n print(glunitpar.shape, outletpar.shape)\n glunitpar=np.append(glunitpar, outletpar, axis=1)\n\n glgwpar=np.array([fdet,fpor,idet,ipor])\n print (\"done\")\n\n \n\n \ndef read_input(file_input):\n global glrecdate, glinflow, glprec, glpet, gltminmax, glnoftsteps,glstatratio\n\n print (\"reading input data from: \"+file_input)\n inputData=pd.read_csv(file_input, index_col=0, parse_dates=True)\n \n glrecdate=inputData.index.strftime(\"%Y-%m-%d\")\n glinflow=inputData['Inflow-Maun'].values.astype(\"float\")\n prec=inputData['Rainfall-Maun'].values.astype(\"float\")\n if inputData.shape[1]==3:\n glpet=inputData['PET-Maun'].values*0.85\n else:\n gltmin=inputData['MinTemperature-Maun'].values\n gltmax=inputData['MaxTemperature-Maun'].values\n evap_calc()\n glnoftsteps=inputData.shape[0]\n \n #calculating unit rainfall\n ratios=np.tile(np.array(glstatratio).reshape(-1,1),glnoftsteps).T\n glprec=prec[:].reshape(-1,1)*ratios\n print(glprec.shape, ratios.shape,prec.shape)\n print (str(glnoftsteps) + \" time steps read\")\n\n#*****************************************************************************\ndef read_init(file_init):\n global glsv_init, glfv_init, gliv_init, glnofswcells, glnofgwcells\n \n print (\"reading initial condition from: \"+file_init)\n with open(file_init, \"r\") as finit:\n data=finit.readlines()\n # initial storage of surface cells\n temp=data[0:glnofswcells]\n temp=np.array([x.strip().split(\",\") for x in temp])\n# print(temp)\n glsv_init=temp[:,1].astype(float)\n \n #initial storage of groundwater cells\n temp=data[glnofswcells:(glnofswcells*2)]\n temp=np.array([x.strip().split(\",\") for x in temp])\n# print (temp)\n glfv_init=temp[:,1:].astype(float)\n \n temp=data[(glnofswcells*2):(glnofswcells*3)]\n temp=np.array([x.strip().split(\",\") for x in temp])\n# print (temp)\n gliv_init=temp[:,1:].astype(float)\n \n print(\"done\")\n\n\n \n \n \n \n\n\n \n \n \nprint (\"parameters\",file_modpar)\nprint (\"initialization\", file_init)\nprint (\"input\",file_input)\nprint (\"spinup\", spinup)\nprint (\"output\", outputfiles)\n\n#debug=False\ndebug1=True\n\n#start timer\nt0 = timeit.default_timer()\n\n\nread_modset(file_modset) #reading model configuration\nread_modpar(file_modpar)\nread_input(file_input) #reading inputs\nread_init(file_init) #reading initial conditions\n\n\n\n\n\ntimer()\nread_modpar(file_modpar)\n\nresult=hcy.model_calc(glinflow, glprec, glpet, glsv_init, glfv_init, gliv_init, glunitpar, glgwpar) #this is when the model is actually run\ntimer()\n\n\nglfin_sqin, glfin_sa, glfin_sv, glfin_sev, glfin_spre, glfin_sqout,glfin_sinf,\\\nglfin_fv, glfin_fev,glfin_fpre,glfin_fgwout,glfin_finf,\\\nglfin_iv, glfin_iev,glfin_ipre=result\n\n\nglout_sqin=mergecells(glfin_sqin, spinup)\nglout_sa=mergecells(glfin_sa, spinup)\nglout_sv=mergecells(glfin_sv, spinup)\nglout_sqout=mergecells(glfin_sqout, spinup)\nglout_sev=mergecells(glfin_sev, spinup)\nglout_sinf=mergecells(glfin_sinf, spinup)\n\nprint(\"done\")\nprint()\n\nthresh=16\nmaxdist=400\n\nfor outputfile in outputfiles:\n print()\n print(outputfile)\n if \"allvolumes\" in outputfile:\n write_output_cellvolume(outputfile)\n if \"alloutflows\" in outputfile:\n write_output_cellq(outputfile)\n if \"inundateddistance\" in outputfile:\n calc_inundateddistance(thresh,maxdist, spinup*12)\n write_output_inundateddistance(outputfile)\n if \"totalinundation\" in outputfile:\n write_output_totalinundation(outputfile) #total inundation\n if \"hydroregions\" in outputfile:\n calc_hydroregions(thresh, spinup)\n write_output_hydroregions(outputfile) #hydroregions\n if \"finalcond\" in outputfile:\n write_init(outputfile, -1)\n if \"input\" in outputfile:\n donothing=True\n\n\nprint ()\nprint(\"success\")\n","sub_path":"model_v3.1/model_boteti.py","file_name":"model_boteti.py","file_ext":"py","file_size_in_byte":15919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"26783312","text":"from PyQt4 import QtGui\nfrom matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas\n\nfrom matplotlib.figure import Figure\nfrom matplotlib.font_manager import FontProperties\nfrom pylab import *\nimport numpy as np\nimport math\n\nclass MplCanvas(FigureCanvas):\n\n def __init__(self):\n self.fig = Figure()\n self.ax = self.fig.add_subplot(111)\n\n FigureCanvas.__init__(self, self.fig)\n FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding)\n FigureCanvas.updateGeometry(self)\n\n\nclass MatplotlibWidgetData(QtGui.QWidget):\n\n def __init__(self, parent = None):\n QtGui.QWidget.__init__(self, parent)\n self.canvas = MplCanvas()\n self.vbl = QtGui.QVBoxLayout()\n self.vbl.addWidget(self.canvas)\n self.setLayout(self.vbl)\n self.canvas.ax.set_title('Integrated traces', fontsize=12)\n self.canvas.fig.patch.set_alpha(0)\n self.intgrTrace = []\n \n def integrator(self, data):\n # integrate scope traces\n intTrace = sum(data) \n return intTrace\n \n def plot(self,data, radioMode):\n plotData = self.integrator(data)\n self.intgrTrace = np.append(self.intgrTrace, plotData)\n self.canvas.ax.clear()\n self.canvas.ax.plot(self.intgrTrace, 'b.-')\n self.canvas.ax.set_title('Integrated traces', fontsize=12)\n if radioMode == 'volt':\n self.canvas.ax.set_xlabel('Extraction Voltage (V)', fontsize=12)\n else:\n self.canvas.ax.set_xlabel(r'2nd Wavelength ($\\lambda$)', fontsize=12)\n self.canvas.ax.set_ylabel('Amplitude (arb.u.)', fontsize=12)\n if len(self.intgrTrace) > 1:\n self.canvas.ax.axis([-0.02*len(self.intgrTrace), len(self.intgrTrace)*1.02, \\\n min(self.intgrTrace)*1.2, max(self.intgrTrace)*1.2])\n self.canvas.fig.patch.set_alpha(0)\n self.canvas.fig.tight_layout()\n self.canvas.draw()\n","sub_path":"Test/MatplotlibWidgetData.py","file_name":"MatplotlibWidgetData.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"639627688","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nfrom codecs import open\nfrom os import path, system\nfrom re import compile as re_compile\n\nfrom setuptools import setup, find_packages\n\n# For convenience\nif sys.argv[-1] == \"publish\":\n system(\"python setup.py sdist upload\")\n sys.exit()\n\n\ndef read(filename):\n kwds = {\"encoding\": \"utf-8\"} if sys.version_info[0] >= 3 else {}\n with open(filename, **kwds) as fp:\n contents = fp.read()\n return contents\n\n\n# Get the version information\nhere = path.abspath(path.dirname(__file__))\nvre = re_compile(\"__version__ = \\\"(.*?)\\\"\")\nversion = vre.findall(read(path.join(here, \"eas_batman_wrapper\", \"__init__.py\")))[0]\n\n# Python module properties\nsetup(\n name=\"eas_batman_wrapper\",\n version=version,\n author=\"Dominic Ford\",\n author_email=\"dcf21@dcford.org.uk\",\n description=\"Helper functions for the PLATO WP36 EAS pipeline\",\n long_description=read(path.join(here, \"README.md\")),\n url=\"https://dcford.org.uk/\",\n license=\"MIT\",\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python :: 3.6\",\n \"Topic :: Scientific/Engineering :: Astronomy\",\n \"Topic :: Scientific/Engineering :: Physics\"\n ],\n keywords=\"PLATO\",\n packages=find_packages(exclude=[\"docs\", \"tests\"]),\n install_requires=[],\n extras_require={\n \"test\": [\"coverage\"]\n },\n package_data={\n \"\": [\"LICENSE\"],\n },\n include_package_data=True,\n data_files=None\n)\n","sub_path":"docker_containers/testbed/python_modules/eas_batman_wrapper/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"214870504","text":"# from flow.envs.multiagent.ring.accel import AccelEnv\n# from flow.envs.ring.lane_change_accel import LaneChangeAccelEnv\nfrom flow.core import lane_change_rewards as rewards\nfrom flow.core.params import InitialConfig, NetParams\nfrom flow.envs.multiagent.base import MultiEnv\n\nfrom gym.spaces.box import Box\nfrom gym.spaces.tuple import Tuple\nfrom gym.spaces.multi_discrete import MultiDiscrete\n\nimport numpy as np\nimport random\n\nfrom collections import defaultdict\nfrom pprint import pprint\n\nADDITIONAL_ENV_PARAMS = {\n # maximum acceleration for autonomous vehicles, in m/s^2\n \"max_accel\": 3,\n # maximum deceleration for autonomous vehicles, in m/s^2\n \"max_decel\": 3,\n # # lane change duration for autonomous vehicles, in s. Autonomous vehicles\n # # reject new lane changing commands for this duration after successfully\n # # changing lanes.\n # \"lane_change_duration\": 5,\n # # desired velocity for all vehicles in the network, in m/s\n # \"target_velocity\": 10,\n # # specifies whether vehicles are to be sorted by position during a\n # # simulation step. If set to True, the environment parameter\n # # self.sorted_ids will return a list of all vehicles sorted in accordance\n # # with the environment\n # 'sort_vehicles': False\n # bounds on the ranges of ring road lengths the autonomous vehicle is\n # trained on\n 'ring_length': [220, 270],\n}\n\nclass TD3MILCAccelEnv(MultiEnv):\n \"\"\"Fully observable lane change and acceleration environment.\n\n This environment is used to train autonomous vehicles to improve traffic\n flows when lane-change and acceleration actions are permitted by the rl\n agent.\n\n \"\"\"\n coef_log = []\n \n def __init__(self, env_params, sim_params, network, simulator='traci'):\n for p in ADDITIONAL_ENV_PARAMS.keys():\n if p not in env_params.additional_params:\n raise KeyError(\n 'Environment parameter \"{}\" not supplied'.format(p))\n\n super().__init__(env_params, sim_params, network, simulator)\n\n @property\n def action_space(self):\n \"\"\"See class definition.\"\"\"\n max_decel = self.env_params.additional_params[\"max_decel\"]\n max_accel = self.env_params.additional_params[\"max_accel\"]\n\n lb = [-abs(max_decel), -1] #* self.initial_vehicles.num_rl_vehicles\n ub = [max_accel, 1.] #* self.initial_vehicles.num_rl_vehicles\n shape = self.initial_vehicles.num_rl_vehicles,\n return Box(np.array(lb), np.array(ub), dtype=np.float32)\n\n @property\n def observation_space(self):\n \"\"\"See class definition.\"\"\"\n return Box(\n low=0,\n high=1,\n shape=(3 * self.initial_vehicles.num_vehicles,),\n dtype=np.float32)\n\n\n def Coef(self):\n global coef_log\n \n np.set_printoptions(precision=4)\n # print(self.time_counter)\n if self.time_counter == 0:\n coef_log = []\n rl_des = random.sample([i for i in np.arange(0,2,0.1)],1)[-1]\n uns4IDM_p = random.sample([i for i in np.arange(0, 2, 0.1)], 1)[-1]\n mlp = random.sample([i for i in np.arange(0,2,0.1)],1)[-1]\n \n coef_log.append([rl_des, uns4IDM_p, mlp])\n\n else:\n rl_des = coef_log[0][0]\n uns4IDM_p = coef_log[0][1]\n mlp = coef_log[0][2]\n \n return rl_des, uns4IDM_p, mlp\n \n def compute_reward(self, rl_actions, **kwargs):\n global r, pen1, pen2, pen3\n if rl_actions is None:\n return {}\n \n rls = self.k.vehicle.get_rl_ids()\n \n reward = {} # reward = 0\n\n # Training\n rl_des, uns4IDM_p, mlp = self.Coef()\n # print('compute_reward:{},{},{}'.format(rl_des, uns4IDM_p, mlp))\n\n # # Execution\n # rl_des = {}\n # uns4IDM_p = {}\n # mlp = {}\n #\n # for k in range(len(rls)):\n # rl_des[rls[k]] = self.initial_config.reward_params.get('rl_desired_speed', 0)[k]\n # uns4IDM_p[rls[k]] = self.initial_config.reward_params.get('uns4IDM_penalty', 0)[k]\n # mlp[rls[k]] = self.initial_config.reward_params.get('meaningless_penalty', 0)[k]\n\n # print(rl_des, uns4IDM_p, mlp)\n\n rl_action_p = self.initial_config.reward_params.get('rl_action_penalty', 0)\n\n for rl in rls:\n r = 0\n if rl_des:\n if self.k.vehicle.get_speed(rl) > 0.:\n vel = np.array([\n self.k.vehicle.get_speed(rl)\n ])\n\n # num_vehicles = len(rls)\n\n if any(vel < -100) or kwargs['fail']:\n return 0.\n\n target_vel = self.env_params.additional_params['target_velocity']\n max_cost = np.array([target_vel])\n max_cost = np.linalg.norm(max_cost)\n\n cost = vel - target_vel\n cost = np.linalg.norm(cost)\n\n # epsilon term (to deal with ZeroDivisionError exceptions)\n eps = np.finfo(np.float32).eps\n\n r = rl_des * (1 - (cost / (max_cost + eps)))\n # r = rl_des[rl] * (1 - (cost / (max_cost + eps)))\n\n reward[rl] = r\n\n for veh_id in rls:\n pen1 = 0\n if self.k.vehicle.get_leader(veh_id) is not None:\n if mlp:\n if self.k.vehicle.get_last_lc(veh_id) == self.time_counter:\n lane_leaders = self.k.vehicle.get_lane_leaders(veh_id)\n headway = [(self.k.vehicle.get_x_by_id(leader) - self.k.vehicle.get_x_by_id(veh_id))\n % self.k.network.length() / self.k.network.length() for leader in lane_leaders]\n # FOR N LANE\n if headway[self.k.vehicle.get_previous_lane(veh_id)] \\\n - headway[self.k.vehicle.get_lane(veh_id)] > 0:\n pen1 -= mlp * (headway[self.k.vehicle.get_previous_lane(veh_id)]\n - headway[self.k.vehicle.get_lane(veh_id)]) * 130 \\\n * (headway[self.k.vehicle.get_previous_lane(veh_id)])\n # pen1 -= mlp[veh_id] * (headway[self.k.vehicle.get_previous_lane(veh_id)]\n # - headway[self.k.vehicle.get_lane(veh_id)]) * 130 \\\n # * (headway[self.k.vehicle.get_previous_lane(veh_id)])\n\n reward[veh_id] += pen1\n\n for veh_id in rls:\n pen2 = 0\n if self.k.vehicle.get_follower(veh_id) is not None:\n v = self.k.vehicle.get_speed(veh_id)\n tw = self.k.vehicle.get_tailway(veh_id)\n follow_id = self.k.vehicle.get_follower(veh_id)\n\n if uns4IDM_p:\n T = 1\n a = 1\n b = 1\n s0 = 2\n\n if abs(tw) < 1e-3:\n tw = 1e-3\n\n if follow_id is None or follow_id == '':\n s_star = 0\n\n else:\n follow_vel = self.k.vehicle.get_speed(follow_id)\n s_star = s0 + max(\n 0, follow_vel * T + follow_vel * (follow_vel - v) /\n (2 * np.sqrt(a * b)))\n\n pen2 = uns4IDM_p * max(-5, min(0, 1 - (s_star / tw) ** 2))\n # pen2 = uns4IDM_p[veh_id] * max(-5, min(0, 1 - (s_star / tw) ** 2))\n\n reward[veh_id] = reward[veh_id] + pen2\n\n for rl in rls:\n if rl_action_p and rl_actions:\n pen3 = 0\n\n dir = rl_actions[rl][1::2]\n if dir <= -0.333:\n dir = -1\n elif dir >= 0.333:\n dir = 1\n else:\n dir = 0\n\n if dir:\n if self.k.vehicle.get_previous_lane(rl) == self.k.vehicle.get_lane(rl):\n pen3 -= rl_action_p\n\n reward[rl] = reward[rl] + pen3\n\n return reward\n\n def get_state(self):\n \"\"\"See class definition.\"\"\"\n # normalizers\n max_speed = self.k.network.max_speed()\n length = self.k.network.length()\n max_lanes = max(\n self.k.network.num_lanes(edge)\n for edge in self.k.network.get_edge_list())\n\n speed = [self.k.vehicle.get_speed(veh_id) / max_speed\n for veh_id in self.sorted_ids]\n pos = [self.k.vehicle.get_x_by_id(veh_id) / length\n for veh_id in self.sorted_ids]\n lane = [self.k.vehicle.get_lane(veh_id) / max_lanes\n for veh_id in self.sorted_ids]\n\n return np.array(speed + pos + lane)\n\n # def _to_lc_action(self, rl_action):\n # \"\"\"Make direction components of rl_action to discrete\"\"\"\n # if rl_action is None:\n # return rl_action\n # for i in range(1, len(rl_action), 2):\n # if rl_action[i] <= -0.333:\n # rl_action[i] = -1\n # elif rl_action[i] >= 0.333:\n # rl_action[i] = 1\n # else:\n # rl_action[i] = 0\n # return rl_action\n\n def _apply_rl_actions(self, actions):\n # actions = self._to_lc_action(actions)\n # print(actions)\n rl_ids = list(actions.keys())\n acceleration = []\n direction = []\n for i in actions.values():\n acceleration.append(i[::2])\n dir = i[1::2]\n if dir <= -0.333:\n dir = -1\n elif dir >= 0.333:\n dir = 1\n else:\n dir = 0\n\n direction.append(dir)\n\n # self.last_lane = self.k.vehicle.get_lane(self.k.vehicle.get_rl_ids())\n #\n # # re-arrange actions according to mapping in observation space\n # sorted_rl_ids = [veh_id for veh_id in self.sorted_ids\n # if veh_id in self.k.vehicle.get_rl_ids()]\n #\n # # represents vehicles that are allowed to change lanes\n # non_lane_changing_veh = \\\n # [self.time_counter <=\n # self.env_params.additional_params[\"lane_change_duration\"]\n # + self.k.vehicle.get_last_lc(veh_id)\n # for veh_id in sorted_rl_ids]\n #\n # # vehicle that are not allowed to change have their directions set to 0\n # direction[non_lane_changing_veh] = \\\n # np.array([0] * sum(non_lane_changing_veh))\n\n self.k.vehicle.apply_acceleration(rl_ids, acc=acceleration)\n self.k.vehicle.apply_lane_change(rl_ids, direction=direction)\n\n def additional_command(self):\n \"\"\"Define which vehicles are observed for visualization purposes.\"\"\"\n # specify observed vehicles\n if self.k.vehicle.num_rl_vehicles > 0:\n for veh_id in self.k.vehicle.get_human_ids():\n self.k.vehicle.set_observed(veh_id)\n\n\nclass TD3MILCAccelPOEnv(TD3MILCAccelEnv):\n \"\"\"POMDP version of LaneChangeAccelEnv.\n\n Required from env_params:\n\n * max_accel: maximum acceleration for autonomous vehicles, in m/s^2\n * max_decel: maximum deceleration for autonomous vehicles, in m/s^2\n * lane_change_duration: lane change duration for autonomous vehicles, in s\n * target_velocity: desired velocity for all vehicles in the network, in m/s\n\n \"\"\"\n\n def __init__(self, env_params, sim_params, network, simulator='traci'):\n super().__init__(env_params, sim_params, network, simulator)\n\n self.num_lanes = max(self.k.network.num_lanes(edge)\n for edge in self.k.network.get_edge_list())\n self.visible = []\n\n @property\n def observation_space(self):\n \"\"\"See class definition.\"\"\"\n return Box(\n low=-1,\n high=1,\n shape=(17*self.initial_vehicles.num_rl_vehicles, ),\n # shape=(2 * self.initial_vehicles.num_rl_vehicles *\n # (self.num_lanes + 5) + 2,),\n dtype=np.float32)\n\n def get_state(self):\n \"\"\"See class definition.\"\"\"\n # normalizers\n max_speed = self.k.network.max_speed()\n length = self.k.network.length()\n max_lanes = max(\n self.k.network.num_lanes(edge)\n for edge in self.k.network.get_edge_list())\n\n # # Execution\n # rls = self.k.vehicle.get_rl_ids()\n # RD = {}\n # UP = {}\n # MLP = {}\n #\n # for k in range(len(rls)):\n # RD[rls[k]] = self.initial_config.reward_params.get('rl_desired_speed', 0)[k]\n # UP[rls[k]] = self.initial_config.reward_params.get('uns4IDM_penalty', 0)[k]\n # MLP[rls[k]] = self.initial_config.reward_params.get('meaningless_penalty', 0)[k]\n \n \"\"\"See class definition.\"\"\"\n obs = {}\n for rl_id in self.k.vehicle.get_rl_ids():\n lane_leaders = self.k.vehicle.get_lane_leaders(rl_id) or rl_id\n lane_followers = self.k.vehicle.get_lane_followers(rl_id)\n\n # Velocity of vehicles\n lane_followers_speed = self.k.vehicle.get_lane_followers_speed(rl_id)\n lane_leaders_speed = self.k.vehicle.get_lane_leaders_speed(rl_id)\n\n rl_speed = self.k.vehicle.get_speed(rl_id)\n # for i in rl_speed:\n if rl_speed / max_speed > 1:\n rl_speed = 1.\n\n # Position of Vehicles\n lane_followers_pos = [self.k.vehicle.get_x_by_id(follower) for follower in lane_followers]\n lane_leaders_pos = [self.k.vehicle.get_x_by_id(leader) for leader in lane_leaders]\n\n # Sampling Characteristic\n rl_des, uns4IDM_p, mlp = self.Coef()\n \n # # Execution\n # rl_des = RD[rl_id]\n # uns4IDM_p = UP[rl_id]\n # mlp = MLP[rl_id]\n\n for i in range(0, max_lanes):\n # print(max_lanes)\n if self.k.vehicle.get_lane(rl_id) == i:\n lane_followers_speed = lane_followers_speed[max(0, i - 1):i + 2]\n lane_leaders_speed = lane_leaders_speed[max(0, i - 1):i + 2]\n lane_leaders_pos = lane_leaders_pos[max(0, i - 1):i + 2]\n lane_followers_pos = lane_followers_pos[max(0, i - 1):i + 2]\n\n if i == 0:\n f_sp = [(speed - rl_speed) / max_speed\n for speed in lane_followers_speed]\n f_sp.insert(0, -1.)\n l_sp = [(speed - rl_speed) / max_speed\n for speed in lane_leaders_speed]\n l_sp.insert(0, -1.)\n f_pos = [-((self.k.vehicle.get_x_by_id(rl_id) - pos) % length / length)\n for pos in lane_followers_pos]\n f_pos.insert(0, -1.)\n l_pos = [(pos - self.k.vehicle.get_x_by_id(rl_id)) % length / length\n for pos in lane_leaders_pos]\n l_pos.insert(0, +1.)\n lanes = [0.]\n\n elif i == max_lanes - 1:\n f_sp = [(speed - rl_speed) / max_speed\n for speed in lane_followers_speed]\n f_sp.insert(2, -1.)\n l_sp = [(speed - rl_speed) / max_speed\n for speed in lane_leaders_speed]\n l_sp.insert(2, -1.)\n f_pos = [-((self.k.vehicle.get_x_by_id(rl_id) - pos) % length / length)\n for pos in\n lane_followers_pos]\n f_pos.insert(2, -1.)\n l_pos = [(pos - self.k.vehicle.get_x_by_id(rl_id)) % length / length\n for pos in\n lane_leaders_pos]\n l_pos.insert(2, +1.)\n lanes = [1.]\n\n else:\n f_sp = [(speed - rl_speed) / max_speed\n for speed in lane_followers_speed]\n l_sp = [(speed - rl_speed) / max_speed\n for speed in lane_leaders_speed]\n f_pos = [-((self.k.vehicle.get_x_by_id(rl_id) - pos) % length / length)\n for pos in lane_followers_pos]\n l_pos = [(pos - self.k.vehicle.get_x_by_id(rl_id)) % length / length\n for pos in lane_leaders_pos]\n lanes = [0.5]\n\n rl_sp = [rl_speed / max_speed]\n positions = l_pos + f_pos\n speeds = rl_sp + l_sp + f_sp\n\n # Coef scailing\n coef = [i / 2 for i in [rl_des, uns4IDM_p, mlp]]\n observation = np.array(speeds + positions + lanes + coef)\n obs.update({rl_id: observation})\n\n return obs\n\n def additional_command(self):\n \"\"\"Define which vehicles are observed for visualization purposes.\"\"\"\n # specify observed vehicles\n for veh_id in self.visible:\n self.k.vehicle.set_observed(veh_id)","sub_path":"flow/flow/envs/multiagent/ring/MIDLC_Ring.py","file_name":"MIDLC_Ring.py","file_ext":"py","file_size_in_byte":17505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"195865328","text":"##############################\n# Anthony Luc, Michael Wang\n# ParadigmsFinal\n# December 1, 2017\n##############################\n\nimport cherrypy\nimport re, json\n\nclass MatchesController(object):\n def __init__(self, ldb):\n self.ldb = ldb\n\n # GET all matches of all players\n def GET(self):\n output = {'result' : 'success'}\n try:\n for k, v in self.ldb.matches.items():\n # k = acc_id\n # v = list of their games\n gameList = []\n for i in range(0, len(v)):\n gameList.append(v[i])\n output[k] = gameList\n except Exception as e:\n output['result'] = 'error'\n output['message'] = str(e)\n return json.dumps(output)\n\n # GET matches of player by acc_id\n def GET_KEY(self, key):\n # key = acc_id\n output = {'result' : 'success'}\n match_history = self.ldb.get_match_history(key)\n if match_history is None:\n output['result'] = 'error'\n output['message'] = 'account does not exist'\n else:\n output['matches'] = match_history\n return json.dumps(output)\n\n # POST mataches of player\n def POST_KEY(self, key):\n # key = acc_id\n output = {'result' : 'success'}\n try:\n dictData = cherrypy.request.body.read().decode()\n dictData = json.loads(dictData)\n self.ldb.set_match_history(key, dictData, dictData['match_num'])\n except Exception as e:\n output['result'] = 'error'\n output['message'] = str(e)\n return json.dumps(output)\n\n # DELETE a player's matches by acc_id\n def DELETE_KEY(self, key):\n # key = acc_id\n output = {'result' : 'success'}\n try:\n self.ldb.delete_match_history(key)\n except Exception as e:\n output['result'] = 'error'\n output['message'] = str(e)\n return json.dumps(output)\n\n","sub_path":"matches_controller.py","file_name":"matches_controller.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"471889282","text":"# '''\n# Linked List hash table key/value pair\n# '''\n\nclass LinkedPair:\n def __init__(self, key, value):\n self.key = key\n self.value = value\n self.next = None\n\nclass HashTable:\n '''\n A hash table that with `capacity` buckets\n that accepts string keys\n '''\n def __init__(self, capacity):\n self.count = 0\n self.capacity = capacity # Number of buckets in the hash table\n self.storage = [None] * capacity\n\n\n def _hash(self, key):\n # Use pythons built-in hash function\n '''\n Hash an arbitrary key and return an integer.\n\n You may replace the Python hash with DJB2 as a stretch goal.\n '''\n return hash(key)\n\n \n\n # def _hash_djb2(self, key):\n # '''\n # Hash an arbitrary key using DJB2 hash\n\n # OPTIONAL STRETCH: Research and implement DJB2\n # '''\n # pass\n\n\n def _hash_mod(self, key):\n '''\n Take an arbitrary key and return a valid integer index\n within the storage capacity of the hash table.\n '''\n return self._hash(key) % self.capacity\n\n\n def insert(self, key, value):\n '''\n Store the value with the given key.\n\n Hash collisions should be handled with Linked List Chaining.\n\n Fill this in.\n '''\n if self.count <= self.capacity:\n self.resize()\n # Hash the key, figure where in the array it should go\n indexLocation = self._hash_mod(key)\n current_node = self.storage[indexLocation]\n if current_node is None:\n self.storage[indexLocation] = LinkedPair(key, value)\n self.count += 1\n return\n if current_node.next is not None:\n while current_node.next is not None:\n if current_node.next is None:\n current_node.next = LinkedPair(key, value)\n self.count += 1\n return\n else:\n current_node.next = current_node.next.next\n else:\n current_node.next = LinkedPair(key, value)\n self.count += 1\n\n\n def remove(self, key):\n '''\n Remove the value stored with the given key.\n\n Print a warning if the key is not found.\n\n Fill this in.\n '''\n indexLocation = self._hash_mod(key)\n if self.storage[indexLocation] is None:\n print(\"Invalid key\")\n return\n self.storage[indexLocation] = None\n \n def retrieve(self, key):\n '''\n Retrieve the value stored with the given key.\n\n Returns None if the key is not found.\n\n Fill this in.\n '''\n indexLocation = self._hash_mod(key)\n current_node = self.storage[indexLocation]\n # if current_node.key is None:\n # print (\"Invalid key\")\n # return\n if current_node is None:\n return None\n if current_node.key is key:\n #print(\"got it on first try\")\n return current_node.value\n else:\n while current_node.next is not None:\n if current_node.next.key is key:\n #print(\"found it in the list\")\n return current_node.next.value\n else:\n #print(\"moving on\")\n current_node = current_node.next\n return current_node.value\n\n def resize(self):\n '''\n Doubles the capacity of the hash table and\n rehash all key/value pairs.\n\n Fill this in.\n '''\n self.capacity *= 2\n new_storage = [None] * self.capacity\n for i in self.storage:\n if i is not None:\n newIndex = self._hash_mod(i.key)\n new_storage[newIndex] = LinkedPair(i.key, i.value)\n self.storage = new_storage\n\n# hashT = HashTable(2)\n# print(hashT.storage)\n# hashT.insert(\"gabba\", \"haha\")\n# print(hashT.storage)\n# hashT.insert(\"zylophone\", \"lol\")\n# print(hashT.storage)\n# print(hashT.storage)\n# hashT.insert(\"gabba222\", \"haha222\")\n# print(hashT.storage)\n# hashT.insert(\"zylophone222\", \"lol222\")\n# print(hashT.storage)\n# print(\"Key return: \", hashT.retrieve(\"gabba\"))\n# print(\"Key return: \", hashT.retrieve(\"zylophone\"))\n# print(\"Key return: \", hashT.retrieve(\"gabba222\"))\n# print(\"Key return: \", hashT.retrieve(\"zylophone222\"))\n# print(hashT.storage)\n# hashT.remove(\"gabba\")\n# print(hashT.storage)\n# hashT.resize()\n# print(hashT.storage)\n# print(\"Key return: \", hashT.retrieve(\"gabba\"))\n# print(\"Key return: \", hashT.retrieve(\"zylophone\"))\n\n# if __name__ == \"__main__\":\n# ht = HashTable(2)\n# print(\"storage: \", ht.storage)\n# ht.insert(\"line_1\", \"Tiny hash table\")\n# ht.insert(\"line_2\", \"Filled beyond capacity\")\n# ht.insert(\"line_3\", \"Linked list saves the day!\")\n\n# print(\"\")\n\n# # Test storing beyond capacity\n# print(ht.retrieve(\"line_1\"))\n# print(ht.retrieve(\"line_2\"))\n# print(ht.retrieve(\"line_3\"))\n\n# # Test resizing\n# old_capacity = len(ht.storage)\n# ht.resize()\n# new_capacity = len(ht.storage)\n\n# print(f\"\\nResized from {old_capacity} to {new_capacity}.\\n\")\n\n# # Test if data intact after resizing\n# print(ht.retrieve(\"line_1\"))\n# print(ht.retrieve(\"line_2\"))\n# print(ht.retrieve(\"line_3\"))\n\n# print(\"\")\n","sub_path":"src/hashtable.py","file_name":"hashtable.py","file_ext":"py","file_size_in_byte":5332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"134504342","text":"import os\nimport sys\nimport logging\nimport libvirt\nimport subprocess\nfrom config import opts\n\nfrom libvirt import libvirtError\n\nLIBVIRT_URL = 'qemu+ssh://{user}@{host}/system'.format(user=opts.user, host=opts.host)\n\n__author__ = 'sshnaidm'\n\ndef handler(ctxt, err):\n global errno\n errno = err\nlibvirt.registerErrorHandler(handler, 'context')\n\nconn = libvirt.open(LIBVIRT_URL)\n\ndef run_cmd(cmd):\n \"\"\"\n Return the exit status and output to stdout and stderr.\n \"\"\"\n logging.debug(\"Running command: %s\" % \" \".join(cmd))\n proc = subprocess.Popen(cmd, stderr=subprocess.PIPE,\n stdout=subprocess.PIPE,\n close_fds=True)\n ret = proc.wait()\n print >> sys.stderr, \"\\n\".join(proc.stdout.readlines()), \"\\n\".join(proc.stderr.readlines())\n return ret, proc.stdout.readlines(), proc.stderr.readlines()\n\ndef basic(name):\n return name + \"-\"\n\ndef erase_net(lab):\n names = [i.name() for i in conn.listAllNetworks() if basic(lab) in i.name()]\n for net_name in names:\n try:\n net = conn.networkLookupByName(net_name)\n except libvirtError:\n print >> sys.stderr, \"Network %s wasn't found, nothing to delete\" % net_name\n try:\n net.destroy()\n except libvirtError:\n print >> sys.stderr, \"Network %s wasn't active, undefining...\" % net_name\n net.undefine()\n print >> sys.stderr, \"Network %s was deleted\" % net_name\n\ndef erase_pool(lab):\n names = [i.name() for i in conn.listAllStoragePools() if lab + \"-default\" in i.name()]\n for name in names:\n try:\n pool = conn.storagePoolLookupByName(name)\n except libvirtError:\n print >> sys.stderr, \"Pool not found, nothing to delete\"\n return\n try:\n pool.destroy()\n except libvirtError:\n print >> sys.stderr, \"Pool wans't active, undefining...\"\n pool.undefine()\n print >> sys.stderr, \"Pool %s was deleted\" % (lab + \"-default\")\n\ndef erase_vm(lab):\n names = [i.name() for i in conn.listAllDomains() if basic(lab) in i.name()]\n for name in names:\n try:\n vm = conn.lookupByName(name)\n except libvirtError:\n print >> sys.stderr, \"Domain {name} not found, nothing to delete\".format(name=name)\n return\n try:\n vm.destroy()\n except libvirtError:\n print >> sys.stderr, \"Domain wans't active, undefining...\"\n vm.undefine()\n print >> sys.stderr, \"Domain {name} deleted\".format(name=name)\n\ndef shutdown_vm(lab):\n names = [i.name() for i in conn.listAllDomains() if basic(lab) in i.name()]\n for name in names:\n try:\n vm = conn.lookupByName(name)\n except libvirtError:\n print >> sys.stderr, \"Domain {name} not found, nothing to shutdown\".format(name=name)\n return\n try:\n vm.shutdown()\n print >> sys.stderr, \"Domain {name} was shut down...\".format(name=name)\n except Exception as e:\n print >> sys.stderr, \"Domain {name} was NOT shut down...\\n{e}\".format(name=name, e=str(e))\n\n\ndef remove_all_imgs(lab_img_path):\n if os.path.exists(lab_img_path):\n for i in os.listdir(lab_img_path):\n os.remove(os.path.join(lab_img_path, i))\n\ndef found_pool(pool_name):\n try:\n pool = conn.storagePoolLookupByName(pool_name)\n return pool\n except libvirtError:\n return None\n\ndef make_network_name(lab, name):\n return lab + \"-net-\" + name\n","sub_path":"tools/cloud/cloudtools.py","file_name":"cloudtools.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"67692055","text":"# Written by Eric Martin for COMP9021\n\n\n'''\nDraws three coloured dodecagrams, separed by a distance of one third\nthe length of the edges, and centred in the window that displays them.\n'''\n\n\nfrom turtle import *\n\n\nedge_length = 50\nangle = 60\n\ndef draw_dodecagram(colour1,colour2):\n\n for _ in range(3):\n color(colour1)\n forward(edge_length)\n right(angle)\n color(colour2)\n forward(edge_length)\n left(angle * 2)\n forward(edge_length)\n right(angle)\n color(colour1)\n forward(edge_length)\n left(angle*2)\ndef teleport(distance):\n penup()\n right(angle)\n forward(distance)\n pendown()\n\n\n# Make sure that the dodecagrams are centred horizontally in the window that displays them.\n# Without the following statement, the left end of the horizontal edge of the green dodecagram,\n# from which the drawing starts, would be at the centre of the screen\n# (so the dodecagrams are not quite centred vertically).\nteleport(-edge_length // 2 )\n# Draw the middle dodecagram, then the left dodecagram, then the right dodecagram.\ndraw_dodecagram('blue','red')\n\n","sub_path":"Challenges/hexagram.py","file_name":"hexagram.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"14357009","text":"import os\nimport numpy as np\nimport pickle\nimport random\nimport time\n\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader, random_split\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import optim\nimport tqdm\nfrom PIL import Image\n\nimport utils\nimport datasets\nimport models\n\nnum_epochs = 3\nATTR_SIZE = 196\nBATCH_SIZE = 8\nSAVE_EMB = True\nTRAIN_MODEL = True\nCAL_SIMILARITY = False\nTRAIN_RATIO = 0.85\n\ndata_dir = '/data2fast/users/haroon/facad_data/'\n# data_dir = 'facad_data'\n\nexperiment_BASE = 'experiments'\nexperiment_name = os.path.join(experiment_BASE, 'cosine_base')\nprint(f\"Running Experiment: {experiment_name} \\n\")\nos.makedirs(experiment_name, exist_ok=True)\n\nmodel_dir = os.path.join(experiment_name, 'weights')\nembeddings_dir = os.path.join(experiment_name,'embeddings')\noutput_dir = os.path.join(experiment_name, 'output')\n\nimages_dir = os.path.join(data_dir, 'images')\nimgs_list = os.listdir(images_dir)\n\n# split data into train and test splits\nif CAL_SIMILARITY:\n train_img_set, test_img_set = utils.train_test_split(experiment_name, imgs_list, TRAIN_RATIO)\n utils.dump_pickle(os.path.join(data_dir, 'train_img_set.pkl'), train_img_set)\n utils.dump_pickle(os.path.join(data_dir, 'test_img_set.pkl'), test_img_set)\nelse:\n train_img_set = utils.read_pickle(os.path.join(data_dir, 'train_img_set.pkl'))\n test_img_set = utils.read_pickle(os.path.join(data_dir, 'test_img_set.pkl'))\n\nfull_img_set = train_img_set + test_img_set\n\nif CAL_SIMILARITY:\n print('Composing the attributes for all images..')\n img_attr_dict = utils.compose_img_attr_vects(data_dir, full_img_set)\n utils.dump_pickle(os.path.join(data_dir, 'img_attr_dict.pkl'), img_attr_dict)\n\n for mode in ['train', 'test']:\n print(f'Calculating the similarity scores for {mode} images...')\n if mode == 'train':\n similarity_dict = utils.cal_similarity_dict_torch(img_attr_dict, train_img_set)\n utils.dump_pickle(os.path.join(data_dir, 'train_similarity_dict.pkl'), similarity_dict)\n else:\n similarity_dict = utils.cal_similarity_dict_torch(img_attr_dict, test_img_set)\n utils.dump_pickle(os.path.join(data_dir, 'test_similarity_dict.pkl'), similarity_dict)\n\nmeta_dict = {}\ntrain_embeddings_dir = os.path.join(embeddings_dir, 'train')\ntest_embeddings_dir = os.path.join(embeddings_dir, 'test')\n\nos.makedirs(model_dir, exist_ok=True)\nos.makedirs(output_dir, exist_ok=True)\nos.makedirs(train_embeddings_dir, exist_ok=True)\nos.makedirs(test_embeddings_dir, exist_ok=True)\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nimg_transforms = transforms.Compose([transforms.Resize((224,224)),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n\ntrain_dataset = datasets.FacadAttrDatasetTriplet(data_dir, train_img_set, mode='train',\n transforms = img_transforms)\n\ntest_dataset = datasets.FacadAttrDatasetTriplet(data_dir, test_img_set, mode='test',\n transforms = img_transforms)\n\ntrain_dataloader = DataLoader(train_dataset,\n shuffle=True,\n num_workers=BATCH_SIZE,\n batch_size=BATCH_SIZE)\n\ntest_dataloader = DataLoader(test_dataset,\n shuffle=False,\n num_workers=BATCH_SIZE,\n batch_size=BATCH_SIZE)\n\nimageEncoder = models.ImageEncoder().to(device)\nattrEncoder = models.AttrEncoder(ATTR_SIZE).to(device)\n\ncriterion = nn.CosineEmbeddingLoss(margin=0.3)\nparams = list(imageEncoder.parameters()) + list(attrEncoder.parameters())\n\noptimizer = optim.Adam(params,lr = 0.00005, weight_decay=0.001)\n\n\ndef train_model(BASE_PATH):\n iteration_number = 0\n counter = []\n loss_history = []\n train_accuracies = []\n test_accuracies = []\n test_precisions = []\n for epoch in range(num_epochs):\n for i, data in enumerate(train_dataloader):\n anc_img, anc_attr ,pos_img, pos_attr, neg_img , neg_attr,_,_ = data\n anc_img, anc_attr, pos_img, pos_attr, neg_img, neg_attr = anc_img.to(device), anc_attr.to(device),pos_img.to(device), pos_attr.to(device), neg_img.to(device), neg_attr.to(device)\n\n diff_attrs = pos_attr - anc_attr\n optimizer.zero_grad()\n\n anc_emb = imageEncoder(anc_img)\n pos_emb = imageEncoder(pos_img)\n neg_emb = imageEncoder(neg_img)\n\n attr_emb = attrEncoder(diff_attrs.float())\n\n y = torch.ones(anc_img.shape[0],).to(device)\n y_hat = -torch.ones(anc_img.shape[0],).to(device)\n\n loss_pos = criterion(anc_emb + attr_emb, pos_emb, y)\n loss_neg = criterion(anc_emb + attr_emb, neg_emb, y_hat)\n\n loss = loss_pos + loss_neg\n\n loss.backward()\n optimizer.step()\n\n if i % 1000 == 0 :\n iteration_number +=1000\n counter.append(iteration_number)\n loss_history.append(loss.item())\n print(f\"Epoch {epoch}/{num_epochs} \\t Current loss: {loss.item()}\\t Test Accs: {test_accuracies}\\t P@10: {test_precisions}\")\n\n if epoch % 1 == 0:\n print(f\"\\nCheckpointing at epoch : {epoch}\")\n trian_save_dir = os.path.join(train_embeddings_dir, \"epoch_\" + str(epoch))\n test_save_dir = os.path.join(test_embeddings_dir, \"epoch_\" + str(epoch))\n\n os.makedirs(trian_save_dir, exist_ok=True)\n os.makedirs(test_save_dir, exist_ok=True)\n\n print(\"Embedding all images using latest model...\")\n # train_splits = embed_all_images(train_dataloader, imageEncoder, os.path.join(train_embeddings_dir, \"epoch_\" + str(epoch)))\n test_splits = embed_all_images(test_dataloader, imageEncoder, test_save_dir)\n\n print('Calculating retrieval accuracy for current model...')\n # train_accuracy = test_model(train_dataloader, imageEncoder, attrEncoder, trian_save_dir, train_splits)\n test_accuracy, test_precision = test_model(test_dataloader, imageEncoder, attrEncoder, test_save_dir, test_splits)\n\n train_accuracy = 1.0\n\n train_accuracies.append(round(train_accuracy,4))\n test_accuracies.append(round(test_accuracy,4))\n test_precisions.append(round(test_precision, 4))\n print(f\"Epoch {epoch+1}/{num_epochs} \\t Current loss: {loss.item()} \\tTest Acc: {test_accuracy} \\t P@10: {test_precision}\")\n\n print(\"Saving model to disk..\")\n torch.save(imageEncoder.state_dict(), os.path.join(BASE_PATH, f'img_encoder_{epoch}.pt'))\n torch.save(attrEncoder.state_dict(), os.path.join(BASE_PATH, f'attr_encoder_{epoch}.pt'))\n\n utils.plot_loss(loss_history, os.path.join(output_dir, 'loss.png'))\n utils.plot_accuracies(train_accuracies, test_accuracies, os.path.join(output_dir, 'acc.png'))\n print('Training Finished...')\n print(f\"Train Accuracies: {train_accuracies}\")\n print(f\"Test Accuracies: {test_accuracies}\")\n print(f\"Precisions: {test_precisions}\")\n return imageEncoder, attrEncoder\n\n\ndef embed_all_images(dataloader, model, embeddings_dir, mode='train'):\n model.eval()\n emb_matrix = None\n img_list = []\n split = 0\n for i, data in enumerate(dataloader):\n img, _ ,_ ,_,_,_, names,_ = data\n img = img.to(device)\n img_emb = model(img)\n if emb_matrix is None:\n emb_matrix = img_emb\n else:\n emb_matrix = torch.cat((emb_matrix, img_emb),0)\n img_list += list(names)\n if emb_matrix.shape[0] >= 10:\n pickle.dump(emb_matrix, open(os.path.join(embeddings_dir, f'emb_matrix_{split}.pt'), 'wb'))\n pickle.dump(img_list, open(os.path.join(embeddings_dir, f'img_list_{split}.list'), 'wb'))\n split += 1\n emb_matrix = None\n img_list = []\n\n # embed the last split\n pickle.dump(emb_matrix, open(os.path.join(embeddings_dir, f'emb_matrix_{split}.pt'), 'wb'))\n pickle.dump(img_list, open(os.path.join(embeddings_dir, f'img_list_{split}.list'), 'wb'))\n return split\n\ndef all_pairs_euclid_torch(A, B):\n sqrA = torch.sum(torch.pow(A, 2), 1, keepdim=True).expand(A.shape[0], B.shape[0])\n sqrB = torch.sum(torch.pow(B, 2), 1, keepdim=True).expand(B.shape[0], A.shape[0]).t()\n return torch.sqrt(\n sqrA - 2*torch.mm(A, B.t()) + sqrB\n )\n\ndef evaluate_query_split(attr_emb, emb_matrix, k=10):\n euclidean_distance = all_pairs_euclid_torch(attr_emb, emb_matrix)\n if euclidean_distance.shape[1] < k:\n k = euclidean_distance.shape[1]\n return torch.topk(euclidean_distance, k=k,largest=False,dim=1)\n\ndef plot_topk(top_images, transforms, save_path=None):\n\n batch = None\n for img in top_images:\n img = Image.open(img)\n img = transforms(img).unsqueeze(dim=0)\n if batch is None:\n batch = img\n else:\n batch = torch.cat((batch, img),0)\n\n utils.imshow(torchvision.utils.make_grid(batch), save_path=save_path)\n\ndef load_embeddings(embeddings_dir, split):\n emb_matrix = pickle.load(open(os.path.join(embeddings_dir,f'emb_matrix_{split}.pt'), 'rb'))\n img_list = pickle.load(open(os.path.join(embeddings_dir, f'img_list_{split}.list'), 'rb'))\n return emb_matrix, img_list\n\ndef evaluate_query(embeddings_dir, attr_emb, splits, k=10):\n batch_size = attr_emb.shape[0]\n top_dists = [[]]*batch_size\n top_imgs = [[]]*batch_size\n topk_imgs = []\n\n for split in range(splits+1):\n # load embeddings for the current split\n emb_matrix, img_list = load_embeddings(embeddings_dir, split)\n\n if emb_matrix is None:\n continue\n\n topk_split = evaluate_query_split(attr_emb, emb_matrix, k)\n\n topk_split_dist = topk_split.values.view(batch_size, -1).tolist()\n topk_split_indices = topk_split.indices.view(batch_size, -1).tolist()\n\n for i in range(batch_size):\n topk_split_imgs = [img_list[k] for k in topk_split_indices[i]]\n\n top_dists[i].extend(topk_split_dist[i])\n top_imgs[i].extend(topk_split_imgs)\n\n for i in range(batch_size):\n topk = np.argpartition(top_dists[i], k)[:k]\n topk_imgs.append([top_imgs[i][idx] for idx in topk])\n\n return topk_imgs\n\ndef eval_results(topk_predictions, targets, attr2, img_attr_dict):\n correct = 0\n total = 0\n true_positive = 0\n total_precision = 0\n correct_ids = []\n\n attr2 = attr2.cpu().numpy()\n for pred, target, t_attr in zip(topk_predictions, targets, attr2):\n total += 1\n Flag = True\n \n for img in pred:\n total_precision += 1\n img_attr = img_attr_dict[img]\n\n if np.allclose(img_attr,t_attr):\n if Flag:\n correct_ids.append(total - 1)\n correct += 1\n Flag = False\n true_positive += 1\n return correct, total, true_positive, total_precision, correct_ids\n\ndef test_model(dataloader, imageEncoder, attrEncoder, embeddings_dir, splits):\n imageEncoder.eval()\n attrEncoder.eval()\n\n img_attr_dict = utils.read_pickle(os.path.join(data_dir, 'img_attr_dict.pkl'))\n\n total = 0\n correct = 0\n tp = 0\n count = 0\n prec_total = 0\n for i, data in enumerate(dataloader):\n img1, attr1 ,img2, attr2,_,_, src_names, target_names = data\n img1, attr1, img2, attr2 = img1.to(device), attr1.to(device), img2.to(device), attr2.to(device)\n\n diff_attrs = attr2 - attr1\n\n add_attrs, sub_attrs = utils.decompose_feature_batch(data_dir, diff_attrs)\n\n img1_emb = imageEncoder(img1)\n attr_emb = attrEncoder(diff_attrs.float())\n\n topk = evaluate_query(embeddings_dir, img1_emb + attr_emb, splits)\n\n correct_batch, _, tp_batch, tp_total, correct_ids = eval_results(topk, target_names, attr2, img_attr_dict)\n\n if len(correct_ids) > 0:\n if count < 5:\n utils.save_imgs(src_names,target_names, topk, correct_ids, images_dir,output_dir, img_attr_dict, add_attrs, sub_attrs)\n count += 1\n \n correct += correct_batch\n total += len(src_names)\n tp += tp_batch\n prec_total += tp_total\n\n return correct / total, tp / prec_total\n\n\n# trian the model\nif TRAIN_MODEL:\n imageEncoder, attrEncoder = train_model(model_dir)\nelse:\n print(f\"Loading weights from ./{model_dir}\")\n imageEncoder.load_state_dict(torch.load(os.path.join(model_dir, f'img_encoder_{num_epochs-1}.pt')))\n attrEncoder.load_state_dict(torch.load(os.path.join(model_dir, f'attr_encoder_{num_epochs-1}.pt')))\n imageEncoder.eval()\n attrEncoder.eval()\n print(f\"Weights Loaded!\")\n\n\n# Embed all the images\nif SAVE_EMB:\n print('Extracting Embeddings for test images...')\n splits = embed_all_images(test_dataloader, imageEncoder, embeddings_dir)\n print(f'Embeddings saved in {splits} splits')\n meta_dict[\"SPLITS\"] = splits\n pickle.dump(meta_dict, open(os.path.join(embeddings_dir, f'meta_dict.pkl'), 'wb'))\n\n\n# Load the embeddings from disk\nprint('Loading embeddings from disk...')\nmeta_dict = pickle.load(open(os.path.join(embeddings_dir, f'meta_dict.pkl'), 'rb'))\nsplits = meta_dict[\"SPLITS\"]\nprint(f\"Found {splits} splits for embedding matrix\")\n\n## Test the model\nprint(\"Evaluating Model...\")\nret_accuracy, ret_prec = test_model(test_dataloader, imageEncoder, attrEncoder, embeddings_dir, splits)\nprint(f\"Final Acc@10: {ret_accuracy * 100}\\t P@10: {ret_prec * 100}\")\n","sub_path":"main_cosine.py","file_name":"main_cosine.py","file_ext":"py","file_size_in_byte":13748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"195486104","text":"A = [2,4,6,8,1,1]\nB = [1,3,5,7,9,9]\nC = []\n\ndef llenar_C (A,B):\n n = len(A)//2\n for i in range(n):\n Ai = A[i+1]**2\n Bi = B[2*i]\n mult = Ai*Bi\n suma = mult + B[n+i]\n C.append(suma)\n resultado = C\n print ('C =', resultado)\n print('\\n')\n\nprint('\\n')\nprint('A continuacion verá el resultado de el arreglo propuesto ')\nllenar_C (A,B)","sub_path":"py3_ciclos/lista.py","file_name":"lista.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"224738414","text":"import json\r\n\r\ndef get_stored_username():\r\n\tfilename = \"user_name.json\"\r\n\ttry:\r\n\t\twith open(filename) as f:\r\n\t\t\tusername = json.load(f)\r\n\texcept FileNotFoundError:\r\n\t\treturn None\r\n\telse:\r\n\t\treturn username\r\n\r\n\r\ndef get_new_username():\r\n\tname = input(\"What is your name? \")\r\n\tfilename = \"user_name.json\"\r\n\twith open(user_name, 'w') as f:\r\n\t\tjson.dump(name, f)\r\n\treturn name\r\n\t\r\ndef greet_user():\r\n\tusername = get_stored_username()\r\n\t\r\n\tif username:\r\n\t\tprint(\"Welcome back, \" + username + \"!\")\r\n\telse:\r\n\t\tusername = get_new_username()\r\n\t\tprint(\"We'll remember you when you come back \" + username + \"!\")\r\n\t\t\r\n\r\ngreet_user()\r\n\t\r\n\r\n\r\n","sub_path":"remember_me.py","file_name":"remember_me.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"610658668","text":"# ********************************************************\n# * ---------------------------------------------- *\n# * Douglas Eduardo Valente Pires - dpires@dcc.ufmg.br *\n# * www.dcc.ufmg.br/~dpires *\n# * Last modification :: 26/10/2015 *\n# * ---------------------------------------------- *\n# ********************************************************\n\nfrom flask import Flask, request, session, redirect, url_for, abort, render_template, flash\nfrom flask_mail import Message, Mail\nfrom rq import Queue\nfrom sqlalchemy.orm import scoped_session, sessionmaker\n\nfrom worker_single import conn\n\n# ============= #\n# CONFIGURATION #\n# ============= #\n\nUPLOAD_FOLDER = 'mcsm_ab/predictions/data'\nCODE_FOLDER = 'mcsm_ab/predictions/code'\nRESULT_FOLDER = 'mcsm_ab/static/results'\n#UPLOAD_FOLDER = '/var/www/mcsm_ab/mcsm_ab/predictions/data'\n#CODE_FOLDER = '/var/www/mcsm_ab/mcsm_ab/predictions/code'\n#RESULT_FOLDER = '/var/www/mcsm_ab/mcsm_ab/static/results'\n\nJOB_TIMEOUT = 3600\nDEBUG = True\n\n# DEFINE THE APP\napp = Flask(__name__)\n\napp.secret_key = 'mcsm_web_is_awesome'\napp.config.from_object(__name__)\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['CODE_FOLDER'] = CODE_FOLDER\n\napp.config[\"MAIL_SERVER\"] = \"smtp.gmail.com\"\napp.config[\"MAIL_PORT\"] = 465\napp.config[\"MAIL_USE_SSL\"] = True\napp.config[\"MAIL_USERNAME\"] = 'mcsm.contact@gmail.com'\napp.config[\"MAIL_PASSWORD\"] = 'devp.mcsm.cont@ct'\n\nqueue_single = Queue(\"mcsm-ab-single\",connection=conn)\nqueue_list = Queue(\"mcsm-ab-list\",connection=conn)\n\n# ADD VIEWS\nimport mcsm_ab.ab_antigen\nimport mcsm_ab.utils\nimport mcsm_ab.main_handler\n\n# ===========\n# RUN THE APP\n# ===========\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"130869346","text":"from airflow.utils.decorators import apply_defaults\nfrom airflow.models import BaseOperator\nfrom airflow.plugins_manager import AirflowPlugin\nfrom nodb import NoDB\n\n\nclass NoDBOperator(BaseOperator):\n \"\"\"\n Base NoDB Operator. Use the derived operators to perform actions on objects\n :param bucket: existing S3 bucket.\n :type bucket: str\n :param index: the NoDB index to save, load or delete from\n :type index: str\n :param serializer: the serializer type to use. Defaults to pickle. Don't use pickle with untrusted data\n :type serializer: str\n :param human_readable_indexes: whether to make the index readable instead of hashed.\n :type human_readable_indexes: bool\n \"\"\"\n @apply_defaults\n def __init__(self, bucket, index, serializer='pickle', human_readable_indexes=False, *args, **kwargs):\n super(NoDBOperator, self).__init__(*args, **kwargs)\n self.bucket = bucket\n self.index = index\n self.serializer = serializer\n self.human_readable_indexes = human_readable_indexes\n\n self.nodb = NoDB()\n self.nodb.bucket = self.bucket\n self.nodb.index = self.index\n self.nodb.serializer = self.serializer\n self.nodb.human_readable_indexes = self.human_readable_indexes\n\n def prepared_request(self):\n pass\n\n def execute(self, context):\n self.prepared_request()\n\n return\n\n\nclass NoDBSaveObjectOperator(NoDBOperator):\n \"\"\"\n Save an object to NoDB\n :param obj: the object to save. Valid object types depend on what type of serializer is being used\n :type obj: object\n \"\"\"\n ui_color = '#3cede7' # blue\n @apply_defaults\n def __init__(self, obj, *args, **kwargs):\n super(NoDBSaveObjectOperator, self).__init__(*args, **kwargs)\n self.obj = obj\n\n def prepared_request(self):\n return self.nodb.save(obj=self.obj)\n\n\nclass NoDBLoadObjectOperator(NoDBOperator):\n \"\"\"\n Load an object from NoDB\n :param idx: the string for searching the index\n :type idx: str\n :param metainfo: if true, return datetime and uuid of the object\n :type metainfo: bool\n \"\"\"\n ui_color = '#66ed3d' # green\n\n @apply_defaults\n def __init__(self, search, metainfo=False, *args, **kwargs):\n super(NoDBLoadObjectOperator, self).__init__(*args, **kwargs)\n self.search = search\n self.metainfo = metainfo\n\n def prepared_request(self):\n if self.metainfo:\n return self.nodb.load(index=self.search, metainfo=self.metainfo)\n else:\n return self.nodb.load(index=self.search)\n\n\nclass NoDBDeleteObjectOperator(NoDBOperator):\n \"\"\"\n Delete an object from NoDB\n :param idx: the string for searching the index\n :type idx: str\n \"\"\"\n ui_color = '#f48c42' # orange\n\n @apply_defaults\n def __init__(self, search, *args, **kwargs):\n super(NoDBDeleteObjectOperator, self).__init__(*args, **kwargs)\n self.search = search\n\n def prepared_request(self):\n return self.nodb.delete(index=self.search)\n\n\nclass AirflowTestPlugin(AirflowPlugin):\n name = 'nodb_plugin'\n operators = [\n NoDBLoadObjectOperator,\n NoDBSaveObjectOperator,\n NoDBDeleteObjectOperator\n ]\n","sub_path":"plugins/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"441800113","text":"from __future__ import division\r\n\r\nimport os\r\nimport os.path\r\nimport os.path\r\nimport random\r\nimport math\r\n\r\nimport torch\r\nimport torch.utils.data as data\r\n\r\nfrom .dataset_utils.util_func import *\r\nfrom .dataset_utils import frame_utils\r\nfrom . import dataset_read\r\n\r\n\r\nclass UCF101AsClips(data.Dataset):\r\n \"\"\"\r\n \"\"\"\r\n\r\n def __init__(self, args, is_train, root=None, loader=default_loader,\r\n replicates=1):\r\n self.args = args\r\n self.is_train = is_train\r\n self.train_size = args.train_size\r\n self.render_size = args.render_size\r\n self.real_size = None\r\n self.replicates = replicates\r\n self.snippet_len = args.snippet_len\r\n self.K = args.K\r\n self.replicates = replicates\r\n \r\n train_set, validation_set = dataset_read.get_ucf101_info(root=root)\r\n video_info = train_set if is_train else validation_set\r\n frames_list, class_list, frames_num = video_info\r\n assert len(frames_list) == len(class_list) == len(frames_num)\r\n\r\n if self.is_train:\r\n ind = list(range(len(frames_list)))\r\n random.shuffle(ind)\r\n frames_list = [frames_list[v] for v in ind]\r\n class_list = [class_list[v] for v in ind]\r\n frames_num = [frames_num[v] for v in ind]\r\n self.loader = loader\r\n self.frames_list = frames_list\r\n self.class_list = class_list\r\n self.frames_num = frames_num\r\n\r\n self.real_size = frame_utils.read_gen(self.frames_list[0] + \"/frame000001.jpg\").shape[:2]\r\n\r\n if self.render_size == [-1, -1]:\r\n # choice the closest size\r\n f_h, f_w = self.real_size[:2]\r\n\r\n min_h, min_w = math.floor(f_h / 64) * 64, math.floor(f_w / 64) * 64\r\n max_h, max_w = math.ceil(f_h / 64) * 64, math.ceil(f_w / 64) * 64\r\n\r\n re_h = min_h if (abs(min_h - f_h) <= abs(max_h - f_h)) else max_h\r\n re_w = min_w if (abs(min_w - f_w) <= abs(max_w - f_w)) else max_w\r\n self.render_size = [re_h, re_w]\r\n assert [self.render_size[0] % 64, self.render_size[0] % 64] == [0, 0]\r\n\r\n # Cautious!\r\n args.render_size = self.render_size\r\n args.real_size = self.real_size\r\n\r\n trans_size = self.train_size if self.is_train else self.render_size\r\n self.transform = get_transform_flow(trans_size=trans_size, is_train=self.is_train,\r\n sparse=False, div_flow=self.args.div_flow, ct_type=args.ct_type)\r\n\r\n def __getitem__(self, index):\r\n\r\n index = index % len(self.frames_list)\r\n frames_path, class_idx, frames_num = self.frames_list[index], self.class_list[index], self.frames_num[index]\r\n\r\n K_clip_idxs = get_sample_index(frames_num, self.K, self.snippet_len, stride=self.args.stride)\r\n K_clip_img = []\r\n\r\n read_paths = []\r\n for clip_idxs in K_clip_idxs:\r\n clip_paths = [os.path.join(frames_path, 'frame%06d.jpg' % (im_idx + 1)) for im_idx in clip_idxs]\r\n read_paths.append(clip_paths)\r\n\r\n clip_img = [np.array(self.loader(p)) for p in clip_paths] # (frame_num, H,W,C)\r\n\r\n input_transform, target_transform, com_transform = self.transform\r\n clip_img, _ = com_transform(clip_img, None)\r\n clip_img = [input_transform(im) for im in clip_img]\r\n clip_img = torch.stack(clip_img)\r\n K_clip_img.append(clip_img)\r\n K_clip_img = torch.stack(K_clip_img, 0)\r\n\r\n # (K, snippet_len, C, H,W)\r\n return {'frames': K_clip_img, 'classes': class_idx, 'paths': read_paths}\r\n\r\n def __len__(self):\r\n return self.replicates * len(self.frames_list)\r\n\r\n def __repr__(self):\r\n fmt_str = 'Dataset ' + self.__class__.__name__ + '\\n'\r\n fmt_str += ' Number of datapoints: {}\\n'.format(self.__len__())\r\n tmp = ' Transforms (if any): '\r\n fmt_str += '{0}{1}\\n'.format(tmp, self.transform.__repr__().replace('\\n', '\\n' + ' ' * len(tmp)))\r\n return fmt_str\r\n","sub_path":"Datasets/UCF101.py","file_name":"UCF101.py","file_ext":"py","file_size_in_byte":4021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"159976730","text":"import maya.cmds as cmds\nimport base\nimport misc\n\n\nclass BackLeg(base.Base):\n def __init__(self, prefix, side, id):\n base.Base.__init__(self, prefix, side, id)\n self.metaType = 'BackLeg'\n\n self.constructNameSpace(self.metaType)\n self.setLocAttr(startPos=[0, 5, -3])\n\n def setLocAttr(self, startPos=[0, 0, 0], distance=1.5, height=0.2, scale=0.4):\n self.startPos = startPos\n self.distance = distance\n self.height = height\n self.scale = scale\n\n def setCtrlShape(self):\n sphere = cmds.createNode('implicitSphere')\n sphereCtrl = cmds.rename(cmds.listRelatives(sphere, p=True), 'Hip_tempShape')\n cmds.scale(0.5, 0.5, 0.5, sphereCtrl)\n\n pole = cmds.createNode('implicitSphere')\n poleCtrl = cmds.rename(cmds.listRelatives(pole, p=True), 'Pole_tempShape')\n cmds.scale(0.2, 0.2, 0.2, poleCtrl)\n\n ctrlShape = cmds.circle(nr=(0, 1, 0), c=(0, 0, 0), radius=1, s=8, name='Foot_tempShape')\n cmds.scale(0.5, 0.5, 0.5, ctrlShape)\n\n def buildGuide(self):\n grp = cmds.group(em=True, n=self.locGrpName)\n\n # hip\n hip = cmds.spaceLocator(n=self.locName+'hip')\n cmds.parent(hip, grp, relative=True)\n cmds.move(self.startPos[0], self.startPos[1], self.startPos[2], hip, relative=True)\n cmds.scale(self.scale, self.scale, self.scale, hip)\n\n # knee\n knee = cmds.spaceLocator(n=self.locName+'knee')\n cmds.parent(knee, hip, relative=True)\n cmds.move(0, -self.distance, 0, knee, relative=True)\n\n # ankle\n ankle = cmds.spaceLocator(n=self.locName+'ankle')\n cmds.parent(ankle, knee, relative=True)\n cmds.move(0, -self.distance, -0.5 * self.distance, ankle, relative=True)\n\n # foot\n foot = cmds.spaceLocator(n=self.locName+'foot')\n cmds.parent(foot, ankle, relative=True)\n cmds.move(0, -self.distance+self.height, 0, foot, relative=True)\n\n # toe\n toe = cmds.spaceLocator(n=self.locName+'toe')\n cmds.parent(toe, foot, relative=True)\n cmds.move(0, 0, 0.5 * self.distance, toe, relative=True)\n\n self.colorLoc()\n cmds.parent(grp, self.locGrp)\n return grp\n\n def constructJnt(self):\n # result jnt chain\n cmds.select(clear=True)\n jntChain = ['hip', 'knee', 'ankle', 'foot', 'toe']\n for name in jntChain:\n loc = cmds.ls(self.locName+name, transforms=True)\n locPos = cmds.xform(loc, q=True, t=True, ws=True)\n jnt = cmds.joint(p=locPos, name=self.jntName+name)\n cmds.setAttr(jnt+'.radius', self.scale)\n misc.orientJnt(self.jntName+jntChain[0])\n cmds.parent(self.jntName+jntChain[0], self.jntGrp)\n\n # helper jnt chain\n cmds.select(clear=True)\n for name in jntChain[:4]:\n loc = cmds.ls(self.locName+name, transforms=True)\n locPos = cmds.xform(loc, q=True, t=True, ws=True)\n jnt = cmds.joint(p=locPos, name=self.jntName+name+'helper')\n cmds.setAttr(jnt+'.radius', 1)\n misc.orientJnt(self.jntName+jntChain[0]+'helper')\n cmds.parent(self.jntName+jntChain[0]+'helper', self.jntGrp)\n cmds.setAttr(self.jntName+jntChain[0]+'helper.visibility', 0)\n\n return self.jntName+jntChain[0]\n\n def placeCtrl(self):\n self.setCtrlShape()\n\n # hip\n hip = cmds.ls(self.jntName+'hip')\n self.hipCtrl = cmds.duplicate('Hip_tempShape', name=self.ctrlName+'hip')[0]\n hipPos = cmds.xform(hip, q=True, ws=True, t=True)\n hipRot = cmds.xform(hip, q=True, ws=True, ro=True)\n\n self.hipCtrlOffset = cmds.group(em=True, name=self.ctrlOffsetGrpName+'hip')\n cmds.move(hipPos[0], hipPos[1], hipPos[2], self.hipCtrlOffset)\n cmds.rotate(hipRot[0], hipRot[1], hipRot[2], self.hipCtrlOffset)\n cmds.parent(self.hipCtrl, self.hipCtrlOffset, relative=True)\n\n # back foot\n foot = cmds.ls(self.jntName+'foot')\n self.footCtrl = cmds.duplicate('Foot_tempShape', name=self.ctrlName+'foot')[0]\n footPos = cmds.xform(foot, q=True, ws=True, t=True)\n cmds.move(footPos[0], 0, footPos[2], self.footCtrl)\n cmds.makeIdentity(self.footCtrl, apply=True, t=1, r=1, s=1)\n # custom attribute for later pivot group access\n cmds.addAttr(self.footCtrl, longName='Flex', attributeType='double', keyable=True)\n cmds.addAttr(self.footCtrl, longName='Swivel', attributeType='double', keyable=True)\n cmds.addAttr(self.footCtrl, longName='Toe_Tap', attributeType='double', keyable=True)\n cmds.addAttr(self.footCtrl, longName='Toe_Tip', attributeType='double', keyable=True)\n\n # pole vector\n ankle = cmds.ls(self.jntName+'ankle')\n self.poleCtrl = cmds.duplicate('Pole_tempShape', name=self.ctrlName+'poleVector')[0]\n poleCtrlOffset = cmds.group(em=True, name=self.ctrlOffsetGrpName+'poleVector')\n anklePos = cmds.xform(ankle, q=True, ws=True, t=True)\n cmds.move(anklePos[0], anklePos[1], anklePos[2]+self.distance, poleCtrlOffset)\n cmds.parent(self.poleCtrl, poleCtrlOffset, relative=True)\n cmds.parent(poleCtrlOffset, self.footCtrl)\n\n misc.batchParent([self.hipCtrlOffset, self.footCtrl], self.ctrlGrp)\n self.deleteShape()\n\n def buildIK(self):\n # result jnt chain IK\n self.legIK = cmds.ikHandle(startJoint=self.jntName+'hip', endEffector=self.jntName+'ankle', name=self.prefix+'_IKLeg'+self.name, solver='ikRPsolver')[0]\n self.footIK = cmds.ikHandle(startJoint=self.jntName+'ankle', endEffector=self.jntName+'foot', name=self.prefix+'_IKFoot'+self.name, solver='ikSCsolver')[0]\n self.toeIK = cmds.ikHandle(startJoint=self.jntName+'foot', endEffector=self.jntName+'toe', name=self.prefix+'_IKToe'+self.name, solver='ikSCsolver')[0]\n \n # helper jnt chain IK\n self.helperIK = cmds.ikHandle(startJoint=self.jntName+'hiphelper', endEffector=self.jntName+'foothelper', name=self.prefix+'_IKHelper'+self.name, solver='ikRPsolver')[0]\n\n cmds.setAttr(self.legIK+'.visibility', 0)\n cmds.setAttr(self.footIK+'.visibility', 0)\n cmds.setAttr(self.toeIK+'.visibility', 0)\n cmds.setAttr(self.helperIK+'.visibility', 0)\n\n def addMeasurement(self):\n # length segment\n hipPos = cmds.xform(self.jntName+'hip', q=True, ws=True, t=True)\n kneePos = cmds.xform(self.jntName+'knee', q=True, ws=True, t=True)\n anklePos = cmds.xform(self.jntName+'ankle', q=True, ws=True, t=True)\n footPos = cmds.xform(self.jntName+'foot', q=True, ws=True, t=True)\n\n straightenLen = ((kneePos[0]-anklePos[0]) ** 2+(kneePos[1]-anklePos[1]) ** 2+(kneePos[2]-anklePos[2]) ** 2) ** 0.5 + \\\n ((footPos[0]-anklePos[0]) ** 2+(footPos[1]-anklePos[1]) ** 2+(footPos[2]-anklePos[2]) ** 2) ** 0.5 + \\\n ((hipPos[0]-kneePos[0]) ** 2+(hipPos[1]-kneePos[1]) ** 2+(hipPos[2]-kneePos[2]) ** 2) ** 0.5\n \n # create measurement\n measureNode = cmds.distanceDimension(sp=hipPos, ep=footPos)\n\n stretchNode = cmds.shadingNode('multiplyDivide', asUtility=True, name=self.ctrlName+'Stretch')\n cmds.setAttr(stretchNode+'.operation', 2)\n cmds.setAttr(stretchNode+'.input2X', straightenLen)\n cmds.connectAttr(measureNode+'.distance', stretchNode+'.input1X')\n\n conditionNode = cmds.shadingNode('condition', asUtility=True, name=self.ctrlName+'Condition')\n cmds.connectAttr(stretchNode+'.outputX', conditionNode+'.firstTerm')\n cmds.setAttr(conditionNode+'.secondTerm', 1)\n cmds.setAttr(conditionNode+'.operation', 2) # Greater than\n cmds.connectAttr(stretchNode+'.outputX', conditionNode+'.colorIfTrueR')\n cmds.setAttr(conditionNode+'.colorIfFalseR', 1)\n\n cmds.connectAttr(conditionNode+'.outColorR', self.jntName+'ankle.scaleX')\n cmds.connectAttr(conditionNode+'.outColorR', self.jntName+'knee.scaleX')\n cmds.connectAttr(conditionNode+'.outColorR', self.jntName+'hip.scaleX')\n cmds.connectAttr(conditionNode+'.outColorR', self.jntName+'anklehelper.scaleX')\n cmds.connectAttr(conditionNode+'.outColorR', self.jntName+'kneehelper.scaleX')\n cmds.connectAttr(conditionNode+'.outColorR', self.jntName+'hiphelper.scaleX')\n\n cmds.rename('distanceDimension1', self.ctrlName+'length')\n cmds.rename('locator1', self.ctrlName+'hipLoc')\n cmds.rename('locator2', self.ctrlName+'ankleLoc')\n cmds.setAttr(self.ctrlName+'length.visibility', 0)\n cmds.setAttr(self.ctrlName+'ankleLoc.visibility', 0)\n cmds.setAttr(self.ctrlName+'hipLoc.visibility', 0)\n misc.batchParent([self.ctrlName+'length', self.ctrlName+'hipLoc', self.ctrlName+'ankleLoc'], self.ctrlGrp)\n\n cmds.parentConstraint(self.hipCtrl, self.ctrlName+'hipLoc')\n cmds.parentConstraint(self.footCtrl, self.ctrlName+'ankleLoc', mo=True)\n\n def addConstraint(self):\n self.buildIK()\n # shoulder pivot\n cmds.parentConstraint(self.hipCtrl, self.jntName+'hip')\n cmds.parentConstraint(self.hipCtrl, self.jntName+'hiphelper')\n\n # front foot pivot group\n flexOffsetGrp = cmds.group(em=True, name=self.ctrlOffsetGrpName+'Flex')\n flexPivotGrp = cmds.group(em=True, name=self.ctrlGrpName+'FlexPivot')\n toeTapPivotGrp = cmds.group(em=True, name=self.ctrlGrpName+'ToeTapPivot')\n swivelPivotGrp = cmds.group(em=True, name=self.ctrlGrpName+'SwivelPivot')\n toeTipPivotGrp = cmds.group(em=True, name=self.ctrlGrpName+'ToeTipPivot')\n\n footPos = cmds.xform(self.jntName+'foot', q=True, ws=True, t=True)\n toePos = cmds.xform(self.jntName+'toe', q=True, ws=True, t=True)\n\n cmds.move(footPos[0], footPos[1], footPos[2], flexOffsetGrp)\n cmds.move(footPos[0], footPos[1], footPos[2], flexPivotGrp)\n cmds.move(footPos[0], footPos[1], footPos[2], toeTapPivotGrp)\n cmds.move(footPos[0], footPos[1], footPos[2], swivelPivotGrp)\n cmds.move(toePos[0], toePos[1], toePos[2], toeTipPivotGrp)\n\n misc.batchParent([self.legIK, self.footIK], flexPivotGrp)\n cmds.parent(flexPivotGrp, flexOffsetGrp)\n cmds.parentConstraint(self.jntName+'foothelper', flexOffsetGrp, mo=True)\n misc.batchParent([self.toeIK, self.helperIK], toeTapPivotGrp)\n misc.batchParent([toeTapPivotGrp, flexOffsetGrp], toeTipPivotGrp)\n cmds.parent(toeTipPivotGrp, swivelPivotGrp)\n cmds.parent(swivelPivotGrp, self.footCtrl)\n\n cmds.connectAttr(self.footCtrl+'.Flex', flexPivotGrp+'.rotateX')\n cmds.connectAttr(self.footCtrl+'.Swivel', swivelPivotGrp+'.rotateY')\n cmds.connectAttr(self.footCtrl+'.Toe_Tap', toeTapPivotGrp+'.rotateX')\n cmds.connectAttr(self.footCtrl+'.Toe_Tip', toeTipPivotGrp+'.rotateX')\n\n # pole vector constraint\n cmds.poleVectorConstraint(self.poleCtrl, self.legIK)\n cmds.poleVectorConstraint(self.poleCtrl, self.helperIK)\n cmds.parent(self.ctrlOffsetGrpName+'poleVector', swivelPivotGrp)\n\n # scalable\n self.addMeasurement()\n\n\n","sub_path":"backLeg.py","file_name":"backLeg.py","file_ext":"py","file_size_in_byte":11138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"606585205","text":"from asyncio import (\r\n IncompleteReadError,\r\n StreamReader,\r\n StreamWriter,\r\n start_server,\r\n run as asyncio_run\r\n)\r\n\r\nfrom .response import ResponseHeader, ResponseCode\r\nfrom .file_manager import FileManager\r\nfrom .request import RequestHandler\r\nfrom .database import Database\r\nfrom .handlers import HANDLERS\r\nfrom .config import config_file\r\n\r\nDEFAULT_RESPONSE = ResponseHeader(0, ResponseCode.SERVER_ERROR, 0)\r\n\r\nHANDLER = RequestHandler(default_response=DEFAULT_RESPONSE)\r\n\r\nDATABASE = Database()\r\n\r\nFILE_MANAGER = FileManager(DATABASE)\r\n\r\nasync def handle_client(reader: StreamReader, writer: StreamWriter):\r\n address, port = writer.get_extra_info('peername')\r\n print(f'[{address}:{port}] Connected!')\r\n while True:\r\n try:\r\n await HANDLER.handle_request(DATABASE, FILE_MANAGER, reader, writer)\r\n except IncompleteReadError:\r\n break\r\n except ConnectionAbortedError:\r\n print(f'[{address}:{port}] Got aborted!')\r\n break\r\n except ConnectionResetError:\r\n print(f'[{address}:{port}] Got reset!')\r\n break\r\n\r\n if not writer.is_closing():\r\n writer.close()\r\n await writer.wait_closed()\r\n\r\n print(f'[{address}:{port}] Goodbye!')\r\n\r\n\r\nasync def listen(port: int):\r\n server = await start_server(handle_client, '0.0.0.0', port)\r\n for socket in server.sockets:\r\n interface, port = socket.getsockname()\r\n print(f'Listening on {interface}:{port}')\r\n\r\n async with server:\r\n await server.serve_forever()\r\n\r\n\r\ndef main():\r\n for request_type in HANDLERS:\r\n HANDLER.add_request_type(request_type)\r\n\r\n try:\r\n with config_file() as port:\r\n asyncio_run(listen(port))\r\n except KeyboardInterrupt:\r\n print('Goodbye!')\r\n\r\n DATABASE.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"20937/maman-15/server/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"253483132","text":"import psycopg2\nconn = psycopg2.connect(database=\"office\", user=\"postgres\", password=\"12345678\",host='127.0.0.1')\ncur = conn.cursor()\nnum='1'\nwhile (num=='1'):\n print(\"enter cr =>creat table\")\n print(\"enter in =>insert table\")\n print(\"enter up =>update table\")\n print(\"enter sh=>show inform\")\n print(\"enter else=>else\")\n var = input('enter char :')\n if var == 'cr':\n print (\"cr - Got a true expression value creat table\") \n print (\"enter em for CREATE edari_man TABLE \")\n print (\"enter jorm for CREATE jorm TABLE \")\n print (\"enter pman for CREATE police-man TABLE \")\n print (\"enter baz for CREATE BAZDASHT TABLE \")\n print (\"enter zendan for CREATE zendan TABLE \")\n print (\"enter mojrem for CREATE mojrem TABLE \") \n print (\"enter sakht for CREATE sakhteman TABLE \") \n print (\"enter edari for CREATE sakhteman_edari TABLE \")\n print (\"enter karkonan for CREATE karkonan TABLE \")\n print (\"enter mahal for CREATE EDARI_MAHAL TABLE \")\n print (\"enter habs for CREATE habs TABLE \")\n com =input ('enter char to creat table :')\n if com =='em':\n cur.execute('''CREATE TABLE edari_man\n (id_em INT PRIMARY KEY NOT NULL, \n name TEXT NOT NULL,\n age INT NOT NULL,\n jensiat CHAR(20),\n salary REAL,\n sale_estekhdam int,\n takhasos text);''')\n print (\"Table created successfully\")\n conn.commit()\n elif com=='jorm':\n cur.execute('''CREATE TABLE jorm\n (id_jo INT PRIMARY KEY NOT NULL,\n name TEXT NOT NULL,\n daste TEXT);''')\n print (\"Table created successfully\")\n conn.commit()\n elif com=='baz': \n cur.execute('''CREATE TABLE bazdasht\n (\n id_mj integer NOT NULL,\n id_po integer,\n id_jo integer,\n date_bazdasht date,\n date_anjamjorm date,\n CONSTRAINT \"bazdasht_pkey\" PRIMARY KEY (id_mj,date_bazdasht),\n CONSTRAINT \"bazdasht_id_mj_fkey\" FOREIGN KEY (id_mj)\n REFERENCES mojrem (id_mj) MATCH SIMPLE\n ON UPDATE NO ACTION ON DELETE NO ACTION );''')\n print (\"Table created successfully\")\n conn.commit()\n elif com=='habs': \n cur.execute('''CREATE TABLE habs\n (\n shoro_habs date,\n id_mj integer NOT NULL,\n id_ze integer,\n payan_habs date,\n CONSTRAINT habs_pkey PRIMARY KEY (id_mj,shoro_habs),\n CONSTRAINT \"habs_id_mj_fkey\" FOREIGN KEY (id_mj)\n REFERENCES mojrem (id_mj) MATCH SIMPLE\n ON UPDATE NO ACTION ON DELETE NO ACTION);''')\n conn.commit()\n elif com=='pman':\n cur.execute('''CREATE TABLE police_man\n (\n id_po INT PRIMARY KEY NOT NULL,\n name TEXT NOT NULL,\n age INT NOT NULL,\n jensiat CHAR(20),\n salary REAL,\n sale_estekhdam int,\n takhasos text);''')\n print (\"Table created successfully\")\n conn.commit()\n elif com=='zendan':\n cur.execute('''CREATE TABLE zendan\n (\n id_ze INT PRIMARY KEY NOT NULL,\n name TEXT NOT NULL,\n zarfiat INT NOT NULL,\n jensiat CHAR(20),\n makan text);''')\n print (\"Table created successfully\")\n conn.commit()\n elif com=='mojrem':\n cur.execute('''CREATE TABLE mojrem\n (\n id_mj INT PRIMARY KEY NOT NULL,\n name TEXT NOT NULL,\n age INT NOT NULL,\n jensiat CHAR(50));''')\n print (\"Table created successfully\")\n conn.commit()\n elif com=='sakht':\n cur.execute('''CREATE TABLE sakhteman\n (\n id INT PRIMARY KEY NOT NULL,\n name TEXT NOT NULL);''')\n print (\"Table created successfully\")\n conn.commit()\n elif com=='edari': \n cur.execute('''CREATE TABLE sakhteman_edari\n (\n id_se INT PRIMARY KEY NOT NULL,\n name_se TEXT NOT NULL,\n addres TEXT NOT NULL);''')\n print (\"Table created successfully\")\n conn.commit()\n elif com=='karkonan':\n cur.execute('''CREATE TABLE karkonan\n (\n id INT PRIMARY KEY NOT NULL,\n name TEXT NOT NULL);''')\n print (\"Table created successfully\")\n conn.commit()\n elif com=='mahal':\n cur.execute('''CREATE TABLE edari_mahal\n (\n id_em integer NOT NULL,\n id_se integer NOT NULL,\n CONSTRAINT edari_mahal_pkey PRIMARY KEY (id_em,id_se),\n CONSTRAINT edari_mahal_id_em_fkey FOREIGN KEY (id_em)\n REFERENCES edari_man (id_em) MATCH SIMPLE\n ON UPDATE NO ACTION ON DELETE NO ACTION,\n CONSTRAINT edari_mahal_id_se_fkey FOREIGN KEY (id_se)\n REFERENCES sakhteman_edari (id_se) MATCH SIMPLE\n ON UPDATE NO ACTION ON DELETE NO ACTION); ''')\n print (\"Table created successfully\")\n conn.commit()\n elif var =='in':\n print (\"in - Got a true expression value insert\")\n print (\"in - Got a true expression value insert\")\n print (\"enter eman for INSERT edari_man TABLE \")\n print (\"enter jorm for INSERT jorm TABLE \")\n print (\"enter pman for INSERT police-man TABLE \")\n print (\"enter bazdasht for INSERT BAZDASHT TABLE \")\n print (\"enter zendan for INSERT zendan TABLE \")\n print (\"enter mojrem for INSERT mojrem TABLE \") \n print (\"enter sakhteman for INSERT sakhteman TABLE \") \n print (\"enter sakhtemanedari for INSERT sakhteman_edari TABLE \")\n print (\"enter kar for INSERT karkonan TABLE \")\n print (\"enter edarimahal for INSERT EDARI_MAHAL TABLE \")\n print (\"enter habs for INSERT habs TABLE \")\n com =input ('enter char to insert table :')\n if com == 'kar' :\n a=input('enter name:')\n s=input('enter id:')\n cur.execute(\"INSERT INTO karkonan (id,name ) \\\n VALUES (%s, %s )\",(s,a,));\n conn.commit()\n print (\"Records created successfully\");\n elif com=='zendan':\n s=input('enter id:')\n a=input('enter name:')\n z=input('enter zarfiat:')\n c=input('enter jensiat:')\n e=input('enter makan:')\n cur.execute(\"INSERT INTO zendan (id_ze,name,zarfiat,jensiat, makan) \\\n VALUES (%s, %s,%s, %s,%s)\",(s,a,z,c,e));\n conn.commit()\n print (\"Records created successfully\")\n elif com == 'eman' :\n print (\"Opened database successfully\")\n cur = conn.cursor()\n a=input('enter name_em:')\n s=input('enter id :')\n d=input('enter age :')\n w=input('enter jensiat:')\n r=input('enter SALARY:') \n t=input('enter sale_estekhdam:') \n y=input('enter takhasos:') \n cur.execute(\"INSERT INTO edari_man (id_em,name,age,jensiat,salary,sale_estekhdam,takhasos ) \\\n VALUES (%s, %s, %s, %s, %s, %s, %s )\",(s,a,d,w,r,t,y));\n conn.commit()\n print (\"Records created successfully\")\n elif com == 'jorm' :\n print (\"Opened database successfully\")\n cur = conn.cursor()\n a=input('enter name:')\n s=input('enter id :') \n w=input('enter daste :') \n cur.execute(\"INSERT INTO jorm (id_jo,name,daste ) \\\n VALUES (%s, %s )\",(s,a,w));\n conn.commit()\n print (\"Records created successfully\")\n elif com == 'bazdasht' :\n print (\"Opened database successfully\")\n cur = conn.cursor()\n a=input('enter id_mj:')\n s=input('enter id_po:')\n d=input('enter id_jo:')\n w=input('enter date_bazdasht:')\n r=input('enter date_anjamjorm:') \n cur.execute(\"INSERT INTO BAZDASHT (id_mj,id_po,id_jo,date_bazdasht,date_anjamjorm ) \\\n VALUES (%s, %s, %s, %s, %s )\",(a,s,d,w,r));\n conn.commit()\n print (\"Records created successfully\")\n elif com == 'pman' :\n print (\"Opened database successfully\")\n cur = conn.cursor()\n a=input('enter name:')\n s=input('enter id_po:')\n d=input('enter age :')\n w=input('enter jensiat:')\n r=input('enter salary:') \n t=input('enter sale_estekhdam:') \n y=input('enter takhasos:') \n cur.execute(\"INSERT INTO police_man (id_po,name,age,jensiat,salary,sale_estekhdam,takhasos ) \\\n VALUES (%s, %s, %s, %s, %s, %s, %s )\",(s,a,d,w,r,t,y));\n conn.commit()\n print (\"Records created successfully\")\n elif com == 'mojrem' :\n print (\"Opened database successfully\")\n cur = conn.cursor()\n a=input('enter name:')\n s=input('enter id_mj :')\n d=input('enter age :')\n w=input('enter jensiat:') \n cur.execute(\"INSERT INTO mojrem (id_mj,name,age,jensiat ) \\\n VALUES (%s, %s , %s, %s)\",(s,a,d,w))\n conn.commit()\n print (\"Records created successfully\")\n elif com == 'sakhteman' :\n print (\"Opened database successfully\")\n cur = conn.cursor()\n a=input('enter name:')\n s=input('enter id :') \n cur.execute(\"INSERT INTO sakhteman (Id,name ) \\\n VALUES (%s, %s )\",(s,a));\n conn.commit()\n print (\"Records created successfully\")\n elif com == 'sakhtemanedari' :\n print (\"Opened database successfully\")\n cur = conn.cursor()\n a=input('enter id_se:')\n s=input('enter name_se :')\n d=input('enter addres:') \n cur.execute(\"INSERT INTO sakhteman_edari (id_se, name_se,addres ) \\\n VALUES (%s, %s, %s )\",(s,a.d));\n conn.commit()\n print (\"Records created successfully\")\n elif com == 'edarimahal' :\n print (\"Opened database successfully\")\n cur = conn.cursor()\n a=input('enter id_em:')\n s=input('enter id_se :') \n cur.execute(\"INSERT INTO edari_mahal (id_em,id_se ) \\\n VALUES (%s, %s )\",(s,a));\n conn.commit()\n print (\"Records created successfully\")\n elif com == 'habs' :\n print (\"Opened database successfully\")\n cur = conn.cursor()\n a=input('enter shoro_habs:')\n s=input('enter id_mj:')\n d=input('enter id_ze:')\n w=input('enter payan_habs:') \n cur.execute('''INSERT INTO habs (shoro_habs,id_mj,id_ze,payan_habs ) \\\n VALUES (%s, %s, %s, %s)''',(a,s,d,w));\n conn.commit()\n print (\"Records created successfully\");\n elif var == 'up':\n print (\"in - Got a true expression value insert\")\n print (\"enter eman for INSERT edari_man TABLE \") \n print (\"enter jorm for INSERT jorm TABLE \") \n print (\"enter pman for INSERT police-man TABLE \") \n print (\"enter bazdasht for INSERT BAZDASHT TABLE \")\n print (\"enter ze for INSERT zendan TABLE \") \n print (\"enter mojrem for INSERT mojrem TABLE \")\n print (\"enter sakhteman for INSERT sakhteman TABLE \") \n print (\"enter sakhtemanedari for INSERT sakhteman_edari TABLE \") \n print (\"enter karkonan for INSERT karkonan TABLE \") \n print (\"enter edarimahal for INSERT edari_mahal TABLE \") \n print (\"enter habs for INSERT habs TABLE \") \n com =input ('enter char to insert table :')\t\n if com =='edari':\n a=input('enter id_se you want to update information about it:')\n s=input('enter name_se :')\n d=input('enter addres:') \n cur.execute('''update sakhteman_edari set name_se=%s where id_se=%s ''',(s,a))\n cur.execute('''update sakhteman_edari set addres=%s where id_se=%s ''',(d,a))\n print (\"Table updated successfully\")\n conn.commit()\n elif com =='eman': \n s=input('enter id_em you want to update information about it:')\n a=input('enter name:')\n d=input('enter age :')\n w=input('enter jensiat:')\n r=input('enter salary:') \n t=input('enter sale_estekhdam:') \n y=input('enter takhasos:') \n cur.execute('''update edari_man set name=%s where id_me=%s''',(a,s))\n cur.execute('''update edari_man set age=%s where id_me=%s''',(d,s))\n cur.execute('''update edari_man set jensiat=%s where id_me=%s''',(w,s))\n cur.execute('''update edari_man set salary=%s where id_me=%s''',(r,s))\n cur.execute('''update edari_man set sale_estekhdam=%s where id_me=%s''',(t,s))\n cur.execute('''update edari_man set takhasos=%s where id_me=%s''',(y,s))\n print (\"Table updated successfully\")\n conn.commit() \n elif com=='ze':\n s=input('enter id_ze you want to update information about it :')\n a=input('enter name:')\n z=input('enter zarfiat:')\n c=input('enter jensiat:')\n e=input('enter makan:')\n cur.execute('''update zendan set name=%s where id_ze=%s''',(a,s))\n cur.execute('''update zendan set jensiat=%s where id_ze=%s''',(c,s))\n cur.execute('''update zendan set zarfiat=%s where id_ze=%s''',(z,s))\n cur.execute('''update zendan set makan=%s where id_ze=%s''',(e,s))\n print (\"Table updated successfully\")\n conn.commit()\n elif com == 'jorm' :\n s=input('enter id_jo you want to update information about it:') \n a=input('enter name:') \n w=input('enter daste :') \n cur.execute('''update jorm set name=%s where id_jo=%s''',(a,s))\n cur.execute('''update jorm set daste=%s where id_jo=%s''',(w,s)) \n print (\"Table updated successfully\")\n conn.commit()\n elif com == 'pman' :\n s=input('enter id_po you want to update information about it:')\n a=input('enter name:')\n d=input('enter age :')\n w=input('enter jensiat:')\n r=input('enter salary:') \n t=input('enter sale_estekhdam:') \n y=input('enter takhasos:')\n cur.execute('''update police_man set name=%s where id_po=%s''',(a,s))\n cur.execute('''update police_man set age=%s where id_po=%s''',(d,s))\n cur.execute('''update police_man set jensiat=%s where id_po=%s''',(w,s))\n cur.execute('''update police_man set salary=%s where id_po=%s''',(r,s))\n cur.execute('''update police_man set sale_estekhdam=%s where id_po=%s''',(t,s))\n cur.execute('''update police_man set takhasos=%s where id_po=%s''',(y,s)) \n print (\"Table updated successfully\")\n conn.commit() \n elif com == 'bazdasht' :\n a=input('enter id_mj you want to update information about it:')\n s=input('enter id_po:')\n d=input('enter id_jo:')\n w=input('enter date_bazdasht:')\n r=input('enter date_anjamjorm:')\n cur.execute('''update bazdasht set id_po=%s where id_mj=%s''',(s,a))\n cur.execute('''update bazdasht set id_jo=%s where id_mj=%s''',(d,a))\n cur.execute('''update bazdasht set date_bazdasht=%s where id_mj=%s''',(w,a))\n cur.execute('''update bazdasht set date_anjamjorm=%s where id_mj=%s''',(r,a))\n print (\"Table updated successfully\")\n conn.commit()\n elif com == 'habs' :\n s=input('enter id_mj you want to update information about it:')\n a=input('enter shoro_habs:')\n d=input('enter id_ze:')\n w=input('enter payan_habs:')\n cur.execute('''update habs set id_ze=%s where id_mj=%s''',(d,s))\n cur.execute('''update habs set shoro_habs=%s where id_mj=%s''',(a,s))\n cur.execute('''update habs set payan_habs=%s where id_mj=%s''',(w,s)) \n print (\"Table updated successfully\")\n conn.commit()\n elif com == 'mojrem' :\n s=input('enter id_mj want to update information about it :')\n a=input('enter name:')\n d=input('enter age :')\n w=input('enter jensiat:') \n cur.execute('''update mojrem set name=%s where id_mj=%s''',(a,s))\n cur.execute('''update mojrem set age=%s where id_mj=%s''',(d,s))\n cur.execute('''update mojrem set jensiat=%s where id_mj=%s''',(w,s)) \n print (\"Table updated successfully\")\n conn.commit()\n elif com == 'edarimahal' :\n s=input('enter id_se want to update information about it:')\n a=input('enter id_em:') \n cur.execute('''update edari_mahal set id_em=%s where id_se=%s''',(a,s)) \n print (\"Table updated successfully\")\n conn.commit()\n elif com == 'karkonan' :\n s=input('enter id want to update information about it:')\n a=input('enter name:')\n cur.execute('''update karkonan set name=%s where id=%s''',(a,s)) \n print (\"Table updated successfully\")\n conn.commit()\n elif com == 'sakhteman' :\n s=input('enter id want to update information about it:')\n a=input('enter name:')\n cur.execute('''update sakhteman set name=%s where id=%s''',(a,s))\n print (\"Table updated successfully\")\n conn.commit()\n elif var=='sh': \n print (\"enter 1 show police man inform*\") \n print (\"enter 2 show mojrem inform*\")\n print (\"enter 3 show zendan inform*\") \n print (\"enter 4 show edari man inform*\")\n print (\"enter 5 show sakhteman edari inform*\")\n print (\"enter 6 show jorm inform*\")\n var1=input(\"enter\")\n if var1 == '1':\n print (\"1 - Got a true expression value find *\")\n def show1 (): \n a=input('inter id police')\n cur.execute('''SELECT * FROM police_man where id_po = %s''', (a,))\n print( cur.fetchall())\n conn.commit()\n show1() \n elif var1 == '2':\n print (\"2 - Got a true expression value find *\")\n def show2 (): \n a=input('inter id mojrem')\n cur.execute('''SELECT * FROM mojrem where id_mj = %s''', (a,))\n print( cur.fetchall())\n conn.commit()\n show2() \n elif var1 =='3':\n print (\"3 - Got a true expression value find *\")\n def show3 (): \n a=input('inter id zendan')\n cur.execute('''SELECT * FROM zendan where id_ze = %s''', (a,))\n print( cur.fetchall())\n conn.commit()\n show3() \n elif var1 =='4':\n print (\"4 - Got a true expression value find *\")\n def show4 (): \n a=input('inter id edariman')\n cur.execute('''SELECT * FROM edari_man where id_em = %s''', (a,))\n print( cur.fetchall())\n conn.commit()\n show4() \n elif var1 =='5':\n print (\"5 - Got a true expression value find *\")\n def show5 (): \n a=input('inter id sakhteman edari')\n cur.execute('''SELECT * FROM sakhteman_edari where id_se = %s''', (a,))\n print( cur.fetchall())\n conn.commit()\n show5() \n elif var1 =='6':\n print (\"6 - Got a true expression value find *\")\n def show6 (): \n a=input('inter id sakhteman edari')\n cur.execute('''SELECT * FROM jorm where id_jo = %s''', (a,))\n print( cur.fetchall())\n conn.commit()\n show6()\n else:\n\t print(\"Got a false expression value\")\n elif var=='else': \n print (\"enter 1 modat zaman mabin ertekab har jorm va bazdasht shodan tavasot police on mojrem*\") \n print (\"enter 2 mojrem hai ke yek police grefte*\")\n print (\"enter 3 sabegh yek mojrem*\")\n print (\"enter 4 tedad zendani haie yek zendan*\")\n print (\"enter 5 tedad afrad habs shode moanas*\")\n print (\"enter 6 tedad karmandan moanas*\")\n print (\"enter 7 miangin sen zendanian yek zendan*\")\n print (\"enter 8 name afrad zire 25 sal*\")\n print (\"enter 9 ke sale bad mitavanand bazneshast shavand*\")\n print (\"enter 10 max jorm afrad zir 25 sal*\")\n print (\"enter 11 zaman anjam yek jorm*\")\n print (\"enter 12 karmandani ke ghabl az 1995 estekhdam shodan*\")\n print (\"enter 13 mojreman yek zendan moshakhas*\")\n print (\"enter 14 zendan haee ke zarfiat bala 1000 va moanas hastand*\")\n print (\"enter 15 mojremani ke jorm moshtarak darand*\")\n print (\"enter 16 karmandani ke dar bakhsh edari semat moshtarak darand*\")\n print (\"enter 17 karmandani ke dar yek sakhteman moshakhas hastan*\")\n print (\"enter 18 police ke mojremi nagrefte*\")\n print (\"enter 19 shologh tarin zendanha*\")\n print (\"enter 20 mojreman zani ke 2 jorm motafavet darand*\")\n print (\"enter 21 bishtarin jorm tekrar shode*\")\n print (\"enter 22 zendani ke kamtar az dah nafar zarfiat dare*\")\n print (\"enter 23 zendani ke bishtar az nesfe an khalie*\")\n print (\"enter 24 mojremi ke bazdasht shode ama habs nashode*\")\n print (\"enter 25 sabeghe dar tarin*\")\n print (\"enter 26 mojremani ke bishtar az 2 sal mahkom be habs shode and*\")\n print (\"enter 27 zanani ke dar sal 1393 ghatl anjam dade and*\")\n print (\"enter 28 bishtarin ghatl dar che mahi sorat gerefte *\")\n print (\"enter 29 bishtarin jormi ke dar har mah anjam gerefte *\") \n print (\"enter 30 sabeghe darhai moanas*\")\n var1=input(\"enter\") \n if var1 == '2':\n def f1 ():\n a=input('enter id police')\n cur.execute('''SELECT mojrem.name FROM police_man natural join bazdasht join mojrem on mojrem.id_mj=bazdasht.id_mj where id_po = %s''', (a,))\n for a in cur.fetchall():\n\t print(a)\n conn.commit() \n f1 ()\n elif var1 =='3':\n print (\"3 - Got a true expression value find *\")\n def f2():\n a=input('enter id mojrem')\n cur.execute('''SELECT jorm.name FROM bazdasht join jorm on jorm.id_jo=bazdasht.id_jo where id_mj = %s''', (a,))\n for a in cur.fetchall():\n\t print(a)\n conn.commit()\n f2() \n elif var1 =='4':\n print (\"4 - Got a true expression value find *\")\n def f3():\n a=input('enter id zendan')\n cur.execute('''SELECT count(*) FROM habs where id_ze = %s ''', (a,))\n n=cur.fetchone()\n print(n)\n conn.commit()\n f3() \n elif var1 =='5':\n print (\"5 - Got a true expression value find *\")\n def f4():\n cur.execute('''SELECT count(*) FROM habs join mojrem on habs.id_mj=mojrem.id_mj where jensiat = 'moanas' ''')\n print( cur.fetchall())\n conn.commit()\n f4() \n elif var1 =='6':\n print (\"6 - Got a true expression value find *\")\n def f5():\n cur.execute('''SELECT count(*) FROM edari_man where jensiat = 'moanas' ''')\n print( cur.fetchall())\n conn.commit()\n f5()\n elif var1 =='7':\n print (\"7 - Got a true expression value find *\")\n def f6():\n a=input('enter id zendan')\n cur.execute('''SELECT avg(age) FROM habs join mojrem on habs.id_mj=mojrem.id_mj where id_ze = %s ''', (a,))\n print(cur.fetchone())\n conn.commit()\n f6()\n elif var1 =='8':\n print (\"8 - Got a true expression value find *\")\n def f7():\n cur.execute('''SELECT name FROM mojrem where age<25 ''')\n for a in cur.fetchall():\n print(a)\n conn.commit()\n f7()\n elif var1 =='9':\n print (\"9 - Got a true expression value find *\")\n def f8():\n cur.execute(''' SELECT name_em from edari_man where sale_estekhdam<1987''')\n print(cur.fetchone())\n conn.commit()\n f8()\n elif var1 =='10':\n print (\"10 - Got a true expression value find *\")\n def f9():\n cur.execute('''SELECT jorm.name,count(*) maximum FROM bazdasht join mojrem on bazdasht.id_mj=mojrem.id_mj join jorm on bazdasht.id_jo=jorm.id_jo\n where age<25 group by jorm.id_jo ORDER BY maximum DESC ''')\n print(cur.fetchone())\n conn.commit()\n f9()\n elif var1 =='11':\n print (\"11 - Got a true expression value find *\")\n def f10():\n a=input('enter id jorm')\n cur.execute('''SELECT date_anjamjorm FROM bazdasht where id_jo = %s ''', (a,))\n for a in cur.fetchall():\n print(a)\n conn.commit()\n f10()\n elif var1 =='12':\n print (\"12 - Got a true expression value find *\")\n def f11():\n cur.execute('''SELECT name_em from edari_man where sale_estekhdam<1995''')\n for a in cur.fetchall():\n print(a)\n conn.commit()\n f11() \n elif var1 == '13':\n print (\"13 - Got a true expression value find *\")\n def f12():\n a=input('enter id zendan')\n cur.execute('''SELECT name FROM habs join mojrem on habs.id_mj = mojrem.id_mj where id_ze = %s''',(a,) )\n for a in cur.fetchall():\n print(a)\n conn.commit()\n f12() \n elif var1 == '14':\n print (\"14 - Got a true expression value find *\")\n def f13():\n cur.execute('''SELECT name FROM zendan where zarfiat > 1000 and jensiat = 'moanas' ''')\n for a in cur.fetchall():\n print(a)\n conn.commit()\n f13()\n elif var1 == '15': \n print (\"15 - Got a true expression value find *\")\n def f14():\n cur.execute('''SELECT mojrem.name as mname,jorm.name as jname FROM mojrem join bazdasht on bazdasht.id_mj = mojrem.id_mj join jorm on jorm.id_jo = bazdasht.id_jo order by bazdasht.id_jo ''')\n for a in cur.fetchall():\n print(a)\n conn.commit()\n f14()\n elif var1 == '16': \n print (\"16 - Got a true expression value find *\")\n def f16():\n cur.execute('''SELECT name_em,takhasos FROM edari_man order by takhasos ''')\n for a in cur.fetchall():\n print(a)\n conn.commit()\n f16()\n elif var1=='17':\n print (\"17 - Got a true expression value find *\")\n def f17():\n a=input('enter id sakhteman edari')\n cur.execute('''SELECT edari_man.name_em FROM sakhteman_edari natural join mahal natural join edari_man where id_se = %s''',(a,) )\n for a in cur.fetchall():\n print(a)\n conn.commit()\n f17()\n elif var1=='18':\n print (\"18 - Got a true expression value find *\")\n def f18():\n cur.execute('''select name from police_man where id_po in (SELECT id_po from police_man except select id_po from bazdasht)''')\n for a in cur.fetchall():\n print(a)\n conn.commit()\n f18()\n elif var1=='19':\n print (\"19 - Got a true expression value find *\")\n def f19():\n cur.execute('''SELECT name,count(*) maximum FROM habs join zendan on zendan.id_ze=habs.id_ze \n group by zendan.id_ze ORDER BY maximum DESC ''')\n print( cur.fetchone())\n conn.commit()\n f19() \n elif var1=='20': \n print (\"20 - Got a true expression value find *\")\n def f20():\n cur.execute('''SELECT name ,count(id_jo) FROM mojrem join bazdasht on mojrem.id_mj=bazdasht.id_mj where jensiat='moanas' group by bazdasht.id_mj,name having count(id_jo) = 2 ''' )\n for a in cur.fetchall():\n print(a)\n conn.commit()\n f20() \n elif var1=='21':\n print (\"21 - Got a true expression value find *\")\n def f21():\n cur.execute('''SELECT name ,count(jorm.id_jo) FROM jorm join bazdasht on jorm.id_jo=bazdasht.id_jo group by bazdasht.id_jo,name ORDER BY count(jorm.id_jo) desc ''' )\n for a in cur.fetchone():\n print(a)\n conn.commit()\n f21()\n elif var1 =='22':\n print (\"22 - Got a true expression value find *\")\n def f22():\n cur.execute('''SELECT count(*),zarfiat,name FROM zendan full outer join habs on zendan.id_ze=habs.id_ze group by zendan.id_ze ''' )\n for a in cur.fetchall():\n for l1 in a:\n s=a[1]\n c=a[0]\n d=s-c\n if d<10:\n print(a[2])\n print()\n conn.commit()\n f22()\n elif var1 =='23':\n print (\"23 - Got a true expression value find *\")\n def f23():\n cur.execute('''SELECT count(*),zarfiat,name FROM zendan full outer join habs on zendan.id_ze=habs.id_ze group by zendan.id_ze ''' )\n for a in cur.fetchall():\n for l1 in a:\n s=a[1]\n c=a[0]\n print()\n d=s/c\n if d>.5:\n print(a[2])\n conn.commit()\n f23()\n elif var1=='24':\n print (\"24 - Got a true expression value find *\")\n def f24():\n cur.execute('''select name from mojrem where id_mj in (SELECT id_mj from bazdasht except select id_mj from habs)''')\n for a in cur.fetchall():\n print(a)\n conn.commit()\n f24()\n elif var1=='25': \n print (\"25 - Got a true expression value find *\")\n def f25():\n cur.execute('''SELECT name,count(*) FROM mojrem join bazdasht on mojrem.id_mj=bazdasht.id_mj group by mojrem.id_mj ORDER BY count(*) desc ''' )\n for a in cur.fetchall():\n print(a)\n conn.commit()\n f25()\n elif var1=='26':\n print (\"26 - Got a true expression value find *\")\n def f26():\n cur.execute('''SELECT name FROM mojrem join habs on mojrem.id_mj=habs.id_mj where (extract(year from payan_habs ))- (extract(year from shoro_habs )) > 0002 ''')\n for a in cur.fetchall():\n print(a)\n conn.commit()\n f26()\n elif var1=='27':\n print (\"27 - Got a true expression value find *\")\n def f27():\n cur.execute('''SELECT mojrem.name FROM mojrem join bazdasht on mojrem.id_mj=bazdasht.id_mj join jorm on bazdasht.id_jo=jorm.id_jo where (extract(year from date_anjamjorm )) =1993 and jorm.name='ghatl' and jensiat='zan' ''')\n for a in cur.fetchall():\n print(a)\n conn.commit()\n f27()\n elif var1=='28':\n print (\"28 - Got a true expression value find *\")\n def f28():\n cur.execute('''SELECT extract(month from date_anjamjorm ) FROM bazdasht join jorm on bazdasht.id_jo=jorm.id_jo where jorm.name='ghatl' group by extract(month from date_anjamjorm ) order by count(extract(month from date_anjamjorm )) desc ''')\n for a in cur.fetchone():\n print(a)\n conn.commit()\n f28()\n elif var1=='29':\n print (\"29 - Got a true expression value find *\")\n def f29():\n cur.execute('''SELECT name,(extract(month from date_anjamjorm )) FROM bazdasht join jorm on bazdasht.id_jo=jorm.id_jo group by jorm.name,extract(month from date_anjamjorm ) order by count(extract(month from date_anjamjorm )) desc ''')\n for a in cur.fetchall():\n print(a)\n conn.commit()\n f29() \n elif var1 =='30':\n print (\"30 - Got a true expression value find *\")\n def f30():\n cur.execute('''SELECT name,count(*) FROM mojrem join bazdasht on mojrem.id_mj=bazdasht.id_mj where jensiat='moanas' group by mojrem.id_mj ORDER BY count(*) desc ''')\n for a in cur.fetchall():\n\t print(a)\n conn.commit()\n f30() \n elif var1 =='1': \n print (\"33 - Got a true expression value find *\")\n def f33():\n cur.execute('''SELECT mojrem.name,jorm.name, (date_bazdasht-date_anjamjorm) FROM bazdasht join jorm on bazdasht.id_jo=jorm.id_jo join mojrem on mojrem.id_mj=bazdasht.id_mj group by mojrem.name,jorm.name,(date_bazdasht-date_anjamjorm) ''') \n for a in cur.fetchall():\n\t print(a)\n conn.commit()\n f33()\n else:\n\t print(\"Got a false expression value\") \n else:\n print (\"Got a false expression value\")\n print(\"enter if you have another work and 0 for exit\")\n num=input()\nprint (\"Good bye!\")\nconn.close()\n","sub_path":"Police-Detention-Center.py","file_name":"Police-Detention-Center.py","file_ext":"py","file_size_in_byte":32682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"279465596","text":"from collections import OrderedDict\nfrom typing import Dict, List\n\nfrom django.contrib.auth.models import User\nfrom django.db import models\nfrom itertools import chain\n\nfrom django.db.models import ForeignKey\nfrom Gym_app.business_logic.util.deep_model_to_dict import DeepMapper\nfrom Gym_app.converters.AchievementsConverter import AchievementsConverter\nfrom Gym_app.converters.MemberToDtoConverter import MemberToDtoConverter\nfrom Gym_app.converters.UserToDtoConverter import UserToDtoConverter\nfrom Gym_app.models import Goal\nfrom Gym_app.models import Member\n\n\nclass DjangoObjectsMapper:\n def __init__(self, should_user_to_email = None, should_member_basic_info = None):\n self.mapper = DeepMapper()\n self.user_converter = UserToDtoConverter()\n self.member_converter = MemberToDtoConverter()\n self.should_user_to_email = should_user_to_email\n self.should_member_basic_info = should_member_basic_info\n self.achievements_converter = AchievementsConverter()\n\n def map(self, collection):\n if self.should_member_basic_info:\n if isinstance(collection, Member):\n return self.member_converter.convert(collection)\n\n if self.should_user_to_email:\n if isinstance(collection, User):\n return collection.email\n\n if isinstance(collection, int):\n return collection\n\n if isinstance(collection, str):\n return collection\n\n if isinstance(collection, Member):\n return self.user_converter.convert(collection)\n\n if isinstance(collection, Goal):\n return self.achievements_converter.convertGoal(collection)\n\n if isinstance(collection, models.Model):\n return self.model_to_dict(collection)\n\n if isinstance(collection, Dict):\n newDict = OrderedDict()\n for key in collection:\n newDict[key] = self.map(collection[key])\n return newDict\n\n if isinstance(collection, List) or isinstance(collection, models.QuerySet):\n newList = []\n for i, value in enumerate(collection):\n newList.insert(i, self.map(collection[i]))\n return newList\n\n def model_to_dict(self, instance, fields=None, exclude=None):\n opts = instance._meta\n data = {}\n for f in chain(opts.concrete_fields, opts.private_fields, opts.many_to_many):\n if not getattr(f, 'editable', False):\n continue\n if fields and f.name not in fields:\n continue\n if exclude and f.name in exclude:\n continue\n if isinstance(f, ForeignKey):\n data[f.name] = self.map(f.related_model.objects.filter(pk=f.value_from_object(instance))[0]) if f.related_model.objects.filter(pk=f.value_from_object(instance)).exists() else None\n continue\n if isinstance(f, models.ManyToManyField):\n data[f.name] = self.map(f.value_from_object(instance))\n continue\n data[f.name] = f.value_from_object(instance)\n return data\n","sub_path":"Gym_app/business_logic/util/django_objects_serializer.py","file_name":"django_objects_serializer.py","file_ext":"py","file_size_in_byte":3124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"356137423","text":"import imutils\nimport cv2\n\n#LOADING IMAGE INTO MEMORY\nimage = cv2.imread(\"jp.png\")\ncv2.imshow(\"Original Image\", image)\n(h, w, d) = image.shape\n\n# apply a Gaussian blur with a 11x11 kernel to the image to smooth it,\n# useful when reducing high frequency noise\nblurred = cv2.GaussianBlur(image, (11, 11), 0)\ncv2.imshow(\"Blurred\", blurred)\n\n#BREAKE THE LOOP\ncv2.waitKey()\n","sub_path":"06 - Smoothing a image.py","file_name":"06 - Smoothing a image.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"616069075","text":"'''\nCheck list:\n\n1. Better practice to store API call output in a variable.\n2. Avoid calling API calls in loops. Instead use variables.\n\nDocumentations:\n\nGraphite -- http://graphite-api.readthedocs.io/en/latest/\n http://graphite.readthedocs.io/en/latest/\nGrafana -- https://www.hostedgraphite.com/docs/advanced/grafana-api.html\nDocker -- https://docker-py.readthedocs.io/en/stable/\nAWS -- https://boto3.readthedocs.io/en/latest/\nVarnish -- https://varnish-cache.org/\ndjango -- https://docs.djangoproject.com/en/2.0/\n\nUseful links:\nhttp://ipython.readthedocs.io/en/stable/interactive/magics.html\nhttps://www.dataquest.io/blog/learn-data-science/\nhttp://docs.activestate.com/activepython/3.3/pywin32/html/com/win32com/HTML/QuickStartClientCom.html\nhttp://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html\nhttps://www.digitalocean.com/community/tutorials/how-to-use-web-apis-in-python-3\nhttps://www.digitalocean.com/community/tutorials/how-to-scrape-web-pages-with-beautiful-soup-and-python-3\nhttps://www.digitalocean.com/community/tutorials/how-to-work-with-web-data-using-requests-and-beautiful-soup-with-python-3\n\n'''\n\n# python modules that you should aware of to do basic automations\n\nimport requests\nimport win32com.client\nimport pywinauto #https://pywinauto.readthedocs.io/en/latest/getting_started.html\n #https://media.readthedocs.org/pdf/pywinauto/latest/pywinauto.pdf\nimport pyautogui\nimport urllib.request #Equivalent to urllib2 in python3\nimport logging\nimport boto3\nimport subprocess\nimport json\nimport random\nimport os\nimport sys\nimport fabric3 # http://docs.fabfile.org/en/1.14/tutorial.html\nimport re\nimport glob\nimport fnmatch\nimport selenium\nimport django\nimport xlwings\nimport openpyxl # https://openpyxl.readthedocs.io/en/stable/tutorial.html\nimport xlsxwriter # http://xlsxwriter.readthedocs.io/index.html\nimport pynput # https://pypi.python.org/pypi/pynput\nimport getpass # https://docs.python.org/3/library/getpass.html\nimport pyHook # http://pyhook.sourceforge.net/doc_1.5.0/\nimport pythoncom\nimport pwd # https://docs.python.org/3/library/pwd.html#module-pwd\nimport pandas\nimport numpy\n\n#Setting up assumerole on boto3\n\nsts=boto3.client('sts')\nres=sts.assume_role(RoleArn='arn:aws:iam::462397709356:role/lakana-fox-admin',RoleSessionName='testrole')\n\ns3=boto3.client('s3',aws_access_key_id=res['Credentials']['AccessKeyId'],\naws_secret_access_key=res['Credentials']['SecretAccessKey'],\naws_session_token=res['Credentials']['SessionToken']) \n\n\n#listing buckets and objects of each bucket\n\nfor i in range(len(s3.list_buckets()['Buckets'])):\n buck=s3.list_buckets()['Buckets'][i]['Name']\n pprint.pprint(s3.list_objects(Bucket=buck))\n time.sleep(1000)\n \n#Listing each object that CacheControl metadata set\n\nAPI_list_buckets\ncount=0\nfor i in range(len(s3.list_buckets()['Buckets'])):\n buck=API_list_buckets['Buckets'][i]['Name']\n pprint.pprint('Bucket=',buck)\n print('\\n'*3)\n if count==4:\n break\n try:\n for j in range(len(s3.list_objects(Bucket=buck)['Contents'])):\n obj=s3.list_objects(Bucket=buck)['Contents'][j]['Key']\n# pprint.pprint(\"Object=\",obj)\n rep=s3.get_object(Bucket=buck,Key=obj)\n if rep['CacheControl']:\n print(obj,\"set CacheControl=\",rep['CacheControl'])\n count=count+1\n \n except:\n pass\n\n\n#listing buckets, objects, Keys \n\ns3l=boto3.client('s3') #Creating s3 boto3 object\ns3_buckets=s3l.list_buckets() #Listing buckets under the account\n\ns3_objects=s3l.list_objects(Bucket='lakana-cloudformation')['Contents']\nno_of_objs=len(s3_objects)\nfor i in range(no_of_objs):\n print(s3_obje_ts[i]['Key']) #Listing object keys under specific bucket\n\ns3_objects=s3l.list_objects(Bucket='lakana-cloudformation')['Contents']\nno_of_objs=len(_)\nfor i in range(no_of_objs):\n if s3_objects[i]['Key'].startswith('platform'):\n print(s3_objects[i]['Key']) #Listing object keys those starts with specific word\n\n'''\nExam\nimport boto3\ns3 = boto3.resource('s3')\ns3.meta.client.download_file('mybucket', 'hello.txt', '/tmp/hello.txt')\n\n'''\n\n#Downloading objects from specific s3 bucket with specific word they start with\n\n''' https://www.peterbe.com/plog/fastest-way-to-download-a-file-from-s3 \n https://alexwlchan.net/2017/07/listing-s3-keys/\n'''\n\ns3_objects=s3l.list_objects(Bucket='lakana-cloudformation')['Contents']\nno_of_objs=len(s3_objects)\nfor i in range(no_of_objs):\n if s3_objects[i]['Key'].startswith('platform/v37'):\n obj_download=s3_objects[i]['Key']\n s3l.download_file('lakana-cloudformation',obj_download,obj_download.split('/')[-1])\n\n\n\n#Deleting security groups from the account\n\n\nec2=boto3.client('ec2')\n\nsg=ec2.describe_security_groups()\n\n#print(\"List of security groups:\")\nfor i in range(len(sg['SecurityGroups'])):\n if sg['SecurityGroups'][i]['GroupName'] == 'default':\n print(\"Default SG can't be deleted\")\n else:\n try:\n del_g=ec2.delete_security_group(GroupName=sg['SecurityGroups'][i]['GroupName'])\n if del_g['ResponseMetadata']['HTTPStatusCode']==200:\n print(sg['SecurityGroups'][i]['GroupName'],\"is deleted\")\n except:\n print(\"Some error occurred while deleting \",sg['SecurityGroups'][i]['GroupName'])\n\n\n#Remove directory from git and local\n'''\nYou could checkout 'master' with both directories;\n\ngit rm -r one-of-the-directories\ngit commit -m \"Remove duplicated directory\"\ngit push origin (typically 'master', but not always)\nRemove directory from git but NOT local\nAs mentioned in the comments, what you usually want to do is remove this directory from git but not delete it entirely from the filesystem (local)\n\nIn that case use:\n\ngit rm -r --cached myFolder\n\n''' \n\n#Solution for json serialize a datetime object and dumping dict object into an external json file.\n\nimport datetime\nimport json\n\ndef myconverter(o):\n if isinstance(o, datetime.datetime):\n return o.__str__()\n\nwith open('data.txt', 'w') as outfile:\n json.dump(data, outfile, default=myconverter) #json.dumps(data,default=myconverter)\n\n#Listing instances Names, instance types\n\nimport boto3\nimport openpyxl as el\nec2=boto3.client(\"ec2\")\n\ndata=ec2.describe_instances() \n\n''' goto with #8 '''\n\ncount=0\nwb=el.Workbook()\nsh1=wb.create_sheet(\"Avg CPU\")\nsh1['A1']=\"Instace Name\"\nsh1['B1']=\"Instance Type\"\nsh1['C1']=\"State\"\nsh1['D1']=\"Avg CPU\"\n\nfor i in range(len(data['Reservations'])):\n for j in range(len(data['Reservations'][i]['Instances'])):\n count=count+len(data['Reservations'][i]['Instances'])\n for k in range(len(data['Reservations'][i]['Instances'][j]['Tags'])):\n if data['Reservations'][i]['Instances'][j]['Tags'][k]['Key']=='Name':\n ins_name=data['Reservations'][i]['Instances'][j]['Tags'][k]['Value'].strip()\n ins_type=data['Reservations'][i]['Instances'][j]['InstanceType']\n state=data['Reservations'][i]['Instances'][j]['State']['Name']\n sh1.cell(row=count+1,column=1,value=ins_name)\n sh1.cell(row=count+1,column=2,value=ins_type)\n sh1.cell(row=count+1,column=3,value=state)\nwb.save(\"ins_info1.xlsx\")\nwb.close()\n\n\n\n\nfor i in range(len(data['Reservations'])):\n for j in range(len(data['Reservations'][i]['Instances'])):\n for k in range(len(data['Reservations'][i]['Instances'][j]['Tags'])):\n if data['Reservations'][i]['Instances'][j]['Tags'][k]['Key']=='Name':\n print(data['Reservations'][i]['Instances'][j]['Tags'][k]['Value'].strip(), (data['Reservations'][i]['Instances'][j]['InstanceType']))\n\n\n\nfor i in range(len(data['Reservations'])):\n for j in range(len(data['Reservations'][i]['Instances'])):\n for k in range(len(data['Reservations'][i]['Instances'][j]['Tags'])):\n if data['Reservations'][i]['Instances'][j]['Tags'][k]['Key']=='Name':\n print(data['Reservations'][i]['Instances'][j]['Tags'][k]['Value'].strip(), (data['Reservations'][i]['Instances'][j]['InstanceType']))\n\n\n#Curser move for defined time intervel, shoud run on top on chrome(tested) or any other applications(untested)\n''' https://www.geeksforgeeks.org/mouse-keyboard-automation-using-python/ '''\nimport time\nimport pyautogui\n\nx=0\ny=700\nfor i in range(1000):\n pyautogui.moveTo(x,y,duration=1)\n pyautogui.click(x,y)\n time.sleep(2)\n x,y=y,x\n\n#Listening to keyboard infinite time, stops when perticular key is pressed\n\nfrom pynput import keyboard\n\ndef on_press(key):\n try:\n print('alphanumeric key {0} pressed'.format(key.char))\n except AttributeError:\n print('special key {0} pressed'.format(key))\n\ndef on_release(key):\n print('{0} released'.format(key))\n if key == keyboard.Key.esc:\n # Stop listener\n return False\n\n#Collect events until released\nwith keyboard.Listener(\n on_press=on_press,\n on_release=on_release) as listener:\n listener.join()\n'''\nimport pythoncom, pyHook \n\ndef uMad(event):\n return False\n\nhm = pyHook.HookManager()\nhm.MouseAll = uMad\nhm.KeyAll = uMad\nhm.HookMouse()\nhm.HookKeyboard()\npythoncom.PumpMessages()\n'''\n\n\n#Work on status of remote servers\n\nimport boto3\nimport fabric3\nfrom fabric.api import run,env\n\nec2=boto3.client('ec2')\n\n\n# How to serialize a datetime object as JSON using Python?\n''' Got this error when dumping json varialbe into a local file \nSolution:\n The solution is quite simple. The json.dumps method can accept an optional parameter called default which is expected to be a function. Every time JSON tries to convert a value it does not know how to convert it will call the function we passed to it. The function will receive the object in question, and it is expected to return the JSON representation of the object.\n\n In the function we just call the __str__ method of the datetime object that will return a string representation of the value. This is what we return.\n \n While the condition we have in the function is not required, if we expect to have other types of objects in our data structure that need special treatment, we can make sure our function handles them too. As dealing with each object will probably be different we check if the current object is one we know to handle and do that inside the if statement. \n'''\n\nimport json\nimport datetime\n\ndef con(o):\n if isinstance(o,datetime.datetime):\n return o.__str__()\nwith open('feedsData.json','w') as outfile:\n print(json.dump(res,outfile,default=con)) #res is json response variable from AWS query\n\nimport json\nwith open('data.txt', 'w') as outfile:\n json.dump(data, outfile)","sub_path":"aws-repo/Lakana_support.py","file_name":"Lakana_support.py","file_ext":"py","file_size_in_byte":10706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"205407962","text":"#\r\n# [551] Student Attendance Record I\r\n#\r\n# https://leetcode.com/problems/student-attendance-record-i/description/\r\n#\r\n# algorithms\r\n# Easy (44.94%)\r\n# Total Accepted: 40.1K\r\n# Total Submissions: 89.1K\r\n# Testcase Example: '\"PPALLP\"'\r\n#\r\n# You are given a string representing an attendance record for a student. The\r\n# record only contains the following three characters:\r\n# \r\n# \r\n# \r\n# 'A' : Absent. \r\n# 'L' : Late.\r\n# ⁠'P' : Present. \r\n# \r\n# \r\n# \r\n# \r\n# A student could be rewarded if his attendance record doesn't contain more\r\n# than one 'A' (absent) or more than two continuous 'L' (late). \r\n# \r\n# You need to return whether the student could be rewarded according to his\r\n# attendance record.\r\n# \r\n# Example 1:\r\n# \r\n# Input: \"PPALLP\"\r\n# Output: True\r\n# \r\n# \r\n# \r\n# Example 2:\r\n# \r\n# Input: \"PPALLL\"\r\n# Output: False\r\n# \r\n# \r\n# \r\n# \r\n# \r\n#\r\nclass Solution:\r\n def checkRecord(self, s):\r\n \"\"\"\r\n :type s: str\r\n :rtype: bool\r\n \"\"\"\r\n suma = 0\r\n for i in range(0,len(s)):\r\n if s[i] == \"A\":\r\n suma += 1\r\n if suma > 1:\r\n return False\r\n if s[i] == \"L\" and i > 1:\r\n if s[i-1] == \"L\" and s[i-2] == \"L\":\r\n return False\r\n return True\r\n\r\nif __name__ == \"__main__\":\r\n print(Solution().checkRecord(\"PLALL\"))\r\n","sub_path":"leetcode/551.student-attendance-record-i.python3.py","file_name":"551.student-attendance-record-i.python3.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"247135853","text":"from metaflow import FlowSpec,step\n\nclass TableAnalysisFlow(FlowSpec):\n \n @step\n def start(self):\n from pathlib import Path\n import random\n import os\n self.ROOT_PATH = Path('data')\n source_path = self.ROOT_PATH / 'sources'\n # self.arxiv_paths = random.sample(os.listdir(source_path),2)\n self.arxiv_paths = os.listdir(source_path) #random.sample(,2)\n self.next(self.table_extractor,foreach='arxiv_paths')\n \n @step\n def table_extractor(self):\n from axcell.helpers.paper_extractor import PaperExtractor\n from axcell.data.paper_collection import PaperCollection\n extract = PaperExtractor(self.ROOT_PATH)\n SOURCE_PATH = self.ROOT_PATH / 'sources' / self.input\n try:\n extract(SOURCE_PATH)\n self.paper_id = self.input.replace('.tar.gz','')\n PAPERS_PATH = self.ROOT_PATH / 'papers'\n pc = PaperCollection.from_files(PAPERS_PATH)\n self.paper = pc.get_by_id(self.paper_id) \n except:\n self.paper=None\n self.paper_id=None\n \n self.next(self.join)\n \n @step\n def join(self,inputs):\n self.processed_papers = []\n for i in inputs:\n self.processed_papers.append((i.paper_id,i.paper))\n self.next(self.end) \n \n @step\n def end(self):\n print(\"Done Computation\")\n\n\n\nif __name__ == '__main__':\n TableAnalysisFlow()\n\n\n\n ","sub_path":"notebooks/metaflow_tables.py","file_name":"metaflow_tables.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"559824590","text":"import json\nwith open('estoque.json', 'r') as arquivo_j:\n texto = arquivo_j.read()\n\ndic = json.loads(texto)\ntotal = 0\nfor k in dic:\n for ki in k:\n q = ki[\"quantidade\"]\n total += q\nprint(total)","sub_path":"backup/user_101/ch159_2020_05_05_03_33_12_728699.py","file_name":"ch159_2020_05_05_03_33_12_728699.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"29245038","text":"# Project Euler #9\n\n# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,\n\n# a^2 + b^2 = c^2\n# For example, 32 + 42 = 9 + 16 = 25 = 52.\n\n# There exists exactly one Pythagorean triplet for which a + b + c = 1000.\n# Find the product abc.\n\n## ========================= ##\n\n# This problem is small enough that we do not need to worry about the run\n# time of iterating 1000*1000 times, so inefficiencies in the loop are negliable \n\nfor a in range (1,1000):\n for b in range(1,1000):\n if a+b+(a**2+b**2)**.5 == 1000:\n print(a*b*(a**2+b**2)**.5) ## prints twice, because the position of\n ## a and b are interchangable in the solution\n break\n \n","sub_path":"9.py","file_name":"9.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"410585157","text":"#coding=utf-8\r\n'''\r\nCreated on 2016年7月2日\r\n\r\n@author: zeroz\r\n'''\r\nimport logging\r\nimport time\r\n\r\ndef getLogger(name):\r\n now = time.strftime('%Y-%m-%d %H:%M:%S')\r\n \r\n logging.basicConfig(\r\n level = logging.DEBUG,\r\n format = now +\" : \" + name + ' LINE %(lineno)-4d %(levelname)-8s %(message)s',\r\n datefmt = '%m-%d %H:%M',\r\n filename = \"F:\\\\python\\\\log\\\\stock.log\",\r\n filemode = 'w');\r\n \r\n console = logging.StreamHandler();\r\n console.setLevel(logging.DEBUG);\r\n formatter = logging.Formatter(name + ': LINE %(lineno)-4d : %(levelname)-8s %(message)s');\r\n console.setFormatter(formatter);\r\n \r\n logger = logging.getLogger(name)\r\n logger.addHandler(console); \r\n return logger\r\n \r\nif __name__ == '__main__':\r\n getLogger(\"www\").debug(\"www\")\r\n","sub_path":"src/log/LoggerFactory.py","file_name":"LoggerFactory.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"393259717","text":"from __future__ import division\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nfrom scipy import stats\nfrom scipy.spatial.distance import cdist\nfrom sklearn.metrics import brier_score_loss\nimport pdb\nst = pdb.set_trace\n\ndef moving_average(values, window):\n weights = np.repeat(1.0, window)/window\n sma = np.convolve(values, weights, 'valid')\n return sma\n\ndef draw_sample(model_batch, real_batch, scale, fname, color=None):\n fig = plt.figure(frameon=False)\n fig.set_size_inches(5, 5)\n ax = fig.add_subplot(1, 1, 1)\n if real_batch is not None:\n ax.scatter(real_batch[:, 0], real_batch[:, 1], s=100, c='g', alpha=0.1)\n if color is None:\n color = 'b'\n if model_batch is not None:\n ax.scatter(model_batch[:, 0], model_batch[:, 1], s=100, c=color, alpha=0.1)\n ax.set_xlim((-scale, scale))\n ax.set_ylim((-scale, scale))\n ax.set_axis_off()\n ax.set_aspect('equal')\n ax.spines['bottom'].set_color('0.5')\n ax.spines['top'].set_color('0.5')\n ax.spines['right'].set_color('0.5')\n ax.spines['left'].set_color('0.5')\n plt.savefig(fname, bbox_inches='tight', pad_inches=0)\n plt.close(fig)\n\ndef draw_landscape(grid_batch, grid_sigmoid, real_batch, scale, fname):\n fig = plt.figure(frameon=False)\n fig.set_size_inches(5, 5)\n ax = fig.add_subplot(1, 1, 1)\n\n # Discriminator contour\n x_mesh = np.reshape(grid_batch[:, 0], [int(np.sqrt(grid_batch.shape[0])), -1]).T\n y_mesh = np.reshape(grid_batch[:, 1], [int(np.sqrt(grid_batch.shape[0])), -1]).T\n v_mesh = np.reshape(grid_sigmoid, [int(np.sqrt(grid_batch.shape[0])), -1]).T\n ax.contourf(x_mesh, y_mesh, v_mesh, 100, cmap='Greys', vmin=0.0, vmax=0.7)\n\n # Real samples\n ax.scatter(real_batch[:, 0], real_batch[:, 1], s=10, c='g')\n\n ax.set_xlim((-scale, scale))\n ax.set_ylim((-scale, scale))\n ax.set_axis_off()\n ax.set_aspect('equal')\n ax.spines['bottom'].set_color('0.5')\n ax.spines['top'].set_color('0.5')\n ax.spines['right'].set_color('0.5')\n ax.spines['left'].set_color('0.5')\n plt.savefig(fname, bbox_inches='tight', pad_inches=0)\n plt.close(fig)\n\ndef draw_density(samps, scale, fname):\n fig = plt.figure(frameon=False)\n fig.set_size_inches(5, 5)\n ax = fig.add_subplot(1, 1, 1)\n\n # Real samples\n import seaborn as sns\n sns.kdeplot(samps[:, 0], samps[:, 1], shade=True, cmap='Greys', n_levels=100)\n\n ax.set_xlim((-scale, scale))\n ax.set_ylim((-scale, scale))\n ax.set_axis_off()\n ax.set_aspect('equal')\n ax.spines['bottom'].set_color('0.5')\n ax.spines['top'].set_color('0.5')\n ax.spines['right'].set_color('0.5')\n ax.spines['left'].set_color('0.5')\n plt.savefig(fname, bbox_inches='tight', pad_inches=0)\n plt.close(fig)\n\ndef draw_histogram(samps, scale, fname):\n fig = plt.figure(frameon=False)\n fig.set_size_inches(5, 5)\n ax = fig.add_subplot(1, 1, 1)\n\n ax.hist2d(samps[:, 0], samps[:, 1], bins=(50, 50), cmap=plt.cm.BuPu)\n ax.set_xlim((-scale, scale))\n ax.set_ylim((-scale, scale))\n ax.set_axis_off()\n ax.set_aspect('equal')\n ax.spines['bottom'].set_color('0.5')\n ax.spines['top'].set_color('0.5')\n ax.spines['right'].set_color('0.5')\n ax.spines['left'].set_color('0.5')\n plt.savefig(fname, bbox_inches='tight', pad_inches=0)\n plt.close(fig)\n\ndef draw_kde(samps, scale, fname):\n fig = plt.figure(frameon=False)\n fig.set_size_inches(5, 5)\n ax = fig.add_subplot(1, 1, 1)\n\n from scipy.stats import kde\n nbins = 100\n x = samps[:, 0]\n y = samps[:, 1]\n k = kde.gaussian_kde([x, y])\n k.set_bandwidth(bw_method=k.factor/2.)\n xi, yi = np.mgrid[-scale:scale:nbins*1j, -scale:scale:nbins*1j]\n zi = k(np.vstack([xi.flatten(), yi.flatten()]))\n\n vmax_factor = 0.2\n ax.pcolormesh(xi, yi, zi.reshape(xi.shape), cmap=plt.cm.BuPu, vmin=np.min(zi), vmax=max(np.max(zi)*vmax_factor, np.min(zi)))\n\n ax.set_xlim((-scale, scale))\n ax.set_ylim((-scale, scale))\n ax.set_axis_off()\n ax.set_aspect('equal')\n ax.spines['bottom'].set_color('0.5')\n ax.spines['top'].set_color('0.5')\n ax.spines['right'].set_color('0.5')\n ax.spines['left'].set_color('0.5')\n plt.savefig(fname, bbox_inches='tight', pad_inches=0)\n plt.close(fig)\n\n\ndef pairwise_distance(real_batch, model_batch):\n dist_matrix = cdist(real_batch, model_batch)\n dist_eye = 10.0*np.identity(dist_matrix.shape[0])\n dist_min = np.min(dist_matrix+dist_eye, axis=0)\n return dist_min\n\ndef metrics_distance(samples, centeroids, thres):\n samples = np.array(samples)\n centeroids = np.array(centeroids)\n n = np.size(samples, 0)\n k = np.size(centeroids, 0)\n distances = np.zeros((n, k))\n for i in range(k):\n distances[:, i] = np.linalg.norm(samples - centeroids[i], axis=1)\n dist_min = np.min(distances, axis=1)\n cnt_good = (dist_min < thres).sum()\n cnt_all = dist_min.size\n rate_good = cnt_good / cnt_all\n mean_dist = np.mean(dist_min)\n return mean_dist, rate_good\n\ndef metrics_recovered(samples, labels, centeroids, thres, thres_good=0.9):\n # conditional, # modes recovered\n samples = np.array(samples)\n centeroids = np.array(centeroids)\n # n = np.size(samples, 0)\n k = np.size(centeroids, 0)\n recovered = np.zeros(k)\n for i in range(k):\n samples_ = samples[labels==i]\n distances_ = np.linalg.norm(samples_ - centeroids[i], axis=1)\n rate_good = (distances_ < thres).sum() / samples_.shape[0]\n if rate_good >= thres_good:\n recovered[i] = 1\n rate_recovered = np.mean(recovered)\n return rate_recovered\n\ndef freq_category(samples, centeroids, thres):\n n_category = np.size(centeroids, 0)\n n_samples = np.size(samples, 0)\n distances = np.ones((n_samples, n_category))\n for i in range(n_category):\n distances[:, i] = np.linalg.norm(samples - centeroids[i], axis=1)\n clusters = distances < thres\n counts = np.sum(clusters, axis=0)\n sum_counts = np.sum(counts)\n if sum_counts > 0:\n freqs_valid = counts / sum_counts\n else:\n freqs_valid = np.ones(n_category) / n_category # uniform\n freqs_all = np.append(counts, n_samples-sum_counts) / n_samples\n return freqs_valid, freqs_all\n\ndef metrics_diversity(real_batch, model_batch, centeroids, thres):\n freq_real, _ = freq_category(real_batch, centeroids, thres)\n freq_model, _ = freq_category(model_batch, centeroids, thres)\n kl = kl_div(freq_model, freq_real)\n return kl\n\ndef kl_div(predictions, targets):\n \"\"\"\n Input: predictions (k,1) ndarray\n targets (k,1) ndarray\n Returns: scalar\n \"\"\"\n targets = np.clip(targets, a_min=1e-12, a_max=1 - 1e-12)\n kl = stats.entropy(predictions, targets)\n return kl\n\ndef metrics_distribution(real_batch, model_batch, centeroids, thres):\n _, freq_real = freq_category(real_batch, centeroids, thres)\n _, freq_model = freq_category(model_batch, centeroids, thres)\n freq_avg = (freq_real + freq_model) * 0.5\n js = 0.5 * kl_div(freq_real, freq_avg) + 0.5 * kl_div(freq_model, freq_avg)\n return js\n\ndef calib_score(y_prob, y_true):\n '''\n Function borrowed from MH-GAN\n y_prob : ndarray, shape (n,)\n floats in [0, 1]\n y_true : ndarray, shape (n,)\n bool\n '''\n Z = np.sum(y_true - y_prob) / np.sqrt(np.sum(y_prob * (1.0 - y_prob)))\n return Z\n\ndef column_or_1d(y, warn=False):\n \"\"\" Ravel column or 1d numpy array, else raises an error\n Parameters\n ----------\n y : array-like\n warn : boolean, default False\n To control display of warnings.\n Returns\n -------\n y : array\n \"\"\"\n shape = np.shape(y)\n if len(shape) == 1:\n return np.ravel(y)\n if len(shape) == 2 and shape[1] == 1:\n if warn:\n pass\n return np.ravel(y)\n\n raise ValueError(\"bad input shape {0}\".format(shape))\n\n\ndef calibration_bins(y_true, y_prob, n_bins=50, strategy='uniform'):\n \"\"\"Compute true and predicted probabilities for a calibration curve.\n The method assumes the inputs come from a binary classifier.\n Calibration curves may also be referred to as reliability diagrams.\n Read more in the :ref:`User Guide `.\n Parameters\n ----------\n y_true : array, shape (n_samples,)\n True targets.\n y_prob : array, shape (n_samples,)\n Probabilities of the positive class.\n normalize : bool, optional, default=False\n Whether y_prob needs to be normalized into the bin [0, 1], i.e. is not\n a proper probability. If True, the smallest value in y_prob is mapped\n onto 0 and the largest one onto 1.\n n_bins : int\n Number of bins. A bigger number requires more data. Bins with no data\n points (i.e. without corresponding values in y_prob) will not be\n returned, thus there may be fewer than n_bins in the return value.\n strategy : {'uniform', 'quantile'}, (default='uniform')\n Strategy used to define the widths of the bins.\n uniform\n All bins have identical widths.\n quantile\n All bins have the same number of points.\n Returns\n -------\n prob_true : array, shape (n_bins,) or smaller\n The true probability in each bin (fraction of positives).\n prob_pred : array, shape (n_bins,) or smaller\n The mean predicted probability in each bin.\n References\n ----------\n Alexandru Niculescu-Mizil and Rich Caruana (2005) Predicting Good\n Probabilities With Supervised Learning, in Proceedings of the 22nd\n International Conference on Machine Learning (ICML).\n See section 4 (Qualitative Analysis of Predictions).\n \"\"\"\n y_true = column_or_1d(y_true)\n y_prob = column_or_1d(y_prob)\n\n if strategy == 'quantile': # Determine bin edges by distribution of data\n quantiles = np.linspace(0, 1, n_bins + 1)\n bins = np.percentile(y_prob, quantiles * 100)\n bins[-1] = bins[-1] + 1e-8\n elif strategy == 'uniform':\n bins = np.linspace(0., 1. + 1e-8, n_bins + 1)\n else:\n raise ValueError(\"Invalid entry to 'strategy' input. Strategy \"\n \"must be either 'quantile' or 'uniform'.\")\n\n binids = np.digitize(y_prob, bins) - 1\n\n bin_sums = np.bincount(binids, weights=y_prob, minlength=len(bins))\n bin_true = np.bincount(binids, weights=y_true, minlength=len(bins))\n bin_total = np.bincount(binids, minlength=len(bins))\n\n nonzero = bin_total != 0\n prob_true = (bin_true[nonzero] / bin_total[nonzero])\n prob_pred = (bin_sums[nonzero] / bin_total[nonzero])\n\n weights_bin = bin_total[nonzero] / y_true.shape[0]\n\n return prob_true, prob_pred, weights_bin\n\ndef calibration_error(confidence, accuracy, weights):\n assert np.absolute(np.sum(weights)-1.0) < 1e-4, 'Abnormal sum of weights, residual = {:.6f}'.format((np.sum(weights)-1.0))\n expeced_calibration_error = np.sum(np.absolute(accuracy - confidence) * weights)\n maximum_calibration_error = np.max(np.absolute(accuracy - confidence))\n return expeced_calibration_error, maximum_calibration_error\n\ndef calibration_diagnostic(fake_sigmoid, real_sigmoid, fname=None):\n y_pred = np.concatenate([(fake_sigmoid), (real_sigmoid)])\n y_true = np.concatenate([np.zeros_like(fake_sigmoid), np.ones_like(real_sigmoid)])\n accuracy, confidence, weights = calibration_bins(y_true, y_pred, n_bins=20)\n z_dawid = calib_score(y_pred, y_true)\n brier_score = brier_score_loss(y_true, y_pred)\n ece, mce = calibration_error(confidence, accuracy, weights)\n if fname is not None:\n draw_reliability(confidence, accuracy, weights, z_dawid, brier_score, ece, mce, fname)\n return z_dawid, brier_score, ece, mce\n\ndef draw_reliability(confidence, accuracy, weights, dawid, brier, ece, mce, fname):\n fig = plt.figure(frameon=False, figsize=(4.6, 6))\n gridspec.GridSpec(5, 1)\n ax1 = plt.subplot2grid((5, 1), (0, 0), rowspan=4)\n ax2 = plt.subplot2grid((5, 1), (4, 0))\n\n ax1.plot([0, 1], [0, 1], \"k:\")\n ax1.plot(confidence, accuracy, \"s-\")\n ax1.set_xlim((0.0, 1.0))\n ax1.set_ylim((0.0, 1.0))\n ax1.set_aspect('equal')\n ax1.xaxis.set_major_formatter(plt.NullFormatter())\n ax1.set_ylabel(\"Accuracy\")\n ax1.set_title('dawid: {:.2f}, brier: {:.2f}, ece: {:.2f}, mce: {:.2f}'.format(dawid, brier, ece, mce))\n\n ax2.plot(confidence, weights, 'x')\n ax2.set_xlim((0.0, 1.0))\n ax2.set_ylim((0.0, 0.6))\n ax2.set_xlabel(\"Confidence\")\n ax2.set_ylabel(\"Weights\")\n\n plt.savefig(fname, bbox_inches='tight', pad_inches=0)\n plt.close(fig)\n","sub_path":"utils_sampling.py","file_name":"utils_sampling.py","file_ext":"py","file_size_in_byte":12547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"474932792","text":"import numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\nimport _init_paths\nfrom network import ResAutoEncoderTrainNet\nfrom network import ResAutoEncoderTestNet\nfrom utils import Avg, apply_window\nfrom dataset import get_train_pair\n\nmodel_name = 'patch_based'\nsave_dir = '/home/mike/models/' + model_name + '/'\nmax_iter = 10000\n\nimg_x = tf.placeholder(tf.float32, [None,None,None])\nimg_y = tf.placeholder(tf.float32, [None,None,None])\n\nrnd_init = tf.placeholder(tf.int32, [2])\n\nx_reshape = tf.expand_dims(img_x, axis=3)\n\nmodel = ResAutoEncoderTrainNet('modelpb')\n#model = ResAutoEncoderTestNet('x_autoencoderk')\ncodes = model.encoder(x_reshape)\nrecon = model.decoder(codes)\n\n\nmask = tf.greater(img_y, tf.reduce_mean(img_y))\nmask = tf.cast(mask, tf.float32) + .1\nloss = tf.reduce_mean( (img_y - recon)**2 * mask ) \\\n * 100.0\n\n\nx_im_patch = tf.extract_image_patches(x_reshape,\n ksizes=[1,31,31,1],\n strides=[1,15,15,1],\n rates=[1,1,1,1],\n padding='VALID')\n\nx_init=2\ny_init=4\n#img_y = img_y[:,rnd_init[0]:, rnd_init[1]:]\ny_im_patch = tf.extract_image_patches(tf.expand_dims(img_y, axis=3),\n ksizes=[1,33,33,1],\n strides=[1,17,17,1],\n rates=[1,1,1,1],\n padding='VALID')\n\n\n# + tf.reduce_mean( tf.abs(img_y - recon) )\n#loss = tf.reduce_mean(tf.square(tf.subtract(img_y, recon)))# + tf.abs(recon))\nopt = tf.train.AdamOptimizer(1e-6)\ntrain_op = opt.minimize(loss)\nupdate_op = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\n#model.pretrain_load(sess)\nsaver = tf.train.Saver()\n#saver.restore(sess, 'models/supervision.ckpt')\n\navg = Avg(['loss'])\nfor i in range(1, 1+max_iter):\n x, y = get_train_pair(8)\n rnd = np.random.randint(100, size=2)\n fd = {img_x: x, img_y: y[:, rnd[0]:, rnd[1]:]}\n# _, _, l = sess.run([train_op, update_op, loss], fd)\n l = 0\n\n p = sess.run(y_im_patch, fd)\n print (p.shape)\n p = sess.run(img_y, fd)\n print (p.shape)\n avg.add(l, 0)\n if i % 10 == 0:\n avg.show(i)\n if i % 10 == 0:\n rc, rx, ry = sess.run([recon, img_x, img_y], fd)\n for k in range(rc.shape[0]):\n np.save('sample_imgs/a_'+str(k)+'.npy', rc[k])\n np.save('sample_imgs/x_'+str(k)+'.npy', rx[k])\n np.save('sample_imgs/y_'+str(k)+'.npy', ry[k])\n np.save('sample_imgs/p.npy', p)\n avg.description()\n print (np.mean(rc), np.mean(ry), np.mean(rx))\n saver.save(sess, save_dir + 'a.ckpt')\n","sub_path":"train/_pb.py","file_name":"_pb.py","file_ext":"py","file_size_in_byte":2534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"44380624","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('group', '0006_auto_20150123_1946'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='month',\n name='time',\n field=models.TimeField(default=datetime.time(19, 51, 17, 378608)),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='month',\n name='time18',\n field=models.TimeField(default=datetime.time(20, 1, 17, 378608)),\n preserve_default=True,\n ),\n ]\n","sub_path":"group/migrations/0007_auto_20150123_1951.py","file_name":"0007_auto_20150123_1951.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"53995124","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat May 11 19:29:56 2019\r\n\r\n@author: Rutger\r\n\"\"\"\r\n\r\nimport math\r\nimport pandas as pd\r\nfrom pandas import Series\r\nfrom matplotlib import pyplot\r\nimport numpy as np\r\nfrom statsmodels.graphics.tsaplots import plot_acf\r\nfrom statsmodels.tsa.stattools import adfuller\r\nfrom statsmodels.tsa.arima_model import ARIMA\r\nfrom statsmodels.graphics.tsaplots import plot_pacf\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom scipy.stats import skew\r\nimport os\r\n\r\n# Make sure that the Excel file is in your working\r\n# directory. Also, make sure that you delete all\r\n# data prior to 2007 in the Excel file.\r\ncwd = os.getcwd()\r\nprint(cwd)\r\n\r\n# INDPRO\r\ndata = pd.read_excel('FREDMD_march2019_upto2007.xlsx')\r\ndf_ip = pd.DataFrame(data, columns= ['INDPRO'])\r\ndf_date = pd.DataFrame(data, columns= ['sasdate'])\r\n\r\npyplot.plot(df_date, df_ip)\r\n\r\nplot_acf(df_ip, lags=60)\r\nplot_pacf(df_ip, lags=10)\r\n\r\n# INDPRO differenced\r\ndf_ip2 = df_ip.iloc[:,0].values\r\ndef difference(dataset, interval):\r\n diff = list()\r\n for i in range(interval, len(dataset)):\r\n value = dataset[i] - dataset[i - interval]\r\n diff.append(value)\r\n return Series(diff)\r\ndf_ip_diff = difference(df_ip2, 1)\r\n\r\ndf_date2 = df_date.iloc[:,0].values\r\ndf_date2 = np.delete(df_date2,0)\r\n\r\npyplot.plot(df_date2, df_ip_diff)\r\npyplot.show()\r\nprint('Skewness: %f' % skew(df_ip_diff))\r\n\r\nplot_acf(df_ip_diff, lags=60)\r\nplot_pacf(df_ip_diff, lags=20)\r\n\r\n# INDPRO differenced log\r\nlogdf_ip = list()\r\nfor i in range(0, len(df_ip2)):\r\n value = math.log(df_ip2[i])\r\n logdf_ip.append(value)\r\n \r\nlogdf_ip = pd.DataFrame(logdf_ip)\r\nlogdf_ip2 = logdf_ip.iloc[:,0].values\r\nlogdf_ip_diff = difference(logdf_ip2, 1)\r\n\r\npyplot.plot(df_date2, logdf_ip_diff)\r\npyplot.show()\r\nprint('Skewness: %f' % skew(logdf_ip_diff))\r\n\r\nplot_acf(logdf_ip_diff, lags=60)\r\nplot_pacf(logdf_ip_diff, lags=20) \r\n\r\n# Adfuller tests\r\n## INDPRO w/o first differencing\r\nresult = adfuller(df_ip2)\r\nprint('ADF Statistic: %f' % result[0])\r\nprint('p-value: %f' % result[1])\r\nprint('Critical Values:')\r\nfor key, value in result[4].items():\r\n print('\\t%s: %.3f' % (key, value))\r\n\r\n## INDPRO first differenced \r\nresult2 = adfuller(df_ip_diff)\r\nprint('ADF Statistic: %f' % result2[0])\r\nprint('p-value: %f' % result2[1])\r\nprint('Critical Values:')\r\nfor key, value in result2[4].items():\r\n print('\\t%s: %.3f' % (key, value))\r\n \r\n## INDPRO first differenced log \r\nresult3 = adfuller(logdf_ip_diff)\r\nprint('ADF Statistic: %f' % result3[0])\r\nprint('p-value: %f' % result3[1])\r\nprint('Critical Values:')\r\nfor key, value in result3[4].items():\r\n print('\\t%s: %.3f' % (key, value))\r\n \r\n# ARIMA INDPRO \r\n## fit model ARIMA(4,1,0), differencing done \r\n## by ARIMA\r\nmodel = ARIMA(df_ip, order=(3, 1, 0))\r\nmodel_fit = model.fit(disp=0)\r\nprint(model_fit.summary())\r\n \r\n## fit model ARIMA(4,0,0), differencing done by me\r\n## beforehand. So this is essentially an ARMA(4, 0) \r\n## model on the already differenced data\r\ndf_ip_diff = pd.DataFrame(df_ip_diff)\r\nmodel2 = ARIMA(df_ip_diff, order=(3, 0, 0))\r\nmodel_fit2 = model2.fit(disp=0)\r\nprint(model_fit2.summary())\r\n\r\n### model2 is equivalent to model\r\n### hence, my differenced series is differenced\r\n### in the same way as the ARIMA function differences\r\n\r\nresiduals = pd.DataFrame(model_fit.resid)\r\nplot_acf(residuals, lags=100)\r\nresiduals.plot()\r\npyplot.show()\r\nresiduals.plot(kind='kde')\r\npyplot.show()\r\nprint(residuals.describe())\r\n\r\n## fit model ARIMA(1,0,0) on differenced log\r\nlogdf_ip_diff = pd.DataFrame(logdf_ip_diff)\r\nmodel3 = ARIMA(logdf_ip_diff, order=(1, 0, 0))\r\nmodel_fit3 = model3.fit(disp=0)\r\nprint(model_fit3.summary())\r\n\r\nresiduals = pd.DataFrame(model_fit3.resid)\r\nplot_acf(residuals, lags=100)\r\nresiduals.plot()\r\npyplot.show()\r\nresiduals.plot(kind='kde')\r\npyplot.show()\r\nprint(residuals.describe())\r\n\r\n### notice that the acf plot of the residuals shows\r\n### no serial correlation, which implies that \r\n### there is no need to include an MA (q) coefficient \r\n### in the ARIMA model\r\n### also notice that the distribution of the\r\n### residuals has mean zero, which is good \r\n\r\n# Forecasting\r\n## forecasting of last 34% differences\r\nX = df_ip_diff.values\r\nsize = int(len(X) *0.66)\r\ntrain, test = X[0:size], X[size:len(X)]\r\nhistory = [x for x in train]\r\npredictions = list()\r\nfor t in range(len(test)):\r\n model = ARIMA(history, order=(4, 0, 0))\r\n model_fit = model.fit(disp=0)\r\n output = model_fit.forecast()\r\n yhat = output[0]\r\n predictions.append(yhat)\r\n obs = test[t]\r\n history.append(obs)\r\n # maybe put a # in front of the line below\r\n #print('predicted=%f, expected=%f' % (yhat, obs))\r\nerror = mean_squared_error(test, predictions)\r\nprint('Test MSE: %.3f' % error)\r\n\r\npyplot.plot(test)\r\npyplot.plot(predictions, color='red')\r\npyplot.show()\r\n\r\n## forecasting of last 34% actual index\r\nX = df_ip.values\r\nsize = int(len(X) *0.66)\r\ntrain, test = X[0:size], X[size:len(X)]\r\nhistory = [x for x in train]\r\npredictions = list()\r\nfor t in range(len(test)):\r\n model = ARIMA(history, order=(4, 1, 0))\r\n model_fit = model.fit(disp=0)\r\n output = model_fit.forecast()\r\n yhat = output[0]\r\n predictions.append(yhat)\r\n obs = test[t]\r\n history.append(obs)\r\n # maybe put a # in front of the line below\r\n #print('predicted=%f, expected=%f' % (yhat, obs))\r\nerror = mean_squared_error(test, predictions)\r\nprint('Test MSE: %.3f' % error)\r\n\r\npyplot.plot(test)\r\npyplot.plot(predictions, color='red')\r\npyplot.show()\r\n\r\n## forecasting of last 34% logged differences\r\nX = logdf_ip_diff.values\r\nsize = int(len(X) *0.66)\r\ntrain, test = X[0:size], X[size:len(X)]\r\nhistory = [x for x in train]\r\npredictions = list()\r\nfor t in range(len(test)):\r\n model = ARIMA(history, order=(1, 0, 0))\r\n model_fit = model.fit(disp=0)\r\n output = model_fit.forecast()\r\n yhat = output[0]\r\n predictions.append(yhat)\r\n obs = test[t]\r\n history.append(obs)\r\n # maybe put a # in front of the line below\r\n #print('predicted=%f, expected=%f' % (yhat, obs))\r\nerror = mean_squared_error(test, predictions)\r\nprint('Test MSE: %.3f' % error)\r\n\r\npyplot.plot(test)\r\npyplot.plot(predictions, color='red')\r\npyplot.show()\r\n\r\n## forecasting of last 34% logged index\r\nX = logdf_ip.values\r\nsize = int(len(X) *0.66)\r\ntrain, test = X[0:size], X[size:len(X)]\r\nhistory = [x for x in train]\r\npredictions = list()\r\nfor t in range(len(test)):\r\n model = ARIMA(history, order=(1, 1, 0))\r\n model_fit = model.fit(disp=0)\r\n output = model_fit.forecast()\r\n yhat = output[0]\r\n predictions.append(yhat)\r\n obs = test[t]\r\n history.append(obs)\r\n # maybe put a # in front of the line below\r\n #print('predicted=%f, expected=%f' % (yhat, obs))\r\nerror = mean_squared_error(test, predictions)\r\nprint('Test MSE: %.3f' % error)\r\n\r\npyplot.plot(test)\r\npyplot.plot(predictions, color='red')\r\npyplot.show()\r\n\r\n# T10YFFM\r\ndf_t10 = pd.DataFrame(data, columns= ['T10YFFM'])\r\npyplot.plot(df_date, df_t10)\r\n\r\n## T10YFFM acf and pacf\r\nplot_acf(df_t10, lags=40)\r\nplot_pacf(df_t10, lags=30)\r\n\r\n## adfuller T10YFFM\r\ndf_t102 = df_t10.iloc[:,0].values\r\nresult4 = adfuller(df_t102)\r\nprint('ADF Statistic: %f' % result4[0])\r\nprint('p-value: %f' % result4[1])\r\nprint('Critical Values:')\r\nfor key, value in result4[4].items():\r\n print('\\t%s: %.3f' % (key, value))\r\n \r\n# ARIMA T10YFFM\r\nmodel4 = ARIMA(df_t10, order=(1, 0, 1))\r\nmodel_fit4 = model4.fit(disp=0)\r\nprint(model_fit4.summary())\r\n\r\nresiduals = pd.DataFrame(model_fit4.resid)\r\nplot_acf(residuals, lags=100)\r\nresiduals.plot()\r\npyplot.show()\r\nresiduals.plot(kind='kde')\r\npyplot.show()\r\nprint(residuals.describe())\r\n\r\n## forecasting of last 34% T10YFFM\r\nX = df_t10.values\r\nsize = int(len(X) *0.66)\r\ntrain, test = X[0:size], X[size:len(X)]\r\nhistory = [x for x in train]\r\npredictions = list()\r\nfor t in range(len(test)):\r\n model = ARIMA(history, order=(1, 0, 1))\r\n model_fit = model.fit(disp=0)\r\n output = model_fit.forecast()\r\n yhat = output[0]\r\n predictions.append(yhat)\r\n obs = test[t]\r\n history.append(obs)\r\n # maybe put a # in front of the line below\r\n #print('predicted=%f, expected=%f' % (yhat, obs))\r\nerror = mean_squared_error(test, predictions)\r\nprint('Test MSE: %.3f' % error)\r\n\r\npyplot.plot(test)\r\npyplot.plot(predictions, color='red')\r\npyplot.show()\r\n","sub_path":"Research Paper.py","file_name":"Research Paper.py","file_ext":"py","file_size_in_byte":8292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"200006675","text":"from __future__ import unicode_literals\nimport frappe\nfrom frappe import msgprint, _\n\ndef execute(filters=None):\n\tcolumns = get_column()\n\tdata = get_silo(filters)\n\treturn columns,data\n\ndef get_column():\n\treturn [_(\"Invoice\") + \":Link/Sales Invoice:120\",_(\"Item Code\") + \":Link/Item:150\",_(\"Item Name\") + \":Data:180\",_(\"Price List Rate\") + \":Currency:100\",_(\"Rate\") + \":Currency:100\",_(\"Qty\") + \":Float:80\",_(\"Amount\") + \":Currency:150\"]\n\ndef get_silo(filters):\n\tif filters.get(\"customer\"):\n\t\tcustomer = filters.get(\"customer\")\n\t\tsales_history = frappe.db.sql(\"\"\" select \n\tsinv.name, sitem.item_code, sitem.item_name, \n\tsitem.price_list_rate,sitem.rate,sitem.qty,sitem.amount \n\t\tfrom `tabSales Invoice` sinv, `tabSales Invoice Item` sitem \n\twhere (sinv.name = sitem.parent) and (sinv.docstatus != 2) and sinv.customer = '%s'; \"\"\"%(customer), as_list=1)\n\n\t\treturn sales_history\n","sub_path":"reports/reports/report/customer_wise_sales_history/customer_wise_sales_history.py","file_name":"customer_wise_sales_history.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"254510923","text":"def separa_trios(s):\n z=[]\n y=[]\n l=[]\n for i in range(len(s)):\n z.append(s[0:3])\n y.append(s[3:6])\n l.append(s[6:len(s)])\n return[z,y,l]\n\ns = ['enrico','murilo','lucca','thiago','gustavo','silvana','victor']\nprint(separa_trios(s))\n \n","sub_path":"backup/user_029/ch68_2019_04_04_18_51_53_634518.py","file_name":"ch68_2019_04_04_18_51_53_634518.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"636878680","text":"from turtle import *\nshape(\"turtle\")\nspeed(-1)\nfor n in range(11, 2, -1):\n if n % 2 != 0:\n color(\"yellow\", \"green\")\n begin_fill()\n for _ in range(n):\n forward(80)\n left(180 - 180 * (n - 2) / n)\n end_fill()\n else:\n color(\"purple\", \"red\")\n begin_fill()\n for _ in range(n):\n forward(80)\n left(180 - 180 * (n - 2) / n)\n end_fill()\n","sub_path":"Homework/september9th_2.py","file_name":"september9th_2.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"235089392","text":"# funtion countEspecialWords\ndef countEspecialWords(myString):\n # return a list it has 4 sorted sections; where each section is:\n # [ words count, alphanumeric count, numbers count, puntuaction count ]\n pmList = [',',';','.',':','?','!']\n lString = myString.split(\" \")\n numbersCount = 0\n alnumCount = 0\n alphaCount = 0\n pmCount = 0\n while '' in lString:\n lString.remove('')\n tsp = len(lString)\n \n print(lString)\n \n for vl in lString:\n # numbers count\n if vl.isdigit():\n numbersCount += 1\n \n \n # alpha count\n if vl.isalpha():\n alphaCount += 1\n \n \n # count puntuation marks\n for vl1 in pmList:\n for vl2 in lString:\n if vl1 == vl2:\n pmCount += 1\n \n alnumCount = tsp - (alphaCount + alnumCount + numbersCount + pmCount)\n return [alphaCount,alnumCount,numbersCount,pmCount]\n\n\nimport os\n\n# Abre archivo en modo lectura\narchivo = open('./Hw3-Resources/paragraph_11.txt','r')\n\n# Lee todas la líneas y asigna a lista\nlista = archivo.readlines() \n\n# Inicializa un contador\nnumlin = 0 \n\n# Recorre todas los elementos de la lista\nfor linea in lista:\n if linea != \"\\n\":\n # incrementa en 1 el contador \n numlin += 1\n linea = linea.rstrip(\"\\n\")\n # muestra contador y elemento (línea)\n print(\"[\" + linea + \"]\")\n counterList = countEspecialWords(linea)\n print(counterList)\n print(\"\\n\")\n \narchivo.close # cierra archivo\n\n","sub_path":"pyParagraph/prueba.py","file_name":"prueba.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"568257108","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jan 17 09:03:27 2019\r\n\r\n@author: Mack\r\n\"\"\"\r\n\r\n# This game is based on pygame 1.9.1\r\nimport pygame\r\nfrom pygame.locals import *\r\nimport random\r\n\r\n# Settings\r\nWIDTH = 1000\r\nHEIGHT = 600\r\nFPS = 30\r\n\r\nBLACK = (0,0,0)\r\nWHITE = (255,255,255)\r\nGREEN = (0,255,0)\r\nPURPLE = (184, 175, 202)\r\nDPURPLE = (124, 80, 157)\r\nAPURPLE = (208, 171, 191)\r\n\r\nOBSTACLE = DPURPLE\r\nBACKGROUND = PURPLE\r\nGROUND = APURPLE\r\n\r\nACC = 1\r\nFRI = 0.2\r\nGRV = 0.7\r\n\r\nINIT_OBSTACLE_NUM = 13\r\n\r\nAXIE_L = pygame.transform.scale(pygame.image.load(\"axie_example_l.png\"), (73, 53))\r\nAXIE_R = pygame.transform.scale(pygame.image.load(\"axie_example_r.png\"), (73, 53))\r\nAXIE_K = pygame.transform.scale(pygame.image.load(\"axie_example_k.png\"), (73, 53))\r\n\r\n# Supplimental Classes\r\nclass Vec2():\r\n def __init__(self, x, y):\r\n self.x = x\r\n self.y = y\r\n self.plain = (x,y)\r\n def __add__(self, another_Vec2):\r\n return Vec2(self.x + another_Vec2.x, self.y + another_Vec2.y)\r\n def __sub__(self, another_Vec2):\r\n return Vec2(self.x - another_Vec2.x, self.y - another_Vec2.y)\r\n def __mul__(self, scalar):\r\n return Vec2(self.x * scalar, self.y * scalar)\r\n def __str__(self):\r\n return \"(\" + str(self.x) + \",\" + str(self.y) +\")\"\r\n \r\n# Game Objects\r\nclass Axie(pygame.sprite.Sprite):\r\n def __init__(self):\r\n super(Axie,self).__init__()\r\n self.image = AXIE_L\r\n self.rect = self.image.get_rect()\r\n self.pos = Vec2(WIDTH / 2, HEIGHT - 60)\r\n self.rect.midbottom = self.pos.plain\r\n self.vel = Vec2(0,0)\r\n self.killed = False\r\n self.out = False\r\n \r\n def update(self):\r\n self.acc = Vec2(0, GRV)\r\n if not self.killed and not self.out:\r\n keys_down = pygame.key.get_pressed()\r\n if keys_down[K_UP] or keys_down[K_w]:\r\n self.acc.y -= ACC\r\n if keys_down[K_DOWN] or keys_down[K_s]:\r\n self.acc.y += ACC\r\n if keys_down[K_LEFT] or keys_down[K_a]:\r\n self.acc.x -= ACC\r\n if keys_down[K_RIGHT] or keys_down[K_d]:\r\n self.acc.x += ACC\r\n \r\n self.acc.x -= self.vel.x * FRI\r\n self.vel += self.acc\r\n self.pos += self.vel + self.acc * 0.5\r\n \r\n #Return Axie to the screen if moved out\r\n if self.pos.x < 0:\r\n self.pos.x = WIDTH\r\n elif self.pos.x > WIDTH:\r\n self.pos.x = 0\r\n# if self.pos.y <= 0:\r\n# self.pos.y = HEIGHT\r\n# elif self.pos.y >= HEIGHT:\r\n# self.pos.y = 0\r\n \r\n self.rect.midbottom = self.pos.plain\r\n \r\n # Animation\r\n if self.killed:\r\n self.image = AXIE_K\r\n elif self.vel.x > 0:\r\n self.image = AXIE_R\r\n elif self.vel.x < 0:\r\n self.image = AXIE_L\r\n \r\n \r\nclass Platform(pygame.sprite.Sprite):\r\n def __init__(self,x,y,wid,hit,color):\r\n super(Platform,self).__init__()\r\n self.image = pygame.Surface((wid,hit))\r\n self.image.fill(color)\r\n self.rect = self.image.get_rect()\r\n self.rect.x = x\r\n self.rect.y = y\r\n\r\nclass Game():\r\n \r\n def __init__(self):\r\n self.running = True\r\n self.clock = pygame.time.Clock()\r\n self.screen = pygame.display.set_mode((WIDTH,HEIGHT))\r\n self.screen.fill(BACKGROUND)\r\n pygame.init()\r\n pygame.mixer.init()\r\n \r\n pygame.display.set_caption(\"Axie\")\r\n \r\n # Supplimental Functions\r\n def draw_text(self, text, size, color, x, y):\r\n font_name = pygame.font.match_font('arial')\r\n font = pygame.font.Font(font_name, size)\r\n text_surface = font.render(text, True, color)\r\n text_rect = text_surface.get_rect()\r\n text_rect.midtop = (x, y)\r\n self.screen.blit(text_surface, text_rect)\r\n \r\n def wait(self):\r\n waiting = True\r\n while waiting:\r\n self.clock.tick(FPS)\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n waiting = False\r\n pygame.quit()\r\n if event.type == KEYUP:\r\n if event.key == K_SPACE:\r\n waiting = False\r\n \r\n # Start and Finish\r\n def start(self):\r\n self.draw_text(\"Axie Flies Up\", 50, WHITE, WIDTH / 2, HEIGHT / 4)\r\n self.draw_text(\"(Don't Touch Me)\", 22, DPURPLE, WIDTH / 2, HEIGHT / 2)\r\n self.draw_text(\"Press Space to Continue\", 22, WHITE, WIDTH / 2, HEIGHT * 3 /5 )\r\n pygame.display.flip()\r\n self.wait()\r\n \r\n def finish(self):\r\n self.draw_text(\"Game Over\", 50, WHITE, WIDTH / 2, HEIGHT / 4)\r\n self.draw_text(\"Score: \" + str(self.level), 22, DPURPLE, WIDTH / 2, HEIGHT / 2)\r\n self.draw_text(\"Press Space to Continue\", 22, WHITE, WIDTH / 2, HEIGHT * 3 /5 )\r\n pygame.display.flip()\r\n self.wait()\r\n \r\n # Main Game Logic\r\n def new_game(self):\r\n # Runtime Initialization\r\n \r\n all_sprites = pygame.sprite.Group()\r\n all_obstacles = pygame.sprite.Group()\r\n all_grounds = pygame.sprite.Group()\r\n \r\n axie = Axie()\r\n all_sprites.add(axie)\r\n \r\n ground = Platform(0, HEIGHT - 20, WIDTH, 500, GROUND)\r\n all_sprites.add(ground)\r\n all_grounds.add(ground)\r\n \r\n while len(all_obstacles) < INIT_OBSTACLE_NUM:\r\n width = random.randrange(50, 100)\r\n x = random.randrange(0, WIDTH -width)\r\n y = random.randrange(-200, HEIGHT - 200)\r\n obstacle = Platform(x, y, width, 20, OBSTACLE)\r\n if not pygame.sprite.spritecollide(obstacle, all_obstacles, False):\r\n all_obstacles.add(obstacle)\r\n all_sprites.add(obstacle)\r\n\r\n self.level = 0\r\n \r\n # Main loop\r\n while self.running:\r\n # Timing\r\n self.clock.tick(FPS)\r\n \r\n # Quit Scenario Examination\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n elif event.type == KEYDOWN:\r\n if event.key == K_ESCAPE:\r\n pygame.quit()\r\n \r\n # Objects Update\r\n self.screen.fill(PURPLE)\r\n all_sprites.update()\r\n self.draw_text(str(self.level), 22, WHITE, 20, 5)\r\n \r\n # Ground Control\r\n touchground = pygame.sprite.spritecollide(axie, all_grounds, False)\r\n if touchground and not axie.killed:\r\n axie.acc.y = 0\r\n axie.vel.y = 0\r\n axie.pos.y = touchground[0].rect.top\r\n \r\n # Game Over Control\r\n collision = pygame.sprite.spritecollide(axie, all_obstacles, False)\r\n if collision:\r\n axie.killed = True\r\n \r\n if axie.rect.bottom > HEIGHT:\r\n axie.out = True\r\n for sprite in all_sprites:\r\n sprite.rect.y -= max(axie.vel.y, 10)\r\n if sprite.rect.bottom < 0:\r\n sprite.kill()\r\n if len(all_obstacles) == 0:\r\n break\r\n \r\n # Camera Control\r\n if axie.rect.top <= HEIGHT / 3:\r\n axie.pos.y += abs(axie.vel.y)\r\n ground.rect.y += abs(axie.vel.y)\r\n if ground.rect.top >= HEIGHT:\r\n ground.kill()\r\n for obstacle in all_obstacles:\r\n obstacle.rect.y += abs(axie.vel.y)\r\n if obstacle.rect.top >= HEIGHT:\r\n self.level += 1\r\n obstacle.kill()\r\n while len(all_obstacles) < INIT_OBSTACLE_NUM:\r\n width = random.randrange(50 + self.level, 100 + self.level)\r\n x = random.randrange(0, WIDTH -width)\r\n y = random.randrange(-600, -20)\r\n obstacle = Platform(x, y, width, 20, OBSTACLE)\r\n if not pygame.sprite.spritecollide(obstacle, all_obstacles, False):\r\n all_obstacles.add(obstacle)\r\n all_sprites.add(obstacle)\r\n \r\n # Frame Update\r\n all_sprites.draw(self.screen)\r\n pygame.display.flip()\r\n\r\nif __name__ == \"__main__\":\r\n game = Game()\r\n game.start()\r\n while game.running:\r\n game.new_game()\r\n game.finish()\r\n pygame.quit()","sub_path":"AxieFliesUp.py","file_name":"AxieFliesUp.py","file_ext":"py","file_size_in_byte":8620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"391149390","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn.ensemble import VotingClassifier, BaggingClassifier, AdaBoostClassifier\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.svm import LinearSVC\nfrom tqdm import tqdm\n\ntqdm.pandas(desc=\"progress-bar\")\n\nfrom utils import Tools\n\n\nclass TextClassifiers():\n def __init__(self):\n self.tools = Tools()\n\n self.unique_labels = [\"0\", \"1\", \"2\"]\n\n def train(self, train_blogs, train_classes, ngram_size=1):\n self.train_blogs = train_blogs\n self.train_classes = train_classes\n\n self.Tfidf_vect = TfidfVectorizer(ngram_range=(1, ngram_size), stop_words='english',\n analyzer=\"word\", min_df=0.0, max_df=1.0, max_features=None, norm=\"l2\", strip_accents=\"unicode\")\n self.Tfidf_vect.fit(self.train_blogs)\n self.train_blogs_Tfidf = self.Tfidf_vect.transform(self.train_blogs)\n\n def multinomialNaiveBayes(self, test_blogs, test_classes):\n self.test_blogs = test_blogs\n self.test_classes = test_classes\n\n self.test_blogs_Tfidf = self.Tfidf_vect.transform(self.test_blogs)\n\n clf = MultinomialNB(alpha=0.2, fit_prior=True)\n clf.fit(self.train_blogs_Tfidf, self.train_classes)\n\n predictions = clf.predict(self.test_blogs_Tfidf)\n\n self.showStats(predictions, \"Multinomial Naive Bayes\")\n\n return predictions\n\n def gridSearchNaiveBayes(self, test_blogs, test_classes):\n self.test_blogs = test_blogs\n self.test_classes = test_classes\n\n self.test_blogs_Tfidf = self.Tfidf_vect.transform(self.test_blogs)\n\n clf = Pipeline([('nb', MultinomialNB(fit_prior=True))])\n\n parameters = {'nb__alpha': np.arange(0.05, 1, 0.05)}\n\n gs = GridSearchCV(clf, parameters, cv=5, n_jobs=-1)\n\n gs.fit(self.train_blogs_Tfidf, self.train_classes)\n print(gs.best_params_)\n\n bestNB = gs.best_estimator_\n bestNB.fit(self.train_blogs_Tfidf, self.train_classes)\n\n predictions = bestNB.predict(self.test_blogs_Tfidf)\n\n self.showStats(predictions, \"Naive Bayes GridSearch\")\n\n def logisticRegression(self, test_blogs, test_classes, c=7):\n self.test_blogs = test_blogs\n self.test_classes = test_classes\n\n self.test_blogs_Tfidf = self.Tfidf_vect.transform(self.test_blogs)\n\n clf = LogisticRegression(solver='sag', n_jobs=-1)\n clf.fit(self.train_blogs_Tfidf, self.train_classes)\n\n predictions = clf.predict(self.test_blogs_Tfidf)\n\n self.showStats(predictions, \"Logistic regression\")\n\n return predictions\n\n def linearSVC(self, test_blogs, test_classes, c=1):\n self.test_blogs = test_blogs\n self.test_classes = test_classes\n\n self.test_blogs_Tfidf = self.Tfidf_vect.transform(self.test_blogs)\n\n clf = LinearSVC(C=c)\n clf.fit(self.train_blogs_Tfidf, self.train_classes)\n\n predictions = clf.predict(self.test_blogs_Tfidf)\n\n self.showStats(predictions, \"Linear SVC\")\n\n return predictions\n\n def baggingClassifier(self, test_blogs, test_classes):\n self.test_blogs = test_blogs\n self.test_classes = test_classes\n\n self.test_blogs_Tfidf = self.Tfidf_vect.transform(self.test_blogs)\n\n clf = BaggingClassifier(random_state=42)\n\n clf.fit(self.train_blogs_Tfidf, self.train_classes)\n\n predictions = clf.predict(self.test_blogs_Tfidf)\n\n self.showStats(predictions, \"Bagging classifier\")\n\n return predictions\n\n def adaBoostClassifier(self, test_blogs, test_classes):\n self.test_blogs = test_blogs\n self.test_classes = test_classes\n\n self.test_blogs_Tfidf = self.Tfidf_vect.transform(self.test_blogs)\n\n clf = AdaBoostClassifier(random_state=42)\n\n clf.fit(self.train_blogs_Tfidf, self.train_classes)\n\n predictions = clf.predict(self.test_blogs_Tfidf)\n\n self.showStats(predictions, \"Adaboost classifier\")\n\n return predictions\n\n def buildVotingClassifier(self):\n clf1 = LogisticRegression(solver='sag', multi_class='auto', n_jobs=-1)\n clf2 = MultinomialNB(alpha=0.2, fit_prior=True)\n clf3 = LinearSVC(C=1)\n\n return VotingClassifier(estimators=[('lr', clf1), ('nb', clf2), ('svm', clf3)], voting='hard')\n\n def votingClassifier(self, test_blogs, test_classes):\n self.test_blogs = test_blogs\n self.test_classes = test_classes\n\n self.test_blogs_Tfidf = self.Tfidf_vect.transform(self.test_blogs)\n\n eclf = self.buildVotingClassifier()\n\n eclf = eclf.fit(self.train_blogs_Tfidf, self.train_classes)\n\n predictions_vote = eclf.predict(self.test_blogs_Tfidf)\n\n self.showStats(predictions_vote, \"Voting classifier\")\n\n return predictions_vote\n\n def accuracyOnEveryTestSplit(self):\n clf = self.buildVotingClassifier()\n clf = clf.fit(self.train_blogs_Tfidf, self.train_classes)\n\n test_corpus1 = pd.read_csv('test_split01.csv', names=['blog', 'label'])\n test_corpus2 = pd.read_csv('test_split02.csv', names=['blog', 'label'])\n test_corpus3 = pd.read_csv('test_split03.csv', names=['blog', 'label'])\n test_corpus4 = pd.read_csv('test_split04.csv', names=['blog', 'label'])\n test_corpus5 = pd.read_csv('test_split05.csv', names=['blog', 'label'])\n test_corpus6 = pd.read_csv('test_split06.csv', names=['blog', 'label'])\n test_corpus7 = pd.read_csv('test_split07.csv', names=['blog', 'label'])\n test_corpus8 = pd.read_csv('test_split08.csv', names=['blog', 'label'])\n test_corpus9 = pd.read_csv('test_split09.csv', names=['blog', 'label'])\n test_corpus10 = pd.read_csv('test_split10.csv', names=['blog', 'label'])\n test_corpus11 = pd.read_csv('test_split11.csv', names=['blog', 'label'])\n\n list_of_corpus = [test_corpus1,\n test_corpus2,\n test_corpus3,\n test_corpus4,\n test_corpus5,\n test_corpus6,\n test_corpus7,\n test_corpus8,\n test_corpus9,\n test_corpus10,\n test_corpus11]\n i = 1\n for test_corpus in list_of_corpus:\n print(\"------------------------------------------------------------------------------------\")\n test_blogs = test_corpus.blog\n self.test_classes = test_corpus.label\n\n test_blogs_Tfidf = self.Tfidf_vect.transform(test_blogs)\n predictions = clf.predict(test_blogs_Tfidf)\n\n self.showStats(predictions, \"Voting classifier\")\n i += 1\n\n print(\"------------------------------------------------------------------------------------\")\n print()\n\n def drawNaiveBayesAndLogRegWith5gram(self, train_blogs, train_labels, test_blogs, test_classes):\n lr_preds = []\n nb_preds = []\n liste_ngram = list(range(1, 6))\n\n for size in liste_ngram:\n self.train(train_blogs, train_labels, ngram_size=size)\n\n accuracy_nb = accuracy_score(y_true=test_classes, y_pred=self.multinomialNaiveBayes(test_blogs, test_classes))\n nb_preds.append(accuracy_nb)\n\n accuracy_lr = accuracy_score(y_true=test_classes, y_pred=self.logisticRegression(test_blogs, test_classes))\n lr_preds.append(accuracy_lr)\n\n import matplotlib.pyplot as plt\n plt.plot(liste_ngram, lr_preds, linewidth=2, markersize=12)\n plt.plot(liste_ngram, nb_preds, linewidth=2, markersize=12)\n plt.grid(True) # add a grid\n plt.legend(('Régression logistique', 'Naïve Bayes multinomial'))\n\n plt.ylabel(\"Précision en %\")\n plt.xlabel(\"Taille du modèle n-gramme.\")\n plt.xticks(liste_ngram)\n plt.title(\"Évolution de la précision de deux classifieurs différents\"\n \"\\n en fonction de la taille des modèles n-gramme\"\n \"\\n sur lesquels ils sont entrainés.\")\n plt.show()\n\n def drawClassesDistribution(self, corpus, filename):\n blue = \"#1F77B4\"\n orange = \"#FF7F0E\"\n green = \"#2CA02C\"\n\n counts = corpus.label.value_counts()\n number_with_label_0 = counts[0]\n number_with_label_1 = counts[1]\n number_with_label_2 = counts[2]\n\n number_of_posts = [number_with_label_0, number_with_label_1, number_with_label_2]\n tags = ['10 - 19 ans', '20 - 29 ans', '30 ans et +']\n\n y_pos = np.arange(len(tags))\n plt.bar(y_pos, number_of_posts, color=[blue, orange, green])\n plt.xticks(y_pos, tags)\n plt.ylabel('\\nNombre de blogs\\n')\n plt.xlabel('\\nClasses\\n')\n plt.title(\"Répartition du nombre de blogs en fonction de\\nchaque classe dans l'ensemble d'entrainement.\\n\")\n plt.savefig(filename)\n plt.show()\n\n def drawConfusionMatrix(self, predictions, filename):\n filename += \" accuracy\"\n\n unique_classes = np.unique(self.train_classes)\n number_of_unique_classes = len(unique_classes)\n\n conf_mat = confusion_matrix(self.test_classes, predictions)\n plt.subplots(figsize=(number_of_unique_classes, number_of_unique_classes))\n sns.heatmap(conf_mat, annot=True, fmt='d', cmap=\"Blues\",\n xticklabels=np.unique(self.train_classes), yticklabels=np.unique(self.train_classes))\n plt.ylabel('Actual')\n plt.xlabel('Predicted')\n filename += \"_confusion_matrix\"\n plt.savefig(filename)\n plt.show()\n\n def showStats(self, predictions, method_used):\n print(\"Accuracy for \", method_used, \": \", accuracy_score(y_true=self.test_classes, y_pred=predictions) * 100)\n\n print(classification_report(y_true=self.test_classes, y_pred=predictions, target_names=self.unique_labels))\n\n\nif __name__ == '__main__':\n text_classifier = TextClassifiers()\n\n train_corpus = pd.read_csv('train_posts.csv', names=['blog', 'label'])\n test_corpus = pd.read_csv('test_split01.csv', names=['blog', 'label'])\n\n train_blogs = train_corpus.blog\n train_labels = train_corpus.label\n\n test_blogs = test_corpus.blog\n test_labels = test_corpus.label\n\n print(\"Training classifier ...\")\n clf = text_classifier.train(train_blogs, train_labels, ngram_size=2)\n print()\n\n print(\"Testing on 11 test splits ...\")\n #text_classifier.accuracyOnEveryTestSplit()\n print()\n\n print(\"Starting to draw ...\")\n text_classifier.drawNaiveBayesAndLogRegWith5gram(train_blogs, train_labels, test_blogs, test_labels)\n\n # print(\"Naive bayes ...\")\n # text_classifier.multinomialNaiveBayes(test_blogs, test_labels)\n # print()\n #\n # print(\"Logistic regression ...\")\n # text_classifier.logisticRegression(test_blogs, test_labels)\n # print()\n #\n # print(\"Linear SVC ...\")\n # text_classifier.linearSVC(test_blogs, test_labels)\n # print()\n\n # print(\"Voting classifier ...\")\n # text_classifier.votingClassifier(test_blogs, test_labels)\n # print()\n\n # text_classifier.drawClassificationModelsComparison(\"model_comparison\")\n","sub_path":"classifiers.py","file_name":"classifiers.py","file_ext":"py","file_size_in_byte":11501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"555925661","text":"\"\"\"Module used to breakdown a string into its phonemes and to check if two words rhyme.\"\"\"\nfrom pdb import set_trace as breakpoint\nimport nltk\n\nBREAKER = nltk.corpus.cmudict.dict()\n\n\ndef wordbreak(single_word_string, mode=\"silent\"):\n \"\"\"Returns phoneme breakdown of a string consisting of a single word.\"\"\"\n single_word_string = single_word_string.lower()\n if single_word_string in BREAKER:\n return BREAKER[single_word_string][0]\n if mode != \"silent\":\n print(\"Word not in dictionary\")\n return None\n\n\ndef stringbreak(mutliple_word_string):\n \"\"\"Returns phoneme breakdown of a string consisting of multiple words.\"\"\"\n split_string = str.split(mutliple_word_string)\n list_of_phoneme_lists = []\n for word in split_string:\n list_of_phoneme_lists.append(wordbreak(word))\n return list_of_phoneme_lists\n\n\ndef transform_phonemes(phoneme_list):\n \"\"\"Strips numbers from phoneme lists, making it easier to check if two words rhyme\"\"\"\n intermediate_phoneme_list = []\n transformed_phoneme_list = []\n for element in phoneme_list:\n intermediate_phoneme_list.append(list(element))\n for element in intermediate_phoneme_list:\n for sub_element in element:\n if sub_element in \"1234567890\":\n element.remove(sub_element)\n transformed_phoneme_list.append(\"\".join(element))\n return transformed_phoneme_list\n\n\ndef rhyme_check(word1, word2, number_of_identical_phonemes):\n \"\"\"Checks if two words rhyme. Returns True if they do and False if they don't.\"\"\"\n phonemes_one = transform_phonemes(wordbreak(word1))\n phonemes_two = transform_phonemes(wordbreak(word2))\n answer = []\n counter = 1\n while counter <= number_of_identical_phonemes:\n if phonemes_one[(-counter)] == phonemes_two[(-counter)]:\n answer.append(True)\n else:\n answer.append(False)\n counter += 1\n if False in answer:\n return False\n if number_of_identical_phonemes > 0 and answer == [True]*number_of_identical_phonemes:\n return True\n return None\n\n\nif __name__ == \"__main__\":\n breakpoint()\n","sub_path":"backend_stuff/rhyme_checker.py","file_name":"rhyme_checker.py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"322085065","text":"from django.shortcuts import render, redirect, reverse\nfrom django.core import serializers\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.http import require_http_methods\nfrom django.views.decorators.csrf import ensure_csrf_cookie\nfrom django.http.response import JsonResponse\nfrom django.forms.models import model_to_dict\nfrom places.settings import GMAPS_API_KEY\nfrom .models import Place, CheckIn\nfrom datetime import datetime\n\n\n# Create your views here.\n\n@login_required\ndef index(request):\n places = serializers.serialize('json', request.user.place_set.filter(togo=False))\n togos = serializers.serialize('json', request.user.place_set.filter(togo=True))\n context = {\n 'gmaps_api_key': GMAPS_API_KEY,\n 'places': places,\n 'togos': togos\n }\n return render(request, 'web/index.html', context)\n\n\n@login_required\n@require_http_methods(['POST'])\ndef post_create_place(request):\n new_place_data = {}\n new_checkin_data = {}\n error = ''\n\n if request.POST.get('name'):\n new_place_data['name'] = request.POST['name']\n else:\n error += 'Need a name for the place. '\n\n if request.POST.get('address'):\n new_place_data['address'] = request.POST['address']\n else:\n error += 'Need an address for the place. '\n\n if request.POST.get('lat'):\n new_place_data['lat'] = float(request.POST['lat'])\n else:\n error += 'Need a latitude for the place. '\n\n if request.POST.get('lng'):\n new_place_data['lng'] = float(request.POST['lng'])\n else:\n error += 'Need a longitude for the place. '\n\n if request.POST.get('notes'):\n new_place_data['notes'] = request.POST['notes']\n else:\n new_place_data['notes'] = ''\n\n if request.POST.get('place_id'):\n new_place_data['place_id'] = request.POST['place_id']\n\n if request.POST.get('date'):\n new_checkin_data['date'] = datetime.strptime(request.POST['date'], '%Y-%m-%d').date()\n else:\n error += 'Need a date. '\n\n if request.POST.get('checkin_notes'):\n new_checkin_data['notes'] = request.POST['checkin_notes']\n else:\n new_checkin_data['notes'] = ''\n\n if error:\n return JsonResponse({\n 'status': 'FAIL',\n 'message': error\n })\n\n else:\n new_place_data['user'] = request.user\n new_place = Place.objects.create(**new_place_data)\n new_checkin_data['place'] = new_place\n new_checkin = CheckIn.objects.create(**new_checkin_data)\n\n return JsonResponse({\n 'status': 'OK',\n 'message': 'Created place and CheckIn',\n 'place': {'pk': new_place.id, 'fields': model_to_dict(new_place)},\n 'checkin': {'pk': new_checkin.id, 'fields': model_to_dict(new_checkin)}\n })\n\n\n@login_required\n@require_http_methods(['POST'])\ndef post_create_togo(request):\n new_togo_data = {}\n error = ''\n\n if request.POST.get('name'):\n new_togo_data['name'] = request.POST['name']\n else:\n error += 'Need a name for the place. '\n\n if request.POST.get('address'):\n new_togo_data['address'] = request.POST['address']\n else:\n error += 'Need an address for the place. '\n\n if request.POST.get('lat'):\n new_togo_data['lat'] = float(request.POST['lat'])\n else:\n error += 'Need a latitude for the place. '\n\n if request.POST.get('lng'):\n new_togo_data['lng'] = float(request.POST['lng'])\n else:\n error += 'Need a longitude for the place. '\n\n if request.POST.get('notes'):\n new_togo_data['notes'] = request.POST['notes']\n else:\n new_togo_data['notes'] = ''\n\n\n if error:\n return JsonResponse({\n 'status': 'FAIL',\n 'message': error\n })\n\n else:\n new_togo_data['togo'] = True\n new_togo_data['user'] = request.user\n new_togo = Place.objects.create(**new_togo_data)\n\n return JsonResponse({\n 'status': 'OK',\n 'message': 'Created place and CheckIn',\n 'place': {'pk': new_togo.id, 'fields': model_to_dict(new_togo)}\n })\n\n\n@login_required\n@require_http_methods(['POST'])\ndef post_delete_togo(request):\n if request.POST.get('id'):\n to_delete = int(request.POST['id'])\n else:\n return JsonResponse({\n 'status': 'FAIL',\n 'message': 'Must provide an id to delete. '\n })\n\n try:\n Place.objects.get(id=to_delete).delete()\n except Place.DoesNotExist:\n return JsonResponse({\n 'status': 'FAIL',\n 'message': 'ID provided does not exist.'\n })\n\n return JsonResponse({\n 'status': 'OK',\n 'message': 'Deleted ToGo'\n })\n\n\n\n","sub_path":"web/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"200006023","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# __author__ = 'hq.l'\n\n\nimport time\nfrom threadpool import *\nimport threading\n\ni = 0\n\nif __name__ == '__main__':\n main = ThreadPool(3)\n while True:\n # try:\n time.sleep(0.5)\n # main.poll()\n print(\"Main thread working...\")\n print(\"(active worker threads: %i)\" % (threading.activeCount() - 1,))\n if i == 10:\n print(\"**** Adding 3 more worker threads...\")\n main.createWorkers(3)\n if i == 20:\n print(\"**** Dismissing 2 worker threads...\")\n main.dismissWorkers(2)\n i += 1\n # except KeyboardInterrupt:\n # print(\"**** Interrupted!\")\n # break\n # except NoResultsPending:\n # print(\"**** No pending results.\")\n # break","sub_path":"threadpool_pro/tp2.py","file_name":"tp2.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"366736344","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\n\ndf = pd.read_excel('data.xlsx', 'Sheet1', index_col=None, na_values=['NA'])\n\n'''print(\n\tdf.ix[0:30, 0:2]\n\t)'''\nprint(\n\tdf\n\t)\n\nstd = df.at[8,'Careful']\nmean = df.at[6,'Careful']\nstd_range_from_mean = [mean-std,mean+std]\nfraction_in_range = len([i for i in df['d (mm)'] if i<=std_range_from_mean[1] and i>=std_range_from_mean[0]])/len(df['d (mm)'])\nprint(\n\tf'Percentage of date +- 1 std: {fraction_in_range*100}%'\n\t)\n\nplt.figure(0)\nplt.errorbar(df['Measurment'],df['d (mm)'],yerr=df['delta d (mm)'],fmt='none',ecolor='red')\nplt.scatter(df['Measurment'],df['d (mm)'],s=5)\n\nplt.xlabel('Trial')\nplt.ylabel('Measured Value (mm)')\n\nmms = plt.axhline(y=mean+std, xmin=0, xmax=30, color='blue', ls='dashed', label=\"mean+-std\")\nmps = plt.axhline(y=mean-std, xmin=0, xmax=30, color='blue', ls='dashed')\nvalues = df['d (mm)']\nplt.yticks(np.arange(14.6, 15.6, 0.1))\n\nplt.legend(handles=[mms])\nplt.savefig('scatter.png')\n\nplt.figure(1)\ndists = [i-15.01275862 for i in df['d (mm)']]\nplt.hist(dists, density=True, bins=7)\nplt.xticks(np.arange(-0.4, 0.5, 0.1))\nplt.savefig('histogram.png')\n\n\nplt.show()\n\n\n\n","sub_path":"Lab 1/plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"634919645","text":"#!/usr/bin/env python\n\n# Copyright 2016 Jim Pivarski\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom histogrammar.defs import *\nfrom histogrammar.primitives.count import *\n\nclass Partition(Factory, Container):\n @staticmethod\n def ed(entries, *cuts):\n if entries < 0.0:\n raise ContainerException(\"entries ({}) cannot be negative\".format(entries))\n\n out = Partition(None, None, *cuts)\n out.entries = float(entries)\n return out\n\n @staticmethod\n def ing(value, expression, *cuts):\n return Partition(value, expression, *cuts)\n\n def __init__(self, value, expression, *cuts):\n self.entries = 0.0\n self.expression = expression\n if value is None:\n self.cuts = cuts\n else:\n self.cuts = tuple((float(x), value.zero()) for x in (float(\"-inf\"),) + cuts)\n\n @property\n def thresholds(self): return [k for k, v in self.cuts]\n @property\n def values(self): return [v for k, v in self.cuts]\n\n def zero(self):\n return Partition(None, self.expression, *[(x, x.zero()) for x in cuts])\n\n def __add__(self, other):\n if isinstance(other, Partition):\n if self.thresholds != other.thresholds:\n raise ContainerException(\"cannot add Partition because cut thresholds differ\")\n\n out = Partition(None, self.expression, *[(k1, v1 + v2) for ((k1, v1), (k2, v2)) in zip(self.cuts, other.cuts)])\n out.entries = self.entries + other.entries\n return out\n\n else:\n raise ContainerException(\"cannot add {} and {}\".format(self.name, other.name))\n\n def fill(self, datum, weight=1.0):\n if self.expression is None:\n raise RuntimeException(\"attempting to fill a container that has no fill rule\")\n\n if weight > 0.0:\n value = self.expression(datum)\n self.entries += weight\n for (low, sub), (high, _) in zip(self.cuts, self.cuts[1:] + (float(\"nan\"), None)):\n if value >= low and not value >= high:\n sub.fill(datum, weight)\n break\n\n def toJsonFragment(self): return {\n \"entries\": floatToJson(self.entries),\n \"type\": self.cuts[0][1].name,\n \"data\": [{\"atleast\": floatToJson(atleast), \"data\": sub.toJsonFragment()} for atleast, sub in self.cuts],\n }\n\n @staticmethod\n def fromJsonFragment(json):\n if isinstance(json, dict) and set(json.keys()) == set([\"entries\", \"type\", \"data\"]):\n if isinstance(json[\"entries\"], (int, long, float)):\n entries = float(json[\"entries\"])\n else:\n raise JsonFormatException(json, \"Partition.entries\")\n\n if isinstance(json[\"type\"], basestring):\n factory = Factory.registered[json[\"type\"]]\n else:\n raise JsonFormatException(json, \"Partition.type\")\n\n if isinstance(json[\"data\"], list):\n cuts = []\n for i, elementPair in enumerate(json[\"data\"]):\n if isinstance(elementPair, dict) and set(elementPair.keys()) == set([\"atleast\", \"data\"]):\n if elementPair[\"atleast\"] not in (\"nan\", \"inf\", \"-inf\") and not isinstance(elementPair[\"atleast\"], (int, long, float)):\n raise JsonFormatException(json, \"Partition.data {} atleast\".format(i))\n\n cuts.append((float(elementPair[\"atleast\"]), factory.fromJsonFragment(elementPair[\"data\"])))\n\n else:\n raise JsonFormatException(json, \"Partition.data {}\".format(i))\n return Partition.ed(entries, *cuts)\n\n else:\n raise JsonFormatException(json, \"Partition.data\")\n\n else:\n raise JsonFormatException(json, \"Partition\")\n\n def __repr__(self):\n return \"Partition[{}, thresholds=[{}]]\".format(self.cuts[0], \", \".join(map(str, self.thresholds)))\n\n def __eq__(self):\n return isinstance(other, Partition) and exact(self.entries, other.entries) and self.expression == other.expression and self.cuts == other.cuts\n\n def __hash__(self):\n return hash((self.entries, self.expression, self.cuts))\n\nFactory.register(Partition)\n","sub_path":"python/histogrammar/primitives/partition.py","file_name":"partition.py","file_ext":"py","file_size_in_byte":4763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"17443744","text":"import numpy as np\n\n\nTARTET_SENTENCE = \"I LOVE YOU !\"\npoeple_SIZE = 300\nCROSS_RATE = 0.5\nMUTATION_RATE = 0.01\nN_GENERATION = 1000\n\nDNA_SIZE = len(TARTET_SENTENCE)\nprint(\"????\", DNA_SIZE)\n# convert string to number 将字符串转换成ASCII数组\nTARGET_ASCII = np.fromstring(TARTET_SENTENCE, dtype=np.uint8)\n# print(TARGET_ASCII)\n# a = np.array([73, 32, 56, 79, 86, 77, 32, 89, 79, 85,\n# 32, 84, 98, 32, 68, 69, 65, 111, 72, 32, 33])\n# print((TARGET_ASCII == a).sum(axis=0))\n# print(TARGET_ASCII.tostring().decode(\"ASCII\")) # 将ASCII转换成字符串\n# print(1e-3)\n\nASCII_BOUND = [32, 126]\n\n\nclass GA(object):\n\n def __init__(self, DNA_size, DNA_bound, cross_rate, mutation_rate, poeple_size):\n self.DNA_size = DNA_size\n DNA_bound[1] += 1\n self.DNA_bound = DNA_bound\n self.cross_rate = cross_rate\n self.mutation_rate = mutation_rate\n self.poeple_size = poeple_size\n\n # int8 for convert to ASCII\n self.poeple = np.random.randint(\n *DNA_bound, size=(poeple_size, DNA_size)).astype(np.int8)\n\n def translate_DNA(self, DNA):\n \"\"\"将ASCII转换成字符串 convert to readable string\n Arguments:\n DNA {[type]} -- [int list]\n Returns:\n [type] -- string\n \"\"\"\n return DNA.tostring().decode(\"ASCII\")\n\n def get_fitness(self):\n \"\"\"计算与目标字符串的相似度, count how many character matches\n Returns:\n int -- 有多少个字符是相似的\n \"\"\"\n # self.poeple = [[23, 45, 78, ...], [67, 54, 121, ...]]每一行是一个个体,\n # 所以要针对每一行来计算相似度,所以axis=1表示安行计算\n match_count = (self.poeple == TARGET_ASCII).sum(axis=1)\n return match_count\n\n def select(self):\n \"\"\"选择出匹配度高的poeple,按照概率选择。\n Returns:\n [type] -- [description]\n \"\"\"\n # add a small amount to avoid all zero fitness\n fitness = self.get_fitness() + 1e-4\n index = np.random.choice(np.arange(\n self.poeple_size), self.poeple_size, replace=True, p=fitness / fitness.sum())\n return self.poeple[index]\n\n def crossover(self, parent, poeple):\n \"\"\"\n # 交叉配对函数\n 交配的并不是前多少用父亲后多少用母亲,二十随机index用,实现方法就如下demo:\n a = np.array([1, 2, 3, 4, 5])\n b = [True, False, False, False, True]\n c = np.array([99, 88])\n a[b] = c\n print(a)\n \"\"\"\n if np.random.rand() < self.mutation_rate:\n index = np.random.randint(0, self.DNA_size, 1)\n # cross_points = np.random.randint(\n # 0, 2, self.DNA_size).astype(np.bool)\n cross_points = np.random.randint(\n 0, 2, self.DNA_size, dtype=np.bool)\n parent[cross_points] = poeple[index, cross_points]\n return parent\n\n def mutate(self, child):\n \"\"\"\n # 变异函数 每一位上都有机会产生变异产生变异\n \"\"\"\n for point in range(self.DNA_size):\n if np.random.rand() < self.mutation_rate:\n child[point] = np.random.randint(*self.DNA_bound)\n # child[point] = np.random.randint(self.DNA_bound[0], self.DNA_bound[1])\n return child\n\n def evolve(self):\n \"\"\"进化函数\n \"\"\"\n poeple = self.select()\n poeple_copy = poeple.copy()\n for parent in poeple:\n child = self.crossover(parent, poeple_copy)\n child = self.mutate(child)\n parent = child\n self.poeple = poeple\n\n\nif __name__ == '__main__':\n ga = GA(DNA_size=DNA_SIZE, DNA_bound=ASCII_BOUND, cross_rate=CROSS_RATE,\n mutation_rate=MUTATION_RATE, poeple_size=poeple_SIZE)\n\n for generation in range(N_GENERATION):\n fitness = ga.get_fitness()\n best_DNA = ga.poeple[np.argmax(fitness)]\n best_phrase = ga.translate_DNA(best_DNA)\n print('Gen', generation, ': ', best_phrase)\n if best_phrase == TARTET_SENTENCE:\n break\n ga.evolve()\n","sub_path":"GeneticAlgorithm/match_sentence.py","file_name":"match_sentence.py","file_ext":"py","file_size_in_byte":4181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"216671845","text":"# -*- coding: utf-8 -*-\nfrom django.forms import ModelForm\nfrom django.forms.widgets import *\nfrom django import forms\nfrom general.models import *\nfrom django.contrib.auth.models import User\n\n\nPRIORIDAD = (\n\t('', '------'),\n\t('Alta', 'Alta'),\n ('Media', 'Media'),\n ('Baja', 'Baja'),\n)\nESTADO = (\n\t('', '------'),\n ('Cerrado', 'Cerrado'),\n)\nTIPO = (\n\t('', '------'),\n\t('Aplicaciones', 'Aplicaciones'),\n)\nclass TicketForm(ModelForm):\n prioridad = forms.ChoiceField(choices=PRIORIDAD, label='Prioridad', required=False)\n estado = forms.ChoiceField(choices=ESTADO, label='Estado', required=False)\n tipo = forms.ChoiceField(choices=TIPO, label='Tipo', required=False)\n class Meta:\n model = Ticket\n fields = '__all__'\n","sub_path":"tickets/general/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"393082656","text":"import re\r\n\r\nprint(\"Calculator\")\r\nprint(\"Type quit to exit\")\r\n\r\nprevious=0\r\nrun=True\r\n\r\ndef Maths():\r\n global run\r\n global previous\r\n equation=\"\"\r\n if previous==0:\r\n equation = input(\"Enter Equation:\\n\")\r\n else:\r\n equation=input(str(previous))\r\n\r\n if equation=='quit':\r\n print(\"Thanks\")\r\n run=False\r\n else:\r\n equation =re.sub('[A-Za-z,.;:()\" \"]','',equation)\r\n\r\n if previous==0:\r\n previous=eval(equation)\r\n else:\r\n previous=eval(str(previous)+equation)\r\n\r\nwhile run:\r\n Maths()\r\n","sub_path":"Advanced_Calculator.py","file_name":"Advanced_Calculator.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"503993532","text":"class Solution(object):\n def addStrings(self, num1, num2):\n \"\"\"\n :type num1: str\n :type num2: str\n :rtype: str\n \"\"\"\n charArray = []\n i = len(num1) - 1\n j = len(num2) - 1\n carryOver = 0\n while i >= 0 or j >= 0:\n curVal = 0\n if i >= 0 and j >= 0:\n curVal += int(num1[i]) + int(num2[j])\n i -= 1\n j -= 1\n elif i >= 0:\n curVal += int(num1[i])\n i -= 1\n else: #j >= 0\n curVal += int(num2[j])\n j -= 1\n curVal += carryOver\n carryOver = curVal / 10\n charArray.append(str(curVal % 10))\n if carryOver == 1:\n charArray.append(str(1))\n charArray.reverse()\n return \"\".join(charArray)\n","sub_path":"addStrings.py","file_name":"addStrings.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"346867670","text":"# Script to run MOFA and MEFISTO for a comparison of interpolation results on evodevo data\n\nimport time\nimport numpy as np\nimport pandas as pd\nimport os\nimport sys\nimport tracemalloc\nfrom datetime import date\nimport copy\nsys.path.append(\"..\")\nfrom utils.interpolation import fit_GP, fit_MOFA, calc_mse\n\n# missing = view/sample combinatinos missing (full sample missingness in a view)\ndef run_grid(nfactors = 5, Tmissing = 5, GP_factors = True, note = \"\", masking_seed = 1234,\n Nviews = 1, seed = 2020, model_groups = True, method = \"FA\", max_iter = 1000,\n species = [\"Mouse\", \"Rabbit\", \"Rat\", \"Human\", \"Opossum\"],\n views = [\"Brain\", \"Cerebellum\", \"Heart\", \"Liver\", \"Testis\"], nm = \"all\", warping = True,\n frac_features = 1, n_genes = 1000):\n\n\n M = len(views)\n G = len(species)\n\n # specify data directory of normalized gene expression data\n datadir = \"data/input_data/all_unmatched/\"\n\n # set and check number of views to mask a time point in\n if Nviews == \"all\":\n Nviews = len(views)\n if Nviews > len(views):\n print(\"Nviews is larger than available number of views, setting to all views.\")\n Nviews = min(Nviews, len(views))\n\n # load data\n data = []\n times = []\n for m in views:\n data_view = []\n for g in species:\n dd_m_g = np.asarray(pd.read_csv(datadir + \"view_\" + m + \"_group_\" + g + \".csv\", header = 0, index_col = 0)).transpose()\n data_view.append(dd_m_g)\n if m == views[0]: # only needed once\n times.append(np.asarray(pd.read_csv(datadir + \"times_group_\" + g + \".csv\", header=0, index_col=0)).transpose())\n data.append(data_view)\n\n if n_genes != \"all\":\n np.random.seed(masking_seed + 2020)\n genes2keep = np.random.choice(range(data[0][0].shape[1]), n_genes, replace=False) # keep a subset of genes in all species and organs\n for m in range(M):\n for g in range(G):\n data[m][g] = data[m][g][:, genes2keep]\n\n # check dimension\n assert len(data) == M, \"problem in loading data, wrong number of groups\"\n assert len(data[0]) == G, \"problem in loading data, wrong number of views\"\n\n # keep unmasked data in data_full and center as done in MOFA (per group)\n data_full = copy.deepcopy(data)\n for g in range(len(species)):\n for m in range(len(views)):\n data_full[m][g]-= np.nanmean(data_full[m][g], axis=0)\n\n # mask values (draw timepoint - species combinations and views at random)\n times_spec = np.vstack(\n [np.repeat(range(len(species)), [len(times[g]) for g in range(len(species))]),\n np.concatenate([np.arange(len(times[g])) for g in range(len(species))])]\n )\n np.random.seed(masking_seed)\n times_spec2mask = np.random.choice(range(times_spec.shape[1]), Tmissing, replace=False)\n if frac_features < 1:\n D = data[0][0].shape[1]\n genes2mask = np.random.choice(range(D), int(frac_features * D), replace=False)\n for ts in times_spec2mask:\n g2mask = times_spec[0, ts]\n t2mask = times_spec[1, ts]\n views2mask = np.random.choice(range(len(views)), Nviews, replace=False)\n for m in views2mask:\n if frac_features < 1:\n data[m][g2mask][t2mask,genes2mask] = np.nan\n else:\n data[m][g2mask][t2mask, :] = np.nan\n\n data_masked = copy.deepcopy(data)\n\n # warping reference as in full training\n warping_ref = \"Mouse\"\n warping_ref = np.where([species[i] == warping_ref for i in range(len(species))])[0][0]\n\n tracemalloc.start()\n t0 = time.time()\n\n if method != \"univGPs\":\n predictions,ent = fit_MOFA(data = data,\n times = times,\n nfactors = nfactors,\n seed = seed,\n GP_factors = GP_factors,\n warping = warping,\n warping_ref = warping_ref,\n model_groups = model_groups,\n iter = max_iter)\n else:\n predictions, model, likelihood = fit_GP(data, times, iter = max_iter)\n t1 = time.time()\n total_time = t1 - t0\n current, peak = tracemalloc.get_traced_memory()\n tracemalloc.stop()\n\n # evaluate interpolation MSE (on missing values that hava a ground truth)\n mse, mse_mean, n_missing = calc_mse(data_masked, data_full, predictions)\n\n # write output to csv\n results = {'mse' : mse, 'mse_mean': mse_mean, 'time': total_time, 'GP_factors' : GP_factors, 'n_missing': n_missing,\n 'Tmissing' : Tmissing, 'masking_seed': masking_seed, 'date' : date.today(),\n 'note' : note, 'mem_usage': peak, 'Nviews' : Nviews, 'method' : method, 'n_genes' : n_genes,\n 'frac_features' : frac_features}\n df = pd.DataFrame.from_dict(data=results,orient='index').T\n\n filenm = 'out/interpol_results_evodevo_%s_%s.csv' % (nm, method)\n if os.path.exists(filenm):\n df.to_csv(filenm, mode='a', header=False)\n else:\n df.to_csv(filenm, header=True)\n\n\nif __name__ == '__main__':\n\n seed = int(sys.argv[1])\n Tmissing = int(sys.argv[2])\n method = sys.argv[3]\n frac_features = float(sys.argv[4])\n\n\n if method != \"univGPs\":\n run_grid(Tmissing = int(Tmissing), GP_factors = True, masking_seed = seed,\n species = [\"Mouse\"], views = [\"Brain\"], nm = \"single_mod\", warping=False, frac_features = frac_features)\n run_grid(Tmissing = int(Tmissing), GP_factors = False, masking_seed = seed,\n species = [\"Mouse\"], views = [\"Brain\"], nm = \"single_mod\", warping=False, frac_features = frac_features)\n else:\n run_grid(Tmissing = int(Tmissing), GP_factors = True, masking_seed = seed, method = \"univGPs\",\n species = [\"Mouse\"], views = [\"Brain\"], nm = \"single_mod\", warping=False, frac_features = frac_features)\n\n\n","sub_path":"evodevo/interpolation_grid_vs_GP.py","file_name":"interpolation_grid_vs_GP.py","file_ext":"py","file_size_in_byte":6009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"206826471","text":"import gym\n\nfrom stable_baselines.common.policies import LnCNNPolicy\nfrom stable_baselines import PPO1\nfrom env.RSEnv import RSEnv\nfrom env.TestRSEnv import TestRSEnv\n\nenv = RSEnv()\n\nmodel = PPO1(LnCNNPolicy, env, verbose=1)\n# model = PPO1.load(\"sbppov3\")\nmodel.set_env(env)\nmodel.learn(total_timesteps=3000000, log_interval=10, reset_num_timesteps=False)\nmodel.save(\"sbppocnn\")\n\nenv = TestRSEnv()\nobs = env.reset()\ndone = False\nwhile not done:\n action, _ = model.predict(obs)\n obs, rewards, done, info = env.step(action)\n env.render()\nenv.close()\n","sub_path":"sbppocnn.py","file_name":"sbppocnn.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"37842140","text":"import os\n# import TensorFlow as tf\nimport tensorflow.compat.v1 as tf\ntf.disable_v2_behavior()\n\n# Turn off TensorFlow warning messages in program output\n# Tells TensorFlow not to output as many log messages as it normally does\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n# Define computational graph\n# Define the X and Y input nodes -> will be placeholder nodes that get assigned\n# a new value every time we make a calculation.\nX = tf.placeholder(tf.float32, name=\"X\") # pass on data type and name as parameters\nY = tf.placeholder(tf.float32, name=\"Y\")\n\n# Define the node that does addition operation\n# Add tf.add node\naddition = tf.add(X, Y, name=\"addition\") # links X and Y nodes to the computational graph\n\n# Create the session\n# To execute operations in the graph, we have to create a session.\nwith tf.Session() as session:\n # pass the operation we want to run\n # When addition operations runs, it needs to grab values of X and Y nodes & also need\n # to feed in values for X and Y -> supply parameter called 'feed dict'\n # feed dict parameter and then pass in X and Y ans five them each a ray value\n\n # Pass in arrays, and result is also an array. Tensors are multi-dimensional arrays\n # result = session.run(addition, feed_dict=({X: [1], Y: [4]}))\n # result = session.run(addition, feed_dict=({X: [1, 2, 3], Y: [4, 5, 6]}))\n result = session.run(addition, feed_dict=({X: [[1, 2, 3], [4, 5, 6]], Y: [[7, 8, 9], [10, 11, 12]]}))\n\n print(result)","sub_path":"Ex_Files_TensorFlow/Exercise Files/02/addition-working.py","file_name":"addition-working.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"605089422","text":"# Copyright 2020 The Cirq Developers\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# https://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 numpy as np\nimport pytest\n\nimport cirq\nimport cirq.ionq as ionq\n\n\ndef test_serialize_empty_circuit_invalid():\n empty = cirq.Circuit()\n serializer = ionq.Serializer()\n with pytest.raises(ValueError, match='empty'):\n _ = serializer.serialize(empty)\n\n\ndef test_serialize_not_line_qubits_invalid():\n q0 = cirq.NamedQubit('a')\n circuit = cirq.Circuit(cirq.X(q0))\n serializer = ionq.Serializer()\n with pytest.raises(ValueError, match='NamedQubit'):\n _ = serializer.serialize(circuit)\n\n\ndef test_serialize_implicit_num_qubits():\n q0 = cirq.LineQubit(2)\n circuit = cirq.Circuit(cirq.X(q0))\n serializer = ionq.Serializer()\n result = serializer.serialize(circuit)\n assert result['qubits'] == 3\n\n\ndef test_serialize_non_gate_op_invalid():\n q0, q1 = cirq.LineQubit.range(2)\n circuit = cirq.Circuit(cirq.ParallelGateOperation(cirq.X, [q0, q1]))\n serializer = ionq.Serializer()\n with pytest.raises(ValueError, match='ParallelGateOperation'):\n _ = serializer.serialize(circuit)\n\n\ndef test_serialize_negative_line_qubit_invalid():\n q0 = cirq.LineQubit(-1)\n circuit = cirq.Circuit(cirq.X(q0))\n serializer = ionq.Serializer()\n with pytest.raises(ValueError, match='-1'):\n _ = serializer.serialize(circuit)\n\n\ndef test_serialize_pow_gates():\n q0 = cirq.LineQubit(0)\n serializer = ionq.Serializer()\n for name, gate in (('rx', cirq.X), ('ry', cirq.Y), ('rz', cirq.Z)):\n for exponent in (1.0, 0.5):\n circuit = cirq.Circuit((gate**exponent)(q0))\n result = serializer.serialize(circuit)\n assert result == {\n 'qubits':\n 1,\n 'circuit': [{\n 'gate': name,\n 'targets': [0],\n 'rotation': exponent * np.pi\n }],\n }\n\n\ndef test_serialize_xx_pow_gate():\n q0, q1 = cirq.LineQubit.range(2)\n serializer = ionq.Serializer()\n for exponent in (0.5, 1.0, 1.5):\n circuit = cirq.Circuit(cirq.XXPowGate(exponent=exponent)(q0, q1))\n result = serializer.serialize(circuit)\n assert result == {\n 'qubits':\n 2,\n 'circuit': [{\n 'gate': 'xx',\n 'targets': [0, 1],\n 'rotation': exponent * np.pi\n }]\n }\n\n\ndef test_serialize_not_serializable():\n q0, q1 = cirq.LineQubit.range(2)\n serializer = ionq.Serializer()\n circuit = cirq.Circuit(cirq.PhasedISwapPowGate()(q0, q1))\n with pytest.raises(ValueError, match='PhasedISwapPowGate'):\n _ = serializer.serialize(circuit)\n","sub_path":"cirq/ionq/serializer_test.py","file_name":"serializer_test.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"439103707","text":"import warnings\nwarnings.simplefilter(\"ignore\")\nimport pandas as pd\nimport os\nimport sys\nimport logging\nfrom src.feature_selection import *\nfrom src.logging_utils import setup_default_logging\nfrom src.preprocess import *\nfrom src.model_selection import *\nfrom src.datasets import read_data\nfrom sklearn.pipeline import Pipeline\nimport numpy as np\nimport pickle\nsetup_default_logging()\nlogger = logging.getLogger(\"test_selection\")\n\ndef get_imputer(train_pd):\n null_imputer = NullImputer()\n remove_imputer = RemovelColsImputer()\n imputer = Pipeline([('null_imputer', null_imputer), (\"remove_imputer\", remove_imputer)])\n return imputer.fit(train_pd)\n\ndef select_features_step(train_pd, model_, strategy):\n select_tool = SelectionFeatures(model_)\n return select_tool.select_features(strategy)\n\ndef get_model(model_class, train_pd, col_levels, predictor_cols, target_col):\n return model_class(train_pd, predictor_cols, target_col, col_levels)\n\ndef process(model_class):\n train_pd = read_data('train.csv')\n imputer = get_imputer(train_pd)\n train_pd = imputer.transform(train_pd)\n predictor_cols = train_pd.columns[:-1]\n target_col = train_pd.columns[-1]\n model_ = get_model(model_class, train_pd, imputer.steps[0][1].col_levels, predictor_cols, target_col)\n results_fit = select_features_step(train_pd, model_, \"mix\")\n results_cv = get_results_cv(results_fit, model_)\n selection = plain_selection(results_cv)\n final_cols, final_model = selection[\"cols\"], selection[\"results\"]\n\n output_info = f\"Final results: With cols = {final_cols} - number_features = {len(final_cols)} - cv_score: {np.sqrt(selection['cv_score_mean'])}\"\n logger.info(output_info)\n\n test_pd = read_data(\"test.csv\")\n test_pd = imputer.transform(test_pd)\n test_result = final_model.predict(test_pd[final_cols])\n test_result = pd.concat([pd.Series(test_pd.index, name=\"Id\"), test_result], axis=1)\n output_path = os.path.dirname(os.path.dirname(__file__)) + \"/outputs\"\n test_result.to_csv(os.path.join(output_path, f\"{model_.name}_output_mix.csv\"), index=False)\n with open(os.path.join(output_path, f\"{model_.name}_output_info.txt\"), \"w\") as f:\n f.write(output_info)","sub_path":"src/process_functions.py","file_name":"process_functions.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"266116937","text":"# -*- coding: utf-8 -*-\nfrom setuptools import setup, find_packages\nimport os\n\nversion = '1.0.0'\n\nwith open(\"requirements.txt\", \"r\") as f:\n\tinstall_requires = f.readlines()\n\t\nsetup(\n name='google_integration',\n version=version,\n description='Application will enable syncing of Calendar and Contacts from ERPNext to Google and vice versa.',\n author='Frappe Technologies Pvt. Ltd.',\n author_email='info@frappe.io',\n packages=find_packages(),\n zip_safe=False,\n include_package_data=True,\n install_requires=install_requires,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"203122688","text":"\"\"\"\nReads MCNP output file\n\"\"\"\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport datetime\nimport sys\nimport argparse\nimport logging\nimport numpy as np\n#import pandas as pd\nimport neut_utilities as ut\n\n\nclass MCNPOutput():\n \"\"\" MCNP output data\"\"\"\n def __init__(self):\n \"\"\" define data\"\"\"\n self.file_name = \"\"\n self.version = \"\"\n self.date = \"\"\n self.start_time = \"\"\n self.cell_mass_volume = []\n self.surface_area = []\n self.num_tallies = 1\n self.num_rendevous = 1\n self.tally_data = []\n self.summary_data = []\n self.tfc_data = []\n self.t60 = None\n self.warnings = []\n self.comments = []\n \n\nclass MCNP_tally_data():\n \"\"\" generic tally object for data common to all tally types \"\"\"\n def __init__(self):\n # general\n self.number = 1\n self.type = 1\n self.particle = \"neutron\"\n self.nps = 1\n self.result = []\n self.err = []\n self.eng = None\n self.stat_tests = None\n self.times = None\n self.user_bins = None\n\n \nclass MCNP_type5_tally(MCNP_tally_data):\n \"\"\" specific tally object for a type 5 point detector tally \"\"\"\n def __init__(self):\n MCNP_tally_data.__init__(self)\n # for type 5 tallies\n self.x = None\n self.y = None\n self.z = None\n self.cell_scores = None\n self.uncoll_flux = None\n self.uncoll_err = None\n\n \nclass MCNP_surface_tally(MCNP_tally_data):\n \"\"\" specific tally object for a type 1 or 2 surface tally\"\"\"\n def __init__(self):\n MCNP_tally_data.__init__(self)\n # for type 1 or 2\n self.surfaces = None\n self.areas = None\n self.ang_bins = None\n \n \nclass MCNP_cell_tally(MCNP_tally_data):\n \"\"\" specific tally object for a type 4 cell tally\"\"\"\n def __init__(self):\n MCNP_tally_data.__init__(self)\n # for type 4\n self.cells = None\n self.vols = None \n\n \nclass MCNP_pulse_tally(MCNP_tally_data):\n \"\"\" specific tally object for a type 8 pulse height tally\"\"\"\n def __init__(self):\n MCNP_tally_data.__init__(self)\n # for type 8\n self.cells = None \n \n \nclass MCNP_summary_data():\n \"\"\" data for the summary table \"\"\"\n def __init__(self):\n self.number = 1\n self.type = 1\n\n\ndef read_version(lines):\n \"\"\" from 1st line of output get the MCNP version\"\"\"\n version = None\n l = lines[0]\n if l[:29]==\" Code Name & Version\":\n version = l.split(\"=\")[1]\n version = version.strip()\n logging.debug(\"Version: %s\", version)\n return version\n\n \ndef read_run_date(lines):\n \"\"\" finds the start date and time of the run \"\"\"\n date = None\n time = None\n if len(lines) > 101:\n lines = lines[:100]\n data_line = lines[ut.find_line(\"1mcnp\", lines, 5)]\n data_line = ut.string_cleaner(data_line)\n data_line = data_line.split(\" \")\n date = data_line[-2]\n time = data_line[-1]\n \n logging.debug(\"Start date: %s\", date)\n logging.debug(\"Start time: %s\", time) \n \n return date, time\n \n\ndef read_cell_mass(data):\n \"\"\" \"\"\"\n return 1\n\n\ndef read_surface_area(data):\n \"\"\" \"\"\"\n return 1\n\n\ndef read_comments_warnings(lines):\n \"\"\" extracts all comments and warnings in the output file \"\"\"\n comments = []\n warnings = []\n for l in lines:\n if l[:10] == \" comment.\":\n comments.append(l)\n elif l[:10] == \" warning.\":\n warnings.append(l)\n return comments, warnings\n\n\ndef get_tally_nums(lines):\n \"\"\" finds the tally numbers used in the problem\"\"\"\n tal_num_list = []\n for l in lines:\n if l[0:11] == \"1tally \":\n l = ut.string_cleaner(l)\n l = l.split(\" \")[1]\n tal_num_list.append(l)\n tal_num_list = set(tal_num_list)\n logging.debug(\"tally numbers:\")\n logging.debug(tal_num_list)\n\n return tal_num_list\n\n\ndef get_num_rendevous(data):\n \"\"\" counts the number of rendevous in the file \"\"\"\n return 1\n \ndef process_ang_string(line):\n \"\"\" converts the tally string describing the angualr bin edges into \n a single float value for the angle \"\"\"\n line=line.strip()\n ang_string = line.split(\":\")[1]\n ang_float = float(ang_string.split()[-2])\n return ang_float\n\ndef read_summary(data, ptype, rnum):\n \"\"\" reads the summary tables in the output file \"\"\"\n return 1\n\n\ndef read_table60(lines):\n \"\"\"read table 60 \n input a list of strings\n returns a reduced list with just the lines in table 60\n \"\"\"\n \n # first check there is a table 60, might not be if it is a continue run\n try:\n start_line = ut.find_line(\"1cells\", lines, 6)\n except ValueError:\n return None\n \n term_line = ut.find_line(\" minimum source weight\", lines, 25)\n lines = lines[start_line:term_line]\n \n return lines\n \n \ndef print_tally_lines_to_file(lines, fname, tnum): \n \"\"\" prints tally section to a file for debugging \"\"\"\n if logging.getLogger().getEffectiveLevel() == 10:\n fname = fname + str(tnum)+\".txt\"\n logging.debug(\"writing \" + fname)\n ut.write_lines(fname, lines) \n \n \ndef process_e_t_userbin(data):\n \"\"\"processes energy time bins in a tally\"\"\"\n time_bins = []\n erg_bins = []\n \n # first find time bins\n for l in data:\n if \"time\" in l:\n l = \" \".join(l.split())\n l=l.split(\" \")[1:]\n for t in l:\n time_bins.append(t)\n\n # find energy bins\n in_data = False\n for l in data:\n if in_data:\n if \"total\" in l:\n in_data = False\n break\n l = \" \".join(l.split())\n erg=l.split(\" \")[0]\n erg_bins.append(erg)\n elif not in_data:\n if \"energy\" in l:\n in_data = True\n \n erg_bins.append(\"total\")\n # create data arrays \n res_data = np.zeros((len(time_bins)+1, len(erg_bins)))\n err_data = np.zeros((len(time_bins)+1, len(erg_bins)))\n # now try get the data\n tcol = 0\n erow = 0\n len_tcol=0\n in_data = False\n for j, l in enumerate(data):\n if in_data:\n if \"total\" in l:\n in_data = False\n \n l = \" \".join(l.split())\n l = l.split(\" \")[1:]\n tvals = l[::2]\n ervals = l[1::2]\n len_tcol=0\n for i, val in enumerate(tvals):\n res_data[tcol+len_tcol, erow] = val\n err_data[tcol+len_tcol, erow] = ervals[i]\n len_tcol = len_tcol+1\n erow = erow + 1\n \n elif not in_data:\n if \"energy\" in l:\n in_data = True\n tcol = tcol + len_tcol - 1\n erow = 0\n \n return time_bins, erg_bins, res_data, err_data\n\n\ndef read_tally(lines, tnum, rnum=-1):\n \"\"\"reads the lines and extracts the tally results\"\"\"\n \n # todo add ability to do all rendevous\n # reduce to only the final result set\n term_line = ut.find_line(\" run terminated \", lines, 21)\n lines = lines[term_line:]\n\n # reduce to only the tally results section\n fline = \"1tally\" + ((9-len(str(tnum)))*\" \")\n res_start_line = ut.find_line(fline + str(tnum), lines, 15)\n \n # add an error catch\n \n # check if tally comment\n if lines[res_start_line +1][0] == \"+\":\n tal_comment_bool = True\n else:\n tal_comment_bool = False\n \n # find tally type and create appropriate class\n if tal_comment_bool:\n type = lines[res_start_line + 2][22]\n else:\n type = lines[res_start_line + 1][22]\n \n if type == '5':\n tally_data = MCNP_type5_tally()\n elif type == '4' or type == '6':\n tally_data = MCNP_cell_tally()\n elif type == '1' or type == '2':\n tally_data = MCNP_surface_tally()\n elif type == '8':\n tally_data = MCNP_pulse_tally()\n else:\n tally_data = MCNP_tally_data()\n \n # get basic common tally data \n tally_data.number = int(tnum)\n \n # get particle type\n if tal_comment_bool:\n tally_data.particle = lines[res_start_line+3][24:33]\n else:\n tally_data.particle = lines[res_start_line+2][24:33]\n \n tally_data.particle = ut.string_cleaner(tally_data.particle)\n tally_data.nps = ut.string_cleaner(lines[res_start_line][28:40])\n tally_data.nps = int(tally_data.nps)\n tally_data.type = type\n \n \n # limit lines to just the tally data\n lines = lines[res_start_line + 1:]\n tal_end_line = ut.find_line(\"1tally\", lines, 6)\n lines = lines[:tal_end_line-1]\n\n # print tally test file\n print_tally_lines_to_file(lines, \"tally_test\", tnum)\n\n # debug \n logging.info('Reading tally %s', str(tnum))\n logging.debug('Run term line number: %s', str(term_line))\n logging.debug('Result start line number: %s', str(res_start_line))\n logging.debug('tally end line number: %s', str(tal_end_line))\n logging.debug('tally particle: %s', tally_data.particle)\n logging.debug('tally nps: %s', str(tally_data.nps))\n logging.debug('tally type: %s', str(tally_data.type))\n\n # depending on tally type choose what to do now\n if tally_data.type == \"4\" or tally_data.type == \"6\":\n tally_data = read_type_cell(tally_data, lines) \n elif tally_data.type == \"5\":\n tally_data = read_type_5(tally_data, lines) \n elif tally_data.type == \"1\" or tally_data.type == \"2\":\n tally_data = read_type_surface(tally_data, lines)\n elif tally_data.type == \"8\":\n tally_data = read_type_8(tally_data, lines)\n else:\n logging.info(\"Tally type not recognised or supported\") \n \n # get statistical test outcomes\n # first check not all zeros\n # if np.array(tally_data.result).any():\n # tally_data.stat_tests = read_stat_tests(lines)\n\n return tally_data\n\ndef read_type_8(tally_data, lines):\n \"\"\" process type 8 tally output data \"\"\"\n logging.debug(\"pulse height tally\")\n # TODO: fix this hard coded part\n tally_data.cells = [\"2\"] # this should not be hard coded\n \n # loop for each cell\n for cell in tally_data.cells:\n cline = \" cell \" \n cell_res_start = ut.find_line(cline + cell, lines, len(cell)+len(cline))\n if lines[cell_res_start + 1] == \" energy \":\n logging.debug(\"noticed energy\")\n tally_data.eng = []\n loc_line_id2=ut.find_line(\" total \", lines[cell_res_start + 1:], 15)\n erg_lines = lines[cell_res_start + 2:cell_res_start + 1 + loc_line_id2]\n for l in erg_lines:\n l=l.strip()\n l=l.split(\" \")\n tally_data.eng.append(float(l[0]))\n tally_data.result.append(float(l[3]))\n tally_data.err.append(float(l[4]))\n else:\n # single value result\n logging.debug('tally e bin count = 1')\n l = lines[cell_res_start + 1]\n l=l.strip()\n l=l.split(\" \")\n tally_data.result.append(float(l[0]))\n tally_data.err.append(float(l[1]))\n \n if tally_data.eng != None: \n logging.debug('tally e bin count: %s', len(tally_data.eng))\n\n return tally_data\n\ndef read_type_surface(tally_data, lines):\n \"\"\" process type 1 or type 2 tally output data\"\"\"\n logging.debug(\"Surface Tally\")\n tally_data.areas = []\n tally_data.surfaces = []\n \n # TODO: if more than a single line of surfaces or areas\n # find areas\n # TODO: sort for type 1 tally with sd card \n if tally_data.type == \"2\":\n area_line_id = ut.find_line(\" areas\", lines, 16)\n area_val_line = lines[area_line_id + 2]\n area_val_line = \" \".join(area_val_line.split())\n tally_data.areas = np.asarray(area_val_line.split(\" \"))\n # find surfaces\n suf_val_line = lines[area_line_id + 1]\n suf_val_line = \" \".join(suf_val_line.split())\n suf_val_line = suf_val_line.split(\":\")[1]\n tally_data.surfaces = suf_val_line.split(\" \")[1:]\n\n logging.debug(\"Tally surface numbers:\")\n logging.debug(tally_data.surfaces)\n logging.debug(\"Tally surface areas:\")\n logging.debug(tally_data.areas) \n \n first_surface_line_id = ut.find_line(\" surface \", lines, 9)\n logging.debug(\"first surface id %s\", first_surface_line_id)\n if tally_data.type ==\"1\": \n tally_data.surfaces = lines[first_surface_line_id].strip() \n tally_data.surfaces = [tally_data.surfaces.split()[-1]]\n logging.debug(\"Tally surface numbers:\")\n logging.debug(tally_data.surfaces)\n \n loc = 0\n surface_line_id = first_surface_line_id\n res_df = []\n rel_err_df = []\n if lines[first_surface_line_id +1] == \" energy \":\n logging.debug(\"energy bins only\")\n \n for s in tally_data.surfaces:\n # find start and end points\n logging.debug(\"Reading Surface: %s\", s)\n tot_line_id = ut.find_line(\" total \", lines[surface_line_id:], 13)\n erg_lines = lines[surface_line_id+2:surface_line_id+tot_line_id]\n\n surface_line_id = ut.find_line(\" surface \", lines[loc:], 9)\n surface_line_id = surface_line_id + loc\n \n loc = tot_line_id + 1\n # set arrays\n erg = []\n res = []\n rel_err = []\n for l in erg_lines:\n l = l.strip()\n l = l.split(\" \")\n erg.append(float(l[0]))\n res.append(float(l[3]))\n rel_err.append(float(l[4]))\n\n res_df.append(res)\n rel_err_df.append(rel_err)\n \n # simplfy if only one surface\n if len(res_df)==1:\n tally_data.result = res\n tally_data.err = rel_err\n else:\n tally_data.result = res_df\n tally_data.err = rel_err_df\n \n # add energy data to tally object\n tally_data.eng = erg\n \n \n elif lines[first_surface_line_id +1][:11] == \" angle bin\":\n logging.debug(\"angle bins\")\n \n if lines[first_surface_line_id +2] == \" energy \":\n logging.debug(\"energy bins\")\n angles_bins = [-1.0]\n \n ebin = []\n rel_err = []\n res = []\n in_res = False\n for l in lines[first_surface_line_id:]:\n if l[:11] == \" angle bin\":\n ang_float = process_ang_string(l)\n angles_bins.append(ang_float)\n logging.debug(ang_float)\n if l[:13] == \" total \":\n in_res = False\n ebin = np.array(ebin)\n tally_data.eng=ebin\n rel_err = np.array(rel_err)\n rel_err_df.append(rel_err)\n res = np.array(res)\n res_df.append(res)\n ebin = []\n rel_err = []\n res = []\n if in_res:\n l = l.strip()\n l = l.split(\" \")\n ebin.append(float(l[0]))\n res.append(float(l[3]))\n rel_err.append(float(l[4]))\n if l == \" energy \":\n in_res = True\n \n tally_data.result = res_df\n tally_data.err = rel_err_df\n tally_data.ang_bins = angles_bins\n \n else:\n logging.debug(\"angle bins only\")\n else:\n logging.debug(\"single value only\")\n l = lines[first_surface_line_id+1]\n l = l.strip()\n l = l.split(\" \")\n tally_data.result = [float(l[0])]\n tally_data.err = [float(l[1])]\n \n return tally_data\n\n \ndef read_type_cell(tally_data, lines): \n \"\"\" process type 4 or type 6 tally output data \"\"\"\n logging.debug(\"Volume tally\")\n tally_data.vols = []\n tally_data.cells = []\n # find cells\n # find volumes\n # TODO: if more than a single line of vols or cells\n \n if tally_data.type == \"4\":\n vol_line_id = ut.find_line(\" volumes \", lines, 19)\n vol_val_line = lines[vol_line_id + 2]\n vol_val_line = \" \".join(vol_val_line.split())\n tally_data.vols = vol_val_line.split(\" \")\n elif tally_data.type == \"6\":\n vol_line_id = ut.find_line(\" masses \", lines, 18)\n vol_val_line = lines[vol_line_id + 2]\n vol_val_line = \" \".join(vol_val_line.split())\n tally_data.vols = vol_val_line.split(\" \")\n cell_val_line = lines[vol_line_id + 1]\n cell_val_line = \" \".join(cell_val_line.split())\n cell_val_line = cell_val_line.split(\":\")[1]\n tally_data.cells = cell_val_line.split(\" \")[1:]\n\n # loop for each cell\n for cell in tally_data.cells:\n cline = \" cell \" \n cell_res_start = ut.find_line(cline + cell, lines, len(cell)+len(cline))\n if lines[cell_res_start + 1] == \" energy \":\n logging.debug(\"noticed energy\")\n tally_data.eng = []\n loc_line_id2=ut.find_line(\" total \", lines[cell_res_start + 1:], 15)\n erg_lines = lines[cell_res_start + 2:cell_res_start + 1 + loc_line_id2]\n for l in erg_lines:\n l=l.strip()\n l=l.split(\" \")\n tally_data.eng.append(float(l[0]))\n tally_data.result.append(float(l[3]))\n tally_data.err.append(float(l[4]))\n else:\n data_line = lines[cell_res_start + 1]\n data_line = \" \".join(data_line.split())\n data_line = data_line.split(\" \")\n tally_data.result.append(float(data_line[0]))\n tally_data.err.append(float(data_line[1]))\n return tally_data\n \n \ndef read_type_5(tally_data, lines):\n \"\"\" processes a type 5 (point detector tally output) \"\"\"\n # read detector position\n loc_line_id=ut.find_line(\" detector located\", lines, 17)\n loc_line = lines[loc_line_id]\n loc_line = loc_line.split(\"=\")[1]\n\n tally_data.x = loc_line[0:12]\n tally_data.x = float(tally_data.x.strip())\n tally_data.y = loc_line[12:24]\n tally_data.y = float(tally_data.y.strip())\n tally_data.z = loc_line[24:36]\n tally_data.z = float(tally_data.z.strip())\n logging.debug(\"x: %s\",tally_data.x)\n logging.debug(\"y: %s\",tally_data.y)\n logging.debug(\"z: %s\",tally_data.z)\n res_line = lines[loc_line_id + 1]\n\n # check if energy dependant\n if res_line == \" energy \":\n logging.debug(\"energy dependant\")\n tally_data.eng = []\n total_line_id2=ut.find_line(\" total\", lines[loc_line_id+1:], 11)\n erg_lines = lines[loc_line_id + 2:loc_line_id + total_line_id2+1]\n \n for l in erg_lines:\n l=l.strip()\n l=l.split(\" \")\n tally_data.eng.append(float(l[0]))\n tally_data.result.append(float(l[3]))\n tally_data.err.append(float(l[4]))\n elif \"time\" in res_line:\n logging.debug(\"found time\")\n # add time counter\n times = []\n t1_res = []\n t1_err = [] \n t2_res = []\n t2_err = []\n t3_res = []\n t3_err = []\n t4_res = []\n t4_err = []\n t5_res = []\n t5_err = []\n ergs = []\n\n\n t_count= 0\n loc_line_id2=ut.find_line(\" detector located\", lines[loc_line_id+2:], 17)\n erg_lines = lines[loc_line_id + 1 :loc_line_id + loc_line_id2-1]\n in_res = False\n for l in erg_lines:\n if (\"total\" in l) and (\"time\" not in l):\n in_res = False\n tally_data.result.append(t1_res)\n tally_data.result.append(t2_res)\n tally_data.result.append(t3_res)\n tally_data.result.append(t4_res)\n tally_data.result.append(t5_res)\n tally_data.err.append(t1_err)\n tally_data.err.append(t2_err)\n tally_data.err.append(t3_err)\n tally_data.err.append(t4_err)\n tally_data.err.append(t5_err)\n tally_data.eng = ergs\n t1_res = []\n t1_err = [] \n t2_res = []\n t2_err = []\n t3_res = []\n t3_err = []\n t4_res = []\n t4_err = []\n t5_res = []\n t5_err = []\n ergs = []\n elif in_res:\n l = l.strip()\n l = \" \".join(l.split())\n l = l.split(\" \")\n ergs.append(float(l[0]))\n if tcount >= 1:\n t1_res.append(float(l[1]))\n t1_err.append(float(l[2]))\n if tcount >= 2:\n t2_res.append(float(l[3]))\n t2_err.append(float(l[4]))\n if tcount >= 3:\n t3_res.append(float(l[5]))\n t3_err.append(float(l[6]))\n if tcount >= 4:\n t4_res.append(float(l[7]))\n t4_err.append(float(l[8]))\n if tcount >= 5:\n t5_res.append(float(l[9]))\n t5_err.append(float(l[10]))\n\n elif \"energy\" in l:\n in_res = True\n elif \"time\" in l:\n l = l.strip()\n l = \" \".join(l.split())\n l = l.split(\" \")\n tcount = len(l[1:])\n\n for t in l[1:]:\n times.append(t)\n\n tally_data.times = times \n elif \"user bin\" in res_line:\n # user bins used \n # assumes if user bins then also energy and time bins\n # curently extracts total flux not uncollided\n logging.debug(\"Special user bin tally\")\n user_bins = []\n user_bin_locs = []\n user_bin = res_line.split(\" \")[-1]\n logging.debug(\"User bin: %s\", user_bin) \n user_bins.append(user_bin)\n user_bin_locs.append(0)\n for i, l in enumerate(lines[loc_line_id+1:]):\n if \"user bin\" in l:\n user_bin = l.split(\" \")[-1]\n user_bins.append(user_bin)\n user_bin_locs.append(i)\n if user_bin == \"total\":\n break\n tally_data.user_bins = user_bins\n \n bin_data = lines[loc_line_id+1:]\n i = 0\n while i < len(user_bin_locs)-1:\n ubin_data = bin_data[user_bin_locs[i]:user_bin_locs[i+1]]\n tdata, edata, resdata, errdata = process_e_t_userbin(ubin_data)\n tally_data.result.append(resdata)\n tally_data.err.append(errdata)\n tally_data.times = tdata\n tally_data.eng = edata\n i = i + 1\n \n \n else:\n # single value and error result\n res_line = res_line.split(\" \")[-2:]\n tally_data.result.append(float(res_line[0]))\n tally_data.err.append(float(res_line[1])) \n\n return tally_data \n \n \ndef read_stat_tests(lines):\n \"\"\" initial stat test reader\"\"\"\n stat_res_line_id = ut.find_line(\" passed\", lines, 7)\n stat_line = lines[stat_res_line_id]\n stat_line = ut.string_cleaner(stat_line)\n stat_line = stat_line.split(\" \")[1:]\n return stat_line\n\n\ndef read_output_file(path):\n \"\"\" reads an mcnp output file\n input is a path the to an ouput file\n output is an mcnp output object\n \"\"\"\n logging.info('Reading MCNP output file: %s', path)\n ofile_data = ut.get_lines(path)\n mc_data = MCNPOutput()\n \n # general \n mc_data.file_name = path \n mc_data.version = read_version(ofile_data)\n mc_data.date, mc_data.start_time = read_run_date(ofile_data)\n mc_data.comments, mc_data.warnings = read_comments_warnings(ofile_data)\n \n # read specific tables\n # mc_data.t60 = read_table60(ofile_data)\n \n # tallies\n tls = get_tally_nums(ofile_data)\n for tnum in tls:\n mc_data.tally_data.append(read_tally(ofile_data, tnum))\n\n return mc_data\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(description=\"Read MCNP output file\")\n parser.add_argument(\"input\", help=\"path to the output file\")\n args = parser.parse_args()\n\n read_output_file(args.input)\n","sub_path":"mcnp_output_reader.py","file_name":"mcnp_output_reader.py","file_ext":"py","file_size_in_byte":24710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"426348978","text":"# -*- coding: UTF8 -*-\n'''\nCreated on 2012-12-5\n\n@author: yuanrui\n'''\n\nimport base\n\nclass comp_node_nostra(base.component_base.comp_base):\n '''\n make node_tbl\n '''\n\n def __init__(self):\n '''\n Constructor\n '''\n base.component_base.comp_base.__init__(self, 'Node')\n\n def _DoCreateTable(self):\n if self.CreateTable2('node_tbl') == -1:\n return -1\n\n return 0\n\n def _DoCreateFunction(self):\n\n return 0\n\n def _Do(self):\n\n sqlcmd = \"\"\"\n insert into node_tbl (\n node_id, kind, light_flag, toll_flag, mainnodeid, node_lid,\n node_name, the_geom )\n (\n select a.node_id, null, null, null, 0,\n array_to_string(b.node_lid, '|'),\n null as node_name, a.the_geom\n from temp_topo_node as a\n left outer join (\n select n.node_id as node_id, array_agg(l.routeid) as node_lid\n from temp_topo_node n, temp_topo_link l\n where n.node_id = l.start_node_id or n.node_id = l.end_node_id\n group by n.node_id\n ) as b\n on a.node_id = b.node_id\n )\n \"\"\"\n\n self.log.info(': Now it is inserting node_tbl...')\n if self.pg.execute2(sqlcmd) == -1:\n return -1\n else:\n self.pg.commit2()\n\n self.log.info(': end of inserting node_tbl...')\n\n return 0\n\n def _DoCreateIndex(self):\n 'create index.'\n self.CreateIndex2('node_tbl_node_id_idx')\n self.CreateIndex2('node_tbl_the_geom_idx')\n\n return 0\n","sub_path":"Suntec/Road_Format13IDDN/source/V13/iDDN/Org2Middle/src/component/nostra/node_nostra.py","file_name":"node_nostra.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"521534785","text":"from oving3.AsciiCoder import AsciiCoder\nfrom oving3.Huffcoder import HuffCoder\nfrom oving3.LempelZivCoder import LempelZivCoder\n\n__author__ = 'Stian'\n\npath = \"D:\\Dropbox\\PyWorkspace\\PLab2\\oving3\\Resources\"\nhuffman_coder = HuffCoder()\nascii_coder = AsciiCoder()\nlempel_ziv_coder = LempelZivCoder()\n\ndef runHuffmanTest():\n for i in 1,2,3:\n huffman_coder.Huff_test(\"\", path+\"\\sample%d.txt\" % i, False)\n print(\"=\"*100)\n huffman_coder.Huff_test(\"\", path+\"\\sample%d.txt\" % i, True)\n print(\"=\"*100)\n for i in \"e\"*100, \"e\"*1000, \"x\"*1000, \"ntnu\"*100, \"ntnu\"*1000:\n huffman_coder.Huff_test(i, False, True)\n print(\"=\"*100)\n\ndef runAsciiTest():\n for i in 1,2,3:\n ascii_coder.Ascii_test(\"\", path+\"\\sample%d.txt\" % i, False)\n print(\"=\"*100)\n ascii_coder.Ascii_test(\"\", path+\"\\sample%d.txt\" % i, True)\n print(\"=\"*100)\n for i in \"e\"*100, \"e\"*1000, \"x\"*1000, \"ntnu\"*100, \"ntnu\"*1000:\n ascii_coder.Ascii_test(i, False, True)\n print(\"=\"*100)\n\ndef runLZTest():\n for i in r\"\\tumbler_bit.txt\", r\"\\potus_bit.txt\", r\"\\rings_bit.txt\":\n lempel_ziv_coder.LZ_test(\"\", path + i)\n print(\"=\"*100)\n\n#runHuffmanTest()\n#runAsciiTest()\n#runLZTest()\nlempel_ziv_coder.LZ_test()","sub_path":"oving3/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"250278967","text":"#+---------------------------------------------------------------------------------------------\n#| ETL DE CARGA DE FACTURAS DE GRUPO POSADAS\n#+---------------------------------------------------------------------------------------------\n#+---------------------------------------------------------------------------------------------\n#| Importes de librerias\n#+---------------------------------------------------------------------------------------------\nfrom contextlib import closing\nimport MySQLdb\nimport pymongo\nimport sys\nimport datetime\nimport facturasClases\nimport facturasConsultas\nfrom pymongo import MongoClient\n#+---------------------------------------------------------------------------------------------\n#| Configuracion de MongoDB\n#+---------------------------------------------------------------------------------------------\nmongoConnectionString = \"mongodb://portalClientesEmision:NextTech2017@52.22.56.51:27017/?authSource=admin\"\nclient = MongoClient(mongoConnectionString)\nmdb = client.PosadasTest # LoadDataMartPosadas PosadasTest\nfactura = mdb.factura\nctl = mdb.Control\ncmpg = mdb.complemento_pago\ncdrp = mdb.doc_relacionado_pago\n\n#+---------------------------------------------------------------------------------------------\n#| Configuracion de Replica de Facto Posadas\n#+---------------------------------------------------------------------------------------------\nhost = \"svpvazscfpmdb02.southcentralus.cloudapp.azure.com\"\nport = 23306\nuser = \"python\"\npasswd = \"y6Ap7OM1zEQZdTuDjs7Wb6uO\"\ndb = \"facto_business\"\n# db = MySQLdb.connect(host=host, port=port, user=user, passwd=passwd, db=db)\n# mySqlCursor = db.cursor()\n\n\nclass DB:\n conn = None\n\n def connect(self):\n self.conn = MySQLdb.connect(\"svpvazscfpmdb02.southcentralus.cloudapp.azure.com\",\"python\", \"y6Ap7OM1zEQZdTuDjs7Wb6uO\", \"facto_business\", 23306)\n\n def query(self, sql):\n try:\n cursor = self.conn.cursor()\n cursor.execute(sql)\n except (AttributeError, MySQLdb.OperationalError):\n self.connect()\n cursor = self.conn.cursor()\n cursor.execute(sql)\n return cursor\n\n\n#+---------------------------------------------------------------------------------------------\n#| Buscamos el ultimo ID de la factura Cargada:\n#+---------------------------------------------------------------------------------------------\nfacturaIdActual = ctl.find_one({\"NombreTabla\": \"factura\"})\ndrpActual = ctl.find_one({\"NombreTabla\": \"doc_relacionado_pago\"})\ncomPagoActual = ctl.find_one({\"NombreTabla\": \"complementos_pago\"})\nfacturaID = facturaIdActual['UltimoId']\ndocRelPagId = drpActual['UltimoId']\ncomPagoId = comPagoActual['UltimoId']\nprint(\"Ultima Factura Cargada: \" + str(facturaID))\nprint(\"Ultimo Doc Rel Pago Cargado: \" + str(docRelPagId))\nprint(\"Ultimo Complemento Cargado: \" + str(comPagoId))\n#+---------------------------------------------------------------------------------------------\n#| Consultamos las Ultimas Facturas y almacenamos en Buffer:\n#+---------------------------------------------------------------------------------------------\nfacturasBuffer = []\nlistaFacturas = facturasConsultas.listaFacturas(facturaID)\ndb = DB()\ncursor = db.query(listaFacturas)\ndata = cursor.fetchall()\nfor row in data:\n facturasBuffer.append({\n \"_id\": row[0],\n \"FOLIO\": row[1],\n \"FOLIO_FISCAL\": row[2],\n \"FECHA_FACTURA\": facturasClases.fechaValida(row[3]),\n \"FECHA_TIMBRADO\": facturasClases.fechaValida(row[3]),\n \"FECHA_CANCELACION\": facturasClases.fechaValida(row[5]),\n \"STATUS\": row[6],\n \"SERIE\": row[7],\n \"MONEDA\": row[8],\n \"TIPO_CAMBIO\": row[9],\n \"METODO_PAGO\": row[10],\n \"FORMA_PAGO\": row[11],\n \"SUBTOTAL_FACTURA\": row[12],\n \"TOTAL_DESCUENTO\": row[13],\n \"TOTAL_IMPUESTO\": row[14],\n \"TOTAL_FACTURA\": row[15],\n \"SALDO_PAGOS\": row[16],\n \"NUM_PARCIALIDAD\": row[17],\n \"ADDENDA\": row[18],\n \"SUCURSAL\": row[19],\n \"RUTA_XML\": row[20],\n \"RUTA_PDF\": row[21],\n \"EMISOR_RFC\": row[22],\n \"EMISOR\": row[23],\n \"EMISOR_RAZON_SOCIAL\": row[24],\n \"IDdesgloce_cliente\": row[25],\n \"dc_RAZON_SOCIAL\": row[26],\n \"dc_RFC\": row[27],\n \"dc_CODIGO_POSTAL\": row[28],\n \"dc_PAIS\": row[29],\n \"dc_CORREO\": row[30],\n \"dhf_ID\": row[31],\n \"dhf_FOLIO\": row[32],\n \"dhf_NOMBRE_HUESPED\": row[33],\n \"dhf_HABITACION\": row[34],\n \"dhf_FECHA_CHECK_IN\": facturasClases.fechaValida(row[35]),\n \"dhf_FECHA_CHECK_OUT\": facturasClases.fechaValida(row[36]),\n \"dhf_RESERVA\": row[37],\n \"dhf_VOUCHER\": row[38],\n \"dhf_CUPON\": row[39],\n \"dhf_EXTENSION\": row[40],\n \"dhf_REFERENCIA\": row[41],\n \"CARGO_NO_FACTURABLE\": [],\n \"fcc\": False\n })\n#+---------------------------------------------------------------------------------------------\n#| Si hay facturas que almacenar se activara esta seccion para cargar nuevas facturas\n#| Despues obtendra la ultima id cargada directamente de la base mongo y actualiza control\n#+---------------------------------------------------------------------------------------------\nif len(facturasBuffer) > 0:\n factura.insert_many(facturasBuffer)\n ultimo = factura.find({}, {\"_id\": 1}).limit(\n 1).sort('_id', pymongo.DESCENDING)\n for x in ultimo:\n ultimoId = x['_id']\n updatedPost = {\"$set\": {\"UltimoId\": ultimoId,\n \"UltimaActualizacion\": datetime.datetime.utcnow()}}\n ctl.update_one({\"NombreTabla\": \"factura\"}, updatedPost, upsert=True)\n#+---------------------------------------------------------------------------------------------\n#| Realizamos la Busqueda de Cargos No facturables\n#+---------------------------------------------------------------------------------------------\n#+---------------------------------------------------------------------------------------------\n#| Si hay cnf en la factura lo actualiza en dado caso de que no este fuera de alcanze\n#+---------------------------------------------------------------------------------------------\nqueryCNF = facturasConsultas.cargosNoFacturables(facturaID)\ncursorCNF = db.query(queryCNF)\ndataCNF = cursorCNF.fetchall()\nbufferCNF = []\nfor item in dataCNF:\n objCNF = facturasClases.cargoNoFacturable()\n objCNF.ID = item[0]\n objCNF.CARGO = item[1]\n objCNF.IMPORTE = item[2]\n bufferCNF.append(objCNF)\nif len(dataCNF) > 0:\n bulk = factura.initialize_ordered_bulk_op()\n for regCnf in bufferCNF:\n prePost = {\"$push\": {\"CARGO_NO_FACTURABLE\": {\n \"CARGO\": regCnf.CARGO, \"IMPORTE\": float(regCnf.IMPORTE)}}}\n bulk.find({'_id': int(regCnf.ID)}).update(prePost)\n bulk.execute()\n#+---------------------------------------------------------------------------------------------\n#| Se buscaran las facturas que contengan complementos de pago\n#| Se aplicara un metodo para Actualizar Factura y otro para cargar F.C.P.\n#+---------------------------------------------------------------------------------------------\nconsultaDocumentosRelacionados = facturasConsultas.docRelacionadoPago(docRelPagId)\ncursorComp = db.query(consultaDocumentosRelacionados)\ndataComp = cursorComp.fetchall()\nbufferFCPid = []\nbufferDRP = []\nfor drpf in dataComp:\n contId = facturasClases.docRelacionadoPagoo()\n contId.ID = drpf[0]\n contId.COMPLEMENTO_PAGO_ID = drpf[1]\n contId.FACTURA_ID = drpf[2]\n contId.ID_DOCUMENTO = drpf[3]\n contId.SERIE = drpf[4]\n contId.FOLIO = drpf[5]\n contId.MONEDA = drpf[6]\n contId.TIPO_CAMBIO = drpf[7]\n contId.METODO_PAGO = drpf[8]\n contId.NUM_PARCIALIDAD = drpf[9]\n contId.IMP_SALDO_ANT = drpf[10]\n contId.IMP_PAGO = drpf[11]\n contId.IMP_SALDO_INSOLUTO = drpf[12]\n bufferFCPid.append(contId)\n#+---------------------------------------------------------------------------------------------\n#| Actualizando Facturas con Documentos Relacionados al pago\n#+---------------------------------------------------------------------------------------------\nif len(bufferFCPid) > 0:\n bulk = factura.initialize_ordered_bulk_op()\n for ids in bufferFCPid:\n prePost = {'$set': {'fcc': True}}\n bulk.find({'_id': int(ids.FACTURA_ID)}).update(prePost)\n bulk.execute()\n\n for drpi in bufferFCPid:\n bufferDRP.append({'ID': int(drpi.ID),\n 'COMPLEMENTO_PAGO_ID': int(drpi.COMPLEMENTO_PAGO_ID),\n 'FACTURA_ID': int(drpi.FACTURA_ID),\n 'ID_DOCUMENTO': drpi.ID_DOCUMENTO,\n 'SERIE': drpi.SERIE,\n 'FOLIO': drpi.FOLIO,\n 'MONEDA': drpi.MONEDA,\n 'TIPO_CAMBIO': float(drpi.TIPO_CAMBIO),\n 'METODO_PAGO': drpi.METODO_PAGO,\n 'NUM_PARCIALIDAD': drpi.NUM_PARCIALIDAD,\n 'IMP_SALDO_ANT': float(drpi.IMP_SALDO_ANT),\n 'IMP_PAGO': float(drpi.IMP_PAGO),\n 'IMP_SALDO_INSOLUTO': float(drpi.IMP_SALDO_INSOLUTO)\n })\n cdrp.insert_many(bufferDRP)\n ultimo = cdrp.find({}, {\"ID\": 1}).limit(1).sort('ID', pymongo.DESCENDING)\n for x in ultimo:\n ultimoIdDRP = x['ID']\n updatedPost = {\"$set\": {\"UltimoId\": ultimoIdDRP,\"UltimaActualizacion\": datetime.datetime.utcnow() } }\n ctl.update_one({\"NombreTabla\": \"doc_relacionado_pago\"}, updatedPost, upsert=True)\n\n#+---------------------------------------------------------------------------------------------\n#| Actualizando Facturas con Complementos de pago\n#+---------------------------------------------------------------------------------------------\n\nconsultaComplementosPago = facturasConsultas.complementoPagos(comPagoId)\ncursorCP = db.query(consultaComplementosPago)\ndataCP = cursorCP.fetchall()\nbufferCP = []\nfor cp in dataCP:\n bufferCP.append({\n \"cp_ID\": int(cp[0]),\n \"cp_FACTURA_ID\": int(cp[1]),\n \"cp_FECHA_PAGO\": facturasClases.fechaValidaSimple(cp[2]),\n \"cp_FORMA_PAGO\": cp[3],\n \"cp_MONEDA\": cp[4],\n \"cp_TIPO_CAMBIO\": facturasClases.validaDecimal(cp[5]),\n \"cp_MONTO\": facturasClases.validaDecimal(cp[6]),\n \"cp_NUM_OPERACION\": cp[7],\n \"cp_RFC_EMISOR_CTA_ORD\": cp[8],\n \"cp_NOM_BANCO_ORD_EXT\": cp[9],\n \"cp_CTA_ORDENANTE\": cp[10],\n \"cp_RFC_EMISOR_CTA_BEN\": cp[11],\n \"cp_CTA_BENEFICIARIO\": cp[12],\n \"cp_TIPO_CAD_PAGO\": cp[13],\n \"cp_CAD_PAGO\": cp[14]\n })\nif len(bufferCP) > 0:\n cmpg.insert_many(bufferCP)\n ultimo = cmpg.find({}, {\"cp_ID\": 1}).limit(1).sort('cp_ID', pymongo.DESCENDING)\n for x in ultimo:\n ultimoIdDRP = x['cp_ID']\n updatedPost = {\"$set\": {\"UltimoId\": ultimoIdDRP,\"UltimaActualizacion\": datetime.datetime.utcnow() } }\n ctl.update_one({\"NombreTabla\": \"complementos_pago\"}, updatedPost, upsert=True)\n # | Actualizamos complementos_pago\n bulkUpdFacCP = factura.initialize_ordered_bulk_op()\n for cps in bufferCP:\n updatedComplementosID = { \"$set\": { \"fcc\": True } }\n bulkUpdFacCP.find({ \"_id\": cps[\"cp_FACTURA_ID\"] }).update(updatedComplementosID)\n bulkUpdFacCP.execute()\n\n# SECCION DE ACTUALIZACION DE ESTATUS >. 0:\n bulkUpdFac = factura.initialize_ordered_bulk_op()\n for fc in bufferFactCan:\n updateStatus = { \"$set\": { \"STATUS\": fc[\"STATUS\"], \"FECHA_CANCELACION\": fc[\"FECHA_CANCELACION\"] } }\n bulkUpdFac.find({'_id': int(fc[\"FACTURA_ID\"])}).update(updateStatus)\n bulkUpdFac.execute()\n\n\n\n\nquit()","sub_path":"PortalClientesEmision/ETL/FacturasETL.py","file_name":"FacturasETL.py","file_ext":"py","file_size_in_byte":12214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"331623919","text":"# @Function: 添加层\n#  @Time:2020/6/7 21:11\n# @Author:Flank\nimport tensorflow as tf\nimport numpy as np\n\n\ndef add_layer(inputs, inSize, outSize, activation_function=None):\n '''\n 添加神经层\n :param inputs:输入数据\n :param inSize:权重的size\n :param outSize:权重的size\n :param activation_function:是否有激励函数\n :return:返回该层的运算结果\n '''\n Weights = tf.Variable(tf.random_normal([inSize, outSize])) # 定义一个insize行,outSize列的矩阵\n biases = tf.Variable(tf.zeros([1, outSize]) + 0.1) # 权重和偏移在每一次训练中会修改\n Wx_plus_b = tf.matmul(inputs, Weights) + biases # 预测出来的值\n # 预测出来的值是否过激励函数\n if activation_function is None:\n outputs = Wx_plus_b\n else:\n outputs = activation_function(Wx_plus_b)\n return outputs\n\nif __name__=='__main__':\n xData=np.linspace(-1,1,10).reshape(10,1)\n noise=np.random.normal(0,0.05,)#0表示中心点,0.05表示方差\n yData=np.square(xData)-0.5+noise# 加一些噪声点,让他不是完全的抛物线来模拟真实情况\n print(xData)\n\n","sub_path":"OperateTensorFlow/Demon2.py","file_name":"Demon2.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"515400412","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nN,L = map(int,input().split(\" \"))\ncities = [list(map(int,input().split(\" \"))) for i in range(0,N)]\ncities = [[a,b-c if b - c >= 0 else 0,c-b if c-b >= 0 else 0 ] for a,b,c in cities]\n\ndef search(left,right,left_count,right_count):\n #left\n count = 0\n while cities[left%N][2] == 0 and L //2 >= count:\n left -= 1\n if cities[(left+1)%N][0] == 0:\n left_count += L - cities[left%N][0]\n else:\n left_count += cities[(left+1)%N][0] - cities[left%N][0]\n count += 1\n count = 0\n while cities[right%N][2] == 0 and L//2 >= count:\n right += 1\n if cities[right%N][0] == 0:\n right_count += L - cities[right%N-1][0]\n else:\n right_count += cities[right%N][0] - cities[right%N-1][0]\n count += 1\n \n left %= N\n right %= N\n if left_count < right_count:\n return (left,right,left,left_count,right_count,left_count)\n else:\n return (left,right,right,left_count,right_count,right_count)\n\nsum_count = 0\nfor i in range(N):\n if cities[i][1] > 0:\n left = right = i\n left_count = right_count = 0\n while cities[i][1] > 0:\n left,right,direct,left_count,right_count,count = search(left,right,left_count,right_count)\n if cities[direct][2] >= cities[i][1]:\n sum_count += count*cities[i][1]\n cities[direct][2] -= cities[i][1]\n cities[i][1] = 0\n else:\n sum_count += count*cities[direct][2]\n cities[i][1] -= cities[direct][2]\n cities[direct][2] = 0\n\n\n\nprint(sum_count)\n","sub_path":"Atcoder/dwango01/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"88734907","text":"\"\"\"\n=================== TASK 2 ====================\n* Name: Product Of Digits\n*\n* Write a script that will take an input from user\n* as integer number and display product of digits\n* for a given number. Consider that user will always\n* provide integer number.\n*\n* Note: Please describe in details possible cases\n* in which your solution might not work.\n===================================================\n\"\"\"\n\ndef proizvod_cifara(broj):\n if not isinstance(broj,int):\n return -1\n\n proizvod = 1\n\n abs_broj = abs(broj)\n while abs_broj > 0:\n cifra = abs_broj % 10\n abs_broj = abs_broj // 10\n proizvod += cifra\n return proizvod\n\ndef main():\n neki_broj = -23\n proizvod = proizvod_cifara(neki_broj)\n print(\"proizvod cifara je\", proizvod)\n\nmain()\n\n\n","sub_path":"task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"303233526","text":"import visualization.panda.world as wd\nimport modeling.geometric_model as gm\nimport modeling.collision_model as cm\nimport grasping.planning.antipodal as gpa\nimport math\nimport numpy as np\nimport basis.robot_math as rm\nimport robot_sim.robots.cobotta.cobotta as cbt\nimport manipulation.pick_place_planner as ppp\nimport motion.probabilistic.rrt_connect as rrtc\n\nbase = wd.World(cam_pos=[1.2, .7, 1], lookat_pos=[.0, 0, .15])\ngm.gen_frame().attach_to(base)\n# ground\nground = cm.gen_box(extent=[5, 5, 1], rgba=[.7, .7, .7, .7])\nground.set_pos(np.array([0, 0, -.51]))\nground.attach_to(base)\n# object holder\nobject_holder = cm.CollisionModel(\"objects/holder.stl\")\nobject_holder.set_rgba([.5,.5,.5,1])\nobject_holder_gl_pos = np.array([-.15, -.3, .0])\nobject_holder_gl_rotmat = np.eye(3)\nobgl_start_homomat = rm.homomat_from_posrot(object_holder_gl_pos, object_holder_gl_rotmat)\nobject_holder.set_pos(object_holder_gl_pos)\nobject_holder.set_rotmat(object_holder_gl_rotmat)\ngm.gen_frame().attach_to(object_holder)\nobject_holder_copy = object_holder.copy()\nobject_holder_copy.attach_to(base)\n# object holder goal\nobject_holder_gl_goal_pos = np.array([.25, -.05, .05])\nobject_holder_gl_goal_rotmat = rm.rotmat_from_euler(0, 0, -math.pi / 2)\nobgl_goal_homomat = rm.homomat_from_posrot(object_holder_gl_goal_pos, object_holder_gl_goal_rotmat)\nobject_holder_goal_copy = object_holder.copy()\nobject_holder_goal_copy.set_homomat(obgl_goal_homomat)\nobject_holder_goal_copy.attach_to(base)\n\nrobot_s = cbt.Cobotta()\n# robot_s.gen_meshmodel().attach_to(base)\nrrtc_s = rrtc.RRTConnect(robot_s)\nppp_s = ppp.PickPlacePlanner(robot_s)\n\noriginal_grasp_info_list = gpa.load_pickle_file('holder', './', 'cobg_holder_grasps.pickle')\nmanipulator_name = \"arm\"\nhand_name = \"hnd\"\nstart_conf = robot_s.get_jnt_values(manipulator_name)\nconf_list, jawwidth_list, objpose_list = \\\n ppp_s.gen_pick_and_place_motion(hnd_name=hand_name,\n objcm=object_holder,\n grasp_info_list=original_grasp_info_list,\n start_conf=start_conf,\n end_conf=start_conf,\n goal_homomat_list=[obgl_start_homomat, obgl_goal_homomat],\n approach_direction_list=[None, np.array([0, 0, -1])],\n approach_distance_list=[.2] * 2,\n depart_direction_list=[np.array([0, 0, 1]), None],\n depart_distance_list=[.2] * 2)\nrobot_attached_list = []\nobject_attached_list = []\ncounter = [0]\ndef update(robot_s,\n object_box,\n robot_path,\n jawwidth_path,\n obj_path,\n robot_attached_list,\n object_attached_list,\n counter,\n task):\n if counter[0] >= len(robot_path):\n counter[0] = 0\n if len(robot_attached_list) != 0:\n for robot_attached in robot_attached_list:\n robot_attached.detach()\n for object_attached in object_attached_list:\n object_attached.detach()\n robot_attached_list.clear()\n object_attached_list.clear()\n pose = robot_path[counter[0]]\n robot_s.fk(manipulator_name, pose)\n robot_s.jaw_to(hand_name, jawwidth_path[counter[0]])\n robot_meshmodel = robot_s.gen_meshmodel()\n robot_meshmodel.attach_to(base)\n robot_attached_list.append(robot_meshmodel)\n obj_pose = obj_path[counter[0]]\n objb_copy = object_box.copy()\n objb_copy.set_rgba([1,0,0,1])\n objb_copy.set_homomat(obj_pose)\n objb_copy.attach_to(base)\n object_attached_list.append(objb_copy)\n counter[0] += 1\n return task.again\n\ntaskMgr.doMethodLater(0.01, update, \"update\",\n extraArgs=[robot_s,\n object_holder,\n conf_list,\n jawwidth_list,\n objpose_list,\n robot_attached_list,\n object_attached_list,\n counter],\n appendTask=True)\nbase.run()\n","sub_path":"0000_examples/cobotta_ppp_animation.py","file_name":"cobotta_ppp_animation.py","file_ext":"py","file_size_in_byte":4183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"8970231","text":"# Given two strings, write a method to decide if one is a permutation of the other\n\n\ndef checkPermutation(str1, str2):\n \n if len(str1) != len(str2): # Permutations must be of same length\n return False\n\n char_set = {chr(i): 0 for i in range(128)} # Create a Hash table with ascii keys\n\n for i in str1:\n char_set[i] += 1\n \n for i in str2:\n char_set[i] -= 1\n if char_set[i] < 0:\n return False\n \n return True\n\nprint(checkPermutation(\"abcd123\", \"123abcd\"))\n\n","sub_path":"Arrays and Strings/checkPermutation.py","file_name":"checkPermutation.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"81320875","text":"from collections import OrderedDict\r\n\r\nfrom app.queries import get_users, get_username_by_user_id\r\nfrom queries import check_if_admin, get_user_id_by_username\r\nfrom flask import Blueprint\r\nfrom flask import render_template, request, url_for, redirect\r\nfrom flask.ext.login import login_required, current_user\r\n\r\nfrom app.performance_summary import s\r\nfrom app.views import admin_required\r\nfrom flask_table import Table, Col, LinkCol\r\nfrom forms import UserForm\r\nfrom queries import create_user, toggle_admin_query\r\n\r\n\r\nclass ItemTableUsers(Table):\r\n username = Col('User')\r\n admin = Col('Admin')\r\n toggle_admin = LinkCol('Toggle Admin', 'admin.toggle_admin', url_kwargs=dict(id='id'))\r\n\r\n\r\nclass ItemTableLocked(Table):\r\n name = Col('Panel')\r\n username = Col('Locked By')\r\n toggle_lock = LinkCol('Toggle Lock', 'admin.toggle_locked', url_kwargs=dict(id='id'))\r\n\r\n\r\nadmin = Blueprint('admin', __name__, template_folder='templates')\r\n\r\n\r\n@admin.route('/user', methods=['GET', 'POST'])\r\n@login_required\r\n@admin_required\r\ndef user_admin():\r\n \"\"\"\r\n view to allow users to be added and admin rights toggled\r\n\r\n :return: render html template\r\n \"\"\"\r\n form = UserForm()\r\n message = None\r\n if request.method == 'POST':\r\n username = request.form[\"name\"]\r\n if check_if_admin(s, current_user.id):\r\n create_user(s, username)\r\n message = \"Added user: \" + username\r\n else:\r\n return render_template('users.html', form=form, message=\"You can't do that\")\r\n users = get_users(s)\r\n result = []\r\n for i in users:\r\n if i.username != current_user.id:\r\n row = dict(zip(i.keys(), i))\r\n result.append(row)\r\n table = ItemTableUsers(result, classes=['table', 'table-striped'])\r\n return render_template('users.html', form=form, table=table, message=message)\r\n\r\n\r\n@admin.route('/user/toggle', methods=['GET', 'POST'])\r\n@login_required\r\n@admin_required\r\ndef toggle_admin():\r\n \"\"\"\r\n toggles admin rights of a user\r\n\r\n :return: redirect to user_admin\r\n \"\"\"\r\n user_id = request.args.get('id')\r\n toggle_admin_query(s, user_id)\r\n return redirect(url_for('admin.user_admin'))\r\n\r\n\r\n\r\n@admin.route('/logs', methods=['GET', 'POST'])\r\n@login_required\r\n@admin_required\r\ndef view_logs():\r\n \"\"\"\r\n view admin logs so that you can see what users have been doing\r\n\r\n :return: render hmtl template\r\n \"\"\"\r\n if request.args.get('file'):\r\n log = request.args.get('file')\r\n else:\r\n log = 'PanelPal.log'\r\n\r\n import glob\r\n files = []\r\n listing = glob.glob('*log*')\r\n for filename in listing:\r\n files.append(filename)\r\n\r\n result = []\r\n with open(log) as f:\r\n for line in f:\r\n result.append(line.rstrip())\r\n\r\n return render_template('logs.html', log=result, files=files)\r\n\r\n","sub_path":"app/mod_admin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"385931601","text":"# Visualizing the PCA transformation...\n\n# Dimension reduction...\n# more efficient storage and computation\n# Remove less-informative 'noise' features...\n\n\n# PCA\n\nwine.head()\nwine.iloc[:, 1:].head()\n\ndf_sample = wine[['nonflavanoid_phenols', 'od280']]\ndf_sample['nonflavanoid_phenols_10'] = df_sample['nonflavanoid_phenols'] *10 \nsamples = df_sample[['nonflavanoid_phenols_10', 'od280']].values\n\nfrom sklearn.decomposition import PCA\nmodel = PCA()\n\nmodel.fit(samples)\n\ntransformed = model.transform(samples)\n\n# Resulting PCA featrues are not linearly correlated('decorrelation')\n\nmodel.components_\n\n# loading data....\nsamples_df = pd.read_csv('./data/seeds.csv', header = None)\nsamples_df.head()\nsamples = samples_df.values\ngrains = samples_df.iloc[:, [4, 3]].values\n\nlist_1 = ['Kama wheat']*70\nlist_2 = ['Rosa wheat']*70\nlist_3 = ['Canadian wheat']*70\n\nvarieties = list_1 + list_2 + list_3\n\ndi = {'Kama wheat' : 1, 'Rosa wheat': 2, 'Canadian wheat' : 3}\nvariety_numbers = pd.DataFrame({'varieties' : varieties})['varieties'].map(di).values\n\n\n# Perform the necessary imports\nimport matplotlib.pyplot as plt\nfrom scipy.stats import pearsonr\n\n# Assign the 0th column of grains: width\nwidth = grains[:, 0]\n\n# Assign the 1st column of grains: length\nlength = grains[:, 1]\n\nplt.clf()\n# Scatter plot width vs length\nplt.scatter(width, length)\nplt.axis('equal')\nplt.show()\n\n# Calculate the Pearson correlation\ncorrelation, pvalue = pearsonr(width, length)\n\n# Display the correlation\nprint(correlation)\n\n\n# Import PCA\nfrom sklearn.decomposition import PCA\n\n# Create PCA instance: model\nmodel = PCA()\n\n# Apply the fit_transform method of model to grains: pca_features\npca_features = model.fit_transform(grains)\n\n# Assign 0th column of pca_features: xs\nxs = pca_features[:,0]\n\n# Assign 1st column of pca_features: ys\nys = pca_features[:,1]\n\nplt.clf()\n# Scatter plot xs vs ys\nplt.scatter(xs, ys)\nplt.axis('equal')\nplt.show()\n\n# Calculate the Pearson correlation of xs and ys\ncorrelation, pvalue = pearsonr(xs, ys)\n\n# Display the correlation\nprint(correlation)\n\n\n# Intrinsic dimension...\n\niris.head()\n\nsamples = iris.iloc[:, [0, 1, 3]].values\n\nfrom sklearn.decomposition import PCA\n\npca = PCA()\n\npca.fit(samples)\n\nfeatures = range(pca.n_components_)\n\npca.explained_variance_\n\nplt.clf()\nplt.bar(features, pca.explained_variance_)\nplt.xticks(features)\nplt.ylabel('variance')\nplt.xlabel('PCA feature')\n\nplt.show()\n\n# data checking...\ngrains\n\nplt.clf()\n# Make a scatter plot of the untransformed points\nplt.scatter(grains[:,0], grains[:,1])\nplt.show()\n\n# Create a PCA instance: model\nmodel = PCA()\n\n# Fit model to points\nmodel.fit(grains)\n\n# Get the mean of the grain samples: mean\nmean = model.mean_\n\n# Get the first principal component: first_pc\nfirst_pc = model.components_[0, :]\n\n# Plot first_pc as an arrow, starting at mean\nplt.arrow(mean[0], mean[1], first_pc[0], first_pc[1], color='red', width=0.01)\n\n# Keep axes on same scale\nplt.axis('equal')\nplt.show()\n\n# loading data....\n\ndf_fish = pd.read_csv('./data/fish.csv', header = None).head()\nsamples = df_fish.iloc[:, 1:].values\n\n\n# Perform the necessary imports\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import make_pipeline\nimport matplotlib.pyplot as plt\n\n# Create scaler: scaler\nscaler = StandardScaler()\n\n# Create a PCA instance: pca\npca = PCA()\n\n# Create pipeline: pipeline\npipeline = make_pipeline(scaler, pca)\n\n# Fit the pipeline to 'samples'\npipeline.fit(samples)\n\npca.n_components_\npca.explained_variance_\n\nplt.clf()\n# Plot the explained variances\nfeatures = range(5) # features = range(pca.n_components_)\nplt.bar(features, pca.explained_variance_)\nplt.xlabel('PCA feature')\nplt.ylabel('variance')\nplt.xticks(features)\nplt.show()\n\n\n# PCA(n_components=2): keep the first 2 PCA features...\n\niris_samples = iris.iloc[:, 0:4].values\n\ndi = {'setosa' : 1, 'versicolor' : 2, 'virginica' : 3} \nspecies = iris.iloc[:, 4].map(di)\n\nfrom sklearn.decomposition import PCA\npca = PCA(n_components=2)\n\npca.fit(samples)\n\ntransformed = pca.transform(samples)\n\ntransformed.shape\n\nxs = transformed[:, 0]\nys = transformed[:, 1]\n\nplt.clf()\nplt.scatter(xs, ys, c = species)\nplt.show()\n\n# Assume the high variance features are informative...\n\n## With word frequency arrays...\n\n# scipy.sparse.csr_matrix instead Numpy array...\n\n# sklearn PCA doesn't support csr_matrix..Use sklearn TruncatedSVD instead...\n\nwiki_vec = pd.read_csv('./data/wikipedia-vectors.csv', index_col=0).iloc[:, 1:]\nwiki_vec.head()\nwiki_vec.shape\n\nfrom sklearn.decomposition import TruncatedSVD\n\nmodel = TruncatedSVD(n_components=3)\n\nmodel.fit(wiki_vec)\n\ntransformed = model.transform(wiki_vec)\n\n## fish data loading...\nsamples = pd.read_csv('./data/fish.csv', header = None).iloc[:, 1:].values\n\n# Import PCA\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\n\nstandard = StandardScaler()\nscaled_samples = standard.fit_transform(samples)\n\n# Create a PCA model with 2 components: pca\npca = PCA(n_components=2)\n\n\n# Fit the PCA instance to the scaled samples\npca.fit(scaled_samples)\n\n# Transform the scaled samples: pca_features\npca_features = pca.transform(scaled_samples)\n\n# Print the shape of pca_features\nprint(pca_features.shape)\n\n\ntoy_doc = ['cats say meow', 'dogs say woof', 'dogs chase cats']\n\n# Import TfidfVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n# Create a TfidfVectorizer: tfidf\ntfidf = TfidfVectorizer()\n\n# Apply fit_transform to document: csr_mat\ncsr_mat = tfidf.fit_transform(toy_doc)\n\n# Print result of toarray() method\nprint(csr_mat.toarray())\n\n# Get the words: words\nwords = tfidf.get_feature_names()\n\n# Print words\nprint(words)\n\n\n## \n\nwiki_vec.head()\n\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.cluster import KMeans\nfrom sklearn.pipeline import make_pipeline\n\nsvd = TruncatedSVD(n_components=50)\n\n# Create a KMeans instance: kmeans\nkmeans = KMeans(n_clusters=6)\n\n# Create a pipeline: pipeline\npipeline = make_pipeline(svd, kmeans)\n\n\n# Import pandas\nimport pandas as pd\n\n# Fit the pipeline to articles\npipeline.fit(articles)\n\n# Calculate the cluster labels: labels\nlabels = pipeline.predict(articles)\n\n# Create a DataFrame aligning labels and titles: df\ndf = pd.DataFrame({'label': labels, 'article': titles})\n\n# Display df sorted by cluster label\nprint(df.sort_values('label'))\n","sub_path":"Unsupervised_Learning_in_Python/ch03_001.py","file_name":"ch03_001.py","file_ext":"py","file_size_in_byte":6342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"375987047","text":"#!/mnt/soft/python/bin/python3\n# --*-- coding: utf-8 --*--\n\"\"\"\nAuthor:zengqingnang\n\"\"\"\ntry:\n import xlrd\nexcept ImportError:\n import xlrd3 as xlrd\n\norigin_data = \"/mnt/misc/test/data/lesson/20140909总功课表.xls\"\n\n#grades = [3, 3+4, 3+4+4, 3+4+4+4, 3+4+4+4+3, 3+4+4+4+3+3]\ngrades = [3, 3+3, 3+3+3, 3+3+3+4, 3+3+3+4+4, 3+3+3+4+4+4]\nchineses = [\"\", \"一\", \"二\", \"三\", \"四\", \"五\", \"六\", \"七\", \"八\", \"九\", \"十\"]\n#lesson_range = (4, 16)\nlesson_range = (4, 16)\n#teacher_range = (17, 24)\nteacher_range = (17, 24)\nteacher_col_range = (1, 17)#教师数据所在列的范围\nPAGE_COLS = 22\nsheet = xlrd.open_workbook(origin_data).sheet_by_index(0)\n\ndef get_data():\n data = list()\n for r in range(sheet.ncols):\n data.append(sheet.col_values(r))\n return data\n\ndef get_lessons(data):\n '''\n return [[day_of_week, grade_num, class_num, class_order, lesson, teacher_order],...]\n '''\n lessons = list()\n start, stop = lesson_range\n lesson_dics = dict()\n for index, col in enumerate(data):\n day_of_week, index_in_cols = divmod(index, 22)\n class_num = -1\n grade_num = -1\n day_of_week = day_of_week + 1\n lesson_list = list()\n if index_in_cols == 0:\n continue\n for index, grade in enumerate(grades):\n if index_in_cols <= grade:\n class_num = index_in_cols\n if index != 0:\n class_num = class_num - grades[index-1]\n grade_num = index + 1\n break\n #print(\"Grade:\" + str(grade_num) + \"Class:\" + str(class_num) + \"DayOfWeek:\" + str(day_of_week))\n col_value = col[start:stop+1]\n new_col_value = list()\n for index, lesson in enumerate(col_value):\n if index == 6 and len(lesson) == 0:\n continue\n if isinstance(lesson, str):\n lesson = lesson.replace(\" \", \"\").replace(\"\\t\", \"\")\n\n new_col_value.append(lesson)\n for index, lesson in enumerate(new_col_value):\n if isinstance(lesson, str) and len(lesson) < 1:\n continue\n if index % 2 == 0:\n #print(\"G:%dC:%dL:%dCOURSE:%sT:%d\" % (grade_num, class_num, index // 2 + 1, lesson, int(new_col_value[index+1])))\n teacher_order = new_col_value[index+1] \n if isinstance(new_col_value[index+1], str) and not new_col_value[index+1].isdigit():\n if lesson=='音' and new_col_value[index+1]=='叶':\n teacher_order = 37\n elif lesson=='品' and new_col_value[index+1]=='周':\n teacher_order = 43\n print(lesson, new_col_value[index+1])\n lesson_list = [day_of_week, grade_num, class_num, index // 2 + 1, lesson, int(teacher_order)]\n lessons.append(lesson_list)\n return lessons\n\ndef get_teachers(data):\n teachers = list()\n start, stop = teacher_range\n teacher_dics = dict()\n #print(data[start:stop+1])\n content_str = \"\"\n #for col in data[:PAGE_COLS]:\n col_start, col_stop = teacher_col_range\n for col in data[col_start:col_stop+1]:\n #print(col)\n cell_values = []\n #for cell in col[start:stop+1]:\n # print(cell)\n # v = cell.replace(\" \", \"\")\n # if len(v) < 2:\n # continue\n # if v[0].isdigit():\n # index, name = v.split(\"、\")\n # if index not in teacher_dics.keys():\n # teacher_dics[int(index)] = name\n for cell in col[start:stop+1]: #根据列数据中的行数,取教师数据\n if cell == \"班子成员\":\n continue\n cell_values.append(str(cell) + \" \")\n content_str = content_str + \"\".join(cell_values)\n content_str = content_str.replace(\" \", \"\").replace(\"\\n\", \"\")\n def get_teacher_dic(content):\n '''\n 由于运用逻辑表达式进行数据的分割���较麻烦,\n 所以选取了一个比较折中的方法:\n 碰到不是数字的下一个字母是数字,则多加一个空格\n 以方便分割数据\n '''\n new_content = \"\"\n for index, c in enumerate(list(content)):\n new_content += c\n if index == len(content) - 1:\n break\n if not c.isdigit() and content[index+1].isdigit():\n new_content += \" \"\n teacher_list = new_content.split()\n teacher_dic = dict()\n for teacher in teacher_list:\n index, name = teacher.split(\"、\")\n teacher_dic[int(index)] = name\n #print(teacher_dic)\n return teacher_dic \n return get_teacher_dic(content_str)\n\n #print(content_str)\n #return teacher_dics\n\nif __name__ == '__main__':\n data = get_data() \n lessons = get_lessons(data)\n teachers = get_teachers(data)\n #print(teachers)\n #print(lessons)\n lesson_map = {\n \"信\":\"信息技术\", \n \"英\":\"英语\", \n \"实践\":\"社会实践\", \n \"地课\":\"地方课程\", \n \"语\":\"语文\", \n \"体\":\"体育\", \n \"学\":\"学课\",\n \"美\":\"美术\", \n \"科\":\"科学\", \n \"数\":\"数学\", \n \"音\":\"音乐\", \n \"地\":\"地学\", \n \"研\":\"研究性学习\", \n \"劳技\":\"劳动技术\", \n \"品生\":\"品德与生活\", \n \"品\":\"品德与社会\",\n \"综1\": \"研究性学习\",\n \"综2\": \"劳技\",\n \"综3\": \"社团\",\n \"综4\": \"社团\",\n \"综\": \"综合实践\",\n }\n lesson_set = set()#all lessons\n\n\n\n #CREATE DBS\n import sqlite3\n conn = sqlite3.connect(\"lesson.sqlite3\")\n cursor = conn.cursor()\n '''\n sql = \"select teacher_id from lesson_records where day_of_week=4 and lesson_order=4;\"\n cursor.execute(sql)\n\n in_teachers = list()\n for t in cursor:\n in_teachers.append(t[0])\n print(in_teachers)\n\n teachers_sql = \"select id, name from teachers;\"\n cursor.execute(teachers_sql)\n for t in cursor:\n if t[0] not in in_teachers:\n print(t)\n\n import sys\n sys.exit(0)\n '''\n db_teachers_schema = '''\n create table if not exists teachers (id INTEGER, name text);'''\n db_lessons_schema = '''\n create table if not exists lessons (id INTEGER, name text);'''\n db_lesson_records_schema = '''\n create table if not exists lesson_records (day_of_week INTEGER, grade INTEGER, cls INTEGER, lesson_order INTEGER, lesson text, teacher_id INTEGER);\n '''\n for db_schema in [db_teachers_schema, db_lessons_schema, db_lesson_records_schema]:\n cursor.execute(db_schema)\n conn.commit()\n\n '''Init TABLE teachers'''\n #teachers[27] = \"池若如\"\n for teacher_id, teacher_name in teachers.items():\n insert_sql = \"insert into teachers values(\\\"%d\\\", \\\"%s\\\")\" % (teacher_id, teacher_name)\n cursor.execute(insert_sql)\n conn.commit()\n #-CREATE DBS\n\n for lesson in lessons:\n day_of_week, grade, cls, lesson_order, lesson, teacher = lesson\n lesson_set.add(lesson)\n\n #INSERT INTO lesson_records\n insert_sql = \"insert into lesson_records values(\\\"%d\\\",\\\"%d\\\",\\\"%d\\\",\\\"%d\\\",\\\"%s\\\",\\\"%d\\\")\" % (day_of_week, grade, cls, lesson_order, lesson_map[lesson], teacher)\n cursor.execute(insert_sql)\n #-INSERT INTO lesson_records\n\n if teacher not in teachers.keys():\n if teacher == 27:\n teacher = \"池若如\"\n else:\n teacher = \"Unknow\" + str(teacher)\n else:\n teacher = teachers[teacher]\n output = \"星期%d %d(%d)班第%d节课:%s老师:%s\" % (day_of_week, grade, cls, lesson_order, lesson_map[lesson], teacher)\n\n #print(output)\n conn.commit()\n\n conn.close()\n","sub_path":"get_school_lessones.py","file_name":"get_school_lessones.py","file_ext":"py","file_size_in_byte":7824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"288699007","text":"\"\"\"init tables\n\nRevision ID: 70a93e1b09ac\nRevises: 72599df16b50\nCreate Date: 2019-12-17 14:50:43.408318\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = '70a93e1b09ac'\ndown_revision = '72599df16b50'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('tp_hotel_near_site',\n sa.Column('create_time', sa.DateTime(), nullable=True),\n sa.Column('update_time', sa.DateTime(), nullable=True),\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('site_name', sa.String(length=500), nullable=True),\n sa.Column('site_distance', sa.String(length=500), nullable=True),\n sa.Column('hotel_id', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.drop_table('tp_hotel_repast_product')\n op.add_column('tp_hotel', sa.Column('desc_pic', sa.String(length=500), nullable=True))\n op.add_column('tp_hotel', sa.Column('eng_name', sa.String(length=500), nullable=True))\n op.add_column('tp_hotel', sa.Column('name', sa.String(length=500), nullable=True))\n op.add_column('tp_hotel', sa.Column('start_level', sa.Integer(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('tp_hotel', 'start_level')\n op.drop_column('tp_hotel', 'name')\n op.drop_column('tp_hotel', 'eng_name')\n op.drop_column('tp_hotel', 'desc_pic')\n op.create_table('tp_hotel_repast_product',\n sa.Column('create_time', mysql.DATETIME(), nullable=True),\n sa.Column('update_time', mysql.DATETIME(), nullable=True),\n sa.Column('id', mysql.INTEGER(display_width=11), autoincrement=True, nullable=False),\n sa.Column('desc', mysql.VARCHAR(collation='utf8mb4_cs_0900_as_cs', length=500), nullable=True),\n sa.Column('hotel_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True),\n sa.PrimaryKeyConstraint('id'),\n mysql_collate='utf8mb4_cs_0900_as_cs',\n mysql_default_charset='utf8mb4',\n mysql_engine='InnoDB'\n )\n op.drop_table('tp_hotel_near_site')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/70a93e1b09ac_init_tables.py","file_name":"70a93e1b09ac_init_tables.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"53524157","text":"import random\n\n\nclass Set():\n def __init__(self):\n self.prizelist = [] # 전체 상품리스트\n self.secondprize = [] # 2등 추첨번호를 담을 리스트\n for length in range(1,101):\n self.prizelist.append(length) # 상품리스트에 1에서 100까지 요소 추가\n\n self.firstprize = self.prizelist.pop(random.randint(0,99)) # 전체상품리스트에서 랜덤자리의 인덱스를 빼와서 firstprize변수에 대입\n for a in range(5): # 5번 반복\n self.secondprize.append(self.prizelist.pop(random.randint(0,len(self.prizelist)-1))) # 전체상품리스트에서 랜덤자리의 인덱스 5개를 빼와서 2등리스트에 요소로 추가한다\n self.prizelist.append(self.firstprize) # 전체상품리스트에서 빼왓던 firstprize의값을 전체상품리스트에 다시 넣는다\n\n for _add in self.secondprize: # 2등 리스트의 각 요소들을 _add에 담고 코드블럭의 코드 실행\n self.prizelist.append(_add) # _add의 값을 전체상품리스트에 다시 넣는다\n\n def bbobgi(self):\n pass\n\nprize = Set()\n\nwhile True:\n select = input(\n\"\"\"\n=====================\n1. 뽑기\n2. 나가기\n=====================\n\"\"\")\n if select == \"1\":\n me_pick = prize.prizelist.pop(random.randint(0,len(prize.prizelist)))\n print(\"뽑으신 추첨번호는 {}번 입니다\".format(me_pick))\n select = input(\"\"\"결과를확인하시려면 아무키나 눌러주세요\"\"\")\n if select:\n if me_pick == prize.firstprize:\n print(\"축하합니다 1등 자동차에 당첨되셨습니다\")\n elif me_pick in prize.secondprize:\n print(\"축하합니다 2등 냉장고에 당첨되셨습니다\")\n else:\n print(\n\"\"\"\n=====================\n당첨되지 않았습니다. 뽑으신 추첨번호는 [{2}]번 입니다\n당첨 번호는 1등 [{0}]번 2등 {1}번입니다\n=====================\n\"\"\".format(prize.firstprize,prize.secondprize,me_pick)\n)\n elif select == \"2\":\n print(\"종료합니다\")\n break\n select = input(\n\"\"\"\n=====================\n1.다시뽑기\n2.초기화하기\n=====================\n\"\"\")\n if select == \"1\":\n print(\"남아있는 추첨권은 {}개 입니다\".format(len(prize.prizelist)))\n continue\n elif select == \"2\":\n prize = Set()\n print(\"뽑기가 초기화 되었습니다\")\n continue\n\n\n\n\n","sub_path":"team-akatsuki/kwontj/prize.Kwontj_20200813.py","file_name":"prize.Kwontj_20200813.py","file_ext":"py","file_size_in_byte":2494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"610800387","text":"# N = int(input())\n# lefts = [0] * N\n# heights = [0] * N\n# area = 0\n\n# for i in range(N):\n# lefts[i], heights[i] = map(int, input().split())\n# highest = max(heights)\n# temp_h = ''.join([str(i) for i in heights])\n# l_end = lefts[temp_h.find(str(highest))]\n# r_end = lefts[temp_h.rfind(str(highest))]\n\n# if l_end == r_end:\n# base = 1\n# else:\n# base = r_end - l_end + 1\n\n# base_l = lefts[0]\n# base_r = lefts[-1]\n# idx = 1\n# prevh_l = heights[0]\n# prevh_r = heights[-1]\n\n# while heights[idx] <= highest:\n# if heights[idx] == highest or heights[idx-1] == highest:\n# idx += 1\n# break\n# elif heights[idx] > prevh_l:\n# base_l = lefts[idx] - base_l\n# area += base_l * prevh_l\n# base_l = lefts[idx]\n# prevh_l = heights[idx]\n# idx += 1\n# else:\n# idx += 1\n# continue\n\n# idx = -2\n\n# while heights[idx] <= highest:\n# if heights[idx] == highest or heights[idx+1] == highest:\n# break\n# elif heights[idx] > prevh_r:\n# base_r = base_r - lefts[idx]\n# area += base_r * prevh_r\n# base_r = lefts[idx]\n# prevh_r = heights[idx]\n# else:\n# continue\n# idx -= 1\n\n# area += base * highest\n\n# print(area)\n\n# N = int(input())\n# area = 0\n# temp = []\n\n# for i in range(N):\n# inp = tuple(map(int, input().split()))\n# temp.append(inp)\n# temp.sort(key=lambda x:x[0]) \n# # print(temp)\n# loc = [a[0] for a in temp]\n# h = [b[1] for b in temp]\n# # print(loc, h)\n# highest = max(h)\n# loc2 = loc[::-1]\n# h2 = h[::-1]\n\n# i = 0\n# temploc = loc[0]\n# temph = h[0]\n# while i < h.index(highest):\n# if i == 0:\n# pass\n# elif h[i] > h[i-1]:\n# area += temph * (loc[i] - temploc)\n# temploc = loc[i]\n# temph = h[i]\n# i += 1\n\n# j = 0\n# temploc2 = loc2[0]\n# temph2 = h2[0]\n# while j < h2.index(highest):\n# if j == 0:\n# pass\n# elif h2[j] > h2[j-1]:\n# area += temph2 * (temploc2 - loc[j])\n# temploc2 = loc2[j]\n# temph2 = h2[j]\n# j += 1\n\n# if h.count(highest) > 1:\n# area += (loc2[h2.index(highest)] - loc[h.index(highest)] + 1) * highest\n# else:\n# area += highest\n\n# print(area)\n\n\n# N = int(input())\n# whole = []\n# for _ in range(N):\n# temp = tuple(map(int, input().split()))\n# whole.append(temp)\n# whole.sort(key=lambda x: x[0])\n# base = whole[-1][0] - whole[0][0] + 1\n# h = [i[1] for i in whole]\n# l_lst = [i[0] for i in whole]\n# r_lst = l_lst[::-1]\n# maxh = max(h)\n\n# i = 0\n# temph = min(h)\n# while temph < maxh:\n\n# N = int(input())\n# whole = []\n# for _ in range(N):\n# temp = tuple(map(int, input().split()))\n# whole.append(temp)\n# whole.sort(key=lambda x:x[0])\n# h = [i[1] for i in whole]\n# std = h.index(max(h))\n\ndef Loc(lst, k):\n return lst[k][0]\n\nN = int(input())\nraw = []\narea = 0\n\nfor i in range(N):\n temp = tuple(map(int, input().split()))\n raw.append(temp)\nraw.sort(key=lambda x: x[0])\n\nh = [i[1] for i in raw]\n\nmaxh = max(h)\nmax_idx = h.index(maxh)\n# max_loc = Loc(raw, max_idx)\n\ntempidx = 0\nfor i in range(1, max_idx + 1):\n if h[tempidx] <= h[i]: ## 바꾼부분 ('='추가)\n area += (Loc(raw, i) - Loc(raw, tempidx)) * h[tempidx]\n tempidx = i\n\nif h.count(maxh) >= 2:\n while tempidx != len(h) and h[tempidx] == maxh:\n tempidx += 1\n rmax_idx = tempidx -1\n area += (Loc(raw, rmax_idx) - Loc(raw, max_idx) + 1) * maxh\nelse:\n rmax_idx = tempidx\n area += maxh\n\ntempidx = -1\nfor j in range(-2, rmax_idx - len(h) -1, -1):\n if h[j] >= h[tempidx]:\n area += (Loc(raw, tempidx) - Loc(raw, j)) * h[tempidx]\n tempidx = j\n\nprint(area)\n\n# print(h)\n# print(raw)\n\n# 인덱스를 고려해야 하는 경우가 많아서 모든 케이스를 집어내기 힘들었다\n# ==> 시점, 종점, 최대 값을 가지는 점.\n\n# N = int(input())\n# raw = []\n# area = 0\n# for i in range(N):\n# temp = tuple(map(int, input().split()))\n# raw.append(temp)\n# raw.sort(key=lambda x: x[0])\n\n# maxidx = raw.index(max(raw, key=lambda x: x[1]))\n\n# lmaxidx = maxidx\n# while lmaxidx >= 0:\n \n\n\n# # print(maxidx)\n# # print(raw)","sub_path":"python/bojprobs/swtest_pdf_list/int6_2304.py","file_name":"int6_2304.py","file_ext":"py","file_size_in_byte":4098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"106122018","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Mar 8 11:10:12 2020\r\n\r\n@author: mrudula\r\n\"\"\"\r\n\r\n#Write a program to check whether character is an alphabet or not using conditional operator.\r\n\r\nch=input(\"enter any alphabet\")\r\nif((ch>='a' and ch<='z') or (ch>='A' and ch<='Z')):\r\n print(ch,\"is an alphabet.\");\r\nelse:\r\n print(ch,\"is not an alphabet.\");\r\n \r\n \r\n \r\n","sub_path":"2nd assign/alphate character, 116.py","file_name":"alphate character, 116.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"146761601","text":"import itertools, collections, math\n\n\n\"\"\"\nTLE\n\nO(n^2) time and space in constructor\nO(1) call to shortest()\n\nFor Online Judge, too costly to pre-compute all results\n\nI was not the only one mislead by problem statement\n\nhttps://leetcode.com/problems/shortest-word-distance-ii/discuss/67035/Why-a-O(n2)-preprocessing-time-while-O(1)-for-shortest-not-a-good-idea\nleetcode.com/problems/shortest-word-distance-ii/discuss/67035/Why-a-O(n2)-preprocessing-time-while-O(1)-for-shortest-not-a-good-idea/69074\nleetcode.com/problems/shortest-word-distance-ii/discuss/67035/Why-a-O(n2)-preprocessing-time-while-O(1)-for-shortest-not-a-good-idea/69073\n\"\"\"\nclass WordDistance:\n\n def __init__(self, words):\n \"\"\"\n :type words: List[str]\n \"\"\"\n def helper(a, b):\n i = j = 0\n res = math.inf\n while i < len(a) and j < len(b):\n res = min(res, abs(a[i] - b[j]))\n if a[i] < b[j]:\n i += 1\n else:\n j += 1\n return res\n self.answers = {}\n word_to_idxs = collections.defaultdict(list)\n for i, w in enumerate(words):\n word_to_idxs[w].append(i)\n keys = list(word_to_idxs.keys())\n keys.sort()\n for i in range(len(keys) - 1):\n for j in range(i + 1, len(keys)):\n k1, k2 = keys[i], keys[j]\n # print(\"{} {}\".format(k1, k2))\n self.answers[(k1, k2)] = helper(word_to_idxs[k1], word_to_idxs[k2])\n\n def shortest(self, word1, word2):\n \"\"\"\n :type word1: str\n :type word2: str\n :rtype: int\n \"\"\"\n if word1 > word2:\n word1, word2 = word2, word1\n return self.answers[(word1, word2)]\n\n\"\"\"\nACE\n\nO(n) time and space in constructor\n\nO(a + b) time in shortest where a, b are lengths\n\nhttps://leetcode.com/problems/shortest-word-distance-ii/discuss/67028/Java-Solution-using-HashMap\n\"\"\"\nclass WordDistance:\n\n def __init__(self, words):\n \"\"\"\n :type words: List[str]\n \"\"\"\n self.word_to_idxs = collections.defaultdict(list)\n for i, w in enumerate(words):\n self.word_to_idxs[w].append(i)\n\n def shortest(self, word1, word2):\n \"\"\"\n :type word1: str\n :type word2: str\n :rtype: int\n\n \"In shortest( ) function, since list1 (size n) and list2 (size m) are\n sorted already, we can use the idea of merge sort and perform the\n comparison in O(n + m) time, rather than O(n * m).\"\n\n leetcode.com/problems/shortest-word-distance-ii/discuss/67028/Java-Solution-using-HashMap/69065\n \"\"\"\n a, b = self.word_to_idxs[word1], self.word_to_idxs[word2]\n i = j = 0\n res = math.inf\n while i < len(a) and j < len(b):\n res = min(res, abs(a[i] - b[j]))\n if a[i] < b[j]:\n i += 1\n else:\n j += 1\n return res\n\n\nif __name__ == '__main__':\n tests = [\n (\n [\"practice\", \"makes\", \"perfect\", \"coding\", \"makes\"],\n [\n (\"coding\", \"practice\", 3),\n (\"makes\", \"coding\", 1)\n ],\n )\n ]\n for words, subtests in tests:\n obj = WordDistance(words)\n for word1, word2, exp in subtests:\n res = obj.shortest(word1, word2)\n print(\"{}, {} : {}\".format(word1, word2, exp))\n assert res == exp\n\n","sub_path":"244_shortest_word_distance_ii.py","file_name":"244_shortest_word_distance_ii.py","file_ext":"py","file_size_in_byte":3457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"571461983","text":"import matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nimport glob\nimport time\nfrom sklearn.svm import LinearSVC\nfrom sklearn.preprocessing import StandardScaler\nfrom skimage.feature import hog\nfrom scipy.ndimage.measurements import label\nfrom sklearn.cross_validation import train_test_split\nimport pickle\nimport os.path\nfrom collections import deque\n\nclass Detector():\n def __init__(self, svc, window):\n self.svc = svc\n self.heatmaps = deque(maxlen = window) \n\n def add_heat(self, heatmap, bbox_list):\n # Iterate through list of bboxes\n for box in bbox_list:\n # Add += 1 for all pixels inside each bbox\n # Assuming each \"box\" takes the form ((x1, y1), (x2, y2))\n heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += 1\n\n # Return updated heatmap\n return heatmap# Iterate through list of bboxes\n \n def apply_threshold(self, heatmap, threshold):\n # Zero out pixels below the threshold\n heatmap[heatmap <= threshold] = 0\n # Return thresholded map\n return heatmap\n\n def draw_labeled_bboxes(self, img, labels):\n # Iterate through all detected cars\n for car_number in range(1, labels[1]+1):\n # Find pixels with each car_number label value\n nonzero = (labels[0] == car_number).nonzero()\n # Identify x and y values of those pixels\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n # Define a bounding box based on min/max x and y\n bbox = ((np.min(nonzerox), np.min(nonzeroy)), (np.max(nonzerox), np.max(nonzeroy)))\n # Draw the box on the image\n cv2.rectangle(img, bbox[0], bbox[1], (0,0,255), 6)\n # Return the image\n return img\n\n def draw_boxes(self, img, bboxes, color=(0, 0, 255), thick=6):\n # Make a copy of the image\n imcopy = np.copy(img)\n # Iterate through the bounding boxes\n for bbox in bboxes:\n # Draw a rectangle given bbox coordinates\n cv2.rectangle(imcopy, bbox[0], bbox[1], color, thick)\n # Return the image copy with boxes drawn\n return imcopy\n\n def find_cars(self, img, ystart_stop, color, scale, svc, X_scaler, orient, pix_per_cell, cell_per_block, hist_bins, channel):\n \n draw_img = np.copy(img)\n img = img.astype(np.float32)/255\n\n ystart = ystart_stop[0]\n ystop = ystart_stop[1]\n \n img_tosearch = img[ystart:ystop,:,:]\n ctrans_tosearch = self.svc.convert_color(img_tosearch, color_space=color)\n if scale != 1:\n imshape = ctrans_tosearch.shape\n ctrans_tosearch = cv2.resize(ctrans_tosearch, (np.int(imshape[1]/scale), np.int(imshape[0]/scale)))\n \n # Define blocks and steps as above\n nxblocks = (ctrans_tosearch[:,:,0].shape[1] // pix_per_cell) - cell_per_block + 1\n nyblocks = (ctrans_tosearch[:,:,0].shape[0] // pix_per_cell) - cell_per_block + 1 \n nfeat_per_block = orient*cell_per_block**2\n \n # 64 was the orginal sampling rate, with 8 cells and 8 pix per cell\n window = 64\n nblocks_per_window = (window // pix_per_cell) - cell_per_block + 1\n cells_per_step = 2 # Instead of overlap, define how many cells to step\n nxsteps = (nxblocks - nblocks_per_window) // cells_per_step\n nysteps = (nyblocks - nblocks_per_window) // cells_per_step\n \n # Compute individual channel HOG features for the entire image\n\n hogs = []\n if channel == 'ALL':\n for ch in range(ctrans_tosearch.shape[2]):\n hogs.append(self.svc.get_hog_features(ctrans_tosearch[:,:,ch], orient, pix_per_cell, cell_per_block, feature_vec=False)) \n else:\n hogs.append(self.svc.get_hog_features(ctrans_tosearch[:,:,channel], orient, pix_per_cell, cell_per_block, feature_vec=False)) \n \n detections = []\n for xb in range(nxsteps):\n for yb in range(nysteps):\n ypos = yb*cells_per_step\n xpos = xb*cells_per_step\n # Extract HOG for this patch\n\n hog_features = []\n for h in hogs:\n hog_features.extend(h[ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel())\n\n xleft = xpos*pix_per_cell\n ytop = ypos*pix_per_cell\n\n # Extract the image patch\n subimg = cv2.resize(ctrans_tosearch[ytop:ytop+window, xleft:xleft+window], (64,64))\n \n # Get color features\n hist_features = self.svc.color_hist(subimg, nbins=hist_bins)\n\n # Scale features and make a prediction\n test_features = X_scaler.transform(np.hstack((hist_features, hog_features)).reshape(1, -1)) \n test_prediction = svc.predict(test_features)\n \n if test_prediction == 1:\n xbox_left = np.int(xleft*scale)\n ytop_draw = np.int(ytop*scale)\n win_draw = np.int(window*scale)\n rect_box = (xbox_left, ytop_draw+ystart),(xbox_left+win_draw,ytop_draw+win_draw+ystart)\n # cv2.rectangle(draw_img,rect_box,(0,0,255),6) \n detections.append(rect_box) \n \n return detections\n\n def overlay_detection(self, image, debug=False):\n windows = []\n boxes = []\n for scale in self.svc.params['scales']:\n boxes.extend(self.find_cars(image, self.svc.params['y_start_stop'], self.svc.params['color_space'], scale, self.svc.svc, \n self.svc.X_scaler, self.svc.params['orient'], self.svc.params['pix_per_cell'], self.svc.params['cell_per_block'], \n self.svc.params['hist_bins'], self.svc.params['hog_channel']))\n\n heat = np.zeros_like(image[:,:,0]).astype(np.float)\n heat = self.add_heat(heat,boxes) \n\n self.heatmaps.append(heat) \n combined = np.sum(self.heatmaps, axis = 0)\n\n heat = self.apply_threshold(combined, self.svc.params['heat_threshold'])\n heatmap = np.clip(heat, 0, 255)\n \n labels = label(heatmap)\n draw_img = self.draw_labeled_bboxes(np.copy(image), labels)\n\n if debug:\n raw_boxes = self.draw_boxes(image, boxes, color=(0, 0, 255), thick=6) \n return raw_boxes, heatmap, draw_img\n\n return draw_img","sub_path":"detector.py","file_name":"detector.py","file_ext":"py","file_size_in_byte":6564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"646265737","text":"# 정확성 풀이\n\nfrom itertools import cycle\n\n\ndef solution(food_times, k):\n index_array = cycle([i for i in range(len(food_times))])\n done = False\n counter = 0\n while done is False:\n index = next(index_array)\n if sum(food_times) == 0:\n return -1\n if food_times[index] > 0:\n counter += 1\n food_times[index] -= 1\n done = True if counter == k + 1 else False\n return index + 1\n\n\nprint(solution([3, 1, 2], 5))\n","sub_path":"Greedy/실전문제/무지의 먹방 라이브.py","file_name":"무지의 먹방 라이브.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"238422546","text":"\nfrom PIL import Image\nim = Image.open(\"image.png\")\n\n# create palette from raw data\n# colours: Red, Green, Blue, Black, and White (5 total)\nRGBBW = [(255,0,0), (0,255,0), (0,0,255), (0,0,0), (255,255,255)]\ndata = sum([list(x) for x in RGBBW], [])[:256]\npimg = Image.new(\"P\",(16,16))\npimg.putpalette(data)\n\n\nim.convert(\"RGB\")\ncim_ = im.im.convert(\"P\", 0, pimg.im)\ncim = im._new(cim_).convert(\"RGB\")\n\ndef colors(im):\n cs = []\n for x in range(im.width):\n for y in range(im.height):\n cs.append(im.getpixel((x,y)))\n return list(set(cs))\n\nprint(\"Original: %s\" % colors(im))\nprint(\"Palette: %s\" % RGBBW)\nprint(\"Convert: %s\" % colors(cim))\n\ndef scopecreep(im,pal):\n creep = []\n cs = colors(im)\n for c in cs:\n if c not in pal:\n creep.append(c)\n\n return list(set((creep)))\n\nprint(scopecreep(cim, RGBBW))\n","sub_path":"2019_05_PyConUS.podium/scripts/so.py","file_name":"so.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"247044692","text":"import turtle \n\nclass SierpinskiCarpet:\n\n def __init__(self, baseLength=400, levels=5, bgcolor='black', pencolor='green'):\n self.baseLength = baseLength\n self.levels = levels\n self.bgcolor = bgcolor\n self.pencolor = pencolor\n\n self.t = turtle.Pen()\n screen = self.t.getscreen()\n screen.bgcolor(self.bgcolor)\n self.t.color(self.pencolor)\n self.t.speed(0)\n self.resetPos((-200,200))\n\n def resetPos(self, coordinates):\n self.t.up()\n self.t.setpos(coordinates[0], coordinates[1])\n self.t.down()\n\n def endThis(self):\n turtle.done()\n\n def drawSquare(self, coordinates, length):\n self.resetPos(coordinates)\n self.t.heading = 0\n self.t.begin_fill()\n for i in range (0,4):\n self.t.forward(length)\n self.t.right(90) \n self.t.end_fill()\n\n def iterate(self, coordinates, level):\n if level > self.levels:\n return\n innerLength = self.baseLength/(3**level)\n inner_x = coordinates[0]+innerLength\n inner_y = coordinates[1]-innerLength\n self.drawSquare((inner_x, inner_y), innerLength)\n\n for i in range(0,3):\n for j in range(0,3):\n if (i!=1) or (j!=1):\n new_x = coordinates[0]+i*innerLength\n new_y = coordinates[1]-j*innerLength\n self.iterate((new_x, new_y), level+1)\n\n\n def display(self):\n leftCorner = (-200, 200)\n self.resetPos(leftCorner)\n self.t.color(self.pencolor)\n self.t.begin_fill()\n for i in range(0, 4):\n self.t.forward(self.baseLength)\n self.t.right(90)\n self.t.end_fill()\n self.t.color(self.bgcolor)\n self.iterate(leftCorner, 1)\n self.endThis()\n\nif __name__ == '__main__':\n s = SierpinskiCarpet()\n s.display()","sub_path":"generative/SierpinskiCarpet.py","file_name":"SierpinskiCarpet.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"163698466","text":"\n\nimport pandas as pd\nfrom nltk.tokenize import WordPunctTokenizer\nimport re\nfrom nltk.corpus import stopwords\nfrom nltk.stem.wordnet import WordNetLemmatizer\nimport emoji\n\n \n\n\ndataset=pd.read_csv(\"C:/Users/nEW u/Documents/GitHub/project_data/netflix_extracted_csv.csv\",encoding='utf-8')\n\ntoken=WordPunctTokenizer()\npart1=r'@[A-Za-z0-9]+'\npart2=r'https?://[_A-Za-z0-9./]+'\npart3=r'http?://[_A-Za-z0-9./]+'\ncombine=r'|'.join((part1,part2,part3))\n\ndef clean_tweets(tweet):\n #soup=BeautifulSoup(tweet,'html.parser')\n #souped=soup.get_text()\n clean_emoji=emoji.demojize(tweet)\n stripped=re.sub(combine,'',clean_emoji)\n # text= \"\".join([char for char in stripped if char not in string.punctuation])\n lower_case=stripped.lower()\n tweets=re.sub('[^a-zA-Z]',' ',lower_case)\n tweets=tweets.strip('rt')\n #print(tweets)\n tweets=tweets.split()\n lem=WordNetLemmatizer()\n #print(tweets)\n lemma=[lem.lemmatize(word) for word in tweets if not word in set(stopwords.words('english'))]\n lemma=\" \".join(lemma)\n #print(root)\n return(lemma)\n \ntwitter_data=[]\nfor tweet in dataset.text:\n twitter_data.append(clean_tweets(tweet))\n \ncleaned_netflix_tweets=pd.DataFrame(twitter_data)\ncleaned_netflix_tweets.to_csv(\"C:/Users/nEW u/Documents/GitHub/project_data/cleaned_netflix_tweets.csv\")\n ","sub_path":"netflix_preprocessing.py","file_name":"netflix_preprocessing.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"400944369","text":"import os\r\nimport glob\r\nimport platform\r\nimport maya.cmds as cmds\r\nimport rgb.utils.ffmpeg as ffmpeg\r\n\r\n\r\ndef playblast(filename=None):\r\n pb = cmds.playblast(viewer=0)\r\n\r\n # Hack because Maya doesnt return the entire filename\r\n file_dir = os.path.dirname(pb)\r\n pb_path = glob.glob(os.path.join(file_dir, pb + '*'))\r\n if pb_path:\r\n pb_path = pb_path[0]\r\n else:\r\n raise RuntimeError('Can not find file on filesystem')\r\n \r\n if not filename:\r\n transcoded_file = transcoded_path(pb_path)\r\n else:\r\n name, extension = os.path.splitext(pb_path)\r\n transcoded_file = os.path.join(file_dir, str(filename) + extension)\r\n \r\n ffmpeg.transcode_h264(pb_path, transcoded_file)\r\n return transcoded_file\r\n\r\n\r\ndef transcoded_path(orig_path):\r\n path, whole_name = os.path.split(orig_path)\r\n name, ext = whole_name.split('.')\r\n user_platform = platform.system().lower()\r\n if user_platform == 'windows':\r\n return path + '\\\\' + name + '_h264.' + ext\r\n return path + '/' + name + '_h264.' + ext\r\n\r\n","sub_path":"rgbnotes/scripts/rgb/tools/playblast/playblast.py","file_name":"playblast.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"342419683","text":"import unittest\nimport csv\nimport os\nfrom palindrome import Palindrome\n\n\nclass PalindromeTestCase(unittest.TestCase):\n csv_file = 'testing.csv'\n\n def setUp(self):\n self.Palindrome = Palindrome(self.csv_file)\n\n def tearDown(self):\n if os.path.isfile(self.csv_file):\n os.remove(self.csv_file)\n\n def test_smallest_base_values_special(self):\n # Test that the special case of integers 1 and 2 return the correct result\n self.assertEqual(2, self.Palindrome.get_smallest_palindrome_base(1))\n self.assertEqual(3, self.Palindrome.get_smallest_palindrome_base(2))\n\n def test_smallest_base_values_small_numbers(self):\n # Test that the smaller values return the correct result\n self.assertEqual(2, self.Palindrome.get_smallest_palindrome_base(3))\n self.assertEqual(3, self.Palindrome.get_smallest_palindrome_base(4))\n self.assertEqual(2, self.Palindrome.get_smallest_palindrome_base(5))\n self.assertEqual(5, self.Palindrome.get_smallest_palindrome_base(6))\n self.assertEqual(2, self.Palindrome.get_smallest_palindrome_base(7))\n self.assertEqual(3, self.Palindrome.get_smallest_palindrome_base(8))\n self.assertEqual(2, self.Palindrome.get_smallest_palindrome_base(9))\n self.assertEqual(3, self.Palindrome.get_smallest_palindrome_base(10))\n\n def test_smallest_base_values_large_numbers(self):\n # Test that some of the larger values return the correct result\n self.assertEqual(2, self.Palindrome.get_smallest_palindrome_base(15))\n self.assertEqual(5, self.Palindrome.get_smallest_palindrome_base(18))\n self.assertEqual(18, self.Palindrome.get_smallest_palindrome_base(19))\n self.assertEqual(3, self.Palindrome.get_smallest_palindrome_base(20))\n\n def test_base_values(self):\n # Test that the given integer is represented in the base values appropriately from base 2 to base N - 1\n def base_array_equality_check(number, ans_array):\n for i, value in enumerate(self.Palindrome.get_base_values(number)):\n self.assertEqual(ans_array[i], value)\n\n ans_array = [[1, 1]]\n base_array_equality_check(3, ans_array)\n ans_array = [[1, 0, 0], [1, 1]]\n base_array_equality_check(4, ans_array)\n ans_array = [[1, 0, 1], [1, 2], [1, 1]]\n base_array_equality_check(5, ans_array)\n ans_array = [[1, 1, 0], [2, 0], [1, 2], [1, 1]]\n base_array_equality_check(6, ans_array)\n ans_array = [[1, 1, 1], [2, 1], [1, 3], [1, 2], [1, 1]]\n base_array_equality_check(7, ans_array)\n ans_array = [[1, 0, 0, 0], [2, 2], [2, 0], [1, 3], [1, 2], [1, 1]]\n base_array_equality_check(8, ans_array)\n ans_array = [[1, 0, 0, 1], [1, 0, 0], [2, 1], [1, 4], [1, 3], [1, 2], [1, 1]]\n base_array_equality_check(9, ans_array)\n ans_array = [[1, 0, 1, 0], [1, 0, 1], [2, 2], [2, 0], [1, 4], [1, 3], [1, 2], [1, 1]]\n base_array_equality_check(10, ans_array)\n\n def test_is_palindrome(self):\n # Test that the is_palindrome function works appropriately\n self.assertTrue(self.Palindrome.is_palindrome([1, 1]))\n self.assertTrue(self.Palindrome.is_palindrome([1, 2, 1]))\n self.assertTrue(self.Palindrome.is_palindrome([2, 2]))\n self.assertFalse(self.Palindrome.is_palindrome([1, 0]))\n self.assertFalse(self.Palindrome.is_palindrome([1, 2]))\n\n def test_print_file(self):\n # Test that the print_palindrome_bases actually creates a file\n self.Palindrome.print_palindrome_bases(1, 20)\n self.assertTrue(os.path.isfile(self.csv_file))\n\n def test_print_out(self):\n # Test that the print_palindrome_bases function outputs a file with values and that the values are correct\n self.Palindrome.print_palindrome_bases(1, 20)\n ans_array = [\n [\"decimal\", \"smallest base in which the number is a palindrome\"],\n [1, 2], [2, 3], [3, 2], [4, 3], [5, 2],\n [6, 5], [7, 2], [8, 3], [9, 2], [10, 3],\n [11, 10], [12, 5], [13, 3], [14, 6], [15, 2],\n [16, 3], [17, 2], [18, 5], [19, 18], [20, 3]]\n\n with open(self.csv_file, 'r') as csvfile:\n csv_dict = [row for row in csv.DictReader(csvfile)]\n self.assertNotEqual(0, len(csv_dict))\n\n reader = csv.reader(csvfile)\n for i, row in enumerate(reader):\n self.assertEquals(ans_array[i], row)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"Telnyx/palindrome_unit_tests.py","file_name":"palindrome_unit_tests.py","file_ext":"py","file_size_in_byte":4569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"500059780","text":"import urllib\nimport re\nimport json\nfrom random import choice\nfrom scrapy.spiders import Spider\nfrom scrapy.http import FormRequest\nfrom scrapy import Request\n\nfrom .lib import lib_parse_subject_detail\n\nclass DoubanDocumentarySubject(Spider):\n\n def __init__(self, score=0,\n fmt_str='https://movie.douban.com/j/new_search_subjects?tags=纪录片&range=%.1f,%.1f&start=0'):\n self.subject_set = set()\n self.url_list = []\n self.fmt_str = fmt_str\n self.score = score\n while self.score <= 10:\n url = self.fmt_str % (self.score, self.score)\n self.url_list.append(url)\n self.score += 0.1\n\n name = 'documentaries'\n\n def start_requests(self):\n self.logger.warning(\"start_request 请求入口\")\n self.logger.warning(self.url_list)\n for url in self.url_list:\n yield Request(url)\n\n\n def parse(self, response):\n if response.status == 200:\n url = response.url\n res = json.loads(response.body_as_unicode())\n data = res.get('data')\n if data:\n for d in data:\n subject_id = d.get('id')\n self.subject_set.add(subject_id)\n detail_url = d.get('url')\n item = {\n 'detail_url': detail_url,\n 'subject_id': subject_id,\n 'category': '纪录片'\n }\n yield Request(\n detail_url,\n callback=self.parse_movie_detail,\n meta={'item': item},\n dont_filter=True)\n # 翻页\n url = url.split('=')\n url[-1] = str(int(url[-1]) + 20)\n url = '='.join(url)\n yield Request(url)\n else:\n # with open('subjects.txt', 'w+', encoding='utf-8') as f:\n # f.write(json.dumps(list(self.subject_set)))\n self.logger.warning('没有数据:{}'.format(url))\n # self.logger.warning(len(self.subject_set))\n else:\n self.logger.error(response.url)\n self.logger.error('状态码为:{}'.format(response.status))\n\n def parse_movie_detail(self, response):\n return lib_parse_subject_detail(self, response)\n\n\n\n","sub_path":"douban/douban/spiders/documentaries.py","file_name":"documentaries.py","file_ext":"py","file_size_in_byte":2409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"27187591","text":"import chen.logger\nimport chen.config\nimport chen.frames.register\nimport chen.frames.login\nimport chen.frames.upload\nfrom time import strftime\nimport wx\nimport os\nimport json\nimport re\nimport uuid\nimport wx.richtext\nimport requests\nimport datetime\nimport io\nimport hashlib\nimport webbrowser\nimport pyperclip\nimport logging\nimport coloredlogs\nfrom twisted.internet import wxreactor\nwxreactor.install()\nfrom twisted.protocols import basic\nfrom twisted.internet import reactor, protocol, ssl\n\n\nclass ChatMessage():\n # Class for containing this data used for the \"database\"\n def __init__(self, channel, mid, username, message, timestamp):\n self.id = mid\n self.username = username\n self.channel = channel\n self.message = message\n self.timestamp = timestamp\n\n\nclass ChatFrame(wx.Frame):\n def __init__(self):\n # the Frame superclass init\n wx.Frame.__init__(self, parent=None, title=\"Chen\")\n # the protocol is set in connectionMade\n self.protocol = None\n # the list of messages for each channel [\"channel_name\" -> [ChatMessage(...), ...]]\n self.database = {}\n # the ID of the newest loaded message in each channel\n self.message_id = {}\n\n # File Menu\n file_menu = wx.Menu()\n about_menu_action = file_menu.Append(\n wx.ID_ABOUT, \"&About\", \" Information about this program\")\n self.Bind(wx.EVT_MENU, self.on_about, about_menu_action)\n exit_menu_action = file_menu.Append(\n wx.ID_EXIT, \"&Exit\", \" Terminate the program\")\n self.Bind(wx.EVT_MENU, self.on_exit, exit_menu_action)\n\n # User Menu\n user_menu = wx.Menu()\n uploads_list_action = user_menu.Append(\n wx.ID_ANY, \"&Uploads\", \" See your previous uploads.\")\n self.Bind(wx.EVT_MENU, self.on_upload_list, uploads_list_action)\n\n # Chat Menu\n chat_menu = wx.Menu()\n #chat_mode_action = chat_menu.Append(wx.ID_ANY, \"&Set Chat Mode\", \" Set the mode for the channel.\")\n #self.Bind(wx.EVT_MENU, self.on_chat_mode, chat_mode_action)\n #chat_topic_action = chat_menu.Append(wx.ID_ANY, \"&Set Chat Topic\", \" Set the topic for the channel.\")\n #self.Bind(wx.EVT_MENU, self.on_chat_topic, chat_topic_action)\n chat_open_sd = chat_menu.Append(\n wx.ID_ANY, \"&Open chat\", \" Open chat with input dialogue.\")\n self.Bind(wx.EVT_MENU, self.on_open_sd, chat_open_sd)\n do_user_list = chat_menu.Append(\n wx.ID_ANY, \"&User list\", \" See channel userlist.\")\n self.Bind(wx.EVT_MENU, self.on_open_sd, chat_open_sd)\n chat_send_sd = chat_menu.Append(\n wx.ID_ANY, \"&Send self-destructing message\", \" Send self destructing message to the selected channel.\")\n self.Bind(wx.EVT_MENU, self.on_send_sd, chat_send_sd)\n\n # Menu bar\n menu_bar = wx.MenuBar()\n menu_bar.Append(file_menu, \"&File\")\n menu_bar.Append(chat_menu, \"&Chat\")\n menu_bar.Append(user_menu, \"&User\")\n self.SetMenuBar(menu_bar)\n\n # Input Row\n input_row = wx.BoxSizer(wx.HORIZONTAL)\n self.user_input = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER)\n self.user_input.Bind(wx.EVT_TEXT_ENTER, self.send)\n upload_button = wx.Button(self, -1, \"Upload\")\n upload_button.Bind(wx.EVT_BUTTON, self.on_open)\n input_row.Add(self.user_input, 5, wx.EXPAND)\n input_row.Add(upload_button, 1, wx.EXPAND)\n\n # Output Box\n output_row = wx.BoxSizer(wx.HORIZONTAL)\n self.output = wx.richtext.RichTextCtrl(\n self, style=wx.richtext.RE_MULTILINE | wx.richtext.RE_READONLY)\n self.channel_list = wx.ListBox(self, style=wx.LB_SINGLE)\n self.Bind(wx.EVT_LISTBOX, self.on_channel_select, self.channel_list)\n output_row.Add(self.channel_list, 1, wx.EXPAND | wx.ALL)\n output_row.Add(self.output, 4, wx.EXPAND | wx.ALL)\n\n # Window Rows\n window_rows = wx.BoxSizer(wx.VERTICAL)\n window_rows.Add(output_row, 5, wx.EXPAND | wx.ALL)\n window_rows.Add(input_row, 0, wx.EXPAND | wx.ALL)\n\n self.SetAutoLayout(True)\n self.SetSizer(window_rows)\n self.Layout()\n\n def send_wrap(self, data):\n self.protocol.sendLine(json.dumps(data).encode(\"utf-8\"))\n\n def do_user_list(self, data):\n pass\n\n def send(self, evt):\n selected_index = self.channel_list.GetSelection()\n if selected_index != -1:\n self.send_wrap({\n \"action\": \"user_message\",\n \"channel\": self.channel_list.GetString(selected_index),\n \"timestamp\": int(datetime.datetime.utcnow().timestamp()),\n \"flags\": [],\n \"message\": self.user_input.GetValue()\n })\n self.user_input.SetValue(\"\")\n else:\n dialog = wx.MessageDialog(\n self, \"No channel is selected.\", \"Warning\", wx.ICON_WARNING)\n dialog.ShowModal()\n dialog.Destroy()\n\n def on_channel_select(self, e):\n selected_index = self.channel_list.GetSelection()\n current_channel = self.channel_list.GetString(selected_index)\n self.output.Clear()\n for message in self.database[current_channel]:\n self.output.WriteText(\n f\"[{strftime('%Y-%m-%d %H:%M:%S')}] {message.username}: {message.message}\")\n self.output.Newline()\n self.output.SetInsertionPointEnd()\n\n def on_upload_list(self, e):\n res = requests.post('http://localhost/api/uploads', json={\n \"username\": self.protocol.user[\"username\"]\n })\n if res.ok:\n result = res.json()\n uploadWin = chen.frames.upload.UploadsFrame(\n \"Login\", self, res.json()[\"uploads\"], parent=self)\n uploadWin.Show()\n\n def on_open_sd(self, e):\n \"\"\"Opening a chat.\n \"\"\"\n # get channel selected\n selected_index = self.channel_list.GetSelection()\n # get name of channel / user\n dlg = wx.TextEntryDialog(\n self, 'Who or where do you want to open a chat with?', 'Username / Channel Name')\n # if user hits ok,\n if dlg.ShowModal() == wx.ID_OK:\n # get the name, open the chat\n if len(dlg.GetValue()):\n self.channel_list.InsertItems(\n [dlg.GetValue()], self.channel_list.GetCount())\n self.database[dlg.GetValue()] = []\n self.message_id[dlg.GetValue()] = 0\n if dlg.GetValue()[0] in [\"&\", \"#\"]:\n self.send_wrap({\n \"action\": \"join_channel\",\n \"channel\": dlg.GetValue()\n })\n else:\n dialog = wx.MessageDialog(\n self, \"Unlikely to be a valid location.\", \"Warning\", wx.ICON_WARNING)\n dialog.ShowModal()\n dialog.Destroy()\n\n def on_send_sd(self, e):\n \"\"\"Sending a self-destructing message.\n \"\"\"\n # get channel selected\n selected_index = self.channel_list.GetSelection()\n # ask user for seconds duration\n dlg = wx.TextEntryDialog(\n self, 'How long do you want that message to last?', 'Message duration in seconds')\n # if the user presses OK,\n if dlg.ShowModal() == wx.ID_OK:\n # get the duration\n duration = int(dlg.GetValue())\n # if a channel is selected,\n if selected_index != -1:\n # send the message and clear the input buffer\n self.send_wrap({\n \"action\": \"user_message\",\n \"duration\": duration,\n \"channel\": self.channel_list.GetString(selected_index),\n \"flags\": [\"sd\"],\n \"timestamp\": int(datetime.datetime.utcnow().timestamp()),\n \"message\": self.user_input.GetValue()\n })\n self.user_input.SetValue(\"\")\n else:\n dialog = wx.MessageDialog(\n self, \"No channel is selected.\", \"Warning\", wx.ICON_WARNING)\n dialog.ShowModal()\n dialog.Destroy()\n\n # def on_chat_mode(self, e):\n # pass\n\n # def on_chat_topic(self, e):\n # pass\n\n def on_about(self, e):\n dialog = wx.MessageDialog(\n self, \"A chat application written in Python using the Twisted networking library and wxWidgets.\", \"Chen v0.0.1\", wx.OK)\n dialog.ShowModal()\n dialog.Destroy()\n\n def on_open(self, e):\n # a channel must be selected for the user to upload a file for it to be linked into\n selected_index = self.channel_list.GetSelection()\n if selected_index != -1:\n # ask the user for the file to open\n with wx.FileDialog(self, \"Upload file\", wildcard=\"*\", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog:\n # if the user hit the cancel button, we don't want to do anything\n if fileDialog.ShowModal() == wx.ID_CANCEL:\n return\n\n # from the file path, try to upload the file in a multipart request with the username being posted alongside the file itself to flask\n pathname = fileDialog.GetPath()\n try:\n files = {\n 'username': (None, self.protocol.user[\"username\"]),\n 'upload_file': (os.path.basename(pathname), open(pathname, 'rb'), 'application/octet-stream')\n }\n r = requests.post(\n \"http://localhost/api/upload\", files=files)\n if r.ok:\n url = f\"http://localhost{r.json()['url']}\"\n self.send_wrap({\n \"action\": \"user_message\",\n \"flags\": [\"upload\"],\n \"channel\": self.channel_list.GetString(selected_index),\n \"timestamp\": int(datetime.datetime.utcnow().timestamp()),\n \"message\": url\n })\n except IOError:\n wx.LogError(\"Cannot open file\")\n else:\n dialog = wx.MessageDialog(\n self, \"No channel is selected.\", \"Warning\", wx.ICON_WARNING)\n dialog.ShowModal()\n dialog.Destroy()\n\n def on_exit(self, e):\n # when the exit button is hit, you wanna close the program\n os._exit(1)\n self.Close(True)\n\n\nclass ChenCProtocol(basic.LineReceiver):\n def __init__(self):\n self.output = None\n # user object from the server\n self.user = None\n\n def delete_line(self, location):\n \"\"\"Facilitates self-destructing messages.\n \"\"\"\n # location -> location[0] is message id, location[1] is channel_name\n logging.debug(location)\n # the message in question before deletion\n previous = self.factory.gui.database[location[1]][location[0] - 1]\n # replacing the message in question -> \"deletion\"\n self.factory.gui.database[location[1]][location[0] - 1] = ChatMessage(\n previous.channel, self.factory.gui.message_id[previous.channel], \"System\", \"Message deleted.\", previous.timestamp)\n # if it's in the current channel, redraw that channel\n selected_index = self.factory.gui.channel_list.GetSelection()\n current_channel = self.factory.gui.channel_list.GetString(\n selected_index)\n if current_channel == location[1]:\n self.factory.gui.output.Clear()\n for message in self.factory.gui.database[current_channel]:\n self.factory.gui.output.WriteText(\n f\"[{datetime.date.fromtimestamp(message.timestamp).strftime('%Y-%m-%d %H:%M:%S')}] {message.username}: {message.message}\")\n self.factory.gui.output.Newline()\n self.factory.gui.output.SetInsertionPointEnd()\n\n def dataReceived(self, line):\n # if it's not valid JSON, it'll ValueError, otherwise the try: and else: blocks will run fine.\n try:\n logging.debug(f\"<- {line}\")\n ingest = json.loads(line)\n except ValueError as e:\n self.drop_user(f\"Malformed JSON sent by \\\"{self.ip}\\\".\")\n else:\n # Safe ingested message\n message = ingest\n # GUI object\n gui = self.factory.gui\n # list for lines to add to GUI\n lines = []\n\n if message[\"action\"] == \"auth_req\":\n # show the login window upon login\n login_window = chen.frames.login.LoginFrame(\n \"Login\", self, parent=self)\n login_window.Show()\n\n if message[\"action\"] == \"auth_success\":\n self.user = message['user']\n gui.channel_list.InsertItems(self.user[\"channels\"], 0)\n for channel in self.user[\"channels\"]:\n gui.database[channel] = []\n gui.message_id[channel] = 0\n lines.append(\n f\"[{strftime('%Y-%m-%d %H:%M:%S')}] Logged in as {self.user['username']} - {self.user['full_name']} - {self.user['email']}.\")\n lines.append(\"\\n\")\n lines.append(\"Please select a channel to begin.\")\n\n if message[\"action\"] == \"register_success\":\n self.user = message['user']\n gui.channel_list.InsertItems(self.user[\"channels\"], 0)\n for channel in self.user[\"channels\"]:\n gui.database[channel] = []\n gui.message_id[channel] = 0\n lines.append(\n f\"Registered as {self.user['username']} - {self.user['full_name']} - {self.user['email']}.\")\n lines.append(\"\\n\")\n lines.append(\"Please select a channel to begin.\")\n\n if message[\"action\"] == \"user_message_out\":\n # if it's not a channel and it's not in the database, it's a new user messaging, so open a \"channel\" for that user.\n if not message[\"channel\"][0] in [\"&\", \"#\"] and message[\"channel\"] not in gui.database:\n gui.database[message[\"channel\"]] = []\n gui.message_id[message[\"channel\"]] = 0\n gui.channel_list.InsertItems(\n [message[\"channel\"]], gui.channel_list.GetCount())\n # append the message to the channel database\n gui.database[message[\"channel\"]].append(ChatMessage(\n message[\"channel\"], gui.message_id[message[\"channel\"]], message[\"username\"], message[\"message\"], message[\"timestamp\"]))\n # increment the message_id, it is never decremented\n gui.message_id[message[\"channel\"]\n ] = gui.message_id[message[\"channel\"]] + 1\n if \"sd\" in message[\"flags\"]:\n reactor.callLater(int(message[\"duration\"]), self.delete_line, (\n gui.message_id[message[\"channel\"]], message[\"channel\"]))\n # get selected channel, if it is the current channel, append the new messages to that channel to it\n if gui.channel_list.GetSelection() != -1:\n selected_index = gui.channel_list.GetSelection()\n selected_channel = gui.channel_list.GetString(selected_index)\n if selected_channel == message[\"channel\"]:\n # The upload flag is formatted specifically differently.\n if \"upload\" in message[\"flags\"]:\n lines.append(\n f\"[{strftime('%Y-%m-%d %H:%M:%S')}] User \\\"{message['username']}\\\" has uploaded: {message['message']}\")\n else:\n lines.append(\n f\"[{strftime('%Y-%m-%d %H:%M:%S')}] {message['username']}: {message['message']}\")\n if gui:\n for output_line in lines:\n if output_line == \"\\n\":\n # if it's a newline, print a newline\n gui.output.Newline()\n else:\n # if it isn't a new line, write it, then place a newline, then set insertion point at the end.\n gui.output.WriteText(output_line)\n gui.output.Newline()\n gui.output.SetInsertionPointEnd()\n\n def connectionMade(self):\n self.factory.gui.protocol = self\n\n\nclass ChenCFactory(protocol.ClientFactory):\n def __init__(self, gui, cfg):\n # protocol definition for the factory\n self.protocol = ChenCProtocol\n # GUI insertion\n self.gui = gui\n # CFG insertion\n self.cfg = cfg\n\n def clientConnectionLost(self, transport, reason):\n reactor.stop()\n\n def clientConnectionFailed(self, transport, reason):\n reactor.stop()\n\n\ndef main():\n # provide the directory of the app.py to other files\n base_path = os.path.dirname(os.path.abspath(__file__))\n # load config\n cfg = chen.config.config_setup(base_path)\n # set up logger\n chen.logger.logging_setup(base_path, cfg)\n # set up the app\n app = wx.App(False)\n frame = ChatFrame()\n frame.Show()\n # bind the app to the reactor\n reactor.registerWxApp(app)\n # run the reactor with SSL verification disabled\n reactor.connectSSL(\"localhost\", 4242, ChenCFactory(\n frame, cfg), ssl.CertificateOptions(verify=False))\n reactor.run()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Packages/ChatClient/chen/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":17455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"84220516","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n############\n# Standard #\n############\nimport logging\n\n###############\n# Third Party #\n###############\nimport cv2\nimport numpy as np\nfrom pyadplugin import ADPluginServer, ADPluginFunction\n\n##########\n# Module #\n##########\nfrom psbeam.beamexceptions import NoBeamPresent\nimport psbeam.beamdetector as psb\nimport psbeam.preprocessing as prep\n\nlogger = logging.getLogger('pyadplugin.pyadplugin')\nlogger.setLevel(logging.DEBUG)\n\ndef stats_01(array, height=None, width=None, resize=1.0, kernel=(13,13)):\n desc = \"Gauss filter for prep. Use largest contour. Use sum for beam \" \\\n \"presence.\"\n # Resize back into an image\n image = np.reshape(array, (height, width))\n # Preprocess with a gaussian filter\n image_prep = prep.uint_resize_gauss(image, kernel=kernel)\n try:\n contours = psb.get_contours(image_prep)\n contour, area = psb.get_largest_contour(image_prep, contours=contours, \n get_area=True)\n M = psb.get_moments(contour=contour)\n # Check if beam is in the image using the sum of the pixel values\n psb.beam_is_present(M=M)\n centroid = [pos//resize for pos in psb.get_centroid(M)]\n _, _, l, w = [val//resize for val in psb.get_bounding_box(\n image_prep, contour)]\n beam_present = True\n except NoBeamPresent:\n beam_present = False\n area = 0\n centroid = [0,0]\n l = 0\n w = 0\n res = {\"AREA\": area, \"BEAM\": beam_present, \"CENT:X\": centroid[0], \n \"CENT:Y\": centroid[1], \"LENGTH\":l, \"WIDTH\":w, \"DESC\":desc}\n return res\n\n# Set up the server\nad_prefix = 'HFX:DG3:CVV:01:'\nserver = ADPluginServer(prefix='PYSTATS:',\n ad_prefix=ad_prefix,\n stream='IMAGE2',\n min_cbtime=10,\n enable_callbacks=True)\n\n\n# Set up the plugins\nstats = ADPluginFunction(\"01\", {\"AREA\": 0, \"BEAM\": False, \"CENT:X\": 0, \n \"CENT:Y\": 0, \"LENGTH\":0, \"WIDTH\":0, \"DESC\":\"\"}, \n stats_01, server)\n\n# import ipdb; ipdb.set_trace()\n\n","sub_path":"psbeam/pyadplugins/beamstats.py","file_name":"beamstats.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"614240155","text":"import sys\nimport argparse\nimport gzip\n\ndef parseArgument():\n\t# Parse the input\n\tparser=argparse.ArgumentParser(description=\\\n\t\t\t\"Convert chromosome names from a bed file to a different naming system\")\n\tparser.add_argument(\"--bedFileName\", required=True,\\\n\t\t\thelp='Bed file with original chromosome names')\n\tparser.add_argument(\"--chromNameDictFileName\", required=True,\\\n help='File that maps the original chromosome names to the new chromosome names')\n\tparser.add_argument(\"--chromNameDictReverse\", action=\"store_true\", \\\n\t\t\trequired=False,\\\n help='Treat the new chomosome names as original chromosome names and the original \\\n\t\t\t\tchromosome names as new chromosome names')\n\tparser.add_argument(\"--removeSuffixes\", action=\"store_true\", \\\n required=False,\\\n help='Remove parts after . in bed file chromosome names')\n\tparser.add_argument(\"--gzip\", action=\"store_true\", required=False,\\\n help='The input and output files are gzipped')\n\tparser.add_argument(\"--includeMissingChrom\", action=\"store_true\", \\\n\t\t\trequired=False,\\\n help='Include chromosomes that are not in the dictionary as NA')\n\tparser.add_argument(\"--outputFileName\", required=True,\\\n\t\t\thelp='bed file where the regions with converted chromosome names will be written')\n\toptions = parser.parse_args()\n\treturn options\n\ndef convertChromNames(options):\n\t# Convert chromosome names from a bed file to a different naming system\n\tchromNameDict = {}\n\tchromNameDictFile = open(options.chromNameDictFileName)\n\tfor line in chromNameDictFile:\n\t\t# Iterate through the chromosomes and create an entry in the dictionary for each\n\t\tlineElements = line.strip().split(\"\\t\")\n\t\tif lineElements[1] == \"-\":\n\t\t\t# There is no chromosome in the conversion\n\t\t\tcontinue\n\t\tif options.chromNameDictReverse:\n\t\t\t# Make the second column the keys and the first column the values\n\t\t\tchromNameDict[lineElements[1]] = lineElements[0]\n\t\telse:\n\t\t\t# Make the first column the keys and the second column the values\n\t\t\tchromNameDict[lineElements[0]] = lineElements[1]\n\tchromNameDictFile.close()\n\tbedFile =\\\n\t\tgzip.open(options.bedFileName) if options.gzip else \\\n\t\t\topen(options.bedFileName) # Use gzip to open the bed file if the bed file is gzipped\n\toutputFile =\\\n\t\tgzip.open(options.outputFileName, 'wb') if options.gzip else \\\n\t\t\topen(options.outputFileName, 'w+') # Use gzip to open the output file if the output file should be gzipped\n\tfor line in bedFile:\n\t\t# Iterate through the lines of the peak motif hit file and select peak summits with a near-by motif hit\n\t\tlineElements = line.strip().split(\"\\t\")\n\t\tchrom = lineElements[0]\n\t\tif options.removeSuffixes:\n\t\t\t# Remove the part of the chromosome name after the .\n\t\t\tchromElements = chrom.split(\".\")\n\t\t\tchrom = chromElements[0]\n\t\tif chrom not in chromNameDict:\n\t\t\t# Skip this region or make it chrNone because the chromosome is not in the list of chromosomes\n\t\t\tif options.includeMissingChrom:\n\t\t\t\t# Include the region as NA\n\t\t\t\toutputFile.write(\"NA\" + \"\\t\" + \\\n\t\t\t\t\t\"\\t\".join(lineElements[1:len(lineElements)]) + \"\\n\")\n\t\t\t\tcontinue\n\t\t\tprint(\"Problem: Chromosome \" + chrom + \\\n\t\t\t\t\" not in list of chromosomes\")\n\t\t\tcontinue\n\t\toutputFile.write(chromNameDict[chrom] + \"\\t\" + \\\n\t\t\t\"\\t\".join(lineElements[1:len(lineElements)]) + \\\n\t\t\t\"\\n\")\n\tbedFile.close()\n\toutputFile.close()\n\nif __name__==\"__main__\":\n\toptions = parseArgument()\n\tconvertChromNames(options)\n","sub_path":"evaluationScriptsCortexLiverModels/convertChromNames.py","file_name":"convertChromNames.py","file_ext":"py","file_size_in_byte":3472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"482297769","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom Crypto.Cipher import AES\nfrom Crypto import Random\nfrom Crypto.Hash import SHA256\nimport zlib\nimport struct\nimport base64\n\nAES_KEY_SIZE = 32 #Key is 256 bit\n'''\npad = lambda s : s if len(s) % AES_KEY_SIZE == 0 else \\\n s + (AES_KEY_SIZE - len(s) % AES_KEY_SIZE) \\\n * chr(AES_KEY_SIZE - len(s) % AES_KEY_SIZE)\n\nunpad = lambda s : s if len(s) % AES_KEY_SIZE == 0 else \\\n s[:-ord(s[len(s)-1])]\n'''\n# note: if len(s) % AES_KEY_SIZE = 0,\n# pad(s) = s + AES_KEY_SIZE * chr(len(s))\n# unpad will remove the extra chars.\n\npad = lambda s : s + (AES_KEY_SIZE - len(s) % AES_KEY_SIZE) \\\n * chr(AES_KEY_SIZE - len(s) % AES_KEY_SIZE)\n\nunpad = lambda s : s[:-ord(s[len(s)-1])]\n\n# Would it be good setting FILE_BLOCK_SIZE = AES_KEY_SIZE * n - 1 to save space?\nFILE_BLOCK_SIZE = 65535\n#FILE_BLOCK_SIZE = 4194304\n\ndef split_file_writer(file_name, split_size=32):\n file_size = split_size * 2 ** 20\n sum_len = [0]\n def write_file(buf):\n sum_len[0] += len(buf)\n file_no = sum_len[0] // file_size\n new_filename = file_name if file_no==0 else file_name+'.'+('0000'+str(file_no))[-4:]\n with open(new_filename,'a') as afile:\n afile.write(buf)\n return write_file\n\ndef split_file_reader(file_name):\n files = [open(file_name,'r')]\n file_no = [0]\n def read_file(buf_size):\n buf = files[0].read(buf_size)\n if len(buf) == 0:\n file_no[0] += 1\n files[0].close()\n try:\n files[0] = open(file_name+'.'+('0000'+str(file_no[0]))[-4:])\n return read_file(buf_size)\n except IOError:\n return ''\n else:\n return buf\n return read_file\n\ndef encrypt(key, data):\n data = pad(data)\n iv = Random.new().read(AES.block_size)\n cipher = AES.new(pad(key)[:AES_KEY_SIZE], AES.MODE_CBC, iv)\n return iv + cipher.encrypt(data)\n\ndef decrypt(key, data):\n #data = base64.b64decode(data)\n iv = data[:AES.block_size]\n cipher = AES.new(pad(key)[:AES_KEY_SIZE], AES.MODE_CBC, iv)\n return unpad(cipher.decrypt(data[AES.block_size:]))\n\ndef pack_file(key, source, target, file_type = 'F'):\n with open(source,'r') as source_file, open(target,'w') as target_file:\n source_file.seek(0, 2)\n source_size = source_file.tell()\n source_file.seek(0)\n header = struct.pack('cQ',\n file_type,\n source_size)\n\n target_file.write(header)\n\n hasher = SHA256.new()\n hasher.update(header)\n\n buf = source_file.read(FILE_BLOCK_SIZE)\n while len(buf) > 0:\n hasher.update(buf)\n buf_size_original = len(buf)\n buf = zlib.compress(buf)\n buf = encrypt(key, buf)\n target_file.write(struct.pack('Q',len(buf)))\n target_file.write(buf)\n buf = source_file.read(FILE_BLOCK_SIZE)\n\n dgst = hasher.hexdigest()\n return dgst\n\ndef unpack_file(key, source, target):\n with open(source,'r') as source_file, open(target,'w') as target_file:\n header = source_file.read(16) #header size\n buf_size = source_file.read(8)\n while len(buf_size) > 0:\n buf = source_file.read(struct.unpack('Q',buf_size)[0])\n try:\n buf = decrypt(key, buf)\n buf = zlib.decompress(buf)\n except:\n print('Error buff_size:{0}'.format(struct.unpack('Q',buf_size)[0]))\n return\n\n target_file.write(buf)\n buf_size = source_file.read(8)\n","sub_path":"encrypted_file_repo/encrepo/pack.py","file_name":"pack.py","file_ext":"py","file_size_in_byte":3681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"474585244","text":"import networkx as nx\nimport sys\nimport collections\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\n\ndef nodelabel(label_filename):\n f = open(label_filename, \"r\")\n line = f.readline()\n label_data = dict()\n while line:\n num, name = line.split()\n label_data[num] = name\n line = f.readline()\n f.close()\n return label_data\n\ndef read_and_relabel(graph_filename, label_filename):\n G = nx.read_edgelist(graph_filename, create_using=nx.DiGraph())\n G = nx.relabel_nodes(G, mapping=nodelabel(label_filename))\n return G\n\ndef basic_data(G):\n print(\"\\n########### Basic Graph Data ###########\")\n print(\"- Number of nodes:\", nx.number_of_nodes(G))\n print(\"- Number of edges:\", nx.number_of_edges(G))\n if nx.is_strongly_connected(G):\n print(\"- Given graph is strongly connected.\")\n print(\"- Diameter:\", nx.diameter(G))\n else:\n print(\"- Given graph is not strongly connected.\")\n return 0\n\ndef shortestpath_data(G, sourcename, targetname):\n print(\"\\n########### ex01 ###########\")\n source2target = nx.shortest_path(G, source=sourcename, target=targetname)\n print(\"- Shortest path from %s to %s:\" % (sourcename, targetname), source2target, \", %d hops\" % (len(source2target)-1))\n\n\n# [fuction for properties]\n# Degree distribution\ndef degree_dist(G):\n x = list(collections.Counter(dict(G.degree()).values()).keys())\n y = list(collections.Counter(dict(G.degree()).values()).values())\n y = list(map(lambda e: e/nx.number_of_nodes(G), y))\n return x, y\n\n# Closeness centrality\ndef closeness_centrality(G):\n close_cent_list = sorted(dict(nx.closeness_centrality(G)).values())\n N = G.number_of_nodes()\n if (len(close_cent_list) != N):\n raise Exception(\"[error] number of nodes is weird !!\")\n close_cent = dict()\n for i in range(0, N):\n close_cent[i] = close_cent_list[i]\n return close_cent\n\ndef plot(x, y, xlabel, ylabel, title, figname, type=\"scatter\", xlog=True, ylog=True):\n fig, ax = plt.subplots()\n plt.title(title)\n plt.scatter(x, y, s=0.8, color='r')\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.xscale('log')\n plt.yscale('log')\n plt.legend()\n plt.savefig(figname, dpi=500)\n return 0\n\n\n##### Main Process\ngraph_filename = sys.argv[1]\nlabel_filename = sys.argv[2]\nG = read_and_relabel(graph_filename, label_filename)\nbasic_data(G)\nshortestpath_data(G, \"jacob\", \"andy\")\nprint(\"\\n\")\n\nx, y = degree_dist(G)\nplot(x,y,\"node degree k\",\"degree distribution p(k)\",\"Degree Distribution\",\"01_degree_distribution.png\")\n# plot(x,y,\"node degree k\",\"degree distribution p(k)\",\"Degree Distribution\",\"02_degree_distribution.png\")\n","sub_path":"ex04/1_analysis.py","file_name":"1_analysis.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"118429799","text":"from django.shortcuts import render\nfrom django.http import HttpResponse # used for debugging\nfrom .models import Book, BookInstance, Author, Language, Genre # models\nfrom django.views import generic\n\n# Create your views here.\n# GF: a view takes a request object and any extra params pulled from the url \n# in our URLconfs. Then, we operate on the data (query the database) and return\n# a formatted http response (we can use render to render a template)\ndef index(request):\n \"\"\"\n View function for the home page of the site.\n \"\"\"\n # Generate counts for some of the objects\n num_books = Book.objects.all().count()\n num_instances = BookInstance.objects.all().count()\n # Available books (status = 'a')\n num_instances_available = BookInstance.objects.filter(status__exact='a').count()\n num_authors = Author.objects.count() # the all() is implied by default\n # GF: note how we query from the objects and can perform various filters and sorts on the ORM models Django provides\n\n # Extra: more queries\n num_genres = Genre.objects.count()\n num_books_containing_pastoralia = Book.objects.filter(title__icontains=\"pAstoralia\").count()\n\n # Sessions: get number of visits to this view\n num_visits = request.session.get('num_visits', 0)\n request.session['num_visits'] = num_visits + 1\n\n # Render the HTML template index.html with the data in the context variable\n return render(\n request,\n 'index.html',\n context={'num_books':num_books,\n 'num_instances':num_instances,\n 'num_instances_available':num_instances_available,\n 'num_authors':num_authors, \n 'num_genres':num_genres,\n 'num_books_containing_pastoralia':num_books_containing_pastoralia,\n 'num_visits':num_visits},\n )\n\n # return HttpResponse('

Hello, world!

') # DEBUG LINE\n\nclass BookListView(generic.ListView):\n model = Book\n paginate_by = 2\n # can overrride get context data or get queryset to change the context passed to the view, or change the query\n\nclass BookDetailView(generic.DetailView):\n model = Book\n\nclass AuthorListView(generic.ListView):\n model = Author\n\nclass AuthorDetailView(generic.DetailView):\n model = Author\n\n def get_context_data(self, **kwargs):\n # Call the base implementation first\n context = super(AuthorDetailView, self).get_context_data(**kwargs)\n\n # Put in some extra info. The args passed in are in the kwargs variable. (HTTP params are in the self.request.GET.)\n # print('pk:', self.kwargs['pk']) # DEBUG LINE\n\n # Lookups can span relationships (like table joins) using double underscores that follow the relationships. pk or id seem to be OK!\n books_by_author = Book.objects.filter(author__pk=self.kwargs['pk'])\n # print(books_by_author) # DEBUG LINE\n context['books_by_author'] = books_by_author\n return context","sub_path":"catalog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"319329386","text":"\"\"\"\n斐波那契数字\n输入要求的是第n个数字\n正确输出第n个数\n\"\"\"\ndef fun(n):\n if n < 0:\n print('输入有误!')\n elif n == 1 or n == 2:\n return 1\n else:\n return fun(n-1) + fun(n-2)\nn = int(input('please input a number:'))\nfor i in range(1,n+1):\n print(fun(i))\n","sub_path":"0804_递归函数_斐波那契.py","file_name":"0804_递归函数_斐波那契.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"522730711","text":"\"\"\"\nS3 and CloudFront.\n\"\"\"\nfrom troposphere import GetAtt, Output\nfrom troposphere.s3 import Bucket, PublicRead, WebsiteConfiguration\n\nfrom hip_edit import resource_title\n\n\ndef build(prefix, template, suffix=None):\n \"\"\"\n Adds S3 and CloudFront elements to CF template.\n \"\"\"\n s3bucket = template.add_resource(Bucket(\n \"%sS3Bucket\" % prefix,\n AccessControl=PublicRead,\n WebsiteConfiguration=WebsiteConfiguration(\n IndexDocument=\"index.html\"\n ),\n BucketName=resource_title.bucket_name(prefix, suffix)\n ))\n\n template.add_output([\n Output(\n \"WebsiteURL\",\n Value=GetAtt(s3bucket, \"WebsiteURL\"),\n Description=\"URL for website hosted on S3\"\n )\n ])\n","sub_path":"hip-edit-infra/hip_edit/resources/bucket.py","file_name":"bucket.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"405376703","text":"#!/usr/bin/env python\n\n#\n# Copyright (c) 2018 Sarah Tollman, 2021 Theo Jepsen\n# All rights reserved.\n#\n# This software was developed by Stanford University and the University of Cambridge Computer Laboratory\n# under National Science Foundation under Grant No. CNS-0855268,\n# the University of Cambridge Computer Laboratory under EPSRC INTERNET Project EP/H040536/1 and\n# by the University of Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-11-C-0249 (\"MRC2\"),\n# as part of the DARPA MRC research programme.\n#\n\nimport socket, struct\nfrom collections import namedtuple\n\nfrom control_plane.utils.addr_conversions import int_to_ip\n\nKEY_LEN = 32\n\n\"\"\"\nA structure that represents an entry in a longest prefix match dictionary\n\"\"\"\nLPM_entry = namedtuple('LPM_entry', ['key', 'prefix_len', 'val'])\n\n\"\"\"\nA dictionary that performs lookups using LPM instead of exact match\nThe keys must be string representations of an IP addresses\n\"\"\"\nclass LPM_dict():\n \"\"\"\n An error class that defines an exception that occurs when an entry is added\n to the LPM_dict that cannot be converted to an integer\n \"\"\"\n class KeyError(TypeError):\n def __init__(self, key):\n self.message = 'Could not convert LPM key {} to int'.format(key)\n\n \"\"\"\n Initializer\n\n @param entries a list of (key, prefix_len, val) to add to the dictionary\n \"\"\"\n def __init__(self, *entries):\n self.entries = []\n for entry in entries:\n self.append(*entry)\n\n \"\"\"\n Convert an IP address string to a long\n\n @param ip the address to convert\n @return a long that represents the same address as the ip parameter\n \"\"\"\n def _ip2long(self, ip):\n packedIP = socket.inet_aton(ip)\n return struct.unpack(\"!L\", packedIP)[0]\n\n \"\"\"\n Adds an entry to the dictionary\n\n @param key a string representation of an IP address\n @param prefix_length the number of relevant bits in the key\n @param val the value to return when the table is matched on `key`.\n Will most likely be (action_name, [action_data])\n @raise KeyError if the key cannot be converted to a long\n \"\"\"\n def append(self, key, prefix_len, val):\n try:\n key = self._ip2long(key)\n except:\n if type(key) != int: raise KeyError(key)\n pass\n self.entries.append(LPM_entry(key, prefix_len, val))\n # entries list is sorted by prefix length, longest to shortest\n self.entries = sorted(self.entries, key=lambda e: e.prefix_len,\n reverse=True)\n\n \"\"\"\n Looks up an entry in the dictionary\n\n @param key a string representation of an IP address\n @return the value associated with the longest prefix match in the table for\n the key, or None if no match exacts\n @raise KeyError if the key cannot be converted to a long\n \"\"\"\n def get(self, key):\n try:\n key = self._ip2long(key)\n except:\n if type(key) != int: raise KeyError(key)\n pass\n for e in self.entries:\n # values are sorted by key length, longest to shortest, so the\n # first match will be the longest\n if ((key >> (KEY_LEN - e.prefix_len)) == \\\n (e.key >> (KEY_LEN - e.prefix_len))): return e.val\n return None\n\n \"\"\"\n Removes all existing entries from the dictionary\n \"\"\"\n def clear(self):\n self.entries = []\n\n \"\"\"\n Creates a duplicate LPM_dict with the same entries as this one\n \"\"\"\n def copy(self):\n new_dict = LPM_dict()\n new_dict.entries = list(self.entries)\n return new_dict\n\n \"\"\"\n Converts the LPM_dict to a string representation where entries are separated\n by newlines and the ip address key is in string form\n \"\"\"\n def __str__(self):\n e_strs = [str(e._replace(key=int_to_ip(e.key))) for e in self.entries]\n return '\\n'.join(e_strs)\n\n","sub_path":"router.p4app/control_plane/utils/LPM_dict.py","file_name":"LPM_dict.py","file_ext":"py","file_size_in_byte":3923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"325964337","text":"# _________________________________________________________________________\n#\n# Pyomo: Python Optimization Modeling Objects\n# Copyright (c) 2014 Sandia Corporation.\n# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n# the U.S. Government retains certain rights in this software.\n# This software is distributed under the BSD License.\n# _________________________________________________________________________\n\nimport logging\nimport sys\nimport types\nimport pyutilib.math\nfrom pyomo.core import *\nfrom pyomo.dae import *\nfrom pyomo.core.base.sparse_indexed_component import *\nfrom pyomo.core.base.misc import apply_indexed_rule\n\nlogger = logging.getLogger('pyomo.core')\n\ndef generate_finite_elements(ds,nfe):\n \"\"\" \n This function first checks to see if the number of finite elements\n in the differential set is equal to nfe. If the number of finite\n elements is less than nfe, additional points will be generated. If\n the number of finite elements is greater than or equal to nfe the \n differential set will not be modified\n \"\"\"\n if (len(ds)-1) >= nfe:\n # In this case the differentialset already contains the\n # desired number or more than the desired number of finite\n # elements so no additional points are needed.\n return \n elif len(ds) == 2:\n # If only bounds have been specified on the differentialset we\n # generate the desired number of finite elements by \n # spreading them evenly over the interval\n step = (max(ds)-min(ds))/float(nfe)\n tmp = min(ds)+step\n while round(tmp,6)<=round((max(ds)-step),6):\n ds.add(round(tmp,6))\n tmp+=step\n ds.set_changed(True)\n ds._fe = sorted(ds)\n return\n else:\n # This is the case where some points have been specified\n # inside of the bounds however the desired number of finite \n # elements has not been met. We first look at the step sizes\n # between the existing points. Then an additional point\n # is placed at the midpoint of the largest step. This\n # process is repeated until we have achieved the desired \n # number of finite elements. If there are multiple \"largest steps\"\n # the point will be placed at the first occurance of the\n # largest step\n\n addpts = nfe-(len(ds)-1)\n while addpts>0:\n _add_point(ds)\n addpts -= 1\n ds.set_changed(True)\n ds._fe = sorted(ds)\n return\n\ndef _add_point(ds):\n sortds = sorted(ds)\n maxstep = sortds[1]-sortds[0]\n maxloc = 0\n for i in range(2,len(sortds)):\n if (sortds[i]-sortds[i-1])>maxstep:\n maxstep = sortds[i]-sortds[i-1]\n maxloc = i-1\n \n ds.add(round((sortds[maxloc]+maxstep/2.0),6))\n\ndef generate_colloc_points(ds,tau):\n \"\"\"\n This function adds collocation points between the finite elements\n in the differential set\n \"\"\"\n fes = sorted(ds)\n for i in range(1,len(fes)):\n h = fes[i]-fes[i-1]\n for j in range(len(tau)):\n if tau[j] == 1 or tau[j] == 0:\n continue\n pt = fes[i-1]+h*tau[j]\n pt = round(pt,6)\n if pt not in ds:\n ds.add(pt)\n ds.set_changed(True)\n\ndef update_contset_indexed_component(comp):\n \"\"\"\n Update any model components other than Differential\n which are indexed by a ContinuousSet that has changed\n \"\"\"\n # FIXME: This implementation is a hack until Var and Constraint get\n # moved over to Sparse_Indexed_Component. The update methods below are \n # roughly what the '_default' method in Var and Constraint should\n # do when they get reimplemented.\n\n # This implementation also assumes that only Var and Constraint components\n # will be explicitly indexed by a ContinuousSet and thus only checks for \n # these two components. \n\n # Additionally, this implemenation will *NOT* check\n # for or update components which use a ContinuousSet implicitly. ex) an objective\n # function which iterates through a ContinuousSet and sums the squared error. \n # If you use a ContinuousSet implicitly you must initialize it with every\n # index you would like to have access to!\n\n if comp.type() is Suffix:\n return\n if comp.dim() == 1:\n if comp._index.type() == ContinuousSet: \n if comp._index.get_changed():\n if isinstance(comp, Var):\n _update_var(comp)\n elif comp.type() == Constraint:\n _update_constraint(comp)\n elif comp.dim() > 1:\n if isinstance(comp,SparseIndexedComponent):\n indexset = comp._implicit_subsets\n else:\n indexset = comp._index_set\n\n for s in indexset:\n if s.type() == ContinuousSet and s.get_changed():\n if isinstance(comp, Var): # Don't use the type() method here because we want to catch\n _update_var(comp) # DerivativeVar components as well as Var components\n elif comp.type() == Constraint:\n _update_constraint(comp)\n \ndef _update_var(v):\n \"\"\"\n This method will construct any additional indices in a variable \n resulting from the discretization of ContinuousSet \n \"\"\"\n\n # Note: This is not required it is handled by the _default method on\n # Var (which is now a SparseIndexedComponent). However, it\n # would be much slower to rely on that method to generate new\n # _VarData for a large number of new indices.\n new_indices = set(v._index)-set(v._data.keys())\n v._add_members(new_indices)\n v._initialize_members(new_indices)\n\ndef _update_constraint(con):\n \"\"\"\n This method will construct any additional indices in a constraint\n resulting from the discretization.\n \"\"\"\n\n for i in con.index_set():\n if i not in con:\n # Code taken from the construct() method of Constraint\n _rule=con.rule\n _parent=con._parent()\n con.add(i,apply_indexed_rule(con,_rule,_parent,i))\n\ndef create_access_function(var):\n \"\"\"\n This method returns a function that returns a component by calling \n it rather than indexing it\n \"\"\"\n def _fun(*args):\n return var[args]\n return _fun\n\ndef create_partial_expression(scheme,expr,ind,loc):\n \"\"\"\n This method returns a function which applies a discretization scheme \n to an expression along a particular indexind set. This is admittedly a\n convoluted looking implementation. The idea is that we only apply a \n discretization scheme to one indexing set at a time but we also want \n the function to be expanded over any other indexing sets.\n \"\"\"\n def _fun(*args):\n return scheme(lambda i: expr(*(args[0:loc]+(i,)+args[loc+1:])),ind)\n return lambda *args:_fun(*args)(args[loc])\n\ndef add_discretization_equations(block,d):\n \"\"\"\n Adds the discretization equations for DerivativeVar d to the Block block.\n Because certain indices will be valid for some discretization schemes and \n not others, we skip any constraints which raise an IndexError.\n \"\"\"\n \n def _disc_eq(m,*args):\n try:\n return d[args] == d._expr(*args)\n except IndexError:\n return Constraint.Skip\n\n if d.dim() == 1:\n block.add_component(d.name+'_disc_eq',Constraint(d._index,rule=_disc_eq))\n else:\n block.add_component(d.name+'_disc_eq',Constraint(*d._implicit_subsets,rule=_disc_eq))\n\ndef add_continuity_equations(block,d,i,loc):\n \"\"\"\n Adds continuity equations in the case that the polynomial basis function\n does not have a root at the finite element boundary\n \"\"\"\n svar = d.get_state_var()\n nme = svar.name+'_'+i.name+'_cont_eq'\n if block.find_component(nme) is not None:\n return\n \n def _cont_exp(v,s):\n ncp = s.get_discretization_info()['ncp']\n afinal = s.get_discretization_info()['afinal']\n def _fun(i):\n tmp = sorted(s)\n idx = tmp.index(i)\n low = s.get_lower_element_boundary(i)\n if i != low or idx == 0:\n raise IndexError(\"list index out of range\")\n low = s.get_lower_element_boundary(tmp[idx-1])\n lowidx = tmp.index(low)\n return sum(v(tmp[lowidx+j])*afinal[j] for j in range(ncp+1))\n return _fun\n expr = create_partial_expression(_cont_exp,create_access_function(svar),i,loc)\n\n def _cont_eq(m,*args):\n try:\n return svar[args] == expr(*args)\n except IndexError:\n return Constraint.Skip\n\n if d.dim() == 1:\n block.add_component(nme,Constraint(d._index,rule=_cont_eq))\n else:\n block.add_component(nme,Constraint(*d._implicit_subsets,rule=_cont_eq))\n\ndef block_fully_discretized(b):\n \"\"\"\n Checks to see if all ContinuousSets in a block have been discretized\n \"\"\"\n\n for i in b.components(ContinuousSet).itervalues():\n if not i.get_discretization_info().has_key('scheme'):\n return False\n return True\n","sub_path":"pyomo/dae/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":9162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"232248445","text":"import sys\nfrom PyQt4 import QtCore, QtGui\nfrom Form import Ui_Dialog\n \n \nclass MyDialog(QtGui.QDialog):\n def __init__(self, parent=None):\n QtGui.QWidget.__init__(self, parent)\n self.ui = Ui_Dialog()\n self.ui.setupUi(self)\n self.ui.pushButton.clicked.connect(self.OK)\n def OK(self):\n \tprint ('OK Pressed')\n \n \nif __name__ == \"__main__\":\n app = QtGui.QApplication(sys.argv)\n myapp = MyDialog()\n myapp.show()\n sys.exit(app.exec_())","sub_path":"14. PyQT/Example.QtDialog/ex1/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"354405746","text":"\"\"\"\n\nReverse Linked List\nReverse a singly linked list.\n\nExample:\n\nInput: 1->2->3->4->5->NULL\nOutput: 5->4->3->2->1->NULL\n\nFollow up:\nA linked list can be reversed either iteratively or recursively. Could you implement both?\n\n\"\"\"\nfrom Leet.Easy.LinkedList.CreateList import List\n\n\n\n\n# Driver Code\nif __name__ == \"__main__\":\n # Create List\n input = [5,4,3,2,1,6]\n ls = List()\n ls.CreateList(input)\n\n\n ls.printList(ls.ReverseList_iterative(ls.head))\n #ls.printList(ls.ReverseList_recursive(ls.head))","sub_path":"Leet/Easy/LinkedList/ReverseList.py","file_name":"ReverseList.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"400567266","text":"class Solution(object):\n def maxCoins(self, piles):\n \"\"\"\n :type piles: List[int]\n :rtype: int\n \"\"\"\n sortedPiles = sorted(piles)\n sum, i, j = 0, 0, len(piles)-2\n while i < j:\n i += 1\n sum += sortedPiles[j]\n j -= 2\n\n return sum\n\n# Slow version\n# for i in range(len(piles)//3):\n# sortedPiles.pop(0)\n# sortedPiles.pop(-1)\n# sum += sortedPiles.pop(-1)\n\n\nif __name__==\"__main__\":\n piles = [2,4,1,2,7,8]\n sol = Solution()\n result = sol.maxCoins(piles)\n print(result)","sub_path":"contest-203/okt/1561_maxCoin.py","file_name":"1561_maxCoin.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"356674256","text":"import plotly.plotly as py\nimport plotly.graph_objs as go\nfrom plotly import tools\n\nimport MySQLdb\nimport pandas as pd\nimport time\nfrom datetime import datetime as dt\n\ndef convert_to_datetime(num):\n num = (num * increment_time) + start_time\n num = dt.fromtimestamp(num)\n return num\n\n\n#Connect to SQL database\ndb_conn = MySQLdb.connect(host=\"localhost\", user=\"pi\", passwd=\"password\", db=\"environment_data\")\ncursor = db_conn.cursor()\ncursor.execute('select * from demo_data');\n\nrows = cursor.fetchall()\nstr(rows)\n\n#Dataframe stuff\ndf = pd.DataFrame([[ij for ij in i] for i in rows])\n#Give each database column a name\ndf.rename(columns={0: 'Time', 1: 'Temperature', 2: 'Humidity', 3: 'Soil Moisture', 4: 'Light Level'}, inplace=True)\n\n#Convert time column to proper datetime format\nstart_time = 1532361000\nincrement_time = 600 #Data was collected every 10 minutes\ndf['Time'] = df['Time'].apply(convert_to_datetime)\n\n\ntemp = go.Scatter(\n x=df['Time'],\n y=df['Temperature'],\n name='Temperature (C)'\n )\n\nhumidity = go.Scatter(\n x=df['Time'],\n y=df['Humidity'],\n name='Relative Humidity (%)'\n )\nsoil = go.Scatter(\n x=df['Time'],\n y=df['Soil Moisture'],\n name='Soil Moisture (%)'\n )\n\nlight = go.Scatter(\n x=df['Time'],\n y=df['Light Level'],\n name='Light Level'\n )\n\n\nfig = tools.make_subplots(rows = 2, cols=2, subplot_titles= ('Temperature vs Time','Relative Humidity vs Time', 'Soil Moisture vs Time', 'Light Levels vs Time'))\nfig.append_trace(temp, 1, 1)\nfig.append_trace(humidity, 1, 2)\nfig.append_trace(soil, 2, 1)\nfig.append_trace(light, 2, 2)\n\nfig['layout']['xaxis1'].update(title = 'Time')\nfig['layout']['xaxis2'].update(title = 'Time')\nfig['layout']['xaxis3'].update(title = 'Time')\nfig['layout']['xaxis4'].update(title = 'Time')\n\nfig['layout']['yaxis1'].update(title = 'Temperature (C)')\nfig['layout']['yaxis2'].update(title = 'Relative Humidity (%)')\nfig['layout']['yaxis3'].update(title = 'Soil Moisture (%)')\nfig['layout']['yaxis4'].update(title = 'Light Level')\n\n\nfig['layout'].update(title = 'Greenhouse Data')\n\n\n#fig = go.Figure(data=data, layout=layout)\npy.iplot(fig)\n\n","sub_path":"humidity.py","file_name":"humidity.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"373583205","text":"from typing import Tuple, Any\n\nfrom prefect import Task\nfrom prefect.engine.results import LocalResult\nfrom prefect.engine.result import Result\nfrom prefect.engine.serializers import JSONSerializer\n\nfrom transform import _to_safe_name\n\n__all__ = [\"Writer\"]\n\n\nclass Writer(Task):\n \"\"\"Read raw data from a Result.\n \"\"\"\n\n def __init__(\n self, result: Result = LocalResult(serializer=JSONSerializer), *args, **kwargs\n ):\n super().__init__(*args, **kwargs)\n\n self.result = result\n\n def run(self, datas: Tuple[str, Any]) -> tuple:\n\n name = datas[0]\n data = datas[1]\n\n # Write raw data\n self.result.location = f\"{name}.prefect\"\n\n written_result = self.result.write(data)\n\n return(written_result)\n\n def _get_name(self, name: str, **kwargs) -> str:\n\n name = _to_safe_name(name)\n\n return name\n","sub_path":"src/load/writer.py","file_name":"writer.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"254454185","text":"from apiclient.discovery import build\n\nYOUTUBE_API_KEY = 'AIzaSyDqZZK_zsS-zoJd7ybGI1cjmlwRqFFENzE'\n\nyoutube = build('youtube', 'v3', developerKey=YOUTUBE_API_KEY)\n\n\nsearch_response = youtube.search().list(\n part='id,snippet',\n #検索したい文字列を指定\n q='dbd',\n #視聴回数が多い順に取得\n # order='viewCount',\n # type='video',\n).execute()\n\nsearch_response\n\nfor sr in search_response.get('items',[]):\n print(sr['snippet']['title'])\n print(sr['snippet']['channelTitle'])\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"50213212","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\" arc2osm beta\n\nThis ArcToolbox Tool takes an esri featureclass and outputs an OSM file\nwith that data.\n\nBy default tags will be naively copied from the input data. Hooks are provided\nso that, with a little python programming, you can translate the tags however\nyou like. More hooks are provided so you can filter or even modify the features\nthemselves.\n\nTo use the hooks, create a file in the translations/ directory called myfile.py\nand run ogr2osm.py -t myfile. This file should define a function with the name\nof each hook you want to use. For an example, see the uvmtrans.py file.\n\nThe program will use projection metadata from the source, if it has any. If\nthere is no projection information, or if you want to override it, you can use\n-e or -p to specify an EPSG code or Proj.4 string, respectively. If there is no\nprojection metadata and you do not specify one, EPSG:4326 will be used (WGS84\nlatitude-longitude)\n\nHeavily based on ogr2osm (https://github.com/pnorman/ogr2osm) released under\nthe following terms:\n\nCopyright (c) 2012-2013 Paul Norman , Sebastiaan Couwenberg\n, The University of Vermont \n\nReleased under the MIT license: http://opensource.org/licenses/mit-license.php\n\nBased very heavily on code released under the following terms:\n\n(c) Iván Sánchez Ortega, 2009\n\n###############################################################################\n# \"THE BEER-WARE LICENSE\": #\n# wrote this file. As long as you retain this notice #\n# you can do whatever you want with this stuff. If we meet some day, and you #\n# think this stuff is worth it, you can buy me a beer in return. #\n###############################################################################\n\n\"\"\"\n\nimport sys\nimport os\nimport arcpy\n\nimport utils\nfrom geom import *\n\n'''\nSince we will be running under ArcGIS 10.x+ we will always have python 2.5+\nand xml.etree.ElementTree. However, lxml (See http://lxml.de/tutorial.html)\nshould be the fastest method\n'''\ntry:\n from lxml import eTree\n\n utils.info(\"running with lxml.etree\")\nexcept ImportError:\n import xml.etree.ElementTree as eTree\n\n utils.info(\"running with ElementTree\")\n\n\nclass Options:\n id = 0 # ID to start counting from for the output file\n roundingDigits = 7 # Number of decimal places for rounding\n significantDigits = 9 # Number of decimal places for coordinates\n addVersion = False # Add version attributes. This can cause big problems.\n addTimestamp = False # Add timestamp attributes. This can cause problems.\n # Omit upload=false from the completed file to surpress JOSM warnings.\n noUploadFalse = True\n translations = {\n 'filterTags': lambda tags: tags,\n 'filterFeature': lambda arcfeature, fieldnames, reproject: arcfeature,\n 'filterFeaturePost': lambda feature, arcfeature, arcgeometry: feature,\n 'preOutputTransform': lambda geometries, features: None\n }\n # Input and output file\n # if no output file given, use the basename of the source but with .osm\n source = None\n outputFile = None\n translationmethod = None\n # If there are multiple point features within rounding distance of each\n # other, then arbitrarily ignore all but one\n mergePoints = False\n # if adjacent vertices in a feature are within rounding distance of each\n # other then generalize the line by omitting the 'redundant' vertices\n mergeWayPoints = False\n\n\ndef settranslation(translator):\n translations = None\n if translator:\n # add dirs to path if necessary\n (root, ext) = os.path.splitext(translator)\n if os.path.exists(translator) and ext == '.py':\n # user supplied translation file directly\n sys.path.insert(0, os.path.dirname(root))\n else:\n # first check translations in the subdir translations of cwd\n sys.path.insert(0, os.path.join(os.getcwd(), \"translations\"))\n # then check subdir of script dir\n sys.path.insert(1, os.path.join(os.path.dirname(__file__),\n \"translations\"))\n # (the cwd will also be checked implicitly)\n\n # strip .py if present, as import wants just the module name\n if ext == '.py':\n translator = os.path.basename(root)\n\n try:\n translations = __import__(translator, fromlist=[''])\n except ImportError:\n utils.die(\n u\"Could not load translation method '{0:s}'. Translation \"\n u\"script must be in your current directory, or in the \"\n u\"'translations' subdirectory of your current or \"\n u\"arc2osm.py directory. The following directories have \"\n u\"been considered: {1:s}\"\n .format(translator, str(sys.path)))\n except SyntaxError as e:\n utils.die(\n u\"Syntax error in '{0:s}'.\"\n \"Translation script is malformed:\\n{1:s}\"\n .format(translator, e))\n utils.info(\n u\"Successfully loaded '{0:s}' translation method ('{1:s}').\"\n .format(translator, os.path.realpath(translations.__file__)))\n else:\n utils.info(\"Using default translations\")\n\n for k in Options.translations:\n if hasattr(translations, k) and getattr(translations, k):\n Options.translations[k] = getattr(translations, k)\n utils.info(\"Using user \" + k)\n else:\n utils.info(\"Using default \" + k)\n\n\ndef parsedata(src):\n if not src:\n return\n shapefield = arcpy.Describe(src).shapeFieldName\n fieldnames = ['Shape@'] +\\\n [f.name for f in arcpy.ListFields(src)if f.name != shapefield]\n sr = arcpy.SpatialReference(4326) # WGS84\n with arcpy.da.SearchCursor(src, fieldnames, None, sr) as cursor:\n for arcfeature in cursor:\n parsefeature(Options.translations['filterFeature'](\n arcfeature, fieldnames, None), fieldnames)\n\n\ndef parsefeature(arcfeature, fieldnames):\n if not arcfeature:\n return\n # rely on parsedata() to put the shape at the beginning of the list\n arcgeometry = arcfeature[0]\n if not arcgeometry:\n return\n geometries = parsegeometry([arcgeometry])\n\n for geometry in geometries:\n if geometry is None:\n return\n\n feature = Feature()\n feature.tags = getfeaturetags(arcfeature, fieldnames)\n feature.geometry = geometry\n geometry.addparent(feature)\n\n Options.translations['filterFeaturePost'](feature, arcfeature,\n arcgeometry)\n\n\ndef getfeaturetags(arcfeature, fieldnames):\n \"\"\"\n This function builds up a dictionary with the source data attributes and\n passes them to the filterTags function, returning the result.\n \"\"\"\n tags = {}\n # skip the first field, as parsedata() put the shape there\n for i in range(len(fieldnames))[1:]:\n # arcpy returns unicode field names and field values (when text)\n # encode all values as unicode since osm only uses text\n if arcfeature[i]:\n if sys.version[0] < '3':\n tags[fieldnames[i].upper()] = unicode(arcfeature[i])\n else:\n tags[fieldnames[i].upper()] = str(arcfeature[i])\n\n return Options.translations['filterTags'](tags)\n\n\ndef parsegeometry(arcgeometries):\n returngeometries = []\n for arcgeometry in arcgeometries:\n geometrytype = arcgeometry.type\n # geometrytype in polygon, polyline, point, multipoint, multipatch,\n # dimension, or annotation\n if geometrytype == 'point':\n returngeometries.append(parsepoint(arcgeometry))\n elif geometrytype == 'polyline' and not arcgeometry.isMultipart:\n returngeometries.append(parselinestring(arcgeometry.getPart(0)))\n elif geometrytype == 'polygon' and not arcgeometry.isMultipart:\n returngeometries.append(parsepolygonpart(arcgeometry.getPart(0)))\n elif geometrytype == 'multipoint' or geometrytype == 'polyline' \\\n or geometrytype == 'polygon':\n returngeometries.extend(parsecollection(arcgeometry))\n else:\n utils.warn(\"unhandled geometry, type: \" + geometrytype)\n returngeometries.append(None)\n\n return returngeometries\n\n\ndef parsepoint(arcpoint):\n x = int(round(arcpoint.X * 10 ** Options.significantDigits))\n y = int(round(arcpoint.Y * 10 ** Options.significantDigits))\n geometry = Point(x, y)\n return geometry\n\n# TODO: parselinestring is inefficient O(n^2) where n = # of vertices.\n# For every vertex we need to search the\n# set of existing vertices (in a hash table, but still) to get the\n# \"real identity\" of this vertex if it exists.\n# This seems necessary to ensure that \"OSM topology\" is obtained - there\n# is only one node created when lines close of intersect\n\n# keep track of all vertices, by (rx,ry), in the dataset.\n# where (rx,ry) is the rounded coordinate as an int\nvertices = {}\n\n\ndef parselinestring(arcpointarray):\n geometry = Way()\n global vertices\n for arcPoint in arcpointarray:\n (x, y) = (arcPoint.X, arcPoint.Y)\n (rx, ry) = (int(round(x * 10 ** Options.roundingDigits)),\n int(round(y * 10 ** Options.roundingDigits)))\n if (rx, ry) in vertices:\n mypoint = vertices[(rx, ry)]\n else:\n (x, y) = (int(round(x * 10 ** Options.significantDigits)),\n int(round(y * 10 ** Options.significantDigits)))\n mypoint = Point(x, y)\n vertices[(rx, ry)] = mypoint\n geometry.points.append(mypoint)\n mypoint.addparent(geometry)\n return geometry\n\n\n# Special case for polygons with only one part\ndef parsepolygonpart(arcpointarray):\n # Outer and inner rings are separated by null points in array\n # the first ring is the outer, and the rest are inner.\n # TODO: Test\n start = 0\n outer = []\n inners = [] # a list of lists\n for i in range(len(arcpointarray)):\n if arcpointarray[i] is None:\n if start == 0:\n outer = arcpointarray[0:i]\n else:\n # ignore deviant case of sequential null points\n inners.append = arcpointarray[start:i]\n start = i + 1\n # finish the open ring\n if start == 0:\n outer = arcpointarray\n else:\n inners.append = arcpointarray[start:]\n\n geometry = Relation()\n exterior = parselinestring(outer)\n exterior.addparent(geometry)\n geometry.members.append((exterior, \"outer\"))\n for inner_ring in inners:\n interior = parselinestring(inner_ring)\n interior.addparent(geometry)\n geometry.members.append((interior, \"inner\"))\n return geometry\n\n\ndef parsecollection(arcgeometry):\n \"\"\"\n :param arcgeometry: is an arcpy.Geometry object (of various compound types)\n :return: a list of geom.Relations\n \"\"\"\n\n geometrytype = arcgeometry.type\n if geometrytype == 'polygon':\n # multipolygon (I already got the single part polygon in parsegeometry)\n for i in range(arcgeometry.partCount):\n parsepolygonpart(arcgeometry.getPart(i))\n geometries = []\n for polygon in range(arcgeometry.partCount):\n geometries.append(parsepolygonpart(arcgeometry.getPart(polygon)))\n return geometries # list of Relations\n elif geometrytype == 'polyline':\n # multipolyline (single part polyline handled in parsegeometry)\n geometries = []\n for linestring in range(arcgeometry.partCount):\n geometries.append(parselinestring(arcgeometry.getPart(linestring)))\n return geometries # list of Ways\n else:\n # multipoint\n geometry = Relation()\n for pnt in arcgeometry:\n member = parsepoint(pnt)\n member.addparent(geometry)\n geometry.members.append((member, \"member\"))\n return [geometry] # list of Points\n\n\n#TODO: mergepoints seems unecessary.\n#points have features (which carry the tags for geomety) as parents\n#so two nodes at the same location with different tags will be merged\n#the remaining node does not get a second parent (bug?), but the two\n#parents point to the same node after merging.\n#When output, the nodes are used to create a dictionary (node:feature},\n#and by the rules of python, the last feature found for a node will be the\n#one that is output.\n#put another way, tags for points with similar geometry are not merged,\n#rather one is arbitrarily ignored\n#either the tags should be merged (values for duplicate keys should be\n# concatenated?) or all points should be output, even if the geometry\n# is the same.\ndef mergepoints():\n \"\"\"\n From all the nodes we have created, remove those that are duplicate (by\n comparing location up to the rounding digits). Parents of the removed\n nodes (ways and relations) are updated to reference the retained\n version of the node)\n :return: Nothing, the list of nodes is in the global state\n \"\"\"\n utils.info(\"Merging points\")\n points = [geom for geom in Geometry.geometries if type(geom) == Point]\n\n # Make list of Points at each location\n utils.info(\"Merging points - Making lists\")\n pointcoords = {} # lists of points for each rounded location\n #TODO make faster by keeping separate dict of dup points (key by (rx,ry))\n for i in points:\n rx = int(round(i.x * 10 ** Options.roundingDigits))\n ry = int(round(i.y * 10 ** Options.roundingDigits))\n if (rx, ry) in pointcoords:\n pointcoords[(rx, ry)].append(i)\n else:\n pointcoords[(rx, ry)] = [i]\n\n # Use list to get rid of extras\n utils.info(\"Merging points - Reducing lists\")\n for (location, pointsatloc) in pointcoords.items():\n if len(pointsatloc) > 1:\n for point in pointsatloc[1:]:\n for parent in set(point.parents):\n parent.replacejwithi(pointsatloc[0], point)\n\n\n#TODO: consider value of mergewaypoints\n#This method is a simple generalizer by removing vertices that are close\n#(within rounding distance) of each other. Nodes in a way are already\n#de-dupped during parselinestring, so a line string may have have the same\n#node in non-adjacent locations (i.e. self intersecting or closed linestrings)\n#or at adjacent locations (i.e. high vertex density) this method finds and\n#collapses close adjacent locations into one vertex.\n#This method can be skipped if we are not interested in generalizing lines\ndef mergewaypoints():\n utils.info(\"Merging duplicate points in ways\")\n ways = [geom for geom in Geometry.geometries if type(geom) == Way]\n\n # Remove duplicate points from ways,\n # a duplicate has the same id as its predecessor\n for way in ways:\n previous = Options.id\n merged_points = []\n\n for node in way.points:\n if previous == Options.id or previous != node.id:\n merged_points.append(node)\n previous = node.id\n\n if len(merged_points) > 0:\n way.points = merged_points\n\n\ndef output_import(path):\n \"\"\"\n Writes an JOSM file (http://wiki.openstreetmap.org/wiki/JOSM_file_format)\n suitable for use with the\n :param path:\n :return:\n \"\"\"\n if not path:\n return\n utils.info(\"Outputting XML\")\n # First, set up a few data structures for optimization purposes\n nodes = [geom for geom in Geometry.geometries if type(geom) == Point]\n ways = [geom for geom in Geometry.geometries if type(geom) == Way]\n relations = [geom for geom in Geometry.geometries if\n type(geom) == Relation]\n featuresmap = {feature.geometry: feature for feature in Feature.features}\n\n # Open up the output file with the system default buffering\n with open(path, 'w') as f:\n\n if Options.noUploadFalse:\n f.write('\\n'\n '\\n')\n else:\n f.write('\\n'\n '\\n')\n\n # Build up a dict for optional settings\n attributes = {}\n if Options.addVersion:\n attributes.update({'version': '1'})\n\n if Options.addTimestamp:\n from datetime import datetime\n\n attributes.update({\n 'timestamp': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')})\n\n for node in nodes:\n xmlattrs = {'visible': 'true', 'id': str(node.id),\n 'lat': str(node.y * 10 ** -Options.significantDigits),\n 'lon': str(node.x * 10 ** -Options.significantDigits)}\n xmlattrs.update(attributes)\n\n xmlobject = eTree.Element('node', xmlattrs)\n\n if node in featuresmap:\n for (key, value) in featuresmap[node].tags.items():\n tag = eTree.Element('tag', {'k': key, 'v': value})\n xmlobject.append(tag)\n\n f.write(eTree.tostring(xmlobject))\n f.write('\\n')\n\n for way in ways:\n xmlattrs = {'visible': 'true', 'id': str(way.id)}\n xmlattrs.update(attributes)\n\n xmlobject = eTree.Element('way', xmlattrs)\n\n for node in way.points:\n nd = eTree.Element('nd', {'ref': str(node.id)})\n xmlobject.append(nd)\n if way in featuresmap:\n for (key, value) in featuresmap[way].tags.items():\n tag = eTree.Element('tag', {'k': key, 'v': value})\n xmlobject.append(tag)\n\n f.write(eTree.tostring(xmlobject))\n f.write('\\n')\n\n for relation in relations:\n xmlattrs = {'visible': 'true', 'id': str(relation.id)}\n xmlattrs.update(attributes)\n\n xmlobject = eTree.Element('relation', xmlattrs)\n\n for (member, role) in relation.members:\n member = eTree.Element('member',\n {'type': 'way', 'ref': str(member.id),\n 'role': role})\n xmlobject.append(member)\n\n tag = eTree.Element('tag', {'k': 'type', 'v': 'multipolygon'})\n xmlobject.append(tag)\n if relation in featuresmap:\n for (key, value) in featuresmap[relation].tags.items():\n tag = eTree.Element('tag', {'k': key, 'v': value})\n xmlobject.append(tag)\n\n f.write(eTree.tostring(xmlobject))\n f.write('\\n')\n\n f.write('')\n\n\ndef output_change(path, changeset=-1):\n \"\"\"\n Writes an osmChange file (see http://wiki.openstreetmap.org/wiki/OsmChange)\n suitable for use with the /api/0.6/changeset/#id/upload API\n :param path:\n :return:\n \"\"\"\n if not path:\n return\n utils.info(\"Outputting XML\")\n # First, set up a few data structures for optimization purposes\n nodes = [geom for geom in Geometry.geometries if type(geom) == Point]\n ways = [geom for geom in Geometry.geometries if type(geom) == Way]\n relations = [geom for geom in Geometry.geometries if\n type(geom) == Relation]\n featuresmap = {feature.geometry: feature for feature in Feature.features}\n\n # Open up the output file with the system default buffering\n #with open(path, 'w') as f:\n\n rootnode = eTree.Element('osmChange',\n {\"version\":\"0.6\", \"generator\":\"npsarc2osm\"})\n createnode = eTree.Element('create')\n rootnode.append(createnode)\n\n # Build up a dict for optional settings\n attributes = {}\n # changeset and version are required for API 0.6\n attributes.update({'changeset': str(changeset)})\n attributes.update({'version': '1'})\n if Options.addTimestamp:\n from datetime import datetime\n attributes.update({\n 'timestamp': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')})\n\n for node in nodes:\n xmlattrs = {'visible': 'true', 'id': str(node.id),\n 'lat': str(node.y * 10 ** -Options.significantDigits),\n 'lon': str(node.x * 10 ** -Options.significantDigits)}\n xmlattrs.update(attributes)\n\n xmlobject = eTree.Element('node', xmlattrs)\n\n if node in featuresmap:\n for (key, value) in featuresmap[node].tags.items():\n tag = eTree.Element('tag', {'k': key, 'v': value})\n xmlobject.append(tag)\n\n createnode.append(xmlobject)\n #f.write(eTree.tostring(xmlobject))\n #f.write('\\n')\n\n for way in ways:\n xmlattrs = {'visible': 'true', 'id': str(way.id)}\n xmlattrs.update(attributes)\n\n xmlobject = eTree.Element('way', xmlattrs)\n\n for node in way.points:\n nd = eTree.Element('nd', {'ref': str(node.id)})\n xmlobject.append(nd)\n if way in featuresmap:\n for (key, value) in featuresmap[way].tags.items():\n tag = eTree.Element('tag', {'k': key, 'v': value})\n xmlobject.append(tag)\n\n createnode.append(xmlobject)\n #f.write(eTree.tostring(xmlobject))\n #f.write('\\n')\n\n for relation in relations:\n xmlattrs = {'visible': 'true', 'id': str(relation.id)}\n xmlattrs.update(attributes)\n\n xmlobject = eTree.Element('relation', xmlattrs)\n\n for (member, role) in relation.members:\n member = eTree.Element('member',\n {'type': 'way', 'ref': str(member.id),\n 'role': role})\n xmlobject.append(member)\n\n tag = eTree.Element('tag', {'k': 'type', 'v': 'multipolygon'})\n xmlobject.append(tag)\n if relation in featuresmap:\n for (key, value) in featuresmap[relation].tags.items():\n tag = eTree.Element('tag', {'k': key, 'v': value})\n xmlobject.append(tag)\n\n createnode.append(xmlobject)\n #f.write(eTree.tostring(xmlobject))\n #f.write('\\n')\n xml = eTree.ElementTree(rootnode)\n xml.write(path, encoding='utf-8', xml_declaration=True)\n #f.write('\\n')\n\n\nif __name__ == '__main__':\n Options.source = arcpy.GetParameterAsText(0)\n Options.outputFile = arcpy.GetParameterAsText(1)\n Options.translationmethod = arcpy.GetParameterAsText(2)\n Options.source = \\\n r\"C:\\tmp\\places\\GOSP\\GOSP_TRANS_TRAILS_LN.gdb\\GOSP_TRANS_TRAILS_LN\"\n Options.outputFile = r\"C:\\tmp\\places\\GOSP\\GOSP_TRANS_TRAILS_LN.osm\"\n Options.translationmethod = \"trails\"\n Geometry.elementIdCounter = Options.id\n utils.info(\n u\"Preparing to convert '{0:s}' to '{1:s}'.\".format(Options.source,\n Options.outputFile))\n settranslation(Options.translationmethod)\n parsedata(Options.source)\n if Options.mergePoints:\n mergepoints()\n if Options.mergeWayPoints:\n mergewaypoints()\n Options.translations['preOutputTransform'](\n Geometry.geometries, Feature.features)\n # output_import(Options.outputFile)\n output_change(Options.outputFile)\n utils.info(u\"Wrote {0:d} elements to file '{1:s}'\"\n .format(Geometry.elementIdCounter, Options.outputFile))\n","sub_path":"arc2osm.py","file_name":"arc2osm.py","file_ext":"py","file_size_in_byte":23529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"228095229","text":"# Configuration file for the Sphinx documentation builder.\n#\nimport os\nimport sys\nsys.path.insert(0, os.path.abspath('..'))\n# For the full list of built-in configuration values, see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Project information -----------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information\n\nproject = 'RLevator'\ncopyright = '2023, Matthew Burke'\nauthor = 'Matthew Burke'\n\n# -- General configuration ---------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration\n\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx.ext.viewcode',\n 'sphinx.ext.napoleon',\n 'sphinx.ext.githubpages',\n 'myst_parser'\n]\n\ntemplates_path = ['_templates']\nexclude_patterns = ['_build']\n\nautoclass_content = 'both'\n\n# -- Options for HTML output -------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output\n\nhtml_theme = 'alabaster'\nhtml_static_path = ['static']\n","sub_path":"docs/source/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"416361602","text":"import numpy as np\nfrom sklearn.datasets import load_boston\nfrom keras.layers import LSTM, Dense\nfrom keras.models import Sequential\n\n\n#1. 데이터\n\"\"\"\ndata : x값\ntarget : y값\n\"\"\"\n\ndataset=load_boston()\nx=dataset.data\ny=dataset.target\n\nfrom sklearn.model_selection import train_test_split\nx_train,x_test,y_train,y_test=train_test_split(x,y,train_size=0.8)\nx_train=x_train.reshape(404,13,1)\nx_test=x_test.reshape(102,13,1)\n\n\n\nprint(\"x_train.shape:\",x_train.shape)\nprint(\"x_test.shape:\",x_test.shape)\nprint(\"y_train.shape:\",y_train.shape)\nprint(\"y_test.shape:\",y_test.shape)\n\nmodel=Sequential()\nmodel.add(LSTM(10,input_shape=(13,1),activation='relu'))\nmodel.add(Dense(20))\nmodel.add(Dense(10,activation='relu'))\nmodel.add(Dense(15,activation='relu'))\nmodel.add(Dense(1,activation='relu'))\n\nmodel.summary()\n\nmodel.compile(loss='mse',optimizer='adam',metrics=['mse'])\nfrom keras.callbacks import EarlyStopping\nearly_stopping=EarlyStopping(monitor='loss',patience=10,mode='aut')\nmodel.fit(x_train,y_train,epochs=10,batch_size=1)\n\nloss_acc=model.evaluate(x_test,y_test,batch_size=1)\n\ny_predict=model.predict(x_test)\n\nprint(\"y_predict:\",y_predict)\n\n\nfrom sklearn.metrics import mean_squared_error as mse\n\ndef RMSE(y_test,y_predict):\n return np.sqrt(mse(y_predict,y_test))\n\nprint(\"RMSE:\",RMSE(y_test,y_predict))\n\nfrom sklearn.metrics import r2_score\nr2=r2_score(y_test,y_predict)\nprint(\"R2:\",r2)\n\n","sub_path":"keras/keras74_boston_lstm.py","file_name":"keras74_boston_lstm.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"522300818","text":"import os\nimport fnmatch\nfrom datetime import datetime\nfrom . import base\n\n\nDATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S'\n\n\nclass Client(base.Client):\n name = 'Directory'\n\n description = '''\n Generator for a filesystem.\n '''\n\n options = {\n 'required': ['path'],\n\n 'properties': {\n 'path': {\n 'description': 'A local filesystem directory.',\n 'type': 'string',\n },\n 'recurse': {\n 'description': 'If true, directories will be recursed into.',\n 'type': 'boolean',\n 'default': True,\n },\n 'pattern': {\n 'description': 'Glob pattern for directories and files.',\n 'type': 'string',\n 'default': '*',\n },\n 'hidden': {\n 'description': 'If true, hidden files and directories will be included.', # noqa\n 'type': 'boolean',\n 'default': False,\n },\n 'depth': {\n 'description': 'The maximum depth to recurse into.',\n 'type': 'integer',\n }\n }\n }\n\n def parse_directory(self, path):\n path_id = os.path.relpath(path, self.options.path)\n\n return {\n 'origins:ident': path_id,\n 'prov:type': 'Directory',\n 'prov:label': path_id,\n 'path': path_id,\n }\n\n def parse_file(self, path):\n path_id = os.path.relpath(path, self.options.path)\n\n stats = os.stat(path)\n\n # Convert into datetime from timestamp floats\n atime = datetime.fromtimestamp(stats.st_atime)\n mtime = datetime.fromtimestamp(stats.st_mtime)\n\n if hasattr(stats, 'st_birthtime'):\n create_time = stats.st_birthtime\n else:\n create_time = stats.st_ctime\n\n ctime = datetime.fromtimestamp(create_time)\n\n return {\n 'origins:ident': path_id,\n 'prov:type': 'File',\n 'prov:label': path_id,\n 'path': path_id,\n 'mode': stats.st_mode,\n 'uid': stats.st_uid,\n 'gid': stats.st_gid,\n 'size': stats.st_size,\n 'accessed': atime.strftime(DATETIME_FORMAT),\n 'modified': mtime.strftime(DATETIME_FORMAT),\n 'created': ctime.strftime(DATETIME_FORMAT),\n }\n\n def parse(self):\n base_path = self.options.path\n\n for root, dirs, names in os.walk(base_path):\n if self.options.depth is not None:\n curpath = os.path.relpath(root, base_path)\n\n if curpath == '.':\n depth = 0\n else:\n depth = len(curpath.split(os.path.sep))\n\n # Remove all subdirectories from traversal once the\n # desired depth has been reached. Note a `break` does\n # not work since this would stop processing sibling\n # directories as well.\n for dirname in dirs[:]:\n if depth >= self.depth:\n dirs.pop()\n elif not self.options.hidden and dirname.startswith('.'):\n dirs.pop()\n\n directory = self.parse_directory(root)\n\n self.document.add('entity', directory)\n\n for f in fnmatch.filter(names, self.options.pattern):\n if not self.options.hidden and f.startswith('.'):\n continue\n\n path = os.path.join(root, f)\n\n _file = self.parse_file(path)\n _file['directory'] = directory\n\n self.document.add('entity', _file)\n","sub_path":"prov_extractor/sources/filesystem.py","file_name":"filesystem.py","file_ext":"py","file_size_in_byte":3692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"576010655","text":"ASSIGNMENT = 'Orange Group - Problem # 8'\r\nSTUDENT = 'hlambing'\r\n# Generators must be able to iterate through any iterable.\r\n# hide is present and called to ensure that your generator code works on\r\n# general iterable parameters (not just a string, list, etc.)\r\n# For example, although we can call len(string) we cannot call\r\n# len(hide(string)), so the generator functions you write should not\r\n# call len on their parameters\r\n# Leave hide in this file and add code for the other generators.\r\n\r\ndef hide(iterable):\r\n for v in iterable:\r\n yield v\r\n\r\n\r\n\r\n\r\ndef start_when(iterable,p):\r\n cruisecontrol = False #determines when the first character matching condition is found, so the loop can keep going\r\n for i in iterable:\r\n if cruisecontrol == True: #is there a more elegant way to do this? basically need a \"when p(i) is true once, append all the letters to the right of it regardless of if p(i) is still true or not)\r\n yield i\r\n elif p(i) == True: #p(i) checks if the lambda statement for current char is true [[[start_when('combustible', lambda x : x >='q')]]] from bsc.txt\r\n yield i\r\n cruisecontrol = True\r\n\r\n \r\n \r\ndef differences(iterable1,iterable2):\r\n for i, (a, b) in enumerate(zip(iterable1,iterable2)): # http://www.saltycrane.com/blog/2008/04/how-to-use-pythons-enumerate-and-zip-to/ <--explains enumerate(zip(crap))\r\n if a != b:\r\n yield((i + 1,a,b))\r\n \r\n\r\n \r\ndef once_in_a_row(iterable):\r\n last_value = object() #wont match anything\r\n for value in iterable: #this part loops? yield is werid.\r\n if value != last_value:\r\n yield value\r\n last_value = value\r\n\r\n \r\ndef alternate(*args):\r\n temp = [iter(arg) for arg in args]\r\n while True: #kinda crazy... not sure how it knows how to break out of the loop exactly, i guess\r\n for letters in temp: #it just happens automagically when next(letters) doesn't have anything else.\r\n yield next(letters)\r\n\r\n\r\ndef windows(iterable,n,m=1):\r\n res = []\r\n temp = iter(iterable) \r\n while True: # PHEW. this shit is bonkers. there's probably a much cleaner way of doing this\r\n if len(res) == n:\r\n del res[0:m]\r\n while len(res) < n:\r\n res.append(next(temp))\r\n if len(res) == 0:\r\n while len(res) < n:\r\n res.append(next(temp)) \r\n yield res\r\n \r\n# while fun:\r\n# temp = iter(iterable)\r\n# res = []\r\n# for i,a in enumerate(temp):\r\n# if start <= i < start + n:\r\n# res.append(a)\r\n# i = 0\r\n# a = 0\r\n# start += n - m\r\n# if len(res) < n:\r\n# fun = False #messy\r\n# else:\r\n# print(res)\r\n# yield res\r\n\r\n #what we need:::::\r\n# yield temp[start:start + n]\r\n# start += n - m \r\n \r\n \r\n# offset = 0\r\n# while True:\r\n# res = []\r\n# count = 0\r\n# for dook in temp:\r\n# while count < n:\r\n# res.append(next(dook))\r\n# count += 1\r\n# offset += m\r\n# yield res\r\n \r\n \r\nif __name__ == '__main__':\r\n from goody import irange\r\n # Uncomment these tests individually\r\n # to check your work. Then, run the batch self-checks.\r\n# # Test start_when; you can add your own test cases\r\n# print('Testing start_when')\r\n# for i in start_when('combustible', lambda x : x >= 'q'):\r\n# print(i,end='')\r\n# print('\\n')\r\n# \r\n# print('Testing start_when on hidden')\r\n# for i in start_when(hide('combustible'), lambda x : x >= 'q'):\r\n# print(i,end='')\r\n# print('\\n\\n')\r\n# \r\n# \r\n# # Test differences; you can add your own test cases\r\n# print('Testing differences')\r\n# for i in differences('3.14159265', '3x14129285'):\r\n# print(i,end=' ') \r\n# print('\\n')\r\n# \r\n# print('Testing differences on hidden')\r\n# for i in differences(hide('3.14159265'), hide('3x14129285')):\r\n# print(i,end=' ') \r\n# print('\\n\\n')\r\n# \r\n# \r\n# # Test once_in_a_row; you can add your own test cases\r\n# print('Testing once_in_a_row')\r\n# for i in once_in_a_row('abcccaaabddeee'):\r\n# print(i,end='') \r\n# print('\\n')\r\n# \r\n# print('Testing once_in_a_row on hidden')\r\n# for i in once_in_a_row(hide('abcccaaabddeee')):\r\n# print(i,end='') \r\n# print('\\n\\n')\r\n# \r\n# \r\n# # Test alternate; you can add your own test cases\r\n# print('Testing alternate')\r\n# for i in alternate('abcde','fg','hijk'):\r\n# print(i,end='')\r\n# print('\\n')\r\n# \r\n# print('Testing alternate on hidden')\r\n# for i in alternate(hide('abcde'), hide('fg'),hide('hijk')):\r\n# print(i,end='')\r\n# print('\\n\\n')\r\n# \r\n# \r\n# # Test windows; you can add your own test cases\r\n# print('Testing windows')\r\n# for i in windows('abcdefghijk',4,2):\r\n# print(i,end=' ')\r\n# print('\\n')\r\n# \r\n# print('Testing windows on hidden')\r\n# for i in windows(hide('abcdefghijk'),4,2):\r\n# print(i,end=' ')\r\n# print('\\n\\n')\r\n# \r\n \r\n import driver\r\n# driver.default_show_exception=True\r\n# driver.default_show_exception_message=True\r\n# driver.default_show_traceback=True\r\n driver.batch_self_check()\r\n \r\n","sub_path":"OG-Problem08/src/generators.py","file_name":"generators.py","file_ext":"py","file_size_in_byte":5502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"82964637","text":"#!/usr/bin/env python\n#\n# Copyright (C) 2013 Alexandros Avdis and others.\n# See the AUTHORS.md file for a full list of copyright holders.\n#\n# This file is part of setuptools-qmesh.\n#\n# setuptools-qmesh 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# setuptools-qmesh 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 setuptools-qmesh. If not, see .\n'''Set-up script for installation and packaging of setuptools-qmesh.\n\nThis script facilitates installation and packaging of setuptools-qmesh, through standardised\nprocedures and utilities. This project need not be explicitly installed by a user:\nsetuptools-qmesh facilitates installation and packaging of other qmesh packages. In\nparticular, setuptools-qmesh introduces commands, setup-keywords and egg-info writers that\nfacilitate the correct operation, installation and packaging of other qmesh packages.\nWhen ``pip`` is used, other qmesh packages will invoke installation of setuptools-qmesh.\nIn particular, a ``setuptools.setup`` call facilitates installation via ``pip``, or\n``(sudo) python setup.py ``.\n'''\n\ndef read(filename):\n '''Function reading file content.\n\n Function storing, and returning, file content as a string. Intended for reading the file\n containing the Version number and the read-me file during installation and packaging.\n\n Args:\n filename (str): Name of file to open and read contents.\n\n Returns:\n The file contents as a string (str).\n '''\n import os\n return open(os.path.join(os.path.dirname(__file__), filename)).read().strip()\n\ndef main():\n '''Function installing, packaging and testing the setuptools-qmesh package.\n\n This function makes a call to setuptools.setup, with appropriate arguments.\n '''\n import setuptools\n #Call setuptools setup() for installation, testing and packaging\n setuptools.setup(\n name='setuptools-qmesh',\n version=read('VERSION'),\n description=\"setuptools plugin for qmesh installation, packaging and testing\",\n long_description=read('README.rst'),\n author=\"The QMesh Development Team.\",\n author_email=\"develop@qmesh.org\",\n url=\"https://www.qmesh.org\",\n download_url='https://bitbucket.org/qmesh-developers/setuptools-qmesh/commits/tag/v'+\\\n read('VERSION'),\n packages=setuptools.find_packages(),\n entry_points={\n \"distutils.commands\":[\n \"check_qgis = setuptools_qmesh.command.check_qgis:CheckQgis\",\n \"check_gmsh = setuptools_qmesh.command.check_gmsh:CheckGmsh\"],\n \"distutils.setup_keywords\": [\n \"qgis_path = setuptools_qmesh.dist:assert_path\",\n \"gmsh_bin_path = setuptools_qmesh.dist:assert_path\",\n \"include_git_sha_key = setuptools.dist:assert_bool\",\n \"include_full_license = setuptools.dist:assert_bool\",\n \"include_author_ids = setuptools.dist:assert_bool\"],\n \"egg_info.writers\": [\n \"QGIS_PATH = setuptools_qmesh.command.egg_info:write_qgis_path\",\n \"GMSH_BIN_PATH = setuptools_qmesh.command.egg_info:write_gmsh_bin_path\",\n \"GIT_SHA_KEY = setuptools_qmesh.command.egg_info:write_git_sha_key\",\n \"LICENSE = setuptools_qmesh.command.egg_info:write_full_license\",\n \"AUTHORS.md = setuptools_qmesh.command.egg_info:write_author_ids\"]},\n license='GPLv3',\n install_requires=['GitPython'],\n test_suite=\"tests\",\n keywords=['GIS', 'mesh generation', 'setuptools'],\n tests_require=['pylint', 'pyenchant',\n 'sphinxcontrib-bibtex', 'sphinxcontrib-napoleon'],\n extras_require=dict(build_doc=['sphinxcontrib-bibtex', 'sphinxcontrib-napoleon'])\n )\n\nif __name__ == '__main__':\n main()\n","sub_path":"pypi_install_script/setuptools-qmesh-1.1.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":4369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"484106537","text":"# coding:utf-8\nfrom selenium import webdriver\nfrom common.base import Base\nimport time\nimport commonConfig.testDate as c\n# -------------定位元素信息------------ #\nloc1 = (\"xpath\", \"//*[@type='tel']\")\nloc2 = (\"xpath\", \"//*[@type='password']\")\nloc3 = (\"xpath\", \"//*[@type='button']\")\nloc4 = (\"xpath\", \"//*[@type='submit']\")\nloc5 = (\"xpath\", \"//*[@role='button']\")\nloc6 = (\"xpath\",\"//*[@class='el-badge l-margin-r-x2']\")\nloc7 = (\"xpath\",\"//*[@class='l-margin-b']/div[1]/b\")\ntext_0 = \"消息中心\"\ntext_1 = \"门店入网\"\n\n#test\nconfig = {\n \"shopName\":\"19867890019\",\n \"shopPwd\":\"890019\",\n \"adminName\":\"15976427941\",\n \"adminPwd\":\"1\",\n \"h5Name\":\"15976427950\",\n \"h5Pwd\":\"1\",\n \"h5path\":\"http://h5.hsbro.com.cn/?_plat=admin\",\n}\n# live\n# config = {\n# \"shopName\":\"15976427940\",\n# \"shopPwd\":\"1\",\n# \"adminName\":\"15976427940\",\n# \"adminPwd\":\"1\",\n# \"h5path\":\"http://h5.hsbro.cn/?_plat=admin\",\n# \"h5Name\":\"15976427941\",\n# \"h5Pwd\":\"hs123456\",\n# }\ndef _loginShop(driver, host ,user=config[\"shopName\"], psw=config[\"shopPwd\"]):\n zen = Base(driver)\n driver.maximize_window()\n driver.get(host+\"/?_plat=shop\")\n zen.sendKeys(loc1, user)\n zen.sendKeys(loc2, psw)\n zen.click(loc3)\n time.sleep(2)\n t = zen.get_text(loc6)\n assert text_0 in t\n\ndef _loginAdmin(driver, host, user=config[\"adminName\"], psw=config[\"adminPwd\"]):\n\n zen = Base(driver)\n driver.maximize_window()\n driver.get(host+\"/?_plat=admin\")\n zen.sendKeys(loc1, user)\n zen.sendKeys(loc2, psw)\n zen.click(loc3)\n time.sleep(2)\n t = zen.get_text(loc6)\n assert text_0 in t\n\ndef _loginH5(driver, user=config[\"h5Name\"], psw=config[\"h5Pwd\"],path=config[\"h5path\"]):\n\n zen = Base(driver)\n driver.set_window_size(500,1100)\n driver.get(path)\n zen.sendKeys(loc1, user)\n zen.sendKeys(loc2, psw)\n zen.click(loc4)\n time.sleep(2)\n t = zen.get_text(loc7)\n assert t == text_1\n\nif __name__ == \"__main__\":\n driver = webdriver.Chrome()\n _loginH5(driver)","sub_path":"hsbro/commonConfig/loginPage.py","file_name":"loginPage.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"259798232","text":"\"\"\"protocols.py :: Provide asyncio protocols for UPnP and SSDP discovery.\"\"\"\n\nimport asyncio\nimport uuid\nfrom email.utils import formatdate\nfrom typing import AnyStr, cast, Iterable\n\nfrom fauxmo import logger\nfrom fauxmo.plugins import FauxmoPlugin\nfrom fauxmo.utils import make_serial\n\n\nclass Fauxmo(asyncio.Protocol):\n \"\"\"Mimics a WeMo switch on the network.\n\n Aysncio protocol intended for use with BaseEventLoop.create_server.\n \"\"\"\n\n def __init__(self, name: str, plugin: FauxmoPlugin) -> None:\n \"\"\"Initialize a Fauxmo device.\n\n Args:\n name: How you want to call the device, e.g. \"bedroom light\"\n plugin: Fauxmo plugin\n \"\"\"\n self.name = name\n self.serial = make_serial(name)\n self.plugin = plugin\n self.transport = None # type: asyncio.Transport\n\n def connection_made(self, transport: asyncio.BaseTransport) -> None:\n \"\"\"Accept an incoming TCP connection.\n\n Args:\n transport: Passed in asyncio.Transport\n \"\"\"\n peername = transport.get_extra_info('peername')\n logger.debug(f\"Connection made with: {peername}\")\n self.transport = cast(asyncio.Transport, transport)\n\n def data_received(self, data: bytes) -> None:\n \"\"\"Decode incoming data.\n\n Args:\n data: Incoming message, either setup request or action request\n \"\"\"\n msg = data.decode()\n\n logger.debug(f\"Received message:\\n{msg}\")\n if msg.startswith('GET /setup.xml HTTP/1.1'):\n logger.debug(\"setup.xml requested by Echo\")\n self.handle_setup()\n\n elif msg.startswith('POST /upnp/control/basicevent1 HTTP/1.1'):\n self.handle_action(msg)\n\n def handle_setup(self) -> None:\n \"\"\"Create a response to the Echo's setup request.\"\"\"\n date_str = formatdate(timeval=None, localtime=False, usegmt=True)\n\n setup_xml = '\\r\\n'.join([\n '',\n '',\n '',\n 'urn:Fauxmo:device:controllee:1',\n f'{self.name}',\n 'Belkin International Inc.',\n 'Emulated Socket',\n '3.1415',\n f'uuid:Socket-1_0-{self.serial}',\n '',\n '']) + 2 * '\\r\\n'\n\n # Made as a separate string because it requires `len(setup_xml)`\n setup_response = '\\r\\n'.join([\n 'HTTP/1.1 200 OK',\n f'CONTENT-LENGTH: {len(setup_xml)}',\n 'CONTENT-TYPE: text/xml',\n f'DATE: {date_str}',\n 'LAST-MODIFIED: Sat, 01 Jan 2000 00:01:15 GMT',\n 'SERVER: Unspecified, UPnP/1.0, Unspecified',\n 'X-User-Agent: Fauxmo',\n 'CONNECTION: close']) + 2 * '\\r\\n' + setup_xml\n\n logger.debug(f\"Fauxmo response to setup request:\\n{setup_response}\")\n self.transport.write(setup_response.encode())\n self.transport.close()\n\n def handle_action(self, msg: str) -> None:\n \"\"\"Execute `on` or `off` method of `plugin`.\n\n Args:\n msg: Body of the Echo's HTTP request to trigger an action\n\n \"\"\"\n success = False\n if '0' in msg:\n logger.debug(f\"Attempting to turn off {self.plugin}\")\n success = self.plugin.off()\n\n elif '1' in msg:\n logger.debug(f\"Attempting to turn on {self.plugin}\")\n success = self.plugin.on()\n\n else:\n logger.debug(f\"Unrecognized request:\\n{msg}\")\n\n if success:\n date_str = formatdate(timeval=None, localtime=False, usegmt=True)\n response = '\\r\\n'.join([\n 'HTTP/1.1 200 OK',\n 'CONTENT-LENGTH: 0',\n 'CONTENT-TYPE: text/xml charset=\"utf-8\"',\n f'DATE: {date_str}',\n 'EXT:',\n 'SERVER: Unspecified, UPnP/1.0, Unspecified',\n 'X-User-Agent: Fauxmo',\n 'CONNECTION: close']) + 2 * '\\r\\n'\n logger.debug(response)\n self.transport.write(response.encode())\n else:\n errmsg = f\"Unable to complete command in {self.plugin}:\\n{msg}\"\n logger.warning(errmsg)\n self.transport.close()\n\n\nclass SSDPServer(asyncio.DatagramProtocol):\n \"\"\"UDP server that responds to the Echo's SSDP / UPnP requests.\"\"\"\n\n def __init__(self, devices: Iterable[dict] = None) -> None:\n \"\"\"Initialize an SSDPServer instance.\n\n Args:\n devices: Iterable of devices to advertise when the Echo's SSDP\n search request is received.\n \"\"\"\n self.devices = list(devices or ())\n self.transport = None # type: asyncio.DatagramTransport\n\n def add_device(self, name: str, ip_address: str, port: int) -> None:\n \"\"\"Keep track of a list of devices for logging and shutdown.\n\n Args:\n name: Device name\n ip_address: IP address of device\n port: Port of device\n \"\"\"\n device_dict = {\n 'name': name,\n 'ip_address': ip_address,\n 'port': port\n }\n self.devices.append(device_dict)\n\n def connection_made(self, transport: asyncio.BaseTransport) -> None:\n \"\"\"Set transport attribute to incoming transport.\n\n Args:\n transport: Incoming asyncio.DatagramTransport\n \"\"\"\n self.transport = cast(asyncio.DatagramTransport, transport)\n\n def datagram_received(self, data: AnyStr, addr: str) -> None:\n \"\"\"Check incoming UDP data for requests for Wemo devices.\n\n Args:\n data: Incoming data content\n addr: Address sending data\n \"\"\"\n logger.debug(f\"Received data below from {addr}:\")\n logger.debug(str(data))\n\n if all(b in data for b in [b'\"ssdp:discover\"',\n b'urn:Belkin:device:**']):\n self.respond_to_search(addr)\n\n def respond_to_search(self, addr: str) -> None:\n \"\"\"Build and send an appropriate response to an SSDP search request.\n\n Args:\n addr: Address sending search request\n \"\"\"\n date_str = formatdate(timeval=None, localtime=False, usegmt=True)\n for device in self.devices:\n\n name = device.get('name')\n ip_address = device.get('ip_address')\n port = device.get('port')\n\n location = f'http://{ip_address}:{port}/setup.xml'\n serial = make_serial(name)\n response = '\\r\\n'.join([\n 'HTTP/1.1 200 OK',\n 'CACHE-CONTROL: max-age=86400',\n f'DATE: {date_str}',\n 'EXT:',\n f'LOCATION: {location}',\n 'OPT: \"http://schemas.upnp.org/upnp/1/0/\"; ns=01',\n f'01-NLS: {uuid.uuid4()}',\n 'SERVER: Unspecified, UPnP/1.0, Unspecified',\n 'ST: urn:Belkin:device:**',\n f'USN: uuid:Socket-1_0-{serial}::urn:Belkin:device:**'\n ]) + 2 * '\\r\\n'\n\n logger.debug(f\"Sending response to {addr}:\\n{response}\")\n self.transport.sendto(response.encode(), addr)\n\n def connection_lost(self, exc: Exception) -> None:\n \"\"\"Handle lost connections.\n\n Args:\n exc: Exception type\n \"\"\"\n if exc:\n logger.warning(f\"SSDPServer closed with exception: {exc}\")\n","sub_path":"venv/lib/python3.5/site-packages/fauxmo/protocols.py","file_name":"protocols.py","file_ext":"py","file_size_in_byte":7560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"469605876","text":"\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the sockMerchant function below.\n# given n number of socks and array of colors of the socks. How many pairs are there?\n# count number of a single color, there will be count // 2 number of pairs\n# add number of pairs to result and loop to next number\n# added cache to prevent counting a number again\n\n\ndef sockMerchant(n, ar):\n result = 0\n cache = []\n for i in range(n-1):\n if ar[i] not in cache:\n cache.append(ar[i])\n count = ar.count(ar[i])\n pairs = count // 2\n result += pairs\n\n return result\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input())\n\n ar = list(map(int, input().rstrip().split()))\n\n result = sockMerchant(n, ar)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","sub_path":"HackerRankInterviewPrep/SockMerchant.py","file_name":"SockMerchant.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"549908046","text":"# To add a new cell, type '# %%'\n# To add a new markdown cell, type '# %% [markdown]'\n\n# %%\nimport pandas as pd\n\ndf = pd.read_csv('pokemon_data.csv')\n\ndf.head(5)\n\n\n# %%\ndf[['Name', 'HP', 'Speed']][0:4]\n\n\n# %%\ndf.iloc[3]\n\n\n# %%\ndf.iloc[2,1]\n\n\n# %%\ndf.loc[df['Type 1'] == \"Fire\"]\n\n\n# %%\ndf.describe()\n\n# %% [markdown]\n# # Sorting Data\n\n# %%\ndf.sort_values('Name', ascending = False)\n\n\n# %%\ndf.sort_values(['HP','Name'], ascending = [0,1]) #[false, true]\n\n# %% [markdown]\n# # Making Changes in Data\n\n# %%\ndf['Total'] = df['HP'] + df['Attack'] + df['Defense'] + df['Sp. Atk'] + df['Sp. Def'] + df['Speed']\n\ndf.sort_values(['Total'] , ascending = False)\n\n\n# %%\ndf = df.drop(columns= ['Total'])\n\ndf.head(5)\n\n\n# %%\ndf['Total'] = df.iloc[:, 4:10].sum(axis = 1)\n\n\ncols = list(df.columns)\n# df = df[cols[0:4] + [cols[-1]] + cols[4:12]] \n# running this multiple time will be a mess \n\ndf.head(7)\n\n\n# %%\ndf.to_csv('modified.csv', index = False)\ndf.to_csv('modified.txt', index = False, sep ='\\t')\n\ndf\n\n# %% [markdown]\n# # Filtering\n\n# %%\nnew_df = df.loc[(df['Type 1'] == 'Fire') & (df['Type 2'] == 'Flying') | (df['HP'] > 200)]\n\nnew_df.reset_index(drop = 1, inplace = True)\n\nnew_df\n\n\n# %%\ndf.loc[~df['Name'].str.contains('Mega')]\n\n\n# %%\nimport re\n\ndf.loc[df['Type 1'].str.contains('fire|grass', flags=re.I, regex=True)]\n\n\n# %%\ndf.loc[df['Name'].str.contains('^pi[a-z]*', flags=re.I, regex=True)]\n\n# %% [markdown]\n# # Conditional Changes\n\n# %%\ndf.loc[(df['Total']>600) & (df['Legendary']==True), 'Legendary'] = 'Hell Yeah True'\n\ndf.loc[df['Legendary'] == 'Hell Yeah True']\n\n# %% [markdown]\n# # Aggregate Statics\n\n# %%\ndf.groupby(['Type 1']).mean().sort_values('HP', ascending = False)\n\n\n# %%\ndf.groupby(['Type 1']).count()['#']\n\n# %% [markdown]\n# \n# # Working With Large Files\n\n# %%\nfor df in pd.read_csv('pokemon_data.csv', chunksize = 10):\n print(\"\\nChunk DF\\n\")\n print(df)\n\n\n# %%\n\n\n","sub_path":"Pandas/pokemon.py","file_name":"pokemon.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"405807171","text":"import re\nimport torch\n\nfrom argparse import ArgumentParser\n\nfrom model import RNN_CRF as rnn_crf\nfrom utils import load_tkn_to_idx, load_idx_to_tkn, load_checkpoint, batchify, normalize, tokenize, iob_to_txt\nfrom parameters import BATCH_SIZE, EOS_IDX, CUDA, UNK_IDX, UNIT, FORMAT\n\n\ndef load_model(args):\n cti = load_tkn_to_idx(args.char_to_idx) # char_to_idx\n wti = load_tkn_to_idx(args.word_to_idx) # word_to_idx\n itt = load_idx_to_tkn(args.idx_to_tag) # idx_to_tag\n model = rnn_crf(len(cti), len(wti), len(itt))\n print(model)\n load_checkpoint(args.model, model)\n return model, cti, wti, itt\n\n\ndef run_model(model, itt, batch):\n batch_size = len(batch) # real batch size\n while len(batch) < BATCH_SIZE:\n batch.append([-1, \"\", [[]], [EOS_IDX], []])\n batch.sort(key=lambda x: -len(x[3]))\n xc, xw = batchify(*zip(*[(x[2], x[3]) for x in batch]), sos=False, eos=False)\n result = model.decode(xc, xw)\n for i in range(batch_size):\n batch[i].append([itt[j] for j in result[i]])\n return [(x[1], x[4], x[5]) for x in sorted(batch[:batch_size])]\n\n\ndef predict(filename, model, cti, wti, itt):\n data = []\n with open(filename) as infile:\n for idx, line in enumerate(infile):\n line = line.strip()\n if FORMAT == \"char+iob\":\n wti = cti\n x, y = tokenize(line, UNIT), []\n for w in line.split(\" \"):\n y.extend([\"B\"] + [\"I\"] * (len(w) - 1))\n elif re.match(\"(\\S+/\\S+( |$))+\", line): # if FORMAT == \"word+tag\":\n x, y = zip(*[re.split(\"/(?=[^/]+$)\", x) for x in line.split()])\n x = [normalize(x) for x in x]\n else:\n x, y = tokenize(line, UNIT), None\n xc = [[cti[c] if c in cti else UNK_IDX for c in w] for w in x]\n xw = [wti[w] if w in wti else UNK_IDX for w in x]\n data.append([idx, line, xc, xw, y])\n with torch.no_grad():\n model.eval()\n for i in range(0, len(data), BATCH_SIZE):\n batch = data[i:i + BATCH_SIZE]\n for y in run_model(model, itt, batch):\n yield y\n\n\ndef parse_args():\n parser = ArgumentParser()\n parser.add_argument(\"model\")\n parser.add_argument(\"char_to_idx\")\n parser.add_argument(\"word_to_idx\")\n parser.add_argument(\"idx_to_tag\")\n parser.add_argument(\"test_data\")\n return parser.parse_args()\n\n\ndef main():\n args = parse_args()\n print(\"cuda: %s\" % CUDA)\n result = predict(args.test_data, *load_model(args))\n for x, y0, y1 in result:\n if FORMAT == \"char+iob\":\n print((x, iob_to_txt(x, y1, UNIT)))\n else:\n print((x, y0, y1) if y0 else (x, y1))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"516598555","text":"N = int(input())\nA = list(map(int, input().split()))\ndp = A.copy()\nfor i in range(len(A)):\n for j in range(i):\n if A[j] < A[i]:\n '''\n Test Case\n 10\n 1 100 55 50 60 3 5 6 7 8\n '''\n dp[i] = max(dp[i], dp[j]+A[i])\nprint(max(dp))\n","sub_path":"DP/11055.py","file_name":"11055.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"133247253","text":"from selenium import webdriver\nimport time\n\ndriver = webdriver.Chrome('C:/Users/vikky/PycharmProjects/selenium/training/chromedriver')\n\ndriver.maximize_window()\n\ndriver.get('http://demowebshop.tricentis.com/')\ntime.sleep(2)\nimages=driver.find_elements_by_xpath(\"//img\")\nprint(\"total images on the page:\", len(images))\ntime.sleep(2)\n\n\n\n\ndriver.quit()","sub_path":"locators.py","file_name":"locators.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"362512103","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 29 17:17:23 2019\n\n@author: lapi7\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 28 13:37:07 2019\n\n@author: lapi7\n\"\"\"\n\nimport networkx as nx\nimport numpy as np \nimport pandas as pd\nimport random as rdm\nimport matplotlib.pyplot as plt\nfrom time import time\nimport datetime as dt\nfrom scipy.stats import truncnorm\nfrom networkx.algorithms.flow import boykov_kolmogorov\nfrom networkx.algorithms.flow import maximum_flow\nfrom networkx.algorithms.flow import edmonds_karp\n\ndef lee_grafo(adress):\n ds = pd.read_csv((adress+\".csv\"), header=None)\n G = nx.from_pandas_adjacency(ds) \n return G\n\ndef calcula_tiempo(G,a,b):\n start_time=time() \n# fm=nx.maximum_flow(G, a, b,capacity=\"weight\")\n for i in range (100):\n fm=edmonds_karp(G, a, b,capacity=\"weight\")\n print(i)\n time_elapsed = time() - start_time\n \n return time_elapsed\n \n\ndef Todo(G,nombre):\n dic={\"Grafo\":[],\n \"Fuente\":[],\n \"Sumidero\":[] , \n \"Mediatime\":[],\n \"Medianatime\":[],\n \"Stdtime\":[],\n \"Flujomaximo\":[],\n \"DistGrado\":[],\n \"CoefAgrup\":[],\n \"CentCercania\":[],\n \"CentCarga\":[],\n \"ExcentCarga\":[],\n \"PageR\":[]}\n \n Nodes=G.nodes;\n for i in Nodes:\n for j in Nodes: \n if i!=j: \n t=[] \n for k in range(10):\n t.append(calcula_tiempo(G,i,j)) \n dic[\"Grafo\"].append(nombre)\n dic[\"Fuente\"].append(i) \n dic[\"Sumidero\"] .append(j) \n dic[\"Mediatime\"].append(np.mean(t)) \n dic[\"Medianatime\"].append(np.median(t)) \n dic[\"Stdtime\"].append(np.std(t))\n dic[\"Flujomaximo\"].append(nx.maximum_flow_value(G,i,j,capacity=\"weight\"))\n \n dic[\"DistGrado\"].append(G.degree(i))\n dic[\"CoefAgrup\"].append(nx.clustering(G,i))\n dic[\"CentCercania\"].append(nx.closeness_centrality(G,i))\n dic[\"CentCarga\"].append(nx.load_centrality(G,i))\n dic[\"ExcentCarga\"].append(nx.eccentricity(G,i))\n PageR=nx.pagerank(G,weight=\"capacity\")\n dic[\"PageR\"].append(PageR[i])\n \n \n df=pd.DataFrame(dic)\n df.to_csv(\"CSVunido.csv\", index=None, mode=\"a\") \n\n\ni=[\"grafo1\", \"grafo2\", \"grafo3\", \"grafo4\", \"grafo5\"]\nfor x in i:\n print (x)\n G=lee_grafo(x)\n Todo(G,x) \n \n\nprint(\"fin\")","sub_path":"Tarea No.5/T5Paraunircsvfinal.py","file_name":"T5Paraunircsvfinal.py","file_ext":"py","file_size_in_byte":2552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"416269237","text":"import json\nstudent1={\n \"name\":\"era\",\n \"mark\":4.5,\n \"marks\":[5,5,5,3,4],\n}\nstudent2={\n \"name\":\"china\",\n \"mark\":5,\n \"marks\":[3,4,2,3,4],\n}\nstudents=[student1,student2]\nwith open(\"students.json\",\"w\") as filewrite:\n json.dump(students,filewrite,indent=4)\n","sub_path":"Lesson8/7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"551734555","text":"# coding=utf-8\n# This is a sample Python script.\n\n# Press ⌃R to execute it or replace it with your code.\n# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.\n\n\n# This is a sample Python script.\n\n# Press ⌃R to execute it or replace it with your code.\n# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nresponse = requests.get(\"http://www.metoffice.gov.uk/pub/data/weather/uk/climate/stationdata/heathrowdata.txt\")\n# get txt file\n\ndata = response.text\n\nhighs = []\nlows = []\nhighs_f = [] # result\nlows_f = []\n\ndata_rows = []\n\nrainfall = []\nrainfall_f = [] # final #result\n\nyears = []\nyears_f = []\n\nyearHigh_temp = {}\nyearLows = {}\nyearRainfall = {}\n\nfor row in data.split(\"\\n\")[7:]:\n # start row from 8th(7index) new lines\n\n fields = [x for x in row.split(\" \") if x]\n # x is nothing, split(empty), if x is nothing\n # assign row[index]\n\n data_rows.append(fields)\n # append each row\n\n year = int(fields[0]) # first element of fields\n years.append(year)\n\n yearHigh_temp.setdefault(year, [])\n yearLows.setdefault(year, [])\n yearRainfall.setdefault(year, [])\n\n yearRainfall[year].append(float(fields[5])) # For assigned year, 6th element of fields is added\n yearHigh_temp[year].append(float(fields[2])) # For assigned year, 3rd element of fields is added\n yearLows[year].append(float(fields[3]))\n\n rainfall.append(float(fields[5]))\n highs.append(float(fields[2]))\n lows.append(float(fields[3]))\n\nyears_f = list(dict.fromkeys(yearHigh_temp))\n## Dictionary An iterable specifying the keys of the new dictionary\n\nlowest = 100\nhighest = 0\n\n# get the highs and lows for the whole table( put in highs and lows )\nfor i in highs:\n if highest < i:\n highest = i\n\nfor i in lows:\n if lowest > i:\n lowest = i\n\n# Double loop\nfor i in yearHigh_temp:\n l = len(yearHigh_temp[i])\n # length of the temperature list for this year\n\n high = 0\n\n for j in range(l):\n if (yearHigh_temp[i][j] > high):\n high = yearHigh_temp[i][j]\n # highest temperature for this year\n\n highs_f.append(high)\n\nfor i in yearLows:\n l = len(yearLows[i])\n low = 100\n # length of the temperature list for this year\n\n for j in range(l):\n if (yearLows[i][j] < low):\n low = yearLows[i][j]\n # lowest temperature for this year\n\n lows_f.append(low)\n\nfor i in yearRainfall:\n l = len(yearRainfall[i])\n # length of rainfall list for this year\n\n rain = 0\n\n for j in range(l):\n rain += yearRainfall[i][j]\n\n rainfall_f.append(rain / l)\n # avg rain fall\n\nprint(\"Average rainfall = {:.1f} mm\".format(sum(rainfall) / len(rainfall)))\nprint(\"The highest temperature in degrees = {}\".format(highest))\nprint(\"The lowest temperature in degrees = {}\".format(lowest))\nprint(\"Year Highest_Degree Lowest_Degree Rainfall\")\n\nfor i in range(len(years_f)):\n print(\"{0}{1:10}{2:15}{3:15.1f}\".format(years_f[i], highs_f[i], lows_f[i], rainfall_f[i]))\n \"\"\"{years_f[i]} {highs_f[i]: the number for the field size} {lows_f[i]: the number for the field size} \n {rainfall_f[i]: the number for the field size. 1 decimal digit }\"\"\"\n","sub_path":"Retrieving files over HTTP and web scraping with beautiful soup/retrieving_http.py","file_name":"retrieving_http.py","file_ext":"py","file_size_in_byte":3285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"268918213","text":"# -*- coding: utf-8 -*-\n\"\"\"\nUpdated on Tue Mar 07 07:22:23 2017\n\nNAME: SystemResponse.py\n\nPURPOSE: Analyzes response of 1260mm-CLR-ST2000 system.\n\n@author: steven.hill\nUpdate: 4/8/2018\n\nThis script plots the responses of the 1260mm-CLR-ST2000 combinations. \nIt also computes the equivalent widths and mean sensitivities of filter \nwindows. Input data are text files of spectra. Program \ncontrol is by a series of configuration files.\n\n****INPUT PARAMETERS (hard coded as of 6/8/16):\n Filter - This string identifies the filter by a alphanumeric index\n that includes the approximate central wavelength, e.g., 380NUV\n Target - This string identifies the target, e.g., \"Jupiter\", \"Vega\", etc.\n This parameter allows the lookup of the target type, e.g.,\n \"Planet\", \"Star\", etc. that permits construction of directory\n paths.\n DateUT - The UT date of the observation. Combined with Target, this forms\n a unique key to the observation, assuming that most unique parameters\n are invariant over a single observing night.\n \nINPUT FILES:\n FluxCalPlotConfig.txt - Master list of target plots, parameters and data.\n It provides pointers to other tables controlling inputs data. See\n the GitHub wiki for the Techniques project for more details on the\n metadata.\n Spectral Files - The actual data plotted are spectral response files. \n These files can have been produced by one of several spectra-from-FITS\n programs.\n \nOUTPUTS:\n Graphics Files - PNG plots are sent to the \n ../Projects/Techniques/Flux Calibration directory\n Equivalent widths - text files are sent to the \n ../Projects/Techniques/Flux Calibration directory\n\"\"\"\nimport sys\ndrive='f:'\nsys.path.append(drive+'\\\\Astronomy\\Python Play')\nsys.path.append(drive+'\\\\Astronomy\\Python Play\\Techniques Library')\nsys.path.append(drive+'\\\\Astronomy\\Python Play\\Galaxies')\n\nimport matplotlib.pyplot as pl\nimport pylab\nimport numpy as np\nimport SysRespLIB as SRL\n\n#RETRIEVE ST2000 RESPONSES#####################################################\npath=drive+\"/Astronomy/Projects/Techniques/Flux Calibration/\"\n# Read and reshape spectral data files \n\nManCamData=SRL.manufacturer_camera_data(path+\"CameraResponse-ST2000Data.txt\")\nManCamData.load_all_data()\nManCamData.uniform_wave_grid()\n\nC8_StarBright_Data=SRL.manufacturer_Celestrom_data(path+\"CameraResponse - StarBright.txt\")\nC8_StarBright_Data.load_all_data()\nC8_StarBright_Data.uniform_wave_grid()\n\nC8_StarBrightXLT_Data=SRL.manufacturer_Celestrom_data(path+\"CameraResponse - StarBrightXLT.txt\")\nC8_StarBrightXLT_Data.load_all_data()\nC8_StarBrightXLT_Data.uniform_wave_grid()\n\nAtmosphere_Data=SRL.atmosphere_data(path+\"CameraResponse - Atmosphere.txt\")\nAtmosphere_Data.load_all_data()\nAtmosphere_Data.uniform_wave_grid()\n\nCLRPlotParams=SRL.SysResp_plot_params(\"FluxCalPlotConfig.txt\")\nCLRPlotParams.loadplotparams(drive,\"550CLR\",\"TBD\")\nCLR550_ObsList=SRL.measurement_list(CLRPlotParams.DataFile)\nCLR550_ObsList.load_select_data(\"1260mm200lpm\")\nMean200linespermm1260mm=SRL.SpectrumAggregation(\"f:\",CLR550_ObsList)\nMean200linespermm1260mm.ComputeAverageandStats()\ntmp=SRL.Compute_EWs(path,\"1260mm200lpm-550CLR-EW\",Mean200linespermm1260mm.MeanSpec,1.0189)\nnp.savetxt(path+'SystemResponseCLR-1260mm200lpm.txt',Mean200linespermm1260mm.MeanSpec,delimiter=\" \",\n fmt=\"%10.3F %10.7F %10.7F %10.7F\")\n\nCLR550_ObsList.load_select_data(\"1260mm100lpm\")\nMean100linespermm1260mm=SRL.SpectrumAggregation(\"f:\",CLR550_ObsList)\nMean100linespermm1260mm.ComputeAverageandStats()\n\nCLR550_ObsList.load_select_data(\"135mm100lpm\")\nMean100linespermm135mm=SRL.SpectrumAggregation(\"f:\",CLR550_ObsList)\nMean100linespermm135mm.ComputeAverageandStats()\ntmp=SRL.Compute_EWs(path,\"135mm100lpm-550CLR-EW\",Mean100linespermm135mm.MeanSpec,1.0224)\nnp.savetxt(path+'SystemResponseCLR-135mm100lpm.txt',Mean100linespermm135mm.MeanSpec,delimiter=\" \",\n fmt=\"%10.3F %10.7F %10.7F %10.7F\")\n\nCLR550_ObsList.load_select_data(\"135mm200lpm\")\nMean200linespermm135mm=SRL.SpectrumAggregation(\"f:\",CLR550_ObsList)\nMean200linespermm135mm.ComputeAverageandStats()\n\n#RETRIEVE FILTER RESPONSES#####################################################\nNIRPlotParams=SRL.SysResp_plot_params(\"FluxCalPlotConfig.txt\")\nNIRPlotParams.loadplotparams(drive,\"685NIR\",\"TBD\")\nNIR685_ObsList=SRL.measurement_list(NIRPlotParams.DataFile)\nNIR685_ObsList.load_all_data()\nMeanNIRtmp=SRL.SpectrumAggregation(\"f:\",NIR685_ObsList)\nMeanNIRtmp.ComputeAverageandStats()\nMeanNIR135mm=MeanNIRtmp.MeanSpec[430:2325,:]\n\n#MAKE ST2000 MEASURED RESPONSE PLOT#####################################################\nCLRPlotParams.Setup_Plot()\ntmp=SRL.Draw_with_Conf_Level(Mean200linespermm1260mm.MeanSpec,1.0189,'C0','1260mm200lpm')\ntmp=SRL.Draw_with_Conf_Level(Mean100linespermm1260mm.MeanSpec,1.0,'b','1260mm100lpm')\npl.legend(loc=0,ncol=2, borderaxespad=0.,prop={'size':6})\npl.subplots_adjust(left=0.08, bottom=0.15, right=0.98, top=0.92,\n wspace=None, hspace=None)\npylab.savefig(path+'Response1260mmCLR-Measured.png',dpi=300)\n\n\nCLRPlotParams.Setup_Plot()\n\n#Plot Mfg. QE -> response to photon counts\n#pl.scatter(ManCamData.Wavelength,ManCamData.ST2000_Norm,\n# label='ST2000 SBIG QE',s=20,color='b')\n#Plot Mfg. response to energy (~QE/wavelength)\nEnergyResponse=ManCamData.griddata/ManCamData.wavegrid*450.\n\n#pl.scatter(ManCamData.Wavelength,np.array(ManCamData.ST2000_Norm)/\n# np.array(ManCamData.Wavelength)*450.,\n# label='ST2000 SBIG Ergs',s=20,color='g')\n\npl.plot(ManCamData.wavegrid,ManCamData.griddata,\n label='ST2000 SBIG Response',linewidth=1.0,color='C7')\n\npl.plot(Atmosphere_Data.wavegrid,Atmosphere_Data.griddata,\n label='Atmospheric Transmission',linewidth=1.0,color='b')\n\n\npl.plot(C8_StarBrightXLT_Data.wavegrid,C8_StarBright_Data.griddata*EnergyResponse,\n label='StarBright Response',linewidth=1.0,color='C1')\npl.plot(C8_StarBrightXLT_Data.wavegrid,C8_StarBrightXLT_Data.griddata*EnergyResponse,\n label='StarBrightXLT Response',linewidth=1.0,color='C1')\n\n#PLOT TOTAL SYSTEM RESPONSE MODELS\npl.plot(C8_StarBright_Data.wavegrid,\n (C8_StarBright_Data.griddata*EnergyResponse*Atmosphere_Data.griddata)/0.52,\n label='StarBright Energy Response',linewidth=1.0,color='g')\npl.plot(C8_StarBright_Data.wavegrid,\n (C8_StarBright_Data.griddata*ManCamData.griddata*Atmosphere_Data.griddata)/0.62,\n label='Total System Response',linewidth=1.0,color='k')\npl.plot(C8_StarBrightXLT_Data.wavegrid,\n (C8_StarBrightXLT_Data.griddata*EnergyResponse*Atmosphere_Data.griddata)/0.6,\n label='XLT Model Response',linewidth=1.0,color='r')\n\npl.legend(loc=0,ncol=2, borderaxespad=0.,prop={'size':6})\npl.subplots_adjust(left=0.08, bottom=0.15, right=0.98, top=0.92,\n wspace=None, hspace=None)\npylab.savefig(path+'Response1260mmCLR-Modeled.png',dpi=300)\n\n","sub_path":"Response1260mmCLR.py","file_name":"Response1260mmCLR.py","file_ext":"py","file_size_in_byte":6966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"124653527","text":"from django.shortcuts import render,redirect\nfrom.models import *\nfrom restaurant.models import *\nfrom django.shortcuts import get_object_or_404\nfrom django.http import HttpResponseRedirect\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nimport sys, os\n \n@login_required(login_url='/accounts/cust/login/')\ndef add_cart(request , menu_id):\n try:\n customer=request.user.customer \n catr_obj, created=Cart.objects.get_or_create(customer=customer,is_paid=False)\n menu_obj=RestrauntMenu.objects.get(id=menu_id)\n print(catr_obj)\n if catr_obj.cart.filter(restraunt_menu=menu_obj).exists():\n cart_item_obj=CartItems.objects.get(cart=catr_obj,restraunt_menu=menu_obj)\n cart_item_obj.quantity +=1\n cart_item_obj.save()\n else:\n CartItems.objects.create(\n cart=catr_obj,\n restraunt_menu=menu_obj\n )\n \n except Exception as e:\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n print(exc_type, fname, exc_tb.tb_lineno)\n print(e)\n\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n\n\n@login_required(login_url='/accounts/cust/login/')\ndef remove_cart(request , menu_id):\n try:\n customer=request.user.customer \n catr_obj=Cart.objects.get(customer=customer,is_paid=False)\n menu_obj=RestrauntMenu.objects.get(id=menu_id)\n print(menu_obj)\n if catr_obj.cart.filter(restraunt_menu=menu_obj).exists():\n cart_item_obj=CartItems.objects.get(cart=catr_obj,restraunt_menu=menu_obj)\n cart_item_obj.quantity -=1\n cart_item_obj.save()\n print(cart_item_obj)\n else:\n CartItems.objects.filter(\n cart=catr_obj,\n restraunt_menu=menu_obj\n ).delete()\n except Exception as e:\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n print(exc_type, fname, exc_tb.tb_lineno)\n print(e)\n \n\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n\ndef get_total(request):\n total_price=0.00\n customer=request.user.customer\n catr_obj=Cart.objects.get(customer=customer,is_paid=False)\n cart_item_obj=CartItems.objects.get(catr_obj='cart_id')\n print(cart_item_obj)\n for item in cart_item_obj():\n cart_price= (item.restraunt_menu)*(item.quantity)\n total_price=cart_price\n total_price=total_price+cart_price\n print(total_price)\n \n","sub_path":"order/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"564217728","text":"# -*- coding: utf-8 -*-\n\n__author__ = 'Traphix'\n\nimport os\nimport time\nimport datetime\nimport random\nimport string\nimport json\nimport yaml\nimport cPickle\nimport Queue\nimport threading\nimport socket\nimport multiprocessing\nfrom apscheduler.schedulers.background import BackgroundScheduler\n\nfrom . import app\nfrom . import db\nfrom config.cfg import *\nfrom lib.config_handlers import *\nfrom lib.vpp_api import *\nfrom lib.runtime_data import *\nfrom lib.hub import *\nfrom utils.utils import *\nfrom utils.vnode_config import *\nfrom models import *\n\nclass MSC():\n \"\"\" MSC main class \"\"\"\n def __init__(self):\n \"\"\"************************************************************************\"\"\"\n \"\"\"* Config *\"\"\"\n \"\"\"************************************************************************\"\"\"\n self.config = {}\n\n \"\"\"************************************************************************\"\"\"\n \"\"\"* Runtime data *\"\"\"\n \"\"\"************************************************************************\"\"\"\n self.runtime_ip_pool = {\"lip\": [], \"vip\": [], \"nip\": []}\n self.runtime_ip_used = []\n self.runtime_unames_used = []\n self.runtime_retain_vips = set([])\n self.runtime_clients_number = 0\n self.runtime_clients = {\n \"line1\": [],\n \"line2\": [],\n \"line3\": [],\n \"line4\": []\n }\n self.runtime_vpp_interface_status = {}\n self.runtime_acl_index = 0\n self.runtime_macip_acl_index = 0\n self.runtime_blocked_clients = {}\n self.runtime_lines_vlans = {}\n self.runtime_intfs = MSInterfaces()\n self.runtime_dns_servers = {}\n self.runtime_dhcp_servers = {}\n self.runtime_dhcpd_conf = \\\n 'ddns-update-style interim; \\n'\\\n 'ignore client-updates; \\n'\\\n 'allow bootp; \\n'\n\n self.current_user = 'admin'\n self.current_user_ip = ''\n\n self.ms_start_time = time.time()\n\n \"\"\"************************************************************************\"\"\"\n \"\"\"* Database *\"\"\"\n \"\"\"************************************************************************\"\"\"\n self.mysql = MSMysqlServer(db)\n\n \"\"\"************************************************************************\"\"\"\n \"\"\"* vpp api *\"\"\"\n \"\"\"************************************************************************\"\"\"\n self.msvpp = MSVPP(app=app, msc=self, mysql=self.mysql, model=LogInterfaces)\n\n \"\"\"************************************************************************\"\"\"\n \"\"\"* vnode config *\"\"\"\n \"\"\"************************************************************************\"\"\"\n self.vnode = vnode_config(vpp=self.msvpp, app=app)\n self.dnat = VPortsConfig(app=app)\n\n \"\"\"************************************************************************\"\"\"\n \"\"\"* dhcp async reply handler *\"\"\"\n \"\"\"************************************************************************\"\"\"\n self.clients_pending = []\n self.dhcp_up_event_q = Queue.Queue()\n self.client_factory_thread = threading.Thread(target=self.client_factory)\n self.client_factory_thread.setDaemon(True)\n\n \"\"\"************************************************************************\"\"\"\n \"\"\"* msc scheduler *\"\"\"\n \"\"\"************************************************************************\"\"\"\n self.scheduler = BackgroundScheduler()\n\n \"\"\"************************************************************************\"\"\"\n \"\"\"* mutation threads *\"\"\"\n \"\"\"************************************************************************\"\"\"\n self.vip_mutation_thread = None\n self.uname_mutation_thread = None\n\n \"\"\"************************************************************************\"\"\"\n \"\"\"* license *\"\"\"\n \"\"\"************************************************************************\"\"\"\n self.license_state = True\n self.ms_license = MSLicense(msc=self)\n\n \"\"\"************************************************************************\"\"\"\n \"\"\"* save runtime data process *\"\"\"\n \"\"\"************************************************************************\"\"\"\n self.save_runtime_data_q = multiprocessing.Queue(256)\n self.save_runtime_data_process = multiprocessing.Process(target=self.save_runtime_data_loop)\n # self.save_runtime_data_process.setDaemon(True)\n\n # atexit.register(msc_atexit, self)\n\n def run(self):\n \"\"\" start msc \"\"\"\n app.logger.info(\"**************************************************************\")\n app.logger.info(\"* MSC server start *\")\n app.logger.info(\"**************************************************************\")\n\n # load config\n self.load_config(app.config['MSC_DEFAULT_CONFIG_FILE_PATH'])\n\n # mgr interface\n app.config['MS_MGR_INTERFACE'] = self.config[\"mgr_intf\"]\n\n # disable dhcp when generating speed test table\n if app.config['MSC_GENERATE_SPEED_TEST_TABLE_ENTRIES'] == 1:\n self.config[\"global_config\"][\"DHCP\"] = \"0\"\n\n # mysql\n self.mysql.serve()\n\n # vnode api\n self.vnode.serve()\n self.dnat.serve()\n\n if self.msvpp.check_vpp_intfs_up_down():\n # all interfaces are up, load runtime data\n self.load_runtime_data()\n else:\n # all interfaces are down\n self.init_config() # initialize config\n # self.mysql.create_all()\n # self.mysql.commit()\n LogInterfaces.query.delete()\n app.logger.debug(\"drop LogInterfaces mysql table\")\n # start ms dhcp server\n if self.config[\"global_config\"][\"DHCP\"] == \"1\":\n with open(app.config['MSC_DHCP_CONF_FILE_PATH'], 'w') as f:\n f.write(self.runtime_dhcpd_conf)\n self.start_dhcp_server()\n\n self.mysql.create_all()\n self.mysql.commit()\n\n # start vpp\n self.msvpp.serve()\n\n # license check\n self.ms_license.get_ms_serial_number()\n self.ms_license.license_check(app.config['MS_LICENSE_FILE'])\n\n # start client_factory_thread\n self.client_factory_thread.start()\n\n # start msc scheduler\n self.scheduler.start()\n \n # start mutation thread\n if app.config['MSC_GENERATE_SPEED_TEST_TABLE_ENTRIES'] == 0:\n self.vip_mutation_thread = spawn(self.vip_mutation, self)\n self.uname_mutation_thread = spawn(self.uname_mutation, self)\n \n # start save runtime data process\n self.save_runtime_data_process.start()\n\n app.logger.info(\"****************** Initialization finished *******************\")\n\n # test only\n self.test_data()\n \n def test_data(self):\n \"\"\" Do something for test \"\"\"\n\n app.logger.debug(\"[+] Run test data\")\n\n self.save_config(app.config['MSC_DEFAULT_CONFIG_FILE_PATH'])\n self.save_config(app.config['MSC_FACTORY_CONFIG_FILE_PATH'])\n self.save_config(app.config['MSC_IMPORT_CONFIG_FILE_PATH'])\n\n if app.config['MSC_GENERATE_SPEED_TEST_TABLE_ENTRIES']:\n self.create_entries_for_speed_test()\n\n app.logger.debug(\"[+] Run test data over\")\n \n def reset_runtime_data(self):\n self.runtime_ip_pool = {\"lip\": [], \"vip\": [], \"nip\": []}\n self.runtime_ip_used = []\n self.runtime_unames_used = []\n self.runtime_retain_vips = set([])\n self.runtime_clients_number = 0\n self.runtime_clients = {\n \"line1\": [],\n \"line2\": [],\n \"line3\": [],\n \"line4\": []\n }\n self.runtime_vpp_interface_status = {}\n self.runtime_acl_index = 0\n self.runtime_macip_acl_index = 0\n self.runtime_blocked_clients = {}\n self.runtime_lines_vlans = {}\n self.runtime_intfs = MSInterfaces()\n self.runtime_dns_servers = {}\n self.runtime_dhcp_servers = {}\n self.runtime_dhcpd_conf = \\\n 'ddns-update-style interim; \\n'\\\n 'ignore client-updates; \\n'\\\n 'allow bootp; \\n'\n\n self.current_user = 'admin'\n self.current_user_ip = ''\n app.logger.info(\"msc runtime data reset\")\n\n def init_config(self):\n \"\"\" initialize MS config\"\"\"\n for k in self.config:\n if type(self.config[k]) == list:\n if k == \"firewall\" or \"_list\" in k:\n config_handlers[k](msc=self, is_add=True, value=i, init=True)\n continue\n for i in self.config[k]:\n config_handlers[k](msc=self, is_add=True, value=i, init=True)\n elif k == \"interfaces_names\":\n continue\n else:\n config_handlers[k](msc=self, is_add=True, value=self.config[k], init=True)\n app.logger.debug(\"initialized %s\", k)\n\n def load_config(self, filename):\n e = MSCError()\n with open(filename) as json_file:\n data = yaml.safe_load(json_file)\n self.config = data\n app.logger.debug(\"load config file - %s\", filename)\n return e\n\n def save_config(self, filename):\n e = MSCError()\n data = self.config\n j_data = json.dumps(data, indent=4, sort_keys=True)\n with open(filename, 'w') as json_file:\n json_file.write(j_data)\n app.logger.debug(\"save config file - %s\", filename)\n return e\n\n @log_action\n def set_config(self, is_add, key, value):\n \"\"\" apply the config from web ui \"\"\"\n e = config_handlers[key](msc=self, is_add=is_add, value=value, init=False)\n if self.config.has_key(key) == False:\n return e\n if e.result:\n if is_add == True:\n if key == \"firewall\":\n for i, val in enumerate(self.config[key]):\n if int(val[\"ruleid\"]) == int(value[\"ruleid\"]):\n self.config[key][i] = value\n break\n else:\n self.config[key].append(value)\n elif type(self.config[key]) == list:\n self.config[key].append(value)\n elif key == \"interfaces_names\":\n cnt = 0\n for (k, v) in self.config[\"interfaces_names\"].items():\n if v[\"line_name\"] == value[0]:\n self.config[\"interfaces_names\"][k][\"custom_name\"] = value[1]\n cnt += 1\n if cnt != 2:\n e.set_msg(u\"修改线路名称失败\")\n return e\n else:\n self.config[key] = value\n return e\n else:\n if type(self.config[key]) == list:\n try:\n self.config[key].remove(value)\n except Exception as _e:\n e.set_msg(u\"删除配置失败: %s - %s\" % (value, _e))\n return e\n return e\n return e\n\n def log_user_login(self, user, ip):\n \"\"\" log when user login \"\"\"\n e = MSCError()\n self.current_user = user\n self.current_user_ip = ip\n newobj = LogUserAction(\n ip = ip,\n user = user,\n time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),\n action = u\"登陆系统\"\n )\n self.mysql.save(newobj)\n return e\n \n def log_user_set_time(self):\n e = MSCError()\n newobj = LogUserAction(\n ip = self.current_user_ip,\n user = self.current_user,\n time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),\n action = u\"修改系统时间\"\n )\n self.mysql.save(newobj)\n return e\n\n def start_dhcp_server(self):\n \"\"\" start ms dhcp server \"\"\"\n cmd = \"ip netns del dhcpd;ip netns add dhcpd;\"\n os.popen(cmd)\n intfs = []\n for line in self.runtime_lines_vlans:\n cmd = ''\n cmd += \"ip link del vpp-{line};\".format(line=line)\n cmd += \"ip link add name dhcpd-{line} type veth peer name vpp-{line};\".format(line=line)\n cmd += \"ip link set dhcpd-{line} netns dhcpd;\".format(line=line)\n cmd += \"ip netns exec dhcpd ifconfig dhcpd-{line} 0.0.0.0 up;\".format(line=line)\n for vlan in self.runtime_lines_vlans[line]:\n ip = ip2long(self.runtime_lines_vlans[line][vlan][0]) + 1\n gw = ip2long(self.runtime_lines_vlans[line][vlan][2])\n if ip == gw:\n ip += 1\n ip = long2ip(ip)\n if vlan == 0:\n cmd += \"ip netns exec dhcpd ifconfig dhcpd-{line} {ip}/{mask} up;\".format(\n line=line,\n ip=ip, # self.runtime_lines_vlans[line][vlan][0],\n mask=mask2length(self.runtime_lines_vlans[line][vlan][1])\n )\n intfs.append(\"dhcpd-{line}\".format(line=line))\n else:\n cmd += \"ip netns exec dhcpd vconfig add dhcpd-{line} {vlan};\".format(line=line, vlan=vlan)\n cmd += \"ip netns exec dhcpd ifconfig dhcpd-{line}.{vlan} {ip}/{mask} up;\".format(\n line=line,\n ip=ip, # self.runtime_lines_vlans[line][vlan][0],\n mask=mask2length(self.runtime_lines_vlans[line][vlan][1]),\n vlan=vlan\n )\n intfs.append(\"dhcpd-{line}.{vlan}\".format(line=line, vlan=vlan))\n os.popen(cmd)\n # print intfs\n cmd = \"ip netns exec dhcpd dhcpd \" + ' '.join([intf for intf in intfs])\n os.popen(\"kill -9 $(ps aux| pgrep dhcpd)\")\n os.popen(cmd)\n app.logger.debug(\"start ms dhcp server\")\n \n def get_uname(self):\n \"\"\" get a 8 bytes uname for a client \"\"\"\n while True:\n uname = list(string.ascii_lowercase)\n random.shuffle(uname)\n # uname = \"ndsc.\" + ''.join(uname[:UNAME_LENGTH])\n uname = ''.join(uname[:UNAME_LENGTH])\n if uname in self.runtime_unames_used:\n continue\n break\n self.runtime_unames_used.append(uname)\n return uname\n \n def release_uname(self, uname):\n \"\"\" release the uname not used \"\"\"\n\n if uname in self.runtime_unames_used:\n self.runtime_unames_used.remove(uname)\n return True\n\n def get_ip(self, iptype, interface, vlan=0, verbose=False):\n \"\"\"\n choose an ip from a corresponding ip pool, put this ip into used ip pool\n \"\"\"\n ip_pools = []\n for i in self.runtime_ip_pool[iptype]:\n if interface in i and vlan in i:\n ip_pools.append(i)\n if ip_pools:\n cnt_1 = 0\n while cnt_1 < NUM_TRY:\n ip_pool = random.choice(ip_pools)\n cnt_2 = 0\n while ip_pool[IPI_POOL] and cnt_2 < NUM_TRY:\n # get a new ip\n short_ip = ip_pool[IPI_POOL].pop()\n base = ip2long(ip_pool[IPI_START_IP]) + (short_ip << 8)\n _ip = base + random.randint(2, 254)\n ip = long2ip(_ip)\n gateway = long2ip(base + 1)\n\n # *************************check*************************#\n # invalid ip check\n if '255' in ip:\n ip_pool[IPI_POOL].insert(0, short_ip)\n cnt_2 += 1\n continue\n # static ip check\n try:\n static_client = self.mysql.query(ClientsStatic, {\"ip\": ip}).first()\n if static_client and (static_client.ip == ip or static_client.ip == gateway):\n ip_pool[IPI_POOL].insert(0, short_ip)\n cnt_2 += 1\n continue\n except Exception as _e:\n app.logger.error(\"failed to query static client in get_ip - %s\", _e)\n # reserve ip seg check\n for res in self.config[iptype + \"_res_seg\"]:\n if long2ip(_ip & ip2long(res[\"mask\"])) == res[\"ip\"]:\n ip_pool[IPI_POOL].insert(0, short_ip)\n cnt_2 += 1\n continue\n # *******************************************************#\n\n mask = '255.255.255.0'\n self.runtime_ip_used.append([ip, mask, ip_pool[IPI_START_IP], interface, vlan, short_ip])\n # self.runtime_ip_used[ip] = [ip, mask, ip_pool[IPI_START_IP], interface, vlan, short_ip]\n return [ip, mask, gateway]\n cnt_1 += 1\n else:\n app.logger.error(\"cannot get %s, %s %s_pool is exhausted\", iptype, interface, iptype)\n return [0, 0, 0]\n else:\n app.logger.error(\"cannot get %s, %s (vlan: %s) %s_pool is empty\", iptype, interface, vlan, iptype)\n return [0, 0, 0]\n\n def release_ip(self, iptype, ipaddr, interface, vlan=0, verbose=False):\n \"\"\"\n release the unused ipaddr, put it into corresponding ip pool\n \"\"\"\n for i in self.runtime_ip_used[:]:\n if (ipaddr in i) and (interface in i) and (vlan in i):\n for j in self.runtime_ip_pool[iptype]:\n if (i[UPI_START_IP] in j) and (i[UPI_INTERFACE] in j) and (i[UPI_VLAN] in j):\n j[IPI_POOL].insert(0, i[UPI_SHORT_IP])\n self.runtime_ip_used.remove(i)\n # app.logger.debug(\"release %s: %s\", iptype, ipaddr)\n return True\n app.logger.error(\"failed to put %s into ip pool, no match pool\", ipaddr)\n return False\n app.logger.error(\"failed to release ip %s, no such clients\", ipaddr)\n return False\n \n def ip_pool_add_del(self, is_add, iptype, config, verbose=False):\n \"\"\" generate a runtime ip pool \"\"\"\n e = MSCError()\n\n for (k, v) in self.config[\"interfaces_names\"].items():\n if config[\"phy_int\"] in v[\"line_name\"]:\n break\n else:\n e.set_msg(u\"添加或删除IP地址池失败,没有这个接口:%s\" % config[\"phy_int\"])\n return e\n\n if is_add:\n for pool in self.runtime_ip_pool[iptype]:\n if int(config[\"vlanid\"]) == pool[IPI_VLAN] and config[\"phy_int\"] == pool[IPI_INTERFACE]:\n e.set_msg(u\"修改配置失败,同一个线路、同一个VLAN只能配置一个IP段\")\n return e\n mask_length = mask2length(config[\"mask\"])\n if mask_length > 22:\n e.set_msg(u\"修改配置失败,掩码长度应小于23\")\n return e\n pool = range(2, 2**(24-mask_length))\n random.shuffle(pool)\n start_ip = long2ip(ip2long(config[\"ip\"]) & ip2long(config[\"mask\"]))\n ip_pool = [\n start_ip, \n pool, \n config[\"mask\"], \n int(config[\"vlanid\"]),\n config[\"phy_int\"]\n ]\n self.runtime_ip_pool[iptype].append(ip_pool)\n app.logger.debug(\"add a %s_pool, start ip %s, mask %s, line %s, vlan %s\", \n iptype, ip_pool[IPI_START_IP], ip_pool[IPI_MASK], ip_pool[IPI_INTERFACE], ip_pool[IPI_VLAN])\n return e \n else:\n status = []\n if config[\"phy_int\"] in self.runtime_clients and self.runtime_clients[config[\"phy_int\"]]:\n status = self.runtime_clients[config[\"phy_int\"]]\n for i in self.runtime_ip_pool[iptype]:\n if long2ip(ip2long(config[\"ip\"]) & ip2long(config[\"mask\"])) in i and config[\"phy_int\"] in i and int(config[\"vlanid\"]) in i:\n self.runtime_ip_pool[iptype].remove(i)\n if status:\n # delete clients in this pool\n if iptype == LIP:\n pass\n else: # VIP\n for client in status[:]:\n if (ip2long(getattr(client, iptype)) & ip2long(config[\"mask\"])) == \\\n (ip2long(config[\"ip\"]) & ip2long(config[\"mask\"])) and client.vlan == int(config[\"vlanid\"]):\n if client.delete():\n app.logger.warning(\"%s - client deleted, because its %s_pool has been deleted\", client.mac, iptype)\n else:\n pass\n app.logger.debug(\"del a %s_pool, start ip %s, mask %s, line %s\",\n iptype, i[IPI_START_IP], i[IPI_MASK], i[IPI_INTERFACE])\n return e\n e.set_msg(u\"删除IP地址池: %s, %s 失败,地址池不存在\" % (config[\"ip\"], config[\"phy_int\"]))\n return e\n\n def ip_res_add_del(self, is_add, iptype, config, verbose=False):\n \"\"\" add a reserve ip segment \"\"\"\n e = MSCError()\n if is_add:\n # check if current clients in reserve ip segment\n for (k, v) in self.runtime_clients.items():\n for client in v:\n if long2ip(ip2long(getattr(client, iptype)) & ip2long(config[\"mask\"])) == config[\"ip\"]:\n if iptype == LIP:\n # TBD\n return e\n else:\n old_ip = getattr(client, iptype)\n self.release_ip(iptype=iptype, interface=k, ipaddr=old_ip, vlan=client.vlan)\n # get new ip\n new_ip = self.get_ip(iptype=iptype, interface=k, vlan=client.vlan)[0]\n if client.change_ip(iptype=iptype, new_ip=new_ip):\n app.logger.debug(\"%s %s in new res_seg, change it to %s\", iptype, old_ip, new_ip)\n return e\n else:\n e.set_msg(\"清理位于预留IP段主机失败 - %s\", client.mac)\n self.release_ip(iptype=iptype, interface=k, ipaddr=new_ip, vlan=client.vlan)\n return e\n else:\n return e\n return e\n\n def client_add_del(self, is_add, mac, intf_inner=None, intf_outer=None, vlanid=None,\n nip=None, nmask=None, ngateway=None, dns_server=None, dhcp_server=None,\n ms_dhcp_mac=None, dhcp_phase=None):\n \"\"\" return an instance of Client from runtime_data.py \"\"\"\n for name, value in self.runtime_intfs.__dict__.items():\n if value.sw_if_index == intf_inner:\n interface = value.line_name\n if is_add == True:\n # *************************************** check ******************************************** #\n # check license state\n if self.license_state == False:\n app.logger.DEBUG(\"%s - license expired, cannot add this client\", mac)\n return False\n # check max clients upper bound\n if self.runtime_clients_number >= app.config['MSC_MAX_CLIENTS']:\n app.logger.warning(\"%s - failed to add client, clients number reaches the maximum\", mac)\n return False\n # check white or black list\n try:\n if self.config[\"global_config\"][\"clientaccess\"] == BLACK_LIST:\n if self.mysql.query(ClientsBlackList, {\"mac\": mac}).first():\n app.logger.warning(\"%s - failed to add client, it is in the black list\", mac)\n return False \n else:\n if not(self.mysql.query(ClientsWhiteList, {\"mac\": mac}).first()):\n app.logger.warning(\"%s - failed to add client, it is not in the white list\", mac)\n return False\n except Exception as _e:\n app.logger.error(\"failed to check white or black list - %s\", _e)\n # *************************************** check ******************************************** #\n # lease renew\n if self.runtime_clients[interface]:\n for client in self.runtime_clients[interface][:]:\n if self.config[\"global_config\"][\"DHCP\"]:\n if client.mac == mac:\n client.renew_lease()\n return True\n # static address\n try:\n static_client = self.mysql.query(ClientsStatic, {\"mac\": mac}).first()\n if static_client:\n lip = static_client.ip\n lmask = '255.255.255.0'\n vip = static_client.ip\n # set inner_gw\n inner_gw = long2ip((ip2long(lip) & ip2long('255.255.255.0')) + 254)\n if inner_gw == lip:\n inner_gw = long2ip((ip2long(lip) & ip2long('255.255.255.0')) + 1)\n return Client(\n msc = self,\n vpp = self.msvpp,\n mysql = self.mysql,\n intf_inner = intf_inner,\n intf_outer = intf_outer,\n mac = mac,\n lip = lip,\n lmask = lmask,\n vip = vip,\n nip = nip,\n honeyd_net = lip,\n inner_gw = inner_gw,\n outer_gw = ngateway,\n dns_server = self.config[\"global_config\"][\"fDNS\"] \\\n if self.config[\"global_config\"][\"DHCP\"] == '1' \\\n else dns_server,\n dhcp_server = dhcp_server,\n ms_dhcp_mac = ms_dhcp_mac,\n uname = self.get_uname(),\n vlan = 0,\n flag_block = u\"否\",\n vnode = self.vnode,\n scheduler = self.scheduler\n )\n except Exception as _e:\n app.logger.error(\"failed to query static client in client_add_del - %s\", _e)\n # add a new client\n (lip, lmask, lgateway) = self.get_ip(iptype=LIP, interface=interface, vlan=vlanid)\n (vip, vmask, vgateway) = self.get_ip(iptype=VIP, interface=interface, vlan=vlanid)\n if nip and nmask and ngateway:\n (nip, nmask, ngateway) = (nip, nmask, ngateway)\n else:\n app.logger.error(\"%s - get no nip from vpp-dhcp-node when add client \", mac)\n return False\n uname = self.get_uname()\n vlan = vlanid # Not sure\n block = False # TBD\n if lip == 0 or vip == 0 or nip == 0:\n app.logger.error(\"%s - failed to add client in interface %s, get_ip error\", mac, interface)\n return False\n return Client(\n msc = self,\n vpp = self.msvpp,\n mysql = self.mysql,\n intf_inner = intf_inner,\n intf_outer = intf_outer,\n mac = mac,\n lip = lip,\n lmask = lmask,\n vip = vip,\n nip = nip,\n honeyd_net = lip,\n inner_gw = lgateway,\n outer_gw = ngateway,\n dns_server = self.config[\"global_config\"][\"fDNS\"] \\\n if self.config[\"global_config\"][\"DHCP\"] == '1' \\\n else dns_server,\n dhcp_server = dhcp_server,\n ms_dhcp_mac = ms_dhcp_mac,\n uname = uname,\n vlan = vlan,\n flag_block = u\"否\",\n vnode = self.vnode,\n scheduler = self.scheduler\n )\n elif is_add == False:\n for client in self.runtime_clients[interface][:]:\n if client.mac == mac:\n if dhcp_phase:\n client.dhcp_phase = dhcp_phase\n if client.delete():\n return True\n else:\n app.logger.error(\"%s - can't del client: \", mac)\n return False\n app.logger.warning(\"%s - can't del client, no such client\", mac)\n return False\n\n def client_block_unblock(self, is_block, mac=None, ipaddrs=None):\n \"\"\"\n block or unblock client \n when is_block is True, ipaddrs is necessary\n when is_block is False, mac is necessary\n \"\"\"\n e = MSCError()\n if is_block and ipaddrs:\n for intf in self.runtime_clients:\n for client in self.runtime_clients[intf]:\n if client.lip in ipaddrs:\n if client.flag_block == u\"是\":\n continue\n if self.config[\"global_config\"][\"clientblock\"] == \"0\":\n app.logger.warning(\"%s - %s - auto block is off - MS won't block it\",\n client.mac, client.lip)\n continue\n if self.mysql.query(ClientsTrustList, {\"mac\": client.mac}).first():\n app.logger.warning(\"%s - %s - client is in the trust list, MS won't block it\",\n client.mac, client.lip)\n continue\n client.block()\n elif is_block == False and mac:\n if self.runtime_blocked_clients.has_key(mac) and self.runtime_blocked_clients[mac].unblock():\n return e\n else:\n e.set_msg(u\"解封主机: %s 失败\" % mac)\n return e\n \n def vip_mutation(self):\n t = time.time()\n self.retain_vips_check()\n # change vips\n for intf in self.runtime_clients:\n for client in self.runtime_clients[intf]:\n if client.flag_block == u\"是\":\n continue\n client.vip_mutation()\n self.save_runtime_data()\n app.logger.info(\"vip mutation cost - %.2fs\", time.time() - t)\n \n def uname_mutation(self):\n t = time.time()\n for intf in self.runtime_clients:\n for client in self.runtime_clients[intf]:\n if client.flag_block == u\"是\":\n continue\n client.uname_mutation()\n self.save_runtime_data()\n app.logger.info(\"uname mutation cost - %.2fs\", time.time() - t)\n \n def retain_vips_check(self):\n # remove old_vip or not?\n retain_vips = set([socket.inet_ntop(socket.AF_INET, v.virtual_ip_address) \\\n for v in self.msvpp.ms_in2in_tcp_session_vips_dump()])\n for v in retain_vips:\n app.logger.debug(\"vip %s has TCP session, retain it in mc session table\", v)\n\n delete_vips = self.runtime_retain_vips.difference(retain_vips)\n for v in delete_vips:\n self.msvpp.mc_add_del_session(is_add=0,\n table_index=TABLE_DNS_OUT2IN_IN2IN,\n match_dst_ip=v,\n lip='0.0.0.0',\n hit_next_index=IN2IN_NODE)\n app.logger.debug(\"vip %s TCP session over, delete it in mc session table\", v)\n \n self.runtime_retain_vips = retain_vips\n\n def save_runtime_data(self):\n data = (\n self.runtime_ip_pool,\n self.runtime_ip_used,\n self.runtime_unames_used,\n self.runtime_retain_vips,\n self.runtime_clients_number,\n self.runtime_clients,\n self.runtime_vpp_interface_status,\n self.runtime_acl_index,\n self.runtime_macip_acl_index,\n self.runtime_blocked_clients,\n self.runtime_lines_vlans,\n self.runtime_intfs,\n self.runtime_dns_servers,\n self.runtime_dhcp_servers,\n self.runtime_dhcpd_conf,\n self.current_user,\n self.current_user_ip\n )\n self.save_runtime_data_q.put(data)\n \n def save_runtime_data_loop(self):\n while True:\n data = self.save_runtime_data_q.get()\n try:\n with open(app.config['MSC_RUNTIME_DATA_FILE_PATH'], 'wb') as f:\n cPickle.dump(data, f)\n except Exception as _e:\n app.logger.error(\"error in save_runtime_data - %s\", _e)\n\n def load_runtime_data(self):\n \"\"\" load runtime_data \"\"\"\n try:\n with open(app.config['MSC_RUNTIME_DATA_FILE_PATH'], 'rb') as f:\n runtime_data = cPickle.load(f)\n except Exception as _e:\n app.logger.warning(\"load runtime data error: %s\", _e)\n return False\n \n if runtime_data:\n self.runtime_ip_pool = runtime_data[0]\n self.runtime_ip_used = runtime_data[1]\n self.runtime_unames_used = runtime_data[2]\n self.runtime_retain_vips = set(runtime_data[3])\n self.runtime_clients_number = runtime_data[4]\n runtime_clients_raw = runtime_data[5]\n self.runtime_vpp_interface_status = runtime_data[6]\n self.runtime_macip_acl_index = runtime_data[7]\n self.runtime_acl_index = runtime_data[8]\n self.runtime_blocked_clients = runtime_data[9]\n self.runtime_lines_vlans = runtime_data[10]\n self.runtime_intfs = runtime_data[11]\n self.runtime_dns_servers = runtime_data[12]\n self.runtime_dhcp_servers = runtime_data[13]\n self.runtime_dhcpd_conf = runtime_data[14]\n self.current_user = runtime_data[15]\n self.current_user_ip = runtime_data[16]\n \n for k, dns_server in self.runtime_dns_servers.items():\n self.msvpp.mc_add_del_session(is_add=1,\n table_index=TABLE_DNS_OUT2IN_IN2IN,\n match_dst_ip=dns_server,\n hit_next_index=DNS_NODE)\n\n for k, dhcp_server in self.runtime_dhcp_servers.items():\n self.msvpp.ip_add_del_route(is_add=1,\n table_id=0,\n dst_address_length=32,\n dst_address=dhcp_server.ip,\n next_hop_address=dhcp_server.ip,\n next_hop_sw_if_index=dhcp_server.sw_if_index,\n next_hop_via_label=0xFFFFF+1)\n self.msvpp.ip_neighbor_add_del(is_add=1,\n sw_if_index=dhcp_server.sw_if_index,\n dst_address=dhcp_server.ip,\n mac_address=dhcp_server.mac)\n\n for intf in runtime_clients_raw:\n self.runtime_clients[intf] = []\n for raw_client in runtime_clients_raw[intf]:\n if (time.time() - raw_client.renew_time) > raw_client.dhcp_lease:\n self.release_ip(iptype=LIP, ipaddr=raw_client.lip, interface=raw_client.line, vlan=raw_client.vlan)\n self.release_ip(iptype=VIP, ipaddr=raw_client.vip, interface=raw_client.line, vlan=raw_client.vlan)\n self.release_uname(uname=raw_client.uname)\n continue\n client = Client(\n msc = self,\n vpp = self.msvpp,\n mysql = self.mysql,\n vnode = self.vnode,\n line = raw_client.line,\n intf_inner = raw_client.intf_inner,\n intf_outer = raw_client.intf_outer,\n mac_inner_if = raw_client.mac_inner_if,\n mac_outer_if = raw_client.mac_outer_if,\n mac = raw_client.mac,\n lip = raw_client.lip,\n lmask = raw_client.lmask,\n vip = raw_client.vip,\n nip = raw_client.nip,\n honeyd_net = raw_client.honeyd_net,\n inner_gw = raw_client.inner_gw,\n outer_gw = raw_client.outer_gw,\n dns_server = raw_client.dns_server,\n uname = raw_client.uname,\n vlan = raw_client.vlan,\n flag_block = raw_client.flag_block,\n dhcp_server = raw_client.dhcp_server,\n flag_save_rd = raw_client.flag_save_rd,\n flag_log = raw_client.flag_log,\n flag_delete = raw_client.flag_delete,\n dhcp_lease = raw_client.dhcp_lease,\n dhcp_phase = raw_client.dhcp_phase,\n connect_time = raw_client.connect_time,\n renew_time = raw_client.renew_time,\n ms_dhcp_intf = raw_client.ms_dhcp_intf,\n ms_dhcp_mac = raw_client.ms_dhcp_mac,\n scheduler = self.scheduler\n )\n client.start_lease_timer()\n self.runtime_clients[intf].append(client)\n if client.lip == client.vip:\n continue\n client.start_vip_mutation()\n client.start_uname_mutation()\n app.logger.debug(\"previous runtime data loaded\")\n return True\n else:\n app.logger.warning(\"load no runtime data, RUNTIME_DATE_FILE is empty\")\n return False\n \n def client_factory(self):\n \"\"\"\n get a dhcp_up_event from dhcp_up_event_q, according to the dhcp_type to\n handle the new_client\n \"\"\"\n t1 = 0\n while True:\n reply = self.dhcp_up_event_q.get()\n with lock:\n if reply.dhcp_type == OFFER:\n mac = mac2str(reply.client_mac, 6)\n # ************************************* check ************************************* #\n # check block client offer\n if self.runtime_blocked_clients.has_key(mac):\n app.logger.debug(\"%s - DHCP OFFER ignored, client is blocked\", mac)\n continue\n # check runtime client offer\n for line in self.runtime_clients:\n for client in self.runtime_clients[line]:\n if client.mac == mac:\n app.logger.warning(\"%s - duplicate DHCP OFFER, it is in runtime_clients\", mac)\n client.delete()\n # check pending client offer\n pending_macs = [client_pending.new_client.mac for client_pending in self.clients_pending]\n if mac in pending_macs:\n rv = self.msvpp.dhcp_down_offer(\n pid = reply.pid,\n broadcast = reply.broadcast,\n deny_flag = 0,\n dhcp_type = reply.dhcp_type,\n rx_sw_if_index = reply.rx_sw_if_index,\n tx_sw_if_index = reply.tx_sw_if_index,\n client_mac = mac.replace(\":\", \"\").decode('hex'),\n net_ip = reply.net_ip,\n net_ip_mask = reply.net_ip_mask,\n net_ip_gw = reply.net_ip_gw, \n link_ip = 0,\n link_ip_mask = 0,\n link_ip_gw = 0,\n server_ip = reply.server_ip,\n dns_server_ip = reply.dns_server_ip,\n lease = reply.lease,\n lease_renewal = reply.lease_renewal,\n lease_rebind = reply.lease_rebind,\n transaction_id = reply.transaction_id,\n eth_header = mac2str(reply.eth_header, 18).replace(\":\", \"\").decode('hex'),\n vlan_flag = reply.vlan_flag,\n net_ip_broadcast = reply.net_ip_broadcast,\n link_ip_broadcast = 0\n )\n if rv.retval:\n app.logger.error(\"%s - failed to send dhcp_down_offer - %s\", mac, rv.retval)\n app.logger.warning(\"%s - duplicate DHCP OFFER, it is in clients_pending\", mac)\n continue\n # ************************************* check ************************************* #\n app.logger.debug(\"%s - DHCP OFFER\", mac)\n # get vlan id\n vlanid = 0\n if reply.vlan_flag:\n tag = struct.unpack('!18B', reply.eth_header)\n vlanid = ((tag[14] << 4) + tag[15]) & 0xFFF\n new_client = self.client_add_del(\n is_add = 1,\n mac = mac,\n intf_inner = reply.tx_sw_if_index,\n intf_outer = reply.rx_sw_if_index,\n vlanid = vlanid,\n nip = long2ip(reply.net_ip),\n nmask = long2ip(reply.net_ip_mask),\n ngateway = long2ip(reply.net_ip_gw),\n dns_server = long2ip(reply.dns_server_ip),\n dhcp_server = long2ip(reply.server_ip),\n ms_dhcp_mac = mac2str(reply.eth_header, 18)[18:35]\n )\n if new_client and new_client.create(dhcp_phase=reply.dhcp_type, dhcp_lease=reply.lease+5):\n self.clients_pending.append(ClientPending(msc=self, new_client=new_client))\n app.logger.debug(\"%s - %s - add to clients_pending, lease_time - %s\", new_client.mac, new_client.lip, reply.lease+5)\n rv = self.msvpp.dhcp_down_offer(\n pid = reply.pid,\n broadcast = reply.broadcast,\n deny_flag = 0 if new_client else 1,\n dhcp_type = reply.dhcp_type,\n rx_sw_if_index = reply.rx_sw_if_index,\n tx_sw_if_index = reply.tx_sw_if_index,\n client_mac = mac.replace(\":\", \"\").decode('hex'),\n net_ip = reply.net_ip,\n net_ip_mask = reply.net_ip_mask,\n net_ip_gw = reply.net_ip_gw, \n link_ip = ip2long(new_client.lip),\n link_ip_mask = ip2long(new_client.lmask),\n link_ip_gw = ip2long(new_client.inner_gw),\n server_ip = reply.server_ip,\n dns_server_ip = reply.dns_server_ip,\n lease = reply.lease,\n lease_renewal = reply.lease_renewal,\n lease_rebind = reply.lease_rebind,\n transaction_id = reply.transaction_id,\n eth_header = mac2str(reply.eth_header, 18).replace(\":\", \"\").decode('hex'),\n vlan_flag = reply.vlan_flag,\n net_ip_broadcast = reply.net_ip_broadcast,\n link_ip_broadcast = (ip2long(new_client.lip) & ip2long(new_client.lmask)) | (~ip2long(new_client.lmask) & 0xFFFFFFFF)\n )\n if rv.retval:\n app.logger.error(\"failed to send dhcp_down_offer - %s\", rv.retval)\n elif reply.dhcp_type == ACK:\n mac = mac2str(reply.client_mac, 6)\n # check blocked client ack\n if self.runtime_blocked_clients.has_key(mac):\n app.logger.debug(\"%s - DHCP ACK ignored, client is blocked\", mac)\n continue\n for client_pending in self.clients_pending:\n if client_pending.new_client.nip == long2ip(reply.net_ip):\n app.logger.debug(\"%s - DHCP ACK - new\", mac)\n # add DNS server table entry\n if self.runtime_dns_servers.has_key(reply.dns_server_ip) == False:\n self.runtime_dns_servers[reply.dns_server_ip] = long2ip(reply.dns_server_ip)\n self.msvpp.mc_add_del_session(is_add=1,\n table_index=TABLE_DNS_OUT2IN_IN2IN,\n match_dst_ip=long2ip(reply.dns_server_ip),\n hit_next_index=DNS_NODE)\n # add DHCP server table entry in DHCP mode\n if self.config[\"global_config\"][\"DHCP\"] == \"1\" and self.runtime_dhcp_servers.has_key(reply.server_ip) == False:\n self.runtime_dhcp_servers[reply.server_ip] = DHCPServer(\n ip = long2ip(reply.server_ip),\n mac = mac2str(reply.eth_header, 18)[18:35],\n sw_if_index = reply.rx_sw_if_index\n )\n self.msvpp.ip_add_del_route(is_add=1,\n table_id=0,\n dst_address_length=32,\n dst_address=self.runtime_dhcp_servers[reply.server_ip].ip,\n next_hop_address=self.runtime_dhcp_servers[reply.server_ip].ip,\n next_hop_sw_if_index=self.runtime_dhcp_servers[reply.server_ip].sw_if_index,\n next_hop_via_label=0xFFFFF+1)\n self.msvpp.ip_neighbor_add_del(is_add=1,\n sw_if_index=self.runtime_dhcp_servers[reply.server_ip].sw_if_index,\n dst_address=self.runtime_dhcp_servers[reply.server_ip].ip,\n mac_address=self.runtime_dhcp_servers[reply.server_ip].mac)\n # delete client pending\n client_pending.stop_ack_timer()\n client_pending.new_client.create(dhcp_phase=reply.dhcp_type)\n self.clients_pending.remove(client_pending)\n for client_pending in self.clients_pending[:]:\n if client_pending.new_client.mac == mac:\n client_pending.stop_ack_timer()\n client_pending.new_client.delete()\n self.clients_pending.remove(client_pending)\n break\n else:\n for name, value in self.runtime_intfs.__dict__.items():\n if value.sw_if_index == reply.tx_sw_if_index:\n line = value.line_name\n for client in self.runtime_clients[line]:\n if client.mac == mac:\n app.logger.debug(\"%s - %s - DHCP ACK - renew\", mac, client.lip)\n client.renew_lease()\n break\n else:\n app.logger.error(\"%s - DHCP ACK, but there is no nuch client\", mac)\n elif reply.dhcp_type == RELEASE:\n mac = mac2str(reply.client_mac, 6)\n app.logger.debug(\"%s - DHCP RELEASE\", mac)\n self.client_add_del(is_add=False, mac=mac, dhcp_phase=reply.dhcp_type,\n intf_inner=reply.rx_sw_if_index)\n elif reply.dhcp_type == DECLINE:\n mac = mac2str(reply.client_mac, 6)\n app.logger.debug(\"%s - DHCP DECLINE\", mac)\n self.client_add_del(is_add=False, mac=mac, dhcp_phase=reply.dhcp_type,\n intf_inner=reply.rx_sw_if_index)\n elif reply.dhcp_type == NACK:\n mac = mac2str(reply.client_mac, 6)\n app.logger.debug(\"%s - DHCP NACK\", mac)\n self.client_add_del(is_add=False, mac=mac, dhcp_phase=reply.dhcp_type,\n intf_inner=reply.tx_sw_if_index)\n \n def vpp_abnormal_restart(self):\n \"\"\"\n 1. flush self.runtime_intfs\n 2. flush self.runtime_vpp_interface_status\n 3. drop table Interfaces\n 4. self.msvpp.rebuild()\n \"\"\"\n with lock:\n self.runtime_intfs = MSInterfaces()\n self.runtime_vpp_interface_status = {}\n LogInterfaces.query.delete()\n self.mysql.create_all()\n self.mysql.commit()\n self.msvpp.rebuild()\n for intf in self.runtime_clients:\n for client in self.runtime_clients[intf]:\n client.stop_lease_timer()\n self.runtime_clients[intf] = []\n for client_pending in self.clients_pending:\n client_pending.stop_ack_timer()\n \n def create_entries_for_speed_test(self):\n \"\"\" create vPC entries for speed test \"\"\"\n self.test_clients = []\n cnt = 0\n lip_generator = ip_generator('172.16.10.124')\n vip_generator = ip_generator('11.0.0.1')\n nip_generator = ip_generator('192.168.10.124')\n while cnt < app.config['MSC_NUMBER_OF_VIRTUAL_CLIENTS']:\n lip = lip_generator.next()\n lmask = '255.255.0.0'\n inner_gw = '172.16.10.254'\n vip = vip_generator.next()\n nip = nip_generator.next()\n outer_gw = '192.168.10.254'\n uname = self.get_uname()\n dns_server_ip = '114.114.114.114'\n client = Client(\n msc = self,\n vpp = self.msvpp,\n mysql = None,\n vnode = self.vnode,\n line = 'line2',\n intf_inner = getattr(self.runtime_intfs, 'line2_in').sw_if_index,\n intf_outer = getattr(self.runtime_intfs, 'line2_out').sw_if_index,\n mac_inner_if = getattr(self.runtime_intfs, 'line2_in').mac,\n mac_outer_if = getattr(self.runtime_intfs, 'line2_out').mac,\n # mac = mac_generator(),\n mac = 'E6:2B:51:30:A8:7C',\n lip = lip,\n lmask = lmask,\n vip = vip,\n nip = nip,\n honeyd_net = lip,\n inner_gw = inner_gw,\n outer_gw = outer_gw,\n dns_server = dns_server_ip,\n uname = uname,\n vlan = 0,\n flag_block = False,\n dhcp_server = '0.0.0.0',\n flag_save_rd = False,\n flag_log = False,\n flag_delete = False,\n dhcp_lease = 0,\n dhcp_phase = 0,\n connect_time = 0,\n renew_time = 0,\n scheduler = None\n )\n self.msvpp.mc_add_del_session(is_add=1,\n table_index=TABLE_DNS_OUT2IN_IN2IN,\n match_dst_ip=dns_server_ip,\n hit_next_index=DNS_NODE)\n client.create_table_entry()\n self.test_clients.append(client)\n app.logger.info(\"[+] add vPC(%s/%s) - %15s - %15s - %15s\" % (cnt + 1, app.config['MSC_NUMBER_OF_VIRTUAL_CLIENTS'], lip, vip, nip))\n cnt += 1\n","sub_path":"msc/msc.py","file_name":"msc.py","file_ext":"py","file_size_in_byte":55363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"567084855","text":"import logging\nimport signal\nimport atexit\nimport asyncio\nfrom datetime import datetime\nfrom zoneinfo import ZoneInfo\n\n\nclass EventProcessor:\n \"\"\"Check if another instance is already running using a socket server. Terminate old instance and\n start new instance (if kill option was not set.)\"\"\"\n\n def __init__(self, name, toml_data):\n self.log = logging.getLogger(\"IndraSignalServer\")\n try:\n self.loglevel = toml_data[name][\"loglevel\"].upper()\n except Exception as e:\n self.loglevel = logging.INFO\n logging.error(\n f\"Missing entry 'loglevel' in indrajala.toml section {name}: {e}\"\n )\n self.log.setLevel(self.loglevel)\n self.port = int(toml_data[name][\"signal_port\"])\n self.toml_data = toml_data\n self.name = name\n self.active = True\n\n def isActive(self):\n return self.active\n\n async def async_init(self, loop):\n self.loop = loop\n self.exit_future = self.loop.create_future()\n await self.check_register_socket()\n return [\"$SYS\"]\n\n async def handle_client(self, reader, writer):\n request = \"\"\n while request != \"quit\":\n request = (await reader.read(255)).decode(\"utf8\").strip()\n if request == \"quit\":\n self.log.info(\"Quit command received\")\n response = \"quitting!\\n\"\n elif request == \"help\":\n response = \"help: this help\\nquit: stop this daemon.\\n\"\n else:\n response = f\"Error: {request} (try: help)\\n\"\n writer.write(response.encode(\"utf8\"))\n await writer.drain()\n self.log.warning(\"quit received\")\n writer.close()\n self.exit_future.set_result(True)\n self.exit = True\n\n async def get_command(self):\n ret = await self.exit_future\n self.log.info(\"exit future set True\")\n return {\"cmd\": \"quit\", \"retstate\": ret}\n\n def close_daemon(self):\n pass\n\n async def signal_handler(self):\n self.log.info(\"QUIT signal received\")\n # sys.exit(0) # this will implicitly call atexit() handler close_daemon()\n self.exit_future.set_result(True)\n\n async def check_register_socket(self):\n try:\n reader, writer = await asyncio.open_connection(\"localhost\", self.port)\n message = \"quit\\n\"\n self.log.debug(f\"Send: {message.strip()}\")\n writer.write(message.encode())\n data = await reader.read(100) # until('\\n')\n writer.close()\n # await asyncio.sleep(1) # otherwise new instance of keyboard fails\n\n self.log.debug(f\"Received: {data.decode()!r}\")\n if \"quitting\" in data.decode():\n print(\"Other instance did terminate.\")\n self.log.info(\"Old instance terminated.\")\n if self.toml_data[self.name][\"kill_daemon\"] is True:\n print(\"Exiting after quitting other instance.\")\n exit(0)\n except Exception as e:\n self.log.debug(f\"Reading from socket failed: {e}\")\n\n try:\n self.server = await asyncio.start_server(\n self.handle_client, \"localhost\", self.port\n )\n except Exception as e:\n self.log.warning(f\"Can't open server at port {self.port}: {e}\")\n return None\n\n atexit.register(self.close_daemon)\n self.loop.add_signal_handler(\n signal.SIGINT, lambda: asyncio.create_task(self.signal_handler())\n )\n self.loop.add_signal_handler(\n signal.SIGTERM, lambda: asyncio.create_task(self.signal_handler())\n )\n # signal.signal(signal.SIGINT, self.signal_handler)\n # signal.signal(signal.SIGTERM, self.signal_handler)\n return self.server\n\n async def get(self):\n _ = await self.exit_future\n return {\n \"cmd\": \"system\",\n \"time\": datetime.now(tz=ZoneInfo(\"UTC\")),\n \"topic\": \"$SYS/PROCESS\",\n \"msg\": \"QUIT\",\n \"origin\": self.name,\n }\n\n async def put(self, _):\n return\n","sub_path":"attic/python_indrajala/src/indrajala/in_signal_server.py","file_name":"in_signal_server.py","file_ext":"py","file_size_in_byte":4142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"141136439","text":"from siamese_network import siamese_net,contrastive_loss\r\n# from simple_network import siamese_net\r\nfrom keras.optimizers import SGD,Adam\r\nfrom keras.callbacks import CSVLogger\r\nfrom keras.utils.vis_utils import plot_model\r\nfrom utils import batch_generator,get_random_batch,loss_plot,compute_accuracy\r\nimport pandas as pd\r\nimport numpy as np\r\nimport time\r\n\"\"\"\r\nimport os\r\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"\"\r\n\"\"\"\r\n\r\nTRAIN_PATH = 'metadata/train.csv'\r\nTEST_PATH = 'metadata/test.csv'\r\nVECTOR_PATH = 'word2vec-embedding/vecs_custom_std.csv'\r\nMODEL_PATH = 'SiameseNet.h5'\r\n\r\ndata = pd.read_csv(TRAIN_PATH)\r\n\r\ngroups = np.unique(data.style_id)\r\ngroup_size = len(groups)\r\n\r\n# train-val split\r\ntrain_groups = np.random.choice(groups,size=round(group_size*0.8),replace=False)\r\nval_groups = np.setdiff1d(groups,train_groups)\r\ntrain = data[data.style_id.isin(train_groups)]\r\nval = data[data.style_id.isin(val_groups)]\r\n\r\n# Create a dict storing word-vectors\r\nvec_dict = dict()\r\nwith open(VECTOR_PATH) as f:\r\n\tfor i,line in enumerate(f):\r\n\t\tif i > 0:\r\n\t\t\tpair = line.strip().split(',')\r\n\t\t\titem_id, item_vec = pair[0], np.array(pair[1:],dtype='float')\r\n\t\t\tvec_dict[item_id] = item_vec\r\n\r\nMODE = 'image-text'\r\n\r\n# Generate Validation Data\r\nv_t_pos,v_i_pos,v_t_neg,v_i_neg,v_sim = get_random_batch(val_groups,val,vec_dict,mode=MODE,batch_halfsize=256)\r\n\r\n\r\nmodel = siamese_net((300,),(200,200,3))\r\nsgd = SGD(lr=0.001,decay=1e-6)\r\nadam = Adam(lr=0.001,decay=1e-6)\r\nEPOCHS = 20\r\ncsv_logger = CSVLogger('log/training.log')\r\n\r\n\r\n# cosine similarity - binary_crossentropy/ euclidean dist - constrastive loss\r\nstart_time = time.time()\r\nmodel.compile(loss='binary_crossentropy',optimizer=sgd,metrics=['accuracy'])\r\nloss_history = model.fit_generator(batch_generator(train_groups,train,vec_dict,match_mode=MODE,batch_size=64), \r\n \t\tsteps_per_epoch = 50,\r\n \t\tvalidation_data=([v_t_pos,v_i_pos,v_t_neg,v_i_neg], v_sim),\r\n epochs = EPOCHS,\r\n verbose = True,\r\n callbacks=[csv_logger])\r\nprint(\"--- Training process takes {} seconds ---\".format(time.time()-start_time))\r\n\r\nmodel.save(MODEL_PATH)\r\n# plot_model(model,to_file='output/model.png',show_layer_names=True)\r\nloss_plot(loss_history,EPOCHS,path='output/Train.png')\r\n\r\n# Evaluation\r\ntest = pd.read_csv(TEST_PATH)\r\ntest_groups = np.unique(test.style_id)\r\nscores = model.evaluate_generator(batch_generator(test_groups,test,vec_dict,match_mode=MODE,batch_size=64),\r\n\t\t\t\t\t\t\t\t\tsteps=10)\r\ntest_p_t,test_p_i,test_n_t,test_n_i,sim_true = get_random_batch(test_groups,test,vec_dict,mode=MODE,batch_halfsize=64)\r\nsim_pred = model.predict([test_p_t,test_p_i,test_n_t,test_n_i])\r\ntest_acc = compute_accuracy(sim_pred,sim_true)\r\n\r\nwith open('output/test.txt','w',encoding='utf-8') as f:\r\n\tf.write('test loss: {} acc-keras: {}'.format(scores[0],scores[1],test_acc))\r\n\r\n\r\n","sub_path":"train_siamese_net.py","file_name":"train_siamese_net.py","file_ext":"py","file_size_in_byte":3007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"123023721","text":"#!/usr/bin/env python\n\n# -*- coding: utf-8 -*-\n\n# -----------------------------------------------------------------------------\n# -----------------------------------------------------------------------------\n# Name: databaseWrapper\n# Purpose:\n#\n# Author: Administrator\n#\n# Created: 12/03/2012\n# Copyright: (c) Administrator 2012\n# Licence: \n# -----------------------------------------------------------------------------\n\nfrom sqlalchemy.pool import NullPool\nfrom sqlalchemy import create_engine\nimport traceback\nimport logging\nlog = logging.getLogger(__name__)\n\n\nfrom schedulingTask import task\nfrom schedulingTask import taskState\nfrom scheduleConfig import *\n\n\nclass databaseWrapper(object):\n def __init__(self, tableName, hostName):\n self.engine = create_engine(DB_URI, poolclass=NullPool, use_native_unicode=False)\n\n self.createTable = createTable % (tableName)\n self.insertSQL = insertTask\n self.locktblSQL = lockTable % (tableName)\n self.unlocktblSQL = unlockTable\n self.checkTaskSQL = checkTask\n self.selectTaskSQL = selectTask\n self.selectFailedTaskSQL = selectFailedTask\n self.selectTimeoutTaskSQL = selectTimeoutTask\n self.chooseTaskSQL = chooseTask\n self.updateTaskSQL = updateTask\n self.purgeTaskSQL = purgeTask\n\n self.tableName = tableName\n self.hostName = hostName\n\n def connect(self):\n log.debug('databaseWrapper.connect')\n try:\n return self.engine.connect()\n except:\n log.error(traceback.format_exc())\n return None\n\n def createMgmtTable(self):\n log.debug('databaseWrapper.createTable')\n\n try:\n con = self.connect()\n con.execute(self.createTable)\n except:\n log.error(traceback.format_exc())\n return None\n\n def addTask(self, task):\n ret = False\n\n conn = self.connect()\n return self._addTask(conn, task)\n\n def _addTask(self, con, task):\n log.debug('databaseWrapper._addTask')\n ret = False\n sql = self.insertSQL % (\n self.tableName,\n task.getid(),\n task.gettaskTime(),\n taskState['waiting'],\n task.gettimeout(),\n task.getRetryInterval(),\n self.hostName,\n task.getMaxExecutionTimes()\n )\n try:\n con.execute(sql)\n ret = True\n except:\n log.error(traceback.format_exc())\n log.error('Failed to execute sql:%s', sql)\n ret = False\n return ret\n\n def _purgeTask(self, con):\n log.debug('databaseWrapper._purgeTask')\n sql = self.purgeTaskSQL % (self.tableName, taskState['failed'])\n try:\n con.execute(sql)\n except:\n log.error(traceback.format_exc())\n log.error('Failed to execute sql:%s', sql)\n\n def requestTask(self):\n log.debug('databaseWrapper.requestTask')\n task = None\n con = None\n try:\n con = self.connect()\n task = self._requestTask(con)\n except Exception:\n log.exception('databaseWrapper.requestTask')\n finally:\n if con:\n con.close()\n return task\n\n def _selectTask(self, con, state):\n log.debug('databaseWrapper._selectTask')\n retTask = None\n if state == taskState['failed']:\n selectSQL = self.selectFailedTaskSQL % (self.tableName, state)\n elif state == taskState['running']:\n selectSQL = self.selectTimeoutTaskSQL % (self.tableName, state)\n else:\n selectSQL = self.selectTaskSQL % (self.tableName, state)\n\n log.debug('selectSQL:%s', selectSQL)\n res = con.execute(selectSQL)\n\n recordSet = self._fetchRecordset(res)\n\n if not recordSet:\n return retTask\n\n selectedRecord = None\n for record in recordSet: # select empty or other node task firstly\n if 'currentOwner' not in record:\n selectedRecord = record\n break\n if record['currentOwner'] != self.hostName:\n selectedRecord = record\n break\n\n if not selectedRecord:\n selectedRecord = recordSet[0]\n\n if recordSet:\n taskid = selectedRecord['id']\n taskTime = int(selectedRecord['taskTime'])\n timeout = int(selectedRecord['timeout'])\n maxTimes = int(selectedRecord['maxExecutionTimes'])\n retryInterval = int(selectedRecord['retryInterval'])\n executionTimes = int(selectedRecord['executionTimes']) + 1\n\n # print taskid, type(taskid)\n log.debug('taskid:%s, taskTime:%d, timeout:%d',\n taskid.encode('utf-8'), taskTime, timeout)\n retTask = task(taskid, taskTime, timeout, maxTimes, retryInterval,\n executionTimes)\n return retTask\n\n def _chooseTask(self, con, task):\n log.debug('databaseWrapper._chooseTask')\n chooseSQL = self.chooseTaskSQL % (\n self.tableName, taskState['running'],\n self.hostName,\n self.hostName,\n task.getid(),\n task.gettaskTime()\n )\n log.debug('chooseSQL:%s', chooseSQL)\n con.execute(chooseSQL)\n\n def _requestTask(self, con):\n log.debug('databaseWrapper._requestTask')\n choosedTask = None\n\n try:\n tran = con.begin()\n except:\n log.error(traceback.format_exc())\n tran = None\n\n self._lockTable(con)\n\n try:\n fakeLoop = True\n while(fakeLoop):\n fakeLoop = False\n # 1. select task with waiting state\n choosedTask = self._selectTask(con, taskState['waiting'])\n if choosedTask:\n log.debug('waiting task selected')\n break\n\n # 2. select task with failed state\n log.debug('no waiting tasks')\n choosedTask = self._selectTask(con, taskState['failed'])\n if choosedTask:\n log.debug('failed task selected')\n break\n\n # 3. select task which is timeout\n log.debug('no failed tasks')\n choosedTask = self._selectTask(con, taskState['running'])\n if choosedTask:\n log.debug('timeout task selected')\n break\n\n log.debug('no timeout tasks')\n\n if choosedTask:\n self._chooseTask(con, choosedTask)\n else:\n log.debug('no tasks avaliable')\n\n except:\n log.exception('request task exception')\n finally:\n self._unlockTable(con)\n\n if tran:\n tran.commit()\n\n return choosedTask\n\n def _fetchRecordset(self, result):\n log.debug('databaseWrapper._fetchRecordset')\n return result.fetchall()\n\n def _lockTable(self, con):\n log.debug('databaseWrapper._lockTable')\n con.execute(self.locktblSQL)\n\n def _unlockTable(self, con):\n log.debug('databaseWrapper._unlockTable')\n if self.unlocktblSQL:\n con.execute(self.unlocktblSQL)\n\n def _endTask(self, con, task, succeed):\n log.debug('databaseWrapper._endTask')\n if succeed:\n updateSQL = self.updateTaskSQL % (\n self.tableName,\n taskState['succeed'],\n task.getid(),\n task.gettaskTime(),\n self.hostName\n )\n else:\n updateSQL = self.updateTaskSQL % (\n self.tableName,\n taskState['failed'],\n task.getid(),\n task.gettaskTime(),\n self.hostName\n )\n log.debug('updateSQL:%s', updateSQL)\n con.execute(updateSQL)\n\n def endTask(self, task, succeed):\n log.debug('databaseWrapper.endTask')\n con = None\n try:\n con = self.connect()\n self._endTask(con, task, succeed)\n if not succeed and task.maxExecutionTimes <= task.executionTimes:\n self._purgeTask(con)\n except Exception:\n log.exception('endTask exception')\n finally:\n if con:\n con.close()\n\n\ndef main():\n pass\n\nif __name__ == '__main__':\n main()\n","sub_path":"CommonModule/schedulingFramework/schedulingFramework/databaseWrapper.py","file_name":"databaseWrapper.py","file_ext":"py","file_size_in_byte":8537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"207298186","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 29 20:43:22 2016\n\n@author: bthalenberg\n\"\"\"\n\ndef quadrados():\n '''Dada uma seqüência de números inteiros não-nulos, seguida por 0, imprime seus quadrados.'''\n \n n = int(input(\"Insira o número desejado (para finalizar, digite 0): \"))\n \n while n != 0:\n print(\"%d^2 = %d.\" %(n, n**2))\n n = int(input(\"Insira o número desejado (para finalizar, digite 0): \"))\n\n#------\n\ndef soma(n):\n '''Dado um número inteiro positivo n, calcular a soma dos n primeiros números inteiros positivos. '''\n \n i = 1 #inteiro positivo que também serve como contador\n soma = 1\n \n while i <= n:\n i += 1\n soma += i\n return soma\n \n#----\n\ndef impares(n):\n ''' Dado um número inteiro positivo n, imprimir os n primeiros naturais ímpares. \n Exemplo: Para n=4 a saída deverá ser 1,3,5,7. '''\n \n i = 1\n k = 1\n \n while k <= n:\n print(i)\n i += 2\n k += 1\n \n#----\n \ndef potencia(x, n):\n '''Dados um inteiro x e um inteiro não-negativo n, calcular x^n. '''\n\n return x**n\n \n#----\n \ndef loja_discos():\n ''' Uma loja de discos anota diariamente durante o mês de março a quantidade de discos vendidos. \n Determinar em que dia desse mês ocorreu a maior venda e qual foi a quantidade de discos vendida nesse dia.'''\n \n dia = 1\n melhor_dia = 1\n melhor_discos = 0\n \n while dia <= 31:\n discos = int(input(\"Insira a quantidade de discos vendida no dia %d: \" %(dia)))\n if discos > melhor_discos:\n melhor_discos = discos\n melhor_dia = dia\n dia += 1\n \n print(\"O melhor dia de vendas foi o dia %d, quando foram vendidos %d discos.\" %(melhor_dia, melhor_discos))\n \n#----\n \ndef mac_414(n):\n '''Dados o número n de alunos de uma turma de Introdução aos Autômatos a Pilha (MAC 414) e suas notas da primeira\n prova, determinar a maior e a menor nota obtidas por essa turma (Nota máxima = 100 e nota mínima = 0). '''\n \n melhor_nota = 0\n pior_nota = 100\n k = 1\n \n while k <= n:\n nota = int(input(\"Insira a nota do %dº aluno: \" %(k)))\n if nota > melhor_nota:\n melhor_nota = nota\n if nota < pior_nota:\n pior_nota = nota\n k += 1\n \n print(\"A melhor nota da turma foi %d, e a pior foi %d.\" %(melhor_nota, pior_nota))\n \n#-----\n \ndef soma_pares(n):\n '''Dados n e uma seqüência de n números inteiros, determinar a soma dos números pares.'''\n \n par = 2\n soma = 2\n \n while par < n:\n par += 2\n soma += par\n \n return soma\n \n#-----\n \ndef fatorial(n):\n '''Dado n, retorna n!'''\n \n k = 1\n fatorial = n\n \n while k < n:\n fatorial *= k\n k += 1\n \n return fatorial \n \n#-----\n \ndef multiplos(n, i, j):\n '''Dados n e dois números inteiros positivos i e j diferentes de 0, imprimir em ordem crescente \n os n primeiros naturais que são múltiplos de i ou de j e ou de ambos. \n Exemplo: Para n = 6 , i = 2 e j = 3 a saída deverá ser : 0,2,3,4,6,8. '''\n \n multiplo = 0\n k = 0\n \n while k < n:\n if multiplo % i == 0 or multiplo % j == 0: #se o resto é zero, é múltiplo\n print(multiplo)\n k += 1\n multiplo += 1\n \n#------\n\ndef triangulador(n):\n '''Dizemos que um número natural é triangular se ele é produto de três números naturais consecutivos.\n Exemplo: 120 é triangular, pois 4.5.6 = 120.\n Dado um inteiro não-negativo n, verificar se n é triangular. '''\n \n a = 1\n b = 2\n c = 3 \n triangular = False\n \n while a*b*c < n:\n a += 1; b += 1; c += 1\n if a*b*c % n == 0:\n print(\"%d é triangular de %d, %d e %d.\" %(n, a, b, c))\n triangular = True\n if triangular == False:\n print(\"O número não é triangular.\") \n \n#-----\n \ndef is_primo(n):\n '''Dado n, verifica se n é primo.'''\n \n k = 2\n is_primo = True\n \n while k < n:\n if n % k == 0:\n is_primo = False\n k += 1\n \n if is_primo == True:\n print(\"O número %d é primo.\" %(n))\n else:\n print(\"O número não é primo.\")\n \n#------\n \ndef mdc_euclides(i,j):\n '''Dados i e j, verifica o MDC entre eles pelo algoritmo de Euclides'''\n \n resto = 12 #apenas para inicializar\n \n while resto != 0:\n resto = i % j #obtém o resto da divisão do maior pelo menor\n i = j #divisor se torna dividendo\n j = resto #resto se torna novo divisor\n print(\"O MDC é %d.\" %(i)) #lembrar que i é o novo j\n\n#-----\n\ndef perfeito(n):\n '''Dizemos que um inteiro positivo n é perfeito se for igual à soma de seus divisores positivos diferentes de n.\n Exemplo: 6 é perfeito, pois 1+2+3 = 6. Dado um inteiro positivo n, verificar se n é perfeito. '''\n \n k = n - 1\n soma = 0\n \n while k >= 1:\n if n % k == 0: #se for divisor\n soma += k\n k -= 1\n \n if soma == n:\n print(\"O número %d é perfeito.\" %(n))\n else:\n print(\"O número %d não é perfeito.\" %(n))\n \n#------\n \ndef fibonacci(n):\n '''Dado n, calcula o enésimo termo da sequência de Fibonacci'''\n \n a = 1\n b = 1\n c = 2\n k = 3 #contador (começa em 3 porque 2 é o terceiro termo)\n \n if n >= 3:\n \n while k <= n:\n c = a + b #o terceiro é a soma do penúltimo com o último \n a = b #o último passa a ser penúltimo a = 1\n b = c #o recém somado passa a ser o último \n k += 1\n print(c)\n \n if n <= 2:\n print(1)\n \n \n#------\n \ndef congruente(n, m, j):\n ''' Dizemos que um número i é congruente módulo m a j se i % m = j % m. Exemplo: 35 é congruente módulo 4 a 39, pois\n 35 % 4 = 3 = 39 % 4. Dados inteiros positivos n, j e m, imprimir os n primeiros naturais congruentes a j módulo m.\n n = quantos números serão impressos\n m = módulo\n j = número'''\n \n i = 0\n \n while n != 0:\n if i % m == j % m and i % m != 0:\n print(i)\n n -= 1\n i += 1\n \n#------\n \ndef binario_decimal(n):\n ''' Dado um número natural n na base binária, transforma-o para base decimal.'''\n \n decimal = 0\n k = 0 #contador de dígitos e também potência\n \n while n != 0:\n if n % 10 != 0: #significa que o algarismo da unidade é 1\n decimal += 2**k \n k += 1\n n //= 10 #próximo dígito\n print(decimal)\n \n#----\n \ndef decimal_binario(n):\n ''' Dado um número natural n na base decimal, transforma-o para base binária.'''\n \n binario = 0\n i = 1\n \n while n > 0:\n unidade = n % 2 #se for ímpar, adiciona o 1; se for par, divide por base 2\n binario = binario + (i * unidade) \n n //= 2 #reduz na base decimal\n i *= 10 #aumenta a potência (que resultará nos zeros em binario)\n print(binario)\n \n#------\n \ndef triangulo_reto(a, b, c):\n ''' Dados três números naturais, verificar se eles formam os lados de um triângulo retângulo.'''\n \n #parte do princípio que c é a hipotenusa\n if a > c: #checa se a é a hipotenusa e coloca em c\n aux = c\n c = a\n a = aux \n elif b > c: #checa se b é a hipotenusa e coloca em c\n aux = c\n c = b\n b = aux\n \n \n if a**2 + b**2 == c**2: #checa se é retângulo\n print(\"Os números formam um triângulo retângulo.\")\n else:\n print(\"Os números não formam um triângulo retângulo.\")\n \n#------\n\ndef crescente(a, b, c):\n '''Dados três números naturais a, b e c, imprime-os em ordem crescente.'''\n \n #parte do princípio que a é menor\n if b < a:\n if c < b:\n print(c, b, a)\n else:\n if c < a:\n print(b, c, a)\n else:\n print(b, a, c)\n elif c < a:\n print(c, a, b) #passou o primeiro loop então já sabemos que b é menor que a\n else:\n if b < c:\n print(a, b, c)\n else:\n print(a, c, b)\n \n#-----\n \ndef raiz_milhar():\n '''Qualquer número natural de quatro algarismos pode ser dividido em duas dezenas formadas pelos seus dois \n primeiros e dois últimos dígitos. Escreva um programa que imprime todos os milhares (4 algarismos) cuja raiz \n quadrada seja a soma das dezenas formadas pela divisão acima. Exemplo: raiz de 9801 = 99 = 98 + 01. Portanto 9801 \n é um dos números a ser impresso.'''\n \n n = 1000\n \n while n < 10000:\n a = n % 100 #segunda dupla\n b = n // 100 #primeira dupla\n \n if (a+b)*(a+b) == n:\n print(n)\n n+=1\n \n#----\ndef segm_seq():\n ''' (POLI 87) Dados n e uma seqüência de n números inteiros, determinar quantos segmentos de números iguais consecutivos \n compõem essa seqüência. Exemplo: A seguinte seqüência é formada por 5 segmentos de números iguais: \n 5, 2, 2, 3, 4, 4, 4, 4, 1, 1 '''\n \n n = int(input(\"Insira o tamanho da sequência: \"))\n k = 0\n ant = 0\n segm = 0\n \n while k != n:\n i = int(input(\"Insira um número natural: \"))\n if i != ant:\n segm += 1\n ant = i\n k += 1\n print(segm) \n \n#-----\ndef segm_max():\n '''Dados n e uma seqüência de n números inteiros, determinar o comprimento de um segmento crescente de comprimento máximo.\n Exemplos:\n Na seqüência 5, 10, 3, 2, 4, 7, 9, 8, 5 o comprimento do segmento crescente máximo é 4.\n Na seqüência 10, 8, 7, 5, 2 o comprimento de um segmento crescente máximo é 1. '''\n \n n = int(input(\"Insira o tamanho da sequência: \"))\n k = 0\n tam = 1\n tam_max = 1\n \n\n i = int(input(\"Insira um número: \"))\n ant = i\n \n while k != n:\n if i > ant:\n tam += 1\n if tam > tam_max:\n tam_max = tam\n else:\n tam = 1\n ant = i\n k += 1\n i = int(input(\"Insira um número: \"))\n \n \n print(tam_max)\n\n#----\n\ndef palindromo(n):\n '''Dizemos que um número natural n é palíndromo (3) se \n o 1º algarismo de n é igual ao seu último algarismo, \n o 2º algarismo de n é igual ao penúltimo algarismo, \n e assim sucessivamente. Dado n, n > 10, verifica se é palíndromo.'''\n\n aux = n #guarda o que resta inverter\n reverso = 0 #guarda o invertido\n \n while aux != 0: \n reverso = (aux % 10) + (reverso * 10) #pega a unidade de n e multiplica reverso para receber a próxima unidade\n aux //= 10\n if reverso == n:\n print(\"O número %d é palíndromo.\" %(n))\n else:\n print(\"O número %d não é palíndromo.\" %(n))\n \n#------\n \ndef subnumero(p, q):\n '''Dados os números naturais p e q, p < q, verifica se p é subnúmero de q.'''\n \n aux = q\n n = 10\n subnumero = False\n r = 0\n \n while n <= p: #se p = 333, n=1000\n n = n*10 #para saber o tamanho de p\n \n \n while aux >= p and not subnumero:\n r = aux % n \n aux //= 10 #aux == 433\n print(n,r,aux)\n if r == p:\n subnumero = True\n \n if subnumero == True:\n print(\"%d é subnúmero de %d.\" %(p, q))\n else:\n print(\"%d não é subnúmero de %d.\" %(p,q))\n \n \n \n \n ","sub_path":"lista-inteiros.py","file_name":"lista-inteiros.py","file_ext":"py","file_size_in_byte":11608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"190302195","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\n\"\"\"Modules with classes to create customs widgets\"\"\"\n\nfrom PyQt5 import QtWidgets\nfrom PyQt5 import QtGui\nfrom PyQt5 import QtCore\n\nimport funcMisc\n\nclass CustomTreeModel(QtGui.QStandardItemModel):\n\n \"\"\"\n Create a custom model. Reimplement dropMimeData to add a custom\n QStandartItem with specific data and disable child item in QTreeView\n \"\"\"\n\n item_added = QtCore.pyqtSignal(object)\n\n\n def __init__(self, parent = None):\n\n QtGui.QStandardItemModel.__init__(self, parent)\n\n\n def dropMimeData(self, data, action, row, column, parent):\n\n \"\"\"\n Reimplement function. Add a new item with epic of\n market added to favorite as data of new item\n\n :param data: QtCore.QMimeData, data dropped\n :param action: QtCore.DropAction\n :param row, column: int row and column where item is added\n :param parent: QtCore.QmodelIndex\n \"\"\"\n\n # data comes from internal drop\n if data.hasFormat(\"application/x-qstandarditemmodeldatalist\"):\n return False\n\n # data comes from a QListWidget\n elif data.hasFormat('application/x-qabstractitemmodeldatalist'):\n\n byte_array = data.data('application/x-qabstractitemmodeldatalist')\n data_items = self.decode_data(byte_array)\n\n # get text and data of dropped item\n text = data_items[0][0].value()\n data = data_items[0][256].value()\n\n favorite_markets = funcMisc.read_favorites()\n favorite_epic = favorite_markets[\"epic\"]\n\n if data in favorite_epic.values: # market already in favorites\n return False\n else:\n # create a new item with epic of market dropped\n item_market = QtGui.QStandardItem(text)\n\n # disable child item\n item_market.setFlags(item_market.flags()^QtCore.Qt.ItemIsDropEnabled)\n item_market.setData(data)\n\n self.appendRow(item_market)\n self.item_added.emit(item_market) # emit item\n\n return True\n else:\n return QStandardItemModel.dropMimeData(self, data, action,\n row, column, parent)\n\n\n def decode_data(self, byte_array):\n\n \"\"\"Decode data dropped\"\"\"\n\n data = []\n item = {}\n\n ds = QtCore.QDataStream(byte_array)\n\n while not ds.atEnd():\n row = ds.readInt32()\n column = ds.readInt32()\n map_items = ds.readInt32()\n\n for i in range(map_items):\n\n key = ds.readInt32()\n value = QtCore.QVariant()\n ds >> value\n\n item[QtCore.Qt.ItemDataRole(key)] = value\n\n data.append(item)\n\n return data\n\n\nclass CustomPushButton(QtWidgets.QPushButton):\n\n \"\"\"\n Create a custom QPushButton to change style\n when user interact with it (hovered, pressed)\n \"\"\"\n\n # signal emitted when left button is clicked\n # btn_clicked = QtCore.pyqtSignal(object)\n\n def __init__(self, text, object_name):\n\n \"\"\"\n :param text: string, text to set inside button\n :param object_name: string\n \"\"\"\n\n QtWidgets.QPushButton.__init__(self, text)\n\n # self.setSizePolicy(QtWidgets.QSizePolicy.Expanding,\n # QtWidgets.QSizePolicy.Expanding)\n\n self.setObjectName(object_name)\n self.object_name = object_name\n\n\n def set_default_style(self, color, background_color):\n\n \"\"\"\n Set a style sheet to change appearance of button when it\n is hovered or clicked.\n\n :param color: string, hexadecimal color\n :param background_color: string, hexadecimal color\n \"\"\"\n\n self.setStyleSheet(\"QPushButton#\" + self.object_name +\n \"{background-color:\" + color + \";\\n\"\n \"border-radius: 4px;\\n\"\n \"font: 12px;\\n\"\n \"color: white;\\n\"\n \"padding: 6px;}\\n\"\n\n \"QPushButton#\" + self.object_name + \":pressed\"\\\n \"{background-color:\" + background_color + \";}\\n\"\n\n \"QPushButton#\" + self.object_name + \":hover\"\\\n \"{border-color: #333333;\\n\"\n \"border-style: solid ;\\n\"\n \"border-width: 1px;}\")\n\n\n def on_order_key(self, background_color):\n\n \"\"\"\n Set a style when button is clicked, changes background alpha color\n \"\"\"\n\n self.setStyleSheet(\"QPushButton#\" + self.object_name +\n \"{background-color:\" + background_color + \";\\n\"\n \"border-radius: 4px;\\n\"\n \"font: 12px;\\n\"\n \"color: white;\\n\"\n # \"min-width: 7em;\\n\"\n \"padding: 6px;}\")\n\n # def mousePressEvent(self, event):\n\n # \"\"\"Reimplement click event to emit object name\"\"\"\n\n # if event.buttons() == QtCore.Qt.LeftButton:\n # self.btn_clicked.emit(self.objectName())\n # else:\n # self.mousePressEvent(self, event)\n\nclass CustomTableWidget(QtWidgets.QTableWidget):\n\n \"\"\"\n Create a custom QtableWidget to overrides keypressEvent\n As the left/right arrow are used to trade ignore them\n when they occurs on tablewidget\n \"\"\"\n\n def __init__(self, nb_row, nb_col):\n\n \"\"\"\n :param nb_row: int\n :param nb_col: int\n \"\"\"\n\n QtWidgets.QTableWidget.__init__(self, nb_row, nb_col)\n\n\n def keyPressEvent(self, event):\n\n \"\"\"\n Ignore key events used to buy and sell\n\n :param event: QKeyEvent\n \"\"\"\n\n config = funcMisc.read_config()\n\n buy_key = config[\"buy_key\"]\n sell_key = config[\"sell_key\"]\n\n\n if type(event) == QtGui.QKeyEvent:\n human_key = QtGui.QKeySequence(event.key())\\\n .toString(QtGui.QKeySequence.NativeText)\n\n if human_key == buy_key or human_key == sell_key:\n event.ignore()\n\n # elif event.key() == QtCore.Qt.Key_Left:\n # event.ignore()\n\n # elif event.key() == QtCore.Qt.Key_Right:\n # event.ignore()\n else:\n event.accept()\n QtWidgets.QTableWidget.keyPressEvent(self, event)\n else:\n event.accept()\n\n\nclass CustomLabel(QtWidgets.QLabel):\n\n \"\"\"\n Class to create a custom QLabel. Set a style when mouse hover\n widget a emit a signal when widget is clicked\n \"\"\"\n\n clicked_signal = QtCore.pyqtSignal(object) # emit when user clicks on widget\n\n\n def __init__(self, object_name):\n\n \"\"\"\n :param object_name: string\n \"\"\"\n\n QtWidgets.QLabel.__init__(self)\n self.setObjectName(object_name)\n\n\n def set_default_style(self, background_color, hover_color, border_color):\n\n \"\"\"Set different style when widget is hovered\"\"\"\n\n self.setStyleSheet(\"QLabel#\" + self.objectName() +\n \"{background-color :\" + background_color + \";\\n\"\n \"border-radius : 1px;\\n\"\n \"padding : 1px;}\\n\"\n\n \"QLabel#\" + self.objectName() +\":hover\"\n \"{background-color :\" + hover_color + \";\\n\"\n \"border-color :\" + border_color + \";\\n\"\n \"border-style : solid ;\\n\"\n \"border-width : 1px;}\")\n\n\n def mousePressEvent(self, event):\n\n \"\"\"\n Emit a signal when widget is clicked\n\n :param event: QMouseEvent\n \"\"\"\n\n self.clicked_signal.emit(self.objectName())\n event.accept()\n\n\n def set_italic(self, is_italic, *args, **kwargs):\n\n \"\"\"\n Set or not an italic font\n\n :param is_italic: boolean\n \"\"\"\n\n font = QtGui.QFont()\n font.setFamily(font.defaultFamily())\n font.setItalic(is_italic)\n self.setFont(font)\n\n\nclass CustomComboBox(QtWidgets.QComboBox):\n\n \"\"\"\n Class to reimplement focusOutEvent and send appropriate signal.\n I couldn't find a better way to catch this event\n \"\"\"\n\n focus_out_signal = QtCore.pyqtSignal() # emit when focus out\n\n\n def __init__(self, object_name):\n\n \"\"\"\n :param object_name: string\n \"\"\"\n\n QtWidgets.QComboBox.__init__(self)\n self.setObjectName(object_name)\n self.setFocusPolicy(QtCore.Qt.StrongFocus)\n\n\n def focusOutEvent(self, event):\n\n \"\"\"\n Emit a custom signal on focus out event\n\n :param event: QFocusEvent\n \"\"\"\n\n self.focus_out_signal.emit()\n event.accept()\n\n\nclass CustomLineEdit(QtWidgets.QLineEdit):\n\n \"\"\"\n Subclass base QLineEdit to reimplement\n focusInEvent and clickEvent and select all text\n \"\"\"\n\n text_changed = QtCore.pyqtSignal(object, object)\n\n def __init__(self, object_name, *args, **kwargs):\n\n \"\"\"\n :param object_name: string\n \"\"\"\n\n QtWidgets.QLineEdit.__init__(self)\n self.setObjectName(object_name)\n\n # connect base signal to custom function\n self.textChanged.connect(self.on_text_changed)\n\n\n def set_italic(self, is_italic, *args, **kwargs):\n\n \"\"\"\n Set or not an italic font\n\n :param is_italic: boolean\n \"\"\"\n\n font = QtGui.QFont()\n font.setFamily(font.defaultFamily())\n font.setItalic(is_italic)\n self.setFont(font)\n\n\n def focusInEvent(self, event):\n\n \"\"\"Select all text when widget get focus\"\"\"\n\n self.selectAll()\n\n\n def mousePressEvent(self, event):\n\n \"\"\"Select all text when widget get click event\"\"\"\n\n self.selectAll()\n\n\n def on_text_changed(self, event):\n\n \"\"\"Emit object name and text set\"\"\"\n\n self.text_changed.emit(self.objectName(), self.text())\n\n\nclass CustomShortcutLineEdit(QtWidgets.QLineEdit):\n\n \"\"\"\n Same as CustomLineEdit excepts that keyPressEvent is also\n reimplementedto capture Qt KeySequence and creates key shortcuts\n \"\"\"\n\n text_changed = QtCore.pyqtSignal(object, object)\n\n def __init__(self, object_name, *args, **kwargs):\n\n \"\"\"\n :param object_name: string\n \"\"\"\n\n QtWidgets.QLineEdit.__init__(self)\n self.setObjectName(object_name)\n\n # connect base signal to custom function\n self.textChanged.connect(self.on_text_changed)\n\n\n def set_italic(self, is_italic, *args, **kwargs):\n\n \"\"\"\n Set or not an italic font\n\n :param is_italic: boolean\n \"\"\"\n\n font = QtGui.QFont()\n font.setFamily(font.defaultFamily())\n font.setItalic(is_italic)\n self.setFont(font)\n\n\n def focusInEvent(self, event):\n\n \"\"\"Select all text when widget get focus\"\"\"\n\n self.selectAll()\n\n\n def mousePressEvent(self, event):\n\n \"\"\"Select all text when widget get click event\"\"\"\n\n self.selectAll()\n\n\n def on_text_changed(self, event):\n\n \"\"\"Emit object name and text set\"\"\"\n\n self.text_changed.emit(self.objectName(), self.text())\n\n\n def set_keysequence(self, keysequence):\n\n \"\"\"Set text of key sequence entered\"\"\"\n\n self.keysequence = keysequence\n human_keysequence = self.keysequence.toString(QtGui.QKeySequence.NativeText)\n self.setText(human_keysequence)\n\n\n def keyPressEvent(self, event):\n\n \"\"\"Reimplement base method to capture key sequence\"\"\"\n\n if event.type() == QtCore.QEvent.KeyPress:\n key = event.key()\n\n favorite_markets = funcMisc.read_favorites()\n favorite_shortcuts = favorite_markets[\"shortcut\"]\n\n config = funcMisc.read_config()\n\n order_keys = [\"buy_key\", \"sell_key\", \"close_key\"]\n order_values = [config[order_key] for order_key in order_keys]\n\n if key == QtCore.Qt.Key_unknown:\n warnings.warn(\"Unknown key from a macro probably\")\n return\n\n # the user have clicked just and only the special keys Ctrl, Shift, Alt, Meta.\n if(key == QtCore.Qt.Key_Control or\n key == QtCore.Qt.Key_Shift or\n key == QtCore.Qt.Key_Alt or\n key == QtCore.Qt.Key_Meta):\n return\n\n # check for a combination of user clicks\n modifiers = event.modifiers()\n keyText = event.text()\n\n # if the keyText is empty than it's a special key like F1, F5, ...\n if modifiers & QtCore.Qt.ShiftModifier:\n key += QtCore.Qt.SHIFT\n if modifiers & QtCore.Qt.ControlModifier:\n key += QtCore.Qt.CTRL\n if modifiers & QtCore.Qt.AltModifier:\n key += QtCore.Qt.ALT\n if modifiers & QtCore.Qt.MetaModifier:\n key += QtCore.Qt.META\n\n human_keysequence = QtGui.QKeySequence(key)\\\n .toString(QtGui.QKeySequence.NativeText)\n\n # check if key sequense is already use\n if human_keysequence in favorite_shortcuts.values:\n idx_conflict = favorite_markets[human_keysequence==favorite_shortcuts].index[0]\n name_conflict = favorite_markets.loc[idx_conflict, \"name\"]\n\n self.keysequence = u\"Shortcut already used for %s !\" %name_conflict\n\n # trigger signal even if text has not been set\n self.text_changed.emit(self.objectName(), self.text())\n\n # if shortcut is arrow key or empty, set shortcut as invalid\n elif human_keysequence in order_values:\n\n idx_conflict = order_values.index(human_keysequence)\n name_conflict = order_keys[idx_conflict].split(\"_\")[0]\n\n self.keysequence = u\"Shortcut already used for %s %s !\"\\\n %(name_conflict, \"order\")\n\n # trigger signal even if text has not been set\n self.text_changed.emit(self.objectName(), self.text())\n\n else:\n self.set_keysequence(QtGui.QKeySequence(key))\n\n\nclass CustomSpinBox(QtWidgets.QDoubleSpinBox):\n\n \"\"\"\n Custom checkbox to customize the numbres of decimals\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n\n\n QtWidgets.QSpinBox.__init__(self, *args, **kwargs)\n\n\n def textFromValue(self, value):\n\n \"\"\"\n Reimplement the default method to adjust digits shown\n\n :param value: float\n \"\"\"\n\n return(\"%.1f\" % value)\n\n\n # def valueFromText(self, text):\n\n # \"\"\"\n # Reimplement the default method to adjust digits shown\n\n # :param text: string, entered by user\n # \"\"\"\n\n # return(float(text))\n\n\nclass CustomCheckBox(QtWidgets.QCheckBox):\n\n \"\"\"\n Custom checkbox to emit a custom signal when state is changed\n \"\"\"\n\n state_changed = QtCore.pyqtSignal(object)\n\n def __init__(self, object_name):\n\n \"\"\"\n :param object_name: string\n \"\"\"\n\n QtWidgets.QCheckBox.__init__(self)\n self.setObjectName(object_name)\n\n # connect base signal to custom one\n self.stateChanged.connect(self.on_state_changed)\n\n\n def on_state_changed(self, event, *args, **kwargs):\n\n \"\"\"\n Emit custom signal with object name\n \"\"\"\n\n self.state_changed.emit(self.objectName())\n\n\n","sub_path":"classCustomWidgets.py","file_name":"classCustomWidgets.py","file_ext":"py","file_size_in_byte":15606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"303231006","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('hosts', '0005_auto_20160129_0720'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='taskinfo',\n name='task_type',\n field=models.CharField(max_length=50, choices=[(b'multi_cmd', b'CMD'), (b'file_send', b'\\xe6\\x96\\x87\\xe4\\xbb\\xb6\\xe4\\xb8\\x8a\\xe4\\xbc\\xa0'), (b'file_get', b'\\xe6\\x96\\x87\\xe4\\xbb\\xb6\\xe4\\xb8\\x8b\\xe8\\xbd\\xbd')]),\n ),\n ]\n","sub_path":"hosts/migrations/0006_auto_20160129_0728.py","file_name":"0006_auto_20160129_0728.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"119509431","text":"# coding=utf-8\n\nimport requests\nfrom io import BytesIO\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime\nfrom bs4 import BeautifulSoup\n\n## 아래 4줄을 추가해 줍니다.\nimport os, re\n# os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"config.settings.production\")\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"config.settings.local\")\nimport django\ndjango.setup()\n\nfrom django.conf import settings\nfrom srim.users.models import User\n\nheaders = {\n 'User-Agent': \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36\",\n 'Referer': 'http://kind.krx.co.kr'\n}\n\nFG_url = 'http://comp.fnguide.com/SVO2/ASP/SVD_main.asp?pGB=1&gicode=A{code}&cID=&MenuYn=Y&ReportGB=&NewMenuID=11&stkGb=&strResearchYN='\n\n###\n### 5년 만기 BBB- 금리 얻어서 파일로 저장\n###\ninterest_url = 'http://www.rating.co.kr/disclosure/QDisclosure029.do'\nres = requests.get(interest_url)\n\nsoup = BeautifulSoup(res.text, 'html.parser')\ntable = soup.find('table')\ndf_raw = pd.read_html(str(table))[0]\ndf_raw.set_index('등급', inplace=True)\n\ninterest = float(\"{0:.2f}\".format(df_raw.loc['BBB-', ['5년']][0]))\n\n### update가 완료되면, admin 유저에 interest 값 추가\nuser = User.objects.get(id=1)\nuser.interest = interest\nuser.save()\n\n\n###\n### 종목코드 크롤링\n###\ndef stock_master():\n url = 'http://kind.krx.co.kr/corpgeneral/corpList.do'\n data = {\n 'method':'download',\n 'orderMode':'1', # 정렬컬럼\n 'orderStat':'D', # 정렬 내림차순\n 'searchType':'13', # 검색유형: 상장법인\n 'fiscalYearEnd':'all', # 결산월: 전체\n 'location':'all', # 지역: 전체\n }\n\n r = requests.post(url, data=data, headers=headers)\n f = BytesIO(r.content)\n dfs = pd.read_html(f, header=0, parse_dates=['상장일'])\n df = dfs[0].copy()\n\n # 숫자를 앞자리가 0인 6자리 문자열로 변환\n df['종목코드'] = df['종목코드'].astype(np.str) \n df['종목코드'] = df['종목코드'].str.zfill(6)\n return df\n\ndf_master = stock_master()\ndf = df_master.loc[:, ['회사명', '종목코드', '업종', '상장일', '결산월']]\ndf.rename(columns={'회사명': '종목명'}, inplace=True)\ndf = df.loc[:, ['종목명', '종목코드']]\n\ndf['현재가'] = np.nan\ndf['매도가'] = np.nan\ndf['적정가'] = np.nan\ndf['매수가'] = np.nan\ndf['지배주주지분'] = np.nan\ndf['roe'] = np.nan\ndf['roe1'] = np.nan\ndf['roe2'] = np.nan\ndf['roe3'] = np.nan\ndf['보통주발행주수'] = np.nan\ndf['우선주발행주수'] = np.nan\ndf['자기주식'] = np.nan\ndf['주식수'] = np.nan\ndf['contrast'] = np.nan\n\nfn_url = 'http://comp.fnguide.com/SVO2/ASP/SVD_main.asp?pGB=1&gicode=A{code}&cID=&MenuYn=Y&ReportGB=&NewMenuID=11&stkGb=&strResearchYN='\nfn_headers = {\n 'User-Agent': \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36\",\n 'Referer': 'http://comp.fnguide.com/SVO2/ASP/SVD_main.asp?pGB=1&gicode=A005930&cID=&MenuYn=Y&ReportGB=&NewMenuID=11&stkGb=&strResearchYN='\n}\n\ndef get_fn_data(code):\n # 종목명\n item = df[df['종목코드']==code]['종목명'][idx]\n \n res = requests.get(fn_url.format(code=code))\n soup = BeautifulSoup(res.text, 'html.parser')\n\n####################################\n### FN 가이드 크롤링\n####################################\n general_shares = None\n prior_shares = None\n try:\n # 현재가\n current_price = int(soup.select('#div1 .rwf .r')[0].text.split('/')[0].replace(',', ''))\n \n # 보통주 / 우선주발행주식수\n titles = soup.select(\"div#svdMainGrid1 table tbody tr > th > div\")\n for title in titles:\n if title.text == \"발행주식수(보통주/ 우선주)\":\n general_shares = int([x for x in title.parent.next_siblings if x!='\\n'][0].text.split('/')[0].replace(',', ''))\n prior_shares = int([x for x in title.parent.next_siblings if x!='\\n'][0].text.split('/')[1].replace(',', ''))\n break\n \n # 자기주식수\n company_shares = soup.select('#svdMainGrid5 th[title*=\"자기주식\"]')[0].parent.find_all('td')[1].text.strip().replace(',', '')\n if company_shares == '':\n company_shares = 0\n else:\n company_shares = int(company_shares)\n \n # 자기자본\n for tag in soup.select('#highlight_D_A tbody tr th.clf'):\n if tag.text.strip() == '지배주주지분':\n equity = int(tag.parent.find_all('td')[2].text.replace(',', ''))\n # roe1(1년 전 roe)\n for tag in soup.select('#highlight_D_A tbody tr th.clf div a span'):\n if tag.text.strip() == 'ROE':\n if tag.find_parent('tr').find_all('td')[2].text.strip() == '':\n roe1 = np.nan\n else:\n try:\n roe1 = float(tag.find_parent('tr').find_all('td')[2].text.strip())\n except:\n roe1 = tag.find_parent('tr').find_all('td')[2].text.strip()\n # roe2(2년 전 roe)\n for tag in soup.select('#highlight_D_A tbody tr th.clf div a span'):\n if tag.text.strip() == 'ROE':\n if tag.find_parent('tr').find_all('td')[1].text.strip() == '':\n roe2 = np.nan\n else:\n try:\n roe2 = float(tag.find_parent('tr').find_all('td')[1].text.strip())\n except:\n roe2 = tag.find_parent('tr').find_all('td')[1].text.strip()\n # roe3(3년 전 roe)\n for tag in soup.select('#highlight_D_A tbody tr th.clf div a span'):\n if tag.text.strip() == 'ROE':\n if tag.find_parent('tr').find_all('td')[0].text.strip() == '':\n roe3 = np.nan\n else:\n try:\n roe3 = float(tag.find_parent('tr').find_all('td')[0].text.strip())\n except:\n roe3 = tag.find_parent('tr').find_all('td')[0].text.strip()\n # roe(올해 추정치)\n for tag in soup.select('#highlight_D_A tbody tr th.clf div a span'):\n if tag.text.strip() == 'ROE':\n if tag.find_parent('tr').find_all('td')[3].text.strip() == '':\n if isinstance(roe1, float) and isinstance(roe2, float) and isinstance(roe3, float):\n # ROE가 3년 연속 상승하고 있으면 전 년도 roe(가장 높은)를 사용하겠다.\n if roe3 < roe2 and roe2 < roe1:\n roe = roe1\n # ROE가 3년 연속 하락하고 있으면 전 년도 roe(가장 낮은)를 사용하겠다.\n elif roe3 > roe2 and roe2 > roe1:\n roe = roe1\n # ROE에 경향이 없으면 최근 값에 가중치를 주어 평균을 내 사용하겠다.\n else:\n roe = (roe1*3 + roe2*2 + roe3*1) / 6\n else:\n roe = np.nan\n else:\n try:\n roe = round(float(tag.find_parent('tr').find_all('td')[3].text.strip()), 2)\n except:\n roe = tag.find_parent('tr').find_all('td')[3].text.strip()\n\n ################################\n ### 크롤링 데이터 기반 SRIM 계산\n ################################\n\n # S-RIM 계산을 위한 주식 수: 보통주 + 우선주 - 자기주식\n shares = general_shares + prior_shares - company_shares\n # 매수가(초과이익 20% 씩 감소)\n try:\n buy_price = int((equity + equity*(roe*0.01-interest*0.01) * 0.8/(1+interest*0.01-0.8))*pow(10,8) / shares)\n except:\n buy_price = np.nan\n # 적정가(초과이익 10% 씩 감소)\n try:\n proper_price = int((equity + equity*(roe*0.01-interest*0.01) * 0.9/(1+interest*0.01-0.9))*pow(10,8) / shares)\n except:\n proper_price = np.nan\n # 매도가(초과이익 지속)\n try:\n sell_price = int((equity + equity*(roe-interest)/interest)*pow(10,8) / shares)\n except:\n sell_price = np.nan\n # 적정가 대비 현재가\n try:\n contrast = round((current_price/proper_price - 1) * 100, 2)\n except:\n contrast = np.nan\n \n except: \n return None\n\n return {\n 'current_price': current_price,\n 'sell_price': sell_price,\n 'proper_price': proper_price,\n 'buy_price': buy_price,\n 'roe': roe,\n 'roe1': roe1,\n 'roe2': roe2,\n 'roe3': roe3,\n 'general_shares': general_shares,\n 'prior_shares': prior_shares,\n 'company_shares': company_shares,\n 'shares': shares,\n 'contrast': contrast,\n 'equity': equity\n }\n\n\nexcept_list = []\n\nfor idx, row in df.iterrows():\n if idx%100==0:\n print(idx)\n code = row['종목코드']\n item = row['종목명']\n res = get_fn_data(code)\n \n # get_fn_data 함수 내부에서 크롤링을 정상 && SRIM 계산 정상\n if res != None:\n df.loc[idx, '현재가'] = res.get('current_price')\n df.loc[idx, '매수가'] = res.get('buy_price')\n df.loc[idx, '적정가'] = res.get('proper_price')\n df.loc[idx, '매도가'] = res.get('sell_price')\n df.loc[idx, '지배주주지분'] = res.get('equity')\n \n df.loc[idx, 'roe'] = res.get('roe')\n df.loc[idx, 'roe1'] = res.get('roe1')\n df.loc[idx, 'roe2'] = res.get('roe2')\n df.loc[idx, 'roe3'] = res.get('roe3')\n \n df.loc[idx, '보통주발행주수'] = res.get('general_shares')\n df.loc[idx, '우선주발행주수'] = res.get('prior_shares')\n df.loc[idx, '자기주식'] = res.get('company_shares')\n \n df.loc[idx, '주식수'] = res.get('shares')\n df.loc[idx, 'contrast'] = res.get('contrast')\n \n # get_fn_data 함수 내부에서 크롤링 or SRIM 계산에서 예외 발생 시 종목명 list에 저장 및 출력\n else:\n except_list.append(item)\n print(\"예외발생: \", item)\n\ndf.rename(columns={\n '종목명': 'cmp_name',\n '종목코드': 'cmp_code',\n '현재가': 'current_price',\n '매수가': 'buy_price',\n '적정가': 'proper_price',\n '매도가': 'sell_price',\n '보통주발행주수': 'general_shares',\n '우선주발행주수': 'prior_shares',\n '자기주식': 'cmp_shares',\n '주식수': 'shares',\n '지배주주지분': 'equity'\n }, inplace=True)\n\n# df.to_csv('srim_data_180425.csv', sep=',',encoding='utf-8')\ntoday = datetime.today().strftime('%Y%m%d')\ndf.to_csv('/home/ec2-user/csv_data/'+today+'_srim.csv',encoding='utf-8')\n\nwith open('/home/ec2-user/csv_data/'+today+'_except_list.txt', 'w') as f:\n for _string in except_list:\n f.write(str(_string)+'\\n')\n","sub_path":"srim_get_data.py","file_name":"srim_get_data.py","file_ext":"py","file_size_in_byte":11138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"214412199","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'music'\n\nurlpatterns = [\n # /music/\n url(r'^$', views.IndexView.as_view(), name='index'),\n\n # /music/id/\n url(r'^(?P[0-9]+)/$', views.DetailView.as_view(), name='info'),\n\n]\n","sub_path":"unchained/music/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"53632755","text":"from spyne import Iterable, Integer, Unicode, rpc, Application, ServiceBase, Array, TTableModel, Integer32, String, ComplexModel, Float, xml\nfrom spyne.protocol.soap import Soap11\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import MetaData\nfrom sqlalchemy.orm import sessionmaker\n\nimport dicttoxml\nimport datetime \n\nfrom lxml import etree\nimport xmlschema\n\n# Generate a ComplexModelBase subclass with\n# metadata information\n# Initialize SQLAlchemy Environment\nengine = create_engine('sqlite:///./air.db')\n\nclass AirTempService(ServiceBase):\n\n @rpc(_returns=String)\n def sendProfile(ctx):\n result_ = \"\"\"\n \n \n 58-010126-3018-1\n Sumet Boonya\n Game, Music\n \n \n \"\"\"\n return result_\n\n @rpc(Integer, String, String, Float, _returns=String)\n def inserItem(ctx, id_, send, recive, weight):\n print(id_, send, recive, weight)\n print(type(id_))\n print(type(send))\n print(type(recive),type(weight))\n \n sql = f'insert into stock values ({id_},\"{send}\",\"{recive}\",{weight},0)'\n result = engine.execute(sql)\n \n return f\"insert success id: {id_}\"\n\n @rpc(Integer, Integer, _returns=String)\n def updateItem(ctx, id_, status):\n sql = f'update stock set status = {status} where id = {id_}'\n result = engine.execute(sql)\n return f\"update success id: {id_} status:{status}\"\n\n @rpc(_returns=String)\n def showStockAll(ctx,): \n sql = f'select * from stock'\n results = engine.execute(sql)\n dictTemp = []\n for r in results:\n tempData={}\n tempData['id'] = r[0]\n tempData['sender'] = r[1]\n tempData['reciever'] = r[2]\n tempData['weight'] = r[3]\n tempData['status'] = r[4]\n dictTemp.append(tempData)\n xml = dicttoxml.dicttoxml(dictTemp) \n return xml\n \ndef create_app(flask_app):\n \"\"\"Creates SOAP services application and distribute Flask config into\n user con defined context for each method call.\n \"\"\"\n application = Application([AirTempService], 'spyne.examples.flask',\n in_protocol=Soap11(validator='lxml'),\n out_protocol=Soap11()\n # out_protocol=Soap11(),\n )\n\n return application","sub_path":"apps/spyned.py","file_name":"spyned.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"648046787","text":"import tkinter as tk\nimport tkinter.ttk as ttk\nimport pyvisa\nimport multiprocessing as mp\nimport queue\nimport time\nimport datetime\nimport os\nimport sys\n#import planilhasExcel as excel\nimport serial\n\n\nclass App(tk.Tk):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n # dispositivosDisponiveis = list()\n # self.rm = pyvisa.ResourceManager()\n # dispositivosDisponiveis = self.rm.list_resources()\n # dispositivosSerialDisponiveis = self.serial_ports()\n\n dispositivosDisponiveis = list()\n dispositivosSerialDisponiveis = list()\n\n self.geometry('762x363') # tab3: 762x422\n self.configure(background='white')\n self.title('Automação Testes')\n self.resizable(0, 0)\n #self.iconphoto(True, tk.PhotoImage(file=self.resource_path('mackico.png')))\n\n self.s = ttk.Style()\n self.s.configure('white.TCheckbutton', background='white')\n\n self.tab_parent = ttk.Notebook(self)\n\n self.tab1 = ttk.Frame(self.tab_parent, style ='TNotebook')\n self.tab2 = ttk.Frame(self.tab_parent, style ='TNotebook')\n self.tab3 = ttk.Frame(self.tab_parent, style ='TNotebook')\n\n self.tab_parent.bind(\"<>\", self.on_tab_selected)\n\n self.tab_parent.add(self.tab1, text=\"Multipercurso ISDB-TB\")\n self.tab_parent.add(self.tab2, text=\"DVB-S2: Faixa de frequência\")\n self.tab_parent.add(self.tab3, text=\"DVB-S2: Máximo C/N\")\n\n self.tab_parent.pack(expand=1, fill='both')\n\n #########################################################################################################################################################\n ################################################################# Multipercurso ISDB-TB #################################################################\n #########################################################################################################################################################\n\n ######################################################################## Frame 1 ########################################################################\n\n self.labelf11= tk.LabelFrame(self.tab1, text='Dispositivos', background='white', height=179, width=746)\n self.labelf11.place(relx=0, rely=0, x=5, y=5)\n\n self.label = ttk.Label(self.labelf11, text='Modulador OFDM', background='white').place(relx=0, rely=0, x=29, y=5)\n\n self.moduladorOFDMTeste1= tk.StringVar()\n self.combo111 = ttk.Combobox(self.labelf11,values=dispositivosDisponiveis, textvariable=self.moduladorOFDMTeste1, width=30, justify='center')\n self.combo111.place(relx=0, rely=0, x=130, y=5)\n self.combo111.bind('<>', lambda event, endereco='self.moduladorOFDMTeste1', entrada='self.moduladorOFDMTeste1IDN': self.verificaIDN(event, endereco, entrada))\n \n self.moduladorOFDMTeste1IDN = tk.StringVar()\n self.entry111 = ttk.Entry(self.labelf11, textvariable=self.moduladorOFDMTeste1IDN, width=63, justify='center', state='read')\n self.entry111.place(relx=0, rely=0, x=340, y=5)\n\n self.label = ttk.Label(self.labelf11, text='Atenuador', background='white').place(relx=0, rely=0, x=69, y=35)\n\n self.atenuadorTeste1 = tk.StringVar()\n self.combo112 = ttk.Combobox(self.labelf11,values=dispositivosDisponiveis, textvariable=self.atenuadorTeste1, width=30, justify='center')\n self.combo112.place(relx=0, rely=0, x=130, y=35)\n self.combo112.bind('<>', lambda event, endereco='self.atenuadorTeste1', entrada='self.atenuadorTeste1IDN': self.verificaIDN(event, endereco, entrada))\n \n self.atenuadorTeste1IDN = tk.StringVar()\n self.entry112 = ttk.Entry(self.labelf11, textvariable=self.atenuadorTeste1IDN, width=63, justify='center', state='read')\n self.entry112.place(relx=0, rely=0, x=340, y=35)\n\n self.label = ttk.Label(self.labelf11, text='Fading Simulator', background='white').place(relx=0, rely=0, x=35, y=65)\n\n self.fadingSimulatorTeste1 = tk.StringVar()\n self.combo113 = ttk.Combobox(self.labelf11,values=dispositivosDisponiveis, textvariable=self.fadingSimulatorTeste1, width=30, justify='center')\n self.combo113.place(relx=0, rely=0, x=130, y=65)\n self.combo113.bind('<>', lambda event, endereco='self.fadingSimulatorTeste1', entrada='self.fadingSimulatorTeste1IDN': self.verificaIDN(event, endereco, entrada))\n \n self.fadingSimulatorTeste1IDN = tk.StringVar()\n self.entry113 = ttk.Entry(self.labelf11, textvariable=self.fadingSimulatorTeste1IDN, width=63, justify='center', state='read')\n self.entry113.place(relx=0, rely=0, x=340, y=65)\n\n self.label = ttk.Label(self.labelf11, text='Analisador de Espectro', background='white').place(relx=0, rely=0, x=5, y=95)\n\n self.analisadorDeEspectroTeste1 = tk.StringVar()\n self.combo114 = ttk.Combobox(self.labelf11,values=dispositivosDisponiveis, textvariable=self.analisadorDeEspectroTeste1, width=30, justify='center')\n self.combo114.place(relx=0, rely=0, x=130, y=95)\n self.combo114.bind('<>', lambda event, endereco='self.analisadorDeEspectroTeste1', entrada='self.analisadorDeEspectroTeste1IDN': self.verificaIDN(event, endereco, entrada))\n\n self.analisadorDeEspectroTeste1IDN = tk.StringVar()\n self.entry114 = ttk.Entry(self.labelf11, textvariable=self.analisadorDeEspectroTeste1IDN, width=63, justify='center', state='read')\n self.entry114.place(relx=0, rely=0, x=340, y=95)\n\n self.label = ttk.Label(self.labelf11, text='MultiRxSat', background='white').place(relx=0, rely=0, x=70, y=125)\n\n self.multiRxSatTeste1 = tk.StringVar(value='COM4')\n self.combo115 = ttk.Combobox(self.labelf11, values=dispositivosSerialDisponiveis, textvariable=self.multiRxSatTeste1, width=30, justify='center')\n self.combo115.place(relx=0, rely=0, x=132, y=125)\n self.combo115.bind('<>', lambda event, endereco='self.multiRxSatTeste1', entrada='self.multiRxSatTeste1IDN': self.verificaIDN(event, endereco, entrada))\n\n self.multiRxSatTeste1IDN = tk.StringVar()\n self.entry115 = ttk.Entry(self.labelf11, textvariable=self.multiRxSatTeste1IDN, width=63, justify='center', state='read')\n self.entry115.place(relx=0, rely=0, x=340, y=125)\n\n ######################################################################## Frame 2 ########################################################################\n\n self.labelf12= tk.LabelFrame(self.tab1, text='Parametros de Teste', background='white', height=100, width=746)\n self.labelf12.place(relx=0, rely=0, x=5, y=190)\n\n ####################################################################### Frame 2.1 #######################################################################\n\n self.labelf121= tk.LabelFrame(self.labelf12, text='Modulador OFDM', background='white', height=55, width=332)\n self.labelf121.place(relx=0, rely=0, x=5, y=5)\n\n self.moduladorEIDENfrequencia = tk.DoubleVar()\n self.moduladorEIDENfrequenciaSTR = tk.StringVar()\n self.label = ttk.Label(self.labelf121, text='Freq', background='white').place(relx=0, rely=0, x=13, y=5)\n self.e11 = ttk.Entry(self.labelf121, textvariable=self.moduladorEIDENfrequencia,width=12, justify='center')\n self.e11.place(relx=0, rely=0, x=41, y=4)\n self.e11.bind('', lambda event, variavel='self.moduladorEIDENfrequencia', valorMin=30.0, valorMax=2000.0, indexVirgula=4, numDeCaracteres=11 , sinal = False, retornar = False: self.enviaComandoEIDEN(event, variavel, valorMin, valorMax, indexVirgula, numDeCaracteres, sinal, retornar))\n self.label = ttk.Label(self.labelf121, text='MHz', background='white').place(relx=0, rely=0, x=120, y=5)\n\n self.moduladorEIDENlevel = tk.DoubleVar()\n self.moduladorEIDENlevelSTR = tk.StringVar()\n self.label = ttk.Label(self.labelf121, text='Level', background='white').place(relx=0, rely=0, x=203, y=5)\n self.e12 = ttk.Entry(self.labelf121, textvariable=self.moduladorEIDENlevel,width=7, justify='center')\n self.e12.place(relx=0, rely=0, x=235, y=4)\n self.e12.bind('', lambda event, variavel='self.moduladorEIDENlevel', valorMin=-89.0, valorMax=10.0, indexVirgula=3, numDeCaracteres=6, sinal = True, retornar = False: self.enviaComandoEIDEN(event, variavel, valorMin, valorMax, indexVirgula, numDeCaracteres, sinal, retornar))\n self.label = ttk.Label(self.labelf121, text='dBm', background='white').place(relx=0, rely=0, x=284, y=5)\n\n ####################################################################### Frame 2.2 #######################################################################\n\n self.labelf122= tk.LabelFrame(self.labelf12, text='Fading Simulator', background='white',height=55, width=332)\n self.labelf122.place(relx=0, rely=0, x=340, y=5)\n\n self.label = ttk.Label(self.labelf122, text='Freq', background='white').place(relx=0, rely=0, x=13, y=5)\n self.e13 = ttk.Entry(self.labelf122, textvariable=self.moduladorEIDENfrequencia,width=12, justify='center')\n self.e13.place(relx=0, rely=0, x=41, y=4)\n self.e13.bind('', lambda event, variavel='self.moduladorEIDENfrequencia', valorMin=30.0, valorMax=2000.0, indexVirgula=4, numDeCaracteres=11 , sinal = False, retornar = False: self.enviaComandoEIDEN(event, variavel, valorMin, valorMax, indexVirgula, numDeCaracteres, sinal, retornar))\n self.label = ttk.Label(self.labelf122, text='MHz', background='white').place(relx=0, rely=0, x=120, y=5)\n\n self.delayFadingSimulator = tk.DoubleVar()\n self.valoresDelay = list()\n self.label = ttk.Label(self.labelf122, text='Delay', background='white').place(relx=0, rely=0, x=178, y=5)\n self.combo14 = ttk.Combobox(self.labelf122, textvariable=self.delayFadingSimulator,width=10, justify='center')\n self.combo14.place(relx=0, rely=0, x=213, y=4)\n self.combo14.bind('', lambda event: self.adicionaDelay(event))\n self.label = ttk.Label(self.labelf122, text='us', background='white').place(relx=0, rely=0, x=297, y=5)\n\n ####################################################################### Progresso #######################################################################\n \n self.labelProgressoTeste1= tk.LabelFrame(self.tab1, text='Status', background='white',height=115, width=346)\n self.labelProgressoTeste1.place(relx=0, rely=0, x=5, y=292)\n\n self.entryBar1VarTeste1 = tk.StringVar(value='Pronto')\n self.entryBar1Teste1 = ttk.Entry(self.labelProgressoTeste1, textvariable=self.entryBar1VarTeste1, background='white', width=24, justify='center')\n self.entryBar1Teste1.place(relx=0, rely=0, x=5, y=5)\n\n self.entryBar2VarTeste1 = tk.StringVar()\n self.entryBar2Teste1 = ttk.Entry(self.labelProgressoTeste1, textvariable=self.entryBar2VarTeste1, background='white', width=14, justify='center')\n self.entryBar2Teste1.place(relx=0, rely=0, x=156, y=5)\n\n self.entryBar3VarTeste1 = tk.StringVar()\n self.entryBar3Teste1 = ttk.Entry(self.labelProgressoTeste1, textvariable=self.entryBar3VarTeste1, background='white', width=14, justify='center')\n self.entryBar3Teste1.place(relx=0, rely=0, x=247, y=5)\n\n self.progressoTeste1= ttk.Progressbar(self.labelProgressoTeste1, orient='horizontal',length=331, value=0, mode='determinate')\n self.progressoTeste1.place(relx=0, rely=0, x=5, y=35)\n\n self.buttonStartTeste1 = ttk.Button(self.labelProgressoTeste1, text='Start', command=lambda: self.iniciar_teste1())\n self.buttonStartTeste1.place(relx=0, rely=0, x=260, y=65)\n\n #########################################################################################################################################################\n\n #########################################################################################################################################################\n ############################################################## DVB-S2: Faixa de frequência ##############################################################\n #########################################################################################################################################################\n\n ######################################################################## Frame 1 ########################################################################\n\n self.labelf21= tk.LabelFrame(self.tab2, text='Dispositivos', background='white', height=148, width=745)\n self.labelf21.place(relx=0, rely=0, x=5, y=5)\n\n self.label = ttk.Label(self.labelf21, text='Modulador DVB-S2 SFU', background='white').place(relx=0, rely=0, x=9, y=5)\n\n self.moduladorSfuTeste2 = tk.StringVar(value='GPIB0::8::INSTR')\n self.combo211 = ttk.Combobox(self.labelf21, values=dispositivosDisponiveis, textvariable=self.moduladorSfuTeste2, width=30, justify='center')\n self.combo211.place(relx=0, rely=0, x=137, y=5)\n self.combo211.bind('<>', lambda event, endereco='self.moduladorSfuTeste2', entrada='self.moduladorSfuTeste2IDN': self.verificaIDN(event, endereco, entrada))\n\n self.moduladorSfuTeste2IDN = tk.StringVar()\n self.entry211 = ttk.Entry(self.labelf21, textvariable=self.moduladorSfuTeste2IDN, width=63, justify='center', state='read')\n self.entry211.place(relx=0, rely=0, x=345, y=5)\n\n self.label = ttk.Label(self.labelf21, text='Atenuador 1', background='white').place(relx=0, rely=0, x=68, y=35)\n\n self.atenuador1Teste2 = tk.StringVar(value='GPIB0::28::INSTR')\n self.combo212 = ttk.Combobox(self.labelf21, values=dispositivosDisponiveis, textvariable=self.atenuador1Teste2, width=30, justify='center')\n self.combo212.place(relx=0, rely=0, x=137, y=35)\n self.combo212.bind('<>', lambda event, endereco='self.atenuador1Teste2', entrada='self.atenuador1Teste2IDN': self.verificaIDN(event, endereco, entrada))\n\n self.atenuador1Teste2IDN = tk.StringVar()\n self.entry212 = ttk.Entry(self.labelf21, textvariable=self.atenuador1Teste2IDN, width=63, justify='center', state='read')\n self.entry212.place(relx=0, rely=0, x=345, y=35)\n\n self.label = ttk.Label(self.labelf21, text='MultiRxSat', background='white').place(relx=0, rely=0, x=75, y=65)\n\n self.multiRxSatTeste2 = tk.StringVar(value='COM4')\n self.combo215 = ttk.Combobox(self.labelf21, values=dispositivosSerialDisponiveis, textvariable=self.multiRxSatTeste2, width=30, justify='center')\n self.combo215.place(relx=0, rely=0, x=137, y=65)\n self.combo215.bind('<>', lambda event, endereco='self.multiRxSatTeste2', entrada='self.multiRxSatTeste2IDN': self.verificaIDN(event, endereco, entrada))\n\n self.multiRxSatTeste2IDN = tk.StringVar()\n self.entry215 = ttk.Entry(self.labelf21, textvariable=self.multiRxSatTeste2IDN, width=63, justify='center', state='read')\n self.entry215.place(relx=0, rely=0, x=345, y=65)\n\n self.label = ttk.Label(self.labelf21, text='Analisador de Espectro', background='white').place(relx=0, rely=0, x=12, y=95)\n\n self.analisadorDeEspectroTeste2 = tk.StringVar(value='GPIB0::20::INSTR')\n self.combo216 = ttk.Combobox(self.labelf21, values=dispositivosDisponiveis, textvariable=self.analisadorDeEspectroTeste2, width=30, justify='center')\n self.combo216.place(relx=0, rely=0, x=137, y=95)\n self.combo216.bind('<>', lambda event, endereco='self.analisadorDeEspectroTeste2', entrada='self.analisadorDeEspectroTeste2IDN': self.verificaIDN(event, endereco, entrada))\n\n self.analisadorDeEspectroTeste2IDN = tk.StringVar()\n self.entry216 = ttk.Entry(self.labelf21, textvariable=self.analisadorDeEspectroTeste2IDN, width=63, justify='center', state='read')\n self.entry216.place(relx=0, rely=0, x=345, y=95)\n\n ######################################################################## Frame 2 ########################################################################\n\n self.labelf22= tk.LabelFrame(self.tab2, text='Parametros de Teste', background='white',height=130, width=612)\n self.labelf22.place(relx=0, rely=0, x=5, y=152)\n\n #########################################################################################################################################################\n\n self.labelf222= tk.LabelFrame(self.labelf22, background='white',height=100, width=173)\n self.labelf222.place(relx=0, rely=0, x=5, y=5)\n\n self.frequenciaTeste2 = tk.DoubleVar(value=985.0)\n self.label = ttk.Label(self.labelf222, text='Frequencia', background= 'white').place(relx=0, rely=0, x=14, y=7)\n self.entry221 = ttk.Entry(self.labelf222, textvariable=self.frequenciaTeste2, width=8, justify='center', state='normal')\n self.entry221.place(relx=0, rely=0, x=76, y=7)\n self.label = ttk.Label(self.labelf222, text='MHz', background= 'white').place(relx=0, rely=0, x=131, y=7)\n\n self.symbolRateTeste2 = tk.DoubleVar(value=7.5)\n self.label = ttk.Label(self.labelf222, text='Symbol Rate', background= 'white').place(relx=0, rely=0, x=5, y=37)\n self.entry222 = ttk.Entry(self.labelf222, textvariable=self.symbolRateTeste2, width=8, justify='center', state='normal')\n self.entry222.place(relx=0, rely=0, x=76, y=37)\n self.label = ttk.Label(self.labelf222, text='MS/s', background= 'white').place(relx=0, rely=0, x=131, y=37)\n\n self.rollTeste2 = tk.DoubleVar(value=0.25)\n self.label = ttk.Label(self.labelf222, text='Roll', background= 'white').place(relx=0, rely=0, x=52, y=67)\n self.entry223 = ttk.Entry(self.labelf222, textvariable=self.rollTeste2, width=8, justify='center', state='normal')\n self.entry223.place(relx=0, rely=0, x=76, y=67)\n\n #########################################################################################################################################################\n\n self.labelf223= tk.LabelFrame(self.labelf22, background='white',height=100, width=80)\n self.labelf223.place(relx=0, rely=0, x=183, y=5)\n\n self.modulation1Teste2 = tk.StringVar(value='0')\n self.checkb221 = ttk.Checkbutton(self.labelf223, text= 'QPSK', onvalue='S4', offvalue='0', variable=self.modulation1Teste2, style='white.TCheckbutton', command=lambda: self.desativaModulacao(self.labelf224.winfo_children(), self.modulation1Teste2.get()))\n self.checkb221.place(relx=0, rely=0, x=5, y=3)\n\n self.modulation2Teste2 = tk.StringVar(value='0')\n self.checkb222 = ttk.Checkbutton(self.labelf223, text= '8PSK', onvalue='S8', offvalue='0', variable=self.modulation2Teste2, style='white.TCheckbutton', command=lambda: self.desativaModulacao(self.labelf225.winfo_children(), self.modulation2Teste2.get()))\n self.checkb222.place(relx=0, rely=0, x=5, y=26)\n\n self.modulation3Teste2 = tk.StringVar(value='0')\n self.checkb223 = ttk.Checkbutton(self.labelf223, text= '16APSK', onvalue='A16', offvalue='0', variable=self.modulation3Teste2, style='white.TCheckbutton', command=lambda: self.desativaModulacao(self.labelf226.winfo_children(), self.modulation3Teste2.get()))\n self.checkb223.place(relx=0, rely=0, x=5, y=49)\n\n self.modulation4Teste2 = tk.StringVar(value='0')\n self.checkb224 = ttk.Checkbutton(self.labelf223, text= '32APSK', onvalue='A32', offvalue='0', variable=self.modulation4Teste2, style='white.TCheckbutton', command=lambda: self.desativaModulacao(self.labelf227.winfo_children(), self.modulation4Teste2.get()))\n self.checkb224.place(relx=0, rely=0, x=5, y=72)\n\n #########################################################################################################################################################\n \n self.labelf224= tk.LabelFrame(self.labelf22, background='white', height=108, width=80, text='QPSK')\n self.labelf224.place(relx=0, rely=0, x=268, y=-3)\n\n self.scrollbarQPSKteste2 = ttk.Scrollbar(self.labelf224)\n self.scrollbarQPSKteste2.place(relx=0, rely=0, x=54, y=0, height= 84)\n\n self.mylistQPSKteste2 = tk.Listbox(self.labelf224, yscrollcommand = self.scrollbarQPSKteste2.set, selectmode='multiple', width= 8, height=5, activestyle = 'dotbox', justify='center', exportselection=0)\n self.mylistQPSKteste2.place(relx=0, rely=0, x=3, y=0)\n self.scrollbarQPSKteste2.config(command = self.mylistQPSKteste2.yview)\n\n for line in ['R1_4', 'R1_3', 'R2_5', 'R1_2', 'R3_5', 'R2_3', 'R3_4', 'R4_5', 'R5_6', 'R8_9', 'R9_10']:\n self.mylistQPSKteste2.insert('end', line)\n\n self.mylistQPSKteste2.configure(state='disable')\n \n #########################################################################################################################################################\n\n self.labelf225= tk.LabelFrame(self.labelf22, background='white',height=108, width=80, text='8PSK')\n self.labelf225.place(relx=0, rely=0, x=353, y=-3)\n\n self.scrollbar8PSKteste2 = ttk.Scrollbar(self.labelf225)\n self.scrollbar8PSKteste2.place(relx=0, rely=0, x=54, y=0, height= 84)\n\n self.mylist8PSKteste2 = tk.Listbox(self.labelf225, yscrollcommand = self.scrollbar8PSKteste2.set, selectmode='multiple', width= 8, height=5, activestyle = 'dotbox', justify='center', exportselection=0)\n self.mylist8PSKteste2.place(relx=0, rely=0, x=3, y=0)\n self.scrollbar8PSKteste2.config(command = self.mylist8PSKteste2.yview)\n \n for line in ['R3_5', 'R2_3', 'R3_4', 'R5_6', 'R8_9', 'R9_10']:\n self.mylist8PSKteste2.insert('end', line)\n\n self.mylist8PSKteste2.configure(state='disable')\n\n #########################################################################################################################################################\n\n self.labelf226= tk.LabelFrame(self.labelf22, background='white',height=108, width=80, text='16APSK')\n self.labelf226.place(relx=0, rely=0, x=438, y=-3)\n\n self.scrollbar16APSKteste2 = ttk.Scrollbar(self.labelf226)\n self.scrollbar16APSKteste2.place(relx=0, rely=0, x=54, y=0, height= 84)\n\n self.mylist16APSKteste2 = tk.Listbox(self.labelf226, yscrollcommand = self.scrollbar16APSKteste2.set, selectmode='multiple', width= 8, height=5, activestyle = 'dotbox', justify='center', exportselection=0)\n self.mylist16APSKteste2.place(relx=0, rely=0, x=3, y=0)\n self.scrollbar16APSKteste2.config(command = self.mylist16APSKteste2.yview)\n \n for line in ['R2_3', 'R3_4', 'R4_5', 'R5_6', 'R8_9', 'R9_10']:\n self.mylist16APSKteste2.insert('end', line)\n\n self.mylist16APSKteste2.configure(state='disable')\n\n #########################################################################################################################################################\n\n self.labelf227= tk.LabelFrame(self.labelf22, background='white',height=108, width=80, text='32APSK')\n self.labelf227.place(relx=0, rely=0, x=523, y=-3)\n\n self.scrollbar32APSKteste2 = ttk.Scrollbar(self.labelf227)\n self.scrollbar32APSKteste2.place(relx=0, rely=0, x=54, y=0, height= 84)\n\n self.mylist32APSKteste2 = tk.Listbox(self.labelf227, yscrollcommand = self.scrollbar32APSKteste2.set, selectmode='multiple', width= 8, height=5, activestyle = 'dotbox', justify='center', exportselection=0)\n self.mylist32APSKteste2.place(relx=0, rely=0, x=3, y=0)\n self.scrollbar32APSKteste2.config(command = self.mylist32APSKteste2.yview)\n \n for line in ['R3_4', 'R4_5', 'R5_6', 'R8_9', 'R9_10']:\n self.mylist32APSKteste2.insert('end', line)\n\n self.mylist32APSKteste2.configure(state='disable')\n\n ####################################################################### Progresso #######################################################################\n \n self.labelProgressoTeste2= tk.LabelFrame(self.tab2, background='white',height=40, width=612)\n self.labelProgressoTeste2.place(relx=0, rely=0, x=5, y=289)\n\n self.entryBar1VarTeste2 = tk.StringVar()\n self.entryBar1Teste2 = ttk.Entry(self.labelProgressoTeste2, textvariable=self.entryBar1VarTeste2, background='white', width=30, justify='center', state='readonly')\n self.entryBar1Teste2.place(relx=0, rely=0, x=5, y=7)\n\n self.entryBar2VarTeste2 = tk.StringVar()\n self.entryBar2Teste2 = ttk.Entry(self.labelProgressoTeste2, textvariable=self.entryBar2VarTeste2, background='white', width=10, justify='center', state='readonly')\n self.entryBar2Teste2.place(relx=0, rely=0, x=218, y=7)\n\n self.progresso1Teste2 = ttk.Progressbar(self.labelProgressoTeste2, orient='horizontal',length=120, value=0, maximum=4, mode='determinate')\n self.progresso1Teste2.place(relx=0, rely=0, x=288, y=7, height=21)\n\n self.entryBar3VarTeste2 = tk.StringVar()\n self.entryBar3Teste2 = ttk.Entry(self.labelProgressoTeste2, textvariable=self.entryBar3VarTeste2, background='white', width=10, justify='center', state='readonly')\n self.entryBar3Teste2.place(relx=0, rely=0, x=412, y=7)\n\n self.progresso2Teste2 = ttk.Progressbar(self.labelProgressoTeste2, orient='horizontal',length=120, value=0, maximum=11, mode='determinate')\n self.progresso2Teste2.place(relx=0, rely=0, x=482, y=7, height=21)\n\n self.buttonStartTeste2 = ttk.Button(self.tab2, text='Start', width= 18, command=lambda: self.iniciar_teste2())\n self.buttonStartTeste2.place(relx=0, rely=0, x=623, y=159, height=123)\n\n #########################################################################################################################################################\n ################################################################### DVB-S2: Máximo C/N ##################################################################\n #########################################################################################################################################################\n\n ######################################################################## Frame 1 ########################################################################\n\n self.labelf31= tk.LabelFrame(self.tab3, text='Dispositivos', background='white', height=207, width=745)\n self.labelf31.place(relx=0, rely=0, x=5, y=5)\n\n self.label = ttk.Label(self.labelf31, text='Modulador DVB-S2 SFU', background='white').place(relx=0, rely=0, x=9, y=5)\n\n self.moduladorSfuTeste3 = tk.StringVar(value='GPIB0::8::INSTR')\n self.combo311 = ttk.Combobox(self.labelf31, values=dispositivosDisponiveis, textvariable=self.moduladorSfuTeste3, width=30, justify='center')\n self.combo311.place(relx=0, rely=0, x=137, y=5)\n self.combo311.bind('<>', lambda event, endereco='self.moduladorSfuTeste3', entrada='self.moduladorSfuTeste3IDN': self.verificaIDN(event, endereco, entrada))\n\n self.moduladorSfuTeste3IDN = tk.StringVar()\n self.entry311 = ttk.Entry(self.labelf31, textvariable=self.moduladorSfuTeste3IDN, width=63, justify='center', state='read')\n self.entry311.place(relx=0, rely=0, x=345, y=5)\n\n self.label = ttk.Label(self.labelf31, text='Atenuador 1', background='white').place(relx=0, rely=0, x=68, y=35)\n\n self.atenuador1Teste3 = tk.StringVar(value='GPIB0::28::INSTR')\n self.combo312 = ttk.Combobox(self.labelf31, values=dispositivosDisponiveis, textvariable=self.atenuador1Teste3, width=30, justify='center')\n self.combo312.place(relx=0, rely=0, x=137, y=35)\n self.combo312.bind('<>', lambda event, endereco='self.atenuador1Teste3', entrada='self.atenuador1Teste3IDN': self.verificaIDN(event, endereco, entrada))\n\n self.atenuador1Teste3IDN = tk.StringVar()\n self.entry312 = ttk.Entry(self.labelf31, textvariable=self.atenuador1Teste3IDN, width=63, justify='center', state='read')\n self.entry312.place(relx=0, rely=0, x=345, y=35)\n\n self.label = ttk.Label(self.labelf31, text='Vector Signal Generator', background='white').place(relx=0, rely=0, x=8, y=65)\n\n self.vectorSignalGeneratorSmuTeste3 = tk.StringVar(value='GPIB0::7::INSTR')\n self.combo313 = ttk.Combobox(self.labelf31, values=dispositivosDisponiveis, textvariable=self.vectorSignalGeneratorSmuTeste3, width=30, justify='center')\n self.combo313.place(relx=0, rely=0, x=137, y=65)\n self.combo313.bind('<>', lambda event, endereco='self.vectorSignalGeneratorSmuTeste3', entrada='self.vectorSignalGeneratorSmuTeste3IDN': self.verificaIDN(event, endereco, entrada))\n\n self.vectorSignalGeneratorSmuTeste3IDN = tk.StringVar()\n self.entry313 = ttk.Entry(self.labelf31, textvariable=self.vectorSignalGeneratorSmuTeste3IDN, width=63, justify='center', state='read')\n self.entry313.place(relx=0, rely=0, x=345, y=65)\n\n self.label = ttk.Label(self.labelf31, text='Atenuador 2', background='white').place(relx=0, rely=0, x=68, y=95)\n\n self.atenuador2Teste3 = tk.StringVar(value='USB0::0x0AAD::0x00B5::101591::INSTR')\n self.combo314 = ttk.Combobox(self.labelf31, values=dispositivosDisponiveis, textvariable=self.atenuador2Teste3, width=30, justify='center')\n self.combo314.place(relx=0, rely=0, x=137, y=95)\n self.combo314.bind('<>', lambda event, endereco='self.atenuador2Teste3', entrada='self.atenuador2Teste3IDN': self.verificaIDN(event, endereco, entrada))\n\n self.atenuador2Teste3IDN = tk.StringVar()\n self.entry314 = ttk.Entry(self.labelf31, textvariable=self.atenuador2Teste3IDN, width=63, justify='center', state='read')\n self.entry314.place(relx=0, rely=0, x=345, y=95)\n\n self.label = ttk.Label(self.labelf31, text='MultiRxSat', background='white').place(relx=0, rely=0, x=75, y=125)\n\n self.multiRxSatTeste3 = tk.StringVar(value='COM4')\n self.combo315 = ttk.Combobox(self.labelf31, values=dispositivosSerialDisponiveis, textvariable=self.multiRxSatTeste3, width=30, justify='center')\n self.combo315.place(relx=0, rely=0, x=137, y=125)\n self.combo315.bind('<>', lambda event, endereco='self.multiRxSatTeste3', entrada='self.multiRxSatTeste3IDN': self.verificaIDN(event, endereco, entrada))\n\n self.multiRxSatTeste3IDN = tk.StringVar()\n self.entry315 = ttk.Entry(self.labelf31, textvariable=self.multiRxSatTeste3IDN, width=63, justify='center', state='read')\n self.entry315.place(relx=0, rely=0, x=345, y=125)\n\n self.label = ttk.Label(self.labelf31, text='Analisador de Espectro', background='white').place(relx=0, rely=0, x=12, y=155)\n\n self.analisadorDeEspectroTeste3 = tk.StringVar(value='GPIB0::20::INSTR')\n self.combo316 = ttk.Combobox(self.labelf31, values=dispositivosDisponiveis, textvariable=self.analisadorDeEspectroTeste3, width=30, justify='center')\n self.combo316.place(relx=0, rely=0, x=137, y=155)\n self.combo316.bind('<>', lambda event, endereco='self.analisadorDeEspectroTeste3', entrada='self.analisadorDeEspectroTeste3IDN': self.verificaIDN(event, endereco, entrada))\n\n self.analisadorDeEspectroTeste3IDN = tk.StringVar()\n self.entry316 = ttk.Entry(self.labelf31, textvariable=self.analisadorDeEspectroTeste3IDN, width=63, justify='center', state='read')\n self.entry316.place(relx=0, rely=0, x=345, y=155)\n\n ######################################################################## Frame 2 ########################################################################\n\n self.labelf32= tk.LabelFrame(self.tab3, text='Parametros de Teste', background='white',height=130, width=612)\n self.labelf32.place(relx=0, rely=0, x=5, y=211)\n\n #########################################################################################################################################################\n\n self.labelf322= tk.LabelFrame(self.labelf32, background='white',height=100, width=173)\n self.labelf322.place(relx=0, rely=0, x=5, y=5)\n\n self.frequenciaTeste3 = tk.DoubleVar(value=985.0)\n self.label = ttk.Label(self.labelf322, text='Frequencia', background= 'white').place(relx=0, rely=0, x=14, y=7)\n self.entry321 = ttk.Entry(self.labelf322, textvariable=self.frequenciaTeste3, width=8, justify='center', state='normal')\n self.entry321.place(relx=0, rely=0, x=76, y=7)\n self.label = ttk.Label(self.labelf322, text='MHz', background= 'white').place(relx=0, rely=0, x=131, y=7)\n\n self.symbolRateTeste3 = tk.DoubleVar(value=7.5)\n self.label = ttk.Label(self.labelf322, text='Symbol Rate', background= 'white').place(relx=0, rely=0, x=5, y=37)\n self.entry322 = ttk.Entry(self.labelf322, textvariable=self.symbolRateTeste3, width=8, justify='center', state='normal')\n self.entry322.place(relx=0, rely=0, x=76, y=37)\n self.label = ttk.Label(self.labelf322, text='MS/s', background= 'white').place(relx=0, rely=0, x=131, y=37)\n\n self.rollTeste3 = tk.DoubleVar(value=0.25)\n self.label = ttk.Label(self.labelf322, text='Roll', background= 'white').place(relx=0, rely=0, x=52, y=67)\n self.entry323 = ttk.Entry(self.labelf322, textvariable=self.rollTeste3, width=8, justify='center', state='normal')\n self.entry323.place(relx=0, rely=0, x=76, y=67)\n\n #########################################################################################################################################################\n\n self.labelf323= tk.LabelFrame(self.labelf32, background='white',height=100, width=80)\n self.labelf323.place(relx=0, rely=0, x=183, y=5)\n\n self.modulation1Teste3 = tk.StringVar(value='0')\n self.checkb321 = ttk.Checkbutton(self.labelf323, text= 'QPSK', onvalue='S4', offvalue='0', variable=self.modulation1Teste3, style='white.TCheckbutton', command=lambda: self.desativaModulacao(self.labelf324.winfo_children(), self.modulation1Teste3.get()))\n self.checkb321.place(relx=0, rely=0, x=5, y=3)\n\n self.modulation2Teste3 = tk.StringVar(value='0')\n self.checkb322 = ttk.Checkbutton(self.labelf323, text= '8PSK', onvalue='S8', offvalue='0', variable=self.modulation2Teste3, style='white.TCheckbutton', command=lambda: self.desativaModulacao(self.labelf325.winfo_children(), self.modulation2Teste3.get()))\n self.checkb322.place(relx=0, rely=0, x=5, y=26)\n\n self.modulation3Teste3 = tk.StringVar(value='0')\n self.checkb323 = ttk.Checkbutton(self.labelf323, text= '16APSK', onvalue='A16', offvalue='0', variable=self.modulation3Teste3, style='white.TCheckbutton', command=lambda: self.desativaModulacao(self.labelf326.winfo_children(), self.modulation3Teste3.get()))\n self.checkb323.place(relx=0, rely=0, x=5, y=49)\n\n self.modulation4Teste3 = tk.StringVar(value='0')\n self.checkb324 = ttk.Checkbutton(self.labelf323, text= '32APSK', onvalue='A32', offvalue='0', variable=self.modulation4Teste3, style='white.TCheckbutton', command=lambda: self.desativaModulacao(self.labelf327.winfo_children(), self.modulation4Teste3.get()))\n self.checkb324.place(relx=0, rely=0, x=5, y=72)\n\n #########################################################################################################################################################\n \n self.labelf324= tk.LabelFrame(self.labelf32, background='white', height=108, width=80, text='QPSK')\n self.labelf324.place(relx=0, rely=0, x=268, y=-3)\n\n self.scrollbarQPSKteste3 = ttk.Scrollbar(self.labelf324)\n self.scrollbarQPSKteste3.place(relx=0, rely=0, x=54, y=0, height= 84)\n\n self.mylistQPSKteste3 = tk.Listbox(self.labelf324, yscrollcommand = self.scrollbarQPSKteste3.set, selectmode='multiple', width= 8, height=5, activestyle = 'dotbox', justify='center', exportselection=0)\n self.mylistQPSKteste3.place(relx=0, rely=0, x=3, y=0)\n self.scrollbarQPSKteste3.config(command = self.mylistQPSKteste3.yview)\n\n for line in ['R1_4', 'R1_3', 'R2_5', 'R1_2', 'R3_5', 'R2_3', 'R3_4', 'R4_5', 'R5_6', 'R8_9', 'R9_10']:\n self.mylistQPSKteste3.insert('end', line)\n\n self.mylistQPSKteste3.configure(state='disable')\n \n #########################################################################################################################################################\n\n self.labelf325= tk.LabelFrame(self.labelf32, background='white',height=108, width=80, text='8PSK')\n self.labelf325.place(relx=0, rely=0, x=353, y=-3)\n\n self.scrollbar8PSKteste3 = ttk.Scrollbar(self.labelf325)\n self.scrollbar8PSKteste3.place(relx=0, rely=0, x=54, y=0, height= 84)\n\n self.mylist8PSKteste3 = tk.Listbox(self.labelf325, yscrollcommand = self.scrollbar8PSKteste3.set, selectmode='multiple', width= 8, height=5, activestyle = 'dotbox', justify='center', exportselection=0)\n self.mylist8PSKteste3.place(relx=0, rely=0, x=3, y=0)\n self.scrollbar8PSKteste3.config(command = self.mylist8PSKteste3.yview)\n \n for line in ['R3_5', 'R2_3', 'R3_4', 'R5_6', 'R8_9', 'R9_10']:\n self.mylist8PSKteste3.insert('end', line)\n\n self.mylist8PSKteste3.configure(state='disable')\n\n #########################################################################################################################################################\n\n self.labelf326= tk.LabelFrame(self.labelf32, background='white',height=108, width=80, text='16APSK')\n self.labelf326.place(relx=0, rely=0, x=438, y=-3)\n\n self.scrollbar16APSKteste3 = ttk.Scrollbar(self.labelf326)\n self.scrollbar16APSKteste3.place(relx=0, rely=0, x=54, y=0, height= 84)\n\n self.mylist16APSKteste3 = tk.Listbox(self.labelf326, yscrollcommand = self.scrollbar16APSKteste3.set, selectmode='multiple', width= 8, height=5, activestyle = 'dotbox', justify='center', exportselection=0)\n self.mylist16APSKteste3.place(relx=0, rely=0, x=3, y=0)\n self.scrollbar16APSKteste3.config(command = self.mylist16APSKteste3.yview)\n \n for line in ['R2_3', 'R3_4', 'R4_5', 'R5_6', 'R8_9', 'R9_10']:\n self.mylist16APSKteste3.insert('end', line)\n\n self.mylist16APSKteste3.configure(state='disable')\n\n #########################################################################################################################################################\n\n self.labelf327= tk.LabelFrame(self.labelf32, background='white',height=108, width=80, text='32APSK')\n self.labelf327.place(relx=0, rely=0, x=523, y=-3)\n\n self.scrollbar32APSKteste3 = ttk.Scrollbar(self.labelf327)\n self.scrollbar32APSKteste3.place(relx=0, rely=0, x=54, y=0, height= 84)\n\n self.mylist32APSKteste3 = tk.Listbox(self.labelf327, yscrollcommand = self.scrollbar32APSKteste3.set, selectmode='multiple', width= 8, height=5, activestyle = 'dotbox', justify='center', exportselection=0)\n self.mylist32APSKteste3.place(relx=0, rely=0, x=3, y=0)\n self.scrollbar32APSKteste3.config(command = self.mylist32APSKteste3.yview)\n \n for line in ['R3_4', 'R4_5', 'R5_6', 'R8_9', 'R9_10']:\n self.mylist32APSKteste3.insert('end', line)\n\n self.mylist32APSKteste3.configure(state='disable')\n\n ####################################################################### Progresso #######################################################################\n \n self.labelProgressoTeste3= tk.LabelFrame(self.tab3, background='white',height=40, width=612)\n self.labelProgressoTeste3.place(relx=0, rely=0, x=5, y=348)\n\n self.entryBar1VarTeste3 = tk.StringVar()\n self.entryBar1Teste3 = ttk.Entry(self.labelProgressoTeste3, textvariable=self.entryBar1VarTeste3, background='white', width=30, justify='center', state='readonly')\n self.entryBar1Teste3.place(relx=0, rely=0, x=5, y=7)\n\n self.entryBar2VarTeste3 = tk.StringVar()\n self.entryBar2Teste3 = ttk.Entry(self.labelProgressoTeste3, textvariable=self.entryBar2VarTeste3, background='white', width=10, justify='center', state='readonly')\n self.entryBar2Teste3.place(relx=0, rely=0, x=218, y=7)\n\n self.progresso1Teste3 = ttk.Progressbar(self.labelProgressoTeste3, orient='horizontal',length=120, value=0, maximum=4, mode='determinate')\n self.progresso1Teste3.place(relx=0, rely=0, x=288, y=7, height=21)\n\n self.entryBar3VarTeste3 = tk.StringVar()\n self.entryBar3Teste3 = ttk.Entry(self.labelProgressoTeste3, textvariable=self.entryBar3VarTeste3, background='white', width=10, justify='center', state='readonly')\n self.entryBar3Teste3.place(relx=0, rely=0, x=412, y=7)\n\n self.progresso2Teste3 = ttk.Progressbar(self.labelProgressoTeste3, orient='horizontal',length=120, value=0, maximum=11, mode='determinate')\n self.progresso2Teste3.place(relx=0, rely=0, x=482, y=7, height=21)\n\n self.buttonStartTeste3 = ttk.Button(self.tab3, text='Start', width= 18, command=lambda: self.iniciar_teste3())\n self.buttonStartTeste3.place(relx=0, rely=0, x=623, y=218, height=123)\n\n ########################################################################################################################################################\n\n self.queueTeste1 = mp.Queue()\n self.queueTeste2 = mp.Queue()\n self.queueTeste3 = mp.Queue()\n # self.queueTeste4 = mp.Queue()\n self.process1 = None\n self.process2 = None\n self.process3 = None\n\n\n def resource_path(self, relative_path):\n \"\"\" Get absolute path to resource, works for dev and for PyInstaller \"\"\"\n try:\n base_path = sys._MEIPASS\n except Exception:\n base_path = os.path.abspath(\".\")\n\n return os.path.join(base_path, relative_path)\n\n def on_tab_selected(self, event):\n global tab_text\n selected_tab = event.widget.select()\n tab_text = event.widget.tab(selected_tab, \"text\")\n if tab_text == \"Multipercurso ISDB-TB\":\n self.geometry(\"762x400\")\n\n if tab_text == \"DVB-S2: Faixa de frequência\":\n self.geometry('762x363')\n\n if tab_text == \"DVB-S2: Máximo C/N\":\n self.geometry('762x422')\n\n\n def verificaIDN(self, event, endereco, entrada):\n print('ok')\n # try:\n # if endereco == 'ARSL4::INSTR':\n # return\n\n # dev = self.rm.open_resource(eval(endereco).get())\n # resposta = dev.query('*IDN?')\n # if resposta[-1] == '\\n':\n # resposta = resposta[:-1]\n # eval(entrada).set(resposta)\n # dev.close()\n \n # except:\n # pass\n # # dev = self.rm.open_resource(eval(endereco).get(), read_termination = '\\r', write_termination = '\\r', baud_rate=115200)\n # # resposta = dev.query('02O4F')\n # # if resposta[-1] == '\\n':\n # # resposta = resposta[:-1]\n # # eval(entrada).set(resposta)\n # # dev.close()\n\n def serial_ports(self):\n\n ports = ['COM%s' % (i + 1) for i in range(256)]\n\n result = []\n\n for port in ports:\n try:\n s = serial.Serial(port)\n s.close()\n result.append(port)\n except (OSError, serial.SerialException):\n pass\n return result\n\n def desativaModulacao(self, childList, onOff):\n estado = str()\n\n if onOff == '0':\n estado= 'disable'\n else:\n estado = 'normal'\n\n for child in childList:\n\n try:\n child.configure(state = estado)\n except:\n continue\n\n def adicionaDelay(self, event):\n valor = self.enviaComandoEIDEN(None,'self.delayFadingSimulator',-1000.0, 1000.0, 5, 9, False, True)\n if valor not in self.valoresDelay:\n self.valoresDelay.append(valor)\n self.valoresDelay.sort()\n self.combo14['values'] = self.valoresDelay\n\n def enviaComandoEIDEN(self, event, variavel, valorMin, valorMax, indexVirgula, numDeCaracteres, sinal, retornar):\n \n levelSaida = str(eval(variavel).get())\n\n if len(levelSaida) > numDeCaracteres:\n levelSaida = levelSaida[:-(len(levelSaida)-numDeCaracteres)]\n \n if type(eval(variavel).get())(levelSaida) > valorMax:\n levelSaida = str(type(eval(variavel).get())(valorMax))\n\n if type(eval(variavel).get())(levelSaida) < valorMin:\n levelSaida = str(type(eval(variavel).get())(valorMin))\n\n if type(eval(variavel).get()) is float:\n\n if (levelSaida[0] == '-'):\n while levelSaida.find('.') < indexVirgula:\n levelSaida = levelSaida[0]+'0'+levelSaida[1:]\n else:\n if sinal is True:\n levelSaida = '+' + levelSaida\n while levelSaida.find('.') < indexVirgula:\n levelSaida = levelSaida[0]+'0'+levelSaida\n else:\n while levelSaida.find('.') < indexVirgula:\n levelSaida = '0'+levelSaida\n \n\n while (len(levelSaida) < numDeCaracteres):\n levelSaida = levelSaida+'0'\n\n else:\n if (levelSaida[0] == '-'):\n while len(levelSaida) < numDeCaracteres:\n levelSaida = levelSaida[0]+'0'+levelSaida[1:]\n else:\n if sinal is True:\n levelSaida = '+' + levelSaida\n while len(levelSaida) < numDeCaracteres:\n levelSaida = '0'+levelSaida\n\n eval(variavel).set(levelSaida)\n try:\n eval(variavel+'STR').set(levelSaida)\n except:\n pass\n\n if retornar == True:\n return levelSaida\n else:\n pass\n\n\n def iniciar_teste1(self):\n self.progressoTeste1.configure(maximum=len(self.valoresDelay)+2)\n valores = [[self.dispositivoModuladorTeste1.get(), self.dispositivoAtenuadorTeste1.get(), self.dispositivoFadingSimulatorTeste1.get(), self.dispositivoAnalisadorDeEspectroTeste1.get()], self.moduladorEIDENfrequenciaSTR.get(), self.moduladorEIDENlevelSTR.get(), self.moduladorEIDENfrequenciaSTR.get(), self.valoresDelay]\n self.process1 = mp.Process(target=teste1, args=(self.queueTeste1, valores, ))\n self.process1.start()\n self.tab_parent.add(self.tab2, state='disable')\n self.tab_parent.add(self.tab3, state='disable')\n self.periodic_call_teste1()\n\n def periodic_call_teste1(self):\n\n self.check_queue_teste1()\n\n if self.process1.exitcode is None:\n self.after(100, self.periodic_call_teste1)\n\n else:\n self.process1.join()\n self.entryBar1VarTeste1.set('Pronto')\n self.tab_parent.add(self.tab2, state='normal')\n self.tab_parent.add(self.tab3, state='normal')\n self.progressoTeste1.configure(value=0)\n\n def check_queue_teste1(self):\n\n while self.queueTeste1.qsize():\n try:\n respostaWork = self.queueTeste1.get(0)\n print(respostaWork)\n self.entryBar1VarTeste1.set(respostaWork[0])\n self.entryBar2VarTeste1.set(respostaWork[1])\n self.entryBar3VarTeste1.set(respostaWork[2])\n \n if respostaWork[3] == True:\n self.progressoTeste1.configure(value=self.progressoTeste1['value'] + 1)\n else:\n pass \n\n except queue.Empty:\n pass\n\n #######################################################################################################################################################\n\n def iniciar_teste2(self):\n\n if len(self.moduladorSfuTeste2.get()) == 0 or len(self.atenuador1Teste2.get()) == 0 or len(self.multiRxSatTeste2.get()) == 0 or len(self.analisadorDeEspectroTeste2.get()) == 0:\n tk.messagebox.showinfo('Aviso',\"Selecione todos os dispositivos\")\n return\n\n try:\n self.frequenciaTeste2.get()\n except:\n tk.messagebox.showinfo('Aviso',\"Erro no valor da frequencia\")\n return\n\n try:\n self.symbolRateTeste2.get()\n except:\n tk.messagebox.showinfo('Aviso',\"Erro no valor de symbol rate\")\n return\n\n try:\n self.rollTeste2.get()\n except:\n tk.messagebox.showinfo('Aviso',\"Erro no valor do roll\")\n return\n \n valores = [[self.moduladorSfuTeste2.get(), self.atenuador1Teste2.get(), self.multiRxSatTeste2.get(), self.analisadorDeEspectroTeste2.get()], self.frequenciaTeste2.get(), self.symbolRateTeste2.get()]\n \n if self.modulation1Teste2.get() == '0' and self.modulation2Teste2.get() == '0' and self.modulation3Teste2.get() == '0' and self.modulation4Teste2.get() == '0':\n tk.messagebox.showinfo('Aviso',\"Selecione a modulação\")\n return\n\n saidaValores = [self.modulation1Teste2.get(), self.modulation2Teste2.get(), self.modulation3Teste2.get(), self.modulation4Teste2.get()]\n\n while True:\n try:\n saidaValores.remove('0')\n except:\n break\n\n self.progresso1Teste2.configure(maximum=len(saidaValores))\n\n valores.append(saidaValores)\n\n saidaValores = list()\n for x in ['self.mylistQPSKteste2', 'self.mylist8PSKteste2', 'self.mylist16APSKteste2', 'self.mylist32APSKteste2']:\n preSaida = list()\n temp = eval(x).curselection()\n\n if len(temp) != 0:\n for y in temp:\n preSaida.append(eval(x).get(y))\n else:\n pass\n saidaValores.append(preSaida)\n\n if (len(saidaValores[0]) == 0 and self.modulation1Teste2.get() != '0') or (len(saidaValores[1]) == 0 and self.modulation2Teste2.get() != '0') or (len(saidaValores[2]) == 0 and self.modulation3Teste2.get() != '0') or (len(saidaValores[3]) == 0 and self.modulation4Teste2.get() != '0'):\n tk.messagebox.showinfo('Aviso',\"Selecione o Code Rate\")\n return\n\n\n valores.append(saidaValores)\n valores.append(self.rollTeste2.get())\n\n self.process2 = mp.Process(target=teste2, args=(self.queueTeste2, valores, ))\n self.process2.start()\n self.tab_parent.add(self.tab1, state='disable')\n self.tab_parent.add(self.tab3, state='disable')\n self.combo211.configure(state='disable')\n self.combo212.configure(state='disable')\n self.combo215.configure(state='disable')\n self.combo216.configure(state='disable')\n\n self.entry221.configure(state='disable')\n self.entry222.configure(state='disable')\n self.entry223.configure(state='disable')\n\n self.checkb221.configure(state='disable')\n self.checkb222.configure(state='disable')\n self.checkb223.configure(state='disable')\n self.checkb224.configure(state='disable')\n self.mylistQPSKteste2.configure(state='disable')\n self.mylist8PSKteste2.configure(state='disable')\n self.mylist16APSKteste2.configure(state='disable')\n self.mylist32APSKteste2.configure(state='disable')\n\n self.buttonStartTeste2.configure(state='disable')\n \n self.periodic_call_teste2()\n\n def periodic_call_teste2(self):\n\n self.check_queue_teste2()\n\n if self.process2.exitcode is None:\n self.after(100, self.periodic_call_teste2)\n\n else:\n self.process2.join()\n self.tab_parent.add(self.tab1, state='normal')\n self.tab_parent.add(self.tab3, state='normal')\n self.combo211.configure(state='normal')\n self.combo212.configure(state='normal')\n self.combo215.configure(state='normal')\n self.combo216.configure(state='normal')\n\n self.entry221.configure(state='normal')\n self.entry222.configure(state='normal')\n self.entry223.configure(state='normal')\n\n self.checkb221.configure(state='normal')\n self.checkb222.configure(state='normal')\n self.checkb223.configure(state='normal')\n self.checkb224.configure(state='normal')\n\n if self.modulation1Teste2.get() == 'S4':\n self.mylistQPSKteste2.configure(state='normal')\n\n if self.modulation2Teste2.get() == 'S8':\n self.mylist8PSKteste2.configure(state='normal')\n\n if self.modulation3Teste2.get() == 'A16':\n self.mylist16APSKteste2.configure(state='normal')\n\n if self.modulation4Teste2.get() == 'A32':\n self.mylist32APSKteste2.configure(state='normal')\n \n self.buttonStartTeste2.configure(state='normal')\n\n self.progresso1Teste2.configure(value=0)\n self.progresso2Teste2.configure(value=0)\n\n def check_queue_teste2(self):\n\n while self.queueTeste2.qsize():\n try:\n respostaWork = self.queueTeste2.get(0)\n print(respostaWork)\n self.entryBar1VarTeste2.set(respostaWork[0])\n self.entryBar2VarTeste2.set(respostaWork[1])\n self.entryBar3VarTeste2.set(respostaWork[2])\n \n if respostaWork[3] == True:\n self.progresso1Teste2.configure(value=self.progresso1Teste2['value'] + 1)\n elif respostaWork[3] == False:\n pass\n else:\n self.progresso1Teste2.configure(value=int(respostaWork[3]))\n \n if respostaWork[4] == 'S4':\n self.progresso2Teste2.configure(value=0)\n self.progresso2Teste2.configure(maximum=len(self.mylistQPSKteste2.curselection()))\n elif respostaWork[4] == 'S8':\n self.progresso2Teste2.configure(value=0)\n self.progresso2Teste2.configure(maximum=len(self.mylist8PSKteste2.curselection()))\n elif respostaWork[4] == 'A16':\n self.progresso2Teste2.configure(value=0)\n self.progresso2Teste2.configure(maximum=len(self.mylist16APSKteste2.curselection()))\n elif respostaWork[4] == 'A32':\n self.progresso2Teste2.configure(value=0)\n self.progresso2Teste2.configure(maximum=len(self.mylist32APSKteste2.curselection()))\n elif respostaWork[4] == True:\n self.progresso2Teste2.configure(value=self.progresso2Teste2['value'] + 1)\n else:\n pass\n \n except queue.Empty:\n pass\n\n #######################################################################################################################################################\n\n def iniciar_teste3(self):\n\n if len(self.moduladorSfuTeste3.get()) == 0 or len(self.atenuador1Teste3.get()) == 0 or len(self.vectorSignalGeneratorSmuTeste3.get()) == 0 or len(self.atenuador2Teste3.get()) == 0 or len(self.multiRxSatTeste3.get()) == 0 or len(self.analisadorDeEspectroTeste3.get()) == 0:\n tk.messagebox.showinfo('Aviso',\"Selecione todos os dispositivos\")\n return\n\n try:\n self.frequenciaTeste3.get()\n except:\n tk.messagebox.showinfo('Aviso',\"Erro no valor da frequencia\")\n return\n\n try:\n self.symbolRateTeste3.get()\n except:\n tk.messagebox.showinfo('Aviso',\"Erro no valor de symbol rate\")\n return\n\n try:\n self.rollTeste3.get()\n except:\n tk.messagebox.showinfo('Aviso',\"Erro no valor do roll\")\n return\n \n valores = [[self.moduladorSfuTeste3.get(), self.atenuador1Teste3.get(), self.vectorSignalGeneratorSmuTeste3.get(), self.atenuador2Teste3.get(), self.multiRxSatTeste3.get(), self.analisadorDeEspectroTeste3.get()], self.frequenciaTeste3.get(), self.symbolRateTeste3.get()]\n \n if self.modulation1Teste3.get() == '0' and self.modulation2Teste3.get() == '0' and self.modulation3Teste3.get() == '0' and self.modulation4Teste3.get() == '0':\n tk.messagebox.showinfo('Aviso',\"Selecione a modulação\")\n return\n\n saidaValores = [self.modulation1Teste3.get(), self.modulation2Teste3.get(), self.modulation3Teste3.get(), self.modulation4Teste3.get()]\n\n while True:\n try:\n saidaValores.remove('0')\n except:\n break\n\n self.progresso1Teste3.configure(maximum=len(saidaValores))\n\n valores.append(saidaValores)\n\n saidaValores = list()\n for x in ['self.mylistQPSKteste3', 'self.mylist8PSKteste3', 'self.mylist16APSKteste3', 'self.mylist32APSKteste3']:\n preSaida = list()\n temp = eval(x).curselection()\n\n if len(temp) != 0:\n for y in temp:\n preSaida.append(eval(x).get(y))\n else:\n pass\n saidaValores.append(preSaida)\n\n if (len(saidaValores[0]) == 0 and self.modulation1Teste3.get() != '0') or (len(saidaValores[1]) == 0 and self.modulation2Teste3.get() != '0') or (len(saidaValores[2]) == 0 and self.modulation3Teste3.get() != '0') or (len(saidaValores[3]) == 0 and self.modulation4Teste3.get() != '0'):\n tk.messagebox.showinfo('Aviso',\"Selecione o Code Rate\")\n return\n\n\n valores.append(saidaValores)\n valores.append(self.rollTeste3.get())\n\n print(valores)\n\n self.process3 = mp.Process(target=teste3, args=(self.queueTeste3, valores, ))\n self.process3.start()\n self.tab_parent.add(self.tab1, state='disable')\n self.tab_parent.add(self.tab2, state='disable')\n self.combo311.configure(state='disable')\n self.combo312.configure(state='disable')\n self.combo313.configure(state='disable')\n self.combo314.configure(state='disable')\n self.combo315.configure(state='disable')\n self.combo316.configure(state='disable')\n\n self.entry321.configure(state='disable')\n self.entry322.configure(state='disable')\n self.entry323.configure(state='disable')\n\n self.checkb321.configure(state='disable')\n self.checkb322.configure(state='disable')\n self.checkb323.configure(state='disable')\n self.checkb324.configure(state='disable')\n self.mylistQPSKteste3.configure(state='disable')\n self.mylist8PSKteste3.configure(state='disable')\n self.mylist16APSKteste3.configure(state='disable')\n self.mylist32APSKteste3.configure(state='disable')\n\n self.buttonStartTeste3.configure(state='disable')\n \n self.periodic_call_teste3()\n\n def periodic_call_teste3(self):\n\n self.check_queue_teste3()\n\n if self.process3.exitcode is None:\n self.after(100, self.periodic_call_teste3)\n\n else:\n self.process3.join()\n self.tab_parent.add(self.tab1, state='normal')\n self.tab_parent.add(self.tab2, state='normal')\n self.combo311.configure(state='normal')\n self.combo312.configure(state='normal')\n self.combo313.configure(state='normal')\n self.combo314.configure(state='normal')\n self.combo315.configure(state='normal')\n self.combo316.configure(state='normal')\n\n self.entry321.configure(state='normal')\n self.entry322.configure(state='normal')\n self.entry323.configure(state='normal')\n\n self.checkb321.configure(state='normal')\n self.checkb322.configure(state='normal')\n self.checkb323.configure(state='normal')\n self.checkb324.configure(state='normal')\n\n if self.modulation1Teste3.get() == 'S4':\n self.mylistQPSKteste3.configure(state='normal')\n\n if self.modulation2Teste3.get() == 'S8':\n self.mylist8PSKteste3.configure(state='normal')\n\n if self.modulation3Teste3.get() == 'A16':\n self.mylist16APSKteste3.configure(state='normal')\n\n if self.modulation4Teste3.get() == 'A32':\n self.mylist32APSKteste3.configure(state='normal')\n \n self.buttonStartTeste3.configure(state='normal')\n\n self.progresso1Teste3.configure(value=0)\n self.progresso2Teste3.configure(value=0)\n\n def check_queue_teste3(self):\n\n while self.queueTeste3.qsize():\n try:\n respostaWork = self.queueTeste3.get(0)\n print(respostaWork)\n self.entryBar1VarTeste3.set(respostaWork[0])\n self.entryBar2VarTeste3.set(respostaWork[1])\n self.entryBar3VarTeste3.set(respostaWork[2])\n \n if respostaWork[3] == True:\n self.progresso1Teste3.configure(value=self.progresso1Teste3['value'] + 1)\n elif respostaWork[3] == False:\n pass\n else:\n self.progresso1Teste3.configure(value=int(respostaWork[3]))\n \n if respostaWork[4] == 'S4':\n self.progresso2Teste3.configure(value=0)\n self.progresso2Teste3.configure(maximum=len(self.mylistQPSKteste3.curselection()))\n elif respostaWork[4] == 'S8':\n self.progresso2Teste3.configure(value=0)\n self.progresso2Teste3.configure(maximum=len(self.mylist8PSKteste3.curselection()))\n elif respostaWork[4] == 'A16':\n self.progresso2Teste3.configure(value=0)\n self.progresso2Teste3.configure(maximum=len(self.mylist16APSKteste3.curselection()))\n elif respostaWork[4] == 'A32':\n self.progresso2Teste3.configure(value=0)\n self.progresso2Teste3.configure(maximum=len(self.mylist32APSKteste3.curselection()))\n elif respostaWork[4] == True:\n self.progresso2Teste3.configure(value=self.progresso2Teste3['value'] + 1)\n else:\n pass\n \n\n except queue.Empty:\n pass\n\ndef devolveChecksumMultirxsat(lista):\n checkum = '0x00'\n for posicao in lista:\n checkum = hex(int(checkum, 16) + ord(posicao))\n\n binario = bin(int(checkum, 16))[2:]\n\n while len(binario) % 4 != 0:\n binario = '0'+binario\n\n binario = '0b'+binario.replace('0','h').replace('1','0').replace('h','1')\n\n checkum = hex(int(binario, 2)+1).upper()\n\n return checkum[-2:].zfill(2)\n\ndef teste1(queue_resposta, valores):\n\n rm = pyvisa.ResourceManager()\n\n # moduladorTeste1 = rm.open_resource(valores[0][0]) # acrescecntar o delay\n atenuadorTeste1 = rm.open_resource(valores[0][1]) # acrescecntar o delay\n # fadingSimulatorTeste1 = rm.open_resource(valores[0][2]) # acrescecntar o delay\n analisadorDeEspectroTeste1 = rm.open_resource(valores[0][3]) # acrescecntar o delay\n # multsatrx\n\n queue_resposta.put(['Iniciando teste', '', '', False])\n \n #setar configurações do modulador, fading e atenuador\n print('FREQ:CENT '+valores[1]+' MHz')\n analisadorDeEspectroTeste1.write('FREQ:CENT '+ valores[1]+' MHz')\n\n # fadingSimulatorTeste1.write('IFFRQ 37.15')\n # fadingSimulatorTeste1.write('IFOUT 1')\n # fadingSimulatorTeste1.write('IFAGC 1')\n # fadingSimulatorTeste1.write('RFFRQ '+ valores[1])\n\n # fadingSimulatorTeste1.write('PTNUM 1')\n # fadingSimulatorTeste1.write('PTMOD 1')\n # fadingSimulatorTeste1.write('PTDLY 00000.000')\n # fadingSimulatorTeste1.write('PTPHS 0000')\n # fadingSimulatorTeste1.write('PTATT 00.0')\n\n # atenuadorTeste1.write('*RST')\n # time.sleep(1.0)\n # atenuadorTeste1.write('ATT1:ATT 139.9')\n \n time.sleep(1.5)\n\n queue_resposta.put(['Calibrando sinal', '', '', False])\n \n # verificar o inicio\n valoresAtenuacao = 139.9\n \n while True:\n if (round(valoresAtenuacao, 1)) < 0 or (round(valoresAtenuacao, 1)) > 139.9:\n queue_resposta.put(['ERRO', '', '', False])\n return\n\n # atenuadorTeste1.write('ATT1:ATT '+str(valoresAtenuacao-degrauAtenuacao)) \n atenuadorTeste1.write('A '+str(round(valoresAtenuacao, 1)))\n\n resposta = 0.0\n contagem = 0.0\n tempoAtual = time.time()\n\n while(time.time() - tempoAtual < 15):\n time.sleep(0.2)\n resposta = resposta + float(analisadorDeEspectroTeste1.query('CALC:MARK:FUNC:POW:RES? CPOW'))\n contagem += 1.0\n resposta = resposta/contagem\n\n if float(resposta) <-45:\n valoresAtenuacao -= 5.0\n\n elif float(resposta) > -35:\n valoresAtenuacao += 5.0\n\n elif float(resposta) <= -35 and float(resposta) > -39:\n valoresAtenuacao += 1.0\n\n elif float(resposta) >= -45 and float(resposta) < -41:\n valoresAtenuacao -= 1.0\n\n elif float(resposta) >= -41 and float(resposta) <= -40.05:\n valoresAtenuacao -= 0.1\n\n elif float(resposta) >= -39.95 and float(resposta) <= -39:\n valoresAtenuacao += 0.1\n\n elif float(resposta) > -40.05 and float(resposta) < -39.95:\n break\n \n else:\n pass\n\n \n # time.sleep(1.5)\n\n queue_resposta.put(['Sinal Calibrado', '', '', True])\n # time.sleep(1.5)\n\n # fadingSimulatorTeste1.write('PTNUM 2')\n # fadingSimulatorTeste1.write('PTMOD 1')\n # fadingSimulatorTeste1.write('PTPHS 0000')\n # fadingSimulatorTeste1.write('PTATT 00.0')\n\n # for valoresDelay in valores[4]:\n # fadingSimulatorTeste1.write('PTDLY '+str(valoresDelay))\n\n # for atenuacao in range(0,500,1):\n\n # fadingSimulatorTeste1.write('PTATT ' + str(atenuacao/10.0))\n # queue_resposta.put(['Teste em andamento', str(valoresDelay),str(atenuacao/10.0), False])\n \n # time.sleep(1.5)\n # valorBER = 0\n # numeroDeMedidas = 0\n # tempoAtual = time.time()\n\n # while (time.time()-tempoAtual) < 60:\n # # medir valor do BER e somar\n # # PER 02V01A\n # # BER 02V01B\n # # if valor de BER/numero de medidas >= 1e-4 adicionar numero de PER\n # # adicionar valores de PER, BER, Atenuação e tempo em um [[valres teste1], [valores teste2]] \n # #break\n\n # queue_resposta.put(['Teste em andamento', '', '', True])\n\n # queue_resposta.put(['Criando arquivo csv', '', '', True])\n # time.sleep(1.5)\n # # criar arquivo csv com os valores encontrados\n\ndef teste2(queue_resposta, valores):\n\n tempoDecorrido = time.time()\n\n rm = pyvisa.ResourceManager()\n\n moduladorSFU = rm.open_resource(valores[0][0], read_termination = '\\n', query_delay = 0.2)\n atenuador1 = rm.open_resource(valores[0][1], read_termination = '\\n')\n multiRxSat = rm.open_resource(valores[0][2], read_termination = '\\r', write_termination = '\\r', baud_rate=115200)\n analisadorDeEspectro = rm.open_resource(valores[0][3], read_termination = '\\n', query_delay = 0.2)\n\n queue_resposta.put(['Iniciando teste','','', False, False])\n\n ###################################################### SFU ######################################################\n\n comandosModuladorSFU = ['OUTP:STAT OFF', ':MOD:STAT ON', ':DM:SOUR DTV', ':DM:FORM DVS2', 'DVB2:SOUR TSPL', ':DM:POL NORM', ':IQC:DVBS2:SYMB '+str(valores[2])+'e6', ':IQC:DVBS2:CONS S4', ':IQC:DVBS2:PIL ON', ':IQC:DVBS2:ROLL 0.25', ':IQC:DVBS2:RATE R2_5', ':POW 0 dBm', 'FREQ '+str(valores[1])+' MHz']\n for comando in comandosModuladorSFU:\n moduladorSFU.write(comando)\n time.sleep(1.0)\n\n queue_resposta.put(['Modulador SFU - OK', '','', False, False])\n\n #################################################################################################################\n \n ################################################## ATENUADORES ##################################################\n\n comandoAtenuador1 = str()\n\n if atenuador1.query('*IDN?') == 'ROHDE & SCHWARZ ,RSP,0,1.5':\n comandoAtenuador1 = 'A'\n else:\n comandoAtenuador1 = 'ATT1:ATT'\n\n atenuador1.write(comandoAtenuador1 + '139.9')\n\n queue_resposta.put(['Atenuador - OK', '','', False, False])\n #################################################################################################################\n\n ############################################# ANALISADOR DE ESPECTRO ############################################\n\n comandosAnalisadorDeEspectro = ['FREQ:CENT '+str(valores[1])+' MHz', 'DISP:TRAC:Y:RLEV -20', 'SWE:TIME 1', 'BAND:VID 3000', 'BAND 300000', \n 'INP:ATT 0', 'SWE:MODE AUTO', 'SENS:POW:ACH:BAND '+str(valores[2])+' MHz', 'FREQ:SPAN 20 MHz']\n for comando in comandosAnalisadorDeEspectro:\n analisadorDeEspectro.write(comando)\n time.sleep(1.0)\n\n queue_resposta.put(['Analisador de Espectro - OK', '','', False, False])\n #################################################################################################################\n\n ################################################### MULTISATRX ##################################################\n\n FrequenciaSymbolRate = '02U0A'+hex(int(valores[1]*1000))[2:].zfill(6).upper()+hex(int(valores[2]*1000))[2:].zfill(4).upper() + devolveChecksumMultirxsat('02U0A'+hex(int(valores[1]*1000))[2:].zfill(6).upper()+hex(int(valores[2]*1000))[2:].zfill(4).upper())\n\n print(FrequenciaSymbolRate)\n\n while True:\n try:\n multiRxSat.write('02O4F')\n time.sleep(10.0)\n print(multiRxSat.read())\n\n multiRxSat.write(FrequenciaSymbolRate)\n time.sleep(10.0)\n print(multiRxSat.read())\n break\n except:\n print('Erro na Placa')\n time.sleep(10.0)\n pass\n\n queue_resposta.put(['MultiSatRx - OK', '','', False, False])\n #################################################################################################################\n\n ##################################################### FUNÇÕES ###################################################\n\n def desativarSetup():\n atenuador1.write(comandoAtenuador1+' 139.9')\n\n moduladorSFU.write('OUTP OFF')\n\n moduladorSFU.close()\n atenuador1.close()\n multiRxSat.close()\n analisadorDeEspectro.close()\n\n time.sleep(5.0)\n\n #################################################################################################################\n \n moduladorSFU.write('OUTP:STAT ON')\n\n pil = ['ON', 'OFF']\n\n respostasExcel = list()\n respostasExcel.append(valores[1])\n respostasExcel.append(valores[2])\n respostasExcel.append(valores[5])\n\n constellation = list()\n codeRates = list()\n\n pilots = list()\n \n maxBitrate = list()\n result = list()\n\n for iten1 in valores[3]:\n queue_resposta.put(['Teste em Andamento', iten1, '', True, iten1])\n moduladorSFU.write(':IQC:DVBS2:CONS ' + iten1)\n moduladorSFU.write(':IQC:DVBS2:PIL ON')\n \n # if iten1 == 'S8':\n # analisadorDeEspectro.write('FREQ:SPAN 20 MHz')\n\n codeRate = None\n\n if iten1 == 'S4':\n codeRate = valores[4][0]\n elif iten1 == 'S8':\n codeRate = valores[4][1]\n elif iten1 == 'A16':\n codeRate = valores[4][2]\n elif iten1 == 'A32':\n codeRate = valores[4][3]\n else:\n pass\n\n for iten2 in codeRate:\n\n queue_resposta.put(['Teste em Andamento', iten1, iten2[1:].replace('_','/') , False, True])\n\n moduladorSFU.write(':IQC:DVBS2:RATE ' + iten2)\n\n atenuador1.write(comandoAtenuador1+' 139.9')\n\n valoresAtenuacao = 70.0\n\n print('Sinal')\n\n controleDoTeste = 0\n\n while True:\n valoresAtenuacao = round(valoresAtenuacao, 1)\n if (valoresAtenuacao) < 0 or (valoresAtenuacao) > 139.9:\n\n desativarSetup()\n queue_resposta.put(['ERRO', '', '', 0, 0])\n return\n\n atenuador1.write(comandoAtenuador1+' '+str(valoresAtenuacao))\n\n resposta = 0.0\n contagem = 0.0\n tempoAtual = time.time()\n\n while(time.time() - tempoAtual < 15):\n time.sleep(0.2)\n resposta = resposta + float(analisadorDeEspectro.query('CALC:MARK:FUNC:POW:RES? CPOW'))\n contagem += 1.0\n resposta = resposta/contagem\n\n print(resposta)\n\n if float(resposta) <-55:\n valoresAtenuacao -= 10.0\n\n elif float(resposta) <-45:\n valoresAtenuacao -= 5.0\n\n elif float(resposta) > -35:\n valoresAtenuacao += 5.0\n\n elif float(resposta) <= -35 and float(resposta) > -39:\n valoresAtenuacao += 1.0\n\n elif float(resposta) >= -45 and float(resposta) < -41:\n valoresAtenuacao -= 1.0\n\n elif float(resposta) >= -41 and float(resposta) <= -40.05:\n controleDoTeste += 1\n if controleDoTeste >= 10:\n break\n else:\n valoresAtenuacao -= 0.1\n\n elif float(resposta) >= -39.95 and float(resposta) <= -39:\n valoresAtenuacao += 0.1\n\n elif float(resposta) > -40.05 and float(resposta) < -39.95:\n break\n \n else:\n pass\n\n\n for iten3 in pil:\n moduladorSFU.write(':IQC:DVBS2:PIL ' + iten3)\n time.sleep(5.0)\n\n controle = 0\n\n while True:\n try:\n\n multiRxSat.write('02L52')\n\n time.sleep(10.0)\n respSatelite = multiRxSat.read()\n print(respSatelite)\n\n if respSatelite == '04L02018D':\n print('Lock OK')\n\n controle2 = 0\n while True:\n try:\n multiRxSat.write('02V01BA5')\n time.sleep(0.5)\n resposta = multiRxSat.read()\n print(resposta)\n except:\n continue\n\n if resposta == '04V01BA3':\n controle2 += 1\n\n if controle2 == 10:\n constellation.append(iten1)\n codeRates.append(iten2)\n pilots.append(iten3)\n result.append('NOK')\n maxBitrate.append('')\n break\n\n continue\n\n else:\n constellation.append(iten1)\n codeRates.append(iten2)\n pilots.append(iten3)\n result.append('OK')\n maxBitrate.append(moduladorSFU.query('READ:DVBS2:USEF:MAX?'))\n break\n\n break\n else:\n pass\n\n controle += 1\n\n if controle == 10:\n constellation.append(iten1)\n codeRates.append(iten2)\n pilots.append(iten3)\n result.append('NOK')\n maxBitrate.append('')\n break\n else:\n pass\n except:\n time.sleep(10.0)\n pass\n\n\n respostasExcel.append([constellation, codeRates, pilots, valores[2], maxBitrate, result])\n\n print(respostasExcel)\n \n queue_resposta.put(['Gerando Excel', '', '', False, False])\n \n excel.excelTeste2(respostasExcel)\n\n time.sleep(5.0)\n\n queue_resposta.put(['Finalizando', '', '', False, False])\n\n desativarSetup()\n\n queue_resposta.put(['Tempo: ' + str(datetime.timedelta(seconds=time.time()-tempoDecorrido)).rsplit('.', 1)[0].replace('day','dia'), '', '', False, False])\n\n\ndef teste3(queue_resposta, valores):\n\n tempoDecorrido = time.time()\n\n rm = pyvisa.ResourceManager()\n\n moduladorSFU = rm.open_resource(valores[0][0], read_termination = '\\n', query_delay = 0.2)\n atenuador1 = rm.open_resource(valores[0][1], read_termination = '\\n')\n vectorSignalGeneratorSMU = rm.open_resource(valores[0][2], read_termination = '\\n', query_delay = 0.2)\n atenuador2 = rm.open_resource(valores[0][3], read_termination = '\\n')\n multiRxSat = serial.Serial(valores[0][4], 115200)\n #multiRxSat = rm.open_resource(valores[0][4], read_termination = '\\r', write_termination = '\\r', baud_rate=115200)\n analisadorDeEspectro = rm.open_resource(valores[0][5], read_termination = '\\n', query_delay = 0.2)\n\n ##################################################### FUNÇÕES ###################################################\n\n def desativarSetup():\n atenuador1.write(comandoAtenuador1+' 139.9')\n atenuador2.write(comandoAtenuador2+' 139.9')\n \n vectorSignalGeneratorSMU.write('OUTP OFF')\n moduladorSFU.write('OUTP OFF')\n\n moduladorSFU.close()\n atenuador1.close()\n vectorSignalGeneratorSMU.close()\n atenuador2.close()\n multiRxSat.close()\n analisadorDeEspectro.close()\n\n time.sleep(5.0)\n\n def comunicacaoSerial(comando):\n\n multiRxSat.write(bytes(comando + '\\r\\n', 'utf-8'))\n\n tempo = time.time()\n\n while multiRxSat.inWaiting() == 0:\n \n if time.time() - tempo > 30:\n return \"erro\"\n \n continue \n \n respostaSerial = multiRxSat.read_until(b'\\r')\n print(respostaSerial)\n return respostaSerial\n\n queue_resposta.put(['Iniciando teste','','', False, False])\n\n #################################################################################################################\n ###################################################### SFU ######################################################\n \n comandosModuladorSFU = ['OUTP:STAT OFF', ':MOD:STAT ON', ':DM:SOUR DTV', ':DM:FORM DVS2', ':IQC:DVBS2:SOUR TSPL', ':DM:POL NORM', ':IQC:DVBS2:SYMB '+str(valores[2])+'e6', ':IQC:DVBS2:CONS S4', ':IQC:DVBS2:PIL ON', ':IQC:DVBS2:ROLL 0.25', ':IQC:DVBS2:RATE R2_5', ':POW 0 dBm', 'FREQ '+str(valores[1])+' MHz']\n \n for comando in comandosModuladorSFU:\n moduladorSFU.write(comando)\n time.sleep(1.0)\n\n queue_resposta.put(['Modulador SFU - OK', '','', False, False])\n\n #################################################################################################################\n\n ###################################################### SMU ######################################################\n\n comandosVectorSignalGeneratorSMU = ['OUTP OFF', ':AWGN:MODE ONLY', ':AWGN:BRAT '+str(valores[2])+'MHz', ':IQ:OUTP:DIG:STAT ON', ':POW 0', ':FREQ '+str(valores[1])+' MHz']\n \n for comando in comandosVectorSignalGeneratorSMU:\n vectorSignalGeneratorSMU.write(comando)\n time.sleep(1.0)\n\n queue_resposta.put(['SMU - OK', '','', False, False])\n\n #################################################################################################################\n \n ################################################## ATENUADORES ##################################################\n\n comandoAtenuador1 = str()\n\n if atenuador1.query('*IDN?') == 'ROHDE & SCHWARZ ,RSP,0,1.5':\n comandoAtenuador1 = 'A'\n else:\n comandoAtenuador1 = 'ATT1:ATT'\n\n atenuador1.write(comandoAtenuador1 + '139.9')\n\n comandoAtenuador2 = str()\n\n if atenuador2.query('*IDN?') == 'ROHDE & SCHWARZ ,RSP,0,1.5':\n comandoAtenuador2 = 'A'\n else:\n comandoAtenuador2 = 'ATT1:ATT'\n\n atenuador2.write(comandoAtenuador2 + '139.9')\n\n queue_resposta.put(['Atenuadores - OK', '','', False, False])\n\n #################################################################################################################\n\n ############################################# ANALISADOR DE ESPECTRO ############################################\n\n comandosAnalisadorDeEspectro = ['FREQ:CENT '+str(valores[1])+' MHz', 'DISP:TRAC:Y:RLEV -20', 'SWE:TIME 1', 'BAND:VID 3000', 'BAND 300000', 'INP:ATT 0', 'SWE:MODE AUTO', 'SENS:POW:ACH:BAND '+str(valores[2])+' MHz', 'FREQ:SPAN 20 MHz']\n for comando in comandosAnalisadorDeEspectro:\n analisadorDeEspectro.write(comando)\n time.sleep(1.0)\n\n queue_resposta.put(['Analisador de Espectro - OK', '','', False, False])\n\n #################################################################################################################\n\n ################################################### MULTISATRX ##################################################\n\n FrequenciaSymbolRate = '02U0A'+hex(int(valores[1]*1000))[2:].zfill(6).upper()+hex(int(valores[2]*1000))[2:].zfill(4).upper() + devolveChecksumMultirxsat('02U0A'+hex(int(valores[1]*1000))[2:].zfill(6).upper()+hex(int(valores[2]*1000))[2:].zfill(4).upper())\n\n print(FrequenciaSymbolRate)\n\n contadorDeErros = 0\n\n while True:\n if contadorDeErros == 6:\n desativarSetup()\n queue_resposta.put(['VERIFICAR PLACA', '', '', 0, 0])\n return\n try:\n temp = comunicacaoSerial('02O4F')\n if temp == \"erro\":\n raise Exception\n\n temp = comunicacaoSerial(FrequenciaSymbolRate)\n if temp == \"erro\":\n raise Exception\n break\n except:\n print('Erro na Placa')\n time.sleep(10.0)\n pass\n\n queue_resposta.put(['MultiSatRx - OK', '','', False, False])\n #################################################################################################################\n \n vectorSignalGeneratorSMU.write('OUTP ON')\n moduladorSFU.write('OUTP:STAT ON')\n\n pil = ['ON', 'OFF']\n attTeste = [60.0, 25.0]\n\n respostasExcel = list()\n respostasExcel.append(valores[3])\n respostasExcel.append(valores[1])\n respostasExcel.append(valores[2])\n respostasExcel.append(valores[4])\n respostasExcel.append(valores[5])\n\n for iten1 in valores[3]:\n queue_resposta.put(['Teste em Andamento', iten1, '', True, iten1])\n moduladorSFU.write(':IQC:DVBS2:CONS ' + iten1)\n moduladorSFU.write(':IQC:DVBS2:PIL ON')\n \n # if iten1 == 'S8':\n # analisadorDeEspectro.write('FREQ:SPAN 20 MHz')\n\n preSaidaATT1 = list()\n preSaidaATT2 = list()\n\n preSaidaTeste25ON = list()\n preSaidaTeste25OFF = list()\n \n preSaidaTeste60ON = list()\n preSaidaTeste60OFF = list()\n\n codeRate = None\n\n if iten1 == 'S4':\n codeRate = valores[4][0]\n elif iten1 == 'S8':\n codeRate = valores[4][1]\n elif iten1 == 'A16':\n codeRate = valores[4][2]\n elif iten1 == 'A32':\n codeRate = valores[4][3]\n else:\n pass\n\n for iten2 in codeRate:\n\n queue_resposta.put(['Teste em Andamento', iten1, iten2[1:].replace('_','/') , False, True])\n\n moduladorSFU.write(':IQC:DVBS2:RATE ' + iten2)\n\n atenuador1.write(comandoAtenuador1+' 139.9')\n atenuador2.write(comandoAtenuador2+' 139.9')\n\n valoresAtenuacao = 70.0\n\n print('Sinal')\n\n controleDoTeste = 0\n\n while True:\n valoresAtenuacao = round(valoresAtenuacao, 1)\n if (valoresAtenuacao) < 0 or (valoresAtenuacao) > 139.9:\n\n desativarSetup()\n queue_resposta.put(['ERRO', '', '', 0, 0])\n return\n\n atenuador1.write(comandoAtenuador1+' '+str(valoresAtenuacao))\n\n resposta = 0.0\n contagem = 0.0\n tempoAtual = time.time()\n\n while(time.time() - tempoAtual < 15):\n time.sleep(0.2)\n resposta = resposta + float(analisadorDeEspectro.query('CALC:MARK:FUNC:POW:RES? CPOW'))\n contagem += 1.0\n resposta = resposta/contagem\n\n print(resposta)\n\n if float(resposta) <-55:\n valoresAtenuacao -= 10.0\n\n elif float(resposta) <-45:\n valoresAtenuacao -= 5.0\n\n elif float(resposta) > -35:\n valoresAtenuacao += 5.0\n\n elif float(resposta) <= -35 and float(resposta) > -39:\n valoresAtenuacao += 1.0\n\n elif float(resposta) >= -45 and float(resposta) < -41:\n valoresAtenuacao -= 1.0\n\n elif float(resposta) >= -41 and float(resposta) <= -40.05:\n controleDoTeste += 1\n if controleDoTeste >= 10:\n preSaidaATT1.append(valoresAtenuacao)\n break\n else:\n valoresAtenuacao -= 0.1\n\n elif float(resposta) >= -39.95 and float(resposta) <= -39:\n valoresAtenuacao += 0.1\n\n elif float(resposta) > -40.05 and float(resposta) < -39.95:\n preSaidaATT1.append(valoresAtenuacao)\n break\n \n else:\n pass\n\n atenuador1.write(comandoAtenuador1+' 139.9')\n atenuador2.write(comandoAtenuador2+' 139.9')\n\n valoresAtenuacao = 70.0\n\n print('Ruido')\n\n controleDoTeste = 0\n\n while True:\n valoresAtenuacao = round(valoresAtenuacao, 1)\n if (valoresAtenuacao) < 0 or (valoresAtenuacao) > 139.9:\n\n desativarSetup()\n queue_resposta.put(['ERRO', '', '', 0, 0])\n return\n\n atenuador2.write(comandoAtenuador2+' '+str(valoresAtenuacao))\n\n resposta = 0.0\n contagem = 0.0\n tempoAtual = time.time()\n\n while(time.time() - tempoAtual < 15):\n time.sleep(0.2)\n resposta = resposta + float(analisadorDeEspectro.query('CALC:MARK:FUNC:POW:RES? CPOW'))\n contagem += 1.0\n resposta = resposta/contagem\n\n print(resposta)\n\n if float(resposta) <-55:\n valoresAtenuacao -= 10.0\n\n elif float(resposta) <-45:\n valoresAtenuacao -= 5.0\n\n elif float(resposta) > -35:\n valoresAtenuacao += 5.0\n\n elif float(resposta) <= -35 and float(resposta) > -39:\n valoresAtenuacao += 1.0\n\n elif float(resposta) >= -45 and float(resposta) < -41:\n valoresAtenuacao -= 1.0\n\n elif float(resposta) >= -41 and float(resposta) <= -40.05:\n controleDoTeste += 1\n if controleDoTeste >= 10:\n preSaidaATT2.append(valoresAtenuacao)\n break\n else:\n valoresAtenuacao -= 0.1\n\n elif float(resposta) >= -39.95 and float(resposta) <= -39:\n valoresAtenuacao += 0.1\n\n elif float(resposta) > -40.05 and float(resposta) < -39.95:\n preSaidaATT2.append(valoresAtenuacao)\n break\n \n else:\n pass\n\n atenuador1.write(comandoAtenuador1+' 139.9')\n atenuador2.write(comandoAtenuador2+' 139.9')\n\n for iten3 in pil:\n moduladorSFU.write(':IQC:DVBS2:PIL ' + iten3)\n time.sleep(10.0)\n\n for iten4 in attTeste:\n\n atenuacaoParaTeste = -40.0 + preSaidaATT1[-1] + iten4 - 6.3\n atenuacaoParaTeste = round(atenuacaoParaTeste, 1)\n\n print('atenuacaoParaTeste', atenuacaoParaTeste, 'preSaidaATT1[-1]', preSaidaATT1[-1])\n\n atenuador1.write(comandoAtenuador1+' '+str(atenuacaoParaTeste))\n\n contadorDeErros = 0\n\n while True:\n if contadorDeErros == 10:\n desativarSetup()\n queue_resposta.put(['ERRO', '', '', 0, 0])\n return\n else:\n pass\n\n try:\n\n temp = comunicacaoSerial('02L52')\n\n if temp == \"erro\":\n raise Exception\n else:\n break\n \n except:\n contadorDeErros += 1\n print('Erro na placa')\n time.sleep(10.0)\n pass\n\n\n valoresAtenuacao = 80.0\n atenuacaoBER = 10.0\n\n ultimaAtenuacaoOK = 0.0\n\n while True:\n\n valoresAtenuacao = round(valoresAtenuacao - atenuacaoBER, 1)\n\n print('valoresAtenuacao', valoresAtenuacao)\n\n atenuador2.write(comandoAtenuador2+' '+str(valoresAtenuacao))\n\n maximoBER = 0.0\n time.sleep(5.0)\n\n valoresBER = list()\n\n numeroDeMedidas = 0\n\n if atenuacaoBER == 10.0:\n numeroDeMedidas = 5\n else:\n numeroDeMedidas = 120\n\n for x in range(numeroDeMedidas):\n\n while True:\n try:\n temp = comunicacaoSerial('02V01BA5')\n if temp == \"erro\":\n raise Exception\n except:\n continue\n\n try:\n temp = str(temp)\n resposta = float(temp[8:10] + 'E-' + temp[10:12])\n valoresBER.append(resposta)\n if resposta > maximoBER:\n maximoBER = resposta\n else:\n pass\n break\n except:\n maximoBER = 1000.0\n valoresBER.append(maximoBER)\n break\n\n\n print('maximoBER', maximoBER)\n print(valoresBER)\n\n if (maximoBER > 2e-4) and atenuacaoBER == 10.0:\n valoresAtenuacao = round(ultimaAtenuacaoOK, 1)\n\n ultimoValor = 0\n for x in range(700, int(valoresAtenuacao*10.0), -50):\n\n atenuador2.write(comandoAtenuador2+' '+str(x/10.0))\n ultimoValor = x\n time.sleep(2.0)\n\n else:\n for x in range(ultimoValor-10, int(valoresAtenuacao*10.0), -10):\n\n atenuador2.write(comandoAtenuador2+' '+str(x/10.0))\n ultimoValor = x\n time.sleep(2.0)\n\n else:\n for x in range(ultimoValor-1, int(valoresAtenuacao*10.0)-1, -1):\n \n atenuador2.write(comandoAtenuador2+' '+str(x/10.0))\n time.sleep(10.0)\n \n atenuacaoBER = 1.0\n\n elif (maximoBER > 2e-4) and atenuacaoBER == 1.0:\n valoresAtenuacao = round(ultimaAtenuacaoOK, 1)\n\n ultimoValor = 0\n for x in range(700, int(valoresAtenuacao*10.0), -50):\n\n atenuador2.write(comandoAtenuador2+' '+str(x/10.0))\n ultimoValor = x\n time.sleep(2.0)\n\n else:\n for x in range(ultimoValor-10, int(valoresAtenuacao*10.0), -10):\n\n atenuador2.write(comandoAtenuador2+' '+str(x/10.0))\n ultimoValor = x\n time.sleep(2.0)\n\n else:\n for x in range(ultimoValor-1, int(valoresAtenuacao*10.0)-1, -1):\n \n atenuador2.write(comandoAtenuador2+' '+str(x/10.0))\n time.sleep(10.0)\n\n atenuacaoBER = 0.1\n\n elif (maximoBER > 2e-4) and atenuacaoBER == 0.1:\n valoresAtenuacao = round(ultimaAtenuacaoOK, 1)\n print('Proximo')\n break\n\n else:\n ultimaAtenuacaoOK = valoresAtenuacao\n pass\n\n if iten3 == 'ON' and iten4 == 25.0:\n preSaidaTeste25ON.append(round(ultimaAtenuacaoOK, 1))\n elif iten3 == 'OFF' and iten4 == 25.0:\n preSaidaTeste25OFF.append(round(ultimaAtenuacaoOK, 1))\n elif iten3 == 'ON' and iten4 == 60.0:\n preSaidaTeste60ON.append(round(ultimaAtenuacaoOK, 1))\n else:\n preSaidaTeste60OFF.append(round(ultimaAtenuacaoOK, 1))\n\n atenuador2.write(comandoAtenuador2+' 139.9')\n\n\n respostasExcel.append([preSaidaATT1, preSaidaATT2, preSaidaTeste60ON, preSaidaTeste25ON, preSaidaTeste60OFF, preSaidaTeste25OFF])\n\n\n print(respostasExcel)\n \n queue_resposta.put(['Gerando Excel', '', '', False, False])\n \n excel.excelTeste3(respostasExcel)\n\n time.sleep(5.0)\n\n queue_resposta.put(['Finalizando', '', '', False, False])\n\n desativarSetup()\n\n queue_resposta.put(['Tempo: ' + str(datetime.timedelta(seconds=time.time()-tempoDecorrido)).rsplit('.', 1)[0].replace('day','dia'), '', '', False, False])\n\n\n\nif __name__ == '__main__':\n mp.freeze_support()\n app = App()\n app.mainloop()","sub_path":"script_edu.py","file_name":"script_edu.py","file_ext":"py","file_size_in_byte":96601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"529750762","text":"import requests\nimport json\nfrom asgiref.sync import async_to_sync\nfrom rest_framework.views import APIView\nfrom rest_framework.exceptions import ParseError\n\nfrom rest_framework.response import Response\nfrom rest_framework import permissions\nfrom fcm_django.models import FCMDevice\nfrom channels.layers import get_channel_layer\n\nfrom halemate_auth.models import User\nfrom halemate_backend.settings import SMS_AUTH\nfrom halemate.utils.nearby_hospitals import searchNearbyHospitals\nfrom halemate_auth.permissions import isVerified\n\n\nclass AlertView(APIView):\n permission_classes = [permissions.IsAuthenticated, isVerified]\n\n def post(self, request, format=None):\n\n try:\n lat = request.data['lat']\n lng = request.data['lng']\n user = request.user\n trusted = user.trusted_contacts.all()\n message = user.name + ' needs medical attention'\n for contact in trusted:\n try:\n usr = User.objects.get(phoneNumber=contact.trusted_phone)\n devices = FCMDevice.objects.filter(user=usr)\n print(devices.registration_id)\n devices.send_message(title='Medical Emergency',\n body=message)\n except:\n continue\n\n contacts_tuple = tuple(map(lambda x: x.trusted_phone, trusted))\n contacts_string = \",\".join(contacts_tuple)\n\n url = \"https://www.fast2sms.com/dev/bulk\"\n querystring = {\n \"authorization\": SMS_AUTH,\n \"sender_id\": \"FSTSMS\",\n \"message\": message,\n \"language\": \"english\",\n \"route\": \"p\",\n \"numbers\": contacts_string,\n }\n\n headers = {\"cache-control\": \"no-cache\"}\n\n response = requests.request(\"GET\", url, headers=headers,\n params=querystring)\n print(response.status_code)\n\n try:\n layer = get_channel_layer()\n message = {\n 'type': 505,\n 'message': \"Medical Emergency\",\n \"lat\": lat,\n \"lng\": lng,\n \"patient_name\": user.name,\n \"patient_contact\": user.phoneNumber\n }\n hospitals = User.objects.filter(registered_as='H')\n for hospital in hospitals:\n room_group_name = 'hospital_' + str(hospital.id)\n async_to_sync(layer.group_send)(\n room_group_name,\n {\n 'type': 'notify',\n 'message': json.dumps(message)\n }\n )\n except:\n pass\n return Response(data={\"detail\": \"success\"}, status=200)\n except:\n raise ParseError\n\n\nclass ReportAlertView(APIView):\n permission_classes = [permissions.IsAuthenticated, isVerified]\n\n def post(self, request, format=None):\n\n try:\n lat = request.data['lat']\n lng = request.data['lng']\n hospitals = searchNearbyHospitals(lat, lng)\n return Response(data=hospitals)\n except:\n raise ParseError\n","sub_path":"halemate/views/alert.py","file_name":"alert.py","file_ext":"py","file_size_in_byte":3355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"100404454","text":"from django.shortcuts import render, redirect\nfrom .models import League, Team, Player\n\nfrom . import team_maker\n\ndef index(request):\n\tcontext = {\n\t\t\"leagues\": League.objects.all(),\n\t\t\"teams\": Team.objects.all(),\n\t\t\"players\": Player.objects.all(),\n\t}\n\treturn render(request, \"leagues/index.html\", context)\n\ndef make_data(request):\n\tteam_maker.gen_leagues(10)\n\tteam_maker.gen_teams(50)\n\tteam_maker.gen_players(200)\n\n\treturn redirect(\"index\")\n\ndef query(request):\n\tif request.method == \"POST\":\n\t\tdata = {\n\t\t\t\"baseball\": League.objects.filter(sport=\"Baseball\"),\n\t\t\t\"womens\": League.objects.filter(name__contains = \"Women\"),\n\t\t\t\"hockey\": League.objects.filter(sport__contains = \"Hockey\"),\n\t\t\t\"not_football\": League.objects.exclude(sport = \"Football\"),\n\t\t\t\"conferences\": League.objects.filter(name__contains = \"Conference\"),\n\t\t\t\"atlantic\": League.objects.filter(name__contains = \"Atlantic\"),\n\t\t\t\"dallas\": Team.objects.filter(location = \"Dallas\"),\n\t\t\t\"raptors\": Team.objects.filter(team_name = \"Raptors\"),\n\t\t\t\"city\": Team.objects.filter(location__contains = \"City\"),\n\t\t\t\"begins_with_t\": Team.objects.filter(team_name__startswith = \"T\"),\n\t\t\t\"alphabetical_location\": Team.objects.order_by('location'),\n\t\t\t\"reverse_order\": Team.objects.order_by('team_name').reverse(),\n\t\t\t\"last_name\": Player.objects.filter(last_name = \"Cooper\"),\n\t\t\t\"first_name\": Player.objects.filter(first_name = \"Joshua\"),\n\t\t\t\"last_name_cooper\": Player.objects.filter(last_name = \"Cooper\").exclude(first_name = \"Joshua\"),\n\t\t\t\"alex_or_wyatt\": (Player.objects.filter(first_name = \"Alexander\") | Player.objects.filter(first_name = \"Wyatt\").order_by(\"first_name\")),\n\t\t\t#level 2 queries\n\t\t\t\"atlantic_teams\": Team.objects.filter(league__name__contains=\"Atlantic Soccer\"),\n\t\t\t\"boston_penguins\": Player.objects.filter(curr_team__team_name = \"Penguins\"),\n\t\t\t\"college_baseball\": Player.objects.filter(curr_team__league__name__contains=\"Collegiate Baseball\"),\n\t\t\t\"lopez\": Player.objects.filter(curr_team__league__name__contains=\"American Conference of Amateur Football\").filter(last_name=\"Lopez\"),\n\t\t\t\"football_players\": Player.objects.filter(curr_team__league__sport=\"Football\"),\n\t\t\t\"sophia\": Team.objects.filter(curr_players__first_name=\"Sophia\"),\n\t\t\t\"league_sophia\": League.objects.filter(teams__curr_players__first_name=\"Sophia\"),\n\t\t\t\"anderson\": Player.objects.filter(last_name=\"Anderson\").exclude(all_teams__team_name=\"Rays\")\n\t\t\t}\n\treturn render(request, 'leagues/query.html', data)\n\n\n\"\"\"\n# Simple finds\n16. Find all players with first name \"Alexander\" OR first name \"Wyatt\"\n\"\"\"\n","sub_path":"johnTruong/django/sports_orm-master/apps/leagues/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"632672924","text":"# -*- coding: utf-8 -*-\n\"\"\"Catch22 Classifier.\n\nPipeline classifier using the Catch22 transformer and an estimator.\n\"\"\"\n\n__author__ = [\"Matthew Middlehurst\"]\n__all__ = [\"Catch22Classifier\"]\n\nimport numpy as np\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.utils.multiclass import class_distribution\n\nfrom sktime.base._base import _clone_estimator\nfrom sktime.classification.base import BaseClassifier\nfrom sktime.transformations.panel.catch22 import Catch22\nfrom sktime.utils.validation.panel import check_X_y, check_X\n\n\nclass Catch22Classifier(BaseClassifier):\n \"\"\"Canonical Time-series Characteristics (catch22) classifier.\n\n This classifier simply transforms the input data using the Catch22 [1]\n transformer and builds a provided estimator using the transformed data.\n\n Parameters\n ----------\n outlier_norm : bool, default=False\n Normalise each series during the two outlier catch22 features, which can take a\n while to process for large values\n estimator : sklearn classifier, default=None\n An sklearn estimator to be built using the transformed data. Defaults to a\n Random Forest with 200 trees.\n n_jobs : int, default=1\n The number of jobs to run in parallel for both `fit` and `predict`.\n ``-1`` means using all processors.\n random_state : int or None, default=None\n Seed for random, integer.\n\n Attributes\n ----------\n n_classes : int\n Number of classes. Extracted from the data.\n classes_ : ndarray of shape (n_classes)\n Holds the label for each class.\n\n See Also\n --------\n Catch22\n\n Notes\n -----\n Authors `catch22ForestClassifier `_.\n\n For the Java version, see `tsml `_.\n\n References\n ----------\n .. [1] Lubba, Carl H., et al. \"catch22: Canonical time-series characteristics.\"\n Data Mining and Knowledge Discovery 33.6 (2019): 1821-1852.\n https://link.springer.com/article/10.1007/s10618-019-00647-x\n\n Examples\n --------\n >>> from sktime.classification.feature_based import Catch22Classifier\n >>> from sktime.datasets import load_italy_power_demand\n >>> X_train, y_train = load_italy_power_demand(split=\"train\", return_X_y=True)\n >>> X_test, y_test = load_italy_power_demand(split=\"test\", return_X_y=True)\n >>> clf = Catch22Classifier()\n >>> clf.fit(X_train, y_train)\n Catch22Classifier(...)\n >>> y_pred = clf.predict(X_test)\n \"\"\"\n\n # Capability tags\n capabilities = {\n \"multivariate\": True,\n \"unequal_length\": False,\n \"missing_values\": False,\n \"train_estimate\": False,\n \"contractable\": False,\n }\n\n def __init__(\n self,\n outlier_norm=False,\n estimator=None,\n n_jobs=1,\n random_state=None,\n ):\n self.outlier_norm = outlier_norm\n self.estimator = estimator\n\n self.n_jobs = n_jobs\n self.random_state = random_state\n\n self._transformer = None\n self._estimator = None\n self.n_classes = 0\n self.classes_ = []\n super(Catch22Classifier, self).__init__()\n\n def fit(self, X, y):\n \"\"\"Fit an estimator using transformed data from the Catch22 transformer.\n\n Parameters\n ----------\n X : nested pandas DataFrame of shape [n_instances, n_dims]\n Nested dataframe with univariate time-series in cells.\n y : array-like, shape = [n_instances] The class labels.\n\n Returns\n -------\n self : object\n \"\"\"\n X, y = check_X_y(X, y)\n self.classes_ = class_distribution(np.asarray(y).reshape(-1, 1))[0][0]\n self.n_classes = np.unique(y).shape[0]\n\n self._transformer = Catch22(outlier_norm=self.outlier_norm)\n self._estimator = _clone_estimator(\n RandomForestClassifier(n_estimators=200)\n if self.estimator is None\n else self.estimator,\n self.random_state,\n )\n\n m = getattr(self._estimator, \"n_jobs\", None)\n if callable(m):\n self._estimator.n_jobs = self.n_jobs\n\n X_t = self._transformer.fit_transform(X, y)\n X_t = np.nan_to_num(X_t, False, 0, 0, 0)\n self._estimator.fit(X_t, y)\n\n self._is_fitted = True\n return self\n\n def predict(self, X):\n \"\"\"Predict class values of n_instances in X.\n\n Parameters\n ----------\n X : pd.DataFrame of shape (n_instances, n_dims)\n\n Returns\n -------\n preds : np.ndarray of shape (n, 1)\n Predicted class.\n \"\"\"\n self.check_is_fitted()\n X = check_X(X)\n\n X_t = self._transformer.transform(X)\n X_t = np.nan_to_num(X_t, False, 0, 0, 0)\n return self._estimator.predict(X_t)\n\n def predict_proba(self, X):\n \"\"\"Predict class probabilities for n_instances in X.\n\n Parameters\n ----------\n X : pd.DataFrame of shape (n_instances, n_dims)\n\n Returns\n -------\n predicted_probs : array of shape (n_instances, n_classes)\n Predicted probability of each class.\n \"\"\"\n self.check_is_fitted()\n X = check_X(X)\n\n X_t = self._transformer.transform(X)\n X_t = np.nan_to_num(X_t, False, 0, 0, 0)\n\n m = getattr(self._estimator, \"predict_proba\", None)\n if callable(m):\n return self._estimator.predict_proba(X_t)\n else:\n dists = np.zeros((X.shape[0], self.n_classes))\n preds = self._estimator.predict(X_t)\n for i in range(0, X.shape[0]):\n dists[i, np.where(self.classes_ == preds[i])] = 1\n return dists\n","sub_path":"sktime/classification/feature_based/_catch22_classifier.py","file_name":"_catch22_classifier.py","file_ext":"py","file_size_in_byte":5813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"144289936","text":"from scipy.io import loadmat\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.fftpack import fft,fftshift,ifft\n\nsinais = loadmat('/home/iagodiogenes/iagodiogenes_DCO2004/Handson6/Pacientes.mat')\n\nsinal1 = sinais['sinal_1'].flatten()\nsinal2 = sinais['sinal_2'].flatten()\nsinal3 = sinais['sinal_3'].flatten()\nsinal4 = sinais['sinal_4'].flatten()\nsinal5 = sinais['sinal_5'].flatten()\nFs = int(sinais['Fs'])\n\nN_samp = len(sinal1)\nN = 10\nT = 1/Fs\nTf = 10 # Tempo final em segundos\nt = np.arange(0,Tf,T) # Definição do eixo do tempo \n\n# Criação das funções, por questão de organização\ndef downsample(array,rate):\n return array[::rate]\n\ndef upsample(array,rate):\n from numpy import zeros\n ret = zeros(rate*len(array))\n ret[::rate] = array \n return ret\n\ndef de2bi(sinal):\n from numpy import fromiter,binary_repr,round \n sinal_bin = round(sinal).astype(int)\n return fromiter(map(binary_repr,sinal_bin),dtype=int)\n#\ndef bi2de(sinal):\n from numpy import ndarray\n sinal_dec = ndarray(len(sinal),dtype=int)\n for i in range(len(sinal_dec)):\n sinal_dec[i] = int(str(sinal[i]),2) \n return sinal_dec\n\n## Amostragem \ns_out1=downsample(sinal1,N) # Coleta 1 amostra a cada N_samp=10 amostras do sinal \ns_out1=upsample(s_out1,N) # Retorna vetor amostrado com o número inicial de elementos\n\n## Amostragem \ns_out2=downsample(sinal2,N) # Coleta 1 amostra a cada N_samp=10 amostras do sinal \ns_out2=upsample(s_out2,N) # Retorna vetor amostrado com o número inicial de elementos\n\n## Amostragem \ns_out3=downsample(sinal3,N) # Coleta 1 amostra a cada N_samp=10 amostras do sinal \ns_out3=upsample(s_out3,N) # Retorna vetor amostrado com o número inicial de elementos\n\n## Amostragem \ns_out4=downsample(sinal4,N) # Coleta 1 amostra a cada N_samp=10 amostras do sinal \ns_out4=upsample(s_out4,N) # Retorna vetor amostrado com o número inicial de elementos\n\n## Amostragem \ns_out5=downsample(sinal5,N) # Coleta 1 amostra a cada N_samp=10 amostras do sinal \ns_out5=upsample(s_out5,N) # Retorna vetor amostrado com o número inicial de elementos\n \n#plotting\nplt.figure(1,[10,4])\n\nplt.subplot(2,3,1)\nplt.plot(t,s_out1,t,sinal1)\nplt.title(\"Sinal Original e Sinal Amostrado (1)\")\nplt.xlabel(\"Tempo [s]\")\nplt.ylabel(\"Amplitude\")\nplt.xlim([0,0.1])\nplt.legend([\"Amostrado\",\"Original\"])\n\nplt.subplot(2,3,2)\nplt.plot(t,s_out2,t,sinal2)\nplt.title(\"Sinal Original e Sinal Amostrado (2)\")\nplt.xlim([0,0.1])\nplt.legend([\"Amostrado\",\"Original\"])\n\nplt.subplot(2,3,3)\nplt.plot(t,s_out3,t,sinal3)\nplt.title(\"Sinal Original e Sinal Amostrado (3)\")\nplt.xlim([0,0.1])\nplt.legend([\"Amostrado\",\"Original\"])\n\nplt.subplot(2,3,4)\nplt.plot(t,s_out4,t,sinal4)\nplt.title(\"Sinal Original e Sinal Amostrado (4)\")\nplt.xlim([0,0.1])\nplt.legend([\"Amostrado\",\"Original\"])\n\nplt.subplot(2,3,5)\nplt.plot(t,s_out5,t,sinal5)\nplt.title(\"Sinal Original e Sinal Amostrado (5)\")\nplt.xlim([0,0.1])\nplt.legend([\"Amostrado\",\"Original\"])\n\nplt.tight_layout()\n\nplt.show()\n\n##########################################################\n############### Quantização e codificação ################\n##########################################################\n\nsig_quan01= s_out1-np.min(s_out1)+1 # Todos elementos positivos\nsig_quan01= np.round(sig_quan01) # Transforma sinal em números inteiros\nsig_code01= de2bi(sig_quan01) # Transforma em sinal binário \n\nsig_quan02= s_out2-np.min(s_out2)+1 # Todos elementos positivos\nsig_quan02= np.round(sig_quan02) # Transforma sinal em números inteiros\nsig_code02= de2bi(sig_quan02) # Transforma em sinal binário \n\nsig_quan03= s_out3-np.min(s_out3)+1 # Todos elementos positivos\nsig_quan03= np.round(sig_quan03) # Transforma sinal em números inteiros\nsig_code03= de2bi(sig_quan03) # Transforma em sinal binário \n\nsig_quan04= s_out4-np.min(s_out4)+1 # Todos elementos positivos\nsig_quan04= np.round(sig_quan04) # Transforma sinal em números inteiros\nsig_code04= de2bi(sig_quan04) # Transforma em sinal binário \n\nsig_quan05= s_out5-np.min(s_out5)+1 # Todos elementos positivos\nsig_quan05= np.round(sig_quan05) # Transforma sinal em números inteiros\nsig_code05= de2bi(sig_quan05) # Transforma em sinal binário \n\n##########################################################\n#################### Multiplexação #######################\n##########################################################\n\nframeSize = 5; # Tamanho do quadro (número máximo de sinais a serem multiplexados) \nmux_sig = np.zeros(len(sig_code01)*frameSize,dtype=int)\n\nfor i in range(1,len(sig_code01)+1): \n mux_sig[4*(i-1)] = sig_code01[i-1] # Indexação em python começa em 0\n mux_sig[4*(i-1)+1] = 0\n mux_sig[4*(i-1)+2] = sig_code02[i-1]\n mux_sig[4*(i-1)+3] = 0\n mux_sig[4*(i-1)+5] = sig_code03[i-1]\n mux_sig[4*(i-1)+6] = 0 \n mux_sig[4*(i-1)+7] = sig_code04[i-1]\n mux_sig[4*(i-1)+8] = 0\n mux_sig[4*(i-1)+9] = sig_code05[i-1]\n mux_sig[4*(i-1)+10] = 0\n\n##################################################################################################################\n################################################ R E C E P Ç Ã O #################################################\n##################################################################################################################\n\n#Demultiplexador de sinais \ndemux_01 = np.zeros(30000,dtype=int)\ndemux_02 = np.zeros(30000,dtype=int)\ndemux_03 = np.zeros(30000,dtype=int)\ndemux_04 = np.zeros(30000,dtype=int)\ndemux_05 = np.zeros(30000,dtype=int)\n\nfor i in range(1,30001):\n demux_01[i-1]= mux_sig[(i-1)*4 ]\n demux_02[i-1]= mux_sig[(i-1)*4 + 2]\n demux_03[i-1]= mux_sig[(i-1)*4 + 4]\n demux_04[i-1]= mux_sig[(i-1)*4 + 6]\n demux_05[i-1]= mux_sig[(i-1)*4 + 8]\n\n##########################################################\n#################### Decodificação #######################\n##########################################################\n\nsig_rec01 = bi2de(demux_01)\nsig_rec02 = bi2de(demux_02)\nsig_rec03 = bi2de(demux_03)\nsig_rec04 = bi2de(demux_04)\nsig_rec05 = bi2de(demux_05)\n\n# Teste se decoficação funcionou\nif (np.array_equal(sig_rec01,sig_quan01)):\n print(\"Sinais sig_rec01 e sig_quan01 são iguais: decodficação realizada com sucesso!!!\")\nelse:\n print(\"Sinais sig_rec01 e sig_quan01 são diferentes: decodficação falhou!!!\")\nif (np.array_equal(sig_rec02,sig_quan02)):\n print(\"Sinais sig_rec02 e sig_quan02 são iguais: decodficação realizada com sucesso!!!\")\nelse:\n print(\"Sinais sig_rec02 e sig_quan02 são diferentes: decodficação falhou!!!\")\n\n\n # Reconstrução realizando a filtragem no domínio da frequência\n \n ## Espectro\nlfft=len(sig_rec01)\nfreq = np.arange(-Fs/2,Fs/2,Fs/lfft)# Comprimento da fft\n\nSIG_rec01=fftshift(fft(sig_rec01,lfft)/lfft) # Sinal m_t na frequência M_f\nSIG_rec02=fftshift(fft(sig_rec02,lfft)/lfft) # Sinal m_t na frequência M_f\nSIG_rec03=fftshift(fft(sig_rec03,lfft)/lfft) # Sinal m_t na frequência M_f\nSIG_rec04=fftshift(fft(sig_rec04,lfft)/lfft) # Sinal m_t na frequência M_f\nSIG_rec05=fftshift(fft(sig_rec05,lfft)/lfft) # Sinal m_t na frequência M_f\n \nBW=10 # Largura de banda de 10\nH_lpf=np.zeros(lfft) # Zera vetor filtro\nH_lpf[lfft//2-BW:lfft//2+BW-1]=1 # Define 1 na frequência desejada\n\nSIG_fil1=N_samp*SIG_rec01*H_lpf # Filtragem ideal\nSig_fil1=np.real(ifft(fftshift(SIG_fil1))) # Reconstroi o sinal no tempo\nSig_fil1=Sig_fil1*np.max(sinal1)/np.max(Sig_fil1) # Dá ganho pro sinal reconstruído\n\nSIG_fil2=N_samp*SIG_rec02*H_lpf # Filtragem ideal\nSig_fil2=np.real(ifft(fftshift(SIG_fil2))) # Reconstroi o sinal no tempo\nSig_fil2=Sig_fil2*np.max(sinal2)/np.max(Sig_fil2) # Dá ganho pro sinal reconstruído\n\nSIG_fil3=N_samp*SIG_rec03*H_lpf # Filtragem ideal\nSig_fil3=np.real(ifft(fftshift(SIG_fil3))) # Reconstroi o sinal no tempo\nSig_fil3=Sig_fil3*np.max(sinal3)/np.max(Sig_fil3) # Dá ganho pro sinal reconstruído\n\nSIG_fil4=N_samp*SIG_rec04*H_lpf # Filtragem ideal\nSig_fil4=np.real(ifft(fftshift(SIG_fil4))) # Reconstroi o sinal no tempo\nSig_fil4=Sig_fil4*np.max(sinal4)/np.max(Sig_fil4) # Dá ganho pro sinal reconstruído\n\nSIG_fil5=N_samp*SIG_rec05*H_lpf # Filtragem ideal\nSig_fil5=np.real(ifft(fftshift(SIG_fil5))) # Reconstroi o sinal no tempo\nSig_fil5=Sig_fil5*np.max(sinal5)/np.max(Sig_fil5) # Dá ganho pro sinal reconstruído\n\n \n#plotting\nplt.figure(2,[10,4])\n\nplt.subplot(2,3,1)\nplt.plot(t,SIG_fil1,t,sinal1)\nplt.title(\"Sinal Original e Sinal Recuperado (1)\")\nplt.xlabel(\"Tempo [s]\")\nplt.ylabel(\"Amplitude\")\nplt.legend([\"Recuperado\",\"Original\"])\n\nplt.subplot(2,3,2)\nplt.plot(t,SIG_fil2,t,sinal2)\nplt.title(\"Sinal Original e Sinal Recuperado (2)\")\nplt.legend([\"Recuperado\",\"Original\"])\n\nplt.subplot(2,3,3)\nplt.plot(t,SIG_fil3,t,sinal3)\nplt.title(\"Sinal Original e Sinal Recuperado (3)\")\nplt.legend([\"Recuperado\",\"Original\"])\n\nplt.subplot(2,3,4)\nplt.plot(t,SIG_fil4,t,sinal4)\nplt.title(\"Sinal Original e Sinal Recuperado (4)\")\nplt.legend([\"Recuperado\",\"Original\"])\n\nplt.subplot(2,3,5)\nplt.plot(t,SIG_fil5,t,sinal5)\nplt.title(\"Sinal Original e Sinal Recuperado (5)\")\nplt.legend([\"Recuperado\",\"Original\"])\n\nplt.tight_layout()\n\nplt.show()","sub_path":"Handson6/teste-entregavel6-2.py","file_name":"teste-entregavel6-2.py","file_ext":"py","file_size_in_byte":10283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"409074146","text":"import numpy as np\nimport argparse\nimport os\nimport torch\nimport torchvision\nimport torch.nn as nn\nimport torch.backends as cudnn\nimport torch.optim as optim\nfrom torchvision import transforms\nfrom torchvision.utils import save_image\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.autograd import Variable\nimport random\nimport glob\nfrom PIL import Image\nimport Null_LDA_for_FSDD\nimport KNN_for_NLDA_Python\nfrom PIL import ImageOps\n\nimport torch.utils.data\nimport visualize_tools\nimport LJY_utils\n\nfrom PIL import ImageDraw\n\n'''\n# Introduction\n\n 1. Dataloader set\n \n 2. Image Pre-Processing\n \n 3. Set the Encoder-Decoder Networks\n \n 4. Networks Parameter Initialization(Xavier)\n \n 5. Define AE Loss function\n \n 6. Train AutoEncoder\n 6.1 Options\n 6.2 Save directory set\n 6.3 Seed set\n 6.4 Cuda set\n 6.5 Data and Parameters\n 6.6 Training settings(criterion set, optimizer set, container generate, make to Variables)\n \n 7. Test NLDA\n'''\n\nsample_dir = 'samples'\npath = '/home/cheeze/PycharmProjects/NLDA_code/data'\npath2 = 'home/cheeze/PycharmProjects/NLDA_code/data'\n\nif not os.path.exists(sample_dir):\n os.makedirs(sample_dir)\n\n\n# Set the Dataloader(train, test)\n\nclass DL(torch.utils.data.Dataset):\n def __init__(self, path, transform, type):\n random.seed = 1\n self.transform = transform\n self.type = type\n assert os.path.exists(path)\n self.base_path = path\n\n total_file_paths = []\n cur_file_paths = glob.glob(os.path.join(self.base_path, 'AR_session1_train', '*'))\n total_file_paths = total_file_paths + cur_file_paths\n #cur_file_paths = glob.glob(os.path.join(self.base_path, 'AR_session2', '*'))\n #total_file_paths = total_file_paths + cur_file_paths\n cur_file_paths = glob.glob(os.path.join(self.base_path, 'Feret_train', '*'))\n total_file_paths = total_file_paths + cur_file_paths\n #cur_file_paths = glob.glob(os.path.join(self.base_path, 'FERET_normal', '*'))\n #total_file_paths = total_file_paths + cur_file_paths\n\n random.shuffle(total_file_paths)\n num_of_valset = int(len(total_file_paths)/10)\n\n self.train_file_paths = total_file_paths[num_of_valset:]\n self.test_file_paths = total_file_paths[:num_of_valset]\n\n def pil_loader(self, path):\n with open(path, 'rb') as f:\n with Image.open(f) as img:\n img = ImageOps.equalize(img)\n return img.resize((120,100))\n\n def __len__(self):\n if self.type == 'train':\n return len(self.train_file_paths)\n if self.type == 'test':\n return len(self.test_file_paths)\n\n def __getitem__(self, item):\n if self.type == 'train':\n path = self.train_file_paths[item]\n elif self.type == 'test':\n path = self.test_file_paths[item]\n\n img = self.pil_loader(path)\n if self.transform is not None:\n img = self.transform(img)\n return img\n\n\n# Image pre-processing\ndef default_image(img):\n image_=img\n return image_\n\ndef make_sunglass(img):\n image_ = img\n\n # make sunglass\n image_[:, :, 6:31, 8:34] = -1\n image_[:, :, 6:31, 49:74] = -1\n image_[:, :, 8:15, 34:49] = -1\n return image_\n\ndef make_sunglass2(img):\n image_ = img\n\n # make sunglass\n image_[:, :, 26:56, 8:40] = -1 # whole, height, width\n image_[:, :, 26:56, 64:96] = -1\n image_[:, :, 30:40, 40:64] = -1\n return image_\n\n\ndef make_sunglass3(img):\n image_ = img\n\n # make sunglass\n image_[:, :, 6:31, 5:29] = -1\n image_[:, :, 6:31, 35:59] = -1\n image_[:, :, 8:15, 29:35] = -1\n return image_\n\n# Set the Encoder-Decoder Networks\n\nclass encoder(nn.Module):\n def __init__(self, z_size=2, channel=3, num_filters=64, type='AE'):\n super().__init__()\n self.type = type\n self.encoder = nn.Sequential(\n nn.Conv2d(channel, num_filters, 4, 2, 1, bias=False),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(num_filters, num_filters * 2, 4, 2, 1, bias=False),\n nn.BatchNorm2d(num_filters * 2),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(num_filters * 2, num_filters * 4, 4, 2, 1, bias=False),\n nn.BatchNorm2d(num_filters * 4),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(num_filters * 4, num_filters * 8, 4, 2, 1, bias=False),\n nn.BatchNorm2d(num_filters * 8),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(num_filters * 8, num_filters * 8, 4, 2, 1, bias=False),\n nn.BatchNorm2d(num_filters * 8),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(num_filters * 8, z_size, 4, 2, 1, bias=False),\n )\n if self.type == 'VAE':\n self.fc_mu = nn.Conv2d(z_size, z_size, 1)\n self.fc_sig = nn.Conv2d(z_size, z_size, 1)\n # init weights\n self.weight_init()\n\n def forward(self, x):\n if self.type == 'AE':\n #AE\n z = self.encoder(x)\n return z\n elif self.type == 'VAE':\n # VAE\n z_ = self.encoder(x)\n mu = self.fc_mu(z_)\n logvar = self.fc_sig(z_)\n return mu, logvar\n def weight_init(self):\n self.encoder.apply(weight_init)\n\nclass decoder(nn.Module):\n def __init__(self, z_size=2,channel=3, num_filters=64):\n super().__init__()\n\n self.decoder = nn.Sequential(\n nn.ConvTranspose2d(z_size, num_filters * 8, 4, 1, 0, bias=False),\n nn.BatchNorm2d(num_filters * 8),\n nn.ReLU(True),\n # state size. (ngf*8) x 4 x 4\n nn.ConvTranspose2d(num_filters * 8, num_filters * 4, 4, 2, 1, bias=False),\n nn.BatchNorm2d(num_filters * 4),\n nn.ReLU(True),\n # state size. (ngf*4) x 8 x 8\n nn.ConvTranspose2d(num_filters * 4, num_filters * 2, 4, 2, 1, bias=False),\n nn.BatchNorm2d(num_filters * 2),\n nn.ReLU(True),\n # state size. (ngf*2) x 16 x 16\n nn.ConvTranspose2d(num_filters * 2, num_filters, 4, 2, 1, bias=False),\n nn.BatchNorm2d(num_filters),\n nn.ReLU(True),\n # state size. (ngf) x 32 x 32\n nn.ConvTranspose2d(num_filters, channel, 4, 2, 1, bias=False),\n nn.Tanh()\n )\n self.decoder_subpixel = nn.Sequential(\n )\n # init weights\n self.weight_init()\n\n def forward(self, z):\n recon_x = self.decoder(z)\n return recon_x\n\n def weight_init(self):\n self.decoder.apply(weight_init)\n\n# Network Parameter Initialization\n\ndef weight_init(module):\n classname = module.__class__.__name__\n if classname.find('Conv') != -1:\n torch.nn.init.xavier_normal_(module.weight.data)\n # module.weight.data.normal_(0.0, 0.01)\n elif classname.find('BatchNorm') != -1:\n module.weight.data.normal_(1.0, 0.02)\n module.bias.data.fill_(0)\n\n\n# Define the Loss-function\n\ndef Variational_loss(input, target, mu, logvar, epoch):\n recon_loss = MSE_loss(input, target)\n KLD_loss = -0.5 * torch.sum(1+logvar-mu.pow(2) - logvar.exp())\n result=recon_loss+ KLD_loss\n if(result >35000 and epoch > 350):\n print(\"%4f %4f\", recon_loss, KLD_loss)\n return recon_loss + KLD_loss\n\n\ndef train_ae():\n class encoder(nn.Module):\n def __init__(self, z_size=2, channel=3, num_filters=64, type='AE'):\n super().__init__()\n self.type = type\n self.encoder = nn.Sequential(\n nn.Conv2d(channel, num_filters, 4, 2, 1, bias=False),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(num_filters, num_filters * 2, 4, 2, 1, bias=False),\n nn.BatchNorm2d(num_filters * 2),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(num_filters * 2, num_filters * 4, 4, 2, 1, bias=False),\n nn.BatchNorm2d(num_filters * 4),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(num_filters * 4, num_filters * 8, 4, 2, 1, bias=False),\n nn.BatchNorm2d(num_filters * 8),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(num_filters * 8, num_filters * 8, 3, 2, 1, bias=False),\n nn.BatchNorm2d(num_filters * 8),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(num_filters * 8, z_size, 3, 1, 1, bias=False),\n )\n if self.type == 'VAE':\n self.fc_mu = nn.Conv2d(z_size, z_size, 1)\n self.fc_sig = nn.Conv2d(z_size, z_size, 1)\n # init weights\n self.weight_init()\n\n def forward(self, x):\n if self.type == 'AE':\n # AE\n z = self.encoder(x)\n return z\n elif self.type == 'VAE':\n # VAE\n z_ = self.encoder(x)\n mu = self.fc_mu(z_)\n logvar = self.fc_sig(z_)\n return mu, logvar\n\n def weight_init(self):\n self.encoder.apply(weight_init)\n\n class decoder(nn.Module):\n def __init__(self, z_size=2, channel=3, num_filters=64):\n super().__init__()\n\n self.decoder = nn.Sequential(\n nn.ConvTranspose2d(z_size, num_filters * 8, 4, 1, 1, bias=False),\n nn.BatchNorm2d(num_filters * 8),\n nn.ReLU(True),\n # state size. (ngf*8) x 4 x 4\n nn.ConvTranspose2d(num_filters * 8, num_filters * 4, 4, 1, 1, bias=False),\n nn.BatchNorm2d(num_filters * 4),\n nn.ReLU(True),\n # state size. (ngf*4) x 8 x 8\n nn.ConvTranspose2d(num_filters * 4, num_filters * 2, 4, 2, 1, bias=False),\n nn.BatchNorm2d(num_filters * 2),\n nn.ReLU(True),\n # state size. (ngf*2) x 16 x 16\n nn.ConvTranspose2d(num_filters * 2, num_filters, 4, 2, 1, bias=False),\n nn.BatchNorm2d(num_filters),\n nn.ReLU(True),\n # state size. (ngf) x 32 x 32\n nn.ConvTranspose2d(num_filters, channel, 5, 5, 0, bias=False),\n nn.Tanh()\n )\n self.decoder_subpixel = nn.Sequential(\n\n )\n # init weights\n self.weight_init()\n\n def forward(self, z):\n recon_x = self.decoder(z)\n return recon_x\n\n def weight_init(self):\n self.decoder.apply(weight_init)\n\n # Options\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--dataset', default='celebA', help='what is dataset?')\n parser.add_argument('--dataroot',\n default='/home/cheeze/PycharmProjects/NLDA_code/data',\n help='path to dataset')\n parser.add_argument('--pretrainedModelName', default='autoencoder', help=\"path of Encoder networks.\")\n parser.add_argument('--pretrainedEpoch', type=int, default=0, help=\"path of Decoder networks.\")\n parser.add_argument('--outf', default='./pretrained_model', help=\"folder to output images and model checkpoints\")\n\n parser.add_argument('--cuda', default='True', action='store_true', help='enables cuda')\n parser.add_argument('--display', default=False, help='display options. default:False. NOT IMPLEMENTED')\n parser.add_argument('--ngpu', type=int, default=1, help='number of GPUs to use')\n parser.add_argument('--workers', type=int, default=1, help='number of data loading workers')\n parser.add_argument('--iteration', type=int, default=10000, help='number of epochs to train for')\n\n # these options are saved for testing\n parser.add_argument('--batchSize', type=int, default=200, help='input batch size')\n parser.add_argument('--imageSize', type=int, default=120, help='the height / width of the input image to network')\n parser.add_argument('--model', type=str, default='pretrained_model', help='Model name')\n parser.add_argument('--nc', type=int, default=1, help='number of input channel.')\n parser.add_argument('--nz', type=int, default=500, help='number of input channel.')\n parser.add_argument('--ngf', type=int, default=64, help='number of generator filters.')\n parser.add_argument('--ndf', type=int, default=64, help='number of discriminator filters.')\n parser.add_argument('--lr', type=float, default=0.0002, help='learning rate')\n parser.add_argument('--beta1', type=float, default=0.5, help='beta1 for Adam.')\n\n parser.add_argument('--seed', type=int, help='manual seed')\n\n options = parser.parse_args()\n print(options)\n\n\n # Save directory make\n\n try:\n os.makedirs(options.outf)\n except OSError:\n pass\n\n # Seed set\n\n if options.seed is None:\n options.seed = random.randint(1, 10000)\n print(\"Random Seed: \", options.seed)\n random.seed(options.seed)\n torch.manual_seed(options.seed)\n\n # Cuda set\n\n if options.cuda:\n torch.cuda.manual_seed(options.seed)\n\n torch.backends.cudnn.benchmark = True\n cudnn.benchmark = True\n if torch.cuda.is_available() and not options.cuda:\n print(\"WARNING: You have a CUDA device, so you should probably run with --cuda\")\n\n # Data and Parameters\n\n ngpu = int(options.ngpu)\n nz = int(options.nz)\n autoencoder_type = 'AE'\n encoder = encoder(options.nz, options.nc, 64, autoencoder_type)\n encoder.apply(LJY_utils.weights_init)\n # if options.netG != '':\n # encoder.load_state_dict(torch.load(options.netG))\n print(encoder)\n\n decoder = decoder(options.nz, options.nc)\n decoder.apply(LJY_utils.weights_init)\n # if options.netD != '':\n # decoder.load_state_dict(torch.load(options.netD))\n print(decoder)\n\n # Training settings(criterion set, optimizer set, container generate, make to Variables)\n\n BCE_loss = nn.BCELoss()\n MSE_loss = nn.MSELoss(size_average=False)\n L1_loss = nn.L1Loss(size_average=False)\n\n optimizerD = optim.Adam(decoder.parameters(), betas=(0.5, 0.999), lr=2e-3)\n optimizerE = optim.Adam(encoder.parameters(), betas=(0.5, 0.999), lr=2e-3)\n\n input = torch.FloatTensor(options.batchSize, 3, options.imageSize, options.imageSize)\n if options.cuda:\n encoder.cuda()\n decoder.cuda()\n MSE_loss.cuda()\n BCE_loss.cuda()\n L1_loss.cuda()\n input = input.cuda()\n\n input = Variable(input)\n\n\n\n ## Start Training\n\n transform = transforms.Compose([\n transforms.Scale((120,100)),\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))\n ])\n unorm = visualize_tools.UnNormalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))\n\n dataloader = torch.utils.data.DataLoader(\n DL(options.dataroot, transform, 'train'),\n batch_size=options.batchSize, shuffle=True, drop_last=True)\n dataloader_val = torch.utils.data.DataLoader(\n DL(options.dataroot, transform, 'test'),\n batch_size=options.batchSize, shuffle=True)\n\n win_dict = visualize_tools.win_dict()\n line_win_dict = visualize_tools.win_dict()\n line_win_dict_train_val = visualize_tools.win_dict()\n print(autoencoder_type)\n print(\"Training Start!\")\n\n ep = 0\n if ep != 0:\n # encoder.load_state_dict(torch.load(os.path.join(options.outf, \"face_noFERET_AE_encoder_epoch_%d.pth\") % ep))\n # decoder.load_state_dict(torch.load(os.path.join(options.outf, \"face_noFERET_AE_decoder_epoch_%d.pth\") % ep))\n encoder.load_state_dict(torch.load(os.path.join(options.outf, \"face_AE_pretrain_start_0.pth\") % ep))\n decoder.load_state_dict(torch.load(os.path.join(options.outf, \"face_AE_decoder_epoch_%.pth\") % ep))\n\n for epoch in range(options.iteration):\n train_err = 0\n for i, data in enumerate(dataloader, 0):\n # autoencoder training ====================================================================================\n optimizerE.zero_grad()\n optimizerD.zero_grad()\n\n real_cpu = data\n batch_size = real_cpu.size(0)\n\n original_data = Variable(real_cpu).cuda()\n input.data.resize_(real_cpu.size()).copy_(make_sunglass2(real_cpu))\n #input.data.resize_(real_cpu.size()).copy_(real_cpu)\n\n if autoencoder_type == 'AE':\n z = encoder(input)\n x_recon = decoder(z)\n err_mse = MSE_loss(x_recon, original_data.detach())\n elif autoencoder_type == 'VAE':\n mu, logvar = encoder(input)\n std = torch.exp(0.5 * logvar)\n eps = Variable(torch.randn(std.size()), requires_grad=False).cuda()\n z = eps.mul(std).add_(mu)\n x_recon = decoder(z)\n err_mse = Variational_loss(x_recon, original_data.detach(), mu, logvar)\n\n\n\n\n err_mse.backward(retain_graph=True)\n train_err += float(err_mse.data.mean())\n\n optimizerE.step()\n optimizerD.step()\n #visualize\n print('[%d/%d][%d/%d] Loss: %.4f'% (epoch, options.iteration, i, len(dataloader), err_mse.data.mean()))\n\n # We need a val_image set, not a test image set. So, move them into the dataloader_val for 3 lines\n testImage = torch.cat((unorm(original_data.data[0]),unorm(input.data[0]), unorm(x_recon.data[0])), 2)\n win_dict = visualize_tools.draw_images_to_windict(win_dict, [testImage], [\"Autoencoder\"])\n\n line_win_dict = visualize_tools.draw_lines_to_windict(line_win_dict,\n [err_mse.data.mean(),0],\n ['loss_recon_x','zero'],\n epoch, i, len(dataloader))\n\n #output_test=testImage.view(-1,1,64,192)\n #save_image(output_test, os.path.join(sample_dir,'sampled-{}.png'.format(epoch+1)))\n i=i+1\n train_err = (train_err/i)\n val_err = 0\n\n for i, data in enumerate(dataloader_val, 0):\n # autoencoder training ====================================================================================\n optimizerE.zero_grad()\n optimizerD.zero_grad()\n\n real_cpu = data\n batch_size = real_cpu.size(0)\n\n original_data = Variable(real_cpu).cuda()\n input.data.resize_(real_cpu.size()).copy_(make_sunglass2(real_cpu))\n # input.data.resize_(real_cpu.size()).copy_(real_cpu)\n\n if autoencoder_type == 'AE':\n z = encoder(input)\n x_recon = decoder(z)\n err_mse = MSE_loss(x_recon, original_data.detach())\n elif autoencoder_type == 'VAE':\n mu, logvar = encoder(input)\n std = torch.exp(0.5 * logvar)\n eps = Variable(torch.randn(std.size()), requires_grad=False).cuda()\n z = eps.mul(std).add_(mu)\n x_recon = decoder(z)\n err_mse = Variational_loss(x_recon, original_data.detach(), mu, logvar, epoch)\n\n val_err += float(err_mse.data.mean())\n\n\n #testImage = torch.cat((unorm(original_data.data[0]), unorm(input.data[0]), unorm(x_recon.data[0])), 2)\n #win_dict = LJY_visualize_tools.draw_images_to_windict(win_dict, [testImage], [\"Autoencoder\"])\n ValidImage = unorm(x_recon.data[0])\n #save_image(ValidImage, os.path.join(sample_dir,'val_sample-{}.png'.format(i+1)))\n '''\n line_win_dict = LJY_visualize_tools.draw_lines_to_windict(line_win_dict,\n [err_mse.data.mean(), 0],\n ['loss_recon_x', 'zero'],\n epoch, i, len(dataloader_val))\n '''\n output_test = ValidImage.view(-1, 1, 120, 100)\n save_image(output_test, os.path.join(sample_dir, '{}.png'.format(epoch + 1)))\n\n i=i+1\n val_err = (val_err / i)\n line_win_dict_train_val = visualize_tools.draw_lines_to_windict(line_win_dict_train_val,\n [train_err, val_err, 0],\n ['train_err_per_epoch', 'val_err_per_epoch','zero'],\n 0, epoch, options.iteration)\n\n\n\n # do checkpointing\n if epoch % 100 == 0:\n torch.save(encoder.state_dict(), '%s/pretrain_AE_encoder_epoch_%d.pth' % (options.outf, ep+epoch))\n torch.save(decoder.state_dict(), '%s/pretrain_AE_decoder_epoch_%d.pth' % (options.outf, ep+epoch))\n\n\ndef test_NLDA():\n\n class DL(torch.utils.data.Dataset):\n def __init__(self, path, transform, type):\n random.seed = 1\n self.transform = transform\n self.type = type\n assert os.path.exists(path)\n self.base_path = path\n\n total_file_paths = []\n cur_file_paths = glob.glob(os.path.join(self.base_path, 'AR', '*'))\n total_file_paths = total_file_paths + cur_file_paths\n #cur_file_paths = glob.glob(os.path.join(self.base_path, 'FERET_normal', '*'))\n #total_file_paths = total_file_paths + cur_file_paths\n\n #random.shuffle(total_file_paths)\n #num_of_valset = 792\n\n self.train_file_paths = total_file_paths[:]\n self.test_file_paths = total_file_paths[451:]\n\n def pil_loader(self, path):\n with open(path, 'rb') as f:\n with Image.open(f) as img:\n img = ImageOps.equalize(img)\n return img.resize((80, 80))\n\n def __len__(self):\n if self.type == 'train':\n return len(self.train_file_paths)\n if self.type == 'test':\n return len(self.test_file_paths)\n\n def __getitem__(self, item):\n if self.type == 'train':\n path = self.train_file_paths[item]\n elif self.type == 'test':\n path = self.test_file_paths[item]\n\n img = self.pil_loader(path)\n if self.transform is not None:\n img = self.transform(img)\n return img\n\n path2 = '/home/cheeze/PycharmProjects/NLDA_code/data'\n\n\n transform = transforms.Compose([\n transforms.Scale(80),\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.5, 0.5, 0.5),\n std=(0.5, 0.5, 0.5))\n ])\n\n dataloader_train = torch.utils.data.DataLoader(DL(path2, transform, 'train'), batch_size= 1, shuffle=False,\n drop_last=False)\n\n win_dict = visualize_tools.win_dict()\n line_win_dict = visualize_tools.win_dict()\n line_win_dict_train_val = visualize_tools.win_dict()\n\n default = torch.FloatTensor(1, 3, 80, 80)\n default = default.cuda()\n\n input = torch.FloatTensor(1, 3, 80, 80)\n input = input.cuda()\n input = Variable(input)\n\n unorm = visualize_tools.UnNormalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))\n\n total_train_vector = np.zeros((1, 6401))\n total_test_vector = np.zeros((1, 6401))\n\n for i, data in enumerate(dataloader_train, 0):\n ###### 200\n real_cpu = data\n original_data = Variable(real_cpu).cuda()\n default.data.resize_(real_cpu.size()).copy_(default_image(real_cpu))\n input.data.resize_(real_cpu.size()).copy_(make_sunglass(real_cpu))\n\n testImage = torch.cat((unorm(original_data.data[0]), unorm(input.data[0]), unorm(default.data[0])), 2)\n\n win_dict = visualize_tools.draw_images_to_windict(win_dict, [testImage], [\"testImage\"])\n width = len(input.data[0][0][0])\n height = len(input.data[0][0])\n input_vector = input.data[0][0].reshape(1, width * height)\n input_vector2 = default.data[0][0].reshape(1, width * height)\n\n label = i // 2\n label_info = np.array([label])\n\n input_vector2 = input_vector2.cpu().numpy()\n input_vector = input_vector.cpu().numpy()\n\n input_train_vector2 = np.hstack((input_vector2[0], label_info))\n input_train_vector = np.hstack((input_vector[0], label_info))\n #if (i <= 199):\n total_train_vector = np.vstack((total_train_vector, input_train_vector2))\n\n #if (i > 199):\n total_test_vector = np.vstack((total_test_vector, input_train_vector))\n\n total_train_vector = total_train_vector[1:]\n total_test_vector = total_test_vector[1:]\n NLDA_Class = Null_LDA_for_FSDD.Null_LDA('')\n NLDA_Class.NULL_LDA(total_train_vector)\n\n ###### 792\n\n std_tr = NLDA_Class.std_tr\n mean_tr = NLDA_Class.mean_tr\n w_final = NLDA_Class.w_dis_com\n\n KNNs = KNN_for_NLDA_Python.Face_kNN_Classification(w_final, total_train_vector, total_test_vector, mean_tr, std_tr)\n KNNs.KNN_INIT(1, 1)\n\nif __name__ == \"__main__\" :\n train_ae()\n #test_NLDA()\n #test_img()\n\n\n\n\n\n","sub_path":"2. research/6. NLDA/AE_NLDA_FACE.py","file_name":"AE_NLDA_FACE.py","file_ext":"py","file_size_in_byte":25269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"312830886","text":"import gc\n\n\nclass Solution(object):\n def getIntersectionNode(self, headA, headB):\n if not headA or not headB:\n return None\n savedA, savedB = headA, headB\n len_diff = 0\n while headA.next:\n len_diff += 1\n headA = headA.next\n while headB.next:\n len_diff -= 1\n headB = headB.next\n if headA != headB:\n return\n headA, headB = savedA, savedB\n while len_diff != 0:\n if len_diff > 0:\n headA = headA.next\n len_diff -= 1\n else:\n headB = headB.next\n len_diff += 1\n while headA != headB:\n headA = headA.next\n headB = headB.next\n gc.collect()\n return headA\n","sub_path":"160/160.intersection-of-two-linked-lists.296227971.Accepted.leetcode.python3.py","file_name":"160.intersection-of-two-linked-lists.296227971.Accepted.leetcode.python3.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"255795382","text":"from flask import Flask, render_template\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n piano = [['black' if key in (1,3,6,8,10) else 'white' for key in range(0,12)] for octave in range(4)]\n blacks = [index for index, elem in enumerate([item for sublist in piano for item in sublist]) if elem == 'black']\n return render_template('index.html', piano=piano, blacks=blacks)\n\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":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"24006701","text":"import math\n\n\ndef main():\n while True:\n n = int(input())\n if n == 0:\n break\n\n nums = list(map(int, input().split()))\n mean = sum(nums) / n\n var = sum((s - mean) ** 2 for s in nums) / n\n sd = math.sqrt(var)\n\n print(sd)\n\nif __name__ == \"__main__\":\n main()","sub_path":"Python_codes/p02381/s425998340.py","file_name":"s425998340.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"171549078","text":"# Lesson Chapter 5\n#\n# Ask user for a number and then print whether it is Even or Odd\n#\n# Entry of a Zero ends the game!\n\nwhile 1:\n num_t = input('Enter a number : ')\n\n num = int(num_t)\n\n if num == 0:\n break\n\n rem = num % 2\n\n if rem:\n print(f'{num} is an ODD number!')\n else:\n print(f'{num} is an EVEN number!')\n\nprint('Thanks for playing!!!')\n","sub_path":"practices/ch05_interactive_code/even_odds.py","file_name":"even_odds.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"229658584","text":"# -*- coding: utf-8 -*-\n__author__ = 'Lvv'\n\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nfrom FieldGenerator.FieldBase import FieldBase\n\nclass tuan_gou_jing_dian(FieldBase):\n def __init__(self, datasource, version=1, *args, **kwargs):\n FieldBase.__init__(self, datasource, version)\n self.cheng_shi = None\n self.jing_dian_ming = None\n self.jing_dian_nei_rong = None\n self.jia_ge = None\n self.jia_zhi = None\n self.yi_shou_fen_shu = None\n self.ping_fen = None\n self.ping_lun_tiao_shu = None\n self.you_xiao_qi = None\n self.tuan_gou_lei_xing = None\n self.sheng_shi = None\n self.gong_ying_shang = None\n self.can_tuan_ren_shu = None\n self.bian_hao = None\n self.xing_cheng_tian_shu = None\n self.wang_fan_jiao_tong = None\n self.chu_fa_shi_qi = None\n self.chan_pin_te_se = None\n self.zhe_kou = None\n self.hao_ping_lv = None\n self.fen_lei = None\n self.chu_fa_cheng_shi = None\n self.shou_cang_shu = None\n self.mu_di_di = None\n self.sheng_yu = None\n\n def makemap(self):\n return {\n u'城市': self.cheng_shi,\n u'景点名': self.jing_dian_ming,\n u'景点内容': self.jing_dian_nei_rong,\n u'价格': self.jia_ge,\n u'价值': self.jia_zhi,\n u'已售份数': self.yi_shou_fen_shu,\n u'评分': self.ping_fen,\n u'评论条数': self.ping_lun_tiao_shu,\n u'有效期': self.you_xiao_qi,\n u'团购类型': self.tuan_gou_lei_xing,\n u'省市': self.sheng_shi,\n u'供应商': self.gong_ying_shang,\n u'参团人数': self.can_tuan_ren_shu,\n u'编号': self.bian_hao,\n u'行程天数': self.xing_cheng_tian_shu,\n u'往返交通': self.wang_fan_jiao_tong,\n u'出发时期': self.chu_fa_shi_qi,\n u'产品特色': self.chan_pin_te_se,\n u'折扣': self.zhe_kou,\n u'好评率': self.hao_ping_lv,\n u'分类': self.fen_lei,\n u'出发城市': self.chu_fa_cheng_shi,\n u'收藏数': self.shou_cang_shu,\n u'目的地': self.mu_di_di,\n u'剩余': self.sheng_yu\n }","sub_path":"FieldGenerator/lvyou/jingdian/tuan_gou_jing_dian.py","file_name":"tuan_gou_jing_dian.py","file_ext":"py","file_size_in_byte":2313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"76637082","text":"\n\n#calss header\nclass _COGENT():\n\tdef __init__(self,): \n\t\tself.name = \"COGENT\"\n\t\tself.definitions = [u'A cogent argument, reason, etc. is clearly expressed and persuades people to believe it.']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_cogent.py","file_name":"_cogent.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"339014471","text":"import os\nimport shutil\nimport json\nimport socket\nfrom time import sleep\nfrom docker import APIClient as Client\nfrom docker.types import Mount\nimport docker\nfrom airflow.exceptions import AirflowException\nfrom airflow.plugins_manager import AirflowPlugin\nfrom airflow.models import Variable\nfrom airflow.operators.docker_operator import DockerOperator\nfrom airflow.providers.docker.hooks.docker import DockerHook\nfrom airflow.utils.file import TemporaryDirectory\n\nimport threading\n\ndef _ensure_unicode(s):\n try:\n return s.decode(\"utf-8\")\n except AttributeError:\n return s\n\n\ndef humanize_bytes(bytesize, precision=2):\n \"\"\"\n Humanize byte size figures\n\n https://gist.github.com/moird/3684595\n \"\"\"\n abbrevs = (\n (1 << 50, 'PB'),\n (1 << 40, 'TB'),\n (1 << 30, 'GB'),\n (1 << 20, 'MB'),\n (1 << 10, 'kB'),\n (1, 'bytes')\n )\n if bytesize == 1:\n return '1 byte'\n for factor, suffix in abbrevs:\n if bytesize >= factor:\n break\n if factor == 1:\n precision = 0\n return '%.*f %s' % (precision, bytesize / float(factor), suffix)\n\n\n# this is taken directly from docker client:\n# https://github.com/docker/docker/blob/28a7577a029780e4533faf3d057ec9f6c7a10948/api/client/stats.go#L309\ndef calculate_cpu_percent(d):\n cpu_percent = 0.0\n try:\n cpu_count = len(d[\"cpu_stats\"][\"cpu_usage\"][\"percpu_usage\"])\n cpu_delta = float(d[\"cpu_stats\"][\"cpu_usage\"][\"total_usage\"]) - \\\n float(d[\"precpu_stats\"][\"cpu_usage\"][\"total_usage\"])\n system_delta = float(d[\"cpu_stats\"][\"system_cpu_usage\"]) - \\\n float(d[\"precpu_stats\"][\"system_cpu_usage\"])\n except KeyError:\n return cpu_percent\n\n if system_delta > 0.0:\n cpu_percent = cpu_delta / system_delta * 100.0 * cpu_count\n return cpu_percent\n\n\n# again taken directly from docker:\n# https://github.com/docker/cli/blob/2bfac7fcdafeafbd2f450abb6d1bb3106e4f3ccb/cli/command/container/stats_helpers.go#L168\n# precpu_stats in 1.13+ is completely broken, doesn't contain any values\ndef calculate_cpu_percent2(d, previous_cpu, previous_system):\n # import json\n # du = json.dumps(d, indent=2)\n # logger.debug(\"XXX: %s\", du)\n cpu_percent = 0.0\n cpu_total = float(d[\"cpu_stats\"][\"cpu_usage\"][\"total_usage\"])\n cpu_delta = cpu_total - previous_cpu\n cpu_system = float(d[\"cpu_stats\"][\"system_cpu_usage\"])\n system_delta = cpu_system - previous_system\n online_cpus = d[\"cpu_stats\"].get(\"online_cpus\", len(d[\"cpu_stats\"][\"cpu_usage\"].get(\"percpu_usage\", [None])))\n if system_delta > 0.0:\n cpu_percent = (cpu_delta / system_delta) * online_cpus * 100.0\n return cpu_percent, cpu_system, cpu_total\n\ndef calculate_blkio_bytes(d):\n \"\"\"\n\n :param d:\n :return: (read_bytes, wrote_bytes), ints\n \"\"\"\n bytes_stats = graceful_chain_get(d, \"blkio_stats\", \"io_service_bytes_recursive\")\n if not bytes_stats:\n return 0, 0\n r = 0\n w = 0\n for s in bytes_stats:\n if s[\"op\"] == \"Read\":\n r += s[\"value\"]\n elif s[\"op\"] == \"Write\":\n w += s[\"value\"]\n return r, w\n\n\ndef calculate_network_bytes(d):\n \"\"\"\n\n :param d:\n :return: (received_bytes, transceived_bytes), ints\n \"\"\"\n networks = graceful_chain_get(d, \"networks\")\n if not networks:\n return 0, 0\n r = 0\n t = 0\n for if_name, data in networks.items():\n r += data[\"rx_bytes\"]\n t += data[\"tx_bytes\"]\n return r, t\n\n\ndef graceful_chain_get(d, *args):\n t = d\n for a in args:\n try:\n t = t[a]\n except (KeyError, ValueError, TypeError):\n return None\n return t\n\n\nclass DockerConfigurableOperator(DockerOperator):\n \"\"\"\n This is modified from https://github.com/apache/incubator-airflow/blob/1.8.2/airflow/operators/docker_operator.py\n with the exception that we are able to inject container and host arguments\n before the container is run.\n \"\"\" # noqa\n def __init__(self, container_args=None, host_args=None, qos=True, *args, **kwargs):\n if container_args is None:\n self.container_args = {}\n else:\n self.container_args = container_args\n\n if host_args is None:\n self.host_args = {}\n else:\n self.host_args = host_args\n\n self.qos = qos\n\n super().__init__(*args, **kwargs)\n\n def _read_task_stats(self):\n cpu_total = 0.0\n cpu_system = 0.0\n cpu_percent = 0.0\n unhealthy_count = 0\n while True:\n try:\n x = self.cli.stats(container=self.container['Id'], decode=False, stream=False)\n except Exception:\n sleep(60)\n\n\n blk_read, blk_write = calculate_blkio_bytes(x)\n net_r, net_w = calculate_network_bytes(x)\n try:\n mem_current = x[\"memory_stats\"][\"usage\"]\n mem_total = x[\"memory_stats\"][\"limit\"]\n except KeyError:\n mem_current = 0\n mem_total = 1\n\n try:\n cpu_percent, cpu_system, cpu_total = calculate_cpu_percent2(x, cpu_total, cpu_system)\n except KeyError:\n cpu_percent = calculate_cpu_percent(x)\n\n self.log.info(\"cpu: {:.2f}%, mem: {} ({:.2f}%), blk read/write: {}/{}, net rx/tx: {}/{}\".\n format(cpu_percent,\n humanize_bytes(mem_current),\n (mem_current / mem_total) * 100.0,\n humanize_bytes(blk_read),\n humanize_bytes(blk_write),\n humanize_bytes(net_r),\n humanize_bytes(net_w)))\n\n try:\n info = self.cli.inspect_container(container=self.container['Id'])\n health_status = info['State']['Health']['Status']\n except:\n health_status = 'none'\n\n if health_status == 'healthy' or health_status == 'starting':\n unhealthy_count = 0\n elif health_status == 'unhealthy':\n unhealthy_count += 1\n self.log.info('Health check Failed')\n else:\n if cpu_percent < 5:\n unhealthy_count += 1\n self.log.info('No health status, container is idle, assuming it is unhealthy.')\n else:\n unhealthy_count = 0\n\n if self.qos and unhealthy_count > 5:\n self.log.info('Health check failed 5 times, stop the container')\n self.cli.stop(self.container['Id'], timeout=1)\n\n sleep(60)\n\n # This needs to be updated whenever we update to a new version of airflow!\n def execute(self, context):\n self.log.info('Starting docker container from image %s', self.image)\n\n if ':' not in self.image:\n image = self.image + ':latest'\n else:\n image = self.image\n\n if self.force_pull or len(self.cli.images(name=image)) == 0:\n self.log.info('Pulling docker image %s', image)\n for l in self.cli.pull(image, stream=True):\n output = json.loads(l.decode('utf-8'))\n try:\n self.log.info(\"%s\", output['status'])\n except KeyError:\n pass\n\n self.log.info(\"Mount extra volumes specified by docker composer\")\n container_id = socket.gethostname()\n info = self.cli.inspect_container(container=container_id)\n mounts = info['Mounts']\n for m in mounts:\n if m['Source'] == '/var/run/docker.sock':\n continue\n if os.environ.get(\"VENDOR\", None) != \"LocalDockerCompose\" and m['Source'] == '/tmp':\n continue\n self.log.info(f\"mount {m['Source']} to {m['Destination']}\")\n self.mounts.append(Mount(source=m['Source'], target=m['Destination'], type=m['Type']))\n\n network_id = None\n if os.environ.get(\"VENDOR\", None) == \"LocalDockerCompose\":\n self.log.info(\"Try to connect to the network created by docker composer\")\n networks = info['NetworkSettings']['Networks']\n for n in networks:\n network_id = networks[n].get('NetworkID', None)\n if network_id:\n self.log.info(f\"use network: {n} ({network_id})\")\n break\n\n cpu_shares = int(round(self.cpus * 1024))\n\n with TemporaryDirectory(prefix='airflowtmp') as host_tmp_dir:\n self.environment['AIRFLOW_TMP_DIR'] = self.tmp_dir\n self.mounts.append(\n Mount(source=host_tmp_dir, target=self.tmp_dir, type='bind')\n )\n\n host_args = {\n 'mounts': self.mounts,\n 'cpu_shares': cpu_shares,\n 'mem_limit': self.mem_limit,\n 'device_requests': self.device_requests,\n 'cap_add': [\"IPC_LOCK\", \"SYS_NICE\"],\n 'network_mode': self.network_mode\n }\n host_args.update(self.host_args)\n\n container_args = {\n 'command': self.format_command(self.command),\n 'environment': self.environment,\n 'host_config': self.cli.create_host_config(**host_args),\n 'image': image,\n 'user': self.user,\n 'working_dir': self.working_dir\n }\n\n container_args.update(self.container_args)\n\n self.container = self.cli.create_container(**container_args)\n\n self.cli.start(self.container['Id'])\n\n if network_id:\n self.cli.connect_container_to_network(self.container['Id'], network_id)\n\n log_reader = threading.Thread(\n target=self._read_task_stats,\n )\n\n log_reader.daemon = True\n log_reader.start()\n\n line = ''\n res_lines = []\n for line in self.cli.logs(\n container=self.container['Id'], stream=True):\n if hasattr(line, 'decode'):\n line = line.decode('utf-8')\n line = line.strip()\n res_lines.append(line)\n self.log.info(line)\n\n exit_code = self.cli.wait(self.container['Id'])['StatusCode']\n if exit_code != 0:\n raise AirflowException('docker container failed')\n\n if self.do_xcom_push:\n return res_lines if self.xcom_all else line\n\n\nclass DockerRemovableContainer(DockerConfigurableOperator):\n \"\"\"\n This manually removes the container after it has exited.\n This is *NOT* to be confused with docker host config with *auto_remove*\n AutoRemove is done on docker side and will automatically remove the\n container along with its logs automatically before we can display the logs\n and get the exit code!\n \"\"\"\n def __init__(self,\n remove=True,\n *args, **kwargs):\n self.remove = remove\n super().__init__(*args, **kwargs)\n\n def execute(self, context):\n try:\n return super().execute(context)\n finally:\n if self.cli and self.container and self.remove:\n self.cli.stop(self.container, timeout=1)\n self.cli.remove_container(self.container)\n\n\nclass DockerWithVariablesOperator(DockerRemovableContainer):\n DEFAULT_MOUNT_POINT = '/run/variables'\n\n def __init__(self,\n variables,\n mount_point=DEFAULT_MOUNT_POINT,\n use_gpus=False,\n *args, **kwargs):\n self.variables = variables\n if mount_point:\n self.mount_point = mount_point\n else:\n self.mount_point=self.DEFAULT_MOUNT_POINT,\n\n if use_gpus:\n device_requests = [docker.types.DeviceRequest(driver=\"nvidia\", count=-1, capabilities=[['gpu']])]\n super().__init__(device_requests=device_requests, *args, **kwargs)\n else:\n super().__init__(*args, **kwargs)\n\n def execute(self, context):\n with TemporaryDirectory(prefix='dockervariables') as tmp_var_dir:\n try:\n shutil.copy('/tmp/sysinfo.txt', tmp_var_dir)\n except FileNotFoundError:\n self.log.info('No sysinfo file found, skip')\n for key in self.variables:\n value = Variable.get(key)\n with open(os.path.join(tmp_var_dir, key), 'w') as value_file:\n # import pdb\n # pdb.set_trace()\n value_file.write(value)\n\n if self.variables:\n self.mounts.append(\n Mount(source=tmp_var_dir, target=self.mount_point, type='bind')\n )\n return super().execute(context)\n\n\nclass CustomPlugin(AirflowPlugin):\n name = \"docker_plugin\"\n operators = [DockerRemovableContainer, DockerWithVariablesOperator,\n DockerConfigurableOperator]\n hooks = []\n executors = []\n macros = []\n admin_views = []\n flask_blueprints = []\n menu_links = []\n","sub_path":"plugins/custom/docker_custom.py","file_name":"docker_custom.py","file_ext":"py","file_size_in_byte":13239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"411565530","text":"class ParabolicEstimationTechnique:\n\n @staticmethod\n def estimate(data, x):\n if data is None or len(data) == 0:\n return None\n if len(data) == 1:\n return data[0][1]\n if len(data) == 2:\n return ParabolicEstimationTechnique.estimate2(data[0], data[1], x)\n if len(data) == 3:\n return ParabolicEstimationTechnique.estimate3(data[0], data[1], data[2], x)\n raise NotImplementedError('The length of data is too long')\n\n @staticmethod\n def are_unique(elements):\n seen = set()\n return not any(i in seen or seen.add(i) for i in elements)\n\n @staticmethod\n def estimate3(coordinate1, coordinate2, coordinate3, x):\n \"\"\"\nFits a parabola to the specified coordinates in the specified dimension and estimates the y value at v\n :param coordinate1:\n :param coordinate2:\n :param coordinate3:\n :param x:\n :return:\n \"\"\"\n x1, y1 = coordinate1\n x2, y2 = coordinate2\n x3, y3 = coordinate3\n assert None not in [y1, y2, y3]\n assert ParabolicEstimationTechnique.are_unique([x1, x2, x3, x]), 'The specified x values must differ'\n\n d = (x1 - x2) * (x1 - x3) * (x2 - x3)\n a = (x3 * (y2 - y1) + x2 * (y1 - y3) + x1 * (y3 - y2)) / d\n b = (x3 * x3 * (y1 - y2) + x2 * x2 * (y3 - y1) + x1 * x1 * (y2 - y3)) / d\n c = (x2 * x3 * (x2 - x3) * y1 + x3 * x1 * (x3 - x1) * y2 + x1 * x2 * (x1 - x2) * y3) / d\n return a * x * x + b * x + c\n\n @staticmethod\n def estimate2(coordinate1, coordinate2, x):\n \"\"\"\nFits a line to the specified coordinates in the specified dimension and estimates the y value at v\n :param coordinate1:\n :param coordinate2:\n :param x:\n :return:\n \"\"\"\n x1, y1 = coordinate1\n x2, y2 = coordinate2\n\n assert y1 is not None\n assert y2 is not None\n assert x1 is not x2, 'The specified x values must differ'\n\n a = (y2 - y1) / (x2 - x1)\n b = y1 - a * x1\n return a * x + b\n","sub_path":"Estimation/ParabolicEstimationTechnique.py","file_name":"ParabolicEstimationTechnique.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"368330929","text":"\"\"\"app URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.10/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\n\nfrom rbac.views import AccountViewSet, RoleViewSet, account_sync\n\n# schedule\nfrom schedule.views import SeasonViewSet, SessionViewSet, get_current_season\n# account\nfrom rest_framework import routers\n\nrouter = routers.DefaultRouter()\nrouter.register(r'account', AccountViewSet)\nrouter.register(r'role', RoleViewSet)\nrouter.register(r'season', SeasonViewSet)\nrouter.register(r'session', SessionViewSet)\n# router.register(r'github', GithubViewSet)\n\n# contents\nfrom content.views import ContentViewSet\napi_content_list = ContentViewSet.as_view({'get': 'list'})\napi_content_detail = ContentViewSet.as_view({'get': 'detail'})\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n # schedule\n url(r'^rest/schedule',get_current_season),\n\n # account\n url(r'^account/sync', account_sync),\n\n # contents\n url(r'^api/notice', api_content_list, name='api_content_list'),\n url(r'^api/page/(?P[^/]+)$', api_content_detail, name = 'api_content_detail'),\n\n url(r'^api/', include(router.urls)),\n]\n","sub_path":"tiger/app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"272106716","text":"# -*- coding: utf-8 -*-\n#import standard libraries and third-party libraries\nimport pandas, os, utils, pyprind, multiprocessing, numpy\nimport openpyxl, time, scipy, io, timeit\nfrom copy import copy\nfrom itertools import repeat\nfrom lxml import objectify\nfrom openpyxl import load_workbook\nfrom scipy.sparse import coo_matrix, lil_matrix, csc_matrix, find\nfrom scipy.sparse import linalg\n#import ecoinvent packages\nimport activity_overview, MasterData, dataset_mapping, activityLink_overview\nimport matrix_builder, folder_structure, parameter_overview, simapro_export, RoW_creation\nimport balance_checks, contribution_analysis\nimport spold2_reader as spold2\ndef keep(ie):\n test = True\n if 'market for ' in ie[0]:\n test = False\n elif 'market group' in ie[0]:\n test = False\n elif 'production mix' in ie[0]:\n test = False\n return test\nfolder = r'C:\\python\\DB_versions\\3.3\\Allocation, cut-off\\pkl'\nZ = utils.pkl_load(folder, 'Z')\nindexes = utils.pkl_load(folder, 'indexes')\ndf = []\nfor ie in pyprind.prog_bar(indexes.ie):\n if keep(ie):\n row = indexes.toggle['ie'][ie]\n rows, columns, coefficients = find(Z.getrow(row))\n for col in columns:\n ie_ = indexes.toggle['ie'][col]\n if keep(ie_):\n to_add = dict(zip(['supplying activityName', 'supplying geography', 'supplied product'], ie))\n to_add.update(dict(zip(['demanding activityName', 'demanding geography', 'reference product'], ie_)))\n df.append(to_add)\ndf = utils.list_to_df(df)\ncolumns = ['supplying activityName', 'supplying geography', 'supplied product', \n 'demanding activityName', 'demanding geography', 'reference product']\ndfs = [(df, 'Sheet1', columns)]\nfolder = r'C:\\python\\PEF\\outputs'\nfilename = 'other_than_markets_TO_FILL.xlsx'\nutils.dataframe_to_excel(folder, filename, dfs)","sub_path":"projects/thinkstep_hybrid/other_than_markets.py","file_name":"other_than_markets.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"371819684","text":"\"\"\"\n 迭代器 --> yield\n 练习:exercise05,06\n\"\"\"\nclass SkillManager:\n def __init__(self):\n self.__skills = []\n\n def add_skill(self, skill):\n self.__skills.append(skill)\n\n def __iter__(self):\n for skill in self.__skills:\n print(\"准备\")\n yield skill\n\n # yield 生成迭代器代码的大致规则:\n # 1. 将yield之前的代码定义到__next__方法中\n # 2. 将yield之后的数据作为__next__方法返回值\n\nmanager = SkillManager()\nmanager.add_skill(\"降龙十八掌\")\nmanager.add_skill(\"六脉神剑\")\nmanager.add_skill(\"乾坤大挪移\")\n\n# 迭代自定义对象\nfor skill in manager:\n print(skill)\n\n# iterator = manager.__iter__()\n# while True:\n# try:\n# item = iterator.__next__()\n# print(item) # 降龙十八掌\n# except StopIteration:\n# break\n\n# 现象:调用__iter__方法,但是不执行\n# 调用__next__方法,执行__iter__方法\n# 执行到yield返回,当再次调用__next__方法继续执行__iter__方法\n","sub_path":"month_01/teacher/day16/demo04.py","file_name":"demo04.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"359222767","text":"import argparse\nimport configparser\nimport requests\nimport smtplib\nimport sys\nimport jinja2\nimport mistune\nimport urllib.request\nimport re\nfrom datetime import datetime\nfrom collections import namedtuple\nfrom requests import get\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\n# The latest IP will be stored here: last_ip.txt\nlast_ip_txt_file = 'last_ip.txt'\n\n# Group the email configuration parameters\n# Note the 'from_' to avoid using a reserved Python keyword (from)\nEmailConfig = namedtuple('EmailConfig', ['user', 'password', 'from_', 'to'])\n\n# Get the email templates from hard disk\nEMAIL_TEMPLATE_FILE = 'email_template.md'\nEMAIL_STYLING_FILE = 'email_styling.html'\n\nwith open(EMAIL_TEMPLATE_FILE) as md_file:\n EMAIL_TEMPLATE = md_file.read()\n\nwith open(EMAIL_STYLING_FILE) as html_file:\n EMAIL_STYLING = html_file.read()\n\n\ndef compose_email_body(ip_):\n text_body = EMAIL_TEMPLATE.format(\n **{'text_to_be_added': 'The new IP is: %s' % ip_,\n 'timestamp': str(datetime.now()),\n 'which_script': 'email_when_ip_changes'})\n\n html_content = mistune.markdown(text_body)\n html_body = jinja2.Template(EMAIL_STYLING).render(content=html_content)\n\n return text_body, html_body\n\n\ndef get_ISP_IP():\n ip_check_sites = (\"https://api.ipify.org\", \"http://checkip.dyndns.org\", \"http://ifconfig.me\")\n for ip_site in ip_check_sites:\n try:\n if urllib.request.urlopen(ip_site).getcode() == 200:\n ip_text = re.findall(r'[0-9]+(?:\\.[0-9]+){3}', get(ip_site).text)\n return ip_text[0]\n except:\n return 'error'\n return 'error'\n\n\ndef send_email(email_config, text_body, html_body):\n '''\n Send an email with the text and html body, using the parameters\n configured in email_config\n '''\n msg = MIMEMultipart('alternative')\n msg['Subject'] = 'Home IP update'\n msg['From'] = email_config.from_\n msg['To'] = email_config.to\n\n part_plain = MIMEText(text_body, 'plain')\n part_html = MIMEText(html_body, 'html')\n\n msg.attach(part_plain)\n msg.attach(part_html)\n\n with smtplib.SMTP('smtp.gmail.com', 587) as server:\n server.starttls()\n server.login(email_config.user, email_config.password)\n server.sendmail(email_config.from_, [email_config.to], msg.as_string())\n\n\ndef init():\n parser = argparse.ArgumentParser()\n parser.add_argument(type=argparse.FileType(\n 'r'), dest='config', help='config file')\n parser.add_argument('-o', dest='output', type=argparse.FileType('w'),\n help='output file', default=sys.stdout)\n\n args = parser.parse_args()\n config = configparser.ConfigParser()\n config.read_file(args.config)\n\n email_user = config['EMAIL']['user']\n # Here is a tricky part with Google. Go to https://support.google.com/accounts/answer/185833?hl=en-GB and follow \"How to generate an App password\"\n # Into App passwords -> Select app: Mail, Select device: Other (or whatever you need)\n email_password = config['EMAIL']['password']\n email_from = config['EMAIL']['from']\n email_to = config['EMAIL']['to']\n email_config = EmailConfig(email_user, email_password, email_from, email_to)\n return email_config\n\n\ndef check_ip_change(ip_):\n if ip_ != 'error':\n try:\n with open(last_ip_txt_file, 'r+') as file:\n line = file.read(1)\n if line == [] or line == '':\n return True\n else:\n if ip_ != line:\n return True\n else:\n return False\n except FileNotFoundError:\n return True\n else:\n return False\n\n\nif __name__ == '__main__':\n #Check the new IP against the oldest one\n isp_ip = get_ISP_IP()\n if check_ip_change(isp_ip):\n email_config = init()\n text_body, html_body = compose_email_body(isp_ip)\n send_email(email_config, text_body, html_body)\n # The last_ip file is updated here in order to be sure that the email is sent\n with open(last_ip_txt_file, 'w') as file:\n file.write(isp_ip)\n","sub_path":"email_when_ip_changes.py","file_name":"email_when_ip_changes.py","file_ext":"py","file_size_in_byte":3954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"606874144","text":"from app.extension import db\n\n\nclass ChannelModel(db.Document):\n id = db.StringField(\n required=True\n )\n\n user_num = db.IntField(\n default=1\n )\n\n user = db.ListField(\n db.TupleField(\n db.StringField(),\n db.StringField()\n ),\n default=[],\n required=False\n )\n\n @classmethod\n def select_id(cls, value):\n return cls.query.filter_by(id=value).first()\n","sub_path":"Server/app/models/channel.py","file_name":"channel.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"131587787","text":"# -*- coding: cp1252 -*-\n\n# Panu Partanen Viikko 4 Tehtävä 2\n# GitHub https://github.com/Hea7hcliff/SchoolProgramming/tree/master/Python/Python16A\n\nfrom tkinter import *\n\nclass Application():\n def __init__(self, master):\n frame = Frame(master)\n frame.pack()\n \n self.num1_Label = Label(frame, text = \"Number 1\", width = 15)\n self.num1_Label.grid(row = 0, column = 0, padx = (0,5), pady = (10,10))\n\n self.num1_Entry = Entry(frame, width = 15)\n self.num1_Entry.grid(row = 0, column = 1)\n\n self.num2_Label = Label(frame, text = \"Number 2\", width = 15)\n self.num2_Label.grid(row = 1, column = 0, padx = (0,5), pady = (10,10))\n\n self.num2_Entry = Entry(frame, width = 15)\n self.num2_Entry.grid(row = 1, column = 1)\n \n self.check_Button = Button(frame, text = \"Check\", width = 15, command = self.Bigger)\n self.check_Button.grid(row = 2, column = 1)\n \n self.Bigger_Label = Label(frame, text = \"Bigger\", width = 15)\n self.Bigger_Label.grid(row = 3, column = 0, padx = (0,5), pady = (10,10))\n\n self.Bigger_Entry = Entry(frame, width = 15)\n self.Bigger_Entry.grid(row = 3, column = 1)\n\n def Bigger(self):\n self.Bigger_Entry.delete(0, END)\n\n num1 = int(Entry.get(self.num1_Entry))\n num2 = int(Entry.get(self.num2_Entry))\n \n if(num1 > num2):\n Entry.insert(self.Bigger_Entry, 0, num1)\n elif(num1 < num2):\n Entry.insert(self.Bigger_Entry, 0, num2)\n else:\n Entry.insert(self.Bigger_Entry, 0, \"Yhtäsuuri\")\nroot = Tk()\nroot.title(\"Form1\")\nroot.geometry(\"250x150\")\nUI = Application(root)\nroot.mainloop()","sub_path":"Python/Python16A/Vko4/Tehtävä2/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"371426058","text":"# First we want to get a better sense of where the glove vectors are failing to cast\n# and what we can do about it. So let's print uncastable words and their context\nimport sys\nimport pandas as pd\nimport numpy as np\nimport load_glove as lg\nimport random\nimport pprint\npp = pprint.PrettyPrinter(indent=4)\n\nvector_map = lg.vector_map\n\nnotes = pd.read_csv('./Covid_Data/CNwO_minus_3day_bias.csv')\nnotes['Note Result'] = notes['Note Result'].astype(str)\n\n# List of punctuation\nPUNCTS = \"!\\\"#$%'()*+,-./:;<=>?@[\\]^_`{|}~\"\ndef pad_punctuation(note):\n # Places spaces around puncatuations so they'll be\n # separated by a .split() method and recognized\n # by GloVe\n updated_list = []\n for i in range(len(note)):\n if note[i] in PUNCTS:\n updated_list.extend([\" \", note[i], \" \"])\n else:\n updated_list.append(note[i])\n return ''.join(updated_list)\n\n# Num words to display before and after\nCONTEXT_WINDOW = 3\nfailure_dict = {}\nfor index, row in notes.iterrows():\n # Quickest way to remove punctuation\n # Also removes Dates\n # note_sans_punct = str.translate(row['Note Result'], transtable)\n note = pad_punctuation(row['Note Result'])\n\n note_split = note.split()\n failure_dict[index] = {}\n for i in range(len(note_split)):\n word = note_split[i]\n # If word isn't represented by glove, use 0 vector of same size\n if not word.lower() in vector_map:\n # Calculate word window\n words_back = i - CONTEXT_WINDOW\n words_forward = i + CONTEXT_WINDOW\n if words_back < 0: words_back = 0\n if words_forward >= len(note_split): words_forward = len(note_split)\n\n failure_dict[index][i] = [note_split[i], \" \".join(note_split[words_back:words_forward])]\n if failure_dict[index] == {}: failure_dict.pop(index, None)\n\n\n# Print a randsom sample of errors\nsubset_dict = {}\nrandom.shuffle(failure_dict.keys())\nfor key in failure_dict.keys()[:100]:\n subset_dict[key] = failure_dict[key]\npp.pprint(subset_dict)\n","sub_path":"preprocess_notes.py","file_name":"preprocess_notes.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"104602128","text":"\n# // Time Complexity :O(log n)\n# // Space Complexity :O(1)\n# // Did this code successfully run on Leetcode :Yes\n# // Any problem you faced while coding this :\n\n#Declare variables for left most index and rightmost index of the array.\n# To cover all test cases , an array with only one element also, check if left<=right\n# While left is lesser or equal to right , assign value for mid index, and check if the target given is exactly mid, if so return mid index.\n# If it is not equal to mid index, then check if lies between left index and mid index, and update the values of the indicies respectively.\n# Do the similar calculation if we find that the the target lies between mid and right most index.\n#Here we keep on updating the left and right indices as we find out taht target lies between certain two numbers in array.\n\n\n\n\nclass Solution:\n def search(self, nums: List[int], target: int) -> int:\n r=len(nums)-1\n l=0\n if not nums:\n return -1\n \n while l<=r:\n mid=l+(r-l)//2\n if nums[mid]==target:\n return mid\n if nums[l]<=nums[mid]:\n if nums[l]<=target<=nums[mid]:\n r=mid-1\n else:\n l=mid+1\n elif nums[r]>=nums[mid]:\n if nums[r]>=target>=nums[mid]:\n l=mid+1\n else:\n r=mid-1\n \n return -1\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n# # Test array\n# arr = [ 2, 3, 4, 10, 40 ]\n# x = 10\n \n# # Function call\n# result = binarySearch(arr, 0, len(arr)-1, x)\n","sub_path":"search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"326973763","text":"import plotly as py\nimport plotly.graph_objs as go\nfrom datetime import datetime\n\n\n# -------------pre def\npyplt = py.offline.plot\n\n# 添加数据\nopen_data = [33.0, 33.3, 33.5, 33.0, 34.1]\nhigh_data = [33.1, 33.3, 33.6, 33.2, 34.8]\nlow_data = [32.7, 32.7, 32.8, 32.6, 32.8]\nclose_data = [33.0, 32.9, 33.3, 33.1, 33.1]\ndates = [datetime(year=2016, month=10, day=10),\n datetime(year=2016, month=11, day=10),\n datetime(year=2016, month=12, day=10),\n datetime(year=2017, month=1, day=10),\n datetime(year=2017, month=2, day=10)]\n\n\n# 创建ohlc\ntrace = go.Ohlc(x=dates,\n open=open_data,\n high=high_data,\n low=low_data,\n close=close_data)\n\ndata = [trace]\n\npyplt(data, filename=r'tmp/ohlc_custom_data.html')\n","sub_path":"Chapter05/ohlc_custom_data.py","file_name":"ohlc_custom_data.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"101547536","text":"# coding=utf-8\nimport requests\nimport re\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'\n}\nurl = 'http://www.hkexnews.hk/sdw/search/mutualmarket_c.aspx?t=sh'\nr = requests.get(url,headers = headers)\nprint (r.status_code)\nhtml = r.text\ntitle = re.search('(.*?)',html,re.S)\n\nprint (title.group(1))\ndata = re.search(u'持股:(.*?)',html)\nprint (data)\nprint(html)\n","sub_path":"requets_test1_HK/muban.py","file_name":"muban.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"609556116","text":"\n\n# import paramiko\n\n# import sys,re\n# import time\n# from tool import get_log\n\n# tran = paramiko.Transport(sock=('sas94p',22))\n# tran.connect(username='yaohui.zhu@beigene.com',password='ZYFH137832!')\n# channel = tran.open_session()\n# channel.get_pty()\n# channel.invoke_shell()\n\n\n\n\n\n\n# channel.send('sasen a.sas &\\n')\n\n# sas_programs =['a.sas','b.sas']\n\n\n# def get_pid():\n# result = ''\n# while True:\n# time.sleep(0.2)\n# # res = channel.recv(65535).decode('utf8')\n# res = channel.recv(65535).decode()\n# result += res\n# # if result:\n# # sys.stdout.write(result.strip('\\n'))\n# if res.endswith('# ') or res.endswith('$ '):\n# break\n# result_list = re.findall('[0-9]{4,6}',result)\n# print(result_list[-1])\n\n\n# def run_sas_in_unix(sasnames,source_val):\n# code_num = 2\n\n# path = self.path_unix + '/%s/pgm/tlfs'%source_val\n# pathWin = self.path_init + '/%s/pgm/tlfs'%source_val\n\n\n# if len(sasnames) >= code_num:\n# sascode = 'sas=\"/opt/sas/sas94/compute/SASHome/SASFoundation/9.4/bin/sas_en\";'\n# sascode += 'cd %s;'%path\n# for sas in sasnames:\n# sascode += \"$sas %s; \"%sas\n# f_sh_name = f'sh_{self.sh_num}.sh'\n# shfile = pathWin +'/' + f_sh_name\n\n# with open(shfile,'w') as f:\n# f.write(sascode)\n# self.sh_num += 1\n# self.channel.send(f\"cd {path} ; sh {f_sh_name} &\\n\")\n# pid=get_log()\n# pid_dict[f_sh_name]=pid\n\n# else:\n# sascode = f'cd {path};'\n# for sas in sasnames:\n# self.channel.send(f\"cd {path} ; sasen {sas} &\\n\")\n# pid=get_log()\n# # sascode += \"sasen %s & \\n \"%sas\n# pid_dict[sas]=pid\n# # self.channel.send(\"cd %s ;%s\"%(path,sascode))\n\n# return ''\n\n\n\n\n\n#channel.send('jobs\\n')\n# print(get_log(channel))\n# # print(get())\n# time.sleep(1)\n# channel.send('jobs\\n')\n# print(get_log(channel))\n# time.sleep(4)\n# channel.send('jobs\\n')\n# print(get_log(channel))\n# time.sleep(2)\n# channel.send('jobs\\n')\n# print(get())\n# # time.sleep(2)\n# # channel.send('jobs\\n')\n# # print(get())\n# # time.sleep(5)\n# # channel.send('jobs\\n')\n# # print(get())\n# channel.close()\n\n# import base64\n\n# def lock(char):\n# salt = 'zyh'\n# to_encryption = salt + char\n# to_bytes = base64.b64encode(bytes(to_encryption,'ascii'))\n# new_char = bytes.decode(to_bytes)\n# return new_char\n\n# def unlock(char):\n# to_bytes = str.encode(char)\n# unlock_char = base64.b64decode(to_bytes)\n# final_char = bytes.decode(unlock_char)[3:]\n# return final_char\n # self.tfl_category = int(dic_cols['tfl_category'])\n # # self.population = 4 -1\n # self.titles = int(dic_cols['titles'])\n # self.output_number = int(dic_cols['output_number'])\n # self.base_output_name = int(dic_cols['base_output_name'])\n # self.source_program_name = int(dic_cols['source_program_name'])\n # self.source_data = int(dic_cols['source_data'])\n # self.source_programmer = int(dic_cols['source_programmer'])\n # self.qc_programmer = int(dic_cols['qc_programmer'])\n # self.qc_program_name = int(dic_cols['qc_program_name'])\n# import xlrd\n# _p = r\"Z:\\bgcrh\\build\\bgb_3111\\bgb_3111_au_003\\csr_20190708_wm\\dev\\metadata\"\n\n# _f = \"prgmtrack_bgb3111_au003_csr_20190708_wm.xlsx\"\n\n\n# excel_path = r'C:\\Users\\yaohui.zhu\\OneDrive - BeiGene\\AU003/prgmtrack_bgb3111_au003_csr_20190708_wm.xlsx'\n# print(excel_path)\n# # excel_path =_p +'/'+_f\n# # print(excel_path)\n# book = xlrd.open_workbook(excel_path)\n# table = book.sheet_by_name(\"TFL\")\n\n\n# row_data = table.row_values(0, start_colx=0, end_colx=None)\n\n# print(row_data)\n# def define(row_data,col_name,col_char):\n# n=0\n# dic={}\n# for col in row_data:\n\n# if col.lower().find(col_char) > -1:\n# num=n\n# n +=1\n# dic[col_name]=num\n# return dic\n\n\n# dict_col_define={\"tfl_category\":\"category\"\n# ,\"titles\":\"title\"\n# ,\"output_number\":\"number\"\n# ,\"base_output_name\":\"base output\"\n# ,\"source_program_name\":\"source program name\"\n# ,\"source_data\":\"source data\"\n# ,\"source_programmer\":\"source programmer\"\n# ,\"qc_programmer\":\"qc programmer\"\n# ,\"qc_program_name\":\"qc program name\"\n# }\n# final={}\n# for keys in dict_col_define.keys():\n# aa=define(row_data,keys,dict_col_define[keys])\n# final.update(aa)\n# print(final)\n\n# print(table.ncols)\n\n# from path import myPath\n# dirname=\"Z:\\\\bgcrh\\\\build\\\\bgb_3111\\\\bgb_3111_au_003\\\\csr_20190708_wm\\\\dev\\\\metadata\"\n# excel_path_2 = myPath(init_path=dirname)\n# path_init = excel_path_2.getPathOfWin(type='init')\n# print(path_init)\n# dirname = excel_path_2.getPathOfWin(type='org')\n# path_unix = excel_path_2.transPathToUnix()\n\n# print(dirname)\n\n\n\n\n\n\n\n\n\n\n#get all the files in a folder\n# import os,re\n# def findFile(path_list,type):\n# file_list=[]\n# for filedir in path_list:\n# temp_list = []\n# for root, dirs, files in os.walk(filedir):\n# for filespath in files :\n# if str(filespath).endswith('%s'%type):\n# mtime = os.path.getmtime(os.path.join(root, filespath))\n# file = filespath[:-4]\n# temp_list.append([file,mtime])\n# file_list += temp_list\n# return file_list if file_list else []\n\n# path_list=['Z:\\\\bgcrh\\\\build\\\\bgb_a317\\\\bgb_a317_001']\n# now = findFile(path_list,type='xlsx')\n# print(now)\n\n\n# get dependentency of code\n\n\n\nimport paramiko\n\nimport sys,re\nimport time,os\nfrom path import myPath\n\n\nclass dependency():\n def __init__(self):\n\n self.username='yaohui.zhu@beigene.com'\n self.password='ZYFH137832!'\n def connect(self):\n self.client = paramiko.SSHClient()\n self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n self.client.connect('sas94p', port=22, username=self.username, password=self.password)\n\n def check(self,path,macro):\n excel_path_2 = myPath(init_path=path)\n path_tools = excel_path_2.transPathToUnix()\n self.new_path=path_tools+'/dev/pgm/tlfs'\n time1=time.time()\n command=f\"cd {self.new_path};grep -E '%{macro}\\s{{0,}};|%{macro}\\s{{0,}}\\(' *.sas\"\n print(command)\n stdin,stdout,stderr=self.client.exec_command(command)\n out=stdout.read().decode()\n error=stderr.read().decode()\n log_with_error = out.split('\\n')\n log_names=[]\n for i in log_with_error:\n aa=i.split(':')[0]\n if aa != '':\n log_names.append(aa)\n log_names=list(set(log_names))\n time2=time.time()\n # print(log_names)\n print(len(log_names))\n # print(error)\n s=time2-time1\n print(str(s))\n self.temp_sasnames=log_names\n return log_names\n def get_tfls(self):\n return ' '.join(self.temp_sasnames)\n def get_sasnames(self):\n return getTime(filePath=self.new_path,type=\".sas\")\n\ndef getTime(filePath,type):\n temp_list = []\n for filename in os.listdir(filePath):\n if str(filename).endswith('%s'%type):\n # mtime = os.path.getmtime(os.path.join(filePath, filename))\n nn=len(type)\n file = filename[:-nn]\n temp_list.append(file)\n return temp_list\n\n\n\npath=r'Z:\\bgcrh\\build\\bgb_3111\\bgb_3111_302\\csrb_201908\\tools'\n\nmacro='ms_sp_dev_pop'\n\n\nlist_macro=getTime(filePath=path,type=\".sas\")\n\ntest = dependency()\ntest.connect()\n\nhtml = '''\n\n'''\nhtml +=''\nhtml += ''\nfor i in list_macro:\n try:\n sasnames_list=test.check(path,i)\n\n sasnames=test.get_tfls()\n\n except Exception as e:\n\n print(e)\n pass\n\n html += ''\n html += '' + ''\n html += ''\n\nhtml +='
ToolsPrograms
' + i + '' + sasnames + '
'\n\n\nwith open('test.html','w') as f:\n f.write(html)\n\n\n# test(path,macro)\n# a = '1.sas'\n# b= a[:-4] if a.endswith('.sas') else a\n# print(b)\n\n\n\n# import time\n# import timeout_decorator\n\n# @timeout_decorator.timeout(5,use_signals=False)\n\n# def mytest():\n# print(\"Start\")\n# for i in range(1,10):\n# time.sleep(1)\n# print(\"{} seconds have passed\".format(i))\n\n# if __name__ == '__main__':\n# mytest()\n\n\n# from func_timeout import func_timeout, FunctionTimedOut,func_set_timeout\n# import time\n\n# @func_set_timeout(10)\n# def myFunction():\n# for i in range(100):\n# time.sleep(1)\n# print(i)\n\n# myFunction()\n\n\n# import os\n# from PyPDF2 import PdfFileReader, PdfFileWriter\n# import time\n\n# pdf = PdfFileReader(open('merge.pdf', \"rb\"))\n# extractedText = pdf.getPage(0).extractText()\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":9376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"284479692","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\nimport sys\nimport serial\nimport time\nimport threading\nfrom threading import Thread\n\n\ndef stdout_print(*args, **kwargs):\n print(*args, file=sys.stdout, **kwargs)\n\n\ndef stdout_flush():\n sys.stdout.flush()\n\n\ndef trace(*args, **kwargs):\n print(*args, file=sys.stderr, sep='\\t', **kwargs)\n\n\ndef info(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\n\nclass PortReader(Thread):\n def __init__ (self, port):\n Thread.__init__(self)\n self.port = port\n self._stop = threading.Event()\n self._done = threading.Event()\n self._go = threading.Event()\n\n def exchange(self, s):\n self._result = ''\n port.write(s)\n port.write(chr(10))\n self._go.set()\n self._done.wait()\n self._done.clear()\n return self._result\n\n def run(self):\n while not self.stopped():\n self._go.wait()\n if self.stopped():\n break\n while True:\n c = port.read(1)\n if c == chr(10):\n self._done.set()\n break\n else:\n self._result = self._result + c\n self._go.clear()\n\n def stop(self):\n self._stop.set()\n self._go.set()\n\n def stopped(self):\n return self._stop.isSet()\n\n\nclass I2CBridge:\n def __init__(self, port_reader):\n self.port_reader = port_reader\n\n def command(self, c):\n # print('Sending', c)\n result = self.port_reader.exchange(c).strip()\n if result.strip() == 'ERROR':\n info('Command ' + c + ' failed: returned [' + result + ']')\n else:\n return result\n\n def init_speed(self):\n self.command('')\n self.command('I1')\n\n def read_event(self):\n event_str = self.command('%02X?01' % ((0x10) * 2))\n if event_str:\n event = int(event_str, 16)\n return event if event !=0 else None\n\n\ndef run(port):\n port_reader = PortReader(port)\n port_reader.start()\n i2c_bridge = I2CBridge(port_reader)\n\n try:\n while True:\n line = i2c_bridge.read_event()\n if line:\n print(line)\n finally:\n port_reader.stop()\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n info(\"Arguments: \")\n sys.exit()\n\n port = serial.Serial()\n port.port = sys.argv[1]\n port.baudrate = int(sys.argv[2])\n port.timeout = 1.0\n port.open()\n\n try:\n run(port)\n finally:\n port.close()\n sys.exit()\n","sub_path":"target/zynthian__hid/software/read_events.py","file_name":"read_events.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"141793361","text":"import torch\nimport torch.nn as nn\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader\nfrom models import ConvAutoencoder, ImgDataset\nimport argparse\nimport time\nimport os\n\n\ndef ensure_folder(folder):\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n\ndef time_msec():\n return int(round(time.time() * 1000))\n\n\ndef train(input_folder, output_folder, lr=0.001, epochs=40, img_format='.png'):\n ensure_folder(output_folder)\n model = ConvAutoencoder()\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n model = model.to(device)\n transform = transforms.ToTensor()\n train_folder = input_folder + '/train'\n print(f\"Create train dataset from - {train_folder}\")\n train_data = ImgDataset(train_folder, transform, device, img_format)\n print(f\"Train dataset size - {len(train_data)}\")\n # Create training\n num_workers = 0\n # how many samples per batch to load\n batch_size = 20\n # prepare data loaders\n print(f\"Create dataloader batches={batch_size} and workers={num_workers}\")\n train_loader = DataLoader(train_data, batch_size=batch_size, num_workers=num_workers, shuffle=True)\n\n # specify loss function\n criterion = nn.BCELoss()\n # specify loss function\n optimizer = torch.optim.Adam(model.parameters(), lr)\n # number of epochs to train the model\n n_epochs = epochs\n\n for epoch in range(1, n_epochs + 1):\n # monitor training loss\n train_loss = 0.0\n\n ###################\n # Train the model #\n ###################\n model.train()\n train_loss = 0\n for images in train_loader:\n # _ stands in for labels, here\n # no need to flatten images\n # clear the gradients of all optimized variables\n optimizer.zero_grad()\n # forward pass: compute predicted outputs by passing inputs to the model\n outputs, encoder_output = model(images, encoder_mode=False)\n # calculate the loss\n loss = criterion(outputs, images)\n # backward pass: compute gradient of the loss with respect to model parameters\n loss.backward()\n # perform a single optimization step (parameter update)\n optimizer.step()\n # update running training loss\n train_loss += loss.item() * images.size(0)\n\n # print avg training statistics\n train_loss = train_loss / len(train_loader)\n print('Epoch: {} \\tTraining Loss: {:.6f}'.format(epoch, train_loss))\n\n ###################\n # Test the model #\n ###################\n model.eval()\n test_folder = input_folder + '/test'\n test_data = ImgDataset(test_folder, transform, device, img_format)\n test_loader = DataLoader(test_data, batch_size=batch_size, num_workers=num_workers)\n eval_loss = 0\n for images in test_loader:\n # forward pass: compute predicted outputs by passing inputs to the model\n outputs, x_encoders = model(images, encoder_mode=False)\n # calculate the loss\n loss = criterion(outputs, images)\n # update running training loss\n eval_loss += loss.item() * images.size(0)\n\n # print avg evaluation statistics\n eval_loss = eval_loss / len(test_loader)\n print('\\tEvaluation Loss: {:.6f}'.format(eval_loss))\n\n # Save model\n model_root = output_folder + '/conv_autoencoder_' + str(time_msec()) + '.pt'\n print(f\"Saving trained model to: {model_root}\")\n torch.save(model.state_dict(), model_root)\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Train conv autoencoder on dataset.'\n 'Must have train and test dataset folders'\n ' located in input')\n parser.add_argument('input', metavar='input', type=str,\n help='Source folder full path.')\n parser.add_argument('output', metavar='output', type=str,\n help='Destination folder full path.')\n parser.add_argument('lr', metavar='lt', type=str,\n help='Learning rate')\n parser.add_argument('epochs', metavar='epochs', type=str,\n help='Number of training epochs.')\n\n args = parser.parse_args()\n input_folder = args.input\n output_folder = args.output\n lr = args.lr\n epochs = args.epochs\n\n train(input_folder, output_folder, float(lr), int(epochs))\n\n\nif __name__ == '__main__':\n print(\"<<<<<<<<<<<<<<< Start training >>>>>>>>>>>>>>>>>\")\n main()\n","sub_path":"models/conv_autoencoder/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"401937621","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom utils.timer import Timer\nfrom tensorboardX import SummaryWriter\nimport torchvision.utils as vutils\n#log_dir = '../visual_featuremaps'\n#writer = SummaryWriter(log_dir=log_dir)\n_a = {'conv1': Timer(), 'conv2': Timer(), 'ince': Timer(), 'conv3': Timer(), 'conv4': Timer(), 'pre': Timer()}\n\n\nclass BasicConv2d(nn.Module):\n\n def __init__(self, in_channels, out_channels, **kwargs):\n super(BasicConv2d, self).__init__()\n self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs)\n self.bn = nn.BatchNorm2d(out_channels, eps=1e-5)\n\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n return F.relu(x, inplace=True)\n\nclass conv_dw(nn.Module):\n\n def __init__(self, in_channels, out_channels,stride, **kwargs):\n super(conv_dw, self).__init__()\n self.conv3_3 = nn.Conv2d(in_channels, in_channels, 3, stride, 1, groups=in_channels, bias=False)\n self.bn3_3= nn.BatchNorm2d(in_channels)\n self.re3_3 = nn.ReLU(inplace=True)\n self.conv1_1 = nn.Conv2d(in_channels, out_channels, 1, 1, 0, bias=False)\n self.bn1_1 = nn.BatchNorm2d(out_channels)\n self.re1_1 = nn.ReLU(inplace=True)\n\n def forward(self, x):\n x = self.conv3_3(x)\n x = self.bn3_3(x)\n x = self.re3_3(x)\n x = self.conv1_1(x)\n x = self.bn1_1(x)\n x = self.re1_1(x)\n return x\n\nclass conv_1_1(nn.Module):\n\n def __init__(self, in_channels, out_channels, **kwargs):\n super(conv_1_1, self).__init__()\n\n self.conv1_1 = nn.Conv2d(in_channels, out_channels, 1, 1, 0, bias=False)\n self.bn1_1 = nn.BatchNorm2d(out_channels)\n self.re1_1 = nn.ReLU(inplace=True)\n\n def forward(self, x):\n\n x = self.conv1_1(x)\n x = self.bn1_1(x)\n x = self.re1_1(x)\n return x\n\n\n\nclass CRelu(nn.Module):\n\n def __init__(self, in_channels, out_channels, **kwargs):\n super(CRelu, self).__init__()\n self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs)\n self.bn = nn.BatchNorm2d(out_channels, eps=1e-5)\n\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n #x = torch.cat([x, -x], 1)\n x = F.relu(x, inplace=True)\n return x\n\n\nclass FaceBoxes(nn.Module):\n\n def __init__(self, phase, size, num_classes):\n super(FaceBoxes, self).__init__()\n self.phase = phase\n self.num_classes = num_classes\n print(num_classes)\n self.size = size\n\n self.conv1 = CRelu(1, 24, kernel_size=7, stride=4, padding=3)\n self.conv2 = CRelu(24, 48, kernel_size=5, stride=2, padding=2)\n\n self.conv2_1 = conv_dw(48, 64,1)\n self.conv2_2 = conv_dw(64, 128, 1)\n self.conv2_3 = conv_dw(128, 256, 1)\n\n\n self.conv3_1 = conv_dw(256, 256, 1)\n self.conv3_2 = conv_dw(256, 512, 2)\n\n self.conv4_1 = conv_dw(512, 256, 1)\n self.conv4_2 = conv_dw(256, 512, 2)\n\n self.loc, self.conf = self.multibox(self.num_classes)\n\n if self.phase == 'test':\n # print('????????')\n self.softmax = nn.Softmax()\n\n if self.phase == 'train':\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n if m.bias is not None:\n nn.init.xavier_normal_(m.weight.data)\n m.bias.data.fill_(0.02)\n else:\n m.weight.data.normal_(0, 0.01)\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n \n def multibox(self, num_classes):\n loc_layers = []\n conf_layers = []\n\n loc_layers += [nn.Conv2d(256, 21 * 4, kernel_size=3, padding=1)]\n conf_layers += [nn.Conv2d(256, 21 * num_classes, kernel_size=3, padding=1)]\n loc_layers += [nn.Conv2d(256, 1 * 4, kernel_size=3, padding=1)]\n conf_layers += [nn.Conv2d(256, 1 * num_classes, kernel_size=3, padding=1)]\n loc_layers += [nn.Conv2d(256, 1 * 4, kernel_size=3, padding=1)]\n conf_layers += [nn.Conv2d(256, 1 * num_classes, kernel_size=3, padding=1)]\n return nn.Sequential(*loc_layers), nn.Sequential(*conf_layers)\n\n def forward(self, x):\n\n sources = list()\n loc = list()\n conf = list()\n detection_dimension = list()\n\n _a['conv1'].tic()\n x = self.conv1(x)\n x = F.max_pool2d(x, kernel_size=3, stride=2, padding=1, ceil_mode=True)\n _a['conv1'].toc()\n\n _a['conv2'].tic()\n x = self.conv2(x)\n #x = F.max_pool2d(x, kernel_size=3, stride=2, padding=1, ceil_mode=True)\n _a['conv2'].toc()\n\n _a['ince'].tic()\n\n x = self.conv2_1(x)\n x = self.conv2_2(x)\n x = self.conv2_3(x)\n #x = self.conv2_4(x)\n #print(x.shape)\n\n #x1 = x.transpose(0, 1) # C£¬B, H, W ---> B£¬C, H, W\n #img_grid1 = vutils.make_grid(x1, normalize=True, scale_each=True, nrow=2) # B£¬C, H, W\n #writer.add_image( '1_feature_maps', img_grid1, global_step=666)\n\n _a['ince'].toc()\n\n detection_dimension.append(x.shape[2:])\n sources.append(x)\n _a['conv3'].tic()\n x = self.conv3_1(x)\n x = self.conv3_2(x)\n #print(x.shape)\n _a['conv3'].toc()\n detection_dimension.append(x.shape[2:])\n sources.append(x)\n\n _a['conv4'].tic()\n x = self.conv4_1(x)\n x = self.conv4_2(x)\n _a['conv4'].toc()\n #print(x.shape)\n\n detection_dimension.append(x.shape[2:])\n sources.append(x)\n _a['pre'].tic()\n detection_dimension = torch.tensor(detection_dimension, device=x.device)\n\n for (x, l, c) in zip(sources, self.loc, self.conf):\n loc.append(l(x).permute(0, 2, 3, 1).contiguous())\n conf.append(c(x).permute(0, 2, 3, 1).contiguous())\n\n loc = torch.cat([o.view(o.size(0), -1) for o in loc], 1)\n\n conf = torch.cat([o.view(o.size(0), -1) for o in conf], 1)\n\n _a['pre'].toc()\n if self.phase == \"test\":\n output = (loc.view(loc.size(0), -1, 4),\n self.softmax(conf.view(-1, self.num_classes)),\n detection_dimension)\n # print('conv1',_a['conv1'].average_time,'conv2',_a['conv2'].average_time,'ince',_a['ince'].average_time,'conv3',_a['conv3'].average_time,'conv4',_a['conv4'].average_time,'pre',_a['pre'].average_time)\n else:\n output = (loc.view(loc.size(0), -1, 4),\n conf.view(conf.size(0), -1, self.num_classes),\n detection_dimension)\n # print('conv1',_a['conv1'].average_time,'conv2',_a['conv2'].average_time,'ince',_a['ince'].average_time,'conv34',_a['conv34'].average_time)\n return output\n#writer.close()","sub_path":"faceboxesMobile.py","file_name":"faceboxesMobile.py","file_ext":"py","file_size_in_byte":6888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"171725870","text":"import sys\n\nfrom PyQt5.Qt import QApplication, QWidget, QStackedLayout, QProxyStyle, QStyle\n\nfrom ui.postprocessing import PostProcessing\nfrom ui.videorecognition import VideoRecognition\n\n\nclass F1TProxyStyle(QProxyStyle):\n def pixelMetric(self, QStyle_PixelMetric, option=None, widget=None):\n if QStyle_PixelMetric == QStyle.PM_SmallIconSize:\n return 60\n else:\n return QProxyStyle.pixelMetric(self, QStyle_PixelMetric, option, widget)\n\n\nclass Window(QWidget):\n def __init__(self, application):\n super(QWidget, self).__init__()\n self.application = application\n\n self.postprocessing = PostProcessing()\n self.videorecognition = VideoRecognition()\n\n self.windowlayout = QStackedLayout(self)\n self.windowlayout.setSpacing(0)\n self.windowlayout.setContentsMargins(0, 0, 0, 0)\n self.windowlayout.addWidget(self.postprocessing)\n self.windowlayout.addWidget(self.videorecognition)\n\n self.windowlayout.setCurrentIndex(0)\n\n def switch_environment(self, new_index):\n self.windowlayout.setCurrentIndex(new_index)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n f1tstyle = F1TProxyStyle('Windows')\n app.setStyle(f1tstyle)\n window = Window(app)\n window.setWindowTitle('F1Telemetry')\n window.show()\n app.exec()\n","sub_path":"f1telemetry/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"526388690","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nimport paho.mqtt.client as paho\nimport json\nimport time\nimport uuid\nimport threading\nimport Queue\n\n# El codigo del drone tomado desde https://github.com/sethyx/py-minidrone\nfrom pyMiniDrone import minidrone\nfrom pyMiniDrone import dronedict\n\nMQTT_SERVER = 'localhost'\nDRONE_TOPIC = 'rcr/RollerSpider'\nSPEAK_TOPIC = 'rcr/Speak'\n\nconnected = False\nmutex = threading.Lock()\nmessages = Queue.Queue( 1 )\n\nDRONEMAC = 'E0:14:CD:17:3D:4E'\n\ndef refresh_data( t, data ):\n global connected, mutex\n\n print( \"Refresh Data:\", t, data )\n if t == 4:\n if( data == 'y' ):\n mutex.acquire()\n connected = True\n mutex.release()\n sendToSpeak( 'Drone conectado' )\n else:\n if( connected ):\n mutex.acquire()\n connected = False\n mutex.release()\n sendToSpeak( 'Drone desconectado' )\n\ndef sendToSpeak( msg ):\n global mqtt_client, SPEAK_TOPIC\n\n mqtt_client.publish( SPEAK_TOPIC, msg )\n\ndef mqtt_on_message( client, userdata, message ):\n global messages\n\n # si no se ha procesado el ultimo mensaje lo eliminamos\n try:\n messages.get_nowait()\n except Queue.Empty:\n pass\n\n # agregamos el mensaje\n try:\n messages.put_nowait( message )\n except Queue.Full:\n pass\n\ndef mqtt_on_connect( client, arg1, arg2, arg3 ):\n global DRONE_TOPIC, MQTT_SERVER\n\n client.subscribe( DRONE_TOPIC )\n print( \"[DroneRollerSpider] Esperando en %s - %s\" % ( MQTT_SERVER, DRONE_TOPIC ) )\n\ndef main():\n global mqtt_client, MQTT_SERVER, messages, mutex\n\n print( '[DroneRollerSpider] Iniciando aplicación' )\n mqtt_client = paho.Client( 'DroneRollerSpider-' + uuid.uuid4().hex )\n mqtt_client.on_connect = mqtt_on_connect\n mqtt_client.on_message = mqtt_on_message\n mqtt_client.connect( MQTT_SERVER, 1883 )\n mqtt_client.loop_start()\n drone = None\n abort = False\n try:\n drone = minidrone.MiniDrone( mac=DRONEMAC, callback=refresh_data )\n sendToSpeak( 'Control del drone iniciado' )\n except Exception as e:\n sendToSpeak( ' No existe puerto de comunicaciones con el drone' )\n abort = True\n while( not abort ):\n message = messages.get()\n print( \"[DroneRollerSpider] Mensaje recibido:\", message.payload )\n\n mutex.acquire()\n isConnected = connected\n mutex.release()\n\n if( message.payload == \"exit\" ):\n if( isConnected ):\n drone.land()\n time.sleep( 3 )\n drone.disconnect()\n drone.die()\n break\n\n if( not isConnected ):\n if( message.payload == 'connect' ):\n drone.connect()\n else:\n if( message.payload == 'disconnect' ):\n drone.land()\n time.sleep( 3 )\n drone.disconnect()\n elif( message.payload == 'takeoff' ):\n drone.takeoff()\n elif( message.payload == 'land' ):\n drone.land()\n elif( message.payload == 'turn_left' ):\n drone.turn_left()\n elif( message.payload == 'turn_right' ):\n drone.turn_right()\n elif( message.payload == 'move_left' ):\n drone.move_left()\n elif( message.payload == 'move_right' ):\n drone.move_right()\n elif( message.payload == 'move_fw' ):\n drone.move_fw()\n elif( message.payload == 'move_bw' ):\n drone.move_bw()\n\n sendToSpeak( 'Control del drone finalizado' )\n mqtt_client.loop_stop()\n print( '[DroneRollerSpider] Finalizando aplicación' )\n\n#--\nmain()\n","sub_path":"DroneRollerSpider/DroneRollerSpider.py","file_name":"DroneRollerSpider.py","file_ext":"py","file_size_in_byte":3793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"423526635","text":"from ._Base import _Base\n\n\nclass Int(_Base):\n \"\"\"\n Работа с int\n \"\"\"\n\n def __init__(self, min=None, max=None, *args, **kwargs):\n # Максимальное значение\n self.max = max\n # Минимальное значение\n self.min = min\n\n super().__init__(*args, **kwargs)\n\n def _validate(self, obj, value):\n \"\"\"\n Проверяем корректность входных данных\n \"\"\"\n if self.max is not None and int(value) > self.max:\n raise ValueError('Value is longer than the max')\n if self.min is not None and int(value) < self.min:\n raise ValueError('Value is less than the min')\n\n return int(value)\n\n def get_db_type(self):\n if self.db_type:\n return self.db_type\n return 'bigint'\n","sub_path":"LightMagic/types/Int.py","file_name":"Int.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"218573386","text":"import os, sys, queue, pickle, time, inspect\nimport pyeq3\n\nimport matplotlib # ensure this dependency imports for later use in fitting results\n\nimport tkinter as tk\nimport tkinter.ttk\nfrom tkinter import messagebox as tk_mbox\nimport tkinter.scrolledtext as tk_stxt\n\nimport DataForControls as dfc\nimport FittingThread\n\n\nclass InterfaceFrame(tk.Frame):\n \n def __init__(self, parent):\n tk.Frame.__init__(self, parent)\n \n self.queue = queue.Queue()\n\n self.equationSelect_2D = tk.IntVar()\n self.equationSelect_3D = tk.IntVar()\n self.fittingTargetSelect_2D = tk.IntVar()\n self.fittingTargetSelect_3D = tk.IntVar()\n\n # ROW 0 - empty labels as visual buffers\n row, col = (0, 0) # left edge\n l = tk.Label(self, text=\" \")\n l.grid(column=col, row=row)\n row, col = (0, 2) # center\n l = tk.Label(self, text=\" \")\n l.grid(column=col, row=row)\n row, col = (0, 4) # right edge\n l = tk.Label(self, text=\" \")\n l.grid(column=col, row=row)\n \n # ROW 1 - text data entry labels\n # no \"self\" needed as no later references exist\n row, col = (1, 1)\n l = tk.Label(self, text=\"--- 2D Data Text Editor ---\", font=\"-weight bold\")\n l.grid(column=col, row=row)\n \n row, col = (1, 3)\n l = tk.Label(self, text=\"--- 3D Data Text Editor ---\", font=\"-weight bold\")\n l.grid(column=col, row=row)\n\n # ROW 2 - text data input, no line wrap\n row, col = (2, 1)\n self.text_2D = tk_stxt.ScrolledText(self, width=45, height=12, wrap=tk.NONE)\n self.text_2D.insert(tk.END, dfc.exampleText_2D) # inital text data\n self.text_2D.grid(column=col, row=row, sticky=(tk.N, tk.W, tk.E, tk.S))\n\n row, col = (2, 3)\n self.text_3D = tk_stxt.ScrolledText(self, width=45, height=12, wrap=tk.NONE)\n self.text_3D.insert(tk.END, dfc.exampleText_3D) # inital text data\n self.text_3D.grid(column=col, row=row, sticky=(tk.N, tk.W, tk.E, tk.S))\n\n # ROW 3 - empty label as visual buffer\n row, col = (3, 0)\n l = tk.Label(self, text=\" \")\n l.grid(column=col, row=row)\n\n # ROW 4 - equation selection labels\n # no \"self\" needed as no later references exist\n row, col = (4, 1)\n l = tk.Label(self, text=\"--- Standard 2D Equations ---\", font=\"-weight bold\")\n l.grid(column=col, row=row)\n \n row, col = (4, 3)\n l = tk.Label(self, text=\"--- Standard 3D Equations ---\", font=\"-weight bold\")\n l.grid(column=col, row=row)\n\n # ROW 5 - equation selection\n row, col = (5, 1)\n f = tk.Frame(self)\n f.grid(column=col, row=row)\n self.cb_Modules2D = tk.ttk.Combobox(f, state='readonly')\n self.cb_Modules2D['values'] = sorted(list(dfc.eq_od2D.keys()))\n self.cb_Modules2D.bind(\"<>\", self.moduleSelectChanged_2D)\n self.cb_Modules2D.set('Polynomial')\n self.cb_Modules2D.pack(anchor=tk.W)\n\n self.cb_Equations2D = tk.ttk.Combobox(f, state='readonly')\n self.cb_Equations2D['width'] = 50\n self.cb_Equations2D['values'] = sorted(list(dfc.eq_od2D['Polynomial'].keys()))\n self.cb_Equations2D.set('1st Order (Linear)')\n self.cb_Equations2D.pack(anchor=tk.W)\n\n row, col = (5, 3)\n f = tk.Frame(self)\n f.grid(column=col, row=row) \n self.cb_Modules3D = tk.ttk.Combobox(f, state='readonly')\n self.cb_Modules3D['values'] = sorted(list(dfc.eq_od3D.keys()))\n self.cb_Modules3D.bind(\"<>\", self.moduleSelectChanged_3D)\n self.cb_Modules3D.set('Polynomial')\n self.cb_Modules3D.pack(anchor=tk.W)\n\n self.cb_Equations3D = tk.ttk.Combobox(f, state='readonly')\n self.cb_Equations3D['width'] = 50\n self.cb_Equations3D['values'] = sorted(list(dfc.eq_od3D['Polynomial'].keys()))\n self.cb_Equations3D.set('Linear')\n self.cb_Equations3D.pack(anchor=tk.W)\n\n # ROW 6 - empty label as visual buffer\n row, col = (6, 0)\n l = tk.Label(self, text=\" \")\n l.grid(column=col, row=row)\n\n # ROW 7 - fitting target selection labels\n # no \"self\" needed as no later references exist\n row, col = (7, 1)\n l = tk.Label(self, text=\"--- Fitting Target 2D ---\", font=\"-weight bold\")\n l.grid(column=col, row=row)\n \n row, col = (7, 3)\n l = tk.Label(self, text=\"--- Fitting Target 3D ---\", font=\"-weight bold\")\n l.grid(column=col, row=row)\n\n # ROW 8 - fitting target selection radio buttons\n row, col = (8, 1)\n f = tk.Frame(self)\n f.grid(column=col, row=row) \n index=0\n for fittingTargetText in dfc.fittingTargetList:\n rb = tk.Radiobutton(f, text=fittingTargetText, variable=self.fittingTargetSelect_2D, value=index)\n rb.pack(anchor=tk.W)\n index += 1\n\n row, col = (8, 3)\n f = tk.Frame(self)\n f.grid(column=col, row=row) \n index=0\n for fittingTargetText in dfc.fittingTargetList:\n rb = tk.Radiobutton(f, text=fittingTargetText, variable=self.fittingTargetSelect_3D, value=index)\n rb.pack(anchor=tk.W)\n index += 1\n \n # ROW 9 - empty label as visual buffer\n row, col = (9, 0)\n l = tk.Label(self, text=\" \")\n l.grid(column=col, row=row)\n \n # ROW 10 - fitting buttons\n row, col = (10, 1)\n self.buttonFit_2D = tk.Button(self, text=\"Fit 2D Text Data\", command=self.OnFit_2D)\n self.buttonFit_2D.grid(column=col, row=row)\n \n row, col = (10, 3)\n self.buttonFit_3D = tk.Button(self, text=\"Fit 3D Text Data\", command=self.OnFit_3D)\n self.buttonFit_3D.grid(column=col, row=row)\n\n # ROW 11 - empty label as visual buffer\n row, col = (11, 0)\n l = tk.Label(self, text=\" \")\n l.grid(column=col, row=row)\n \n # now bind our custom \"\"status_update\"\" event to the handler function\n self.bind('<>', self.StatusUpdateHandler)\n\n\n def moduleSelectChanged_2D(self, event):\n self.cb_Equations2D['values'] = sorted(list(dfc.eq_od2D[event.widget.get()].keys()))\n self.cb_Equations2D.current(0)\n\n\n def moduleSelectChanged_3D(self, event):\n self.cb_Equations3D['values'] = sorted(list(dfc.eq_od3D[event.widget.get()].keys()))\n self.cb_Equations3D.current(0)\n\n\n def OnFit_2D(self):\n textData = self.text_2D.get(\"1.0\", tk.END)\n moduleSelection = self.cb_Modules2D.get()\n equationSelection = self.cb_Equations2D.get()\n fittingTargetSelection = dfc.fittingTargetList[self.fittingTargetSelect_2D.get()]\n \n # the GUI's fitting target string contains what we need - extract it\n fittingTarget = fittingTargetSelection.split('(')[1].split(')')[0]\n\n item = dfc.eq_od2D[moduleSelection][equationSelection]\n eqString = 'pyeq3.Models_2D.' + moduleSelection + '.' + item[0] + \"('\" + fittingTarget + \"','\" + item[1] + \"')\"\n self.equation = eval(eqString)\n\n # convert text to numeric data checking for log of negative numbers, etc.\n try:\n pyeq3.dataConvertorService().ConvertAndSortColumnarASCII(textData, self.equation, False)\n except:\n tk_mbox.showerror(\"Error\", self.equation.reasonWhyDataRejected)\n return\n\n # check for number of coefficients > number of data points to be fitted\n coeffCount = len(self.equation.GetCoefficientDesignators())\n dataCount = len(self.equation.dataCache.allDataCacheDictionary['DependentData'])\n if coeffCount > dataCount:\n tk_mbox.showerror(\"Error\", \"This equation requires a minimum of \" + str(coeffCount) + \" data points, you have supplied \" + repr(dataCount) + \".\")\n return\n \n # Now the status dialog is used. Disable fitting buttons until thread completes\n self.buttonFit_2D.config(state=tk.DISABLED)\n self.buttonFit_3D.config(state=tk.DISABLED)\n \n # create simple top-level text dialog to display status as fitting progresses\n # when the fitting thread completes, it will close the status box\n self.statusBox = tk.Toplevel()\n self.statusBox.title(\"Fitting Status\")\n self.statusBox.text = tk.Text(self.statusBox)\n self.statusBox.text.pack()\n \n # in tkinter the status box must be manually centered\n self.statusBox.update_idletasks()\n width = self.statusBox.winfo_width()\n height = self.statusBox.winfo_height()\n x = (self.statusBox.winfo_screenwidth() // 2) - (width // 2) # integer division\n y = (self.statusBox.winfo_screenheight() // 2) - (height // 2) # integer division\n self.statusBox.geometry('{}x{}+{}+{}'.format(width, height, x, y)) \n\n # thread will automatically start to run\n # \"status update\" handler will re-enable buttons\n self.fittingWorkerThread = FittingThread.FittingThread(self, self.equation)\n\n\n def OnFit_3D(self):\n textData = self.text_3D.get(\"1.0\", tk.END)\n moduleSelection = self.cb_Modules3D.get()\n equationSelection = self.cb_Equations3D.get()\n fittingTargetSelection = dfc.fittingTargetList[self.fittingTargetSelect_3D.get()]\n \n # the GUI's fitting target string contains what we need - extract it\n fittingTarget = fittingTargetSelection.split('(')[1].split(')')[0]\n\n item = dfc.eq_od3D[moduleSelection][equationSelection]\n eqString = 'pyeq3.Models_3D.' + moduleSelection + '.' + item[0] + \"('\" + fittingTarget + \"','\" + item[1] + \"')\"\n self.equation = eval(eqString)\n\n # convert text to numeric data checking for log of negative numbers, etc.\n try:\n pyeq3.dataConvertorService().ConvertAndSortColumnarASCII(textData, self.equation, False)\n except:\n tk_mbox.showerror(\"Error\", self.equation.reasonWhyDataRejected)\n return\n\n # check for number of coefficients > number of data points to be fitted\n coeffCount = len(self.equation.GetCoefficientDesignators())\n dataCount = len(self.equation.dataCache.allDataCacheDictionary['DependentData'])\n if coeffCount > dataCount:\n tk_mbox.showerror(\"Error\", \"This equation requires a minimum of \" + str(coeffCount) + \" data points, you have supplied \" + repr(dataCount) + \".\")\n return\n \n # Now the status dialog is used. Disable fitting buttons until thread completes\n self.buttonFit_2D.config(state=tk.DISABLED)\n self.buttonFit_3D.config(state=tk.DISABLED)\n \n # create simple top-level text dialog to display status as fitting progresses\n # when the fitting thread completes, it will close the status box\n self.statusBox = tk.Toplevel()\n self.statusBox.title(\"Fitting Status\")\n self.statusBox.text = tk.Text(self.statusBox)\n self.statusBox.text.pack()\n \n # in tkinter the status box must be manually centered\n self.statusBox.update_idletasks()\n width = self.statusBox.winfo_width()\n height = self.statusBox.winfo_height()\n x = (self.statusBox.winfo_screenwidth() // 2) - (width // 2) # integer division\n y = (self.statusBox.winfo_screenheight() // 2) - (height // 2) # integer division\n self.statusBox.geometry('{}x{}+{}+{}'.format(width, height, x, y)) \n\n # thread will automatically start to run\n # \"status update\" handler will re-enable buttons\n self.fittingWorkerThread = FittingThread.FittingThread(self, self.equation)\n\n\n # When \"status_update\" event is generated, get\n # text data from queue and display it to the user.\n # If the queue data is not text, it is the fitted equation.\n def StatusUpdateHandler(self, *args):\n data = self.queue.get_nowait()\n \n if type(data) == type(''): # text is used for status box display to user\n self.statusBox.text.insert(tk.END, data + '\\n')\n else: # the queue data is now the fitted equation.\n # write the fitted equation to a pickle file. This\n # allows the possibility of archiving the fitted equations\n pickledEquationFile = open(\"pickledEquationFile\", \"wb\")\n pickle.dump(data, pickledEquationFile)\n pickledEquationFile.close()\n \n # view fitting results\n p = os.popen(sys.executable + ' FittingResultsViewer.py')\n p.close()\n\n # re-enable fitting buttons\n self.buttonFit_2D.config(state=tk.NORMAL)\n self.buttonFit_3D.config(state=tk.NORMAL)\n \n # destroy the now-unused status box\n self.statusBox.destroy()\n \n\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n interface = InterfaceFrame(root)\n interface.pack()\n root.title(\"tkinterFit - Curve And Surface Fitting Interface\")\n \n # manually center the application window on the user display\n root.update_idletasks()\n width = root.winfo_width()\n height = root.winfo_height()\n x = (root.winfo_screenwidth() // 2) - (width // 2) # integer division\n y = (root.winfo_screenheight() // 2) - (height // 2) # integer division\n root.geometry('{}x{}+{}+{}'.format(width, height, x, y)) \n \n root.mainloop()\n","sub_path":"FittingInterface.py","file_name":"FittingInterface.py","file_ext":"py","file_size_in_byte":13463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"199556383","text":"#!/usr/bin/env python\n\n\"\"\"\n@package ion.agents.platform.platform_driver\n@file ion/agents/platform/platform_driver.py\n@author Carlos Rueda\n@brief Base class for platform drivers\n\"\"\"\n\n__author__ = 'Carlos Rueda'\n__license__ = 'Apache 2.0'\n\n\nfrom pyon.public import log\nimport logging\n\nfrom ion.agents.platform.platform_driver_event import DriverEvent\nfrom ion.agents.platform.exceptions import PlatformDriverException\n\nfrom ion.agents.instrument.common import BaseEnum\nfrom ion.agents.instrument.instrument_fsm import InstrumentFSM, FSMError\nfrom ion.agents.platform.exceptions import PlatformConnectionException\nfrom ion.agents.platform.util.network_util import NetworkUtil\n\n\nclass PlatformDriverState(BaseEnum):\n \"\"\"\n Platform driver states\n \"\"\"\n UNCONFIGURED = 'PLATFORM_DRIVER_STATE_UNCONFIGURED'\n DISCONNECTED = 'PLATFORM_DRIVER_STATE_DISCONNECTED'\n CONNECTING = 'PLATFORM_DRIVER_STATE_CONNECTING'\n CONNECTED = 'PLATFORM_DRIVER_STATE_CONNECTED'\n DISCONNECTING = 'PLATFORM_DRIVER_STATE_DISCONNECTING'\n\n\nclass PlatformDriverEvent(BaseEnum):\n \"\"\"\n Base events for driver state machines.\n \"\"\"\n ENTER = 'PLATFORM_DRIVER_EVENT_ENTER'\n EXIT = 'PLATFORM_DRIVER_EVENT_EXIT'\n\n CONFIGURE = 'PLATFORM_DRIVER_EVENT_CONFIGURE'\n CONNECT = 'PLATFORM_DRIVER_EVENT_CONNECT'\n CONNECTION_LOST = 'PLATFORM_DRIVER_CONNECTION_LOST'\n DISCONNECT = 'PLATFORM_DRIVER_EVENT_DISCONNECT'\n\n # Events for the CONNECTED state:\n PING = 'PLATFORM_DRIVER_PING'\n GET_METADATA = 'PLATFORM_DRIVER_GET_METADATA'\n GET_ATTRIBUTE_VALUES = 'PLATFORM_DRIVER_GET_ATTRIBUTE_VALUES'\n SET_ATTRIBUTE_VALUES = 'PLATFORM_DRIVER_SET_ATTRIBUTE_VALUES'\n CONNECT_INSTRUMENT = 'PLATFORM_DRIVER_CONNECT_INSTRUMENT'\n DISCONNECT_INSTRUMENT = 'PLATFORM_DRIVER_DISCONNECT_INSTRUMENT'\n GET_CONNECTED_INSTRUMENTS = 'PLATFORM_DRIVER_GET_CONNECTED_INSTRUMENTS'\n TURN_ON_PORT = 'PLATFORM_DRIVER_TURN_ON_PORT'\n TURN_OFF_PORT = 'PLATFORM_DRIVER_TURN_OFF_PORT'\n START_EVENT_DISPATCH = 'PLATFORM_DRIVER_START_EVENT_DISPATCH'\n STOP_EVENT_DISPATCH = 'PLATFORM_DRIVER_STOP_EVENT_DISPATCH'\n GET_CHECKSUM = 'PLATFORM_DRIVER_GET_CHECKSUM'\n\n\nclass PlatformDriver(object):\n \"\"\"\n A platform driver handles a particular platform in a platform network.\n \"\"\"\n\n def __init__(self, pnode, evt_recv):\n \"\"\"\n Creates a PlatformDriver instance.\n\n @param pnode Root PlatformNode defining the platform network rooted at\n this platform.\n @param evt_recv Listener of events generated by this driver\n \"\"\"\n assert pnode, \"pnode must be given\"\n assert evt_recv, \"evt_recv parameter must be given\"\n\n self._pnode = pnode\n self._send_event = evt_recv\n\n self._platform_id = self._pnode.platform_id\n if self._pnode.parent:\n self._parent_platform_id = self._pnode.parent.platform_id\n else:\n self._parent_platform_id = None\n\n self._platform_attributes = \\\n dict((a.attr_id, a.defn) for a in self._pnode.attrs.itervalues())\n\n if log.isEnabledFor(logging.DEBUG):\n log.debug(\"%r: PlatformDriver constructor called: pnode:\\n%s\\n\"\n \"_platform_attributes=%s\",\n self._platform_id,\n NetworkUtil._dump_pnode(self._pnode, include_subplatforms=False),\n self._platform_attributes)\n\n self._driver_config = None\n\n # construct FSM and start it with initial state UNCONFIGURED:\n self._construct_fsm()\n self._fsm.start(PlatformDriverState.UNCONFIGURED)\n\n def _get_platform_attributes(self):\n \"\"\"\n Gets a dict of the attribute definitions in this platform as given at\n construction time (from pnode parameter).\n \"\"\"\n return self._platform_attributes\n\n def validate_driver_configuration(self, driver_config):\n \"\"\"\n Called by configure so a subclass can perform any needed additional\n validation of the provided configuration.\n Nothing is done in this base class. Note that basic validation is\n done by PlatformAgent prior to creating/configuring the driver.\n\n @param driver_config Driver configuration.\n\n @raise PlatformDriverException Error in driver configuration.\n \"\"\"\n\n def configure(self, driver_config):\n \"\"\"\n Configures this driver. It first calls validate_driver_configuration.\n\n @param driver_config Driver configuration.\n \"\"\"\n if log.isEnabledFor(logging.DEBUG):\n log.debug(\"%r: configure: %s\" % (self._platform_id, str(driver_config)))\n\n self.validate_driver_configuration(driver_config)\n self._driver_config = driver_config\n\n def connect(self):\n \"\"\"\n To be implemented by subclass.\n Establishes communication with the platform device.\n\n @raise PlatformConnectionException\n \"\"\"\n raise NotImplementedError() #pragma: no cover\n\n def disconnect(self):\n \"\"\"\n To be implemented by subclass.\n Ends communication with the platform device.\n\n @raise PlatformConnectionException\n \"\"\"\n raise NotImplementedError() #pragma: no cover\n\n def ping(self):\n \"\"\"\n To be implemented by subclass.\n Verifies communication with external platform returning \"PONG\" if\n this verification completes OK.\n\n @retval \"PONG\"\n @raise PlatformConnectionException\n \"\"\"\n raise NotImplementedError() #pragma: no cover\n\n def get_metadata(self):\n \"\"\"\n To be implemented by subclass.\n Returns the metadata associated to the platform.\n\n @raise PlatformConnectionException\n \"\"\"\n raise NotImplementedError() #pragma: no cover\n\n def get_attribute_values(self, attr_names, from_time):\n \"\"\"\n To be implemented by subclass.\n Returns the values for specific attributes since a given time.\n\n @param attr_names [attrName, ...] desired attributes\n @param from_time time from which the values are requested.\n Assummed to be in the format basically described by\n pyon's get_ion_ts function, \"a str representing an\n integer number, the millis in UNIX epoch.\"\n\n @retval {attrName : [(attrValue, timestamp), ...], ...}\n dict indexed by attribute name with list of (value, timestamp)\n pairs. Timestamps in same format as from_time.\n \"\"\"\n raise NotImplementedError() #pragma: no cover\n\n def set_attribute_values(self, attrs):\n \"\"\"\n To be implemented by subclass.\n Sets values for writable attributes in this platform.\n\n @param attrs \t[(attrName, attrValue), ...] \tList of attribute values\n\n @retval {platform_id: {attrName : [(attrValue, timestamp), ...], ...}}\n dict with a single entry for the requested platform ID and value\n as a list of (value,timestamp) pairs for each attribute indicated\n in the input. Returned timestamps indicate the time when the\n value was set. Each timestamp is \"a str representing an\n integer number, the millis in UNIX epoch;\" this is to be\n aligned with description of pyon's get_ion_ts function.\n \"\"\"\n raise NotImplementedError() #pragma: no cover\n\n def connect_instrument(self, port_id, instrument_id, attributes):\n \"\"\"\n To be implemented by subclass.\n Connects an instrument to a port in this platform.\n\n @param port_id Port ID\n @param instrument_id Instrument ID\n @param attributes Attribute dictionary\n\n @retval The resulting configuration for the instrument.\n\n @raise PlatformConnectionException\n \"\"\"\n raise NotImplementedError() #pragma: no cover\n\n def disconnect_instrument(self, port_id, instrument_id):\n \"\"\"\n To be implemented by subclass.\n Disconnects an instrument from a port in this platform.\n\n @param port_id Port ID\n @param instrument_id Instrument ID\n\n @retval\n\n @raise PlatformConnectionException\n \"\"\"\n raise NotImplementedError() #pragma: no cover\n\n def get_connected_instruments(self, port_id):\n \"\"\"\n To be implemented by subclass.\n Retrieves the IDs of the instruments connected to a port.\n\n @param port_id Port ID\n\n @retval\n\n @raise PlatformConnectionException\n \"\"\"\n raise NotImplementedError() #pragma: no cover\n\n def turn_on_port(self, port_id):\n \"\"\"\n To be implemented by subclass.\n Turns on a port in this platform.\n\n @param port_id Port ID\n\n @retval The resulting on/off of the port.\n\n @raise PlatformConnectionException\n \"\"\"\n raise NotImplementedError() #pragma: no cover\n\n def turn_off_port(self, port_id):\n \"\"\"\n To be implemented by subclass.\n Turns off a port in this platform.\n\n @param port_id Port ID\n\n @retval The resulting on/off of the port.\n\n @raise PlatformConnectionException\n \"\"\"\n raise NotImplementedError() #pragma: no cover\n\n def destroy(self):\n \"\"\"\n Stops all activity done by the driver. Nothing done in this class.\n (previously it stopped resource monitoring).\n \"\"\"\n\n def _notify_driver_event(self, driver_event):\n \"\"\"\n Convenience method for subclasses to send a driver event to\n corresponding platform agent.\n\n @param driver_event a DriverEvent object.\n \"\"\"\n log.debug(\"platform driver=%r: notify driver_event=%s\",\n self._platform_id, driver_event)\n\n assert isinstance(driver_event, DriverEvent)\n\n self._send_event(driver_event)\n\n def start_event_dispatch(self):\n \"\"\"\n To be implemented by subclass.\n Starts the dispatch of events received from the platform network to do\n corresponding event notifications.\n \"\"\"\n raise NotImplementedError() #pragma: no cover\n\n def stop_event_dispatch(self):\n \"\"\"\n To be implemented by subclass.\n Stops the dispatch of events received from the platform network.\n \"\"\"\n raise NotImplementedError() #pragma: no cover\n\n def get_checksum(self):\n \"\"\"\n To be implemented by subclass.\n Returns the checksum for this platform.\n\n @return SHA1 hash value as string of hexadecimal digits.\n @raise PlatformConnectionException\n \"\"\"\n raise NotImplementedError() #pragma: no cover\n\n def get_driver_state(self):\n \"\"\"\n Returns the current FSM state.\n \"\"\"\n return self._fsm.get_current_state()\n\n ##############################################################\n # FSM event handlers.\n ##############################################################\n\n def _common_state_enter(self, *args, **kwargs):\n \"\"\"\n Common work upon every state entry.\n Nothing done in this base class.\n @todo determine what should be done, in particular regarding eventual\n notification of the platform driver state transition.\n \"\"\"\n state = self.get_driver_state()\n if log.isEnabledFor(logging.DEBUG):\n log.debug('%r: driver entering state: %s' % (self._platform_id, state))\n\n # TODO: publish the platform driver FSM state transition?\n # event_data = {\n # 'state': state\n # }\n # result = self._event_publisher.publish_event(\n # event_type = ?????,\n # origin = ?????,\n # **event_data)\n # if log.isEnabledFor(logging.DEBUG):\n # log.debug('%r: PlatformDriver published state change: %s, '\n # 'time: %s result: %s',\n # self._platform_id, state, get_ion_ts(), str(result))\n\n def _common_state_exit(self, *args, **kwargs):\n \"\"\"\n Common work upon every state exit.\n Nothing done in this base class.\n \"\"\"\n\n ##############################################################\n # UNCONFIGURED event handlers.\n ##############################################################\n\n def _handler_unconfigured_configure(self, *args, **kwargs):\n \"\"\"\n \"\"\"\n if log.isEnabledFor(logging.TRACE): # pragma: no cover\n log.trace(\"%r/%s args=%s kwargs=%s\" % (\n self._platform_id, self.get_driver_state(),\n str(args), str(kwargs)))\n\n driver_config = kwargs.get('driver_config', None)\n if driver_config is None:\n raise FSMError('configure: missing driver_config argument')\n\n try:\n result = self.configure(driver_config)\n next_state = PlatformDriverState.DISCONNECTED\n except PlatformDriverException as e:\n result = None\n next_state = None\n log.error(\"Error in platform driver configuration\", e)\n\n return next_state, result\n\n ##############################################################\n # DISCONNECTED event handlers.\n ##############################################################\n\n def _handler_disconnected_connect(self, *args, **kwargs):\n \"\"\"\n \"\"\"\n if log.isEnabledFor(logging.TRACE): # pragma: no cover\n log.trace(\"%r/%s args=%s kwargs=%s\" % (\n self._platform_id, self.get_driver_state(),\n str(args), str(kwargs)))\n\n result = self.connect()\n next_state = PlatformDriverState.CONNECTED\n\n return next_state, result\n\n ##############################################################\n # CONNECTED event handlers.\n ##############################################################\n\n def _handler_connected_disconnect(self, *args, **kwargs):\n \"\"\"\n \"\"\"\n if log.isEnabledFor(logging.TRACE): # pragma: no cover\n log.trace(\"%r/%s args=%s kwargs=%s\" % (\n self._platform_id, self.get_driver_state(),\n str(args), str(kwargs)))\n\n result = self.disconnect(*args, **kwargs)\n next_state = PlatformDriverState.DISCONNECTED\n\n return next_state, result\n\n def _handler_connected_ping(self, *args, **kwargs):\n \"\"\"\n \"\"\"\n if log.isEnabledFor(logging.TRACE): # pragma: no cover\n log.trace(\"%r/%s args=%s kwargs=%s\" % (\n self._platform_id, self.get_driver_state(),\n str(args), str(kwargs)))\n\n result = None\n try:\n result = self.ping()\n next_state = None\n except PlatformConnectionException as e:\n next_state = PlatformDriverState.DISCONNECTED\n log.error(\"Ping failed\", e)\n\n return next_state, result\n\n def _handler_connected_get_metadata(self, *args, **kwargs):\n \"\"\"\n \"\"\"\n if log.isEnabledFor(logging.TRACE): # pragma: no cover\n log.trace(\"%r/%s args=%s kwargs=%s\" % (\n self._platform_id, self.get_driver_state(),\n str(args), str(kwargs)))\n\n result = self.get_metadata()\n next_state = None\n\n return next_state, result\n\n def _handler_connected_get_attribute_values(self, *args, **kwargs):\n \"\"\"\n \"\"\"\n if log.isEnabledFor(logging.TRACE): # pragma: no cover\n log.trace(\"%r/%s args=%s kwargs=%s\" % (\n self._platform_id, self.get_driver_state(),\n str(args), str(kwargs)))\n\n attr_names = kwargs.get('attr_names', None)\n if attr_names is None:\n raise FSMError('get_attribute_values: missing attr_names argument')\n\n from_time = kwargs.get('from_time', None)\n if from_time is None:\n raise FSMError('get_attribute_values: missing from_time argument')\n\n result = self.get_attribute_values(attr_names, from_time)\n next_state = None\n\n return next_state, result\n\n def _handler_connected_set_attribute_values(self, *args, **kwargs):\n \"\"\"\n \"\"\"\n if log.isEnabledFor(logging.TRACE): # pragma: no cover\n log.trace(\"%r/%s args=%s kwargs=%s\" % (\n self._platform_id, self.get_driver_state(),\n str(args), str(kwargs)))\n\n attrs = kwargs.get('attrs', None)\n if attrs is None:\n raise FSMError('set_attribute_values: missing attrs argument')\n\n result = self.set_attribute_values(attrs)\n next_state = None\n\n return next_state, result\n\n def _handler_connected_connect_instrument(self, *args, **kwargs):\n \"\"\"\n \"\"\"\n if log.isEnabledFor(logging.TRACE): # pragma: no cover\n log.trace(\"%r/%s args=%s kwargs=%s\" % (\n self._platform_id, self.get_driver_state(),\n str(args), str(kwargs)))\n\n port_id = kwargs.get('port_id', None)\n if port_id is None:\n raise FSMError('connect_instrument: missing port_id argument')\n\n instrument_id = kwargs.get('instrument_id', None)\n if instrument_id is None:\n raise FSMError('connect_instrument: missing instrument_id argument')\n\n attributes = kwargs.get('attributes', None)\n if attributes is None:\n raise FSMError('connect_instrument: missing attributes argument')\n\n result = self.connect_instrument(port_id, instrument_id, attributes)\n next_state = None\n\n return next_state, result\n\n def _handler_disconnected_connect_instrument(self, *args, **kwargs):\n \"\"\"\n \"\"\"\n if log.isEnabledFor(logging.TRACE): # pragma: no cover\n log.trace(\"%r/%s args=%s kwargs=%s\" % (\n self._platform_id, self.get_driver_state(),\n str(args), str(kwargs)))\n\n port_id = kwargs.get('port_id', None)\n if port_id is None:\n raise FSMError('disconnect_instrument: missing port_id argument')\n\n instrument_id = kwargs.get('instrument_id', None)\n if instrument_id is None:\n raise FSMError('disconnect_instrument: missing instrument_id argument')\n\n result = self.disconnect_instrument(port_id, instrument_id)\n next_state = None\n\n return next_state, result\n\n def _handler_connected_get_connected_instruments(self, *args, **kwargs):\n \"\"\"\n \"\"\"\n if log.isEnabledFor(logging.TRACE): # pragma: no cover\n log.trace(\"%r/%s args=%s kwargs=%s\" % (\n self._platform_id, self.get_driver_state(),\n str(args), str(kwargs)))\n\n port_id = kwargs.get('port_id', None)\n if port_id is None:\n raise FSMError('get_connected_instruments: missing port_id argument')\n\n result = self.get_connected_instruments(port_id)\n next_state = None\n\n return next_state, result\n\n def _handler_connected_turn_on_port(self, *args, **kwargs):\n \"\"\"\n \"\"\"\n if log.isEnabledFor(logging.TRACE): # pragma: no cover\n log.trace(\"%r/%s args=%s kwargs=%s\" % (\n self._platform_id, self.get_driver_state(),\n str(args), str(kwargs)))\n\n port_id = kwargs.get('port_id', None)\n if port_id is None:\n raise FSMError('turn_on_port: missing port_id argument')\n\n result = self.turn_on_port(port_id)\n next_state = None\n\n return next_state, result\n\n def _handler_connected_turn_off_port(self, *args, **kwargs):\n \"\"\"\n \"\"\"\n if log.isEnabledFor(logging.TRACE): # pragma: no cover\n log.trace(\"%r/%s args=%s kwargs=%s\" % (\n self._platform_id, self.get_driver_state(),\n str(args), str(kwargs)))\n\n port_id = kwargs.get('port_id', None)\n if port_id is None:\n raise FSMError('turn_off_port: missing port_id argument')\n\n result = self.turn_off_port(port_id)\n next_state = None\n\n return next_state, result\n\n def _handler_connected_start_event_dispatch(self, *args, **kwargs):\n \"\"\"\n \"\"\"\n if log.isEnabledFor(logging.TRACE): # pragma: no cover\n log.trace(\"%r/%s args=%s kwargs=%s\" % (\n self._platform_id, self.get_driver_state(),\n str(args), str(kwargs)))\n\n result = self.start_event_dispatch()\n next_state = None\n\n return next_state, result\n\n def _handler_connected_stop_event_dispatch(self, *args, **kwargs):\n \"\"\"\n \"\"\"\n if log.isEnabledFor(logging.TRACE): # pragma: no cover\n log.trace(\"%r/%s args=%s kwargs=%s\" % (\n self._platform_id, self.get_driver_state(),\n str(args), str(kwargs)))\n\n result = self.stop_event_dispatch()\n next_state = None\n\n return next_state, result\n\n def _handler_connected_get_checksum(self, *args, **kwargs):\n \"\"\"\n \"\"\"\n if log.isEnabledFor(logging.TRACE): # pragma: no cover\n log.trace(\"%r/%s args=%s kwargs=%s\" % (\n self._platform_id, self.get_driver_state(),\n str(args), str(kwargs)))\n\n result = self.get_checksum()\n next_state = None\n\n return next_state, result\n\n ##############################################################\n # Platform driver FSM setup\n ##############################################################\n\n def _construct_fsm(self):\n \"\"\"\n \"\"\"\n log.debug(\"constructing fsm\")\n\n self._fsm = InstrumentFSM(PlatformDriverState,\n PlatformDriverEvent,\n PlatformDriverEvent.ENTER,\n PlatformDriverEvent.EXIT)\n\n for state in PlatformDriverState.list():\n self._fsm.add_handler(state, PlatformDriverEvent.ENTER, self._common_state_enter)\n self._fsm.add_handler(state, PlatformDriverEvent.EXIT, self._common_state_exit)\n\n # UNCONFIGURED state event handlers:\n self._fsm.add_handler(PlatformDriverState.UNCONFIGURED, PlatformDriverEvent.CONFIGURE, self._handler_unconfigured_configure)\n\n # DISCONNECTED state event handlers:\n self._fsm.add_handler(PlatformDriverState.DISCONNECTED, PlatformDriverEvent.CONNECT, self._handler_disconnected_connect)\n\n # CONNECTING state event handlers:\n # NONE.\n\n # DISCONNECTING state event handlers:\n # NONE.\n\n # CONNECTED state event handlers:\n self._fsm.add_handler(PlatformDriverState.CONNECTED, PlatformDriverEvent.DISCONNECT, self._handler_connected_disconnect)\n self._fsm.add_handler(PlatformDriverState.CONNECTED, PlatformDriverEvent.CONNECTION_LOST, self._handler_connected_disconnect)\n\n self._fsm.add_handler(PlatformDriverState.CONNECTED, PlatformDriverEvent.PING, self._handler_connected_ping)\n self._fsm.add_handler(PlatformDriverState.CONNECTED, PlatformDriverEvent.GET_METADATA, self._handler_connected_get_metadata)\n self._fsm.add_handler(PlatformDriverState.CONNECTED, PlatformDriverEvent.GET_ATTRIBUTE_VALUES, self._handler_connected_get_attribute_values)\n self._fsm.add_handler(PlatformDriverState.CONNECTED, PlatformDriverEvent.SET_ATTRIBUTE_VALUES, self._handler_connected_set_attribute_values)\n self._fsm.add_handler(PlatformDriverState.CONNECTED, PlatformDriverEvent.CONNECT_INSTRUMENT, self._handler_connected_connect_instrument)\n self._fsm.add_handler(PlatformDriverState.CONNECTED, PlatformDriverEvent.DISCONNECT_INSTRUMENT, self._handler_disconnected_connect_instrument)\n self._fsm.add_handler(PlatformDriverState.CONNECTED, PlatformDriverEvent.GET_CONNECTED_INSTRUMENTS, self._handler_connected_get_connected_instruments)\n self._fsm.add_handler(PlatformDriverState.CONNECTED, PlatformDriverEvent.TURN_ON_PORT, self._handler_connected_turn_on_port)\n self._fsm.add_handler(PlatformDriverState.CONNECTED, PlatformDriverEvent.TURN_OFF_PORT, self._handler_connected_turn_off_port)\n self._fsm.add_handler(PlatformDriverState.CONNECTED, PlatformDriverEvent.START_EVENT_DISPATCH, self._handler_connected_start_event_dispatch)\n self._fsm.add_handler(PlatformDriverState.CONNECTED, PlatformDriverEvent.STOP_EVENT_DISPATCH, self._handler_connected_stop_event_dispatch)\n self._fsm.add_handler(PlatformDriverState.CONNECTED, PlatformDriverEvent.GET_CHECKSUM, self._handler_connected_get_checksum)\n","sub_path":"ion/agents/platform/platform_driver.py","file_name":"platform_driver.py","file_ext":"py","file_size_in_byte":24939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"92558553","text":"from flask import Flask, jsonify\nfrom pymemcache.client import base\n\nfrom config import Config\n\n\n# Initiate Flask app\napp = Flask(__name__)\napp.config.from_object(Config)\n\n# Initiate memcached client\nclient = base.Client((Config.MEMCACHED_HOST, Config.MEMCACHED_PORT))\n\nLIMITS = Config.REQUEST_LIMITS\n\n\ndef get_cache_key(**kwargs) -> str:\n \"\"\"\n Function that returns the transformed cache key\n :param kwargs: Params for transform\n :return: Transformed cache key\n :rtype: str\n \"\"\"\n\n return \"current_limit_{period}\".format(**kwargs)\n\n\ndef get_spent(period: int) -> int:\n \"\"\"\n Function that returns already spent sum in specified period\n :param period: Specified period\n :type period: int\n :return: Already spent sum in specified period\n :rtype: int\n \"\"\"\n\n # Load data from memcached and convert to int, if exists otherwise return 0\n cached_value = client.get(get_cache_key(period=period))\n return int(cached_value.decode('utf8')) if cached_value else 0\n\n\ndef check_limit(period: int, limit: int, amount: int) -> bool:\n \"\"\"\n Function that check limit exceeded with entered sum\n :param period: Specified period\n :type period: int\n :param limit: Limit for period\n :type limit: int\n :param amount: Entered sum\n :type amount: int\n :return: Is limit exceeded\n :rtype: bool\n \"\"\"\n\n spent = get_spent(period)\n\n if (spent + amount) > limit:\n return True\n return False\n\n\ndef set_limit(period: int, amount: int):\n \"\"\"\n Function that set or increment spent sum\n :param period: Specified period\n :type period: int\n :param amount: Entered sum\n :type amount: int\n \"\"\"\n\n cache_key = get_cache_key(period=period)\n spent = get_spent(period)\n\n if not spent:\n client.set(cache_key, amount, period)\n else:\n client.incr(cache_key, amount)\n\n\n@app.route(\"/request/\", methods=[\"GET\"])\ndef pay(amount: int):\n \"\"\"\n This is the payment API with some limits of payment sum per seconds\n ---\n parameters:\n - name: amount\n in: path\n type: int\n required: true\n description: The payment sum\n responses:\n 200:\n description: Operation status\n schema:\n id: awesome\n properties:\n result:\n type: string\n description: The operation result\n default: OK\n error:\n type: string\n description: Description of error\n \"\"\"\n\n result = {\"result\": \"OK\"}\n\n # Check exceeded limits\n exceeded = list(\n filter(lambda limit: check_limit(*limit, amount), LIMITS.items())\n )\n\n if exceeded:\n # If any limit is exceeded - return error with names of those limits\n exceeded_keys = [str(limit[0]) for limit in exceeded]\n result = {\n \"error\": f\"amount limit exceeded ({'/'.join(exceeded_keys)}sec)\"\n }\n else:\n # Otherwise set/increment all limits\n for period in LIMITS.keys():\n set_limit(period, amount)\n\n return jsonify(result)\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"425054069","text":"#! /usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\nCreated on Nov 26, 2013\n\n@author: yankel\n\"\"\"\n\ndata_xml_url_radiation = \"http://www.ims.gov.il/ims/PublicXML/isr_rad.xml\"\n\nfile_encoding = 'iso-8859-8'","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"62299362","text":"# -*- coding: utf-8 -*-\n# Copyright 2023 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfrom typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union\nimport warnings\n\nfrom google.api_core import gapic_v1, grpc_helpers_async, operations_v1\nfrom google.auth import credentials as ga_credentials # type: ignore\nfrom google.auth.transport.grpc import SslCredentials # type: ignore\nfrom google.iam.v1 import iam_policy_pb2 # type: ignore\nfrom google.iam.v1 import policy_pb2 # type: ignore\nfrom google.longrunning import operations_pb2 # type: ignore\nimport grpc # type: ignore\nfrom grpc.experimental import aio # type: ignore\n\nfrom google.cloud.resourcemanager_v3.types import projects\n\nfrom .base import DEFAULT_CLIENT_INFO, ProjectsTransport\nfrom .grpc import ProjectsGrpcTransport\n\n\nclass ProjectsGrpcAsyncIOTransport(ProjectsTransport):\n \"\"\"gRPC AsyncIO backend transport for Projects.\n\n Manages Google Cloud Projects.\n\n This class defines the same methods as the primary client, so the\n primary client can load the underlying transport implementation\n and call it.\n\n It sends protocol buffers over the wire using gRPC (which is built on\n top of HTTP/2); the ``grpcio`` package must be installed.\n \"\"\"\n\n _grpc_channel: aio.Channel\n _stubs: Dict[str, Callable] = {}\n\n @classmethod\n def create_channel(\n cls,\n host: str = \"cloudresourcemanager.googleapis.com\",\n credentials: Optional[ga_credentials.Credentials] = None,\n credentials_file: Optional[str] = None,\n scopes: Optional[Sequence[str]] = None,\n quota_project_id: Optional[str] = None,\n **kwargs,\n ) -> aio.Channel:\n \"\"\"Create and return a gRPC AsyncIO channel object.\n Args:\n host (Optional[str]): The host for the channel to use.\n credentials (Optional[~.Credentials]): The\n authorization credentials to attach to requests. These\n credentials identify this application to the service. If\n none are specified, the client will attempt to ascertain\n the credentials from the environment.\n credentials_file (Optional[str]): A file with credentials that can\n be loaded with :func:`google.auth.load_credentials_from_file`.\n This argument is ignored if ``channel`` is provided.\n scopes (Optional[Sequence[str]]): A optional list of scopes needed for this\n service. These are only used when credentials are not specified and\n are passed to :func:`google.auth.default`.\n quota_project_id (Optional[str]): An optional project to use for billing\n and quota.\n kwargs (Optional[dict]): Keyword arguments, which are passed to the\n channel creation.\n Returns:\n aio.Channel: A gRPC AsyncIO channel object.\n \"\"\"\n\n return grpc_helpers_async.create_channel(\n host,\n credentials=credentials,\n credentials_file=credentials_file,\n quota_project_id=quota_project_id,\n default_scopes=cls.AUTH_SCOPES,\n scopes=scopes,\n default_host=cls.DEFAULT_HOST,\n **kwargs,\n )\n\n def __init__(\n self,\n *,\n host: str = \"cloudresourcemanager.googleapis.com\",\n credentials: Optional[ga_credentials.Credentials] = None,\n credentials_file: Optional[str] = None,\n scopes: Optional[Sequence[str]] = None,\n channel: Optional[aio.Channel] = None,\n api_mtls_endpoint: Optional[str] = None,\n client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,\n ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,\n client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,\n quota_project_id: Optional[str] = None,\n client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,\n always_use_jwt_access: Optional[bool] = False,\n api_audience: Optional[str] = None,\n ) -> None:\n \"\"\"Instantiate the transport.\n\n Args:\n host (Optional[str]):\n The hostname to connect to.\n credentials (Optional[google.auth.credentials.Credentials]): The\n authorization credentials to attach to requests. These\n credentials identify the application to the service; if none\n are specified, the client will attempt to ascertain the\n credentials from the environment.\n This argument is ignored if ``channel`` is provided.\n credentials_file (Optional[str]): A file with credentials that can\n be loaded with :func:`google.auth.load_credentials_from_file`.\n This argument is ignored if ``channel`` is provided.\n scopes (Optional[Sequence[str]]): A optional list of scopes needed for this\n service. These are only used when credentials are not specified and\n are passed to :func:`google.auth.default`.\n channel (Optional[aio.Channel]): A ``Channel`` instance through\n which to make calls.\n api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.\n If provided, it overrides the ``host`` argument and tries to create\n a mutual TLS channel with client SSL credentials from\n ``client_cert_source`` or application default SSL credentials.\n client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):\n Deprecated. A callback to provide client SSL certificate bytes and\n private key bytes, both in PEM format. It is ignored if\n ``api_mtls_endpoint`` is None.\n ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials\n for the grpc channel. It is ignored if ``channel`` is provided.\n client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):\n A callback to provide client certificate bytes and private key bytes,\n both in PEM format. It is used to configure a mutual TLS channel. It is\n ignored if ``channel`` or ``ssl_channel_credentials`` is provided.\n quota_project_id (Optional[str]): An optional project to use for billing\n and quota.\n client_info (google.api_core.gapic_v1.client_info.ClientInfo):\n The client info used to send a user-agent string along with\n API requests. If ``None``, then default info will be used.\n Generally, you only need to set this if you're developing\n your own client library.\n always_use_jwt_access (Optional[bool]): Whether self signed JWT should\n be used for service account credentials.\n\n Raises:\n google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport\n creation failed for any reason.\n google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``\n and ``credentials_file`` are passed.\n \"\"\"\n self._grpc_channel = None\n self._ssl_channel_credentials = ssl_channel_credentials\n self._stubs: Dict[str, Callable] = {}\n self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None\n\n if api_mtls_endpoint:\n warnings.warn(\"api_mtls_endpoint is deprecated\", DeprecationWarning)\n if client_cert_source:\n warnings.warn(\"client_cert_source is deprecated\", DeprecationWarning)\n\n if channel:\n # Ignore credentials if a channel was passed.\n credentials = False\n # If a channel was explicitly provided, set it.\n self._grpc_channel = channel\n self._ssl_channel_credentials = None\n else:\n if api_mtls_endpoint:\n host = api_mtls_endpoint\n\n # Create SSL credentials with client_cert_source or application\n # default SSL credentials.\n if client_cert_source:\n cert, key = client_cert_source()\n self._ssl_channel_credentials = grpc.ssl_channel_credentials(\n certificate_chain=cert, private_key=key\n )\n else:\n self._ssl_channel_credentials = SslCredentials().ssl_credentials\n\n else:\n if client_cert_source_for_mtls and not ssl_channel_credentials:\n cert, key = client_cert_source_for_mtls()\n self._ssl_channel_credentials = grpc.ssl_channel_credentials(\n certificate_chain=cert, private_key=key\n )\n\n # The base transport sets the host, credentials and scopes\n super().__init__(\n host=host,\n credentials=credentials,\n credentials_file=credentials_file,\n scopes=scopes,\n quota_project_id=quota_project_id,\n client_info=client_info,\n always_use_jwt_access=always_use_jwt_access,\n api_audience=api_audience,\n )\n\n if not self._grpc_channel:\n self._grpc_channel = type(self).create_channel(\n self._host,\n # use the credentials which are saved\n credentials=self._credentials,\n # Set ``credentials_file`` to ``None`` here as\n # the credentials that we saved earlier should be used.\n credentials_file=None,\n scopes=self._scopes,\n ssl_credentials=self._ssl_channel_credentials,\n quota_project_id=quota_project_id,\n options=[\n (\"grpc.max_send_message_length\", -1),\n (\"grpc.max_receive_message_length\", -1),\n ],\n )\n\n # Wrap messages. This must be done after self._grpc_channel exists\n self._prep_wrapped_messages(client_info)\n\n @property\n def grpc_channel(self) -> aio.Channel:\n \"\"\"Create the channel designed to connect to this service.\n\n This property caches on the instance; repeated calls return\n the same channel.\n \"\"\"\n # Return the channel from cache.\n return self._grpc_channel\n\n @property\n def operations_client(self) -> operations_v1.OperationsAsyncClient:\n \"\"\"Create the client designed to process long-running operations.\n\n This property caches on the instance; repeated calls return the same\n client.\n \"\"\"\n # Quick check: Only create a new client if we do not already have one.\n if self._operations_client is None:\n self._operations_client = operations_v1.OperationsAsyncClient(\n self.grpc_channel\n )\n\n # Return the client from cache.\n return self._operations_client\n\n @property\n def get_project(\n self,\n ) -> Callable[[projects.GetProjectRequest], Awaitable[projects.Project]]:\n r\"\"\"Return a callable for the get project method over gRPC.\n\n Retrieves the project identified by the specified ``name`` (for\n example, ``projects/415104041262``).\n\n The caller must have ``resourcemanager.projects.get`` permission\n for this project.\n\n Returns:\n Callable[[~.GetProjectRequest],\n Awaitable[~.Project]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"get_project\" not in self._stubs:\n self._stubs[\"get_project\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.resourcemanager.v3.Projects/GetProject\",\n request_serializer=projects.GetProjectRequest.serialize,\n response_deserializer=projects.Project.deserialize,\n )\n return self._stubs[\"get_project\"]\n\n @property\n def list_projects(\n self,\n ) -> Callable[\n [projects.ListProjectsRequest], Awaitable[projects.ListProjectsResponse]\n ]:\n r\"\"\"Return a callable for the list projects method over gRPC.\n\n Lists projects that are direct children of the specified folder\n or organization resource. ``list()`` provides a strongly\n consistent view of the projects underneath the specified parent\n resource. ``list()`` returns projects sorted based upon the\n (ascending) lexical ordering of their ``display_name``. The\n caller must have ``resourcemanager.projects.list`` permission on\n the identified parent.\n\n Returns:\n Callable[[~.ListProjectsRequest],\n Awaitable[~.ListProjectsResponse]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"list_projects\" not in self._stubs:\n self._stubs[\"list_projects\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.resourcemanager.v3.Projects/ListProjects\",\n request_serializer=projects.ListProjectsRequest.serialize,\n response_deserializer=projects.ListProjectsResponse.deserialize,\n )\n return self._stubs[\"list_projects\"]\n\n @property\n def search_projects(\n self,\n ) -> Callable[\n [projects.SearchProjectsRequest], Awaitable[projects.SearchProjectsResponse]\n ]:\n r\"\"\"Return a callable for the search projects method over gRPC.\n\n Search for projects that the caller has both\n ``resourcemanager.projects.get`` permission on, and also satisfy\n the specified query.\n\n This method returns projects in an unspecified order.\n\n This method is eventually consistent with project mutations;\n this means that a newly created project may not appear in the\n results or recent updates to an existing project may not be\n reflected in the results. To retrieve the latest state of a\n project, use the\n [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject]\n method.\n\n Returns:\n Callable[[~.SearchProjectsRequest],\n Awaitable[~.SearchProjectsResponse]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"search_projects\" not in self._stubs:\n self._stubs[\"search_projects\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.resourcemanager.v3.Projects/SearchProjects\",\n request_serializer=projects.SearchProjectsRequest.serialize,\n response_deserializer=projects.SearchProjectsResponse.deserialize,\n )\n return self._stubs[\"search_projects\"]\n\n @property\n def create_project(\n self,\n ) -> Callable[[projects.CreateProjectRequest], Awaitable[operations_pb2.Operation]]:\n r\"\"\"Return a callable for the create project method over gRPC.\n\n Request that a new project be created. The result is an\n ``Operation`` which can be used to track the creation process.\n This process usually takes a few seconds, but can sometimes take\n much longer. The tracking ``Operation`` is automatically deleted\n after a few hours, so there is no need to call\n ``DeleteOperation``.\n\n Returns:\n Callable[[~.CreateProjectRequest],\n Awaitable[~.Operation]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"create_project\" not in self._stubs:\n self._stubs[\"create_project\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.resourcemanager.v3.Projects/CreateProject\",\n request_serializer=projects.CreateProjectRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs[\"create_project\"]\n\n @property\n def update_project(\n self,\n ) -> Callable[[projects.UpdateProjectRequest], Awaitable[operations_pb2.Operation]]:\n r\"\"\"Return a callable for the update project method over gRPC.\n\n Updates the ``display_name`` and labels of the project\n identified by the specified ``name`` (for example,\n ``projects/415104041262``). Deleting all labels requires an\n update mask for labels field.\n\n The caller must have ``resourcemanager.projects.update``\n permission for this project.\n\n Returns:\n Callable[[~.UpdateProjectRequest],\n Awaitable[~.Operation]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"update_project\" not in self._stubs:\n self._stubs[\"update_project\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.resourcemanager.v3.Projects/UpdateProject\",\n request_serializer=projects.UpdateProjectRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs[\"update_project\"]\n\n @property\n def move_project(\n self,\n ) -> Callable[[projects.MoveProjectRequest], Awaitable[operations_pb2.Operation]]:\n r\"\"\"Return a callable for the move project method over gRPC.\n\n Move a project to another place in your resource hierarchy,\n under a new resource parent.\n\n Returns an operation which can be used to track the process of\n the project move workflow. Upon success, the\n ``Operation.response`` field will be populated with the moved\n project.\n\n The caller must have ``resourcemanager.projects.move``\n permission on the project, on the project's current and proposed\n new parent.\n\n If project has no current parent, or it currently does not have\n an associated organization resource, you will also need the\n ``resourcemanager.projects.setIamPolicy`` permission in the\n project.\n\n Returns:\n Callable[[~.MoveProjectRequest],\n Awaitable[~.Operation]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"move_project\" not in self._stubs:\n self._stubs[\"move_project\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.resourcemanager.v3.Projects/MoveProject\",\n request_serializer=projects.MoveProjectRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs[\"move_project\"]\n\n @property\n def delete_project(\n self,\n ) -> Callable[[projects.DeleteProjectRequest], Awaitable[operations_pb2.Operation]]:\n r\"\"\"Return a callable for the delete project method over gRPC.\n\n Marks the project identified by the specified ``name`` (for\n example, ``projects/415104041262``) for deletion.\n\n This method will only affect the project if it has a lifecycle\n state of\n [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE].\n\n This method changes the Project's lifecycle state from\n [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE]\n to\n [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Project.State.DELETE_REQUESTED].\n The deletion starts at an unspecified time, at which point the\n Project is no longer accessible.\n\n Until the deletion completes, you can check the lifecycle state\n checked by retrieving the project with [GetProject]\n [google.cloud.resourcemanager.v3.Projects.GetProject], and the\n project remains visible to [ListProjects]\n [google.cloud.resourcemanager.v3.Projects.ListProjects].\n However, you cannot update the project.\n\n After the deletion completes, the project is not retrievable by\n the [GetProject]\n [google.cloud.resourcemanager.v3.Projects.GetProject],\n [ListProjects]\n [google.cloud.resourcemanager.v3.Projects.ListProjects], and\n [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects]\n methods.\n\n This method behaves idempotently, such that deleting a\n ``DELETE_REQUESTED`` project will not cause an error, but also\n won't do anything.\n\n The caller must have ``resourcemanager.projects.delete``\n permissions for this project.\n\n Returns:\n Callable[[~.DeleteProjectRequest],\n Awaitable[~.Operation]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"delete_project\" not in self._stubs:\n self._stubs[\"delete_project\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.resourcemanager.v3.Projects/DeleteProject\",\n request_serializer=projects.DeleteProjectRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs[\"delete_project\"]\n\n @property\n def undelete_project(\n self,\n ) -> Callable[\n [projects.UndeleteProjectRequest], Awaitable[operations_pb2.Operation]\n ]:\n r\"\"\"Return a callable for the undelete project method over gRPC.\n\n Restores the project identified by the specified ``name`` (for\n example, ``projects/415104041262``). You can only use this\n method for a project that has a lifecycle state of\n [DELETE_REQUESTED] [Projects.State.DELETE_REQUESTED]. After\n deletion starts, the project cannot be restored.\n\n The caller must have ``resourcemanager.projects.undelete``\n permission for this project.\n\n Returns:\n Callable[[~.UndeleteProjectRequest],\n Awaitable[~.Operation]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"undelete_project\" not in self._stubs:\n self._stubs[\"undelete_project\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.resourcemanager.v3.Projects/UndeleteProject\",\n request_serializer=projects.UndeleteProjectRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs[\"undelete_project\"]\n\n @property\n def get_iam_policy(\n self,\n ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]:\n r\"\"\"Return a callable for the get iam policy method over gRPC.\n\n Returns the IAM access control policy for the specified project,\n in the format ``projects/{ProjectIdOrNumber}`` e.g.\n projects/123. Permission is denied if the policy or the resource\n do not exist.\n\n Returns:\n Callable[[~.GetIamPolicyRequest],\n Awaitable[~.Policy]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"get_iam_policy\" not in self._stubs:\n self._stubs[\"get_iam_policy\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.resourcemanager.v3.Projects/GetIamPolicy\",\n request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString,\n response_deserializer=policy_pb2.Policy.FromString,\n )\n return self._stubs[\"get_iam_policy\"]\n\n @property\n def set_iam_policy(\n self,\n ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]:\n r\"\"\"Return a callable for the set iam policy method over gRPC.\n\n Sets the IAM access control policy for the specified project, in\n the format ``projects/{ProjectIdOrNumber}`` e.g. projects/123.\n\n CAUTION: This method will replace the existing policy, and\n cannot be used to append additional IAM settings.\n\n Note: Removing service accounts from policies or changing their\n roles can render services completely inoperable. It is important\n to understand how the service account is being used before\n removing or updating its roles.\n\n The following constraints apply when using ``setIamPolicy()``:\n\n - Project does not support ``allUsers`` and\n ``allAuthenticatedUsers`` as ``members`` in a ``Binding`` of\n a ``Policy``.\n\n - The owner role can be granted to a ``user``,\n ``serviceAccount``, or a group that is part of an\n organization. For example, group@myownpersonaldomain.com\n could be added as an owner to a project in the\n myownpersonaldomain.com organization, but not the\n examplepetstore.com organization.\n\n - Service accounts can be made owners of a project directly\n without any restrictions. However, to be added as an owner, a\n user must be invited using the Cloud Platform console and\n must accept the invitation.\n\n - A user cannot be granted the owner role using\n ``setIamPolicy()``. The user must be granted the owner role\n using the Cloud Platform Console and must explicitly accept\n the invitation.\n\n - Invitations to grant the owner role cannot be sent using\n ``setIamPolicy()``; they must be sent only using the Cloud\n Platform Console.\n\n - If the project is not part of an organization, there must be\n at least one owner who has accepted the Terms of Service\n (ToS) agreement in the policy. Calling ``setIamPolicy()`` to\n remove the last ToS-accepted owner from the policy will fail.\n This restriction also applies to legacy projects that no\n longer have owners who have accepted the ToS. Edits to IAM\n policies will be rejected until the lack of a ToS-accepting\n owner is rectified. If the project is part of an\n organization, you can remove all owners, potentially making\n the organization inaccessible.\n\n Returns:\n Callable[[~.SetIamPolicyRequest],\n Awaitable[~.Policy]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"set_iam_policy\" not in self._stubs:\n self._stubs[\"set_iam_policy\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.resourcemanager.v3.Projects/SetIamPolicy\",\n request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString,\n response_deserializer=policy_pb2.Policy.FromString,\n )\n return self._stubs[\"set_iam_policy\"]\n\n @property\n def test_iam_permissions(\n self,\n ) -> Callable[\n [iam_policy_pb2.TestIamPermissionsRequest],\n Awaitable[iam_policy_pb2.TestIamPermissionsResponse],\n ]:\n r\"\"\"Return a callable for the test iam permissions method over gRPC.\n\n Returns permissions that a caller has on the specified project,\n in the format ``projects/{ProjectIdOrNumber}`` e.g.\n projects/123..\n\n Returns:\n Callable[[~.TestIamPermissionsRequest],\n Awaitable[~.TestIamPermissionsResponse]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"test_iam_permissions\" not in self._stubs:\n self._stubs[\"test_iam_permissions\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.resourcemanager.v3.Projects/TestIamPermissions\",\n request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString,\n response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString,\n )\n return self._stubs[\"test_iam_permissions\"]\n\n def close(self):\n return self.grpc_channel.close()\n\n @property\n def get_operation(\n self,\n ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:\n r\"\"\"Return a callable for the get_operation method over gRPC.\"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"get_operation\" not in self._stubs:\n self._stubs[\"get_operation\"] = self.grpc_channel.unary_unary(\n \"/google.longrunning.Operations/GetOperation\",\n request_serializer=operations_pb2.GetOperationRequest.SerializeToString,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs[\"get_operation\"]\n\n\n__all__ = (\"ProjectsGrpcAsyncIOTransport\",)\n","sub_path":"packages/google-cloud-resource-manager/google/cloud/resourcemanager_v3/services/projects/transports/grpc_asyncio.py","file_name":"grpc_asyncio.py","file_ext":"py","file_size_in_byte":31878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"347246926","text":"import json\n\nfrom bokeh.embed import components\nfrom bokeh.plotting import figure\nfrom bokeh.models import (\n NumeralTickFormatter,\n HoverTool,\n ColumnDataSource,\n AjaxDataSource,\n CustomJS,\n Slider\n)\nfrom bokeh.layouts import column, widgetbox\n\n\ndef ajax_bar_chart(url, title):\n \"\"\"Create a bar chart of resource outages that polls a RESTful\n endpoint for data\n\n Args:\n url (str): the RESTful endpoint\n title (str): the chart title\n\n Returns: the script and dev components to embed in a template\n \"\"\"\n # Setup AjaxDataSource\n source = AjaxDataSource(\n data_url=url,\n polling_interval=20000,\n method='GET',\n mode='replace'\n )\n source.data = dict(x=[.5, 1.5, 2.5, 3.5], y=[0, 0, 0, 0])\n\n # Setup and format figure\n x_axis = ['NATURAL GAS', 'SOLAR', 'HYDRO', 'WIND']\n fig = figure(\n title=title,\n x_range=x_axis,\n plot_width=100,\n plot_height=60,\n sizing_mode='scale_width',\n tools='save'\n )\n fig.yaxis.axis_label = \"MW of Outages\"\n fig.xgrid.grid_line_color = None\n fig.xaxis.major_tick_line_color = None\n fig.xaxis.minor_tick_line_color = None\n\n fig.vbar(x='x', top='y', source=source, width=.3, fill_color='#b3ccdb')\n\n # Create script and div elements for embedding\n script, div = components(fig)\n return {'script': script, 'div': div}\n\n\ndef ajax_map(url, title):\n \"\"\"Create a map of outages in California\n\n Args:\n url (str): the RESTful endpoint\n title (str): the chart title\n\n Returns: the script and dev components to embed in a template\n \"\"\"\n # Setup AjaxDataSource\n outage_source = AjaxDataSource(\n data_url=url,\n polling_interval=20000,\n method='GET',\n mode='replace'\n )\n outage_source.data = dict(\n lon=[],\n lat=[],\n unit_name=[],\n fuel_type=[],\n forced=[],\n curtailment=[],\n size=[],\n color=[]\n )\n\n # Figure settings\n hover = HoverTool(tooltips=[\n (\"Unit Name\", \"@unit_name\"),\n (\"Fuel Type\", \"@fuel_type\"),\n (\"Outage Type\", \"@forced\"),\n (\"Curtailment (MW)\", \"@curtailment\")\n ])\n tools = [hover, 'save']\n fig = figure(\n title=title,\n tools=tools,\n plot_width=100,\n plot_height=120,\n sizing_mode='scale_width',\n\n )\n fig.grid.grid_line_color = None\n fig.axis.visible = False\n\n # Add state boundries\n with open('resources/ca.json') as ca_json:\n map = json.loads(ca_json.read())\n map_source = ColumnDataSource(\n data=dict(\n lat=map['lats'],\n lon=map['lons']\n )\n )\n fig.patch(\n x='lon',\n y='lat',\n source=map_source,\n line_color=\"black\",\n line_width=1,\n fill_color=None\n )\n\n # Add outage locations\n fig.square(\n x='lon',\n y='lat',\n size='size',\n color='color',\n source=outage_source\n )\n\n # Create script and div elements for embedding\n script, div = components(fig)\n return {'script': script, 'div': div}\n\n\ndef ajax_line_chart(url, title=None):\n \"\"\"Create a line chart of resource outages that polls a RESTful endpoint\n for data\n\n Args:\n url (str): the RESTful endpoint\n title (str): the chart title\n\n Returns: the script and dev components to embed in a template\n \"\"\"\n # Setup AjaxDataSource\n source = AjaxDataSource(\n data_url=url,\n polling_interval=20000,\n method='GET',\n mode='replace'\n )\n source.data = dict(\n x=[i for i in range(30)],\n natgas=[0 for i in range(30)],\n sun=[0 for i in range(30)],\n wind=[0 for i in range(30)],\n water=[0 for i in range(30)]\n )\n\n # Setup and format figure\n fig = figure(\n title=title,\n x_axis_type='datetime',\n plot_width=100,\n plot_height=60,\n sizing_mode='scale_width',\n tools='save'\n )\n fig.yaxis.formatter = NumeralTickFormatter(format='0 %')\n fig.yaxis.axis_label = \"Percent of Resource\"\n fig.xgrid.grid_line_color = None\n fig.xaxis.major_tick_line_color = None\n fig.xaxis.minor_tick_line_color = None\n\n fig.line(\n x='x', y='natgas', source=source,\n legend='NATURAL GAS', color='#ff0000', line_width=1\n )\n fig.line(\n x='x', y='sun', source=source,\n legend='SOLAR', color='#ffff00', line_width=1\n )\n fig.line(\n x='x', y='wind', source=source,\n legend='WIND', color='#cc0099', line_width=1\n )\n fig.line(\n x='x', y='water', source=source,\n legend='HYDRO', color='#0000cc', line_width=1\n )\n\n fig.legend.location = \"top_left\"\n fig.legend.orientation = 'horizontal'\n\n # Create script and div elements for embedding\n script, div = components(fig)\n return {'script': script, 'div': div}\n\n\ndef regional_forecast(load_forecast, intensity_forecast):\n \"\"\"\n\n Args:\n load_forecast:\n intensity_forecast:\n\n Returns:\n\n \"\"\"\n # Import data from bokeh\n from bokeh.sampledata import us_states\n from bokeh.palettes import Viridis256 as palette\n\n us_states = us_states.data.copy()\n del us_states[\"HI\"]\n del us_states[\"AK\"]\n\n hover = HoverTool(tooltips=[\n (\"State\", \"@state\"),\n (\"Region\", \"@region\"),\n (\"Forecast (MW)\", \"@forecast\"),\n (\"Load Intensity (0.0 - 1.0)\", \"@intensity\")\n ])\n tools = [hover, 'save']\n fig = figure(\n tools=tools,\n plot_width=1100,\n plot_height=700\n )\n\n base = [0, 1, 1, 0]\n state_xs = [[cord + i for cord in base] for i in range(10)]\n state_ys = [[0, 0, 1, 1] for i in range(10)]\n regions = [\n 'northwest',\n 'central',\n 'midatlantic',\n 'northeast',\n 'southwest',\n 'southeast',\n 'florida',\n 'california',\n 'carolinas',\n 'lower48'\n ]\n forecast = load_forecast.iloc[0]\n intensity = intensity_forecast.iloc[0]\n forecast_data = load_forecast.T.values.tolist()\n intensity_data = intensity_forecast.T.values.tolist()\n\n palette.reverse()\n color_mapper = [palette[int(value * 256) - 1] for value in intensity]\n\n source = ColumnDataSource(\n data=dict(\n x=state_xs,\n y=state_ys,\n region=regions,\n forecast=forecast,\n forecast_data=forecast_data,\n intensity=intensity,\n intensity_data=intensity_data,\n colors=color_mapper,\n )\n )\n\n fig.patches(\n 'x', 'y',\n source=source,\n fill_alpha=0.7,\n fill_color='colors',\n line_color=\"black\",\n line_alpha=0.5,\n line_width=1\n )\n\n js_palette = ColumnDataSource(data=dict(palette=palette))\n callback = CustomJS(args=dict(source=source, palette=js_palette), code=\"\"\"\n var data = source.data;\n var p = palette.data['palette']\n var h = hour.value;\n\n color = data['colors']\n forecast = data['forecast']\n intensity = data['intensity']\n forecast_data = data['forecast_data']\n intensity_data = data['intensity_data']\n for (i = 0; i < forecast.length; i++) {\n forecast[i] = forecast_data[i][h-1];\n intensity[i] = intensity_data[i][h-1];\n color[i] = p[Math.floor((intensity[i] * 256)-1)]\n }\n source.change.emit();\n \"\"\")\n\n hour_slider = Slider(start=1, end=10, value=1, step=1,\n title=\"Hour\", callback=callback)\n callback.args[\"hour\"] = hour_slider\n\n layout = column(fig, widgetbox(hour_slider))\n\n script, div = components(layout)\n final_figure = {'script': script, 'div': div}\n\n return final_figure\n\n\nif __name__ == '__main__':\n ajax_line_chart(\n 'http://localhost:5000/dashboard-api/outage-history-chart',\n 'test'\n )\n","sub_path":"visuals.py","file_name":"visuals.py","file_ext":"py","file_size_in_byte":7958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"227179636","text":"# 리스트의 최대값, 최소값, 정렬\n\nscore = [79, 80, 50, 60, 90, 45]\n\nmax = score[0]\nn= len(score)\n\n\nfor i in range(1,n):\n if score[0] < score[i]:\n max = score[i]\nprint('최대값 : ', max)\n\nprint('='*50)\n\n#간단하게 정렬하는 방법은 sort()메서드를 호출한다. 다만 구문형식을 주의하라.\nscore.sort() #먼저 메서드를 써서 리스트를 정렬하고 이것은 오름차순\nprint('sort()함수 오름차순 정렬 : ', score) #출력해본다.\n\nscore.reverse()\nprint('reverse()함수 내림차순 정렬 : ', score)\n\nprint('='*50)\n\n\n#알로리즘을 짜서 오름차순 정렬하기 : 이거 생각할 알고리즘 과정이 길다.\n#리스트 요소를 순차정렬하려면 반드시 행렬을 생성하고 변수 교환까지 짜야 한다.\n\nfor i in range(0, n):\n for j in range(0, n-1):\n if score[j] > score[j+1]:\n score[j], score[j+1] = score[j+1], score[j]\n\nprint('알고리즘 오름차순 정렬 : ', score)\n\nprint('='*50)\n\n\n'''\n반복문 수행과정 추\n#1행\n79, 50, 60, 80, 45, 90\n#2행\n50 60 79 45 80 90\n#3행\n50 60 45 79 80 90\n#4행\n50 45 60 79 80 90\n#5행\n45 50 60 79 80 90 : 완성\n'''\n\n\n\n \n \n","sub_path":"ch04/py0504listcalc_minmaxalign.py","file_name":"py0504listcalc_minmaxalign.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"579504077","text":"# Kevin \n# 2017.06.10\n# ================================================================\n\"\"\"An implement of Bidirectional Recurrent Neural Network(LSTM) with MNIST data using Tensorflow\"\"\"\n\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nfrom tensorflow.contrib import rnn\n\nmnist = input_data.read_data_sets('/tmp/MNIST_data/', one_hot=True)\n\n# Basic model parameters\nlearning_rate = 1e-4\ntraining_epoch = 1000\nbatch_size = 100\ndisplay_step = 1\n\n# Network Parameters\nn_input = 28 # MNIST data input ( img shape: 28*28 )\nn_steps = 28 # timesteps\nn_hidden = 128 # hidden layer num of features\nn_classes = 10 # MNIST total classes ( 0-9 digits )\n\n\n# tf Graph input\nx = tf.placeholder(tf.float32, [None, n_steps, n_input])\ny = tf.placeholder(tf.float32, [None, n_classes])\n\n\n# Define weights & biases\nweights = {\n 'out':tf.Variable(tf.random_normal([2*n_hidden, n_classes]))\n}\n\nbiases = {\n 'out':tf.Variable(tf.random_normal([n_classes]))\n}\n\ndef BiRNN(x, weights, biases):\n # Unstack to get a list of 'n_steps' tensor of shape (batch_size, n_input)\n x = tf.unstack(x, n_steps, 1)\n \n # Define lstm cells with tensorflow\n # Forward direction cell\n lstm_fw_cell = rnn.BasicLSTMCell(n_hidden, forget_bias=1.0)\n # Backward direction cell\n lstm_bw_cell = rnn.BasicLSTMCell(n_hidden, forget_bias=1.0)\n \n # Get lstm cell output\n outputs, _, _ = rnn.static_bidirectional_rnn(lstm_fw_cell, lstm_bw_cell, x, dtype=tf.float32)\n \n return tf.add(tf.matmul(outputs[-1], weights['out']), biases['out'])\n\n\nlogits = BiRNN(x, weights, biases)\n\n# Define loss and optimizer\nloss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))\noptimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss)\n\n# Evaluation\ncorrect_prediction = tf.equal(tf.arg_max(logits, 1), tf.arg_max(y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n# Initialize\ninit = tf.global_variables_initializer()\nsess = tf.InteractiveSession()\n\nsess.run(init)\n\n\nwith tf.device('/cpu:0'):\n training_images = mnist.train.images.reshape([mnist.train.num_examples, n_steps, n_input])\n training_labels = mnist.train.labels\n testing_images = mnist.test.images.reshape([mnist.test.num_examples, n_steps, n_input])\n testing_labels = mnist.test.labels\n\n# training & testing & displaying\nfor epoch in range(training_epoch):\n total_batch = int(mnist.train.num_examples/batch_size)\n for i in range(total_batch):\n batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n batch_xs = batch_xs.reshape([batch_size, n_steps, n_input])\n \n sess.run(optimizer, feed_dict={x:batch_xs, y:batch_ys})\n if epoch % display_step == 0:\n print('Epoch: %d, training loss: %.4f, training accuracy: %.4f,testing loss: %.4f, testing accuracy: %.4f'\n %(epoch+1, \n sess.run(loss, feed_dict={x:training_images, y:training_labels}),\n sess.run(accuracy, feed_dict={x:training_images, y:training_labels}),\n sess.run(loss, feed_dict={x:testing_images, y:testing_labels}),\n sess.run(accuracy, feed_dict={x:testing_images, y:testing_labels})))\n","sub_path":"birnn_mnist/birnn_mnist.py","file_name":"birnn_mnist.py","file_ext":"py","file_size_in_byte":3207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"426477711","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Katale', '0005_auto_20150818_1406'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='CartItem',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('cart_id', models.CharField(max_length=50)),\n ('date_added', models.DateTimeField(auto_now_add=True)),\n ('quantity', models.PositiveIntegerField(default=1)),\n ('product', models.ForeignKey(to='Katale.Product')),\n ],\n options={\n 'ordering': ['date_added'],\n 'db_table': 'Cart_Items',\n },\n ),\n ]\n","sub_path":"Katale/migrations/0006_cartitem.py","file_name":"0006_cartitem.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"609709499","text":"try:\n from io import BytesIO\nexcept ImportError:\n BytesIO = None\n import StringIO\nfrom base64 import b64decode\nimport collections\nimport json\nimport mimetypes\n\nfrom apiclient.discovery import build\nfrom apiclient.errors import HttpError\nfrom django.conf import settings\nfrom django.core.files.base import ContentFile\nfrom django.core.validators import URLValidator\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom jsonfield.fields import JSONField\nfrom psi.settings import PsiAppConf\n\n\nmimetypes.init()\n\n\nclass PageInsight(models.Model):\n STRATEGY_DESKTOP = 'desktop'\n STRATEGY_MOBILE = 'mobile'\n STRATEGY_CHOICES = (\n (STRATEGY_DESKTOP, 'Desktop'),\n (STRATEGY_MOBILE, 'Mobile'),\n )\n\n STATUS_PENDING = 'pending'\n STATUS_CONSUMING = 'consuming'\n STATUS_CONSUMED = 'consumed'\n STATUS_POPULATED = 'populated'\n STATUS_ERROR = 'error'\n STATUS_CHOICES = (\n (STATUS_PENDING, 'Pending'),\n (STATUS_CONSUMING, 'Consuming'),\n (STATUS_CONSUMED, 'Consumed'),\n (STATUS_POPULATED, 'Populated'),\n (STATUS_ERROR, 'Error'),\n )\n\n # Mandatory fields\n url = models.URLField(_('URL'), max_length=191, db_index=True)\n strategy = models.CharField(_('Strategy'), max_length=50, choices=STRATEGY_CHOICES, db_index=True)\n locale = models.CharField(_('Locale'), max_length=16, default='en_US')\n # Managed fields\n status = models.CharField(_('Status'), max_length=32, choices=STATUS_CHOICES, db_index=True)\n created = models.DateTimeField(_('Date Created'), auto_now_add=True)\n updated = models.DateTimeField(_('Date Updated'), auto_now=True)\n # Populated fields\n response_code = models.IntegerField(_('Response Code'), default=0)\n title = models.CharField(_('Page Title'), max_length=255)\n score = models.IntegerField(_('Score'), default=0)\n number_resources = models.IntegerField(_('Number of Resources'), default=0)\n number_hosts = models.IntegerField(_('Number of Hosts'), default=0)\n total_request_bytes = models.IntegerField(_('Total Request Bytes'), default=0)\n number_static_resources = models.IntegerField(_('Number of Static Resources'), default=0)\n html_response_bytes = models.IntegerField(_('HTML Response Bytes'), default=0)\n css_response_bytes = models.IntegerField(_('CSS Response Bytes'), default=0)\n image_response_bytes = models.IntegerField(_('Image Response Bytes'), default=0)\n javascript_response_bytes = models.IntegerField(_('Javascript Response Bytes'), default=0)\n other_response_bytes = models.IntegerField(_('Other Response Bytes'), default=0)\n number_js_resources = models.IntegerField(_('Number of JS Resources'), default=0)\n number_css_resources = models.IntegerField(_('Number of CSS Resources'), default=0)\n json = JSONField(_('JSON Response'), load_kwargs={'object_pairs_hook': collections.OrderedDict})\n\n def __unicode__(self):\n return _('%s (%s)') % (self.url, self.created.date())\n\n def set_consuming(self):\n self.status = self.STATUS_CONSUMING\n self.save()\n\n def set_consumed(self):\n self.status = self.STATUS_CONSUMED\n self.save()\n\n def set_populated(self):\n self.status = self.STATUS_POPULATED\n self.save()\n\n def set_error(self):\n self.status = self.STATUS_ERROR\n self.save()\n\n def consume(self):\n \"\"\"\n Retrieve the Google Page Insight data from the API.\n \"\"\"\n try:\n self.set_consuming()\n\n # Ensure we have a valid url\n URLValidator(self.url)\n\n # Build api service\n service = build(serviceName='pagespeedonline', \n version='v1', \n developerKey=getattr(settings, 'GOOGLE_API_KEY', None))\n\n # Make request\n data = service.pagespeedapi().runpagespeed(url=self.url,\n strategy=self.strategy,\n locale=self.locale,\n screenshot=settings.PSI_SCREENSHOT).execute()\n # Save json before we continue\n self.json = data\n self.set_consumed()\n return data\n\n except HttpError as e:\n self.json = json.loads(e.content)\n self.set_error()\n raise\n except Exception:\n self.set_error()\n raise\n\n def populate(self, data=None):\n \"\"\"\n Populate this insight from the API.\n \"\"\"\n if data is None:\n data = self.consume()\n\n self.response_code = data[\"responseCode\"]\n self.title = data[\"title\"]\n self.score = data[\"score\"]\n self.url = data['id']\n self.number_resources = data['pageStats'].get(\"numberResources\")\n self.number_hosts = data['pageStats'][\"numberHosts\"]\n self.total_request_bytes = int(data['pageStats'][\"totalRequestBytes\"])\n self.number_static_resources = data['pageStats'].get(\"numberStaticResources\", 0)\n self.html_response_bytes = int(data['pageStats'][\"htmlResponseBytes\"])\n self.css_response_bytes = int(data['pageStats'].get(\"cssResponseBytes\", 0))\n self.image_response_bytes = int(data['pageStats'].get(\"imageResponseBytes\", 0))\n self.javascript_response_bytes = int(data['pageStats'].get(\"javascriptResponseBytes\", 0))\n self.other_response_bytes = int(data['pageStats'].get(\"otherResponseBytes\", 0))\n self.number_js_resources = int(data['pageStats'].get(\"numberJsResources\", 0))\n self.number_css_resources = int(data['pageStats'].get(\"numberCssResources\", 0))\n self.save()\n\n if settings.PSI_SCREENSHOT and data.get('screenshot'):\n screenshot = Screenshot()\n screenshot.page_insight = self\n screenshot.width = data.get('screenshot').get('width')\n screenshot.height = data.get('screenshot').get('height')\n screenshot.mime_type = data.get('screenshot').get('mime_type')\n\n # Write file to memory\n if BytesIO:\n f = BytesIO(b64decode(data.get('screenshot').get('data').replace('_', '/').replace('-', '+')))\n else:\n f = StringIO.StringIO(b64decode(data.get('screenshot').get('data').replace('_', '/').replace('-', '+')))\n # Determine the file extension\n ext = mimetypes.guess_extension(screenshot.mime_type)\n # Save to disk\n screenshot.image.save('screenshot%s' % ext, ContentFile(f.read()))\n\n screenshot.save()\n\n # Save the rules\n for key, values in data.get('formattedResults').get('ruleResults').items():\n ruleResult = RuleResult()\n ruleResult.page_insight = self\n ruleResult.title = values.get('localizedRuleName')\n ruleResult.impact = values.get('ruleImpact')\n ruleResult.description = values.get('urlBlocks')[0]['header']['format']\n ruleResult.save()\n\n self.set_populated()\n\n\nclass RuleResult(models.Model):\n page_insight = models.ForeignKey(PageInsight, related_name='rule_results')\n title = models.CharField(_('Page Title'), max_length=255)\n impact = models.FloatField(_('Impact'))\n description = models.TextField(_('Description'), blank=True, null=True)\n\n class Meta:\n verbose_name_plural = _('Rule Results')\n\n def __unicode__(self):\n return self.title\n\n\ndef screenshot_upload_to(instance, filename):\n \"\"\"\n Return the upload path for a screenshot.\n \"\"\"\n return '%s/%s/%s' % (settings.PSI_MEDIA_PATH, instance.page_insight.pk, filename)\n\n\nclass Screenshot(models.Model):\n page_insight = models.OneToOneField(PageInsight, related_name='screenshot')\n width = models.IntegerField(_('Width'))\n height = models.IntegerField(_('Height'))\n mime_type = models.CharField(_('Mime Type'), max_length=32)\n image = models.ImageField(_('Image'), max_length=255, upload_to=screenshot_upload_to)\n\n def __unicode__(self):\n return _('Screenshot for %s') % self.page_insight\n","sub_path":"psi/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"56239831","text":"import numpy as np\nfrom scipy import fftpack\nfrom operator import mul\nimport matplotlib.pyplot as plt\nimport progressbar\n\ndef fourier_transform(m):\n return fftpack.fft2(m)\n\n\ndef chi_square(ft_simulation, ft_image):\n return np.sum((np.square(abs(abs(ft_simulation) - abs(ft_image))) / abs(ft_image)))\n\n\n# def DFT_Matrix(x_old, y_old, x_new, y_new, F_old, simulated_image):\n# before_row, before_column = F_old[x_old, :], F_old[:, y_old]\n# F_s = fourier_transform(simulated_image)\n# after_row, after_column = F_s[x_new, :], F_s[:, y_new]\n# U_new = np.outer(after_column, after_row)\n# U_old = np.outer(before_column, before_row)\n# U = U_new - U_old\n# return U\n\n\ndef Metropolis(x_old, y_old, x_new, y_new, old_point, new_point, delta_chi, simulated_image, T, acceptance, chi_old,\n chi_new):\n if delta_chi < 0:\n simulated_image[x_old][y_old] = new_point\n simulated_image[x_new][y_new] = old_point\n acceptance += 1.0\n chi_old = chi_new\n else:\n b = np.exp(-delta_chi / T)\n if b > np.random.rand():\n simulated_image[x_old][y_old] = new_point\n simulated_image[x_new][y_new] = old_point\n acceptance += 1.0\n chi_old = chi_new\n else:\n simulated_image[x_old][y_old] = old_point\n simulated_image[x_new][y_new] = new_point\n return acceptance, chi_old\n\ndef random_initial(image:np.array):\n initial = np.zeros_like(image)\n initial2 = initial.reshape(mul(*image.shape))\n initial2[: np.count_nonzero(image == 1)] = 1\n np.random.shuffle(initial2)\n initial = initial2.reshape(image.shape)\n return initial\n\ndef rmc(image:np.array, T, initial:np.array=None):\n if initial is None:\n initial = random_initial(image)\n\n simulated_image = initial.copy()\n F_image = fourier_transform(image)\n F_old = fourier_transform(simulated_image)\n chi_old = chi_square(F_old, F_image)\n for _ in progressbar.progressbar(range(0, 30000)):\n move_count = 0.0\n acceptance = 0.0\n for _ in range(np.count_nonzero(simulated_image == 1)):\n move_count += 1\n # before_move = simulated_image.copy()\n x_old = np.random.randint(0, image.shape[0])\n y_old = np.random.randint(0, image.shape[1])\n while simulated_image[x_old][y_old] != 1:\n x_old = np.random.randint(0, image.shape[0])\n y_old = np.random.randint(0, image.shape[1])\n x_new = np.random.randint(0, image.shape[0])\n y_new = np.random.randint(0, image.shape[1])\n old_point = simulated_image[x_old][y_old]\n new_point = simulated_image[x_new][y_new]\n while new_point == old_point:\n x_new = np.random.randint(0, image.shape[0])\n y_new = np.random.randint(0, image.shape[1])\n new_point = simulated_image[x_new][y_new]\n simulated_image[x_old][y_old] = new_point\n simulated_image[x_new][y_new] = old_point\n old_array = np.zeros_like(image)\n old_array[x_old][y_old] = 1\n new_array = np.zeros_like(image)\n new_array[x_new][y_new] = 1\n # U = DFT_Matrix(x_old, y_old, x_new, y_new, F_old, simulated_image)\n F_new = F_old - fourier_transform(old_array) + fourier_transform(new_array)\n chi_new = chi_square(F_new, F_image)\n delta_chi = chi_new - chi_old\n acceptance, chi_old = Metropolis(x_old, y_old, x_new, y_new, old_point, new_point, delta_chi,\n simulated_image, T, acceptance, chi_old, chi_new)\n F_old = fourier_transform(simulated_image)\n T = T * 0.9998\n\n return simulated_image\n","sub_path":"hiprmc/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"172907432","text":"#!/usr/bin/env python3\r\n# encoding: utf-8-\r\n\"\"\"\r\nA utility program to install a SaltStack minion, and optionally, a master with cloud controller.\r\n\r\narguments: add one or more file_roots and pillar_roots entries. \"[]\" are optional, spaces not permitted.\r\n --add-roots=[path/to/directory1,path/to/directory2]\r\n where each directory is expected to have a ./salt and ./pillar subdirectory\r\n If you use a definition like: --add-roots=[/full/path/to/directory1/local_salt=../directory1/local_salt]\r\n These entries will be mapped as Vagrant shared directories,\r\n\r\nMaintenance command-line switches:\r\n --no-sudo = Do not attempt to run with elevated privileges, use the present level\r\n --no-read-settings = Do not read an existing BEVY_SETTINGS_FILE\r\n\"\"\"\r\nimport subprocess, os, getpass, json, socket, platform, ipaddress, sys, time\r\nfrom pathlib import Path, PurePosixPath\r\nfrom urllib.request import urlopen\r\n\r\ntry:\r\n import yaml\r\n import ifaddr\r\nexcept ImportError:\r\n print('\\nERROR: Python3 setup incomplete. You are missing required prerequisite modules.')\r\n if platform.system() == 'Windows':\r\n print('Try something like: \"py -3 -m pip install pyyaml ifaddr passlib\"')\r\n print('If \"pip\" is not found, you may need to exit and re-open your console window.')\r\n elif platform.system() == 'Darwin': # MacOS\r\n print('Try something like: \"sudo -H pip3 install pyyaml ifaddr passlib\"')\r\n else: # Linux\r\n print('Try something like: \"sudo pip3 install pyyaml ifaddr\"')\r\n print('If you are using Ubuntu (Debian, etc), you may need to \"sudo apt install python3-pip\" first.')\r\n print('Then re-run this command.')\r\n sys.exit(10) # Windows ERROR_BAD_ENVIRONMENT\r\n\r\n# import modules from this directory\r\n# noinspection PyUnresolvedReferences\r\nimport pwd_hash\r\n# noinspection PyUnresolvedReferences\r\nimport sudo\r\n\r\n\r\n# # # # #\r\n# This program attempts to establish a DRY single source of truth as the file\r\nBEVY_SETTINGS_FILE_NAME = '/srv/pillar/01_bevy_settings.sls'\r\n# That should actually work in many (but not all) cases. It can be extended to more cases.\r\n#\r\n# Normal minions will receive their settings from the Bevy Master.\r\n# If the Bevy Master is a stand-alone server, it might be a \"good idea\" to connect its /srv directory to\r\n# the /srv directory on your Workstation using a deployment engine such as PyCharm's.\r\n#\r\n# .. A given machine in the Bevy could be a Workstation, a bevy_master (perhaps as a local VM on a workstation),\r\n# or a bevy minion which is a headless server for some service (perhaps also as a local VM).\r\n# Any of these (except a local VM) might very possibly already have been a minion of some other Salt Master\r\n# before our bevy arrives on the scene. We may want to preserve that minion's connection.\r\n# We will attempt to detect that situation, and we will use the setting \"additional_minion_tag\" (which may contain\r\n# \"\" or a string literal \"2\") to allow both minions to operate side-by-side.\r\n# It theoretically might work to have \"additional_minion_tag\" be any of the values \"3\" through \"Z\",\r\n# if we were running three or more minions, but that situation would be really weird.\r\n# # # # #\r\nMY_SETTINGS_FILE_NAME = '/etc/salt-bevy_my_settings.conf' # settings specific to the currant machine\r\nMINIMUM_SALT_VERSION = \"2018.3.0\" # ... as a string... the month will be converted to an integer below\r\nSALT_BOOTSTRAP_URL = \"http://bootstrap.saltstack.com/stable/bootstrap-salt.sh\"\r\nSALT_DOWNLOAD_SOURCE = \"stable\"\r\n\r\nSALT_SRV_ROOT = '/srv/salt'\r\nSALT_PILLAR_ROOT = '/srv/pillar'\r\n# the path to write the bootstrap Salt Minion configuration file\r\nSALTCALL_CONFIG_FILE = '/srv/saltcall_config/minion'\r\nGUEST_MASTER_CONFIG_FILE = '/srv/bevymaster_config/minion'\r\nGUEST_MINION_CONFIG_FILE = '/srv/guest_config/minion'\r\nWINDOWS_GUEST_CONFIG_FILE = '/srv/windows_config/minion'\r\n\r\nDEFAULT_VAGRANT_PREFIX = '172.17' # first two bytes of Vagrant private network\r\nDEFAULT_VAGRANT_NETWORK = '172.17.0.0/16' # Vagrant private network\r\nDEFAULT_FQDN_PATTERN = '{}.{}.test' # .test is ICANN reserved for test networks.\r\n\r\nminimum_salt_version = MINIMUM_SALT_VERSION.split('.')\r\n# noinspection PyTypeChecker\r\nminimum_salt_version[1] = int(minimum_salt_version[1]) # use numeric compare of month field\r\nthis_file = Path(__file__).resolve() # the absolute path name of this program's source\r\nuser_ssh_key_file_directory = this_file.parent.parent / 'bevy_srv/salt/ssh_keys'\r\n\r\nargv = [s.strip() for s in sys.argv]\r\nif '--help' in argv:\r\n print(__doc__)\r\n exit()\r\n\r\nsettings = {} # global variable\r\nmy_settings = {}\r\n\r\ndef read_bevy_settings_files():\r\n global settings\r\n global my_settings\r\n\r\n def read_settings_file(provision_file_name):\r\n prov_file = Path(provision_file_name)\r\n try:\r\n print(\"Trying to read settings from '{}'\".format(prov_file))\r\n with prov_file.open() as provision_file:\r\n stored_settings = yaml.safe_load(provision_file.read()) or {}\r\n except (OSError, yaml.YAMLError) as e:\r\n print(\"Unable to read previous values from {} --> {}.\".format(provision_file_name, e))\r\n stored_settings = {}\r\n return stored_settings\r\n\r\n if '--no-read-settings' not in argv:\r\n settings = read_settings_file(BEVY_SETTINGS_FILE_NAME) # settings for entire bevy\r\n my_settings = read_settings_file(MY_SETTINGS_FILE_NAME) # settings for only this machine\r\n\r\n\r\ndef write_bevy_settings_files():\r\n def write_bevy_settings_file(bevy_settings_file_name, store_settings: dict, store_additional=False):\r\n try:\r\n # python 3.4\r\n os.makedirs(str(bevy_settings_file_name.parent), exist_ok=True)\r\n # python 3.5\r\n # bevy_settings_file_name.parent.mkdir(parents=True, exist_ok=True)\r\n with bevy_settings_file_name.open('w') as f:\r\n # creating a YAML file the hard way ...\r\n f.write('# This file was created by {}\\n'.format(this_file))\r\n f.write('# Manual edits here will also persist to become new default values.\\n')\r\n f.write('# (except when a tag is ALL_CAPS)\\n')\r\n for name, value in store_settings.items():\r\n if not name.isupper(): # ignore old Vagrant settings (added below)\r\n if isinstance(value, str): # single-quote strings in YAML values\r\n f.write(\"{}: '{}'\\n\".format(name, value))\r\n else: # Python repr() for everything else should work\r\n f.write('{}: {!r}\\n'.format(name, value))\r\n if store_additional:\r\n f.write('# settings for Vagrant to read...\\n') # NOTE: names are in UPPER_CASE\r\n #... f'strings' are only available in Python 3.5+ ! ...#\r\n # f.write(f\"SALTCALL_CONFIG_FILE: '{SALTCALL_CONFIG_FILE}'\\n\")\r\n # f.write(f\"GUEST_MASTER_CONFIG_FILE: '{GUEST_MASTER_CONFIG_FILE}'\\n\")\r\n # f.write(f\"GUEST_MINION_CONFIG_FILE: '{GUEST_MINION_CONFIG_FILE}'\\n\")\r\n # f.write(f\"WINDOWS_GUEST_CONFIG_FILE: '{WINDOWS_GUEST_CONFIG_FILE}'\\n\")\r\n f.write(\"SALTCALL_CONFIG_FILE: '{}'\\n\".format(SALTCALL_CONFIG_FILE))\r\n f.write(\"GUEST_MASTER_CONFIG_FILE: '{}'\\n\".format(GUEST_MASTER_CONFIG_FILE))\r\n f.write(\"GUEST_MINION_CONFIG_FILE: '{}'\\n\".format(GUEST_MINION_CONFIG_FILE))\r\n f.write(\"WINDOWS_GUEST_CONFIG_FILE: '{}'\\n\".format(WINDOWS_GUEST_CONFIG_FILE))\r\n print('File \"{}\" written.'.format(bevy_settings_file_name))\r\n print()\r\n except PermissionError:\r\n print('Sorry. Permission error trying to write {}'.format(bevy_settings_file_name))\r\n write_bevy_settings_file(Path(BEVY_SETTINGS_FILE_NAME), settings, store_additional=True)\r\n write_bevy_settings_file(Path(MY_SETTINGS_FILE_NAME), my_settings)\r\n\r\n\r\ndef get_additional_roots():\r\n '''\r\n set up lists for additional file_roots and pillar_root directories\r\n if the command line calls for them using --add-roots\r\n DIRTY! -- MODIFIES the contents of \"settings\"\r\n '''\r\n global settings\r\n add_roots = '--add-roots='\r\n len_ar = len(add_roots)\r\n more_parents = [] # list of additional file_roots directories\r\n try: # pick out the substring after \"=\" if --add-roots= exists as a CLI argument\r\n more = next((arg[len_ar:] for arg in argv if arg.startswith(add_roots)), '')\r\n if more: # divide up any comma-separated strings, strip [] & posixify\r\n more_parents = more.replace('\\\\', '/').strip('[').rstrip(']').split(',')\r\n except Exception:\r\n raise ValueError('Error in \"{}\" processing.'.format(add_roots))\r\n\r\n if len(settings.setdefault('application_roots', [])) + len(more_parents) == 0:\r\n return # quick silent return in default case\r\n print()\r\n print('Additional application state roots from old settings: {!r}'.format(settings['application_roots']))\r\n print('Additional application state roots from new CLI --add-roots: {}'.format(more_parents))\r\n default = 'k' if settings['application_roots'] else 'n' if more_parents else 'x'\r\n possibilites = 'knax'\r\n prompt = possibilites.replace(default, default.upper())\r\n resp = 'impossible'\r\n while resp not in possibilites:\r\n print('(K)Keep old, use (N)New, (A)Append both, or (X) use no eXtra apps.')\r\n resp = input('your choice? [{}]:'.format(prompt)) or default\r\n resp = resp.lower()\r\n for i, parent in enumerate(more_parents): # make relative paths absolute\r\n paths = parent.split('=')\r\n paths[0] = Path(paths[0]).resolve().as_posix()\r\n more_parents[i] = '='.join(paths)\r\n if resp == 'n':\r\n settings['application_roots'] = more_parents\r\n elif resp == 'a':\r\n settings['application_roots'] = settings['application_roots'] + more_parents\r\n elif resp == 'x':\r\n settings['application_roots'] = []\r\n\r\n\r\ndef format_additional_roots(settings, virtual):\r\n '''\r\n create formatted lists of Salt file-roots and pillar-roots directories\r\n :param settings: parsed YAML bevy_settings file\r\n :param virtual: creating path names for a VM?\r\n :return: a list of Salt file-roots and a list of pillar-roots\r\n '''\r\n def make_the_list(more_parents, condiment):\r\n some_roots = []\r\n for parent in more_parents:\r\n try:\r\n phys, virt = parent.split('=')\r\n except (ValueError, AttributeError):\r\n if virtual:\r\n raise ValueError(\r\n 'application root parameter \"{}\" should have real-path=virtual-name'.format(parent))\r\n else:\r\n phys = parent\r\n virt = NotImplemented\r\n dir = Path(phys) / condiment\r\n if dir.is_dir and dir.exists(): # extract the absolute path of any ./salt directory\r\n if virtual: # refer to the Vagrant shared path, not the real one\r\n virt_dir = PurePosixPath('/', virt) / condiment\r\n some_roots.append(str(virt_dir))\r\n else:\r\n some_roots.append(str(dir.resolve().as_posix()))\r\n else:\r\n print('WARNING: cannot find application directory \"{}\"'.format(dir))\r\n return some_roots\r\n\r\n more_parents = settings['application_roots']\r\n more_roots = make_the_list(more_parents, 'salt')\r\n more_pillars = make_the_list(more_parents, 'pillar')\r\n return more_roots, more_pillars\r\n\r\n\r\ndef write_config_file(config_file_name, is_master: bool, virtual=True, windows=False, master_host=False):\r\n '''\r\n writes a copy of the template, below, into a file in this /srv/salt directory\r\n substituting the actual path to the ../bevy_srv salt and pillar subdirectories,\r\n -- which will be used as the Salt minion configuration during the \"salt_state_apply\" function below.\r\n '''\r\n template = \"\"\"\r\n# initial configuration file for a bevy member.\r\n# from file: {0}\r\n# written by: {1}\r\n#\r\nmaster: {2}\r\n{5}\r\n{6}\r\nfile_roots: # states are searched in the given order -- first found wins\r\n base: {3!r}\r\ntop_file_merging_strategy: same # do not merge the top.sls file from srv/salt, just use it\r\n\r\npillar_roots: # all pillars are merged -- the last entry wins\r\n base: {4!r}\r\npillar_source_merging_strategy: recurse\r\n\r\nfile_ignore_regex:\r\n - '/\\.git($|/)'\r\n\r\nuse_superseded: # feature flags\r\n - module.run \r\n\r\nfileserver_backend:\r\n - roots\r\n \r\n# log_level_logfile: debug # uncomment this to get minion logs at debug level\r\n\"\"\"\r\n bevy_srv_path = PurePosixPath('/vagrant') if virtual else PurePosixPath(this_file.parent.parent.as_posix())\r\n master_url = settings.get('master_vagrant_ip', '') \\\r\n if master_host else settings.get('master_external_ip', '')\r\n master = 'localhost' if is_master else master_url\r\n id2m = my_settings.get('second_minion_id', 'none')\r\n id = '' if virtual else 'id: {}'.format(id2m if id2m.lower() != 'none' else my_settings['id'])\r\n local = 'file_client: local' if is_master else ''\r\n\r\n more_roots, more_pillars = format_additional_roots(settings, virtual)\r\n\r\n file_roots = ['/srv/salt'] + more_roots + [str(bevy_srv_path / 'bevy_srv/salt')]\r\n pillar_roots = ['/srv/pillar'] + more_pillars + [str(bevy_srv_path / 'bevy_srv/pillar')]\r\n\r\n os.makedirs(str(config_file_name.parent), exist_ok=True) # old Python 3.4 method\r\n # config_file_name.parent.mkdir(parents=True, exist_ok=True) # 3.5+\r\n newline = '\\r\\n' if windows else '\\n'\r\n try:\r\n with config_file_name.open('w', newline=newline) as config_file:\r\n config_file.write(template.format(config_file_name, this_file, master, file_roots, pillar_roots, id, local))\r\n print('file {} written'.format(str(config_file_name)))\r\n except PermissionError:\r\n print('Sorry. Permission error when trying to write {}'.format(str(config_file_name)))\r\n\r\n\r\ndef salt_state_apply(salt_state, **kwargs):\r\n '''\r\n Run a salt state using a standalone minion\r\n\r\n :param salt_state: Salt state command to send\r\n :param kwargs: keyword arguments ...\r\n expected keyword argements are:\r\n file_root: a salt fileserver environment.\r\n pillar_root: a Pillar environment.\r\n config_dir: a minion configuration environment.\r\n all other kwargs are assembled as pillar data.\r\n :return: None\r\n '''\r\n\r\n file_root = kwargs.pop('file_root', '')\r\n pillar_root = kwargs.pop('pillar_root', '')\r\n config_dir = kwargs.pop('config_dir', '')\r\n id = kwargs.pop('id', '')\r\n\r\n command_args = {'salt_state': salt_state,\r\n 'id': '--id={}'.format(id) if id else \"\",\r\n 'file_root': '--file-root={}'.format(file_root) if file_root else \"\",\r\n 'pillar_root': '--pillar-root={}'.format(pillar_root) if pillar_root else \"\",\r\n 'config_dir': '--config-dir={}'.format(config_dir) if config_dir else '',\r\n 'pillar_data': 'pillar=\"{!r}\"'.format(kwargs) if kwargs else ''}\r\n\r\n cmd = \"salt-call --local state.apply {salt_state} --retcode-passthrough \" \\\r\n \"--state-output=mixed \" \\\r\n \"{file_root} {pillar_root} {config_dir} --log-level=info \" \\\r\n \"{pillar_data} \".format(**command_args)\r\n\r\n print(cmd)\r\n ret = subprocess.call(cmd, shell=True)\r\n if ret == 0:\r\n print(\"Success\")\r\n else:\r\n print('Error {} occurred while running Salt state \"{}\"'.format(\r\n ret, salt_state if salt_state else \"highstate\"))\r\n\r\n\r\ndef salt_call_json(salt_command):\r\n cmd = 'salt-call {} --local --out=json'.format(salt_command)\r\n print(cmd)\r\n try:\r\n out = subprocess.check_output(cmd, shell=True)\r\n except subprocess.CalledProcessError as e:\r\n print(e.output)\r\n print('Error code %d returned from Salt command %r\"' % (\r\n e.returncode, cmd))\r\n out = b''\r\n out = out.decode()\r\n left = out.find('{') # locate the actual json within the (Windows) response\r\n right = out.rfind('}')\r\n try:\r\n ret = json.loads(out[left:right + 1])\r\n return ret\r\n except ValueError: # Python 3.5+ --> json.decoder.JSONDecodeError:\r\n print(\"JSON error loading ==>\", out)\r\n return {}\r\n\r\n\r\n# noinspection PyShadowingNames\r\ndef get_ip_choices():\r\n \"\"\"\r\n lists the addresses and names of available network interfaces\r\n :return: list of dicts {'addr', 'name', 'prefix'}\r\n addr is the IPv4 or IPv6 network address\r\n name is the \"nice\" name.\r\n prefix is the number of bits in the network prefix\r\n \"\"\"\r\n adapters = ifaddr.get_adapters()\r\n rtn = []\r\n for adapter in adapters:\r\n for ip in adapter.ips:\r\n if isinstance(ip.ip, str): # IPv4\r\n rtn.append({\"addr\": ipaddress.IPv4Address(ip.ip),\r\n \"name\": adapter.nice_name,\r\n \"prefix\": ip.network_prefix})\r\n else: # IPv6\r\n rtn.append({\"addr\": ipaddress.IPv6Address(ip.ip[0]),\r\n \"name\": adapter.nice_name,\r\n \"prefix\": ip.network_prefix})\r\n return rtn\r\n\r\n\r\ndef salt_minion_version():\r\n try:\r\n out = salt_call_json(\"test.version\")\r\n version = out['local'].split('.')\r\n version[1] = int(version[1])\r\n except (IndexError, subprocess.CalledProcessError, TypeError, KeyError):\r\n print(\"salt-minion not installed or no output\")\r\n version = ['', 0, '']\r\n else:\r\n print(\"Detected installed Salt version={!r}\".format(version))\r\n return version\r\n\r\n\r\ndef affirmative(yes, default=False):\r\n '''\r\n returns True if user typed \"yes\"\r\n '''\r\n if len(yes) == 0:\r\n return default\r\n try:\r\n return yes.lower().startswith('y')\r\n except AttributeError:\r\n return default\r\n\r\n\r\ndef get_affirmation(question: str, default_sense: bool):\r\n prompt = '[Y/n]' if default_sense else '[y/N]'\r\n return affirmative(input('{} {}:'.format(question, prompt)), default_sense)\r\n\r\n\r\ndef booleanize(name):\r\n try:\r\n if name.lower() in ['false', 'none', '']:\r\n return False\r\n except AttributeError:\r\n return False\r\n return name\r\n\r\n\r\ndef normalize_literal_none(name):\r\n return name if booleanize(name) else 'None'\r\n\r\n\r\ndef salt_install(master=True):\r\n print(\"Checking Salt Version...\")\r\n _current_salt_version = salt_minion_version()\r\n if _current_salt_version >= minimum_salt_version:\r\n print(\"Success: %s\" % _current_salt_version)\r\n else:\r\n if platform.system() != 'Linux':\r\n print()\r\n print('Sorry! Cannot automatically install Salt on your'\r\n '\"{}\" system)'.format(platform.system()))\r\n print('Please install Salt version {}'.format(MINIMUM_SALT_VERSION))\r\n print('or later, according to the instructions in the README text,')\r\n print('and then re-run this script. ...')\r\n if affirmative(input('... unless, Salt is already installed and it is Okay to continue? [y/N]:')):\r\n return False # we did not install Salt\r\n write_bevy_settings_files() # keep the settings we have already found\r\n exit(1)\r\n print('\\nYou need a recent version of SaltStack installed for this project.')\r\n okay = affirmative(input('Shall I install that for you now?[Y/n]:'), True)\r\n if not okay:\r\n if affirmative(input('Do you wish to try using the old version? [y/N]:')):\r\n return False # we did not install Salt\r\n write_bevy_settings_files() # keep the settings we have already found\r\n exit(1)\r\n _salt_install_script = \"/tmp/bootstrap-salt.sh\"\r\n print(\"Downloading Salt Bootstrap to %s\" % _salt_install_script)\r\n with open(_salt_install_script, \"w+\") as f:\r\n f.write(urlopen(SALT_BOOTSTRAP_URL).read().decode())\r\n print(\"Download complete from {}\".format(SALT_BOOTSTRAP_URL))\r\n print(\"Bootstrapping Salt\")\r\n command = \"{} {} -P -X -c /tmp {}\".format(\r\n _salt_install_script,\r\n '-L -M ' if master else '',\r\n SALT_DOWNLOAD_SOURCE)\r\n try:\r\n print(\"sudo sh {}\".format(command))\r\n ret = subprocess.call(\"sudo sh {}\".format(command), shell=True)\r\n\r\n print(\"Salt Installation script done.\")\r\n except OSError as ex:\r\n print(ex)\r\n if not affirmative(input('Continue to process? [y/N]:')):\r\n exit(1) # quit with error indication\r\n ret = 1 # return an error indication\r\n return ret == 0 # show whether we installed Salt\r\n\r\n\r\ndef request_bevy_username_and_password(user_name: str):\r\n \"\"\"\r\n get user's information so that we can build a user for her on each minion\r\n\r\n :param user_name: system default user name\r\n \"\"\"\r\n bevy = my_linux_user = pub_key = hash = ''\r\n loop = Ellipsis # Python trivia: Ellipsis evaluates as True\r\n while loop:\r\n print()\r\n my_bevy = settings.get('bevy', 'bevy01')\r\n print('\\nUse \"local\" as your bevy name for masterless operation of Salt...')\r\n bevy = input(\"Name your bevy: [{}]:\".format(my_bevy)) or my_bevy\r\n print()\r\n print('Salt will create a personal interactive user for you on each machine in the bevy.')\r\n print('If you do not wish to have a user created for you, enter \"None\" as the user name.')\r\n print()\r\n default_user = settings.get('my_linux_user') or user_name\r\n print('Please supply your desired user name to be used on Linux minions.')\r\n print('(Hit to use \"{}\")'.format(default_user))\r\n my_linux_user = normalize_literal_none(input('User Name:') or default_user)\r\n print()\r\n\r\n hash = settings.get('linux_password_hash', '')\r\n if booleanize(my_linux_user): # establish a password for the user\r\n if hash != \"\" and loop is Ellipsis: # only True the first time around\r\n print('(using the password hash {}'.format(hash))\r\n else:\r\n hash = pwd_hash.make_hash() # asks your user to type a password.\r\n loop = not affirmative(\r\n input('Use user name \"{}\" in bevy \"{}\" with that hash'\r\n '? [Y/n]:'.format(my_linux_user, bevy)),\r\n default=True) # stop looping if done\r\n return bevy, my_linux_user, hash\r\n\r\n\r\ndef request_windows_username_and_password(user_name: str):\r\n \"\"\"\r\n get user's information so that we can build a user for her on each minion\r\n\r\n :param user_name: system default user name\r\n \"\"\"\r\n print()\r\n print('NOTE:')\r\n print('If you wish to use your Microsoft Account username, you _must_ do it from a GUI,')\r\n print(' not from Salt, so, enter \"None\" as the user name below...')\r\n print()\r\n my_windows_user = my_windows_password = ''\r\n loop = Ellipsis # Python trivia: Ellipsis evaluates as True\r\n while loop:\r\n print()\r\n default_user = settings.get('my_windows_user', 'None') or user_name\r\n print('Please supply your desired user name to be used on any Windows and MacOS minions.')\r\n print('Enter \"None\" to skip...')\r\n my_windows_user = normalize_literal_none(input(\r\n 'Windows User Name [{}]:'.format(default_user)) or default_user)\r\n print()\r\n if booleanize(my_windows_user):\r\n print('CAUTION: Windows and MacOS passwords are stored in plain text.')\r\n print('Do not use a valuable password here...')\r\n default_wpwd = settings.get('my_windows_password', '')\r\n my_windows_password = input('Windows/MacOS insecure password: [{}]:'.format(default_wpwd)) or default_wpwd\r\n else:\r\n my_windows_password = ''\r\n loop = not affirmative(\r\n input('Use Windows/MacOS user name \"{}\" with password \"{}\"'\r\n '? [Y/n]:'.format(my_windows_user, my_windows_password)),\r\n default=True) # stop looping if done\r\n return my_windows_user, my_windows_password\r\n\r\n\r\ndef write_ssh_key_file(my_linux_user):\r\n pub = None # object to contain the user's ssh public key\r\n okay = 'n'\r\n pub_key = ''\r\n try:\r\n user_home_pub = Path.home() / '.ssh' / 'id_rsa.pub' # only works on Python 3.5+\r\n except AttributeError: # older Python3 (not seen on Windows os)\r\n user_home_pub = Path('/home/') / getpass.getuser() / '.ssh' / 'id_rsa.pub'\r\n\r\n user_key_file = user_ssh_key_file_directory / (my_linux_user + '.pub')\r\n try: # maybe it is already in our tree?\r\n print('trying file: \"{}\"'.format(user_key_file))\r\n pub = user_key_file.open()\r\n except OSError:\r\n try: # named user's default location on this machine?\r\n print('Not found. trying file: \"{}\"'.format(user_home_pub))\r\n pub = user_home_pub.open()\r\n except OSError:\r\n print('No ssh public key found. You will have to supply it the hard way...')\r\n if pub:\r\n pub_key = pub.read()\r\n if len(pub_key) < 64:\r\n print('File too short to contain a good ssh key.') # use default okay = 'n'\r\n else:\r\n okay = input(\r\n 'File exists, and contains:\"{}\"\\n Use that on all minions? [Y/n]:'.format(\r\n pub_key))\r\n\r\n while not affirmative(okay, default=True):\r\n print('Now, cut the text of your ssh public key to transmit it to your new server.\\n')\r\n print(' (or type \"exit\" to bypass ssh key uploads.)')\r\n print('You can usually get your ssh key by typing:\\n')\r\n print(' cat ~/.ssh/id_rsa.pub\\n')\r\n print()\r\n pub_key = input('Paste it here --->')\r\n print('.......... (checking) ..........')\r\n if len(pub_key) < 64:\r\n if pub_key == 'exit':\r\n return\r\n print('too short!')\r\n continue\r\n print('I received ===>{}\\n'.format(pub_key))\r\n okay = input(\"Use that? ('exit' to bypass ssh keys)[Y/n]:\")\r\n if affirmative(okay) or okay.lower() == 'exit':\r\n break\r\n if affirmative(okay, default=True):\r\n try:\r\n if user_key_file.samefile(pub.name):\r\n print('using existing {}'.format(str(user_key_file)))\r\n return\r\n except OSError:\r\n pass\r\n # user_key_file.parent.mkdir(parents=True, exist_ok=True) # only works for Python3.5+\r\n os.makedirs(str(user_key_file.parent), exist_ok=True) # 3.4\r\n # 3.5 user_key_file.write_text(pub_key)\r\n with user_key_file.open('w') as f: # 3.4\r\n f.write(pub_key) # 3.4\r\n f.close()\r\n print('file {} written.'.format(str(user_key_file)))\r\n\r\n\r\ndef get_salt_master_url():\r\n try: # use a stored value -- needed for 2nd minion\r\n ans = my_settings['master_url']\r\n except KeyError:\r\n # get it the hard way\r\n out = salt_call_json(\"config.get master\")\r\n try:\r\n master_url = out['local']\r\n except (KeyError, TypeError):\r\n master_url = \"!!No answer from salt-call!!\"\r\n ans = master_url[0] if isinstance(master_url, list) else master_url\r\n print('configured master now = \"{}\"'.format(ans))\r\n return ans\r\n\r\n\r\ndef get_salt_minion_id():\r\n # get an existing id from Salt if possible\r\n out = salt_call_json(\"config.get id\")\r\n try:\r\n ans = out['local']\r\n print('Detected minion ID (of first minion) as = \"{}\"'.format(ans))\r\n except (KeyError, TypeError):\r\n print(\"(Present minion ID was not detected.)\")\r\n ans = \"\"\r\n return ans\r\n\r\n\r\ndef choose_master_address(host_name):\r\n default = host_name\r\n if my_settings['master']:\r\n choices = get_ip_choices()\r\n print('This machine has the following IP addresses:')\r\n for ip in choices:\r\n if not ip['addr'].is_loopback and not ip['addr'].is_link_local:\r\n print('{addr}/{prefix} - {name}'.format(**ip))\r\n try:\r\n # noinspection PyArgumentList\r\n ip_ = socket.getaddrinfo(default, 4506, type=socket.SOCK_STREAM)\r\n print('The name {} translates to {}'.format(host_name, ip_[0][4][0]))\r\n except (socket.error, IndexError):\r\n pass\r\n while Ellipsis: # repeat until user types a valid entry\r\n resp = input(\"What default url address for the master (for other minions)? [{}]:\".format(default))\r\n choice = resp or default\r\n try: # look up the address we have, and see if it appears good\r\n # noinspection PyArgumentList\r\n ip_ = socket.getaddrinfo(choice, 4506, type=socket.SOCK_STREAM)\r\n addy = ip_[0][4][0]\r\n print(\"Okay, the bevy master's address returns as {}\".format(addy))\r\n return choice # it looks good -- exit the loop\r\n except (socket.error, IndexError, AttributeError):\r\n print('\"{}\" is not a valid IP address.'.format(choice))\r\n\r\n\r\ndef choose_vagrant_network():\r\n while Ellipsis:\r\n network = settings['vagrant_network']\r\n resp = input(\r\n 'What is your desired Vagrant internal network? [{}]:'.format(network))\r\n network = resp or network\r\n try:\r\n ip_net = ipaddress.ip_network(network, strict=False)\r\n except ipaddress.NetmaskValueError:\r\n print('Invalid network string. Try again.')\r\n continue\r\n if not ip_net.is_private:\r\n print('Sorry, internal network must be private.')\r\n continue\r\n try:\r\n if ip_net.version == 4:\r\n prefix = '.'.join(str(ip_net).split('.')[0:2]) # the first two octets of the network\r\n else:\r\n prefix = ip_net.compressed.partition(\"::\")[0:2] # leave out the part after the \"::\"\r\n except Exception as e:\r\n print(e)\r\n continue\r\n return prefix, network # break out of loop if no errors\r\n\r\n\r\ndef choose_bridge_interface():\r\n host_network = ipaddress.ip_network(settings['vagrant_network'])\r\n choices = []\r\n for ip in get_ip_choices():\r\n addy = ip['addr']\r\n if addy.is_loopback or addy.is_link_local:\r\n continue\r\n if addy in host_network:\r\n continue\r\n choices.append(ip)\r\n while Ellipsis:\r\n print('This machine has the following possible external IP interfaces:')\r\n i = 0\r\n for ip in choices:\r\n i += 1\r\n print(i, ': {addr}/{prefix} - {name}'.format(**ip), sep='')\r\n if i == 0:\r\n raise RuntimeError('Sorry. No external IP interfaces found.')\r\n if i == 1:\r\n print('Will use the only possible choice.')\r\n return choices[0]\r\n else:\r\n try:\r\n choice = choices[int(input('Which network interface do you want to use for bridging?:')) - 1]\r\n return choice\r\n except (ValueError, IndexError, AttributeError):\r\n print('Bad choice.')\r\n\r\n\r\ndef get_projects_directory():\r\n while Ellipsis:\r\n try:\r\n default = settings.get('projects_root', str(this_file.parents[2]))\r\n except (IndexError, AttributeError):\r\n default = '/projects'\r\n print('We can set up a Vagrant share \"/projects\" to find all of your working directories.')\r\n print('Use \"none\" to disable this feature.')\r\n resp = input('What is the root directory for your projects directories? [{}]:'.format(default))\r\n resp = resp or default\r\n if os.path.isdir(resp) or resp.lower() == 'none':\r\n return resp\r\n\r\n\r\ndef display_introductory_text():\r\n intro = \"\"\"\r\nThis program will take you step-by-step through the process of defining a new Bevy,\r\n(if run on a new Salt-master or a workstation which will host the new master),\r\nor will collect the information needed to become a minion in an existing Bevy.\r\n\r\nAnswers you give will (if possible) be stored for use as the defaults for later runs.\r\n\r\nThe default will appear at the end of the question [in square brackets, like this]:.\r\nJust hit to select the default.\r\nThe default for a yes-no or multiple choice question will be capitalized, like [y/N] or [knAx].\r\nYou can select one of the letters, or just hit for the default.\r\nCase is not significant for multiple choice or \"None\" responses. \r\nCase is preserved for strings.\r\n....\r\n\"\"\"\r\n if '--help' in argv:\r\n print(__doc__)\r\n exit(0)\r\n print(intro)\r\n\r\n\r\nif __name__ == '__main__':\r\n if not sudo.already_elevated():\r\n display_introductory_text()\r\n\r\n user_name = getpass.getuser()\r\n if user_name == 'root':\r\n user_name = os.environ['SUDO_USER']\r\n\r\n read_bevy_settings_files()\r\n settings.update(sudo.get_context())\r\n\r\n try:\r\n import pwd # works on Posix only\r\n pwd_entry = pwd.getpwnam(user_name) # look it up the hard way -- we may be running SUDO\r\n if pwd_entry[2] > 2000: # skip uid numbers too close to automatically assigned values\r\n settings.setdefault('my_linux_uid', pwd_entry[2]) # useful for network shared files\r\n if pwd_entry[3] > 2000:\r\n settings.setdefault('my_linux_gid', pwd_entry[3])\r\n except (ImportError, IndexError, AttributeError):\r\n settings.setdefault('my_linux_uid', '')\r\n settings.setdefault('my_linux_gid', '')\r\n\r\n settings.setdefault('vagrant_prefix', DEFAULT_VAGRANT_PREFIX)\r\n settings.setdefault('vagrant_network', DEFAULT_VAGRANT_NETWORK)\r\n try:\r\n desktop = Path.home() / \"Desktop\" # try for a /home//Desktop directory\r\n on_a_workstation = desktop.exists()\r\n except AttributeError:\r\n on_a_workstation = False # blatant assumption: Python version is less than 3.5, therefore not a Workstation\r\n\r\n if sudo.already_elevated(): # the program has already called itself, and is now running as an administrator\r\n if 'my_linux_user' not in settings or 'bevy' not in settings:\r\n raise RuntimeError('Expected settings[] entry was not found')\r\n else: # this is the first run. We will call ourselves soon if needed...\r\n settings['bevy'], settings['my_linux_user'], settings['linux_password_hash'] = request_bevy_username_and_password(user_name)\r\n settings['my_windows_user'], settings['my_windows_password'] = request_windows_username_and_password(user_name)\r\n print('Setting up user \"{}\" for bevy \"{}\"'.format(settings['my_linux_user'], settings['bevy']))\r\n write_bevy_settings_files()\r\n\r\n if sudo.already_elevated():\r\n print('Now running as Administrator...')\r\n elif sudo.isUserAdmin():\r\n print('(program was run by an administrator to start)')\r\n elif '--no-sudo' in argv: # \"sudo off\" switch for testing\r\n print('\\n\\n!!! Running in \"--no-sudo\" mode. Expect permissions violations...\\n')\r\n else:\r\n print('\\n\\n ... Okay. Now requesting elevated (sudo) privileges...\\n')\r\n names = {k: settings[k] for k in ('bevy', 'my_linux_user', 'my_windows_user', 'my_windows_password')}\r\n time.sleep(2) # give user a moment to absorb this ...\r\n sudo.run_elevated(context=names) # Run this script using Administrator privileges\r\n\r\n my_settings.setdefault('master_host', False) # assume this machine is NOT the VM host for the Master\r\n if settings['bevy'] == \"local\":\r\n my_settings['master'] = True # a masterless system is a master to itself\r\n else:\r\n print('\\n\\nThis program can make this machine a simple workstation to join the bevy')\r\n if platform.system() != 'Windows':\r\n print('or a bevy salt-master (including cloud-master),')\r\n if on_a_workstation:\r\n print('or a Vagrant host, possibly hosting a bevy master.')\r\n my_settings.setdefault('master', False)\r\n if platform.system() != 'Windows':\r\n my_settings['master'] = get_affirmation('Should this machine BE the master?', my_settings['master'])\r\n if not my_settings['master'] and on_a_workstation:\r\n my_settings['master_host'] = get_affirmation('Will the Bevy Master be a VM guest of this machine?',\r\n my_settings['master_host'])\r\n get_additional_roots()\r\n\r\n print()\r\n first_id = get_salt_minion_id()\r\n\r\n\r\n if my_settings['master'] and not settings['bevy'] == \"local\":\r\n print('NOTE: The Salt Node ID of the Bevy Master on itself should by \"bevymaster\".')\r\n\r\n node_name = default = my_settings.get('id', # determine machine ID\r\n 'bevymaster' if my_settings['master'] and not settings['bevy'] == \"local\" else\r\n first_id if \".\" not in first_id else platform.node().split('.')[0])\r\n while Ellipsis:\r\n name = input(\"What will be the Salt Node ID for this machine (for the first or only minion)? [{}]:\".format(default)) or default\r\n if name == default or affirmative(input('Use node name \"{}\"? [Y/n]:'.format(name)), True):\r\n node_name = name\r\n break\r\n my_settings['id'] = node_name\r\n\r\n my_directory = Path(os.path.dirname(os.path.abspath(__file__)))\r\n bevy_root_node = (my_directory / '../bevy_srv').resolve() # this dir is part of the Salt file_roots dir\r\n if not bevy_root_node.is_dir():\r\n raise SystemError('Unexpected situation: Expected directory not present -->{}'.format(bevy_root_node))\r\n\r\n if my_settings['master'] or my_settings['master_host']:\r\n write_ssh_key_file(settings['my_linux_user'])\r\n\r\n # check for use of virtualbox and Vagrant\r\n vagrant_present = False\r\n while on_a_workstation: # if on a workstation, repeat until user says okay\r\n vbox_install = False\r\n vhost = settings.setdefault('vagranthost', 'none') # node ID of Vagrant host machine\r\n default = my_settings.get('vm_host') or my_settings['master_host'] or vhost == node_name\r\n my_settings['vm_host'] = my_settings['master_host'] or \\\r\n get_affirmation('Will this machine be the Host for other Vagrant virtual machines?', default)\r\n if my_settings['vm_host']:\r\n # test for Vagrant being already installed\r\n rtn = subprocess.call('vagrant -v', shell=True)\r\n vagrant_present = rtn == 0\r\n settings['vagranthost'] = node_name\r\n vbox_install = False if vagrant_present else affirmative(input(\r\n 'Do you wish help to install VirtualBox and Vagrant? [y/N]:'))\r\n if vbox_install:\r\n import webbrowser\r\n debian = False\r\n try:\r\n if 'ID_LIKE=debian' in Path('/etc/os-release').read_text():\r\n debian = True\r\n except Exception:\r\n pass\r\n if debian:\r\n subprocess.call('apt install virtualbox', shell=True)\r\n else:\r\n webbrowser.open('https://www.virtualbox.org/wiki/Downloads')\r\n\r\n webbrowser.open(\"https://www.vagrantup.com/downloads.html\")\r\n\r\n rtn = subprocess.call('vagrant -v', shell=True)\r\n vagrant_present = rtn == 0\r\n\r\n elif my_settings['master']:\r\n print('What is/will be the Salt node id of the Vagrant host machine? [{}]'\r\n .format(settings['vagranthost']))\r\n settings['vagranthost'] = input('(Type \"none\" if none.):') or settings['vagranthost']\r\n if settings['vagranthost'] and settings['vagranthost'] != \"none\":\r\n try: # if the entry was an IP address, the user messed up. Test for that.\r\n socket.inet_aton(settings['vagranthost']) # an exception is expected and is correct\r\n print('Please enter a node ID, not an IP address.')\r\n continue # user committed an entry error ... retry\r\n except OSError:\r\n pass # entry was not an IP address. Good.\r\n if my_settings['vm_host'] and settings['vagranthost'] and settings['vagranthost'] != \"none\":\r\n runas = settings.get('runas') or settings['my_linux_user']\r\n resp = input(\r\n 'What user on {} will own the Vagrantbox files?'\r\n ' [{}]:'.format(settings['vagranthost'], runas))\r\n settings['runas'] = resp or runas\r\n\r\n parent = settings.get('cwd') or os.path.abspath('.')\r\n resp = input(\r\n 'What is the full path to the Vagrantfile on {}?'\r\n '[{}]:'.format(settings['vagranthost'], parent))\r\n settings['cwd'] = resp or parent\r\n print()\r\n print('Using \"{}\" on node \"{}\"'.format(\r\n os.path.join(settings['cwd'], 'Vagrantfile'),\r\n settings['vagranthost']\r\n ))\r\n print('owned by {}.'.format(settings['runas']))\r\n if vagrant_present:\r\n print('Vagrant is already present on this machine.')\r\n else:\r\n print('CAUTION: Vagrant may not yet be installed on this machine.')\r\n else:\r\n print('No Vagrant Box will be used.')\r\n if affirmative(input('Continue? [Y/n]:'), default=True):\r\n break\r\n\r\n if my_settings.setdefault('vm_host', False):\r\n settings['vagrant_prefix'], settings['vagrant_network'] = choose_vagrant_network()\r\n choice = choose_bridge_interface()\r\n settings['vagrant_interface_guess'] = choice['name']\r\n settings['projects_root'] = get_projects_directory()\r\n\r\n settings.setdefault('fqdn_pattern', DEFAULT_FQDN_PATTERN)\r\n\r\n master_url = get_salt_master_url()\r\n we_installed_it = salt_install(my_settings['master']) # download & run salt\r\n\r\n if we_installed_it and master_url.startswith('!'):\r\n ask_second_minion = False\r\n master_url = 'salt'\r\n else:\r\n if master_url is None or master_url.startswith('!'):\r\n print('WARNING: Something wrong. Salt master should be known at this point.')\r\n if affirmative(input('continue anyway?')):\r\n master_url = 'salt'\r\n else:\r\n exit(1)\r\n ask_second_minion = master_url not in ['localhost', 'salt', '127.0.0.1'] and \\\r\n platform.system() != 'Windows' # TODO: figure out how to run 2nd minion on Windows\r\n second_minion_id = my_settings.setdefault('second_minion_id', 'None')\r\n historic_second_minion = second_minion_id != 'None'\r\n if ask_second_minion or historic_second_minion:\r\n print('Your primary Salt master URL was detected as: {}'.format(master_url))\r\n if settings.get('master_external_ip', None):\r\n print(\"Your bevymaster's (external) URL was: {}\".format(settings['master_external_ip']))\r\n print('You may continue to use your primary master, and also use a second master to connect your bevy.')\r\n print('Your previously used minion ID was \"{}\" on your (optional) second master'.format(\r\n my_settings.get('second_minion_id', 'None')))\r\n while ...:\r\n default = my_settings.get('second_minion_id', 'bevymaster' if my_settings['master'] else node_name)\r\n print('Enter \"None\" to use the primary Salt Master only.')\r\n response = normalize_literal_none(input(\r\n 'What ID do you want to use for this node on your second master? [{}]:'.format(default))) or default\r\n if response == 'None' or affirmative(input('Use \"{}\"?: [Y/n]:'.format(response)), True):\r\n my_settings['second_minion_id'] = response\r\n break\r\n ask_second_minion = my_settings['second_minion_id'] != \"None\"\r\n two = my_settings.get('additional_minion_tag') or '2' if ask_second_minion else ''\r\n my_settings['additional_minion_tag'] = two\r\n\r\n if settings['bevy'] == \"local\":\r\n master_address = 'localhost'\r\n else:\r\n master_address = choose_master_address(settings.get('master_external_ip', master_url))\r\n settings['master_external_ip'] = master_address\r\n\r\n if platform.system() == 'Windows':\r\n master_pub = Path(r'C:\\salt{}\\conf\\pki\\minion\\minion_master.pub'.format(two))\r\n else:\r\n master_pub = Path('/etc/salt{}/pki/minion/minion_master.pub'.format(two))\r\n try:\r\n if master_pub.exists():\r\n if settings['bevy'] == \"local\" \\\r\n or affirmative(input('Will this be a new minion<-->master relationship? [y/N]:')):\r\n print('Removing public key for master:\"{}\"'.format(master_pub))\r\n master_pub.unlink()\r\n print(\"\\n** Remember to accept this machine's Minion key on its new Master. **\\n\")\r\n except FileNotFoundError:\r\n pass\r\n except PermissionError:\r\n print(\"Sorry. Permission error when trying to read or remove {}\".format(master_pub))\r\n\r\n if my_settings['master_host']:\r\n settings['master_vagrant_ip'] = settings['vagrant_prefix'] + '.2.2'\r\n write_config_file(Path(SALT_SRV_ROOT) / GUEST_MASTER_CONFIG_FILE, is_master=True, virtual=True, master_host=my_settings['master_host'])\r\n else:\r\n settings['master_vagrant_ip'] = 'None'\r\n\r\n write_config_file(Path(SALTCALL_CONFIG_FILE), my_settings['master'], virtual=False, windows=platform.system()=='Windows', master_host=my_settings['master_host'])\r\n if my_settings['vm_host']:\r\n write_config_file(Path(GUEST_MINION_CONFIG_FILE), is_master=False, virtual=True, master_host=my_settings['master_host'])\r\n write_config_file(Path(WINDOWS_GUEST_CONFIG_FILE), is_master=False, virtual=True, windows=True, master_host=my_settings['master_host'])\r\n\r\n settings.setdefault('force_linux_user_password', True) # insure that it is defined\r\n settings.setdefault('linux_password_hash', '')\r\n write_bevy_settings_files()\r\n\r\n if my_settings['master']:\r\n print('\\n\\n. . . . . . . . . .\\n')\r\n salt_state_apply('', # blank name means: apply highstate\r\n id=node_name,\r\n config_dir=str(Path(SALTCALL_CONFIG_FILE).resolve().parent),\r\n bevy_root=str(bevy_root_node),\r\n bevy=settings['bevy'],\r\n master_vagrant_ip=master_address,\r\n additional_minion_tag=two,\r\n vbox_install=settings.get('vbox_install', False),\r\n vagranthost=settings.get('vagranthost', False),\r\n runas=settings.get('runas', ''),\r\n cwd=settings.get('cwd', ''),\r\n server_role='master',\r\n doing_bootstrap=True, # initialize environment\r\n )\r\n\r\n else: # not making a master, make a minion\r\n default = settings.get('master_vagrant_ip', '') if my_settings['master_host'] else \\\r\n settings.get('master_external_ip', '')\r\n my_master_url = my_settings.get('my_master_url', default)\r\n while Ellipsis: # loop until user says okay\r\n print('Checking {} for bevy master{} address validity...'.format(my_master_url, two))\r\n try: # look up the address we have, and see if it appears good\r\n # noinspection PyArgumentList\r\n ip_ = socket.getaddrinfo(my_master_url, 4506, type=socket.SOCK_STREAM)\r\n if my_settings['master_host']:\r\n print(\"(Hint: your guest VM bevy master local address will be {})\"\r\n .format(settings['master_vagrant_ip']))\r\n okay = input(\"Use {} as this machine's bevy master address? [Y/n]:\".format(ip_[0][4][0]))\r\n if affirmative(okay, True):\r\n my_settings['my_master_url'] = my_master_url\r\n if my_settings['vm_host'] and my_master_url != settings['master_vagrant_ip']:\r\n if affirmative(input(\"Also use {} as master address for other Vagrant VMs? [Y/n]:\"\r\n .format(my_master_url)), True):\r\n settings['master_vagrant_ip'] = my_master_url\r\n write_bevy_settings_files()\r\n break # it looks good -- exit the loop\r\n except (socket.error, IndexError) as e:\r\n print('Sorry. That produced the error==>{}'.format(e))\r\n my_master_url = input(\"Okay. Type the name or address for this machine's master{}?:\".format(two))\r\n\r\n print('\\n\\n. . . . . . . . . .\\n')\r\n salt_state_apply('configure_bevy_member',\r\n id=node_name,\r\n config_dir=str(Path(SALTCALL_CONFIG_FILE).resolve().parent), # for local\r\n bevy_root=str(bevy_root_node),\r\n bevy=settings['bevy'],\r\n master_vagrant_ip=settings['master_vagrant_ip'],\r\n my_master_url=my_master_url,\r\n additional_minion_tag=two,\r\n vbox_install=settings.get('vbox_install', False),\r\n my_linux_user=settings['my_linux_user'],\r\n vagranthost=settings.get('vagranthost', False),\r\n runas=settings.get('runas', ''),\r\n cwd=settings.get('cwd', ''),\r\n )\r\n print()\r\n print('{} done.'.format(__file__))\r\n print()\r\n if platform.system() == 'Windows':\r\n input('Hit to close this window:')\r\n print('and ... if you see this message, you may need to hit , too.')\r\n","sub_path":"configure_machine/bootstrap_bevy_member_here.py","file_name":"bootstrap_bevy_member_here.py","file_ext":"py","file_size_in_byte":49965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"305996034","text":"import sys\n\n# this should be the unique token\ntok = \"xiayingce-ustc\"\n\nwith open(sys.argv[1], \"r\") as ff:\n all_lines = [x.strip() for x in ff]\n \nfor fname in sys.argv[2:]:\n with open(fname, \"r\") as ff:\n for idx, sent in enumerate(ff):\n all_lines[idx] += (tok + sent.strip())\n \n \nall_lines = list(set(all_lines))\n\nfws = [open(fname + \".uniq\",\"w\") for fname in sys.argv[1:]]\n\nfor sent in all_lines:\n segs = sent.split(tok)\n for ii, seg in enumerate(segs):\n print >>fws[ii], seg\n \nfor ff in fws:\n ff.close()\n\n\n\n","sub_path":"remove_duplicate.py","file_name":"remove_duplicate.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"587274908","text":"__author__ = 'Ester'\nimport pymysql\nfrom collections import namedtuple\nfrom xml.etree.ElementTree import Element, SubElement, tostring\nfrom xml.etree import ElementTree\n\nArticle = namedtuple(\"Article\", \"url, body, headline, author, datetime, progress_sentiment, feeling_sentiment\")\n\n\ndef convert_to_article(row_data):\n article = Article(*row_data)\n\n return article\n\n\ndef get_connection():\n connection = pymysql.connect(host='mysql.server', port=3306, user='BolanleOnifade',\n db='BolanleOnifade$sentimentanalysis', passwd='C0m1ngh0m3')\n\n return connection\n\n\ndef get_cursor(connection):\n query = 'select url, body, headline, author, datetime, progress_sentiment, feeling_sentiment ' \\\n 'from collect_news order by datetime'\n\n cur = connection.cursor()\n cur.execute(query)\n\n return cur\n\n\ndef write_to_xml_file(cursor, file_name):\n root = Element(\"news\")\n\n for row in cursor.fetchall():\n article = convert_to_article(row)\n\n if article.feeling_sentiment and article.progress_sentiment:\n entry = SubElement(root, 'entry',\n {'author': article.author, 'datetime': article.datetime, 'url': article.url,\n 'progress_sentiment': article.progress_sentiment,\n 'feeling_sentiment': article.feeling_sentiment})\n headline = SubElement(entry, 'headline')\n headline.text = article.headline\n body = SubElement(entry, 'body')\n body.text = article.body\n ElementTree.ElementTree(root).write(file_name, xml_declaration=True)\n\n\ndef separate_files():\n count_unrecognised_company = 0\n files = dict(chevron=['chevron.xml', Element(\"news\")],\n goldman=['goldman.xml', Element(\"news\")],\n cocacola=['cocacola.xml', Element(\"news\")],\n disney=['disney.xml', Element(\"news\")],\n exxon=['exxon.xml', Element(\"news\")], ibm=['ibm.xml', Element(\"news\")],\n jpmorgan=['jpmorgan.xml', Element(\"news\")],\n microsoft=['microsoft.xml', Element(\"news\")],\n pfizer=['pfizer.xml', Element(\"news\")],\n visa=['visa.xml', Element(\"news\")],\n unsure=['unsure.xml', Element(\"news\")])\n companies_keywords = ['goldman', 'sachs', 'coca', 'coca-cola', 'jpmorgan', 'jp', 'j.p.', 'j. p.', 'jp morgan', 'microsoft',\n 'disney',\n 'chevron', 'exxon', 'pfizer', 'visa', 'visa inc', 'ibm',\n ]\n path = \"manual_labelled.xml\"\n tree = ElementTree.parse(path)\n\n root = tree.getroot()\n for child in root:\n possible_companies = []\n for company in companies_keywords:\n if company.lower() in child.find('headline').text.lower():\n standardized_name = company.lower()\n if company.lower() in [\"goldman\", \"sachs\"]:\n standardized_name = \"goldman\"\n elif company.lower() in ['jp', 'j.p.', 'j. p.', 'jp morgan', 'jpmorgan'] and not 'bjp' in child.find('headline').text.lower():\n standardized_name = \"jpmorgan\"\n elif company.lower() in [\"coca\", \"coca-cola\"]:\n standardized_name = \"cocacola\"\n elif company.lower() in [\"visa\"] and not \"televisa\" in child.find('headline').text.lower():\n standardized_name = \"visa\"\n\n if standardized_name not in possible_companies:\n possible_companies.append(standardized_name)\n if len(possible_companies) == 1:\n try:\n files.get(possible_companies[0])[1].append(child)\n\n except TypeError:\n count_unrecognised_company += 1\n print(\"skipping unrecognised company.... \", count_unrecognised_company)\n else:\n files.get('unsure')[1].append(child)\n\n for key, value in files.items():\n ElementTree.ElementTree(value[1]).write(value[0], xml_declaration=True)\n\nif __name__ == '__main__':\n # conn = get_connection()\n # cur = get_cursor(conn)\n # write_to_xml_file(cur, 'manual_labelled.xml')\n # cur.close()\n # cur.close()\n separate_files()","sub_path":"Repository/Labelling/manual_labelling.py","file_name":"manual_labelling.py","file_ext":"py","file_size_in_byte":4252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"610833411","text":"import tensorflow as tf\n\n\ndef bboxes_intersection(bbox_ref, bboxes):\n \"\"\"Compute relative intersection between a reference box and a\n collection of bounding boxes. Namely, compute the quotient between\n intersection area and box area.\n Args:\n bbox_ref: (N, 4) or (4,) Tensor with reference bounding box(es).\n bboxes: (N, 4) Tensor, collection of bounding boxes.\n Return:\n (N,) Tensor with relative intersection.\n \"\"\"\n\n # Should be more efficient to first transpose.\n bboxes = tf.transpose(bboxes)\n bbox_ref = tf.transpose(bbox_ref)\n # Intersection bbox and volume.\n int_ymin = tf.maximum(bboxes[0], bbox_ref[0])\n int_xmin = tf.maximum(bboxes[1], bbox_ref[1])\n int_ymax = tf.minimum(bboxes[2], bbox_ref[2])\n int_xmax = tf.minimum(bboxes[3], bbox_ref[3])\n h = tf.maximum(int_ymax - int_ymin, 0.)\n w = tf.maximum(int_xmax - int_xmin, 0.)\n # Volumes.\n inter_vol = h * w\n bboxes_vol = (bboxes[2] - bboxes[0]) * (bboxes[3] - bboxes[1])\n\n return tf.where(\n tf.equal(bboxes_vol, 0.0),\n tf.zeros_like(inter_vol), inter_vol / bboxes_vol)\n\n\ndef normalize_image(image):\n \"\"\"Normalizes the image to zero mean and unit variance.\n ref: https://github.com/tensorflow/models/blob/3462436c91897f885e3593f0955d24cbe805333d/official/vision/detection/utils/input_utils.py\n \"\"\"\n image = tf.cast(image, dtype=tf.float32)\n image /= 256\n\n return image\n\n\ndef denormalize_image(image):\n \"\"\"Normalizes the image to zero mean and unit variance.\n ref: https://github.com/tensorflow/models/blob/3462436c91897f885e3593f0955d24cbe805333d/official/vision/detection/utils/input_utils.py\n \"\"\"\n image *= 256\n\n return image\n\n\n# mapping from [ymin, xmin, ymax, xmax] to [cx, cy, w, h]\ndef map_to_center_form(x):\n h = x[:, 2] - x[:, 0]\n w = x[:, 3] - x[:, 1]\n cy = x[:, 0] + (h / 2)\n cx = x[:, 1] + (w / 2)\n return tf.stack([cx, cy, w, h], axis=-1)\n\n\n# encode the gt and anchors to offset\ndef map_to_offset(x):\n g_hat_cx = (x[0, 0] - x[0, 1]) / x[2, 1]\n g_hat_cy = (x[1, 0] - x[1, 1]) / x[3, 1]\n g_hat_w = tf.math.log(x[2, 0] / x[2, 1])\n g_hat_h = tf.math.log(x[3, 0] / x[3, 1])\n return tf.stack([g_hat_cx, g_hat_cy, g_hat_w, g_hat_h])\n\n\n# crop the prediction of mask so as to calculate the linear combination mask loss\ndef crop(pred, boxes, origin_w, origin_h):\n \n pred_shape = tf.shape(pred)\n num_mask, mask_w, mask_h = pred_shape[0], pred_shape[1], pred_shape[2]\n cols = tf.cast(tf.range(mask_w), tf.float32)\n rows = tf.expand_dims(tf.cast(tf.range(mask_h), tf.float32), axis=-1)\n\n cols = tf.broadcast_to(cols, pred_shape)\n rows = tf.broadcast_to(rows, pred_shape)\n\n ymin = boxes[:, 0] / origin_h * tf.cast(mask_h, tf.float32)\n xmin = boxes[:, 1] / origin_w * tf.cast(mask_w, tf.float32)\n ymax = boxes[:, 2] / origin_h * tf.cast(mask_h, tf.float32)\n xmax = boxes[:, 3] / origin_w * tf.cast(mask_w, tf.float32)\n\n ymin = tf.broadcast_to(tf.reshape(ymin, [-1, 1, 1]), pred_shape)\n xmin = tf.broadcast_to(tf.reshape(xmin, [-1, 1, 1]), pred_shape)\n ymax = tf.broadcast_to(tf.reshape(ymax, [-1, 1, 1]), pred_shape)\n xmax = tf.broadcast_to(tf.reshape(xmax, [-1, 1, 1]), pred_shape)\n\n mask_top = (rows >= ymin)\n mask_bottom = (rows < ymax)\n mask_left = (cols >= xmin)\n mask_right = (cols < xmax)\n\n mask_top = tf.cast(mask_top, tf.float32)\n mask_bottom = tf.cast(mask_bottom, tf.float32)\n mask_left = tf.cast(mask_left, tf.float32)\n mask_right = tf.cast(mask_right, tf.float32)\n\n return pred * mask_left * mask_right * mask_bottom * mask_top\n\n\n# decode the offset back to center form bounding box when evaluation and prediction\ndef map_to_bbox(anchors, loc_pred):\n # we use this variance also when we encode the offset\n variances = [0.1, 0.2]\n\n # convert anchor to center_form\n anchor_h = anchors[:, 2] - anchors[:, 0]\n anchor_w = anchors[:, 3] - anchors[:, 1]\n anchor_cx = anchors[:, 1] + (anchor_w / 2)\n anchor_cy = anchors[:, 0] + (anchor_h / 2)\n\n pred_cx, pred_cy, pred_w, pred_h = tf.unstack(loc_pred, axis=-1)\n\n new_cx = pred_cx * (anchor_w * variances[0]) + anchor_cx\n new_cy = pred_cy * (anchor_h * variances[0]) + anchor_cy\n new_w = tf.math.exp(pred_w * variances[1]) * anchor_w\n new_h = tf.math.exp(pred_h * variances[1]) * anchor_h\n\n ymin = new_cy - (new_h / 2)\n xmin = new_cx - (new_w / 2)\n ymax = new_cy + (new_h / 2)\n xmax = new_cx + (new_w / 2)\n\n decoded_boxes = tf.stack([ymin, xmin, ymax, xmax], axis=-1)\n\n return decoded_boxes\n\n\ndef intersection(box_a, box_b):\n \"\"\"\n ref: https://github.com/tensorflow/models/blob/831281cedfc8a4a0ad7c0c37173963fafb99da37/official/vision/detection/utils/object_detection/box_list_ops.py\n :param gt_bbox: [num_obj, 4]\n :return:\n \"\"\"\n\n # unstack the ymin, xmin, ymax, xmax\n ymin_anchor, xmin_anchor, ymax_anchor, xmax_anchor = tf.unstack(box_a, axis=-1)\n ymin_gt, xmin_gt, ymax_gt, xmax_gt = tf.unstack(box_b, axis=-1)\n\n # calculate intersection\n all_pairs_max_xmin = tf.math.maximum(tf.expand_dims(xmin_anchor, axis=-1), tf.expand_dims(xmin_gt, axis=1))\n all_pairs_min_xmax = tf.math.minimum(tf.expand_dims(xmax_anchor, axis=-1), tf.expand_dims(xmax_gt, axis=1))\n all_pairs_max_ymin = tf.math.maximum(tf.expand_dims(ymin_anchor, axis=-1), tf.expand_dims(ymin_gt, axis=1))\n all_pairs_min_ymax = tf.math.minimum(tf.expand_dims(ymax_anchor, axis=-1), tf.expand_dims(ymax_gt, axis=1))\n intersect_heights = tf.math.maximum(0.0, all_pairs_min_ymax - all_pairs_max_ymin)\n intersect_widths = tf.math.maximum(0.0, all_pairs_min_xmax - all_pairs_max_xmin)\n return intersect_heights * intersect_widths\n\n\ndef jaccard(box_a, box_b):\n \"\"\"\n ref: https://github.com/tensorflow/models/blob/831281cedfc8a4a0ad7c0c37173963fafb99da37/official/vision/detection/utils/object_detection/box_list_ops.py\n :param gt_bbox: [num_obj, 4]\n :return:\n \"\"\"\n # A ∩ B / A ∪ B = A ∩ B / (areaA + areaB - A ∩ B)\n # calculate A ∩ B (pairwise)\n pairwise_inter = intersection(box_a, box_b)\n\n # calculate areaA, areaB\n ymin_anchor, xmin_anchor, ymax_anchor, xmax_anchor = tf.unstack(box_a, axis=-1)\n ymin_gt, xmin_gt, ymax_gt, xmax_gt = tf.unstack(box_b, axis=-1)\n\n area_anchor = (xmax_anchor - xmin_anchor) * (ymax_anchor - ymin_anchor)\n area_gt = (xmax_gt - xmin_gt) * (ymax_gt - ymin_gt)\n\n # create same shape of matrix as intersection\n pairwise_area = tf.expand_dims(area_anchor, axis=-1) + tf.expand_dims(area_gt, axis=1)\n\n # calculate A ∪ B\n pairwise_union = pairwise_area - pairwise_inter\n\n # IOU(Jaccard overlap) = intersection / union, there might be possible to have division by 0\n return pairwise_inter / pairwise_union\n\ndef jaccard_numpy(box_a, box_b):\n ymin_a, xmin_a, ymax_a, xmax_a = box_a\n ymin_b, xmin_b, ymax_b, xmax_b = box_b\n\n xleft = max(xmin_a, xmin_b)\n ytop = max(ymin_a, ymin_b)\n xright = min(xmax_a, xmax_b)\n ybottom = min(ymax_a, ymax_b)\n\n if xright < xleft or ybottom < ytop:\n return 0.0\n\n intersection_area = (xright - xleft) * (ybottom - ytop)\n box_a_area = (xmax_a - xmin_a) * (ymax_a - ymin_a)\n box_b_area = (xmax_b - xmin_b) * (ymax_b - ymin_b)\n\n iou = intersection_area / float(box_a_area + box_b_area - intersection_area)\n\n return iou\n\n\n# post process after detection layer\n# Todo: Use tensorflows intepolation mode option\ndef postprocess(detection, w, h, batch_idx, intepolation_mode=\"bilinear\", crop_mask=True, score_threshold=0):\n dets = detection[batch_idx]\n dets = dets['detection']\n\n # Todo: If dets is None\n # Todo: If scorethreshold is not zero\n \"\"\"\n Ref:\n if dets is None:\n return [torch.Tensor()] * 4 # Warning, this is 4 copies of the same thing\n if score_threshold > 0:\n keep = dets['score'] > score_threshold\n for k in dets:\n if k != 'proto':\n dets[k] = dets[k][keep]\n \n if dets['score'].size(0) == 0:\n return [torch.Tensor()] * 4\n \"\"\"\n classes = dets['class']\n boxes = dets['box']\n scores = dets['score']\n masks = dets['mask']\n proto_pred = dets['proto']\n pred_mask = tf.linalg.matmul(proto_pred, masks, transpose_a=False, transpose_b=True)\n pred_mask = tf.nn.sigmoid(pred_mask)\n pred_mask = tf.transpose(pred_mask, perm=(2, 0, 1))\n masks = crop(pred_mask, boxes, origin_w=256, origin_h=256)\n\n # intepolate to original size (test 550*550 here)\n masks = tf.image.resize(tf.expand_dims(masks, axis=-1), [w, h], method=intepolation_mode)\n\n # masks < 0.5 --> 0\n # masks >= 0.5 --> 1\n masks = tf.cast(masks + 0.5, tf.int64)\n masks = tf.squeeze(masks, axis=-1)\n\n return classes, scores, boxes, masks","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"493321775","text":"import argparse\nimport os\nimport time\nimport math\nimport numpy as np\nimport random\nimport sys\nimport shutil\nimport json\nimport string\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nimport run_cad\nfrom utils import *\nfrom models import Seq2Seq, MLP_D, MLP_G\n\nfrom regularizer import calc_gradient_penalty\n\nargs = run_cad.load_cadgan_args()\n\n# Set the random seed manually for reproducibility.\nrandom.seed(args.seed) \nnp.random.seed(args.seed)\ntorch.manual_seed(args.seed)\ntorch.cuda.manual_seed(args.seed)\n\n###############################################################################\n# Load data\n###############################################################################\n# load pretraiend models and vocabs\nchar_ae_params, char_word2idx, char_args = load_ckpt(args.char_ckpt)\nword_ae_params, word_word2idx, word_args = load_ckpt(args.word_ckpt)\n\n# create corpus\nchar_vocab = Dictionary()\nchar_vocab.load_from_word2idx(char_word2idx)\nword_vocab = Dictionary()\nword_vocab.load_from_word2idx(word_word2idx)\n\ncorpus = CADCorpus(args.data_path,\n maxlen=args.maxlen,\n char_vocab=char_vocab,\n word_vocab=word_vocab,\n lowercase=args.lowercase,\n )\n\n# save arguments\nlogger = init_logger(os.path.join(args.save, \"log.txt\"))\nlogger.info(vars(args))\nlogger.info(\"Vocabulary Size: char vocab={}, word vocab={}\".format(len(char_word2idx), len(word_word2idx)))\n\n# exp dir\ncreate_exp_dir(os.path.join(args.save), ['train.py', 'models.py', 'utils.py'],\n dict=(char_word2idx, word_word2idx), options=args)\n\nlogger.info(str(vars(args)))\n\n###############################################################################\n# Build the models\n###############################################################################\nchar_ae = Seq2Seq(emsize=char_args.emsize,\n nhidden=char_args.nhidden,\n ntokens=char_args.ntokens,\n nlayers=char_args.nlayers,\n noise_r=char_args.noise_r,\n hidden_init=char_args.hidden_init,\n dropout=char_args.dropout)\n\nchar_ae.load_state_dict(char_ae_params)\n\nword_ae = Seq2Seq(emsize=word_args.emsize,\n nhidden=word_args.nhidden,\n ntokens=word_args.ntokens,\n nlayers=word_args.nlayers,\n noise_r=word_args.noise_r,\n hidden_init=word_args.hidden_init,\n dropout=word_args.dropout)\n\nword_ae.load_state_dict(word_ae_params)\n\n\ngan_gen = MLP_G(input_dim=args.z_size, output_dim=args.nhidden, arch_layers=args.arch_g)\ngan_disc = MLP_D(input_dim=args.nhidden, output_dim=1, arch_layers=args.arch_d)\n\nprint(char_ae)\nprint(word_ae)\nprint(gan_gen)\nprint(gan_disc)\n\noptimizer_ae = optim.SGD(char_ae.parameters() + word_ae.parameters(), lr=args.lr_ae)\noptimizer_gan_g = optim.Adam(gan_gen.parameters(),\n lr=args.lr_gan_g,\n betas=(args.beta1, 0.999))\noptimizer_gan_d = optim.Adam(gan_disc.parameters(),\n lr=args.lr_gan_d,\n betas=(args.beta1, 0.999))\n\nif torch.cuda.is_available():\n char_ae = char_ae.cuda()\n word_ae = word_ae.cuda()\n gan_gen = gan_gen.cuda()\n gan_disc = gan_disc.cuda()\n\n\n###############################################################################\n# Training code\n###############################################################################\n\ndef evaluate_autoencoder(autoencoder, data_source, epoch):\n # Turn on evaluation mode which disables dropout.\n autoencoder.eval()\n total_loss = 0\n ntokens = len(corpus.dictionary.word2idx)\n all_accuracies = 0\n bcnt = 0\n for i, batch in enumerate(data_source):\n source, target, lengths = batch\n source = Variable(source.cuda(), volatile=True)\n target = Variable(target.cuda(), volatile=True)\n\n mask = target.gt(0)\n masked_target = target.masked_select(mask)\n # examples x ntokens\n output_mask = mask.unsqueeze(1).expand(mask.size(0), ntokens)\n\n # output: batch x seq_len x ntokens\n output = autoencoder(source, lengths, noise=True)\n flattened_output = output.view(-1, ntokens)\n\n masked_output = \\\n flattened_output.masked_select(output_mask).view(-1, ntokens)\n total_loss += F.cross_entropy(masked_output, masked_target).data\n\n # accuracy\n max_vals, max_indices = torch.max(masked_output, 1)\n all_accuracies += \\\n torch.mean(max_indices.eq(masked_target).float()).data.item()\n bcnt += 1\n\n aeoutf = os.path.join(args.save, \"autoencoder.txt\")\n with open(aeoutf, \"a\") as f:\n max_values, max_indices = torch.max(output, 2)\n max_indices = \\\n max_indices.view(output.size(0), -1).data.cpu().numpy()\n target = target.view(output.size(0), -1).data.cpu().numpy()\n for t, idx in zip(target, max_indices):\n # real sentence\n chars = \" \".join([corpus.dictionary.idx2word[x] for x in t])\n f.write(chars + '\\n')\n # autoencoder output sentence\n chars = \" \".join([corpus.dictionary.idx2word[x] for x in idx])\n f.write(chars + '\\n'*2)\n\n return total_loss.item() / len(data_source), all_accuracies/bcnt\n\n\ndef gen_fixed_noise(noise, to_save):\n gan_gen.eval()\n autoencoder.eval()\n\n fake_hidden = gan_gen(noise)\n max_indices = autoencoder.generate(fake_hidden, args.maxlen, sample=args.sample)\n\n with open(to_save, \"w\") as f:\n max_indices = max_indices.data.cpu().numpy()\n for idx in max_indices:\n # generated sentence\n words = [corpus.dictionary.idx2word[x] for x in idx]\n # truncate sentences to first occurrence of \n truncated_sent = []\n for w in words:\n if w != '':\n truncated_sent.append(w)\n else:\n break\n chars = \" \".join(truncated_sent)\n f.write(chars + '\\n')\n\n\ndef train_lm():\n save_path = os.path.join(\"/tmp\", ''.join(random.choice(\n string.ascii_uppercase + string.digits) for _ in range(6)))\n\n indices = []\n noise = Variable(torch.ones(100, args.z_size).cuda())\n for i in range(1000):\n noise.data.normal_(0, 1)\n fake_hidden = gan_gen(noise)\n max_indices = autoencoder.generate(fake_hidden, args.maxlen, sample=args.sample)\n indices.append(max_indices.data.cpu().numpy())\n indices = np.concatenate(indices, axis=0)\n\n with open(save_path, \"w\") as f:\n # laplacian smoothing\n for word in corpus.dictionary.word2idx.keys():\n f.write(word+'\\n')\n for idx in indices:\n words = [corpus.dictionary.idx2word[x] for x in idx]\n # truncate sentences to first occurrence of \n truncated_sent = []\n for w in words:\n if w != '':\n truncated_sent.append(w)\n else:\n break\n chars = \" \".join(truncated_sent)\n f.write(chars+'\\n')\n # reverse ppl\n try:\n rev_lm = train_ngram_lm(kenlm_path=args.kenlm_path,\n data_path=save_path,\n output_path=save_path+\".arpa\",\n N=args.N)\n with open(os.path.join(args.data_path, 'test.txt'), 'r') as f:\n lines = f.readlines()\n if args.lowercase:\n lines = list(map(lambda x: x.lower(), lines))\n sentences = [l.replace('\\n', '') for l in lines]\n rev_ppl = get_ppl(rev_lm, sentences)\n except:\n print(\"reverse ppl error: it maybe the generated files aren't valid to obtain an LM\")\n rev_ppl = 1e15\n # forward ppl\n for_lm = train_ngram_lm(kenlm_path=args.kenlm_path,\n data_path=os.path.join(args.data_path, 'train.txt'),\n output_path=save_path+\".arpa\",\n N=args.N)\n with open(save_path, 'r') as f:\n lines = f.readlines()\n sentences = [l.replace('\\n', '') for l in lines]\n for_ppl = get_ppl(for_lm, sentences)\n return rev_ppl, for_ppl\n\n\ndef train_ae(epoch, batch, total_loss_ae, start_time, i):\n autoencoder.train()\n optimizer_ae.zero_grad()\n\n source, target, lengths = batch\n source = Variable(source.cuda())\n target = Variable(target.cuda())\n output = autoencoder(source, lengths, noise=True)\n\n mask = target.gt(0)\n masked_target = target.masked_select(mask)\n output_mask = mask.unsqueeze(1).expand(mask.size(0), ntokens)\n flat_output = output.view(-1, ntokens)\n masked_output = flat_output.masked_select(output_mask).view(-1, ntokens)\n loss = F.cross_entropy(masked_output, masked_target)\n loss.backward()\n torch.nn.utils.clip_grad_norm_(autoencoder.parameters(), args.clip)\n optimizer_ae.step()\n\n total_loss_ae += loss.data.item()\n if i % args.log_interval == 0:\n probs = F.softmax(masked_output, dim=-1)\n max_vals, max_indices = torch.max(probs, 1)\n accuracy = torch.mean(max_indices.eq(masked_target).float()).data.item()\n cur_loss = total_loss_ae / args.log_interval\n elapsed = time.time() - start_time\n logger.info('| epoch {:3d} | {:5d}/{:5d} batches | ms/batch {:5.2f} | '\n 'loss {:5.2f} | ppl {:8.2f} | acc {:8.2f}'.format(\n epoch, i, len(train_data),\n elapsed * 1000 / args.log_interval,\n cur_loss, math.exp(cur_loss), accuracy))\n total_loss_ae = 0\n start_time = time.time()\n return total_loss_ae, start_time\n\n\ndef train_gan_g():\n gan_gen.train()\n optimizer_gan_g.zero_grad()\n\n z = Variable(torch.Tensor(args.batch_size, args.z_size).normal_(0, 1).cuda())\n fake_hidden = gan_gen(z)\n errG = gan_disc(fake_hidden)\n errG.backward(one)\n optimizer_gan_g.step()\n\n return errG\n\n\ndef grad_hook(grad):\n #gan_norm = torch.norm(grad, p=2, dim=1).detach().data.mean()\n #print(gan_norm, autoencoder.grad_norm)\n return grad * args.grad_lambda\n\n\ndef train_gan_d(batch):\n gan_disc.train()\n optimizer_gan_d.zero_grad()\n\n # + samples\n source, target, lengths = batch\n source = Variable(source.cuda())\n target = Variable(target.cuda())\n real_hidden = autoencoder(source, lengths, noise=False, encode_only=True)\n errD_real = gan_disc(real_hidden.detach())\n errD_real.backward(one)\n\n # - samples\n z = Variable(torch.Tensor(args.batch_size, args.z_size).normal_(0, 1).cuda())\n fake_hidden = gan_gen(z)\n errD_fake = gan_disc(fake_hidden.detach())\n errD_fake.backward(mone)\n\n # gradient penalty\n gradient_penalty = calc_gradient_penalty(gan_disc, real_hidden.data, fake_hidden.data)\n gradient_penalty.backward()\n\n optimizer_gan_d.step()\n return -(errD_real - errD_fake), errD_real, errD_fake\n\n\ndef train_gan_d_into_ae(batch):\n autoencoder.train()\n optimizer_ae.zero_grad()\n\n source, target, lengths = batch\n source = Variable(source.cuda())\n target = Variable(target.cuda())\n real_hidden = autoencoder(source, lengths, noise=False, encode_only=True)\n real_hidden.register_hook(grad_hook)\n errD_real = gan_disc(real_hidden)\n errD_real.backward(mone)\n torch.nn.utils.clip_grad_norm_(autoencoder.parameters(), args.clip)\n\n optimizer_ae.step()\n return errD_real\n\n\ndef train():\n logger.info(\"Training\")\n # gan: preparation\n if args.niters_gan_schedule != \"\":\n gan_schedule = [int(x) for x in args.niters_gan_schedule.split(\"-\")]\n else:\n gan_schedule = []\n niter_gan = 1\n fixed_noise = Variable(torch.ones(args.batch_size, args.z_size).normal_(0, 1).cuda())\n\n best_rev_ppl = None\n impatience = 0\n for epoch in range(1, args.epochs+1):\n train_data = corpus.batchify(corpus.train, args.batch_size, shuffle=True)\n train_data = corpus.add_fake_labels(train_data, field=\"long\")\n\n test_data = corpus.batchify(corpus.test, args.batch_size, shuffle=False)\n test_data = corpus.add_fake_labels(test_data, field=\"long\")\n\n # update gan training schedule\n if epoch in gan_schedule:\n niter_gan += 1\n logger.info(\"GAN training loop schedule: {}\".format(niter_gan))\n\n total_loss_ae = 0\n epoch_start_time = time.time()\n start_time = time.time()\n niter = 0\n niter_g = 1\n\n while niter < len(train_data):\n # train ae\n for i in range(args.niters_ae):\n if niter >= len(train_data):\n break # end of epoch\n total_loss_ae, start_time = train_ae(epoch, train_data[niter],\n total_loss_ae, start_time, niter)\n niter += 1\n # train gan\n for k in range(niter_gan):\n for i in range(args.niters_gan_d):\n errD, errD_real, errD_fake = train_gan_d(\n train_data[random.randint(0, len(train_data)-1)])\n for i in range(args.niters_gan_ae):\n train_gan_d_into_ae(train_data[random.randint(0, len(train_data)-1)])\n for i in range(args.niters_gan_g):\n errG = train_gan_g()\n\n niter_g += 1\n if niter_g % 100 == 0:\n autoencoder.noise_anneal(args.noise_anneal)\n logger.info('[{}/{}][{}/{}] Loss_D: {:.8f} (Loss_D_real: {:.8f} '\n 'Loss_D_fake: {:.8f}) Loss_G: {:.8f}'.format(\n epoch, args.epochs, niter, len(train_data),\n errD.data.item(), errD_real.data.item(),\n errD_fake.data.item(), errG.data.item()))\n # eval\n test_loss, accuracy = evaluate_autoencoder(test_data, epoch)\n logger.info('| end of epoch {:3d} | time: {:5.2f}s | test loss {:5.2f} | '\n 'test ppl {:5.2f} | acc {:3.3f}'.format(epoch,\n (time.time() - epoch_start_time), test_loss,\n math.exp(test_loss), accuracy))\n gen_fixed_noise(fixed_noise, os.path.join(args.save,\n \"{:03d}_examplar_gen\".format(epoch)))\n\n # eval with rev_ppl and for_ppl\n rev_ppl, for_ppl = train_lm(args.data_path)\n logger.info(\"Epoch {:03d}, Reverse perplexity {}\".format(epoch, rev_ppl))\n logger.info(\"Epoch {:03d}, Forward perplexity {}\".format(epoch, for_ppl))\n if best_rev_ppl is None or rev_ppl < best_rev_ppl:\n impatience = 0\n best_rev_ppl = rev_ppl\n logger.info(\"New saving model: epoch {:03d}.\".format(epoch))\n save_model()\n else:\n if not args.no_earlystopping and epoch >= args.min_epochs:\n impatience += 1\n if impatience > args.patience:\n logger.info(\"Ending training\")\n sys.exit()\n\nif __name__ == '__main__':\n train()\n\n","sub_path":"cad/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":15140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"588054","text":"def alphabet(letters):\n num = list()\n for i in range(len(letters)):\n num.append(i)\n return dict(zip(list(letters),num))\n\n\ndef f(x,letters):\n return divmod(22*x+25,len(letters)+1)\n\ndef encript_sequence(letters,message):\n alpha = alphabet(letters)\n encripted = []\n for letter in message.lower():\n if letter == \" \":\n encripted.append(len(letters)-1)\n continue\n for key in alpha.keys():\n if letter in key:\n encripted.append(f(alpha[key],letters)[1])\n return encripted\n\n\ndef encripted_message(letters,message):\n alpha = alphabet(letters)\n seq = encript_sequence(letters,message)\n code = \"\"\n for num in seq:\n for key in alpha.keys():\n if alpha[key] == num:\n code += key\n return code\n\n\ndef get_message(file):\n message = \"\"\n with open(file,\"r\") as file:\n lines = file.readlines()\n for line in lines:\n message += line\n return message\n\ndef write_message(file,letters,message):\n code = encripted_message(letters,message)\n with open(file,\"w\") as file:\n file.writelines(code)\n\n\npath = \"//home/pedro/Documentos/Python/Mod_encripter/texto.txt\"\nletters = \"abcdefghijklmnopkrstuvwxyz,.-!()€\"\nwrite_message(\"encripted.txt\",letters,get_message(path))\n","sub_path":"Others/Python/Mod_encripter/encripter.py","file_name":"encripter.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"339794353","text":"# coding:iso-8859-9 Türkçe\r\n# p_30409a.py: Skalar/sayısal çarpma ve toplamada küçük matrisin büyüğe otomatik yayılması örneği.\r\n\r\nimport numpy as np\r\n\r\nA = np.array ([\r\n [11, 12, 13],\r\n [21, 22, 23],\r\n [31, 32, 33] ])\r\n\r\nB = np.array ([1, 2, 3])\r\n\r\nb = np.array ([\r\n [1, 2, 3],\r\n [1, 2, 3],\r\n [1, 2, 3] ])\r\n\r\n# A ve B dizileri farklıysa, Numpy işlemleri büyüğe uyumluluk yayılımıyla gerçekleştirir...\r\n\r\nprint (\"A ve B dizileri:\\n\", A, \"\\n\\n\", B, sep=\"\")\r\nprint (\"\\n'A*B' bire-bir çarpım:\\n\", (A * B), sep=\"\")\r\nprint (\"\\n'A+B' bire-bir toplam:\\n\", (A + B), sep=\"\")\r\n\r\nprint (\"\\nBüyük A'ya otomatikmen uyumlu yayılan B dizisi:\\n\", b, sep=\"\")\r\n\r\n\r\n\r\n\"\"\"Çıktı:\r\n>python p_30409a.py\r\nA ve B dizileri:\r\n[[11 12 13]\r\n [21 22 23]\r\n [31 32 33]]\r\n\r\n[1 2 3]\r\n\r\n'A*B' bire-bir çarpım:\r\n[[11 24 39]\r\n [21 44 69]\r\n [31 64 99]]\r\n\r\n'A+B' bire-bir toplam:\r\n[[12 14 16]\r\n [22 24 26]\r\n [32 34 36]]\r\n\r\nBüyük A'ya otomatikmen uyumlu yayılan B dizisi:\r\n[[1 2 3]\r\n [1 2 3]\r\n [1 2 3]]\r\n\"\"\"","sub_path":"Bernd Klein (520) ile Python/p_30409a.py","file_name":"p_30409a.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"314116621","text":"from app.common import logger, errors\nfrom app.usecases.context import Context\n\nfrom app.domain import fees\nfrom app.domain import clients\n\nfrom app.common import security as sek\nfrom app.common import json as json_util\n\n\nEVENT_TYPE_SEND_ETRANSFER = 'etransfer_send'\n\n#\n# writes\n#\nasync def create(ctx: Context, client_id, event_type, fee_value,\n fee_type=fees.FEE_TYPE_FIXED,\n currency_code=fees.DEFAULT_CURRENCY_CODE):\n f_repo = fees.FeesRepo(ctx.db)\n c_repo = clients.ClientsRepo(ctx.db) \n\n client_exists = await c_repo.get_by_client_id(client_id)\n if not client_exists:\n return False, errors.E['fees_invalid_client_id']\n\n # check that this fee doesn't already exists for client\n fee_exists = await f_repo.search(client_id=client_id, event_type=event_type,\n fee_status=fees.STATUS_ACTIVE)\n if fee_exists:\n return False, errors.E['fees_exists_for_event_type']\n\n rec = await f_repo.create(client_id, event_type, fee_value,\n fee_type=fee_type, currency_code=currency_code)\n if rec:\n return True, fees.Fee.from_record(rec) \n else:\n return False, errors.E['fees_unable_to_create']\n\nasync def disable(ctx: Context, fee_id, client_id):\n changed = await _change_status(ctx, client_id, fee_id, fees.STATUS_INACTIVE,\n errors.E['fees_unable_to_disable'])\n return changed\n\n\nasync def enable(ctx: Context, client_id, fee_id):\n changed = await _change_status(ctx, client_id, fee_id, fees.STATUS_ACTIVE,\n errors.E['fees_unable_to_enable'])\n return changed\n\n\nasync def _change_status(ctx: Context, client_id, fee_id, status, failure_message):\n f_repo = fees.FeesRepo(ctx.db)\n\n exists = await f_repo.get_by_fee_id(fee_id)\n\n if not exists:\n return False, errors.E['fees_id_not_found']\n\n rec = await f_repo.change_status(fee_id, status)\n\n if rec:\n return True, fees.Fee.from_record(rec)\n else:\n return False, failure_message\n\n\n#\n# reads\n#\nasync def view_fee(ctx: Context, fee_id):\n f_repo = fees.FeesRepo(ctx.db)\n\n rec = await f_repo.search(fee_id=fee_id)\n if rec:\n return True, fees.Fee.from_record(rec[0])\n else:\n return False, errors.E['fees_id_not_found']\n\n\n","sub_path":"main-service-master/mount/app/usecases/fees.py","file_name":"fees.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"506419222","text":"\nimport re\nimport nltk\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk import bigrams, trigrams\nfrom nltk.stem import *\nimport math\nimport DataReader as DR\n\nRel_Songs=DR.readData(\"Data-Set/Relaxed/Train/\",\"relaxed\")\n#Hap_Songs=DR.readData(\"Data-Set/Happy/Train/\",\"happy\")\n#Sad_Songs=DR.readData(\"Data-Set/Sad/Train/\",\"sad\")\n\nstopwords = nltk.corpus.stopwords.words('english')\ntokenizer = RegexpTokenizer(\"[\\w’]+\", flags=re.UNICODE)\n#stemmer = PorterStemmer()\nstemmer = SnowballStemmer(\"english\")\n#lemmatizer=WordNetLemmatizer()\n\n\n\ndef freq(word, doc):\n return doc.count(word)\n\n\ndef word_count(doc):\n return len(doc)\n\n\ndef tf(word, doc):\n return (freq(word, doc) / float(word_count(doc)))\n\n\ndef num_docs_containing(word, list_of_docs):\n count = 0\n for document in list_of_docs:\n if freq(word, document) > 0:\n count += 1\n return 1 + count\n\n\ndef idf(word, list_of_docs):\n return math.log(len(list_of_docs) / float(num_docs_containing(word, list_of_docs)))\n\n\ndef tf_idf(word, doc, list_of_docs):\n return (tf(word, doc) * idf(word, list_of_docs))\n\n#Compute the frequency for each term.\nvocabulary = []\ndocs = {}\nall_tips = []\nfor tip in (Rel_Songs):\n tokens = tokenizer.tokenize(tip[4])\n #bi_tokens = bigrams(tokens)\n #tri_tokens = trigrams(tokens)\n tokens = [token.lower() for token in tokens if len(token) > 2]\n tokens = [token for token in tokens if token not in stopwords]\n #tokens = [lemmatizer.lemmatize(t) for t in tokens]\n tokens = [stemmer.stem(t) for t in tokens]\n \n \"\"\" \t\n bi_tokens = [' '.join(token).lower() for token in bi_tokens]\n bi_tokens = [token for token in bi_tokens if token not in stopwords]\n\n tri_tokens = [' '.join(token).lower() for token in tri_tokens]\n tri_tokens = [token for token in tri_tokens if token not in stopwords]\n \"\"\"\n final_tokens = []\n final_tokens.extend(tokens)\n #final_tokens.extend(bi_tokens)\n #final_tokens.extend(tri_tokens)\n docs[tip[0]] = {'freq': {}, 'tf': {}, 'idf': {},'tf-idf': {}, 'tokens': []}\t\n for token in final_tokens:\n #The frequency computed for each tip\n\n docs[tip[0]]['freq'][token] = freq(token, final_tokens)\n #The term-frequency (Normalized Frequency)\n docs[tip[0]]['tf'][token] = tf(token, final_tokens)\n docs[tip[0]]['tokens'] = final_tokens\n\n vocabulary.append(final_tokens)\n\nfor doc in docs:\n for token in docs[doc]['tf']:\n #The Inverse-Document-Frequency\n docs[doc]['idf'][token] = idf(token, vocabulary)\n #The tf-idf\n docs[doc]['tf-idf'][token] = tf_idf(token, docs[doc]['tokens'], vocabulary)\n\n#Now let's find out the most relevant words by tf-idf.\nwords = {}\nfor doc in docs:\n for token in docs[doc]['tf-idf']:\n if token not in words:\n words[token] = docs[doc]['tf-idf'][token]\n else:\n if docs[doc]['tf-idf'][token] > words[token]:\n words[token] = docs[doc]['tf-idf'][token]\n \"\"\"\t\n print (doc)\n for token in docs[doc]['tf-idf']:\n print (token, docs[doc]['tf-idf'][token])\n \"\"\"\t\n\n#Now let's find out the most relevant words by tf-idf.\nfreq_words = {}\nfor doc in docs:\n for token in docs[doc]['freq']:\n if token not in freq_words:\n freq_words[token] = docs[doc]['freq'][token]\n else:\n if docs[doc]['freq'][token] > freq_words[token]:\n freq_words[token] = docs[doc]['freq'][token]\n\n\n# top 5 words acc to tf-idf\ni=0\nfor item in sorted(words.items(), key=lambda x: x[1], reverse=True):\n\t#if i == 5:\n\t#\tbreak \n\tprint (\"%f <= %s\" % (item[1], item[0]))\n\t#i+=1\n\n\"\"\"\n# top 5 words acc to freq\t\ni=0\nfor item in sorted(freq_words.items(), key=lambda x: x[1], reverse=True):\n\tif i == 5:\n\t\tbreak \n\tprint (\"%f <= %s\" % (item[1], item[0]))\n\ti+=1\t\n\"\"\"\n","sub_path":"tdff.py","file_name":"tdff.py","file_ext":"py","file_size_in_byte":3817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"384516691","text":"from django.conf.urls import patterns, url\nfrom unicorn import views\nfrom django.conf.urls import include\nfrom .router import router\nunicorn_api_router = router().router\nurlpatterns = patterns('', url(r'api/', include(unicorn_api_router.urls)),\n url(r'^warranty_lookup/$', views.warranty_lookup),\n url(r'^queues_standing_ticket_all/$',\n views.queues_standing_ticket_all),\n url(r'^queues_standing_ticket_daily/$',\n views.queues_standing_ticket_daily),\n url(r'^queues_standing_deliveries_daily/$',\n views.queues_standing_deliveries_daily),\n url(r'^queues_standing_income_all/$',\n views.queues_standing_income_all),\n url(r'^queues_standing_income_daily/$',\n views.queues_standing_income_daily),\n url(r'^user_standing_assigned_created_all/$',\n views.user_standing_assigned_created_all),\n url(r'^feedback_standing_all/$',\n views.feedback_standing_all),\n url(r'^communicateCurrentStatus/(?P\\w+)$',\n views.communicateCurrentStatus),\n url(r'^download_barcode/(?P\\w+)$',\n views.download_barcode),\n url(\n r'^download_daily_status_report/(?P
\\w+)/(?P\\w+)/(?P\\d{4})/(?P\\d{1,2})/(?P\\d{1,2})/$', views.download_daily_status_report),\n url(\n r'^download_daily_status_report_outward/(?P
\\w+)/(?P\\w+)/(?P\\d{4})/(?P\\d{1,2})/(?P\\d{1,2})/$', views.download_daily_status_report_outward),\n url(r'^service_product_standing_all/$',\n views.service_product_standing_all),\n url(r'^service_product_standing_daily/$',\n views.service_product_standing_daily),\n url(r'^dashboard/$', views.dashboard),\n )\n","sub_path":"unicorn/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"280773895","text":"def build_profile(first, last, **user_info):\n \"\"\"Build a dictionary containing everything we know about a user.\"\"\"\n profile = {}\n profile['first_name'] = first\n profile['last_name'] = last\n for key, value in user_info.items():\n profile[key] = value\n return profile\n\n\nuser_profile = build_profile('Michael', 'Frankovic',\n location='New Jersey',\n field='IT', hobby='I like to lift')\nprint(user_profile)\n","sub_path":"Chapter 8/8-13_user_profile.py","file_name":"8-13_user_profile.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"286064717","text":"import os\nimport pygame\nfrom miniworldmaker.containers.container import Container\nfrom miniworldmaker.containers.actionbar_widgets import *\n\n\nclass ActionBar(Container):\n\n def __init__(self, board):\n super().__init__()\n self.widgets = []\n self.position = \"right\"\n self.board = board\n self.listen_to_all_events = False\n self.add_widget(PlayButton(self.board))\n self.add_widget(RunButton(self.board))\n self.add_widget(ResetButton(self.board))\n self.add_widget(InfoButton(self.board))\n self.add_widget(SpeedDownButton(self.board))\n self.add_widget(SpeedLabel(self.board))\n self.add_widget(SpeedUpButton(self.board))\n self.board.is_running = False\n self.dirty = 1\n self.default_size = 40\n\n def add_widget(self, widget):\n \"\"\"\n adds a widget to the toolbar\n :param widget: A toolbar widget\n :return:\n \"\"\"\n widget.clear()\n widget.parent = self\n self.widgets.append(widget)\n widget.dirty = 1\n\n def repaint(self):\n if self.dirty:\n self.surface.fill((255, 255, 255))\n if self.widgets:\n actual_position = 5\n for widget in self.widgets:\n widget.height = self._container_height - 10\n widget.repaint()\n self.surface.blit(widget.surface, (actual_position, 5))\n actual_position += widget.width + 5 # 5 is padding between elements\n self.dirty = 0\n self._window.repaint_areas.append(self.rect)\n\n def _widgets_total_width(self):\n width = 0\n for widget in self.widgets:\n width += widget.width + 5\n return width - 5\n\n def get_event(self, event, data):\n if event == \"mouse_left\":\n actual_position = 5\n x, y = data[0], data[1]\n if not x > self._widgets_total_width():\n for widget in self.widgets:\n if actual_position + widget.width + 5 > x:\n return widget.get_event(event, data)\n else:\n actual_position = actual_position + widget.width + 5\n elif event == \"board_speed_changed\":\n for widget in self.widgets:\n widget.get_event(event, data)\n else:\n return \"no toolbar event\"\n","sub_path":"source/miniworldmaker/containers/actionbar.py","file_name":"actionbar.py","file_ext":"py","file_size_in_byte":2420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"587542028","text":"# -*- coding: utf-8 -*-\nfrom random import choice, randint, shuffle\nimport Image, ImageDraw, ImageFont\nfrom settings import MEDIA_ROOT, SECRET_KEY, MEDIA_URL\nfrom hashlib import sha1 as sha\n\ndef gerar_captcha_view(request):\n DIR_ARQ_ENTRADA = MEDIA_ROOT + '/imagem/captcha/'\n\n numeros = '123456789'\n letras = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n caracteres_captcha = 5\n\n fonte_ttf = 'comic.ttf'\n fonte_ttf_tam = 16\n fonte_ttf_cor = (0, 0, 0)\n fonte_ttf_espacamento = margem_esquerda, margem_topo = 10, -1\n \n num_img_fundo = randint(0, 5)\n img_fundo = 'captcha%d.jpg' % num_img_fundo\n \n num_numeros = randint(2, caracteres_captcha - 1)\n num_letras = caracteres_captcha - num_numeros\n \n textoImagem = [choice(letras) for i in range(num_letras)] + [choice(numeros) for i in range(num_numeros)]\n \n shuffle(textoImagem)\n textoImagem = ''.join(textoImagem)\n request.session['cod_captcha'] = textoImagem\n \n im = Image.open('%s%s' % (DIR_ARQ_ENTRADA, img_fundo))\n draw = ImageDraw.Draw(im)\n font_img = ImageFont.truetype('%s%s' % (DIR_ARQ_ENTRADA, fonte_ttf), fonte_ttf_tam)\n draw.text(fonte_ttf_espacamento, textoImagem, font=font_img, fill=fonte_ttf_cor)\n\n from django.http import HttpResponse\n from StringIO import StringIO\n data = StringIO()\n im.save(data, format='JPEG')\n data.seek(0)\n \n return HttpResponse(data.read(), mimetype='image/jpeg')\n\n\nclass Captcha:\n\n def gerarImagem(self, nomeArquivo):\n\n DIR_ARQ_ENTRADA = MEDIA_ROOT + '/imagem/captcha/'\n DIR_ARQ_SAIDA = MEDIA_ROOT + '/tmp/'\n SALT = SECRET_KEY[:20]\n\n\n tipo_validacao = 2 # fixando para que sempre seja pedido toda a string\n numeros = '123456789'\n letras = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n caracteres_captcha = 5\n\n\n fonte_ttf = 'comic.ttf'\n fonte_ttf_tam = 16\n fonte_ttf_cor = (0,0,0)\n fonte_ttf_espacamento = margem_esquerda, margem_topo = 10,-1\n\n num_img_fundo = randint(0,5)\n img_fundo = 'captcha' + str(num_img_fundo) + '.jpg'\n\n\n num_numeros = randint(2, caracteres_captcha-1)\n num_letras = caracteres_captcha - num_numeros\n\n imgtextL = ''.join([choice(letras) for i in range(num_letras)])\n imgtextN = ''.join([choice(numeros) for i in range(num_numeros)])\n\n textoImagem = imgtextL + imgtextN\n textoImagem = list(textoImagem)\n shuffle(textoImagem)\n textoImagem = ''.join(textoImagem)\n\n\n imgtextL = ''.join([i for i in textoImagem if i.isalpha()])\n imgtextN = ''.join([i for i in textoImagem if i.isdigit()])\n\n im = Image.open(DIR_ARQ_ENTRADA + img_fundo)\n draw = ImageDraw.Draw(im)\n font_img = ImageFont.truetype(DIR_ARQ_ENTRADA + fonte_ttf, fonte_ttf_tam)\n draw.text(fonte_ttf_espacamento, textoImagem, font = font_img, fill = fonte_ttf_cor)\n arqSaida = DIR_ARQ_SAIDA + nomeArquivo + '.jpg'\n tempname = MEDIA_URL + 'tmp/' + nomeArquivo + '.jpg'\n im.save(arqSaida, \"JPEG\")\n\n\n if tipo_validacao == 0:\n imghash = sha.new(SALT + imgtextN).hexdigest()\n\n if tipo_validacao == 1:\n imghash = sha.new(SALT + imgtextL).hexdigest()\n\n if tipo_validacao == 2:\n imghash = sha.new(SALT + textoImagem).hexdigest()\n\n return {\n 'captcha_img_name':tempname,\n 'hash_code_captcha':imghash,\n 'tipo_validacao':tipo_validacao,\n 'url_arquivo':arqSaida,\n 'texto':textoImagem,\n 'numeros':imgtextN,\n 'letras':imgtextL\n }\n","sub_path":"lab_django1_4/captchas_old/Captcha.py","file_name":"Captcha.py","file_ext":"py","file_size_in_byte":3630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"616309019","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 18 07:01:03 2019\n\n@author: ASUS-PC\n\"\"\"\n\n# keras layers\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, DepthwiseConv2D\nfrom keras.layers import MaxPooling2D,GlobalAveragePooling2D\nfrom keras.layers import Flatten\nfrom keras.layers import Dense\nfrom keras.layers import Dropout\nfrom keras.layers import BatchNormalization,LeakyReLU\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras import regularizers\n# Image Preprocessing\nfrom keras.preprocessing.image import ImageDataGenerator\nimport numpy as np\n\n# model\nclassifier = Sequential()\n\n# adding layers\nclassifier.add(Conv2D(32, kernel_size=3, strides=1, padding=\"same\", kernel_regularizer=regularizers.l2(0.00001), input_shape=(128, 128, 3)))\nclassifier.add(LeakyReLU())\nclassifier.add(Conv2D(32, kernel_size=3, strides=1, padding=\"same\", kernel_regularizer=regularizers.l2(0.00001)))\nclassifier.add(LeakyReLU())\nclassifier.add(Conv2D(32, kernel_size=3, strides=1, padding=\"same\", kernel_regularizer=regularizers.l2(0.00001)))\nclassifier.add(LeakyReLU())\nclassifier.add(MaxPooling2D(pool_size=(2, 2)))\n\nclassifier.add(Dropout(0.6))\n\nclassifier.add(Conv2D(32, kernel_size=3, strides=1, padding=\"same\"))\nclassifier.add(LeakyReLU())\nclassifier.add(Conv2D(32, kernel_size=3, strides=1, padding=\"same\",))\nclassifier.add(LeakyReLU())\nclassifier.add(Conv2D(32, kernel_size=3, strides=1, padding=\"same\",))\nclassifier.add(LeakyReLU())\n\nclassifier.add(MaxPooling2D(pool_size=(2, 2)))\n\nclassifier.add(DepthwiseConv2D( kernel_size=3, strides=1, padding=\"same\",kernel_initializer='he_normal'))\nclassifier.add(LeakyReLU())\nclassifier.add(BatchNormalization(axis=3))\nclassifier.add(Conv2D(32, kernel_size=1, strides=1, padding=\"same\",kernel_initializer='he_normal'))\nclassifier.add(LeakyReLU())\nclassifier.add(BatchNormalization(axis=3))\n\nclassifier.add(DepthwiseConv2D( kernel_size=3, strides=1, padding=\"same\",kernel_initializer='he_normal'))\nclassifier.add(LeakyReLU())\nclassifier.add(BatchNormalization(axis=3))\nclassifier.add(Conv2D(32, kernel_size=1, strides=1, padding=\"same\",kernel_initializer='he_normal'))\nclassifier.add(LeakyReLU())\nclassifier.add(BatchNormalization(axis=3))\n\nclassifier.add(Conv2D(64, kernel_size=3, strides=1, padding=\"same\"))\nclassifier.add(LeakyReLU())\nclassifier.add(Conv2D(64, kernel_size=3, strides=1, padding=\"same\"))\nclassifier.add(LeakyReLU())\nclassifier.add(Conv2D(64, kernel_size=3, strides=1, padding=\"same\",))\nclassifier.add(LeakyReLU())\nclassifier.add(Conv2D(64, kernel_size=3, strides=1, padding=\"same\",))\nclassifier.add(LeakyReLU())\nclassifier.add(MaxPooling2D(pool_size=(2, 2)))\n\nclassifier.add(Dropout(0.6))\n\nclassifier.add(Conv2D(64, kernel_size=3, strides=1, padding=\"same\"))\nclassifier.add(LeakyReLU())\nclassifier.add(Conv2D(64, kernel_size=3, strides=1, padding=\"same\"))\nclassifier.add(LeakyReLU())\nclassifier.add(Conv2D(64, kernel_size=3, strides=1, padding=\"same\",))\nclassifier.add(LeakyReLU())\nclassifier.add(Conv2D(64, kernel_size=3, strides=1, padding=\"same\",))\nclassifier.add(LeakyReLU())\n\n# classifier.add(GlobalAveragePooling2D())\nclassifier.add(MaxPooling2D(pool_size=(2, 2)))\nclassifier.add(Flatten())\nclassifier.add(Dropout(0.4))\n\nclassifier.add(Dense(1024, activation='relu'))\nclassifier.add(Dropout(0.4))\nclassifier.add(Dense(512, activation='relu'))\nclassifier.add(Dropout(0.4))\nclassifier.add(Dense(256, activation='relu'))\nclassifier.add(Dropout(0.4))\nclassifier.add(Dense(128, activation='relu'))\nclassifier.add(Dense(units=24, activation='softmax'))\n\n# compiling cnn\nclassifier.compile(optimizer='adam',\n loss='categorical_crossentropy',\n metrics=['accuracy']\n )\n\nclassifier.summary()\n\ntrain_datagen = ImageDataGenerator(\n rescale=1./255,\n shear_range=0.2,\n zoom_range=0.1,\n rotation_range=10,\n horizontal_flip=True,\n height_shift_range=0.1,\n width_shift_range=0.1,\n fill_mode='nearest',\n samplewise_center=True,\n samplewise_std_normalization=True,\n # featurewise_center=True,\n # featurewise_std_normalization=True,\n )\n# train_datagen.mean = np.array([0.50732507, 0.39511367, 0.39813832], dtype=np.float32).reshape((1,1,3))\n# train_datagen.std = 0.05979150389245361\n\ntest_datagen = ImageDataGenerator(\n rescale=1./255,\n samplewise_center=True,\n samplewise_std_normalization=True,\n # featurewise_center=True,\n # featurewise_std_normalization=True,\n )\n# test_datagen.mean = np.array([0.42023899, 0.30655081, 0.29950314], dtype=np.float32).reshape((1,1,3))\n# test_datagen.std = 0.059090827181001726\n\ntraining_set = train_datagen.flow_from_directory('B',\n target_size=(128, 128),\n batch_size=170,\n class_mode='categorical',\n )\n\ntest_set = test_datagen.flow_from_directory('A',\n target_size=(128, 128),\n batch_size=170,\n class_mode='categorical',\n )\n\nclassifier.fit_generator(training_set,\n steps_per_epoch=156,\n epochs=30,\n validation_data=test_set,\n validation_steps=156,\n shuffle=True,\n callbacks=[ReduceLROnPlateau(monitor='val_acc', factor=0.2, patience=4, verbose=1, mode='auto')]\n )\n\n\nclassifier.save('cus.h5') \n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom glob import glob\nimport time\nimport seaborn as sns\nimport itertools\nCLASSES = [folder[len('B') + 1:] for folder in glob('B' + '/*')]\nCLASSES.sort()\n\n\n\ndef evaluate_model(generator):\n start_time = time.time()\n evaluations = classifier.evaluate_generator(generator, steps=1)\n for i in range(len(classifier.metrics_names)):\n print(\"{}: {:.2f}%\".format(\n classifier.metrics_names[i], evaluations[i] * 100))\n print('Took {:.0f} seconds to evaluate this set.'.format(\n time.time() - start_time))\n\n start_time = time.time()\n predictions = classifier.predict_generator(generator, steps=1)\n print('Took {:.0f} seconds to get predictions on this set.'.format(\n time.time() - start_time))\n\n y_pred = np.argmax(predictions, axis=1)\n y_true = generator.classes\n print(y_true,\" = \", y_pred)\n return dict(y_pred=y_pred, y_true=y_true)\n\n\ndef evaluate_validation_dataset():\n predict_datagen = ImageDataGenerator()\n predict_set = predict_datagen.flow_from_directory('E',\n target_size=(128, 128),\n batch_size=240,\n class_mode='categorical',\n shuffle=False\n )\n \n return evaluate_model(predict_set)\n\nprint(\"run: =\")\nCNN_VALIDATION_SET_EVAL = evaluate_validation_dataset()\nprint(classification_report(**CNN_VALIDATION_SET_EVAL, target_names=CLASSES))","sub_path":"Transfer Learning/ayatCus.py","file_name":"ayatCus.py","file_ext":"py","file_size_in_byte":7857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"472342187","text":"\"\"\"A baseline recommender implementation.\"\"\"\n\nfrom collections import defaultdict\n\n\nclass User(object):\n \"\"\" Data class that represents one user in the recommender network.\n \"\"\"\n def __init__(self, user_id):\n self.user_id = user_id # String identifier of the user.\n self.user_profile = defaultdict(float) # A dict with users interests (interactions), { item_id => interaction weight}\n\n\nclass Item(object):\n \"\"\" Data class that represents one item in the recommender network.\n \"\"\"\n def __init__(self, item_id):\n self.item_id = item_id # String with the item identification.\n self.item_profile = defaultdict(float) # {user_id => interaction weight}\n\n\nclass Recommender(object):\n \"\"\"\n A Baseline Recommender.\n It allows to add a new interaction into the network.\n Recommendations candidates are obtained as all items on the path of the length 3 from the user.\n\n \"\"\"\n def __init__(self):\n self.users = dict() # {user_id => User()}\n self.items = dict() # {item_id => Item()}\n\n def put_interaction(self, user_id, item_id, weight):\n \"\"\" Add a new edge in the network.\n \"\"\"\n # Obtain the user if already exists.\n if user_id in self.users:\n user = self.users[user_id]\n # ...or create a new one.\n else:\n user = self.users[user_id] = User(user_id)\n\n # Obtain the item if already exists.\n if item_id in self.items:\n item = self.items[item_id]\n # ...or create a new one.\n else:\n item = self.items[item_id] = Item(item_id)\n\n # Insert a new interest into the user/item profile.\n # If there is the same interests, use the higher weight.\n # Here you can try different methods how to deal with repeating interactions (e.g. sum them)\n user.user_profile[item_id] = max(weight, user.user_profile[item_id])\n item.item_profile[user_id] = max(weight, item.item_profile[user_id])\n\n def recommend(self, user_id):\n \"\"\" Find all items on the path of the length 3 from the given user.\n \"\"\"\n if user_id not in self.users:\n return []\n\n # One item could be accessible by more then one path in the network.\n # If so, we will sum all these paths into the item's score.\n scores = defaultdict(float)\n user_node = self.users[user_id]\n for user_item_id, user_item_weight in user_node.user_profile.items():\n user_item_node = self.items[user_item_id]\n for neighbour_id, neighbour_weight in user_item_node.item_profile.items():\n neighbour_node = self.users[neighbour_id]\n for neighbour_item_id, neighbour_item_weight in neighbour_node.user_profile.items():\n # Add the path weight to the item's score.\n scores[neighbour_item_id] += user_item_weight * neighbour_weight * neighbour_item_weight\n\n # Return top 10 items with the best score.\n return sorted(scores.keys(), key=lambda item_id: scores[item_id], reverse=True)[:10]\n","sub_path":"recommender/baseline_recommender.py","file_name":"baseline_recommender.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"452528407","text":"import struct\nimport numpy as np\nimport scipy\nTrolleys = [[0x94, 0xAA, 0x82, 0x12, 0xCF, 0xA4],\n [0xa4, 0x20, 0xb9, 0xab, 0x62, 0x24]]\n\n\nBeacons = [[0x97, 0xf9, 0x61, 0x20, 0x41, 0x58],\n [0xc1, 0x4f, 0x79, 0x20, 0x41, 0x58],\n [0x6c, 0xfa, 0x61, 0x20, 0x41, 0x58],\n [0x99, 0xfa, 0x61, 0x20, 0x41, 0x58],\n [0xd8, 0x6b, 0x79, 0x20, 0x41, 0x58],\n [0xef, 0x6f, 0x79, 0x20, 0x41, 0x58],\n [0x58, 0x41, 0x20, 0x79, 0x6F, 0xEF]]\nBeaconXs = [0.66, 8.36, 9.00, 13.13, 16.12, 17.44]\nBeaconYs = [4.43, 7.49, 13.98, 6.75, 7.31, 9.71]\n\ndef macCompare(self, mac, Array):# to do...\n flag = True\n for i in range(0,len(Array)):\n flag = True\n for j in range(0,len(Array[0])):\n if Array[i][j] != mac[j]:\n flag = False\n break\n if flag:\n return i\n return -1\n\n#!/usr/bin/env python2\n\n# a simple script for one of my articles - https://cryptolok.blogspot.com/2017/08/practical-wifi-hosts-triangulation-with.html\n\nfrom math import log10\n\ndef dbm2m(self, dbm):\n MHz = 2400\n dBm = 54 \n FSPL = 27.55\n # Free-Space Path Loss adapted avarage constant for home WiFI routers and following units\n m = 10 ** (( FSPL - (20 * log10(MHz)) + dBm ) / 20 )\n m = round(m,2)\n print ('DISTANCE : ',m,'m')\n return m\n\nfrom scipy import optimize\nimport math\n\ndef locate(self, Xs, Ys, Beacons):\n x_Beacons = []\n y_Beacons = []\n for i in range(0, len(self.sensedBeacons)):\n id = self.macCompare(self.sensedBeacons[i], Beacons)\n x_Beacons.append(Xs[id])\n y_Beacons.append(Ys[id])\n\n def mse(pos, x_Beacons, y_Beacons, distances):\n mse = 0.0\n for x,y, distance in zip(x_Beacons, y_Beacons,distances):\n mse += (np.sqrt((pos[0]-x)**2 + (pos[1]-y)**2) - distance)**2\n return mse / len(distances)\n\n initial_location = (x_Beacons[0], y_Beacons[0])\n\n result = scipy.optimize.minimize(\n mse, # The error function\n initial_location, # The initial guess\n args=(x_Beacons, y_Beacons, self.sensedDistance), # Additional parameters for mse\n method='L-BFGS-B', # The optimisation algorithm\n options={\n 'ftol':1e-5, # Tolerance\n 'maxiter': 1e+4 # Maximum iterations\n })\n (self.x, self.y) = result.x\n\n\ndef mse(pos, x_Beacons, y_Beacons, distances):\n mse = 0.0\n for x,y, distance in zip(x_Beacons, y_Beacons,distances):\n mse += (np.sqrt((pos[0]-x)**2 + (pos[1]-y)**2) - distance)**2\n return mse / len(distances) \n\ninitial_location = [5, 6]\nx_Beacons = [1,2,3]\ny_Beacons = [1,2,3]\nresult = optimize.minimize(\n mse, # The error function\n initial_location, # The initial guess\n args=(x_Beacons, y_Beacons, [1, 2, 3]), # Additional parameters for mse\n method='L-BFGS-B', # The optimisation algorithm\n options={\n 'ftol':1e-5, # Tolerance\n 'maxiter': 1e+4 # Maximum iterations\n })\n\nimport cv2 as cv\nimg = cv.imread('J:\\GoogleDrive\\HKUST\\ISDN 3002\\Map.JPG')\n\nloc2pixel_x = img.shape[1] / 22.35\nloc2pixel_y = img.shape[0] / 14.9\n\n# for i in range(0,6):\n# img2 = cv.circle(img2,\n# (round(trolleylist[i].x*loc2pixel_x), round(trolleylist[i].y*loc2pixel_y)),\n# 10, (0,255,0), -1)\n\n# while True:\n# cv.imshow('4223', img)\n# cv.waitKey(1)\n\nmap = [[0] * 11] * 7\nprint(map)\nprint(map[6][10])\n","sub_path":"Server/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"393572236","text":"#!/usr/bin/env python3\nimport argparse\nimport datetime\nimport logging\nimport numpy as np\n\nfrom aiohttp import ClientConnectionError\nfrom pyModbusTCP.client import ModbusClient\nfrom pymodbus.constants import Endian\nfrom pymodbus.payload import BinaryPayloadDecoder\nimport asyncio\nfrom aioinflux import InfluxDBClient, InfluxDBWriteError\n\ndatapoint = {\n 'measurement': 'SolarEdge',\n 'tags': {},\n 'fields': {}\n}\nreg_block = {}\nlogger = logging.getLogger('solaredge')\n\n\nasync def write_to_influx(dbhost, dbport, mbmeters, dbname='solaredge'):\n global client\n global datapoint\n global reg_block\n\n def trunc_float(floatval):\n return float('%.2f' % floatval)\n\n try:\n solar_client = InfluxDBClient(host=dbhost, port=dbport, db=dbname)\n await solar_client.create_database(db=dbname)\n except ClientConnectionError as e:\n logger.error(f'Error during connection to InfluxDb {dbhost}: {e}')\n return\n\n logger.info('Database opened and initialized')\n while True:\n try:\n reg_block = {}\n reg_block = client.read_holding_registers(40069, 38)\n if reg_block:\n datapoint = {\n 'measurement': 'SolarEdge',\n 'tags': {},\n 'fields': {}\n }\n # print(reg_block)\n # reg_block[0] = Sun Spec DID\n # reg_block[1] = Length of Model Block\n # reg_block[2] = AC Total current value\n # reg_block[3] = AC Phase A current value\n # reg_block[4] = AC Phase B current value\n # reg_block[5] = AC Phase C current value\n # reg_block[6] = AC current scale factor\n # reg_block[7] = AC Phase A to B voltage value\n # reg_block[8] = AC Phase B to C voltage value\n # reg_block[9] = AC Phase C to A voltage value\n # reg_block[10] = AC Phase A to N voltage value\n # reg_block[11] = AC Phase B to N voltage value\n # reg_block[12] = AC Phase C to N voltage value\n # reg_block[13] = AC voltage scale factor\n # reg_block[14] = AC Power value\n # reg_block[15] = AC Power scale factor\n # reg_block[16] = AC Frequency value\n # reg_block[17] = AC Frequency scale factor\n # reg_block[27] = DC Current value\n # reg_block[28] = DC Current scale factor\n # reg_block[29] = DC Voltage value\n # reg_block[30] = DC Voltage scale factor\n # reg_block[31] = DC Power value\n # reg_block[32] = DC Power scale factor\n # reg_block[34] = Inverter temp\n # reg_block[37] = Inverter temp scale factor\n datapoint['tags']['inverter'] = 1\n\n # AC Current\n logger.debug(f'Block6: {str(reg_block[6])}')\n logger.debug(f'AC Current SF: {str(np.int16(reg_block[6]))}')\n scalefactor = np.float_power(10,np.int16(reg_block[6]))\n logger.debug(f'AC Current mult: {str(scalefactor)}')\n if reg_block[2]<65535:\n datapoint['fields']['AC Total Current'] = trunc_float(reg_block[2] * scalefactor)\n if reg_block[3] <65535:\n datapoint['fields']['AC Current phase A'] = trunc_float(reg_block[3] * scalefactor)\n if reg_block[4]<65535:\n datapoint['fields']['AC Current phase B'] = trunc_float(reg_block[4] * scalefactor)\n if reg_block[5]<65535:\n datapoint['fields']['AC Current phase C'] = trunc_float(reg_block[5] * scalefactor)\n\n # AC Voltage\n logger.debug(f'Block13: {str(reg_block[13])}')\n logger.debug(f'AC Voltage SF: {str(np.int16(reg_block[13]))}')\n scalefactor = np.float_power(10,np.int16(reg_block[13]))\n logger.debug(f'AC Voltage mult: {str(scalefactor)}')\n if reg_block[7]<65535:\n datapoint['fields']['AC Voltage phase A-B'] = trunc_float(reg_block[7] * scalefactor)\n if reg_block[8]<65535:\n datapoint['fields']['AC Voltage phase B-C'] = trunc_float(reg_block[8] * scalefactor)\n if reg_block[9]<65535:\n datapoint['fields']['AC Voltage phase C-A'] = trunc_float(reg_block[9] * scalefactor)\n if reg_block[10]<65535:\n datapoint['fields']['AC Voltage phase A-N'] = trunc_float(reg_block[10] * scalefactor)\n if reg_block[11]<65535:\n datapoint['fields']['AC Voltage phase B-N'] = trunc_float(reg_block[11] * scalefactor)\n if reg_block[12]<65535:\n datapoint['fields']['AC Voltage phase C-N'] = trunc_float(reg_block[12] * scalefactor)\n\n # AC Frequency\n logger.debug(f'AC Frequency SF: {str(np.int16(reg_block[17]))}')\n scalefactor = np.float_power(10,np.int16(reg_block[17]))\n if reg_block[16]<65535:\n datapoint['fields']['AC Frequency'] = trunc_float(reg_block[16] * scalefactor)\n\n \n # AC Power\n logger.debug(f'Block15: {str(reg_block[15])}')\n logger.debug(f'AC Power SF: {str(np.int16(reg_block[15]))}')\n scalefactor = np.float_power(10,np.int16(reg_block[15]))\n logger.debug(f'AC Power mult: {str(scalefactor)}')\n if reg_block[14]<65535:\n datapoint['fields']['AC Power output'] = trunc_float(reg_block[14] * scalefactor)\n\n # DC Current\n logger.debug(f'Block28: {str(reg_block[28])}')\n logger.debug(f'DC Current SF: {str(np.int16(reg_block[28]))}')\n scalefactor = np.float_power(10,np.int16(reg_block[28]))\n logger.debug(f'DC Current mult: {str(scalefactor)}')\n if reg_block[27]<65535:\n datapoint['fields']['DC Current'] = trunc_float(reg_block[27] * scalefactor)\n\n # DC Voltage\n logger.debug(f'Block30: {str(reg_block[30])}')\n logger.debug(f'DC voltage SF: {str(np.int16(reg_block[30]))}')\n scalefactor = np.float_power(10,np.int16(reg_block[30]))\n logger.debug(f'DC Voltage mult: {str(scalefactor)}')\n if reg_block[29]<65535:\n datapoint['fields']['DC Voltage'] = trunc_float(reg_block[29] * scalefactor)\n\n # DC Power\n logger.debug(f'Block32: {str(reg_block[32])}')\n logger.debug(f'DC Power SF: {str(np.int16(reg_block[32]))}')\n scalefactor = np.float_power(10,np.int16(reg_block[32]))\n logger.debug(f'DC Power mult: {str(scalefactor)}')\n if reg_block[31]<65535:\n datapoint['fields']['DC Power input'] = trunc_float(reg_block[31] * scalefactor)\n\n # Inverter Temp \n logger.debug(f'Block37: {str(reg_block[37])}')\n logger.debug(f'Temp SF: {str(np.int16(reg_block[37]))}')\n scalefactor = np.float_power(10,np.int16(reg_block[37]))\n logger.debug(f'Temp mult: {str(scalefactor)}')\n if reg_block[34]<65535:\n datapoint['fields']['Inverter Temperature'] = trunc_float(reg_block[34] * scalefactor)\n\n datapoint['time'] = str(datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat())\n logger.debug(f'Writing to Influx: {str(datapoint)}')\n\n await solar_client.write(datapoint)\n\n else:\n # Error during data receive\n if client.last_error() == 2:\n logger.error(f'Failed to connect to SolarEdge inverter {client.host()}!')\n elif client.last_error() == 3 or client.last_error() == 4:\n logger.error('Send or receive error!')\n elif client.last_error() == 5:\n logger.error('Timeout during send or receive operation!')\n \n for x in range(1, mbmeters+1):\n # Now loop through this for each meter that is attached.\n logger.debug(f'Meter={str(x)}')\n reg_block = {}\n \n # Clear data from inverter, otherwise we publish that again!\n datapoint = {\n 'measurement': 'SolarEdge',\n 'tags': {\n 'meter': x\n },\n 'fields': {}\n }\n\n # Start point is different for each meter\n if x==1:\n reg_block = client.read_holding_registers(40190, 36)\n if x==2:\n reg_block = client.read_holding_registers(40364, 36)\n if x==3:\n reg_block = client.read_holding_registers(40539, 36)\n if reg_block:\n # print(reg_block)\n # reg_block[0] = AC Total current value\n # reg_block[1] = AC Phase A current value\n # reg_block[2] = AC Phase B current value\n # reg_block[3] = AC Phase C current value\n # reg_block[4] = AC current scale factor\n # reg_block[5] = AC Phase Line (average) to N voltage value\n # reg_block[6] = AC Phase A to N voltage value\n # reg_block[7] = AC Phase B to N voltage value\n # reg_block[8] = AC Phase C to N voltage value\n # reg_block[9] = AC Phase Line to Line voltage value\n # reg_block[10] = AC Phase A to B voltage value\n # reg_block[11] = AC Phase B to C voltage value\n # reg_block[12] = AC Phase C to A voltage value\n # reg_block[13] = AC voltage scale factor\n # reg_block[14] = AC Frequency value\n # reg_block[15] = AC Frequency scale factor\n # reg_block[16] = Total Real Power\n # reg_block[17] = Phase A Real Power\n # reg_block[18] = Phase B Real Power\n # reg_block[19] = Phase C Real Power\n # reg_block[20] = Real Power scale factor\n # reg_block[21] = Total Apparent Power\n # reg_block[22] = Phase A Apparent Power\n # reg_block[23] = Phase B Apparent Power\n # reg_block[24] = Phase C Apparent Power\n # reg_block[25] = Apparent Power scale factor\n # reg_block[26] = Total Reactive Power\n # reg_block[27] = Phase A Reactive Power\n # reg_block[28] = Phase B Reactive Power\n # reg_block[29] = Phase C Reactive Power\n # reg_block[30] = Reactive Power scale factor\n # reg_block[31] = Average Power Factor\n # reg_block[32] = Phase A Power Factor\n # reg_block[33] = Phase B Power Factor\n # reg_block[34] = Phase C Power Factor\n # reg_block[35] = Power Factor scale factor\n \n logger.debug(f'meter reg_block: {str(reg_block)}')\n\n # AC Current\n logger.debug(f'AC Current SF: {str(np.int16(reg_block[4]))}')\n scalefactor = np.float_power(10,np.int16(reg_block[4]))\n datapoint['fields']['AC Total Current'] = trunc_float(np.int16(reg_block[0]) * scalefactor)\n datapoint['fields']['AC Current phase A'] = trunc_float(np.int16(reg_block[1]) * scalefactor)\n datapoint['fields']['AC Current phase B'] = trunc_float(np.int16(reg_block[2]) * scalefactor)\n datapoint['fields']['AC Current phase C'] = trunc_float(np.int16(reg_block[3]) * scalefactor)\n\n # AC Voltage\n logger.debug(f'AC Voltage SF: {str(np.int16(reg_block[13]))}')\n scalefactor = np.float_power(10,np.int16(reg_block[13]))\n datapoint['fields']['AC Voltage phase L-N'] = trunc_float(np.int16(reg_block[5]) * scalefactor)\n datapoint['fields']['AC Voltage phase A-N'] = trunc_float(np.int16(reg_block[6]) * scalefactor)\n datapoint['fields']['AC Voltage phase B-N'] = trunc_float(np.int16(reg_block[7]) * scalefactor)\n datapoint['fields']['AC Voltage phase C-N'] = trunc_float(np.int16(reg_block[8]) * scalefactor)\n datapoint['fields']['AC Voltage phase L-L'] = trunc_float(np.int16(reg_block[9]) * scalefactor)\n datapoint['fields']['AC Voltage phase A-B'] = trunc_float(np.int16(reg_block[10]) * scalefactor)\n datapoint['fields']['AC Voltage phase B-C'] = trunc_float(np.int16(reg_block[11]) * scalefactor)\n datapoint['fields']['AC Voltage phase C-A'] = trunc_float(np.int16(reg_block[12]) * scalefactor)\n\n # AC Frequency\n logger.debug(f'AC Frequency SF: {str(np.int16(reg_block[15]))}')\n scalefactor = np.float_power(10,np.int16(reg_block[15]))\n datapoint['fields']['AC Frequency'] = trunc_float(np.int16(reg_block[14]) * scalefactor)\n \n # AC Real Power\n logger.debug(f'AC Real Power SF: {str(np.int16(reg_block[20]))}')\n scalefactor = np.float_power(10,np.int16(reg_block[20]))\n datapoint['fields']['AC Total Real Power'] = trunc_float(np.int16(reg_block[16]) * scalefactor)\n datapoint['fields']['AC Real Power Phase A'] = trunc_float(np.int16(reg_block[17]) * scalefactor)\n datapoint['fields']['AC Real Power Phase B'] = trunc_float(np.int16(reg_block[18]) * scalefactor)\n datapoint['fields']['AC Real Power Phase C'] = trunc_float(np.int16(reg_block[19]) * scalefactor)\n \n # AC Apparent Power\n logger.debug(f'AC Apparent Power SF: {str(np.int16(reg_block[25]))}')\n scalefactor = np.float_power(10,np.int16(reg_block[25]))\n datapoint['fields']['AC Total Apparent Power'] = trunc_float(np.int16(reg_block[21]) * scalefactor)\n datapoint['fields']['AC Apparent Power Phase A'] = trunc_float(np.int16(reg_block[22]) * scalefactor)\n datapoint['fields']['AC Apparent Power Phase B'] = trunc_float(np.int16(reg_block[23]) * scalefactor)\n datapoint['fields']['AC Apparent Power Phase C'] = trunc_float(np.int16(reg_block[24]) * scalefactor)\n\n # AC Reactive Power\n logger.debug(f'AC Reactive Power SF: {str(np.int16(reg_block[30]))}')\n scalefactor = np.float_power(10,np.int16(reg_block[30]))\n datapoint['fields']['AC Total Reactive Power'] = trunc_float(np.int16(reg_block[26]) * scalefactor)\n datapoint['fields']['AC Reactive Power Phase A'] = trunc_float(np.int16(reg_block[27]) * scalefactor)\n datapoint['fields']['AC Reactive Power Phase B'] = trunc_float(np.int16(reg_block[28]) * scalefactor)\n datapoint['fields']['AC Reactive Power Phase C'] = trunc_float(np.int16(reg_block[29]) * scalefactor)\n\n # AC Power Factor\n logger.debug(f'AC Power Factor SF: {str(np.int16(reg_block[30]))}')\n scalefactor = np.float_power(10,np.int16(reg_block[35]))\n datapoint['fields']['AC Average Power Factor'] = trunc_float(np.int16(reg_block[31]) * scalefactor)\n datapoint['fields']['AC Power Factor Phase A'] = trunc_float(np.int16(reg_block[32]) * scalefactor)\n datapoint['fields']['AC Power Factor Phase B'] = trunc_float(np.int16(reg_block[33]) * scalefactor)\n datapoint['fields']['AC Power Factor Phase C'] = trunc_float(np.int16(reg_block[34]) * scalefactor)\n\n \n datapoint['time'] = str(datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat())\n logger.debug(f'Writing to Influx: {str(datapoint)}')\n\n await solar_client.write(datapoint)\n\n\n else:\n # Error during data receive\n if client.last_error() == 2:\n logger.error(f'Failed to connect to SolarEdge inverter {client.host()}!')\n elif client.last_error() == 3 or client.last_error() == 4:\n logger.error('Send or receive error!')\n elif client.last_error() == 5:\n logger.error('Timeout during send or receive operation!') \n \n \n \n \n except InfluxDBWriteError as e:\n logger.error(f'Failed to write to InfluxDb: {e}')\n except IOError as e:\n logger.error(f'I/O exception during operation: {e}')\n except Exception as e:\n logger.error(f'Unhandled exception: {e}')\n\n await asyncio.sleep(5)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--influxdb', default='localhost')\n parser.add_argument('--influxport', type=int, default=8086)\n parser.add_argument('--port', type=int, default=502, help='ModBus TCP port number to use')\n parser.add_argument('--unitid', type=int, default=1, help='ModBus unit id to use in communication')\n parser.add_argument('--meters', type=int, default=0, help='Number of ModBus meters attached to inverter (0-3)')\n parser.add_argument('solaredge', metavar='SolarEdge IP', help='IP address of the SolarEdge inverter to monitor')\n parser.add_argument('--debug', '-d', action='count')\n args = parser.parse_args()\n\n logging.basicConfig()\n if args.debug and args.debug >= 1:\n logging.getLogger('solaredge').setLevel(logging.DEBUG)\n if args.debug and args.debug == 2:\n logging.getLogger('aioinflux').setLevel(logging.DEBUG)\n\n print('Starting up solaredge monitoring')\n print(f'Connecting to Solaredge inverter {args.solaredge} on port {args.port} using unitid {args.unitid}')\n print(f'Writing data to influxDb {args.influxdb} on port {args.influxport}')\n print(f'Number of meters is {args.meters}')\n client = ModbusClient(args.solaredge, port=args.port, unit_id=args.unitid, auto_open=True)\n logger.debug('Running eventloop')\n asyncio.get_event_loop().run_until_complete(write_to_influx(args.influxdb, args.influxport, args.meters))\n","sub_path":"solaredge.py","file_name":"solaredge.py","file_ext":"py","file_size_in_byte":19031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"193425085","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 25 22:54:40 2020\n\n@author: Fatema Akter\n\"\"\"\n\nSPY={}\ni=0\nPriceChange=[]\n\nf=open(\"SPY1.csv\", 'r')\n\nfor line in f:\n SPYList = line.split(',')\n SPY[i]={}\n SPY[i][\"date\"] = SPYList[0]\n SPY[i][\"open\"]=SPYList[1]\n SPY[i][\"high\"]=SPYList[2]\n SPY[i][\"low\"]=SPYList[3]\n SPY[i][\"close\"]=SPYList[4]\n SPY[i][\"volume\"]=SPYList[6]\n \n \n if i>0:\n closeDiff =float(SPY[i]['close']) - float(SPY[i-1]['close'])\n PriceChange.append(closeDiff)\n\n i+=1","sub_path":"Project3 done by professor.py","file_name":"Project3 done by professor.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"358449907","text":"# STEP1. 영상 찍기\n\nimport cv2 as cv\nimport os\n\nopt = input(\"(0)train? or (1)test?: \")\nwhile opt!='0' and opt!='1':\n print(\"error\")\n opt = input(\"(0)for train? or (1)test?: \")\nif opt=='0': opt='training_set'\nelif opt=='1': opt='test_set'\n\nfilename = input(\"write what/who it is : \")\n# cv2로부터 VideoCapture 객체 생성\n# cap = cv.VideoCapture('input.mp4')\ncap = cv.VideoCapture(0)\n\nif not os.path.exists('./dataset_img/training_set/'+filename):\n os.mkdir('./dataset_img/training_set/'+filename)\n os.mkdir('./dataset_img/test_set/'+filename)\n print(\"Directory \" , filename , \" Created \")\nelse:\n print(\"Directory \" , filename , \" already exists\")\n\n# fourcc = cv.VideoWriter_fourcc(*'XVID')\nfourcc = cv.VideoWriter_fourcc(*'mp4v')\nout = cv.VideoWriter('./output.mp4',fourcc,30.0, (640,480))\n\nif cap.isOpened() == False:\n print(\"error01\")\n\nwhile(cap.isOpened()):\n # capture the image from camera\n ret, frame = cap.read()\n # if not captured / error happened\n if ret==0: break\n\n # 상하 뒤집기\n frame = cv.resize(frame,(640,480))\n # 이미지를 파일로 저장. VideoWriter 개체에 연속적 저장 : 동영상으로\n out.write(frame)\n\n # 화면에 이미지 출력, 연속적으로 화면에 출력하면 동영상이 된다\n cv.imshow('frame',frame)\n\n # ESC누르면 종료\n if cv.waitKey(1) & 0xFF==27:\n print(\"fin\")\n break\n\n# VideoCapture 객체의 메모리 해제하고 모든 윈도 창 종료\ncap.release()\nout.release()\ncv.destroyAllWindows()\n\n# STEP2. 영상 to 이미지\n\nimport cv2\nimport os\nimport time\n\ndef video_to_frames(video, path_output_dir):\n # extract frames from a video and save to directory as 'x.png' where\n # x is the frame index\n vidcap = cv2.VideoCapture(video)\n count = 0\n while vidcap.isOpened():\n success, image = vidcap.read()\n if success:\n cv2.imwrite(os.path.join(path_output_dir, str(round(time.time()))+'%d.jpg') % count, image)\n count += 1\n else:\n break\n cv2.destroyAllWindows()\n vidcap.release()\n\nvideo_to_frames('./output.mp4', './dataset_img/'+opt+'/'+filename)\nprint('save '+filename)\nprint('dir : ./dataset_img/'+opt+'/'+filename)\nos.remove('./output.mp4')\n","sub_path":"capture.py","file_name":"capture.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"37421774","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom xml.createXml import Xml\nimport os\n\nclass createTNDusENM:\n\n def __init__(self, path, node, site, oss_region, bb):\n self.Enodebrel = Xml().getEnodebRel()\n self.site = site\n self.path = path\n self.node = node\n self.bb_type = bb\n self.oss_region = oss_region\n self.name_SiteTnFile = '04_TN_'+self.node+'_ENM_'+self.bb_type+'_'+self.Enodebrel+'_Telecom_Italia.xml'\n self.path_SiteTnFile = os.path.join(os.path.join(self.path, self.node), self.name_SiteTnFile)\n path_model = os.path.join(path, 'Input BSIM')\n self.SiteTNModel = open(os.path.join(path_model,'04_TN_ENM_DUS_Model.xml'), 'r')\n\n def getTNFileName(self):\n return self.name_SiteTnFile\n\n def go(self):\n eNBId = [x['eNBId'] for x in self.site][0]\n s = ''\n for line in self.SiteTNModel:\n if '$$$OSS_REGION$$$' in line:\n s += line.replace('$$$OSS_REGION$$$', self.oss_region).replace('$$$NODE$$$', self.node)\n elif '$$$NODE$$$' in line:\n s += line.replace('$$$NODE$$$', self.node)\n elif '$$$ENBID$$$' in line:\n s += line.replace('$$$ENBID$$$', eNBId)\n else:\n s += line\n TnFile = open(self.path_SiteTnFile, 'w')\n TnFile.write(s)\n TnFile.close()\n","sub_path":"create/createTNDusENM.py","file_name":"createTNDusENM.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"491659384","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, JsonResponse # 결과 확인\nfrom django.views.decorators.csrf import csrf_exempt # 보안 토큰\nfrom .models import Kitchen_info, Consulting\nfrom django.contrib.auth import get_user_model\nimport json\n\ndef home(request):\n return render(request,'chatbot/home.html')\n\ndef chat(request):\n return render(request,'chatbot/chatbot.html')\n\n# 웹훅의 default response\n@csrf_exempt\ndef webhook(request):\n # build a request object\n req = json.loads(request.body)\n # get action from json\n action = req.get('queryResult').get('action')\n if action:\n \n # 시간 확인하기\n if action=='Consulting2.Consulting2-custom-2.Consulting2-custom-2-custom': \n time = req['queryResult']['parameters']['date-time']['date_time']\n fulfillmentText = {'fulfillmentText':f'요청하신 시간으로 상담 신청 할까요? 요청시간 :{time}'}\n\n # 예약 확인하기\n if action=='Consulting2.Consulting2-custom-2.Consulting2-custom-2-custom.Consulting2-custom-2-custom-yes': \n name = req['queryResult']['outputContexts'][1]['parameters']['KITCHEN_name']\n time = req['queryResult']['outputContexts'][1]['parameters']['date-time']['date_time']\n fulfillmentText = {'fulfillmentText':f'[{name}]으로[{time}]에 상담이 신청되었습니다.\\n라인에서 Our Kitchen을 친구 추가하시고 신청 결과를 받아보세요! \\n https://qr-official.line.me/sid/L/079xpssr.png'}\n \n Consulting.objects.create(kitchen=name,datetime=time)\n\n # 주방 이름 모를 때\n if action=='Consulting2.Consulting2-custom.Consulting2-custom-custom': \n location = req['queryResult']['parameters']['KITCHEN_location']\n \n kitchen_ob = Kitchen_info.objects.filter(kitchen_name__endswith=f'{location}점')\n kitchen_list = ''\n for i in kitchen_ob:\n #kitchen_list += \"(\"+i+\")\"+kitchen_ob[i].kitchen_name\n kitchen_list += '\"'+i.kitchen_name+'\" '\n\n fulfillmentText = {'fulfillmentText':f'어느 주방에 상담을 신청해 드릴까요? [{location}]에는 {kitchen_list}이 있네요!'}\n\n if action=='Consulting2.Consulting2-custom.Consulting2-custom-custom.Consulting2-custom-custom-custom.Consulting2-custom-custom-custom-custom':\n time = req['queryResult']['parameters']['date-time']['date_time']\n fulfillmentText = {'fulfillmentText':f'요청하신 시간으로 상담 신청 할까요? 요청시간 :{time}'} \n\n if action=='Consulting2.Consulting2-custom.Consulting2-custom-custom.Consulting2-custom-custom-custom.Consulting2-custom-custom-custom-custom.Consulting2-custom-custom-custom-custom-yes':\n name = req['queryResult']['outputContexts'][1]['parameters']['KITCHEN_name']\n time = req['queryResult']['outputContexts'][1]['parameters']['date-time']['date_time']\n fulfillmentText = {'fulfillmentText':f'[{name}]으로[{time}]에 상담이 신청되었습니다.\\n라인에서 Our Kitchen을 친구 추가하시고 신청 결과를 받아보세요! \\n https://qr-official.line.me/sid/L/079xpssr.png'}\n\n Consulting.objects.create(kitchen=name,datetime=time)\n\n return JsonResponse(fulfillmentText, safe=False)\n\ndef mypage(request):\n consultings = Consulting.objects.all()\n return render(request,'chatbot/mypage.html',{'consultings':consultings})","sub_path":"chatbot/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"291717877","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom scrapy.selector import Selector\nimport time\nfrom settings import LOCALHOST_MYSQL_HOST, LOCALHOST_MYSQL_USER, LOCALHOST_MYSQL_PASSWD, LOCALHOST_MYSQL_DB\nfrom tools.get_topic_from_mysql import get_topics_from_mysql\nimport pymysql\nimport random\n\n# 建立数据库连接\nconn = pymysql.connect(host=LOCALHOST_MYSQL_HOST, user=LOCALHOST_MYSQL_USER, passwd=LOCALHOST_MYSQL_PASSWD, db=LOCALHOST_MYSQL_DB, charset=\"utf8\")\ncursor = conn.cursor()\n\n# 生成全局的browser\n# 设置无界面启动Chrome\nchrome_options = Options()\nchrome_options.add_argument('--headless')\n# browser = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver')\nbrowser = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver', options=chrome_options)\n\n\n# father_topics = [\n# {\"father_topic_name\": \"根话题\", \"father_topic_id\": \"19776749\", \"topic_level\": 1, \"father_topic_url\": \"https://www.zhihu.com/topic/19776749/organize/entire#anchor-children-topic\"},\n# ]\n# print(father_topics)\n\n\n# 解析url\ndef analysis_response(f_name, f_id, t_level, text):\n topics_selector = Selector(text=text)\n topics_item = topics_selector.css('.zm-topic-organize-item a')\n topics_list = []\n for topic_item in topics_item:\n topic_name = topic_item.css('::text').extract_first()\n if topic_name != '显示子话题' and topic_name != '加载更多':\n topic_id = topic_item.css('::attr(data-token)').extract_first()\n topic_url = 'https://www.zhihu.com/topic/' + topic_id + '/top-answers'\n topic = {\"father_topic_name\": f_name, \"topic_name\": topic_name, \"topic_id\": topic_id, \"topic_level\": t_level}\n topics_list.append(topic)\n\n # 插入数据库\n cursor.execute(\n \"insert into zhihu_topics_tree(father_topic_name, father_topic_id, topic_name, topic_id, topic_url, topic_level)\"\n \"VALUES(%s, %s, %s, %s, %s, %s)\",\n (f_name, f_id, topic_name, topic_id, topic_url, t_level)\n )\n conn.commit()\n print('插入成功 ------ {}'.format(topic))\n\n\n# 获得按钮位置\ndef get_btn_place(page_source):\n more_btn_location = page_source.find('加载更多')\n more_btn_lst = [more_btn_location, '加载更多']\n\n return more_btn_lst\n\n\n# 判断是否继续按钮\ndef click_more_btn(a):\n if a[0] != -1:\n return a[1]\n else:\n return False\n\n\n# 点击按钮\ndef click_front_btn(btn_name):\n try:\n browser.find_element_by_link_text(btn_name).click()\n except Exception as e:\n print('Reason', e)\n print('未能点击按钮:{}!'.format(btn_name))\n\n\n# 接受并发起请求\ndef request_url(url):\n print(url)\n browser.get(url)\n time.sleep(3)\n page_source = browser.page_source\n # print(page_source)\n return page_source\n\n\n# 主程序\ndef get_next_level_topics(start_level, start_id, end_id):\n\n # 获取爬取的父级topics\n father_topics = get_topics_from_mysql(start_level, start_id, end_id)\n father_topics_nums = len(father_topics)\n print('\\n6秒后对登陆二维码截图!')\n\n # 扫码登陆\n login_url = 'https://www.zhihu.com/signin'\n browser.get(login_url)\n time.sleep(4)\n browser.find_element_by_xpath(u\"(.//*[normalize-space(text()) and normalize-space(.)='登录'])[2]/following::button[1]\").click()\n time.sleep(2)\n png_name = random.randint(1, 9999)\n browser.get_screenshot_as_file('/Users/wutengyue/Downloads/login{}.png'.format(png_name))\n print('\\n二维码已经截图,名字为login{}.png'.format(png_name))\n time.sleep(15)\n print('\\n若登陆成功,将爬取该层级父级下的url!')\n\n # 循环访问该层级父级url,以获取下层url\n loop_times = 0\n for father_topic in father_topics:\n loop_times += 1\n remaining_times = father_topics_nums - loop_times\n print('\\n第{0}次循环抓取,剩余{1}次'.format(loop_times, remaining_times))\n\n response_text = request_url(father_topic['father_topic_url'])\n count_click = 0\n\n while True:\n btn_place = get_btn_place(response_text)\n click_btn_name = click_more_btn(btn_place)\n if click_btn_name:\n click_front_btn(click_btn_name)\n count_click += 1\n print('\\nclick {0} btn times: {1}'.format(click_btn_name, count_click))\n time.sleep(2)\n response_text = browser.page_source\n else:\n analysis_response(father_topic['father_topic_name'], father_topic['father_topic_id'], father_topic['topic_level'], response_text)\n break\n\n browser.quit()\n","sub_path":"SpiderProjects/tools/get_next_level_topic.py","file_name":"get_next_level_topic.py","file_ext":"py","file_size_in_byte":4791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"65087594","text":"import os\nimport json\nfrom shapely.geometry import Point\nfrom shapely.geometry.polygon import Polygon\n#? s1 : cloudy / cloudy2\n#? s2 : rainy / sunny\n#? s3 : night\n\nS = {\"cloudy\" : \"s1\", \"cloudy2\" : \"s1\", \"rainy\" : \"s2\", \"sunny\" : \"s2\", \"night\" : \"s3\"}\nclasses = {\"car\" : 0, \"bike\" : 1, \"person\" : 2}\n\nmodel = \"gt\"\npath = f\"video-analysis/lane-count/parts\"\nscenes = {}\ncounter = {}\n\nfor file in os.listdir(path):\n name = file.split(\".\")[0]\n j = json.load(open(f\"{path}/{file}\"))\n scenes[f\"{name}_left\"] = Polygon([(int(x), int(y)) for (x,y) in j[\"left\"]])\n scenes[f\"{name}_right\"] = Polygon([(int(x), int(y)) for (x,y) in j[\"right\"]])\n\nf = open(f\"video-analysis/{model}_centroids.json\")\nC = json.load(f)\n\nfor f in C:\n\n scene = S[f.split(\"_\")[0]]\n\n counter[f\"{f}_left\"] = [0, 0, 0]\n counter[f\"{f}_right\"] = [0, 0, 0]\n\n for p in C[f]:\n\n x, y, c = p.split(\"_\")\n pt = Point(int(x),int(y))\n\n if scenes[f\"{scene}_left\"].contains(pt):\n counter[f\"{f}_left\"][int(c)-1] += 1\n elif scenes[f\"{scene}_right\"].contains(pt):\n counter[f\"{f}_right\"][int(c)-1] += 1\n\nwith open(f\"{model}_count.json\", \"w\") as f:\n json.dump(counter, fp=f, indent=3)\n","sub_path":"src/video-analysis/count.py","file_name":"count.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"550984641","text":"import json\nimport random\nimport re\n\nimport discord\nimport numpy as np\nimport requests\nfrom bs4 import BeautifulSoup\n\nfrom cardNote import CardNote\nfrom dice import Dice\nfrom roToolSearch import RoToolSearch\nfrom seiren import Seiren\nfrom kuji import Kuji\n\n\nclass MyClient(discord.Client):\n\n diceDict = {}\n\n @staticmethod\n def diceRoll(size=1, high=6):\n diceNum = Dice.rollList(size, 1, high)\n diceStr = list(map(str, diceNum))\n return 'dice: ' + ', '.join(diceStr) + '. 合計:' + str(sum(diceNum))\n\n async def on_ready(self):\n print('Logged on as {0}!'.format(self.user))\n\n async def on_message(self, message):\n print(\n 'Message from {0.author}: {0.content}, channel: {0.channel}'.format(message))\n\n if await RoToolSearch.on_message(message):\n return\n\n if await Seiren.on_message(message):\n return\n\n if await Kuji.on_message(message):\n return\n\n if await CardNote.on_message(message):\n return\n\n if message.content.startswith('/hi'):\n if message.content == '/hi':\n reply = '{0.author}様。ご機嫌はいかがでしょうか。'.format(message)\n await message.channel.send(reply)\n return\n\n if message.content.startswith('/neko'):\n if message.content == '/neko':\n reply = 'にゃーん'\n await message.channel.send(reply)\n return\n\n if message.content.startswith('/inu'):\n if message.content == '/inu':\n reply = 'わぉーん'\n await message.channel.send(reply)\n return\n\n if message.content.startswith('/40'):\n if message.content == '/40':\n reply = 'あ、どうもヨンです'\n await message.channel.send(reply)\n return\n\n if message.channel.name == '⚅dice':\n if message.content.startswith('/'):\n s = message.content\n pattern = re.compile(r'/([1-9][0-9]*)[dD]([1-9][0-9]*)$')\n m = pattern.match(s)\n if m:\n diceCount = int(m.group(1))\n diceNum = int(m.group(2))\n\n if diceCount > 100:\n reply = 'Error: ダイスは100個まで'\n await message.channel.send(reply)\n return\n\n if diceNum > 2147483647:\n reply = 'Error: ダイスの目は2,147,483,647まで'\n await message.channel.send(reply)\n return\n\n if(diceCount == 1):\n reply = 'dice:' + Dice.rollToStr(1, diceNum)\n else:\n reply = MyClient.diceRoll(diceCount, diceNum)\n\n await message.channel.send(reply)\n return\n\n if message.content.startswith('/help'):\n reply = '解説するよ!\\n/e19 or /dice: ダイス振るよ!\\n/result: 集計するよ!\\n/reset: リセットするよ!'\n await message.channel.send(reply)\n return\n\n if message.content.startswith('/dice'):\n diceNum = ''.join(Dice.rollListToStr(3))\n MyClient.diceDict[('{0.author}').format(\n message)] = int(diceNum)\n reply = ('dice ' + diceNum + ': {0.author}').format(message)\n await message.channel.send(reply)\n return\n\n if message.content.startswith('/e19'):\n diceNum = ''.join(Dice.rollListToStr(3))\n MyClient.diceDict[('{0.author}').format(\n message)] = int(diceNum)\n reply = ('dice ' + diceNum + ': {0.author}').format(message)\n await message.channel.send(reply)\n return\n\n if message.content.startswith('/result'):\n reply = 'Dice is none'\n\n if len(MyClient.diceDict) > 0:\n reply = 'result \\n'\n for k, v in sorted(MyClient.diceDict.items(), key=lambda x: -x[1]):\n reply = reply + k + ': ' + str(v) + '\\n'\n\n await message.channel.send(reply)\n return\n\n if message.content.startswith('/reset'):\n MyClient.diceDict = {}\n reply = '---------------------------------------------\\nReset dice'\n await message.channel.send(reply)\n return\n\n\ndef main():\n\n with open('token.txt') as file:\n token = file.readline()\n\n client = MyClient()\n client.run(token)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ro-bot.py","file_name":"ro-bot.py","file_ext":"py","file_size_in_byte":4783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"109549484","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\n\nfrom alipay.aop.api.constant.ParamConstants import *\n\n\nclass AlipayEcoMycarParkingOvertimecharginginfoSyncModel(object):\n\n def __init__(self):\n self._car_number = None\n self._isv_url = None\n self._parking_id = None\n self._serial_no = None\n\n @property\n def car_number(self):\n return self._car_number\n\n @car_number.setter\n def car_number(self, value):\n self._car_number = value\n @property\n def isv_url(self):\n return self._isv_url\n\n @isv_url.setter\n def isv_url(self, value):\n self._isv_url = value\n @property\n def parking_id(self):\n return self._parking_id\n\n @parking_id.setter\n def parking_id(self, value):\n self._parking_id = value\n @property\n def serial_no(self):\n return self._serial_no\n\n @serial_no.setter\n def serial_no(self, value):\n self._serial_no = value\n\n\n def to_alipay_dict(self):\n params = dict()\n if self.car_number:\n if hasattr(self.car_number, 'to_alipay_dict'):\n params['car_number'] = self.car_number.to_alipay_dict()\n else:\n params['car_number'] = self.car_number\n if self.isv_url:\n if hasattr(self.isv_url, 'to_alipay_dict'):\n params['isv_url'] = self.isv_url.to_alipay_dict()\n else:\n params['isv_url'] = self.isv_url\n if self.parking_id:\n if hasattr(self.parking_id, 'to_alipay_dict'):\n params['parking_id'] = self.parking_id.to_alipay_dict()\n else:\n params['parking_id'] = self.parking_id\n if self.serial_no:\n if hasattr(self.serial_no, 'to_alipay_dict'):\n params['serial_no'] = self.serial_no.to_alipay_dict()\n else:\n params['serial_no'] = self.serial_no\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = AlipayEcoMycarParkingOvertimecharginginfoSyncModel()\n if 'car_number' in d:\n o.car_number = d['car_number']\n if 'isv_url' in d:\n o.isv_url = d['isv_url']\n if 'parking_id' in d:\n o.parking_id = d['parking_id']\n if 'serial_no' in d:\n o.serial_no = d['serial_no']\n return o\n\n\n","sub_path":"alipay/aop/api/domain/AlipayEcoMycarParkingOvertimecharginginfoSyncModel.py","file_name":"AlipayEcoMycarParkingOvertimecharginginfoSyncModel.py","file_ext":"py","file_size_in_byte":2394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"240113557","text":"# -*- coding: utf-8 -*-\nimport re\n\nfrom intelmq.lib import utils\nfrom intelmq.lib.bot import ParserBot\n\nclass NmapPortsParserBot(ParserBot):\n\n def parse_line(self, val, report):\n try:\n l = val.split(\"Ports:\")\n if len(l) > 1:\n host = l[0].split()[1]\n ports = l[1].split(', ')\n for p in ports:\n p_data = p.split('/')\n port = p_data[0].strip()\n state = p_data[1].strip()\n protocol = p_data[2].strip()\n self.logger.info(\"{} {} {} {}\".format(host, protocol, port, state))\n\n event = self.new_event(report)\n\n event.add('extra.ip', host)\n event.add('extra.protocol_transport', protocol)\n event.add('extra.port', port)\n event.add('extra.state', state)\n\n event.add('raw', self.recover_line(val))\n\n yield event\n except Exception as e:\n self.logger.error('Cannot parse line: {}'.format(val))\n raise e\n\nBOT = NmapPortsParserBot","sub_path":"volumes/intelmq-bots/bots/parsers/nmap/nmap_ports.py","file_name":"nmap_ports.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"610939059","text":"# Treasure Map Puller by MatsaMilla\r\n# SHOULD pull gold first and palce in beetle\r\n# keeps recalls, gate & lvl 8 summoning scrolls no matter what\r\n# you will have to re-assign bags every time you close Razor... fault of the program.\r\n\r\ndragTime = 1000\r\nmsgColor = 68\r\nself = Mobiles.FindBySerial(Player.Serial)\r\n\r\n# *** Replace with beetle serial if you have one *** \r\nbeetle = 0x0006EB2A\r\n\r\n# *** False if you don not have beetle *** \r\nbeetleBag = True\r\n\r\n# True if you want to keep scrolls\r\nsortScrolls = False\r\n\r\n#check for reg bag\r\nif Misc.CheckSharedValue('regBag'):\r\n regBag = Misc.ReadSharedValue('regBag')\r\n if Items.FindBySerial(regBag):\r\n Misc.NoOperation()\r\n else:\r\n regBag = Target.PromptTarget('Select Bag for Regs')\r\n Misc.SetSharedValue('regBag', regBag)\r\nelse:\r\n regBag = Target.PromptTarget('Select Bag for Regs')\r\n Misc.SetSharedValue('regBag', regBag)\r\n#check for wep bag\r\nif Misc.CheckSharedValue('wepBag'):\r\n wepBag = Misc.ReadSharedValue('wepBag')\r\n if Items.FindBySerial(wepBag):\r\n Misc.NoOperation()\r\n else:\r\n wepBag = Target.PromptTarget('Select Bag for Weapons')\r\n Misc.SetSharedValue('wepBag', wepBag)\r\nelse:\r\n wepBag = Target.PromptTarget('Select Bag for Weapons')\r\n Misc.SetSharedValue('wepBag', wepBag)\r\n#check for armor bag \r\nif Misc.CheckSharedValue('armorBag'):\r\n armorBag = Misc.ReadSharedValue('armorBag')\r\n if Items.FindBySerial(armorBag):\r\n Misc.NoOperation()\r\n else:\r\n armorBag = Target.PromptTarget('Select Bag for Armor')\r\n Misc.SetSharedValue('armorBag', armorBag)\r\nelse:\r\n armorBag = Target.PromptTarget('Select Bag for Armor')\r\n Misc.SetSharedValue('armorBag', armorBag)\r\n#check for gem bag \r\nif Misc.CheckSharedValue('gemBag'):\r\n gemBag = Misc.ReadSharedValue('gemBag')\r\n if Items.FindBySerial(gemBag):\r\n Misc.NoOperation()\r\n else:\r\n gemBag = Target.PromptTarget('Select Bag for Gems')\r\n Misc.SetSharedValue('gemBag', gemBag)\r\nelse:\r\n gemBag = Target.PromptTarget('Select Bag for Gems')\r\n Misc.SetSharedValue('gemBag', gemBag)\r\n#check for scroll bag\r\nif sortScrolls:\r\n if Misc.CheckSharedValue('scrollBag'):\r\n scrollBag = Misc.ReadSharedValue('scrollBag')\r\n if Items.FindBySerial(scrollBag):\r\n Misc.NoOperation()\r\n else:\r\n scrollBag = Target.PromptTarget('Select Bag for Scrolls')\r\n Misc.SetSharedValue('scrollBag', scrollBag)\r\n else:\r\n scrollBag = Target.PromptTarget('Select Bag for Scrolls')\r\n Misc.SetSharedValue('scrollBag', scrollBag)\r\n#check for corpse bag \r\nif Misc.CheckSharedValue('trashCan'):\r\n trashCan = Misc.ReadSharedValue('trashCan')\r\n if Items.FindBySerial(trashCan):\r\n Misc.NoOperation()\r\n else:\r\n trashCan = Target.PromptTarget('Select Corpse to dump on')\r\n Misc.SetSharedValue('trashCan', trashCan)\r\nelse:\r\n trashCan = Target.PromptTarget('Select Corpse to dump on')\r\n Misc.SetSharedValue('trashCan', trashCan)\r\n#trashCan = Target.PromptTarget('Select Corpse to dump on')\r\nchest = Target.PromptTarget('Select Treasure Chest')\r\n\r\n\r\n\r\n#loot includes gate, recall & lvl 8 summoning scrolls\r\nloot = [0x2260,0x1f4c,0x1f60,0x1f66,0x1f68,0x1f69,0x1f6a,0x1f6b,0x1f6c]\r\n\r\ngold = [0xeed]\r\ngems = [0xf16,0xf15,0xf19,0xf25,0xf21,0xf10,0xf26,0xf2d,0xf13]\r\nwands = [0xdf5,0xdf3,0xdf4,0xdf2]\r\nboneArmor = [0x1450,0x1f0b,0x1452,0x144f,0x1451,0x144e]\r\nregs= [0xf7a,0xf7b,0xf86,0xf84,0xf85,0xf88,0xf8d,0xf8c]\r\n\r\nweps = [0xf62,0x1403,0xe87,0x1405,0x1401,0xf52,0x13b0,0xdf0,0x1439,0x1407,0xe89,0x143d,0x13b4,0xe81,0x13f8,\r\n0xf5c,0x143b,0x13b9,0xf61,0x1441,0x13b6,0xec4,0x13f6,0xf5e,0x13ff,0xec3,0xf43,0xf45,0xf4d,0xf4b,0x143e,\r\n0x13fb,0x1443,0xf47,0xf49,0xe85,0xe86,0x13fd,0xf50,0x13b2,]\r\n\r\narmor = [0x1b72,0x1b73,0x1b7b,0x1b74,0x1b79,0x1b7a,0x1b76,0x1408,0x1410,0x1411,0x1412,0x1413,0x1414,0x1415,\r\n0x140a,0x140c,0x140e,0x13bb,0x13be,0x13bf,0x13ee,0x13eb,0x13ec,0x13f0,0x13da,0x13db,0x13d5,0x13d6,0x13dc,\r\n0x13c6,0x13cd,0x13cc,0x13cb,0x13c7,0x1db9,0x1c04,0x1c0c,0x1c02,0x1c00,0x1c08,0x1c06,0x1c0a,]\r\n\r\nscrolls = [0x1f2d,0x1f2e,0x1f2f,0x1f30,0x1f31,0x1f32,0x1f33,0x1f34,0x1f35,0x1f36,0x1f37,0x1f38,0x1f39,\r\n0x1f3a,0x1f3b,0x1f3c,0x1f3d,0x1f3e,0x1f3f,0x1f40,0x1f41,0x1f42,0x1f43,0x1f44,0x1f45,0x1f46,0x1f47,0x1f48,\r\n0x1f49,0x1f4a,0x1f4b,0x1f4d,0x1f4e,0x1f4f,0x1f50,0x1f51,0x1f52,0x1f53,0x1f54,0x1f55,0x1f56,0x1f57,0x1f58,\r\n0x1f59,0x1f5a,0x1f5b,0x1f5c,0x1f5d,0x1f5e,0x1f5f,0x1f60,0x1f61,0x1f62,0x1f63,0x1f64,0x1f65,0x1f66,0x1f67,\r\n0x1f68,0x1f69,0x1f6a,0x1f6b,0x1f6c]\r\n\r\ntrash = [0x171c,0x1717,0x1718,0x1544,0x1540,0x1713,0x1715,0x1714,0x1716,0x1717,0x1718,0x1719,0x171a,0x171b,\r\n0x171c,0x2306,0x13f6,0xec4,0x1716,0x171c,0xe81,0xe86,]\r\n\r\nmapChest = Items.FindBySerial(chest)\r\nItems.UseItem(mapChest)\r\nMisc.Pause(dragTime)\r\n#Items.WaitForContents(mapChest, 50)\r\nMisc.Pause(dragTime)\r\n\r\ndef checkDistance():\r\n #Timer.Create('Distance', 5000)\r\n while mapChest.DistanceTo(self) > 2:\r\n Misc.NoOperation()\r\n if not Timer.Check('Distance'):\r\n Player.HeadMessage(msgColor, 'Too Far Away')\r\n Timer.Create('Distance', 2500)\r\n\r\n\r\ndef checkWeight():\r\n if Player.Weight >= Player.MaxWeight:\r\n Player.ChatSay(msgColor, 'I am Overweight, stopping')\r\n Stop \r\n \r\n#moves gold to beetle\r\nif beetleBag:\r\n for s in mapChest.Contains:\r\n checkDistance()\r\n if s.ItemID in gold:\r\n if Player.Mount:\r\n Mobiles.UseMobile(Player.Serial)\r\n Misc.Pause(dragTime)\r\n Items.Move(s, beetle, 0)\r\n Misc.Pause(dragTime)\r\n if not Player.Mount:\r\n Mobiles.UseMobile(beetle)\r\n Misc.Pause(dragTime)\r\n\r\nfor e in mapChest.Contains :\r\n checkDistance()\r\n checkWeight()\r\n if e.ItemID in gold:\r\n Items.Move(e, Player.Backpack.Serial, 0)\r\n Misc.Pause(dragTime)\r\n elif e.ItemID in gems:\r\n Items.Move(e, gemBag, 0)\r\n Misc.Pause(dragTime)\r\n \r\nfor i in mapChest.Contains :\r\n checkDistance()\r\n checkWeight()\r\n if i.ItemID in loot:\r\n Items.Move(i, Player.Backpack.Serial, 0)\r\n Misc.Pause(dragTime)\r\n elif i.ItemID in boneArmor:\r\n Items.Move(i, armorBag, 0)\r\n Misc.Pause(dragTime)\r\n elif i.ItemID in regs:\r\n Items.Move(i, regBag, 0)\r\n Misc.Pause(dragTime)\r\n elif i.ItemID in weps:\r\n Items.Move(i, wepBag, 0)\r\n Misc.Pause(dragTime)\r\n elif i.ItemID in armor:\r\n Items.Move(i, armorBag, 0)\r\n Misc.Pause(dragTime)\r\n elif i.ItemID in wands:\r\n Items.Move(i, Player.Backpack.Serial, 0)\r\n Misc.Pause(dragTime)\r\n elif sortScrolls:\r\n if i.ItemID in scrolls:\r\n Items.Move(i, scrollBag, 0)\r\n Misc.Pause(dragTime)\r\n# elif i.ItemID in trash:\r\n# Items.Move(i, trashCan, 0)\r\n# Misc.Pause(dragTime)\r\n\r\nfor t in mapChest.Contains :\r\n checkDistance()\r\n checkWeight()\r\n if t.ItemID in scrolls:\r\n Items.Move(t, trashCan, 0)\r\n Misc.Pause(dragTime)\r\n elif t.ItemID in trash:\r\n Items.Move(t, trashCan, 0)\r\n Misc.Pause(dragTime)\r\n \r\nPlayer.HeadMessage(msgColor, 'All Done') \r\n","sub_path":"Treasure_Hunting/looting_treasure_chests.py","file_name":"looting_treasure_chests.py","file_ext":"py","file_size_in_byte":7263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"462898532","text":"import unittest\nfrom datetime import date\n\nfrom tastyworks.models.option import Option, OptionType, OptionUnderlyingType\n\n\nclass TestOptionModel(unittest.TestCase):\n def setUp(self):\n self.test_option = Option(\n ticker='AKS',\n quantity=1,\n expiry=date(2018, 8, 10),\n strike=3.5,\n option_type=OptionType.CALL,\n underlying_type=OptionUnderlyingType.EQUITY\n )\n\n def test_occ2010_integer_strike(self):\n self.test_option.strike = 3\n expected_result = 'AKS 180810C00003000'\n\n res = self.test_option.get_occ2010_symbol()\n self.assertEqual(expected_result, res)\n\n def test_occ2010_fraction_strike(self):\n self.test_option.strike = 3.45\n expected_result = 'AKS 180810C00003450'\n\n res = self.test_option.get_occ2010_symbol()\n self.assertEqual(expected_result, res)\n\n self.test_option.strike = 3.5\n expected_result = 'AKS 180810C00003500'\n\n res = self.test_option.get_occ2010_symbol()\n self.assertEqual(expected_result, res)\n\n def test_occ2010_ticker_padding(self):\n self.test_option.ticker = 'BOB123'\n expected_result = 'BOB123180810C00003500'\n\n res = self.test_option.get_occ2010_symbol()\n self.assertEqual(expected_result, res)\n\n self.test_option.ticker = 'BOB'\n expected_result = 'BOB 180810C00003500'\n\n res = self.test_option.get_occ2010_symbol()\n self.assertEqual(expected_result, res)\n\n def test_occ2010_ticker_trimming(self):\n self.test_option.ticker = 'BOB123456'\n expected_result = 'BOB123180810C00003500'\n\n res = self.test_option.get_occ2010_symbol()\n self.assertEqual(expected_result, res)\n","sub_path":"tests/models/test_option.py","file_name":"test_option.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"175003370","text":"#!/usr/bin/env python\n\n\"\"\"Setup file for cassobjects\"\"\"\n\nfrom setuptools import setup, find_packages\n\nversion_tuple = (0, 0, 1)\n__version__ = '.'.join(map(str, version_tuple))\n\nsetup(\n name='cassobjects',\n version=__version__,\n description=open('README.rst', 'r').read(),\n author='Thomas Meson',\n author_email='zllak@hycik.org',\n maintainer='Thomas Meson',\n maintainer_email='zllak@hycik.org',\n url='https://github.com/zllak/cassobjects',\n packages=find_packages('src'),\n package_dir={'': 'src'},\n requires=[\n \"pycassa >= 1.2\",\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"410096622","text":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom keras.layers import Dense\nfrom keras.models import Sequential\nfrom dataset import get_data\nimport matplotlib.pyplot as plt\n\n\ndef plot_convergence(history):\n all_data_metrics = list(history.history.keys())\n metrics = [item for item in all_data_metrics \n if not item.startswith('val')]\n data = {}\n for metric in metrics:\n data[metric] = [item for item in all_data_metrics\n if item.endswith(metric)]\n fig, ax = plt.subplots(len(metrics))\n fig.suptitle('Convergence')\n for i, metric in enumerate(metrics):\n for datapart in data[metric]:\n ax[i].plot(history.history[datapart])\n ax[i].set(xlabel='epoch', ylabel=metric)\n legend = []\n for item in data[metric]:\n aux = item.split('_')\n if len(aux) > 1:\n legend.append(aux[0])\n else:\n legend.append('train') \n plt.legend(legend)\n plt.show()\n\n# Get data\ndf_yelp = get_data(['yelp', 'amazon', 'imdb'])\nsentences = df_yelp['sentence'].values\ny = df_yelp['label'].values\n\n# Train-test split\n(sentences_train,\n sentences_test,\n y_train,\n y_test) = train_test_split(sentences,\n y,\n test_size=0.25,\n random_state=1000)\n\n# Data preparation (tokenizator)\nvectorizer = CountVectorizer()\nvectorizer.fit(sentences_train)\nX_train = vectorizer.transform(sentences_train)\nX_test = vectorizer.transform(sentences_test)\n\n# Define model\ninput_dim = X_train.shape[1]\nmodel = Sequential()\nmodel.add(Dense(10, input_dim = input_dim, activation='relu'))\nmodel.add(Dense(1, input_dim = 10, activation='sigmoid'))\nmodel.compile(loss='binary_crossentropy', \n optimizer='adam', \n metrics=['accuracy'])\nmodel.summary()\n\nhistory = model.fit(X_train,\n y_train,\n epochs=100,\n verbose=True,\n validation_data=(X_test, y_test),\n batch_size=10)\n\nloss, accuracy = model.evaluate(X_test, y_test, verbose=False)\nprint('-'*79)\nprint(\"Accuracy\", accuracy)\nplot_convergence(history)\n","sub_path":"cnn/fully_connected.py","file_name":"fully_connected.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"499360043","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime, timedelta\n\nfrom django.contrib.auth import authenticate\nfrom django.forms import *\nfrom django.db.models import Q\n\nfrom models import *\nfrom .utils import email\n\n\nclass CommonForm(Form):\n def errors_list(self):\n return [u\"%s: %s\" % (self.fields[_].label, message) for _, l in self.errors.items() for message in l]\n\n def str_errors(self, divider=u\" \"):\n return divider.join(self.errors_list())\n\n\nclass RegistrationForm(CommonForm):\n login = CharField(label=u'Ник', max_length=100)\n passwd = CharField(label=u'Пароль', max_length=100, widget=PasswordInput)\n email = EmailField(label=u'Email', max_length=100)\n name = CharField(label=u'ФИО', max_length=100)\n age = IntegerField(label=u'Возраст')\n city = CharField(label=u'Город', max_length=100)\n icq = IntegerField(label=u'ICQ', required=False)\n tel = CharField(label=u'Телефон', max_length=100, required=False)\n med = CharField(label=u'Мед. особенности', max_length=100, widget=Textarea, required=False)\n portrait = ImageField(label=u'Фото')\n\n def clean_login(self):\n try:\n User.objects.get(username=self.cleaned_data['login'])\n raise ValidationError(u\"Этот ник занят. Может, вы уже зарегистрированы на сайте?\")\n except User.DoesNotExist:\n return self.cleaned_data['login']\n\n def save(self):\n new_user = User.objects.create_user(self.cleaned_data['login'],\n self.cleaned_data['email'],\n self.cleaned_data['passwd'])\n new_user.is_active = True\n new_user.save()\n\n profile = Profile.objects.create(\n user=new_user,\n name=self.cleaned_data['name'],\n age=self.cleaned_data['age'],\n city=self.cleaned_data['city'],\n icq=self.cleaned_data['icq'],\n tel=self.cleaned_data['tel'],\n med=self.cleaned_data['med'],\n portrait=self.cleaned_data['portrait'],\n )\n\n return authenticate(username=new_user.username, password=self.cleaned_data['passwd'])\n\n\nclass ChooseRoleForm(CommonForm):\n role = IntegerField(label=u'Роль', widget=Select)\n\n def __init__(self, *args, **kwargs):\n super(ChooseRoleForm, self).__init__(*args, **kwargs)\n self.fields['role'].widget.choices = [(0, u'-- выберите персонажа --')] + [(role.pk, role.name) for role in Role.objects.filter(profile__isnull=True).order_by('name')]\n\n def clean_role(self):\n try:\n return Role.objects.get(pk=self.cleaned_data['role'], profile__isnull=True)\n except Role.DoesNotExist:\n raise ValidationError(u\"Эта роль занята, попробуйте выбрать другую\")\n\n\nclass TraditionTextForm(CommonForm):\n title = CharField(label=u'Название', max_length=100)\n content = CharField(label=u\"Содержание\", widget=Textarea)\n\n\nclass CreateDuelForm(ModelForm):\n class Meta:\n model = Duel\n fields = ('role_2', 'number_1')\n\n @classmethod\n def check_number(cls, number, number_len=None):\n try:\n int(number)\n if number_len:\n if len(number) != number_len:\n raise ValidationError(u\"Загаданное число должно содержать %s цифр\" % number_len)\n else:\n if len(number) > 10:\n raise ValidationError(u\"Загаданное число должно содержать не более 10 цифры\")\n\n if len(set(number)) != len(number):\n raise ValidationError(u\"Все цифры числа должны быть разными\")\n\n return number\n\n except ValueError:\n raise ValidationError(u\"Введите четырехзначное число\")\n\n def clean_number_1(self):\n return self.check_number(self.cleaned_data['number_1'])\n\n def save(self, role, *args, **kwargs):\n duel = Duel.objects.create(\n role_1=role,\n role_2=self.cleaned_data['role_2'],\n number_1=self.cleaned_data['number_1'],\n dt=datetime.now()\n )\n\n email(\n u\"Анклав: Дуэль\",\n u\"%s, вы вызваны на дуэль. http://anklav-ekb.ru%s\" % (self.cleaned_data['role_2'].name, reverse('duel', args=[duel.pk])),\n [self.cleaned_data['role_2'].profile.user.email]\n )\n\n return duel\n\n\nclass DealForm(CommonForm):\n company = IntegerField(label=u'Фирма', widget=Select)\n amount = IntegerField(label=u'Количество акций')\n cost = IntegerField(label=u'Цена сделки')\n\n def get_actions(self, role):\n return RoleStock.objects.filter(role=role, amount__gt=0)\n\n def __init__(self, role, *args, **kwargs):\n super(DealForm, self).__init__(*args, **kwargs)\n\n self.role = role\n self.fields['company'].widget.choices = [(0, u'-- выберите компанию --')] + [(action.company.pk, action.company.name) for action in self.get_actions(role)]\n\n def clean_company(self):\n try:\n return Tradition.objects.get(pk=self.cleaned_data['company'], type='corporation')\n except Tradition.DoesNotExist:\n raise ValidationError(u\"Фирма не найдена\")\n\n def clean_amount(self):\n if self.cleaned_data.get('amount') <= 0:\n raise ValidationError(u\"Хакерам здесь не место\")\n else:\n return self.cleaned_data.get('amount')\n\n def clean(self):\n if self.errors:\n return self.cleaned_data\n\n try:\n actions = RoleStock.objects.get(role=self.role, company=self.cleaned_data['company'])\n if actions.amount < self.cleaned_data.get('amount', 1000):\n raise ValidationError(u\"У вас недостаточно акций этой фирмы, уменьшите заявку до %s акций.\" % actions.amount)\n\n return self.cleaned_data\n\n except RoleStock.DoesNotExist:\n raise ValidationError(u\"У вас нет акций этой фирмы\")\n\n def save(self):\n deal = Deal.objects.create(\n role=self.role,\n amount=self.cleaned_data['amount'],\n company=self.cleaned_data['company'],\n cost=self.cleaned_data['cost'],\n )\n\n return deal\n\n\nclass TransferForm(CommonForm):\n recipient = CharField(label=u'Получатель', widget=Select)\n amount = IntegerField(label=u'Сумма')\n\n def __init__(self, role, *args, **kwargs):\n super(TransferForm, self).__init__(*args, **kwargs)\n\n self.sender = role\n self.fields['recipient'].widget.choices =\\\n [(0, u'-- выберите получателя --')] + \\\n [(r.name, r.name) for r in Role.objects.filter(profile__isnull=False, in_game=True).exclude(pk=role.id).order_by('name')] + \\\n [(r.dd_number, r.dd_number) for r in Role.objects.filter(dd_number__isnull=False, in_game=True).exclude(pk=role.id).order_by('dd_number')]\n\n\n def _get_role(self, recipient):\n try:\n if self.cleaned_data['recipient'].isdigit():\n return Role.objects.get(dd_number=self.cleaned_data['recipient'])\n else:\n return Role.objects.get(name=self.cleaned_data['recipient'])\n except Role.DoesNotExist:\n pass\n\n return None\n\n def clean_recipient(self):\n recipient = self._get_role(self.cleaned_data['recipient'])\n if not recipient:\n raise ValidationError(u\"Получатель не найден\")\n\n if recipient == self.sender:\n raise ValidationError(u\"Нельзя отправлять перевод самому себе\")\n\n return recipient\n\n def clean_amount(self):\n if self.cleaned_data.get('amount') <= 0:\n raise ValidationError(u\"Хакерам здесь не место\")\n\n if self.sender.money >= int(self.cleaned_data['amount']):\n return int(self.cleaned_data['amount'])\n else:\n raise ValidationError(u\"У вас недостаточно средств\")\n\n def save(self):\n self.sender.money -= self.cleaned_data['amount']\n self.sender.save()\n\n self.cleaned_data['recipient'].money += self.cleaned_data['amount']\n self.cleaned_data['recipient'].save()\n\n\nclass TransferActionsForm(CommonForm):\n recipient = CharField(label=u'Получатель', widget=Select)\n company = IntegerField(label=u'Компания', widget=Select)\n amount = IntegerField(label=u'Количество')\n\n def __init__(self, role, *args, **kwargs):\n super(TransferActionsForm, self).__init__(*args, **kwargs)\n\n self.sender = role\n self.fields['recipient'].widget.choices = \\\n [(0, u'-- выберите получателя --')] + \\\n [(r.name, r.name) for r in Role.objects.filter(profile__isnull=False, in_game=True).exclude(pk=role.id).order_by('name')] +\\\n [(r.dd_number, r.dd_number) for r in Role.objects.filter(dd_number__isnull=False, in_game=True).exclude(pk=role.id).order_by('dd_number')]\n\n self.fields['company'].widget.choices = [(0, u'-- выберите компанию --')] + [(stocks.company.id, stocks.company.name)\n for stocks in RoleStock.objects.filter(role=self.sender, amount__gt=0)]\n\n\n def _get_role(self, recipient):\n try:\n if self.cleaned_data['recipient'].isdigit():\n role = Role.objects.get(dd_number=self.cleaned_data['recipient'])\n role.by_dd = True\n else:\n role = Role.objects.get(name=self.cleaned_data['recipient'])\n role.by_dd = False\n\n return role\n\n except Role.DoesNotExist:\n pass\n\n return None\n\n def clean_recipient(self):\n recipient = self._get_role(self.cleaned_data['recipient'])\n if not recipient:\n raise ValidationError(u\"Получатель не найден\")\n\n if recipient == self.sender:\n raise ValidationError(u\"Нельзя отправлять перевод самому себе\")\n\n return recipient\n\n def clean_company(self):\n try:\n return Tradition.objects.get(type='corporation', pk=self.cleaned_data['company'])\n except Tradition.DoesNotExist:\n raise ValidationError(u\"Получатель не найден\")\n\n def clean_amount(self):\n if self.cleaned_data.get('amount') <= 0:\n raise ValidationError(u\"Хакерам здесь не место\")\n else:\n return self.cleaned_data.get('amount')\n\n def clean(self):\n if self.errors:\n return self.cleaned_data\n\n try:\n actions = RoleStock.objects.get(role=self.sender, company=self.cleaned_data['company'])\n\n except RoleStock.DoesNotExist:\n raise ValidationError(u\"У вас нет акций этой компании\")\n\n if actions.amount < self.cleaned_data['amount']:\n raise ValidationError(u\"У вас недостаточно акций этой компании, уменьшите количество для передачи.\")\n\n return self.cleaned_data\n\n def save(self):\n sender_actions = RoleStock.objects.get(role=self.sender, company=self.cleaned_data['company'])\n sender_actions.amount -= self.cleaned_data['amount']\n sender_actions.save()\n\n recipient_actions, _ = RoleStock.objects.get_or_create(\n role=self.cleaned_data['recipient'],\n company=self.cleaned_data['company'],\n defaults={\n 'amount': 0,\n }\n )\n\n recipient_actions.amount += self.cleaned_data['amount']\n recipient_actions.save()\n\n Deal.objects.create(\n role=self.sender,\n company=self.cleaned_data['company'],\n amount=self.cleaned_data['amount'],\n cost=0,\n buyer=self.cleaned_data['recipient'],\n is_closed=True,\n dt_closed=datetime.now(),\n is_hidden=self.cleaned_data['recipient'].by_dd\n )\n\n if self.cleaned_data['recipient'].by_dd:\n sender = self.sender.dd_number\n recipient = self.cleaned_data['recipient'].dd_number\n else:\n sender = self.sender\n recipient = self.cleaned_data['recipient']\n\n email(\n u\"Анклав: передача акций\",\n u\"На ваш счет поступили акции корпорации %s в количестве %s шт от клиента %s.\" % \\\n (self.cleaned_data['company'].name, self.cleaned_data['amount'], sender),\n [self.cleaned_data['recipient'].profile.user.email]\n )\n\n email(\n u\"Анклав: передача акций\",\n u\"Вы передали акции корпорации %s в количестве %s шт клиенту %s.\" % \\\n (self.cleaned_data['company'].name, self.cleaned_data['amount'], recipient),\n [self.sender.profile.user.email]\n )\n\n\nclass DefenderTransferForm(Form):\n client = IntegerField(label=u'Подзащитный', widget=Select)\n new_defender = IntegerField(label=u'Новый защитник', widget=Select)\n\n def __init__(self, defender, *args, **kwargs):\n super(DefenderTransferForm, self).__init__(*args, **kwargs)\n\n self.defender = defender\n self.fields['client'].widget.choices = \\\n [(0, u'-- выберите клиента --')] + \\\n [(role.pk, role.name) for role in Role.objects.filter(in_game=True, defender=self.defender)]\n self.fields['new_defender'].widget.choices = \\\n [(0, u'-- выберите нового защитника --')] + \\\n [(role.pk, role.name) for role in Role.objects.filter(in_game=True) if role.is_programmer()]\n\n def clean_client(self):\n try:\n return Role.objects.get(pk=self.cleaned_data['client'], in_game=True, defender=self.defender)\n except Role.DoesNotExist:\n raise ValidationError(u\"Клиент не найден\")\n\n def clean_new_defender(self):\n try:\n return Role.objects.get(pk=self.cleaned_data['new_defender'], in_game=True)\n except Role.DoesNotExist:\n raise ValidationError(u\"Машинист не найден\")\n\n def save(self):\n self.cleaned_data['client'].defender = self.cleaned_data['new_defender']\n self.cleaned_data['client'].save()\n\n email(\n u\"Анклав: смена защитника\",\n u\"%s, у вас новый защитник - %s\" % (self.cleaned_data['client'], self.cleaned_data['new_defender']),\n [self.cleaned_data['client'].profile.user.email]\n )\n\n email(\n u\"Анклав: смена защитника\",\n u\"%s, у вас новый клиент на защиту - %s\" % (self.cleaned_data['new_defender'], self.cleaned_data['client']),\n [self.cleaned_data['new_defender'].profile.user.email]\n )\n\n email(\n u\"Анклав: смена защитника\",\n u\"%s, вы передали клиента %s машинисту %s\" % (self.defender, self.cleaned_data['client'], self.cleaned_data['new_defender']),\n [self.defender.profile.user.email]\n )\n\n\nclass PersonHackTarget(CommonForm):\n role = IntegerField(label=u'Кого ломаем', widget=Select)\n field = CharField(label=u'Что ломаем', widget=Select)\n number = CharField(label=u'Ваше число', help_text=u\"4 цифры\")\n\n def __init__(self, role, *args, **kwargs):\n super(PersonHackTarget, self).__init__(*args, **kwargs)\n\n self.hacker = role\n self.fields['role'].widget.choices = [(0, u'-- выберите цель атаки --')] + \\\n [(role.pk, role.name) for role in Role.objects.filter(profile__isnull=False, in_game=True).exclude(pk=role.id).exclude(access_level='offline')]\n self.fields['field'].widget.choices = [field[:2] for field in settings.ROLE_FIELDS]\n\n def clean_role(self):\n try:\n return Role.objects.get(pk=self.cleaned_data['role'], in_game=True, access_level__in=('online', 'restricted'))\n except Role.DoesNotExist:\n raise ValidationError(u\"Жертва не найдена\")\n\n def clean_number(self):\n number = self.cleaned_data['number']\n number_len = 4\n try:\n int(number)\n if len(number) != number_len:\n raise ValidationError(u\"Загаданное число должно содержать %s цифр\" % number_len)\n\n if len(set(number)) != len(number):\n raise ValidationError(u\"Все цифры числа должны быть разными\")\n\n return number\n\n except ValueError:\n raise ValidationError(u\"Введите четырехзначное число\")\n\n def clean(self):\n self.cleaned_data['key'] = 'person/%s/%s' % (self.cleaned_data['role'].id, self.cleaned_data['field'])\n\n yesterday = datetime.now() - timedelta(days=1)\n if Hack.objects.filter(hacker=self.hacker, key=self.cleaned_data['key'], dt__gt=yesterday).exclude(result='late').exists():\n raise ValidationError(u\"Вы недавно уже ломали эту информацию. Передохните.\")\n\n return self.cleaned_data\n\n def save(self):\n # создаем новый взлом\n from .hack import generate_number\n\n if self.cleaned_data['role'].defender:\n hack = TraditionHack.objects.create(\n hacker=self.hacker,\n key=self.cleaned_data['key'],\n hacker_number=self.cleaned_data['number'],\n security_number=generate_number(self.cleaned_data['key']),\n )\n\n else:\n hack = Hack.objects.create(\n hacker=self.hacker,\n key=self.cleaned_data['key'],\n number=generate_number(self.cleaned_data['key']),\n )\n\n return hack\n\n\nclass TraditionHackTarget(CommonForm):\n tradition = IntegerField(label=u'Кого ломаем', widget=Select)\n field = CharField(label=u'Что ломаем', widget=Select)\n file = CharField(label=u'Имя файла', help_text=u\"для взлома одного документа\", required=False)\n number = CharField(label=u'Ваше число', help_text=u\"4 цифры\")\n\n def __init__(self, role, *args, **kwargs):\n super(TraditionHackTarget, self).__init__(*args, **kwargs)\n\n self.hacker = role\n self.fields['tradition'].widget.choices = [(0, u'-- выберите цель атаки --')] + [(tradition.pk, tradition.name) for tradition in Tradition.objects.exclude(type='profession')]\n self.fields['field'].widget.choices = [field[:2] for field in settings.TRADITION_FIELDS]\n\n def clean_tradition(self):\n try:\n return Tradition.objects.get(pk=self.cleaned_data['tradition'])\n except Tradition.DoesNotExist:\n raise ValidationError(u\"Жертва не найдена\")\n\n def clean_number(self):\n number = self.cleaned_data['number']\n number_len = 4\n try:\n int(number)\n if len(number) != number_len:\n raise ValidationError(u\"Загаданное число должно содержать %s цифр\" % number_len)\n\n if len(set(number)) != len(number):\n raise ValidationError(u\"Все цифры числа должны быть разными\")\n\n return number\n\n except ValueError:\n raise ValidationError(u\"Введите четырехзначное число\")\n\n def clean(self):\n if self.cleaned_data['tradition'].type == 'tradition' and self.cleaned_data['field'] == 'corporation_questbook':\n raise ValidationError(u\"Выберите взлом гостевой книги Традиции\")\n\n if self.cleaned_data['tradition'].type in ('corporation', 'crime') and self.cleaned_data['field'] == 'tradition_questbook':\n raise ValidationError(u\"Выберите взлом гостевой книги корпорации\")\n\n if self.cleaned_data['field'] == 'document' and not self.cleaned_data['file']:\n raise ValidationError(u\"Введите название документа\")\n\n self.cleaned_data['key'] = u'tradition/%s/%s/%s' % \\\n (self.cleaned_data['tradition'].id, self.cleaned_data['field'], self.cleaned_data['file'] or '')\n\n yesterday = datetime.now() - timedelta(days=1)\n if TraditionHack.objects.filter(hacker=self.hacker, key=self.cleaned_data['key'], dt__gt=yesterday).exclude(state='late').exists():\n raise ValidationError(u\"Вы недавно уже ломали эту информацию. Передохните.\")\n\n return self.cleaned_data\n\n def save(self):\n # создаем новый взлом\n from .hack import generate_number\n hack = TraditionHack.objects.create(\n hacker=self.hacker,\n key=self.cleaned_data['key'],\n hacker_number=self.cleaned_data['number'],\n security_number=generate_number(self.cleaned_data['key']),\n )\n\n return hack\n\n\nclass StaticDefenceForm(CommonForm):\n field = CharField(label=u'Что защищать', widget=Select)\n question = CharField(label=u'Вопрос', widget=forms.Textarea())\n answer = CharField(label=u'Ответ')\n float = CharField(label=u'Поплавок')\n\n def __init__(self, role, *args, **kwargs):\n self.role = role\n super(StaticDefenceForm, self).__init__(*args, **kwargs)\n\n self.fields['field'].widget.choices = [('0', u'-- выберите защищаемую информацию --')] + [field[:2] for field in settings.ROLE_FIELDS]\n\n def clean_field(self):\n if self.cleaned_data['field'] == '0':\n raise ValidationError(u\"Выберите защищаемую информацию\")\n\n return self.cleaned_data['field']\n\n def clean_float(self):\n try:\n return Float.objects.get(number=self.cleaned_data['float'].strip(), is_used=False)\n\n except Float.DoesNotExist:\n raise ValidationError(u\"Неизвестный номер поплавка\")\n\n def save(self):\n key = 'person/%s/%s' % (self.role.id, self.cleaned_data['field'])\n defences = list(StaticDefence.objects.filter(key=key).order_by('-level'))\n if defences:\n level = defences[0].level + 1\n else:\n level = 1\n\n sd = StaticDefence.objects.create(\n key=key,\n level=level,\n floats_spend=1,\n question=self.cleaned_data['question'],\n answer=self.cleaned_data['answer'],\n )\n\n self.cleaned_data['float'].is_used = True\n self.cleaned_data['float'].comment = (self.cleaned_data['float'].comment or u\"\") + u\"Потрачено на защиту %s\" % sd.id\n self.cleaned_data['float'].static_defence = sd\n self.cleaned_data['float'].save()\n\n\nclass StaticDefenceTraditionForm(CommonForm):\n field = CharField(label=u'Что защищать', widget=Select)\n file = CharField(label=u'Имя файла', help_text=u\"для взлома одного документа\", required=False)\n question = CharField(label=u'Вопрос')\n answer = CharField(label=u'Ответ')\n float = CharField(label=u'Поплавок')\n\n def __init__(self, role, tradition, *args, **kwargs):\n self.tradition = tradition\n self.role = role\n super(StaticDefenceTraditionForm, self).__init__(*args, **kwargs)\n\n self.fields['field'].widget.choices = [(0, u'-- выберите защищаемую информацию --')] + [field[:2] for field in settings.TRADITION_FIELDS]\n\n def clean_float(self):\n try:\n return Float.objects.get(number=self.cleaned_data['float'].strip(), is_used=False)\n\n except Float.DoesNotExist:\n raise ValidationError(u\"Неизвестный номер поплавка\")\n\n def save(self):\n key = 'tradition/%s/%s/%s' % (self.tradition.id, self.cleaned_data['field'], self.cleaned_data['file'] or u\"\")\n defences = list(StaticDefence.objects.filter(key=key).order_by('-level'))\n if defences:\n level = defences[0].level + 1\n else:\n level = 1\n\n sd = StaticDefence.objects.create(\n key=key,\n level=level,\n floats_spend=1,\n question=self.cleaned_data['question'],\n answer=self.cleaned_data['answer'],\n )\n\n self.cleaned_data['float'].is_used = True\n self.cleaned_data['float'].comment = (self.cleaned_data['float'].comment or u\"\") + u\"Потрачено на защиту %s\" % sd.id\n self.cleaned_data['float'].save()\n\n\nclass StaticDefenceHackForm(CommonForm):\n answer = CharField(label=u'Ответ', required=False)\n float = CharField(label=u'Поплавок', required=False)\n\n def __init__(self, role, *args, **kwargs):\n self.role = role\n super(StaticDefenceHackForm, self).__init__(*args, **kwargs)\n\n def clean_float(self):\n if self.cleaned_data['float']:\n try:\n return Float.objects.get(number=self.cleaned_data['float'].strip(), is_used=False)\n\n except Float.DoesNotExist:\n raise ValidationError(u\"Неизвестный номер поплавка\")\n\n def save(self):\n pass\n\n\nfrom django.forms.models import modelform_factory, inlineformset_factory\n\nProfileForm = modelform_factory(Profile, exclude=('user', 'role', 'paid', 'locked_fields'))\nRoleForm = modelform_factory(Role, exclude=('order', 'profile', 'quest', 'dd_number', 'defender', 'online', 'money'))\nQuestForm = modelform_factory(Role, fields=('quest',))\nTraditionForm = modelform_factory(Tradition, fields=('content',))\nTraditionTextModelForm = modelform_factory(TraditionText, fields=('title', 'content',))\nTraditionFileForm = modelform_factory(TraditionFile, fields=('title' ,'file'))\nConnectionFormSet = inlineformset_factory(Role, RoleConnection, fk_name=\"role\", exclude=('is_locked',), extra=1)\n#LayerFormSet = inlineformset_factory(Role, LayerConnection, fk_name=\"role\", exclude=('is_locked',), extra=1)\nDDForm = modelform_factory(DDRequest, fields=('description', 'cost'))\n","sub_path":"src/core/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":27102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"271393609","text":"#!/usr/bin/python3\n\nimport ukcensusapi.Nomisweb as Api\n\napi = Api.Nomisweb(\"./\")\n\nprint(\"Nomisweb census data geographical query example\")\nprint(\"See README.md for details on how to use this package\")\n\n# In the previous example we had a predefined query using Leeds at MSOA resolution,\n# but we want to expand the geographical area and refine the resolution\nTABLE = \"NM_618_1\"\nquery_params = {}\nquery_params[\"CELL\"] = \"7...13\"\nquery_params[\"date\"] = \"latest\"\nquery_params[\"RURAL_URBAN\"] = \"0\"\nquery_params[\"select\"] = \"GEOGRAPHY_CODE,CELL,OBS_VALUE\"\nquery_params[\"geography\"] = \"1245710558...1245710660,1245714998...1245714998,1245715007...1245715007,1245715021...1245715022\"\nquery_params[\"MEASURES\"] = \"20100\"\n\n# Define the new coverage area in terms of local authorities\ncoverage = [\"Leeds\", \"Bradford\"]\n# Define the new resolution\nresolution = Api.Nomisweb.OA\n# Convert the coverage area into nomis codes\ncoverage_codes = api.getLADCodes(coverage)\n# replace the geography value in the query\nquery_params[\"geography\"] = api.geoCodes(coverage_codes, resolution)\n# get the data\nKS401FINE = api.getData(TABLE, query_params)\nhead(KS401FINE, 5)\n\n# Now widen the coverage to England & Wales and coarsen the resolution to LA\nquery_params[\"geography\"] = api.geoCodes([Api.Nomisweb.EnglandWales], Api.Nomisweb.LAD)\n# get the data\nKS401BROAD = api.getData(TABLE, query_params)\n\n\n","sub_path":"examples/geoquery.py","file_name":"geoquery.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"570631416","text":"''' Fvtk module implements simple visualization functions using VTK.\n\nThe main idea is the following:\nA window can have one or more renderers. A renderer can have none, one or more actors. Examples of actors are a sphere, line, point etc.\nYou basically add actors in a renderer and in that way you can visualize the forementioned objects e.g. sphere, line ...\n\nExamples\n---------\n>>> from dipy.viz import fvtk\n>>> r=fvtk.ren()\n>>> a=fvtk.axes()\n>>> fvtk.add(r,a)\n>>> #fvtk.show(r)\n'''\nfrom __future__ import division, print_function, absolute_import\n\nfrom dipy.utils.six.moves import xrange\n\nimport types\n\nimport numpy as np\n\nimport scipy as sp\n\nfrom dipy.core.ndindex import ndindex\n\n# Conditional import machinery for vtk\nfrom ..utils.optpkg import optional_package\n\n# Allow import, but disable doctests if we don't have vtk\nvtk, have_vtk, setup_module = optional_package('vtk')\n\n'''\nFor more color names see\nhttp://www.colourlovers.com/blog/2007/07/24/32-common-color-names-for-easy-reference/\n'''\n# Some common colors\nred = np.array([1, 0, 0])\ngreen = np.array([0, 1, 0])\nblue = np.array([0, 0, 1])\nyellow = np.array([1, 1, 0])\ncyan = np.array([0, 1, 1])\nazure = np.array([0, 0.49, 1])\ngolden = np.array([1, 0.84, 0])\nwhite = np.array([1, 1, 1])\nblack = np.array([0, 0, 0])\n\naquamarine = np.array([0.498, 1., 0.83])\nindigo = np.array([0.29411765, 0., 0.50980392])\nlime = np.array([0.74901961, 1., 0.])\nhot_pink = np.array([0.98823529, 0.05882353, 0.75294118])\n\ngray = np.array([0.5, 0.5, 0.5])\ndark_red = np.array([0.5, 0, 0])\ndark_green = np.array([0, 0.5, 0])\ndark_blue = np.array([0, 0, 0.5])\n\ntan = np.array([0.82352941, 0.70588235, 0.54901961])\nchartreuse = np.array([0.49803922, 1., 0.])\ncoral = np.array([1., 0.49803922, 0.31372549])\n\n\n# a track buffer used only with picking tracks\ntrack_buffer = []\n# indices buffer for the tracks\nind_buffer = []\n# tempory renderer used only with picking tracks\ntmp_ren = None\n\nif have_vtk:\n\n version = vtk.vtkVersion.GetVTKSourceVersion().split(' ')[-1]\n major_version = vtk.vtkVersion.GetVTKMajorVersion()\n\n # Create a text mapper and actor to display the results of picking.\n textMapper = vtk.vtkTextMapper()\n tprop = textMapper.GetTextProperty()\n tprop.SetFontFamilyToArial()\n tprop.SetFontSize(10)\n # tprop.BoldOn()\n # tprop.ShadowOn()\n tprop.SetColor(1, 0, 0)\n textActor = vtk.vtkActor2D()\n textActor.VisibilityOff()\n textActor.SetMapper(textMapper)\n # Create a cell picker.\n picker = vtk.vtkCellPicker()\n\n\ndef ren():\n '''Create a renderer.\n\n Returns\n -------\n v : vtkRenderer() object\n Renderer.\n\n Examples\n --------\n >>> from dipy.viz import fvtk\n >>> import numpy as np\n >>> r=fvtk.ren()\n >>> lines=[np.random.rand(10,3)]\n >>> c=fvtk.line(lines,fvtk.red)\n >>> fvtk.add(r,c)\n >>> #fvtk.show(r)\n '''\n return vtk.vtkRenderer()\n\n\ndef add(ren, a):\n ''' Add a specific actor\n '''\n if isinstance(a, vtk.vtkVolume):\n ren.AddVolume(a)\n else:\n ren.AddActor(a)\n\n\ndef rm(ren, a):\n ''' Remove a specific actor\n '''\n ren.RemoveActor(a)\n\n\ndef clear(ren):\n ''' Remove all actors from the renderer\n '''\n ren.RemoveAllViewProps()\n\n\ndef rm_all(ren):\n ''' Remove all actors from the renderer\n '''\n clear(ren)\n\n\ndef _arrow(pos=(0, 0, 0), color=(1, 0, 0), scale=(1, 1, 1), opacity=1):\n ''' Internal function for generating arrow actors.\n '''\n arrow = vtk.vtkArrowSource()\n # arrow.SetTipLength(length)\n\n arrowm = vtk.vtkPolyDataMapper()\n\n if major_version <= 5:\n arrowm.SetInput(arrow.GetOutput())\n else:\n arrowm.SetInputData(arrow.GetOutput())\n\n arrowa = vtk.vtkActor()\n arrowa.SetMapper(arrowm)\n\n arrowa.GetProperty().SetColor(color)\n arrowa.GetProperty().SetOpacity(opacity)\n arrowa.SetScale(scale)\n\n return arrowa\n\n\ndef axes(scale=(1, 1, 1), colorx=(1, 0, 0), colory=(0, 1, 0), colorz=(0, 0, 1),\n opacity=1):\n ''' Create an actor with the coordinate system axes where red = x, green = y, blue =z.\n '''\n\n arrowx = _arrow(color=colorx, scale=scale, opacity=opacity)\n arrowy = _arrow(color=colory, scale=scale, opacity=opacity)\n arrowz = _arrow(color=colorz, scale=scale, opacity=opacity)\n\n arrowy.RotateZ(90)\n arrowz.RotateY(-90)\n\n ass = vtk.vtkAssembly()\n ass.AddPart(arrowx)\n ass.AddPart(arrowy)\n ass.AddPart(arrowz)\n\n return ass\n\n\ndef _lookup(colors):\n ''' Internal function\n Creates a lookup table with given colors.\n\n Parameters\n ------------\n colors : array, shape (N,3)\n Colormap where every triplet is encoding red, green and blue e.g.\n\n ::\n r1,g1,b1\n r2,g2,b2\n ...\n rN,gN,bN\n\n where\n\n ::\n 0= 2:\n raise ValueError('Incorrect shape of array in colors')\n\n if colors.ndim == 1:\n N = 1\n\n if colors.ndim == 2:\n\n N = colors.shape[0]\n\n lut = vtk.vtkLookupTable()\n lut.SetNumberOfColors(N)\n lut.Build()\n\n if colors.ndim == 2:\n scalar = 0\n for (r, g, b) in colors:\n\n lut.SetTableValue(scalar, r, g, b, 1.0)\n scalar += 1\n if colors.ndim == 1:\n\n lut.SetTableValue(0, colors[0], colors[1], colors[2], 1.0)\n\n return lut\n\n\ndef line(lines, colors, opacity=1, linewidth=1):\n ''' Create an actor for one or more lines.\n\n Parameters\n ------------\n lines : list of arrays representing lines as 3d points for example\n lines=[np.random.rand(10,3),np.random.rand(20,3)]\n represents 2 lines the first with 10 points and the second with 20 points in x,y,z coordinates.\n colors : array, shape (N,3)\n Colormap where every triplet is encoding red, green and blue e.g.\n\n ::\n r1,g1,b1\n r2,g2,b2\n ...\n rN,gN,bN\n\n where\n\n ::\n 0=>> from dipy.viz import fvtk\n >>> r=fvtk.ren()\n >>> lines=[np.random.rand(10,3),np.random.rand(20,3)]\n >>> colors=np.random.rand(2,3)\n >>> c=fvtk.line(lines,colors)\n >>> fvtk.add(r,c)\n >>> #fvtk.show(r)\n '''\n if not isinstance(lines, types.ListType):\n lines = [lines]\n\n points = vtk.vtkPoints()\n lines_ = vtk.vtkCellArray()\n linescalars = vtk.vtkFloatArray()\n\n # lookuptable=vtk.vtkLookupTable()\n lookuptable = _lookup(colors)\n\n scalarmin = 0\n if colors.ndim == 2:\n scalarmax = colors.shape[0] - 1\n if colors.ndim == 1:\n scalarmax = 0\n\n curPointID = 0\n\n m = (0.0, 0.0, 0.0)\n n = (1.0, 0.0, 0.0)\n\n scalar = 0\n # many colors\n if colors.ndim == 2:\n for Line in lines:\n\n inw = True\n mit = iter(Line)\n nit = iter(Line)\n next(nit)\n\n while(inw):\n\n try:\n m = next(mit)\n n = next(nit)\n\n # scalar=sp.rand(1)\n\n linescalars.SetNumberOfComponents(1)\n points.InsertNextPoint(m)\n linescalars.InsertNextTuple1(scalar)\n\n points.InsertNextPoint(n)\n linescalars.InsertNextTuple1(scalar)\n\n lines_.InsertNextCell(2)\n lines_.InsertCellPoint(curPointID)\n lines_.InsertCellPoint(curPointID + 1)\n\n curPointID += 2\n except StopIteration:\n break\n\n scalar += 1\n # one color only\n if colors.ndim == 1:\n for Line in lines:\n\n inw = True\n mit = iter(Line)\n nit = iter(Line)\n next(nit)\n\n while(inw):\n\n try:\n m = next(mit)\n n = next(nit)\n\n # scalar=sp.rand(1)\n\n linescalars.SetNumberOfComponents(1)\n points.InsertNextPoint(m)\n linescalars.InsertNextTuple1(scalar)\n\n points.InsertNextPoint(n)\n linescalars.InsertNextTuple1(scalar)\n\n lines_.InsertNextCell(2)\n lines_.InsertCellPoint(curPointID)\n lines_.InsertCellPoint(curPointID + 1)\n\n curPointID += 2\n except StopIteration:\n break\n\n polydata = vtk.vtkPolyData()\n polydata.SetPoints(points)\n polydata.SetLines(lines_)\n polydata.GetPointData().SetScalars(linescalars)\n\n mapper = vtk.vtkPolyDataMapper()\n if major_version <= 5:\n mapper.SetInput(polydata)\n else:\n mapper.SetInputData(polydata)\n\n mapper.SetLookupTable(lookuptable)\n\n mapper.SetColorModeToMapScalars()\n mapper.SetScalarRange(scalarmin, scalarmax)\n mapper.SetScalarModeToUsePointData()\n\n actor = vtk.vtkActor()\n actor.SetMapper(mapper)\n actor.GetProperty().SetLineWidth(linewidth)\n actor.GetProperty().SetOpacity(opacity)\n\n return actor\n\n\ndef dots(points, color=(1, 0, 0), opacity=1):\n '''\n Create one or more 3d dots(points) returns one actor handling all the points\n '''\n\n if points.ndim == 2:\n points_no = points.shape[0]\n else:\n points_no = 1\n\n polyVertexPoints = vtk.vtkPoints()\n polyVertexPoints.SetNumberOfPoints(points_no)\n aPolyVertex = vtk.vtkPolyVertex()\n aPolyVertex.GetPointIds().SetNumberOfIds(points_no)\n\n cnt = 0\n if points.ndim > 1:\n for point in points:\n polyVertexPoints.InsertPoint(cnt, point[0], point[1], point[2])\n aPolyVertex.GetPointIds().SetId(cnt, cnt)\n cnt += 1\n else:\n polyVertexPoints.InsertPoint(cnt, points[0], points[1], points[2])\n aPolyVertex.GetPointIds().SetId(cnt, cnt)\n cnt += 1\n\n aPolyVertexGrid = vtk.vtkUnstructuredGrid()\n aPolyVertexGrid.Allocate(1, 1)\n aPolyVertexGrid.InsertNextCell(aPolyVertex.GetCellType(), aPolyVertex.GetPointIds())\n\n aPolyVertexGrid.SetPoints(polyVertexPoints)\n aPolyVertexMapper = vtk.vtkDataSetMapper()\n if major_version <= 5:\n aPolyVertexMapper.SetInput(aPolyVertexGrid)\n else:\n aPolyVertexMapper.SetInputData(aPolyVertexGrid)\n aPolyVertexActor = vtk.vtkActor()\n aPolyVertexActor.SetMapper(aPolyVertexMapper)\n\n aPolyVertexActor.GetProperty().SetColor(color)\n aPolyVertexActor.GetProperty().SetOpacity(opacity)\n return aPolyVertexActor\n\n\ndef point(points, colors, opacity=1, point_radius=0.1, theta=3, phi=3):\n\n if np.array(colors).ndim == 1:\n # return dots(points,colors,opacity)\n colors = np.tile(colors, (len(points), 1))\n\n scalars = vtk.vtkUnsignedCharArray()\n scalars.SetNumberOfComponents(3)\n\n pts = vtk.vtkPoints()\n cnt_colors = 0\n\n for p in points:\n\n pts.InsertNextPoint(p[0], p[1], p[2])\n scalars.InsertNextTuple3(\n round(255 * colors[cnt_colors][0]), round(255 * colors[cnt_colors][1]), round(255 * colors[cnt_colors][2]))\n # scalars.InsertNextTuple3(255,255,255)\n cnt_colors += 1\n\n '''\n src = vtk.vtkDiskSource()\n src.SetRadialResolution(1)\n src.SetCircumferentialResolution(10)\n src.SetInnerRadius(0.0)\n src.SetOuterRadius(0.001)\n '''\n # src = vtk.vtkPointSource()\n src = vtk.vtkSphereSource()\n src.SetRadius(point_radius)\n src.SetThetaResolution(theta)\n src.SetPhiResolution(phi)\n\n polyData = vtk.vtkPolyData()\n polyData.SetPoints(pts)\n polyData.GetPointData().SetScalars(scalars)\n\n glyph = vtk.vtkGlyph3D()\n glyph.SetSourceConnection(src.GetOutputPort())\n if major_version <= 5:\n glyph.SetInput(polyData)\n else:\n glyph.SetInputData(polyData)\n glyph.SetColorModeToColorByScalar()\n glyph.SetScaleModeToDataScalingOff()\n\n mapper = vtk.vtkPolyDataMapper()\n if major_version <= 5:\n mapper.SetInput(glyph.GetOutput())\n else:\n mapper.SetInputData(glyph.GetOutput())\n actor = vtk.vtkActor()\n actor.SetMapper(mapper)\n\n return actor\n\n\ndef sphere(position=(0, 0, 0), radius=0.5, thetares=8, phires=8,\n color=(0, 0, 1), opacity=1, tessel=0):\n ''' Create a sphere actor\n '''\n sphere = vtk.vtkSphereSource()\n sphere.SetRadius(radius)\n sphere.SetLatLongTessellation(tessel)\n\n sphere.SetThetaResolution(thetares)\n sphere.SetPhiResolution(phires)\n\n spherem = vtk.vtkPolyDataMapper()\n if major_version <= 5:\n spherem.SetInput(sphere.GetOutput())\n else:\n spherem.SetInputData(sphere.GetOutput())\n spherea = vtk.vtkActor()\n spherea.SetMapper(spherem)\n spherea.SetPosition(position)\n spherea.GetProperty().SetColor(color)\n spherea.GetProperty().SetOpacity(opacity)\n\n return spherea\n\n\ndef ellipsoid(R=np.array([[2, 0, 0], [0, 1, 0], [0, 0, 1]]),\n position=(0, 0, 0), thetares=20, phires=20, color=(0, 0, 1),\n opacity=1, tessel=0):\n ''' Create a ellipsoid actor.\n\n Stretch a unit sphere to make it an ellipsoid under a 3x3 translation\n matrix R.\n\n R = sp.array([[2, 0, 0],\n [0, 1, 0],\n [0, 0, 1] ])\n '''\n\n Mat = sp.identity(4)\n Mat[0:3, 0:3] = R\n\n '''\n Mat=sp.array([[2, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1] ])\n '''\n mat = vtk.vtkMatrix4x4()\n\n for i in sp.ndindex(4, 4):\n\n mat.SetElement(i[0], i[1], Mat[i])\n\n radius = 1\n sphere = vtk.vtkSphereSource()\n sphere.SetRadius(radius)\n sphere.SetLatLongTessellation(tessel)\n\n sphere.SetThetaResolution(thetares)\n sphere.SetPhiResolution(phires)\n\n trans = vtk.vtkTransform()\n\n trans.Identity()\n # trans.Scale(0.3,0.9,0.2)\n trans.SetMatrix(mat)\n trans.Update()\n\n transf = vtk.vtkTransformPolyDataFilter()\n transf.SetTransform(trans)\n\n if major_version <= 5:\n transf.SetInput(sphere.GetOutput())\n else:\n transf.SetInputData(sphere.GetOutput())\n transf.Update()\n\n spherem = vtk.vtkPolyDataMapper()\n if major_version <= 5:\n spherem.SetInput(transf.GetOutput())\n else:\n spherem.SetInputData(transf.GetOutput())\n\n spherea = vtk.vtkActor()\n spherea.SetMapper(spherem)\n spherea.SetPosition(position)\n spherea.GetProperty().SetColor(color)\n spherea.GetProperty().SetOpacity(opacity)\n # spherea.GetProperty().SetRepresentationToWireframe()\n\n return spherea\n\n\ndef label(ren, text='Origin', pos=(0, 0, 0), scale=(0.2, 0.2, 0.2),\n color=(1, 1, 1)):\n\n ''' Create a label actor.\n\n This actor will always face the camera\n\n Parameters\n ----------\n ren : vtkRenderer() object\n Renderer as returned by ``ren()``.\n text : str\n Text for the label.\n pos : (3,) array_like, optional\n Left down position of the label.\n scale : (3,) array_like\n Changes the size of the label.\n color : (3,) array_like\n Label color as ``(r,g,b)`` tuple.\n\n Returns\n ----------\n l : vtkActor object\n Label.\n\n Examples\n ----------\n >>> from dipy.viz import fvtk\n >>> r=fvtk.ren()\n >>> l=fvtk.label(r)\n >>> fvtk.add(r,l)\n >>> #fvtk.show(r)\n '''\n atext = vtk.vtkVectorText()\n atext.SetText(text)\n\n textm = vtk.vtkPolyDataMapper()\n if major_version <= 5:\n textm.SetInput(atext.GetOutput())\n else:\n textm.SetInputData(atext.GetOutput())\n\n texta = vtk.vtkFollower()\n texta.SetMapper(textm)\n texta.SetScale(scale)\n\n texta.GetProperty().SetColor(color)\n texta.SetPosition(pos)\n\n ren.AddActor(texta)\n texta.SetCamera(ren.GetActiveCamera())\n\n return texta\n\n\ndef volume(vol, voxsz=(1.0, 1.0, 1.0), affine=None, center_origin=1,\n info=0, maptype=0, trilinear=1, iso=0, iso_thr=100,\n opacitymap=None, colormap=None):\n ''' Create a volume and return a volumetric actor using volumetric\n rendering.\n\n This function has many different interesting capabilities. The maptype,\n opacitymap and colormap are the most crucial parameters here.\n\n Parameters\n ----------\n vol : array, shape (N, M, K), dtype uint8\n An array representing the volumetric dataset that we want to visualize\n using volumetric rendering.\n voxsz : (3,) array_like\n Voxel size.\n affine : (4, 4) ndarray\n As given by volumeimages.\n center_origin : int {0,1}\n It considers that the center of the volume is the\n point ``(-vol.shape[0]/2.0+0.5,-vol.shape[1]/2.0+0.5,-vol.shape[2]/2.0+0.5)``.\n info : int {0,1}\n If 1 it prints out some info about the volume, the method and the\n dataset.\n trilinear : int {0,1}\n Use trilinear interpolation, default 1, gives smoother rendering. If\n you want faster interpolation use 0 (Nearest).\n maptype : int {0,1}\n The maptype is a very important parameter which affects the raycasting algorithm in use for the rendering.\n The options are:\n If 0 then vtkVolumeTextureMapper2D is used.\n If 1 then vtkVolumeRayCastFunction is used.\n iso : int {0,1}\n If iso is 1 and maptype is 1 then we use\n ``vtkVolumeRayCastIsosurfaceFunction`` which generates an isosurface at\n the predefined iso_thr value. If iso is 0 and maptype is 1\n ``vtkVolumeRayCastCompositeFunction`` is used.\n iso_thr : int\n If iso is 1 then then this threshold in the volume defines the value\n which will be used to create the isosurface.\n opacitymap : (2, 2) ndarray\n The opacity map assigns a transparency coefficient to every point in\n the volume. The default value uses the histogram of the volume to\n calculate the opacitymap.\n colormap : (4, 4) ndarray\n The color map assigns a color value to every point in the volume.\n When None from the histogram it uses a red-blue colormap.\n\n Returns\n -------\n v : vtkVolume\n Volume.\n\n Notes\n --------\n What is the difference between TextureMapper2D and RayCastFunction? Coming\n soon... See VTK user's guide [book] & The Visualization Toolkit [book] and\n VTK's online documentation & online docs.\n\n What is the difference between RayCastIsosurfaceFunction and\n RayCastCompositeFunction? Coming soon... See VTK user's guide [book] &\n The Visualization Toolkit [book] and VTK's online documentation &\n online docs.\n\n What about trilinear interpolation?\n Coming soon... well when time permits really ... :-)\n\n Examples\n --------\n First example random points.\n\n >>> from dipy.viz import fvtk\n >>> import numpy as np\n >>> vol=100*np.random.rand(100,100,100)\n >>> vol=vol.astype('uint8')\n >>> vol.min(), vol.max()\n (0, 99)\n >>> r = fvtk.ren()\n >>> v = fvtk.volume(vol)\n >>> fvtk.add(r,v)\n >>> #fvtk.show(r)\n\n Second example with a more complicated function\n\n >>> from dipy.viz import fvtk\n >>> import numpy as np\n >>> x, y, z = np.ogrid[-10:10:20j, -10:10:20j, -10:10:20j]\n >>> s = np.sin(x*y*z)/(x*y*z)\n >>> r = fvtk.ren()\n >>> v = fvtk.volume(s)\n >>> fvtk.add(r,v)\n >>> #fvtk.show(r)\n\n If you find this function too complicated you can always use mayavi.\n Please do not forget to use the -wthread switch in ipython if you are\n running mayavi.\n\n from enthought.mayavi import mlab\n import numpy as np\n x, y, z = np.ogrid[-10:10:20j, -10:10:20j, -10:10:20j]\n s = np.sin(x*y*z)/(x*y*z)\n mlab.pipeline.volume(mlab.pipeline.scalar_field(s))\n mlab.show()\n\n More mayavi demos are available here:\n\n http://code.enthought.com/projects/mayavi/docs/development/html/mayavi/mlab.html\n\n '''\n if vol.ndim != 3:\n raise ValueError('3d numpy arrays only please')\n\n if info:\n print('Datatype', vol.dtype, 'converted to uint8')\n\n vol = np.interp(vol, [vol.min(), vol.max()], [0, 255])\n vol = vol.astype('uint8')\n\n if opacitymap is None:\n\n bin, res = np.histogram(vol.ravel())\n res2 = np.interp(res, [vol.min(), vol.max()], [0, 1])\n opacitymap = np.vstack((res, res2)).T\n opacitymap = opacitymap.astype('float32')\n\n '''\n opacitymap=np.array([[ 0.0, 0.0],\n [50.0, 0.9]])\n '''\n\n if info:\n print('opacitymap', opacitymap)\n\n if colormap == None:\n\n bin, res = np.histogram(vol.ravel())\n res2 = np.interp(res, [vol.min(), vol.max()], [0, 1])\n zer = np.zeros(res2.shape)\n colormap = np.vstack((res, res2, zer, res2[::-1])).T\n colormap = colormap.astype('float32')\n\n '''\n colormap=np.array([[0.0, 0.5, 0.0, 0.0],\n [64.0, 1.0, 0.5, 0.5],\n [128.0, 0.9, 0.2, 0.3],\n [196.0, 0.81, 0.27, 0.1],\n [255.0, 0.5, 0.5, 0.5]])\n '''\n\n if info:\n print('colormap', colormap)\n\n im = vtk.vtkImageData()\n im.SetScalarTypeToUnsignedChar()\n im.SetDimensions(vol.shape[0], vol.shape[1], vol.shape[2])\n # im.SetOrigin(0,0,0)\n # im.SetSpacing(voxsz[2],voxsz[0],voxsz[1])\n im.AllocateScalars()\n\n for i in range(vol.shape[0]):\n for j in range(vol.shape[1]):\n for k in range(vol.shape[2]):\n\n im.SetScalarComponentFromFloat(i, j, k, 0, vol[i, j, k])\n\n if affine != None:\n\n aff = vtk.vtkMatrix4x4()\n aff.DeepCopy((affine[0, 0], affine[0, 1], affine[0, 2], affine[0, 3], affine[1, 0], affine[1, 1], affine[1, 2], affine[1, 3], affine[2, 0], affine[\n 2, 1], affine[2, 2], affine[2, 3], affine[3, 0], affine[3, 1], affine[3, 2], affine[3, 3]))\n # aff.DeepCopy((affine[0,0],affine[0,1],affine[0,2],0,affine[1,0],affine[1,1],affine[1,2],0,affine[2,0],affine[2,1],affine[2,2],0,affine[3,0],affine[3,1],affine[3,2],1))\n # aff.DeepCopy((affine[0,0],affine[0,1],affine[0,2],127.5,affine[1,0],affine[1,1],affine[1,2],-127.5,affine[2,0],affine[2,1],affine[2,2],-127.5,affine[3,0],affine[3,1],affine[3,2],1))\n\n reslice = vtk.vtkImageReslice()\n if major_version <= 5:\n reslice.SetInput(im)\n else:\n reslice.SetInputData(im)\n # reslice.SetOutputDimensionality(2)\n # reslice.SetOutputOrigin(127,-145,147)\n\n reslice.SetResliceAxes(aff)\n # reslice.SetOutputOrigin(-127,-127,-127)\n # reslice.SetOutputExtent(-127,128,-127,128,-127,128)\n # reslice.SetResliceAxesOrigin(0,0,0)\n # print 'Get Reslice Axes Origin ', reslice.GetResliceAxesOrigin()\n # reslice.SetOutputSpacing(1.0,1.0,1.0)\n\n reslice.SetInterpolationModeToLinear()\n # reslice.UpdateWholeExtent()\n\n # print 'reslice GetOutputOrigin', reslice.GetOutputOrigin()\n # print 'reslice GetOutputExtent',reslice.GetOutputExtent()\n # print 'reslice GetOutputSpacing',reslice.GetOutputSpacing()\n\n changeFilter = vtk.vtkImageChangeInformation()\n if major_version <= 5:\n changeFilter.SetInput(reslice.GetOutput())\n else:\n changeFilter.SetInputData(reslice.GetOutput())\n # changeFilter.SetInput(im)\n if center_origin:\n changeFilter.SetOutputOrigin(-vol.shape[0] / 2.0 + 0.5, -vol.shape[1] / 2.0 + 0.5, -vol.shape[2] / 2.0 + 0.5)\n print('ChangeFilter ', changeFilter.GetOutputOrigin())\n\n opacity = vtk.vtkPiecewiseFunction()\n for i in range(opacitymap.shape[0]):\n opacity.AddPoint(opacitymap[i, 0], opacitymap[i, 1])\n\n color = vtk.vtkColorTransferFunction()\n for i in range(colormap.shape[0]):\n color.AddRGBPoint(colormap[i, 0], colormap[i, 1], colormap[i, 2], colormap[i, 3])\n\n if(maptype == 0):\n\n property = vtk.vtkVolumeProperty()\n property.SetColor(color)\n property.SetScalarOpacity(opacity)\n\n if trilinear:\n property.SetInterpolationTypeToLinear()\n else:\n property.SetInterpolationTypeToNearest()\n\n if info:\n print('mapper VolumeTextureMapper2D')\n mapper = vtk.vtkVolumeTextureMapper2D()\n if affine == None:\n if major_version <= 5:\n mapper.SetInput(im)\n else:\n mapper.SetInputData(im)\n else:\n if major_version <= 5:\n mapper.SetInput(changeFilter.GetOutput())\n else:\n mapper.SetInputData(changeFilter.GetOutput())\n\n if (maptype == 1):\n\n property = vtk.vtkVolumeProperty()\n property.SetColor(color)\n property.SetScalarOpacity(opacity)\n property.ShadeOn()\n if trilinear:\n property.SetInterpolationTypeToLinear()\n else:\n property.SetInterpolationTypeToNearest()\n\n if iso:\n isofunc = vtk.vtkVolumeRayCastIsosurfaceFunction()\n isofunc.SetIsoValue(iso_thr)\n else:\n compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()\n\n if info:\n print('mapper VolumeRayCastMapper')\n\n mapper = vtk.vtkVolumeRayCastMapper()\n if iso:\n mapper.SetVolumeRayCastFunction(isofunc)\n if info:\n print('Isosurface')\n else:\n mapper.SetVolumeRayCastFunction(compositeFunction)\n\n # mapper.SetMinimumImageSampleDistance(0.2)\n if info:\n print('Composite')\n\n if affine == None:\n if major_version <= 5:\n mapper.SetInput(im)\n else:\n mapper.SetInputData(im)\n else:\n # mapper.SetInput(reslice.GetOutput())\n if major_version <= 5:\n mapper.SetInput(changeFilter.GetOutput())\n else:\n mapper.SetInputData(changeFilter.GetOutput())\n # Return mid position in world space\n # im2=reslice.GetOutput()\n # index=im2.FindPoint(vol.shape[0]/2.0,vol.shape[1]/2.0,vol.shape[2]/2.0)\n # print 'Image Getpoint ' , im2.GetPoint(index)\n\n volum = vtk.vtkVolume()\n volum.SetMapper(mapper)\n volum.SetProperty(property)\n\n if info:\n\n print('Origin', volum.GetOrigin())\n print('Orientation', volum.GetOrientation())\n print('OrientationW', volum.GetOrientationWXYZ())\n print('Position', volum.GetPosition())\n print('Center', volum.GetCenter())\n print('Get XRange', volum.GetXRange())\n print('Get YRange', volum.GetYRange())\n print('Get ZRange', volum.GetZRange())\n print('Volume data type', vol.dtype)\n\n return volum\n\n\ndef contour(vol, voxsz=(1.0, 1.0, 1.0), affine=None, levels=[50],\n colors=[np.array([1.0, 0.0, 0.0])], opacities=[0.5]):\n ''' Take a volume and draw surface contours for any any number of\n thresholds (levels) where every contour has its own color and opacity\n\n Parameters\n ----------\n vol : (N, M, K) ndarray\n An array representing the volumetric dataset for which we will draw\n some beautiful contours .\n voxsz : (3,) array_like\n Voxel size.\n affine : None\n Not used.\n levels : array_like\n Sequence of thresholds for the contours taken from image values needs\n to be same datatype as `vol`.\n colors : (N, 3) ndarray\n RGB values in [0,1].\n opacities : array_like\n Opacities of contours.\n\n Returns\n -----------\n ass : assembly of actors\n Representing the contour surfaces.\n\n Examples\n -------------\n >>> import numpy as np\n >>> from dipy.viz import fvtk\n >>> A=np.zeros((10,10,10))\n >>> A[3:-3,3:-3,3:-3]=1\n >>> r=fvtk.ren()\n >>> fvtk.add(r,fvtk.contour(A,levels=[1]))\n >>> #fvtk.show(r)\n\n '''\n\n im = vtk.vtkImageData()\n im.SetScalarTypeToUnsignedChar()\n im.SetDimensions(vol.shape[0], vol.shape[1], vol.shape[2])\n # im.SetOrigin(0,0,0)\n # im.SetSpacing(voxsz[2],voxsz[0],voxsz[1])\n im.AllocateScalars()\n\n for i in range(vol.shape[0]):\n for j in range(vol.shape[1]):\n for k in range(vol.shape[2]):\n\n im.SetScalarComponentFromFloat(i, j, k, 0, vol[i, j, k])\n\n ass = vtk.vtkAssembly()\n # ass=[]\n\n for (i, l) in enumerate(levels):\n\n # print levels\n skinExtractor = vtk.vtkContourFilter()\n if major_version <= 5:\n skinExtractor.SetInput(im)\n else:\n skinExtractor.SetInputData(im)\n skinExtractor.SetValue(0, l)\n\n skinNormals = vtk.vtkPolyDataNormals()\n skinNormals.SetInputConnection(skinExtractor.GetOutputPort())\n skinNormals.SetFeatureAngle(60.0)\n\n skinMapper = vtk.vtkPolyDataMapper()\n skinMapper.SetInputConnection(skinNormals.GetOutputPort())\n skinMapper.ScalarVisibilityOff()\n\n skin = vtk.vtkActor()\n\n skin.SetMapper(skinMapper)\n skin.GetProperty().SetOpacity(opacities[i])\n\n # print colors[i]\n skin.GetProperty().SetColor(colors[i][0], colors[i][1], colors[i][2])\n # skin.Update()\n\n ass.AddPart(skin)\n\n del skin\n del skinMapper\n del skinExtractor\n # ass=ass+[skin]\n\n return ass\n\n\ndef _cm2colors(colormap='Blues'):\n '''\n Colormaps from matplotlib\n ['Spectral', 'summer', 'RdBu', 'gist_earth', 'Set1', 'Set2', 'Set3', 'Dark2',\n 'hot', 'PuOr_r', 'PuBuGn_r', 'RdPu', 'gist_ncar_r', 'gist_yarg_r', 'Dark2_r',\n 'YlGnBu', 'RdYlBu', 'hot_r', 'gist_rainbow_r', 'gist_stern', 'cool_r', 'cool',\n 'gray', 'copper_r', 'Greens_r', 'GnBu', 'gist_ncar', 'spring_r', 'gist_rainbow',\n 'RdYlBu_r', 'gist_heat_r', 'OrRd_r', 'bone', 'gist_stern_r', 'RdYlGn', 'Pastel2_r',\n 'spring', 'Accent', 'YlOrRd_r', 'Set2_r', 'PuBu', 'RdGy_r', 'spectral', 'flag_r', 'jet_r',\n 'RdPu_r', 'gist_yarg', 'BuGn', 'Paired_r', 'hsv_r', 'YlOrRd', 'Greens', 'PRGn',\n 'gist_heat', 'spectral_r', 'Paired', 'hsv', 'Oranges_r', 'prism_r', 'Pastel2', 'Pastel1_r',\n 'Pastel1', 'gray_r', 'PuRd_r', 'Spectral_r', 'BuGn_r', 'YlGnBu_r', 'copper',\n 'gist_earth_r', 'Set3_r', 'OrRd', 'PuBu_r', 'winter_r', 'jet', 'bone_r', 'BuPu',\n 'Oranges', 'RdYlGn_r', 'PiYG', 'YlGn', 'binary_r', 'gist_gray_r', 'BuPu_r',\n 'gist_gray', 'flag', 'RdBu_r', 'BrBG', 'Reds', 'summer_r', 'GnBu_r', 'BrBG_r',\n 'Reds_r', 'RdGy', 'PuRd', 'Accent_r', 'Blues', 'Greys', 'autumn', 'PRGn_r', 'Greys_r',\n 'pink', 'binary', 'winter', 'pink_r', 'prism', 'YlOrBr', 'Purples_r', 'PiYG_r', 'YlGn_r',\n 'Blues_r', 'YlOrBr_r', 'Purples', 'autumn_r', 'Set1_r', 'PuOr', 'PuBuGn']\n\n '''\n try:\n from pylab import cm\n except ImportError:\n ImportError('pylab is not installed')\n\n blue = cm.datad[colormap]['blue']\n blue1 = [b[0] for b in blue]\n blue2 = [b[1] for b in blue]\n\n red = cm.datad[colormap]['red']\n red1 = [b[0] for b in red]\n red2 = [b[1] for b in red]\n\n green = cm.datad[colormap]['green']\n green1 = [b[0] for b in green]\n green2 = [b[1] for b in green]\n\n return red1, red2, green1, green2, blue1, blue2\n\n\ndef create_colormap(v, name='jet', auto=True):\n ''' Create colors from a specific colormap and return it\n as an array of shape (N,3) where every row gives the corresponding\n r,g,b value. The colormaps we use are similar with those of pylab.\n\n Parameters\n ----------\n v : (N,) array\n vector of values to be mapped in RGB colors according to colormap\n name : str. 'jet', 'blues', 'blue_red', 'accent'\n name of the colourmap\n auto : bool,\n if auto is True then v is interpolated to [0, 10] from v.min()\n to v.max()\n\n Notes\n -----\n If you want to add more colormaps here is what you could do. Go to\n this website http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps\n see which colormap you need and then get in pylab using the cm.datad\n dictionary.\n\n e.g.::\n\n cm.datad['jet']\n\n {'blue': ((0.0, 0.5, 0.5),\n (0.11, 1, 1),\n (0.34000000000000002, 1, 1),\n (0.65000000000000002, 0, 0),\n (1, 0, 0)),\n 'green': ((0.0, 0, 0),\n (0.125, 0, 0),\n (0.375, 1, 1),\n (0.64000000000000001, 1, 1),\n (0.91000000000000003, 0, 0),\n (1, 0, 0)),\n 'red': ((0.0, 0, 0),\n (0.34999999999999998, 0, 0),\n (0.66000000000000003, 1, 1),\n (0.89000000000000001, 1, 1),\n (1, 0.5, 0.5))}\n\n '''\n if v.ndim > 1:\n ValueError('This function works only with 1d arrays. Use ravel()')\n\n if auto:\n v = np.interp(v, [v.min(), v.max()], [0, 1])\n else:\n v = np.interp(v, [0, 1], [0, 1])\n\n if name == 'jet':\n # print 'jet'\n\n red = np.interp(v, [0, 0.35, 0.66, 0.89, 1], [0, 0, 1, 1, 0.5])\n green = np.interp(v, [0, 0.125, 0.375, 0.64, 0.91, 1], [0, 0, 1, 1, 0, 0])\n blue = np.interp(v, [0, 0.11, 0.34, 0.65, 1], [0.5, 1, 1, 0, 0])\n\n if name == 'blues':\n # cm.datad['Blues']\n # print 'blues'\n\n red = np.interp(\n v, [\n 0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0], [0.96862745285, 0.870588243008, 0.776470601559, 0.61960786581,\n 0.419607847929, 0.258823543787, 0.129411771894, 0.0313725508749, 0.0313725508749])\n green = np.interp(\n v, [\n 0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0], [0.984313726425, 0.921568632126, 0.858823537827, 0.792156875134,\n 0.68235296011, 0.572549045086, 0.443137258291, 0.317647069693, 0.188235297799])\n blue = np.interp(\n v, [0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0], [1.0, 0.96862745285, 0.937254905701, 0.882352948189,\n 0.839215695858, 0.776470601559, 0.709803938866, 0.611764729023, 0.419607847929])\n\n if name == 'blue_red':\n # print 'blue_red'\n # red=np.interp(v,[],[])\n\n red = np.interp(v, [0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0], [0.0, 0.125, 0.25, 0.375, 0.5,\n 0.625, 0.75, 0.875, 1.0])\n green = np.zeros(red.shape)\n blue = np.interp(v, [0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0], [1.0, 0.875, 0.75, 0.625, 0.5,\n 0.375, 0.25, 0.125, 0.0])\n\n blue = green\n\n if name == 'accent':\n # print 'accent'\n red = np.interp(\n v, [0.0, 0.14285714285714285, 0.2857142857142857, 0.42857142857142855, 0.5714285714285714,\n 0.7142857142857143, 0.8571428571428571, 1.0],\n [0.49803921580314636, 0.7450980544090271, 0.99215686321258545, 1.0, 0.21960784494876862, 0.94117647409439087, 0.74901962280273438, 0.40000000596046448])\n green = np.interp(\n v, [0.0, 0.14285714285714285, 0.2857142857142857, 0.42857142857142855, 0.5714285714285714,\n 0.7142857142857143, 0.8571428571428571, 1.0],\n [0.78823530673980713, 0.68235296010971069, 0.75294119119644165, 1.0, 0.42352941632270813, 0.0078431377187371254, 0.35686275362968445, 0.40000000596046448])\n blue = np.interp(\n v, [0.0, 0.14285714285714285, 0.2857142857142857, 0.42857142857142855, 0.5714285714285714,\n 0.7142857142857143, 0.8571428571428571, 1.0],\n [0.49803921580314636, 0.83137255907058716, 0.52549022436141968, 0.60000002384185791, 0.69019609689712524, 0.49803921580314636, 0.090196080505847931, 0.40000000596046448])\n\n return np.vstack((red, green, blue)).T\n\n\ndef sphere_funcs(sphere_values, sphere, image=None, colormap='jet',\n scale=2.2, norm=True, radial_scale=True):\n \"\"\"Plot many morphed spheres simultaneously.\n\n Parameters\n ----------\n sphere_values : (M,) or (X, M) or (X, Y, M) or (X, Y, Z, M) ndarray\n Values on the sphere.\n sphere : Sphere\n image : None,\n Not yet supported.\n colormap : None or 'jet'\n If None then no color is used.\n scale : float,\n Distance between spheres.\n norm : bool,\n Normalize `sphere_values`.\n radial_scale : bool,\n Scale sphere points according to odf values.\n\n Returns\n -------\n actor : vtkActor\n Spheres.\n\n Examples\n --------\n >>> from dipy.viz import fvtk\n >>> r = fvtk.ren()\n >>> odfs = np.ones((5, 5, 724))\n >>> odfs[..., 0] = 2.\n >>> from dipy.data import get_sphere\n >>> sphere = get_sphere('symmetric724')\n >>> fvtk.add(r, fvtk.sphere_funcs(odfs, sphere))\n >>> #fvtk.show(r)\n\n \"\"\"\n\n sphere_values = np.asarray(sphere_values)\n if sphere_values.ndim == 1:\n sphere_values = sphere_values[None, None, None, :]\n if sphere_values.ndim == 2:\n sphere_values = sphere_values[None, None, :]\n if sphere_values.ndim == 3:\n sphere_values = sphere_values[None, :]\n if sphere_values.ndim > 4:\n raise ValueError(\"Wrong shape\")\n\n grid_shape = np.array(sphere_values.shape[:3])\n faces = np.asarray(sphere.faces, dtype=int)\n vertices = sphere.vertices\n\n if sphere_values.shape[-1] != sphere.vertices.shape[0]:\n msg = 'Sphere.vertice.shape[0] should be the same as the'\n msg += 'last dimensions of sphere_values i.e. sphere_values.shape[-1]'\n raise ValueError(msg)\n\n list_sq = []\n list_cols = []\n\n for ijk in np.ndindex(*grid_shape):\n m = sphere_values[ijk].copy()\n\n if norm:\n m /= abs(m).max()\n\n if radial_scale:\n xyz = vertices.T * m\n else:\n xyz = vertices.T.copy()\n\n xyz += scale * (ijk - grid_shape / 2.)[:, None]\n\n xyz = xyz.T\n\n list_sq.append(xyz)\n if colormap is not None:\n cols = create_colormap(m, colormap)\n cols = np.interp(cols, [0, 1], [0, 255]).astype('ubyte')\n list_cols.append(cols)\n\n points = vtk.vtkPoints()\n triangles = vtk.vtkCellArray()\n if colormap is not None:\n colors = vtk.vtkUnsignedCharArray()\n colors.SetNumberOfComponents(3)\n colors.SetName(\"Colors\")\n\n for k in xrange(len(list_sq)):\n\n xyz = list_sq[k]\n if colormap is not None:\n cols = list_cols[k]\n\n for i in xrange(xyz.shape[0]):\n\n points.InsertNextPoint(*xyz[i])\n if colormap is not None:\n colors.InsertNextTuple3(*cols[i])\n\n for j in xrange(faces.shape[0]):\n\n triangle = vtk.vtkTriangle()\n triangle.GetPointIds().SetId(0, faces[j, 0] + k * xyz.shape[0])\n triangle.GetPointIds().SetId(1, faces[j, 1] + k * xyz.shape[0])\n triangle.GetPointIds().SetId(2, faces[j, 2] + k * xyz.shape[0])\n triangles.InsertNextCell(triangle)\n del triangle\n\n polydata = vtk.vtkPolyData()\n polydata.SetPoints(points)\n polydata.SetPolys(triangles)\n\n if colormap is not None:\n polydata.GetPointData().SetScalars(colors)\n polydata.Modified()\n\n mapper = vtk.vtkPolyDataMapper()\n if major_version <= 5:\n mapper.SetInput(polydata)\n else:\n mapper.SetInputData(polydata)\n\n actor = vtk.vtkActor()\n actor.SetMapper(mapper)\n\n return actor\n\n\ndef tensor(evals, evecs, scalar_colors=None, sphere=None, scale=2.2, norm=True):\n \"\"\"Plot many tensors as ellipsoids simultaneously.\n\n Parameters\n ----------\n evals : (3,) or (X, 3) or (X, Y, 3) or (X, Y, Z, 3) ndarray\n eigenvalues\n evecs : (3, 3) or (X, 3, 3) or (X, Y, 3, 3) or (X, Y, Z, 3, 3) ndarray\n eigenvectors\n scalar_colors : (3,) or (X, 3) or (X, Y, 3) or (X, Y, Z, 3) ndarray\n RGB colors used to show the tensors\n Default None, color the ellipsoids using ``color_fa``\n sphere : Sphere,\n this sphere will be transformed to the tensor ellipsoid\n Default is None which uses a symmetric sphere with 724 points.\n scale : float,\n distance between ellipsoids.\n norm : boolean,\n Normalize `evals`.\n\n Returns\n -------\n actor : vtkActor\n Ellipsoids\n\n Examples\n --------\n >>> from dipy.viz import fvtk\n >>> r = fvtk.ren()\n >>> evals = np.array([1.4, .35, .35]) * 10 ** (-3)\n >>> evecs = np.eye(3)\n >>> from dipy.data import get_sphere\n >>> sphere = get_sphere('symmetric724')\n >>> fvtk.add(r, fvtk.tensor(evals, evecs, sphere=sphere))\n >>> #fvtk.show(r)\n\n \"\"\"\n\n evals = np.asarray(evals)\n if evals.ndim == 1:\n evals = evals[None, None, None, :]\n evecs = evecs[None, None, None, :, :]\n if evals.ndim == 2:\n evals = evals[None, None, :]\n evecs = evecs[None, None, :, :]\n if evals.ndim == 3:\n evals = evals[None, :]\n evecs = evecs[None, :, :]\n if evals.ndim > 4:\n raise ValueError(\"Wrong shape\")\n\n grid_shape = np.array(evals.shape[:3])\n\n if sphere is None:\n from dipy.data import get_sphere\n sphere = get_sphere('symmetric724')\n faces = np.asarray(sphere.faces, dtype=int)\n vertices = sphere.vertices\n\n colors = vtk.vtkUnsignedCharArray()\n colors.SetNumberOfComponents(3)\n colors.SetName(\"Colors\")\n\n if scalar_colors is None:\n from dipy.reconst.dti import color_fa, fractional_anisotropy\n cfa = color_fa(fractional_anisotropy(evals), evecs)\n else:\n cfa = scalar_colors\n\n list_sq = []\n list_cols = []\n\n for ijk in ndindex(grid_shape):\n ea = evals[ijk]\n if norm:\n ea /= ea.max()\n ea = np.diag(ea.copy())\n\n ev = evecs[ijk].copy()\n xyz = np.dot(ev, np.dot(ea, vertices.T))\n\n xyz += scale * (ijk - grid_shape / 2.)[:, None]\n\n xyz = xyz.T\n\n list_sq.append(xyz)\n\n acolor = np.zeros(xyz.shape)\n acolor[:, :] = np.interp(cfa[ijk], [0, 1], [0, 255])\n\n list_cols.append(acolor.astype('ubyte'))\n\n points = vtk.vtkPoints()\n triangles = vtk.vtkCellArray()\n\n for k in xrange(len(list_sq)):\n\n xyz = list_sq[k]\n\n cols = list_cols[k]\n\n for i in xrange(xyz.shape[0]):\n\n points.InsertNextPoint(*xyz[i])\n colors.InsertNextTuple3(*cols[i])\n\n for j in xrange(faces.shape[0]):\n\n triangle = vtk.vtkTriangle()\n triangle.GetPointIds().SetId(0, faces[j, 0] + k * xyz.shape[0])\n triangle.GetPointIds().SetId(1, faces[j, 1] + k * xyz.shape[0])\n triangle.GetPointIds().SetId(2, faces[j, 2] + k * xyz.shape[0])\n triangles.InsertNextCell(triangle)\n del triangle\n\n polydata = vtk.vtkPolyData()\n polydata.SetPoints(points)\n polydata.SetPolys(triangles)\n\n polydata.GetPointData().SetScalars(colors)\n polydata.Modified()\n\n mapper = vtk.vtkPolyDataMapper()\n if major_version <= 5:\n mapper.SetInput(polydata)\n else:\n mapper.SetInputData(polydata)\n\n actor = vtk.vtkActor()\n actor.SetMapper(mapper)\n\n return actor\n\n\ndef tube(point1=(0, 0, 0), point2=(1, 0, 0), color=(1, 0, 0), opacity=1, radius=0.1, capson=1, specular=1, sides=8):\n\n ''' Deprecated\n\n Wrap a tube around a line connecting point1 with point2 with a specific\n radius.\n\n '''\n points = vtk.vtkPoints()\n points.InsertPoint(0, point1[0], point1[1], point1[2])\n points.InsertPoint(1, point2[0], point2[1], point2[2])\n\n lines = vtk.vtkCellArray()\n lines.InsertNextCell(2)\n\n lines.InsertCellPoint(0)\n lines.InsertCellPoint(1)\n\n profileData = vtk.vtkPolyData()\n profileData.SetPoints(points)\n profileData.SetLines(lines)\n\n # Add thickness to the resulting line.\n profileTubes = vtk.vtkTubeFilter()\n profileTubes.SetNumberOfSides(sides)\n if major_version <= 5:\n profileTubes.SetInput(profileData)\n else:\n profileTubes.SetInputData(profileData)\n profileTubes.SetRadius(radius)\n\n if capson:\n profileTubes.SetCapping(1)\n else:\n profileTubes.SetCapping(0)\n\n profileMapper = vtk.vtkPolyDataMapper()\n profileMapper.SetInputConnection(profileTubes.GetOutputPort())\n\n profile = vtk.vtkActor()\n profile.SetMapper(profileMapper)\n profile.GetProperty().SetDiffuseColor(color)\n profile.GetProperty().SetSpecular(specular)\n profile.GetProperty().SetSpecularPower(30)\n profile.GetProperty().SetOpacity(opacity)\n\n return profile\n\n\ndef _closest_track(p, tracks):\n ''' Return the index of the closest track from tracks to point p\n '''\n\n d = []\n # enumt= enumerate(tracks)\n\n for (ind, t) in enumerate(tracks):\n for i in range(len(t[:-1])):\n\n d.append(\n (ind, np.sqrt(np.sum(np.cross((p - t[i]), (p - t[i + 1])) ** 2)) / np.sqrt(np.sum((t[i + 1] - t[i]) ** 2))))\n\n d = np.array(d)\n\n imin = d[:, 1].argmin()\n\n return int(d[imin, 0])\n\n\ndef crossing(a, ind, sph, scale, orient=False):\n \"\"\" visualize a volume of crossings\n\n Examples\n ----------\n See 'dipy/doc/examples/visualize_crossings.py' at :ref:`examples`\n\n \"\"\"\n\n T = []\n Tor = []\n if a.ndim == 4 or a.ndim == 3:\n x, y, z = ind.shape[:3]\n for pos in np.ndindex(x, y, z):\n i, j, k = pos\n pos_ = np.array(pos)\n ind_ = ind[i, j, k]\n a_ = a[i, j, k]\n\n try:\n len(ind_)\n except TypeError:\n ind_ = [ind_]\n a_ = [a_]\n\n for (i, _i) in enumerate(ind_):\n T.append(pos_ + scale * a_[i] * np.vstack((sph[_i], -sph[_i])))\n if orient:\n Tor.append(sph[_i])\n\n if a.ndim == 1:\n\n for (i, _i) in enumerate(ind):\n T.append(scale * a[i] * np.vstack((sph[_i], -sph[_i])))\n if orient:\n Tor.append(sph[_i])\n if orient:\n return T, Tor\n return T\n\n\ndef slicer(ren, vol, voxsz=(1.0, 1.0, 1.0), affine=None, contours=1,\n planes=1, levels=[20, 30, 40], opacities=[0.8, 0.7, 0.3],\n colors=None, planesx=[20, 30], planesy=[30, 40], planesz=[20, 30]):\n ''' Slicer and contour rendering of 3d volumes\n\n Parameters\n ----------------\n vol : array, shape (N, M, K), dtype uint8\n An array representing the volumetric dataset that we want to visualize\n using volumetric rendering.\n voxsz : sequence of 3 floats\n Voxel size.\n affine : array, shape (4,4), default None\n As given by ``volumeimages``.\n contours : bool 1 to show contours\n Whether to show contours.\n planes : boolean 1 show planes\n Whether to show planes.\n levels : sequence\n Contour levels.\n opacities : sequence\n Opacity for every contour level.\n colors : None or sequence of 3-tuples\n Color for each contour level.\n planesx : (2,) array_like\n Saggital.\n planesy : (2,) array_like\n Coronal.\n planesz :\n Axial (2,) array_like\n\n Examples\n --------------\n >>> import numpy as np\n >>> from dipy.viz import fvtk\n >>> x, y, z = np.ogrid[-10:10:80j, -10:10:80j, -10:10:80j]\n >>> s = np.sin(x*y*z)/(x*y*z)\n >>> r=fvtk.ren()\n >>> #fvtk.slicer(r,s) #does showing too\n '''\n vol = np.interp(vol, xp=[vol.min(), vol.max()], fp=[0, 255])\n vol = vol.astype('uint8')\n\n im = vtk.vtkImageData()\n im.SetScalarTypeToUnsignedChar()\n im.SetDimensions(vol.shape[0], vol.shape[1], vol.shape[2])\n # im.SetOrigin(0,0,0)\n im.SetSpacing(voxsz[2], voxsz[0], voxsz[1])\n im.AllocateScalars()\n\n for i in range(vol.shape[0]):\n for j in range(vol.shape[1]):\n for k in range(vol.shape[2]):\n\n im.SetScalarComponentFromFloat(i, j, k, 0, vol[i, j, k])\n\n Contours = []\n for le in levels:\n # An isosurface, or contour value of 500 is known to correspond to the\n # skin of the patient. Once generated, a vtkPolyDataNormals filter is\n # is used to create normals for smooth surface shading during rendering.\n # The triangle stripper is used to create triangle strips from the\n # isosurface these render much faster on may systems.\n skinExtractor = vtk.vtkContourFilter()\n # skinExtractor.SetInputConnection(im.GetOutputPort())\n if major_version <= 5:\n skinExtractor.SetInput(im)\n else:\n skinExtractor.SetInputData(im)\n skinExtractor.SetValue(0, le)\n skinNormals = vtk.vtkPolyDataNormals()\n skinNormals.SetInputConnection(skinExtractor.GetOutputPort())\n skinNormals.SetFeatureAngle(60.0)\n skinStripper = vtk.vtkStripper()\n skinStripper.SetInputConnection(skinNormals.GetOutputPort())\n skinMapper = vtk.vtkPolyDataMapper()\n skinMapper.SetInputConnection(skinStripper.GetOutputPort())\n skinMapper.ScalarVisibilityOff()\n skin = vtk.vtkActor()\n skin.SetMapper(skinMapper)\n if colors == None:\n skin.GetProperty().SetDiffuseColor(1, .49, .25)\n else:\n colorskin = colors[le]\n skin.GetProperty().SetDiffuseColor(colorskin[0], colorskin[1], colorskin[2])\n skin.GetProperty().SetSpecular(.3)\n skin.GetProperty().SetSpecularPower(20)\n\n Contours.append(skin)\n\n # An outline provides context around the data.\n outlineData = vtk.vtkOutlineFilter()\n # outlineData.SetInputConnection(im.GetOutputPort())\n if major_version <= 5:\n outlineData.SetInput(im)\n else:\n outlineData.SetInputData(im)\n mapOutline = vtk.vtkPolyDataMapper()\n mapOutline.SetInputConnection(outlineData.GetOutputPort())\n outline = vtk.vtkActor()\n outline.SetMapper(mapOutline)\n outline.GetProperty().SetColor(1, 0, 0)\n\n # Now we are creating three orthogonal planes passing through the\n # volume. Each plane uses a different texture map and therefore has\n # diferent coloration.\n\n # Start by creatin a black/white lookup table.\n lut = vtk.vtkLookupTable()\n lut.SetTableRange(vol.min(), vol.max())\n lut.SetSaturationRange(0, 0)\n lut.SetHueRange(0, 0)\n lut.SetValueRange(0, 1)\n lut.SetRampToLinear()\n lut.Build()\n\n x1, x2, y1, y2, z1, z2 = im.GetExtent()\n\n # print x1,x2,y1,y2,z1,z2\n\n # Create the first of the three planes. The filter vtkImageMapToColors\n # maps the data through the corresponding lookup table created above.\n # The vtkImageActor is a type of vtkProp and conveniently displays an\n # image on a single quadrilateral plane. It does this using texture\n # mapping and as a result is quite fast. (Note: the input image has to\n # be unsigned char values, which the vtkImageMapToColors produces.)\n # Note also that by specifying the DisplayExtent, the pipeline\n # requests data of this extent and the vtkImageMapToColors only\n # processes a slice of data.\n planeColors = vtk.vtkImageMapToColors()\n # saggitalColors.SetInputConnection(im.GetOutputPort())\n if major_version <= 5:\n planeColors.SetInput(im)\n else:\n planeColors.SetInputData(im)\n planeColors.SetLookupTable(lut)\n planeColors.Update()\n\n saggitals = []\n for x in planesx:\n\n saggital = vtk.vtkImageActor()\n if major_version <= 5:\n saggital.SetInput(planeColors.GetOutput())\n else:\n saggital.SetInputData(planeColors.GetOutput())\n saggital.SetDisplayExtent(x, x, y1, y2, z1, z2)\n\n saggitals.append(saggital)\n\n axials = []\n for z in planesz:\n axial = vtk.vtkImageActor()\n if major_version <= 5:\n axial.SetInput(planeColors.GetOutput())\n else:\n axial.SetInputData(planeColors.GetOutput())\n axial.SetDisplayExtent(x1, x2, y1, y2, z, z)\n axials.append(axial)\n\n coronals = []\n for y in planesy:\n coronal = vtk.vtkImageActor()\n if major_version <= 5:\n coronal.SetInput(planeColors.GetOutput())\n else:\n coronal.SetInputData(planeColors.GetOutput())\n coronal.SetDisplayExtent(x1, x2, y, y, z1, z2)\n coronals.append(coronal)\n\n # It is convenient to create an initial view of the data. The FocalPoint\n # and Position form a vector direction. Later on (ResetCamera() method)\n # this vector is used to position the camera to look at the data in\n # this direction.\n aCamera = vtk.vtkCamera()\n aCamera.SetViewUp(0, 0, -1)\n aCamera.SetPosition(0, 1, 0)\n aCamera.SetFocalPoint(0, 0, 0)\n aCamera.ComputeViewPlaneNormal()\n\n # saggital.SetOpacity(0.1)\n\n # Actors are added to the renderer.\n ren.AddActor(outline)\n if planes:\n for sag in saggitals:\n ren.AddActor(sag)\n for ax in axials:\n ren.AddActor(ax)\n for cor in coronals:\n ren.AddActor(cor)\n\n if contours:\n cnt = 0\n for actor in Contours:\n actor.GetProperty().SetOpacity(opacities[cnt])\n ren.AddActor(actor)\n cnt += 1\n\n # Turn off bone for this example.\n # bone.VisibilityOff()\n\n # Set skin to semi-transparent.\n\n # An initial camera view is created. The Dolly() method moves\n # the camera towards the FocalPoint, thereby enlarging the image.\n ren.SetActiveCamera(aCamera)\n ren.ResetCamera()\n aCamera.Dolly(1.5)\n\n # Set a background color for the renderer and set the size of the\n # render window (expressed in pixels).\n ren.SetBackground(0, 0, 0)\n # renWin.SetSize(640, 480)\n\n # Note that when camera movement occurs (as it does in the Dolly()\n # method), the clipping planes often need adjusting. Clipping planes\n # consist of two planes: near and far along the view direction. The\n # near plane clips out objects in front of the plane the far plane\n # clips out objects behind the plane. This way only what is drawn\n # between the planes is actually rendered.\n # ren.ResetCameraClippingRange()\n\n # return ren\n\n renWin = vtk.vtkRenderWindow()\n renWin.AddRenderer(ren)\n iren = vtk.vtkRenderWindowInteractor()\n iren.SetRenderWindow(renWin)\n\n ren.ResetCameraClippingRange()\n\n # Interact with the data.\n iren.Initialize()\n renWin.Render()\n iren.Start()\n\n\ndef annotatePick(object, event):\n ''' Create a Python function to create the text for the\n text mapper used to display the results of picking.\n '''\n global picker, textActor, textMapper, track_buffer\n\n if picker.GetCellId() < 0:\n textActor.VisibilityOff()\n else:\n if len(track_buffer) != 0:\n\n selPt = picker.GetSelectionPoint()\n pickPos = picker.GetPickPosition()\n\n closest = _closest_track(np.array([pickPos[0], pickPos[1], pickPos[2]]), track_buffer)\n\n if major_version <= 5:\n textMapper.SetInput(\"(%.6f, %.6f, %.6f)\" % pickPos)\n else:\n textMapper.SetInputData(\"(%.6f, %.6f, %.6f)\" % pickPos)\n textActor.SetPosition(selPt[:2])\n textActor.VisibilityOn()\n\n label(tmp_ren, text=str(ind_buffer[closest]), pos=(track_buffer[closest][0][0], track_buffer[\n closest][0][1], track_buffer[closest][0][2]))\n\n tmp_ren.AddActor(line(track_buffer[closest], golden, opacity=1))\n\n\ndef show(ren, title='Dipy', size=(300, 300), png_magnify=1):\n ''' Show window\n\n Notes\n -----\n To save a screenshot press's' and check your current directory\n for ``fvtk.png``.\n\n Parameters\n ------------\n ren : vtkRenderer() object\n As returned from function ``ren()``.\n title : string\n A string for the window title bar.\n size : (int, int)\n ``(width, height)`` of the window\n png_magnify : int\n Number of times to magnify the screenshot.\n\n Notes\n -----\n If you want to:\n\n * navigate in the the 3d world use the left - middle - right mouse buttons\n * reset the screen press 'r'\n * save a screenshot press 's'\n * quit press 'q'\n\n See also\n ---------\n dipy.viz.fvtk.record\n\n Examples\n ----------\n >>> import numpy as np\n >>> from dipy.viz import fvtk\n >>> r=fvtk.ren()\n >>> lines=[np.random.rand(10,3),np.random.rand(20,3)]\n >>> colors=np.array([[0.2,0.2,0.2],[0.8,0.8,0.8]])\n >>> c=fvtk.line(lines,colors)\n >>> fvtk.add(r,c)\n >>> l=fvtk.label(r)\n >>> fvtk.add(r,l)\n >>> #fvtk.show(r)\n\n See also\n ----------\n dipy.viz.fvtk.record\n\n '''\n\n ren.ResetCamera()\n window = vtk.vtkRenderWindow()\n window.AddRenderer(ren)\n window.SetWindowName(title)\n window.SetSize(size[0], size[1])\n style = vtk.vtkInteractorStyleTrackballCamera()\n iren = vtk.vtkRenderWindowInteractor()\n iren.SetRenderWindow(window)\n iren.SetPicker(picker)\n\n def key_press(obj, event):\n\n key = obj.GetKeySym()\n if key == 's' or key == 'S':\n print('Saving image...')\n renderLarge = vtk.vtkRenderLargeImage()\n if major_version <= 5:\n renderLarge.SetInput(ren)\n else:\n renderLarge.SetInputData(ren)\n renderLarge.SetMagnification(png_magnify)\n renderLarge.Update()\n writer = vtk.vtkPNGWriter()\n writer.SetInputConnection(renderLarge.GetOutputPort())\n writer.SetFileName('fvtk.png')\n writer.Write()\n print('Look for fvtk.png in your current working directory.')\n\n iren.AddObserver('KeyPressEvent', key_press)\n iren.SetInteractorStyle(style)\n iren.Initialize()\n picker.Pick(85, 126, 0, ren)\n window.Render()\n iren.Start()\n\n # window.RemoveAllObservers()\n # ren.SetRenderWindow(None)\n window.RemoveRenderer(ren)\n ren.SetRenderWindow(None)\n\n\ndef record(ren=None, cam_pos=None, cam_focal=None, cam_view=None,\n out_path=None, path_numbering=False, n_frames=10, az_ang=10,\n magnification=1, size=(300, 300), bgr_color=(0, 0, 0),\n verbose=False):\n ''' This will record a video of your scene\n\n Records a video as a series of ``.png`` files of your scene by rotating the\n azimuth angle az_angle in every frame.\n\n Parameters\n -----------\n ren : vtkRenderer() object\n as returned from function ren()\n cam_pos : None or sequence (3,), optional\n camera position\n cam_focal : None or sequence (3,), optional\n camera focal point\n cam_view : None or sequence (3,), optional\n camera view up\n out_path : str, optional\n output directory for the frames\n path_numbering : bool\n when recording it changes out_path ot out_path + str(frame number)\n n_frames : int, optional\n number of frames to save, default 10\n az_ang : float, optional\n azimuthal angle of camera rotation.\n magnification : int, optional\n how much to magnify the saved frame\n\n Examples\n ---------\n >>> from dipy.viz import fvtk\n >>> r=fvtk.ren()\n >>> a=fvtk.axes()\n >>> fvtk.add(r,a)\n >>> #uncomment below to record\n >>> #fvtk.record(r)\n >>> #check for new images in current directory\n '''\n if ren == None:\n ren = vtk.vtkRenderer()\n ren.SetBackground(bgr_color)\n renWin = vtk.vtkRenderWindow()\n renWin.AddRenderer(ren)\n renWin.SetSize(size[0], size[1])\n iren = vtk.vtkRenderWindowInteractor()\n iren.SetRenderWindow(renWin)\n\n # ren.GetActiveCamera().Azimuth(180)\n\n ren.ResetCamera()\n\n renderLarge = vtk.vtkRenderLargeImage()\n if major_version <= 5:\n renderLarge.SetInput(ren)\n else:\n renderLarge.SetInputData(ren)\n renderLarge.SetMagnification(magnification)\n renderLarge.Update()\n\n writer = vtk.vtkPNGWriter()\n ang = 0\n\n if cam_pos != None:\n cx, cy, cz = cam_pos\n ren.GetActiveCamera().SetPosition(cx, cy, cz)\n if cam_focal != None:\n fx, fy, fz = cam_focal\n ren.GetActiveCamera().SetFocalPoint(fx, fy, fz)\n if cam_view != None:\n ux, uy, uz = cam_view\n ren.GetActiveCamera().SetViewUp(ux, uy, uz)\n\n cam = ren.GetActiveCamera()\n if verbose:\n print('Camera Position (%.2f,%.2f,%.2f)' % cam.GetPosition())\n print('Camera Focal Point (%.2f,%.2f,%.2f)' % cam.GetFocalPoint())\n print('Camera View Up (%.2f,%.2f,%.2f)' % cam.GetViewUp())\n\n for i in range(n_frames):\n ren.GetActiveCamera().Azimuth(ang)\n renderLarge = vtk.vtkRenderLargeImage()\n if major_version <= 5:\n renderLarge.SetInput(ren)\n else:\n renderLarge.SetInputData(ren)\n renderLarge.SetMagnification(magnification)\n renderLarge.Update()\n writer.SetInputConnection(renderLarge.GetOutputPort())\n # filename='/tmp/'+str(3000000+i)+'.png'\n if path_numbering:\n if out_path == None:\n filename = str(1000000 + i) + '.png'\n else:\n filename = out_path + str(1000000 + i) + '.png'\n else:\n filename = out_path\n writer.SetFileName(filename)\n writer.Write()\n\n ang = +az_ang\n\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"dipy/viz/fvtk.py","file_name":"fvtk.py","file_ext":"py","file_size_in_byte":61520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"532164747","text":"# -*- coding: utf-8 -*-\n\n\nimport pygame\nfrom pygame.sprite import Group\nfrom settings import Settings\nfrom ship import Ship\nfrom alien import Alien\nimport game_functions as gf\n\ndef run_game():\n #crear ventana\n pygame.init()\n \n # cargar configuracion del juego\n ai_settings = Settings()\n \n # crear una nueva pantalla\n screen = pygame.display.set_mode(\n (ai_settings.screen_width, ai_settings.screen_height))\n \n # crear una nueva navecita xD\n ship = Ship(ai_settings, screen)\n # hacer un grupo de bullets \n bullets = Group()\n # hacer un alien\n aliens = Group()\n \n # crear flota de aliens\n gf.create_fleet(ai_settings, screen, aliens)\n \n # poner titulo a la ventana\n pygame.display.set_caption(\"Alien Invasion\")\n \n \n #empezar el bucle del juego\n while True:\n # escuchar eventos del mouse y teclado\n gf.check_events(ai_settings, screen, ship, bullets)\n #actualizar la posicion de la nave del olvido\n ship.update()\n \n gf.update_bullets(bullets)\n \n # actualizar la pantalla \n gf.update_screen(ai_settings, screen, ship, aliens, bullets)\n \n \n \nrun_game()","sub_path":"alien_invasion.py","file_name":"alien_invasion.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"280798891","text":"#!/usr/bin/env python\n# -*- coding: euc-jp -*-\n\n##\n# @file ComponentObserverProvider.py\n# @brief test for ComponentObserverConsumer\n# @date $Date$\n# @author Shinji Kurihara\n#\n# Copyright (C) 2011\n# Noriaki Ando\n# Intelligent Systems Research Institute,\n# National Institute of\n# Advanced Industrial Science and Technology (AIST), Japan\n# All rights reserved.\n#\n\nimport sys\n\nfrom omniORB import CORBA, PortableServer\nimport RTC\nimport OpenRTM, OpenRTM__POA\nimport SDOPackage\nimport OpenRTM_aist\n\nclass ComponentObserver_i(OpenRTM__POA.ComponentObserver):\n def __init__(self):\n pass\n\n def update_status(self, status_kind, hint):\n print(\"update_status: \", status_kind, \", \", hint)\n return\n\ndef main():\n orb = CORBA.ORB_init(sys.argv)\n poa = orb.resolve_initial_references(\"RootPOA\")\n poa._get_the_POAManager().activate()\n naming = OpenRTM_aist.CorbaNaming(orb, \"localhost\")\n servant = ComponentObserver_i()\n oid = poa.servant_to_id(servant)\n provider = poa.id_to_reference(oid)\n\n rtc = naming.resolve(\"COCTestRTC0.rtc\")._narrow(RTC.RTObject)\n config = rtc.get_configuration()\n properties = [OpenRTM_aist.NVUtil.newNV(\"heartbeat.enable\",\"YES\"),\n OpenRTM_aist.NVUtil.newNV(\"heartbeat.interval\",\"10\"),\n OpenRTM_aist.NVUtil.newNV(\"observed_status\",\"ALL\")]\n\n id = OpenRTM_aist.toTypename(servant)\n sprof = SDOPackage.ServiceProfile(\"test_id\", id,\n properties, provider)\n\n ret = config.add_service_profile(sprof)\n flag = True\n print(\"If you exit program, please input 'q'.\")\n sys.stdin.readline()\n ret = config.remove_service_profile(\"test_id\")\n print(\"test program end. ret : \", ret)\n return\n \n############### test #################\nif __name__ == '__main__':\n main()\n","sub_path":"OpenRTM_aist/ext/sdo/observer/test/ComponentObserverProvider.py","file_name":"ComponentObserverProvider.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"494089242","text":"\nimport pytest\n\nfrom trafficgenerator.tgn_utils import ApiType\n\n\ndef pytest_addoption(parser):\n parser.addoption('--api', action='store', default='rest', help='api options: rest or tcl')\n parser.addoption('--server', action='store', default='localhost:11009', help='REST server in format ip:port')\n parser.addoption('--chassis', action='store', default='192.168.42.217', help='chassis IP address')\n parser.addoption('--port1', action='store', default='1/1', help='module1/port1')\n parser.addoption('--port2', action='store', default='1/2', help='module2/port2')\n\n\n@pytest.fixture\ndef api(request):\n request.cls.api = ApiType[request.param]\n\n\ndef pytest_generate_tests(metafunc):\n if metafunc.config.getoption('--api') == 'all':\n apis = ['tcl', 'rest']\n else:\n apis = [metafunc.config.getoption('--api')]\n metafunc.parametrize('api', apis, indirect=True)\n","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"84078649","text":"import json\nimport datetime\nimport psycopg2\nimport logging\nimport os\nfrom r import r\n\n# connect to postgres\nconnection = psycopg2.connect(\"dbname='filesystem' host='localhost'\")\n\n# file extension jazz\ncwd = os.getcwd()\nbad_extensions = {'swp', 'pyc', 'log'}\nbad_extensions_path = os.path.join(cwd, 'bad_extensions.txt')\nbad_dirs = {'node_modules', 'venv', '__pycache__'}\nbad_dirs_path = os.path.join(cwd, 'bad_dirs.txt')\ngood_extensions = {'py', 'txt'}\ngood_extensions_path = os.path.join(cwd, 'good_extensions.txt')\n\ndef walk_and_save(base_path, verbose=False):\n for root, dirs, files in os.walk(base_path):\n dirs[:] = [d for d in dirs if '.' not in d and d not in bad_dirs]\n for name in files:\n path = os.path.join(root, name)\n if verbose:\n print(path)\n _look_for_shitty_extensions(path)\n if extract_extension(path) in good_extensions:\n process_path(path=path)\n\ndef process_path(*, path):\n new_file_contents = open(path, 'r').readlines()\n save_file_to_db(path=path, contents=new_file_contents)\n old_file_contents = read_file_from_db(path)\n if old_file_contents:\n publish_changed_file(path=path, old=old_file_contents, new=new_file_contents)\n else:\n publish_new_file(path=path, new=new_file_contents)\n\ndef publish_changed_file(*, path, old, new):\n changes = num_lines_changed(old=old, new=new)\n message_data = {\n 'time': datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"),\n 'path': path,\n 'changes': changes,\n }\n message = '{time} -- {path} -- {changes} lines changed'.format(**message_data)\n r.publish('file.changed', message)\n\ndef publish_new_file(*, path, new):\n message_data = {\n 'time': datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"),\n 'path': path,\n 'changes': 'new file',\n }\n message = '{time} -- {path} -- {changes}'.format(**message_data)\n r.publish('file.new', message)\n\ndef delete_db():\n cursor = connection.cursor()\n cursor.execute(\"delete from files\")\n connection.commit()\n cursor.close()\n\ndef save_file_to_db(*, path, contents):\n \"\"\" executes an \"upsert\" \"\"\"\n cursor = connection.cursor()\n contents = json.dumps(contents)\n statement = \"\"\"\n update files set contents=%(contents)s where path=%(path)s;\n insert into files (path, contents)\n select %(path)s, %(contents)s\n where not exists (select 1 from files where path=%(path)s);\n \"\"\"\n cursor.execute(statement, {'path': path, 'contents': contents})\n connection.commit()\n cursor.close()\n\ndef read_file_from_db(path):\n cursor = connection.cursor()\n cursor.execute(\"select contents from files where path=(%s);\", (path,))\n record = cursor.fetchone()\n record = record[0]\n cursor.close()\n return json.loads(record)\n\ndef num_lines_changed(old, new):\n return len(set(old).union(set(new))) - len(set(old))\n\ndef extract_extension(path):\n return path.split('.')[-1] if (path.count('.') == 1) else path.split('/')[-1]\n\ndef _look_for_shitty_extensions(path):\n extension = extract_extension(path)\n if extension in bad_extensions or extension in good_extensions:\n return\n try:\n f = open(path, 'r')\n lines = f.read()\n # if reading succeeds, it's a readable extension\n good_extensions.add(extension)\n except UnicodeDecodeError as e:\n bad_extensions.add(extension)\n\ndef write_to_disk(data, destination):\n previous = open(destination, 'r').read().split('\\n')\n data = set(previous).union(set(data))\n with open(destination, 'a') as f:\n f.write('\\n'.join(data))\n\nif __name__ == '__main__':\n # for now, delete db contents and log files each time\n #delete_db()\n for path in [bad_extensions_path, bad_dirs_path, good_extensions_path]:\n open(path, 'w').close(),\n walk_and_save('/Users/Justin/Code/Projects')\n write_to_disk(good_extensions, good_extensions_path)\n write_to_disk(bad_extensions, bad_extensions_path)\n connection.close()\n\n","sub_path":"stream/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":4036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"34440","text":"import mxnet as mx\nfrom mxnet.gluon import Block\n\nfrom core.utils.dataprocessing.targetFunction.encoder import ClassEncoder, BoxEncoder\nfrom core.utils.dataprocessing.targetFunction.matching import MatchSampler\n\n\nclass TargetGenerator(Block):\n\n def __init__(self, foreground_iou_thresh=0.5, stds=(0.1, 0.1, 0.2, 0.2), means=(0., 0., 0., 0.)):\n super(TargetGenerator, self).__init__()\n self._matchsampler = MatchSampler(foreground_iou_thresh=foreground_iou_thresh)\n self._cls_encoder = ClassEncoder()\n self._box_encoder = BoxEncoder(stds=stds, means=means)\n\n def forward(self, anchors, gt_boxes, gt_ids):\n \"\"\"Generate training targets.\"\"\"\n anchors_corner, matches, samples = self._matchsampler(anchors, gt_boxes)\n cls_targets = self._cls_encoder(matches, samples, gt_ids)\n box_targets = self._box_encoder(matches, samples, anchors_corner, gt_boxes)\n return cls_targets, box_targets\n\n\n# test\nif __name__ == \"__main__\":\n from core import SSD_VGG16, SSDTrainTransform, DetectionDataset\n import os\n\n input_size = (512, 512)\n root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n transform = SSDTrainTransform(input_size[0], input_size[1], make_target=False)\n dataset = DetectionDataset(path=os.path.join(root, 'Dataset', 'train'), transform=transform)\n num_classes = dataset.num_class\n image, label, _, _, _ = dataset[0]\n label = mx.nd.array(label)\n\n net = SSD_VGG16(version=512, input_size=input_size,\n # box_sizes=[21, 45, 101.25, 157.5, 213.75, 270, 326.25],\n box_sizes=[21, 51.2, 133.12, 215.04, 296.96, 378.88, 460.8, 542.72],\n # box_ratios=[[1, 2, 0.5]] + # conv4_3\n # [[1, 2, 0.5, 3, 1.0 / 3]] * 3 + # conv7, conv8_2, conv9_2\n # [[1, 2, 0.5]] * 2, # conv10_2, conv11_2\n box_ratios=[[1, 2, 0.5]] + # conv4_3\n [[1, 2, 0.5, 3, 1.0 / 3]] * 4 + # conv7, conv8_2, conv9_2, conv10_2\n [[1, 2, 0.5]] * 2, # conv11_2, conv12_2\n num_classes=num_classes,\n pretrained=False,\n pretrained_path=os.path.join(root, \"modelparam\"),\n anchor_box_offset=(0.5, 0.5),\n anchor_box_clip=True,\n ctx=mx.cpu())\n\n net.hybridize(active=True, static_alloc=True, static_shape=True)\n\n targetgenerator = TargetGenerator(foreground_iou_thresh=0.5, stds=(0.1, 0.1, 0.2, 0.2), means=(0., 0., 0., 0.))\n\n # batch 형태로 만들기\n image = image.expand_dims(axis=0)\n label = label.expand_dims(axis=0)\n\n gt_boxes = label[:, :, :4]\n gt_ids = label[:, :, 4:5]\n _, _, anchors = net(image)\n cls_targets, box_targets = targetgenerator(anchors, gt_boxes, gt_ids)\n print(f\"cls_targets shape : {cls_targets.shape}\")\n print(f\"box_targets shape : {box_targets.shape}\")\n '''\n cls_targets shape : (1, 24564)\n box_targets shape : (1, 24564, 4)\n '''\n","sub_path":"SSD/core/utils/dataprocessing/target.py","file_name":"target.py","file_ext":"py","file_size_in_byte":3105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"201547529","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\n\nfrom swagger_server.models.connection_def import ConnectionDef\nfrom swagger_server.models.info_def import InfoDef\nfrom swagger_server.models.demo_graphic_def import DemoGraphicDef\nfrom swagger_server.models.connection_def import ConnectionDef\nfrom swagger_server.models.info_def import InfoDef\nfrom swagger_server.encoder import JSONEncoder\nimport connexion\nfrom flask import json\nfrom flask_testing import TestCase\nimport logging\nimport os\nimport requests\nfrom six import BytesIO\n\n# see https://pythonhosted.org/Flask-Testing/\n\nclass BaseTestCase(TestCase):\n\n def create_app(self):\n logging.getLogger('connexion.operation').setLevel('ERROR')\n app = connexion.App(__name__, specification_dir='../swagger/')\n app.app.json_encoder = JSONEncoder\n app.add_api('swagger.yaml')\n return app.app\n\n\n\nclass TestDefaultController(BaseTestCase):\n\n def test_authen_post(self):\n\n if os.environ.get(\"service_key\"):\n service_key=os.environ.get(\"service_key\")\n else:\n service_key = input('Enter service_key: ')\n if not service_key:\n raise Exception('Environment variable service_key not set')\n \n if os.environ.get(\"service_secret\"):\n service_secret=os.environ.get(\"service_secret\")\n else:\n service_secret = input('Enter service_secret: ')\n if not service_secret:\n raise Exception('Environment variable service_secret not set')\n\n timezone='UTC+09'\n user_id='TESTer'\n user_ip_address='10.12.3.1'\n\n dgList = []\n dg = DemoGraphicDef(name = 'city',\n value = 'Los Angeles')\n dgList.append(dg)\n dg = DemoGraphicDef(name = 'zipcode',\n value = '91355')\n dgList.append(dg)\n\n userInfo = InfoDef(service_key=service_key, \n service_secret=service_secret,\n user_id=user_id,\n user_ip_address=user_ip_address, \n timezone=timezone, \n demo_graphics=dgList\n )\n \n# url='http://localhost:5000/v1/authen'\n url='https://njih7nw2d0.execute-api.us-east-1.amazonaws.com/production' + '/v1/authen'\n \n response = requests.post(url,json=json.dumps(userInfo))\n \n print(response)\n if response.status_code == 200:\n print(response.json())\n\nif __name__ == '__main__': \n import unittest\n unittest.main()\n","sub_path":"python-flask-server/swagger_server/test/test_default_controller.py","file_name":"test_default_controller.py","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"332845301","text":"from modules import *\nfrom osgeo import ogr\n\nif __name__ == '__main__':\n\n folder = \"C:/Users/rm885/Dropbox/projects/NAU/landsat_deciduous/data/SAMPLES/gee_extract/\"\n samp_file = folder + \"gee_samp_extract_short_v2019_01_21T01_49_06.csv\"\n\n samp_data = Handler(filename=samp_file).read_from_csv(return_dicts=True)\n\n print(len(samp_data))\n print(samp_data[0])\n sites = list(set(list(samp['site']\n for samp in samp_data)))\n\n print(len(sites))\n\n vec = Vector(in_memory=True,\n name='gee_vec',\n geom_type='point',\n primary_key=None,\n attr_def={'site': 'str',\n 'decid_frac': 'float',\n 'year': 'int'},\n epsg=4326)\n\n print(vec)\n for site in sites:\n for samp in samp_data:\n if samp['site'] == site:\n feat_dict = dict()\n\n lat = samp['latitude']\n lon = samp['longitude']\n\n wkt = vec.wkt_from_coords((lon, lat),\n geom_type='point')\n\n geom = ogr.CreateGeometryFromWkt(wkt)\n\n feat_dict['site'] = site\n feat_dict['decid_frac'] = samp['decid_frac']\n feat_dict['year'] = samp['year']\n\n vec.add_feat(geom,\n primary_key=None,\n attr=feat_dict)\n\n break\n print(vec)\n vec.write_vector(folder + 'gee_ran_samp_vector.shp')\n\n\n\n\n\n","sub_path":"samples/landsat_samp_data.py","file_name":"landsat_samp_data.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"251960627","text":"from __future__ import print_function\nimport logging\nfrom scrapy.responsetypes import responsetypes\nfrom scrapy.utils.request import request_fingerprint\nfrom scrapy.utils.python import to_bytes\nfrom scrapy.http.headers import Headers\nfrom datetime import datetime\nfrom invana_bot.settings import DATA_COLLECTION, DATABASE\nfrom invana_bot.utils.url import get_urn, get_domain\nimport pysolr\n\nlogger = logging.getLogger(__name__)\n\n\nclass SolrCacheStorage(object):\n \"\"\"\n should set HTTPCACHE_ES_DATABASE in the settings.py\n\n\n \"\"\"\n COLLECTION_NAME = \"web_link\"\n\n solr_date_fields = [\n 'headers_Last-Modified',\n 'headers_Expires',\n 'headers_Date',\n 'created'\n ]\n\n solr_int_fields = [\n 'status',\n 'headers_X-Cache-Hits'\n ]\n\n solr_content_fields = [\n\n 'description',\n 'content'\n ]\n\n def __init__(self, settings):\n self.core_name = settings['COLLECTION_NAME']\n self.solr_host = settings.get('HTTPCACHE_HOST', '127.0.0.1')\n self.port = settings.get('HTTPCACHE_SOLR_PORT', '8983')\n\n self.solr = pysolr.Solr('http://{0}:{1}/solr/{2}'.format(self.solr_host, self.port, DATA_COLLECTION),\n timeout=10)\n self.expiration_secs = settings.getint('HTTPCACHE_EXPIRATION_SECS')\n\n def open_spider(self, spider):\n logger.debug(\"Using solr cache storage with core name %(core_name)s\" % {'core_name': self.core_name},\n extra={'spider': spider})\n\n def close_spider(self, spider):\n pass\n\n def get_headers(self, obj):\n \"\"\"\n this will convert all the headers_Server, headers_Date\n into \"header\": {\n \"Server\": \"\",\n \"Date\": \"\"\n }\n\n :param obj:\n :return:\n \"\"\"\n headers = {}\n for k, v in obj.items():\n if k.startswith(\"headers_\"):\n headers[k.replace(\"headers_\", \"\").rstrip(\"_s\").rstrip(\"_i\").rstrip(\"_dt\")] = v\n\n obj['headers'] = headers\n return obj\n\n def retrieve_response(self, spider, request):\n data = self._read_data(spider, request)\n\n if data is None:\n return # not cached\n else:\n if data['status_i'] == 200 and data['html'] is None:\n return None\n\n data = self.get_headers(data)\n url = data['url_s']\n status = data['status_i']\n headers = Headers(data['headers'])\n body = bytes(data['html'][0], encoding=\"utf-8\")\n respcls = responsetypes.from_args(headers=headers, url=url)\n response = respcls(url=url, headers=headers, status=status, body=body)\n return response\n\n def _clean_headers(self, obj):\n cleaned_object = {}\n for k, v in obj.items():\n cleaned_object[k.decode('utf-8')] = v[0].decode('utf-8')\n return cleaned_object\n\n def _flatten_headers(self, obj):\n flat_data = {}\n for k, v in obj.items():\n flat_data['headers_{}'.format(k)] = v\n return flat_data\n\n def handle_date(self, v):\n new_v = None\n try:\n if type(v) == str:\n if \"+\" in v:\n v = v.split(\"+\")[0].strip()\n else:\n v = v.replace(\"GMT\", \"\").strip()\n new_v = datetime.strptime(v, '%a, %d %b %Y %H:%M:%S')\n else:\n new_v = v\n except Exception as e:\n pass\n return new_v\n\n def map_to_solr_datatypes(self, data):\n mapped_data = {}\n for k, v in data.items():\n if k in self.solr_date_fields:\n new_v = self.handle_date(v)\n if new_v:\n mapped_data[\"{}_dt\".format(k)] = new_v\n\n elif k in self.solr_int_fields:\n mapped_data[\"{}_i\".format(k)] = v\n else:\n if k in self.solr_content_fields:\n mapped_data[\"{}\".format(k)] = v\n else:\n mapped_data[\"{}_s\".format(k)] = v\n\n if \"html_s\" in mapped_data:\n mapped_data['html'] = mapped_data['html_s']\n del mapped_data['html_s']\n return mapped_data\n\n def clean_str(self, url):\n return url.replace(\".\", \"-\").replace(\":\", \"-\")\n\n def store_response(self, spider, request, response):\n data = {\n 'status': response.status,\n 'domain': get_domain(response.url),\n 'url': response.url,\n 'html': str(response.body).lstrip(\"b'\").strip(\"'\")\n .replace(\"\\\\n\", \"\")\n .replace(\"\\\\t\", \"\")\n .replace(\"\\\\\\\\\", \"\\\\\"),\n 'created': datetime.now()\n }\n data.update(self._flatten_headers(self._clean_headers(response.headers)))\n\n data = self.map_to_solr_datatypes(data=data)\n data['id'] = self.clean_str(get_urn(response.url))\n\n self.solr.add([data])\n\n def _read_data(self, spider, request):\n try:\n result = self.solr.search(q='id:{}'.format(self.clean_str(get_urn(request.url))))\n doc = result.docs[0]\n return doc\n except Exception as e:\n return None\n\n def _request_key(self, request):\n return to_bytes(request_fingerprint(request))\n","sub_path":"invana_bot/httpcache/solr.py","file_name":"solr.py","file_ext":"py","file_size_in_byte":5279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"144848730","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport unittest\n\nfrom gabbi import runner\nfrom gabbi import suitemaker\nfrom gabbi import utils\nfrom tempest import config\nfrom tempest.scenario import manager\n\nTEST_DIR = os.path.join(os.path.dirname(__file__), '..', '..',\n 'integration', 'gabbi', 'gabbits-live')\n\n\nclass TestTelemetryIntegration(manager.ScenarioTest):\n credentials = ['admin', 'primary']\n\n TIMEOUT_SCALING_FACTOR = 5\n\n @classmethod\n def skip_checks(cls):\n super(TestTelemetryIntegration, cls).skip_checks()\n for name in [\"aodh_plugin\", \"gnocchi\", \"nova\", \"heat\", \"panko\",\n \"ceilometer\", \"glance\"]:\n cls._check_service(name)\n\n @classmethod\n def _check_service(cls, name):\n if not getattr(config.CONF.service_available, name, False):\n raise cls.skipException(\"%s support is required\" %\n name.capitalize())\n\n @staticmethod\n def _get_endpoint(auth, service):\n opt_section = getattr(config.CONF, service)\n endpoint_type = opt_section.endpoint_type\n is_keystone_v3 = 'catalog' in auth[1]\n\n if is_keystone_v3:\n if endpoint_type.endswith(\"URL\"):\n endpoint_type = endpoint_type[:-3]\n catalog = auth[1]['catalog']\n endpoints = [e['endpoints'] for e in catalog\n if e['type'] == opt_section.catalog_type]\n if not endpoints:\n raise Exception(\"%s endpoint not found\" %\n opt_section.catalog_type)\n endpoints = [e['url'] for e in endpoints[0]\n if e['interface'] == endpoint_type]\n if not endpoints:\n raise Exception(\"%s interface not found for endpoint %s\" %\n (endpoint_type,\n opt_section.catalog_type))\n return endpoints[0]\n\n else:\n if not endpoint_type.endswith(\"URL\"):\n endpoint_type += \"URL\"\n catalog = auth[1]['serviceCatalog']\n endpoints = [e for e in catalog\n if e['type'] == opt_section.catalog_type]\n if not endpoints:\n raise Exception(\"%s endpoint not found\" %\n opt_section.catalog_type)\n return endpoints[0]['endpoints'][0][endpoint_type]\n\n def _do_test(self, filename):\n admin_auth = self.os_admin.auth_provider.get_auth()\n auth = self.os_primary.auth_provider.get_auth()\n networks = self.os_primary.networks_client.list_networks(\n **{'router:external': False, 'fields': 'id'})['networks']\n\n os.environ.update({\n \"ADMIN_TOKEN\": admin_auth[0],\n \"USER_TOKEN\": auth[0],\n \"AODH_GRANULARITY\": str(config.CONF.telemetry.alarm_granularity),\n \"AODH_SERVICE_URL\": self._get_endpoint(auth, \"alarming_plugin\"),\n \"GNOCCHI_SERVICE_URL\": self._get_endpoint(auth, \"metric\"),\n \"PANKO_SERVICE_URL\": self._get_endpoint(auth, \"event\"),\n \"HEAT_SERVICE_URL\": self._get_endpoint(auth, \"orchestration\"),\n \"NOVA_SERVICE_URL\": self._get_endpoint(auth, \"compute\"),\n \"GLANCE_SERVICE_URL\": self._get_endpoint(auth, \"image\"),\n \"GLANCE_IMAGE_NAME\": self.glance_image_create(),\n \"NOVA_FLAVOR_REF\": config.CONF.compute.flavor_ref,\n \"NEUTRON_NETWORK\": networks[0].get('id'),\n })\n\n with open(os.path.join(TEST_DIR, filename)) as f:\n test_suite = suitemaker.test_suite_from_dict(\n loader=unittest.defaultTestLoader,\n test_base_name=\"gabbi\",\n suite_dict=utils.load_yaml(f),\n test_directory=TEST_DIR,\n host=None, port=None,\n fixture_module=None,\n intercept=None,\n handlers=runner.initialize_handlers([]),\n test_loader_name=\"tempest\")\n\n # NOTE(sileht): We hide stdout/stderr and reraise the failure\n # manually, tempest will print it itself.\n with open(os.devnull, 'w') as stream:\n result = unittest.TextTestRunner(\n stream=stream, verbosity=0, failfast=True,\n ).run(test_suite)\n\n if not result.wasSuccessful():\n failures = (result.errors + result.failures +\n result.unexpectedSuccesses)\n if failures:\n test, bt = failures[0]\n name = test.test_data.get('name', test.id())\n msg = 'From test \"%s\" :\\n%s' % (name, bt)\n self.fail(msg)\n\n self.assertTrue(result.wasSuccessful())\n\n\ndef test_maker(name, filename):\n def test(self):\n self._do_test(filename)\n test.__name__ = name\n return test\n\n\n# Create one scenario per yaml file\nfor filename in os.listdir(TEST_DIR):\n if not filename.endswith('.yaml'):\n continue\n name = \"test_%s\" % filename[:-5].lower().replace(\"-\", \"_\")\n setattr(TestTelemetryIntegration, name,\n test_maker(name, filename))\n","sub_path":"ceilometer/tests/tempest/scenario/test_telemetry_integration.py","file_name":"test_telemetry_integration.py","file_ext":"py","file_size_in_byte":5747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"606062227","text":"\n\ndef get_docker_disk_usage_facts(self):\n try:\n if self.verbose_output:\n return self.client.df()\n else:\n return dict(LayersSize=self.client.df()['LayersSize'])\n except APIError as exc:\n self.client.fail(('Error inspecting docker host: %s' % to_native(exc)))\n","sub_path":"Data Set/bug-fixing-2/97ebc9578407989395616052d2b4a592780422fe--fix.py","file_name":"97ebc9578407989395616052d2b4a592780422fe--fix.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"207427299","text":"import time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\nmonths = ['january', 'february', 'march', 'april', 'may', 'june']\n\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Hello! Let\\'s explore some US bikeshare data!')\n print('-'*40)\n # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n while True:\n try:\n city = input('Which city do you like to analyze? Please choose a city from chicago, '\n 'new york city, or washington: ').lower()\n if city not in CITY_DATA.keys():\n raise ValueError\n break\n except ValueError:\n print('That\\'s not a valid input, please enter a city name again.\\n')\n\n print('-'*40)\n # get user input for month (all, january, february, ... , june)\n while True:\n try:\n month = input('Which month do you like to analyze? Please enter a month name from january to june, '\n 'or \"all\" to select all months: ').lower()\n if month not in ['january', 'february', 'march', 'april', 'may', 'june', 'all']:\n raise ValueError\n break\n except ValueError:\n print('That\\'s not a valid input, please enter a month name again, or \"all\" to select all months.\\n')\n\n print('-'*40)\n # get user input for day of week (all, monday, tuesday, ... sunday)\n while True:\n try:\n day = input('Which day of week do you like to analyze? Please enter a weekday name from monday to sunday, '\n 'or \"all\" to select the entire week: ').lower()\n if day not in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'all']:\n raise ValueError\n break\n except ValueError:\n print('That\\'s not a valid input, please enter a weekday name again, or \"all\" to select the entire week.\\n')\n\n\n print('-'*40)\n return city, month, day\n\n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n # load data file into a dataframe\n df = pd.read_csv(CITY_DATA[city])\n\n # convert the Start Time column to datetime\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n # extract month and day of week from Start Time to create new columns\n df['month'] = df['Start Time'].dt.month\n df['day_of_week'] = df['Start Time'].dt.weekday_name\n\n\n # filter by month if applicable\n if month != 'all':\n # use the index of the months list to get the corresponding int\n month = months.index(month) + 1\n\n # filter by month to create the new dataframe\n df = df[df['month'] == month]\n\n # filter by day of week if applicable\n if day != 'all':\n # filter by day of week to create the new dataframe\n df = df[df['day_of_week'] == day.title()]\n\n return df\n\n\n\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n # display the most common month\n if len(df['month'].unique()) > 1:\n max_idx = df.groupby('month')['Start Time'].count().idxmax() - 1\n print('The most popular month of travel is', months[max_idx])\n else:\n max_idx = df['month'].values[0] - 1\n print(\"You have filtered the data to contain only month {}\".format(months[max_idx].title()))\n\n # display the most common day of week\n if len(df['day_of_week'].unique()) > 1:\n print('The most popular day of week of travel is',\n df.groupby('day_of_week')['Start Time'].count().idxmax())\n else:\n print(\"You have filtered the data to contain only {}\".format(df['day_of_week'].values[0]))\n\n # display the most common start hour\n df['hour'] = df['Start Time'].dt.hour\n max_hour = df.groupby('hour')['Start Time'].count().idxmax()\n if max_hour == 0:\n print('The most popular hour of day of travel is 12 AM')\n elif 0 < max_hour < 12:\n print('The most popular hour of day of travel is', max_hour, 'AM')\n elif max_hour == 12:\n print('The most popular hour of day of travel is', max_hour, 'PM')\n else:\n print('The most popular hour of day of travel is', max_hour-12, 'PM')\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n # display most commonly used start station\n print('The most commonly used start station is', df['Start Station'].mode()[0])\n\n # display most commonly used end station\n print('The most commonly used end station is', df['End Station'].mode()[0])\n\n # display most frequent combination of start station and end station trip\n df['start_end_station'] = df['Start Station'] + ' and ' + df['End Station']\n print('The most frequent combination of start station and end station trip is',\n df['start_end_station'].mode()[0])\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n # display total travel time\n print('The total time people spent on the trip are', df['Trip Duration'].sum()/(3600*24),\n 'days')\n\n # display mean travel time\n print('The average time people spent on the trip are', df['Trip Duration'].mean()/60,\n 'minutes')\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n # Display counts of user types\n user_count = df['User Type'].value_counts()\n print('There are', len(user_count), 'types of users. '\n 'Their counts are as follows:')\n for i in range(len(user_count)):\n print(user_count.index[i],': ',user_count[i])\n\n # Display counts of gender\n if 'Gender' in df.columns:\n gender_count = df['Gender'].value_counts()\n print('The gender counts are as follows:')\n for i in range(len(gender_count)):\n print(gender_count.index[i],': ',gender_count[i])\n\n # Display earliest, most recent, and most common year of birth\n if 'Birth Year' in df.columns:\n print('The earliest year of birth is', int(df['Birth Year'].min()))\n print('The most recent year of birth is', int(df['Birth Year'].max()))\n print('The most common year of birth is', int(df['Birth Year'].mode()[0]))\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef print_lines_generator(df):\n \"\"\" This is a generator function to yield 5 lines of dataframe sequentially \"\"\"\n i = 0\n while(i < df.shape[0] - 5):\n pd.set_option('display.max_columns', None) # display all columns\n yield df.iloc[i:i+5,]\n i += 5\n if i >= df.shape[0] - 5:\n yield df.iloc[i:,]\n\n\ndef print_lines(df):\n \"\"\" Prompt the user for input to print 5 lines of raw data sequentially \"\"\"\n gen_fun = print_lines_generator(df)\n while True:\n try:\n lines = input('Do you want to see 5 lines of raw data? Please type yes or no: ').lower()\n if lines == 'yes':\n try:\n print(next(gen_fun))\n except StopIteration:\n print('You have reached the end of this file. Exiting...')\n break\n elif lines == 'no':\n break\n else:\n raise ValueError\n except ValueError:\n print('That\\'s not a valid input! Please enter yes or no.\\n')\n\n\ndef get_restart_prompt():\n \"\"\" This function is used to prompt for user input about whether to restart the program \"\"\"\n while True:\n try:\n restart = input('\\nWould you like to restart? Enter yes or no.\\n').lower()\n if restart in ['yes' , 'no']:\n return restart\n else:\n raise ValueError\n except ValueError:\n print('Sorry. I cannot understand what you mean.')\n\ndef main():\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n print_lines(df)\n\n if get_restart_prompt() == 'yes':\n continue\n else:\n print('Thank you for your interests in our US Bike Share data. Have a great day and goodbye~~~~~~')\n break\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":9694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"534063803","text":"from flask import Flask, render_template, Response\nfrom streamer import Streamer\nfrom udp_streamer import Streamer as UdpStreamer\n\napp = Flask(__name__)\n\ndef gen():\n streamer = Streamer('10.0.0.220', 8080)\n streamer.start()\n\n while True:\n if streamer.streaming:\n yield (b'--frame\\r\\n'b'Content-Type: image/jpeg\\r\\n\\r\\n' + streamer.get_jpeg() + b'\\r\\n\\r\\n')\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/video_feed')\ndef video_feed():\n return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')\n\ndef udp_gen(streamer):\n while streamer.streaming:\n yield (b'--frame\\r\\n'b'Content-Type: image/jpeg\\r\\n\\r\\n' + streamer.get_jpeg() + b'\\r\\n\\r\\n')\n\n@app.route('/udp_video_feed')\ndef udp_video_feed():\n streamer = UdpStreamer(\"10.0.0.220\", 8081)\n generator = (b'--frame\\r\\nContent-Type: image/jpeg\\r\\n\\r\\n' + jpeg_bytes + \n b'\\r\\n\\r\\n'for jpeg_bytes in streamer.get())\n return Response(generator, mimetype='multipart/x-mixed-replace; boundary=frame')\n\n@app.route('/udp_streaming')\ndef udp_streaming():\n return render_template('udp_streaming.html')\n\nif __name__ == '__main__':\n app.run(host='10.0.0.220', threaded=True)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"484331095","text":"def anagrams(filename):\n with open(filename,'r') as f:\n txt=f.read()\n words=txt.split()\n list1=charsets(words)\n d={}\n for charset in list1:\n listout=[]\n for word in words:\n flag=True\n for items in charset:\n flag = flag and (items in word)\n if flag == True:\n listout.append(word)\n d[charset]=listout\n for keys in d:\n print(d[keys])\n\ndef anagrams2(filename):\n with open(filename,'r') as f:\n txt=f.read()\n words=txt.split()\n list1=charsets(words)\n d={}\n for charset in list1:\n listout=[]\n for word in words:\n flag=True\n for items in charset:\n flag = flag and (items in word)\n if flag == True:\n listout.append(word)\n d[charset]=listout\n list1=[]\n for keys in d:\n list1.append(d[keys])\n list2=sorted(list1, key=len, reverse=True)\n for items in list2:\n print(items)\n\ndef charsets(words):\n list1=[]\n for word in words:\n t=()\n for n in range(len(word)):\n t+=(word[n],)\n list1.append(t)\n list2=[]\n for tuples in list1:\n list2.append(tuple(sorted(tuples)))\n list1=list(set(list2))\n return list1\n\ndef main():\n print('\\nPart1: \\n')\n anagrams('anagram.txt')\n print('\\n\\nPart2: \\n')\n anagrams2('anagram.txt')\n\nif __name__ == '__main__':\n main()\n","sub_path":"HW09_ch12_ex02.py","file_name":"HW09_ch12_ex02.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"480213968","text":"\"\"\"\r\nLab Test\r\n(AI CSC3206 Semester March 2020)\r\n\r\nName: Leong Wen Hao \r\nStudent ID: 17003906\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nfrom sklearn import datasets\r\nimport matplotlib.pyplot as pt\r\n\r\n# import glass.csv as DataFrame\r\ndata = pd.read_csv(\"glass.csv\", names=[\"Id\", \"RI\", \"Na\", \"Mg\", \"Al\", \"Si\", \"K\", \"Ca\", \"Ba\", \"Fe\", \"Glass type\"], index_col=0)\r\n\r\n''' Instructions\r\n1. split the data into 70% training and 30% testing data\r\n - use Na, Mg, Al, Si, K, Ca, Ba, and Fe (i.e. all columns except Glass type) as the input features.\r\n - use Glass type as the target attribute.\r\n\r\n2. plot the accuracy of knn classifiers for all odd value of k between 3 to 100, i.e. k = 3, 5, 7, ..., 100. This is achieved by fulfilling the following tasks:\r\n i. create a loop to \r\n A. fit the training data into knn classifiers with respective k.\r\n B. calculate the accuracy of applying the knn classifier on the testing data.\r\n C. print out the accuracy for each k.\r\n\r\n ii. plot a line graph with the y-axis being the accuracy for the respective k and x-axis being the value of k. You DO NOT need to save the graph.\r\n'''\r\n\r\n# start your code after this line\r\n\r\nattribute_columns = [\"Na\", \"Mg\", \"Al\", \"Si\", \"K\", \"Ca\", \"Ba\", \"Fe\"]\r\ntarget_columns = [\"Glass type\"]\r\ndata = {\r\n 'attributes': pd.DataFrame(data, columns = attribute_columns),\r\n 'target': pd.DataFrame(data, columns = target_columns)\r\n}\r\n\r\n#split the data for test and train\r\nfrom sklearn.model_selection import train_test_split\r\nx_train, x_test, y_train, y_test = train_test_split(data['attributes'], data['target'], test_size=0.3)\r\n\r\ndata['train'] = {\r\n 'attributes': x_train,\r\n 'target': y_train\r\n }\r\n\r\ndata['test'] = {\r\n 'attributes': x_test,\r\n 'target': y_test\r\n }\r\n\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nknc = KNeighborsClassifier(5)\r\n\r\ninput_columns = data['attributes'].columns[:2].tolist()\r\nx_train = data['train']['attributes'][input_columns]\r\ny_train = data['train']['target']\r\nknc.fit(x_train, y_train)\r\n\r\nx_test = data['test']['attributes'][input_columns]\r\ny_test = data['test']['target']\r\ny_predict = knc.predict(x_test)\r\n\r\nk_values = []\r\naccuracies = []\r\n\r\nstart = 3\r\nstop = 100\r\nstep = 2\r\nfor k in range(start, stop, step):\r\n\r\n k_values.append(k)\r\n knc = KNeighborsClassifier(k)\r\n knc.fit(x_train, y_train)\r\n accuracy = knc.score(x_test, y_test)\r\n accuracies.append(accuracy)\r\n\r\n print(\"\\nK: {} \\nAccuracy: {}\".format(k, accuracy))\r\n\r\npt.figure()\r\npt.plot(k_values, accuracies)\r\n\r\n#labels\r\npt.xlabel(\"k\")\r\npt.ylabel(\"accuracy\")\r\npt.title(\"accuracy vs k\")\r\n\r\npt.show()","sub_path":"202003-ai-labtest-results/Submissions/17003906.py","file_name":"17003906.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"19615488","text":"'''Leia 3 (três) números, verifique e escreva quantos números iguais existem entre os números.'''\r\n\r\n# ENTRADA\r\nnum1 = int(input('Digite o primeiro número: '))\r\nnum2 = int(input('Digite o segundo número: '))\r\nnum3 = int(input('Digite o terceiro número: '))\r\n\r\n# PROCESSAMENTO\r\nif num1 == num2 == num3:\r\n print('Existem 3 números iguais.')\r\n\r\nelif num1 == num2:\r\n print('Existem 2 números iguais.')\r\n\r\nelif num2 == num3:\r\n print('Existem 2 números iguais.')\r\n\r\nelif num1 == num3:\r\n print('Existem 2 números iguais.')\r\n","sub_path":"G - Fabio 2a e 2b - Condicionais/G - Fabio 2a - Condicionais/G_Fabio_2a_q1_iguais.py","file_name":"G_Fabio_2a_q1_iguais.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"432132359","text":"'''\nCreated on Jun 14, 2013\n\n@author: land\n'''\nimport numpy as np\nfrom getanglesdata import getanglesdata\nfrom smooth import smooth\n\ndef smoothing(datain,angles,grid_time,tol,window):\n\tdata=np.copy(datain)\n\t#\n\ttimes=[]\n\twinds=[]\n\twinds_error=[]\n\ttemps=[]\n\ttemps_error=[]\n\tsignals=[]\n\tsignals_error=[]\n\tazimuths=[]\n\tzeniths=[]\n\tfor item in angles:\n\t\t#selecting each angle's data\n\t\tidata=getanglesdata(data,item,tol)\n\t\titimes=idata[:,0]\n\t\tindexes=np.logical_and(itimes<=grid_time[-1],itimes>=grid_time[0])\n\t\titimes=itimes[indexes]\n\t\ttimes=np.concatenate((times,itimes))\n\t\t#smoothing wind\n\t\tiwinds=idata[indexes,1]\n\t\tiwinds_error=idata[indexes,2]\n\t\tiresult=smooth(iwinds,iwinds_error,window)\n\t\tinewwinds=iresult['y']\n\t\tinewwinds_error=iresult['e']\n\t\twinds=np.concatenate((winds,inewwinds))\n\t\twinds_error=np.concatenate((winds_error,inewwinds_error))\n\t\t#smoothing temp\n\t\titemps=idata[indexes,3]\n\t\titemps_error=idata[indexes,4]\n\t\tiresult=smooth(itemps,itemps_error,window)\n\t\tinewtemps=iresult['y']\n\t\tinewtemps_error=iresult['e']\n\t\ttemps=np.concatenate((temps,inewtemps))\n\t\ttemps_error=np.concatenate((temps_error,inewtemps_error))\n\t\t#smoothing signal\n\t\tisignals=idata[indexes,5]\n\t\tisignals_error=idata[indexes,6]\n\t\tiresult=smooth(isignals,isignals_error,window)\n\t\tinewsignals=iresult['y']\n\t\tinewsignals_error=iresult['e']\n\t\tsignals=np.concatenate((signals,inewsignals))\n\t\tsignals_error=np.concatenate((signals_error,inewsignals_error))\n\t\t#others\n\t\tiazimuths=np.array([item[0]]*len(itimes))\n\t\tizeniths=np.array([item[1]]*len(itimes))\n\t\tazimuths=np.concatenate((azimuths,iazimuths))\n\t\tzeniths=np.concatenate((zeniths,izeniths))\n\t\n\ttimes=times.reshape((times.shape[0],1))\n\twinds=winds.reshape((winds.shape[0],1))\n\ttemps=temps.reshape((temps.shape[0],1))\n\tsignals=signals.reshape((signals.shape[0],1))\n\t\n\twinds_error=winds_error.reshape((winds_error.shape[0],1))\n\ttemps_error=temps_error.reshape((temps_error.shape[0],1))\n\tsignals_error=signals_error.reshape((signals_error.shape[0],1))\n\t\n\tazimuths=azimuths.reshape((azimuths.shape[0],1))\n\tzeniths=zeniths.reshape((zeniths.shape[0],1))\n\tnewdata=np.concatenate((times,winds,winds_error,temps,temps_error,signals,signals_error,azimuths,zeniths),1)\n\treturn newdata","sub_path":"library/smoothing.py","file_name":"smoothing.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"437285519","text":"import numpy as np, os\nimport h5py\nimport glob\nimport imgaug as ia\nfrom imgaug import augmenters as iaa\nimport numpy as np\nimport time, csv\nimport cv2\nimport pandas\n\n\nimage_size = 256\n\n\n\n\n\ntest_data_path =\"/home/mil/gupta/ifood18/data/test_set/\"\ntest_label_path =\"/home/mil/gupta/ifood18/data/labels/test_info.csv\"\n\n\ndata = pandas.read_csv(test_label_path, header=None , names= [\"name_of_pic\"])\nprint(data.head())\n#If you want your lists as in the question, you can now do:\n\n\n#val_labels = data.noisy_label.tolist()\n# read addresses and labels from the 'train' folder\ntest_data = data.name_of_pic.tolist()\nprint(\"Length of val data is : \",len(test_data))\n#combined = zip(train_data, train_labels)\n\n\n\n\n\nstart =time.time()\ndata_order = 'pytorch'# 'th' for Theano, 'tf' for Tensorflow\n# check the order of data and chose proper data shape to save images\n# if data_order == 'th':\n# train_shape = (len(train_addrs), 3,)\n# val_shape = (len(val_addrs), 3, 224, 224)\n# test_shape = (len(test_addrs), 3, 224, 224)\n# elif\n\nif data_order == 'pytorch':\n\ttest_shape = (len(test_data),3, image_size, image_size)\n# \tval_shape = (len(val_data_path), image_size, image_size, 3)\n# \ttest_shape = (len(test_data_path), image_size, image_size, 3)\n\n\n\t\n\t\n\n\nhdf5_path = \"/home/mil/gupta/ifood18/data/h5data/test_data.h5py\"\n# open a hdf5 file and create earrays\nhdf5_file = h5py.File(hdf5_path, mode='w')\n\nhdf5_file.create_dataset(\"data\", test_shape, np.float32)\nhdf5_file.create_dataset(\"mean\", test_shape[1:], np.float32)\n#hdf5_file.create_dataset(\"labels\", (len(test_data),), np.int32)\n#hdf5_file[\"labels\"][...] = val_labels\n\n\n\nfrom tqdm import tqdm\n# a numpy array to save the mean of the images\nmean = np.zeros(test_shape[1:], np.float32)\n# loop over train addresses\nfor i in tqdm(range(len(test_data))):\t\t\t \n\taddr = os.path.join(test_data_path,test_data[i])\n\t#print(\"image addres is :\",addr)\n\timg = cv2.imread(addr)\n\t#print(img)\n\timg = cv2.resize(img, (image_size, image_size), interpolation=cv2.INTER_CUBIC)\n\timg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\t\n\n\n\t#current_image = ia.imresize_single_image(addr, (256, 256))\n\timage_aug = img.transpose(2,0,1)\n\thdf5_file[\"data\"][i, ...] = image_aug[None]\n\tmean += image_aug / float(len(test_data))\n\n\t\n\t\n\t\nprint(\"time taken for image\" , time.time()-start)\nhdf5_file[\"mean\"][...] = mean\nhdf5_file.close()","sub_path":"prepare_test.py","file_name":"prepare_test.py","file_ext":"py","file_size_in_byte":2339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"578343262","text":"import discord\n\nfrom discord.ext import commands\nfrom .utils.checks import is_commander\nfrom .utils.strings import join_or_default, collect_attributes\n\nfrom typing import Union\n\n\nclass RoleManager(commands.Cog):\n\n def __init__(self, bot):\n self.bot = bot\n\n async def get_ignored(self, guild):\n ignored_roles = []\n ignored_users = []\n\n check = await self.bot.db.execute(\"SELECT `model`, `is_role` FROM `rm_ignore` WHERE `rm_ignore`.`server` = ?\",\n guild.id, fetch_all=True)\n\n if check is not None:\n for row in check:\n model_id, is_role = row\n\n if is_role:\n role = guild.get_role(model_id)\n\n if role is not None:\n ignored_roles.append(role)\n else:\n user = self.bot.get_user(model_id)\n\n if user is not None:\n ignored_users.append(user)\n\n return ignored_roles, ignored_users\n\n @commands.group(name=\"rm\", invoke_without_command=True)\n @is_commander(manage_roles=True)\n async def role_manager(self, ctx):\n enabled = await self.bot.db.execute(\"SELECT `enabled` FROM `rm_enabled` WHERE `rm_enabled`.`server` = ?\",\n ctx.guild.id)\n\n if enabled is None:\n enabled = False\n\n roles, users = await self.get_ignored(ctx.guild)\n\n em = discord.Embed(\n title=ctx.lang[\"rm\"][\"title\"],\n description=ctx.lang[\"shared\"][\"enabled\"] if\n enabled else ctx.lang[\"shared\"][\"disabled\"],\n colour=ctx.color)\n em.add_field(\n name=ctx.lang[\"rm\"][\"ignored_roles\"],\n value=join_or_default(\n collect_attributes(roles, \"mention\"), ', ', \n ctx.lang[\"shared\"][\"no\"]),\n inline=False)\n em.add_field(\n name=ctx.lang[\"rm\"][\"ignored_users\"],\n value=join_or_default(\n collect_attributes(users, \"mention\"), ', ', \n ctx.lang[\"shared\"][\"no\"]),\n inline=False)\n\n await ctx.send(embed=em)\n\n @role_manager.command(name=\"toggle\")\n @is_commander(manage_roles=True)\n async def role_manager_toggle(self, ctx): \n toggled = await self.bot.db.execute(\"UPDATE `rm_enabled` SET `enabled` = NOT `enabled` WHERE `rm_enabled`.`server` = ?\",\n ctx.guild.id, with_commit=True)\n\n if toggled:\n await ctx.answer(ctx.lang[\"rm\"][\"toggled\"])\n else:\n await self.bot.db.execute(\"INSERT INTO `rm_enabled` VALUES (?, ?)\",\n ctx.guild.id, True, with_commit=True)\n \n await ctx.answer(ctx.lang[\"rm\"][\"now_enabled\"])\n\n @role_manager.command(name=\"ignore\")\n @is_commander(manage_roles=True)\n async def role_manager_ignore(self, ctx, role_or_user: Union[discord.Role, discord.User]):\n check = await self.bot.db.execute(\"DELETE FROM `rm_ignore` WHERE `rm_ignore`.`server` = ? AND `rm_ignore`.`model` = ?\",\n ctx.guild.id, role_or_user.id, with_commit=True)\n\n if not check:\n await self.bot.db.execute(\"INSERT INTO `rm_ignore` VALUES (?, ?, ?)\", \n ctx.guild.id, \n role_or_user.id, \n isinstance(role_or_user, discord.Role),\n with_commit=True)\n\n return await ctx.answer(\n ctx.lang[\"rm\"][\"now_ignored\"].format(role_or_user.mention))\n \n await ctx.answer(ctx.lang[\"rm\"][\"now_not_ignored\"].format(\n role_or_user.mention))\n\n @commands.Cog.listener()\n async def on_member_join(self, member):\n if member.guild.me is None:\n return\n\n if not member.guild.me.guild_permissions.manage_roles:\n return\n\n enabled = await self.bot.db.execute(\"SELECT `enabled` FROM `rm_enabled` WHERE `rm_enabled`.`server` = ?\",\n member.guild.id)\n\n if not enabled:\n return\n\n ignored_roles, ignored_users = await self.get_ignored(member.guild)\n\n if member in ignored_users:\n return\n\n check = await self.bot.db.execute(\"SELECT `role` FROM `rm_buffer` WHERE `rm_buffer`.`server` = ? AND `rm_buffer`.`member` = ?\",\n member.guild.id, member.id, fetch_all=True)\n\n if check is None or not len(check):\n return\n\n roles_to_return = []\n\n for row in check:\n role = member.guild.get_role(row[0])\n\n if role is not None and member.guild.me.top_role > role \\\n and role.id != member.guild.id and role not in ignored_roles \\\n and role not in member.roles:\n roles_to_return.append(role)\n\n await self.bot.db.execute(\"DELETE FROM `rm_buffer` WHERE `rm_buffer`.`server` = ? AND `rm_buffer`.`member` = ?\",\n member.guild.id, member.id, with_commit=True)\n\n if len(roles_to_return):\n await member.add_roles(*roles_to_return, reason=\"Role manager\")\n\n @commands.Cog.listener()\n async def on_member_remove(self, member):\n if member.guild.me is None:\n return\n\n if not member.guild.me.guild_permissions.manage_roles:\n return\n \n enabled = await self.bot.db.execute(\"SELECT `enabled` FROM `rm_enabled` WHERE `rm_enabled`.`server` = ?\",\n member.guild.id)\n\n if not enabled:\n return\n\n query_args = tuple(\n (member.guild.id, member.id, role.id) for role in member.roles\n if role < member.guild.me.top_role)\n\n if len(query_args):\n await self.bot.db.executemany(\"INSERT INTO `rm_buffer` VALUES (?, ?, ?)\",\n query_args, with_commit=True)\n\n\ndef setup(bot):\n bot.add_cog(RoleManager(bot))","sub_path":"src/cogs/role_manager.py","file_name":"role_manager.py","file_ext":"py","file_size_in_byte":5783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"255891515","text":"# -*- coding: utf8 -*-\n\nimport os.path\nimport logging\nimport logging.handlers\nfrom datetime import datetime\nfrom puppy.logging.handlers import PermanentRotatingFileHandler, GzipRotatingFileHandler\n\nONEBIGFILE = 0\nROTATING = 1\nTIMED = 2\nPERMANENTROTATING = 3\nGZIPROTATING = 4\n\nclass QueryLogger(object):\n \"\"\"Logs queries for a SearchService.\n \n The QueryLogger will log all queries submitted to a SearchService, sending them to:\n \n a) current directory, if there is no given log_dir\n b) specific directory, if a log_dir filepath is given (by constructor or config)\n \n The QueryLogger has five logging modes:\n \n a) OneBigFile - single file that grows endlessly\n b) Rotational - files rotate when log file size is = 1GB\n c) Timed - files rotate every day at midnight\n d) Permanent Rotating - files rate when the log file size is reached taking a unique name for each new log\n e) Gzip Permanent Rotating - same as above by using Gz compression\n \n \"\"\"\n def __init__(self, search_service, log_mode=0, log_dir=None, log_period='midnight', log_maxbytes=1000000000):\n super(QueryLogger, self).__init__()\n self.search_service = search_service\n self.log_mode = log_mode\n self.log_dir = log_dir if log_dir else self.get_log_dir()\n self.log_period = log_period \n self.log_maxbytes = log_maxbytes\n self.query_logger = self.create_logger()\n \n \n def get_log_dir(self):\n \"\"\"Find the log_dir if none was passed in the constructor.\n \n Checks the service config files, then defaults to creating \n a log directory in the current working directory\n \"\"\"\n if 'log_dir' in self.search_service.config:\n log_dir = self.search_service.config['log_dir']\n if os.path.exists(log_dir) is False:\n os.mkdir(log_dir)\n return log_dir\n else:\n log_dir = os.path.join(os.getcwd(), 'query_logs')\n if os.path.exists(log_dir) is False:\n os.mkdir(log_dir)\n return log_dir\n \n \n def create_logger(self):\n \"\"\"Create a new logger with a specific handler\"\"\"\n query_logger = logging.getLogger(self.search_service.name)\n query_logger.setLevel(logging.DEBUG)\n log_name = self.search_service.name + \"_query_log\"\n log_filename = os.path.join(self.log_dir, log_name)\n \n if self.log_mode is ONEBIGFILE:\n handler = logging.FileHandler(log_filename)\n query_logger.addHandler(handler)\n return query_logger\n elif self.log_mode is ROTATING:\n handler = logging.handlers.RotatingFileHandler(log_filename, maxBytes=self.log_maxbytes)\n query_logger.addHandler(handler)\n return query_logger\n elif self.log_mode is TIMED:\n handler = logging.handlers.TimedRotatingFileHandler(log_filename, when=self.log_period)\n query_logger.addHandler(handler)\n return query_logger\n elif self.log_mode is PERMANENTROTATING:\n handler = PermanentRotatingFileHandler(log_filename, maxBytes=self.log_maxbytes)\n query_logger.addHandler(handler)\n return query_logger\n elif self.log_mode is GZIPROTATING:\n handler = GzipRotatingFileHandler(log_filename, maxBytes=self.log_maxbytes)\n query_logger.addHandler(handler)\n return query_logger\n else:\n handler = logging.handlers.NullHandler()\n query_logger.addHandler(handler)\n return query_logger\n \n \n def log(self, query, processed=False):\n \"\"\"logs a query using a simple [ISO Timestamp, Query Terms] format\"\"\"\n if processed:\n self.query_logger.debug(\"{0}, {1}, {2}\".format(datetime.today().isoformat(), 'Processed Query (post pipeline)', query.search_terms))\n else:\n self.query_logger.debug(\"{0}, {1}\".format(datetime.today().isoformat(), query.search_terms))\n \n\n","sub_path":"reference-code/puppy/logging/querylogger.py","file_name":"querylogger.py","file_ext":"py","file_size_in_byte":3680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"513861207","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom __future__ import absolute_import\nimport yaml\nfrom jsonschema import validate\n\nfrom airflow.utils.module_loading import import_string\n\nSCHEMA = {\n \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n \"type\": \"object\",\n \"properties\": {\n \"ignored_rules\": {\"type\": [\"array\", \"null\"], \"items\": {\"type\": \"string\"}},\n \"custom_rules\": {\"type\": [\"array\", \"null\"], \"items\": {\"type\": \"string\"}},\n },\n \"additionalProperties\": False,\n}\n\n\nclass UpgradeConfig(object):\n def __init__(self, raw_config):\n self._raw_config = raw_config\n\n def get_ignored_rules(self):\n return self._raw_config.get(\"ignored_rules\") or []\n\n def get_custom_rules(self):\n custom_rules = self._raw_config.get(\"custom_rules\") or []\n return [import_string(r)() for r in custom_rules]\n\n @classmethod\n def read(cls, path):\n with open(path) as f:\n raw_config = yaml.safe_load(f)\n validate(raw_config, schema=SCHEMA)\n return cls(raw_config)\n","sub_path":"airflow/upgrade/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"256644626","text":"#!/usr/bin/env python3\n__description__ = \\\n\"\"\"\n\"\"\"\n__author__ = \"Michael J. Harms\"\n__date__ = \"2018-05-09\"\n\nfrom .base import Processor\n\n\nclass ImageProcessor(Processor):\n \"\"\"\n Process an image file. Looks for lines like this:\n\n ![sm.image](image_file) html_formatting_options\n\n and copies images into the target directory.\n \"\"\"\n\n def process(self,line):\n \"\"\"\n Process an image line.\n \"\"\"\n\n # If the line does not match, return the original line\n if not self._pattern.match(line):\n return line\n\n image_file, args = self._parse_markdown_line(line,delim=None)\n\n new_file = self._copy_file(image_file)\n\n if args is not None:\n style = args\n else:\n style = \"\"\n\n out_line = \"\".format(new_file,style)\n\n return out_line\n","sub_path":"slidemachine/processors/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"7941086","text":"# Import required packages\nimport sqlite3\nimport operations\nimport os\nimport time\n\n# Establish connection with database\nconnection = sqlite3.connect(\"books.db\")\n\n# Instantiate cursor\ncursor = connection.cursor()\n\n# Create the books table\ncursor.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS books (\n BookId INTEGER PRIMARY KEY,\n Title TEXT NOT NULL,\n Price DECIMAL(5, 2),\n Stock INTEGER\n )\n\"\"\")\n\nif __name__ == \"__main__\":\n # Print welcome screen\n operations.clear_screen()\n print(\"Hello \\U0001f600\\n\")\n time.sleep(2)\n begin_page = None\n # Ask user for valid page number\n while begin_page not in range(1, 51):\n try:\n print(\"At what page would you like to start scraping?\\n\\n\"\n \"Please type a number between 1 and 50.\\n\\n\"\n \"The higher the number, the faster the program will be done.\\n\"\n )\n begin_page = int(input(\"Number > \"))\n if begin_page not in range(1, 51):\n raise Exception()\n except:\n operations.clear_screen()\n # Start scraping\n operations.clear_screen()\n print(\"Let the scraping begin! \\U0001f600\")\n time.sleep(2)\n book_urls = operations.scrape_book_urls(begin=begin_page)\n books = operations.scrape_books(book_urls)\n operations.write_to_csv_file(books)\n\n try:\n current_book = 1\n for book in books:\n query = \"\"\"\n INSERT INTO [dbo].[Books] (title, price, stock)\n VALUES (?, ?, ?)\"\"\"\n cursor.execute(query, (book[\"title\"], book[\"price\"], book[\"stock\"]))\n print(f\"Saving book {current_book}/{len(books)} to the database\")\n current_book += 1\n time.sleep(0.1)\n except:\n pass\n\n # Commit data to the database\n connection.commit()\n operations.clear_screen()\n print(\"Completed!\\nNow type 'open books.csv' \\U0001f600\")\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"209370616","text":"\"\"\"\nHow many clusters of grain?\n\nIn the video, you learned how to choose a good number of clusters for a dataset using the k-means inertia graph.\nYou are given an array samples containing the measurements (such as area, perimeter, length, and several others) of\nsamples of grain. What's a good number of clusters in this case?\n\nKMeans and PyPlot (plt) have already been imported for you.\n\nThis dataset was sourced from the UCI Machine Learning Repository.\n\"\"\"\n\nimport numpy as np\nfrom sklearn.cluster import KMeans\nimport matplotlib.pyplot as plt\n\nsamples = np.array([[15.26, 14.84, 0.871, 3.312, 2.221, 5.22],\n [14.88, 14.57, 0.8811, 3.333, 1.018, 4.956],\n [14.29, 14.09, 0.905, 3.337, 2.699, 4.825],\n [13.2, 13.66, 0.8883, 3.232, 8.315, 5.056],\n [11.84, 13.21, 0.8521, 2.836, 3.598, 5.044],\n [12.3, 13.34, 0.8684, 2.974, 5.637, 5.063]])\nks = range(1, 6)\ninertias = []\n\nfor k in ks:\n # Create a KMeans instance with k clusters: model\n model = KMeans(n_clusters=k)\n\n # Fit model to samples\n model.fit(samples)\n\n # Append the inertia to the list of inertias\n model.inertia_\n inertias.append(model.inertia_)\n\n# Plot ks vs inertias\nplt.plot(ks, inertias, '-o')\nplt.xlabel('number of clusters, k')\nplt.ylabel('inertia')\nplt.xticks(ks)\nplt.show()\n","sub_path":"Specialist Certificate in Data Analytics Essentials/DataCamp/11-Unsupervised_Learning_in_Python/e4_how_many_clusters_of_grain.py","file_name":"e4_how_many_clusters_of_grain.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"116658239","text":"__author__ = 'janak'\n\"\"\"\nDjango settings for pronoun project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.6/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '76z)%js2d=b&gn!2mwg4_uig+7=9cc5tvvp7i-je2^$8n&&cv!'\n\nALLOWED_HOSTS = ['*']\n\n# Application definition\n\nDJANGO_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n)\n\n# THIRD_PARTY_APPS = ('haystack',)\n\nCUSTOM_APPS = ('sitehome',\n 'loginmgmt',\n 'pmhome',\n 'companies',\n 'contacts',\n 'internalresources',\n 'projects',\n 'utils',\n 'search',\n 'converse',\n)\n\nINSTALLED_APPS = DJANGO_APPS + CUSTOM_APPS #THIRD_PARTY_APPS +\n\nAUTH_USER_MODEL = 'loginmgmt.PronounUser'\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'pronoun.urls'\n\nWSGI_APPLICATION = 'pronoun.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.6/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'America/New_York'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.6/howto/static-files/\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\n# STATIC_ROOT = 'static'\nSTATIC_URL = '/static/'\n\nSTATICFILES_DIRS = (\n # os.path.join(BASE_DIR, 'static'),\n os.path.join(BASE_DIR, '../static'),\n)\n\n#Media files information\nMEDIA_URL = '/media/'\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\n\n# SETTING UP THE DIFFERNT CORES FOR SOLR. THE MAIN URL IS SETUP IN THE MAIN DEV AND PROD SETTINGS FILES.\nSOLR_CORE_URLS = dict(\n SOLR_CORE_ALL='pronoun',\n SOLR_CORE_COMPANY='company',\n SOLR_CORE_CONTACT='contact',\n SOLR_CORE_PROJECT='project',\n SOLR_CORE_INTERNAL_RESOURCES='internal_resource'\n)\n\n#LOG file path\nLOG_FILE_NAME = BASE_DIR + '/../logs/pronoun_log.log'","sub_path":"settings/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"252125140","text":"\"\"\"\n 1. 匹配 (){}[]\n \"\"\"\n\n\ndef isValid(s: str) -> bool:\n dic = {'{': '}', '[': ']', '(': ')', '?': '?'}\n stack = ['?']\n for c in s:\n if c in dic:\n stack.append(c)\n elif dic[stack.pop()] != c:\n return False\n return len(stack) == 1\n\n\nteststr = '(){}[]'\n# print(isValid(teststr))\n\n\n\"\"\"\n 2. 柱状图最大面积\n\n \"\"\"\n\n\ndef getMaxArea(heights: []):\n l = len(heights)\n i = 0\n j = 1\n maxArea = 0\n while(i < l):\n print('i->' + str(i))\n minHeight = heights[i]\n while(j < l):\n print('j->' + str(j))\n minHeight = min(minHeight, heights[j])\n area = (j - i + 1) * minHeight\n maxArea = max(maxArea, area)\n j += 1\n i += 1\n j = i + 1\n\n return maxArea\n\n\nprint(getMaxArea([2, 1, 5, 6, 2, 3]))\n","sub_path":"LeetCode/stackAndQueue/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"522807315","text":"# Reference: CTCI\n# Author: Shreyas Padhye\n# Problem 1.3 (Pg 97) : Design an algorithm and write code to remove the duplicate characters in a string without using any additional buffer. \n# NOTE: One or two additional variables are fine. An extra copy of the array is not. FOLLOW UP Write the test cases for this method\n# Solution Approach: Do a single pass. Create a dictionary to keep track of already passed elements and delete from dictionary if you encounter repeats. Merge dict elements to get string back\n\n# Note: Remember - When you store keys in dictioanry, they are arranged alphabetically\nfrom collections import OrderedDict\nclass solution():\n def remove_duplicates(self, s):\n d = OrderedDict()\n\n # single pass, avoid on duplicate entry and add to res string otherwise\n res = \"\"\n for char in s:\n if char not in d:\n d[char] = True\n res += char\n \n return res\n \nt = solution()\nt.remove_duplicates(\"abssateryyv\")\nt.remove_duplicates(\"abstr\")\nt.remove_duplicates(\"aaaa\")\nt.remove_duplicates(\"\")\nt.remove_duplicates(\"aaabbb\")\nt.remove_duplicates(\"ababab\")\n","sub_path":"ctci-solutions/1.3 remove-duplicates.py","file_name":"1.3 remove-duplicates.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"}