diff --git "a/5413.jsonl" "b/5413.jsonl" new file mode 100644--- /dev/null +++ "b/5413.jsonl" @@ -0,0 +1,568 @@ +{"seq_id":"398526708","text":"import pyautogui, sys\nimport pygetwindow as gw\nimport re\nimport input as i\nimport time\n\nfrom pynput.keyboard import Key, Controller\n\nVK_RETURN = 0x1C # ENTER key\nKEY_A = 0x41\n\nKEYEVENTF_EXTENDEDKEY = 0x0001\nKEYEVENTF_KEYUP = 0x0002\n#######################################################################################################################\n\npyautogui.FAILSAFE = True #Moving mouse to top left of screen will abort execution\npyautogui.PAUSE = 1 #Seconds to wait between each pyautogui API call\n\nscreenWidth, screenHeight = pyautogui.size()\npyautogui.moveTo(screenWidth / 2, screenHeight / 2) #Move to middle of screen each loop\n\n#Ensure Black Desert Window is active window\nr = re.compile(\"BLACK DESERT.*\")\nwindowList = gw.getAllTitles()\nbdo = list(filter(r.match, windowList))[0]\ngw.getWindowsWithTitle(bdo)[0].activate()\ntime.sleep(1)\n# keyboard = Controller()\n# keyboard.press(Key.enter)\n# time.sleep(0.2)\n# keyboard.release(Key.enter)\n\n\ni.SendInput(i.Keyboard(VK_RETURN))\ntime.sleep(0.2)\ni.SendInput(i.Keyboard(VK_RETURN, KEYEVENTF_KEYUP))\ntime.sleep(0.2)\ni.SendInput(i.Keyboard(KEY_H))\ntime.sleep(0.2)\ni.SendInput(i.Keyboard(KEY_H, KEYEVENTF_KEYUP))\n\n\n","sub_path":"Python-Macro-Improved/pyautogui_implementation.py","file_name":"pyautogui_implementation.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"455666734","text":"import threading\nimport time\n\n# 线程通过两种方式,一种是创建thread子类,一种是直接创建Thread类\n\nclass SubThreadEx(threading.Thread):\n \"\"\"\n 创建Thread的子类\n \"\"\"\n def __init__(self):\n threading.Thread.__init__(self)\n self.message = 'Hello Python'\n\n def print_message(self):\n print(self.message)\n\n\n def run(self):\n print(\"Thread Starting\")\n self.print_message()\n time.sleep(2)\n print('Thread End')\n\n\nhello_python = SubThreadEx()\nhello_python.start()\n\n\ndef thread_func(i):\n print(type(i))#\n print(threading.current_thread())\n return\n\nth = threading.Thread(target=thread_func,args = ('1',))\nth.start()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"LearnPython/Python_New/Parallels/ThreadEx.py","file_name":"ThreadEx.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"171112196","text":"import logging\nfrom pathlib import Path\n\nimport fiona\nimport xarray as xr\nfrom ravenpy.models import GR4JCN, HBVEC, HMETS, MOHYSE, get_model\nfrom ravenpy.utilities import forecasting\n\nfrom . import wpsio as wio\nfrom .wps_raven import RavenProcess\n\nLOGGER = logging.getLogger(\"PYWPS\")\n\n\nclass RealtimeForecastProcess(RavenProcess):\n identifier = \"realtime-forecast\"\n title = \"Perform realtime forecast using most recent ECCC forecast data.\"\n abstract = \"Perform a deterministic or probabilistic raven forecast using the most recent ECCC forecast.\"\n version = \"0.1\"\n keywords = [\n \"forecasting\",\n \"ECCC\",\n \"GEPS\",\n \"REPS\",\n \"GDPS\",\n \"RDPS\",\n \"ensemble forecasts\",\n ]\n tuple_inputs = {\n \"hmets\": HMETS.Params,\n \"gr4jcn\": GR4JCN.Params,\n \"hbvec\": HBVEC.Params,\n \"mohyse\": MOHYSE.Params,\n }\n inputs = [\n wio.forecast_model,\n wio.region_vector,\n wio.hmets,\n wio.gr4jcn,\n wio.hbvec,\n wio.duration,\n wio.run_name,\n wio.area,\n wio.latitude,\n wio.longitude,\n wio.elevation,\n wio.rain_snow_fraction,\n wio.nc_spec,\n wio.rvc,\n ]\n\n def model(self, request):\n \"\"\"Return model class.\"\"\"\n models = list(set(request.inputs.keys()).intersection(self.tuple_inputs.keys()))\n if len(models) > 1:\n raise NotImplementedError(\"Multi-model simulations are not supported. \")\n name = models.pop()\n params = self.parse_tuple(request.inputs.pop(name)[0])\n model = get_model(name)(workdir=self.workdir)\n model.config.update(\"params\", params)\n return model\n\n def meteo(self, request):\n \"\"\"Fetch the latest forecast from ECCC.\n\n Returns\n -------\n list\n List of input file paths.\n \"\"\"\n # Region shapefile from request\n vector_file = self.region(request)\n\n # Forecast model from request\n forecast_model = request.inputs.pop(\"forecast_model\")[0].data\n\n # Short-cut for testing\n # return [Path(\"/home/david/src/raven-testdata/eccc_geps/fcstfile.nc\"),]\n\n # Fetch data and average over region\n fcst = forecasting.get_recent_ECCC_forecast(\n fiona.open(vector_file), climate_model=forecast_model\n )\n\n # Write the forecast data to file on-disk\n # To speed-up testing, copy this file and return it instead of recomputing every time.\n fn = Path(self.workdir) / \"fcstfile.nc\"\n fcst.to_netcdf(fn)\n\n return [fn]\n\n def run(self, model, ts, kwds):\n \"\"\"Initialize the model with the RVC file, then run it with the forecast data.\"\"\"\n # Open forecast file and set some attributes.\n fcst = xr.open_dataset(ts[0])\n kwds[\"nc_index\"] = range(fcst.dims.get(\"member\"))\n\n model(ts=ts, **kwds)\n\n fcst.close()\n","sub_path":"raven/processes/wps_realtime_forecast.py","file_name":"wps_realtime_forecast.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"381604585","text":"import nba_py.player\nimport pandas\n'''\nconvertNameString( userString ):\n\n\nplayerSearch( playerList, userString ):\n\tparameters: \n\t\tplayerList: DataFrame object containing player's ids, name in (Last, First) and (First Last) forms, etc.\n\t\tuserString: input string from user. Compared to names in playerList to determine if it is a substring\n\n\toutput:\n\t\treturns a tuple containing two lists: a list of possible player names in (First Last) format and a list of those possible player's IDs\n'''\n\ndef convertNameString( userString ):\n\t'''\n\tgiven a user's search string, convert into something that\n\tcan be compared to an element of PlayerList().info()\n\t'''\n\treturn userString\n\n\n\ndef playerSearch( playerList, userString ):\n\t'''\n\tgiven a string that can be compared to an element of PlayerList().info(),\n\treturn associated playerId\n\t'''\n\tnameString = convertNameString(userString)\n\tplayerId = 0\n\tpossiblePlayers = []\n\tpossiblePlayerIds = []\n\n\t# loop through all rows of display_first_last and collect a list of possible players\n\tfor index in range(0, playerList.shape[0] - 1):\n\t\t#if namestring is a substring of this player's name\n\t\tif nameString in playerList.get_value(index, \"DISPLAY_FIRST_LAST\" ):\n\t\t\t\n\t\t\t# add this player to the list of possible players\t\t\t\n\t\t\tpossiblePlayers.append( playerList.get_value(index, \"DISPLAY_FIRST_LAST\") )\n\n\t\t\t# add this player's id to the list of possible player ids\n\t\t\tplayerId = playerList.get_value(index, \"PERSON_ID\")\n\t\t\tpossiblePlayerIds.append( playerId )\n\n\treturn possiblePlayers, possiblePlayerIds\n","sub_path":"playerFinder.py","file_name":"playerFinder.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"647269053","text":"# lib import\nimport os\nimport mne\nfrom mne.time_frequency import psd_multitaper\nimport numpy as np\nimport useful_notations\nfrom spikes_events import create_events\nfrom classification import predict_perceptron, predict_svm\nfrom visualization import plot_results, plot_mean_topomaps\n\n\n# EEG class for epochs and power estimation. Instance of epochs\nclass Eeg:\n def __init__(self, path_to_set, path_to_txt, path_to_folder):\n powers, epochs = [], []\n # create two lists with .set and .txt files names\n files_eeg, files_events = [f for f in sorted(os.listdir(path_to_set))], [f for f in\n sorted(os.listdir(path_to_txt))]\n for ind, path in enumerate(files_eeg):\n raw = self._read_raw_with_annotations(path_to_set + '/{0}'.format(path))\n ch_names = raw.ch_names\n events = create_events(raw)\n epoch = self._create_epochs(raw, events)\n epochs.append(epoch)\n power = Power(epoch)\n powers.append(power)\n self.ch_names = ch_names\n self.powers = powers\n self.epochs = epochs\n self.path_for_save = path_to_folder\n del powers, epochs, raw, events, ch_names\n\n @staticmethod\n def _read_raw_with_annotations(path):\n raw = mne.io.read_raw_eeglab(path, preload=True)\n return raw\n\n @staticmethod\n def _create_epochs(raw, events):\n epoch = mne.Epochs(raw, events=events, event_id=useful_notations.event_dict, tmin=-0.05, tmax=0.05,\n baseline=(None, 0), preload=True)\n return epoch\n\n def classification(self):\n result = Results(self.powers, self.path_for_save)\n return result\n\n def save_powers(self, path_to_folder):\n pass\n\n def plot(self, path_to):\n pass\n\n\n# class fo making plots for results of classification\nclass Results:\n def __init__(self, powers, path):\n self.perceptron = predict_perceptron(powers)\n self.svm = predict_svm(powers)\n self.path_for_save = path\n\n def plot(self, save=False):\n plot_results([self.perceptron, self.svm], save)\n\n\n# class fo key accessing the Powers\nclass Power:\n def __init__(self, epochs):\n bands = useful_notations.bands\n events_list = useful_notations.event_list_ext\n for _, k in enumerate(events_list):\n psds, freqs = psd_multitaper(epochs[k])\n psds /= np.sum(psds, axis=-1, keepdims=True)\n x = []\n for fmin, fmax in bands.values():\n psds_band = psds[:, :, (freqs >= fmin) & (freqs < fmax)].mean(axis=-1)\n x.append(psds_band.reshape(len(psds), -1))\n np.concatenate(x, axis=1)\n self.__dict__[k] = x\n\n # create key accessing\n def __getitem__(self, key):\n return self.key\n","sub_path":"main_eeg_tms.py","file_name":"main_eeg_tms.py","file_ext":"py","file_size_in_byte":2878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"561243227","text":"import torch\nimport torch.nn.functional as F\nimport pyprind\nimport os\nimport sys\nfrom torch.utils.tensorboard import SummaryWriter\nimport shutil\n\ndef train_model(model, criterion, optimizer, epochs, trainloader, testloader, device):\n shutil.rmtree(\"../logs\", ignore_errors=True)\n os.mkdir(\"../logs\")\n writer = SummaryWriter(\"../logs\")\n\n history = {\"loss\": [], \"accuracy\": []}\n\n for epoch in range(epochs): # loop over the dataset multiple times\n running_loss = 0.0\n bar = pyprind.ProgBar(len(trainloader), track_time=True, title=\"Training Model\")\n\n for i, data in enumerate(trainloader, 0):\n # get the inputs; data is a list of [inputs, labels]\n inputs, labels = data[0].to(device), data[1].to(device)\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n outputs = model(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n\n bar.update()\n\n correct = 0\n total = 0\n\n with torch.no_grad():\n for data in testloader:\n images, labels = data[0].to(device), data[1].to(device)\n outputs = model(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\n history[\"loss\"].append(running_loss / len(trainloader))\n history[\"accuracy\"].append(correct / total)\n\n writer.add_scalar(\"Train Loss\", running_loss / len(trainloader), epoch)\n writer.add_scalar(\"Test Accuracy\", (100 * correct / total), epoch)\n\n print(\"Epoch: {} Loss: {:.3f}\".format(epoch + 1, running_loss / len(trainloader)))\n print(\"Accuracy of the network on the 10000 test images: %d %%\" % (100 * correct / total))\n\n print(\"Finished Training\")\n return model, history","sub_path":"CIFARTrain/Distribution/NormalReluReduced/source/train_util.py","file_name":"train_util.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"17346526","text":"import numpy as np\nfrom spline_registration.utils import descomposar\n\n\ndef SSD(reference_image, transformed_image):\n\n N = reference_image.shape[0] * reference_image.shape[1]\n a = reference_image - transformed_image\n '''\n N és el nombre de pixels de la imatge de referència\n suposam ambdues imatges de la mateixa dimensió ja quan les introduim.\n a són els errors en els valors de les imatges\n '''\n SSD = np.sum(a * a) / N\n\n return SSD\n\n\ndef RMSE(reference_image, transformed_image):\n\n N = reference_image.shape[0] * reference_image.shape[1]\n dif = reference_image - transformed_image\n RMSE = np.sqrt(np.sum(dif * dif) / N)\n return RMSE\n\n\ndef info_mutua(reference_image, transformed_image, n):\n '''\n n ens dona en quants de grups dividim cada color\n\n x és la reference_imatge, y la transformed_image\n pxy distribucio de probabilitat conjunta\n px i py distribucions marginals (la d'x s'obté sumant per files i la de y per columnes).\n '''\n\n imatge1 = descomposar(reference_image, n)\n imatge2 = descomposar(transformed_image, n)\n\n '''\n descomposant reference_image i transformed_image obtenim dos vectors d'una fila i \n reference_image.shape[0]*reference_image.shape[1] columnes\n on cada element és la classe del color que hi havia abans. \n '''\n\n histograma = np.histogram2d(imatge1, imatge2, bins=(n**3))\n\n '''\n ara feim un histograma que histograma[0] conté els pics que la imatge1 val un valor mentre que a la imatge2 un altre\n per totes les combinacions possibles. Per tant la distibició de probabilitat conjunta és histograma[0] normalitzat.\n '''\n\n pxy = histograma[0]/np.sum(histograma[0])\n px = pxy.sum(axis=1) # sumes els elements de la mateixa fila obtenim un array\n py = pxy.sum(axis=0) # sumes els elements de la mateixa columna\n\n # els pxy que siguin 0 no les tenim en compte ja que no aporten res\n # a la informació mutua i el log de 0 no està definit\n\n pxy = histograma[0] / np.sum(histograma[0])\n\n PX = np.transpose(np.tile(px, (n ** 3, 1)))\n PY = np.tile(py, (n ** 3, 1))\n den = PX * PY\n den2 = np.where(den == 0, 1, den)\n num = pxy\n log = np.log(np.where(den*num == 0, 1, num / den2))\n mutual_info = np.sum(pxy*log)\n\n return (pxy*log).ravel()\n # return mutual_info","sub_path":"spline_registration/losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"241767696","text":"'''\nDoubly linked lists - Very similar to singly linked; however, these have prev pointer\n and a tail node.\n Move left, to previous node, from a given node\n Move immediately to the last node\n'''\n\nclass DoubleNode:\n def __init__(self,data,next=None,prev=None):\n self.data = data\n self.next = next\n self.prev = prev\n\nclass DoublyLinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n def print_linked_list(self):\n probe = self.head\n while probe != None:\n print(probe.data)\n probe = probe.next\n def append(self,data):\n newNode = DoubleNode(data)\n if self.head is None:\n newNode.prev = None\n self.head = newNode\n self.tail = self.head\n else:\n self.tail.next = newNode\n newNode.prev = self.tail\n self.tail = self.tail.next\n\n\n\ndoubly_linked_list = DoublyLinkedList()\ndoubly_linked_list.append(\"first node's data\")\n\ndoubly_linked_list.print_linked_list()\n","sub_path":"double_node.py","file_name":"double_node.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"627203052","text":"from django.shortcuts import render\r\nfrom django.db import connection as conn\r\nimport re\r\nfrom .models import Annotation\r\nfrom watson import search as watson\r\n\r\ndef list_view(request): # parse input from search bar and GET requested info\r\n # from database\r\n # get the user query\r\n user_query = request.GET.get('query')\r\n if user_query is not '': # at the risk of incorrectly interpreting some\r\n # search queries, we will simply pass the whole query to watson\r\n search_results = watson.search(user_query)\r\n return render(\r\n request,\r\n 'results/list.html',\r\n {\r\n 'search_results': search_results,\r\n 'query': user_query\r\n }\r\n )\r\n else: # if they submitted a blank query, give them all U12s\r\n search_results = watson.search('U12-Dependent/Minor')\r\n return render(\r\n request,\r\n 'results/list.html',\r\n {\r\n 'search_results': search_results,\r\n 'query': 'No input detected; showing all U12-dependent introns\\\r\n in all species currently in the database'\r\n }\r\n )\r\n\r\ndef advanced_list(request):\r\n # dictionary for converting between database column names and user-friendly\r\n # display names\r\n column_names = {\r\n 'short_seq': 'Abbreviated Sequence',\r\n 'tax_name': 'Taxonomic Name',\r\n 'com_name': 'Common Name',\r\n 'genome': 'Genome Assembly',\r\n 'score': 'Score',\r\n 'intron_class': 'Class',\r\n 'id': 'Intron ID',\r\n 'chromosome': 'Chromosome',\r\n 'start': 'Start',\r\n 'stop': 'Stop',\r\n 'length': 'Length',\r\n 'strand': 'Strand',\r\n 'intron_rank': 'Rank in Transcript',\r\n 'phase': 'Phase',\r\n 'tds': 'Terminal Dinucleotides',\r\n 'up_seq': 'Upstream Exonic Sequence',\r\n 'branch_seq': 'Branch Point Sequence',\r\n 'down_seq': 'Downstream Exonic Sequence',\r\n 'full_seq': 'Full Sequence',\r\n 'symbol': 'Gene Symbol or Name',\r\n 'gene_id': 'Ensembl Gene ID',\r\n 'trans_id': 'Ensembl Transcript ID'\r\n }\r\n # parse user input into list of columns to show in table and QuerySet\r\n # filters\r\n column_list = ['id'] # we will always need to get the intron id to make\r\n # links to the individual intron pages\r\n # start a QuerySet to tack appropriate filters onto\r\n search_results = Annotation.objects.all()\r\n # make a list of all of their search criteria to make a string to appear\r\n # above the table. If it is an empty list after the loop, we know that\r\n # they didn't input anything into any of the fields, and can give them all\r\n # U12s (maybe they just wanted different columns?)\r\n filters = []\r\n for field in request.GET.items():\r\n if 'y_' in field[0]: # anything prefixed with x_ is a field the\r\n # user wants shown in the results table\r\n column_list.append(field[0].lstrip('y_'))\r\n elif field[1] == '': # skip over fields that had no user input\r\n pass\r\n else: # everything else should be a queryset filter\r\n search_results = search_results.filter(**{field[0] : field[1]})\r\n # add to string describing user input\r\n filters.append(column_names[field[0]]+' = '+field[1])\r\n # if filters is still an empty list, query_text will be an empty string\r\n query_text = 'Showing results for: ' + ', '.join(filters) + '. '\r\n\r\n # the user entered nothing into any field, so give them all U12s\r\n if query_text == 'Showing results for: . ':\r\n search_results = search_results.filter(\r\n intron_class = 'U12-Dependent/Minor'\r\n )\r\n query_text = 'No search input; showing all U12-dependent introns \\\r\nfrom all species currently in the database. '\r\n\r\n # make column names user-friendly\r\n html_columns = []\r\n if len(column_list) != 1: # the user specified columns\r\n # we need to get the intron id for every hit from every query, but the\r\n # user may want to see the intron id column (I don't blame them; they\r\n # are gross and long). We defined column_list with id already in it,\r\n # so if the user checked the intron id box on the form, it will be in\r\n # the list twice. list.remove() will only remove the first instance of\r\n # id from the list, so that it only remains in the list if the user\r\n # actually wants to see that column.\r\n column_list.pop(0)\r\n # we need some nicer names for these columns to appear in the html\r\n \r\n for column in column_list:\r\n html_columns.append(column_names[column])\r\n else: # the user specified no columns, so we give them default columns\r\n column_list.extend(\r\n [\r\n 'genome',\r\n 'tax_name',\r\n 'com_name',\r\n 'tds',\r\n 'chromosome',\r\n 'start',\r\n 'stop'\r\n ]\r\n )\r\n html_columns = [\r\n 'Genome Assembly',\r\n 'Taxonomic Name',\r\n 'Common Name',\r\n 'Terminal Dinucleotides',\r\n 'Chromosome',\r\n 'Start',\r\n 'Stop'\r\n ]\r\n # always nice to let the user know what we're doing\r\n query_text += 'No columns specified; showing default columns.'\r\n\r\n # turn the QuerySet into a list of lists\r\n rows = []\r\n for hit in search_results:\r\n row = []\r\n for column in column_list:\r\n row.append(getattr(hit, column))\r\n rows.append(row)\r\n\r\n # at this point, we should have everything that we need\r\n return render(\r\n request,\r\n 'results/advanced_list.html',\r\n {\r\n 'rows': rows,\r\n 'columns': html_columns,\r\n 'query': query_text\r\n }\r\n )\r\n\r\ndef individual(request, input_intron_id): # once a specific entry has been\r\n # chosen from the list, show the detailed view\r\n\r\n # use the given ID to get all the information corresponding to that intron\r\n # from the database\r\n info = Annotation.objects.get(pk=input_intron_id)\r\n\r\n # create links to the ensembl pages corresponding to the ensembl gene\r\n # and transcript IDs\r\n species = re.sub(' ', '_', info.tax_name) # need the species and genus\r\n # names to be separated by an underscore for the ensembl URLs\r\n\r\n if info.tax_name in ['arabidopsis', 'zea', 'soy', 'rice']: # ensembl plants\r\n gene_url = 'https://plants.ensembl.org/' + species + \\\r\n '/Gene/Summary?g=' + info.gene_id\r\n transcript_url = 'https://plants.ensembl.org/' + species + \\\r\n '/Transcript/Summary?t=' + search_results.trans_id\r\n else: # normal ensembl\r\n gene_url = 'https://ensembl.org/' + species + '/Gene/Summary?g=' + \\\r\n info.gene_id\r\n transcript_url = 'https://ensembl.org/' + species + \\\r\n '/Transcript/Summary?t=' + info.trans_id\r\n\r\n # all phases were listed in the database as 'phase 1' so we could use full\r\n # text search, but when we display them here, we just want the number.\r\n phase = info.phase.lstrip('phase ')\r\n\r\n # get a list of orthologous introns for this intron (easier said than done)\r\n # start by getting a list of all the genome assemblies other than the one\r\n # the selected intron is in, since we are only looking for orthologs\r\n dict_assembly_list = list(Annotation.objects.values('genome').distinct())\r\n assembly_list = [x['genome'] for x in dict_assembly_list]\r\n assembly_list.remove(info.genome)\r\n # some assmebly names have characters like periods and hyphens, hence `s\r\n escaped_assembly_list = ['`' + x + '`' for x in assembly_list]\r\n # now use a raw SQL statement to get a list of all the orthologs\r\n assemblies = ','.join(escaped_assembly_list)\r\n cur = conn.cursor()\r\n cur.execute(\r\n f'SELECT {assemblies} FROM orthologs WHERE {info.genome} = \\\r\n\"{info.gene_id}\"'\r\n )\r\n # each row is a list of orthologs, so cur.fetchall() return a list of lists\r\n # since just want a single list of orthologs, we use this line to flatten\r\n ortholog_list = [ortholog for row in cur.fetchall() for ortholog in row]\r\n # there may be duplicates in that list, which will be removed by\r\n # transiently converting it to a set\r\n unique_ortholog_list = list(set(ortholog_list))\r\n # use ensembl gene IDs to find all orthologous intron IDs\r\n id_list = []\r\n for ortholog in unique_ortholog_list:\r\n id_list.append(\r\n Annotation.objects.filter(**{'gene_id': ortholog}).values('id')\r\n )\r\n\r\n return render(\r\n request,\r\n 'results/individual.html',\r\n {\r\n 'data': info,\r\n 'gene_url': gene_url,\r\n 'transcript_url': transcript_url,\r\n 'orthologs': id_list\r\n }\r\n )\r\n \r\n","sub_path":"results/old_views.py","file_name":"old_views.py","file_ext":"py","file_size_in_byte":8925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"42448910","text":"# oled.py Display useful info on 0.96\" OLED display\n# Written by mosquito@darlingevil.com, 2019-11-15\n\nimport os\nimport time\nfrom datetime import datetime\nimport board\nimport digitalio\nimport subprocess\nfrom PIL import Image, ImageDraw, ImageFont\nimport adafruit_ssd1306\n\n# These are pulled in from the host when the container is run\nGATEWAY = os.environ['GATEWAY']\nIPV4_ADDR = os.environ['IPV4_ADDR']\n\n# Commands to check LAN, WAN, etc.\nLAN_COMMAND = 'curl -sS https://' + GATEWAY + ' 2>/dev/null | wc -l'\nWAN_COMMAND = 'curl -sS https://google.com 2>/dev/null | wc -l'\nUPTIME_COMMAND = \"uptime | awk '{printf \\\"up %s avg %.2f\\\", $3, $(NF-2)}'\"\n\n# Define the Reset Pin\noled_reset = digitalio.DigitalInOut(board.D4)\n\n# Change these\n# to the right size for your display!\nWIDTH = 128\nHEIGHT = 64\nBORDER = 5\n\n# Use for I2C.\ni2c = board.I2C()\noled = adafruit_ssd1306.SSD1306_I2C(WIDTH, HEIGHT, i2c, addr=0x3c, reset=oled_reset)\n\n# Clear display.\noled.fill(0)\noled.show()\n\n# Create blank image for drawing.\n# Make sure to create image with mode '1' for 1-bit color.\n#image = Image.new('1', (oled.width, oled.height))\n\n# Get drawing object to draw on image.\n# Create blank image for drawing.\n# Make sure to create image with mode '1' for 1-bit color.\nimage = Image.new('1', (oled.width, oled.height))\ndraw = ImageDraw.Draw(image)\n\n# Load default font.\nfont = ImageFont.load_default()\n\n# Draw text at coordinates\ndef text_xy(x, y, text):\n draw.text((x, y), text, font=font, fill=255)\n\n# Draw center-aligned text\ndef text_centered_y(y, text):\n (font_width, font_height) = font.getsize(text)\n draw.text((oled.width//2 - font_width//2, y), text, font=font, fill=255)\n\nwhile (True):\n\n # Draw a black background\n draw.rectangle((0, 0, oled.width, oled.height), outline=0, fill=0)\n\n lan = '0' != str(subprocess.check_output(LAN_COMMAND, shell=True)).strip()\n wan = '0' != str(subprocess.check_output(WAN_COMMAND, shell=True)).strip()\n\n text_centered_y(2, \"IPv4: \" + IPV4_ADDR)\n if lan:\n text_xy(0, 14, \"Gateway: (connected)\")\n else:\n text_xy(0, 14, \"Gateway: UNREACHABLE!\")\n if wan:\n text_xy(0, 24, \"Internet: (reachable)\")\n else:\n text_xy(0, 24, \"Internet: UNREACHABLE!\")\n\n text_xy(0, 34, \" \")\n\n date = datetime.utcnow().strftime(\"UTC: %H:%M:%S\")\n text_centered_y(44, date)\n uptime = subprocess.check_output(UPTIME_COMMAND, shell=True)\n uptime = uptime.decode(\"utf-8\").strip()\n text_centered_y(54, \"\" + uptime)\n\n # Display image\n oled.image(image)\n oled.show()\n\n time.sleep(5)\n\n\n","sub_path":"oled-status.py","file_name":"oled-status.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"610055097","text":"def fattoriale(x):\n \"\"\"\n this function returns the factorial of a number x\n to store the value in a variable use value = factorial(x)\n \"\"\"\n f = 1\n if x == 0:\n return f\n\n else:\n for i in range(x):\n f = f * (i + 1)\n return f\ndef butterfly(s):\n \"\"\" converts a string into butterfly language. Every S is converted into an F.\n For example: butterfly(\"abyss\") returns abyff\n\n Args:\n s(str) = the string that needs to be converted in butterfly language\n\n Returns:\n str -> a string where all S have been changed in to F\n\n \"\"\"\n l1 = []\n if isinstance(s, str) == False:\n return \"inserted value is not a string\"\n\n else:\n for i in s:\n if i == \"s\":\n l1.append(\"f\")\n else:\n l1.append(i)\n return \"\".join(l1)\n\n\ndef vowelcount(s, y):\n \"\"\"\n this function counts the amounts of vowels in a string\n insert y = 1 counts the letter y as a vowel\n if y = 0 the letter y is not counted as vowel\n\n Args:\n s = type(str). It's the string you want to count for vowels\n y = type(int). If y == 1 the letter Y is counted as vowel, otherwise it is not.\n Returns:\n int number of vowels in the word or sentence\n \"\"\"\n n = 0\n vowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n vowels_y = [\"a\", \"e\", \"i\", \"o\", \"u\", \"y\"]\n\n if isinstance(s, str) == False:\n return \"inserted value is not a string\"\n\n if y != 1 and y != 0:\n return \"wrong y value. y must be either 1 or 0\"\n\n else:\n if y == 1:\n for i in s:\n if i in vowels_y:\n n = n+1\n else:\n pass\n if y == 0:\n for i in s:\n if i in vowels:\n n = n+1\n else:\n pass\n return n\n\n # add some comments to check some stuff on the repository\n","sub_path":"exercise.py","file_name":"exercise.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"604840288","text":"import cv2\nimport numpy as np\nfrom dataPath import DATA_PATH\n\nimg = cv2.imread(DATA_PATH+\"images/sample.jpg\", cv2.IMREAD_GRAYSCALE)\n\nkernelSize = 3\n\n# Applying laplacian\nimg1 = cv2.GaussianBlur(img,(3,3),0,0)\nlaplacian = cv2.Laplacian(img1, cv2.CV_32F, ksize = kernelSize,\n scale = 1, delta = 0)\n\n# Normalize results\ncv2.normalize(laplacian,\n dst = laplacian,\n alpha = 0,\n beta = 1,\n norm_type = cv2.NORM_MINMAX,\n dtype = cv2.CV_32F)\n\ncv2.imshow(\"Laplacian\", laplacian)\ncv2.waitKey(0)\n","sub_path":"Course1/week4/ImageGradients/laplacian.py","file_name":"laplacian.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"407955270","text":"import speech_recognition as sr\r\n\r\ndef getText(file1):\r\n\tr = sr.Recognizer()\r\n\twith sr.WavFile(file1) as source:\r\n\t audio = r.record(source) # extract audio data from the file\r\n\r\n\ttry:\r\n\t list = r.recognize(audio,True)\r\n\t for prediction in list:\r\n\t return (prediction[\"text\"])\r\n\texcept LookupError: # speech is unintelligible\r\n\t return(\"Could not understand audio\")","sub_path":"AudioStuff/SpeechTT.py","file_name":"SpeechTT.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"509721712","text":"import sys\nimport logging\nfrom rainbow_logging_handler import RainbowLoggingHandler\n\n\ndef main():\n\n logger = logging.getLogger('test_logging')\n logger.setLevel(logging.DEBUG)\n\n handler = RainbowLoggingHandler(sys.stderr)\n logger.addHandler(handler)\n\n logger.debug(\"デバッグ\")\n logger.info(\"インフォ\")\n logger.warn(\"警告\")\n logger.error(\"エラー\")\n logger.critical(\"深刻なエラー\")\n try:\n raise RuntimeError(\"例外も色つきます\")\n except Exception as e:\n logger.exception(e)\n\n return\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"test and sample/rainbow.py","file_name":"rainbow.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"568795901","text":"from django.shortcuts import render\nfrom django.http import HttpRequest\nfrom .models import feed,like,Comment,Notification,chatmessages\nfrom django.http import HttpResponseRedirect\nfrom django.db.models import F\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\nfrom login_register.models import Profile\nimport datetime\nimport requests\nfrom bs4 import BeautifulSoup\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\n\n@login_required(login_url='/account/error/')\ndef addFeed(request):\n '''\n This function is used to add feed provided by the Logeed in user\n '''\n if request.method=='POST':\n user=request.user\n body=request.POST['feedfield']\n f=feed.objects.create(user=user,body=body)\n f.save()\n return HttpResponseRedirect('/feed/home/')\n\n\n@login_required(login_url='/account/error/')\ndef updateLikes(request,pagename,isLike,id,touserid):\n '''\n This function is used to update like count on the basis fo like and dislike\n '''\n if request.method=='GET':\n feedid=id\n user=request.user\n if isLike=='Like' :\n feed.objects.filter(id=feedid).update(likes=F('likes')+1)\n feedobj=feed.objects.filter(id=feedid)[0]\n like.objects.create(user=user,feed=feedobj).save()\n addNotification(user,touserid,feedid,\"Like\")\n else:\n feed.objects.filter(id=feedid).update(likes=F('likes')-1)\n feedobj=feed.objects.filter(id=feedid)[0]\n like.objects.filter(feed=feedobj,user=user).delete()\n deleteNotification(user,touserid,feedid,\"Like\")\n\n if pagename=='homepage':\n return HttpResponseRedirect('/feed/home/')\n elif pagename=='feedpage':\n return showParticularFeed(request,id)\n else:\n #code to be added for other pages\n pass\n\n@login_required(login_url='/account/error/') \ndef addComment(request):\n '''\n This function is used to add Comment\n '''\n if request.method=='POST':\n user=request.user\n body=request.POST['commentfield']\n feedid=request.POST['id']\n touserid=request.POST['touserid']\n pagename=request.POST['pagename']\n feedobj=feed.objects.filter(id=feedid)[0]\n f=Comment.objects.create(user=user,coment_body=body,feed=feedobj)\n f.save()\n feed.objects.filter(id=feedid).update(comments=F('comments')+1)\n addNotification(user,touserid,feedid,\"Commented\")\n \n if pagename=='homepage':\n return HttpResponseRedirect('/feed/home/')\n elif pagename=='feedpage':\n return showParticularFeed(request,feedid)\n else:\n #code to be added for other pages\n pass\n\n\ndef addNotification(user,touserid,feedid,activitytype):\n '''\n This function is used to add notification for the user\n '''\n touser=User.objects.get(id=touserid)\n feedobj=feed.objects.get(id=feedid)\n if user.id != int(touserid):\n notificationObj=Notification.objects.create(fromuser=user.username,touser=touser,feed=feedobj,activitytype=activitytype)\n notificationObj.save()\n\n \ndef deleteNotification(user,touserid,feedid,activitytype):\n '''\n this function is used to delete notification for the user\n '''\n touser=User.objects.get(id=touserid)\n feedobj=feed.objects.get(id=feedid)\n if user.id != int(touserid):\n notificationObj=Notification.objects.create(fromuser=user.username,touser=touser,feed=feedobj,activitytype=activitytype)\n Notification.objects.filter(fromuser=user.username,touser=touser,feed=feedobj,activitytype=activitytype).delete()\n\n@login_required(login_url='/account/error/')\ndef showAllNotification(request):\n '''\n this is used to show all the notification for the user\n '''\n args={}\n user=request.user\n notificationObj=Notification.objects.filter(touser=request.user,viewed=False)\n args['notification']=notificationObj\n return render(request, 'feedback/notification.html',args)\n\n@login_required(login_url='/account/error/')\ndef showParticularFeed(request,id):\n '''\n this is used to showParticularFeed\n '''\n args={}\n feedobj=feed.objects.get(id=id)\n args['feed']=feedobj\n return render(request, 'feedback/Feed.html',args)\n\n\n@login_required(login_url='/account/error/')\ndef markasReadNotification(request,fid):\n args={}\n user=request.user\n Notification.objects.filter(id=fid).update(viewed=True)\n notificationObj=Notification.objects.filter(touser=request.user,viewed=False)\n totalNotification=len(Notification.objects.filter(touser=request.user,viewed=False))\n args['notification']=notificationObj\n request.session['notifications']=totalNotification\n return render(request, 'feedback/notification.html',args)\n \n \n@login_required(login_url='/account/error/') \ndef addChatMessage(request):\n if request.method=='POST': \n profile=Profile.objects.get_or_create(user=request.user)[0]\n chat=chatmessages.objects.create(user=request.user,chat=request.POST['chat'])\n profile.save()\n chat.save()\n return HttpResponseRedirect('/getChatMessage/')\n\n@login_required(login_url='/account/error/') \ndef getMessages(request):\n chatObj=chatmessages.objects.filter(msg_date__startswith=datetime.date.today())\n return render(request,'feedback/chat_msg.html',{'chatObj':chatObj})\n\n \n@login_required(login_url='/account/error/') \ndef getNewsFeed(request):\n page = requests.get(\"https://news.google.co.in/\")\n soup = BeautifulSoup(page.content, 'html.parser')\n sectioncontent=soup.find(class_='section-content')\n escbody=soup.find_all(class_='esc-body')\n newsimg=[]\n newstitle=[]\n newstimestamp=[]\n newssource=[]\n newsbody=[]\n newsurl=[]\n for newsobj in escbody:\n try:\n if newsobj.find(class_='esc-thumbnail-image')!=None:\n newsimg.append(newsobj.find(class_='esc-thumbnail-image').attrs['src'])\n except:\n newsimg.append(newsobj.find(class_='esc-thumbnail-image').attrs['imgsrc'])\n\n newsurl.append(newsobj.find(class_='esc-lead-article-title').find('a').attrs['href'])\n newstitle.append(newsobj.find(class_='titletext').get_text())\n newssource.append(newsobj.find(class_='al-attribution-source').get_text())\n newstimestamp.append(newsobj.find(class_='al-attribution-timestamp').get_text())\n newsbody.append(newsobj.find(class_='esc-lead-snippet-wrapper').get_text())\n\n\n newsobjlist=list(zip(newsimg,newstitle,newssource,newstimestamp,newsbody,newsurl))\n paginator = Paginator(newsobjlist, 7)\n pageno = request.GET.get('page')\n\n try:\n newsobj = paginator.page(pageno)\n except PageNotAnInteger:\n newsobj = paginator.page(1)\n except EmptyPage:\n newsobj = paginator.page(paginator.num_pages)\n\n return render(request,'feedback/newsFeed.html',{'newsobj':newsobj})\n\n \n","sub_path":"myfeedapp/feed/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"593377979","text":"from django.conf.urls import url\n\nfrom geoloc import views\n\nurlpatterns = [\n # ex: /geoloc/\n url(r'^$', views.index, name='start'),\n\n # ex: /geoloc/load-projections/\n url(r'^load-projections/$', views.load_projections, name='load_projections'),\n\n # ex: /geoloc/read-points/\n url(r'^read-points/$', views.read_points, name='read_points'),\n\n # ex: /geoloc/read-waypoints/\n url(r'^read-waypoints/$', views.read_waypoints, name='read_waypoints'),\n\n # ex /geoloc/results/\n url(r'^results/$', views.results, name='results'),\n]\n","sub_path":"geoloc/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"636870906","text":"# -*- coding: utf-8 -*-\n\nimport codecs\nimport sys\n\nfrom setuptools import setup\n\n\nwith codecs.open('README.rst', encoding='utf-8') as f:\n long_description = f.read()\n\n\n# Require the 'enum34' package on Python versions before 3.4.\nversion_dependent_install_requires = []\nif sys.version_info[:2] < (3, 4):\n version_dependent_install_requires.append('enum34')\n\n\nsetup(\n name='syslog2IRC',\n version='0.9.2-dev',\n description='A proxy to forward syslog messages to IRC',\n long_description=long_description,\n url='http://homework.nwsnet.de/releases/c474/#syslog2irc',\n author='Jochen Kupperschmidt',\n author_email='homework@nwsnet.de',\n license='MIT',\n classifiers=[\n 'Environment :: Console',\n 'Intended Audience :: System Administrators',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Topic :: Communications :: Chat :: Internet Relay Chat',\n 'Topic :: Internet',\n 'Topic :: System :: Logging',\n 'Topic :: System :: Monitoring',\n 'Topic :: System :: Networking :: Monitoring',\n 'Topic :: System :: Systems Administration',\n ],\n packages=['syslog2irc'],\n install_requires=[\n 'blinker >= 1.3',\n 'irc >= 8.9.1',\n 'syslogmp >= 0.2',\n ] + version_dependent_install_requires,\n tests_require=['nose2'],\n test_suite='nose2.collector.collector',\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"374494240","text":"### CRE of clusters\nimport pandas as pd\nimport scanpy as sc\nimport sys\nimport os\nimport pickle\nfrom multiprocessing import Process\n\nscript_path='/home/xionglei/yanqiu/regulatory'\nsys.path.insert(1,script_path)\nsys.path.insert(1,'/home/xionglei/yanqiu')\nsys.path.insert(1, '/home/xionglei/yanqiu/joint_analysis/')\nfrom process_data import overlap_adata\nfrom identify_CRE import identify_cre\nfrom utils import load_data, write_mtx\n\n\noutdir='/home/xionglei/yanqiu/joint_analysis/WYF191116'\ngene_info = pickle.load(open('/home/xionglei/yanqiu/lib/gene_info_hg.pkl', 'rb'))\n\n'''\ncluster_df=pd.read_csv(outdir+'/WYF191116_cluster.txt', sep='\\t', index_col=0, header=0)\nclusters=cluster_df['clusters'].unique()\ncluster_dict=cluster_df.to_dict()\n'''\n\ngenedata=sc.read_h5ad(outdir+'/gene_expression.h5ad')\nprodata=sc.read_h5ad(outdir+'/promoter_accessibility.h5ad')\ngenedata.obs['clusters']=genedata.obs['seurat_clusters']\natac_adata=sc.read_h5ad(outdir+'/atac.h5ad')\n\n'''\natac_dir='/home/xionglei/data/joint_ATAC_RNA/WYF191116/ATAC/peak'\natac=load_data(atac_dir) \natac_adata=sc.AnnData(atac.T)\nsc.pp.filter_cells(atac_adata, min_genes=1)\nsc.pp.filter_genes(atac_adata, min_cells=1)\natac_adata.write(outdir+'/atac.h5ad')\n'''\n\nrn, an=overlap_adata(genedata, atac_adata)\nrn, pro=overlap_adata(genedata, prodata)\n\n#print(rn.shape, an.shape, pro.shape)\n\ndef cre_cluster(rn, an, pro, cluster, outdir):\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n cells=rn[rn.obs['clusters']==cluster].obs_names\n #print(len(cells))\n rn_f=rn[cells, ]\n an_f=an[cells, ]\n pro_f=pro[cells, ]\n #print(rn_f.shape, an_f.shape, pro_f.shape)\n CRE_df=identify_cre(rn_f, an_f, pro_f, gene_info, outdir)\n\n\nclusters=rn.obs['clusters'].unique()\n# cannot run together??\nPros=[]\ni=0\nfor c in ['2','4']:\n i+=1\n print('Starting processing %d' %i)\n p = Process(target=cre_cluster, args=(rn, an, pro, c, outdir+'/CRE/'+str(c)))\n Pros.append(p)\n p.start()\nfor t in Pros:\n t.join()\n\n\n\n#cluster=sys.argv[1]\n#for c in clusters:\n# cre_cluster(rn, an, pro, c, outdir+'/CRE/'+str(c))","sub_path":"joint_analysis/CRE_cluster.py","file_name":"CRE_cluster.py","file_ext":"py","file_size_in_byte":2112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"449989332","text":"#! /usr/bin/python\n\nCG_PROXIED = None\n\"\"\"Full path to the executable you want to trace IO of\"\"\"\nCG_LOGDIR = None\n\"\"\"dir to write the stdin/out/err files to\"\"\"\nCG_SLEEP = 0.01\n\nfrom subprocess import Popen, PIPE\nimport sys\nimport os\nfrom time import sleep\nfrom os.path import isdir, join\nimport fcntl\n\np = Popen([CG_PROXIED] + sys.argv[1:], stdin=PIPE, stdout=PIPE, stderr=PIPE)\n\nfd = p.stdout.fileno()\nfl = fcntl.fcntl(fd, fcntl.F_GETFL)\nfcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)\n\nfd = p.stderr.fileno()\nfl = fcntl.fcntl(fd, fcntl.F_GETFL)\nfcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)\n\nfd = sys.stdin.fileno()\nfl = fcntl.fcntl(fd, fcntl.F_GETFL)\nfcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)\n\nif not isdir(CG_LOGDIR):\n os.mkdir(CG_LOGDIR)\n\nstdin = open(join(CG_LOGDIR, 'in.log'), 'a')\nstdout = open(join(CG_LOGDIR, 'out.log'), 'a')\nstderr = open(join(CG_LOGDIR, 'err.log'), 'a')\n\nfor i in stdin,stdout,stderr:\n i.write(\"new execution\\n\")\n\nwhile True:\n try:\n xs = p.stderr.read()\n except IOError as e:\n if e.errno != 11:\n raise\n else:\n stderr.write(xs)\n sys.stderr.write(xs)\n\n try:\n xs = p.stdout.read()\n except IOError as e:\n if e.errno != 11:\n raise\n else:\n stdout.write(xs)\n sys.stdout.write(xs)\n\n try:\n xs = sys.stdin.read()\n except IOError as e:\n if e.errno != 11:\n raise\n else:\n stdin.write(xs)\n p.stdin.write(xs)\n\n rc = p.poll()\n if rc is not None:\n sys.exit(rc)\n\n sleep(CG_SLEEP)\n\nstdin.close()\nstdout.close()\nstderr.close()\n","sub_path":"iologr.py","file_name":"iologr.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"322484502","text":"from aiohttp import web\nimport asyncio\n\nroutes = web.RouteTableDef()\n\n@routes.post(\"/model/upload\")\nasync def receive_model(request):\n data = await request.post()\n input_file = data['file']\n path = \"\"\n\n extension = input_file.filename.split('.')[1]\n if extension == \"pb\":\n path = \"tensorflow-ssd/fine_tuned_model/saved_model/new_model.pb\"\n elif extension == \"m5\":\n path = \"keras-retinanet/new_model.h5\"\n else: \n return web.Response(status=415) #Unsupported media type\n\n\n with open(path, 'w+b') as f:\n content = input_file.file.read()\n f.write(content)\n\n return web.Response(status=200)\n\nif __name__ == \"__main__\": \n app = web.Application(client_max_size=0)\n app.add_routes(routes)\n web.run_app(app, host='0.0.0.0', port=5000)\n","sub_path":"service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"66510120","text":"import torch\nimport torch.nn as nn\nfrom config import START, STOP, PAD, log_sum_exp_pytorch\nfrom model.charbilstm import CharBiLSTM\nfrom model.bilstm_encoder import BiLSTMEncoder\nfrom model.linear_partial_crf_inferencer import LinearCRF\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\nfrom config import ContextEmb\nfrom typing import Tuple\nfrom overrides import overrides\nimport numpy as np\n\ndef check_remove_ratio(gold_tags,tags,small_loss_mask,mask,negative_mask):\n remove_mask=(1-small_loss_mask)*mask\n positive_mask=(1-negative_mask)*mask\n clean_mask=torch.eq(gold_tags,tags).float()*mask\n noise_mask=(1-clean_mask)*mask.float()\n remove_neg=remove_mask*negative_mask\n remove_right_neg=noise_mask*remove_neg\n remove_pos=remove_mask*(1-negative_mask)*mask\n remove_right_pos=noise_mask*remove_pos\n noise_positive=noise_mask*positive_mask*mask\n noise_negative=noise_mask*negative_mask*mask\n neg_recall=remove_right_neg.sum() / (noise_negative.sum()+1e-8)\n pos_recall=remove_right_pos.sum() / (noise_positive.sum()+1e-8)\n neg_precision=remove_right_neg.sum() / (remove_neg.sum()+1e-8)\n pos_precision=remove_right_pos.sum() / (remove_pos.sum()+1e-8)\n neg_f1=2*neg_recall*neg_precision/(neg_recall+neg_precision+1e-8)\n pos_f1=2*pos_recall*pos_precision/(pos_recall+pos_precision+1e-8)\n \n \n return neg_recall.item(),pos_recall.item(),neg_precision.item(),pos_precision.item(),neg_f1.item(),pos_f1.item()\n\ndef gen_dic(labels,label2idx):\n types=set()\n for label in labels:\n if(label.startswith('B') or label.startswith('S') or label.startswith('E') or label.startswith('I')):\n tp=label.split('-')[1]\n types.add(tp)\n pos_dic={'O':[label2idx['O']]}\n type_dic={'O':[label2idx['O']]}\n for label in labels:\n if(label=='O' or label.startswith('<')):\n continue\n pos,type=label.split('-')[0],label.split('-')[1]\n if(pos in pos_dic):\n pos_dic[pos].append(label2idx[label])\n else:\n pos_dic[pos]=[label2idx[label]]\n if(type in type_dic):\n type_dic[type].append(label2idx[label])\n else:\n type_dic[type]=[label2idx[label]]\n for tp in types:\n type_dic[tp].append(label2idx['O'])\n for pos in ['B','I','E','S']:\n pos_dic[pos].append(label2idx['O'])\n return pos_dic,type_dic\n\ndef gen_embedding_table(idx2label,type_dic,pos_dic):\n type_embedding=torch.zeros(len(idx2label),len(idx2label))\n pos_embedding=torch.zeros(len(idx2label),len(idx2label))\n #type_embedding\n for id,label in enumerate(idx2label):\n \n if(label.startswith('B') or label.startswith('S') or label.startswith('E') or label.startswith('I')):\n indexes=type_dic[label.split('-')[1]]\n for index in indexes:\n type_embedding[id][index]=1\n elif(label=='O'):\n type_embedding[id]=torch.ones_like(type_embedding[id])\n \n #pos_embedding\n for id,label in enumerate(idx2label):\n \n if(label.startswith('B') or label.startswith('S') or label.startswith('E') or label.startswith('I')):\n indexes=pos_dic[label.split('-')[0]]\n for index in indexes:\n pos_embedding[id][index]=1\n elif(label=='O'):\n pos_embedding[id]=torch.ones_like(pos_embedding[id])\n \n type_embedding,pos_embedding =pos_embedding,type_embedding\n return type_embedding,pos_embedding\n\n\n\nclass NNCRF_sl(nn.Module):\n\n def __init__(self, config, print_info: bool = True):\n super(NNCRF_sl, self).__init__()\n self.device = config.device\n self.encoder = BiLSTMEncoder(config, print_info=print_info)\n self.inferencer = LinearCRF(config, print_info=print_info)\n self.label2idx = config.label2idx\n self.idx2word=config.idx2word\n self.idx2labels=config.idx2labels\n self.Oid = self.label2idx['O']\n self.padid = self.label2idx['']\n self.startid=self.label2idx['']\n self.stopid=self.label2idx['']\n \n \n self.pos_dic, self.type_dic=gen_dic(config.label2idx.keys(),self.label2idx)\n \n self.tags_num=len(self.idx2labels)\n e_type,pos=gen_embedding_table(self.idx2labels,self.type_dic,self.pos_dic)\n self.type_embedding = torch.nn.Embedding(self.tags_num, self.tags_num).from_pretrained(e_type,freeze=True).cuda(self.device)\n self.pos_embedding=torch.nn.Embedding(self.tags_num, self.tags_num).from_pretrained(pos,freeze=True).cuda(self.device)\n \n @overrides\n def forward(self, words: torch.Tensor,\n word_seq_lens: torch.Tensor,\n batch_context_emb: torch.Tensor,\n chars: torch.Tensor,\n char_seq_lens: torch.Tensor,\n annotation_mask : torch.Tensor,\n tags: torch.Tensor,\n gold_tags=None,\n forget_rate_neg=0,forget_rate_pos=0,is_constrain=False) -> torch.Tensor:\n \"\"\"\n Calculate the negative loglikelihood.\n :param words: (batch_size x max_seq_len)\n :param word_seq_lens: (batch_size)\n :param batch_context_emb: (batch_size x max_seq_len x context_emb_size)\n :param chars: (batch_size x max_seq_len x max_char_len)\n :param char_seq_lens: (batch_size x max_seq_len)\n :param tags: (batch_size x max_seq_len)\n :return: the loss with shape (batch_size)\n \"\"\"\n \n lstm_scores= self.encoder(words, word_seq_lens, batch_context_emb, chars, char_seq_lens)\n batch_size = words.size(0)\n sent_len = words.size(1)\n maskTemp = torch.arange(1, sent_len + 1, dtype=torch.long).view(1, sent_len).expand(batch_size, sent_len).to(self.device)\n mask = torch.le(maskTemp, word_seq_lens.view(batch_size, 1).expand(batch_size, sent_len)).to(self.device).float()\n\n onehot_label = torch.zeros_like(lstm_scores).scatter_(-1, tags.unsqueeze(-1), 1)\n log_marginals = self.inferencer.marginal(lstm_scores,word_seq_lens)\n token_prob = log_marginals\n forward_loss = -(onehot_label * token_prob).sum(dim=-1) * mask\n forward_loss=forward_loss.detach()\n negative_mask=torch.eq(tags, self.Oid).float()* mask.float()\n positive_mask =(1 - negative_mask)*mask.float()\n\n\n tmp = forward_loss.view(batch_size * sent_len) + (1000 * (1 - mask).view(batch_size * sent_len)) + (\n 1000 * (positive_mask.view(batch_size * sent_len)))\n \n index=torch.argsort(tmp, dim=-1)\n remember_rate_neg = 1.0 - forget_rate_neg\n \n num_remember = int(remember_rate_neg * (negative_mask.sum()))\n small_loss_index = index[:num_remember]\n small_loss_mask_neg = torch.zeros_like(tmp)\n for num in small_loss_index:\n small_loss_mask_neg[num] = 1\n small_loss_mask_neg = small_loss_mask_neg.view((batch_size, sent_len))\n if num_remember == 0:\n small_loss_mask_neg = negative_mask\n remove_num_neg = negative_mask.sum() - small_loss_mask_neg.sum()\n \n tmp = forward_loss.view(batch_size * sent_len) + (1000 * (1 - mask).view(batch_size * sent_len)) + (\n 1000 * (negative_mask.view(batch_size * sent_len)))\n \n index=torch.argsort(tmp, dim=-1)\n remember_rate_pos = 1.0 - forget_rate_pos\n \n num_remember = int(remember_rate_pos * (positive_mask.sum()))\n small_loss_index = index[:num_remember]\n small_loss_mask_pos = torch.zeros_like(tmp)\n for num in small_loss_index:\n small_loss_mask_pos[num] = 1\n small_loss_mask_pos = small_loss_mask_pos.view((batch_size, sent_len))\n if num_remember == 0:\n small_loss_mask_pos = positive_mask\n\n small_loss_mask = (small_loss_mask_pos.bool() + small_loss_mask_neg.bool()).float()\n small_loss_mask = small_loss_mask.detach()\n \n if(gold_tags!=None): \n neg_recall,pos_recall,neg_precision,pos_precision,neg_f1,pos_f1=check_remove_ratio(gold_tags,tags,small_loss_mask,mask,negative_mask)\n \n \n partial_label=torch.ones_like(onehot_label)\n \n \n type_lookup = self.type_embedding(tags)\n pos_lookup=self.pos_embedding(tags)\n \n prob = log_marginals.exp()\n prob=prob.detach()\n type_prob=(prob*type_lookup).mean(dim=-1)\n pos_prob=(prob*pos_lookup).mean(dim=-1)\n type_change_mask=(type_prob>pos_prob)*mask*(1-small_loss_mask)\n pos_change_mask=(type_prob Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Decode the batch input\n :param batchInput:\n :return:\n \"\"\"\n wordSeqTensor, wordSeqLengths, batch_context_emb, charSeqTensor, charSeqLengths, annotation_mask, tagSeqTensor,_= batchInput\n \n features = self.encoder(wordSeqTensor, wordSeqLengths, batch_context_emb,charSeqTensor,charSeqLengths)\n bestScores, decodeIdx = self.inferencer.decode(features, wordSeqLengths, annotation_mask)\n \n return bestScores, decodeIdx\n\n","sub_path":"model/neuralcrf_small_loss_constrain_global.py","file_name":"neuralcrf_small_loss_constrain_global.py","file_ext":"py","file_size_in_byte":10326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"322473515","text":"import cv2\nimport roi\n\n\ndef process_and_detect(src, window_manager):\n height, width, channels = src.shape\n cropping = src[300:900, 500:width-500]\n\n # TODO: Image Processor\n processing = _image_processing_template_one(cropping, window_manager)\n # gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)\n # filtering = cv2.bilateralFilter(gray, 1, 10, 120)\n\n # TODO: Object Detector\n processing_output = cv2.cvtColor(processing, cv2.COLOR_GRAY2BGR)\n success_detect, contour, approx = _try_detect(\n input_image=processing, output_image=processing_output, window_manager=window_manager)\n\n roi_output = None\n if success_detect:\n # ROI\n roi_output = roi.post_detect(original_image=cropping, output_image=processing_output,\n contour=contour, approx=approx)\n roi.decode_barcode(original_image=cropping, roi_image=roi_output)\n else:\n # TODO: image_processing_template_two\n pass\n\n # TODO: to be continued\n return processing_output, roi_output\n\n\ndef _image_processing_template_one(src, window_manager):\n # TODO: Color space: GRAYSCALE, HSV, ...\n gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)\n\n # TODO: Convolution, Blurring, ...\n # filtering = cv2.bilateralFilter(gray, 1, 10, 120)\n filtering = _image_filtering(gray, window_manager)\n\n # TODO: Edge detection\n # edges = cv2.Canny(gray, 10, 250)\n edges = _edge_detection(filtering, window_manager)\n\n # TODO: Morphological operations\n # kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7))\n # closed = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel)\n closed = _morphological_transformations(edges, window_manager)\n return closed\n\n\ndef _image_filtering(src, window_manager):\n diameter = window_manager.get_trackbar_value('Diameter (bilateralFilter)')\n sigma_color = window_manager.get_trackbar_value('SigmaColor (bilateralFilter)')\n sigma_space = window_manager.get_trackbar_value('SigmaSpace (bilateralFilter)')\n filtering = cv2.bilateralFilter(src, diameter, sigma_color, sigma_space)\n return filtering\n\n\ndef _edge_detection(src, window_manager):\n threshold_min = window_manager.get_trackbar_value('Threshold min (Canny edge detection)')\n threshold_max = window_manager.get_trackbar_value('Threshold max (Canny edge detection)')\n edges = cv2.Canny(src, threshold_min, threshold_max)\n return edges\n\n\ndef _morphological_transformations(src, window_manager):\n kernel_size = window_manager.get_trackbar_value('Kernel size (morphological operation)')\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (kernel_size, kernel_size))\n closed = cv2.morphologyEx(src, cv2.MORPH_CLOSE, kernel)\n return closed\n\n\ndef _try_detect(input_image, output_image, window_manager):\n success_standard, contour, approx = _detect_standard_rects(input_image, output_image, window_manager)\n if not success_standard:\n # TODO: detect_rects_by_lines\n pass\n\n return success_standard, contour, approx\n\n\ndef _detect_standard_rects(input_image, output_image, window_manager):\n contour_area_points = window_manager.get_trackbar_value('Contour area min amount points (*1000)')\n # approx_edges_amount = self._windowManager.get_trackbar_value('Approx edges amount')\n approx_edges_amount = 4\n\n _, contours, h = cv2.findContours(input_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n rects_count = 0\n finding_4contour_area = 0\n finding_4contour = None\n finding_appox = None\n for contour in contours:\n if cv2.contourArea(contour) > contour_area_points * 1000:\n arc_len = cv2.arcLength(contour, True)\n approx = cv2.approxPolyDP(contour, 0.1 * arc_len, True)\n if len(approx) == approx_edges_amount:\n # Find 4contour with maximum area\n if cv2.contourArea(contour) > finding_4contour_area:\n finding_4contour = contour\n finding_appox = approx\n finding_4contour_area = cv2.contourArea(finding_4contour)\n\n rects_count += 1\n\n return rects_count > 0, finding_4contour, finding_appox\n","sub_path":"research/opencv/src/mvp2/processing.py","file_name":"processing.py","file_ext":"py","file_size_in_byte":4163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"627863172","text":"_symbol_dict = {\n \"dot\":r\"\\dot\",\n \"cdot\":r\"\\cdot\",\n \"cdots\":r\"\\cdots\",\n \"vdot\":r\"\\vdot\",\n \"vdots\":r\"\\vdots\",\n \"ddot\":r\"\\ddot\",\n \"ddots\":r\"\\ddots\",\n \"leq\":r\"\\leq\",\n \"les\":r\"<\",\n \"geq\":r\"\\geq\",\n \"great\":r\">\",\n \"leqslant\":r\"\\leqslant\",\n \"geqslant\":r\"\\geqslant\",\n \"eq\":r\"=\",\n \"doteq\":r\"\\doteq\",\n \"ngtr\":r\"\\ngtr\",\n \"nltr\":r\"\\nltr\",\n}\n\n\n\n\ndef _fix_brace(brace):\n assert brace in \".{}[]()|<\" and len(brace) == 1,\"bracket must be {}[]() or .\"\n\n if brace in [\"{\",\"}\"]:\n brace = rf\"\\{brace}\"\n elif brace == \"<\":\n brace = r\"\\langle\"\n elif brace == \">\":\n brace = r\"\\rangle\"\n\n return brace\n\ndef left(what=\".\"):\n res = r\"\\left\"\n what = _fix_brace(what)\n res += what\n return res\n\ndef right(what = \".\"):\n res = r\"\\right\"\n what = _fix_brace(what)\n res+=what\n return res\n\nif __name__ == \"__main__\":\n for k,v in _symbol_dict.items():\n print(f\"def {k}():return r'{v}'\")\n","sub_path":"pyMathJax/symbol.py","file_name":"symbol.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"612859897","text":"# Caudae v1.5 kiosk_settings definition\n# Taken from v1.0\n\n\"\"\"Screen Configuration settings for the CAUDAE project\n\nTo keep the site as dynamic as possible, certain screen sizes and dimensions need to be dynamically changed. For example, many elements are defined in page division tags (
...
), and are positioned absolutely on the screen. This absolute position gives us pixel accuracy on where elements are placed on the screen. However, some elements need to be centered dynamically, for example, based upon object's width and the screen height and width parameters.\n\nEach page of the project has a 'sub-object' associated with it for clarity. For example, the first page of the client kiosk screen has an object \"client_kiosk\" based upon class ClientKiosk. This way, we can clearly see where each element is located from it's base path. In this case, the WELCOME_WIDTH is located in this module as: kiosk_settings.client_kiosk.WELCOME_TOP.\n\n\n\"\"\"\n\n#################################\n# Screen and Browser parameters #\n#################################\n\n# Screen parameters\nSCREEN_HEIGHT = 768\nSCREEN_WIDTH = 1024\n\n# These parameters are common to all buttons\n# on all screens\nBUTTON_WIDTH_RATIO = 0.25\nBUTTON_HEIGHT_RATIO = 0.25\n\nTIMER_INTERVAL = 30;\nLAST_PAGE_TIMER_INTERVAL = 6;\n\n\ndef calculate_left(object_width):\n \"\"\"Calculates Left so object is centered.\"\"\"\n\n return int(float(SCREEN_WIDTH - object_width)/2.0)\n\n\n#######################\n# Choose Kiosk Screen #\n#######################\nclass ChooseKiosk:\n # Font size for both buttons\n CHOOSE_BUTTON_FONT_SIZE = 45\n # Choose employee kiosk button constants\n CHOOSE_EMPLOYEE_BUTTON_TOP = 100\n CHOOSE_EMPLOYEE_BUTTON_LEFT = 400\n CHOOSE_EMPLOYEE_BUTTON_HEIGHT = 200\n CHOOSE_EMPLOYEE_BUTTON_WIDTH = 400\n # Choose customer kiosk button constants\n # For visual effect, most of these parameters are\n # Dynamically et to be equal to the first button\n CHOOSE_CLIENT_BUTTON_TOP = 350\n CHOOSE_CLIENT_BUTTON_LEFT = CHOOSE_EMPLOYEE_BUTTON_LEFT\n CHOOSE_CLIENT_BUTTON_HEIGHT = CHOOSE_EMPLOYEE_BUTTON_HEIGHT\n CHOOSE_CLIENT_BUTTON_WIDTH = CHOOSE_EMPLOYEE_BUTTON_WIDTH\n\nchoose_kiosk = ChooseKiosk()\n\n#######################\n# Client Kiosk Screen #\n#######################\n\nclass ClientKiosk:\n # Welcome Text constants\n WELCOME_TOP = 100\n WELCOME_WIDTH = 600\n WELCOME_LEFT = calculate_left(WELCOME_WIDTH) # Centered\n WELCOME_FONT_SIZE = 60\n # Splash Graphic constants\n SPLASH_TOP = 200\n SPLASH_HEIGHT = 639\n SPLASH_WIDTH = 662\n SPLASH_LEFT = calculate_left(SPLASH_WIDTH) # Centered\n # Instructions constants\n INSTRUCTIONS_TOP = 500\n INSTRUCTIONS_WIDTH = 600\n INSTRUCTIONS_LEFT = calculate_left(INSTRUCTIONS_WIDTH) # Centered\n INSTRUCTIONS_FONT_SIZE = 40\n # Barcode field constants\n BARCODE_FIELD_TOP = 625\n BARCODE_FIELD_WIDTH = 200\n BARCODE_FIELD_INPUT_WIDTH = 10\n BARCODE_FIELD_LEFT = calculate_left(BARCODE_FIELD_WIDTH) # Centered\n # Barcode image constants\n BARCODE_IMAGE_TOP = 675\n BARCODE_IMAGE_HEIGHT = 50\n BARCODE_IMAGE_WIDTH = 110\n BARCODE_IMAGE_LEFT = calculate_left(BARCODE_IMAGE_WIDTH) # Centered\n\nclient_kiosk = ClientKiosk()\n\n\n#########################\n# Client Kiosk Screen 2 #\n#########################\n\nclass ClientKiosk2:\n # Welcome text Constants\n INSTRUCTIONS_TOP = 100\n INSTRUCTIONS_WIDTH = 900\n INSTRUCTIONS_LEFT = calculate_left(INSTRUCTIONS_WIDTH)\n INSTRUCTIONS_FONT_SIZE = 60\n # Service buttons constants\n SERVICE_BUTTONS_TOP = 270\n SERVICE_BUTTONS_HEIGHT = 400\n SERVICE_BUTTONS_WIDTH = INSTRUCTIONS_WIDTH # Keep same for visual effect\n SERVICE_BUTTONS_LEFT = calculate_left(SERVICE_BUTTONS_WIDTH)\n # Cancel button constants\n CANCEL_BUTTON_HEIGHT = 70\n CANCEL_BUTTON_WIDTH = 150\n CANCEL_BUTTON_TOP = SCREEN_HEIGHT - CANCEL_BUTTON_HEIGHT\n CANCEL_BUTTON_LEFT = SCREEN_WIDTH - CANCEL_BUTTON_WIDTH\n\nclient_kiosk2 = ClientKiosk2()\n\n#########################\n# Client Kiosk Screen 3 #\n#########################\n\nclass ClientKiosk3:\n # You have selected constants\n HAVE_SELECTED_TOP = 100\n HAVE_SELECTED_WIDTH = 900\n HAVE_SELECTED_LEFT = calculate_left(HAVE_SELECTED_WIDTH)\n HAVE_SELECTED_FONT_SIZE = 60\n # Display box constants\n DISPLAY_BOX_TOP = 200\n DISPLAY_BOX_HEIGHT = 200\n DISPLAY_BOX_WIDTH = 300\n DISPLAY_BOX_LEFT = calculate_left(DISPLAY_BOX_WIDTH)\n DISPLAY_BOX_FONT_SIZE = 38\n # Is this correct constants\n IS_CORRECT_TOP = 415\n IS_CORRECT_WIDTH = HAVE_SELECTED_WIDTH # Keep same for visual effect\n IS_CORRECT_LEFT = calculate_left(IS_CORRECT_WIDTH)\n IS_CORRECT_FONT_SIZE = 60\n # Yes button constants\n YES_TOP = 525\n YES_HEIGHT = 100\n YES_WIDTH = 200\n # No button constants\n NO_TOP = YES_TOP # Keep same for visual effect\n NO_HEIGHT = YES_HEIGHT # Keep same for visual effect\n NO_WIDTH = YES_WIDTH # Keep same for visual effect\n # Calculate LEFT paramters for above buttons\n YES_LEFT = int(float(SCREEN_WIDTH - 3.0 * YES_WIDTH)/2.0)\n NO_LEFT = YES_LEFT + 2 * YES_WIDTH\n\nclient_kiosk3 = ClientKiosk3()\n\n\n#########################\n# Client Kiosk Screen 4 #\n#########################\n\nclass ClientKiosk4:\n # Thank you constants\n THANK_YOU_TOP = 100\n THANK_YOU_WIDTH = 900\n THANK_YOU_LEFT = calculate_left(THANK_YOU_WIDTH)\n THANK_YOU_FONT_SIZE = 60\n # Thank you constants\n MESSAGE_TOP = 200\n MESSAGE_WIDTH = THANK_YOU_WIDTH # Keep same for visual effect\n MESSAGE_LEFT = calculate_left(MESSAGE_WIDTH)\n MESSAGE_FONT_SIZE = 30\n # Loyalty box constants\n LOYALTY_BOX_TOP = 325\n LOYALTY_BOX_WIDTH = 800\n LOYALTY_BOX_LEFT = calculate_left(LOYALTY_BOX_WIDTH)\n LOYALTY_BOX_FONT_SIZE = 38\n # OK button constants\n OK_BUTTON_HEIGHT = 70\n OK_BUTTON_WIDTH = 150\n OK_BUTTON_TOP = SCREEN_HEIGHT - OK_BUTTON_HEIGHT\n OK_BUTTON_LEFT = SCREEN_WIDTH - OK_BUTTON_WIDTH\n\nclient_kiosk4 = ClientKiosk4()\n\n\n##############################\n# Employee Services Screen 1 #\n##############################\n\nclass EmployeeServices1:\n FIELDS_TOP = 150\n FIELDS_HEIGHT = 75\n FIELDS_WIDTH = 300\n FIELDS_LEFT = calculate_left(FIELDS_WIDTH)\n # Yes button constants\n START_TOP = 300\n START_HEIGHT = 75\n START_WIDTH = 150\n # No button constants\n FINISH_TOP = START_TOP # Keep same for visual effect\n FINISH_HEIGHT = START_HEIGHT # Keep same\n FINISH_WIDTH = START_WIDTH # Keep same\n # Cancel button constants\n CANCEL_TOP = START_TOP # Keep same for visual effect\n CANCEL_HEIGHT = START_HEIGHT # Keep same\n CANCEL_WIDTH = START_WIDTH # Keep same\n # Calculate LEFT parameters\n START_LEFT = int(float(SCREEN_WIDTH - 5.0 * START_WIDTH)/2.0) + 100\n FINISH_LEFT = START_LEFT + 2 * START_WIDTH\n CANCEL_LEFT = START_LEFT + 4 * START_WIDTH\n\nemployee_services1 = EmployeeServices1()\n\n\n\n##############################\n# Employee Services Screen 2 #\n##############################\n\nclass EmployeeServices2:\n # Services label constants\n LABEL_TOP = 200\n LABEL_HEIGHT = 50\n LABEL_WIDTH = 400\n LABEL_LEFT = calculate_left(LABEL_WIDTH)\n # Service box constants\n SERVICES_TOP = LABEL_TOP + LABEL_HEIGHT\n SERVICES_WIDTH = LABEL_WIDTH\n SERVICES_HEIGHT = 400\n SERVICES_LEFT = LABEL_LEFT # For visual effect\n # Yes button constants\n ACCEPT_TOP = 100\n ACCEPT_HEIGHT = 75\n ACCEPT_WIDTH = 150\n # No button constants\n CANCEL_TOP = ACCEPT_TOP # Keep same for visual effect\n CANCEL_HEIGHT = ACCEPT_HEIGHT # Keep same\n CANCEL_WIDTH = ACCEPT_WIDTH # Keep same\n # Calculate LEFT parameters\n ACCEPT_LEFT = int(float(SCREEN_WIDTH - 3.0 * ACCEPT_WIDTH)/2.0)\n CANCEL_LEFT = ACCEPT_LEFT + 2 * ACCEPT_WIDTH\n\nemployee_services2 = EmployeeServices2()\n\n\n\n##############################\n# Employee Services Screen 4 #\n##############################\n\nclass EmployeeServices4:\n # Service conducted constants\n SERVICES_CONDUCTED_TOP = 100\n SERVICES_CONDUCTED_WIDTH = 600\n SERVICES_CONDUCTED_LEFT = calculate_left(SERVICES_CONDUCTED_WIDTH)\n SERVICES_CONDUCTED_FONT_SIZE = 30\n # Price box constants\n PRICE_BOX_TOP = 150\n PRICE_BOX_WIDTH = 300\n PRICE_BOX_LEFT = calculate_left(PRICE_BOX_WIDTH)\n PRICE_BOX_FONT_SIZE = 40\n # Loyalty promotion constants\n LOYALTY_TOP = 350\n LOYALTY_WIDTH = SERVICES_CONDUCTED_WIDTH # Keep same\n LOYALTY_LEFT = calculate_left(LOYALTY_WIDTH)\n # Promotion phrase constants\n PROMO_TOP = 400\n PROMO_WIDTH = SERVICES_CONDUCTED_WIDTH # Keep same\n PROMO_LEFT = calculate_left(PROMO_WIDTH)\n PROMO_FONT_SIZE = 40\n # Original price constants\n ORIGINAL_PRICE_TOP = 500\n ORIGINAL_PRICE_WIDTH = SERVICES_CONDUCTED_WIDTH # Keep same\n ORIGINAL_PRICE_LEFT = calculate_left(ORIGINAL_PRICE_WIDTH)\n ORIGINAL_PRICE_FONT_SIZE = 20\n # Visit number constants\n VISIT_TOP = 550\n VISIT_WIDTH = SERVICES_CONDUCTED_WIDTH # Keep same\n VISIT_LEFT = calculate_left(VISIT_WIDTH)\n VISIT_FONT_SIZE = 20\n # Yes button constants\n YES_TOP = 600\n YES_HEIGHT = 75\n YES_WIDTH = 150\n # No button constants\n NO_TOP = YES_TOP # Keep same for visual effect\n NO_HEIGHT = YES_HEIGHT # Keep same\n NO_WIDTH = YES_WIDTH # Keep same\n # Cancel button constants\n CANCEL_TOP = YES_TOP # Keep same for visual effect\n CANCEL_HEIGHT = YES_HEIGHT # Keep same\n CANCEL_WIDTH = YES_WIDTH # Keep same\n # Calculate LEFT parameters\n YES_LEFT = int(float(SCREEN_WIDTH - 5.0 * YES_WIDTH)/2.0)\n NO_LEFT = YES_LEFT + 2 * YES_WIDTH\n CANCEL_LEFT = YES_LEFT + 4 * YES_WIDTH\n\nemployee_services4 = EmployeeServices4()\n\n\n\n\n\n\n\n\n\n\n\n\n############################\n# Employee Time Management #\n############################\n\nclass TimeManagement:\n # Input field constants\n INPUT_FIELD_WIDTH = 30\n # Time Management button area constants\n TIME_BUTTON_TOP = 260\n TIME_BUTTON_LEFT = 200\n TIME_BUTTON_HEIGHT = 400\n TIME_BUTTON_WIDTH = 800\n\ntime_management = TimeManagement()\n\n","sub_path":"caudae/kiosk_settings.py","file_name":"kiosk_settings.py","file_ext":"py","file_size_in_byte":9990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"143807487","text":"# Kai Chang - Caltech CMS-CERN 2016\n#\n# Program runs a cmsRun program on a large scale. Outputs a series of ROOT\n# files.\n#\n#\n# Needs to have a chosen file selected, and the filesname variable untampered,\n# Has to run on CMS environment (cmsenv)\n# =============================================================================\n\nimport sys, os\nimport fileinput\n\n## PARAMETERS YOU FILL IN ##\nfile_dir\t= './deep-learning/data/neutrinos.list'\nname\t\t= 'pdg12_pt35'\ndirname\t\t= 'neutrino_pt35'\n\n# open and create neutrino list file\nnfile = open(file_dir)\nlines = nfile.readlines()\nnfile.close()\n\n# checks to see if folder directory exists\n\nif not os.path.exists(dirname):\n\tos.makedirs(dirname)\n\nfor line in lines:\n\tf = open('particle_nosmear_calib.py', 'r')\n\toldfile = f.read()\n\tf.close()\n\n\tnewfile = oldfile.replace(\"eos/to/reco/root\", line[:-1])\n\n\tif line[-9] != '_': #single digit \n\t\tnewfile = newfile.replace(\"rootname\", name + \"_\" + str(line[-7]) + \".root\")\n\telse:\n\t\tnewfile = newfile.replace(\"rootname\", name + \"_\" + str(line[-8:-6]) + \".root\")\n\n\tf = open('particle_nosmear_calib.py', 'w')\n\tf.write(newfile)\n\tf.close()\n\n\t# runs the root processor\n\tos.system('cmsRun particle_nosmear_calib.py')\n\n\t# return to original format\n\tf = open('particle_nosmear_calib.py', 'w')\n\tf.write(oldfile)\n\tf.close()\n\ncmd = 'mv %s* ./%s/' %(name, dirname)\nos.system(cmd)\n","sub_path":"HGCalAnalysis/test/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"295422120","text":"from django.db import models\n\nfrom .time_point_status import TimePointStatus\n\n\nclass TimePointStatusMixin(models.Model):\n\n def save(self, *args, **kwargs):\n # TimePointStatus = models.get_model('data_manager', 'TimePointStatus')\n using = kwargs.get('using')\n if self.id:\n try:\n TimePointStatus.check_time_point_status(\n self.get_visit().appointment, using=using)\n except AttributeError:\n TimePointStatus.check_time_point_status(self.appointment, using=using)\n if 'is_off_study' in dir(self):\n if self.is_off_study():\n raise ValueError(\n 'Model cannot be saved. Subject is off study. Perhaps catch '\n 'this exception in forms clean() method.')\n super(TimePointStatusMixin, self).save(*args, **kwargs)\n\n class Meta:\n abstract = True\n","sub_path":"edc/data_manager/models/time_point_status_mixin.py","file_name":"time_point_status_mixin.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"265645893","text":"import collections\nimport json\nimport logging\nimport sys\n\nimport regex as re\nimport requests\nimport discord\n\nlog = logging.getLogger(__name__)\n\n\nclass ActionParser:\n bot = None\n\n @staticmethod\n def parse(raw_data=None, data=None):\n from greenbot.dispatch import Dispatch\n\n if not data:\n data = json.loads(raw_data)\n if data[\"type\"] == \"reply\":\n action = ReplyAction(\n data[\"message\"], ActionParser.bot, functions=data.get(\"functions\", \"\")\n )\n elif data[\"type\"] == \"privatemessage\":\n action = PrivateMessageAction(\n data[\"message\"], ActionParser.bot, functions=data.get(\"functions\", \"\")\n )\n elif data[\"type\"] == \"func\":\n action = FuncAction(getattr(Dispatch, data[\"cb\"]))\n elif data[\"type\"] == \"multi\":\n action = MultiAction(data[\"args\"], data[\"default\"])\n else:\n raise Exception(f\"Unknown action type: {data['type']}\")\n return action\n\n\nclass Function:\n function_regex = re.compile(\n r\"(?= index + 1\n else \"\"\n ),\n 1,\n )\n count += 1\n\n for sub_key in Substitution.substitution_regex.finditer(_input):\n needle = sub_key.group(0)\n filter_name = sub_key.group(1)\n args = sub_key.group(2)\n key = sub_key.group(8)\n array_args = []\n for arg in Substitution.args_sub_regex.finditer(args):\n array_args.append(\n revert_escape_args(Substitution.apply_subs(\n arg.group(1) if arg.group(1) else \"\", args, extra\n )[0])\n )\n\n final_sub = needle\n if filter_name in MappingMethods.subs_methods():\n resp, embed = MappingMethods.subs_methods()[filter_name](\n args=array_args, key=key, extra=extra\n )\n if embed != None:\n embeds.append(embed)\n final_sub = resp\n _input = _input.replace(\n needle, str(final_sub) if final_sub is not None else \"\", 1\n )\n count += 1\n if count > 0:\n _input, embeds_ = Substitution.apply_subs(_input, args, extra)\n embeds += embeds_\n return _input, embeds\n\n\nclass MappingMethods:\n bot = None\n\n @staticmethod\n def init(bot):\n MappingMethods.bot = bot\n\n @staticmethod\n def subs_methods():\n method_mapping = {}\n bot = MappingMethods.bot\n try:\n method_mapping[\"role\"] = bot.filters.get_role if bot else None\n method_mapping[\"_role\"] = bot.filters.get_role_value if bot else None\n method_mapping[\"member\"] = bot.filters.get_member if bot else None\n method_mapping[\"currency\"] = bot.filters.get_currency if bot else None\n method_mapping[\"user\"] = bot.filters.get_user if bot else None\n method_mapping[\"userinfo\"] = bot.filters.get_user_info if bot else None\n method_mapping[\"roleinfo\"] = bot.filters.get_role_info if bot else None\n method_mapping[\"commands\"] = bot.filters.get_commands if bot else None\n method_mapping[\"commandinfo\"] = (\n bot.filters.get_command_info if bot else None\n )\n method_mapping[\"time\"] = bot.filters.get_time_value if bot else None\n method_mapping[\"command\"] = bot.filters.get_command_value if bot else None\n method_mapping[\"author\"] = bot.filters.get_author_value if bot else None\n method_mapping[\"_channel\"] = bot.filters.get_channel_value if bot else None\n method_mapping[\"channel\"] = bot.filters.get_channel if bot else None\n method_mapping[\"emoji\"] = bot.filters.get_emoji_url if bot else None\n except AttributeError:\n pass\n return method_mapping\n\n @staticmethod\n def func_methods():\n method_mapping = {}\n bot = MappingMethods.bot\n try:\n method_mapping[\"kick\"] = bot.functions.func_kick_member if bot else None\n method_mapping[\"ban\"] = bot.functions.func_ban_member if bot else None\n method_mapping[\"unban\"] = bot.functions.func_unban_member if bot else None\n method_mapping[\"addrole\"] = (\n bot.functions.func_add_role_member if bot else None\n )\n method_mapping[\"removerole\"] = (\n bot.functions.func_remove_role_member if bot else None\n )\n method_mapping[\"level\"] = bot.functions.func_level if bot else None\n method_mapping[\"setpoints\"] = (\n bot.functions.func_set_balance if bot else None\n )\n method_mapping[\"adjpoints\"] = (\n bot.functions.func_adj_balance if bot else None\n )\n method_mapping[\"output\"] = bot.functions.func_output if bot else None\n method_mapping[\"embed\"] = bot.functions.func_embed_image if bot else None\n method_mapping[\"rename\"] = bot.functions.func_rename if bot else None\n except AttributeError:\n pass\n return method_mapping\n\n\nclass BaseAction:\n type = None\n subtype = None\n\n def reset(self):\n pass\n\n\nclass FuncAction(BaseAction):\n type = \"func\"\n\n def __init__(self, cb):\n self.cb = cb\n\n async def run(self, bot, author, channel, message, args):\n try:\n return await self.cb(\n bot=bot, author=author, channel=channel, message=message, args=args\n )\n except:\n log.exception(\"Uncaught exception in FuncAction\")\n\n\nclass RawFuncAction(BaseAction):\n type = \"rawfunc\"\n\n def __init__(self, cb):\n self.cb = cb\n\n async def run(self, bot, author, channel, message, args):\n return await self.cb(\n bot=bot, author=author, channel=channel, message=message, args=args\n )\n\n\nclass MultiAction(BaseAction):\n type = \"multi\"\n\n def __init__(self, args, default=None, fallback=None):\n from greenbot.models.command import Command\n\n self.commands = {}\n self.default = default\n self.fallback = fallback\n\n for command in args:\n cmd = Command.from_json(command)\n for alias in command[\"command\"].split(\"|\"):\n if alias not in self.commands:\n self.commands[alias] = cmd\n else:\n log.error(f\"Alias {alias} for this multiaction is already in use.\")\n\n import copy\n\n self.original_commands = copy.copy(self.commands)\n\n def reset(self):\n import copy\n\n self.commands = copy.copy(self.original_commands)\n\n def __iadd__(self, other):\n if other is not None and other.type == \"multi\":\n self.commands.update(other.commands)\n return self\n\n @classmethod\n def ready_built(cls, commands, default=None, fallback=None):\n \"\"\" Useful if you already have a dictionary\n with commands pre-built.\n \"\"\"\n\n multiaction = cls(args=[], default=default, fallback=fallback)\n multiaction.commands = commands\n import copy\n\n multiaction.original_commands = copy.copy(commands)\n return multiaction\n\n async def run(self, bot, author, channel, message, args):\n \"\"\" If there is more text sent to the multicommand after the\n initial alias, we _ALWAYS_ assume it's trying the subaction command.\n If the extra text was not a valid command, we try to run the fallback command.\n In case there's no extra text sent, we will try to run the default command.\n \"\"\"\n\n cmd = None\n if message:\n msg_lower_parts = message.lower().split(\" \")\n command = msg_lower_parts[0]\n cmd = self.commands.get(command, None)\n extra_msg = \" \".join(message.split(\" \")[1:])\n if cmd is None and self.fallback:\n cmd = self.commands.get(self.fallback, None)\n extra_msg = message\n elif self.default:\n command = self.default\n cmd = self.commands.get(command, None)\n extra_msg = None\n\n if cmd:\n if args[\"user_level\"] >= cmd.level:\n return await cmd.run(bot, author, channel, extra_msg, args)\n\n log.info(\n f\"User {author} tried running a sub-command he had no access to ({command}).\"\n )\n\n return None\n\n\ndef escape_args(args):\n return [x.replace(\"$\", \"\\\\$\").replace(\"'\", \"\\\\'\").replace(\"\\\"\", \"\\\\\\\"\") for x in args]\n\ndef revert_escape_args(resp):\n return resp.replace(\"\\\\$\", \"$\").replace(\"\\\\'\", \"'\").replace(\"\\\\\\\"\", \"\\\"\")\n\nclass MessageAction(BaseAction):\n type = \"message\"\n\n def __init__(self, response, bot, functions=\"\"):\n self.response = response\n self.functions = functions\n\n def get_response(self, bot, extra):\n MappingMethods.init(bot)\n if not self.response:\n return None, None\n\n resp, embeds = Substitution.apply_subs(\n self.response, escape_args(extra[\"message\"].split(\" \")), extra\n )\n return revert_escape_args(resp), embeds\n\n @staticmethod\n def get_extra_data(author, channel, message, args):\n return {\"author\": author, \"channel\": channel, \"message\": message, **args}\n\n async def run(self, bot, author, channel, message, args):\n raise NotImplementedError(\"Please implement the run method.\")\n\n\nclass ReplyAction(MessageAction):\n subtype = \"Reply\"\n\n async def run(self, bot, author, channel, message, args):\n extra = self.get_extra_data(author, channel, message, args)\n MappingMethods.init(bot)\n await Function.run_functions(\n self.functions,\n escape_args(extra[\"message\"].split(\" \")),\n extra,\n author,\n channel,\n args[\"whisper\"],\n bot,\n )\n\n resp, embeds = self.get_response(bot, extra)\n if not resp and not embeds:\n return True\n\n messages = []\n if resp:\n messages.append(\n await bot.private_message(author, resp)\n if args[\"whisper\"]\n else await bot.say(channel, resp)\n )\n for embed in embeds:\n messages.append(\n await bot.private_message(author, embed=embed)\n if args[\"whisper\"]\n else await bot.say(channel, embed=embed)\n )\n return True\n\n\nclass PrivateMessageAction(MessageAction):\n subtype = \"Private Message\"\n\n async def run(self, bot, author, channel, message, args):\n extra = self.get_extra_data(author, channel, message, args)\n MappingMethods.init(bot)\n await Function.run_functions(\n self.functions,\n extra[\"message\"].split(\" \"),\n extra,\n author,\n channel,\n args[\"whisper\"],\n bot,\n )\n\n resp, embeds = self.get_response(bot, extra)\n if not resp and not embeds:\n return True\n\n messages = []\n if resp:\n messages.append(await bot.private_message(author, resp))\n for embed in embeds:\n messages.append(await bot.private_message(author, embed=embed))\n return True\n","sub_path":"greenbot/models/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":13436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"62319846","text":"'''\nhttps://leetcode-cn.com/problems/word-ladder/\n127. 单词接龙\n'''\nclass Solution(object):\n def ladderLength(self, beginWord, endWord, wordList):\n \"\"\"\n :type beginWord: str\n :type endWord: str\n :type wordList: List[str]\n :rtype: int\n \"\"\"\n if endWord not in wordList: return 0\n wordList = set(wordList)\n front = {beginWord}#向后扩散\n back = {endWord}#向前扩散\n step = 1\n while front:\n step += 1\n tempSet = set()#临时集合\n for word in front:\n for i in range(len(word)):\n for c in string.lowercase:\n next_word = word[:i] + c + word[i+1:]#并不改变word本身\n if next_word in back:#相遇时返回\n return step\n if next_word in wordList:\n tempSet.add(next_word)#加入新的节点\n wordList.remove(next_word)#同时从字典中删除\n front = tempSet#临时集合 赋给front\n if len(front) > len(back):#比较哪个集合扩散得到的节点少,从少的继续扩散\n front, back = back, front\n return 0\n","sub_path":"Week_05/Leetcode_127.py","file_name":"Leetcode_127.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"154949671","text":"import numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom loadData import preProcess, filterColumn\n\n# Load and preprocess data \ndf = preProcess('./data/athlete_events.csv')\n\n# select summer games only\ndf = filterColumn(df, 'Season', 'Summer')\n# select a subset of data and drop duplicate ID from the same year\ndf = df[['Year', 'ID', 'Age', 'Sex']].drop_duplicates(['Year', 'ID']).reset_index(drop=True)\n\n# drop ID column\ndf.drop('ID', axis=1, inplace=True)\ndf2 = df.copy()\ndf.set_index(['Year','Sex'], inplace=True, append=True)\n#group by year and sex columns, and calculate average age for each group\ndf_grouped = df.groupby(level=['Year', 'Sex'])['Age'].mean()\n# Move 'Sex' level out of row index to columns index\navg_age_vs_time = df_grouped.unstack()\n\nfig, ax = plt.subplots(figsize=(8, 6))\n\navg_age_vs_time.plot(ax = ax, linewidth=3)\nsns.scatterplot(x=\"Year\", \ny=\"Age\", \ndata=df2,\nhue=\"Sex\",\ns=14,\nalpha=0.4,\nedgecolor='none',\npalette={\"Male\": \"#18a1cd\", \"Female\":\"#fa8c00\"})\n# add legend, x and y labels, x ticks and title\nax.legend(labels=['Men', 'Women'],bbox_to_anchor=(1.0, 1.0))\n\nax.set_xlabel('Year', size=14, labelpad=10)\nax.set_ylabel('Average age (years)', size=14, labelpad=10)\nax.set_title(\"Average age of Hungarian athletes in the Olympics\", pad=20, weight='heavy')\n\nyears = list(range(1896, 2022, 8))\nplt.xticks(years)\n\nplt.tight_layout()\nplt.show()","sub_path":"data_visualization/src/avg_age_scatter.py","file_name":"avg_age_scatter.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"626420392","text":"# Copyright 2017 Google Inc.\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# http://www.apache.org/licenses/LICENSE-2.0\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 gapit_test_framework import gapit_test, require, require_equal\nfrom gapit_test_framework import require_not_equal, little_endian_bytes_to_int\nfrom gapit_test_framework import GapitTest, get_read_offset_function\nfrom struct_offsets import VulkanStruct, UINT32_T, SIZE_T, POINTER\nfrom struct_offsets import HANDLE, FLOAT, CHAR, ARRAY\nfrom vulkan_constants import *\n\nPIPELINE_CACHE_CREATE_INFO = [\n (\"sType\", UINT32_T),\n (\"pNext\", POINTER),\n (\"flags\", UINT32_T),\n (\"initialDataSize\", SIZE_T),\n (\"pInitialData\", POINTER),\n]\n\n\n@gapit_test(\"PipelineCache_test\")\nclass EmptyPipelineCache(GapitTest):\n\n def expect(self):\n architecture = self.architecture\n device_properties = require(self.next_call_of(\n \"vkGetPhysicalDeviceProperties\"))\n\n create_pipeline_cache = require(self.nth_call_of(\n \"vkCreatePipelineCache\", 1))\n destroy_pipeline_cache = require(self.next_call_of(\n \"vkDestroyPipelineCache\"))\n\n pipeline_cache_create_info = VulkanStruct(\n architecture, PIPELINE_CACHE_CREATE_INFO, get_read_offset_function(\n create_pipeline_cache, create_pipeline_cache.hex_pCreateInfo))\n\n require_equal(VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO,\n pipeline_cache_create_info.sType)\n require_equal(0, pipeline_cache_create_info.pNext)\n require_equal(0, pipeline_cache_create_info.flags)\n require_equal(0, pipeline_cache_create_info.initialDataSize)\n require_equal(0, pipeline_cache_create_info.pInitialData)\n\n require_not_equal(0, destroy_pipeline_cache.int_device)\n require_not_equal(0, destroy_pipeline_cache.int_pipelineCache)\n","sub_path":"gapid_tests/resource_creation_tests/PipelineCache_test/PipelineCache_test.py","file_name":"PipelineCache_test.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"343432488","text":"#!/usr/bin/env python3\n\nimport logging\nimport subprocess\nimport time\nimport json\nfrom io import BytesIO\n\n\nclass RunCommandTimeoutError(Exception):\n def __init__(self, cmd, timeout, msg=''):\n super(RunCommandTimeoutError, self).__init__()\n self.args = (msg if msg else \"Error: Run Command Timeout [%s s]: {%s}\" % (timeout, cmd), )\n\n\ndef run_command(cmd, branch=True, timeout=30, logger=None):\n logger = logger if logger else logging.getLogger()\n logger.debug(cmd)\n p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)\n t_beginning = time.time()\n out = BytesIO()\n while True:\n if p.poll() is not None:\n break\n data = p.stdout.read()\n out.write(data)\n seconds_passed = time.time() - t_beginning\n if timeout and seconds_passed > timeout:\n p.terminate()\n raise RunCommandTimeoutError(cmd, timeout)\n time.sleep(0.01)\n return_code = p.returncode\n output_raw = out.getvalue()\n try:\n output = output_raw.decode()\n except Exception as e:\n logger.exception(\"output_raw.decode exception: %s\", e)\n try:\n output = output_raw.decode('utf-8')\n except Exception as e:\n logger.exception(\"output_raw.decode utf-8 exception: %s\", e)\n output = output_raw.decode('gbk')\n if branch:\n return return_code, [x for x in output.strip().strip('\\n').split('\\n') if not x == '']\n else:\n return return_code, output\n\n\ndef get_ip_link():\n ifn_ip = dict()\n cmd = \"ip -br a\"\n status, result = run_command(cmd)\n if status == 0:\n for line in result:\n words = line.split()\n if len(words) > 2:\n if words[2] and words[0] not in [\"lo\", \"docker0\"]:\n ip_addr = words[2].split()[0].split(\"/\")[0]\n if ip_addr:\n ifn_ip[ip_addr] = words[0].split(\"@\")[0]\n return ifn_ip\n\n\ndef get_index_of_string(string, string_list):\n index = None\n for i, x in enumerate(string_list):\n if x.startswith(string):\n index = i\n break\n return index\n\n\ndef split_ss_addr(ip_string):\n if ']' in ip_string:\n ip = ip_string.split(\"]\")[0].split(\":\")[-1]\n else:\n ip = ip_string.split(\":\")[0]\n\n ip = ip.split(\"%\")[0]\n return ip\n\n\ndef parse_output(data):\n tcp_send_out = dict()\n tcp_retrans = dict()\n ip_set = set()\n for line in data:\n words = line.split()\n if words[0] == \"ESTAB\":\n ip = split_ss_addr(words[3])\n if ip in [\"127.0.0.1\"]:\n continue\n s_index = get_index_of_string(\"segs_out\", words)\n if s_index is None:\n continue\n segs_out = int(words[s_index].split(\":\")[1])\n ip_set.add(ip)\n if tcp_send_out.get(ip):\n tcp_send_out[ip] += segs_out\n else:\n tcp_send_out[ip] = segs_out\n\n if \"retrans\" in line:\n index = get_index_of_string(\"retrans\", words)\n if index is None:\n continue\n\n retrans_segs = int(words[index].split(\":\")[1].split(\"/\")[1])\n\n if tcp_retrans.get(ip):\n tcp_retrans[ip] += retrans_segs\n else:\n tcp_retrans[ip] = retrans_segs\n return ip_set, tcp_send_out, tcp_retrans\n\n\ndef get_tcp_retrans():\n ifn_ip = get_ip_link()\n tcp_send_out, tcp_retrans_segs, tcp_retrans_dict = dict(), dict(), dict()\n ip_set = set()\n cmd = \"ss -nit |grep -v 'Address:Port' | xargs -L 1\"\n status, result = run_command(cmd)\n if status == 0:\n ip_set, tcp_send_out, tcp_retrans_segs = parse_output(result)\n\n for i in ip_set:\n if ifn_ip.__contains__(i) and tcp_retrans_segs.__contains__(i):\n tmp = float(tcp_retrans_segs[i]) / float(tcp_send_out[i]) * 100\n tcp_retrans_dict[ifn_ip[i]] = tmp\n\n return json.dumps(tcp_retrans_dict)\n\n\nif __name__ == '__main__':\n tcp_retrans_result = get_tcp_retrans()\n print(tcp_retrans_result)\n","sub_path":"project_python/work_tools/line_tcp_retrans.py","file_name":"line_tcp_retrans.py","file_ext":"py","file_size_in_byte":4141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"331917337","text":"# doctor that up so visit will show it\nds=xr.open_dataset('dispersion_K_v02_wsmooth.nc')\n\nds['time']=('time',), [np.datetime64(\"2014-04-01 00:00\")]\n\nfor v in ['K','Ksmooth']:\n K=ds[v].values[None,:].copy()\n K[np.isnan(K)] = -999\n\n ds[v]=('time','face'),K\n\nds.to_netcdf('K_v02_with_time.nc')\nds.close()\n","sub_path":"ptm/dispersion_map/disp_to_nc.py","file_name":"disp_to_nc.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"72844214","text":"# V1.05_final\nfrom random import choice\nfrom Siga import showBoard\n\n\n# global list used to insert (1 or more user's) or the computer's input.\nslots = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']\n# demo list to show the user how to use the board.\ndemo = ['1', '2', '3', '4', '5', '6', '7', '8', '9']\n\n\ndef help():\n '''prints game manual'''\n print('''hello! this is TicTacToe made by Adham and supervised by our team '3x3.'\nthe concept is pretty simple, you choose whether you want to play with the computer or with your friend and based on turns\neach player will try to hit his/her letter (X or O) horizontally, vertically, or diagonally in 3 slots.\nwho ever claims three consecutive of his letter, Wins the game!\n''')\n\n\ndef SingleOrMulti():\n '''multiplayer / single player checker\n returning string that is either 'single' or 'multi'''\n\n gametype = ''\n # loop to keep asking the user for one of the two inputs, y or n.\n while gametype == '':\n mode = input('are you alone? y for yes and n for no please.')\n if mode == 'y':\n gametype += 'single'\n print(\"alright! you'll play with Ultron :)\")\n return gametype\n elif mode == 'n':\n print(\"oh, you are with a friend. this will be interesting.\")\n gametype += 'multi'\n return gametype\n else:\n print('oh-oh. use y for yes and n for no. no capitalization.')\n\n\ndef shwBoard(board): # function that calls the board, imported.\n '''function that calls showboard function from the siga.py file'''\n\n # print('' +board[3]+ ' | ' +board[4]+ ' | '+board[5] ) \\/\\/\\/\\/\\/\n # print('' +board[0]+ ' | ' +board[1]+ ' | '+board[2] ) old board\n # print('' +board[6]+ ' | ' +board[7]+ ' | '+board[8] ) /\\/\\/\\/\\/\\\n # print('-------------')\n\n showBoard(board, Labels=False)\n\n\ndef whosfirst():\n '''player1 chooses who goes first, returning whether P1 is playing W comp or P2 as a string'''\n\n answertype = ''\n while answertype == '':\n # loop to keep asking the user for one of the two inputs, y or n\n answer = input(\n 'Player 1, do you wanna go first? y for yes and n for no please.')\n if answer == 'y':\n print('okay! good luck. make your first move player 1.')\n answertype += 'yes'\n return answertype\n elif answer == 'n':\n print('okay! good luck player 1, your opponent is going first.')\n answertype += 'no'\n return answertype\n else:\n print('please stick with y for yes and n for no, no capitalization.')\n\n\ndef emptyspace(plyr_mve):\n '''function that identifies blank spaces in the global list (slot)\n while returning boolean True/False'''\n if slots[plyr_mve] == ' ':\n return True\n else:\n return False\n\n\ndef compmove():\n '''Function that loops random no choices no from range 0 to 8.\n if the choice is not taken,checked by empytyspace,\n the choice is saved in the global list (slots)\n if not the loop starts again.'''\n\n state = bool\n while state != True:\n\n x = choice(list(range(8)))\n y = emptyspace(x)\n state = y\n\n if state == True:\n slots[x] = 'O'\n shwBoard(slots)\n\n\ndef player1move(symb):\n '''function that lets the player choose\n his move and stores it into (slots) list '''\n\n shwBoard(demo)\n while True:\n loc = input(\n \"choose your move's place from 1-9 as stated in the board infront of you\")\n if loc.isnumeric(): # checks if input is a number. flo\n possible = (\n float(eval(loc)) == 1.0 or float(eval(loc)) == 2.0 or float(eval(loc)) == 3.0 or\n float(eval(loc)) == 4.0 or float(eval(loc)) == 5.0 or float(eval(loc)) == 6.0 or\n float(eval(loc)) == 7.0 or float(eval(loc)) == 8.0 or float(eval(loc)) == 9.0\n )\n # checks if the input after being filtered is between 1-9 whole numbers.\n if possible == True:\n if emptyspace(eval(loc)-1) == True:\n slots[eval(loc)-1] = symb\n shwBoard(slots)\n\n break\n\n else: # repeats the loop if number exceeds 9 or lower 1\n print('please choose between 1-9 only!!')\n else: # repeats loop if user inputs anything other than numeric values\n print('dont use complex expression.')\n\n\ndef boardfull():\n '''checks if the board is full and\n prints that game has ended and returns a true val.'''\n\n marker = 0 # initializer\n for i in slots:\n if i == ' ':\n marker += 1\n return False\n if marker == 0:\n print(\"oh no it's a draw.\")\n return True\n\n\ndef checkwin(symb):\n '''checks if the designated player X or O\n has won and returns their status'''\n status = True # initializing condition\n\n possible = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6],\n [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]\n # possible winning combinations.\n for item in possible:\n emp_lst = []\n for i in item:\n # adding correlating items from possible with slots\n emp_lst.append(slots[i])\n if emp_lst[0] != ' ' and emp_lst[0] == emp_lst[1] and emp_lst[1] == emp_lst[2]:\n if emp_lst[0] == symb: # prints that the designated player won\n print('you won player using letter {}!'.format(symb))\n status = True\n\n return status\n\n\ndef Gene_checkwin():\n '''Checks if either of players has won.\n similar to checkwin(f) but generalized to be\n used as an initial starting condition'''\n status = False # initializing condition false since no one wins at the start\n\n possible = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6],\n [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]\n\n for item in possible:\n emp_lst = []\n for i in item:\n emp_lst.append(slots[i])\n if emp_lst[0] != ' ' and emp_lst[0] == emp_lst[1] and emp_lst[1] == emp_lst[2]:\n\n status = True\n else:\n status = False\n\n return status\n else:\n status = False\n return status\n\n\ndef runGame():\n ''' the central code that runs the game'''\n help() # introduces player to the rules and the team\n mode = SingleOrMulti() # user chooses game mode\n if mode == 'multi':\n if whosfirst() == 'yes': # if player chooses to go first\n while Gene_checkwin() == False:\n # initial condition\n player1move('X') # P1 moves\n if checkwin('X') == True: # if P1 \"X\" wins game breaks and player wins\n break\n else: # ends P1 turn\n if boardfull() != True: # checks draw\n if checkwin('O') != True:\n # initial condition\n player1move('O') # P2 moves\n # if P2 \"O\" wins game breaks and player wins\n if checkwin('O') == True:\n break\n else: # end P2 turn\n if boardfull() == True: # checks draw\n break\n else:\n break\n\n else: # if P2 is going to start first\n while Gene_checkwin() == False:\n # initial condition\n player1move('O') # P2 moves\n if checkwin('O') == True: # if P2 \"O\" wins game breaks and player wins\n break\n else: # end P2 turn\n if boardfull() != True: # checks draw\n if checkwin('X') != True:\n # initial condition\n player1move('X') # P1 moves\n \n if checkwin('X') == True: # if P1 \"X\" wins game breaks and player wins\n break\n else:\n if boardfull() == True: # checks draw\n break\n else:\n break\n\n if mode == 'single': # if player chooses single with comp\n if whosfirst() == 'yes': # player chooses to go first\n while Gene_checkwin() == False:\n '''^^^ initial condition ^^^'''\n player1move('X') # P1 moves\n if checkwin('X') == True: # if P1 \"X\" wins game breaks and player wins\n break\n else: # ends P1 turn\n if boardfull() != True: # checks draw\n if checkwin('O') != True:\n # initial condition\n compmove() # comp moves\n # if COMP \"O\" wins game breaks and player wins\n if checkwin('O') == True:\n break\n else: # end COMP turn\n if boardfull() == True: # checks draw\n break\n else:\n break\n\n else: # COMP goes first\n while Gene_checkwin() == False:\n # initial condition\n compmove() # COMP moves\n if checkwin('O') == True: # if COMP \"O\" wins game breaks and player wins\n break\n else: # end COMP turn\n if boardfull() != True: # checks draw\n if checkwin('X') != True:\n # initial condition\n player1move('X') # P1 moves\n # if P1 \"X\" wins game breaks and player wins\n if checkwin('X') == True:\n break\n else: # end P1 turn\n if boardfull() == True: # checks draw\n break\n else:\n break\n","sub_path":"game/TicTacToe.py","file_name":"TicTacToe.py","file_ext":"py","file_size_in_byte":10213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"488952767","text":"print(\"Welcome to the Cave Trivia Game\")\nyourName = input(\"what is your name ?\")\nprint(yourName, \", Are you ready to play and get a trip to the Amazing Bora Bora ? Let's go!! Good luck Adventurer\")\ntrollCaveChoice = input(\"Would you like to enter the troll cave, Adventurer?\" \"Choose yes or no?\",)\ntrollCaveChoice = trollCaveChoice.lower()\n\n# if you output yes, you get to answer the Kennedy question\nif trollCaveChoice == \"yes\":\n kennedyQuestion = input(\"Who was the 35th President of America? Kennedy or Roosevelt?\")\n kennedyQuestion = kennedyQuestion.lower()\n # if you answer kennedy, you get closer to the prize\n if kennedyQuestion == \"kennedy\":\n print(yourName, \", You are almost there Adventurer!!\", sep=\"\")\n # if you answer anything other than kennedy, you don't win the prize\n if not(kennedyQuestion == \"kennedy\"):\n print(\"Oh shucks\", yourName, \"you can't make it to Bora Bora\")\n # if your answer was not kennedy, the game proceeds the user to the taller mountain quesion\n else:\n tallestMountainQuestion = int(input(\"How tall is the Mt. Everest?\"))\n # If answer is greater or less than 26000, the output is that you don't get to bora bora\n if tallestMountainQuestion != 26000:\n print(\"Oh shucks, \", yourName, \" , you can't make it to Bora Bora\" , sep = \"\")\n # if the answer is 26000, then the game encourages you and asks about the Largest Lake Question\n else:\n print(yourName, \", one more question Adventurer!! Keep at it!!\", sep = \"\")\n largestLakeQuestion = input(\"Name the Largest Freshwater lake in the world?\" )\n largestLakeQuestion = largestLakeQuestion.lower()\n # if largest lake equals to lake superior, then code prints you get to go to bora bora\n if largestLakeQuestion == \"lake superior\":\n print(yourName, \", You get to go to Bora Bora\", sep=\"\")\n # if largest lake does not equal to lake superior, the code prints you can't make it to bora bora\n else:\n print(\"Oh shucks\", yourName, \"you can't make it to Bora Bora\" , sep = \"\")\n# if you choose not to go to the Troll cave, the game asks if you want to go to the fairy cave\nelse:\n fairyCaveOption = input(\"Would you like to enter the Fairy Cave, Adventurer? Choose yes or no?\")\n fairyCaveOption = fairyCaveOption.lower()\n # if input equals to yes, the program proceeds to asking the decimal questiom\n if fairyCaveOption ==\"yes\":\n decimalQuestion = float(input(\"What is 12//100?\"))\n # if answer is less than .12, you don't get to go to Bora Bora\n if decimalQuestion < .12:\n print(\"\")\n print(\"Oh shucks, \", yourName, \" , you can't make it to Bora Bora\" , sep = \"\")\n # if answer equals to .12, you get to go to Bora Bora\n elif decimalQuestion ==.12:\n print(yourName, \", You get to go to Bora Bora\", sep=\"\")\n # if answer is greater than .12, you get redirected to the world war question\n elif decimalQuestion > .12:\n worldWarQuestion = input(\"Who won World War II? Allied Powers or Axis Power? \")\n worldWarQuestion = worldWarQuestion.lower( )\n # if answer equals to allied powers, you get to go to bora bora\n if worldWarQuestion == \"allied powers\":\n print(yourName, \", You get to go to Bora Bora\", sep=\"\")\n # if answer does not equal to allied powers, you do not go to Bora Bora\n else:\n print(\"Oh shucks,\", yourName, \",you can't make it to Bora Bora\", sep=\"\")\n\n # If user does not want to enter the troll cave or fairy cave, you automatically enter the dragon cave and immediately asked a question\n else:\n dragonCaveChoice = input(\"What is the name of the inventor who invented the light bulb? a) Edison b) Einstein ?\")\n dragonCaveChoice = dragonCaveChoice.lower()\n #if answer equals to edison, you get to go to Bora Bora\n if dragonCaveChoice == \"edison\":\n print(yourName, \", You get to go to Bora Bora\", sep=\"\")\n #if answer does not equal edison, you can't make it to Bora Bora\n else:\n print(\"Oh shucks, \", yourName, \" , you can't make it to Bora Bora\", sep=\"\")\n\nprint (\"Thank you for playing the Cave Trivia game, Play some other time!\")\n\n\n","sub_path":"ChiamakaG.NPA2.py","file_name":"ChiamakaG.NPA2.py","file_ext":"py","file_size_in_byte":4356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"537270136","text":"from flask import request\nimport collections\nfrom flask_restful import Resource, marshal, marshal_with\nfrom flask_login import login_required\n\nfrom app.services.models.attendance import Attendance\nfrom app.services.forms.attendances import CreateAttendanceForm, EditAttendanceForm\nfrom app import db\nfrom app.services.repositories import AttendanceRepo\nfrom ..helpers import *\nfrom app.authentications.decorators import user_has\nfrom app.services.permissions import EmployeeAttendances\n\nattendanceRepo = AttendanceRepo(db, Attendance)\n\nattendance_fields = collections.OrderedDict()\n\nattendance_fields['id'] = fields.Integer\nattendance_fields['employee_id'] = fields.Integer\nattendance_fields['employee'] = fields.String\n\nattendance_fields['attendanceDate'] = fields.DateTime(dt_format='iso8601')\nattendance_fields['arriveTime'] = fields.DateTime(dt_format='iso8601')\nattendance_fields['leaveTime'] = fields.DateTime(dt_format='iso8601')\n\nattendance_fields['$self'] = fields.Url(\"apisMod.employee_attendance\")\n\nattendances_fields = dict(paginate_fields)\nattendances_fields['items'] = fields.List(fields.Nested(attendance_fields))\n\n\nclass AttendanceApi(Resource):\n @login_required\n @marshal_with(attendance_fields)\n @user_has(EmployeeAttendances.show)\n def get(self, id):\n entity = attendanceRepo.get(id)\n if entity is None:\n return notFoundResponse()\n return entity\n\n @login_required\n @user_has(EmployeeAttendances.delete)\n def delete(self, id):\n entity = attendanceRepo.get(id)\n if entity is None:\n return notFoundResponse()\n\n if isSuperUser():\n attendanceRepo.remove(entity)\n else:\n return notAuthorizedResponse()\n\n return successResponse()\n\n @login_required\n @user_has(EmployeeAttendances.update)\n def put(self, id):\n entity = attendanceRepo.get(id)\n if entity is None:\n return notFoundResponse()\n\n form = EditAttendanceForm(obj=entity)\n\n if form.validate():\n form.populate_obj(entity)\n\n attendanceRepo.save(entity)\n return successResponse()\n\n return unableToProcessResponse(form.errors)\n\n\nclass AttendancesApi(Resource):\n @login_required\n @user_has(EmployeeAttendances.list)\n def get(self):\n\n # handle pagination\n parser = paginageParser.copy()\n parser.add_argument('active', type=str)\n parser.add_argument('employee_id', type=int)\n parser.add_argument('attendanceDate', type=str)\n\n args = parser.parse_args()\n page = args.get('page')\n limit = args.get('limit')\n\n active = args.get('active')\n employee_id = args.get('employee_id')\n attendanceDate = args.get('attendanceDate')\n # type = args.get('type')\n\n # handle search\n q = request.args.get('q')\n\n if q:\n return marshal(attendanceRepo.search(q), attendances_fields)\n\n if attendanceDate:\n attendanceRepo.getByDate(attendanceDate)\n\n if employee_id:\n attendanceRepo.getByEmployee(employee_id)\n\n if q:\n return marshal(attendanceRepo.search(q), attendances_fields)\n\n return marshal(attendanceRepo.paginate(page, limit, False), attendances_fields)\n\n # return marshal(doctorRepo.paginate(page, limit, False), users_fields)\n\n @login_required\n @user_has(EmployeeAttendances.create)\n def post(self):\n form = CreateAttendanceForm()\n\n if form.validate():\n entity = Attendance(**form.data)\n attendanceRepo.save(entity)\n return createdResponseWithPayload(marshal(entity, attendance_fields))\n\n return unableToProcessResponse(form.errors)\n","sub_path":"app/api/resources/attendances.py","file_name":"attendances.py","file_ext":"py","file_size_in_byte":3743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"164037203","text":"''' A handful of words have their letters in alphabetical order,\nthat is nowhere in the word do you change direction in the word if\nyou were to scan along the English alphabet. An example is the word\n\"almost\", which has its letters in alphabetical order.\n\nYour challenge today is to write a program that can determine if the\nletters in a word are in alphabetical order.\n\nAs a bonus, see if you can find words spelled in reverse alphebatical order.\n'''\n\ndef alpha_order(lst):\n out_list = []\n for word in lst:\n state = 0\n for x in range(1, len(word)):\n if word[x] >= word[x - 1]:\n if x == len(word) - 1 and state == 0:\n out_list.append((word, ' IN ORDER'))\n if x == len(word) - 1 and state == 1:\n out_list.append((word, ' IN REVERSE ORDER'))\n continue\n else:\n state += 1\n if state == 2:\n out_list.append((word, 'OUT OF ORDER'))\n word = word[::-1]\n continue\n return out_list\n\n\nif __name__ == '__main__':\n\n word_list = ['billowy', 'biopsy', 'chinos', 'defaced', 'chintz', 'sponged','bijoux',\n 'abhors', 'fiddle', 'begins', 'chimps', 'wronged']\n ans = alpha_order(word_list)\n for x in range(0, len(ans)):\n print(ans[x][0].strip(''),ans[x][1].strip(''))","sub_path":"albums/3/challenge228_easydev/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"403127414","text":"import os\nimport time\nimport threading\nfrom .events import StopEvent, RevolutionEvent, SessionStartEvent, SessionEndEvent\n\n\nclass FileLogger(threading.Thread):\n def __init__(self, queue, persist_dir):\n super(FileLogger, self).__init__()\n\n self.queue = queue\n self.persist_dir = persist_dir\n\n self.persist_file = None\n\n def run(self):\n while True:\n event = self.queue.get()\n\n if isinstance(event, RevolutionEvent):\n self.on_revolution(event)\n\n if isinstance(event, SessionStartEvent):\n self.on_session_start(event)\n\n if isinstance(event, SessionEndEvent):\n self.on_session_stop(event)\n\n self.queue.task_done()\n\n def on_revolution(self, event):\n # Write a millisecond-accurate, UTC timestamp to the file\n # Datetime -> timestamp with milliseconds https://stackoverflow.com/a/8159893\n dt = event.timestamp\n timestamp = int((time.mktime(dt.utctimetuple()) + dt.microsecond / 1000000.0)*1000)\n\n if self.persist_file is None:\n self.open_persist_file(event.timestamp)\n\n self.persist_file.write(str(timestamp) + \"\\n\")\n\n def on_session_start(self, event):\n self.open_persist_file(event.started_at)\n\n def open_persist_file(self, timestamp):\n filename = \"cyclelog-%s.log\" % timestamp.strftime(\"%Y%m%d%H%M%S\")\n persist_file_path = os.path.join(self.persist_dir, filename)\n\n self.persist_file = open(persist_file_path, 'a')\n\n def on_session_stop(self, event):\n if self.persist_file:\n self.persist_file.close()\n self.persist_file = None\n\n","sub_path":"onboard/cycles/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"353802647","text":"import json\nfrom msa_sdk.variables import Variables\nfrom msa_sdk.msa_api import MSA_API\nfrom msa_sdk.order import Order\n\n# List all the parameters required by the task\ndev_var = Variables()\ndev_var.add('profile', var_type='String')\n#dev_var.add('gateway', var_type='String')\ncontext = Variables.task_call(dev_var)\n\n# read the ID of the selected managed entity\ndevice_id = context['device']\nobject_id = context['gateway']\nprofile = context['profile']\n\n# extract the database ID\ndevicelongid = device_id[-3:]\n\n# build the Microservice JSON params for IMPORT\n#{\"Gateway\":\"0\"}\n#micro_service_vars_array = {\"object_id\":object_id}\n\ngateway = {\"Gateway\":\"0\"}\n\n# call the CREATE for simple_firewall MS for each device\norder = Order(devicelongid)\norder.command_execute('IMPORT', gateway)\n\n# convert dict object into json\ncontent = json.loads(order.content)\n\n# check if the response is OK\nif order.response.ok:\n ret = MSA_API.process_content('ENDED',\n f'STATUS: {content[\"status\"]}, \\\n MESSAGE: {profile} activated on {object_id}',\n context, True)\nelse:\n ret = MSA_API.process_content('FAILED',\n f'Import failed \\\n - {order.content}',\n context, True)\n\n\nprint(ret)\n","sub_path":"Checkpoint/Good_Better_Best/New_Synchronise.py","file_name":"New_Synchronise.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"395911595","text":"# coding: utf-8\nimport logging\nimport re\nimport subprocess\nimport threading\nimport time\nfrom datetime import datetime\n\nimport docker\nfrom docker import errors\nfrom docker import types\nfrom docker import utils\nfrom .nodes_trace import NodesTrace\n\n\nclass Benchmark:\n \"\"\"\n Author: Jocelyn Thode\n\n A class in charge of Setting up and running a benchmark\n \"\"\"\n\n def __init__(self, app_config, cluster_config, local, use_tracker,\n churn=None,\n client=docker.DockerClient(\n base_url='unix://var/run/docker.sock')):\n self.client = client\n self.app_config = app_config\n self.cluster_config = cluster_config\n self.local = local\n self.logger = logging.getLogger('benchmarks')\n self.churn = churn\n self.use_tracker = use_tracker\n\n def run(self, time_add, time_to_run, peer_number, runs=1):\n \"\"\"\n Run the benchmark\n\n :param peer_number: How many starting peers\n :param time_add: How much time before starting the benchmark\n :param time_to_run: How much time to run the benchmark for\n :param runs: RUn the benchmark how many time\n \"\"\"\n time_add *= 1000\n time_to_run *= 1000\n if self.local:\n service_image = self.app_config['service']['name']\n if self.use_tracker:\n tracker_image = self.app_config['tracker']['name']\n with subprocess.Popen(['../gradlew', '-p', '..', 'docker'],\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n universal_newlines=True) as p:\n for line in p.stdout:\n print(line, end='')\n else:\n service_image = (self.app_config['repository']['name']\n + self.app_config['service']['name'])\n self.logger.info(self.client.images.pull(service_image))\n\n if self.use_tracker:\n tracker_image = (self.app_config['repository']['name']\n + self.app_config['tracker']['name'])\n self.logger.info(self.client.images.pull(tracker_image))\n\n try:\n self.client.swarm.init()\n if not self.local:\n self.logger.info('Joining Swarm on every hosts:')\n token = self.client.swarm.attrs['JoinTokens']['Worker']\n subprocess.call(\n [\n 'parallel-ssh',\n '-t',\n '0',\n '-h',\n 'config/hosts',\n 'docker',\n 'swarm',\n 'join',\n '--token',\n token,\n '{:s}:2377'.format(\n self.cluster_config['manager_ip'])])\n ipam_pool = utils.create_ipam_pool(\n subnet=self.app_config['service']['network']['subnet'])\n ipam_config = utils.create_ipam_config(\n pool_configs=[ipam_pool])\n self.client.networks.create(\n self.app_config['service']['network']['name'],\n driver='overlay', ipam=ipam_config)\n except errors.APIError:\n self.logger.info('Host is already part of a swarm')\n if not self.client.networks.list(\n names=[self.app_config['service']['network']['name']]):\n self.logger.error('Network doesn\\'t exist!')\n exit(1)\n\n for run_nb, _ in enumerate(range(runs), 1):\n if self.use_tracker:\n self._create_service(\n self.app_config['tracker']['name'],\n tracker_image,\n placement=['node.role == manager'],\n mem_limit=self.app_config['service']['mem_limit'])\n self._wait_on_service(self.app_config['tracker']['name'], 1)\n time_to_start = int((time.time() * 1000) + time_add)\n self.logger.debug(\n datetime.utcfromtimestamp(\n time_to_start /\n 1000).isoformat())\n\n environment_vars = {'PEER_NUMBER': peer_number,\n 'TIME': time_to_start,\n 'TIME_TO_RUN': time_to_run}\n if 'parameters' in self.app_config['service']:\n environment_vars.update(\n self.app_config['service']['parameters'])\n environment_vars = [\n '{:s}={}'.format(k, v) for k, v in environment_vars.items()]\n self.logger.debug(environment_vars)\n\n service_replicas = 0 if self.churn else peer_number\n log_storage = (self.cluster_config['local_data']\n if self.local\n else self.cluster_config['cluster_data'])\n\n if 'mem_limit' in self.app_config['service']:\n self._create_service(\n self.app_config['service']['name'],\n service_image,\n env=environment_vars,\n mounts=[\n types.Mount(\n target='/data',\n source=log_storage,\n type='bind')],\n replicas=service_replicas,\n mem_limit=self.app_config['service']['mem_limit'])\n else:\n self._create_service(\n self.app_config['service']['name'],\n service_image,\n env=environment_vars,\n mounts=[\n types.Mount(\n target='/data',\n source=log_storage,\n type='bind')],\n replicas=service_replicas)\n\n self.logger.info(\n 'Running Benchmark -> Experiment: {:d}/{:d}'.format(\n run_nb, runs))\n if self.churn:\n thread = threading.Thread(\n target=self._run_churn, args=[\n time_to_start + self.churn.delay], daemon=True)\n thread.start()\n self._wait_on_service(\n self.app_config['service']['name'], 0, inverse=True)\n self.logger.info('Running with churn')\n if self.churn.synthetic:\n # Wait for some peers to at least start\n time.sleep(120)\n total = [sum(x) for x\n in zip(*self.churn.churn_params['synthetic'])]\n # Wait until only stopped containers are still alive\n self._wait_on_service(\n self.app_config['service']['name'],\n containers_nb=total[0],\n total_nb=total[1])\n else:\n # TODO not the most elegant solution\n thread.join() # Wait for churn to finish\n time.sleep(300) # Wait 5 more minutes\n\n else:\n self._wait_on_service(\n self.app_config['service']['name'], 0, inverse=True)\n self.logger.info('Running without churn')\n self._wait_on_service(self.app_config['service']['name'], 0)\n self.stop()\n\n self.logger.info('Services removed')\n time.sleep(30)\n\n if not self.local:\n subprocess.call(\n 'parallel-ssh -t 0 -h config/hosts'\n ' \"mkdir -p {path}/test-{nb}/capture &&'\n ' mv {path}/*.txt {path}/test-{nb}/ &&'\n ' mv {path}/capture/*.csv {path}/test-{nb}/capture/\"'\n .format(path=self.cluster_config['cluster_data'],\n nb=run_nb),\n shell=True)\n\n subprocess.call(\n 'mkdir -p {path}/test-{nb}/capture'.format(path=log_storage,\n nb=run_nb),\n shell=True)\n subprocess.call(\n 'mv {path}/*.txt {path}/test-{nb}/'.format(path=log_storage,\n nb=run_nb),\n shell=True)\n subprocess.call(\n 'mv {path}/capture/*.csv {path}/test-{nb}/capture/'.format(\n path=log_storage, nb=run_nb), shell=True)\n\n self.logger.info('Benchmark done!')\n\n def stop(self, is_signal=False):\n \"\"\"\n Stop the benchmark and get every logs\n\n :return:\n \"\"\"\n try:\n if self.use_tracker:\n self.client.api.remove_service(self.app_config['tracker']['name'])\n self.client.api.remove_service(self.app_config['service']['name'])\n if not self.local and is_signal:\n time.sleep(15)\n with open('config/hosts', 'r') as file:\n for host in file.read().splitlines():\n subprocess.call('rsync --remove-source-files '\n '-av {:s}:{:s}/*.txt ../data'\n .format(host, self.cluster_config['cluster_data']),\n shell=True)\n subprocess.call(\n 'rsync --remove-source-files '\n '-av {:s}:{:s}/capture/*.csv ../data/capture'\n .format(host, self.cluster_config['cluster_data']),\n shell=True)\n except errors.NotFound:\n pass\n\n def set_logger_level(self, log_level):\n \"\"\"\n Set the logger level of the object\n\n :param log_level: The logger level\n :return:\n \"\"\"\n self.logger.setLevel(log_level)\n\n def _run_churn(self, time_to_start):\n self.logger.debug('Time to start churn: {:d}'.format(time_to_start))\n if self.churn.synthetic:\n self.logger.info(self.churn.churn_params['synthetic'])\n nodes_trace = NodesTrace(\n synthetic=self.churn.churn_params['synthetic'])\n else:\n real_churn_params = self.churn.churn_params['real_churn']\n nodes_trace = NodesTrace(\n database=real_churn_params['database'],\n min_time=real_churn_params['epoch']\n + real_churn_params['start_time'],\n max_time=real_churn_params['epoch']\n + real_churn_params['start_time']\n + real_churn_params['duration'],\n time_factor=real_churn_params['time_factor'])\n\n delta = self.churn.period\n\n # Add initial cluster\n self.logger.debug(\n 'Initial size: {}'.format(\n nodes_trace.initial_size()))\n self.churn.add_processes(nodes_trace.initial_size())\n delay = int((time_to_start - (time.time() * 1000)) / 1000)\n self.logger.debug('Delay: {:d}'.format(delay))\n self.logger.info(\n 'Starting churn at {:s} UTC' .format(\n datetime.utcfromtimestamp(\n time_to_start //\n 1000).isoformat()))\n time.sleep(delay)\n self.logger.info('Starting churn')\n nodes_trace.next()\n for size, to_kill, to_create in nodes_trace:\n self.logger.debug('curr_size: {:d}, to_kill: {:d}, to_create {:d}'\n .format(size, len(to_kill), len(to_create)))\n self.churn.add_suspend_processes(len(to_kill), len(to_create))\n time.sleep(delta / 1000)\n\n self.logger.info('Churn finished')\n\n def _create_service(\n self,\n service_name,\n image,\n env=None,\n mounts=None,\n placement=None,\n replicas=1,\n mem_limit=314572800):\n network = self.app_config['service']['network']['name']\n self.client.services.create(image,\n name=service_name,\n restart_policy=types.RestartPolicy(),\n env=env,\n mode={'Replicated': {'Replicas': replicas}},\n networks=[network],\n resources=types.Resources(mem_limit=mem_limit),\n mounts=mounts,\n constraints=placement)\n\n def _wait_on_service(self, service_name, containers_nb,\n total_nb=None, inverse=False):\n def get_nb():\n output = subprocess.check_output(['docker',\n 'service',\n 'ls',\n '-f',\n 'name={:s}'.format(service_name)],\n universal_newlines=True).splitlines()[1]\n match = re.match(r'.+ (\\d+)/(\\d+)', output)\n return int(match.group(1)), int(match.group(2))\n\n if inverse: # Wait while current nb is equal to containers_nb\n current_nb = containers_nb\n while current_nb == containers_nb:\n self.logger.debug(\n 'current_nb={:d}, containers_nb={:d}'.format(\n current_nb, containers_nb))\n time.sleep(1)\n current_nb = get_nb()[0]\n else:\n current_nb = -1\n current_total_nb = -1\n while current_nb > containers_nb or current_total_nb != total_nb:\n self.logger.debug(\n 'current_nb={:d}, containers_nb={:d}'.format(\n current_nb, containers_nb))\n self.logger.debug(\n 'current_total_nb={:d}'.format(current_total_nb))\n time.sleep(5)\n current_nb, current_total_nb = get_nb()\n if not total_nb:\n total_nb = current_total_nb\n else:\n self.logger.debug(\n 'current_total_nb={:d}, total_nb={:d}'.format(\n current_total_nb, total_nb))\n","sub_path":"projects/EpTOTester/lsdssuite/lsdssuite/benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":14697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"328231702","text":"import re\n\nl = \"Beautiful is better than ugly.\"\nmatches = re.findall(\"beautiful\", l, re.IGNORECASE)\n\nprint(matches)\n\nzen = \"\"\"Although never is\noften better than\n*right* now.\nIf the implementation\nis hard to explain,\nit's a bad idea.\nIf the implementation\nis easy to explain,\nit may be a good\nidea. Namespaces\nare one honking\ngreat idea -- let's\ndo more of those!\n\"\"\"\nm = re.findall(\"^If\", zen, re.MULTILINE)\n\nprint(m)\n\n\nstring = \"Two too.\"\nm = re.findall(\"t[ow]o\", string, re.IGNORECASE)\nprint(m)\n\nline = \"123 hi 34 hello.\"\nm = re.findall(\"\\d\", line, re.IGNORECASE)\nprint(m)\n\nt = \"__one__ __two__ __three__\"\nfound = re.findall(\"__.*?__\", t, re.IGNORECASE)\nprint(found)\n\n\nline = \"I love $\"\nm = re.findall(\"\\$\", line)\nprint(m)\n\nline = \"The ghost that says boo haunts the loo\"\nm = re.findall(\".oo\", line)\nprint(m)\n\n\n#text = \"\"\"Giraffes have aroused\n# the curiosity of __PLURAL_NOUN__\n# since earliest times. The\n# giraffe is the tallest of all\n# living __PLURAL_NOUN__, but\n# scientists are unable to\n# explain how it got its long\n# __PART_OF_THE_BODY__. The\n# giraffe's tremendous height,\n# which might reach __NUMBER__\n# __PLURAL_NOUN__, comes from\n# it legs and __BODYPART__.\n#\"\"\"\n#\n#\n#def mad_libs(mls):\n# \"\"\"\n# :param mls: String\n# with parts the user\n# should fill out surrounded\n# by double underscores.\n# Underscores cannot\n# be inside hint e.g., no\n# __hint_hint__ only\n# __hint__.\n# \"\"\"\n# hints = re.findall(\"__.*?__\", mls)\n# if hints is not None:\n# for word in hints:\n# q = \"Enter a {}\"\\\n# .format(word)\n# new = input(q)\n# mls = mls.replace(word,\n# new,\n# 1)\n# print('\\n')\n# mls = mls.replace(\"\\n\", \"\")\n# print(mls)\n# else:\n# print(\"invalid mls\")\n#\n#mad_libs(text)","sub_path":"python3/regular_expressions_test.py","file_name":"regular_expressions_test.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"302679313","text":"# MTH1102, Calcul II\n# Chapitre 6\n# Intégrale double sur un rectangle.\n# Corentin Faucher\n# 21 janvier 2020\n\n# Import python\nfrom random import randint\nfrom sympy import Integral, integrate, latex, mathematica_code, Rational, symbols\nfrom sympy.parsing.mathematica import mathematica\n# Import personnel\nfrom app.maths.mathutils import latexWrapInPar\n\n\nclass Chap6_intR:\n\tname = \"Intégrale double sur un rectangle\"\n\n\tdef __init__(self):\n\t\t# Domaine\n\t\tself.a = randint(-10, 9)\n\t\tself.b = randint(self.a + 1, 10)\n\t\tself.c = randint(-10, 9)\n\t\tself.d = randint(self.c + 1, 10)\n\t\t# Init de la fonction à intégrer\n\t\tx, y = symbols('x,y')\n\t\tnb_termes = randint(1, 3)\t\t# Ici, on fait un simple polynôme.\n\t\tf = Rational(randint(-5, 5))\t# Init comme expression symbolique.\n\t\tfor i in range(nb_termes):\n\t\t\tf += randint(-5, 5) * x ** randint(0, 2) * y ** randint(0, 2)\n\t\t# On ne garde pas l'expression symbolique (trop lourd pour les cookies),\n\t\t# on ne garde que l'expression sous forme de string.\n\t\tself.f_string = mathematica_code(f)\n\n\tdef getStatement(self):\n\t\tf = mathematica(self.f_string)\n\t\t# Rédaction de l'énoncé.\n\t\treturn '\\n'.join([\n\t\t\tr\"Évaluez l'intégrale\",\n\t\t\tr\"\\[ J = \\iint_R %s \\, dA, \\]\" % latexWrapInPar(f),\n\t\t\trf\"où \\( R \\) est le rectangle \\( R = [{self.a}, {self.b}] \\times [{self.c}, {self.d}] \\).\"\n\t\t])\n\n\tdef getSolution(self):\n\t\t# Calculs\n\t\tx, y = symbols('x,y')\n\t\tf = mathematica(self.f_string)\n\t\ta, b, c, d = self.a, self.b, self.c, self.d\n\t\tJ1 = Integral(Integral(f, (y, c, d)), (x, a, b))\n\t\tAx = integrate(f, (y, c, d))\n\t\tJ2 = Integral(Ax, (x, a, b))\n\t\tJ3 = integrate(Ax, (x, a, b))\n\t\tJ4 = Integral(Integral(f, (x, a, b)), (y, c, d))\n\t\tAy = integrate(f, (x, a, b))\n\t\tJ5 = Integral(Ay, (y, c, d))\n\t\tJ6 = integrate(Ay, (y, c, d))\n\t\t# Rédaction de la solution\n\t\treturn '\\n'.join([\n\t\t\tr\"Selon l'ordre \\( dx\\, dy \\) : \",\n\t\t\tr\"\\[\\renewcommand{\\arraystretch}{3.0}\\begin{array}{lll}\",\n\t\t\tr\"J &= & %s \\\\\" % latex(J4),\n\t\t\tr\" &= & %s \\\\\" % latex(J5),\n\t\t\tr\" &= & %s. \" % latex(J6),\n\t\t\tr\"\\end{array}\\]\",\n\t\t\tr\"Selon l'ordre \\( dy\\, dx \\) : \",\n\t\t\tr\"\\[\\renewcommand{\\arraystretch}{3.0}\\begin{array}{lll}\",\n\t\t\tr\"J &= & %s \\\\\" % latex(J1),\n\t\t\tr\" &= & %s \\\\\" % latex(J2),\n\t\t\tr\" &= & %s. \" % latex(J3),\n\t\t\tr\"\\end{array}\\]\",\n\t\t])\n\n# Testing de chap6_intD.py\nif __name__ == '__main__':\n\tproblem = Chap6_intD()\n\tproblem.setDomain()\n\tproblem.setIntegrand()\n\tproblem.generateStatement()\n\tproblem.generateSolution()\n\tprint(problem.statement)\n\tprint(problem.solution)\n\n","sub_path":"app/maths/chap6_intR.py","file_name":"chap6_intR.py","file_ext":"py","file_size_in_byte":2479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"430971651","text":"import random\n\nprint('儿子,欢迎使用老爸的答题系统,开始吧!!!')\ncorrect = 0\nwrong = 0\n\nfor i in range(5):\n # 随机生成2个数字\n n1 = random.randint(1,20)\n n2 = random.randint(1,20)\n # 随机生成操作符\n s = ['+','-']\n option = random.choice(s)\n # 完成出题,并判断正确与否\n if n1 < n2 and option == '-':\n result = input('%d %s %d = ' % (n2,option,n1))\n result = int(result)\n if result == n2-n1:\n print('你真棒,继续...')\n correct += 1\n else:\n print('回答错误,正确答案:%d' % (n2-n1))\n wrong += 1\n elif n1 >= n2 and option == '-':\n result = input('%d %s %d = ' % (n1,option,n2))\n result = int(result)\n if result == n1-n2:\n print('正确,请继续...')\n correct += 1\n else:\n print('错误,正确答案为: %d' % (n1-n2))\n wrong += 1\n else:\n result = input('%d %s %d = ' % (n1,option,n2))\n result = int(result)\n if result == n1+n2:\n print('正确,请继续...')\n correct += 1\n else:\n print('错误,正确答案为: %d' % (n1+n2))\n wrong += 1\n\nprint('共5道题,正确:%d道 错误:%d道' % (correct,wrong))\n\n\n\n\n\n\n\n\n\n","sub_path":"code/day05/06_答题.py","file_name":"06_答题.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"212972288","text":"import torch\nimport pickle\nimport numpy as np\nfrom pathlib import Path\nfrom torch.utils.data import DataLoader\nimport torch.nn as nn\n\nfrom Dataset import KTDataset\nfrom VMGNet import SimpleVMG\nimport pathlib\n\nnum_classes=2\nbase_model=SimpleVMG(num_classes)\nbase_model.load_state_dict(torch.load(\"weights/KT_tumor_1.pth\", map_location=torch.device('cpu')))\nlabel_encoder=pickle.load(open(\"encoders/label_tumor_encoder.pkl\", 'rb'))\n\ndef predict(model, test_loader):\n with torch.no_grad():\n logits = []\n\n for inputs in test_loader:\n model.eval()\n outputs = model(inputs).cpu()\n logits.append(outputs)\n\n probs = nn.functional.softmax(torch.cat(logits), dim=-1).numpy()\n return probs\n\ndef predict_picture():\n TEST_DIR = Path('test_img')\n test_files=list(TEST_DIR.rglob('*.jpg'))\n # test_files=[str(pathlib.PurePosixPath(\"C:/Users/Digitaljay/Documents/GitHub/strokes_diagnostic/test_img/ВЖК_1.jpg\"))]\n for file in test_files:\n test_dataset = KTDataset([file], mode=\"test\")\n test_loader = DataLoader(test_dataset, shuffle=False, batch_size=64)\n probs = predict(base_model, test_loader)\n predicted_proba = np.max(probs)*100\n y_pred = np.argmax(probs)\n predicted_label = label_encoder.classes_[y_pred]\n print(file, y_pred, predicted_label, predicted_proba)\n\npredict_picture()\n","sub_path":"check_model_tumor.py","file_name":"check_model_tumor.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"49609020","text":"import argparse\nfrom collections import namedtuple\nimport os\nimport tempfile\nimport unittest\n\nimport asdf\nfrom scipy.sparse import coo_matrix\n\nfrom ast2vec import Repo2Coocc, Repo2CooccTransformer\nfrom ast2vec.bblfsh_roles import SIMPLE_IDENTIFIER\nimport ast2vec.tests as tests\nfrom ast2vec.repo2.coocc import repo2coocc_entry\n\n\ndef validate_asdf_file(obj, filename):\n data = asdf.open(filename)\n obj.assertIn(\"meta\", data.tree)\n obj.assertIn(\"matrix\", data.tree)\n obj.assertIn(\"tokens\", data.tree)\n obj.assertEqual(data.tree[\"meta\"][\"model\"], \"co-occurrences\")\n\n\nclass Repo2CooccTests(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n tests.setup()\n\n def test_obj(self):\n basedir = os.path.dirname(__file__)\n repo2 = Repo2Coocc(linguist=tests.ENRY)\n coocc = repo2.convert_repository(os.path.join(basedir, \"..\", \"..\"))\n self.assertIsInstance(coocc, tuple)\n self.assertEqual(len(coocc), 2)\n self.assertIn(\"document\", coocc[0])\n self.assertIsInstance(coocc[1], coo_matrix)\n self.assertEqual(coocc[1].shape, (len(coocc[0]),) * 2)\n self.assertGreater(coocc[1].getnnz(), 20000)\n\n def test_asdf(self):\n basedir = os.path.dirname(__file__)\n with tempfile.NamedTemporaryFile() as file:\n args = argparse.Namespace(\n linguist=tests.ENRY, output=file.name,\n repository=os.path.join(basedir, \"..\", \"..\"),\n bblfsh_endpoint=None, timeout=None)\n repo2coocc_entry(args)\n validate_asdf_file(self, file.name)\n\n def test_zero_tokens(self):\n def skip_uast(root, word2ind, dok_mat):\n pass\n\n repo2 = Repo2Coocc(linguist=tests.ENRY)\n repo2._traverse_uast = skip_uast\n basedir = os.path.dirname(__file__)\n coocc = repo2.convert_repository(os.path.join(basedir, \"..\", \"..\"))\n self.assertEqual(coocc[0], [])\n self.assertEqual(coocc[1].shape, (0, 0))\n self.assertEqual(coocc[1].nnz, 0)\n\n def test_extract_ids(self):\n Node = namedtuple(\"Node\", [\"roles\", \"token\", \"children\"])\n node1 = Node([SIMPLE_IDENTIFIER], 1, [])\n node2 = Node([], 2, [])\n node3 = Node([SIMPLE_IDENTIFIER], 3, [node1, node2])\n node4 = Node([SIMPLE_IDENTIFIER], 4, [])\n root = Node([], 5, [node3, node4])\n repo2 = Repo2Coocc(linguist=tests.ENRY)\n self.assertEqual(list(repo2._extract_ids(root)), [4, 3, 1])\n\n def test_linguist(self):\n # If this test fails, check execution permissions for provided paths.\n with self.assertRaises(FileNotFoundError):\n Repo2Coocc(linguist=\"xxx\")\n with self.assertRaises(FileNotFoundError):\n Repo2Coocc(linguist=__file__)\n\n\nclass Repo2CooccTransformerTests(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n tests.setup()\n\n def test_transform(self):\n basedir = os.path.dirname(__file__)\n with tempfile.TemporaryDirectory() as tmpdir:\n r2cc = Repo2CooccTransformer(\n linguist=tests.ENRY)\n r2cc.transform(repos=basedir, output=tmpdir)\n\n # check that output file exists\n outfile = r2cc.prepare_filename(basedir, tmpdir)\n self.assertEqual(os.path.exists(outfile), 1)\n\n validate_asdf_file(self, outfile)\n\n def test_empty(self):\n basedir = os.path.dirname(__file__)\n with tempfile.TemporaryDirectory() as tmpdir:\n r2cc = Repo2CooccTransformer(\n linguist=tests.ENRY)\n r2cc.transform(repos=os.path.join(basedir, \"coocc\"), output=tmpdir)\n self.assertFalse(os.listdir(tmpdir))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"ast2vec/tests/test_repo2coocc.py","file_name":"test_repo2coocc.py","file_ext":"py","file_size_in_byte":3741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"594581483","text":"#\n# @lc app=leetcode.cn id=26 lang=python3\n#\n# [26] 删除排序数组中的重复项\n#\n\n# @lc code=start\nclass Solution:\n def removeDuplicates(self, nums: list) -> int:\n for num_index in range(len(nums)-1, 0, -1):\n if nums[num_index] == nums[num_index-1]:\n nums.pop(num_index)\n return len(nums)\n\n# @lc code=end\n\n","sub_path":"Week_01/26.remove-duplicates-from-sorted-array.py","file_name":"26.remove-duplicates-from-sorted-array.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"580730563","text":"from google.transit import gtfs_realtime_pb2\nimport urllib.request \nimport pandas as pd\nimport time\nimport datetime\nfrom pandas.io import sql\nimport pymysql as sql\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import exc\n\nclass MTARealtime123456S:\n def __init__(self,con):\n #get the most recent update from the MTA\n self.__engine=create_engine(con)\n self.__feed= gtfs_realtime_pb2.FeedMessage()\n response=urllib.request.urlopen('http://datamine.mta.info/mta_esi.php?key=fc8e4cc33aa9c355103b737886bcf1aa&feed_id=1')\n try:\n self.__feed.ParseFromString(response.read())\n \n \n #initialize the lists of schedule fields\n schedule_trips=[]\n schedule_routes=[]\n schedule_arrivals=[]\n schedule_departures=[]\n schedule_stops=[]\n \n \n #initialize the lists of trip fields. The trip refers to the real-time position of each train.\n trip_ids=[]\n start_dates=[]\n route_ids=[]\n stop_sequences=[]\n current_statuses=[]\n vehicle_timestamps=[]\n stop_ids=[]\n \n #initialize the lists of alert fields.\n \n alert_texts=[]\n alert_trips=[]\n alert_routes=[]\n \n #loop through the feed, adding the relevant fields into lists\n \n for entity in self.__feed.entity:\n if entity.HasField('trip_update'):\n for i in entity.trip_update.stop_time_update:\n schedule_arrivals.append(datetime.datetime.fromtimestamp(max(i.arrival.time,86400)).strftime('%Y-%m-%d %H:%M:%S'))\n schedule_departures.append(datetime.datetime.fromtimestamp(max(i.departure.time,86400)).strftime('%Y-%m-%d %H:%M:%S'))\n schedule_stops.append(i.stop_id)\n trips=[entity.trip_update.trip.trip_id for j in range(len(entity.trip_update.stop_time_update))]\n routes=[entity.trip_update.trip.route_id for j in range(len(entity.trip_update.stop_time_update))]\n schedule_trips+=trips\n schedule_routes+=routes \n if entity.HasField('vehicle'):\n trip_ids.append(entity.vehicle.trip.trip_id)\n start_dates.append(entity.vehicle.trip.start_date)\n route_ids.append(entity.vehicle.trip.route_id)\n stop_sequences.append(entity.vehicle.current_stop_sequence)\n current_statuses.append(entity.vehicle.current_status)\n vehicle_timestamps.append(datetime.datetime.fromtimestamp(max(entity.vehicle.timestamp,86400)).strftime('%Y-%m-%d %H:%M:%S'))\n stop_ids.append(entity.vehicle.stop_id)\n if entity.HasField('alert'):\n for i in entity.alert.informed_entity:\n alert_trips.append(i.trip.trip_id)\n alert_routes.append(i.trip.route_id)\n alert_texts=[entity.alert.header_text.translation[0].text for i in range(len(entity.alert.informed_entity))]\n \n \n #Add the current feed timestamp to each set of fields\n curr_time=datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')\n alert_timestamps=[curr_time for i in range(len(alert_trips))]\n schedule_timestamps=[curr_time for i in range(len(schedule_trips))]\n trip_timestamps=[curr_time for i in range(len(trip_ids))]\n \n #create the data frames\n self.__subway_frame=pd.DataFrame({'feed_timestamp':trip_timestamps,'trip_id':trip_ids,'route_id':route_ids,'stop_sequence':stop_sequences,'current_status':current_statuses,'vehicle_timestamp':vehicle_timestamps,'stop_id':stop_ids})\n self.__alert_frame=pd.DataFrame({'feed_timestamp':alert_timestamps,'alert_trip':alert_trips,'alert_route':alert_routes,'alert_text':alert_texts})\n self.__schedule_frame=pd.DataFrame({'feed_timestamp':schedule_timestamps,'schedule_trip':schedule_trips,'schedule_route':schedule_routes,'schedule_arrival':schedule_arrivals,'schedule_departure':schedule_departures,'schedule_stop':schedule_stops})\n except:\n self.__feed=None\n self.__subway_frame=None\n self.__schedule_frame=None\n self.__alert_frame=None\n \n def get_raw_feed(self):\n return self.__feed\n \n def get_dfs_feed(self):\n return self.__subway_frame,self.__alert_frame,self.__schedule_frame\n \n def write_dfs_to_db(self):\n if self.__feed==None:\n print('Empty feed, not writing to db')\n else:\n #subway_write.to_sql(con=engine,name='mta_trip_data',if_exists='append',index=False)\n for i in range(len(self.__subway_frame)):\n try:\n self.__subway_frame.iloc[i:i+1].to_sql(name=\"mta_trip_data\",if_exists='append',con = self.__engine,index=False)\n except:\n print('cannot write row to mta_trip_data')\n #alert_write.to_sql(con=engine,name='mta_alert_data',if_exists='append',index=False)\n for i in range(len(self.__alert_frame)):\n try:\n self.__alert_frame.iloc[i:i+1].to_sql(name=\"mta_alert_data\",if_exists='append',con = self.__engine,index=False)\n except:\n print('cannot write row to mta_alert_data')\n #Sometimes schedule feeds contain two ETAs for the same stop on the same trip. This accounts for that issue.\n for i in range(len(self.__schedule_frame)):\n try:\n self.__schedule_frame.iloc[i:i+1].to_sql(name=\"mta_schedule_data\",if_exists='append',con = self.__engine,index=False)\n except exc.IntegrityError:\n print('cannot write row to mta_schedule_data')\n \n \n \n \n ","sub_path":"data_setup/nyc_mta/mta_realtime_123456s.py","file_name":"mta_realtime_123456s.py","file_ext":"py","file_size_in_byte":6096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"32278568","text":"#!/usr/bin/python\n# ex:set fileencoding=utf-8:\n\nfrom __future__ import unicode_literals\n\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.db.models import signals\nfrom django.dispatch import receiver\n\nfrom djangobmf.conf import settings\nfrom djangobmf.signals import activity_create\nfrom djangobmf.signals import activity_update\nfrom djangobmf.signals import activity_addfile\nfrom djangobmf.signals import activity_workflow\nfrom djangobmf.tasks import djangobmf_user_watch\nfrom djangobmf.utils.serializers import DjangoBMFEncoder\n\nimport json\n\nfrom .base import BMFModel\nfrom .base import BMFModelBase\n\nfrom .activity import ACTION_COMMENT\nfrom .activity import ACTION_CREATED\nfrom .activity import ACTION_UPDATED\nfrom .activity import ACTION_WORKFLOW\nfrom .activity import ACTION_FILE\n\nfrom .activity import Activity as AbstractActivity\nfrom .configuration import Configuration as AbstractConfiguration\nfrom .document import Document as AbstractDocument\nfrom .notification import Notification as AbstractNotification\nfrom .numberrange import NumberRange as AbstractNumberRange\nfrom .renderer import PDFRenderer as AbstractPDFRenderer\nfrom .report import Report as AbstractReport\n\n\n__all__ = (\n 'BMFModel',\n 'BMFModelBase',\n 'ACTION_COMMENT',\n 'ACTION_CREATED',\n 'ACTION_UPDATED',\n 'ACTION_WORKFLOW',\n 'ACTION_FILE',\n 'Activity',\n 'Document',\n 'Configuration',\n 'Notification',\n 'NumberCycle',\n 'Renderer',\n 'Report',\n)\n\n\nclass Activity(AbstractActivity):\n class Meta(AbstractActivity.Meta):\n abstract = False\n app_label = settings.APP_LABEL\n\n\nclass Configuration(AbstractConfiguration):\n class Meta(AbstractConfiguration.Meta):\n abstract = False\n app_label = settings.APP_LABEL\n\n\n# class Dashboard(AbstractDashboard):\n# class Meta(AbstractDashboard.Meta):\n# abstract = False\n# app_label = settings.APP_LABEL\n\n\nclass Document(AbstractDocument):\n class Meta(AbstractDocument.Meta):\n abstract = False\n app_label = settings.APP_LABEL\n\n\nclass Notification(AbstractNotification):\n class Meta(AbstractNotification.Meta):\n abstract = False\n app_label = settings.APP_LABEL\n\n\nclass NumberRange(AbstractNumberRange):\n class Meta(AbstractNumberRange.Meta):\n abstract = False\n app_label = settings.APP_LABEL\n\n\nclass PDFRenderer(AbstractPDFRenderer):\n class Meta(AbstractPDFRenderer.Meta):\n abstract = False\n app_label = settings.APP_LABEL\n\n\nclass Report(AbstractReport):\n class Meta(AbstractReport.Meta):\n abstract = False\n app_label = settings.APP_LABEL\n\n\n@receiver(activity_create)\ndef object_created(sender, instance, **kwargs):\n if instance._bmfmeta.has_logging:\n history = Activity(\n user=instance.created_by,\n parent_ct=ContentType.objects.get_for_model(sender),\n parent_id=instance.pk,\n action=ACTION_CREATED,\n )\n history.save()\n\n\n@receiver(activity_update)\ndef object_changed(sender, instance, **kwargs):\n\n if instance._bmfmeta.has_logging and len(instance._bmfmeta.observed_fields) > 0:\n changes = []\n for key in instance._bmfmeta.observed_fields:\n try:\n if instance._bmfmeta.changelog[key] != getattr(instance, key):\n changes.append((key, instance._bmfmeta.changelog[key], getattr(instance, key)))\n except KeyError:\n pass\n\n if len(changes) > 0:\n history = Activity(\n user=instance.modified_by,\n parent_ct=ContentType.objects.get_for_model(sender),\n parent_id=instance.pk,\n action=ACTION_UPDATED,\n text=json.dumps(changes, cls=DjangoBMFEncoder),\n )\n history.save()\n\n\n@receiver(activity_workflow)\ndef new_state(sender, instance, **kwargs):\n if instance._bmfmeta.has_logging:\n history = Activity(\n user=instance.modified_by,\n parent_ct=ContentType.objects.get_for_model(sender),\n parent_id=instance.pk,\n action=ACTION_WORKFLOW,\n text=json.dumps({\n 'old': instance._bmfmeta.workflow.initial,\n 'new': instance._bmfmeta.workflow.key,\n }, cls=DjangoBMFEncoder),\n )\n history.save()\n\n\n@receiver(activity_addfile)\ndef new_file(sender, instance, file, **kwargs):\n if instance._bmfmeta.has_logging:\n history = Activity(\n user=instance.modified_by,\n parent_ct=ContentType.objects.get_for_model(sender),\n parent_id=instance.pk,\n action=ACTION_FILE,\n text=json.dumps({\n 'pk': file.pk,\n 'size': file.size,\n 'name': '%s' % file,\n }, cls=DjangoBMFEncoder),\n )\n history.save()\n\n\ndef activity_post_save(sender, instance, *args, **kwargs):\n djangobmf_user_watch(instance.pk)\nsignals.post_save.connect(activity_post_save, sender=Activity)\n","sub_path":"djangobmf/models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"469755771","text":"load(\n \"@io_bazel_rules_dotnet//dotnet/private:context.bzl\",\n \"dotnet_context\",\n)\nload(\n \"@io_bazel_rules_dotnet//dotnet/private:providers.bzl\",\n \"DotnetLibrary\",\n \"DotnetResource\",\n \"DotnetResourceList\",\n)\n\ndef _library_impl(ctx):\n \"\"\"_library_impl emits actions for compiling dotnet executable assembly.\"\"\"\n dotnet = dotnet_context(ctx)\n name = ctx.label.name\n\n # Handle case of empty toolchain on linux and darwin\n if dotnet.assembly == None:\n library = dotnet.new_library(dotnet = dotnet)\n return [library]\n\n library = dotnet.assembly(\n dotnet,\n name = name,\n srcs = ctx.attr.srcs,\n deps = ctx.attr.deps,\n resources = ctx.attr.resources,\n out = ctx.attr.out,\n defines = ctx.attr.defines,\n unsafe = ctx.attr.unsafe,\n data = ctx.attr.data,\n keyfile = ctx.attr.keyfile,\n executable = False,\n server = ctx.executable.server,\n )\n\n runfiles = ctx.runfiles(files = [], transitive_files = library.runfiles)\n\n return [\n library,\n DefaultInfo(\n files = depset([library.result]),\n runfiles = runfiles,\n ),\n ]\n\ndotnet_library = rule(\n _library_impl,\n attrs = {\n \"deps\": attr.label_list(providers = [DotnetLibrary]),\n \"resources\": attr.label_list(providers = [DotnetResourceList]),\n \"srcs\": attr.label_list(allow_files = [\".cs\"]),\n \"out\": attr.string(),\n \"defines\": attr.string_list(),\n \"unsafe\": attr.bool(default = False),\n \"data\": attr.label_list(allow_files = True),\n \"keyfile\": attr.label(allow_files = True),\n \"dotnet_context_data\": attr.label(default = Label(\"@io_bazel_rules_dotnet//:dotnet_context_data\")),\n },\n toolchains = [\"@io_bazel_rules_dotnet//dotnet:toolchain\"],\n executable = False,\n)\n\ncore_library = rule(\n _library_impl,\n attrs = {\n \"deps\": attr.label_list(providers = [DotnetLibrary]),\n \"resources\": attr.label_list(providers = [DotnetResourceList]),\n \"srcs\": attr.label_list(allow_files = [\".cs\"]),\n \"out\": attr.string(),\n \"defines\": attr.string_list(),\n \"unsafe\": attr.bool(default = False),\n \"data\": attr.label_list(allow_files = True),\n \"keyfile\": attr.label(allow_files = True),\n \"dotnet_context_data\": attr.label(default = Label(\"@io_bazel_rules_dotnet//:core_context_data\")),\n \"server\": attr.label(\n default = Label(\"@io_bazel_rules_dotnet//tools/server:Compiler.Server.Multiplex\"),\n executable = True,\n cfg = \"host\",\n ),\n },\n toolchains = [\"@io_bazel_rules_dotnet//dotnet:toolchain_core\"],\n executable = False,\n)\n\nnet_library = rule(\n _library_impl,\n attrs = {\n \"deps\": attr.label_list(providers = [DotnetLibrary]),\n \"resources\": attr.label_list(providers = [DotnetResourceList]),\n \"srcs\": attr.label_list(allow_files = [\".cs\"]),\n \"out\": attr.string(),\n \"defines\": attr.string_list(),\n \"unsafe\": attr.bool(default = False),\n \"data\": attr.label_list(allow_files = True),\n \"keyfile\": attr.label(allow_files = True),\n \"dotnet_context_data\": attr.label(default = Label(\"@io_bazel_rules_dotnet//:net_context_data\")),\n },\n toolchains = [\"@io_bazel_rules_dotnet//dotnet:toolchain_net\"],\n executable = False,\n)\n","sub_path":"dotnet/private/rules/library.bzl","file_name":"library.bzl","file_ext":"bzl","file_size_in_byte":3393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"389525649","text":"# -*- coding: utf-8 -*-\n# Calculate the mean and variance of the strain, for all voxels in the support\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib.colors import LinearSegmentedColormap\nimport tkinter as tk\nfrom tkinter import filedialog\nimport gc\n\nscan = 2227\ndatadir = \"C:/Users/carnis/Work Folders/Documents/data/CH4760_Pt/S\"+str(scan)+\"/simu/crop400phase/no_apodization/avg1/\" # no_apodization\" # apodize_during_phasing # apodize_postprocessing\nstrain_range = 0.001 # for plots\nsupport_threshold = 0.73 # threshold for support determination\nflag_plot = 0 # 1 to show plots of data\n######################################\n# define a colormap\ncdict = {'red': ((0.0, 1.0, 1.0),\n (0.11, 0.0, 0.0),\n (0.36, 0.0, 0.0),\n (0.62, 1.0, 1.0),\n (0.87, 1.0, 1.0),\n (1.0, 0.0, 0.0)),\n 'green': ((0.0, 1.0, 1.0),\n (0.11, 0.0, 0.0),\n (0.36, 1.0, 1.0),\n (0.62, 1.0, 1.0),\n (0.87, 0.0, 0.0),\n (1.0, 0.0, 0.0)),\n 'blue': ((0.0, 1.0, 1.0),\n (0.11, 1.0, 1.0),\n (0.36, 1.0, 1.0),\n (0.62, 0.0, 0.0),\n (0.87, 0.0, 0.0),\n (1.0, 0.0, 0.0))}\nmy_cmap = LinearSegmentedColormap('my_colormap', cdict, 256)\n#######################################\n\nplt.ion()\nroot = tk.Tk()\nroot.withdraw()\nfile_path = filedialog.askopenfilename(initialdir=datadir, filetypes=[(\"NPZ\", \"*.npz\")])\nprint('Opening ', file_path)\nnpzfile = np.load(file_path)\nbulk = npzfile['bulk']\nnz, ny, nx = bulk.shape\nprint(\"Initial data size: (\", nz, ',', ny, ',', nx, ')')\nsupport = np.ones((nz, ny, nx))\nsupport[abs(bulk) < support_threshold * abs(bulk).max()] = 0\n\n########################################\n# plot data\n########################################\nif flag_plot == 1:\n plt.figure(figsize=(18, 15))\n plt.subplot(2, 2, 1)\n plt.imshow(bulk[:, :, nx//2], cmap=my_cmap)\n plt.colorbar()\n plt.axis('scaled')\n plt.title('Amplitude at middle frame in YZ')\n plt.subplot(2, 2, 2)\n plt.imshow(bulk[:, ny//2, :], cmap=my_cmap)\n plt.colorbar()\n plt.axis('scaled')\n plt.title('Amplitude at middle frame in XZ')\n plt.subplot(2, 2, 3)\n plt.imshow(bulk[nz//2, :, :], cmap=my_cmap)\n plt.gca().invert_yaxis()\n plt.colorbar()\n plt.axis('scaled')\n plt.title('Amplitude at middle frame in XY')\n plt.pause(0.1)\ndel bulk\ngc.collect()\n\nstrain = npzfile['strain']\nif flag_plot == 1:\n plt.figure(figsize=(18, 15))\n plt.subplot(2, 2, 1)\n plt.imshow(strain[:, :, nx//2], vmin=-strain_range, vmax=strain_range, cmap=my_cmap)\n plt.colorbar()\n plt.axis('scaled')\n plt.title(\"Strain at middle frame in YZ\")\n plt.subplot(2, 2, 2)\n plt.imshow(strain[:, ny//2, :], vmin=-strain_range, vmax=strain_range, cmap=my_cmap)\n plt.colorbar()\n plt.title(\"Strain at middle frame in XZ\")\n plt.axis('scaled')\n plt.subplot(2, 2, 3)\n plt.imshow(strain[nz//2, :, :], vmin=-strain_range, vmax=strain_range, cmap=my_cmap)\n plt.gca().invert_yaxis()\n plt.colorbar()\n plt.title(\"Strain at middle frame in XY\")\n plt.axis('scaled')\n plt.pause(0.1)\n\n plt.figure(figsize=(18, 15))\n plt.subplot(2, 2, 1)\n plt.imshow(support[:, :, nx//2], vmin=0, vmax=1, cmap=my_cmap)\n plt.colorbar()\n plt.axis('scaled')\n plt.title(\"Support at middle frame in YZ\")\n plt.subplot(2, 2, 2)\n plt.imshow(support[:, ny//2, :], vmin=0, vmax=1, cmap=my_cmap)\n plt.colorbar()\n plt.title(\"Support at middle frame in XZ\")\n plt.axis('scaled')\n plt.subplot(2, 2, 3)\n plt.imshow(support[nz//2, :, :], vmin=0, vmax=1, cmap=my_cmap)\n plt.gca().invert_yaxis()\n plt.colorbar()\n plt.title(\"Support at middle frame in XY\")\n plt.axis('scaled')\n plt.pause(0.1)\n\n########################################\n# calculate mean and variance of the strain\n########################################\nmean_strain = strain[np.nonzero(support)].mean()\nvar_strain = strain[np.nonzero(support)].var()\nrms_strain = np.sqrt(np.mean(np.ndarray.flatten(strain[np.nonzero(support)])**2))\nprint('Mean strain = ', str('{:.4e}'.format(mean_strain)),\n '\\nVariance strain = ', str('{:.4e}'.format(var_strain)),\n '\\nRMS strain = ', str('{:.4e}'.format(rms_strain)))\n\nplt.ioff()\nplt.show()\n","sub_path":"strain_mean_var_rms.py","file_name":"strain_mean_var_rms.py","file_ext":"py","file_size_in_byte":4393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"499592334","text":"# --------------\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# code starts here\ndf = pd.read_csv(path)\np_a = len(df[df['fico']>700])/len(df)\np_b = len(df[df['purpose']=='debt_consolidation'])/len(df)\nprint(p_b)\ndf1 = df[df['purpose']=='debt_consolation']\nprint(len(df1))\np_a_b = (len(df1[df1['fico']>700]/len(df)))/p_a\n\nresult = p_a_b==p_a\n# code ends here\n\n\n# --------------\n# code starts here\nprob_lp = len(df[df['paid.back.loan']=='Yes'])/len(df)\n\nprob_cs = len(df[df['credit.policy']=='Yes'])/len(df)\n\nnew_df = df[df['paid.back.loan']=='Yes']\n\nprob_pd_cs = len(new_df[new_df['credit.policy']=='Yes'])/len(new_df)\n\nbayes = prob_pd_cs*prob_lp/prob_cs\n# code ends here\n\n\n# --------------\n# code starts here\npb = df['purpose'].value_counts()\n\nplt.bar(pb.index,pb.values)\nprint()\n\ndf1 = df[df['paid.back.loan']=='No']\n\npb1 = df1['purpose'].value_counts()\nplt.bar(pb1.index,pb1.values)\n#plt.bar(df1['purpose'])\nplt.show()\n# code ends here\n\n\n# --------------\n# code starts here\ninst_median = np.median(df['installment'])\n\ninst_mean = np.mean(df['installment'])\n\nplt.hist(df['installment'],bins=20)\nplt.show()\n# code ends here\n\n\n","sub_path":"Probability-Basics/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"231674648","text":"import os\nimport gc\nimport time\n\nimport pcd8544\nimport framebuf\nfrom machine import Pin, SPI\n\n\nspi = SPI(1)\nspi.init(baudrate=8000000, polarity=0, phase=0)\nbl = Pin(12, Pin.OUT, value=1)\nlcd = pcd8544.PCD8544(spi, Pin(2), Pin(15), Pin(0))\n\nbuffer = bytearray((lcd.height // 8) * lcd.width)\nframebuf = framebuf.FrameBuffer1(buffer, lcd.width, lcd.height)\n\nframebuf.fill(0)\nframebuf.text('SEX?', 28, 20, 1)\nlcd.data(buffer)\n\nfor i in range(6):\n bl.value(i % 2)\n time.sleep_ms(200)\n\n \nwith open('last.txt', 'r') as fd:\n last = int(fd.read())\n\npics = os.listdir('pics')\nnext = (last + 1) % len(pics)\n\nwith open('last.txt', 'w') as fd:\n fd.write(str(next))\n\nwith open('pics/' + pics[next], 'rb') as fd:\n bmp = fd.read()\n lcd.data(bmp)\n\nfor i in range(10):\n time.sleep_ms(500)\n lcd.invert(bool(i % 2))\n \ntime.sleep(10)\nbl.off()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"138679123","text":"#!usr/bin/python\n\nimport cv2\nimport numpy as np\nimport mediapipe as mp\nfrom tensorflow.keras import models\nfrom collections import deque\nfrom data_preprocessing import prepare_image\n\nmp_drawing = mp.solutions.drawing_utils\nmp_drawing_styles = mp.solutions.drawing_styles\nmp_hands = mp.solutions.hands\n\n#Load trained model\nmy_model = models.load_model('model/DenseNet201_120_rgb_full_da_full_layers_add.h5')\n\nclass_id = ['A','B','C','D','E','F','G','H','I','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y']\n\ncap = cv2.VideoCapture(0)\nwidth_target = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\nheight_target = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n\n#Create a queue for mean averaging result\nmean_result = np.zeros(len(class_id))\nresult_pred = deque(maxlen=15)\nextended_max_x = deque(maxlen=5)\nextended_max_y = deque(maxlen=5)\nextended_min_x = deque(maxlen=5)\nextended_min_y = deque(maxlen=5)\n\nwith mp_hands.Hands(min_detection_confidence=0.5,min_tracking_confidence=0.5) as hands:\n\n while(True):\n\n # Capture frame-by-frame\n grabbed, img = cap.read()\n\n if not grabbed:\n print(\"[ERROR]: Problem with camera\")\n break\n\n image_height = img.shape[0]\n image_width = img.shape[1]\n\n image = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n results = hands.process(image)\n\n # If no landmarks have been found, just display current frame\n if results.multi_hand_landmarks:\n\n # Find min and max coordinates from all landmark\n min_y = image_height+1\n max_y = 0\n min_x = image_width+1\n max_x = 0\n\n # Select only first landmark because we only show one hand\n for landmark in results.multi_hand_landmarks[0].landmark:\n\n # Landmark variable is normalize between 0 and 1, so\n # we need to scale it to image dimension\n scale_x = landmark.x*image_width\n scale_y = landmark.y*image_height\n\n if scale_xmax_x:\n max_x=scale_x\n \n if scale_ymax_y:\n max_y=scale_y\n \n # Extend coordinates to get a proper hand image \n extended_max_x.append(int(1.2*max_x) if (1.2*max_x)0 else 0)\n extended_min_y.append(int(min_y/1.2) if (min_y/1.2)>0 else 0)\n\n # Average coordinate on few frames in order to avoid wavering\n avg_x_max = int(np.array(extended_max_x).mean(axis=0))\n avg_x_min = int(np.array(extended_min_x).mean(axis=0))\n avg_y_max = int(np.array(extended_max_y).mean(axis=0))\n avg_y_min = int(np.array(extended_min_y).mean(axis=0))\n\n \n selected_part = img[avg_y_min:avg_y_max, avg_x_min:avg_x_max]\n\n # Preprocessing image\n selected_part = prepare_image(selected_part)\n selected_part = np.expand_dims(selected_part,axis=0)\n\n prediction = my_model.predict(selected_part)\n\n # Predicion averaging on last predictions to smooth our result\n result_pred.append(prediction)\n mean_result = np.array(result_pred).mean(axis=0)\n index= np.argmax(mean_result)\n predict_class = class_id[index]\n\n text = \"Prediction is : {} ({:.2f}%)\".format(predict_class,mean_result[0][index]*100)\n font = cv2.FONT_HERSHEY_SIMPLEX\n cv2.rectangle(img,(avg_x_min,avg_y_min), (avg_x_max,avg_y_max),(255, 0, 0),2)\n\n y_text = avg_y_min-10\n x_text = avg_x_min+10\n\n cv2.putText(img,text,(x_text,y_text), font, 0.65,(255,0,0),2,cv2.LINE_AA)\n cv2.imshow('American Sign Recognation',img)\n\n else:\n cv2.imshow('American Sign Recognation',img)\n\n\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n\n# When everything done, release the capture\ncap.release()","sub_path":"live_video.py","file_name":"live_video.py","file_ext":"py","file_size_in_byte":4305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"484205356","text":"#!var/env/bin/python\nimport _setup # noqa\nimport os\n\nimport cfg\nimport lib.fs\n\n\ntemplate = lib.fs.read_text('cfg/nginx.txt')\ncontent = template % {\n 'root': lib.fs.ROOT,\n 'host': cfg.HOST.encode('idna').decode('utf-8'),\n 'port': cfg.PORT,\n}\nfilename = '/etc/nginx/sites-enabled/{}'.format(cfg.HOST)\nlib.fs.write_text(filename, content)\nprint('Nginx config created:', filename)\nos.system('/etc/init.d/nginx configtest && sudo /etc/init.d/nginx restart')\n","sub_path":"bin/configure_nginx.py","file_name":"configure_nginx.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"360269733","text":"import unittest\n\nfrom main.enrichers.location_enricher import LocationEnricher\n\n\nclass TestLocationEnricherMethods(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.location_enricher = LocationEnricher()\n cls.dst_src_information_local = {\n \"dst\": {\n \"rdns\": \"10.0.0.1\",\n \"asn\": \"\",\n \"isp\": \"\",\n \"latitude\": \"\",\n \"longitude\": \"\"\n },\n \"src\": {\n \"rdns\": \"10.0.0.2\",\n \"asn\": \"\",\n \"isp\": \"\",\n \"latitude\": \"\",\n \"longitude\": \"\"\n }\n }\n cls.dst_src_information_public = {\n \"dst\": {\n \"rdns\": \"8.8.8.8\",\n \"asn\": \"15169\",\n \"isp\": \"Google LLC\",\n \"latitude\": \"37.751\",\n \"longitude\": \"-97.822\"\n },\n \"src\": {\n \"rdns\": \"10.0.0.1\",\n \"asn\": \"\",\n \"isp\": \"\",\n \"latitude\": \"\",\n \"longitude\": \"\"\n }\n }\n\n def test_header(self):\n expected_header = \"dst_latitude,dst_longitude,src_latitude,src_longitude\"\n self.assertEqual(self.location_enricher.header, expected_header)\n\n def test_extract_location_local_connection(self):\n locations = self.location_enricher.extract_location(self.dst_src_information_local)\n empty_location = '\"\",\"\",\"\",\"\"'\n self.assertEqual(locations, empty_location)\n\n def test_extract_location_public_connection(self):\n locations = self.location_enricher.extract_location(self.dst_src_information_public)\n expected_fqnds = '\"37.751\",\"-97.822\",\"\",\"\"'\n self.assertEqual(locations, expected_fqnds)\n\n\nif __name__ == \"__main__\":\n suite = unittest.TestLoader().loadTestsFromTestCase(TestLocationEnricherMethods)\n unittest.TextTestRunner(verbosity=2).run(suite)\n","sub_path":"backend/bin/test/test_enrichers/test_location_enricher.py","file_name":"test_location_enricher.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"271040341","text":"import cv2\nimport numpy as np\nimport sys\n\nimage = cv2.imread(sys.argv[1])\nheight, width, channels = image.shape\nif width / height > 16 / 9:\n cv2.imwrite(sys.argv[2],image)\n exit()\n\nimgray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)\n\n# Set threshold\n#th1 = cv2.adaptiveThreshold(imgray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,1023,0)\n_,th2 = cv2.threshold(imgray,8,255,cv2.THRESH_BINARY)\nim2, contours, hierarchy = cv2.findContours(th2,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)\n\n# Find with the largest rectangle\nareas = [cv2.contourArea(contour) for contour in contours]\nmax_index = np.argmax(areas)\ncnt = contours[max_index]\nx,y,w,h = cv2.boundingRect(cnt)\n\n# Ensure bounding rect should be at least 16:9 or taller\nif w / h > 16 / 9:\n # increase top and bottom margin\n newHeight = w / 16 * 9\n y = y - (newHeight - h ) / 2\n h = newHeight\n\n\n# Crop with the largest rectangle\ncrop = image[y:y+h,x:x+w]\ncv2.imwrite(sys.argv[2],crop)\n\nexit()\n# Draw preview image\nimagePreview = cv2.imread(sys.argv[1])\nfor contour in contours:\n #epsilon = 0.001 * cv2.arcLength(contour,True)\n #cv2.drawContours(imagePreview, [cv2.approxPolyDP(contour, epsilon, True)], 0, (0,255,0), 1)\n cv2.drawContours(imagePreview, [contour], 0, (0,255,0), 1)\ncv2.imshow(\"adaptiveThreshold\", th1)\ncv2.imshow(\"globalThreshold\", th2)\ncv2.imshow(\"drawContours\", imagePreview)\ncv2.imshow(\"cropped\", crop)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"crop.py","file_name":"crop.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"66743491","text":"from __future__ import print_function\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport os \nimport pdb\nimport copy\nimport random\nimport itertools\nimport numpy as np \nimport tensorflow as tf \n\nfrom tqdm import tqdm\nfrom sklearn.datasets import make_moons\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import normalize\nfrom sklearn.utils import shuffle\nglobal_seed = 25325\n\n\n\ntest_idx = 208\nepsilon = 0.001\n\n# set random seed\nnp.random.seed(global_seed)\nrandom.seed(global_seed)\ntf.set_random_seed(global_seed)\nhd_str = 'Creditability,Account Balance,Duration of Credit \\\n (month),Payment Status of Previous Credit,Purpose,Credit Amount,Value Savings/Stocks,Length of current employment,Instalment per cent,Sex & Marital Status,Guarantors,Duration in Current address,Most valuable available asset,Age (years),Concurrent Credits,Type of apartment,No of Credits at this Bank,Occupation,No of dependents,Telephone,Foreign Worker'\n\n# TODO transfer y to hot vector\n# construct models\nos.environ['CUDA_VISIBLE_DEVICES'] = '-1'\n\n\n# load dataset\ndataset = np.loadtxt('german_credit.csv', delimiter=',', skiprows=1)\ndata_X = dataset[:, 1:].astype(np.float)\nmean_X = np.mean(data_X, axis=0)\nstd_X = np.std(data_X, axis=0)\ndata_X = (data_X - mean_X) / std_X\ndata_y = dataset[:, 0]\ndata_y = np.eye(2)[data_y.astype(np.int)]\nx_train, x_test, y_train, y_test = train_test_split(data_X, data_y)\nx_train , y_train = shuffle(x_train, y_train)\n\ns_x = tf.constant(np.array([x_test[test_idx]]), dtype=tf.float32)\ns_y = tf.constant(np.array([y_test[test_idx]]), dtype=tf.float32)\n\n\n\ndef plot_data(name, x_train, y_train, nn_x = None, rdata=None):\n # plot visualization figure\n plt.figure(figsize=[4, 4])\n # plt.axis('off')\n plt.gca().xaxis.set_major_locator(plt.NullLocator())\n plt.gca().yaxis.set_major_locator(plt.NullLocator())\n\n yy = np.argmax(y_train, axis=1)\n pos = np.where(yy == 1)\n neg = np.where(yy == 0)\n\n plt.scatter(x_train[pos, 0], x_train[pos, 1], marker='o', c='b',s=5**2)\n plt.scatter(x_train[neg, 0], x_train[neg, 1], marker='x', c='r',s=5**2)\n \n if nn_x is not None:\n plt.scatter(nn_x[:, 0], nn_x[:, 1], marker='.', c='k', s=5**2)\n\n if rdata is not None and len(rdata) > 0:\n rdata = np.array(rdata)\n plt.scatter(data_X[test_idx, 0], data_X[test_idx, 1], marker='o', c='c',s=10**2)\n plt.scatter(rdata[:, 0], rdata[:, 1], marker='>', c='m', s=10**2)\n \n # plt.xlabel('Feature 1')\n # plt.ylabel('Feature 2')\n plt.savefig(name, bbox_inches='tight')\n plt.clf()\n\ndef linear_model(x_ph, reuse=False):\n with tf.variable_scope('model') as vs:\n if reuse:\n vs.reuse_variables()\n \n return tf.layers.dense(x_ph, 2, activation=None)\n\ndef mlp_model(x_ph, reuse=False):\n with tf.variable_scope(\"model\") as vs:\n if reuse:\n vs.reuse_variables()\n h1 = tf.layers.dense(x_ph, 4, activation=tf.nn.tanh)\n h2 = tf.layers.dense(h1, 4, activation=tf.nn.tanh)\n # h2 = h1\n logit = tf.layers.dense(h2, 2, activation=None)\n \n return logit\n\nmodel = mlp_model\n\nx1 = np.arange(-0.1, 1.1, 0.001)\nx2 = np.arange(-0.1, 1.1, 0.001)\nmargin_X = np.array(list(itertools.product(x1, x2)))\n\n\nmaxiter = 30\n# linear\n# maxiter = 50\nn_class = 2\nX = tf.placeholder(tf.float32, [None, x_train.shape[1]], name=\"X\")\nY = tf.placeholder(tf.float32, [None, 2], name=\"Y\")\n\n\n \nlogit = model(X, reuse=False)\nlogit_ent = tf.nn.softmax_cross_entropy_with_logits(logits=logit, labels=Y)\nloss = tf.reduce_mean(logit_ent)\n\n# First lets try trainditional optimizer\noptimizer = tf.contrib.opt.ScipyOptimizerInterface(loss, \n method='SLSQP',\n options={'maxiter': maxiter})\nprint(\"maxiter=%d\"%(maxiter))\n\ntrain_variables = tf.trainable_variables()\nflat_vars = tf.concat([tf.reshape(var, [-1]) for var in train_variables], axis=0)\n\n\nfeed_dict = {X:x_train, Y:y_train}\ntest_fd = {X:x_test, Y:y_test}\ncorrect_prediction = tf.equal(tf.argmax(logit, 1), tf.argmax(Y, 1))\naccuracy = tf.reduce_mean(tf.to_float(correct_prediction))\n\n\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n optimizer.minimize(sess, feed_dict=feed_dict)\n best_loss = sess.run(loss, feed_dict)\n b_lent = sess.run(logit_ent, feed_dict=feed_dict)\n\n print(\"Training accuracy: %f\"%(accuracy.eval({X:x_train, Y:y_train})))\n print(\"loss = %f\"%(loss.eval(feed_dict)))\n s_logit = model(s_x, reuse=True)\n\n print(\"Test acc %f, loss %f\" %(accuracy.eval(test_fd), loss.eval(test_fd)))\n\n\n # plot_data(\"hpnn/opt.pdf\", x_train, y_train, nn_x=nn_x)\n # tf.nn.softmax_cross_entropy_with_logits(logits=model(s_x, reuse=True), labels=s_y)\n # TODO check label for s_y\n # lets do the ugly part\n # inequalities\n if np.argmax(y_test[test_idx]) == 0:\n inequalities = [- ((s_logit[0][0] - s_logit[0][1]) + epsilon)]\n else:\n inequalities = [- ((s_logit[0][1] - s_logit[0][0]) + epsilon)]\n pdb.set_trace()\n # Here is the new dataset\n \n sess.run(tf.global_variables_initializer())\n # x_train = np.delete(x_train, test_idx, axis=0)\n # y_train = np.delete(y_train, test_idx, axis=0)\n feed_dict = {X:x_train, Y:y_train}\n\n new_ops = tf.contrib.opt.ScipyOptimizerInterface(loss, \n inequalities=inequalities, \n method='SLSQP',\n options={'maxiter': maxiter })\n \n new_ops.minimize(sess, feed_dict=feed_dict)\n cur_loss = sess.run(loss, feed_dict)\n print('New loss %f'%(cur_loss))\n #TODO after accuracy\n print(\"Training accuracy: %f\"%(accuracy.eval(feed_dict)))\n print(tf.nn.softmax(s_logit).eval(), sess.run(inequalities))\n # nn_x = fine_marginline(logit)\n # plot_data(\"hpnn/opt_1.pdf\", x_train, y_train, nn_x=nn_x)\n hat_lent = b_lent # np.delete(b_lent, test_idx, axis=0)\n rdata_x = []\n rdata_y = []\n pdb.set_trace()\n # starting optimization process\n for tt in range(50):\n print(\"Start iter=%d------------------------------------\"%(tt))\n \n # constraint one\n cur_ent = logit_ent.eval(feed_dict)\n idx = np.argmax((cur_ent - hat_lent), axis=0)\n\n rdata_x.append(x_train[idx])\n rdata_y.append(y_train[idx])\n print(\"selecting data x=%s, y_train=%s, diff =%s\"%(x_train[idx], y_train[idx], cur_ent[idx] - hat_lent[idx]))\n\n # delete data points from dataset\n x_train = np.delete(x_train, idx, axis=0)\n y_train = np.delete(y_train, idx, axis=0)\n # hat_lent = np.delete(hat_lent, idx, axis=0)\n feed_dict={X:x_train, Y:y_train}\n\n sess.run(tf.global_variables_initializer())\n optimizer.minimize(sess, feed_dict=feed_dict)\n best_loss = sess.run(loss, feed_dict)\n hat_lent = sess.run(logit_ent, feed_dict=feed_dict)\n print(\"Test acc %f, loss %f\" %(accuracy.eval(test_fd), loss.eval(test_fd)))\n print(\"Unconstrain iter %d loss: %f, acc: %f\"%(tt,loss.eval(feed_dict), accuracy.eval({X:x_train, Y:y_train})))\n s_logit = model(s_x, reuse=True)\n\n # first one\n # nn_x = fine_marginline(logit)\n # plot_data(\"hpnn/demo_%d_0.pdf\"%(tt), x_train, y_train, nn_x=nn_x)\n\n # second one\n # sess.run(tf.global_variables_initializer())\n new_ops.minimize(sess, feed_dict=feed_dict)\n cur_loss = sess.run(loss, feed_dict)\n print(\"Constrained Iter %d loss %f accuracy: %f\"%(tt, cur_loss, accuracy.eval(feed_dict)))\n print(\"Test acc %f, loss %f\" %(accuracy.eval(test_fd), loss.eval(test_fd)))\n # nn_x = fine_marginline(logit)\n # plot_data(\"hpnn/demo_%d_1.pdf\"%(tt), x_train, y_train, nn_x=nn_x, rdata=rdata_x)\n print(tf.nn.softmax(s_logit).eval(), sess.run(inequalities))\n \n if best_loss >= cur_loss :\n # save to file\n rdata_x.append(x_test[test_idx])\n rdata_y.append(y_test[test_idx])\n\n rdata_x = np.array(rdata_x, dtype=np.float)\n rdata_x = rdata_x * std_X + mean_X\n rdata_x = np.array(rdata_x, dtype=np.int)\n rdata_y = np.array(rdata_y, dtype=np.int)\n rdata_y = np.expand_dims(np.argmax(rdata_y, axis=1), axis=1)\n \n data = np.concatenate([rdata_y, rdata_x], axis=1)\n\n np.savetxt('nn_select.csv', data, fmt='%d', delimiter=',', header=hd_str)\n break\n\n","sub_path":"german_uci/ger_nn.py","file_name":"ger_nn.py","file_ext":"py","file_size_in_byte":8395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"169538967","text":"#Define Python dictionary of key values\n\natrib = {'i_ComMode': 0,\n'i_leftV': 0,\n'i_leftH': 0,\n'i_RightV': 0,\n'i_RightH': 0,\n'i_BodyRot1y': 0,\n'i_BodyRot1z': 0,\n'i_TravelLengthx': 0,\n'i_TravelLengthz': 0,\n'i_TravelLengthy': 0,\n'i_SpeedControl': 0,\n'i_BodyYOffset': 0,\n'i_BodyYShift': 0,\n'i_SelectedLeg': 0,\n'i_LegLiftHeight': 0,\n'i_LegLiftHeight': 0,\n'i_Bal': 0,\n'i_Gait': 0}\n\n#attributes for a standard packet\nstdatrib = ['i_ComMode',\n 'i_leftV',\n 'i_leftH',\n 'i_RightV',\n 'i_RightH',\n 'buttons',\n 'ext']\n\n#attributes with negative values\naddatrib = ['i_leftV',\n 'i_leftH',\n 'i_RightV',\n 'i_RightH']\n\n","sub_path":"JimBob/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"599789605","text":"#!/usr/bin/python\r\n#\r\n# Automation script to update the DNS record inside the instance and DNS record based on Tag value\r\n#\r\n#\r\n# Written specifically for Accenture and NAB by dong.yang@accenture.com\r\n#\r\n\r\n# import labs\r\nimport boto3\r\nimport time\r\nimport requests\r\nimport Script00mylib as mylib\r\n\r\n# Variables. Update values if required\r\n\r\nAWS_REGION=\"ap-southeast-2\"\r\n# DNSTag_Name=\"ServerRole\"\r\nDNSZone_Name=\"cemad.extnp.national.com.au.\"\r\nHostedZoneId=\"Z3RQD0UV5PMRBG\"\r\nTTL=300\r\nCommentVal=\"This is created by DNS script\"\r\n\r\n## init mylog - setup the log file etc.\r\nmylogger = mylib.myloginit('DNSUpdate')\r\nmylib.mylog(mylogger, 'message',\"===========Start DNS update logging===============\")\r\n\r\n## Set default reagion for AWS call\r\nSetDefaultRegion = boto3.setup_default_session(region_name=AWS_REGION)\r\nmylib.mylog(mylogger, 'message',\"Set default region to (\" + AWS_REGION +\")\")\r\n\r\n## Get InstanceID\r\nInstanceId = requests.get('http://169.254.169.254/latest/meta-data/instance-id')\r\nInstanceId = InstanceId.text\r\nmylib.mylog(mylogger, 'message',\"Got instance ID (\" + InstanceId +\")\")\r\n\r\n## Get Instance private IP\r\nPrivateIP = requests.get('http://169.254.169.254/latest/meta-data/local-ipv4')\r\nPrivateIP = PrivateIP.text\r\nmylib.mylog(mylogger, 'message',\"Got instance Private IP (\" + PrivateIP +\")\")\r\n\r\n## Setup ec2 connection\r\nec2client = boto3.client('ec2')\r\n\r\n## get the stack name and convert to DNS name\r\nTags = ec2client.describe_tags(Filters=[{'Name': 'resource-id', 'Values': [ InstanceId ] }, {'Name': 'key', 'Values': [ 'aws:cloudformation:stack-name' ] }])\r\nStack_Name = Tags['Tags'][0]['Value']\r\nmylib.mylog(mylogger, 'message',\"Got Stack name (\" + Stack_Name +\")\")\r\n\r\nDNSName= Stack_Name+'.'+DNSZone_Name\r\nmylib.mylog(mylogger, 'message',\"Combined the instance DNS name to (\" + DNSName +\")\")\r\n\r\n\r\n### Assume the role\r\nstsclient = boto3.client('sts')\r\nstsresponse = stsclient.assume_role(\r\n RoleArn='arn:aws:iam::803264201466:role/HIPExtNpRoute53UpdateRole',\r\n RoleSessionName='CallFromDNSUpdate',\r\n)\r\n\r\nACCESS_KEY=stsresponse['Credentials']['AccessKeyId']\r\nSECRET_KEY=stsresponse['Credentials']['SecretAccessKey']\r\nSESSION_TOKEN=stsresponse['Credentials']['SessionToken']\r\n\r\nmylib.mylog(mylogger, 'message',\"Assume role with Access key ID (\" + ACCESS_KEY +\")\")\r\n\r\n####\r\nrt53client = boto3.client('route53',\r\n aws_access_key_id=ACCESS_KEY,\r\n aws_secret_access_key=SECRET_KEY,\r\n aws_session_token=SESSION_TOKEN,\r\n )\r\n\r\ncont_code = {'ContinentCode':'AS'}\r\n\r\nDNSupdateresponse = rt53client.change_resource_record_sets(\r\n HostedZoneId = HostedZoneId,\r\n ChangeBatch={\r\n 'Comment': 'This is a test',\r\n 'Changes': [\r\n {\r\n 'Action': 'UPSERT',\r\n 'ResourceRecordSet': {\r\n 'Name': DNSName,\r\n 'Type': 'A',\r\n 'SetIdentifier': 'my_a_record',\r\n 'GeoLocation': cont_code,\r\n 'TTL': TTL,\r\n 'ResourceRecords': [\r\n {\r\n 'Value': PrivateIP\r\n },\r\n ],\r\n }\r\n },\r\n ]\r\n }\r\n)\r\n\r\nDNSupdateStatus = rt53client.get_change(Id=DNSupdateresponse['ChangeInfo']['Id'])\r\ni=1\r\nwhile DNSupdateStatus['ChangeInfo']['Status'] == 'PENDING' :\r\n # print(i, \"DNS record update status %s \" % DNSupdateStatus['ChangeInfo']['Status'])\r\n mylib.mylog(mylogger, 'message', \"Updating DNS update status: \" + DNSupdateStatus['ChangeInfo']['Status'] +\" - \" + str(i))\r\n DNSupdateStatus = rt53client.get_change(Id=DNSupdateresponse['ChangeInfo']['Id'])\r\n time.sleep(1)\r\n i=i+1\r\n\r\nif DNSupdateStatus['ChangeInfo']['Status'] == 'INSYNC':\r\n mylib.mylog(mylogger, 'message', \"DNS updated successful with status: (\"+ DNSupdateStatus['ChangeInfo']['Status'] + \")\")\r\nelse:\r\n mylib.mylog(mylogger, 'error', \"DNS updated with status: (\"+ DNSupdateStatus['ChangeInfo']['Status'] + \")\")\r\n","sub_path":"cloudformation/cfndsl/01-Scripts/Script41UpdateDNS.py","file_name":"Script41UpdateDNS.py","file_ext":"py","file_size_in_byte":3994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"143228356","text":"\"\"\"\nStandardization of datasets is a common requirement for many machine learning estimators implemented in scikit-learn;\nthey might behave badly if the individual features do not more or less look like standard normally distributed data: Gaussian with zero mean and unit variance.\n\"\"\"\nfrom sklearn import preprocessing\nimport numpy as np\nX_train = np.array([[ 1., -1., 2.],\n [ 2., 0., 0.],\n [ 0., 1., -1.]])\nX_scaled = preprocessing.scale(X_train)\nprint(X_scaled)\n\n#the purpose of standardization is to make the mean become 0\nprint(X_scaled.mean())\nprint(X_scaled.std(axis=0))","sub_path":"2_Preprocessing_Data/Standardization.py","file_name":"Standardization.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"65722348","text":"#!/usr/bin/env python3\n\"\"\"\nCopyright (c) 2014-2018, Ian Smith (m4r35n357)\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\nfrom json import loads\nfrom sys import stdin, stderr, argv\nfrom gmpy2 import get_context, mpfr, sqrt, sin, cos, acos\nget_context().precision = 236 # Set this BEFORE importing or defining any Taylor Series / Dual Number stuff!\nfrom dual import Dual\n\n# ./Bh.py = start and i % tr == 0:\n self.plot(τ)\n self.stormer_verlet(δτ)\n i += 1\n τ = δτ * i\n self.plot(τ)\n\n def plot(self, τ):\n h = self.h(self.qr, self.qθ, self.pt, self.pr, self.pθ, self.pφ).val\n print(f'{{\"tau\":{τ:.9e},\"v4e\":{h - self.h0:.9e},\"H\":{h:.9e},\"E\":{- self.pt.val:.9e},\"L\":{self.pφ.val:.9e},'\n f'\"Q\":{(self.pθ.sqr + self.qθ.cos.sqr * (self.a**2 * (self.μ2 - self.pt.sqr) + (self.pφ / self.qθ.sin).sqr)).val:.9e},'\n f'\"t\":{self.qt:.9e},\"r\":{self.qr.val:.9e},\"th\":{self.qθ.val:.9e},\"ph\":{self.qφ:.9e}}}')\n\n\ndef secant(f, a, b, h, ε, limit=101):\n f_a = f(h, a)\n f_b = f(h, b)\n count = δx = c = f_c = 1\n while abs(f_c) > ε or abs(δx) > ε:\n if count == limit:\n raise RuntimeError(\"{}\\n Giving up after {} iterations, value {}, previous {}\".format(f, count - 1, a, b))\n c = (b * f_a - a * f_b) / (f_a - f_b)\n f_c = f(h, c)\n b = a\n f_b = f_a\n a = c\n f_a = f_c\n δx = b - a\n count += 1\n return c\n\nif __name__ == \"__main__\":\n # Example: ./Bh.py initial-conditions.json | ./filegraphics-pi.py initial-conditions.json\n print(\"Simulator: {}\".format(argv[0]), file=stderr)\n input_data = open(argv[1]).read() if len(argv) == 2 else stdin.read()\n ic = loads(input_data, parse_float=mpfr)['IC']\n print(input_data, file=stderr)\n step = ic['step']\n bh = Kerr(ic['M'], ic['a'], ic['q'], ic['mu'], ic['E'], ic['L'], ic['Q'], ic['r0'], ic['th0'], ic['tol'])\n bh.solve(step, ic['start'], ic['end'], ic['plotratio'])\nelse:\n print(__name__ + \" module loaded\", file=stderr)\n","sub_path":"Bh.py","file_name":"Bh.py","file_ext":"py","file_size_in_byte":7618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"600514774","text":"#Mario Edmundo Ac Hernandez\r\n#No. Control: 18390055\r\n#Programa para plotear un plano(Triangular) y el hit point, asi como sus respectivos triangulos y\r\n#el calculo de sus area para saber si el hit point esta dentro o fuera\r\n\r\n#Profe no pude realizar que es programa finalizara presionando la tecla Esc, solo pude escribiendo esc.\r\nimport matplotlib.pyplot as plt \r\nimport numpy as np\r\nfrom math import sin, cos, radians,sqrt\r\n#import keyboard\r\n\r\n#Coordenadas globales\r\nxg=[]\r\nyg=[]\r\nzg=[]\r\n#Cordenadas centrales\r\nxc=80\r\nyc=40\r\nzc=40\r\n#Plano del sistema y hitpoint\r\nx=[]\r\ny=[]\r\nz=[]\r\n\r\ndef plotTriangleLine(x,y,z,xg,yg,zg,hpx,hpy):#Funcion para plotear el Plano(Triangular) y el hitpoint\r\n\r\n plt.axis([0,250,200,0])#Definimos el tamaño de la ventana\r\n plt.axis('on')\r\n plt.grid(True)\r\n\r\n #Ejes X Y \r\n plt.plot([8,240],[8,8],color='k')\r\n plt.text(120,5.5,'X')\r\n plt.plot([8,8],[8,190],color='k')\r\n plt.text(3,80,'Y')\r\n\r\n x=[40,30,80,hpx]#Llenamos los vectores con el hitpoint\r\n y=[60,10,60,hpy]\r\n z=[0,0,0,0]\r\n\r\n for i in range(len(x)):#Llenamos los vectores globales\r\n xg.append(x[i]+xc)\r\n yg.append(y[i]+yc)\r\n zg.append(z[i]+zc)\r\n\r\n AA,AA1,AA2=plotHitpoint(x,y,z)\r\n\r\n plt.text(xg[0],yg[0],'0')\r\n plt.text(xg[1],yg[1],'1')\r\n plt.text(xg[2],yg[2],'2')\r\n plt.text(xg[3],yg[3],'3')\r\n plt.text(xg[3]+4,yg[3]+4,'Hitpoint')\r\n plt.title(\"Triangular Plane And Hitpoint\")\r\n \r\n plt.plot([xg[0],xg[1]],[yg[0],yg[1]],color='k')#Ploteamos el Plano Base(Triangulo A)\r\n plt.plot([xg[1],xg[2]],[yg[1],yg[2]],color='k')\r\n plt.plot([xg[2],xg[0]],[yg[2],yg[0]],color='k')\r\n plt.text(xg[0]+10,yg[0]-15,'A',color ='k')\r\n\r\n plt.plot([xg[0],xg[1]],[yg[0],yg[1]],color='purple')#Ploteamos el Triangulo A1\r\n plt.plot([xg[1],xg[3]],[yg[1],yg[3]],color='purple')\r\n plt.plot([xg[3],xg[0]],[yg[3],yg[0]],color='purple')\r\n plt.text(xg[1]-5,yg[1]+30,'A1',color ='purple')\r\n\r\n plt.plot([xg[0],xg[2]],[yg[0],yg[2]],color='g')#Ploteamos el triangulo A2\r\n plt.plot([xg[2],xg[3]],[yg[2],yg[3]],color='g')\r\n plt.plot([xg[3],xg[0]],[yg[3],yg[0]],color='g')\r\n plt.text(xg[2]-27,yg[2]+7,'A2',color ='g')\r\n\r\n #ETIQUETAS DE LAS AREAS\r\n plt.text(15,150,'El area del Triangulo A es: ' + str(AA),color ='k')\r\n plt.text(15,160,'El area del Triangulo A1 es: ' + str(AA1),color='purple')\r\n plt.text(15,170,'El area del Triangulo A2 es: ' + str(AA2),color ='g')\r\n Total=AA1+AA2\r\n plt.text(15,180,'La suma del area de los Triangulos A1+A2= ' + str(Total))\r\n\r\n #Calculamos si el Hitpoint está dentro o fuera del límite\r\n if(AA1+AA2 > AA):\r\n plt.text(15,25,'El Hitpoint esta fuera del límite',color ='k')\r\n plt.scatter(xg[3],yg[3],s=22,color='orange') #Pintamos el hitpoint\r\n elif (AA1+AA2 < AA):\r\n plt.text(15,25,'El Hitpoint esta dentro del límite',color ='k')\r\n plt.scatter(xg[3],yg[3],s=22,color='blue') #Pintamos el hitpoint \r\n\r\n plt.show()\r\n\r\n\r\ndef plotHitpoint(x,y,z):#Calculamos cada una de las areas de los triangulos con el Hitpoint\r\n #Triangulo A\r\n #Distance point 0 to 1\r\n a=x[1]-x[0]\r\n b=y[1]-y[0]\r\n c=z[1]-z[0]\r\n D1=sqrt(a*a+b*b+c*c) \r\n #Distance point 1 to 2\r\n a=x[2]-x[1]\r\n b=y[2]-y[1]\r\n c=z[2]-z[1]\r\n D2=sqrt(a*a+b*b+c*c) \r\n #Distance point 2 to 0\r\n a=x[2]-x[0]\r\n b=y[2]-y[0]\r\n c=z[2]-z[0]\r\n D3=sqrt(a*a+b*b+c*c) \r\n\r\n s1 = (D1+D2+D3)/2 #Calculamos el semiperimetro del triangulo A\r\n A1 = sqrt(s1*(s1-D1)*(s1-D2)*(s1-D3))\r\n\r\n #Triangulo A1\r\n #Distance point 0 to 1\r\n a=x[1]-x[0]\r\n b=y[1]-y[0]\r\n c=z[1]-z[0]\r\n D11=sqrt(a*a+b*b+c*c) \r\n #_____distance point 1 to 3\r\n a=x[3]-x[1]\r\n b=y[3]-y[1]\r\n c=z[3]-z[1]\r\n D22=sqrt(a*a+b*b+c*c) \r\n #_____distance point 3 to 0\r\n a=x[3]-x[0]\r\n b=y[3]-y[0]\r\n c=z[3]-z[0]\r\n D33=sqrt(a*a+b*b+c*c) \r\n\r\n s2 = (D11+D22+D33)/2 #Calculamos el semiperimetro del triangulo A1\r\n A2 = sqrt(s2*(s2-D11)*(s2-D22)*(s2-D33)) \r\n\r\n #Triangulo A2\r\n #__Distance point 0 to 2\r\n a=x[2]-x[0]\r\n b=y[2]-y[0]\r\n c=z[2]-z[0]\r\n D111=sqrt(a*a+b*b+c*c) \r\n #__Distance point 2 to 3\r\n a=x[3]-x[2]\r\n b=y[3]-y[2]\r\n c=z[3]-z[2]\r\n D222=sqrt(a*a+b*b+c*c) \r\n #__Distance point 3 to 0\r\n a=x[3]-x[0]\r\n b=y[3]-y[0]\r\n c=z[3]-z[0]\r\n D333=sqrt(a*a+b*b+c*c) \r\n\r\n s3 = (D111+D222+D333)/2 #Calculamos el semiperimetro del triangulo A2\r\n A3 = sqrt(s3*(s3-D111)*(s3-D222)*(s3-D333))\r\n\r\n return A1,A2,A3\r\n\r\n#Pedimimos al usuario que ingrese las coordenas del Hitpoint y luego ploteamos\r\nwhile True:\r\n axis=input('Presione una tecla para ingresar la coordenadas del Hitpoint o escriba esc para salir: ')\r\n if axis=='esc':\r\n break\r\n elif axis!=\"\":\r\n hpx=(float(input('Coordenada X: ')))\r\n hpy=(float(input('Coordenada Y: ')))\r\n plotTriangleLine(x,y,z,xg,yg,zg,hpx,hpy)\r\n\r\n\r\n\r\n","sub_path":"3D-Recuperacion.py","file_name":"3D-Recuperacion.py","file_ext":"py","file_size_in_byte":4901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"146075978","text":"import sys\r\npath = sys.argv[1]\r\n\r\nfile = open(path)\r\ntext = file.read().lower()\r\nfile.close()\r\n\r\nintp = '''!\"#%&\\()*+,./:;<=>?@[\\\\]^_{|}~'''\r\nfor sign in text:\r\n\tif sign in intp:\r\n\t\ttext = text.replace(sign, \"\")\r\nwords = text.split()\r\n\r\np = open(\"p.txt\")\r\npositive = p.read().split()\r\np.close()\r\n\r\nn = open(\"n.txt\")\r\nnegative = n.read().split()\r\nn.close()\r\n\r\nnots = open(\"negation.txt\")\r\nnegation = nots.read().split()\r\nnots.close()\r\n\r\nsentiment = 0\r\nbeforenotpos = \"\"\r\nbeforenotneg = \"\"\r\n\r\nfor number, word in enumerate(words):\r\n\tif word in positive:\r\n\t\tbeforenotpos += words[number - 1]\r\n\t\tif beforenotpos in negation:\r\n\t\t\tsentiment -= 2\r\n\t\telse:\r\n\t\t\tsentiment += 1\r\n\telif word in negative:\r\n\t\tbeforenotneg += words[number - 1]\r\n\t\tif beforenotneg in negation:\r\n\t\t\tsentiment += 2\r\n\t\telse:\r\n\t\t\tsentiment -= 1\r\n\r\nif sentiment > 0:\r\n\tprint(text)\r\n\tprint(\"Positive sentence.\")\r\nelif sentiment < 0 :\r\n\tprint(text)\r\n\tprint(\"Negative sentence.\")\r\nelse:\r\n\tprint(text)\r\n\tprint(\"Neutral sentence.\")\r\n","sub_path":"sentiment/sentiment.py","file_name":"sentiment.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"333439996","text":"from django.conf.urls.defaults import *\nfrom django.conf import settings\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\n\nurlpatterns = patterns('',\n # Example:\n # (r'^apprising/', include('apprising.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n (r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n (r'^admin/', include(admin.site.urls)),\n\n # django-tinymce\n # (r'^tinymce/', include('tinymce.urls')),\n\n # this breaks css - why?\n #(r'', include('django.contrib.flatpages.urls')),\n)\n\nif settings.DEBUG:\n urlpatterns += patterns('',\n (r'^static/(?P.*)$', 'django.views.static.serve', \\\n\t\t{'document_root': settings.STATIC_FILE_ROOT}),\n\t# tinymce setup from \"Practical Django Projects\", Ch. 3\n\t(r'^tiny_mce/(?P.*)$', 'django.views.static.serve', \\\n\t\t{'document_root': settings.STATIC_FILE_ROOT + \"/js/tiny_mce\"}),\n )\n","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"457029954","text":"# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n ARKspatial\n A QGIS plugin for Archaeological Recording.\n Part of the Archaeological Recording Kit by L - P : Archaeology\n http://ark.lparchaeology.com\n -------------------\n copyright : 2017 by L - P : Heritage LLP\n email : ark@lparchaeology.com\n copyright : 2017 by John Layt\n email : john@layt.net\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program is free software; you can redistribute it and/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\nfrom PyQt4.QtCore import pyqtSignal\nfrom PyQt4.QtGui import QAction, QIcon\n\nfrom qgis.core import QgsProject\n\nfrom .snapping_ import Snapping\n\n\nclass ProjectSnappingEnabledAction(QAction):\n\n \"\"\"Action to enable snapping.\"\"\"\n\n snappingEnabledChanged = pyqtSignal()\n\n def __init__(self, parent=None):\n super(ProjectSnappingEnabledAction, self).__init__(parent)\n\n self._selectedLayers = []\n self._prevType = Snapping.Off\n\n self.setText('Toggle Snapping')\n self.setStatusTip('Enbale/disable snapping')\n self.setIcon(QIcon(':/plugins/ark/snapEnable.png'))\n self.setCheckable(True)\n self._refresh()\n self.triggered.connect(self._triggered)\n\n # Make sure we catch changes in the main snapping dialog\n QgsProject.instance().snapSettingsChanged.connect(self._refresh)\n # If a new project is read, update to that project's setting\n QgsProject.instance().readProject.connect(self._refresh)\n self.snappingEnabledChanged.connect(QgsProject.instance().snapSettingsChanged)\n\n def setInterface(self, iface):\n self._toleranceAction.setInterface(iface)\n\n def unload(self):\n QgsProject.instance().snapSettingsChanged.disconnect(self._refresh)\n QgsProject.instance().readProject.disconnect(self._refresh)\n self.snappingEnabledChanged.disconnect(QgsProject.instance().snapSettingsChanged)\n\n # Private API\n\n def _triggered(self, checked):\n if checked:\n if Snapping.snappingMode() == Snapping.SelectedLayers:\n Snapping.setLayerSnappingEnabledLayers(self._selectedLayers)\n else:\n Snapping.setProjectSnappingType(self._prevType)\n else:\n if Snapping.snappingMode() == Snapping.SelectedLayers:\n self._selectedLayers = Snapping.layerSnappingEnabledLayers()\n Snapping.setLayerSnappingEnabledLayers([])\n else:\n self._prevType = Snapping.projectSnappingType()\n Snapping.setProjectSnappingType(Snapping.Off)\n self.snappingEnabledChanged.emit()\n\n def _refresh(self):\n self.blockSignals(True)\n snapMode = Snapping.snappingMode()\n snapType = Snapping.projectSnappingType()\n if snapType != Snapping.Off:\n self._prevType = snapType\n selectedLayers = Snapping.layerSnappingEnabledLayers()\n if len(selectedLayers) > 0:\n self._selectedLayers = selectedLayers\n if snapMode == Snapping.SelectedLayers:\n self.setChecked(len(selectedLayers) > 0)\n else:\n self.setChecked(snapType != Snapping.Off)\n self.blockSignals(False)\n","sub_path":"ark/lib/snapping/project_snapping_enabled_action.py","file_name":"project_snapping_enabled_action.py","file_ext":"py","file_size_in_byte":3985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"212003361","text":"\r\ndef main():\r\n\tflag = -1;\r\n\r\n\twhile flag < 0:\r\n\t\tinput1 = raw_input(\"Input: \")\r\n\t\tfile = open(\"file1.ncc\", \"a\")\r\n\t\tfile.write(input1)\r\n\t\tfile.write(\"\\n\")\r\n\t\tif(input1 == \"M2\"):\r\n\t\t\tflag = 1;\r\n\t\t\tfile.close()\r\n\r\nmain()","sub_path":"input.py","file_name":"input.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"8160842","text":"from typing import Dict, List, Set\n\nfrom BaseClasses import MultiWorld\nfrom Options import TechTreeLayout\nfrom worlds.factorio.Technologies import technology_table\n\ndef get_shapes(world: MultiWorld, player: int) -> Dict[str, List[str]]:\n prerequisites: Dict[str, Set[str]] = {}\n layout = world.tech_tree_layout[player].value\n custom_technologies = world.custom_data[player][\"custom_technologies\"]\n if layout == TechTreeLayout.option_small_diamonds:\n slice_size = 4\n tech_names: List[str] = list(set(custom_technologies) - world._static_nodes)\n tech_names.sort()\n world.random.shuffle(tech_names)\n while len(tech_names) > slice_size:\n slice = tech_names[:slice_size]\n tech_names = tech_names[slice_size:]\n slice.sort(key=lambda tech_name: len(custom_technologies[tech_name].ingredients))\n diamond_0, diamond_1, diamond_2, diamond_3 = slice\n\n # 0 |\n # 1 2 |\n # 3 V\n prerequisites[diamond_3] = {diamond_1, diamond_2}\n prerequisites[diamond_2] = prerequisites[diamond_1] = {diamond_0}\n elif layout == TechTreeLayout.option_medium_diamonds:\n slice_size = 9\n tech_names: List[str] = list(set(custom_technologies) - world._static_nodes)\n tech_names.sort()\n world.random.shuffle(tech_names)\n while len(tech_names) > slice_size:\n slice = tech_names[:slice_size]\n tech_names = tech_names[slice_size:]\n slice.sort(key=lambda tech_name: len(custom_technologies[tech_name].ingredients))\n\n # 0 |\n # 1 2 |\n # 3 4 5 |\n # 6 7 |\n # 8 V\n\n prerequisites[slice[1]] = {slice[0]}\n prerequisites[slice[2]] = {slice[0]}\n\n prerequisites[slice[3]] = {slice[1]}\n prerequisites[slice[4]] = {slice[1], slice[2]}\n prerequisites[slice[5]] = {slice[2]}\n\n prerequisites[slice[6]] = {slice[3], slice[4]}\n prerequisites[slice[7]] = {slice[4], slice[5]}\n\n prerequisites[slice[8]] = {slice[6], slice[7]}\n\n elif layout == TechTreeLayout.option_pyramid:\n slice_size = 1\n tech_names: List[str] = list(set(custom_technologies) - world._static_nodes)\n tech_names.sort()\n world.random.shuffle(tech_names)\n tech_names.sort(key=lambda tech_name: len(custom_technologies[tech_name].ingredients))\n previous_slice = []\n while len(tech_names) > slice_size:\n slice = tech_names[:slice_size]\n world.random.shuffle(slice)\n tech_names = tech_names[slice_size:]\n for i, tech_name in enumerate(previous_slice):\n prerequisites.setdefault(slice[i], set()).add(tech_name)\n prerequisites.setdefault(slice[i + 1], set()).add(tech_name)\n previous_slice = slice\n slice_size += 1\n\n elif layout == TechTreeLayout.option_funnel:\n\n\n tech_names: List[str] = list(set(custom_technologies) - world._static_nodes)\n # find largest inverse pyramid\n # https://www.wolframalpha.com/input/?i=x+=+1/2+(n++++1)+(2++++n)+solve+for+n\n import math\n slice_size = int(0.5*(math.sqrt(8*len(tech_names)+1)-3))\n tech_names.sort()\n world.random.shuffle(tech_names)\n tech_names.sort(key=lambda tech_name: len(custom_technologies[tech_name].ingredients))\n previous_slice = []\n while slice_size:\n slice = tech_names[:slice_size]\n world.random.shuffle(slice)\n tech_names = tech_names[slice_size:]\n if previous_slice:\n for i, tech_name in enumerate(slice):\n prerequisites.setdefault(tech_name, set()).update(previous_slice[i:i+2])\n previous_slice = slice\n slice_size -= 1\n\n world.tech_tree_layout_prerequisites[player] = prerequisites\n return prerequisites\n","sub_path":"worlds/factorio/Shapes.py","file_name":"Shapes.py","file_ext":"py","file_size_in_byte":3997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"159631426","text":"from os import popen\nfrom pathlib import Path\n\n\ndef dir_is_valid(dir_p) -> bool:\n \"\"\"验证有效性:只有以2位数字开头的文件夹才是需要的\"\"\"\n return dir_p.name[0:2].isdigit()\n\n\ndef file_is_valid(file_p) -> bool:\n \"\"\"验证有效性:根据本项目命名规律,所有.py或.md文件才是需要目录的\"\"\"\n return file_p.suffix in ('.py', '.md')\n\n\nclass TocMaker:\n \"\"\"\n 生成项目toc目录、统计代码行数并写入markdown文件\n \"\"\"\n\n def __init__(self, working_dir: str = './'):\n self.working_dir = Path(working_dir)\n self.tree_dict = None\n self.cloc_result = None\n self.tree()\n\n def tree(self):\n \"\"\"\n 列出工作目录下所有符合要求的目录和文件\n \"\"\"\n tree_result = dict()\n file_name_list = list()\n\n # 列出工作目录下所有项目并验证有效性:只有以2位数字开头的文件夹才是需要的\n valid_dir_list = [x for x in self.working_dir.iterdir() if x.is_dir() and dir_is_valid(x)]\n valid_dir_list.sort() # 按照名称排序\n\n # 验证有效性\n for valid_dir in valid_dir_list:\n iterated_files = list(valid_dir.iterdir())\n iterated_files.sort()\n for file in iterated_files:\n # 根据本项目命名规律,所有.py或.md文件才是需要目录的\n if file_is_valid(file):\n file_name_list.append(file)\n tree_result.update({valid_dir: file_name_list})\n file_name_list = list() # 重新置空\n\n self.tree_dict = tree_result\n\n def cloc(self, gitignore_file: str = '.gitignore'):\n \"\"\"\n 使用cloc统计项目代码行数\n \"\"\"\n ignored_dir = ''\n gitignore_file_p = Path(gitignore_file)\n with gitignore_file_p.open('r', encoding='UTF-8') as f:\n for dir_name in f.readlines():\n dir_name = dir_name.replace('/', '')\n dir_name = dir_name.replace('\\n', ',')\n ignored_dir += dir_name\n\n # 调用cloc,并排除gitignore中的目录,需要提前将cloc添加到系统环境变量\n cmd = f'cloc --exclude-dir {ignored_dir} {str(self.working_dir)}'\n\n with popen(cmd) as p:\n cmd_result = p.read()\n # 如果cmd执行正常退出则p.close()返回None,失败则返回状态码\n if p.close():\n print(\"cloc调用失败,请检查\")\n else:\n # 根据cloc返回结果,连续两个换行符后面的内容是需要的信息\n self.cloc_result = cmd_result.split('\\n\\n', 1)[1]\n print(self.cloc_result)\n\n def write_into_md(self, toc_file='./toc.md'):\n \"\"\"\n 把目录和文件名写入toc.md文件\n \"\"\"\n write_lines = list()\n file_counter = 0\n toc_file_p = Path(toc_file)\n\n if self.tree_dict:\n for dir_name in self.tree_dict:\n write_lines.append(f'### [{dir_name.name}](./{dir_name.name})\\n')\n for file_name in self.tree_dict[dir_name]:\n write_lines.append(f'[{file_name.name}](./{file_name.as_posix()})\\n\\n')\n file_counter += 1\n counter_info = f\"共{len(self.tree_dict)}个目录,{file_counter}个文件.\" # 计数器\n write_lines += counter_info\n with toc_file_p.open('wt', encoding='UTF-8') as f:\n f.writelines(write_lines)\n print(f\"TOC生成成功,{counter_info}\")\n else:\n print(\"tree列表为空,请检查\")\n\n\nif __name__ == '__main__':\n toc_maker = TocMaker('./')\n toc_maker.write_into_md('./toc.md')\n toc_maker.cloc() # 需要在系统中安装cloc并且把命令 'cloc' 添加到环境变量,否则注释掉本行\n","sub_path":"toc_script.py","file_name":"toc_script.py","file_ext":"py","file_size_in_byte":3861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"510954541","text":"import random\nfrom collections import defaultdict\n\nimport pyglet\n\n\nclass Game(object):\n def __init__(self):\n self.window = pyglet.window.Window(\n caption=\"Conway's Game of Life - Generation 0\",\n width=1366, height=768)\n\n self.generation = 0\n\n self.batch = pyglet.graphics.Batch()\n\n self.set_grid()\n self.universe = Universe(self.grid_h, self.grid_w)\n self.set_texture()\n\n self.window.maximize()\n pyglet.clock.schedule_interval(self.update, 1 / 30)\n pyglet.clock.schedule_interval(self.step, 1.5)\n\n def set_grid(self):\n self.grid_w = self.window.width // 16 - 1\n self.grid_h = self.window.height // 16 - 2\n self.x_margin = (self.window.width - self.grid_w * 16) // 2\n self.y_margin = (self.window.height - self.grid_h * 16) // 2\n self.img_ = pyglet.image.load('grass.png')\n self.img1 = self.img_.get_region(x=0, y=0, width=16, height=16)\n self.img2 = self.img_.get_region(x=16, y=0, width=16, height=16)\n self.grid = {}\n for row in range(self.grid_h):\n for col in range(self.grid_w):\n self.grid[(row, col)] = pyglet.sprite.Sprite(\n self.img2,\n y=self.window.height - self.y_margin - 24 - 16 * row,\n x=int(self.x_margin + 16 * col),\n batch=self.batch)\n\n def update(self, dt):\n self.window.clear()\n self.batch.draw()\n\n def step(self, dt=0):\n self.universe.step()\n self.generation += 1\n self.set_texture()\n self.set_title()\n\n def set_texture(self):\n for row in range(self.grid_h):\n for col in range(self.grid_w):\n if self.universe.t0[(row+1, col+1)]:\n self.grid[(row, col)]._set_texture(self.img1.get_texture())\n else:\n self.grid[(row, col)]._set_texture(self.img2.get_texture())\n\n def set_title(self):\n title = \"Conway's Game of Life - Generation {}\".format(\n self.generation)\n print(title)\n self.window.set_caption(title)\n self.window.maximize()\n\n\nclass Universe(object):\n def __init__(self, rows, cols):\n self.t0 = defaultdict(int)\n self.rows = rows\n self.cols = cols\n self.randomize()\n\n def randomize(self):\n for row in range(1, self.rows + 1):\n for col in range(1, self.cols + 1):\n rnd = random.randint(0, 3)\n if rnd:\n self.t0[(row, col)] = 0\n else:\n self.t0[(row, col)] = 1\n return self.t0\n\n def step(self):\n t1 = defaultdict(int)\n for row in range(1, self.rows + 1):\n for col in range(1, self.cols + 1):\n x = sum([\n self.t0[(r, c)]\n for r in range(row - 1, row + 1 + 1)\n for c in range(col - 1, col + 1 + 1)])\n x -= self.t0[(row, col)]\n if self.t0[(row, col)] == 0:\n if x == 3:\n t1[(row, col)] = 1\n else:\n if x >= 4:\n t1[(row, col)] = 0\n elif x <= 1:\n t1[(row, col)] = 0\n else:\n t1[(row, col)] = 1\n self.t0 = t1\n return self.t0\n\n\nif __name__ == '__main__':\n Game()\n pyglet.app.run()\n","sub_path":"pyglet_view.py","file_name":"pyglet_view.py","file_ext":"py","file_size_in_byte":3496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"97541403","text":"## This is a function to walk through\n## an list of words (passed as arg) to\n## focus word selection for madlib.\ndef selectWord (x):\n print(\"Provide a word from this list:\")\n #Shows the user the options available\n print(x)\n #Get user input\n userInput = input()\n #Input validation for input matching a list item\n while userInput not in x:\n print(\"Invalid selection, please retry\")\n print(x)\n userInput = input()\n return userInput\n\nnouns = ['dog','leader','house','car','phone','desk']\nverbs = ['catches','runs','celebrates','forgets','wins','tests']\npreps = ['ahead','behind','above','below','under','over']\nadjectives = ['joyful','underwhelming','breezy','hot','fast','slow']\ncolors = ['gold','purple','green','red','silver','yellow']\n\nprint(\"Hello! Please enter the following: \")\n#getting input for each of the terms to be used in the sentences\nnoun = selectWord(nouns)\nnoun2 = selectWord(nouns)\nverb = selectWord(verbs)\nadjective = selectWord(adjectives)\nadjective2 = selectWord(adjectives)\nprep = selectWord(preps)\ncolor = selectWord(colors)\n\n#taking input and putting them into sentences\nprint(\"The {} {} {} {} {} the {} {}!\".format(adjective,color,noun,verb,prep,adjective2,noun2))\nprint(\"A {} is a {} {} {}!\".format(noun,adjective2,color,noun2))\n","sub_path":"LABS/Labs-3-4/lab3a-madlib.py","file_name":"lab3a-madlib.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"458488508","text":"import os\nimport shutil\nimport time\n\nfrom contextlib import contextmanager\nfrom os.path import exists, join\n\nfrom twspam import network\nfrom twspam.config import Config\nfrom twspam.controllers.vnc import VNCDoController\nfrom twspam.guests.vbox import VBoxVM\nfrom twspam.logger import Logger\nfrom twspam.regions import RegionLoader\nfrom twspam.sessions import SessionInfo\n\nfrom .. import TwitterApp\n\n\nconfig = Config(__name__)\nmain_config = Config('twspam')\nlogger = Logger(__name__)\n\n\nclass TwitterWindowsChromeVM(VBoxVM):\n\n def __init__(self):\n super().__init__(config.vm_name, config.vm_snapshot)\n self.interface = config.vm_interface\n\n def start(self):\n if exists(config.vm_sslkeys_filepath):\n os.remove(config.vm_sslkeys_filepath)\n super().start()\n time.sleep(config.vm_startup_time)\n\n\nclass TwitterWindowsChromeApp(TwitterApp):\n\n def __init__(self):\n controller = VNCDoController(config.vm_ip)\n regions = RegionLoader(config.regions_dirpath)\n session_info = SessionInfo(app='Twitter', os='Windows 7',\n guest='VirtualBox', browser='Google Chrome')\n super().__init__(controller, regions, session_info)\n self.vm = TwitterWindowsChromeVM()\n\n @contextmanager\n def capturing(self, tempdir):\n pcap_filepath = join(tempdir, main_config.session_pcap_filename)\n sslkeys_filepath = join(tempdir, main_config.session_sslkeys_filename)\n with self.vm.started():\n with network.capturing([self.vm.interface], pcap_filepath,\n ips=config.capture_ips,\n ports=config.capture_ports):\n yield\n shutil.copy(config.vm_sslkeys_filepath, sslkeys_filepath)\n\n def open_browser(self):\n self.controller.wait_region(self.regions.taskbar_nobrowser)\n self.controller.click((212, 748), 3)\n self.controller.wait_region(self.regions.taskbar_chromemenu)\n for i in range(3):\n self.controller.keystroke('up')\n self.controller.keystroke('enter')\n self.controller.wait_region(self.regions.magicbar_empty)\n self.controller.type(config.twitter_start_page)\n self.controller.keystroke('enter')\n self.controller.wait_region(self.regions.passfield_cookies, timeout=60)\n\n def accept_cookies(self):\n self.controller.check_region(self.regions.cookiebtn)\n self.controller.click((905, 192))\n self.controller.wait_region(self.regions.passfield_nocookies)\n\n def login(self):\n self.controller.click((650, 205))\n self.controller.type(config.twitter_username)\n self.controller.keystroke('tab')\n self.controller.type(config.twitter_password)\n with self.session_info.adding_event('login'):\n self.controller.keystroke('enter')\n self.controller.wait_region(self.regions.tweetfield_collapsed)\n\n def tweet(self, message):\n self.controller.click((455, 145))\n self.controller.wait_region(self.regions.tweetbtn_disabled)\n self.controller.click((460, 145))\n self.controller.type(message)\n self.controller.wait_region(self.regions.tweetbtn_enabled)\n with self.session_info.adding_event('tweet'):\n self.controller.click((860, 250))\n self.controller.wait_region(self.regions.tweetfield_collapsed)\n\n def logout(self):\n self.controller.click((878, 86))\n self.controller.wait_region(self.regions.usermenu_expanded)\n with self.session_info.adding_event('logout'):\n self.controller.click((800, 380))\n self.controller.wait_region(self.regions.byelogo)\n\n def close_browser(self):\n self.controller.keystroke('ctrl-Q')\n self.controller.wait_region(self.regions.taskbar_nobrowser)\n","sub_path":"twspam_apps/twitter/windows_cr/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"164215764","text":"from struct import *\nimport sys\nimport socket\n\ndef ethernet_head(raw_data):\n dest, src, prototype = struct.unpack('! 6s 6s H', raw_data[:14])\n dest_mac = get_mac_addr(dest)\n src_mac = get_mac_addr(src)\n proto = socket.htons(prototype)\n data = raw_data[14:]\n return dest_mac, src_mac, proto, data\n\ndef main():\n s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))\n while True:\n raw_data, addr = s.recvfrom(65535)\n eth = ethernet(raw_data)\n print('\\nEthernet Frame:')\n print('Destination: {}, Source: {}, Protocol: {}'.format(eth[0], eth[1],eth[2]))\nmain()\n\ndef ipv4_head(raw_data):\n version_header_length = raw_data[0]\n version = version_header_length >> 4\n header_length = (version_header_length & 15) * 4\n ttl, proto, src, target = struct.unpack('! 8x B B 2x 4s 4s', raw_data[:20])\n data = raw_data[header_length:]\n return version, header_length, ttl, proto, src, target, data\ndef main():\n s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))\n while True:\n raw_data, addr = s.recvfrom(65535)\n eth = ethernet(raw_data)\n print('\\nEthernet Frame:')\n print('Destination: {}, Source: {}, Protocol: {}'.format(eth[0], eth[1],eth[2]))\n if eth[2] == 8:\n ipv4 = ipv4(ethp[4])\n print( '\\t - ' + 'IPv4 Packet:')\n print('\\t\\t - ' + 'Version: {}, Header Length: {}, TTL:{},'.format(ipv4[1], ipv4[2], ipv4[3]))\n print('\\t\\t - ' + 'Protocol: {}, Source: {}, Target:{}'.format(ipv4[4], ipv4[5], ipv4[6]))\n\ndef get_ip(addr):\n return '.'.join(map(str, addr))\nsrc = get_ip(src)\ntarget = get_ip(target)\n\ndef tcp_head( raw_data):\n (src_port, dest_port, sequence, acknowledgment, offset_reserved_flags) =struct.unpack(\n '! H H L L H', raw_data[:14])\n offset = (offset_reserved_flags >> 12) * 4\n flag_urg = (offset_reserved_flags & 32) >> 5\n flag_ack = (offset_reserved_flags & 16) >> 4\n flag_psh = (offset_reserved_flags & 8) >> 3\n flag_rst = (offset_reserved_flags & 4) >> 2\n flag_syn = (offset_reserved_flags & 2) >> 1\n flag_fin = offset_reserved_flags & 1\n data = raw_data[offset:]\n return src_port, dest_port, sequence, acknowledgment, flag_urg, flag_ack,\nflag_psh, flag_rst, flag_syn, flag_fin, data\n \nif ipv4[4] == 6:\n tcp = tcp_head(ipv4[7])\n print(TAB_1 + 'TCP Segment:')\n print(TAB_2 + 'Source Port: {}, Destination Port: {}'.format(tcp[0], tcp[1]))\n print(TAB_2 + 'Sequence: {}, Acknowledgment: {}'.format(tcp[2], tcp[3]))\n print(TAB_2 + 'Flags:')\n print(TAB_3 + 'URG: {}, ACK: {}, PSH:{}'.format(tcp[4], tcp[5], tcp[6]))\n print(TAB_3 + 'RST: {}, SYN: {}, FIN:{}'.format(tcp[7], tcp[8], tcp[9]))\n if len(tcp[10]) > 0:\n # HTTP\n if tcp[0] == 80 or tcp[1] == 80:\n print(TAB_2 + 'HTTP Data:')\n try:\n http = HTTP(tcp[10])\n http_info = str(http[10]).split('\\n')\n for line in http_info:\n print(DATA_TAB_3 + str(line))\n except:\n print(format_multi_line(DATA_TAB_3, tcp[10]))\n else:\n print(TAB_2 + 'TCP Data:')\n print(format_multi_line(DATA_TAB_3, tcp[10]))\nelif ipv4[4] == 1:\n icmp = icmp_head(ipv4[7])\n print('\\t -' + 'ICMP Packet:')\n print('\\t\\t -' + 'Type: {}, Code: {}, Checksum:{},'.format(icmp[0], icmp[1],icmp[2]))\n print('\\t\\t -' + 'ICMP Data:')\n print(format_multi_line('\\t\\t\\t', icmp[3]))\n\nelif ipv4[4] == 17:\n udp = udp_head(ipv4[7])\n print('\\t -' + 'UDP Segment:')\n print('\\t\\t -' + 'Source Port: {}, Destination Port: {}, Length:{}'.format(udp[0], udp[1], udp[2]))\n\n\n\n\n\n\n\n","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":3738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"143641322","text":"from webapi import json_pipeline\n\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nimport http.client\nimport json\nimport enum\nimport traceback\nfrom typing import *\n\n\nclass Routes(enum.Enum):\n COMPILE = '/compile'\n\n\nclass _LocalCompilerApiServer(BaseHTTPRequestHandler):\n def do_POST(self):\n content_length = int(self.headers['Content-Length']) # <--- Gets the size of data\n post_data = self.rfile.read(content_length) # <--- Gets the data itself\n print(\"POST request,\\nPath: %s\\nHeaders:\\n%s\\n\\nBody:\\n%s\\n\" % (\n str(self.path), str(self.headers), post_data.decode('utf-8')))\n if str(self.path) == Routes.COMPILE.value:\n try:\n response = json_pipeline.handle(post_data.decode('utf-8'))\n self.send_response(response.status)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n self.wfile.write(response.body.encode('utf-8'))\n except Exception as e:\n self.send_response(500)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n self.wfile.write(\"{}\\n\\nRequest was {}\".format(traceback.format_exc(), post_data.decode('utf-8')).encode('utf-8'))\n else:\n self.send_response(404)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n self.wfile.write(\"POST Route not found: {}\".format(self.path).encode('utf-8'))\n\n\nSAMPLE_CIRCUIT = \"\"\"\nOPENQASM 2.0;\ninclude \"qelib1.inc\";\n\nqreg q[2];\n\nh q[0];\ncx q[0],q[1];\nh q[0];\nt q[1];\ns q[0];\nx q[0];\n\"\"\"\n\nJSON_POST_PARAMETERS = {\n 'circuit_source': 'str', # alternative would be 'file'\n 'circuit': SAMPLE_CIRCUIT,\n 'apply_litinski_transform': True\n}\n\n\ndef probe(request_post_params: Optional[Dict] = None):\n if request_post_params is None:\n request_post_params = JSON_POST_PARAMETERS\n\n conn = http.client.HTTPConnection('localhost:9876')\n headers = {'Content-type': 'application/json'}\n\n conn.request('POST', '/compile', json.dumps(request_post_params), headers)\n\n response = conn.getresponse()\n print(response.read().decode())\n\n\nif __name__ == \"__main__\":\n server_address = ('', 9876)\n httpd = HTTPServer(server_address, _LocalCompilerApiServer)\n httpd.serve_forever()\n","sub_path":"webapi/local_compiler_api_server.py","file_name":"local_compiler_api_server.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"603074173","text":"\nfrom sklearn.preprocessing.data import RobustScaler as Op\nimport lale.helpers\nimport lale.operators\nimport lale.docstrings\nfrom numpy import nan, inf\n\nclass RobustScalerImpl():\n\n def __init__(self, with_centering=True, with_scaling=True, quantile_range=(25.0, 75.0), copy=True):\n self._hyperparams = {\n 'with_centering': with_centering,\n 'with_scaling': with_scaling,\n 'quantile_range': quantile_range,\n 'copy': copy}\n self._wrapped_model = Op(**self._hyperparams)\n\n def fit(self, X, y=None):\n if (y is not None):\n self._wrapped_model.fit(X, y)\n else:\n self._wrapped_model.fit(X)\n return self\n\n def transform(self, X):\n return self._wrapped_model.transform(X)\n_hyperparams_schema = {\n '$schema': 'http://json-schema.org/draft-04/schema#',\n 'description': 'inherited docstring for RobustScaler Scale features using statistics that are robust to outliers.',\n 'allOf': [{\n 'type': 'object',\n 'required': ['with_centering', 'with_scaling', 'quantile_range', 'copy'],\n 'relevantToOptimizer': ['with_centering', 'with_scaling', 'copy'],\n 'additionalProperties': False,\n 'properties': {\n 'with_centering': {\n 'type': 'boolean',\n 'default': True,\n 'description': 'If True, center the data before scaling'},\n 'with_scaling': {\n 'type': 'boolean',\n 'default': True,\n 'description': 'If True, scale the data to interquartile range.'},\n 'quantile_range': {\n 'XXX TODO XXX': 'tuple (q_min, q_max), 0.0 < q_min < q_max < 100.0',\n 'description': 'Default: (25.0, 75.0) = (1st quantile, 3rd quantile) = IQR Quantile range used to calculate ``scale_``',\n 'type': 'array',\n 'laleType': 'tuple',\n 'default': (25.0, 75.0)},\n 'copy': {\n 'XXX TODO XXX': 'boolean, optional, default is True',\n 'description': 'If False, try to avoid a copy and do inplace scaling instead',\n 'type': 'boolean',\n 'default': True},\n }}],\n}\n_input_fit_schema = {\n '$schema': 'http://json-schema.org/draft-04/schema#',\n 'description': 'Compute the median and quantiles to be used for scaling.',\n 'type': 'object',\n 'required': ['X'],\n 'properties': {\n 'X': {\n 'type': 'array',\n 'items': {\n 'type': 'array',\n 'items': {\n 'type': 'number'},\n },\n 'description': 'The data used to compute the median and quantiles used for later scaling along the features axis.'},\n },\n}\n_input_transform_schema = {\n '$schema': 'http://json-schema.org/draft-04/schema#',\n 'description': 'Center and scale the data.',\n 'type': 'object',\n 'required': ['X'],\n 'properties': {\n 'X': {\n 'type': 'array',\n 'items': {\n 'laleType': 'Any',\n 'XXX TODO XXX': 'item type'},\n 'XXX TODO XXX': '{array-like, sparse matrix}',\n 'description': 'The data used to scale along the specified axis.'},\n },\n}\n_output_transform_schema = {\n '$schema': 'http://json-schema.org/draft-04/schema#',\n 'description': 'Center and scale the data.',\n 'laleType': 'Any',\n}\n_combined_schemas = {\n '$schema': 'http://json-schema.org/draft-04/schema#',\n 'description': 'Combined schema for expected data and hyperparameters.',\n 'documentation_url': 'https://scikit-learn.org/0.20/modules/generated/sklearn.preprocessing.RobustScaler#sklearn-preprocessing-robustscaler',\n 'type': 'object',\n 'tags': {\n 'pre': [],\n 'op': ['transformer'],\n 'post': []},\n 'properties': {\n 'hyperparams': _hyperparams_schema,\n 'input_fit': _input_fit_schema,\n 'input_transform': _input_transform_schema,\n 'output_transform': _output_transform_schema},\n}\nlale.docstrings.set_docstrings(RobustScalerImpl, _combined_schemas)\nRobustScaler = lale.operators.make_operator(RobustScalerImpl, _combined_schemas)\n\n","sub_path":"lale/lib/autogen/robust_scaler.py","file_name":"robust_scaler.py","file_ext":"py","file_size_in_byte":4211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"539347237","text":"from kivy.app import App\nfrom kivy.garden.graph import Graph, MeshLinePlot\nfrom kivy.uix.behaviors import ButtonBehavior\nfrom kivy.uix.boxlayout import BoxLayout\nfrom numpy import sin\nfrom threading import Thread\nfrom time import sleep\nfrom kivy import config\nfrom kivy.utils import get_color_from_hex as rgb\nconfig.Config.set('input', 'mouse', 'mouse,disable_multitouch')\nimport matplotlib.pyplot as plt\nfrom kivy.garden.matplotlib.backend_kivyagg import FigureCanvas\n\n\nclass Graphmatplot(BoxLayout):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n fig1 = plt.figure()\n fig1.add_subplot(111)\n wid = FigureCanvas(fig1)\n self.add_widget(wid)\n\n\nclass MainScreen(BoxLayout):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n\nclass GraphCustom(ButtonBehavior, Graph):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.label_options = {'color': rgb('#000000'), 'bold': True}\n self.background_color = rgb('f8f8f2')\n self.tick_color = rgb('808080')\n self.border_color = rgb('808080')\n self.xlabel = 'X'\n self.ylabel = 'Y'\n self.x_ticks_minor = 5\n self.x_ticks_major = 25\n self.y_ticks_major = 1\n self.y_grid_label = True\n self.x_grid_label = True\n self.padding = 5\n self.x_grid = True\n self.y_grid = True\n self.xmin = -0\n self.xmax = 100\n self.ymin = -1\n self.ymax = 1\n self.i = 1\n self.stop = False\n self.plot = MeshLinePlot(color=[0, 0, 0.75, 1])\n self.plot.points = [(x, sin(x / 10.)) for x in range(0, 101)]\n self.add_plot(self.plot)\n Thread(target=self.redraw).start()\n\n def redraw(self):\n while not self.stop:\n self.i += 0.1\n self.plot.points = [(x, sin(x / 10. + self.i)) for x in range(0, 101)]\n sleep(0.1)\n return 0\n\n def start_graph(self):\n if self.stop:\n self.stop = False\n Thread(target=self.redraw).start()\n\n def stop_graph(self):\n self.stop = True\n\n def on_press(self):\n if self.last_touch.button == 'left':\n self.stop = True\n\n\nclass MainApp(App):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def build(self):\n self.root = MainScreen()\n return self.root\n\n def on_stop(self):\n self.root.children[1].stop = True\n\n\nif __name__ == \"__main__\":\n app = MainApp()\n app.run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"341433327","text":"import pynput\nimport time\nfrom tkinter import Tk\nimport json\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom pprint import pprint\n\nwith open('waifus.json') as f:\n data = json.load(f)\n\n\nwaifus_list = data['names']\nkeyboard = pynput.keyboard.Controller()\nmouse = pynput.mouse.Controller()\nleft_button = pynput.mouse.Button.left\nfirst_iteration_complete = False\nroll_time = 0\n\n\ndef triple_click():\n mouse.click(left_button)\n mouse.click(left_button)\n mouse.click(left_button)\n keyboard.press(pynput.keyboard.Key.page_down)\n time.sleep(0.25)\n keyboard.press(pynput.keyboard.Key.end)\n time.sleep(0.5)\n\n mouse.click(left_button)\n mouse.click(left_button)\n mouse.click(left_button)\n time.sleep(0.25)\n keyboard.press(pynput.keyboard.Key.end)\n time.sleep(0.75)\n\n mouse.click(left_button)\n mouse.click(left_button)\n mouse.click(left_button)\n time.sleep(0.25)\n keyboard.press(pynput.keyboard.Key.end)\n time.sleep(0.9)\n\n with keyboard.pressed(pynput.keyboard.Key.ctrl_l):\n keyboard.press('c')\n keyboard.release('c')\n\n try:\n waifu = Tk().clipboard_get()\n except:\n print('error')\n waifu = \"fallback\"\n\n return waifu\n\n\ndef checkIfAvailable(waifu_name):\n if waifu_name in waifus_list:\n return True\n return False\n\n\ndef afk():\n keyboard.press(pynput.keyboard.Key.end)\n\n waifu_check = triple_click()\n\n if (checkIfAvailable(waifu_check) == True):\n mouse.move(-8, 323)\n mouse.click(left_button)\n mouse.move(8, -323)\n\n\ndef waifu_command():\n counter1 = 0\n\n while counter1 < 10:\n keyboard.press(pynput.keyboard.Key.end)\n\n keyboard.type(\"$w\")\n keyboard.press(pynput.keyboard.Key.enter)\n keyboard.release(pynput.keyboard.Key.enter)\n time.sleep(1)\n\n keyboard.press(pynput.keyboard.Key.end)\n keyboard.press(pynput.keyboard.Key.end)\n\n time.sleep(1)\n waifu_check = triple_click()\n\n if (checkIfAvailable(waifu_check) == True):\n mouse.move(-8, 323)\n mouse.click(left_button)\n mouse.move(8, -323)\n print(waifu_check)\n\n counter1 = counter1 + 1\n mouse.move(0, 405)\n mouse.click(left_button)\n mouse.move(0, -405)\n\n\ndef open_discord(): \n initial_position = mouse.position\n mouse.move(-initial_position[0], -initial_position[1])\n mouse.move(424, 695)\n mouse.click(left_button)\n time.sleep(0.25)\n\n mouse.move(-53, -58)\n mouse.click(left_button)\n time.sleep(1)\n mouse.move(0, -405)\n\n\nprint('script started at time %s' % (str(datetime.now().time())))\n\n\nstarting_mode = input(\"Immediate mode (1) or interval mode(2)?\")\n\nif (starting_mode == \"1\"):\n open_discord()\n\n\nwhile True:\n current_minute = datetime.now().time().minute\n\n if ((first_iteration_complete == True or starting_mode == \"1\") and roll_time == 0):\n if (current_minute == 52):\n roll_time = 1\n afk()\n\n if (current_minute == 52):\n if (first_iteration_complete == False and starting_mode != \"1\"):\n open_discord\n\n waifu_command()\n while (current_minute == 52):\n afk()\n current_second = datetime.now().time().second\n first_iteration_complete = True\n roll_time = 0\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"260805234","text":"from tables.base_table_class import Base_Table\n\nclass HOUSEHOLD_LANGUAGE_LIMITED_Table(Base_Table):\n\t\"The definition of the Household Language Limited Table in the database\"\n\n\ttable_name = \"HOUSEHOLD_LANGUAGE_LIMITED\"\n\n\tdef __init__(self) :\n\t\tself.table_name = HOUSEHOLD_LANGUAGE_LIMITED_Table.table_name\n\t\tself.columns = Base_Table.columns + [\"Total Households\",\n\t\t\t\t\t\"English only\",\n\t\t\t\t\t\"Spanish\",\n\t\t \t\t\t\"Indo-European languages\",\n\t\t\t\t\t\"Asian and Pacific Island languages\",\n\t\t\t\t\t\"Other Languages\",\n\t\t\t\t\t\"Spanish Category\",\n\t\t\t\t\t\"Spanish: Limited English speaking household\",\n\t\t\t\t\t\"Spanish: Not a limited English speaking household\",\n\t\t\t\t\t\"Indo-European languages Category\",\n\t\t\t\t\t\"Indo-European: Limited English speaking household\",\n\t\t\t\t\t\"Indo-European: Not a limited English speaking household\",\n\t\t\t\t\t\"Asian and Pacific Island languages Category\",\n\t\t\t\t\t\"Asian and Pacific: Limited English speaking household\",\n\t\t\t\t\t\"Asian and Pacific: Not a limited English speaking household\",\n\t\t\t\t\t\"Other languages Category\",\n\t\t\t\t\t\"Other: Limited English speaking household\",\n\t\t\t\t\t\"Other: Not a limited English speaking household\",\n\t\t\t\t\t\"Total Households English vs Not Limited English\",\n\t\t\t\t\t\"Limited english speaking\",\n\t\t\t\t\t\"Not limited English speaking\"]\n\n\t\tself.table_extra_meta_data = Base_Table.table_extra_meta_data\n\t\tself.initalize()\n\n\tdef getInsertQueryForCSV(self, csvFile, fromYear, toYear) :\n\t\tskipCount = 0\n\t\tinsertDataQuery = \"\"\"REPLACE INTO `{0}` VALUES \"\"\".format(self.table_name)\n\t\tfor line in csvFile:\n\t\t\trow = line.split(\",\")\n\t\t\tif (skipCount < Base_Table.num_of_rows_to_leave) :\n\t\t\t\tskipCount += 1\n\t\t\t\tcontinue\n\n\t\t\tdefaultQuery = self.getIDAndYearQueryForRow(row, fromYear, toYear)\n\t\t\tdataQuery = \"%d, %d, %d, %d, %d, %d, %d, %d, %d, %d,\\\n\t %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d\" %(int(row[3]), #B\n\t\t\t\t\t\t int(row[4]), #C\n\t\t\t\t\t\t int(row[5]), #D\n\t\t\t\t\t\t int(row[8]), #E\n\t\t\t\t\t\t int(row[11]), #F\n\t\t\t\t\t\t int(row[14]), #G\n\t\t\t\t\t\t int(row[5]), #H\n\t\t\t\t\t\t int(row[6]), #I\n\t\t\t\t\t\t int(row[7]), #J\n\t\t\t\t\t\t int(row[8]), #K\n\t\t\t\t\t\t int(row[9]), #L\n\t\t\t\t\t\t int(row[10]), #M\n\t\t\t\t\t\t int(row[11]), #N\n\t\t\t\t\t\t int(row[12]), #O\n\t\t\t\t\t\t int(row[13]), #P\n\t\t\t\t\t\t int(row[14]), #Q\n\t\t\t\t\t\t int(row[15]), #R\n\t\t\t\t\t\t int(row[16]), #S\n\t\t\t\t\t\t int(row[3]), #T\n\t\t\t\t\t\t int(row[6])+int(row[9])+int(row[12])+int(row[15]), #U\n\t\t\t\t\t\t int(row[7])+int(row[10])+int(row[13])+int(row[16]))\n\t\t\tinsertDataQuery += \"(\" + defaultQuery + dataQuery + \"),\"\n\n\t\tinsertDataQuery = insertDataQuery[:-1]\n\t\tinsertDataQuery += \";\"\n\t\treturn insertDataQuery\n","sub_path":"wca_server/tables/demographics/household_language_limited_table.py","file_name":"household_language_limited_table.py","file_ext":"py","file_size_in_byte":2526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"152853068","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/firstblood/unifiedIO/shortcuts.py\n# Compiled at: 2018-10-28 13:45:36\n# Size of source mod 2**32: 1436 bytes\nimport functools as fn\nfrom math import inf\nfrom .unified import Unified\n\ndef _shortcut(funcname, mode, ret):\n\n def inner(path, *args, **kwargs):\n with Unified(open(path, mode)) as (f):\n res = (getattr(f, funcname))(*args, **kwargs)\n if ret:\n return res\n\n inner.__name__ = funcname\n inner.__qualname__ = funcname\n return inner\n\n\nread = _shortcut('read', 'r', True)\nreadline = _shortcut('readline', 'r', True)\nreadlines = _shortcut('readlines', 'r', True)\nreaduntil = _shortcut('readuntil', 'r', True)\nwrite = _shortcut('write', 'w', False)\nwriteline = _shortcut('writeline', 'w', False)\nwritelines = _shortcut('writelines', 'w', False)\nappend = _shortcut('write', 'a', False)\nappendline = _shortcut('writeline', 'a', False)\nappendlines = _shortcut('writelines', 'a', False)\nreadbin = _shortcut('read', 'rb', True)\nreadbinline = _shortcut('readline', 'rb', True)\nreadbinlines = _shortcut('readlines', 'rb', True)\nreadbinuntil = _shortcut('readuntil', 'rb', True)\nwritebin = _shortcut('write', 'wb', False)\nwritebinline = _shortcut('writeline', 'wb', False)\nwritebinlines = _shortcut('writelines', 'wb', False)\nappendbin = _shortcut('write', 'ab', False)\nappendbinline = _shortcut('writeline', 'ab', False)\nappendbinlines = _shortcut('writelines', 'ab', False)","sub_path":"pycfiles/firstblood-0.0.1-py3.7/shortcuts.cpython-37.py","file_name":"shortcuts.cpython-37.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"100945078","text":"import sys\n\nDNA_NUCLEOBASES = 'ATCG'\n\nNUC2NUM={'A':0,'C':1,'G':2,'T':3}\nNUM2NUC={0:'A',1:'C',2:'G',3:'T'}\n\n\ndef stringify(num,k):\n if k== 1:\n return NUM2NUC[num]\n remain = num\n chars = []\n for i in range(k):\n chars.append(NUM2NUC[remain%4])\n remain = (remain-remain%4)/4\n return ''.join(chars[-1::-1])\n\n\ndef numerify(s,k):\n if len(s) != k:\n print(\"k not match the length of s when numerify\")\n num = 0\n for i in range(k):\n num += NUC2NUM[s[-i-1]]*(4**i)\n return num\n\ndef computeFreq(subtext,k):\n freqArray = [0 for i in range(4**k)]\n for i in range(len(subtext)-k+1):\n n = numerify(subtext[i:i+k],k)\n freqArray[n] = freqArray[n] + 1\n return freqArray\n\ndef clumpFind2(text,k,L,t):\n result = []\n clumps = [0 for i in range(4**k)]\n freqArray = computeFreq(text[0:L],k)\n for i in range(4**k):\n if freqArray[i] >= t:\n clumps[i] = 1\n for i in range(1,len(text)-L+1):\n firstPattern = text[i-1:i-1+k]\n index = numerify(firstPattern,k)\n freqArray[index] = freqArray[index] - 1\n lastPattern = text[i+L-k:i+L]\n index = numerify(lastPattern,k)\n freqArray[index] = freqArray[index] + 1\n if freqArray[index] >=t:\n clumps[index] = 1\n\n for i in range(4**k):\n if clumps[i] == 1:\n pattern = stringify(i,k)\n result.append(pattern)\n return result\n\n\nif __name__ == '__main__':\n f = open(sys.argv[1],'r')\n text = f.readline().rstrip()\n #line2 = f.readline().rstrip().split(' ')\n #k = int(line2[0])\n #L = int(line2[1])\n #t = int(line2[2])\n print(' '.join(clumpFind2(text,9,500,3)))\n\n","sub_path":"problem_set/clump_find2.py","file_name":"clump_find2.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"388535507","text":"import Skill\nfrom PyQt4 import QtCore, QtGui\n\nclass Player:\n\n\tdef __init__(self, fast_casting_level, ping, skillbar):\n\t\tself.fast_casting_level = fast_casting_level\n\t\tself.ping = ping\n\t\tself.skillbar = skillbar #dictionary\n\t\tself.attempted_casts = 0\n\t\tself.successful_casts = 0\n\t\tself.rupts = 0\n\n\tdef cast(self,key,fast_cast_percentage):\n\t\tskill = self.skillbar.get(key)\n\t\tif not skill.recharging:\n\t\t\tself.attempted_casts += 1\n\t\t\tif(fast_casting_level):\n\t\t\t\t#this means it's our player, as enemy does not have fast casting\n\t\t\t\tcast_time = skill.computeCastingTime(fast_cast_percentage)\n\t\t\t\treturn [\"enemy\",cast_time + self.ping]\n\t\t\telse:\n\t\t\t\tcast_time = skill.computeCastingTime()\n\t\t\t\treturn [\"player\", cast_time + self.ping]\n\t\telse:\n\t\t\treturn [False]\n","sub_path":"Player.py","file_name":"Player.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"474279733","text":"#Latent Semantic Analysis\n\nfrom gensim import corpora, models\n\ndocuments = [\"Human machine interface for lab abc computer applications\",\n \"A survey of user opinion of computer system response time\",\n \"The EPS user interface management system\",\n \"System and human system engineering testing of EPS\",\n \"Relation of user perceived response time to error measurement\",\n \"The generation of random binary unordered trees\",\n \"The intersection graph of paths in trees\",\n \"Graph minors IV Widths of trees and well quasi ordering\",\n \"Graph minors A survey\"]\n\n# remove common words and tokenize\nstoplist = set('for a of the and to in'.split())\ntexts = [[word for word in document.lower().split() if word not in stoplist]\n for document in documents]\n#----------------------------------------------------------------------------#\n#print(texts)\n#[['human', 'machine', 'interface', 'lab', 'abc', 'computer', 'applications'],\n# ['survey', 'user', 'opinion', 'computer', 'system', 'response', 'time'],\n# ['eps', 'user', 'interface', 'management', 'system'],\n# ['system', 'human', 'system', 'engineering', 'testing', 'eps'],\n# ['relation', 'user', 'perceived', 'response', 'time', 'error', 'measurement'],\n# ['generation', 'random', 'binary', 'unordered', 'trees'],\n# ['intersection', 'graph', 'paths', 'trees'],\n# ['graph', 'minors', 'iv', 'widths', 'trees', 'well', 'quasi', 'ordering'],\n# ['graph', 'minors', 'survey']]\n#----------------------------------------------------------------------------#\n\n# remove words that appear only once\nall_tokens = sum(texts, [])\n#----------------------------------------------------------------------------#\n# print(all_tokens)\n# ['human', 'machine', 'interface', 'lab', 'abc', 'computer', 'applications', \n# 'survey', 'user', 'opinion', 'computer', 'system', 'response', 'time', \n# 'eps', 'user', 'interface', 'management', 'system', \n# 'system', 'human', 'system', 'engineering', 'testing', 'eps', \n# 'relation', 'user', 'perceived', 'response', 'time', 'error', 'measurement', \n# 'generation', 'random', 'binary', 'unordered', 'trees', \n# 'intersection', 'graph', 'paths', 'trees', \n# 'graph', 'minors', 'iv', 'widths', 'trees', 'well', 'quasi', 'ordering',\n# 'graph', 'minors', 'survey']\n#----------------------------------------------------------------------------#\ntokens_once = set(word for word in set(all_tokens) if all_tokens.count(word) == 1)\n#----------------------------------------------------------------------------#\n# print(tokens_once)\n# {'paths', 'testing', 'relation', 'well', 'binary', 'quasi', 'unordered', 'lab', \n# 'random', 'applications', 'management', 'intersection', 'generation', 'ordering',\n# 'abc', 'error', 'engineering', 'measurement', 'machine', 'opinion', 'perceived',\n# 'iv', 'widths'}\n#----------------------------------------------------------------------------#\ntexts = [[word for word in text if word not in tokens_once] for text in texts]\n#----------------------------------------------------------------------------#\n# print(texts)\n# [['human', 'interface', 'computer'], \n# ['survey', 'user', 'computer', 'system', 'response', 'time'], \n# ['eps', 'user', 'interface', 'system'], \n# ['system', 'human', 'system', 'eps'], \n# ['user', 'response', 'time'], \n# ['trees'],\n# ['graph', 'trees'], \n# ['graph', 'minors', 'trees'], \n# ['graph', 'minors', 'survey']]\n#----------------------------------------------------------------------------#\n\n# Create Dictionary.\ndictionary = corpora.Dictionary(texts)\n# dictionary.save('/tmp/deerwester.dict') # store the dictionary, for future reference\n#----------------------------------------------------------------------------#\n# print(dictionary.token2id)\n# {'time': 3, 'interface': 0, 'graph': 10, 'trees': 9, 'eps': 8, \n# 'survey': 7, 'minors': 11, 'computer': 2, 'response': 5, 'human': 1, \n# 'system': 6, 'user': 4}\n#----------------------------------------------------------------------------#\n \n# Creates the Bag of Word corpus.\n#Convert `document` (a list of words) into the bag-of-words format \n#= list of `(token_id, token_count)` 2-tuples\ncorpus = [dictionary.doc2bow(text) for text in texts]\n#corpora.MmCorpus.serialize('/tmp/deerwester.mm', corpus) # store to disk, for later use\n#corpus = corpora.MmCorpus('/tmp/corpus.mm')# to to load a corpus iterator from a Matrix Market file\n#print(list(corpus)) \n#----------------------------------------------------------------------------#\n# print(corpus)\n# [[(0, 1), (1, 1), (2, 1)], \n# [(2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1)],\n# [(1, 1), (5, 1), (6, 1), (8, 1)],\n# [(0, 1), (5, 2), (8, 1)],\n# [(3, 1), (6, 1), (7, 1)],\n# [(9, 1)], [(9, 1), (10, 1)], \n# [(9, 1), (10, 1), (11, 1)], \n# [(4, 1), (10, 1), (11, 1)]]\n#----------------------------------------------------------------------------#\n\n# Trains the LDA models.\nlsa_model = models.lsimodel.LsiModel(corpus=corpus, id2word=dictionary, num_topics=3)\n\n# Prints the topics.\nprint(\"------------------------Topics--------------------------------------\")\n#print(lda.show_topics()) #will do same\n\nfor model in lsa_model.print_topics():\n print(model)\nprint(\"--------------------------------------------------------------------\")\n\n#-----------------------------------------------------------------------------#\nquery = 'I am human not system, evolve with time'\nquery = query.split()\nquery = dictionary.doc2bow(query)#corpus\nprint(lsa_model[query])\n\n","sub_path":"pymining/jay/lsa.py","file_name":"lsa.py","file_ext":"py","file_size_in_byte":5464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"609795681","text":"from __future__ import absolute_import\n\nfrom unet_collection.layer_utils import *\n\nfrom tensorflow.keras.layers import Input, Conv3D\nfrom tensorflow.keras.layers import BatchNormalization, Activation, concatenate, multiply\nfrom tensorflow.keras.layers import ReLU, LeakyReLU, PReLU, ELU\nfrom tensorflow.keras.models import Model\n\ndef UNET_left3D(X, channel, kernel_size=3, stack_num=2, activation='ReLU', \n pool=True, batch_norm=False, name='left0'):\n '''\n The encoder block of U-net.\n \n UNET_left(X, channel, kernel_size=3, stack_num=2, activation='ReLU', \n pool=True, batch_norm=False, name='left0')\n \n Input\n ----------\n X: input tensor.\n channel: number of convolution filters.\n kernel_size: size of 2-d convolution kernels.\n stack_num: number of convolutional layers.\n activation: one of the `tensorflow.keras.layers` interface, e.g., 'ReLU'.\n pool: True or 'max' for MaxPooling2D.\n 'ave' for AveragePooling2D.\n False for strided conv + batch norm + activation.\n batch_norm: True for batch normalization, False otherwise.\n name: prefix of the created keras layers.\n \n Output\n ----------\n X: output tensor.\n \n '''\n pool_size = 2\n \n X = encode_layer3D(X, channel, pool_size, pool, activation=activation, \n batch_norm=batch_norm, name='{}_encode'.format(name))\n\n X = CONV_stack3D(X, channel, kernel_size, stack_num=stack_num, activation=activation, \n batch_norm=batch_norm, name='{}_conv'.format(name))\n \n return X\n\n\ndef UNET_right3D(X, X_list, channel, kernel_size=3, \n stack_num=2, activation='ReLU',\n unpool=True, batch_norm=False, concat=True, name='right0'):\n \n '''\n The decoder block of U-net.\n \n Input\n ----------\n X: input tensor.\n X_list: a list of other tensors that connected to the input tensor.\n channel: number of convolution filters.\n kernel_size: size of 2-d convolution kernels.\n stack_num: number of convolutional layers.\n activation: one of the `tensorflow.keras.layers` interface, e.g., 'ReLU'.\n unpool: True or 'bilinear' for Upsampling2D with bilinear interpolation.\n 'nearest' for Upsampling2D with nearest interpolation.\n False for Conv2DTranspose + batch norm + activation.\n batch_norm: True for batch normalization, False otherwise.\n concat: True for concatenating the corresponded X_list elements.\n name: prefix of the created keras layers.\n \n Output\n ----------\n X: output tensor.\n \n '''\n \n pool_size = 2\n \n X = decode_layer3D(X, channel, pool_size, unpool, \n activation=activation, batch_norm=batch_norm, name='{}_decode'.format(name))\n \n # linear convolutional layers before concatenation\n X = CONV_stack3D(X, channel, kernel_size, stack_num=1, activation=activation, \n batch_norm=batch_norm, name='{}_conv_before_concat'.format(name))\n if concat:\n # <--- *stacked convolutional can be applied here\n X = concatenate([X,]+X_list, axis=4, name=name+'_concat')\n \n # Stacked convolutions after concatenation \n X = CONV_stack3D(X, channel, kernel_size, stack_num=stack_num, activation=activation, \n batch_norm=batch_norm, name=name+'_conv_after_concat')\n \n return X\n\ndef unet_3d(input_size, filter_num, n_labels,\n stack_num_down=2, stack_num_up=2,\n activation='ReLU', output_activation='Softmax', \n batch_norm=False, pool=True, unpool=True, name='unet'):\n '''\n U-net\n \n unet_3d(input_size, filter_num, n_labels,\n stack_num_down=2, stack_num_up=2,\n activation='ReLU', output_activation='Softmax', \n batch_norm=False, pool=True, unpool=True, name='unet')\n \n ----------\n Ronneberger, O., Fischer, P. and Brox, T., 2015, October. U-net: Convolutional networks for biomedical image segmentation. \n In International Conference on Medical image computing and computer-assisted intervention (pp. 234-241). Springer, Cham.\n \n Input\n ----------\n input_size: a tuple that defines the shape of input, e.g., (None, None, 3)\n filter_num: an iterable that defines number of filters for each \\\n down- and upsampling level. E.g., [64, 128, 256, 512]\n the depth is expected as `len(filter_num)`\n n_labels: number of output labels.\n stack_num_down: number of convolutional layers per downsampling level/block. \n stack_num_up: number of convolutional layers (after concatenation) per upsampling level/block.\n activation: one of the `tensorflow.keras.layers` or `keras_unet_collection.activations` interfaces, e.g., ReLU\n output_activation: one of the `tensorflow.keras.layers` or `keras_unet_collection.activations` interfaces or 'Sigmoid'.\n Default option is Softmax\n if None is received, then linear activation is applied.\n batch_norm: True for batch normalization.\n pool: True for maxpooling, False for strided convolutional layers.\n unpool: True for unpooling (i.e., reflective padding), False for transpose convolutional layers. \n name: prefix of the created keras layers.\n \n Output\n ----------\n X: a keras model \n \n '''\n activation_func = eval(activation)\n\n IN = Input(input_size)\n X = IN\n X_skip = []\n \n # downsampling blocks\n X = CONV_stack3D(X, filter_num[0], stack_num=stack_num_down,\n activation=activation,\n batch_norm=batch_norm,\n name='{}_down0'.format(name))\n X_skip.append(X)\n \n for i, f in enumerate(filter_num[1:]):\n X = UNET_left3D(X, f, stack_num=stack_num_down,\n activation=activation, pool=pool, \n batch_norm=batch_norm,\n name='{}_down{}'.format(name, i+1)) \n X_skip.append(X)\n \n # upsampling blocks\n X_skip = X_skip[:-1][::-1]\n for i, f in enumerate(filter_num[:-1][::-1]):\n X = UNET_right3D(X, [X_skip[i],], f, stack_num=stack_num_up,\n activation=activation, \n unpool=unpool, batch_norm=batch_norm,\n name='{}_up{}'.format(name, i+1))\n\n OUT = CONV_output3D(X, n_labels, kernel_size=1,\n activation=output_activation,\n name='{}_output'.format(name))\n \n model = Model(inputs=[IN], outputs=[OUT], name='{}_model'.format(name))\n \n return model\n","sub_path":"bin/assets/scripts/unet3Plus/unet_collection/unet_3d.py","file_name":"unet_3d.py","file_ext":"py","file_size_in_byte":6823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"422771203","text":"#encapsulation 封装\n\nclass A:\n name = \"stanlong\"\n __age = \"27\" #静态字段\n\n def fun(self):\n print(self.__age)\n print(A.__age)\n print(\"fun()\")\n\na = A()\n#print(a.__age) #实例化对象不能访问静态字段\n#'A' object has no attribute '__age'\n#print(A.__age) #类名不能访问私有静态字段\n#有种方式可以访问,但是不建议用 print(A._A.__age())\n\na.fun() #类的内部可以访问\n\n#对于私有化静态字段,只能在本类中访问,类的外部,派生类均不可访问。\n","sub_path":"class_day/encapsulation.py","file_name":"encapsulation.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"587838486","text":"import torch\nimport os\n\nfrom FLAlgorithms.cluster.clusteravg import ClusterFedAvg\nfrom FLAlgorithms.servers.serverbase import Server\nimport numpy as np\n\nfrom logging_results import eps_logging\n\nclass FedAvg(Server):\n def __init__(self, device, args, train_loader, test_loader, model, train_data_samples, cluster_total_train_data_sample, server_total_train_data_sample, running_time, hyper_param):\n super().__init__(device, args, train_loader, test_loader, model, train_data_samples, cluster_total_train_data_sample, server_total_train_data_sample, running_time, hyper_param)\n\n for i in range(self.num_clusters):\n train_data = train_loader[i]\n test_data = test_loader[i]\n cluster = ClusterFedAvg(device, args, train_data, test_data, model, train_data_samples[i], cluster_total_train_data_sample[i], running_time, i, hyper_param)\n self.clusters.append(cluster)\n\n \n def train(self):\n\n for server_iter in range(self.server_iters):\n print(\"\")\n print(\"---------------------------server iter: \",server_iter, \" ---------------------------\")\n\n epsilons_list = []\n losses = []\n\n # do update for all clusters not only selected clusters\n for cluster in self.clusters:\n if self.if_DP:\n train_loss, epsilons = cluster.train(server_iter)\n epsilons_list.append(epsilons)\n losses.append(train_loss)\n else:\n train_loss = cluster.train(server_iter)\n losses.append(train_loss)\n\n # choose several clusters to send back upated model to server\n self.selected_cluster = self.select_cluster(server_iter, self.num_clusters)\n\n # Evaluate average model on server for each interation\n print(\"\")\n print(\"Evaluate server average model\")\n self.evaluate(server_iter, losses)\n\n self.aggregate_parameters()\n\n self.send_parameters()\n\n if self.if_DP:\n eps = sum(epsilons_list) / len(epsilons_list)\n eps_logging(server_iter, eps, self.running_time)\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"FLAlgorithms/servers/serveravg.py","file_name":"serveravg.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"38268980","text":"from __future__ import absolute_import\n#import matplotlib.pyplot as plt\nfrom datetime import datetime\nimport tensorflow as tf\nimport unet_input\nimport numpy as np\nimport unet_model\nimport settings_unet\nimport time\nimport os\nfrom sklearn.metrics import mean_squared_error\nimport cv2\n#os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\nfrom scipy import misc\n\nparser = settings_unet.parser\nPARAMS = parser.parse_args()\n\nVAL_DIR = PARAMS.dir_validate\n# VAL_Raw_DIR = PARAMS.val_Raw_dir\n# VAL_Seg_DIR = PARAMS.val_Seg_dir\n \nVAL_BATCH_SIZE = 1 # process a single image (NOT patch) one time\nVAL_INTERVAL_SECS = 180\nRaw_NAME_LIST, Seg_NAME_LIST = unet_input.GetFileNameList(VAL_DIR)\n#TOTAL_VALID_IMAGES = len(os.listdir(VAL_DIR)) // 2\nINPUT_SIZE = PARAMS.img_input\nOUTPUT_SIZE = PARAMS.img_output\nrawNameList, segNameList = unet_input.GetFileNameList(VAL_DIR)\nTOTAL_VALID_IMAGES = len(rawNameList) \n\ndef EvaluateOnceAndSaveImages(saver, summ_writer, summ_op, seg_image, raw_image, seg_model):\n with tf.Session(config = tf.ConfigProto(log_device_placement = PARAMS.log_device_placement)) as sess:\n #ckpt = tf.train.get_checkpoint_state(train.LogDir)\n ckpt = tf.train.get_checkpoint_state(PARAMS.log_dir)\n if ckpt and ckpt.model_checkpoint_path:\n saver.restore(sess, ckpt.model_checkpoint_path)\n global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]\n else:\n print('no checkpoint file found!')\n return\n \n # start the queue runners\n coord = tf.train.Coordinator()\n try:\n threads = []\n for qr in tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS):\n threads.extend(qr.create_threads(sess, coord = coord, daemon = True, start = True))\n \n # calculate the number of iterations for validation set. Because the batch size in this case\n # is 1, we just need to excute TOTAL_VALID_EXAMPLES times loop.\n step = 0\n model_loss = 0\n while not coord.should_stop() and step < TOTAL_VALID_IMAGES:\n print('processing image %d/%d...' % (step + 1, TOTAL_VALID_IMAGES))\n \n image_seg, image_raw, model_seg = sess.run([seg_image, raw_image, seg_model])\n \n image_name = Raw_NAME_LIST[step].split('/')[-1]\n image_path = os.path.join(PARAMS.image_save_dir, image_name)\n# plt.imsave(image_path, model_seg[0, :, :, 0], cmap = \"gray\") # Note batch_size = 1\n# cv2.imwrite(image_path, model_seg[0, :, :, 0]) \n misc.imsave(image_path, model_seg[0, :, :, 0])\n #pred_seg = tf.reshape(model_seg[0,:,:,0], [184, 184])\n #np.reshape(model_seg[0,:,:,0], (184,184,1))\n #print(\"*************************\",model_seg[0,:,:,0].shape)\n #print('******************', image_seg.shape)\n# tem_loss = unet_model.loss(model_seg[0,:,:,0], image_seg)\n model_seg = np.reshape(model_seg, (184,184))\n image_seg = np.reshape(image_seg, (184,184))\n # tmp_loss = np.square(np.subtract(model_seg, image_seg)).mean() #MSE\n model_seg_new = np.float32(model_seg > 0.)\t#转为1-0\n image_seg_new = np.float32(image_seg > 0.)\n intersection = np.sum(model_seg_new * image_seg_new)\n summ = np.sum(model_seg_new) +np.sum(image_seg_new) \n tmp_loss = (2*intersection + 10) /(summ + 10)\n with open(\"Records/validate_records.txt\", \"a\") as file:\n #format_str = \"%d\\t%.6f\\t%.6f\\t%.6f\\t%.6f\\n\"\n# file.write(str(format_str) % (\n# step + 1, loss_value, min_loss, dice_value, max_dice))\n file.write(str(\"%d\\t%.4f\\n\") %(step+1, tmp_loss))\n\n# tmp_loss = ((model_seg - image_seg) ** 2).mean() # mean_squared_error(model_seg, image_seg)\n print(\" ---- %s:\\n\\tmodel_loss = %.4f\" % (image_name, tmp_loss))\n # print(\" \\tgibbs_psnr = %.4f\\tgibbs_ssim = %.4f\" % (before_psnr, before_ssim))\n model_loss += tmp_loss\n \n step += 1\n \n model_loss = model_loss / TOTAL_VALID_IMAGES\n \n print(\"%s: -- Validation Set:\" % datetime.now())\n print(\"\\tmean_model_loss = %.4f\\t\" % (model_loss))\n \n # writer relative summary into val_log_dir\n summary = tf.Summary()\n summary.ParseFromString(sess.run(summ_op))\n summary.value.add(tag='Average model MSE over validation set', simple_value = model_loss)\n \n summ_writer.add_summary(summary, global_step)\n except Exception as e:\n coord.request_stop(e)\n finally:\n coord.request_stop()\n coord.join(threads, stop_grace_period_secs = 10)\n \n\ndef EvaluateOnce(saver, summ_writer, summ_op, clear_image, gibbs_image, clear_model):\n with tf.Session(config = tf.ConfigProto(log_device_placement = PARAMS.log_device_placement)) as sess: \n # Synchronous assessment: it should use train logs train.LogDir here!\n ckpt = tf.train.get_checkpoint_state(PARAMS.model_dir)\n if ckpt and ckpt.model_checkpoint_path:\n saver.restore(sess, ckpt.model_checkpoint_path)\n global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]\n else:\n print('no checkpoint file found!')\n return\n \n # start the queue runners\n coord = tf.train.Coordinator()\n try:\n threads = []\n for qr in tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS):\n threads.extend(qr.create_threads(sess, coord = coord, daemon = True, start = True))\n \n # calculate the number of iterations for validation set\n model_psnr = 0.0\n model_ssim = 0.0\n gibbs_psnr = 0.0\n gibbs_ssim = 0.0\n step = 0\n while not coord.should_stop() and step < TOTAL_VALID_IMAGES:\n print('processing image %d/%d...' % (step + 1, TOTAL_VALID_IMAGES))\n \n image_CLEAR, image_GIBBS, model_CLEAR = sess.run([clear_image, gibbs_image, clear_model])\n tmp_psnr, tmp_ssim = cal_psnr_and_ssim(image_CLEAR, model_CLEAR)\n before_psnr, before_ssim = cal_psnr_and_ssim(image_CLEAR, image_GIBBS)\n model_psnr += tmp_psnr\n model_ssim += tmp_ssim\n gibbs_psnr += before_psnr\n gibbs_ssim += before_ssim\n \n step += 1\n \n # calculate the average PSNR over the whole validation set\n model_psnr = model_psnr / TOTAL_VALID_IMAGES\n model_ssim = model_ssim / TOTAL_VALID_IMAGES\n gibbs_psnr = gibbs_psnr / TOTAL_VALID_IMAGES\n gibbs_ssim = gibbs_ssim / TOTAL_VALID_IMAGES\n print(\"%s: -- Validation Set:\" % datetime.now())\n print(\"\\tmodel_psnr = %.4fdB\\tmodel_ssim = %.4fdB\" % (model_psnr, model_ssim))\n print(\"\\tgibbs_psnr = %.4fdB\\tgibbs_ssim = %.4fdB\" % (gibbs_psnr, gibbs_ssim))\n \n # writer relative summary into val_log_dir\n summary = tf.Summary()\n summary.ParseFromString(sess.run(summ_op))\n summary.value.add(tag='Average model PSNR over validation set', simple_value = model_psnr)\n summary.value.add(tag='Average model PSNR over validation set', simple_value = model_ssim)\n summary.value.add(tag='Average gibbs PSNR over validation set', simple_value = gibbs_psnr)\n summary.value.add(tag='Average gibbs PSNR over validation set', simple_value = gibbs_ssim)\n summ_writer.add_summary(summary, global_step)\n except Exception as e:\n coord.request_stop(e)\n finally:\n coord.request_stop()\n coord.join(threads, stop_grace_period_secs = 10)\n\n\ndef Evaluate():\n with tf.Graph().as_default() as g:\n# rawNameList, segNameList = unet_input.GetFileNameList(VAL_DIR)\n# TOTAL_VALID_IMAGES = len(rawNameList)\n raw_image, seg_image = unet_input.GetBatchFromFile_Valid(rawNameList, segNameList, VAL_BATCH_SIZE)\n \n # Build computational graph\n seg_model = unet_model.UNet(raw_image)\n #raw_image = tf.image.resize_bicubic(raw_image, [OUTPUT_SIZE, OUTPUT_SIZE])\n saver = tf.train.Saver()\n \n summ_op = tf.summary.merge_all()\n summ_writer = tf.summary.FileWriter(PARAMS.val_log_dir, g)\n while True:\n if PARAMS.eval_once:\n EvaluateOnceAndSaveImages(saver, summ_writer, summ_op, seg_image, raw_image, seg_model)\n break\n else:\n EvaluateOnce(saver, summ_writer, summ_op, seg_image, raw_image, seg_model)\n time.sleep(VAL_INTERVAL_SECS)\n \n\ndef main(argv = None): # pylint: disable=unused-argument\n if tf.gfile.Exists(PARAMS.val_log_dir):\n tf.gfile.DeleteRecursively(PARAMS.val_log_dir)\n tf.gfile.MakeDirs(PARAMS.val_log_dir)\n Evaluate()\n\n\nif __name__ == '__main__':\n tf.app.run() \n","sub_path":"unet_seg.py","file_name":"unet_seg.py","file_ext":"py","file_size_in_byte":9348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"106151380","text":"import os\nimport json\nimport shutil\nimport copy\nfrom typing import Dict, Any, List\n\nSCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))\n\nRESOURCES_DIR = os.path.abspath(os.path.join(SCRIPT_PATH, \"..\", \"..\", \"resources\"))\nRESOURCES_SERVER_DIR = os.path.abspath(os.path.join(SCRIPT_PATH, \"..\", \"..\", \"Server\", \"resources\"))\n\nACCOUNTS_DIR = os.path.join(RESOURCES_SERVER_DIR, \"accounts\")\n\nINFO_FILE = os.path.join(SCRIPT_PATH, \"info.json\")\n\nRESOURCES_SUBFOLDER_NAMES = [\"heroCards\", \"minionCards\", \"spellCards\"]\nSUPPORTED_CARD_TYPES = [\"HERO\", \"MINION\", \"SPELL\"]\n\nsubfolder_for_type = dict(zip(SUPPORTED_CARD_TYPES, RESOURCES_SUBFOLDER_NAMES)) \n\ndef load_json(fullpath: str) -> Dict[Any, Any]:\n with open(fullpath) as f:\n data = json.load(f)\n return data\n\ndef is_name_valid(filename: str, card_type: str, cardId: str) -> bool:\n check_1 = filename.endswith(f\".{card_type.lower()}.card.json\")\n check_2 = filename.startswith(cardId)\n \n return check_1 and check_2\n\ndef get_card_id_for_account(account_name: str, card_id: str, i: int) -> str:\n acc_name = account_name.replace(\" \", \"\")\n return f\"{acc_name}_{card_id}_{i}\"\n\ndef make_copies(ids: List[str], data: Dict[Any, Any]) -> List[Dict[Any,Any]]:\n\n c1 = data.copy() \n c1[\"cardId\"] = ids[0]\n\n if len(ids) == 1:\n return [c1]\n \n else:\n c2 = data.copy()\n c3 = data.copy() \n\n c2[\"cardId\"] = ids[1]\n c3[\"cardId\"] = ids[2]\n\n return [c1, c2, c3]\n\ndef main(card: str, card_path: str, account_path: str) -> None:\n \n print(\"loading json...\")\n data = load_json(card_path)\n\n card_type = data[\"type\"]\n assert card_type in SUPPORTED_CARD_TYPES, f\"ERROR: '{card_type}' is not a supported card type.\"\n\n card_id = data[\"cardId\"]\n assert (\" \" not in card_id), \"ERROR: Spaces should not be in cardId field\"\n\n assert is_name_valid(card, card_type, card_id), f\"ERROR: '{card}' does not follow naming convention.\"\n\n loc_1 = os.path.join(RESOURCES_DIR, subfolder_for_type[card_type])\n print(f\"attempting to copy card to dir: {loc_1}\")\n shutil.copy(card_path, loc_1)\n\n loc_2 = os.path.join(RESOURCES_SERVER_DIR, subfolder_for_type[card_type])\n print(f\"attempting to copy card to dir: {loc_2}\")\n shutil.copy(card_path, loc_2)\n\n\n print(f\"Attempting to add card to account\")\n acc_json = load_json(account_path)\n username = acc_json[\"username\"]\n \n if card_type != \"HERO\":\n print(\"Adding 3x copies...\")\n ## Creates the new account id's for all three copies. Each new id follows the format: '{username}_{cardid}_{number}'\n acc_ids = [get_card_id_for_account(username, card_id, i) for i in range(1, 4)]\n else:\n print(\"Adding 1x copy...\")\n acc_ids = [get_card_id_for_account(username, card_id, 1)]\n\n card_objects = make_copies(acc_ids, data)\n\n key = card_type.lower() + \"s\" if card_type in [\"MINION\", \"SPELL\"] else card_type.lower() + \"es\" ## minion(s), spell(s), hero(es)\n collection = acc_json[\"collection\"][key]\n for idx, collected_card in enumerate(collection): \n if collected_card[\"cardId\"] in acc_ids:\n print(f\"Card was found in account, overwriting\")\n\n x_card = acc_ids.index(collected_card[\"cardId\"])\n collection[idx] = card_objects[x_card]\n \n acc_ids.pop(x_card)\n card_objects.pop(x_card) ## pop both to keep index in sync\n\n for copy in card_objects:\n collection.append(copy)\n\n print(\"Saving changes made to account\")\n with open(account_path, \"w\") as jsonFile:\n json.dump(acc_json, jsonFile, indent=4)\n\n\nif __name__ == \"__main__\":\n\n print(\"+===========================================+\")\n print(\"| NEW CARD INSTALLER SCRIPT ver1.0 |\")\n print(\"+===========================================+\")\n\n assert os.path.isdir(RESOURCES_DIR), \"ERROR: {RESOURCES_PATH} is not a valid directory!\"\n assert os.path.isdir(RESOURCES_SERVER_DIR), \"ERROR: {RESOURCES_SERVER_PATH} is not a valid directory!\"\n assert os.path.isdir(ACCOUNTS_DIR), \"ERROR: {ACCOUNTS_DIR} is not a valid directory!\"\n assert os.path.isfile(INFO_FILE), f\"ERROR: {INFO_FILE} is not a valid file!\"\n\n print(\"Loading Info.json...\")\n info = load_json(INFO_FILE)\n account_name = info[\"account_name\"]\n\n print(f\"Checking '{account_name}' account exists...\")\n account_path = os.path.join(ACCOUNTS_DIR, account_name + \".account.json\")\n assert os.path.isfile(account_path), f\"ERROR: '{account_path}' is not a file!\"\n\n import_card_path = os.path.abspath(info[\"import_directory\"])\n assert os.path.isdir(import_card_path), f\"ERROR: {import_card_path} is not a valid directory!\"\n print(f\"Looking for cards in: {import_card_path}\")\n\n cards = []\n for f in os.listdir(import_card_path):\n if f.endswith(\".card.json\"):\n cards.append(f)\n assert cards, f\"ERROR: no cards were found in {import_card_path}\"\n \n print(f\"Number of cards Found: {len(cards)}\")\n\n for c in cards:\n card_path = os.path.join(import_card_path, c)\n print(\"---------------------------------------\")\n print(f\"Starting import process for Card: {c}\")\n main(c, card_path, account_path)\n print(f\"Finished import process for Card: {c}\\n\")\n\n print(\"¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦\")\n print(\"SCRIPT COMPLETE -- If you see this message no errors were detected :)\")\n","sub_path":"devTools/cardCreator/AddJsonCardToGame.py","file_name":"AddJsonCardToGame.py","file_ext":"py","file_size_in_byte":5473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"169891319","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('icekit_workflow', '0004_auto_20170130_1146'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='workflowstate',\n name='assigned_to',\n field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL, help_text=b'User who is responsible for this content at this stage in the workflow', blank=True),\n ),\n ]\n","sub_path":"icekit/workflow/migrations/0005_auto_20170208_1146.py","file_name":"0005_auto_20170208_1146.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"599507980","text":"name = 'WebSearch'\nicon = 'web-browser'\n\ndef main(query):\n if query.startswith('google=') or query.startswith('g='):\n label = 'Search Google: '\n infos = compose_url(query, 'https://google.com/search?q=')\n return (label + infos[1], icon, 'firefox \"' + infos[0] + '\"')\n elif query.startswith('wikipedia=') or query.startswith('w=') or query.startswith('wiki='):\n label = 'Search Wikipedia: '\n infos = compose_url(query, 'https://en.wikipedia.org/wiki/')\n return (label + infos[1], icon, 'firefox \"' + infos[0] + '\"')\n elif query.startswith('stackoverflow') or query.startswith('so='):\n label = 'Search Stack Overflow: '\n infos = compose_url(query, 'http://stackoverflow.com/search?q=')\n return (label + infos[1], icon, 'firefox \"' + infos[0] + '\"')\n elif query.startswith('duckduckgo=') or query.startswith('ddg='):\n label = 'Search Duck Duck Go: '\n infos = compose_url(query, 'https://duckduckgo.com/?q=')\n return (label + infos[1], icon, 'firefox \"' + infos[0] + '\"')\n else:\n return 0\n \ndef compose_url(query, url):\n search = query.split('=')[1]\n url = url + search\n return (url, search)\n\n# if not os.path.exists(CACHE_DIR):\n# os.makedirs(CACHE_DIR)\n","sub_path":"extensions/websearch/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"381914600","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport os\nimport re\n\nfrom django import forms\nfrom django.forms import ModelForm\nfrom django.forms.widgets import Textarea, HiddenInput, PasswordInput\n\nfrom utils import connect_node\nfrom .models import (\n IceServiceCenter, IceServiceNode, IceServiceJar, IceServiceConfig, IceService, Script,\n TomcatApp, TomcatServer, TomcatServerWarDir, TomcatAppSql, TomcatAppWar\n)\nfrom .tasks import download_ice_jar, download_war\n\n\nclass IceServiceCenterForm(ModelForm):\n class Meta:\n model = IceServiceCenter\n exclude = ['create_time', 'modify_time']\n widgets = {\n 'note': Textarea(attrs={'rows': 3}),\n }\n\n\nclass IceServiceNodeForm(ModelForm):\n class Meta:\n model = IceServiceNode\n exclude = ['create_time', 'modify_time']\n widgets = {\n 'center': HiddenInput(),\n 'user': HiddenInput(),\n 'note': Textarea(attrs={'rows': 3}),\n }\n\n\nclass IceServiceJarForm(ModelForm):\n class Meta:\n model = IceServiceJar\n exclude = ['create_time', 'modify_time', 'package', 'finished']\n widgets = {\n 'active': HiddenInput(),\n 'ice_service': HiddenInput(),\n }\n\n def clean_url(self):\n url = self.cleaned_data['url']\n base, ext = os.path.splitext(url)\n if ext != '.jar':\n raise forms.ValidationError('地址有误!请提供可以下载的jar包地址')\n return url\n\n def save(self, commit=True):\n instance = super(IceServiceJarForm, self).save(commit=commit)\n if 'url' in self.changed_data:\n download_ice_jar.delay(instance.url, instance.id)\n return instance\n\n\nclass IceServiceConfigForm(ModelForm):\n class Meta:\n model = IceServiceConfig\n exclude = ['create_time', 'modify_time']\n widgets = {\n 'active': HiddenInput(),\n 'ice_service': HiddenInput(),\n }\n\n def clean_config(self):\n config = str(self.cleaned_data['config'])\n if config[-4:] != '.zip':\n raise forms.ValidationError('文件格式错误, 请上传zip文件!')\n return self.cleaned_data['config']\n\n\nclass IceServiceForm(ModelForm):\n class Meta:\n model = IceService\n exclude = ['create_time', 'modify_time', 'deployed']\n widgets = {\n 'center': HiddenInput(),\n 'user': HiddenInput(),\n 'note': Textarea(attrs={'rows': 3}),\n }\n\n def clean_name(self):\n center = self.cleaned_data['center']\n name = self.cleaned_data['name']\n if IceService.objects.filter(center=center, name=name).exists():\n if self.instance.pk is None:\n raise forms.ValidationError('该注册中心中, 已经存在%s' % name)\n else:\n if IceService.objects.get(center=center, name=name).id != self.instance.id:\n raise forms.ValidationError('该注册中心中, 已经存在%s' % name)\n return name\n\n def clean_dir_name(self):\n center = self.cleaned_data['center']\n dir_name = self.cleaned_data['dir_name']\n if IceService.objects.filter(center=center, dir_name=dir_name).exists():\n if self.instance.pk is None:\n raise forms.ValidationError('该注册中心中, 该工程目录已经存在: %s' % dir_name)\n else:\n if IceService.objects.get(center=center, dir_name=dir_name).id != self.instance.id:\n raise forms.ValidationError('该注册中心中, 该工程目录已经存在: %s' % dir_name)\n return dir_name\n\n\nclass TomcatServerForm(ModelForm):\n class Meta:\n model = TomcatServer\n exclude = ['create_time']\n\n def clean_port(self):\n port = self.cleaned_data['port']\n if not 0 < port <= 65535:\n raise forms.ValidationError('端口范围应该在[0, 65535]')\n return port\n\n\nclass TomcatServerWarDirForm(ModelForm):\n class Meta:\n model = TomcatServerWarDir\n fields = ['tomcat_server', 'war_dir', 'note']\n widgets = {\n 'tomcat_server': HiddenInput(),\n }\n labels = {\n 'war_dir': 'war包目录(填写绝对路径)'\n }\n\n def clean_war_dir(self):\n war_dir = self.cleaned_data['war_dir']\n ts = self.cleaned_data['tomcat_server']\n tomcat_dir = os.path.sep.join(ts.cmd.split(os.path.sep)[:3])\n if tomcat_dir != os.path.sep.join(war_dir.split(os.path.sep)[:3]):\n raise forms.ValidationError('请设置在此tomcat-server下的目录!')\n node = connect_node(ts.host.ip)\n try:\n if not node.path_exists(war_dir):\n if not node.create_path(war_dir):\n raise forms.ValidationError('在Tomcat-Sserver下创建目录失败, marmot可能缺少权限!')\n except IOError:\n raise forms.ValidationError('连接不上Tomcat-server的服务器, 无法验证和创建目录!')\n return war_dir\n\n\nclass TomcatAppForm(ModelForm):\n class Meta:\n model = TomcatApp\n exclude = ['create_time', 'identifier', 'bak_flag']\n widgets = {\n 'tomcat_server': HiddenInput(),\n 'user': HiddenInput(),\n }\n\n def __init__(self, *args, **kwargs):\n super(TomcatAppForm, self).__init__(*args, **kwargs)\n if 'initial' in kwargs:\n self.fields['war_dir'].queryset = TomcatServerWarDir.objects.filter(\n tomcat_server=kwargs['initial']['tomcat_server']\n )\n\n def clean_name(self):\n name = self.cleaned_data['name']\n if not re.match(r'^[a-zA-Z0-9_]+$', name):\n raise forms.ValidationError('只能输入字母、数字和下划线')\n return name\n\n def clean_port(self):\n port = self.cleaned_data['db_port']\n if not 0 < port <= 65535:\n raise forms.ValidationError('端口范围应该在[0, 65535]')\n return port\n\n\nclass TomcatAppWarForm(ModelForm):\n class Meta:\n model = TomcatAppWar\n exclude = ['create_time', 'package', 'state']\n widgets = {\n 'tomcat_app': HiddenInput(),\n }\n\n def clean_url(self):\n url = self.cleaned_data['url']\n base, ext = os.path.splitext(url)\n if ext != '.war':\n raise forms.ValidationError('地址有误!请提供war包地址')\n return url\n\n def save(self, commit=True):\n instance = super(TomcatAppWarForm, self).save(commit=commit)\n if 'url' in self.changed_data:\n download_war.delay(instance.url, instance.id)\n return instance\n\n\nclass TomcatAppSqlForm(ModelForm):\n class Meta:\n model = TomcatAppSql\n exclude = ['create_time', 'state', 'sys_bak']\n widgets = {\n 'tomcat_app': HiddenInput(),\n }\n\n def clean_sql(self):\n sql = str(self.cleaned_data['sql'])\n if sql[-4:] != '.sql':\n raise forms.ValidationError('文件格式错误, 请上传sql文件!')\n return self.cleaned_data['sql']\n\n\nclass ScriptForm(ModelForm):\n class Meta:\n model = Script\n exclude = ['create_time', 'modify_time']\n widgets = {\n 'owner': HiddenInput(),\n 'note': Textarea(attrs={'rows': 5}),\n }\n labels = {\n 'script': '脚本文件(Shell或Python)'\n }\n","sub_path":"tags/v1.5.2/marmot/services/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":7434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"488337807","text":"import numpy as np\r\n\r\n\r\ndef check(NUM):\r\n check_help = True\r\n try:\r\n num_1 = float(NUM)\r\n except ValueError:\r\n print(\"Error, уведите целое или дробное число\")\r\n check_help = False\r\n return check_help\r\n\r\n\r\ndef square(x1, x2, y1, y2):\r\n res_1 = abs(float((x1 * y2 - x2 * y1) / 2))\r\n return res_1\r\n\r\n\r\ndef work():\r\n while 1:\r\n n = input(\"Уведите количество точек: \")\r\n if check(n) == False:\r\n continue\r\n if int(n) <= 0:\r\n print(\"Ошибка, невозможно такое количество чисел\")\r\n continue\r\n if int(n) == 1:\r\n sqr = 0\r\n else:\r\n n = int(n)\r\n x = []\r\n y = []\r\n z = []\r\n sqr = 0\r\n while n > 0:\r\n num_x = input(\"Уведите число x: \")\r\n if check(num_x) == False:\r\n continue\r\n num_y = input(\"Уведите число y: \")\r\n if check(num_y) == False:\r\n continue\r\n else:\r\n num_x = float(num_x)\r\n num_y = float(num_y)\r\n x.append(num_x)\r\n y.append(num_y)\r\n print(x, y, sep='\\n')\r\n n -= 1\r\n k = np.size(x)\r\n res = 0\r\n for i in range(0, k, 1):\r\n if i == (k - 1):\r\n z.append(square(x[0], x[k - 1], y[1], y[k - 1]))\r\n else:\r\n z.append(square(x[i], x[i + 1], y[i], y[i + 1]))\r\n res += z[i]\r\n print(\"Площадь н-угольника ровняется: \" + str(res))\r\n\r\n break\r\n\r\n\r\nif __name__ == \"__main__\":\r\n work()","sub_path":"results/laba 5/lab_5.1.py","file_name":"lab_5.1.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"397775612","text":"\"\"\" The Geebaby web framework.\n\"\"\"\n\n\ndef uri2tea(uri):\n \"\"\" Takes a URI and converts it to tags, entities and actions.\n \"\"\" \n from geebaby import tags, actions, entities\n \n t = tags.from_uri(uri)\n e = entities.from_uri(uri)\n a = actions.from_uri(uri)\n\n return t, e, a\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"388844824","text":"from multiprocessing import Pool, cpu_count\nfrom collections import namedtuple\nimport numpy as np\n\nfrom script_run_real_data_job import run_single_job\n\nArguments = namedtuple('Arguments', ('input_path', 'top', 'output_path',\n 'algo_filter', 'no_std_redirect',\n 'as_pr', 'ar_pr'))\n\nif __name__ == \"__main__\":\n\n globals()[\"Arguments\"] = Arguments\n\n INPUT_PATH = 'data/enron_dataset_splitted_receivers.csv.gz'\n TOP = 100\n OUTPUT_PATH = 'output/real-data/'\n ALGO_FILTER = ['vi', 'vifb', 'gb']\n\n arg_list = list()\n\n for i in range(10):\n\n as_pr = np.random.uniform(0.01, 50.0)\n ar_pr = np.random.uniform(0.01, 50.0)\n\n args = Arguments(\n input_path=INPUT_PATH, top=TOP,\n output_path=OUTPUT_PATH,\n algo_filter=ALGO_FILTER,\n no_std_redirect=False,\n as_pr=as_pr, ar_pr=ar_pr)\n\n name_suffix = str(i)\n\n arg_list.append((args, name_suffix))\n\n # Init pool of processes\n pool = Pool(2)\n # Run in parallel\n pool.starmap(run_single_job, arg_list)\n # Close pool\n pool.close()\n # Wait for them to finish\n pool.join()\n","sub_path":"script_run_real_data_prior_random_search.py","file_name":"script_run_real_data_prior_random_search.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"70883850","text":"# Given:\n# 'AAABCCCaaYYY'\n# Return:\n# 'A3B1C3a2Y3'\n\n#region my implementation\ndef stringCompress(s):\n data = []\n current = ''\n count = 0\n for i in range(0, len(s)):\n if s[i] == current and i != len(s) - 1:\n count += 1\n elif s[i] != current or (i == len(s) - 1):\n if i == len(s) - 1: \n count += 1\n if current != '': #save item first\n data.append(\"{}{}\".format(current,count))\n count = 1\n current = s[i]\n \n return ''.join(data)\n#endregion\n\ndef test_stringCompress():\n stubs = [stringCompress]\n for stub in stubs: \n assert stub('AAABCCCaaYYY') == 'A3B1C3a2Y3'\n assert stub('') == ''\n assert stub('AABBCC') == 'A2B2C2'\n assert stub('AAABCCDDDDD') == 'A3B1C2D5'\n","sub_path":"Python-Algorithms/ArraySequences/06_StringCompress.py","file_name":"06_StringCompress.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"567948156","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\n\nimport torch.nn as nn\n\nclass DeepSuperviseLoss(nn.Module):\n def __init__(self, params):\n super(DeepSuperviseLoss, self).__init__()\n self.deep_sup_weight = params.get('deep_suervise_weight', None)\n self.base_loss = params['base_loss']\n\n def forward(self, loss_input_dict):\n predict = loss_input_dict['prediction']\n if(not isinstance(predict, (list,tuple))):\n raise ValueError(\"\"\"For deep supervision, the prediction should\n be a list or a tuple\"\"\")\n predict_num = len(predict)\n if(self.deep_sup_weight is None):\n self.deep_sup_weight = [1.0] * predict_num\n else:\n assert(predict_num == len(self.deep_sup_weight))\n loss_sum, weight_sum = 0.0, 0.0\n for i in range(predict_num):\n loss_input_dict['prediction'] = predict[i]\n temp_loss = self.base_loss(loss_input_dict)\n loss_sum += temp_loss * self.deep_sup_weight[i]\n weight_sum += self.deep_sup_weight[i]\n loss = loss_sum/weight_sum\n return loss","sub_path":"pymic/loss/seg/deep_sup.py","file_name":"deep_sup.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"151700869","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# 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, 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\"\"\"Endpoint for sending emails to the list via the UI\"\"\"\nimport plugins.server\nimport plugins.session\nimport email.message\nimport email.utils\nimport email.header\nimport aiosmtplib\nimport fnmatch\nimport typing\nimport aiohttp.web\nimport uuid\n\nCOMPOSER_VERSION = \"0.4\" # Bump when changing logic\n\nasync def process(\n server: plugins.server.BaseServer,\n session: plugins.session.SessionObject,\n indata: dict,\n) -> typing.Union[dict, aiohttp.web.Response]:\n\n if not server.config.ui.mailhost:\n return {\"error\": \"This server has not been set up for sending email yet.\"}\n\n # Figure out outgoing MTA\n mailhost = server.config.ui.mailhost\n mailport = 25\n if \":\" in mailhost:\n mailhost, _mailport = mailhost.split(\":\", 1)\n mailport = int(_mailport)\n\n # Figure out if recipient list is on allowed list\n to = indata.get(\"to\", \"\")\n mldomain = to.strip(\"<>\").split(\"@\")[-1]\n allowed_to_send = False\n for allowed_domain in server.config.ui.sender_domains.split(\" \"):\n if fnmatch.fnmatch(mldomain, allowed_domain):\n allowed_to_send = True\n break\n if not allowed_to_send:\n return {\"error\": \"Recipient mailing list is not an allowed recipient for emails via the web.\"}\n\n # If logged in and everything, prep for dispatch\n if session.credentials and session.credentials.authoritative:\n subject = indata.get(\"subject\")\n body = indata.get(\"body\")\n irt = indata.get(\"in-reply-to\")\n references = indata.get(\"references\")\n\n if to and subject and body:\n msg = email.message.EmailMessage()\n if irt:\n msg[\"In-reply-to\"] = irt\n if references:\n msg[\"References\"] = references\n msg[\"From\"] = email.utils.formataddr(\n (str(email.header.Header(session.credentials.name, \"utf-8\")), session.credentials.email)\n )\n msg[\"To\"] = to\n msg[\"Subject\"] = str(email.header.Header(subject, \"utf-8\"))\n msg[\"Date\"] = email.utils.formatdate()\n msg[\"Message-ID\"] = f\"\"\n msg[\"User-Agent\"] = \"Apache Pony Mail Foal Composer v/%s\" % COMPOSER_VERSION\n msg.set_charset(\"utf-8\")\n msg.set_content(body)\n await aiosmtplib.send(msg, hostname=mailhost, port=mailport)\n return {\"okay\": True, \"message\": \"Message dispatched!\"}\n else:\n return {\"error\": \"You need to fill out both recipient, subject and text body.\"}\n else:\n return {\"error\": \"You need to be logged in via an authoritative source to send emails.\"}\n\n\ndef register(server: plugins.server.BaseServer):\n return plugins.server.Endpoint(process)\n","sub_path":"server/endpoints/compose.py","file_name":"compose.py","file_ext":"py","file_size_in_byte":3574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"398056469","text":"# -*- coding: utf-8 -*-\nfrom odoo import api, fields, models, tools, _\n\n\n\nclass AccountInvoiceLine(models.Model):\n _inherit = \"account.invoice.line\"\n\n dnk_profit_margin_color = fields.Char('- Color')\n dnk_profit_margin_html = fields.Char('- ', readonly=True)\n dnk_profit_margin_ratio = fields.Float('- Margin Ratio')\n\n @api.onchange('price_unit','discount')\n def dnk_onchange_price(self):\n self.dnk_getmargin_profit()\n\n\n @api.onchange('product_id')\n def _onchange_product_id(self):\n res = super(AccountInvoiceLine, self)._onchange_product_id()\n self.dnk_getmargin_profit()\n return res\n\n def dnk_get_color(self):\n if self.dnk_profit_margin_ratio >= 0.5:\n self.dnk_profit_margin_html = \"
 
\";\n self.dnk_profit_margin_color = \"Blue\"\n elif self.dnk_profit_margin_ratio >= 0.4:\n self.dnk_profit_margin_html = \"
 
\";\n self.dnk_profit_margin_color = \"Green\"\n elif self.dnk_profit_margin_ratio >= 0.3:\n self.dnk_profit_margin_html = \"
 
\";\n self.dnk_profit_margin_color = \"Yellow\"\n elif self.dnk_profit_margin_ratio >= 0.2:\n self.dnk_profit_margin_html = \"
 
\";\n self.dnk_profit_margin_color = \"Gray\"\n else:\n self.dnk_profit_margin_html = \"
 
\";\n self.dnk_profit_margin_color = \"Black\"\n\n\n def dnk_getmargin_profit(self):\n if self.price_unit > 0 and self.product_id.dnk_cost_mp > 0:\n # Primero checar la moneda de sale order\n if self.invoice_id.currency_id == self.product_id.dnk_costs_currency_id:\n self.dnk_profit_margin_ratio =(self.price_unit-(self.product_id.dnk_cost_mp+self.product_id.dnk_cost_mo+self.product_id.dnk_cost_gif))/self.price_unit\n self.dnk_get_color()\n else :\n #Lo haré sólo tomando en cuenta la moneda del precio\n #porque se supone que el precio siempre estará en USD\n # y como siempre está el producto en USD y son diferentes, entonces la lista de precios es MXN\n #if self.product_id.dnk_costs_currency_id.name == 'MXN':\n self.dnk_profit_margin_ratio = ((self.price_unit/self.invoice_id.company_id.dnk_usd_cost_fixed_rate)-(self.product_id.dnk_cost_mp+self.product_id.dnk_cost_mo+self.product_id.dnk_cost_gif))/(self.price_unit/self.invoice_id.company_id.dnk_usd_cost_fixed_rate)\n self.dnk_get_color()\n #else :\n # self.dnk_profit_margin_ratio = ((self.invoice_id.company_id.dnk_usd_cost_fixed_rate/self.price_unit)-(self.product_id.dnk_cost_mp+self.product_id.dnk_cost_mo+self.product_id.dnk_cost_gif))/(self.invoice_id.company_id.dnk_usd_cost_fixed_rate/self.price_unit)\n # self.dnk_get_color()\n\nclass AccountInvoice(models.Model):\n _inherit = \"account.invoice\"\n\n def _write(self, vals):\n for rec in self:\n for linea in rec.invoice_line_ids:\n linea.dnk_getmargin_profit()\n res = super(AccountInvoice, self)._write(vals)\n return res\n","sub_path":"denker/dnk_sale_profit_margin_color/models/account_invoice.py","file_name":"account_invoice.py","file_ext":"py","file_size_in_byte":3881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"51983810","text":"import json\nfrom collections import OrderedDict\nfrom unittest.mock import patch\n\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom rest_framework.test import APITestCase\nfrom faker import Faker\n\nfrom api_2007scape_tools.items.models import Item, ItemOsbuddyExchangeSnapshot\nfrom api_2007scape_tools.services.osbuddy_service import OsbuddyService\n\n\nclass OsbuddyServiceTestCase(APITestCase):\n def setUp(self):\n self.faker = Faker(OrderedDict([(\"en-US\", 1)]))\n Faker.seed(0)\n\n @patch(\"api_2007scape_tools.services.osbuddy_service.requests.get\")\n def test_get_item_not_in_json(self, mock_response):\n mock_response.return_value.content = '{\"2\":{\"id\":2,\"name\":\"Cannonball\",\"members\":true,\"sp\":5,\"buy_average\":179,\"buy_quantity\":164959,\"sell_average\":178,\"sell_quantity\":475611,\"overall_average\":178,\"overall_quantity\":640570}}'\n service = OsbuddyService()\n\n item_id = 0\n Item.objects.create(id=item_id)\n\n self.assertIsNone(service.get_snapshot(0))\n\n @patch(\"api_2007scape_tools.services.osbuddy_service.requests.get\")\n def test_get_item_in_json(self, mock_response):\n item_id = 2\n Item.objects.create(id=item_id)\n\n buy_average = self.faker.random_int(min=-2147483647, max=2147483647, step=1)\n buy_quantity = self.faker.random_int(min=0)\n sell_average = self.faker.random_int(min=-2147483647, max=2147483647, step=1)\n sell_quantity = self.faker.random_int(min=0)\n overall_average = self.faker.random_int(min=-2147483647, max=2147483647, step=1)\n overall_quantity = self.faker.random_int(min=0)\n\n mock_data = {\n item_id: {\n \"id\": item_id,\n \"name\": \"Cannonball\",\n \"members\": True,\n \"sp\": 5,\n \"buy_average\": buy_average,\n \"buy_quantity\": buy_quantity,\n \"sell_average\": sell_average,\n \"sell_quantity\": sell_quantity,\n \"overall_average\": overall_average,\n \"overall_quantity\": overall_quantity,\n }\n }\n\n mock_response.return_value.content = json.dumps(mock_data)\n\n service = OsbuddyService()\n snapshot_data = service.get_snapshot(item_id)\n\n self.assertEqual(buy_average, snapshot_data[\"buy_average\"])\n self.assertEqual(buy_quantity, snapshot_data[\"buy_quantity\"])\n self.assertEqual(sell_average, snapshot_data[\"sell_average\"])\n self.assertEqual(sell_quantity, snapshot_data[\"sell_quantity\"])\n self.assertEqual(overall_average, snapshot_data[\"overall_average\"])\n self.assertEqual(overall_quantity, snapshot_data[\"overall_quantity\"])\n","sub_path":"api_2007scape_tools/tests/services/test_osbuddy_service.py","file_name":"test_osbuddy_service.py","file_ext":"py","file_size_in_byte":2697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"493668209","text":"from categories import *\nfrom questions import *\nfrom player import *\n\nclass Board:\n\t\"\"\"\n\t>>> c = Categories('categories_6123.txt')\n\t>>> q = Questions('qs_6123.txt', 'an_6123.txt', c)\n\t>>> b = Board(c, q)\n\t>>> print(b.display())\n\t\n\t\n\t1. CARTOON FEMALES: 200, 400, 600, 800, 1000\n\t2. STOCK SYMBOLS: 200, 400, 600, 800, 1000\n\t3. A RIVER RUNS THROUGH IT: WORLD CAPITAL EDITION: 200, 400, 600, 800, 1000\n\t4. I NEED A HOBBY!: 200, 400, 600, 800, 1000\n\t5. METEROLOGICAL RHYME TIME: 200, 400, 600, 800, 1000\n\t6. EDISON LABS: 200, 400, 600, 800, 1000\n\t\n\t\n\t>>> b.is_done()\n\tFalse\n\t>>> b.questions.qs = {c:{}}\n\t>>> b.is_done()\n\tTrue\n\t\"\"\"\n\tdef __init__(self, cats=[], qs=[], dj=False):\n\t\tself.categories = cats\n\t\tself.questions = qs\n\n\t\tif not dj:\n\t\t\tself.values = [200, 400, 600, 800, 1000]\n\t\telse:\n\t\t\tself.values = [400, 800, 1200, 1600, 2000]\n\n\n\tdef display(self):\n\t\tresult = '\\n\\n'\n\t\tfor i in self.categories.cats:\n\t\t\tresult += f'{i+1}. {self.categories.cats[i]}: {\", \".join([str(i) for i in self.questions.qs[self.categories.cats[i]]])}\\n'\n\t\tresult += '\\n'\n\t\treturn result\n\n\n\tdef question(self, cat, value):\n\t\tif value not in self.values:\n\t\t\traise Exception('The value entered is not in the list')\n\t\ttry:\n\t\t\treturn self.questions.qs[cat][value]\n\t\texcept KeyError as e:\n\t\t\treturn 'Sorry, but that value as already been selected.'\n\n\tdef answer_question(self, cat, value):\n\t\tq = self.question(cat, value)\n\t\t#answer = input()\n\t\tif q.check_answer(answer):\n\t\t\t#print(f'Correct! Your score is now ${player.score}') # DEFINE PLAYER!!!!!!!!!!!\n\t\t\tdel self.questions.qs[cat][val]\n\t\t\treturn True\n\t\telse:\n\t\t\tdel self.questions.qs[cat][val]\n\t\t\treturn False\n\n\tdef is_done(self):\n\t\tqs_left = [len(self.questions.qs[cat]) for cat in self.questions.qs]\n\t\tif sum(qs_left) == 0:\n\t\t\treturn True\n\t\treturn False\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()","sub_path":"jeopardy/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"416378279","text":"def mutate_list(a_list, index_num, v):\n ''' Inserts v at index index_num in a_list'''\n a_list.insert(index_num, v)\n\n\ndef remove_ch(a_list, index_num):\n ''' Removes character at index_num from a_list'''\n a_list.pop(index_num)\n\n\ndef get_list():\n ''' Reads in values for a list and returns the list '''\n user_list = input(\"Enter values in list separated by commas: \")\n user_list = user_list.split(\",\")\n user_list = [int(i) for i in user_list]\n return user_list\n\n# Main program starts here\n\na_list = get_list()\nprint(a_list)\nchoice = input(\"Enter choice (m,r): \")\nif choice == \"m\":\n num = input()\n num = num.split(\",\")\n mutate_list(a_list, int(num[0]), int(num[1]))\n print(a_list)\nelif choice == \"r\":\n num = input()\n remove_ch(a_list, int(num[0]),)\n print(a_list)\nelse:\n print(a_list)\n\n\n\n","sub_path":"Verkefni 10/Project 5/Aefing 11 Tuples_Lists/Aefing1.py","file_name":"Aefing1.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"421055973","text":"Import(\"env\")\n\n# remove -ffast-math compile option\nnanoBragg_env = env.Clone()\nccflags = nanoBragg_env['SHCCFLAGS']\no = '-ffast-math'\nif o in ccflags:\n ccflags.remove(o)\nnanoBragg_env.Replace(SHCCFLAGS=ccflags)\nnanoBragg_obj = nanoBragg_env.SharedObject(\n source=[\n \"nanoBragg_ext.cpp\",\n \"nanoBragg.cpp\",\n ])\n\nenv.SharedLibrary(\n target=\"#lib/simtbx_nanoBragg_ext\",\n source=[\n nanoBragg_obj\n ]\n)\n\n","sub_path":"simtbx/nanoBragg/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"415671099","text":"import sys\nfrom functools import reduce\nfrom math import sqrt\nfrom math import acos\nfrom math import pi\nimport os\n# pre: 2 vetores do mesmo tamanho\ndef normalized_dot_product( v1, v2):\n dot = reduce((lambda a, b: a+b), [x * y for (x, y) in zip(v1, v2)])\n sq_sum = lambda v: reduce((lambda a, b: a+b), [x*x for x in v])\n multNorm = sqrt(sq_sum(v1)) * sqrt(sq_sum(v2))\n if multNorm == 0:\n return 0\n return dot / multNorm\n# pos: produto escalar normalizado\n \ndef angle(v1, v2):\n return acos(normalized_dot_product(v1, v2)) # * 180 / pi \n\ndef str_to_int_tuple(list_of_str_tuples):\n return map((lambda t: map((lambda i: int(i)), t.split(','))), list_of_str_tuples)\n\ndef vec_subtraction( v1, v2):\n return (v1[0] - v2[0], v1[1] - v2[1])\n \ndef read_paths_and_people(path):\n\n f = open(path)\n\n meter_to_pixel = int(f.readline().replace('[', '').replace(']', ''))\n\n # Loads the paths taken by each person, disconsiders the number of frames said path appears\n lines = [l.replace('\\n', '').split()[1] for l in f]\n\n #dictionares - one for postions in time and another for positions per person\n position_delta = dict()\n angular_delta = dict()\n\n\n # separates the tuples into different objects, disconsiders the frame count\n counter = -1\n for line in lines:\n #since each person is a line, we create a new mapping in this dictionary for each person\n counter += 1\n position_delta[counter] = []\n angular_delta[counter] = []\n str_list = (line[1:-1]).replace(\"(\", '').split(')')\n str_list = [s.split(',') for s in str_list]\n \n pos_tuples = []\n for tuple in str_list:\n x, y, frameindex = tuple\n pos_tuples.append((int(x), int(y)))\n \n last_position = pos_tuples[1]\n last_angle = angle(vec_subtraction(pos_tuples[1], pos_tuples[0]) , (1, 0))\n \n #breaks line in tuples\n for tuple in pos_tuples[2:]:\n # reads position: x, y, frame_index\n x, y = tuple\n \n current_angle = angle((x, y), (1, 0))\n angular_delta[counter].append(current_angle - last_angle)\n\n #adds this frame to the person's list of frames in the dictionary\n position_delta[counter].append((x - last_position[0], y - last_position[1]))\n\n last_angle = current_angle\n last_position = (x, y)\n\n\n return position_delta, angular_delta\n\n\nif __name__ == \"__main__\":\n dir = sys.argv[1]\n paths = os.listdir(dir)\n\n pos_delta = open(\"pos_delta.txt\", 'w')\n ang_delta = open(\"ang_delta.txt\", 'w')\n\n for path in paths:\n dicts = read_paths_and_people(dir+'\\\\'+ path)\n for v in dicts[0].values():\n pos_delta.write(str(v[1:]) + '\\n')\n for v in dicts[1].values():\n ang_delta.write(str(v[1:]) + '\\n')","sub_path":"DataGenerator/dataset_generator.py","file_name":"dataset_generator.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"421130917","text":"import config\nimport recordkeeper\nimport sqlite3 as sql\nimport time\nimport math\n\nstart_time = round(time.time())\nrecords = recordkeeper.get_range(0, start_time)\n\nconn = sql.connect(config.data + \"/attendance.db\")\ncur = conn.cursor()\ncur.execute(\"DELETE FROM history_cache\")\nfor record in records:\n time_in = record[\"timein\"]\n time_out = record[\"timeout\"]\n if time_in == -1:\n time_in = 0\n if time_out == -1:\n time_out = 0\n if time_in == -2:\n time_in = start_time\n if time_out == -2:\n time_out = start_time\n cur.execute(\"INSERT INTO history_cache(name,time_in,time_out) VALUES (?,?,?)\", (record[\"name\"],time_in,time_out))\nconn.commit()\nconn.close()","sub_path":"cache_history.py","file_name":"cache_history.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"472159145","text":"# Given a word/ phrase, return True if it's a palindrome\n\n\n# brute force simple solution\n# takes up extra space\ndef palindrome(s):\n s = \"\".join(letter.lower() for letter in s if letter.isalpha())\n return s == s[::-1]\n\n# more efficient solution\ndef is_palindrome(s):\n i = 0 \n j = len(s)-1\n\n while i < j:\n while not s[i].isalpha():\n i += 1\n while not s[j].isalpha():\n j -= 1\n \n if s[i].lower() != s[j].lower():\n return False \n \n i+=1 \n j -=1\n\n return True\n\n\n\nprint(is_palindrome(\"Was it a cat i saw\")) # True\nprint(is_palindrome(\"buttermilk\")) # False \nprint(is_palindrome(\"Live on time, emit no evil\")) # True","sub_path":"Educative.io/Lesson_Practice/str_palindrome.py","file_name":"str_palindrome.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"369251918","text":"\"\"\"\nhttps://leetcode.com/problems/find-all-anagrams-in-a-string/\nSliding window of length len(p), record the count of characters in the window.\nTime compelxity: O(n), n = len(s)\n\"\"\"\nclass Solution:\n def findAnagrams(self, s: str, p: str):\n cnt, k = len(p), len(p)\n if cnt > len(s):\n return []\n\n ans = []\n ref = {}\n for ch in p:\n ref[ch] = ref.get(ch, 0) + 1\n\n for i in range(k):\n if s[i] in ref:\n ref[s[i]] -= 1\n if ref[s[i]] >= 0:\n cnt -= 1\n\n if cnt == 0:\n ans.append(0)\n\n for i in range(1, len(s)-k+1):\n old_ch, new_ch = s[i-1], s[i+k-1]\n if old_ch in ref:\n ref[old_ch] += 1\n if ref[old_ch] > 0:\n cnt += 1\n if new_ch in ref:\n ref[new_ch] -= 1\n if ref[new_ch] >= 0:\n cnt -= 1\n if cnt == 0:\n ans.append(i)\n\n return ans\n","sub_path":"0438_FindAllAnagramsInAString.py","file_name":"0438_FindAllAnagramsInAString.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"631582266","text":"import time\nfrom tqdm import tqdm\nfrom helper import get_object_query_func\nfrom entity_properties.pred_via_lda import props_per_entities\nfrom pprint import pprint\n\nimport random\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom word_embeddings.sent_emb import preproc, sent_vec, cos_sim_sen\n\n\n\ndef add_to_subject_networkx(graph, subject_id, subject_name, predicates, predicate_ids, objects, object_ids, directions):\n for p, p_id, o, o_id, d in list(zip(predicates, predicate_ids, objects, object_ids, directions)):\n\n if d == \"S->O\":\n triple_exists = True if graph.has_edge(*(subject_id, o_id, p)) else False\n else:\n triple_exists = True if graph.has_edge(*(o_id, subject_id, p)) else False\n \n if triple_exists == False:\n if graph.has_node(subject_id) == False:\n graph.add_node(subject_id, name=subject_name)\n if graph.has_node(o_id) == False:\n graph.add_node(o_id, name=o)\n\n if d == \"S->O\":\n graph.add_edge(subject_id, o_id, key=p, pred_id=p_id)\n else:\n graph.add_edge(o_id, subject_id, key=p, pred_id=p_id)\n\n\ndef create(nx_graph, kb_string, annotations, kb_url, exclude_pred_by_name=\"\", use_pred_by_name=\"\",\n use_pred_by_id=\"\", exclude_pred_by_id=\"\", min_branches_per_node=15, max_nodes_per_hop=500, max_nodes=1200,\n printouts=True, consider_relation_directions=False, pred_infos=None, el_relation=\"WIKIFIERED\",\n find_paths=True, retrieve_concept_names=True, max_graph_depth=-1, include_lda=False, include_wordvec=False, whole_sen = '',\n par_query=False):\n \"\"\"\n Create local networkX graph\n :param annotations:\n :param entities_table: Entities table instance of neo4j\n :param entities: string entities for which to look for, e.g. \"instance of; subclass of\"\n :param no_hops: number of hops over the graph\n :param use_official_wikidata: use official wikidata or Daniil's\n \"\"\"\n\n def init_nx_graph(annotations, graph):\n for annotation in annotations:\n object_id = annotation[0] # related entity found for concept of sentence\n object_name = annotation[1] # label for entity id\n subject_id = annotation[2] # concept found in the input sentence\n subject_name = annotation[3] # concept found in the input sentence\n if graph.has_node(subject_id) == False:\n graph.add_node(subject_id, name=subject_name)\n if graph.has_node(object_id) == False:\n graph.add_node(object_id, name=object_name)\n graph.add_edge(subject_id, object_id, key=el_relation)\n graph.add_edge(object_id, subject_id, key=el_relation)\n\n\n get_all_objects = get_object_query_func(kb_string)\n\n total_time = time.time()\n all_paths_exhausted = True\n if printouts == True:\n print(\"\\n========== Create local graph ==========\")\n\n init_nx_graph(annotations, nx_graph)\n if include_wordvec:\n w2v = preproc()\n sen_vec = sent_vec(w2v, whole_sen)\n\n if include_lda:\n entities = [an[1] for an in annotations]\n entity_preds = props_per_entities(cnt_topics = 5, entities=entities, max_props=150, count_threshold=40000)\n for (pred_id, pred_name) in entity_preds:\n use_pred_by_id.append(pred_id)\n\n # 2) DO BFS: search recursivly for x hops over the graph\n # 2.1) prevent creating a graph twice\n next_subject = []\n next_subject_ids = []\n for anno in annotations:\n if anno[0] not in next_subject_ids:\n next_subject.append(anno)\n next_subject_ids.append(anno[0])\n\n # 2.2) iterating over hops\n no_hops = 0\n visited = []\n while len(next_subject) > 0 and find_paths==True:\n if max_graph_depth != -1 and no_hops >= max_graph_depth:\n break\n no_hops += 1\n temp_next_subjects = []\n\n # calculate a limit of branching on each node by the max number of new nodes that are allowed each hop\n new_limit = int(max_nodes_per_hop/len(next_subject))\n if new_limit < min_branches_per_node:\n new_limit = min_branches_per_node\n\n if printouts == True:\n bar = \"Processing hop \" + str(no_hops) + \" with \" + str(len(next_subject)) + \" next subjects and new limit of \"+str(new_limit)+\"...{l_bar}{bar}{r_bar}\"\n next_subj_iterator = tqdm(next_subject, bar_format=bar)\n else:\n next_subj_iterator = next_subject\n # iterating over subjects left in queue\n for subject in next_subj_iterator:\n if subject[0] not in visited:\n visited.append(subject[0])\n\n temp_predicates, temp_p_ids, temp_objects, temp_o_ids, directions = [], [], [], [], []\n \n\n '''\n for every pred query via sparql for objects with sub+p_id and returns:\n list: predicate names\n list: predicate ids\n list: object names\n list: object ids\n list: directions\n pred_infos are just sent all the way to ask for the label name when a pred_id is found\n '''\n if par_query:\n tps, tpidss, tos, toidss, dss = get_all_objects(kb_url, subject[0], use_pred_by_id, limit=new_limit,\n consider_relation_directions=consider_relation_directions, pred_infos=pred_infos,\n retrieve_concept_names=retrieve_concept_names, par_query=par_query)\n temp_predicates.extend(tps)\n temp_p_ids.extend(tpidss)\n temp_objects.extend(tos)\n temp_o_ids.extend(toidss)\n directions.extend(dss)\n else:\n for pred in use_pred_by_id:\n tp, tpids, \\\n to, toids, \\\n ds = get_all_objects(kb_url, subject[0], pred, limit=new_limit,\n consider_relation_directions=consider_relation_directions, pred_infos=pred_infos,\n retrieve_concept_names=retrieve_concept_names, par_query=par_query)\n temp_predicates.extend(tp)\n temp_p_ids.extend(tpids)\n temp_objects.extend(to)\n temp_o_ids.extend(toids)\n directions.extend(ds)\n\n if consider_relation_directions == True and \"O->S\" in directions:\n print(\"Error: O->S relation used although directed boolean is set to true.\")\n\n\n if len(temp_predicates) > 0:\n temp_list = list(zip(temp_o_ids, temp_objects, temp_p_ids, temp_predicates, directions))\n\n # remove nodes with empty names\n temp_list = [(o_id, o, p_id, p, d) for o_id, o, p_id, p, d in temp_list if o != \"\" and o != \"None\" and o != None]\n\n # include only certain predicates (by name or id)\n if len(use_pred_by_name) > 0 or len(use_pred_by_id) > 0:\n temp_list = [(o_id, o, p_id, p, d) for o_id, o, p_id, p, d in temp_list if p in use_pred_by_name or p_id in use_pred_by_id]\n\n # exclude certain predicates by name and id\n if len(exclude_pred_by_name) > 0 or len(exclude_pred_by_id) > 0:\n temp_list = [(o_id, o, p_id, p, d) for o_id, o, p_id, p, d in temp_list if p not in exclude_pred_by_name and p_id not in exclude_pred_by_id]\n\n # next line only for o_id,o,p_id,p,d if cos_sim(o, subject[1])>threshold\n if include_wordvec:\n temp_next_subjects.extend([(o_id, o, subject[0]) for o_id, o, p_id, p, d in temp_list if (\n o_id, o, subject[0]) not in temp_next_subjects and o_id not in visited and cos_sim_sen(w2v, sen_vec, o)])\n else:\n temp_next_subjects.extend([(o_id, o, subject[0]) for o_id, o, p_id, p, d in temp_list if (\n o_id, o, subject[0]) not in temp_next_subjects and o_id not in visited])\n\n if len(temp_list) > 0:\n temp_o_ids, temp_objects, temp_p_ids, temp_predicates, directions = list(zip(*temp_list))\n\n # add all found objects via the predicate to the subject in the graph\n add_to_subject_networkx(nx_graph, subject[0], subject[1], temp_predicates, temp_p_ids,\n temp_objects, temp_o_ids, directions)\n\n # if the amount of visited nodes are bigger than max_nodes => stop\n if len(visited) >= max_nodes:\n all_paths_exhausted = False\n break\n\n\n next_subject = temp_next_subjects\n\n # if the amount of visited nodes + the amount of nodes that are next in the queue are bigger than max_nodes => stop\n if len(visited)+len(next_subject) >= max_nodes:\n all_paths_exhausted = False\n break\n\n total_time = time.time() - total_time\n if printouts == True:\n print(\"\\n[local graph] Total time needed: \" + '{0:.2f}'.format(float(total_time)/60) + \" minutes\")\n\n return total_time, no_hops, len(visited), all_paths_exhausted, len(use_pred_by_id)\n\n\n","sub_path":"project/local_graph.py","file_name":"local_graph.py","file_ext":"py","file_size_in_byte":9527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"551084234","text":"from scipy.stats import skew\nimport pandas as pd\nimport numpy as np\n\ndata = pd.read_csv('data/train.csv')\ndef skewness_log(df):\n sale = df['SalePrice']\n area = df['GrLivArea']\n\n sale = np.log(sale)\n area = np.log(area)\n\n return skew(area), skew(sale)\n\n# Write code here:\n","sub_path":"q03_skewness_log/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"234319654","text":"import os\n\n# Database initialization\nif os.environ.get('DATABASE_URL') is None:\n basedir = os.path.abspath(os.path.dirname(__file__))\n SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')\n # id de l'app TEST\n FB_APP_ID = 2097060923780902\nelse:\n SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'].replace('postgres://', 'postgresql://')\n FB_APP_ID = 869310400439313\n\nSECRET_KEY = \"fbjgleoqq6g^z3=+(7x4&by=xl&nuf)z=y-aujb)#81h16vodooq++jgfb\"\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"459763581","text":"\"Utility functions and classes useful within the DDS.\"\n\n####################################################################################################\n# IMPORTS ################################################################################ IMPORTS #\n####################################################################################################\n\n# Standard library\nimport datetime\nimport os\nimport re\nimport typing\nimport urllib.parse\nimport time\nimport smtplib\n\n# Installed\nfrom contextlib import contextmanager\nimport flask\nfrom dds_web.errors import (\n AccessDeniedError,\n VersionMismatchError,\n DDSArgumentError,\n NoSuchProjectError,\n MaintenanceOngoingException,\n)\nimport flask_mail\nimport flask_login\nimport werkzeug\nimport sqlalchemy\n\n# # imports related to scheduling\nimport marshmallow\nimport wtforms\n\n\n# Own modules\nfrom dds_web.database import models\nfrom dds_web import auth, mail\nfrom dds_web.version import __version__\n\n####################################################################################################\n# VALIDATORS ########################################################################## VALIDATORS #\n####################################################################################################\n\n# General ################################################################################ General #\n\n\n# Cannot have type hint for return due to models.Project giving circular import\ndef collect_project(project_id: str):\n \"\"\"Get project object from database.\"\"\"\n project = models.Project.query.filter(\n models.Project.public_id == sqlalchemy.func.binary(project_id)\n ).one_or_none()\n if not project:\n raise NoSuchProjectError(project=project_id)\n\n return project\n\n\ndef get_required_item(req: str, obj: werkzeug.datastructures.ImmutableMultiDict = None) -> str:\n \"\"\"Get value from dict.\"\"\"\n error_message = f\"Missing required information: '{req}'\"\n if not obj:\n raise DDSArgumentError(message=error_message)\n\n req_val = obj.get(req)\n if not req_val:\n raise DDSArgumentError(message=error_message)\n\n return req_val\n\n\n# Cannot have type hint for return due to models.Project giving circular import\ndef verify_project_access(project) -> None:\n \"\"\"Verify that current authenticated user has access to project.\"\"\"\n if project not in auth.current_user().projects:\n raise AccessDeniedError(\n message=\"Project access denied.\",\n username=auth.current_user().username,\n project=project.public_id,\n )\n\n\ndef verify_cli_version(version_cli: str = None) -> None:\n \"\"\"Verify that the CLI version in header is compatible with the web version.\"\"\"\n # Verify that version is specified\n if not version_cli:\n raise VersionMismatchError(message=\"No version found in request, cannot proceed.\")\n flask.current_app.logger.info(f\"CLI VERSION: {version_cli}\")\n\n # Split version string up into major, middle, minor\n version_cli_parts = version_cli.split(\".\")\n version_correct_parts = __version__.split(\".\")\n\n # The versions must have the same lengths\n if len(version_cli_parts) != len(version_correct_parts):\n raise VersionMismatchError(message=\"Incompatible version lengths.\")\n\n # Verify that major versions match\n if version_cli_parts[0] != version_correct_parts[0]:\n raise VersionMismatchError\n\n\ndef contains_uppercase(indata):\n \"\"\"Verify that string contains at least one upper case letter.\"\"\"\n if not re.search(\"[A-Z]\", indata):\n raise marshmallow.ValidationError(\"Required: at least one upper case letter.\")\n\n\ndef contains_lowercase(indata):\n \"\"\"Verify that string contains at least one lower case letter.\"\"\"\n if not re.search(\"[a-z]\", indata):\n raise marshmallow.ValidationError(\"Required: at least one lower case letter.\")\n\n\ndef contains_digit_or_specialchar(indata):\n \"\"\"Verify that string contains at least one special character OR digit.\"\"\"\n if not any(re.search(x, indata) for x in [\"[0-9]\", \"[#?!@$%^&*-]\"]):\n raise marshmallow.ValidationError(\n \"Required: at least one digit OR a special character (#?!@$%^&*-).\"\n )\n\n\ndef contains_disallowed_characters(indata):\n \"\"\"Indatas like <9f><98><80> cause issues in Project names etc.\"\"\"\n disallowed = re.findall(r\"[^(\\w\\s)]+\", indata)\n if disallowed:\n disallowed = set(disallowed) # unique values\n chars = \"characters\"\n raise marshmallow.ValidationError(\n f\"The {chars if len(disallowed) > 1 else chars[:-1]} '{' '.join(disallowed)}' within '[italic]{indata}[/italic]' {'are' if len(disallowed) > 1 else 'is'} not allowed.\"\n )\n\n\ndef contains_unicode_emojis(indata):\n \"\"\"Find unicode emojis in string - cause SQLAlchemyErrors.\"\"\"\n # Ref: https://gist.github.com/Alex-Just/e86110836f3f93fe7932290526529cd1#gistcomment-3208085\n # Ref: https://en.wikipedia.org/wiki/Unicode_block\n EMOJI_PATTERN = re.compile(\n \"([\"\n \"\\U0001F1E0-\\U0001F1FF\" # flags (iOS)\n \"\\U0001F300-\\U0001F5FF\" # symbols & pictographs\n \"\\U0001F600-\\U0001F64F\" # emoticons\n \"\\U0001F680-\\U0001F6FF\" # transport & map symbols\n \"\\U0001F700-\\U0001F77F\" # alchemical symbols\n \"\\U0001F780-\\U0001F7FF\" # Geometric Shapes Extended\n \"\\U0001F800-\\U0001F8FF\" # Supplemental Arrows-C\n \"\\U0001F900-\\U0001F9FF\" # Supplemental Symbols and Pictographs\n \"\\U0001FA00-\\U0001FA6F\" # Chess Symbols\n \"\\U0001FA70-\\U0001FAFF\" # Symbols and Pictographs Extended-A\n \"\\U00002702-\\U000027B0\" # Dingbats\n \"])\"\n )\n emojis = re.findall(EMOJI_PATTERN, indata)\n if emojis:\n raise marshmallow.ValidationError(f\"This input is not allowed: {''.join(emojis)}\")\n\n\ndef email_not_taken(indata):\n \"\"\"Validator - verify that email is not taken.\n\n If used by marshmallow Schema, this validator should never raise an error since the email\n field should not be changable and if it is the form validator should catch it.\n \"\"\"\n if email_in_db(email=indata):\n raise marshmallow.validate.ValidationError(\"The email is already taken by another user.\")\n\n\ndef email_taken(indata):\n \"\"\"Validator - verify that email is taken.\"\"\"\n if not email_in_db(email=indata):\n raise marshmallow.validate.ValidationError(\n \"If the email is connected to a user within the DDS, you should receive an email with the password reset instructions.\"\n )\n\n\ndef username_not_taken(indata):\n \"\"\"Validate that username is not taken.\n\n If used by marshmallow Schema, this validator should never raise an error since\n the form validator should catch it.\n \"\"\"\n if username_in_db(username=indata):\n raise marshmallow.validate.ValidationError(\n \"That username is taken. Please choose a different one.\"\n )\n\n\ndef valid_user_role(specified_role):\n \"\"\"Returns whether or not a role is valid in the DDS.\"\"\"\n return specified_role in [\n \"Super Admin\",\n \"Unit Admin\",\n \"Unit Personnel\",\n \"Project Owner\",\n \"Researcher\",\n ]\n\n\n# wtforms ################################################################################ wtforms #\n\n\ndef username_contains_valid_characters():\n def _username_contains_valid_characters(form, field):\n \"\"\"Validate that the username contains valid characters.\"\"\"\n if not valid_chars_in_username(indata=field.data):\n raise wtforms.validators.ValidationError(\n \"The username contains invalid characters. \"\n \"Usernames can only contain letters, digits and underscores (_).\"\n )\n\n return _username_contains_valid_characters\n\n\ndef password_contains_valid_characters():\n def _password_contains_valid_characters(form, field):\n \"\"\"Validate that the password contains valid characters and raise ValidationError.\"\"\"\n errors = []\n validators = [\n contains_uppercase,\n contains_lowercase,\n contains_digit_or_specialchar,\n ]\n for val in validators:\n try:\n val(indata=field.data)\n except marshmallow.ValidationError as valerr:\n errors.append(str(valerr).strip(\".\"))\n\n if errors:\n raise wtforms.validators.ValidationError(\", \".join(errors))\n\n return _password_contains_valid_characters\n\n\ndef username_not_taken_wtforms():\n def _username_not_taken(form, field):\n \"\"\"Validate that the username is not taken already.\"\"\"\n try:\n username_not_taken(indata=field.data)\n except marshmallow.validate.ValidationError as valerr:\n raise wtforms.validators.ValidationError(valerr)\n\n return _username_not_taken\n\n\ndef email_not_taken_wtforms():\n def _email_not_taken(form, field):\n \"\"\"Validate that the email is not taken already.\"\"\"\n try:\n email_not_taken(indata=field.data)\n except marshmallow.validate.ValidationError as valerr:\n raise wtforms.validators.ValidationError(valerr)\n\n return _email_not_taken\n\n\ndef email_taken_wtforms():\n def _email_taken(form, field):\n \"\"\"Validate that the email exists.\"\"\"\n try:\n email_taken(indata=field.data)\n except marshmallow.validate.ValidationError as valerr:\n raise wtforms.validators.ValidationError(valerr)\n\n return _email_taken\n\n\n####################################################################################################\n# FUNCTIONS ############################################################################ FUNCTIONS #\n####################################################################################################\n\n\ndef verify_enough_unit_admins(unit_id: str, force_create: bool = False):\n \"\"\"Verify that the unit has enough Unit Admins.\"\"\"\n num_admins = models.UnitUser.query.filter_by(is_admin=True, unit_id=unit_id).count()\n if num_admins < 2:\n raise AccessDeniedError(\n message=(\n \"Your unit does not have enough Unit Admins. \"\n \"At least two Unit Admins are required for a project to be created.\"\n )\n )\n\n if num_admins < 3 and not force_create:\n return (\n f\"Your unit only has {num_admins} Unit Admins. This poses a high risk of data loss. \"\n \"We HIGHLY recommend that you do not create this project until there are more Unit \"\n \"Admins connected to your unit.\"\n )\n\n\ndef valid_chars_in_username(indata):\n \"\"\"Check if the username contains only valid characters.\"\"\"\n return bool(re.search(r\"^[a-zA-Z0-9_\\.-]+$\", indata))\n\n\ndef email_in_db(email):\n \"\"\"Check if the email is in the Email table.\"\"\"\n if models.Email.query.filter_by(email=email).first():\n return True\n\n return False\n\n\ndef username_in_db(username):\n \"\"\"Check if username is in the User table.\"\"\"\n if models.User.query.filter_by(username=username).first():\n return True\n\n return False\n\n\ndef get_username_or_request_ip():\n \"\"\"Util function for action logger: Try to identify the requester\"\"\"\n\n if auth.current_user():\n current_user = auth.current_user().username\n elif flask_login.current_user.is_authenticated:\n current_user = flask_login.current_user.username\n else:\n username = (\n flask.request.authorization.get(\"username\") if flask.request.authorization else \"---\"\n )\n if flask.request.remote_addr:\n current_user = f\"{username} ({flask.request.remote_addr})\" # log IP instead of username\n elif flask.request.access_route:\n current_user = (\n f\"{username} ({flask.request.access_route[0]})\" # log IP instead of username\n )\n else:\n current_user = f\"{username} (anonymous)\"\n\n return current_user\n\n\ndef delrequest_exists(email):\n \"\"\"Check if there is already a deletion request for that email.\"\"\"\n if models.DeletionRequest.query.filter_by(email=email).first():\n return True\n return False\n\n\ndef send_reset_email(email_row, token):\n \"\"\"Generate password reset email.\"\"\"\n msg = flask_mail.Message(\n \"WARNING! Password Reset Request for SciLifeLab Data Delivery System\",\n recipients=[email_row.email],\n )\n\n # Need to attach the image to be able to use it\n msg.attach(\n \"scilifelab_logo.png\",\n \"image/png\",\n open(os.path.join(flask.current_app.static_folder, \"img/scilifelab_logo.png\"), \"rb\").read(),\n \"inline\",\n headers=[\n [\"Content-ID\", \"\"],\n ],\n )\n\n link = flask.url_for(\"auth_blueprint.reset_password\", token=token, _external=True)\n msg.body = flask.render_template(\"mail/password_reset.txt\", link=link)\n msg.html = flask.render_template(\"mail/password_reset.html\", link=link)\n\n mail.send(msg)\n\n\ndef send_project_access_reset_email(email_row, email, token):\n \"\"\"Generate password reset email.\"\"\"\n msg = flask_mail.Message(\n \"WARNING! A Unit Admin has lost access\",\n recipients=[email_row.email],\n )\n\n # Need to attach the image to be able to use it\n msg.attach(\n \"scilifelab_logo.png\",\n \"image/png\",\n open(os.path.join(flask.current_app.static_folder, \"img/scilifelab_logo.png\"), \"rb\").read(),\n \"inline\",\n headers=[\n [\"Content-ID\", \"\"],\n ],\n )\n\n msg.body = flask.render_template(\"mail/project_access_reset.txt\", email=email)\n msg.html = flask.render_template(\"mail/project_access_reset.html\", email=email)\n\n mail.send(msg)\n\n\ndef is_safe_url(target):\n \"\"\"Check if the url is safe for redirects.\"\"\"\n ref_url = urllib.parse.urlparse(flask.request.host_url)\n test_url = urllib.parse.urlparse(urllib.parse.urljoin(flask.request.host_url, target))\n return test_url.scheme in (\"http\", \"https\") and ref_url.netloc == test_url.netloc\n\n\ndef current_time(to_midnight=False):\n \"\"\"Return the current time for UTC\"\"\"\n\n curr_time = datetime.datetime.utcnow()\n if to_midnight:\n curr_time = curr_time.replace(hour=23, minute=59, second=59)\n\n return curr_time\n\n\ndef timestamp(dts=None, datetime_string=None, ts_format=\"%Y-%m-%d %H:%M:%S.%f\"):\n \"\"\"Gets the current time. Formats timestamp.\n\n Returns:\n str: Timestamp in format 'YY-MM-DD_HH-MM-SS'\n\n \"\"\"\n if datetime_string is not None:\n datetime_stamp = datetime.datetime.strptime(datetime_string, ts_format)\n return str(datetime_stamp.date())\n\n now = current_time() if dts is None else dts\n t_s = str(now.strftime(ts_format))\n return t_s\n\n\ndef rate_limit_from_config():\n return flask.current_app.config.get(\"TOKEN_ENDPOINT_ACCESS_LIMIT\", \"10/hour\")\n\n\n@contextmanager\ndef working_directory(path):\n \"\"\"Contexter for changing working directory\"\"\"\n current_path = os.getcwd()\n try:\n if not os.path.exists(path):\n os.mkdir(path)\n os.chdir(path)\n yield\n finally:\n os.chdir(current_path)\n\n\ndef page_query(q):\n offset = 0\n while True:\n r = False\n for elem in q.limit(1000).offset(offset):\n r = True\n yield elem\n offset += 1000\n if not r:\n break\n\n\ndef send_email_with_retry(msg, times_retried=0, obj=None):\n \"\"\"Send email with retry on exception\"\"\"\n if obj is None:\n obj = mail\n try:\n obj.send(msg)\n except smtplib.SMTPException as err:\n # Wait a little bit\n time.sleep(10)\n # Retry twice\n if times_retried < 2:\n retry = times_retried + 1\n send_email_with_retry(msg, times_retried=retry, obj=obj)\n\n\ndef create_one_time_password_email(user, hotp_value):\n \"\"\"Create HOTP email.\"\"\"\n msg = flask_mail.Message(\n \"DDS One-Time Authentication Code\",\n recipients=[user.primary_email],\n )\n\n msg.attach(\n \"scilifelab_logo.png\",\n \"image/png\",\n open(os.path.join(flask.current_app.static_folder, \"img/scilifelab_logo.png\"), \"rb\").read(),\n \"inline\",\n headers=[\n [\"Content-ID\", \"\"],\n ],\n )\n msg.body = flask.render_template(\n \"mail/authenticate.txt\", one_time_value=hotp_value.decode(\"utf-8\")\n )\n msg.html = flask.render_template(\n \"mail/authenticate.html\", one_time_value=hotp_value.decode(\"utf-8\")\n )\n\n return msg\n\n\ndef bucket_is_valid(bucket_name):\n \"\"\"Verify that the bucket name is valid.\"\"\"\n valid = False\n message = \"\"\n if not (3 <= len(bucket_name) <= 63):\n message = f\"The bucket name has the incorrect length {len(bucket_name)}\"\n elif re.findall(r\"[^a-zA-Z0-9.-]\", bucket_name):\n message = \"The bucket name contains invalid characters.\"\n elif not bucket_name[0].isalnum():\n message = \"The bucket name must begin with a letter or number.\"\n elif bucket_name.count(\".\") > 2:\n message = \"The bucket name cannot contain more than two dots.\"\n elif bucket_name.startswith(\"xn--\"):\n message = \"The bucket name cannot begin with the 'xn--' prefix.\"\n elif bucket_name.endswith(\"-s3alias\"):\n message = \"The bucket name cannot end with the '-s3alias' suffix.\"\n else:\n valid = True\n return valid, message\n\n\ndef get_active_motds():\n \"\"\"Return latest MOTD.\"\"\"\n motds_active = (\n models.MOTD.query.filter_by(active=True).order_by(models.MOTD.date_created.desc()).all()\n )\n return motds_active or None\n\n\ndef calculate_bytehours(\n minuend: datetime.datetime, subtrahend: datetime.datetime, size_bytes: int\n) -> float:\n \"\"\"Calculate byte hours.\"\"\"\n # Calculate the time difference as timedelta\n time_diff_timedelta = minuend - subtrahend\n\n # Convert the timedelta to hours\n hours_stored = time_diff_timedelta.total_seconds() / (60 * 60)\n\n # Calculate the bytehours\n bytehours = hours_stored * size_bytes\n\n return bytehours\n\n\ndef calculate_version_period_usage(version):\n bytehours: int = 0\n if not version.time_deleted and version.time_invoiced:\n # Existing and invoiced version\n now = current_time()\n bytehours = calculate_bytehours(\n minuend=now, subtrahend=version.time_invoiced, size_bytes=version.size_stored\n )\n version.time_invoiced = now\n elif version.time_deleted and not version.time_invoiced:\n # Version uploaded >and< deleted after last usage calculation\n bytehours = calculate_bytehours(\n minuend=version.time_deleted,\n subtrahend=version.time_uploaded,\n size_bytes=version.size_stored,\n )\n version.time_invoiced = version.time_deleted\n elif version.time_deleted != version.time_invoiced:\n # Version has been deleted after last usage calculation\n # (if version.time_deleted > version.time_invoiced)\n bytehours = calculate_bytehours(\n minuend=version.time_deleted,\n subtrahend=version.time_invoiced,\n size_bytes=version.size_stored,\n )\n version.time_invoiced = version.time_deleted\n elif not version.time_deleted and not version.time_invoiced:\n # New version: uploaded after last usage calculation\n now = current_time()\n bytehours = calculate_bytehours(\n minuend=now, subtrahend=version.time_uploaded, size_bytes=version.size_stored\n )\n version.time_invoiced = now\n\n return bytehours\n\n\n# maintenance check\ndef block_if_maintenance(user=None):\n \"\"\"Block API requests if maintenance is ongoing and projects are busy.\"\"\"\n # Get maintenance row\n maintenance: models.Maintenance = models.Maintenance.query.first()\n\n # Possibly block request if maintenance ongoing / planned\n if maintenance.active:\n if not user:\n # Endpoints accepting requests during active maintenance - only login for non-logged in users\n admin_endpoints: typing.List = [\n \"/api/v1/user/encrypted_token\",\n \"/api/v1/user/second_factor\",\n ]\n\n # Request not to accepted endpoint\n # OR request to accepted endpoint but project not specified or busy\n current_endpoint: str = flask.request.path\n if current_endpoint not in admin_endpoints:\n # Request not accepted during maintenance\n raise MaintenanceOngoingException()\n else:\n if user.role != \"Super Admin\":\n raise MaintenanceOngoingException()\n","sub_path":"dds_web/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":20530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"290176288","text":"import requests\nimport time\nimport random\n\n\ndef fflash(wx_session):\n try:\n url = 'https://qr.chinaums.com/netpay-mer-portal/merchant/queryBills.do'\n wx_session = wx_session\n # print(wx_session)\n headers = {\n 'Host': 'qr.chinaums.com',\n 'Connection': 'keep-alive',\n 'Content-Length': '89',\n 'Accept': 'application/json, text/javascript, */*; q=0.01',\n 'Origin': 'https://qr.chinaums.com',\n 'X-Requested-With': 'XMLHttpRequest',\n 'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0.1; MI NOTE LTE Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/6.2 TBS/043906 Mobile Safari/537.36 MicroMessenger/6.6.1.1220(0x26060135) NetType/WIFI Language/zh_CN',\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'Referer': 'https://qr.chinaums.com/netpay-mer-portal/merchant/merAuth.do',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,en-US;q=0.8',\n 'Cookie': 'SESSION=%s; route=ff7ccc9ac07719e8e706ebafb1588dfa; JSESSIONID=0doJ-707FwJx2fGA7Fbf8Fse3cQTQYth1_NpUDuVlw_teeQf_cnj!-1058374088' % (\n wx_session)\n }\n # year = billDate.split('-')[0]\n # month = billDate.split('-')[1]\n # day = billDate.split('-')[2]\n # reqmid = session['reqmid']\n # print('1a1a', reqmid)\n data = {\n 'reqMid': '898352254990101',\n 'pageSize': '15',\n 'curPage': '1',\n 'billDate': '2018年07月04日'\n }\n # print(data)\n html = requests.post(url, headers=headers, data=data)\n # print(html)\n except BaseException as e:\n print(e)\n return '0000'\n\n\ndef run():\n session_list = ['26710055-0662-4a35-b49b-ff1da810b433', 'e11b3d1b-05f3-4f49-8e74-d2c86fba068c', \\\n '0e3fe945-4391-4ba2-bdbe-399b9aad1e00', '27a696ea-1780-4c04-93ec-bd2ecf29e0e0', \\\n 'a36ff750-865d-431d-b543-2e39c92491f4', 'f69c053d-94a2-4c32-aa17-9703db06d9d2', \\\n 'c0a00b1a-829e-4099-ade0-d64afeb3d2bf', 'a5b704ed-e444-43ab-8f29-b51c618a51ea', \\\n 'aa23815d-a216-4b00-86ca-052df67f38da'\n ]\n for each in session_list:\n fflash(wx_session=each)\n time.sleep(1.41)\n print(each)\n\n\nwhile 1:\n time.sleep(5)\n run()\n sleep_time = random.uniform(30, 65)\n time.sleep(sleep_time)\n","sub_path":"speedpos/pos_api/keep_sess.py","file_name":"keep_sess.py","file_ext":"py","file_size_in_byte":2515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"221585973","text":"import itertools\n# Devide the whole string into 111 000 11 000000 1111..\n# The strings we want to count must be locating between two groups.\n# The number of such strings between to groups is min(len1, len2)\n# For example, 0001111 or 1110000 has 3 valid substrings.\nclass Solution(object):\n def countBinarySubstrings(self, s):\n groups = [len(list(v)) for _, v in itertools.groupby(s)]\n return sum(min(a, b) for a, b in zip(groups, groups[1:]))\n\n\n# Improvement, space O(1)\n# Do not store the whole group array\n# Only store prev and cur\nclass Solution:\n def countBinarySubstrings(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n prev, cur, result = 0, 1, 0\n for i in range(1, len(s)):\n if s[i] != s[i - 1]:\n result += min(prev, cur)\n prev = cur\n cur = 1\n else:\n cur += 1\n result += min(prev, cur)\n return result\n\n","sub_path":"696 Count Binary Substrings.py","file_name":"696 Count Binary Substrings.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"85032952","text":"import turtle\nimport time\nimport connections\n\ntshaper= turtle.Turtle()\n\nturtle.addshape(\"o.gif\")\nturtle.addshape(\"x.gif\")\n\nt1 = turtle.Turtle(\"o.gif\")\nt2 = turtle.Turtle(\"x.gif\")\nt1.hideturtle()\nt2.hideturtle()\nt1.penup()\nt2.penup()\n\nt1.speed(3)\n\nsel =[0,0,0,0,0,0,0,0,0,0]\n\ndef sqrdraw(a):\n for i in range(4):\n tshaper.fd(a)\n tshaper.lt(90)\ndef drawrow():\n tshaper.pendown()\n for i in range(3):\n sqrdraw(200)\n tshaper.fd(200)\n tshaper.penup()\n\ntshaper.speed(100)\ndef drawfield():\n tshaper.penup()\n tshaper.goto(-300, -300)\n tshaper.pendown()\n sqrdraw(600)\n drawrow()\n for i in [-100 , 100]:\n tshaper.goto(-300,i)\n drawrow()\n tshaper.penup()\n\n #coordinates\n tshaper.goto(-200,200)\n tshaper.write(\"1\")\n tshaper.goto(0,200)\n tshaper.write(\"2\")\n tshaper.goto(200,200)\n tshaper.write(\"3\")\n tshaper.goto(-200,0)\n tshaper.write(\"4\")\n tshaper.goto(0,0)\n tshaper.write(\"5\")\n tshaper.goto(200,0)\n tshaper.write(\"6\")\n tshaper.goto(-200,-200)\n tshaper.write(\"7\")\n tshaper.goto(0,-200)\n tshaper.write(\"8\")\n tshaper.goto(200,-200)\n tshaper.write(\"9\")\n tshaper.hideturtle()\n\n\ndef init():\n drawfield()\n print(\"\")\n print(\" ██████╗ ███╗ ██╗██╗ ██╗███╗ ██╗███████╗ ████████╗██╗ ██╗██████╗ ████████╗██╗ ███████╗ ██████╗ █████╗ ███╗ ███╗███████╗\")\n time.sleep(0.05)\n print(\"██╔═══██╗████╗ ██║██║ ██║████╗ ██║██╔════╝ ╚══██╔══╝██║ ██║██╔══██╗╚══██╔══╝██║ ██╔════╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝\")\n time.sleep(0.05)\n print(\"██║ ██║██╔██╗ ██║██║ ██║██╔██╗ ██║█████╗ ██║ ██║ ██║██████╔╝ ██║ ██║ █████╗ ██║ ███╗███████║██╔████╔██║█████╗ \")\n time.sleep(0.05)\n print(\"██║ ██║██║╚██╗██║██║ ██║██║╚██╗██║██╔══╝ ██║ ██║ ██║██╔══██╗ ██║ ██║ ██╔══╝ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝ \")\n time.sleep(0.05)\n print(\"╚██████╔╝██║ ╚████║███████╗██║██║ ╚████║███████╗ ██║ ╚██████╔╝██║ ██║ ██║ ███████╗███████╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗\")\n time.sleep(0.05)\n print(\"\")\n print(\" By Mobile System Engineering 32190984 김이수\")\n print(\" Ver. 0.1\")\n\n\ndef mycommand(command):\n t1.hideturtle()\n if sel[command] == 0:\n if command == 1:\n t1.goto(-200,200)\n t1.showturtle()\n t1.stamp()\n t1.hideturtle()\n sel[command] = 1\n connections.sendcord(str(command))\n\n if command == 2:\n t1.goto(0,200)\n t1.showturtle()\n t1.stamp()\n t1.hideturtle()\n sel[command] = 1\n connections.sendcord(str(command))\n\n if command == 3:\n t1.goto(200,200)\n t1.showturtle()\n t1.stamp()\n t1.hideturtle()\n sel[command] = 1\n connections.sendcord(str(command))\n\n if command == 4:\n t1.goto(-200,0)\n t1.showturtle()\n t1.stamp()\n t1.hideturtle()\n sel[command] = 1\n connections.sendcord(str(command))\n\n if command == 5:\n t1.goto(0,0)\n t1.showturtle()\n t1.stamp()\n t1.hideturtle()\n sel[command] = 1\n connections.sendcord(str(command))\n\n if command == 6:\n t1.goto(200,0)\n t1.showturtle()\n t1.stamp()\n t1.hideturtle()\n sel[command] = 1\n connections.sendcord(str(command))\n\n if command == 7:\n t1.goto(-200,-200)\n t1.showturtle()\n t1.stamp()\n t1.hideturtle()\n sel[command] = 1\n connections.sendcord(str(command))\n\n if command == 8:\n t1.goto(0,-200)\n t1.showturtle()\n t1.stamp()\n t1.hideturtle()\n sel[command] = 1\n connections.sendcord(str(command))\n\n if command == 9:\n t1.goto(200,-200)\n t1.showturtle()\n t1.stamp()\n t1.hideturtle()\n sel[command] = 1\n connections.sendcord(str(command))\n\n else:\n print(\"Already Selected\")\n getcommandagain()\n\ndef foecommand(command):\n t2.hideturtle()\n if command == 1:\n t2.goto(-200,200)\n t2.showturtle()\n t2.stamp()\n t2.hideturtle()\n sel[foecord] = 1\n\n if command == 2:\n t2.goto(0,200)\n t2.showturtle()\n t2.stamp()\n t2.hideturtle()\n sel[foecord] = 1\n\n if command == 3:\n t2.goto(200,200)\n t2.showturtle()\n t2.stamp()\n t2.hideturtle()\n sel[foecord] = 1\n\n if command == 4:\n t2.goto(-200,0)\n t2.showturtle()\n t2.stamp()\n t2.hideturtle()\n sel[foecord] = 1\n\n if command == 5:\n t2.goto(0,0)\n t2.showturtle()\n t2.stamp()\n t2.hideturtle()\n sel[foecord] = 1\n\n if command == 6:\n t2.goto(200,0)\n t2.showturtle()\n t2.stamp()\n t2.hideturtle()\n sel[foecord] = 1\n\n if command == 7:\n t2.goto(-200,-200)\n t2.showturtle()\n t2.stamp()\n t2.hideturtle()\n sel[foecord] = 1\n\n if command == 8:\n t2.goto(0,-200)\n t2.showturtle()\n t2.stamp()\n t2.hideturtle()\n sel[foecord] = 1\n\n if command == 9:\n t2.goto(200,-200)\n t2.showturtle()\n t2.stamp()\n t2.hideturtle()\n sel[foecord] = 1\n\n\ndef getcommandagain():\n cmd = turtle.textinput(str(name + \"\\'s turn\"),\"Coordinate\")\n if (cmd != '') :\n command = int(cmd)\n if (command > 0 and command < 10):\n mycommand(command)\n else :\n getcommandagain()\n else:\n getcommandagain()\n\ninit()\nprint(\"\")\nglobal name\nglobal friendname\nname = turtle.textinput(\"3-Mok Online\" , \"Name :\")\n\nconnections.Allinit()\n\nfor i in range (7):\n getcommandagain()\n foecord = connections.getcord()\n foecommand(foecord)\n\ngetcommandagain()\n\n\n\ntime.sleep(10)\n\n\n\n\n\n\n\n\n#connections.init()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"329669614","text":"from setuptools import setup, find_packages\n\n\ndef read(filename):\n return [\n req.strip() for req in open(filename).readlines()\n ]\n\n\nsetup(\n name=\"Brasil Prev\",\n version=\"1.0.0\",\n description=\"Sistema teste Brasil Prev\",\n packages=find_packages(),\n include_package_data=True,\n install_requires=read(\"requirements.txt\")\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"580533768","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url('login$', views.login, name='login'),\n url('regist$', views.regist, name='regist'),\n url('loginView$', views.loginView, name='loginView'),\n url('registView$', views.registView, name='registView'),\n]\n","sub_path":"admin/main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"135408054","text":"import numpy as np\nimport Euler as E\nimport numpy.linalg as nl\nimport EulerBackProp as EBP\n\ndef ObjFuncAndBackProp(M, h, K, Y0, sigma, eta, C, W):\n #Forward model\n YM, sigma_list, Y_list = EBP.EulerBackProp(M, h, K, Y0, sigma)\n projv = eta(np.dot(YM, W))\n error = (1/2)*nl.norm(projv - C)**2\n\n #Backpropagation\n #deriv. w.r.t. W\n dW = np.dot(YM.T, ((projv - C) * projv * (1 - projv))) # * is elementwise (hadamard) operation\n\n #deriv. w.r.t. YM\n dYM = np.array(np.matrix((projv - C) * projv * (1 - projv)).T * np.matrix(W.T)) # * is elementwise (hadamard) operation\n\n #deriv. w.r.t. the different K_m\n #Starting with dYM as first upstream derivative we pass the gradient through the computational graph\n dJ = np.zeros((M, 4, 4))\n dY_upstream = dYM\n for i in range(len(Y_list)-2, -1, -1):\n dJ[i] = Y_list[i].T.dot(h * (1 - sigma_list[i] ** 2) * dY_upstream)\n dY_upstream = np.dot((h * (1 - sigma_list[i] ** 2) * dY_upstream), K[i].T) + dY_upstream\n return error, dJ, dW\n","sub_path":"Project2/ObjFuncBackProp.py","file_name":"ObjFuncBackProp.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"194357390","text":"from pymongo import MongoClient\nimport requests, datetime, pprint\n\nclassmate_one = requests.get('https://api.github.com/users/AJStrizzy').json()\nclassmate_two = requests.get('https://api.github.com/users/JaxonNarramore').json()\nclassmate_three = requests.get('https://api.github.com/users/alanavery').json()\nclassmate_four = requests.get('https://api.github.com/users/sschneeberg').json()\nclassmate_five = requests.get('https://api.github.com/users/zfinnan').json()\n\nobj_one = {\n 'name': classmate_one.get('name'),\n 'login': classmate_one.get('login'),\n 'location': classmate_one.get('location'),\n 'company': classmate_one.get('company'),\n 'bio': classmate_one.get('bio')\n}\n\nobj_two = {\n 'name': classmate_two.get('name'),\n 'login': classmate_two.get('login'),\n 'location': classmate_two.get('location'),\n 'company': classmate_two.get('company'),\n 'bio': classmate_two.get('bio')\n}\n\nobj_three = {\n 'name': classmate_three.get('name'),\n 'login': classmate_three.get('login'),\n 'location': classmate_three.get('location'),\n 'company': classmate_three.get('company'),\n 'bio': classmate_three.get('bio')\n}\n\nobj_four = {\n 'name': classmate_four.get('name'),\n 'login': classmate_four.get('login'),\n 'location': classmate_four.get('location'),\n 'company': classmate_four.get('company'),\n 'bio': classmate_four.get('bio')\n}\n\nobj_five = {\n 'name': classmate_five.get('name'),\n 'login': classmate_five.get('login'),\n 'location': classmate_five.get('location'),\n 'company': classmate_five.get('company'),\n 'bio': classmate_five.get('bio')\n}\n\nprint(obj_one)\nprint(obj_two)\nprint(obj_three)\nprint(obj_four)\nprint(obj_five)","sub_path":"github.py","file_name":"github.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"372651751","text":"#!/usr/bin/env python3\n\n'''aionfpga ~ throw analysis\nCopyright (C) 2020 Dominik Müller and Nico Canzani\n'''\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\nimport fhnwtoys.training as fh\n\nrows = fh.fetch_all_rows(fh.tab_frames)\n\nnofs = list() # number of frames of each throw\n\nfid = 1\nnof = 0\nfor row in rows:\n if row[2] == fid:\n nof += 1\n else:\n nofs.append(nof)\n # print(nofs)\n nof = 1\n fid += 1\nnofs.append(nof)\n\n# print(max(nofs))\n# print(len(nofs))\n# print(sum(nofs))\n\nx1 = range(1, max(nofs) + 1)\nx2 = range(1, max(nofs) + 2)\n\nhist, _ = np.histogram(nofs, bins=max(nofs))\ncumsum = np.cumsum(hist) / len(nofs)\ncumsum = [0,] + list(cumsum)\n\n# print(list(hist))\n# print(cumsum)\n\nfig, ax = plt.subplots(figsize=[8, 4])\nax.bar(x1, hist)\n\nplt.xticks([t+1 for t in range(max(nofs)) if t%9 == 0])\n\nplt.xlabel('Number of Frames $x$')\nplt.ylabel('Number of Throws')\n\nplt.savefig('distribution.pdf', transparent=True, bbox_inches='tight')\n\n# --------------------------------------------\n\nfig, ax = plt.subplots(figsize=[8, 4])\nax.step(x2, cumsum)\n\nbottom, top = plt.ylim()\nplt.ylim(0, top)\n\nplt.autoscale(False)\n\nax.hlines(0.8, -5, 22, colors='gray', ls='--', lw=1)\nax.vlines(22, 0, 0.8,colors='gray', ls='--', lw=1)\n\nplt.xticks([t+1 for t in range(max(nofs)) if t%9 == 0 or t == 21])\n\nplt.xlabel('Number of Frames $x$')\nplt.ylabel('Probability')\n\nplt.savefig('cumulative_distribution.pdf', transparent=True, bbox_inches='tight')\n\nplt.show()\n","sub_path":"doc/thesis/graphics/originals/throw_analysis.py","file_name":"throw_analysis.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"178955079","text":"n = int(input())\narr = [int(a) for a in input().split()]\n\nsumm = sum(arr)\nans = 0\nfor i in range(n-1):\n a = arr[i]\n summ -= arr[i]\n b = summ\n ans += (a*b)%(int(1e9+7))\n\nprint(ans%(int(1e9+7)))","sub_path":"atcoder/abc 177-c/abc 177 c.py","file_name":"abc 177 c.py","file_ext":"py","file_size_in_byte":204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"270674572","text":"import re\nfrom datetime import datetime\nimport subprocess\nimport shlex\nimport urllib\n\nfilepath = '/Users/Alex/Desktop/newlog.txt'\ntemp = []\n\n\ndef make_params(line):\n params = {}\n for m in range(len(line)):\n o = re.split(\"=\", line[m])\n params.update({o[0]:o[1]})\n return params\n\n\ndef parse_lines(lines, response):\n for l in lines:\n if l:\n line = re.split(\" \", l)\n request = re.split(\"\\?\", line[7])\n request[1] = urllib.unquote(request[1]).decode(\"utf8\")\n e = re.split(\"&\", request[1])\n pur_time = str(datetime.strptime(line[3], '[%d/%b/%Y:%H:%M:%S'))\n line2 = ''.join(line)\n iu = re.split(\"req_time=\", line2)\n uy = re.split(\"\\]\\[\", iu[1])\n response.append({\n 'time': uy[0],\n \"status\": line[9],\n \"date\": pur_time,\n \"params\": make_params(e),\n \"method_type\": request[0],\n \"original_req\": 'http://sailplay.ru%s' % line[7],\n })\n\n\ndef parse(some_dict):\n response = []\n if \"methods\" in some_dict:\n for dep_id in some_dict['department_id']:\n for method in some_dict['methods']:\n command1 = subprocess.Popen(shlex.split('grep -m 10000 store_department_id=%s& %s' % (dep_id, filepath)),\n stdout=subprocess.PIPE)\n command2 = subprocess.Popen(shlex.split('grep %s' % method), stdin=command1.stdout,\n stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()[0]\n lines = command2.split(\"\\n\")\n parse_lines(lines, response)\n return response\n\n else:\n for dep_id in some_dict[\"department_id\"]:\n command = subprocess.Popen(shlex.split('grep -m 10000 store_department_id=%s& %s' % (dep_id, filepath)),\n stdout=subprocess.PIPE).communicate()[0]\n lines = command.split(\"\\n\")\n parse_lines(lines, response)\n return response\n","sub_path":"transactions/helpers/logparser.py","file_name":"logparser.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"491352083","text":"from cms.plugin_base import CMSPluginBase\nfrom cms.plugin_pool import plugin_pool\n\nfrom glad_plugins.models import GladImageZoomPlugin\n\nclass glad_image_zoom(CMSPluginBase):\n render_template = \"glad_plugins/glad_image_zoom.html\"\n module = 'glad_plugins'\n model = GladImageZoomPlugin\n name = 'Маштабируемое изображение'\n\n def render(self, context, instance, placeholder):\n context.update({'instance':instance})\n return context\n\nplugin_pool.register_plugin(glad_image_zoom)","sub_path":"glad_plugins/cms_plugins/GladImageZoom.py","file_name":"GladImageZoom.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"13369757","text":"import sys\n\n\ndef sol():\n # sys.stdin = open(\"./18808/input.txt\")\n input = sys.stdin.readline\n N, M, K = map(int, input().split())\n stickers = []\n for _ in range(K):\n r, c = map(int, input().split())\n sticker = [list(map(int, input().split())) for _ in range(r)]\n stickers.append((r, c, sticker))\n paper = [[0] * M for _ in range(N)]\n for R, C, sticker in stickers:\n degree = 0\n cur_R, cur_C = R, C\n while degree < 4:\n result, target_r, target_c = match(N, M, paper, cur_R, cur_C, sticker)\n if result:\n fill(target_r, target_c, paper, cur_R, cur_C, sticker)\n break\n cur_R, cur_C, sticker = rotate(cur_R, cur_C, sticker)\n degree += 1\n print(sum([sum(row) for row in paper]))\n\n\ndef match(N, M, paper, R, C, sticker):\n if R > N or C > M:\n return False, None, None\n for r in range(N - R + 1):\n for c in range(M - C + 1):\n tmp = True\n for cur_r in range(R):\n for cur_c in range(C):\n if (\n tmp\n and sticker[cur_r][cur_c] == 1\n and paper[r + cur_r][c + cur_c] == 1\n ):\n tmp = False\n break\n if tmp:\n return True, r, c\n return False, None, None\n\n\ndef fill(N, M, paper, R, C, sticker):\n for r in range(R):\n for c in range(C):\n if sticker[r][c] == 1:\n paper[r + N][c + M] = sticker[r][c]\n\n\ndef rotate(r, c, sticker):\n # rotate -90 degrees\n return c, r, list(zip(*sticker[::-1]))\n\n\nif __name__ == \"__main__\":\n sol()\n","sub_path":"18808/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"308279012","text":"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport unittest\n\nfrom pytext.models.embeddings.char_embedding import CharacterEmbedding\nfrom pytext.models.embeddings.embedding_list import EmbeddingList\nfrom pytext.models.embeddings.word_embedding import WordEmbedding\n\n\nclass EmbeddingListTest(unittest.TestCase):\n def test_get_param_groups_for_optimizer(self):\n word_embedding = WordEmbedding(\n num_embeddings=5,\n embedding_dim=4,\n embeddings_weight=None,\n init_range=[-1, 1],\n unk_token_idx=4,\n mlp_layer_dims=[],\n )\n char_embedding = CharacterEmbedding(\n num_embeddings=5,\n embed_dim=4,\n out_channels=2,\n kernel_sizes=[1, 2],\n highway_layers=1,\n projection_dim=3,\n )\n embedding_list = EmbeddingList([word_embedding, char_embedding], concat=True)\n param_groups = embedding_list.get_param_groups_for_optimizer()\n self.assertEqual(len(param_groups), 1)\n\n param_names = set(param_groups[0].keys())\n expected_param_names = {name for name, _ in embedding_list.named_parameters()}\n self.assertSetEqual(param_names, expected_param_names)\n","sub_path":"pytext/models/test/embedding_list_test.py","file_name":"embedding_list_test.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"173227556","text":"\"\"\"Readers for the SMILE and properties.\"\"\"\n\nfrom __future__ import division, print_function\n\nimport numpy as np\nimport tensorflow as tf\n\n# TODO: Switch to explicit relative import.\nfrom data_utils import sentence_to_token_ids, true_smile_tokenizer\nfrom six.moves import range\n\n\ndef vectorize_smile(data_dict, vocab, data_hparams):\n \"\"\"Vectorize the SMILEs and generate the sequence inputs and labels.\"\"\"\n # Fix the GO symbol and shift the seq_label.\n smile = data_dict[\"smile\"]\n tokenizer = lambda x: true_smile_tokenizer(\n x, skip_at_symbol=data_hparams.skip_at_symbol)\n\n if data_hparams.skip_at_symbol:\n smile = tf.regex_replace(smile, \"@\", \"\")\n\n def py_func_tokenize_smile(smi):\n \"\"\"Return a py_func for tokenizing SMILE string in tf tensors.\"\"\"\n # Extract token nums\n tokens = sentence_to_token_ids(\n smi, vocabulary=vocab, tokenizer=tokenizer)\n tokens = np.array(tokens, dtype=np.int32)\n # truncate if needed.\n if len(tokens) > (data_hparams.max_seq_len - 1):\n # Truncate the sequence with a space for EOS_ID\n tokens = tokens[:(data_hparams.max_seq_len - 1)]\n return tokens\n\n # Raw encode of the SMILEs.\n tokens = tf.py_func(py_func_tokenize_smile, [smile], tf.int32)\n tokens.set_shape((None, ))\n seq_len = tf.shape(tokens)[0] + 1\n # Save the seq_labels. [seq_length]\n seq_labels = tf.concat(\n [tokens, tf.constant([vocab.EOS_ID], dtype=tokens.dtype)], -1)\n # Produce inputs.\n seq_inputs = tf.concat(\n [tf.constant([vocab.GO_ID], dtype=tokens.dtype), tokens], -1)\n # One-hot each vector. -> [? (seq_length), TOK_DIM]\n seq_inputs = tf.one_hot(seq_inputs, len(vocab), dtype=tf.float32)\n # One-hot encoder inputs. -> [? (seq_length), TOK_DIM]\n encoder_inputs = tf.one_hot(tokens, len(vocab), dtype=tf.float32)\n return {\n \"smile\": smile,\n \"decoder_lens\": seq_len,\n \"decoder_inputs\": seq_inputs,\n \"decoder_labels\": seq_labels,\n \"encoder_inputs\": encoder_inputs\n }\n\n\n#\n# Dataset readers.\n#\n\n\nclass BaseDataset(object):\n\n def __init__(self, data_hparams, dataset_spec):\n \"\"\"Initialization of the base dataset.\n Args:\n data_hparams: A HParams instance from base_hparams.py.\n dataset_spec: A json dict object. Usually specify the dataset path.\n \"\"\"\n self._data_hparams = data_hparams\n self._dataset_spec = dataset_spec\n\n def __call__(self):\n \"\"\"Produce a tuple of training and validation tf.data.Dataset object.\"\"\"\n raise NotImplementedError\n\n\nclass DiscoveryReader(BaseDataset):\n\n # Discovery Reader, by default, only reads the first SMILE string in each \n # file.\n\n def _read_csv_dataset(self, dev=False):\n \"\"\"Read CSV from the generative dataset.\"\"\"\n train_csv_path = self._dataset_spec.get(\"train_csv_path\", None)\n val_csv_path = self._dataset_spec.get(\"val_csv_path\", None)\n test_csv_path = self._dataset_spec.get(\"test_csv_path\", None)\n if train_csv_path is None or val_csv_path is None or test_csv_path is None:\n raise IOError(\n \"train_csv_path or val_csv_path or test_csv_path does not exist in dataset_spec.\")\n\n record_defaults = [tf.string]\n select_cols = [0]\n dataset_func = lambda path : tf.contrib.data.CsvDataset(\n path,\n record_defaults,\n header=False,\n select_cols=select_cols).map(lambda *args: {\"smile\": args[0]})\n\n return {\n \"train\": dataset_func(train_csv_path),\n \"val\": dataset_func(val_csv_path),\n \"test\": dataset_func(test_csv_path)\n }\n \n def __call__(self):\n return self._read_csv_dataset()\n","sub_path":"reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":3793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"248879195","text":"import utils\r\nimport pandas as pd\r\nimport numpy as np\r\nimport progressbar\r\nfrom sklearn import tree\r\nfrom sklearn.metrics import matthews_corrcoef\r\n\r\ntrain_row_nu = 1183747\r\nchunk_nu = 50\r\nmax_chunk_size = 1000\r\n\r\n\r\n'''\r\nproba of categorical cols\r\n'''\r\ncolumn_names = utils.read_variable('outputs/column_names.pkl')\r\ncols_cate = column_names['categorical']\r\nvotes_cate = np.zeros((train_row_nu, cols_cate.size))\r\nbar = progressbar.ProgressBar()\r\nprint('loading cate proba...')\r\nfor chunk_id in bar(range(0,chunk_nu,1)):\r\n chunk = utils.read_variable('model_stats/train_cate_proba/'+str(chunk_id)+'.pkl')\r\n votes_cate[chunk_id*max_chunk_size:chunk_id*max_chunk_size+chunk.shape[0],:] = chunk\r\ndel chunk_id, bar, chunk\r\n\r\n#%\r\nresponses = utils.read_variable('outputs/responses.pkl').astype(int)\r\n#%%\r\n\r\nx_tr = votes_cate[:45000,:]\r\ny_tr = responses[:45000]\r\n\r\nx_val = votes_cate[45000:50000,:]\r\ny_val = responses[45000:50000]\r\n\r\n#%%\r\n\r\nfor i in range(1000,2000,1):\r\n\r\n if y_tr.iloc[i]['Response']==1:\r\n a2 = votes_cate[i,:]\r\n break\r\na0= votes_cate[1,:]\r\n\r\n#%%\r\nimport matplotlib.pyplot as plt\r\nt = np.arange(0, 2140, 1)\r\nplt.plot(a1,a2)\r\n\r\nplt.ylim([0.9940,0.9950])\r\nplt.xlim([0.9940,0.9950])\r\n\r\nplt.show()\r\n\r\n#%%\r\nfor i in range(0,len(a0),1):\r\n if a1[i] != a2[i]:\r\n print(i, a1[i],a2[i])\r\n\r\n#%%\r\nfrom sklearn.feature_selection import SelectKBest\r\nfrom sklearn.feature_selection import chi2\r\nmodel = SelectKBest( k=1).fit(x_tr, y_tr)\r\na = model.scores_\r\n\r\nfeature_selected = []\r\nfor i in range(0,len(a),1):\r\n if a[i]>1:\r\n feature_selected.append(i) \r\nprint(model.scores_)\r\n\r\n#%%\r\n\r\nmin_samples_leaf =1\r\nmax_depth=2\r\n\r\n\r\n# training 0\r\nx = x_tr[:,feature_selected]\r\ny = y_tr[:]\r\n# overfitting problem solution: smaller max_depth or larger min_sample_leaf\r\nprint(max_depth,min_samples_leaf, end='->')\r\nprint('model 0:','training...',end='')\r\ntree_votes_0 = tree.DecisionTreeClassifier().fit(x,y)\r\ny_pred = tree_votes_0.predict(x)\r\nmcc = matthews_corrcoef(y, y_pred) \r\nprint('mcc:',mcc,end='')\r\n#utils.save_variable(tree_votes_0,'models/tree_votes_0.pkl')\r\nprint(',val...',end='')\r\ny_pred = tree_votes_0.predict(x_val[:,feature_selected])\r\nmcc = matthews_corrcoef(y_val, y_pred) \r\nprint('mcc:',mcc)\r\n\r\n","sub_path":"history/4_model_on_cate.py","file_name":"4_model_on_cate.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"485999068","text":"from django.core.servers.basehttp import FileWrapper\nfrom django.http import HttpResponseRedirect\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom CabinetProject import CabinetProject\nfrom CabinetDoor import CabinetDoor\nfrom CabinetDrawer import CabinetDrawer\nfrom CabinetHamper import CabinetHamper\nfrom CabinetBox import CabinetBox\nfrom SheetSet import SheetSet\nfrom WoodPiece import WoodPiece\nimport os\nimport json\nimport base64\nimport labels\nfrom reportlab.graphics import shapes\n\ndef index(request):\n if request.method == \"POST\" and not request.POST.get('labeldata', '') == '':\n return generateLabels(request)\n if request.method == \"POST\" and not request.POST.get('project_data_json', '') == '':\n return generatePlans(request, request.POST.get('project_data_json', ''))\n if request.method == \"POST\":\n json_of_post = json.dumps(request.POST)\n return generatePlans(request, json_of_post)\n if not request.GET.get('p', '') == '':\n json_of_post = base64.b64decode(request.GET.get('p', ''))\n return generatePlans(request, json_of_post)\n return generateInputForm(request)\n\ndef generateLabels(request):\n if request.POST.get('labeldata', '') == '':\n return HttpResponseRedirect('/')\n\n items_for_labels = json.loads(base64.b64decode(request.POST.get('labeldata', '')))\n label_specs = labels.Specification(\n 215,\n 280,\n 4,\n 20,\n 45,\n 11.0,\n corner_radius=2,\n top_margin = 10,\n bottom_margin = 11,\n left_margin = 4,\n right_margin = 4,\n )\n sheet = labels.Sheet(label_specs, draw_label, border=True)\n\n for cur_piece in items_for_labels:\n sheet.add_label(cur_piece)\n sheet.save('/tmp/basic.pdf')\n\n filename = '/tmp/basic.pdf'\n wrapper = FileWrapper(file(filename))\n response = HttpResponse(wrapper, content_type='application/pdf')\n response['Content-Length'] = os.path.getsize(filename)\n return response\n\ndef draw_label(label, width, height, obj):\n label.add(shapes.String(5, height-10, obj['id'].upper() + ' ' + obj['label'].upper(), fontName=\"Times-Bold\", fontSize=10))\n label.add(shapes.String(5, height-20, obj['width'] + '\" x ' + obj['length'] + '\"' + obj['material'], fontName=\"Helvetica\", fontSize=8))\n label.add(shapes.String(5, height-28, obj['comments'], fontName=\"Helvetica\", fontSize=8))\n\ndef generateInputForm(request):\n context = {}\n return render(request, 'input.html', context)\n\ndef generatePlans(request, project_data_json):\n\n post_base64 = base64.b64encode(project_data_json)\n project_data = json.loads(project_data_json)\n\n project = CabinetProject()\n project.rail_bit_cut_depth = float(project_data['rail-bit-cut-depth'])\n project.stock_thickness = float(project_data['stock-thickness'])\n\n # Loop over all section items:\n for section_number in range(1, int(project_data['num-section-counter-input'])+1):\n # Door Project\n if 'door-opening-overflow_' + str(section_number) in project_data:\n # Sections Add\n box_sections = []\n for section_ratio in str(project_data['box-dividers_' + str(section_number)]).split('|'):\n box_sections.append({\n 'type': CabinetDoor,\n 'ratio': section_ratio\n })\n box_section_counter = 0\n for cur_box_section in box_sections:\n box_section_counter += 1\n for _ in xrange(int(project_data['door-number-doors_' + str(section_number)])):\n door = CabinetDoor()\n door.id = str(project.get_new_door_id())\n project.summary['DOOR' + str(door.id)] = str(project_data['door-opening-width_' + str(section_number)]) + '\" x ' + str(project_data['door-opening-height_' + str(section_number)]) + '\"'\n door.panel_material = str(project_data['door-panel-type_' + str(section_number)])\n door.panel_undersize = float(project_data['panel-undersize'])\n door.rail_bit_cut_depth = float(project.rail_bit_cut_depth)\n door.stock_thickness = float(project.stock_thickness)\n door.frame_width = float(project_data['door-frame-width_' + str(section_number)])\n if str(project_data['door-number-doors_' + str(section_number)]) == \"2\" :\n door.width = (float(project_data['door-opening-width_' + str(section_number)]) + 2 * float(project_data['door-opening-overflow_' + str(section_number)]) - float(project_data['door-split-gap_' + str(section_number)]))/2\n else :\n door.width = float(project_data['door-opening-width_' + str(section_number)]) + 2 * float(project_data['door-opening-overflow_' + str(section_number)])\n door.height = float(project_data['door-opening-height_' + str(section_number)]) + 2 * float(project_data['door-opening-overflow_' + str(section_number)])\n project.doors.append(door)\n\n # Compute heights for sections\n door_split_gap = float(project_data['door-split-gap_' + str(section_number)])\n divisible_height = door.height - ((len(box_sections) - 1) * door_split_gap)\n door.height = divisible_height * float(cur_box_section['ratio'])\n\n # Box Project\n elif 'box-depth_' + str(section_number) in project_data:\n # Determine Ratios\n # Special Case : Drawer on Top\n box_sections = []\n if str(project_data['box-dividers_' + str(section_number)]) == '6\" Drawer on Top':\n # Find Ratio of 6\" to height\n drawer_ratio = (6.0 + float(project_data['box-door-reveal-top_' + str(section_number)])) / float(project_data['box-height_' + str(section_number)])\n box_sections.append({\n 'type': CabinetDrawer,\n 'ratio': drawer_ratio\n })\n box_sections.append({\n 'type': CabinetDoor,\n 'ratio': 1 - drawer_ratio\n })\n elif str(project_data['box-dividers_' + str(section_number)]) == '6\" Drawer on Top With Hamper':\n # Find Ratio of 6\" to height\n drawer_ratio = (6.0 + float(project_data['box-door-reveal-top_' + str(section_number)])) / float(project_data['box-height_' + str(section_number)])\n box_sections.append({\n 'type': CabinetDrawer,\n 'ratio': drawer_ratio\n })\n box_sections.append({\n 'type': CabinetHamper,\n 'ratio': 1 - drawer_ratio\n })\n else:\n for section_ratio in str(project_data['box-dividers_' + str(section_number)]).split('|'):\n box_sections.append({\n 'type': CabinetDoor,\n 'ratio': section_ratio\n })\n\n num_doors_per_gap = int(project_data['box-number-doors_' + str(section_number)])\n door_split_gap = float(project_data['box-door-split-gap_' + str(section_number)])\n\n # Doors / Drawers\n box_section_counter = 0\n for cur_box_section in box_sections:\n box_section_counter += 1\n doors_across_gap_counter = 0\n for _ in xrange(num_doors_per_gap):\n doors_across_gap_counter += 1\n door = cur_box_section['type']()\n door.id = str(project.get_new_door_id())\n door.box_depth = float(project_data['box-depth_' + str(section_number)])\n door.box_width = float(project_data['box-width_' + str(section_number)])\n door.box_sheet_thickness = float(project_data['box-sheet-thickness_' + str(section_number)])\n door.reveal_left = float(project_data['box-door-reveal-left_' + str(section_number)])\n door.reveal_right = float(project_data['box-door-reveal-right_' + str(section_number)])\n door.reveal_top = float(project_data['box-door-reveal-top_' + str(section_number)])\n door.reveal_bottom = float(project_data['box-door-reveal-bottom_' + str(section_number)])\n door.panel_material = str(project_data['box-door-panel-type_' + str(section_number)])\n door.panel_undersize = float(project_data['panel-undersize'])\n door.rail_bit_cut_depth = float(project.rail_bit_cut_depth)\n door.stock_thickness = float(project.stock_thickness)\n door.frame_width = float(project_data['box-door-frame-width_' + str(section_number)])\n\n # Compute widths for multiple doors across box\n if num_doors_per_gap == 2:\n door.width = (float(project_data['box-width_' + str(section_number)]) - door_split_gap)/2\n else:\n door.width = float(project_data['box-width_' + str(section_number)])\n\n # Deal with multiple doors across gap and reveals properly\n # Door splits are already considered in door_split_gap\n if num_doors_per_gap == 2:\n if doors_across_gap_counter == 1:\n door.reveal_right = 0.0\n if doors_across_gap_counter == 2:\n door.hinge_side = \"right\"\n door.reveal_left = 0.0\n\n # Compute heights for sections\n divisible_height = float(project_data['box-height_' + str(section_number)]) - ((len(box_sections) - 1) * door_split_gap)\n\n # Since we may have modified the ratios earlier for a drawer on top, force a width here. It usually doesn't matter.\n if cur_box_section['type'] == CabinetDrawer and box_section_counter == 1 and str(project_data['box-dividers_' + str(section_number)]) in ['6\" Drawer on Top', '6\" Drawer on Top With Hamper']:\n door.height = 6.0\n door.reveal_top = 0.0\n else:\n door.height = divisible_height * float(cur_box_section['ratio'])\n\n # Deal with sections and reveals properly\n # Gaps in sections are already considered in door_split_gap\n if len(box_sections) > 1:\n if box_section_counter == 1:\n door.reveal_bottom = 0.0\n elif box_section_counter == len(box_sections):\n door.reveal_top = 0.0\n else:\n door.reveal_bottom = 0.0\n door.reveal_top = 0.0\n\n if cur_box_section['type'] == CabinetDoor:\n project.doors.append(door)\n if cur_box_section['type'] == CabinetDrawer or cur_box_section['type'] == CabinetHamper:\n project.drawers.append(door)\n\n # Box Carcass\n box = CabinetBox()\n box.id = str(project.get_new_box_id())\n project.summary['BOX' + str(box.id)] = str(project_data['box-width_' + str(section_number)]) + '\" wide x ' + str(project_data['box-height_' + str(section_number)]) + '\" high x ' + str(project_data['box-depth_' + str(section_number)]) + '\" deep (' + str(project_data['box-dividers_' + str(section_number)]) + ')'\n box.material = str(project_data['box-sheet-material_' + str(section_number)])\n box.sheet_thickness = float(project_data['box-sheet-thickness_' + str(section_number)])\n box.width = float(project_data['box-width_' + str(section_number)])\n box.height = float(project_data['box-height_' + str(section_number)])\n box.depth = float(project_data['box-depth_' + str(section_number)]) - float(project_data['bumper-thickness']) - float(project_data['stock-thickness'])\n box.num_dividers = len(box_sections) - 1\n if str(project_data['box-dividers_' + str(section_number)]) == '6\" Drawer on Top':\n box.divider_is_spreader = True\n box.num_shelves = int(project_data['box-number-shelves_' + str(section_number)])\n if 'box-counter-on-top_' + str(section_number) in project_data:\n box.counter_on_top = True\n project.boxes.append(box)\n\n # Freeform Piece\n elif 'piece-width_' + str(section_number) in project_data:\n if str(project_data['piece-sheet-material_' + str(section_number)]) == 'solid':\n material_string = 'solid'\n else:\n material_string = str(float(project_data['piece-sheet-thickness_' + str(section_number)])) + '-' + str(project_data['piece-sheet-material_' + str(section_number)])\n piece = WoodPiece(\n str(str(project_data['piece-label-input_' + str(section_number)]) + str(project.get_new_door_id())).upper().replace(' ', '_'),\n str(project_data['piece-label-input_' + str(section_number)]),\n float(project_data['piece-sheet-thickness_' + str(section_number)]),\n float(project_data['piece-height_' + str(section_number)]),\n float(project_data['piece-width_' + str(section_number)]),\n material_string,\n str(project_data['piece-comments-input_' + str(section_number)])\n )\n project.pieces.append(piece)\n\n project.generate_cut_summary()\n\n stock_length = 96\n stock_length = stock_length - 1.5\n\n message_to_print = 'Based on ' + str(stock_length) + '\"' + \"\\n\"\n\n # Get Number of Solid Lengths Needed For Each Based on Passed Length\n for width, material_pieces in project.cut_summary['pieces']['solid'].items():\n solid_set = SheetSet(1, 'solid', float(width), float(stock_length))\n for cur_length in material_pieces['pieces']:\n for x in range(0, len(material_pieces['pieces'][cur_length])):\n solid_set.add_piece( WoodPiece('1', '1', 1, float(width), float(cur_length), '', ''), True)\n message_to_print = message_to_print + str(len(solid_set.sheets)) + ' lengths needed for ' + width + \"\\n\"\n\n context = {\n 'project_summary' : project.summary,\n 'cut_summary' : project.cut_summary,\n 'sheet_layouts' : project.sheet_layout,\n 'banding' : project.banding,\n 'hardware' : project.hardware,\n 'project_hash' : post_base64,\n 'label_hash' : base64.b64encode(json.dumps(project.labels)),\n 'project_data_json' : project_data_json,\n 'stock_message' : message_to_print,\n }\n\n return render(request, 'cutlist.html', context)\n","sub_path":"cutlist/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"33025760","text":"import functools as ft\nimport sublime\nfrom . import WView\n\ndef fwShowQuickPanel(timeout=10):\n def decorator(f):\n @ft.wraps(f)\n def wrapper(*args, **kwds):\n ret = f(*args, **kwds)\n if ret is None:\n return\n\n self, items, selected_index, *flagArg = ret\n if flagArg:\n flags, = flagArg\n else:\n flags = 0\n\n on_done, on_highlight = None, None\n metaOfSelf = dir(self)\n if \"onQuickPanelDone\" in metaOfSelf:\n on_done = self.onQuickPanelDone\n\n if \"onQuickPanelHighlight\" in metaOfSelf:\n on_highlight = self.onQuickPanelHighlight\n\n showQuickPanel(\n None, items, on_done, timeout,\n on_highlight=on_highlight, flags=flags, selected_index=selected_index)\n\n return wrapper\n\n return decorator\n\n@WView.fwPrepareWindow\ndef showInputPanel(window, onDone, title=\"\", initText=\"\", *, onChange=None, onCancel=None):\n window.show_input_panel(\n title, initText, onDone, onChange, onCancel)\n\n@WView.fwPrepareWindow\ndef showQuickPanel(window, items, on_done, timeout=10, **kwds):\n if timeout:\n sublime.set_timeout(lambda: window.show_quick_panel(items, on_done, **kwds), timeout)\n else:\n window.show_quick_panel(items, on_done, **kwds)\n","sub_path":"SublimeStorm-Dep-Utils/st3/SublimeUtils/Panel.py","file_name":"Panel.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"359817157","text":"\n\ndef permutations(string):\n if len(string) == 0 :\n output = []\n output.append('')\n return output\n smalloutput = permutations(string[1 : ])\n finaloutput = []\n for i in range(0 , len(smalloutput)) :\n for j in range(0, len(smalloutput[i]) + 1) :\n str1 = smalloutput[i][0 : j]\n str2 = smalloutput[i][j : ]\n finaloutput.append(str1 + string[0] + str2)\n return finaloutput\n\n#This Code has bad Time Complexity\ndef printpermutations(string , output = '') :\n if len(string) == 0 :\n print(output)\n return\n for j in range(0, len(string)) :\n printpermutations(string[0 : j] + string[j + 1 : ] , output + string[j])\nstring = input()\n#printpermutations(string)\nans = permutations(string)\nfor s in ans:\n print(s)\n","sub_path":"DATASTRUCTURESANDALGORITHMS/Python/ADVANCED RECURSION/ReturnPermutations.py","file_name":"ReturnPermutations.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"484678946","text":"from taiga_contrib_github_auth import connector\nfrom taiga_contrib_github_auth.services import github_register\nfrom taiga.auth.services import make_auth_response_data\nfrom urllib.parse import urljoin\nfrom django.conf import settings\nimport logging\nimport requests\nfrom taiga.base import exceptions as exc\n\nlogger = logging.getLogger(__name__)\n\n\ndef check_org_membership(github_id, org, headers:dict=connector.HEADERS):\n logger.debug(\"Checking membership of user with github id '{0}' in org {1}...\".format(github_id, org))\n\n \"\"\"\n Get authenticated user organization membership. \n \"\"\"\n\n url = urljoin(connector.API_URL, \"orgs/{0}/members/{1}\".format(org, github_id))\n logger.debug(\"Checking via URL {0}.\".format(url))\n logger.debug(\"Headers: {0}\".format(headers))\n\n response = requests.get(url, headers=headers)\n if response.status_code not in [204, 302]:\n logger.debug(\"User was not a member of GitHub organization {0}.Status was {1}\".format(org, response.status_code))\n return False\n else:\n return True\n\n\n# a twiddled replacement for the login method in taiga-contrib-github-auth/connector.py that requests a broader scope\ndef login(access_code:str, client_id: str=connector.CLIENT_ID, client_secret: str=connector.CLIENT_SECRET,\n headers: dict=connector.HEADERS):\n \"\"\"\n Get access_token fron an user authorized code, the client id and the client secret key.\n (See https://developer.github.com/v3/oauth/#web-application-flow).\n \"\"\"\n if not connector.CLIENT_ID or not connector.CLIENT_SECRET:\n raise connector.GitHubApiError({\"error_message\": _(\"Login with github account is disabled. Contact \"\n \"with the sysadmins. Maybe they're snoozing in a \"\n \"secret hideout of the data center.\")})\n\n url = urljoin(connector.URL, \"login/oauth/access_token\")\n\n # note -> scope: read:user instead of \"user:email\"; required to determine *private* org membership\n params={\"code\": access_code,\n \"client_id\": client_id,\n \"client_secret\": client_secret,\n \"scope\": \"user:emails\"}\n data = connector._post(url, params=params, headers=headers)\n return connector.AuthInfo(access_token=data.get(\"access_token\", None))\n\n\ndef github_login_func(request):\n logger.debug(\"Attempting login using taiga_contrib_github_extended_auth plugin....\")\n\n code = request.DATA.get('code', None)\n token = request.DATA.get('token', None)\n\n auth_info = login(code)\n\n headers = connector.HEADERS.copy()\n headers[\"Authorization\"] = \"token {}\".format(auth_info.access_token)\n\n user_info = connector.get_user_profile(headers=headers)\n username = user_info.username\n logger.debug(\"username: {0}\".format(username))\n\n organization = getattr(settings, \"TAIGA_GITHUB_EXTENDED_AUTH_ORG\", None)\n logger.debug(\"organization: {0}\".format(organization))\n\n if organization and check_org_membership(username, organization, headers=headers):\n logger.debug(\"confirmed membership...\")\n\n emails = connector.get_user_emails(headers=headers)\n\n primary_email = next(filter(lambda x: x.is_primary, emails)).email\n\n logger.debug(\"Primary email is {}\".format(primary_email))\n\n user = github_register(username=username,\n email=primary_email.lower(),\n full_name=user_info.full_name,\n github_id=user_info.id,\n bio=user_info.bio,\n token=token)\n\n return make_auth_response_data(user)\n else:\n raise exc.PermissionDenied(detail=\"User {0} was not a member of GitHub organization {1} and is not permitted to register for access to this Taiga instance.\".format(username, organization))\n","sub_path":"apps/taiga/back/django/taiga/taiga_contrib_github_extended_auth/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":3873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"623183338","text":"import asyncio\nimport json\nimport logging\nimport os\nimport time\n\nimport asyncclick as click\nfrom core.exceptions import BadRequestException\nfrom core.requester import Requester\nfrom core.web3.eth_client import RestEthClient\n\nfrom contracts import create_contract_store\n\nGWEI = 1000000000\nGAS_LIMIT = 1000000\n\n@click.command()\n@click.option('-t', '--starting-token', 'startTokenId', required=True, type=int)\n@click.option('-w', '--width', 'width', required=True, type=int)\n@click.option('-h', '--height', 'height', required=True, type=int)\n@click.option('-r', '--receive-address', 'receiveAddress', required=True, type=str)\nasync def run(startTokenId: int, width: int, height: int, receiveAddress: str):\n accountAddress = os.environ['ACCOUNT_ADDRESS']\n privateKey = os.environ['PRIVATE_KEY']\n requester = Requester()\n rinkebyEthClient = RestEthClient(url=os.environ['ALCHEMY_URL'], requester=requester)\n mumbaiEthClient = RestEthClient(url='https://matic-mumbai.chainstacklabs.com', requester=requester)\n contractStore = create_contract_store(rinkebyEthClient=rinkebyEthClient, mumbaiEthClient=mumbaiEthClient, accountAddress=accountAddress, privateKey=privateKey)\n\n network = 'rinkeby5'\n contract = contractStore.get_contract(network=network)\n ethClient = contract.ethClient\n\n nonce = await ethClient.get_transaction_count(address=accountAddress)\n transactionHash = None\n for row in range(0, height):\n for column in range(0, width):\n tokenId = startTokenId + (row * 100) + column\n print(f'Transferring token {tokenId} with nonce {nonce} to {receiveAddress}')\n try:\n transactionHash = await contractStore.transfer_token(network=network, tokenId=tokenId, toAddress=receiveAddress, nonce=nonce, gas=150000, gasPrice=int(1.1 * GWEI))\n except BadRequestException as exception:\n print(f'Failed to transfer {tokenId}: {str(exception)}')\n nonce += 1\n time.sleep(0.2)\n print(f'Waiting for last transaction to finish: https://rinkeby.etherscan.io/tx/{transactionHash}')\n await contractStore.wait_for_transaction(network=network, transactionHash=transactionHash)\n await requester.close_connections()\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO)\n run(_anyio_backend='asyncio')\n","sub_path":"api/transfer_tokens.py","file_name":"transfer_tokens.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"82563146","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport time\nfrom selenium import webdriver\n\n# 需求\n### 获取当前iframe的目录结构\n\ndef getIframeUrls(iframes):\n iframeUrls = []\n if len(iframes) < 1:\n return iframeUrls\n for i in range(len(iframes)):\n driver.switch_to.parent_frame()\n iframeUrl = iframes[i].get_attribute('src')\n driver.switch_to.frame(i)\n print('index:{} , iframeUrl:{}'.format(i, iframeUrl))\n sonIframes = driver.find_elements_by_tag_name('iframe')\n if len(sonIframes) > 0 :\n iframeUrls.append(getIframeUrls(sonIframes))\n else:\n iframeUrls.append(iframeUrl)\n driver.switch_to.parent_frame()\n return iframeUrls\n\ndriver = webdriver.Chrome('/Users/liuji/soft/dirver/chromedriver')\ntry:\n print('--------------------------start---------------------------------')\n driver.maximize_window()\n driver.implicitly_wait(5)\n\n # 打开iframe嵌套页面\n driver.get('http://127.0.0.1/iframe.html')\n parent_window_handle = driver.current_window_handle\n time.sleep(4)\n #iframes = driver.execute_script('return document.getElementsByTagName(\"iframe\")')\n # iframeUrls = getIframeUrls(iframes)\n iframes = driver.find_elements_by_tag_name('iframe')\n driver.switch_to.frame(1)\n sonIframes = driver.find_elements_by_tag_name('iframe')\n print('index:{} , iframeUrl:{}'.format('1-1', sonIframes[1].get_attribute('src')))\n print('-------------------------success--------------------------------')\nexcept Exception as e:\n print('Error:', e)\nfinally:\n driver.quit()\n\n","sub_path":"selenium-example/iframeCatalog.py","file_name":"iframeCatalog.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"32335150","text":"import math\r\nt=int(input())\r\nn,j=map(int,input().split())\r\n\r\nprint(\"Case #1:\")\r\n'''\r\ndef divisorGenerator(n):\r\n large_divisors = []\r\n for i in range(1, int(math.sqrt(n) + 1)):\r\n if n % i == 0:\r\n yield i\r\n if i*i != n:\r\n large_divisors.append(n / i)\r\n for divisor in reversed(large_divisors):\r\n yield divisor\r\n'''\r\ndef is_prime(n):\r\n if n == 2 or n == 3: return True,1\r\n if n < 2 or n%2 == 0: return False,2\r\n if n < 9: return True,1\r\n if n%3 == 0: return False,3\r\n r = int(n**0.5)\r\n f = 5\r\n while f <= r:\r\n #print ('\\t',f)\r\n if n%f == 0: return False,f\r\n if n%(f+2) == 0: return False,f+2\r\n f +=6\r\n return True,1\r\n\r\ncount=0 \r\nfor i in range(32769,65536):\r\n b=bin(i)[2:]\r\n \r\n p=0\r\n divi=[]\r\n if count'\n\ttemp = re.findall(pattern,driver.page_source)\n\tpprint.pprint(temp)\n\n\t__outputFile(\"seleniumTest.1txt\",driver.page_source)\n\tdriver.close()\n\t\n\t# testSele2 = TestSele2()\n\t# testSele2.selenium_init('*chrome','http://ent.163.com/14/0210/07/9KN3TG0200032DGD.html')\n\n\nif __name__==\"__main__\":\n\t# unittest.main()\n\tmain()","sub_path":"163spiderTest/seleniumTest.py","file_name":"seleniumTest.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"426460313","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jul 22 14:43:29 2017\r\n\r\n@author: Jeff Hsueh\r\nReference: https://www.kaggle.com/apapiu/regularized-linear-models\r\n\"\"\"\r\n# data analysis and wrangling\r\nimport pandas as pd\r\nimport numpy as np\r\nimport random as rnd\r\nimport os\r\n# visualization\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\n\r\n#ML\r\nfrom sklearn.linear_model import Ridge, RidgeCV, ElasticNet, LassoCV, LassoLarsCV,LogisticRegression\r\nfrom sklearn.svm import SVC, LinearSVC\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom scipy.stats import spearmanr, kendalltau, pearsonr\r\nfrom scipy.stats import norm\r\n\r\nfor file in os.listdir( os.curdir ):\r\n if file == \"test.csv\":\r\n file_test= file\r\n if file == \"train.csv\":\r\n file_train= file\r\n \r\ncwd = os.getcwd()\r\ntrain_df = pd.read_csv(cwd+\"\\\\\"+file_train)\r\ntest_df = pd.read_csv(cwd+\"\\\\\"+file_test)\r\n\r\ndata= pd.concat([train_df,test_df])\r\nprint (train_df.shape,\"\\n\",test_df.shape,\"\\n\",data.shape)\r\n\r\n#filling NA's with the mean of the column:\r\ndata = data.fillna(data.mean())\r\n\r\n#Normalizing sale price\r\n#applying log transformation\r\ntrain_df['SalePrice'] = np.log(train_df['SalePrice'])\r\n\r\n#transformed histogram and normal probability plot\r\nsns.distplot(train_df['SalePrice'], fit=norm);\r\n#plt.show()\r\n\r\n#Association for each variable with salePrice\r\n#saleprice correlation matrix\r\n#correlation matrix\r\ncorrmat = data.corr()\r\nf, ax = plt.subplots(figsize=(12, 9))\r\nk = 10 #number of variables for heatmap\r\ncols = corrmat.nlargest(k, 'SalePrice')['SalePrice'].index\r\ncols2 = corrmat.nlargest(k, 'SalePrice')['SalePrice']\r\ncm = np.corrcoef(data[cols].values.T) #cm2 = np.corrcoef(train_df[cols].values,rowvar=False)\r\nsns.set(font_scale=1.25)\r\nhm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.values)\r\n#plt.show()\r\n\r\nclean_df = pd.DataFrame(data= data[cols])\r\nX_train =clean_df[:train_df.shape[0]]\r\ny = train_df['SalePrice'].fillna(train_df['SalePrice'].mean())\r\nX_test= clean_df[train_df.shape[0]:]\r\n\r\nmodel_lasso = LassoCV(alphas = [1, 0.1, 0.001, 0.0005]).fit(X_train, y)\r\nlasso_preds = np.expm1(model_lasso.predict(X_test))\r\nresult = pd.DataFrame({\"Id\":test_df.Id, \"SalePrice\":lasso_preds})\r\nresult.to_csv(\"result.csv\", index = False)\r\n","sub_path":"sale_price.py","file_name":"sale_price.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"265211338","text":"import torch\nimport torch_geometric.nn as pygnn\nfrom torch import nn\nfrom torch_scatter import scatter_add\n\n\n# for model develop\nclass GlobalAddPool(nn.Module):\n def forward(self, x, batch, *args):\n return pygnn.global_add_pool(x, batch)\n\n\n# model develop\nclass NodeAttentionPool(nn.Module):\n def __init__(self, gate_nn, nn):\n super().__init__()\n self.gate_nn = gate_nn\n self.nn = nn\n\n def forward(self, x, batch, *args, return_score=False):\n size = batch[-1].item() + 1\n gate = self.gate_nn(x).view(-1, 1)\n x = self.nn(x)\n gate = torch.sigmoid(gate)\n out = scatter_add(gate * x, batch, dim=0, dim_size=size)\n if return_score:\n return out, gate\n else:\n return out\n\n def __repr__(self):\n return '{}(gate_nn={}, nn={})'.format(self.__class__.__name__, self.gate_nn, self.nn)\n\n\n# for final model\nclass StructureAttentionPool(nn.Module):\n def __init__(self, num_features):\n super(StructureAttentionPool, self).__init__()\n self.num_features = num_features\n self.fc = nn.Linear(num_features, num_features)\n\n def forward(self, x, batch, *args, return_score=False):\n ctx = self.fc(pygnn.global_mean_pool(x, batch))\n ctx = torch.tanh(ctx) # (numG, num_features)\n repeats = scatter_add(torch.ones(batch.size()[0], dtype=torch.long).to(batch.device), batch)\n ctx = torch.repeat_interleave(ctx, repeats, dim=0) # (numN, num_features)\n score = torch.bmm(x.view(x.size()[0], 1, x.size()[1]), ctx.view(ctx.size()[0], ctx.size()[1], 1)).squeeze()\n score = torch.sigmoid(score).view(-1, 1) # (numN, 1)\n out = pygnn.global_add_pool(score * x, batch)\n if return_score:\n return out, score\n else:\n return out\n\n def __repr__(self):\n return '{}(num_features={}, ctx_nn={})'.format(self.__class__.__name__,\n self.num_features, self.fc)\n","sub_path":"lib/model_util.py","file_name":"model_util.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"271927876","text":"\"\"\"First function gets the list of criteria to be used and adds\r\nany needed new columns to the main pt data database.\r\n\r\nSecond function gets the headings for each criterion from the database\r\nand sets up a dictionary.\r\nThen retrieves entry input from available data in\r\nthe database, and prompts user to enter the remaining values.\r\nThen updates the database and then updates the dictionary.\r\nReturns a completed dictionary of criteria items:values.\r\n\"\"\"\r\n\r\nimport sqlite3\r\n\r\nfrom Database_functions import Validate_entry\r\n\r\nLastName = input(\"Enter Last Name:\")\r\nreference_list = input(\"Enter Criteria List:\")\r\n\r\n\r\n\"\"\" This function adds any new criteria items as a column\r\n to the main patient db\"\"\"\r\n\r\n\r\ndef add_new_column_for_new_db_field(reference_list):\r\n conn = sqlite3.connect('Patient_data.db')\r\n cur = conn.cursor()\r\n\r\n # list all the fields already in the large data base\r\n\r\n strsql = \"PRAGMA table_info('Pt_Current_Status')\"\r\n cur.execute(strsql)\r\n dataset = cur.fetchall()\r\n # print(dataset)\r\n\r\n fields_list = []\r\n for row in dataset:\r\n field_name = row[1]\r\n fields_list.append(field_name)\r\n\r\n # print(\"List of columns already in db: \", fields_list)\r\n # return fields_list\r\n\r\n # next, check if the field in the current criteria list is in the large db\r\n\r\n # next section brings the criteria list into program from db\r\n\r\n criteria_list = [] # this is the list of criteria currently being evaluated\r\n\r\n # table_selected = input(\"Enter the name of the Criteria List:\")\r\n select_text = 'SELECT Criterion FROM ' + reference_list\r\n cur.execute(select_text)\r\n dataset = cur.fetchall()\r\n # print(dataset)\r\n\r\n for row in dataset:\r\n criteria_list.append(row[0])\r\n # print(criteria_list)\r\n\r\n # now check the criteria list against the fields list in the large db and\r\n # make a list of the new fields\r\n\r\n new_fields = []\r\n for item in criteria_list:\r\n if item not in fields_list:\r\n new_fields.append(item)\r\n else:\r\n continue\r\n # print('Fields list already in pt database:', fields_list)\r\n # print('New columns to be added to database:', new_fields)\r\n\r\n # next, add new columns to the Pt_Current_Status db for all new fields\r\n\r\n for item in new_fields:\r\n item = str(item)\r\n sqlstring = 'ALTER TABLE Pt_Current_Status ADD COLUMN ' + item\r\n # print(sqlstring)\r\n cur.execute(sqlstring)\r\n\r\n conn.commit()\r\n conn.close()\r\n print(\"Database column headings updated.\")\r\n\r\n\r\n\"\"\"Function pulls in available data from database and then updates\r\nthe dictionary values, asks user to input missing data and then \r\nupdates the database and the dictionary values. \r\nReturns the completed dictionary\"\"\"\r\n\r\n\r\ndef pull_in_available_data(LastName, reference_list):\r\n conn = sqlite3.connect('Patient_data.db')\r\n cur = conn.cursor()\r\n\r\n # next section brings the criteria list into program\r\n criteria_list = [] # this is the list of criteria which are keys for the dictionary\r\n criteria_dict = {} # this is the dictionary of (criteria) keys:values\r\n missing_items_list = []\r\n\r\n # table_selected = input(\"Enter the name of the Criteria List:\")\r\n select_text = 'SELECT Criterion FROM ' + reference_list\r\n\r\n cur.execute(select_text)\r\n dataset = cur.fetchall()\r\n # print(dataset)\r\n\r\n for row in dataset:\r\n criteria_list.append(row[0])\r\n # print(\"Criteria list is:, \", criteria_list)\r\n for item in criteria_list:\r\n strsql = 'SELECT ' + item + ' FROM Pt_Current_Status WHERE NameLast = ? '\r\n cur.execute(strsql, (LastName,))\r\n dataset = cur.fetchone()\r\n # print(\"Retrieved values: \", str(dataset))\r\n criteria_dict.update({item: str(dataset[0])})\r\n # print(criteria_dict)\r\n # print(\"For pt \" + LastName + \", \" + item + \"=: \" + str(dataset[0]))\r\n\r\n # if (dataset[0]) == \"\":\r\n # missing_items_list.append(item)\r\n\r\n field_value = str(dataset[0]) # eliminate the Null entries\r\n field_value = field_value.upper\r\n if (field_value != 'Y') and (field_value != 'N'):\r\n missing_items_list.append(item)\r\n # print(\"Missing items:\", LastName, missing_items_list)\r\n\r\n if len(missing_items_list) > 0:\r\n print(\"\"\"\\n\\nSome items are missing from the database.\r\n Enter the required information.\"\"\")\r\n # print(\"Missing items:\", missing_items_list)\r\n\r\n # this next section will let user enter the missing data and update the database:\r\n\r\n for criteria in missing_items_list:\r\n user_input = input(\"\\n\\nEnter value for \" + criteria + \" (must be 'y' or 'n' or a number): \")\r\n entry = Validate_entry(user_input)\r\n print(\"Database will be updated.\")\r\n\r\n # Update the large pt database\r\n\r\n strsql = 'UPDATE Pt_Current_Status SET ' + criteria + ' = ? WHERE NameLast = ? '\r\n # print(strsql)\r\n cur.execute(strsql, (entry, LastName))\r\n conn.commit()\r\n\r\n \"\"\"update the entries dictionary and return the final\r\n updated dictionary\"\"\"\r\n\r\n for item in criteria_list:\r\n strsql = 'SELECT ' + item + ' FROM Pt_Current_Status WHERE NameLast = ? '\r\n cur.execute(strsql, (LastName,))\r\n dataset = cur.fetchone()\r\n # print(\"Retrieved values: \", str(dataset))\r\n criteria_dict.update({item: str(dataset[0])})\r\n # print(criteria_dict)\r\n\r\n # print(\"Entered dictionary values are:\", criteria_dict)\r\n conn.close()\r\n return criteria_dict\r\n\r\n\r\nadd_new_column_for_new_db_field(reference_list)\r\n\r\ncompleted_entries = pull_in_available_data(LastName, reference_list)\r\n\r\nprint(\"\\n\\nFinal summary:\\n\\nLast Name is:\", LastName)\r\nprint(\"\\n\\n Final dictionary:\", completed_entries)\r\n\r\n\r\n","sub_path":"General_case_query.py","file_name":"General_case_query.py","file_ext":"py","file_size_in_byte":5822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"595603779","text":"#!/usr/bin/python3\n\nimport sys\nimport re\nimport datetime\nimport statistics\n\nrecord = re.compile(\"(.)\\\\[([0-9-]+\\\\|[0-9:.]+)\\\\] (Committed state) +(.*)\")\n\ndef process_log(log):\n\tblockTime=None\n\troundTimes = []\n\n\tfor line in log:\n\t\tline = line.strip()\n\t\tm = record.match(line)\n\t\tif m:\n\t\t\tlvl,tstamp,msg,param = m.groups()\n\t\t\tcommitTime = datetime.datetime.strptime(tstamp, \"%Y-%m-%d|%H:%M:%S.%f\")\n\t\t\tif blockTime is not None:\n\t\t\t\tdelta = commitTime - blockTime\n\t\t\t\troundTimes.append(delta.total_seconds())\n\t\t\tblockTime = commitTime\n\treturn roundTimes\n\nroundTimes = process_log(sys.stdin)\n\nprint(\"Number of completed rounds: \", len(roundTimes))\nif len(roundTimes) > 0:\n\tprint(\"Average round time: \", statistics.mean(roundTimes))\n\tprint(\"Median round time: \", statistics.median(roundTimes))","sub_path":"scripts/process-commit-messages.py","file_name":"process-commit-messages.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"605266574","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nfrom django.conf import settings\nimport django.contrib.auth.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='CustomUser',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('phone', models.CharField(max_length=30, null=True, verbose_name=b'\\xd0\\xa2\\xd0\\xb5\\xd0\\xbb\\xd0\\xb5\\xd1\\x84\\xd0\\xbe\\xd0\\xbd', blank=True)),\n ('yandex_login', models.CharField(max_length=255, null=True, verbose_name=b'Yandex login', blank=True)),\n ('yandex_token', models.CharField(max_length=255, null=True, verbose_name=b'Yandex token', blank=True)),\n ('status_arch', models.BooleanField(default=False, verbose_name=b'\\xd0\\xa3\\xd1\\x87\\xd0\\xb5\\xd1\\x82\\xd0\\xbd\\xd0\\xb0\\xd1\\x8f \\xd0\\xb7\\xd0\\xb0\\xd0\\xbf\\xd0\\xb8\\xd1\\x81\\xd1\\x8c \\xd0\\xb2 \\xd0\\xb0\\xd1\\x80\\xd1\\x85\\xd0\\xb8\\xd0\\xb2\\xd0\\xb5')),\n ('yandex_role', models.CharField(max_length=255, null=True, verbose_name=b'\\xd0\\xa0\\xd0\\xbe\\xd0\\xbb\\xd1\\x8c \\xd0\\xb2 \\xd0\\xaf\\xd0\\xbd\\xd0\\xb4\\xd0\\xb5\\xd0\\xba\\xd1\\x81.\\xd0\\x94\\xd0\\xb8\\xd1\\x80\\xd0\\xb5\\xd0\\xba\\xd1\\x82\\xd0\\xb5', blank=True)),\n ('vk_code', models.CharField(max_length=255, null=True, verbose_name=b'VK code', blank=True)),\n ('vk_token', models.CharField(max_length=255, null=True, verbose_name=b'VK token', blank=True)),\n ('vk_account', models.CharField(max_length=255, null=True, verbose_name=b'VK account', blank=True)),\n ('account_leadr', models.IntegerField(verbose_name=b'\\xd0\\x90\\xd0\\xba\\xd0\\xba \\xd0\\xb2 \\xd1\\x81\\xd0\\xb8\\xd1\\x81\\xd1\\x82\\xd0\\xb5\\xd0\\xbc\\xd0\\xb5 lead-R')),\n ('account_advt', models.EmailField(max_length=254, verbose_name=b'\\xd0\\x90\\xd0\\xba\\xd0\\xba \\xd0\\xb2 \\xd1\\x80\\xd0\\xb5\\xd0\\xba\\xd0\\xbb\\xd0\\xb0\\xd0\\xbc\\xd0\\xbd\\xd0\\xbe\\xd0\\xb9 \\xd1\\x81\\xd0\\xb5\\xd1\\x82\\xd0\\xb8')),\n ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'Manager',\n 'verbose_name_plural': 'Managers',\n },\n managers=[\n ('objects', django.contrib.auth.models.UserManager()),\n ],\n ),\n ]\n","sub_path":"profile/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"299194100","text":"import json\nimport sys\nfrom datetime import datetime\nfrom io import StringIO\n\nimport six\nfrom prov.constants import PROV_QUALIFIEDNAME, PROV_ATTRIBUTES_ID_MAP, PROV_ATTRIBUTES, PROV_MEMBERSHIP, \\\n PROV_ATTR_ENTITY, PROV_ATTRIBUTE_QNAMES, PROV_ATTR_COLLECTION, XSD_ANYURI\nfrom prov.model import Literal, Identifier, QualifiedName, Namespace, parse_xsd_datetime\n\nfrom provdbconnector.db_adapters.baseadapter import METADATA_KEY_NAMESPACES\nfrom provdbconnector.exceptions.utils import SerializerException\n\nimport logging\n\nlog = logging.getLogger(__name__)\n\nlogger = logging.getLogger(__name__)\n# Reverse map for prov.model.XSD_DATATYPE_PARSERS\nLITERAL_XSDTYPE_MAP = {\n float: 'xsd:double',\n int: 'xsd:int'\n # boolean, string values are supported natively by PROV-JSON\n # datetime values are converted separately\n}\n\n# Add long on Python 2\nif six.integer_types[-1] not in LITERAL_XSDTYPE_MAP:\n LITERAL_XSDTYPE_MAP[six.integer_types[-1]] = 'xsd:long'\n\n\ndef encode_dict_values_to_primitive(dict_values):\n new_dict_values = dict()\n for key, value in dict_values.items():\n key_simple = str(key)\n new_dict_values.update({key_simple: encode_string_value_to_primitive(value)})\n\n return new_dict_values\n\n\ndef encode_string_value_to_primitive(value):\n if sys.version_info[0] < 3 and type(value) is unicode:\n return value.encode(\"utf8\")\n if isinstance(value, Literal):\n return value.value\n elif type(value) is int:\n return value\n elif type(value) is float:\n return value\n elif type(value) is bool:\n return value\n elif type(value) is list:\n return value\n elif type(value) is dict:\n io = StringIO()\n json.dump(value, io)\n return io.getvalue()\n return str(value)\n\n\ndef literal_json_representation(literal):\n # TODO: QName export\n value, datatype, langtag = literal.value, literal.datatype, literal.langtag\n if langtag:\n return {'lang': langtag}\n else:\n return {'type': six.text_type(datatype)}\n\n\ndef encode_json_representation(value):\n if isinstance(value, Literal):\n return literal_json_representation(value)\n elif isinstance(value, datetime):\n return {'type': 'xsd:dateTime'}\n elif isinstance(value, QualifiedName):\n # TODO Manage prefix in the whole structure consistently\n # TODO QName export\n return {'type': PROV_QUALIFIEDNAME._str}\n elif isinstance(value, Identifier):\n return {'type': 'xsd:anyURI'}\n elif type(value) in LITERAL_XSDTYPE_MAP:\n return {'type': LITERAL_XSDTYPE_MAP[type(value)]}\n else:\n return None\n\n\n# DECODE\n\ndef add_namespaces_to_bundle(prov_bundle, metadata):\n namespaces = dict()\n try:\n namespace_str = metadata[METADATA_KEY_NAMESPACES]\n except ValueError:\n SerializerException(\"No valid namespace provided, should be a string of a dict: {}\".format(metadata))\n return\n\n if type(namespace_str) is str:\n io = StringIO(namespace_str)\n namespaces = json.load(io)\n elif type(namespace_str) is dict:\n namespaces = namespace_str\n else:\n raise SerializerException(\n \"Namespaces metadata should returned as json string or dict not as {}\".format(type(namespace_str)))\n\n for prefix, uri in namespaces.items():\n if prefix is not None and uri is not None:\n if prefix != 'default':\n prov_bundle.add_namespace(Namespace(prefix, uri))\n else:\n prov_bundle.set_default_namespace(uri)\n else:\n SerializerException(\"No valid namespace provided for the metadata: {}\".format(metadata))\n\n\ndef create_prov_record(bundle, prov_type, prov_id, properties, type_map):\n \"\"\"\n\n :param bundle:\n :param prov_type: valid prov type like prov:Entry as string\n :param prov_id: valid id as string like :\n :param properties: dict{attr_name:attr_value} dict with all properties (prov and additional)\n :param type_map: dict{attr_name:type_str} Contains the type information for each property (only if type is necessary)\n :return: ProvRecord\n \"\"\"\n # Parse attributes\n if isinstance(properties, dict):\n properties_list = properties.items()\n elif isinstance(properties, list):\n properties_list = properties\n else:\n raise SerializerException(\n \"Please provide properties as list[(key,value)] or dict your provided: {}\".format(\n properties.__class__.__name__))\n\n attributes = dict()\n other_attributes = []\n # this is for the multiple-entity membership hack to come\n membership_extra_members = None\n for attr_name, values in properties_list:\n\n attr = (\n PROV_ATTRIBUTES_ID_MAP[attr_name]\n if attr_name in PROV_ATTRIBUTES_ID_MAP\n else bundle.valid_qualified_name(attr_name)\n )\n if attr in PROV_ATTRIBUTES:\n if isinstance(values, list):\n # only one value is allowed\n if len(values) > 1:\n # unless it is the membership hack\n if prov_type == PROV_MEMBERSHIP and \\\n attr == PROV_ATTR_ENTITY:\n # This is a membership relation with\n # multiple entities\n # HACK: create multiple membership\n # relations, one x each entity\n\n # Store all the extra entities\n membership_extra_members = values[1:]\n # Create the first membership relation as\n # normal for the first entity\n value = values[0]\n else:\n error_msg = (\n 'The prov package does not support PROV'\n ' attributes having multiple values.'\n )\n logger.error(error_msg)\n raise SerializerException(error_msg)\n else:\n value = values[0]\n else:\n value = values\n value = (\n bundle.valid_qualified_name(value)\n if attr in PROV_ATTRIBUTE_QNAMES\n else parse_xsd_datetime(value)\n )\n attributes[attr] = value\n else:\n value_type = None\n if type_map:\n value_type = type_map.get(attr_name)\n\n if isinstance(values, list):\n other_attributes.extend(\n (\n attr,\n decode_json_representation(value, value_type, bundle)\n )\n for value in values\n )\n else:\n # single value\n other_attributes.append(\n (\n attr,\n decode_json_representation(values, value_type, bundle)\n )\n )\n record = bundle.new_record(\n prov_type, prov_id, attributes, other_attributes\n )\n # HACK: creating extra (unidentified) membership relations\n if membership_extra_members:\n collection = attributes[PROV_ATTR_COLLECTION]\n for member in membership_extra_members:\n bundle.membership(\n collection, bundle.valid_qualified_name(member)\n )\n return record\n\n\ndef decode_json_representation(value, type, bundle):\n if isinstance(type, dict):\n # complex type\n datatype = type['type'] if 'type' in type else None\n datatype = bundle.valid_qualified_name(datatype)\n langtag = type['lang'] if 'lang' in type else None\n if datatype == XSD_ANYURI:\n return Identifier(value)\n elif datatype == PROV_QUALIFIEDNAME:\n return bundle.valid_qualified_name(value)\n else:\n # The literal of standard Python types is not converted here\n # It will be automatically converted when added to a record by\n # _auto_literal_conversion()\n return Literal(value, datatype, langtag)\n else:\n # simple type, just return it\n return value\n","sub_path":"provdbconnector/utils/serializer.py","file_name":"serializer.py","file_ext":"py","file_size_in_byte":8255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"296421028","text":"import asyncio\n\nimport dotenv\n\nfrom utils.iceteabot import Iceteabot\n\n\nasync def main():\n dotenv.load_dotenv()\n bot = Iceteabot()\n bot.setup_logging()\n await bot.setup_database()\n await bot.start()\n\n\nif __name__ == '__main__':\n asyncio.run(main())\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"390962348","text":"# -*- coding: utf-8 -*-\n__author__ = 'lnx'\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom TEB.displaySURFEX.CONVERTSURFEXTEXTE import loadfile\n\nPVfile = \"/home/lnx/MODELS/SURFEX/2_source/SURFEX_TRUNK_4818/trunk/MY_RUN/KTEST/lnx/TCANYON.TXT\"\n#STQfile = \"/home/lnx/MODELS/SURFEX/2_source/SURFEX_TRUNK_4818/trunk/MY_RUN/KTEST/hapex/TCANYON.TXT\"\n#test = \"/home/lnx/MODELS/SURFEX/2_source/SURFEX_TRUNK_4818/trunk/MY_RUN/KTEST/lnx/TCANYON.TXT\"\nSTQfile = \"/home/lnx/MODELS/SURFEX/2_source/SURFEX_TRUNK_4818/trunk/MY_RUN/KTEST/lnx/1_Platz_A_N/2017_242/TCANYON.TXT\"\nS2 = \"/home/lnx/MODELS/SURFEX/2_source/SURFEX_TRUNK_4818/trunk/MY_RUN/KTEST/lnx/2_Platz_A_N_Wiese/2017_242/TCANYON.TXT\"\nS3 = \"/home/lnx/MODELS/SURFEX/2_source/SURFEX_TRUNK_4818/trunk/MY_RUN/KTEST/lnx/3_Platz_A_N_Park/2017_242/TCANYON.TXT\"\nS4 = \"/home/lnx/MODELS/SURFEX/2_source/SURFEX_TRUNK_4818/trunk/MY_RUN/KTEST/lnx/4_Platz_B_N/2017_242/TCANYON.TXT\"\nS5 = \"/home/lnx/MODELS/SURFEX/2_source/SURFEX_TRUNK_4818/trunk/MY_RUN/KTEST/lnx/5_Platz_B_N_Wiese/2017_242/TCANYON.TXT\"\nS6 = \"/home/lnx/MODELS/SURFEX/2_source/SURFEX_TRUNK_4818/trunk/MY_RUN/KTEST/lnx/6_Platz_B_N_Park/2017_242/TCANYON.TXT\"\nFORCfile = \"/home/lnx/MODELS/SURFEX/3_input/met_forcing/201706_08_BOKU_ENGBA.txt\"\nPVvalues = loadfile(PVfile)\n#test = loadfile(test)\nSTQvalues = loadfile(STQfile)\nS2values = loadfile(S2)\nS3values = loadfile(S3)\nS4values = loadfile(S4)\nS5values = loadfile(S5)\nS6values = loadfile(S6)\n\nFORCvalues = pd.read_csv(FORCfile, delimiter=r\"\\s+\", skiprows=range(1,720)) #cut only last day = 30.8.2017\n#FORCvalues = FORCvalues[720:]\n#print PVvalues, STQvalues, FORCvalues['Td']\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nplt.title(u\"Influence of Materials\")\nax.plot(PVvalues, label=\"asphalt + PV\")\nax.plot(STQvalues, label=\"asphalt + plaster\")#, color=\"red\")\nax.plot(S4values, label=\"concrete + plaster\")#, color=\"blue\")\nax.plot(FORCvalues['Td'],label=\"forcing (roof)\")\nax.set_ylabel(u'canyon air temperature [°C]')\nax.set_xlabel('[10min since 0UTC]')\nax.legend(loc=\"upper left\")\nplt.show()\n\nexit()\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nplt.title(\"Einfluss des Vegetation bei Asphalt\")\n#ax.plot(PVvalues, label=\"PV(canyon)\")\n#ax.plot(test, label=\"test\")\nax.plot(STQvalues, label=\"keine Vegetation\")\nax.plot(S2values, label=\"Wiese\")\nax.plot(S3values, label=\"Park\")\nax.plot(FORCvalues['Td'],label=\"Forcing (Dach)\")\nax.set_ylabel(u'Lufftemperatur 2m [°C]')\nax.set_xlabel('[10min seit 0UTC]')\nax.legend(loc=\"upper left\")\nplt.show()\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nplt.title(\"Einfluss des Vegetation bei Beton\")\n#ax.plot(PVvalues, label=\"PV(canyon)\")\nax.plot(S4values, label=\"keine Vegetation\")\nax.plot(S5values, label=\"Wiese\")\nax.plot(S6values, label=\"Park\")\nax.plot(FORCvalues['Td'],label=\"Forcing (Dach)\")\nax.set_ylabel(u'Lufftemperatur 2m [°C]')\nax.set_xlabel('[10min seit 0UTC]')\nplt.legend(loc=\"upper left\")\nplt.show()\n\n\n","sub_path":"3_PVOPTIRay/notused/PV_Place_Tair_engl.py","file_name":"PV_Place_Tair_engl.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"442498347","text":"'''\n======================\nTP4 - matplotlib\nYAN Wenli - PENG Hanyuan\n======================\n'''\nimport random\nimport numpy as np\nfrom tkinter import *\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plot\n\n#datas\nnumbers_x = [1,2,3,4,5,6,7,8,9,10]\nnumbers_y = np.random.randint(30,size=10)\nnumbers_y2 = np.random.randint(30,size=10)\nnumbers_y3 = np.random.randint(20,size=10)\n\n\ndef quitProgram():\n bg.destroy()\n\ndef quick_sort(lists, left, right):\n\n if left >= right:\n return lists\n key = lists[left]\n low = left\n high = right\n while left < right:\n while left < right and lists[right] >= key:\n right -= 1\n lists[left] = lists[right]\n while left < right and lists[left] <= key:\n left += 1\n lists[right] = lists[left]\n lists[right] = key\n quick_sort(lists, low, left - 1)\n quick_sort(lists, left + 1, high)\n return lists\n\ndef drawScatter():\n\n global plot\n plot.figure('Scatter fig')\n\n ax = plot.gca()\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n\n l1 = ax.scatter(numbers_x, numbers_y, c='g', marker = 'o', s=10, alpha=0.5)\n l2 = ax.scatter(numbers_x, numbers_y2, c='blue', marker = '*', s=10, alpha=0.5)\n\n plot.plot([0, 10], [0, 30], color = 'red', linestyle = 'solid')\n plot.annotate(text=\"this point is important\", xy=(5, 15), xytext=(6, 16),arrowprops={\"arrowstyle\":\"->\"})\n\n plot.legend(handles = [l1, l2,], labels = ['a', 'b'], loc = 'best')\n plot.show()\n\n\ndef drawLine():\n global plot\n plot.figure('Line fig')\n # plot.xlabel('X axis')\n # plot.ylabel('Y axis')\n ax = plot.gca()\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n\n g1 = ax.plot(numbers_x, numbers_y, c='r', linewidth=1, alpha=0.6)\n g2 = ax.plot(numbers_x, numbers_y2, color='#054E9F', linewidth=1, alpha=0.6)\n g3 = ax.plot(numbers_x, numbers_y3, color='#1DF09B', linewidth=1, alpha=0.6)\n plot.legend(handles = [g1,g2,g3,], labels = ['line1', 'line2','line3'], loc = 'best')\n plot.show()\n\ndef drawHisto():\n\n global plot\n plot.figure('Historique Bar fig')\n ax = plot.gca()\n ax.set_xlabel('value')\n ax.set_ylabel('count')\n\n xticks = np.arange(1, len(numbers_x)+1)\n bar_width=0.5\n\n ax.bar(xticks, numbers_y, width=bar_width, edgecolor='none')\n ax.set_xticks(xticks)\n\n ax.set_xticklabels(numbers_x)\n ax.set_xlim(0,len(xticks))\n plot.show()\n\ndef drawCamenbert():\n\n plot.figure('Camenbert fig',figsize = (5, 5))\n x = [1, 2, 3, 4, 10]\n plot.pie(x, labels = ['A', 'B', 'C', 'D', 'E'],\n colors = ['red', 'green', 'yellow', 'blue', 'pink'],\n explode = [0, 0.2, 0, 0, 0],\n autopct = lambda x: str(round(x, 2)) + '%',\n pctdistance = 0.7, labeldistance = 0.4,\n shadow = True)\n plot.legend(loc='upper left')\n plot.show()\n\ndef showAllFigs():\n fig = plot.figure()\n ax1 = fig.add_subplot(223)\n ax2 = fig.add_subplot(221)\n ax3 = fig.add_subplot(222)\n ax4 = fig.add_subplot(224)\n\n ax1.plot(range(5), color = 'blue')\n ax2.bar(range(5), range(5), color = 'green')\n ax3.plot(range(5), color = 'red')\n ax4.plot(range(5), color = 'black')\n\n # ax3 = fig.add_subplot(224)\n\n # plot.subplot(1, 2, 1)\n # plot.scatter(range(5), [x ** 2 for x in range(5)], color = 'blue')\n # # plot.subplot(2, 2, 2)\n # plot.bar(range(5), range(5), color = 'green')\n # # plot.subplot(2, 2, 4)\n # plot.plot(range(5), color = 'red')\ndef fun(x, y):\n return x**2 + y\n\ndef mesh_2d_3d():\n fig = plot.figure('3D Mesh fig') # titre\n ax = fig.add_subplot(111, projection='3d') #une image en 3D\n\n\n # x = y = np.arange(-3.0, 3.0, 0.05)\n # X, Y = np.meshgrid(x, y)\n # zs = np.array([fun(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])\n # Z = zs.reshape(X.shape)\n\n # ax.plot_surface(X,Y,Z)\n x = np.random.sample(100)\n y = np.random.sample(100)\n\n ax.set_xlim(0, 1)\n ax.set_ylim(0, 1)\n ax.set_zlim(0, 1)\n ax.set_xlabel('X')\n ax.set_ylabel('Y')\n ax.set_zlabel('Z')\n\n ax.scatter(x, y, zs=0, zdir='y', label='points in (x,z)')\n ax.legend()\n plot.show()\n\ndef mesh_3d():\n fig = plot.figure('3D Mesh fig')\n ax = fig.add_subplot(111, projection='3d')\n\n x = y = np.arange(-3.0, 3.0, 0.05)\n X, Y = np.meshgrid(x, y)\n zs = np.array([fun(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])\n Z = zs.reshape(X.shape)\n\n ax.plot_surface(X,Y,Z)\n plot.show()\n\n\nif __name__ == '__main__':\n\n bg = Tk()\n #window\n bg.geometry('720x200+500+200')\n bg.title('Python TP4 : Matplotlib')\n\n #labels\n label = Label(bg,text=\"Please choose a mode from the menu.\").grid(row=0, column=0, columnspan=6, sticky=N+W+S+E)\n label_warning = Label(bg,\n text = 'Warning: We choose single mode window. So you should close the current mode window when you want to open another mode!\\n Otherwise, it will crash!',\n bg = 'yellow',\n height = 4,\n wraplength = 300,\n justify = 'center').grid(row=1, column=0, columnspan=6,sticky=N+W+S+E)\n\n btn_scatter = Button(text='Scatter fig',relief=RIDGE, width = 10, command=drawScatter).grid(row=3,column=0)\n btn_line = Button(text='Line fig',relief=RIDGE,width = 10,command=drawLine).grid(row=3,column=1)\n btn_histogramme = Button(text='Histo fig',relief=RIDGE,width = 10,command=drawHisto).grid(row=3,column=2)\n btn_camenbert = Button(text='Camenbert fig',relief=RIDGE,width = 10,command=drawCamenbert).grid(row=3,column=3)\n btn_2d_3d = Button(text='2D_in_3D fig',relief=RIDGE,width = 10,command=mesh_2d_3d).grid(row=3,column=4)\n btn_3d = Button(text='3D fig',relief=RIDGE,width = 10,command=mesh_3d).grid(row=3,column=5)\n btn_all = Button(text='Show all figures together',relief=RIDGE,width = 10,command=showAllFigs).grid(row=4,column=0, columnspan=6,sticky=N+W+S+E)\n\n\n #buttons\n menuBar = Menu(bg)\n bg.config(menu=menuBar)\n\n #menus\n modeMenu = Menu(menuBar)\n menuBar.add_cascade(label=\"Mode\", menu=modeMenu)\n modeMenu.add_command(label=\"Scatter\", command=drawScatter)\n modeMenu.add_command(label=\"Line\", command=drawLine)\n modeMenu.add_command(label=\"Histo\", command=drawHisto)\n modeMenu.add_command(label=\"Camenbert\", command=drawCamenbert)\n modeMenu.add_command(label=\"22D_in_3D\", command=mesh_2d_3d)\n modeMenu.add_command(label=\"3DMesh\", command=mesh_3d)\n\n modeMenu.add_separator()\n modeMenu.add_command(label=\"Exit\", command=quitProgram)\n\n bg.mainloop()\n","sub_path":"TP4/tp4.py","file_name":"tp4.py","file_ext":"py","file_size_in_byte":6564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"82390177","text":"\"\"\"\nDrives. Can accept input from joysticks or values [-1, 1].\n\"\"\"\nimport helpers\nimport wpilib\nimport math\nfrom networktables import NetworkTables\n\nclass Chassis(object):\n def __init__(self, drive, gyro, encoderY):\n self.drive = drive\n self.gyro = gyro\n self.encoderY = encoderY\n self.jDeadband = 0.06\n self.sd = NetworkTables.getTable('SmartDashboard')\n\n # PID loop for angle\n self.pidAngleDefault = {'p': 0.01, 'i': 0, 'd': 0.004}\n self.sd.putNumber('pidAngleP', self.pidAngleDefault['p'])\n self.sd.putNumber('pidAngleI', self.pidAngleDefault['i'])\n self.sd.putNumber('pidAngleD', self.pidAngleDefault['d'])\n\n self.pidAngle = wpilib.PIDController(self.pidAngleDefault['p'], self.pidAngleDefault['i'], self.pidAngleDefault['d'], self.gyro, self.updateAnglePID)\n self.pidAngle.setAbsoluteTolerance(2)\n self.pidRotateRate = 0\n self.wasRotating = False\n\n # PID loop for Cartesian Y direction\n self.pidYDefault = {'p': 0.15, 'i': 0, 'd': 0.05}\n self.sd.putNumber('pidYP', self.pidYDefault['p'])\n self.sd.putNumber('pidYI', self.pidYDefault['i'])\n self.sd.putNumber('pidYD', self.pidYDefault['d'])\n\n self.pidY = wpilib.PIDController(self.pidYDefault['p'], self.pidYDefault['i'], self.pidYDefault['d'], self.encoderY.getDistance, self.updateYPID)\n self.pidYRate = 0\n\n self.toDistanceFirstCall = True\n self.toAngleFirstCall = True\n self.toTimeFirstCall = True\n self.lastAngle = 0\n\n self.timer = wpilib.Timer()\n\n def run(self, x, y, rotation):\n '''Intended for use in telelop. Use .cartesian() for auto.'''\n # Map joystick values to curve\n x = self.curve(helpers.deadband(x, 0.1))\n y = self.curve(helpers.deadband(y, 0.1))\n rotation = helpers.deadband(-rotation * 0.5, 0.1)\n\n # write manipulated values to motors\n self.cartesian(-x, y, rotation)\n\n def cartesian(self, x, y, rotation):\n # assign speeds\n speeds = [0] * 4\n speeds[0] = x + y + rotation # front left\n speeds[1] = -x + y - rotation # front right\n speeds[2] = -x + y + rotation # back left\n speeds[3] = x + y - rotation # back right\n\n # scales all speeds if one is in range\n # (-inf, -1) U (1, inf)\n maxSpeed = max(abs(x) for x in speeds)\n if maxSpeed > 1.0:\n for i in range(0, 4):\n speeds[i] = speeds[i] / maxSpeed\n\n # write speeds to controllers\n for i in range(0, 4):\n self.drive[i].set(speeds[i])\n\n def updateAnglePID(self, value):\n self.pidAngle.setP(self.sd.getNumber('pidAngleP', self.pidAngleDefault['p']))\n self.pidAngle.setI(self.sd.getNumber('pidAngleI', self.pidAngleDefault['i']))\n self.pidAngle.setD(self.sd.getNumber('pidAngleD', self.pidAngleDefault['d']))\n\n self.pidRotateRate = value\n\n def updateYPID(self, value):\n self.pidY.setP(self.sd.getNumber('pidYP', self.pidYDefault['p']))\n self.pidY.setI(self.sd.getNumber('pidYI', self.pidYDefault['i']))\n self.pidY.setD(self.sd.getNumber('pidYD', self.pidYDefault['d']))\n\n self.pidYRate = value\n\n def curve(self, value):\n \"\"\"Because this divides by sin(1), an input\n in range [-1, 1] will always have an output\n range of [-1, 1]. \"\"\"\n\n value = helpers.deadband(helpers.raiseKeepSign(value, 1), self.jDeadband)\n\n return (math.sin(value) / math.sin(1));\n\n def toAngle(self, angle, reset=False):\n \"\"\"Intended for use in auto.\"\"\"\n if (self.toAngleFirstCall and reset == True):\n self.gyro.reset()\n self.toAngleFirstCall = False\n\n self.pidAngle.setSetpoint(angle)\n self.pidAngle.enable()\n\n #print(self.pidAngle.getError())\n\n if (self.pidAngle.getError() < 0.5):\n self.pidAngle.disable()\n self.toAngleFirstCall = True\n self.lastAngle = angle\n return True\n else:\n self.cartesian(0, 0, -self.pidRotateRate)\n return False\n\n def toDistance(self, distance):\n \"\"\"Intended for use in auto.\"\"\"\n if (self.toDistanceFirstCall):\n self.encoderY.reset()\n self.toDistanceFirstCall = False\n\n self.pidY.setContinuous(False)\n self.pidY.setSetpoint(distance)\n self.pidY.enable()\n\n # simple P for rotation\n rotation = helpers.remap((self.lastAngle - self.gyro.getAngle()), -180, 180, -1, 1)\n rotation = rotation * 1\n #print(self.pidY.getError())\n rotation = 0\n if (self.pidY.getError() < 0.05):\n self.pidY.disable()\n self.cartesian(0, 0, 0)\n self.toDistanceFirstCall = True\n return True\n else:\n self.cartesian(0, -self.pidYRate, -rotation)\n return False\n\n def toTime(self, time, power):\n if (self.toTimeFirstCall):\n self.timer.start()\n self.toTimeFirstCall = False\n\n if (self.timer.hasPeriodPassed(time)):\n self.cartesian(0, 0, 0)\n return True\n else:\n self.cartesian(0, -power, 0)\n return False\n","sub_path":"components/chassis.py","file_name":"chassis.py","file_ext":"py","file_size_in_byte":5297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"4378999","text":"# Copyright Pincer 2021-Present\n# Full MIT License can be found in `LICENSE` at the project root.\n\n\"\"\"sent when a channel is updated\"\"\"\n\nfrom ..core.dispatch import GatewayDispatch\nfrom ..objects import Channel\nfrom ..utils.conversion import construct_client_dict\n\n\nasync def channel_update_middleware(self, payload: GatewayDispatch):\n \"\"\"|coro|\n\n Middleware for ``on_channel_update`` event.\n\n Parameters\n ----------\n payload : :class:`GatewayDispatch`\n The data received from the channel update event.\n\n Returns\n -------\n Tuple[:class:`str`, List[:class:`~pincer.objects.channel.channel.Channel`]]\n ``on_channel_update`` and a ``Channel``\n \"\"\"\n\n channel = Channel.from_dict(construct_client_dict(self, payload.data))\n\n if channel.guild_id in self.guilds.keys():\n guild = self.guilds[channel.guild_id]\n old = filter(lambda c: c.id == channel.id, guild.channels)\n if old:\n guild.channels.remove(old)\n guild.channels.append(channel)\n\n return \"on_channel_update\", [channel]\n\n\ndef export():\n return channel_update_middleware\n","sub_path":"pincer/middleware/channel_update.py","file_name":"channel_update.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"472226419","text":"from django.shortcuts import render\nfrom .models import GiftCard, ProductPrice\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom datetime import datetime\nimport json\n\n\n# helper func to check if eligible black friday dates\ndef is_black_friday(date):\n allowed_dates = ('11-23', '11-24', '11-25')\n return date.strftime(\"%m-%d\") in allowed_dates\n\n\n@csrf_exempt\ndef product_price(request):\n if request.method == 'POST':\n # get args from request\n payload = json.loads(request.body)\n productCode = payload['productCode']\n date = datetime.strptime(payload['date'], \"%Y-%m-%d\")\n try:\n giftCardCode = payload['giftCardCode']\n except:\n giftCardCode = None\n giftCardAmount = 0\n\n # check if within black friday dates\n if is_black_friday(date):\n product = ProductPrice.objects.filter(name=\"Black Friday\", productCode=productCode).first()\n # check if 2019 prices apply\n elif date.strftime(\"%Y\") == '2019':\n product = ProductPrice.objects.filter(name=\"2019\", productCode=productCode).first()\n # original pricing\n else:\n product = ProductPrice.objects.filter(name=\"Standard\", productCode=productCode).first()\n\n if giftCardCode is not None:\n # get amount for gift card if is after start date\n giftCard = GiftCard.objects.filter(code=giftCardCode, date_start__lte=date).first()\n\n if giftCard is not None:\n # check if there is an end date, then check if we passed it\n if giftCard.date_end is None or giftCard.date_end >= date.date():\n giftCardAmount = giftCard.amount\n\n # don't let price be negative\n price = max(product.price - giftCardAmount, 0)\n\n # setup response format\n try:\n response = json.dumps([{\n 'Product': product.productCode,\n 'Type': product.name,\n 'Price': price\n }])\n except:\n response = json.dumps([{'Error': 'Error getting price'}])\n # return json\n return HttpResponse(response, content_type='text/json')\n","sub_path":"smilewidgets/products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"509962822","text":"import xbmcgui\nfrom urllib.parse import urlsplit\n\nfrom resources.lib import stream_resolver\nfrom resources.lib import utils\nfrom resources.lib.utils import ADDON_ID, ICON_NEXT, ICON_240, ICON_360, ICON_720\n\n\"\"\"\n Main API for tamilyogi site\n\"\"\"\n\n\nclass TamilYogi(object):\n def __init__(self, plugin):\n self.plugin = plugin\n\n @property\n def get_site_name(self):\n \"\"\"\n set site name\n :return:\n \"\"\"\n return \"tamilyogi\"\n\n def get_main_url(self):\n \"\"\"\n site site main url\n :return:\n \"\"\"\n return \"http://tamilyogi.vip/\"\n\n def get_sections(self):\n \"\"\"\n get all section for tamilyogi website\n :return:\n \"\"\"\n sections = [\n {\n \"name\": \"Tamil New Movies\",\n \"url\": \"http://tamilyogi.vip/category/tamilyogi-full-movie-online/\",\n },\n {\n \"name\": \"Tamil Bluray Movies\",\n \"url\": \"http://tamilyogi.vip/category/tamilyogi-bluray-movies/\",\n },\n {\n \"name\": \"Tamil DVDRip Movies\",\n \"url\": \"http://tamilyogi.vip/category/tamilyogi-dvdrip-movies/\",\n },\n {\n \"name\": \"Tamil Dubbed Movies\",\n \"url\": \"http://tamilyogi.vip/category/tamilyogi-dubbed-movies-online/\",\n },\n {\n \"name\": \"Tamil Web Series\",\n \"url\": \"http://tamilyogi.vip/category/tamil-web-series/\",\n },\n {\"name\": \"Search\", \"url\": \"http://tamilyogi.vip/search\"},\n ]\n\n return [section for section in sections if section[\"name\"] and section[\"url\"]]\n\n def get_movies(self, url):\n \"\"\"\n get all movies from given section url\n :param url:\n :return:\n \"\"\"\n movies = []\n added_items = []\n img = \"\"\n next_page = {}\n infos = {}\n\n if url == \"http://tamilyogi.vip/search\":\n s = xbmcgui.Dialog().input(\n \"Search for movie name\", type=xbmcgui.INPUT_ALPHANUM\n )\n if s == \"\":\n return []\n\n url = \"http://tamilyogi.vip/?s={}\".format(s)\n\n soup = utils.get_soup_from_url(url)\n\n for a in soup.find_all(\"a\"):\n title = a.get(\"title\")\n try:\n nextpagetag = a.get(\"class\")\n if \"next\" in nextpagetag:\n next_page_url = a.get(\"href\")\n next_page = {\n \"name\": \"Next Page\",\n \"image\": ICON_NEXT,\n \"infos\": {},\n \"url\": next_page_url,\n }\n except:\n pass\n\n try:\n img = a.find(\"img\")[\"src\"]\n except:\n pass\n\n if (title is not None) and (title != \"Tamil Movie Online\") and img != \"\":\n print(utils.movie_name_resolver(title))\n try:\n if title not in added_items:\n d = dict(\n name=utils.movie_name_resolver(title),\n image=img,\n url=a.get(\"href\"),\n infos={\"title\": utils.movie_name_resolver(title)},\n )\n movies.append(d)\n added_items.append(title)\n except Exception as e:\n print(e)\n\n if bool(next_page): # If next page\n movies.append(next_page)\n\n # if len(movies) == 0:\n # self.plugin.notify(msg=\"404 No movies found\", title='Not found')\n return [movie for movie in movies if movie[\"name\"] and movie[\"url\"]]\n\n def get_stream_urls(self, movie_name, url):\n \"\"\"\n get stream urls from movie page url.\n :param movie_name:\n :param url:\n :return:\n \"\"\"\n stream_urls = None\n soup = utils.get_soup_from_url(url)\n l = soup.find_all(\"iframe\")\n for iframe in l:\n\n src = iframe.get(\"src\")\n if src is None:\n continue\n\n link = urlsplit(src)\n host = link.hostname\n host = host.replace(\"www.\", \"\")\n host = host.replace(\".com\", \"\")\n host = host.replace(\".tv\", \"\")\n host = host.replace(\".net\", \"\")\n host = host.replace(\".cc\", \"\")\n host = host.replace(\".sx\", \"\")\n host = host.replace(\".to\", \"\")\n\n print(\"hostname is ---> \" + host)\n\n if host.lower() == \"vidmad\":\n stream_urls = stream_resolver.load_vidmad_video(src)\n\n elif host.lower() == \"vidmx.xyz\":\n stream_urls = stream_resolver.load_vidmx_video(src)\n\n elif host.lower() == \"fastplay\":\n # print(src)\n stream_urls = stream_resolver.load_fastplay_video(src)\n\n elif host.lower() == \"vidorg\":\n stream_urls = stream_resolver.load_vidorg_videos(src)\n\n elif host.lower() == \"vembx.one\":\n stream_urls = stream_resolver.load_vembxone_videos(src)\n else:\n print(\"Host ingored!!\")\n\n # stream_urls = [{\n # 'name': movie_name,\n # 'quality': 'HD',\n # 'url': steam_url\n # }]\n\n return [\n {\n \"name\": movie_name,\n \"quality\": stream_url[\"quality\"],\n \"quality_icon\": stream_url[\"quality_icon\"],\n \"url\": stream_url[\"url\"],\n }\n for stream_url in stream_urls\n if stream_url[\"url\"]\n ]\n","sub_path":"plugin.video.tamilstreamer/resources/lib/tamilyogi.py","file_name":"tamilyogi.py","file_ext":"py","file_size_in_byte":5774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"328264960","text":"from django.urls import path\nfrom . import views\n\n# SET THE NAMESPACE!\napp_name = 'basicapp'\n\nurlpatterns = [\n \n path('', views.tasks_list,name='tasks_list'),\n path('/delete/', views.tasks_delete,name='tasks_delete'),\n]\n","sub_path":"todo/basicapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"297917494","text":"#--------------------------------------------------------------------\n# Import modules\n#--------------------------------------------------------------------\n\nfrom simep.scenarii.metascenario import MetaScenario\n\n\n\n#--------------------------------------------------------------------\n# Define slave file : this is the file which will be generated just before simulation\n#--------------------------------------------------------------------\n\nSimulationSlaveFile = 'C:/st_repository/simep_scenarii/gui\\\\SimepRunner_ABBN_VX_18_2010823_slave.py'\nInputXMLFile = 'C:/st_sim/simep/st_sim.xml'\n\n\n\n#--------------------------------------------------------------------\n# Write all the dictionaries of parameters\n#--------------------------------------------------------------------\n\nEngineParametersDictionary = {\n 'number_of_bt' : 10,\n 'full' : True\n}\nExchangeParametersDictionary = {\n 'date' : '20100823',\n 'trading_destination_id' : 18,\n 'input_file_name' : 'Q:/tick_ged',\n 'trading_destination_name' : 'VIRTX',\n 'security_id' : 80940,\n 'ric' : 'ABBN.VX',\n 'data_type' : 'TBT2'\n}\nOrdersReplayer001_params = {\n 'setup' : {'name' : 'OrdersReplayer001'},\n 'context' : {'date' : '20100823', \n 'security_id' : 80940, \n 'trading_destination_id' : 18, \n 'ric' : 'ABBN.VX'},\n 'parameters' : {'delta_t' : '00:00:01:000',\n 'loading_method' : 'headed_text_file', \n 'cmd_filename' : 'C:/st_sim/dev/usr/benca/data/detail_occ_3_modified.txt'}\n}\n\n\n\n#--------------------------------------------------------------------\n# Define meta-scenario\n#--------------------------------------------------------------------\n\nMyScenario = MetaScenario(InputXMLFile, SimulationSlaveFile)\nMyScenario.SetEngine('ROBModel', EngineParametersDictionary)\nMyScenario.SetUniverse({'20100823' : [ExchangeParametersDictionary]})\nMyScenario.AddTrader('OrdersReplayer', OrdersReplayer001_params)\nMyScenario.GenerateAndRunSimulations('C:/st_repository/simep_scenarii/gui')\n\n\n\n","sub_path":"usr/benca/scenarii/SimepRunner_ABBN_VX_18_2010823.py","file_name":"SimepRunner_ABBN_VX_18_2010823.py","file_ext":"py","file_size_in_byte":2405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"214399289","text":"import sys, os\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom UcsBase import ManagedObject\nsys.path.remove(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nclass ExtvmmFabricNetworkDefinition(ManagedObject):\n\tdef __init__(self):\n\t\tManagedObject.__init__(self,\"ExtvmmFabricNetworkDefinition\")\n\n\t@staticmethod\n\tdef ClassId():\n\t\treturn \"extvmmFabricNetworkDefinition\"\n\n\tALLOWED_VNIC_TYPE = \"AllowedVnicType\"\n\tDESCR = \"Descr\"\n\tDN = \"Dn\"\n\tGUID = \"Guid\"\n\tNAME = \"Name\"\n\tPOLICY_LEVEL = \"PolicyLevel\"\n\tPOLICY_OWNER = \"PolicyOwner\"\n\tPRIMARY_VLAN_ID = \"PrimaryVlanId\"\n\tREF_OPER_STATE = \"RefOperState\"\n\tRN = \"Rn\"\n\tSTATUS = \"Status\"\n\n\tCONST_ALLOWED_VNIC_TYPE_ETHER = \"ether\"\n\tCONST_ALLOWED_VNIC_TYPE_FC = \"fc\"\n\tCONST_ALLOWED_VNIC_TYPE_IPC = \"ipc\"\n\tCONST_ALLOWED_VNIC_TYPE_SCSI = \"scsi\"\n\tCONST_ALLOWED_VNIC_TYPE_UNKNOWN = \"unknown\"\n\tCONST_INT_ID_NONE = \"none\"\n\tCONST_POLICY_OWNER_LOCAL = \"local\"\n\tCONST_POLICY_OWNER_PENDING_POLICY = \"pending-policy\"\n\tCONST_POLICY_OWNER_POLICY = \"policy\"\n\tCONST_REF_OPER_STATE_INVALID_REFERENCE = \"invalid-reference\"\n\tCONST_REF_OPER_STATE_UP = \"up\"\n","sub_path":"UcsSdk-0.8.3/src/UcsSdk/MoMeta/ExtvmmFabricNetworkDefinition.py","file_name":"ExtvmmFabricNetworkDefinition.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"363944604","text":"#!/usr/bin/env python\n# -*- coding: latin-1 -*-\n#█▀▀▀▀█▀▀▀▀▀██▀▀▀▀██▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▓▒▀▀▀▀▀▀▀▀▀▀█▓▀ ▀▀▀██▀▀▀▀▀▀▀▀▀▓▓▀▀▀▀▀▀▀▀▀▌\n#▌▄██▌ ▄▓██▄ ▀▄█▓▄▐ ▄▓█▓▓▀█ ▄▓██▀▓██▓▄ ▌▄█▓█▀███▓▄ ▌▄█▓█ ▀ ▄▓██▀▓██▓▄ ▄█▓█▀███▄■\n#▌▀▓█▓▐▓██▓▓█ ▐▓█▓▌▐▓███▌■ ▒▓██▌ ▓██▓▌▐▓▒█▌▄ ▓██▓▌ ▐▓▒█▌▐ ▒▓██▌ ▓██▓▌▓▒█▌ ▓█▓▌\n#▐▓▄▄▌░▓▓█▓▐▓▌ █▓▓▌░▓▓█▓▄▄ ▓▓██▓▄▄▓█▓▓▌░▓█▓ █ ▓█▓▓▌░▓█▓ ▒ ▓▓██▓▄▄▓█▓▓▌▓█▓ ░ ▓█▓▓\n#▐▓▓█▌▓▓▓█▌ █▓▐██▓▌▐▓▒▓▌ ▄ ▐░▓█▌▄ ▀▀▀ ▐▓▓▓ ▐▌ ▀▀▀ ▐▓▓▓▄▄ ▐░▓█▌ ▄ ▀▀▀ ▓▓▓ ░ ██▓▓\n#▐▓▓▓█▐▓▒██ ██▓▓▓▌▐▓▓██ █▌▐▓▓▒▌▐ ███░▌▐▓▓▒▌▐ ███░▌ ▐▓▓▒▌ ▐▓▓▒▌▀ ███░▌▓▓▒▌ ███░\n# ▒▓▓█▌▒▓▓█▌ ▐▓█▒▒ ▒▓██▌▐█ ▒▓▓█ ▐█▓▒▒ ▒▒▓█ ▐█▓▒▒ ▒▒▓█ ▓▌▒▓▓█ ▐█▓▒▒ ▒▒▓█ ▐█▓▒▌\n#▌ ▒▒░▀ ▓▒▓▀ ▀░▒▓ ▐▌ ▓▓▓▀ █ █▒▓▀▀░█▓ ▄▌ ▒▒▓▀▀░█▓ ▄▌ ▒▒▓▀▀ █▒▓▀▀░█▓ ▒▒▓▀▀░█▀\n#█▄ ▀ ▄▄ ▀▄▄▀■ ▀ ▀▓█▄ ▀ ▄█▓█▄ ▀ ▓▄▄▄▄▄█▀ ▄▀ ▄▄▄▄▄▄█▓▄ ▀ ▄▄█▓▄▀ ▄▓▄█▄▀ ▄▄▄█▌\n#\n# Copyright (C) 2015 Jonathan Racicot\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n# \n# Jonathan Racicot\n# infectedpacket@gmail.com\n# 2015-03-26\n# https://github.com/infectedpacket\n\n#//////////////////////////////////////////////////////////////////////////////\n# Import Statements \nfrom Exceptions import InvalidPageNumberException\nfrom Exceptions import InvalidByteSizeException\nfrom Exceptions import MemoryAccessViolationException\n#//////////////////////////////////////////////////////////////////////////////\n# Memory Class\n#\nclass Memory(object):\n\n\tdef __init__(self, _nbpages, _bytesize, _bytes_per_page, _readonly = False, _logger=None):\n\t\tself.logger = _logger\n\t\tif (self.logger): self.logger.print_debug(\"Creating {:d} page(s) of memory, with {:d} bytes/page. Read-only: {:b}\".format(_nbpages, _bytes_per_page, _readonly)) \n\n\t\tself.readonly = _readonly\n\n\t\tif _nbpages < 1:\n\t\t\traise InvalidPageNumberException(_nbpages)\n\t\telse:\n\t\t\tself.nbpages = _nbpages\n\n\t\tif _bytesize < 1:\n\t\t\traise InvalidByteSizeException(_bytesize)\n\t\telse:\n\t\t\tself.bytesize = _bytesize\n\n\t\tif _bytes_per_page < 1:\n\t\t\traise InvalidByteSizeException(_bytes_per_page)\n\t\telse:\n\t\t\tself.bytes_per_page = _bytes_per_page\n\n\t\tself.memory = [0] * (self.nbpages * self.bytes_per_page)\n\n\tdef write(self, _page, _offset, _bytes):\n\t\tif (self.logger): self.logger.print_debug(\"Writing {:d} byte(s) to memory at {:04X}:{:04X}\".format(len(_bytes), _page, _offset)) \n\t\tif (self.readonly):\n\t\t\traise MemoryAccessViolationException(\"trying to write to read-only memory.\")\n\t\telse:\n\t\t\tsegment = _page * self.bytes_per_page\n\t\t\tmemptr = segment + _offset\n\t\t\tif (self.logger): self.logger.print_debug(\"{:04X}:{:04X} translated to {:02X}\".format(_page, _offset, memptr)) \n\t\t\tif (memptr + len(_bytes)) > len(self.memory):\n\t\t\t\traise MemoryAccessViolationException(\"not enough memory.\")\n\t\t\tfor i in range(0, len(_bytes)):\n\t\t\t\tself.memory[memptr+i] = _bytes[i]\n\t\t\tif (self.logger): self.logger.print_debug(\"{:d} byte(s) written to {:04X}:{:04X}.\".format(len(_bytes), _page, _offset)) \n\t\t\t\n\n\tdef flash(self, _bytes):\n\t\tif (self.logger): self.logger.print_debug(\"Flashing {:d} byte(s) to memory.\".format(len(_bytes))) \n\t\tmem_protect = self.readonly\n\t\tself.readonly =False\n\t\tself.write(0, 0, _bytes)\n\t\tself.readonly = mem_protect\n\n\t\t\n\tdef read(self, _page, _offset, _nbbytes):\n\t\tif (self.logger): self.logger.print_debug(\"Reading {:d} byte(s) from memory {:04X}:{:04X}\".format(_nbbytes, _page, _offset)) \n\t\tsegment = _page * self.bytes_per_page\n\t\tmemptr = segment + _offset\n\t\tbytes_read = []\n\t\tfor i in range(0, _nbbytes):\n\t\t\tif memptr + i > len(self.memory):\n\t\t\t\traise MemoryAccessViolationException(\"memory pointer out of bounds: {:04X}.\".format(memptr+i))\n\t\t\telse:\n\t\t\t\tbytes_read.append(self.memory[memptr+i])\n\t\treturn bytes_read\n\n\tdef list_memory(self, _page, _offset, _nbbytes, _logger):\n\t\tsegment = _page * self.bytes_per_page\n\t\tmemptr = segment + _offset\n\t\tfor i in range(0, _nbbytes):\n\t\t\tsegment = int((memptr+i)/self.bytes_per_page)\n\t\t\toffset = int((memptr+i) % self.bytes_per_page)\n","sub_path":"Memory.py","file_name":"Memory.py","file_ext":"py","file_size_in_byte":5671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"119452474","text":"#!/usr/bin/env/python\nimport os\nfrom setuptools import setup\n\n\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\n\nsetup(\n name=\"askminmax\",\n version=\"1.0.0\",\n author=\"Aurko Roy\",\n author_email=\"aurko@gatech.edu\",\n description=\"Expert system for optimization problems \",\n license=\"BSD\",\n keywords=\"expert system\",\n url=\"https://github.com/royaurko/ask-minmax\",\n\n install_requires=['pymongo', 'scipy', 'numpy', 'matplotlib', 'nltk', 'scikit-learn', 'gensim', 'feedparser',\n 'jenks', 'lxml', 'cython', 'requests'],\n dependency_links=['git+https://github.com/perrygeo/jenks.git#egg=jenks'],\n packages=['askminmax'],\n package_dir={'askminmax': 'src/askminmax'},\n package_data={'askminmax': ['src/askminmax/database', 'src/askminmax/models']},\n long_description=read('Readme.md'),\n classifiers=[\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3\",\n \"Development Status :: 3 - Alpha\",\n \"Topic :: Utilities\",\n \"License :: OSI Approved :: BSD License\",\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"506977113","text":"\nfrom pyclustering.utils import euclidean_distance_square\n\nimport numpy as np\n\ndef GMM(D, K,initRecords):\n S = []\n S.extend(list(initRecords))\n D.remove(initRecords[0])\n D.remove(initRecords[1])\n minMap = {}\n\n for i in D:\n dist = euclidean_distance_square(i, initRecords[0])\n minMap[tuple(i)] = dist\n nextItem = initRecords[1]\n\n for k in range(K - 2):\n L = []\n for i in D:\n min = minMap[tuple(i)]\n dist = euclidean_distance_square(i, nextItem)\n if min > dist:\n min = dist\n minMap[tuple(i)] = min\n L.append(min)\n index_max = np.argmax(L)\n nextItem = D[index_max]\n S.append(D[index_max])\n D.remove(D[index_max])\n return S\n","sub_path":"AugGMM/GMM.py","file_name":"GMM.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"403298049","text":"#!/usr/bin/python3\n\"\"\" 0-rotate_2d_matrix.py\"\"\"\n\n\ndef rotate_2d_matrix(matrix):\n \"\"\"Rotate a matrix 90 degrees clockwise\"\"\"\n tmp_matrix = matrix.copy()\n matrix.clear()\n rows_n = len(tmp_matrix)\n i = 0\n while (i < rows_n):\n new_row = []\n j = rows_n - 1\n while (j >= 0):\n new_row.append(tmp_matrix[j][i])\n j -= 1\n matrix.append(new_row)\n i += 1\n","sub_path":"0x16-rotate_2d_matrix/0-rotate_2d_matrix.py","file_name":"0-rotate_2d_matrix.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"217762277","text":"# Copyright 2020 The FastEstimator 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# ==============================================================================\nimport unittest\n\nimport numpy as np\n\nfrom fastestimator.trace.metric import Accuracy\nfrom fastestimator.util import Data\n\n\nclass TestAccuracy(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n x = np.array([[1, 2], [3, 4]])\n x_pred = np.array([[1, 5, 3], [2, 1, 0]])\n x_1d = np.array([2.5])\n x_pred_1d = np.array([1])\n x_1d_logit = np.array([1])\n x_pred_1d_logit = np.array([2.5])\n\n cls.data = Data({'x': x, 'x_pred': x_pred})\n cls.data_1d = Data({'x': x_1d, 'x_pred': x_pred_1d})\n cls.data_1d_logit = Data({'x': x_1d_logit, 'x_pred': x_pred_1d_logit})\n cls.accuracy = Accuracy(true_key='x', pred_key='x_pred')\n cls.accuracy_logit = Accuracy(true_key='x', pred_key='x_pred', from_logits=True)\n\n def test_on_epoch_begin(self):\n self.accuracy.on_epoch_begin(data=self.data)\n with self.subTest('Check initial value of correct'):\n self.assertEqual(self.accuracy.correct, 0)\n with self.subTest('Check initial value of total'):\n self.assertEqual(self.accuracy.total, 0)\n\n def test_on_batch_end(self):\n self.accuracy.on_batch_end(data=self.data)\n with self.subTest('Check correct values'):\n self.assertEqual(self.accuracy.correct, 1)\n with self.subTest('Check total values'):\n self.assertEqual(self.accuracy.total, 3)\n\n def test_on_epoch_end(self):\n self.accuracy.correct = 1\n self.accuracy.total = 3\n self.accuracy.on_epoch_end(data=self.data)\n with self.subTest('Check if accuracy value exists'):\n self.assertIn('accuracy', self.data)\n with self.subTest('Check the value of accuracy'):\n self.assertEqual(round(self.data['accuracy'], 2), 0.33)\n\n def test_1d_data_on_batch_end(self):\n self.accuracy.on_batch_end(data=self.data_1d)\n with self.subTest('Check correct values'):\n self.assertEqual(self.accuracy.correct, 0)\n with self.subTest('Check total values'):\n self.assertEqual(self.accuracy.total, 1)\n\n def test_1d_data_on_epoch_end(self):\n self.accuracy.correct = 0\n self.accuracy.total = 1\n self.accuracy.on_epoch_end(data=self.data_1d)\n with self.subTest('Check if accuracy value exists'):\n self.assertIn('accuracy', self.data_1d)\n with self.subTest('Check the value of accuracy'):\n self.assertEqual(round(self.data_1d['accuracy'], 2), 0.0)\n\n def test_1d_logit_data_on_batch_end(self):\n self.accuracy_logit.on_batch_end(data=self.data_1d_logit)\n with self.subTest('Check correct values'):\n self.assertEqual(self.accuracy_logit.correct, 1)\n with self.subTest('Check total values'):\n self.assertEqual(self.accuracy_logit.total, 1)\n","sub_path":"test/PR_test/integration_test/trace/metric/test_accuracy.py","file_name":"test_accuracy.py","file_ext":"py","file_size_in_byte":3512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"128972230","text":"from unittest import mock\nimport unittest\nfrom unittest.mock import patch,MagicMock\nfrom domainInsercion import insertarDatos\nfrom pokemon import pokebase\nfrom entrenador import entrenadorbase\n\n\nclass testMockDomain(unittest.TestCase):\n \n \n \n @patch('domainInsercion.insertarDatos.insert_entrenador_data',return_value=True)\n def test_funcionaCorrecto(self,mock_get):\n llamar=insertarDatos()\n resultado_esperado=True\n resultado_actual=llamar.insert_entrenador_data(\"mock\")\n \n assert resultado_esperado==resultado_actual\n \n @patch('domainInsercion.insertarDatos.eliminarEquipo',return_value=\"Se borraron los pokemon correctamente\")\n def test_eliminar_equipo(self,mock_get):\n llamar=insertarDatos()\n \n resultado_esperado=\"Se borraron los pokemon correctamente\"\n resultado_actual=llamar.eliminarEquipo(\"mock\",1)\n \n assert resultado_esperado==resultado_actual\n \n @patch('domainInsercion.insertarDatos.eliminarEquipo',return_value=\"No se eliminó\")\n def test_eliminar_equipo_dos(self,mock_get):\n llamar=insertarDatos()\n \n resultado_esperado=\"No se eliminó\"\n resultado_actual=llamar.eliminarEquipo(\"mock\",1)\n \n assert resultado_esperado==resultado_actual\n \n @patch('domainInsercion.insertarDatos.get_entrenador_data',return_value=1)\n def test_get_data_entrenador(self,mock_get):\n llamar=insertarDatos()\n \n resultado_esperado=1\n resultado_actual=llamar.get_entrenador_data(\"mock\")\n \n assert resultado_esperado==resultado_actual\n\n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"domainMock.py","file_name":"domainMock.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"314971360","text":"import sys\nimport math\n\nn=int(input())\nt=int(input())\n\ndef print_pegs(pegs, n):\n for i in range(0, n):\n str=''\n for num_peg in range(0,3):\n peg=pegs [num_peg]\n if n-i > len(peg):\n str=str+' '*n+'|'+' '*n+' '\n else:\n r=peg [n-1-i]\n str=str+' '*(n-r)+'#'*(2*r+1)+' '*(n-r)+' '\n print(str.rstrip())\n\n# hanoi recursive solver\ndef solve_hanoi_rec(pegs, n, t, src, dst, mid, ncur, tcur):\n if (ncur>1):\n tcur=solve_hanoi_rec(pegs, n, t, src, mid, dst, ncur-1, tcur)\n tcur=solve_hanoi_rec(pegs, n, t, src, dst, mid, 1, tcur)\n tcur=solve_hanoi_rec(pegs, n, t, mid, dst, src, ncur-1, tcur)\n else:\n pegs [dst].append(pegs [src].pop())\n tcur=tcur+1\n if tcur==t:\n print_pegs(pegs, n)\n return tcur\n\n# hanoi iterative solver\ndef solve_hanoi_iter(pegs, n, t):\n small=0\n tcur=0\n dir=1 if (n%2)==0 else -1;\n while len(pegs[2])!=n:\n pegs [(small+dir)%3].append(pegs[small].pop())\n tcur=tcur+1\n if tcur==t:\n print_pegs(pegs, n)\n if len(pegs[2])==n:\n return tcur\n if len(pegs [(small-dir)%3])==0 or (len(pegs[small])>0 and pegs[(small-dir)%3][-1] > pegs[small][-1]):\n pegs [(small-dir)%3].append(pegs[small].pop())\n else: \n pegs [small].append(pegs[(small-dir)%3].pop())\n tcur=tcur+1\n if tcur==t:\n print_pegs(pegs, n)\n small=(small+dir)%3\npegs = [[],[],[]]\n\nfor i in range(n-1,-1,-1):\n pegs [0].append(i+1)\nif t==0:\n print_pegs(pegs, n)\n\n# print(solve_hanoi_rec(pegs, n, t, 0, 2, 1, n, 0))\nprint(solve_hanoi_iter(pegs, n, t))","sub_path":"hanoi.py","file_name":"hanoi.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"116209966","text":"\n# Standard libs\nimport os\nimport time\nimport json\nimport re\nfrom datetime import datetime\n\n# Requests\nimport requests\n\n# Vectors\nimport numpy as np\n\n# Images\nimport cv2\n\n# Google Cloud client libraries\nimport googleapiclient.discovery\nfrom google.cloud import datastore\nfrom google.cloud import storage\nfrom google.cloud import pubsub_v1\n\nBUCKET_NAME = os.environ['BUCKET_NAME']\nPROJECT_ID = os.environ['PROJECT_ID']\nMODEL_NAME = os.environ['MODEL_NAME']\nVERSION_NAME = os.environ['VERSION_NAME']\nREGION = os.environ['REGION']\nTRESHOLD = int(os.environ['TRESHOLD'])\nWIDTH = int(os.environ['WIDTH'])\nHEIGHT = int(os.environ['HEIGHT'])\nDELAY_ONLINE = int(os.environ['DELAY_ONLINE'])\n\n\ndef make_batch_job_body(project_name, input_paths, output_path,\n model_name, region, data_format='TEXT',\n version_name=None, max_worker_count=None,\n runtime_version=None):\n \"\"\"make_batch_job_body\n Args:\n images (nparray): Images\n name (string): Name of the file written\n \"\"\"\n\n project_id = 'projects/{}'.format(project_name)\n model_id = '{}/models/{}'.format(project_id, model_name)\n if version_name:\n version_id = '{}/versions/{}'.format(model_id, version_name)\n\n # Make a jobName of the format \"model_name_batch_predict_YYYYMMDD_HHMMSS\"\n timestamp = time.strftime('%Y%m%d_%H%M%S', time.gmtime())\n\n # Make sure the project name is formatted correctly to work as the basis\n # of a valid job name.\n clean_project_name = re.sub(r'\\W+', '_', project_name)\n\n job_id = '{}_{}_{}'.format(clean_project_name, model_name,\n timestamp)\n\n # Start building the request dictionary with required information.\n body = {'jobId': job_id,\n 'predictionInput': {\n 'dataFormat': data_format,\n 'inputPaths': input_paths,\n 'outputPath': '{}/{}'.format(output_path, job_id),\n 'region': region}}\n\n # Use the version if present, the model (its default version) if not.\n if version_name:\n body['predictionInput']['versionName'] = version_id\n else:\n body['predictionInput']['modelName'] = model_id\n\n # Only include a maximum number of workers or a runtime version if specified.\n # Otherwise let the service use its defaults.\n if max_worker_count:\n body['predictionInput']['maxWorkerCount'] = max_worker_count\n\n if runtime_version:\n body['predictionInput']['runtimeVersion'] = runtime_version\n\n return body\n\n\ndef batch_predict(project_name, body):\n \"\"\"ask for a batch job\n Args:\n project_name (string): project id\n body (dict): args of the batch job\n \"\"\"\n project_id = 'projects/{}'.format(project_name)\n\n service = googleapiclient.discovery.build('ml', 'v1') # its not ai platform model / version btw\n request = service.projects().jobs().create(parent=project_id,\n body=body)\n\n response = request.execute()\n\n print('Job requested.')\n\n # The state returned will almost always be QUEUED.\n print('state : {}'.format(response['state']))\n\n if 'error' in response:\n raise RuntimeError(response['error'])\n return response\n\n\ndef online_predict(project, model, instances, version=None):\n \"\"\"Send json data to a deployed model for prediction.\n Args:\n project (str): project where the Cloud ML Engine Model is deployed.\n model (str): model name.\n instances ([Mapping[str: Any]]): Keys should be the names of Tensors\n your deployed model expects as inputs. Values should be datatypes\n convertible to Tensors, or (potentially nested) lists of datatypes\n convertible to tensors.\n version: str, version of the model to target.\n Returns:\n Mapping[str: any]: dictionary of prediction results defined by the\n model.\n \"\"\"\n # Create the ML Engine service object.\n # To authenticate set the environment variable\n # GOOGLE_APPLICATION_CREDENTIALS=\n # TODO: what is 'ml' arg\n service = googleapiclient.discovery.build('ml', 'v1')\n name = 'projects/{}/models/{}'.format(project, model)\n if version is not None:\n name += '/versions/{}'.format(version)\n response = service.projects().predict(\n name=name,\n body={'instances': instances}\n ).execute()\n if 'error' in response:\n raise RuntimeError(response['error'])\n return response\n\n\ndef predict_update_datastore(client, frame):\n \"\"\"\n \"\"\"\n # Model input is b64\n # Compose a JSON Predict request (send JPEG image in base64).\n # img = base64.b64encode(dl_request.content).decode('utf-8')\n # img = base64.b64encode(open('id_pic.jpg', \"rb\").read()).decode()\n\n # Model input is array\n # Compose a JSON Predict request (send JPEG image as array).\n arr = np.asarray(bytearray(frame), dtype=np.uint8)\n img = cv2.resize(cv2.cvtColor(cv2.imdecode(\n arr, -1), cv2.COLOR_BGR2RGB), (WIDTH, HEIGHT))\n\n # Create an object containing the data\n # b64\n # image_byte_dict = {\"image_bytes\": {\"b64\": img}}\n # array\n image_byte_dict = {\"inputs\": img.tolist()}\n instances = [image_byte_dict]\n\n # Query AI Platform with the media\n result = online_predict(PROJECT_ID, MODEL_NAME, instances, VERSION_NAME)\n\n # Put the prediction in Datastore\n key_prediction = client.key('Prediction')\n entity_prediction = datastore.Entity(key=key_prediction)\n\n keys_object = list()\n\n # For each object detected ...\n # Assuming there is only one prediction possible even though there is a 's' at predictions ?\n for i in range(int(result['predictions'][0]['num_detections'])):\n object_detected = dict()\n object_detected['detection_classes'] = int(\n result['predictions'][0]['detection_classes'][i])\n object_detected['detection_boxes'] = result['predictions'][0]['detection_boxes'][i]\n object_detected['detection_scores'] = result['predictions'][0]['detection_scores'][i]\n\n # Put the information about the object into a new table row ...\n key_object = client.key('Object')\n entity_object = datastore.Entity(key=key_object)\n entity_object.update(object_detected)\n client.put(entity_object)\n\n # Store the id generated for reference in Prediction table\n keys_object.append(entity_object.id)\n\n # Put a list of objects detected in prediction row\n entity_prediction.update({'objects': keys_object})\n client.put(entity_prediction)\n\n return entity_prediction\n\n# TODO: optimize code ...\n\n\ndef online_batch_prediction(event, context):\n \"\"\"Triggered by a change to a Cloud Storage bucket.\n Args:\n event (dict): Event payload.\n context (google.cloud.functions.Context): Metadata for the event.\n \"\"\"\n # GCP doesn't handle trigger on folder level, so either change architecture\n # either multiple bucket (is that more expensive or ? ...)\n # https://googlecloud.tips/tips/018-trigger-cloud-functions-on-gcs-folders/\n if event['name'].startswith('batch_results/') or event['name'].startswith('batches/'): # (e.g. batch results put here, we skip)\n return\n\n if event['contentType'].startswith('video'):\n publisher = pubsub_v1.PublisherClient()\n topic_path = publisher.topic_path(PROJECT_ID, 'topic_extractor')\n publisher.publish(\n topic_path,\n data=os.path.join('gs://{}'.format(BUCKET_NAME),\n event['name']).encode('utf-8') # data must be a bytestring.\n )\n\n # A file has been added to the bucket but it's either an image or a video (split into frames)\n if not event['contentType'].startswith('image'):\n print(\"Unhandled file type\")\n return\n\n client = datastore.Client()\n # Then get by key for this entity\n query_frame = client.query(kind='Frame')\n query_frame.add_filter('predictions', '=', None)\n frames_to_process = list(query_frame.fetch())\n\n # Above which amount of frames we pick batch instead of online predictions\n # TODO: only start online if under treshold and a specific length of time\n # has passed (from the image timestamp)\n if len(frames_to_process) > TRESHOLD:\n # Instantiates a GCS client\n storage_client = storage.Client()\n body = make_batch_job_body(PROJECT_ID,\n 'gs://{}/batches/*'.format(BUCKET_NAME),\n 'gs://{}/batch_results'.format(BUCKET_NAME),\n MODEL_NAME,\n REGION,\n version_name=VERSION_NAME,\n max_worker_count=72)\n # TODO: handle case where the batch is too big to be written to a single file\n for frame in frames_to_process:\n # Download\n dl_request = requests.get(frame['imageUrl'], stream=True)\n dl_request.raise_for_status()\n\n # Load into array\n arr = np.asarray(bytearray(dl_request.content), dtype=np.uint8)\n\n # Preprocessing\n # TODO:calculate the scaling that has been done and put into the image datastore in order to rescale boxes etc\n img = cv2.resize(cv2.cvtColor(cv2.imdecode(arr, -1), cv2.COLOR_BGR2RGB), (WIDTH, HEIGHT))\n\n # Create an object containing the data\n image_byte_dict = {\"inputs\": img.tolist(), \"input_keys\": str(frame.id)}\n json_object = json.dumps(image_byte_dict)\n file_path = \"/tmp/inputs.json\"\n\n # Open file with \"a\" = append the file\n with open(file_path, \"a+\") as json_file:\n json_file.write(json_object + \"\\n\")\n\n # Get the frame key in Datastore\n key_frame = client.key('Frame', frame.id)\n entity_frame = datastore.Entity(key=key_frame)\n\n # Create an object to put in datastore\n obj = dict(frame)\n\n # Update the predictions properties of the Frame row to stop launching jobs\n obj['predictions'] = 'processing' #TODO: handle case where multiple job ended => #\n obj['job'] = body['jobId']\n\n # Push into datastore\n entity_frame.update(obj)\n client.put(entity_frame)\n\n bucket = storage_client.get_bucket(BUCKET_NAME)\n blob = bucket.blob('batches/inputs.json')\n\n blob.upload_from_filename(file_path)\n\n print('File uploaded')\n\n print('Response', batch_predict(PROJECT_ID, body))\n return\n\n # Avoid jumping on online prediction too early\n elif (datetime.now() - datetime.strptime(event['timeCreated'], '%Y-%m-%dT%H:%M:%S.%fZ')).total_seconds() < DELAY_ONLINE:\n print('Waiting more frames',\n (datetime.now() - datetime.strptime(event['timeCreated'], '%Y-%m-%dT%H:%M:%S.%fZ')).total_seconds())\n return\n else:\n # Iterate through the media to process\n for frame in frames_to_process:\n image_url = frame['imageUrl']\n\n # Download the image\n dl_request = requests.get(image_url, stream=True)\n dl_request.raise_for_status()\n\n entity_prediction = predict_update_datastore(\n client, dl_request.content)\n\n # Get the frame key in Datastore\n key_frame = client.key('Frame', frame.id)\n entity_frame = datastore.Entity(key=key_frame)\n\n # Create an object to put in datastore\n obj = dict(frame)\n\n # Update the predictions properties of the Frame row\n obj['predictions'] = entity_prediction.id\n\n # Push into datastore\n entity_frame.update(obj)\n client.put(entity_frame)\n","sub_path":"cloud_functions/online_batch/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"608684332","text":"def getPrime():\n __name__\nprime_list=[]\nstart =int(input(\"enter start number: \\t\"))\nfor num in range(start,start+100):\n\tisPrime =True\n\tfor i in range(2,num):\n\t\tif(num % i) == 0:\n\t\t\tisPrime =False\n\tif isPrime:\n\t\tprime_list.append(num)\nprint(prime_list)\n\nif __name__ == \"__main__\":\n getPrime()","sub_path":"DAY-2/MyPackage/modulePrime.py","file_name":"modulePrime.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"203952627","text":"import socket\nimport struct\nimport abc\nimport threading\nfrom datetime import datetime, timedelta\nfrom collections import namedtuple, deque\nfrom enum import Enum\nimport numpy as np\nimport cv2\nimport sys\nimport time\nfrom app.yolov4 import *\nimport logging\nimport json\n\nnp.warnings.filterwarnings('ignore')\n\nVIDEO_STREAM_HEADER_FORMAT = \"@qIIII18f\"\n\nVIDEO_FRAME_STREAM_HEADER = namedtuple(\n 'SensorFrameStreamHeader',\n 'Timestamp ImageWidth ImageHeight PixelStride RowStride fx fy '\n 'PVtoWorldtransformM11 PVtoWorldtransformM12 PVtoWorldtransformM13 PVtoWorldtransformM14 '\n 'PVtoWorldtransformM21 PVtoWorldtransformM22 PVtoWorldtransformM23 PVtoWorldtransformM24 '\n 'PVtoWorldtransformM31 PVtoWorldtransformM32 PVtoWorldtransformM33 PVtoWorldtransformM34 '\n 'PVtoWorldtransformM41 PVtoWorldtransformM42 PVtoWorldtransformM43 PVtoWorldtransformM44 '\n)\n\nVIDEO_STREAM_PORT = 23940\n\nHOST = '192.168.43.21'\n\nclass FrameReceiverThread(threading.Thread):\n def __init__(self, host, port, header_format, header_data):\n super(FrameReceiverThread, self).__init__()\n self.header_size = struct.calcsize(header_format)\n self.header_format = header_format\n self.header_data = header_data\n self.host = host\n self.port = port\n self.latest_frame = None\n self.latest_header = None\n self.socket = None\n\n def get_data_from_socket(self):\n reply = self.recvall(self.header_size)\n\n if not reply:\n print('ERROR: Failed to receive data from stream.')\n return\n\n data = struct.unpack(self.header_format, reply)\n header = self.header_data(*data)\n\n image_size_bytes = header.ImageHeight * header.RowStride\n image_data = self.recvall(image_size_bytes)\n\n return header, image_data\n\n def recvall(self, size):\n msg = bytes()\n while len(msg) < size:\n part = self.socket.recv(size - len(msg))\n if part == '':\n break # the connection is closed\n msg += part\n return msg\n\n def start_socket(self):\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.socket.connect((self.host, self.port))\n # send_message(self.socket, b'socket connected at ')\n print('INFO: Socket connected to ' + self.host + ' on port ' + str(self.port))\n\n def start_listen(self):\n t = threading.Thread(target=self.listen)\n t.start()\n\n @abc.abstractmethod\n def listen(self):\n return\n\n @abc.abstractmethod\n def get_mat_from_header(self, header):\n return\n\n\nclass VideoReceiverThread(FrameReceiverThread):\n def __init__(self, host):\n super().__init__(host, VIDEO_STREAM_PORT, VIDEO_STREAM_HEADER_FORMAT,\n VIDEO_FRAME_STREAM_HEADER)\n\n def listen(self):\n while True:\n self.latest_header, image_data = self.get_data_from_socket()\n self.latest_frame = np.frombuffer(image_data, dtype=np.uint8).reshape((self.latest_header.ImageHeight,\n self.latest_header.ImageWidth,\n self.latest_header.PixelStride))\n\n def get_mat_from_header(self, header):\n pv_to_world_transform = np.array(header[7:24]).reshape((4, 4)).T\n return pv_to_world_transform\n\t\n\t\ndef detection(frame):\n sized = cv2.resize(frame,(darknet.width,darknet.height))\n sized = cv2.cvtColor(sized, cv2.COLOR_BGR2RGB)\n\t\n boxes = do_detect(darknet, sized, 0.5, 0.4, USE_CUDA)\n boxes = np.array(boxes[0]).tolist()\n\t\n result_img = plot_boxes_cv2(video_receiver.latest_frame, boxes, class_names = class_names)\n\t\n for i in range(len(boxes)):\n boxes[i][6] = class_names[int(boxes[i][6])]\n\t\n formatBoxes = []\n for i in range(len(boxes)):\n formatBoxes.append({\n 'X1': boxes[i][0],\n 'Y1': boxes[i][1],\n 'X2': boxes[i][2],\n 'Y2': boxes[i][3],\n 'Unknown': boxes[i][4],\n 'Conf': boxes[i][5],\n 'Name': boxes[i][6]\n })\n print(formatBoxes) \n formatBoxes = json.dumps(formatBoxes)\n\t\t\n return result_img, formatBoxes\n\n \n\nif __name__ == '__main__':\n\t\n #video_receiver.socket.send(b'test')\n\n video_receiver = VideoReceiverThread(HOST)\n video_receiver.start_socket()\n video_receiver.start_listen()\n\n namesfile = 'data/coco.names'\n class_names = load_class_names(namesfile)\n\n s = socket.socket()\n s.bind(('0.0.0.0', 5000))\n #s.bind(('127.0.0.1', 5000))\n s.listen()\n c, addr = s.accept()\n #c.send(b'test')\n #print(\"well\")\n\n\n while True:\n if np.any(video_receiver.latest_frame) :\n result_img, formatBoxes = detection(video_receiver.latest_frame)\n c.send(formatBoxes.encode('utf8'))\n #c.send(b'test')\n #print(\"fine\")\n cv2.imshow('Result', result_img)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n\n\n\n","sub_path":"hololens2_detect.py","file_name":"hololens2_detect.py","file_ext":"py","file_size_in_byte":5081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"335658546","text":"import requests\nimport json\n\n\n# url = \"https://free-nba.p.rapidapi.com/stats\"\n\n# querystring = {\"page\":\"0\",\"per_page\":\"100\",\"player_ids\":\"1043\"}\n\n# headers = {\n# 'x-rapidapi-key': \"59aba308e6msh85019965c5ae5aap1e13cbjsn114e29b1e51c\",\n# 'x-rapidapi-host': \"free-nba.p.rapidapi.com\"\n# }\n\n# response = requests.request(\"GET\", url, headers=headers, params=querystring)\n\n# print(response.text)\n\n\n\nheaders = {\n 'x-rapidapi-key': \"59aba308e6msh85019965c5ae5aap1e13cbjsn114e29b1e51c\",\n 'x-rapidapi-host': \"free-nba.p.rapidapi.com\"\n }\n\npage=1\nresults = []\nwhile True:\n\n url = \"https://free-nba.p.rapidapi.com/stats\"\n\n querystring = {\"page\":page,\"per_page\":\"100\",\"player_ids\":\"1043\"}\n response = requests.request(\"GET\", url, headers=headers, params = querystring)\n\n if response.status_code != 200:\n continue\n\n data = response.json()\n \n if len(data['data']) <= 0:\n break\n\n print(data.get('meta', None))\n results += data['data']\n \n page += 1\n\n # print(response.json())\n\n\nwith open(\"data.json\", \"w\") as data_file: \n json.dump(results, data_file, indent=2)\n data_file.close()","sub_path":"data/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"426140171","text":"from django.shortcuts import redirect\nfrom django.shortcuts import render\nfrom django.views.generic.base import TemplateView\nfrom anabond.forms import SpecialChafinalForm\nfrom anabond.models import SpecialChafinal, SpecialChafinal_teammembers\n\n\nclass specialchar(TemplateView):\n template_name = 'base/special_characteristics.html'\n def get(self, request, *args, **kwargs):\n specdata = SpecialChafinal.objects.filter(project_id=request.session.get(\"current_project_id\")).last()\n if specdata:\n if specdata.status == 'saved':\n specdata = SpecialChafinal.objects.get(pk=specdata.id)\n elif specdata.status == 'completed':\n return redirect('/spl-CHARFINAL-detail/' + str(specdata.id) + '/')\n elif specdata.status == 'obsoleted':\n specdata = SpecialChafinal()\n specdata.project_id = request.session.get(\"current_project_id\")\n specdata.save()\n else:\n #TO CREATE DEFAULT DATA WHEN NO RECOREDS THERE\n specdata = SpecialChafinal()\n specdata.project_id = request.session.get(\"current_project_id\")\n specdata.save()\n form = SpecialChafinalForm(instance=specdata)\n spec_popup = SpecialChafinal_teammembers.objects.filter(special_chafinal_id=specdata.id)\n\n history_detail_url = \"/spl-CHARFINAL-detail/\"\n history_detail_url_name = \"spl_CHARFINAL_detail\"\n histor_lists = SpecialChafinal.objects.filter(project_id=request.session.get(\"current_project_id\"),status='obsoleted').order_by(\"-id\")[:5]\n history_title = \"Identification of special process/product characteristics final RD 7306-01\"\n model_name = \"SpecialChafinal\"\n\n return render(request, self.template_name, {\"form\": form,\"specdata\":specdata,\"spec_popups\":spec_popup,\"history_detail_url\":history_detail_url,\"history_detail_url_name\":history_detail_url_name,\"histor_lists\":histor_lists,\"history_title\":history_title,\"model_name\":model_name})\n\n def post(self, request):\n data = request.POST\n form_name = data.get('form_name')\n spec_popup = SpecialChafinal_teammembers.objects.filter(special_chafinal_id=data.get('special_chafinal_id'))\n\n\n history_detail_url = \"/spl-CHARFINAL-detail/\"\n history_detail_url_name = \"spl_CHARFINAL_detail\"\n histor_lists = SpecialChafinal.objects.filter(project_id=request.session.get(\"current_project_id\"),status='obsoleted').order_by(\"-id\")[:5]\n history_title = \"Identification of special process/product characteristics final RD 7306-01\"\n model_name = \"SpecialChafinal\"\n\n if form_name == 'special_char':\n form = SpecialChafinalForm(data)\n if form.is_valid():\n froms_save = SpecialChafinal.objects.get(id=data.get('special_chafinal_id'))\n froms_save.review_details = data.get('review_details')\n froms_save.critical_characteristics = data.get('critical_characteristics')\n froms_save.special_characteristics = data.get('special_characteristics')\n froms_save.assumptions = data.get('assumptions')\n froms_save.reliability = data.get('reliability')\n froms_save.identification_special_process = data.get('identification_special_process')\n froms_save.similar = data.get('similar')\n froms_save.previous_experience = data.get('previous_experience')\n froms_save.symbol_splChar = data.get('symbol_splChar')\n froms_save.symbol_criticalChar = data.get('symbol_criticalChar')\n froms_save.status = data.get('action')\n\n\n froms_save.created_by_id = request.user.id\n froms_save.save()\n return redirect('spl_CHARFINAL')\n else:\n return render(request, self.template_name, {\"form\": form,\"spec_popups\":spec_popup,\"history_detail_url\":history_detail_url,\"history_detail_url_name\":history_detail_url_name,\"histor_lists\":histor_lists,\"history_title\":history_title,\"model_name\":model_name})\n elif form_name == 'special_char_popup':\n spec_popup_del = SpecialChafinal_teammembers.objects.filter(special_chafinal=data.get('special_chaprilim_id')).delete()\n team_member_names = data.getlist('team_member_name')\n team_member_positions = data.getlist('team_member_position')\n i=0\n for team_member_name in team_member_names:\n if len(team_member_names[i].strip()) != 0 or len(team_member_positions[i].strip()) != 0:\n spec_popup_data = SpecialChafinal_teammembers()\n spec_popup_data.team_member_name = team_member_name\n spec_popup_data.team_member_position = team_member_positions[i]\n spec_popup_data.special_chafinal_id = data.get('special_chaprilim_id')\n spec_popup_data.save()\n i=i+1\n specdata = SpecialChafinal.objects.get(pk=data.get('special_chaprilim_id'))\n form = SpecialChafinalForm(instance=specdata)\n spec_popup = SpecialChafinal_teammembers.objects.filter(special_chafinal=specdata.id)\n return render(request, self.template_name, {\"form\": form,\"specdata\":specdata,\"spec_popups\":spec_popup,\"history_detail_url\":history_detail_url,\"history_detail_url_name\":history_detail_url_name,\"histor_lists\":histor_lists,\"history_title\":history_title,\"model_name\":model_name})\n\nclass specialchardetail(TemplateView):\n template_name = 'base/templates/base/special_characteristics_detail.html'\n\n def get(self,request,form_id):\n raise Exception(\"5365345435\")\n specdata = SpecialChafinal.objects.get(pk=form_id)\n form = SpecialChafinalForm(instance=specdata)\n spec_popup = SpecialChafinal_teammembers.objects.filter(special_chafinal_id=specdata.id)\n history_detail_url = \"/spl-CHARFINAL-detail/\"\n history_detail_url_name = \"spl_CHARFINAL_detail\"\n histor_lists = SpecialChafinal.objects.filter(project_id=request.session.get(\"current_project_id\"),status='obsoleted').order_by(\"-id\")[:5]\n history_title = \"Identification of special process/product characteristics final RD 7306-01\"\n model_name = \"SpecialChafinal\"\n return render(request, self.template_name, {\"form\": form,\"specdata\":specdata,\"spec_popups\":spec_popup,\"history_detail_url\":history_detail_url,\"history_detail_url_name\":history_detail_url_name,\"histor_lists\":histor_lists,\"history_title\":history_title,\"model_name\":model_name})\n def post(self,request,form_id):\n\n data = request.POST\n spec = SpecialChafinal.objects.get(pk=form_id)\n action = data.get('action')\n if action == \"approval\":\n spec.form_status = \"approval\"\n spec.approval_by_id = request.user.id\n spec.approval_at = datetime.now()\n spec.save()\n return redirect('/spl-CHARFINAL-detail/' + str(spec.id) + '/')\n # return redirect('preliminary_BOM')\n if action == \"reject\":\n spec.reason = data.get('rej_reason')\n spec.form_status = action\n spec.status = \"saved\"\n\n spec.save()\n return redirect('spl_CHARFINAL')\n\n if action == \"Obsolete\":\n spec.obsolete_reason = data.get('versionreason')\n spec.status = \"obsoleted\"\n spec.completed_at = datetime.now()\n spec.completed_by_id = request.user.id\n spec.save()\n return redirect('spl_CHARFINAL')\n spec.save()\n return redirect('spl_CHARFINAL')","sub_path":"anabond/views/special_char.py","file_name":"special_char.py","file_ext":"py","file_size_in_byte":7659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"20068698","text":"#!/usr/bin/python3\n \nnumeros = (5,4,3,2,1,6,45,3,6,6,6,6,6)\n \nnumero = int(input(\"Dame un numero: \"))\n \ncontador= 0\nfor i in numeros:\n if numero == i:\n contador = contador + 1\n \nprint (\"Hay \",contador,\" repeticion/es\")\n","sub_path":"taresas/25.py","file_name":"25.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"626283664","text":"from samples.samplesUL import *\nimport json\n\n\nclass singleSample:\n sigma = -999\n dataset = ''\n year = -999\n def __init__(self, sigma, dataset, year):\n self.sigma = sigma\n self.dataset = dataset\n self.year = year\n \n def printt(self):\n print('dataset: ', self.dataset)\n print('sigma: ', self.sigma)\n print('year: ', self.year)\n\n def jOut(self):\n output = {\n 'dataset' : self.dataset,\n 'sigma' : self.sigma,\n 'year' : self.year\n }\n return output\n\nclass process:\n components = []\n color = -999\n style = -999\n fill = -999\n label = ''\n def __init__(self, color, style, fill, label):\n self.components = []\n self.color = color\n self.style = style\n self.fill = fill\n self.label = label\n\n def addSample(self, s):\n self.components.append(s)\n\n def printt(self):\n print (self.label)\n for s in self.components:\n s.printt()\n\n def jOut(self):\n components = []\n for j in self.components:\n components.append(j.jOut()) \n out = {\n 'label' : self.label,\n 'components' : components,\n 'color' : self.color,\n 'style' : self.style,\n 'fill' : self.fill,\n }\n return out\n\nfileName = 'samples/samplesUL.json'\nprint('checking if sample files exist already')\nif os.path.exists(fileName):\n a = input('it does... removing previous one, press y to proceed, any other key to stop \\n')\n if a == 'y': \n os.popen('rm ' + fileName)\n\nallSamples = {}\nallSamples['condor_dict'] = []\n\nfor s in condor_dict.items():\n #print(s[0])\n data = {}\n data['sample'] = []\n label = s[1].label\n color = s[1].color\n style = s[1].style\n fill = s[1].fill \n label = s[1].label\n \n p = process(color, style, fill, label)\n print('label from condor: ',s[0])\n components = s[1].components\n if components == None:\n p.addSample(singleSample(s[1].sigma, s[1].dataset, s[1].year))\n if components != None:\n for k in components:\n p.addSample(singleSample(k.sigma, k.dataset, k.year))\n allSamples['condor_dict'].append(p.jOut())\n\n\nwith open(fileName, 'a') as f:\n json.dump(allSamples, f, indent = 4)\n","sub_path":"python/postprocessing/jsonWriter.py","file_name":"jsonWriter.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"70433511","text":"from tkinter import *\r\nfrom tkinter.ttk import Treeview\r\nfrom db import Baza\r\nfrom tkinter import messagebox\r\nfrom functools import partial \r\nfrom RacunDB import Racun\r\nimport random\r\nfrom time import strftime\r\n\r\n\r\n#Inicijalizacija prozora i uvodjenje baza podataka\r\n\r\ndb = Baza('lek.db')\r\ndb2 = Racun('racun.db')\r\nprozor = Tk()\r\nsirina= prozor.winfo_screenwidth() \r\nvisina= prozor.winfo_screenheight()\r\n\r\nprozor.geometry(\"%dx%d\" % (sirina, visina))\r\nprozor.resizable(width = False, height = False)\r\nprozor.configure(bg = 'lime green')\r\nprozor.title('Apoteka')\r\n#Definisanje funkcije za sat\r\n\r\ndef sat():\r\n vreme = strftime('%H:%M:%S %p')\r\n lb = Label(prozor, bg='limegreen', font=(30))\r\n lb.config(text = vreme)\r\n lb.after(1000, sat)\r\n lb.grid(row = 0, column=6)\r\nsat()\r\n\r\n#Funkcije\r\ndef selektuj(event):\r\n \r\n try:\r\n global n, c, s,odabrani_lek\r\n n = ''\r\n c = 0\r\n index = lek_tree_view.selection()[0]\r\n odabrani_lek = lek_tree_view.item(index)['values']\r\n \r\n n = odabrani_lek[1]\r\n c = odabrani_lek[3]\r\n s = 1\r\n except IndexError:\r\n pass\r\n\r\n \r\ndef selektuj2(event):\r\n try:\r\n global odabrani_lek2\r\n index = racun_tree_view.selection()[0]\r\n odabrani_lek2 = racun_tree_view.item(index)['values']\r\n \r\n except IndexError:\r\n pass\r\n\r\ndef popuni(naziv=''):\r\n for i in lek_tree_view.get_children():\r\n lek_tree_view.delete(i)\r\n for redovi in db.pokupi1(naziv):\r\n lek_tree_view.insert('', 'end', values=redovi)\r\n\r\ndef pretrazuj():\r\n naziv = pretraga.get()\r\n popuni(naziv)\r\n \r\ndef popuni_racun(naziv=''):\r\n for i in racun_tree_view.get_children():\r\n racun_tree_view.delete(i)\r\n for redovi in db2.pokupi(naziv):\r\n racun_tree_view.insert('', 'end', values=redovi)\r\n\r\n\r\niznos = 0 \r\ndef iznos_racuna_plus(x):\r\n global iznos\r\n iznos += x\r\n iznos_lbl.configure(text='Iznos je: %d' % iznos + 'rsd')\r\n\r\n\r\ndef iznos_racuna_minus(x):\r\n global iznos\r\n iznos -= x\r\n if iznos <0:\r\n iznos = 0\r\n iznos_lbl.configure(text='Iznos je: %d' % iznos + 'rsd')\r\n\r\n\r\n\r\ndef dodaj_na_racun():\r\n odabrani_lek[4] = odabrani_lek[4] - s\r\n if odabrani_lek[4]<0:\r\n messagebox.showerror('GRESKA!', 'Ne moze bit imanje od 0')\r\n return\r\n \r\n db.azuriraj(odabrani_lek[0], odabrani_lek[1], odabrani_lek[2], odabrani_lek[3], odabrani_lek[4])\r\n db2.ubaci(n, c, s)\r\n iznos_racuna_plus(odabrani_lek[3])\r\n popuni_racun()\r\n \r\n\r\ndef obrisi_sa_racuna():\r\n vracanje_na_stanje()\r\n db2.izbrisi(odabrani_lek2[0])\r\n \r\n iznos_racuna_minus(odabrani_lek2[2])\r\n popuni_racun()\r\n\r\n\r\n#Funkcije za racun i kasu\r\n \r\nname = \"\"\r\nkasa_iznos = 0\r\ndef ocisti_racun():\r\n racun_tree_view.delete(*racun_tree_view.get_children())\r\n global iznos\r\n iznos = 0\r\n\r\n\r\ndef racun_txt():\r\n lista = []\r\n x = random.randint(1, 100000)\r\n if x not in lista:\r\n lista.append(x)\r\n else:\r\n x = random.randint(1, 1000000)\r\n global name\r\n name = \"racun%d\" % (x)\r\n file = open(\"%s.txt\" % (name), 'w' )\r\n with open(\"%s.txt\" % (name),\"w\") as file:\r\n file.write(\"\\t \\t Fiskalni racun br. %d\\n\" % (x))\r\n\r\n for redovi in db2.stampaj():\r\n with open(\"%s.txt\" % (name),\"a\") as file:\r\n file.write(\"Artikal: %s ---------- Cena: %d\\n\" % (redovi[1], redovi[2]))\r\n with open(\"%s.txt\" % (name),\"a\") as file:\r\n file.write(\"\\nZa uplatu: %d\\n\" % (iznos))\r\n with open(\"%s.txt\" % (name),\"a\") as file:\r\n file.write(\"\\n====================================\\n\")\r\n file.close()\r\n global kasa_iznos\r\n kasa_iznos += iznos\r\n ocisti_racun()\r\n db2.obrisi()\r\n\r\n\r\ndef stanje_kase():\r\n global kasa_iznos\r\n kasa_lbl.configure(text='U kasi je: %d' % kasa_iznos + ' rsd')\r\n\r\n\r\nfile = open(\"Zarada.txt\", 'a')\r\nwith open(\"Zarada.txt\",'w') as file:\r\n file.write(\"\\t Ukupna zarada \\n\")\r\n\r\n\r\ndef presek_stanja():\r\n global kasa_iznos\r\n file = open(\"Zarada.txt\", 'a')\r\n with open(\"Zarada.txt\",'a') as file:\r\n file.write(\"Zarada pri ovom preseku je: %d rsd\\n\" % kasa_iznos)\r\n with open(\"Zarada.txt\",'a') as file:\r\n file.write(\"------------------------------------\\n\" )\r\n file.close()\r\n kasa_iznos= 0\r\n\r\n\r\n \r\n\r\n\r\ndef vracanje_na_stanje():\r\n x =0\r\n global odabrani_lek2\r\n #################ne radi\r\n for redovi2 in db.stampaj():\r\n if odabrani_lek2[1] == redovi2[1]:\r\n x = redovi2[4]+1\r\n db.azuriraj(redovi2[0], redovi2[1], redovi2[2], redovi2[3], x)\r\n \r\n \r\n \r\n \r\n \r\n\r\n#Dugmici i polja za input\r\n#presek\r\npresek = Button(prozor, text = \"Presek\", padx = 70, pady =10, bg='yellow', command =presek_stanja)\r\npresek.grid(row = 10, column = 0, sticky=\"E\")\r\n#pretraga polje za unos\r\npretraga = StringVar()\r\nPretraga = Entry(prozor, width = 145, textvariable=pretraga)\r\nPretraga.grid(row = 0, column = 0, columnspan = 10, pady = 5, padx = 10, sticky=\"W\")\r\n\r\n#dugme pretraga\r\nTrazi_pretraga = Button(prozor, text = \"Trazi/Osvezi\", padx = 70, pady =10, bg='blue', command =pretrazuj)\r\nTrazi_pretraga.grid(row = 1, column = 0)\r\n\r\n#prikaz\r\nprikaz_naslov = Label (text='Pretraga', font=('bold', 27), bg = 'lime green')\r\nprikaz_naslov.grid(row = 2, column = 0)\r\n\r\n# Prikaz lekova\r\nokvir = Frame(prozor)\r\nokvir.grid( row=3, column = 0 , rowspan=6, ipady=120, padx = 1, pady = 10)\r\n\r\ncolumns = ['Sifra', 'Naziv', 'Proizvodjac', 'Cena', 'Stanje']\r\nlek_tree_view = Treeview(okvir, columns=columns, show=\"headings\")\r\n\r\nfor col in columns[0:]:\r\n lek_tree_view.column(col, width=160)\r\n lek_tree_view.heading(col, text=col)\r\nlek_tree_view.bind('<>', selektuj)\r\nlek_tree_view.pack(side=\"left\", fill=\"y\")\r\nscrollbar = Scrollbar(okvir, orient='vertical')\r\nscrollbar.configure(command=lek_tree_view.yview)\r\nscrollbar.pack(side=\"right\", fill=\"y\")\r\nlek_tree_view.config(yscrollcommand=scrollbar.set)\r\n\r\n#Jos dugmica - za rad izmedju baza (magacin i racun)\r\ndodaj = Button(prozor, text = \"Dodaj na racun\", padx = 50, pady =10, bg='cadet blue', command = dodaj_na_racun)\r\ndodaj.grid(row = 4, column = 3)\r\n\r\nukloni = Button(prozor, text = \"Vrati na stanje\", padx = 50, pady =10, bg='red', command = obrisi_sa_racuna)\r\nukloni.grid(row = 5, column = 3)\r\n\r\nstampaj = Button(prozor, text = \"Stampaj racun\", padx = 55, pady =10, bg='orange', command=racun_txt)\r\nstampaj.grid(row = 10, column = 6, pady = 10)\r\n\r\nkasa = Button(prozor, text = \"Stanje kase\", padx = 55, pady =10, bg='yellow', command=stanje_kase)\r\nkasa.grid(row = 10, column = 0, pady = 120)\r\n\r\n\r\n#Prikaz iznosa i stanja kase\r\niznos_lbl = Label(font=('bold', 27), bg = 'lime green')\r\niznos_lbl.grid(row=2, column= 6)\r\n\r\nkasa_lbl = Label(font=('bold', 15), bg = 'lime green')\r\nkasa_lbl.grid(row=10, column= 0, sticky=\"w\")\r\n\r\n#Prikaz racuna\r\nokvir2 = Frame(prozor)\r\nokvir2.grid( row=3, column = 6 , rowspan=6, padx = 1, pady = 1, ipady = 150)\r\n\r\ncolumns2 = ['Sifra', 'Naziv', 'Cena', 'Kolicina']\r\nracun_tree_view = Treeview(okvir2, columns=columns2, show=\"headings\")\r\n\r\nfor col in columns2[0:]:\r\n racun_tree_view.column(col, width=100)\r\n racun_tree_view.heading(col, text=col)\r\nracun_tree_view.bind('<>', selektuj2)\r\nracun_tree_view.pack(side=\"left\", fill=\"y\")\r\nscrollbar2 = Scrollbar(okvir2, orient='vertical')\r\nscrollbar2.configure(command=racun_tree_view.yview)\r\nscrollbar2.pack(side=\"right\", fill=\"y\")\r\nracun_tree_view.config(yscrollcommand=scrollbar2.set)\r\n#Pozivanje funkcija za baze podataka\r\npopuni()\r\npopuni_racun()\r\n# Pokretanje programa\r\nprozor.mainloop()\r\n","sub_path":"Apoteka.py","file_name":"Apoteka.py","file_ext":"py","file_size_in_byte":7645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"101028327","text":"import numpy as np\n\nA = np.array([\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n\nvalues, vectors = np.linalg.eig(A)\nprint(\"matrix:\\n\", A)\nprint(\"values:\\n\", values)\nprint(\"vectors:\\n\", vectors)\n\nB = A.dot(vectors[:, 0])\nprint(\"matrix with eigenvector:\\n\", B)\nC = vectors[:, 0] * values[0]\nprint(\"values with vectors:\\n\", C)\n\n# create matrix from eigenvectors\nQ = vectors\n# create inverse of eigenvectors matrix\nR = np.linalg.inv(Q)\n# create diagonal matrix from eigenvalues\nL = np.diag(values)\n# reconstruct the original matrix\nreconstructed = Q.dot(L).dot(R)\nprint(\"reconstructed:\\n\", reconstructed)\nprint(\"inversed vectors:\", R)\nprint(\"diagonal matrix:\\n\", L)\n","sub_path":"study/numpy_study/eigendecomposition.py","file_name":"eigendecomposition.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"49259861","text":"import bs4 as bs\nfrom urllib.request import urlopen\nimport time\nimport pandas as pd\n\n\nclass Injury_Scraper(object):\n global url, teams, years, cols\n url = 'http://www.pro-football-reference.com/teams/'\n\n # all team tickers\n teams = ['mia','nyj','nwe','buf','clt','jax','htx','oti'\n ,'rav','pit','cle','cin','sdg','rai','kan','den'\n ,'phi','was','dal','nyg','tam','car','nor','atl'\n ,'chi','min','gnb','det','ram','sea','sfo','crd']\n\n # range of years (might make non-constant in the future)\n years = list(range(2009,2017))\n\n # scrapes pro football reference injuries from site\n # url format: http://www.pro-football-reference.com/teams/TICKER/YEAR_injuries.htm'\n # output: list of list: [player name, date, opposing team, injury, chance of playing, played(bool)]\n @staticmethod\n def scrape(url, sleep_time=2):\n\n # url request delay time\n time.sleep(sleep_time)\n\n # url request\n source = urlopen(url)\n soup = bs.BeautifulSoup(source, \"lxml\", from_encoding=\"utf-8\")\n\n # get current year\n year = soup.find('title').text.split()[0]\n\n # table headers\n thead = soup.find('thead').findAll('th')\n del thead[0] # useless row header 'Player'\n\n # dates and opponents from table header\n dates = [year+'/'+game.text.split('vs. ')[0] for game in thead]\n\n#[unicode(x.strip()) if x is not None else '' for x in row]\n print(dates)\n # format dates\n dates = [w.replace('/', '-') for w in dates]\n\n # get opponents\n verses = [game.text.split('vs. ')[1] for game in thead]\n\n table = soup.find('tbody').findAll('tr')\n # get all players in table\n players = [t.find('th').text for t in table]\n\n table = [t.findAll('td') for t in table]\n\n # corresponds to the shading on table, not sure if this means they actually played.\n played = [[x.get('class', '') for x in t] for t in table]\n\n # flatten list\n played = [val for sublist in played for val in sublist]\n played = [False if 'dnp' in x else True for x in played]\n\n # gets player injury status on given day\n injuries = [[x.get('data-tip', 'Healthy') for x in t] for t in table]\n\n # flatten list\n injuries = [val for sublist in injuries for val in sublist]\n\n # split injury and chance of playing\n chance_of_playing = [x.split(': ')[0] if len(x.split(': ')) == 2 else 'Good' for x in injuries]\n injuries = [x.split(': ')[1] if len(x.split(': ')) == 2 else x.split(': ')[0] for x in injuries]\n\n # putting it all together\n temp = [[player,date,vs] for player in players for date,vs in zip(dates,verses)]\n output = [(t+[i]+[c]+[p]) for t,i,c,p in zip(temp,injuries,chance_of_playing,played)]\n\n return output\n\n # scrapes all injuries from the list of teams and years above\n @staticmethod\n def scrape_all(sleep_time=2):\n # loops through every team for every year\n fails = 0\n injuries = []\n starttime = time.time()\n for team in teams:\n for year in years:\n current_url = url+team+'/'+str(year)+'_injuries.htm'\n current_urls_injuries = []\n try:\n print('Scraping:',team,year)\n current_urls_injuries = Injury_Scraper().scrape(current_url,sleep_time)\n except:\n fails+=1\n print('Scrape failed on:',team,year,current_url)\n continue\n\n injuries = injuries + current_urls_injuries\n\n print('Scrape completed. Scrapes failed:',fails)\n print('Elapsed time',time.time()-starttime)\n\n return injuries\n\n\"\"\"\ndf = pd.read_csv('injuries.csv')\n\n#print(df.iloc[2010:2035][['Player','Date','Injury','Chance_of_playing', 'Played']])\nprint(df.loc[df['Player'] == 'Benny Cunningham'])\n#print((df.loc[df['Player'] == 'Bruce Miller']).iloc[15:])\n#print(df[(df['Player'] == 'Bruce Miller') & (df['Date'] == '2012-01-12' )])\n\"\"\"\n\n# get all injuries\ninj = Injury_Scraper().scrape_all(0)\n\n# create df & save to csv\ncols = ['Player','Date','Opp','Injury','Chance_of_playing','Played']\ndf = pd.DataFrame(inj, columns=cols)\ndf.to_csv('injuries.csv')\n\nprint(df.head())\nprint(len(inj))\n\n\n","sub_path":"Injury_Scraper.py","file_name":"Injury_Scraper.py","file_ext":"py","file_size_in_byte":4326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"68120281","text":"\nimport subprocess\n\nfrom vector.apps.DataAPI.api import Api\n\nclass Link( object ):\n\n def __init__(self, envName ):\n super(Link, self).__init__()\n\n self.envName = envName\n self.init()\n\n\n def init( self ):\n\n self.api = Api( self.envName )\n\n self.testCases = self.api.TestCase.all()\n print( self.testCases )\n\n self.environment_name = self.api.environment.name\n\n\n def linkTestCase( self, tcName, reqKeys ):\n\n self.testCase_info = self.api.TestCase.get( tcName )\n self.testCase_name = self.testCase_info.name\n self.function_name = self.testCase_info.function_display_name\n self.unit_name = self.testCase_info.unit_display_name\n\n print( self.environment_name )\n print( self.unit_name )\n print( self.function_name )\n print( self.testCase_name )\n\n for key in reqKeys:\n\n # The requirement keys to which the test cases shall be linked must be known.\n # Example given for requirement key /item/1033.\n # One linkage at a time.\n\n # %VECTORCAST_DIR%\\clicast -lc -e environment_name -u unit_name -s function_name -t testCase_name RGW Testcase Link /item/1033\n\n assocProc = subprocess.Popen( [ \"C:\\VCAST19\\clicast\", \"-lc\", \\\n \"-e\", self.environment_name, \\\n \"-u\", self.unit_name, \\\n \"-s\", self.function_name, \\\n \"-t\", self.testCase_name, \\\n \"RGW\", \"Testcase\", \"Link\", key ], \\\n stdout=subprocess.PIPE, \\\n stderr=subprocess.PIPE )\n\n print( assocProc.stdout.read() )\n print( assocProc.stderr.read() )\n\n\nif \"__main__\" == __name__:\n\n # Note:\n # For the example to work launch dataApi.py from the working directory\n # containing the folder corresponding to the chosen environment name, here \"TEST\".\n # Command to issue: %vectorcast_dir%\\vpython Path\\To\\dataApi.py\n # You need to be licensed.\n\n envName = \"TEST\"\n reqKeys = [ \"/item/1033\" ]\n\n linkInstance = Link( envName ) \n linkInstance.linkTestCase( \"Pie\", reqKeys ) \n","sub_path":"DataAPI/dataApi.py","file_name":"dataApi.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"409594296","text":"import discord\nfrom discord.ext import commands\nfrom random import randint\nimport aiohttp\nimport random\n\nclass Echofun:\n \"\"\"echo fun commands.\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n #Reserved for further ...\n\n \"\"\"Commands section\"\"\"\n\n @commands.command(no_pm=True)\n async def sr(self, *text):\n \"\"\"sr [keyword] - Retrieves a random picture from subreddit\"\"\"\n imgurclient = ImgurClient(\"ad8952f4d3e875e\", \"7438169dd1b096d0dca330e826aeb120fbec6bcc\")\n if text[0] != ():\n randpage = randint(0, 9) #randomize page 0-9\n items = imgurclient.subreddit_gallery(text[0], sort='time', window='all', page=randpage)\n rand = randint(0, len(items)) #randomize result\n if len(items) < 1:\n await self.bot.say(\"No result for: {}\".format(text[0]))\n else:\n await self.bot.say(items[rand].link)\n \n elif text[0] == ():\n await self.bot.say(\"Type help sr for details.\")\n\nclass ModuleNotFound(Exception):\n def __init__(self, m):\n self.message = m\n def __str__(self):\n return self.message\n\ndef setup(bot):\n global ImgurClient\n try:\n from imgurpython import ImgurClient\n except:\n raise ModuleNotFound(\"imgurpython is not installed. Do 'pip3 install imgurpython' to use this cog.\")\n bot.add_cog(Echofun(bot))","sub_path":"cogs/echolog/echolog.py","file_name":"echolog.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"392628241","text":"from django.conf import settings\nfrom django.forms import DecimalField\n\nfrom .widgets import DecimalInputMask\n\n\nclass DecimalField(DecimalField):\n widget = DecimalInputMask\n\n def __init__(self, max_digits=10, decimal_places=2, *args, **kwargs):\n super(DecimalField, self).__init__(*args, **kwargs)\n\n self.widget.max_digits = max_digits\n self.widget.decimal_places = decimal_places\n\n self.localize = True\n\n def to_python(self, value):\n old_settings = settings.USE_L10N, settings.USE_THOUSAND_SEPARATOR\n\n settings.USE_L10N = True\n settings.USE_THOUSAND_SEPARATOR = True\n\n result = super(DecimalField, self).to_python(value)\n\n # restore original values\n settings.USE_L10N, settings.USE_THOUSAND_SEPARATOR = old_settings\n\n return result\n","sub_path":"input_mask/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"136244823","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef f(t): return np.exp(-t) * np.cos(2*np.pi*t)\n\n\nt1 = np.linspace(5, 10, num=100)\nyt1 = f(t1)\nt2 = np.linspace(5, 25, num=100)\nyt2 = f(t2)\n\nplt.figure(1)\nplt.subplot(2, 1, 1)\nplt.plot(t1, yt1, 'bo', t2, yt2, 'k')\nplt.subplot(2, 1, 2)\nycos = np.cos(2*np.pi*t2)\nplt.plot(t2, ycos, 'r--')\nplt.show()\n","sub_path":"Graficos/DoisGraficos.py","file_name":"DoisGraficos.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"506751628","text":"## import SLPFunctions\r\nimport SLPFunctions as slp\r\n\r\n## Magic Number -> Orange Attributes and Orange Class ##\r\norange_attribute_1 = 1\r\norange_attribute_2 = 0\r\norange_class = 1\r\n\r\n## Magic Number -> Apple Attributes and Apple Class ##\r\napple_attribute_1 = 0\r\napple_attribute_2 = 1\r\napple_class = 0\r\n\r\n## Magic Number -> Weight, Threshold Value ve Learning Coefficient ##\r\nweight_value_1 = 1\r\nweight_value_2 = 2\r\nthreshold_value = -1\r\nlearning_coefficient = 0.5\r\n\r\n## Iteration Value ##\r\niteration_value = 0\r\n\r\nwhile(True):\r\n print(\"------------------------------------\")\r\n iteration_value += 1\r\n print(iteration_value, \". Iteration\")\r\n print(\"------------------------------------\")\r\n\r\n OrangeNET = slp.calculateNETValue(orange_attribute_1,orange_attribute_2,weight_value_1,weight_value_2)\r\n AppleNET = slp.calculateNETValue(apple_attribute_1,apple_attribute_2,weight_value_2,weight_value_2)\r\n\r\n print(\"NET Orange Value: \",OrangeNET)\r\n print(\"NET Apple Value : \",AppleNET)\r\n print(\"------------------------------------\")\r\n\r\n if(OrangeNET == orange_class):\r\n if(slp.calculateThresholdValue(OrangeNET,AppleNET,threshold_value)):\r\n print(\"Output : Orange\")\r\n if(AppleNET == apple_class):\r\n if(slp.calculateThresholdValue(OrangeNET,AppleNET,threshold_value)):\r\n print(\"Output : Apple\")\r\n break\r\n else:\r\n weight_value_1, weight_value_2 = slp.reductionWeight(weight_value_1, weight_value_2,\r\n learning_coefficient, apple_attribute_1,\r\n apple_attribute_2)\r\n else:\r\n weight_value_1, weight_value_2 = slp.reductionWeight(weight_value_1, weight_value_2,\r\n learning_coefficient, apple_attribute_1, apple_attribute_2)\r\n else:\r\n weight_value_1, weight_value_2 = slp.reductionWeight(weight_value_1, weight_value_2, learning_coefficient,apple_attribute_1, apple_attribute_2)\r\n else:\r\n weight_value_1, weight_value_2 = slp.reductionWeight(weight_value_1, weight_value_2, learning_coefficient,orange_attribute_1, orange_attribute_2)\r\n\r\nprint(\"------------------------\")\r\nprint(\"Class Prediction\")\r\nprint(\"Orange Class : \", OrangeNET)\r\nprint(\"Apple Class : \", AppleNET)\r\nprint(\"Itration Value: \", iteration_value)\r\n","sub_path":"basic-slp-algorithm/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"182966473","text":"import requests\n#get接口测试样例\ndata={\n \"courseType\":\"3\",\n \"courseName\":\"\",\n \"isVip\":\"false\",\n \"isFree\":\"false\",\n \"isPublishTime\":\"true\",\n \"isHeat\":\"false\",\n \"industryId\":\"-1\",\n \"skillId\":\"-1\",\n \"softwareId\":\"-1\",\n \"levelId\":\"-1\",\n \"pageNo\":\"-1\",\n \"searchCourseType\":\"-1\"\n }\nreq=requests.get(url='https://w3-test.aboutcg.org/api/course/getSearchCategoryList?',params=data)\nprint(req.text)","sub_path":"interface_test/interface_get_test01.py","file_name":"interface_get_test01.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"214763370","text":"from flask import request, session, g, redirect, url_for, \\\n render_template, flash, Blueprint, json\nimport requests\nfrom bikeandwalk import app\nimport logging\n\nmod = Blueprint('persona',__name__)\n\n## persona authentication ##\n@mod.route('/_auth/login', methods=['GET', 'POST'])\ndef login_handler():\n \"\"\"This is used by the persona.js file to kick off the\n verification securely from the server side. If all is okay\n the email address is remembered on the server.\n \"\"\"\n resp = requests.post(app.config['PERSONA_VERIFIER'], data={\n 'assertion': request.form['assertion'],\n 'audience': request.host_url,\n }, verify=True)\n if resp.ok:\n verification_data = json.loads(resp.content)\n if verification_data['status'] == 'okay':\n session['email'] = verification_data['email']\n logging.info(verification_data['email'])\n return 'OK'\n\n abort(400)\n\n@mod.route('/_auth/logout', methods=['POST'])\ndef logout_handler():\n \"\"\"This is what persona.js will call to sign the user\n out again.\n \"\"\"\n session.clear()\n return 'OK'\n","sub_path":"views/persona.py","file_name":"persona.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"636149409","text":"# Copyright 2018 SAP SE, F5 Networks, Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nRoutines for configuring Octavia F5 Provider\n\"\"\"\nimport sys\n\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\n\nfrom octavia_f5.common import constants\nfrom octavia_lib.i18n import _\n\nLOG = logging.getLogger(__name__)\n\n\ndef init(args, **kwargs):\n cfg.CONF(args=args, project='octavia_f5',\n **kwargs)\n\n\ndef setup_logging(conf):\n \"\"\"Sets up the logging options for a log with supplied name.\n\n :param conf: a cfg.ConfOpts object\n \"\"\"\n product_name = \"octavia_f5\"\n logging.setup(conf, product_name)\n LOG.info(\"Logging enabled!\")\n LOG.debug(\"command line: %s\", \" \".join(sys.argv))\n\n\nf5_agent_opts = [\n cfg.BoolOpt('bigip_token', default=True,\n help=_('Use token authentication.')),\n cfg.BoolOpt('bigip_verify', default=False,\n help=_('Verify AS3 endpoint TLS cert.')),\n cfg.ListOpt('bigip_urls',\n item_type=cfg.types.URI(schemes=['http', 'https']),\n help=_('The URL to the bigip host device with AS3 endpoint')),\n cfg.StrOpt('esd_dir',\n help=_('Directory of the esd files')),\n\n cfg.StrOpt('tcp_service_type', default=constants.SERVICE_TCP,\n choices=[constants.SERVICE_L4,\n constants.SERVICE_TCP],\n help=_(\"Service type used for TCP listener\")),\n cfg.StrOpt('profile_l4', default=None,\n help=_(\"Path to default l4 acceleration profile\"\n \"(e.g. /Common/custom_fastl4)\")),\n cfg.StrOpt('profile_multiplex', default=None,\n help=_(\"Path to default multiplex (oneconnect) acceleration\"\n \" profile (e.g. /Common/custom_oneconnect)\")),\n cfg.StrOpt('healthmonitor_receive', default='\"HTTP/1.(0|1) 200',\n help=_(\"Default HTTP health monitor receive string\")),\n cfg.StrOpt('sync_to_group', default='',\n help=_(\"Name (like /Common/my_dg) of the config-sync \"\n \"group TO which the system should synchronize the \"\n \"targetHost configuration after (and only if) \"\n \"this request deploys any changes.\"\n \"When empty (default) this request will not affect \"\n \"config-sync at all.\")),\n cfg.BoolOpt('prometheus', default=True,\n help=_(\"Enable prometheus metrics exporter\")),\n cfg.PortOpt('prometheus_port', default=8000,\n help=_('Port for prometheus to expose, defaults to 8000.')),\n cfg.BoolOpt('dry_run', default=False,\n help=_(\"Run in dry-run, do not realize AS3 definitions.\")),\n\n]\n\nf5_networking_opts = [\n cfg.BoolOpt('caching', default=True,\n help=_('Enable caching of segmentation ids and ports')),\n cfg.IntOpt('cache_time', default=3600,\n help=_('Caching time in seconds (default=3600)')),\n cfg.StrOpt('f5_network_segment_physical_network', default=\"\",\n help=_('Restrict discovery of network segmentation ID '\n 'to a specific physical network name.')),\n]\n\n# Register the configuration options\ncfg.CONF.register_opts(f5_agent_opts, group='f5_agent')\ncfg.CONF.register_opts(f5_networking_opts, group='networking')\n","sub_path":"octavia_f5/common/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"212498048","text":"def EditClick(sender, context):\n app = context.OwnerForm.ClientApplication\n\n NIK=context.GetFieldValue('RR.EmployeeId')\n RID=context.GetFieldValue('RR.ReimbursementRealizationId')\n key =\"%s#%s#1\" % (NIK,RID)\n\n ph = app.CreateValues(['key', key])\n frm = app.CreateForm('karyawan/fEditHealthReimburse', 'fEditHealthReimburse', 0, ph, None)\n frm.Show(0)\n context.Refresh()\n\n\n","sub_path":"menus/popupmenus/karyawan/MnuOtorReimburse.py","file_name":"MnuOtorReimburse.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"326538393","text":"'''\nCreated on Jan 30, 2014\n\n@author: otrebor\n'''\nimport sys\n\nimport pygame\nimport gameEngine.Debug as Debug\nimport util.Vector2 as Vector2\nimport World\nimport Resources\nimport random\n\ndef init():\n random.seed(pygame.time.get_ticks())\n\ndef getNextRange( min, max ):\n return random.randrange( min, max )\n\nclass Game:\n DEBUG = False\n RESOLUTION = (1024, 768)\n GAMENAME = \"null\"\n INIT = False \n _instance = None\n @classmethod\n def Instance(cls): \n return cls._instance\n \n @classmethod\n def setInstance(cls,inst): \n cls._instance = inst\n \n def ToggleFullScreen(self):\n self.fullscreen = not self.fullscreen\n if self.fullscreen:\n self.screen = pygame.display.set_mode(self.RESOLUTION, pygame.FULLSCREEN)\n else:\n self.screen = pygame.display.set_mode(self.RESOLUTION)\n \n def __init__ (self):\n self.fullscreen = True\n self.ToggleFullScreen()\n Game.setInstance(self)\n self.INIT = True\n pygame.init()\n self.resources = Resources.Resources() \n \n pygame.display.set_caption(self.GAMENAME)\n #pygame.display.toggle_fullscreen()\n \n if not hasattr(self, 'World'):\n self.world = World.World(self, self.RESOLUTION, Vector2.Vector2(0, 0))\n \n self.fps = 0\n self.fps_time = 0\n self.delta = 0\n #self.skipGUI = True\n \n def draw(self):\n self.fps_time += self.delta\n if self.fps_time > 1:\n self.fps_time -= 1\n self.fps = 0\n \n self.screen.fill((0, 0, 0, 0))\n self.world.draw(self.screen)\n self.world.OnGUI(self.screen)\n if self.DEBUG:\n self.world.debDraw(self.screen)\n Debug.draw(self.screen)\n pygame.display.flip()\n self.fps += 1\n return\n \n def update(self, delta):\n pygame.event.pump()\n for evt in pygame.event.get():\n if evt.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if pygame.key.get_pressed()[pygame.K_ESCAPE]:\n pygame.quit()\n sys.exit()\n if pygame.key.get_pressed()[pygame.K_F4]:\n self.ToggleFullScreen()\n self.world.update(delta)\n return\n \n def run(self):\n if not self.INIT:\n self.init()\n oldtime = pygame.time.get_ticks()\n pygame.time.wait(5)\n while True:\n newtime = pygame.time.get_ticks()\n delta = newtime - oldtime\n oldtime = newtime\n deltaf = delta / 1000.0\n self.delta = deltaf\n self.update(deltaf)\n self.draw()\n \n def load(self,data):\n pass\n \n def reset(self):\n pass\n","sub_path":"GameEngine/gameEngine/Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":2814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"28848830","text":"'''card class'''\n\n# pylint: disable=E1101, E1601, W0612\n\nclass Card(object):\n '''card class'''\n \n def __init__(self, card):\n '''card initialization\n \n >>> import pcard\n >>>\n >>> CARD = pcard.Card('Ts')\n '''\n\n if card[0].upper() in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'] \\\n and card[1].upper() in ['C', 'D', 'H', 'S']:\n self.__figure = card[0].upper()\n self.__color = card[1].upper()\n self.__card = self.__figure + self.__color\n\n if self.__figure == 'A':\n self.__value = 14\n elif self.__figure == 'K':\n self.__value = 13\n elif self.__figure == 'Q':\n self.__value = 12\n elif self.__figure == 'J':\n self.__value = 11\n elif self.__figure == 'T':\n self.__value = 10\n else:\n self.__value = int(self.__figure)\n else:\n raise TypeError('')\n\n def show_card(self):\n '''show card\n \n >>> import pcard\n >>>\n >>> CARD = pcard.Card('Ts')\n >>> CARD.show_card()\n '''\n\n return self.__card\n\n def figure(self):\n '''show figure\n \n >>> import pcard\n >>>\n >>> CARD = pcard.Card('Ts')\n >>> CARD.figure()\n '''\n\n return self.__figure\n\n def color(self):\n '''show color\n \n >>> import pcard\n >>>\n >>> CARD = pcard.Card('Ts')\n >>> CARD.color()\n '''\n\n return self.__color\n\n def value(self):\n '''show value\n \n >>> import pcard\n >>>\n >>> CARD = pcard.Card('Ts')\n >>> CARD.value()\n '''\n\n return self.__value\n","sub_path":"py/version1/pcard.py","file_name":"pcard.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"212936735","text":"import cv2 \r\nimport math\r\n\r\nMAX_DIST = 50 \r\nP = 'C:/Users/HS/Pictures/Image/'\r\n\r\nclass Test:\r\n def __init__(self):\r\n print('Start')\r\n pass \r\n \r\n def readIMG(self, path):\r\n if path[-3:] == 'jpg' or path[-3:] == 'png':\r\n img = cv2.imread(P + path)\r\n return img\r\n \r\n elif path[-3:] == 'mp4':\r\n video = cv2.VideoCapture(P + path)\r\n return video\r\n \r\n def binIMG(self, img):\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n _, bin_img = cv2.threshold(img, 100, 255, cv2.THRESH_BINARY_INV)\r\n img_contours, _ = cv2.findContours(bin_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n \r\n return img_contours\r\n \r\n def count(self, cen, dis):\r\n visit = [0 for i in range(len(cen))]\r\n \r\n for i in range(len(self.center_list1)):\r\n min_dist = MAX_DIST\r\n index2 = 0\r\n for j in range(len(cen)):\r\n d = math.sqrt(((self.center_list1[i][0]-cen[j][0])**2) + ((self.center_list1[i][1]-cen[j][1])**2))\r\n if d < min_dist:\r\n min_dist = d\r\n index2 = j\r\n \r\n if min_dist < MAX_DIST:\r\n visit[index2] = 1\r\n \r\n if self.ditect_list1[i][0] == dis[index2][0]: #case1 : 이전과 같은 경우 \r\n continue\r\n elif (self.ditect_list1[i][0] != dis[index2][0]): #이전과 다른 경우 \r\n if self.ditect_list1[i][0] == 'N': #case2 : n > 인식\r\n #print('case2')\r\n self.img_count[self.filelist.index(dis[index2][0])] += 1\r\n else : \r\n if dis[index2][0] == 'N': #case3 : 인식 > n\r\n #print('case3 : ', self.ditect_list1[i], \" \", dis[index2])\r\n dis[index2] = self.ditect_list1[i]\r\n else : #case4 : 인식1 > 인식2 \r\n if self.ditect_list1[i][1] > dis[index2][1]:\r\n self.img_count[self.filelist.index(dis[index2][0])] += 1\r\n self.img_count[self.filelist.index(self.ditect_list1[i][0])] -= 1\r\n else: \r\n dis[index2] = self.ditect_list1[i]\r\n \r\n for i in range(len(visit)):\r\n if visit[i] == 0 and dis[i][0] != 'N': #case5 새로운 객체 인식 \r\n self.img_count[self.filelist.index(dis[i][0])] += 1\r\n \r\n self.center_list1 = cen\r\n self.ditect_list1 = dis\r\n \r\n def Run(self, filename):\r\n self.filelist = filename.split(' ')\r\n #img_list = [0 for i in range(len(self.filelist))]\r\n img_contours = [0 for i in range(len(self.filelist))]\r\n self.img_count = [0 for i in range(len(img_contours))]\r\n cnt = 0\r\n \r\n self.center_list1 = []\r\n self.ditect_list1 = []\r\n \r\n for i in range(len(self.filelist)):\r\n #img_list[i] = self.readIMG(self.filelist[i])\r\n img_contours[i] = self.binIMG(self.readIMG(self.filelist[i]))[0]\r\n \r\n video = cv2.VideoCapture(P + 'test_video2.mp4')\r\n \r\n while 1:\r\n ret, v_img = video.read()\r\n \r\n if not ret:\r\n print('Failed open Video')\r\n break\r\n \r\n v_contours = self.binIMG(v_img)\r\n center_list2 = []\r\n ditect_list2 = []\r\n visited = [0 for i in range(len(v_contours))]\r\n \r\n for i in range(len(v_contours)):\r\n pts = v_contours[i]\r\n if cv2.contourArea(pts) < 1000:\r\n continue\r\n \r\n rc = cv2.boundingRect(pts)\r\n \r\n M = cv2.moments(pts)\r\n cx = int(M['m10']/M['m00'])\r\n cy = int(M['m01']/M['m00'])\r\n \r\n if cnt == 0:\r\n self.center_list1.append([cx,cy])\r\n else :\r\n center_list2.append([cx,cy])\r\n \r\n cv2.drawContours(v_img,[pts],-1,(0,255,255),5)\r\n for j in range(len(img_contours)):\r\n dist = cv2.matchShapes(img_contours[j], pts, cv2.CONTOURS_MATCH_I3, 0.0)\r\n if dist < 0.5:\r\n cv2.rectangle(v_img, rc, (0, 0, 255), 2)\r\n cv2.circle(v_img, (cx, cy), 1, (0,0,255), 3)\r\n #cv2.putText(v_img, self.filelist[j][:-4], (rc[0], rc[1]-3), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 1, cv2.LINE_AA)\r\n if cnt == 0:\r\n if visited[i] == 1:\r\n if dist < self.ditect_list1[-1][1]:\r\n self.ditect_list1[-1] = [self.filelist[j], dist]\r\n \r\n elif visited[i] == 0:\r\n self.ditect_list1.append([self.filelist[j], dist]) \r\n visited[i] = 1\r\n else:\r\n if visited[i] == 1:\r\n if dist < ditect_list2[-1][1]:\r\n ditect_list2[-1] = [self.filelist[j], dist]\r\n \r\n elif visited[i] == 0:\r\n ditect_list2.append([self.filelist[j], dist]) \r\n visited[i] = 1\r\n else:\r\n if cnt == 0:\r\n self.ditect_list1.append(['N', dist])\r\n else:\r\n ditect_list2.append(['N', dist])\r\n \r\n cv2.imshow('Result', v_img)\r\n \r\n if cnt == 0:\r\n cnt += 1\r\n for i in self.ditect_list1:\r\n if i[0] != 'N':\r\n self.img_count[self.filelist.index(i[0])] += 1\r\n print('First : ', self.img_count)\r\n else:\r\n self.count(center_list2, ditect_list2)\r\n \r\n if cv2.waitKey(40) == 26:\r\n print('CTRL Z')\r\n break \r\n \r\n print('Result')\r\n for i in range(len(self.img_count)):\r\n print(self.filelist[i][:-4] + \" : \" + str(self.img_count[i]))\r\n \r\n print('End')\r\n cv2.destroyAllWindows()\r\n \r\nif __name__ == '__main__':\r\n cpimg = Test()\r\n cpimg.Run('s3.jpg')\r\n\r\n","sub_path":"Object_Tracking/윤곽선 매칭/Matching.py","file_name":"Matching.py","file_ext":"py","file_size_in_byte":6748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"337728764","text":"#!/usr/bin/env python\n# -*- coding=utf-8 -*-\n\nimport sys\nfrom pymongo import MongoClient\n\nfilesave = open('./road_id.txt','w')\n\nclient = MongoClient('127.0.0.1', 27017)\ndb = client.gisdb\ncollection = db.xqpoint\n\ncursor = collection.find()\nlen_cursor = cursor.count()\n\nfor i in range(0, len_cursor):\n temp = cursor.next()\n tempid = temp['ID']\n filesave.write(\"%s\\n\" % (tempid))\n\nclient.disconnect()\nfilesave.close()\n","sub_path":"new/everyid.py","file_name":"everyid.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"302484815","text":"import pandas as pd\nimport yaml \nimport csv\nimport re\nimport warnings\nimport os\nwarnings.filterwarnings(\"ignore\")\n\ndef make_list(alist):\n\t#Removes null from lists\n\tblist = []\n\tfor val in alist:\n\t\tblist.append(val)\n\treturn blist \n\ndef remove_null(alist):\n\t#Removes null from lists\n\tblist = []\n\tfor val in alist:\n\t\tif pd.isna(val) == False:\n\t\t\tblist.append(val)\n\treturn blist \n\ndef make_not_columns(nflevels, levels):\n\t#Gives the rows which are to be dropped\n\tnot_rows = []\n\tfor i in range(1,nflevels + 1):\n\t\tif i not in levels:\n\t\t\tnot_rows.append(i - 1)\n\treturn not_rows\n\ndef make_and_think(js,arr,level):\n\t#Forms the basic structure of json\n\tif level == len(arr) - 1:\n\t\tif arr[level] not in js:\n\t\t\tjs[arr[level]] = []\n\telif arr[level] not in js:\n\t\tjs[arr[level]] = {}\n\t\tmake_and_think(js[arr[level]],arr,level + 1)\n\telse:\n\t\tmake_and_think(js[arr[level]],arr,level + 1)\n\treturn js\n\ndef make_liwc(dict_levels,arr):\n\tglobal head_count\n\tglobal all_items\n\tglobal all_headings\n\titem_arr = []\n\tfor key in dict_levels:\n\t\tif key not in all_headings:\n\t\t\tall_headings[key] = head_count\n\t\t\tif head_count not in item_arr:\n\t\t\t\titem_arr.append(all_headings[key])\n\t\t\thead_count += 1\n\t\telse:\n\t\t\titem_arr.append(all_headings[key])\n\tfor item in arr:\n\t\tif item in all_items:\n\t\t\tfor number in item_arr:\n\t\t\t\tif number not in all_items[item]:\n\t\t\t\t\tall_items[item].append(number)\n\t\telse:\n\t\t\tall_items[item] = []\n\t\t\tfor number in item_arr:\n\t\t\t\tif number not in all_items[item]:\n\t\t\t\t\tall_items[item].append(number)\n\ndef makeliwc_comp(filename):\n\tglobal head_count\n\tglobal all_items\n\tglobal all_headings\n\twith open(filename,\"a\") as file:\n\t\tfile.write('%\\n')\n\t\tfor key in all_headings:\n\t\t\tfile.write(str(key) + \"\\t\" + str(all_headings[key]) + \"\\n\")\n\t\tfile.write('%\\n')\n\t\tfor key in all_items.keys():\n\t\t\tfile.write(str(key) + \"\\t\")\n\t\t\tfor number in range(len(all_items[key])):\n\t\t\t\tif number == len(all_items[key]) - 1:\n\t\t\t\t\tfile.write(str(all_items[key][number]) + \"\\n\")\n\t\t\t\telse:\n\t\t\t\t\tfile.write(str(all_items[key][number]) + \"\\t\")\n\n\ndef make_and_put(js,arr,value,level):\n\t#Adds an array is the json as value for the pair arr[len(arr) - 1] \n\tif level == len(arr)-1:\n\t\tif arr[level] in js:\n\t\t\tassert(isinstance(js[arr[level]],list))\n\t\t\tfor v in value:\n\t\t\t\tjs[arr[level]].append(v)\n\tif arr[level] in js and level != len(arr)-1:\n\t\tmake_and_put(js[arr[level]],arr,value,level + 1)\n\treturn js\n\ndef check_script(filename = \"dictionary.yml\"):\n\tnon_utf_8_pattern = \"\\\\\\\\x\"\n\twith open(filename, 'rb') as stream:\n\t\tdata = stream.read()\n\t\tdata = data.decode(\"utf-8\",\"backslashreplace\")\n\t\tz = re.match(non_utf_8_pattern, data)\n\t\tif z:\n\t\t\tprint((z.groups()))\n\t\telse:\n\t\t\tpass\n\t\t\t#print(\"NO MATCH FOUND\")\n\n\ndef rem_utf_8(filename,filename2):\n\tnon_utf_8_pattern = \"\\\\\\\\x\"\n\twith open(filename, 'rb') as stream:\n\t\tdata = stream.read()\n\t\tdata = data.decode(\"utf-8\",\"backslashreplace\")\n\t\tz = re.match(non_utf_8_pattern, data)\n\t\t#print(data)\n\t\tdata = re.sub(\"\\\\\\\\x92\",\"\\'\",data)\n\t\tdata = re.sub(\"\\\\\\\\x96\",\"-\",data)\n\t\tdata = re.sub(\"\\\\\\\\x97\",\"—\",data)\n\t\tdata = re.sub(\"\\\\\\\\xf3\",\"ó\",data)\n\t\tprint(data)\n\t\twith open(filename2, 'w+') as file:\n\t\t\tfile.write(data)\n\ndef make_dictionary(nflevels = 6,levels = [1,2,3,4,5],filename = \"dictionary.yml\",file_to_read = \"dictionary.csv\",liwc_filename = \"dictionary.dic\"):\n\t#---------------------------\n\tdf = pd.read_csv(file_to_read)\n\tlevelsdropped = make_not_columns(nflevels,levels)\n\tdf = df.drop(levelsdropped)\n\tnflevelsdropped = len(levelsdropped)\n\tlevels_remaining = nflevels - nflevelsdropped\n\t#print(\"levels_remaining = \",levels_remaining)\n\tdf = df.T\n\t(nfrows,nfcolumns) = df.shape\n\t#---------------------------\n\t#Preprocessing\n\trows = []\n\tfor i in range(nfrows):\n\t\trow = df.iloc[i]\n\t\t#if i % 2 == 0:\n\t\trow = make_list(row)\n\t\trows.append(row) \n\t#---------------------------\n\t#print(\"Rows = \",rows)\n\t#Make Json\n\tjs = {}\n\tfor row_no in range(0,len(rows) - 1,2):\n\t\trow = rows[row_no]\n\t\tc_row = rows[row_no + 1]\n\t\tlevel = 0\n\t\tdict_levels = row[:levels_remaining]\n\t\tmake_and_think(js,dict_levels,0)\n\t\tarr = []\n\t\tfor item_no in range(levels_remaining,len(row)):\n\t\t\t#print(\"Item_no = \",item_no)\n\t\t\titem = row[item_no]\n\t\t\tif pd.isna(item) == False:\n\t\t\t\titem = item.strip()\n\t\t\t\titem = re.sub(\"\\\\\\\\x92\",\"\\'\",item)\n\t\t\t\titem = re.sub(\"\\\\\\\\x96\",\"-\",item)\n\t\t\t\titem = re.sub(\"\\\\\\\\x97\",\"—\",item)\n\t\t\t\titem = re.sub(\"\\\\\\\\xf3\",\"ó\",item)\n\t\t\t\t#item = str(item,'utf-8')\n\t\t\t\t#print(\"Item = \",item)\n\t\t\t\tif c_row[item_no] == \"nc\":\n\t\t\t\t\tif item == item.lower():\n\t\t\t\t\t\tarr.append(item)\n\t\t\t\t\t\tarr.append(item[0].capitalize() + item[1:])\n\t\t\t\t\telse:\n\t\t\t\t\t\tarr.append(item)\n\t\t\t\t\t\tarr.append(item.lower())\n\t\t\t\telse:\n\t\t\t\t\tarr.append(item)\n\t\t\telse:\n\t\t\t\tpass\n\t\t\t\t#print(\"Null Item Here\")\n\t\tmake_liwc(dict_levels,arr)\n\t\tmake_and_put(js,dict_levels,arr,0)\n\t#---------------------------------------\n\t#DUMP Json onto yml file and liwc\n\tmakeliwc_comp(liwc_filename)\n\tff = open(\"temp.yml\", 'w+')\n\tyaml.dump(js,ff,allow_unicode = True,default_flow_style = False)\n\trem_utf_8(\"temp.yml\",filename)\n\tff.close()\n\tos.remove(\"temp.yml\")\n\nall_headings = {}\nall_items = {}\nhead_count = 1\n\nmake_dictionary()\n","sub_path":"workflow/BonusNiravGenerateLIWCdictionary.py","file_name":"BonusNiravGenerateLIWCdictionary.py","file_ext":"py","file_size_in_byte":5060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"34838732","text":"import sys\nimport numpy as np\nimport getopt\nimport os.path\nimport subprocess\nimport csv\n\ndef check_existence(FILENAME):\n if os.path.isfile(FILENAME) == False:\n print('File', FILENAME, 'not found')\n sys.exit(2)\n else:\n return True\n\ndef read_csv_audioset(file):\n with open(file, newline='') as csvfile:\n fileobject = csv.reader(csvfile, delimiter=',', quotechar='|') #delimeter for normal file is ','!\n youtube_id_list = []\n star_time_list = []\n stop_time_list = []\n for row in fileobject: \n youtube_id_list.append(row[0])\n star_time_list.append(row[1])\n stop_time_list.append(row[2])\n \n star_time_list = star_time_list[3:]\n stop_time_list = stop_time_list[3:]\n youtube_id_list = youtube_id_list[3:]\n\n youtube_id_list = ' '.join(youtube_id_list).replace(',','').split()\n star_time_list = ' '.join(star_time_list).replace(',','').split()\n stop_time_list = ' '.join(stop_time_list).replace(',','').split()\n return youtube_id_list,star_time_list,stop_time_list\n\n \n\n\ndef download_crop_wav(name,START_TIME,STOP_TIME,link):\n#--------------------------------------------------\n#Downloads audio file from the provided link\n#Converts downloaded m4a file into wav file\n#Crops wav file according to START_TIME and STOP_TIME\n#Adds to the name of the file _AI\n#Takes only str objects!\n#--------------------------------------------------\n print('---------------------------\\n')\n print('Processing file: ',name,'.wav')\n print('Invoking youtube-dl...\\n') \n print('---------------------------')\n os.system('youtube-dl -f 140 ' + link)\n os.system('ls') \n print('---------------------------\\n')\n print('Renaming downloaded file according with the DataBase...\\n')\n print('---------------------------') \n os.system('mv *m4a ' + name + '.m4a')\n os.system('avconv -i ' + name + '.m4a ' + name + '.wav')\n print('---------------------------\\n')\n print('Cropping...\\n')\n print('---------------------------')\n #cropping to START_TIME <-> STOP_TIME\n os.system('ffmpeg -i '+ name + '.wav -ss ' + START_TIME + ' -to ' + STOP_TIME + ' ' + name + '_.wav')\n print('---------------------------\\n')\n print('AI-ready file created...\\nRemoving temp files...\\n')\n print('---------------------------')\n os.system('rm -rf *m4a') #Clean-up, we don't have a lot of dosk space there\n os.system('rm -rf ' + name + '.wav')\n os.system('ls')\n\ndef main(argv):\n inputfile=''\n #outputfile=''\n try:\n opts, args = getopt.getopt(argv,\"hi:\",[\"ifile=\"])\n except getopt.GetoptError:\n print(\"acesim.py \")\n sys.exit(2)\n for opt,arg in opts:\n if opt == \"-h\":\n print(\"Converts Google AudioSet to the labeled A.C.E Database\\nFilename structure: